Compare commits

..
Author SHA1 Message Date
paseo-bot[bot] 2e4def4eb7 fix(server): reconcile projects nested under a changed Git root
Git initialization or removal changes the checkout for directories
beneath the watched root. Include nested projects and workspaces in
the event-driven pass, including workspaces attached to another project.
2026-11-22 03:25:34 +00:00
paseo-bot[bot]andVictor Dozal 9d64a5fc50 test(server): compare Git reconciliation paths across platforms
Use portable separators for relative checkout paths. Resolve the
expected repository root so a Windows short path does not fail the
checkout identity assertion.

Co-authored-by: Victor Dozal <v.dozal@live.com>
2026-11-22 03:13:33 +00:00
Victor Dozal ab8107757b Read a checkout's identity for reconciliation without scanning its working tree 2026-11-20 18:22:08 -06:00
Victor Dozal 3c4556c06e Re-read only the workspaces of the project whose .git changed 2026-11-20 18:09:27 -06:00
19 changed files with 437 additions and 813 deletions
@@ -1,149 +0,0 @@
import { test, expect, type Page } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { seedWorkspace, type SeededWorkspace } from "../support/helpers/seed-client";
import { selectSidebarStatusGrouping } from "../support/helpers/sidebar";
import {
createGatedTeardown,
pressArchiveShortcut,
workspaceRow,
} from "../support/helpers/workspace-archive-undo";
// The archive shortcut used to be registered by the sidebar row itself, so it did nothing whenever
// the row was unmounted — a collapsed project section being the common case. It now lives in a
// single always-mounted handler keyed on the active route selection, like the pin shortcut.
// Returns the workspace route, so the test can assert archiving redirected off it.
async function openWorkspace(page: Page, workspaceId: string): Promise<string> {
const row = workspaceRow(page, workspaceId);
await expect(row).toBeVisible({ timeout: 30_000 });
await row.click();
await expect(page).toHaveURL((url) => url.pathname.endsWith(`/workspace/${workspaceId}`), {
timeout: 30_000,
});
return page.url();
}
async function collapseProjectSection(page: Page, project: SeededWorkspace): Promise<void> {
const header = page
.locator('[data-testid^="sidebar-project-row-"]')
.filter({ hasText: project.projectDisplayName });
await expect(header).toHaveCount(1, { timeout: 30_000 });
await header.click();
await expect(workspaceRow(page, project.workspaceId)).toHaveCount(0, { timeout: 10_000 });
}
async function collapseStatusGroupContaining(page: Page, workspaceId: string): Promise<void> {
const rows = page
.locator('[data-testid^="sidebar-status-group-rows-"]')
.filter({ has: workspaceRow(page, workspaceId) });
await expect(rows).toHaveCount(1, { timeout: 30_000 });
const rowsTestId = await rows.getAttribute("data-testid");
const bucket = rowsTestId?.replace("sidebar-status-group-rows-", "");
expect(bucket).toBeTruthy();
await page.getByTestId(`sidebar-status-group-${bucket}`).click();
await expect(workspaceRow(page, workspaceId)).toHaveCount(0, { timeout: 10_000 });
}
async function expectArchived(page: Page, workspace: SeededWorkspace, workspaceUrl: string) {
await expect(page).not.toHaveURL(workspaceUrl);
await expect
.poll(async () => {
const { entries } = await workspace.client.fetchWorkspaces();
return entries.some((entry) => entry.id === workspace.workspaceId);
})
.toBe(false);
}
test.describe("Archive workspace shortcut", () => {
test("archives the active workspace while its row is rendered", async ({ page }) => {
const workspace = await seedWorkspace({ repoPrefix: "archive-shortcut-expanded-" });
try {
await gotoAppShell(page);
const workspaceUrl = await openWorkspace(page, workspace.workspaceId);
await pressArchiveShortcut(page);
await expectArchived(page, workspace, workspaceUrl);
} finally {
await workspace.cleanup();
}
});
test("archives the active workspace while its project section is collapsed", async ({ page }) => {
const workspace = await seedWorkspace({ repoPrefix: "archive-shortcut-collapsed-" });
try {
await gotoAppShell(page);
const workspaceUrl = await openWorkspace(page, workspace.workspaceId);
await collapseProjectSection(page, workspace);
await pressArchiveShortcut(page);
await expectArchived(page, workspace, workspaceUrl);
} finally {
await workspace.cleanup();
}
});
test("archives the active workspace while its status group is collapsed", async ({ page }) => {
const workspace = await seedWorkspace({ repoPrefix: "archive-shortcut-status-" });
try {
await gotoAppShell(page);
const workspaceUrl = await openWorkspace(page, workspace.workspaceId);
await selectSidebarStatusGrouping(page);
await expect(page.getByTestId("sidebar-status-list-scroll")).toBeVisible({
timeout: 10_000,
});
await collapseStatusGroupContaining(page, workspace.workspaceId);
await pressArchiveShortcut(page);
await expectArchived(page, workspace, workspaceUrl);
} finally {
await workspace.cleanup();
}
});
test("archives a different workspace while the first worktree is still tearing down", async ({
page,
}) => {
const teardown = createGatedTeardown();
const project = await seedWorkspace({
repoPrefix: "archive-shortcut-teardown-",
repo: { paseoConfig: teardown.paseoConfig },
});
const next = await seedWorkspace({ repoPrefix: "archive-shortcut-next-" });
try {
const { workspace: worktree, error } = await project.client.createWorkspace({
source: {
kind: "worktree",
cwd: project.repoPath,
worktreeSlug: "archive-shortcut-teardown",
},
});
if (!worktree) throw new Error(error ?? "Could not seed the worktree");
await gotoAppShell(page);
await test.step("start the first archive and wait for its teardown", async () => {
await openWorkspace(page, worktree.id);
await pressArchiveShortcut(page);
await teardown.expectStarted();
});
await test.step("archive the second workspace before the first archive finishes", async () => {
const workspaceUrl = await openWorkspace(page, next.workspaceId);
await pressArchiveShortcut(page);
await expectArchived(page, next, workspaceUrl);
});
} finally {
teardown.release();
await project.cleanup();
await next.cleanup();
}
});
});
@@ -318,37 +318,6 @@ test.describe("Workspace archive undo", () => {
}
});
test("archives a restored workspace while its undo is queued", async ({ page }) => {
const teardown = createGatedTeardown();
const repo = await createTempGitRepo("archive-undo-archive-", {
paseoConfig: teardown.paseoConfig,
});
try {
await openProjectViaDaemon(client, repo.path);
const worktree = await createWorktreeViaDaemon(client, {
cwd: repo.path,
slug: "archive-undo-archive",
});
worktreeDirectories.add(worktree.workspaceDirectory);
await gotoAppShell(page);
await archiveFromRowButton(page, worktree.workspaceId);
await teardown.expectStarted();
await undoButton(page).click();
await workspaceRow(page, worktree.workspaceId).click();
await expect(page).toHaveURL(new RegExp(`/workspace/${worktree.workspaceId}$`));
await pressArchiveShortcut(page);
await expectWorkspaceAbsentFromSidebar(page, worktree.workspaceId);
teardown.release();
await expectDirectoryPresence(worktree.workspaceDirectory, false);
} finally {
teardown.release();
await repo.cleanup();
}
});
test("Cmd/Ctrl+Z without an archive to undo leaves the sidebar alone", async ({ page }) => {
const worktree = await seedWorktree(page, "archive-undo-none");
@@ -20,7 +20,6 @@ import {
} from "../support/helpers/sidebar";
import { createTempGitRepo } from "../support/helpers/workspace";
import {
pressArchiveShortcut,
rowArchiveButton,
undoButton,
workspaceRow,
@@ -99,18 +98,6 @@ async function clickRowArchiveButton(page: Page, workspaceId: string): Promise<v
await rowArchiveButton(page, workspaceId).click();
}
async function cycleThemeAndWaitForSidebar(page: Page, workspaceId: string): Promise<void> {
const rowBeforeThemeChange = await workspaceRow(page, workspaceId).elementHandle();
if (!rowBeforeThemeChange)
throw new Error("The workspace row must be mounted before cycling the theme");
await page.keyboard.press("ControlOrMeta+Alt+t");
await expect
.poll(() => rowBeforeThemeChange.evaluate((element) => element.isConnected), {
message: "the sidebar remounts after the theme changes",
})
.toBe(false);
}
interface SessionEnvelope {
type?: unknown;
message?: {
@@ -224,28 +211,18 @@ async function relayDaemon(
* Holds the app's next checkout status request for `directory` once armed, so a test can act
* while the archive waits for the host's answer.
*/
async function holdCheckoutStatusRequest(
page: Page,
worktree: { workspaceDirectory: string; workspaceId: string },
) {
async function holdCheckoutStatusRequest(page: Page, directory: string) {
let armed = false;
let held: (() => void) | null = null;
let archiveRequests = 0;
await page.routeWebSocket(daemonWsRoutePattern(), (browser) => {
const server = browser.connectToServer();
browser.onMessage((message) => {
const request = typeof message === "string" ? parseSessionEnvelope(message)?.message : null;
if (
request?.type === "archive_workspace_request" &&
request.workspaceId === worktree.workspaceId
) {
archiveRequests += 1;
}
if (
armed &&
!held &&
request?.type === "checkout_status_request" &&
request.cwd === worktree.workspaceDirectory
request.cwd === directory
) {
held = () => server.send(message);
return;
@@ -259,7 +236,6 @@ async function holdCheckoutStatusRequest(
armed = true;
},
waitForHeld: () => expect.poll(() => held !== null).toBe(true),
archiveRequests: () => archiveRequests,
release: () => {
if (!held) throw new Error("No checkout status request is held");
held();
@@ -412,7 +388,7 @@ test.describe("Workspace archive risk warning for worktree backing", () => {
): Promise<string> {
const serverId = getServerId();
const worktree = await createWorktree(slug);
const statusRequest = await holdCheckoutStatusRequest(page, worktree);
const statusRequest = await holdCheckoutStatusRequest(page, worktree.workspaceDirectory);
await openSidebarRow(page, worktree.workspaceId);
await workspaceRow(page, worktree.workspaceId).click();
await expectAppRoute(page, buildHostWorkspaceRoute(serverId, worktree.workspaceId));
@@ -456,82 +432,6 @@ test.describe("Workspace archive risk warning for worktree backing", () => {
await expectAppRoute(page, openedRoute);
});
async function openWorktreeWithCheckoutHeld(page: Page, slug: string) {
const worktree = await createWorktree(slug);
const statusRequest = await holdCheckoutStatusRequest(page, worktree);
// Opening the workspace can start a checkout read that the archive reuses.
statusRequest.arm();
await openSidebarRow(page, worktree.workspaceId);
await workspaceRow(page, worktree.workspaceId).click();
await expectAppRoute(page, buildHostWorkspaceRoute(getServerId(), worktree.workspaceId));
return { worktree, statusRequest };
}
test("the archive shortcut works in another workspace while a checkout check is pending", async ({
page,
}) => {
const { worktree, statusRequest } = await openWorktreeWithCheckoutHeld(
page,
"archive-risk-switch-shortcut",
);
await pressArchiveShortcut(page);
await statusRequest.waitForHeld();
try {
const otherWorkspaceId = worktree.project.workspaceId;
await workspaceRow(page, otherWorkspaceId).click();
await expectAppRoute(page, buildHostWorkspaceRoute(getServerId(), otherWorkspaceId));
await pressArchiveShortcut(page);
await expect.poll(() => hostListsWorkspace(otherWorkspaceId)).toBe(false);
} finally {
statusRequest.release();
}
await expect.poll(() => hostListsWorkspace(worktree.workspaceId)).toBe(false);
});
test("the row button and shortcut send one archive for the same worktree", async ({ page }) => {
const { worktree, statusRequest } = await openWorktreeWithCheckoutHeld(
page,
"archive-risk-repeat-shortcut",
);
await clickRowArchiveButton(page, worktree.workspaceId);
await statusRequest.waitForHeld();
try {
await pressArchiveShortcut(page);
} finally {
statusRequest.release();
}
await expect.poll(() => hostListsWorkspace(worktree.workspaceId)).toBe(false);
expect(statusRequest.archiveRequests()).toBe(1);
});
test("keeps the newly opened workspace after a theme change during an archive check", async ({
page,
}) => {
const { worktree, statusRequest } = await openWorktreeWithCheckoutHeld(
page,
"archive-risk-theme",
);
await pressArchiveShortcut(page);
await statusRequest.waitForHeld();
const otherWorkspaceId = worktree.project.workspaceId;
const otherRoute = buildHostWorkspaceRoute(getServerId(), otherWorkspaceId);
try {
await cycleThemeAndWaitForSidebar(page, otherWorkspaceId);
await workspaceRow(page, otherWorkspaceId).click();
await expectAppRoute(page, otherRoute);
} finally {
statusRequest.release();
}
await expect.poll(() => hostListsWorkspace(worktree.workspaceId)).toBe(false);
await expectAppRoute(page, otherRoute);
});
test("archiving the open worktree from its git actions leaves it for a new workspace", async ({
page,
}) => {
+1 -1
View File
@@ -40,7 +40,7 @@
"dev:ios": "npm --prefix ../.. run build:client && cross-env APP_VARIANT=development expo run:ios",
"build:apk": "npm --prefix ../.. run build:apk",
"build:apk:arm64": "npm --prefix ../.. run build:apk:arm64",
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListBlockquoteMeasurementTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
},
"dependencies": {
"@codemirror/commands": "6.10.4",
-2
View File
@@ -54,7 +54,6 @@ import { WindowSidebarMenuToggle } from "@/components/headers/sidebar-menu-toggl
import { DesktopWindowControls } from "@/components/desktop/window-controls";
import { SidebarModelProvider } from "@/components/sidebar/sidebar-model";
import { WorkspacePinShortcutHandler } from "@/components/workspace-pin-shortcut-handler";
import { WorkspaceArchiveShortcutHandler } from "@/components/workspace-archive-shortcut-handler";
import { WorkspaceRenameHost } from "@/components/workspace-rename-host";
import { WorkspaceArchiveUndoShortcutHost } from "@/workspace/archive-undo";
import { WorkspaceExplorerOpenGesture } from "@/mobile-panels/explorer-open-gesture";
@@ -538,7 +537,6 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon
<View style={layoutStyles.surfaceFill}>
{workspaceChrome}
<AddHostFlowHost />
<WorkspaceArchiveShortcutHandler />
<AppearanceStyleBoundary>
{!isCompactLayout && appChromeLayout.sidebarToggleOwner === "window" ? (
<WindowChromeRegion corners="top-left">
@@ -128,6 +128,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip
import { Shortcut } from "@/components/ui/shortcut";
import type { ShortcutKey } from "@/utils/format-shortcut";
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
import { useWorkspaceReadState } from "@/hooks/use-workspace-read-state";
import type { PrHint } from "@/git/use-pr-status-query";
import {
@@ -1297,6 +1298,17 @@ function WorkspaceRowWithMenu({
});
}, [markUnread, toast]);
useKeyboardActionHandler({
handlerId: `workspace-archive-${workspace.workspaceKey}`,
actions: ["workspace.archive"],
enabled: selected && !isArchiving,
priority: 0,
handle: () => {
handleArchive();
return true;
},
});
return (
<>
<WorkspaceRowInner
@@ -42,6 +42,7 @@ import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-ar
import { useWorkspaceArchive } from "@/workspace/use-workspace-archive";
import type { ShortcutKey } from "@/utils/format-shortcut";
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
import { useWorkspaceReadState } from "@/hooks/use-workspace-read-state";
import {
SidebarWorkspaceRowFrame,
@@ -701,6 +702,17 @@ function StatusWorkspaceRowWithMenu({
});
}, [markUnread, toast]);
useKeyboardActionHandler({
handlerId: `workspace-archive-${workspace.workspaceKey}`,
actions: ["workspace.archive"],
enabled: selected && !isArchiving,
priority: 0,
handle: () => {
handleArchive();
return true;
},
});
return (
<>
<StatusWorkspaceRowInner
@@ -1,8 +0,0 @@
import { useGlobalWorkspaceArchiveAction } from "@/hooks/use-global-workspace-archive-action";
// Headless host for the archive shortcut, kept out of the root layout for the same reason as
// WorkspacePinShortcutHandler: the hook subscribes to the active workspace's fields.
export function WorkspaceArchiveShortcutHandler() {
useGlobalWorkspaceArchiveAction();
return null;
}
@@ -1,77 +0,0 @@
import { useCallback } from "react";
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher";
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
import { useWorkspaceFields } from "@/stores/session-store-hooks";
import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-archive-redirect";
import { useWorkspaceArchive } from "@/workspace/use-workspace-archive";
import { isWorkspaceListed, type WorkspaceArchiveTarget } from "@/workspace/workspace-archive";
const WORKSPACE_ARCHIVE_ACTIONS: readonly KeyboardActionId[] = ["workspace.archive"];
// The archive shortcut used to live on the sidebar row, so it did nothing whenever the row was not
// rendered — a collapsed project or status group, a collapsed Pinned section, or focus mode. Like
// the pin shortcut (see use-global-workspace-pin-action.ts), it is one registration keyed on the
// active route selection.
export function useGlobalWorkspaceArchiveAction() {
const selection = useActiveWorkspaceSelection();
const serverId = selection?.serverId ?? null;
const routeWorkspaceId = selection?.workspaceId ?? null;
// `id` is the descriptor id, not the route id; see use-global-workspace-pin-action.ts.
const fields = useWorkspaceFields(serverId, routeWorkspaceId, (workspace) => ({
id: workspace.id,
workspaceKind: workspace.workspaceKind,
workspaceDirectory: workspace.workspaceDirectory,
name: workspace.name,
archivingAt: workspace.archivingAt,
diffStat: workspace.diffStat,
}));
// useWorkspaceArchive calls the latest render's callback, so `activeWorkspaceId` is whatever is
// routed when the archive starts, after any confirmation. It is the descriptor id, which is what
// the redirect compares against.
const activeWorkspaceId = fields?.id ?? null;
const redirectAfterArchive = useCallback(
(workspace: WorkspaceArchiveTarget) => {
redirectIfArchivingActiveWorkspace({
...workspace,
activeWorkspaceSelection:
serverId && activeWorkspaceId ? { serverId, workspaceId: activeWorkspaceId } : null,
});
},
[activeWorkspaceId, serverId],
);
const archiveController = useWorkspaceArchive({
serverId: serverId ?? "",
workspaceId: fields?.id ?? "",
workspaceKind: fields?.workspaceKind ?? "directory",
workspaceDirectory: fields?.workspaceDirectory ?? "",
name: fields?.name ?? "",
diffStat: fields?.diffStat,
onArchiveStarted: redirectAfterArchive,
});
const canArchive = fields !== null && fields.archivingAt === null;
const handle = useCallback(() => {
if (!canArchive || !serverId) {
return false;
}
// Archiving hides its target immediately. Read the store in case the shortcut
// runs again before React renders that update.
if (!isWorkspaceListed({ serverId, workspaceId: fields.id })) {
return false;
}
archiveController.archive();
return true;
}, [archiveController, canArchive, fields, serverId]);
useKeyboardActionHandler({
handlerId: "workspace-archive-global",
actions: WORKSPACE_ARCHIVE_ACTIONS,
enabled: canArchive,
priority: 0,
handle,
});
}
@@ -14,7 +14,6 @@ import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
import { archiveWorkspaceWithUndo, supportsWorkspaceArchiveUndo } from "@/workspace/archive-undo";
import {
archiveWorkspaceOptimistically,
runWorkspaceArchiveAttempt,
type WorkspaceArchiveTarget,
} from "@/workspace/workspace-archive";
@@ -57,6 +56,7 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch
} = input;
const { t } = useTranslation();
const toast = useToast();
const confirmingRef = useRef(false);
// The archive starts after the host answers and you confirm. By then you may have opened another
// workspace, so the redirect reads the selection from the latest render.
const onArchiveStartedRef = useRef(onArchiveStarted);
@@ -119,12 +119,26 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch
}, [diffStat, name, serverId, t, toast, warningLabels, workspaceDirectory]);
const archive = useCallback(() => {
void runWorkspaceArchiveAttempt({
workspace: { serverId, workspaceId },
confirm: workspaceKind === "worktree" ? confirmWorktreeArchive : undefined,
archive: archiveWorkspaceRecord,
});
}, [archiveWorkspaceRecord, confirmWorktreeArchive, serverId, workspaceId, workspaceKind]);
// A second press while the host answers or the warning is open would ask twice.
if (confirmingRef.current) {
return;
}
void (async () => {
if (workspaceKind === "worktree") {
confirmingRef.current = true;
let confirmed: boolean;
try {
confirmed = await confirmWorktreeArchive();
} finally {
confirmingRef.current = false;
}
if (!confirmed) {
return;
}
}
await archiveWorkspaceRecord();
})();
}, [archiveWorkspaceRecord, confirmWorktreeArchive, workspaceKind]);
return {
archive,
@@ -17,30 +17,6 @@ export interface WorkspaceArchiveTarget {
workspaceId: string;
}
const pendingArchiveAttempts = new Set<string>();
/** Checks and starts one archive at a time for a workspace. */
export async function runWorkspaceArchiveAttempt(input: {
workspace: WorkspaceArchiveTarget;
confirm?: () => Promise<boolean>;
archive: () => Promise<void>;
}): Promise<void> {
const { serverId, workspaceId } = input.workspace;
const key = JSON.stringify([serverId, workspaceId]);
if (pendingArchiveAttempts.has(key)) return;
pendingArchiveAttempts.add(key);
try {
if (input.confirm && !(await input.confirm())) return;
if (!isWorkspaceListed(input.workspace)) return;
// Archive hides the row synchronously. Undo can restore it and start a new
// archive while the previous daemon request is still settling.
return input.archive();
} finally {
pendingArchiveAttempts.delete(key);
}
}
interface WorkspaceArchiveClient {
archiveWorkspace: (workspaceId: string) => Promise<{ error: string | null; canceled?: boolean }>;
}
@@ -134,6 +134,36 @@ test("a fresh checkout read makes a newly initialized repository available to ca
expect(realpathSync.native(repoRoot)).toBe(realpathSync.native(repo));
}, 30_000);
test("a checkout read for reconciliation never scans the working tree", async () => {
const root = realpathSync(mkdtempSync(path.join(tmpdir(), "paseo-checkout-read-")));
const repo = path.join(root, "repo");
mkdirSync(repo);
const git = (...args: string[]) =>
execFileSync("git", ["-c", "commit.gpgsign=false", ...args], { cwd: repo, stdio: "pipe" });
git("init", "-b", "main");
git("config", "user.email", "test@example.com");
git("config", "user.name", "Test");
writeFileSync(path.join(repo, "README.md"), "base\n");
git("add", ".");
git("commit", "-m", "base");
const service = new WorkspaceGitServiceImpl({
logger: pino({ enabled: false }),
paseoHome: path.join(root, "home"),
});
cleanup.push(async () => {
await service.dispose();
rmSync(root, { recursive: true, force: true });
});
startGitCommandMetrics();
const checkout = await service.getCheckout(repo, { priority: "background" });
const verbs = stopGitCommandMetrics().commands.map((command) => command.args[0]);
expect(checkout).toMatchObject({ isGit: true, currentBranch: "main" });
expect(verbs.length).toBeGreaterThan(0);
expect(verbs.filter((verb) => ["status", "ls-files", "rev-list"].includes(verb))).toEqual([]);
}, 30_000);
test("recursive observation updates tracked state and prunes ignored storms", async () => {
const tempDir = realpathSync(mkdtempSync(path.join(tmpdir(), "paseo-git-observation-")));
const repoDir = path.join(tempDir, "repo");
@@ -427,7 +427,7 @@ describe("WorkspaceGitServiceImpl primitive refresh entrypoint", () => {
test("getCheckout surfaces an unexpected Git read failure", async () => {
const service = createService({
getCheckoutStatus: vi.fn(async () => {
getCheckoutIdentity: vi.fn(async () => {
throw new Error("Git read failed");
}),
});
@@ -18,6 +18,7 @@ import {
getCheckoutRefDerivedState,
getCheckoutSnapshotFacts,
getCheckoutShortstat,
getCheckoutIdentity,
getCheckoutStatus,
getCheckoutWorktreeState,
getPullRequestStatus,
@@ -407,6 +408,7 @@ interface WorkspaceGitServiceDependencies {
subscribe: SubscribeToFileChanges;
getCheckoutSnapshotFacts: typeof getCheckoutSnapshotFacts;
getCheckoutRefDerivedState: typeof getCheckoutRefDerivedState;
getCheckoutIdentity: typeof getCheckoutIdentity;
getCheckoutStatus: typeof getCheckoutStatus;
getCheckoutShortstat: typeof getCheckoutShortstat;
getCheckoutWorktreeState: typeof getCheckoutWorktreeState;
@@ -624,6 +626,7 @@ function buildDefaultWorkspaceGitServiceDeps(
subscribe,
getCheckoutSnapshotFacts,
getCheckoutRefDerivedState,
getCheckoutIdentity,
getCheckoutStatus,
getCheckoutShortstat,
getCheckoutWorktreeState,
@@ -857,7 +860,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
): Promise<ProjectCheckoutLitePayload> {
this.assertNotDisposed();
const normalizedCwd = resolve(cwd);
const status = await this.deps.getCheckoutStatus(normalizedCwd, {
const identity = await this.deps.getCheckoutIdentity(normalizedCwd, {
paseoHome: this.paseoHome,
worktreesRoot: this.worktreesRoot,
logger: this.logger,
@@ -866,7 +869,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
: {}),
});
const cached = this.getCachedSnapshot(normalizedCwd);
if (cached && cached.git.isGit !== status.isGit) {
if (cached && cached.git.isGit !== identity.isGit) {
// A fresh checkout read discovered a repository transition. Keep the
// shared snapshot current before exposing the new project capability.
await this.getSnapshot(normalizedCwd, {
@@ -875,7 +878,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
reason: "checkout-classification-changed",
});
}
if (!status.isGit) {
if (!identity.isGit) {
return checkoutLiteFromGitSnapshot(normalizedCwd, {
isGit: false,
currentBranch: null,
@@ -887,11 +890,11 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
}
return checkoutLiteFromGitSnapshot(normalizedCwd, {
isGit: true,
currentBranch: status.currentBranch,
remoteUrl: status.remoteUrl,
repoRoot: status.repoRoot,
isPaseoOwnedWorktree: status.isPaseoOwnedWorktree,
mainRepoRoot: status.mainRepoRoot,
currentBranch: identity.currentBranch,
remoteUrl: identity.remoteUrl,
repoRoot: identity.repoRoot,
isPaseoOwnedWorktree: identity.isPaseoOwnedWorktree,
mainRepoRoot: identity.mainRepoRoot,
});
}
@@ -175,6 +175,7 @@ class ObservedPlacements {
private readonly service: WorkspaceReconciliationService;
private started = false;
private checkoutReadCount = 0;
private readonly checkoutReadCwds: string[] = [];
constructor(private readonly specs: ProjectSpec[]) {
cleanupPaths.push(this.home);
@@ -324,6 +325,11 @@ class ObservedPlacements {
return this.checkoutReadCount;
}
/** Home-relative directories read since the last call, with portable separators. */
takeCheckoutReads(): string[] {
return this.checkoutReadCwds.splice(0).sort();
}
get pendingTimers(): number {
return this.clock.pendingCount;
}
@@ -370,6 +376,7 @@ class ObservedPlacements {
private async readCheckout(cwd: string): Promise<ProjectCheckoutLitePayload> {
this.checkoutReadCount += 1;
this.checkoutReadCwds.push(path.relative(this.home, cwd).split(path.sep).join("/"));
const configured = [...this.checkoutByCwd.entries()].find(([root]) =>
areEquivalentPaths(root, cwd),
)?.[1];
@@ -398,6 +405,18 @@ class ObservedPlacements {
}
}
/** Projects `a`, `b` and `c`, each rooted at `repo-<name>` with its own worktrees. */
function threeProjects(worktreeCount: number): ProjectSpec[] {
return ["a", "b", "c"].map((name) => ({
id: `project-${name}`,
root: `repo-${name}`,
workspaces: Array.from({ length: worktreeCount }, (_, index) => ({
id: `${name}${index + 1}`,
cwd: `repo-${name}/worktree-${index + 1}`,
})),
}));
}
describe("observed workspace placement", () => {
test("installs and publishes a new project before add resolves without Git feedback", async () => {
const observed = new ObservedPlacements([]);
@@ -462,6 +481,118 @@ describe("observed workspace placement", () => {
observed.dispose();
});
test("reads only the workspaces of the project whose Git directory changed", async () => {
const observed = new ObservedPlacements(threeProjects(3));
await observed.start();
observed.change("repo-b", ".git");
await observed.advanceBy(DEBOUNCE_MS);
expect(observed.takeCheckoutReads()).toEqual([
"repo-b",
"repo-b/worktree-1",
"repo-b/worktree-2",
"repo-b/worktree-3",
]);
observed.dispose();
});
test("updates nested projects and workspaces when a parent directory becomes a Git repository", async () => {
const observed = new ObservedPlacements([
{ id: "parent", root: "repo", workspaces: [{ id: "parent-ws", cwd: "repo" }] },
{ id: "nested", root: "repo/sub", workspaces: [{ id: "nested-ws", cwd: "repo/sub" }] },
{ id: "outside", root: "outside", workspaces: [{ id: "attached-ws", cwd: "repo/sub" }] },
{ id: "unrelated", root: "repo-other" },
]);
await observed.start();
try {
observed.makeProjectGit("parent");
observed.makeProjectGit("nested");
observed.change("repo", ".git");
await observed.advanceBy(DEBOUNCE_MS);
expect(observed.projectUpdates).toContainEqual({
kind: "upsert",
project: expect.objectContaining({ projectId: "nested", kind: "git" }),
});
expect(await observed.placement("nested-ws")).toMatchObject({ kind: "local_checkout" });
expect(await observed.placement("attached-ws")).toMatchObject({ kind: "local_checkout" });
expect(observed.workspaceBatches.map((batch) => batch.sort())).toEqual([
["attached-ws", "nested-ws", "parent-ws"],
]);
expect(observed.takeCheckoutReads()).toEqual(["outside", "repo", "repo/sub"]);
} finally {
observed.dispose();
}
});
test("turns Git changes under several roots into one read per changed root", async () => {
const observed = new ObservedPlacements(threeProjects(1));
await observed.start();
for (const root of ["repo-a", "repo-c", "repo-a", "repo-c", "repo-a"]) {
observed.change(root, ".git");
}
await observed.advanceBy(DEBOUNCE_MS);
expect(observed.takeCheckoutReads()).toEqual([
"repo-a",
"repo-a/worktree-1",
"repo-c",
"repo-c/worktree-1",
]);
observed.dispose();
});
test("a change that lands during a pass queues a pass for only that root", async () => {
const observed = new ObservedPlacements(threeProjects(1));
await observed.start();
observed.makeProjectGit("project-a");
observed.makeProjectGit("project-b");
const firstPassRead = observed.holdNextReconciliation();
const firstBatch = observed.waitForWorkspaceBatch();
const secondBatch = firstBatch.then(() => observed.waitForWorkspaceBatch());
observed.change("repo-a", ".git");
const firstPass = observed.advanceBy(DEBOUNCE_MS);
await firstPassRead.started;
observed.change("repo-b", ".git");
observed.change("repo-b", ".git");
await observed.advanceBy(DEBOUNCE_MS);
firstPassRead.release();
await firstPass;
await secondBatch;
expect(observed.workspaceBatches).toEqual([["a1"], ["b1"]]);
expect(observed.takeCheckoutReads()).toEqual([
"repo-a",
"repo-a/worktree-1",
"repo-b",
"repo-b/worktree-1",
]);
observed.dispose();
});
test("keeps the changed roots of a failed pass for the next one", async () => {
const observed = new ObservedPlacements([
{ id: "project-a", root: "repo-a", workspaces: [{ id: "a1", cwd: "repo-a" }] },
{ id: "project-b", root: "repo-b", workspaces: [{ id: "b1", cwd: "repo-b" }] },
]);
await observed.start();
observed.makeProjectGit("project-a");
observed.failNextReconciliation(new Error("registry unavailable"));
observed.change("repo-a", ".git");
await observed.advanceBy(DEBOUNCE_MS);
observed.change("repo-b", ".git");
await observed.advanceBy(DEBOUNCE_MS);
expect(observed.takeCheckoutReads()).toEqual(["repo-a", "repo-b"]);
expect((await observed.placement("a1"))?.kind).toBe("local_checkout");
observed.dispose();
});
test("recovers errored and temporarily unavailable watchers on the periodic pass", async () => {
const observed = new ObservedPlacements([
{ id: "project-errored", root: "errored" },
@@ -11,7 +11,7 @@ import type {
PersistedWorkspaceRecord,
} from "./workspace-registry.js";
import type { WorkspaceGitService } from "./workspace-git-service.js";
import { areEquivalentPaths } from "../utils/path.js";
import { areEquivalentPaths, isPathInsideRoot } from "../utils/path.js";
import {
deriveProjectKind,
reconcileWorkspacePlacement,
@@ -151,6 +151,9 @@ export class WorkspaceReconciliationService {
private disposed = false;
private started = false;
private reconciling = false;
// Project roots whose `.git` changed since the last observed pass. A metadata
// pass reads only these; the periodic full pass covers everything else.
private readonly changedRoots = new Set<string>();
private reconcileQueuedMode: "metadata" | "full" | null = null;
constructor(options: WorkspaceReconciliationServiceOptions) {
@@ -211,17 +214,34 @@ export class WorkspaceReconciliationService {
this.watchers.length = 0;
}
/** Reconciles mutable Git facts only; never archives missing records. */
async reconcileGitMetadata(): Promise<ReconciliationResult> {
/**
* Reconciles mutable Git facts only; never archives missing records. With
* `rootPaths`, read projects and workspaces whose checkouts can change under those paths.
*/
async reconcileGitMetadata(options?: { rootPaths?: string[] }): Promise<ReconciliationResult> {
const start = Date.now();
const changes: ReconciliationChange[] = [];
const [projects, workspaces] = await Promise.all([
const [allProjects, workspaces] = await Promise.all([
this.projectRegistry.list(),
this.workspaceRegistry.listActive(),
]);
const rootPaths = options?.rootPaths;
const isAffectedDirectory = (cwd: string) =>
rootPaths?.some((rootPath) => isPathInsideRoot(rootPath, cwd)) ?? true;
// A nested project can gain or lose its Git checkout when a parent .git changes.
const affectedProjectIds = new Set(
allProjects
.filter((project) => !project.archivedAt && isAffectedDirectory(project.rootPath))
.map((project) => project.projectId),
);
// An explicitly chosen project can own a workspace outside its root.
const workspacesByProject = new Map<string, PersistedWorkspaceRecord[]>();
const workspaceStates = await mapBounded(
workspaces.filter((w) => !w.archivedAt),
workspaces.filter(
(workspace) =>
!workspace.archivedAt &&
(affectedProjectIds.has(workspace.projectId) || isAffectedDirectory(workspace.cwd)),
),
async (workspace) => ({ workspace, state: await this.inspectDirectory(workspace.cwd) }),
);
for (const { workspace, state } of workspaceStates) {
@@ -232,7 +252,11 @@ export class WorkspaceReconciliationService {
workspacesByProject.set(workspace.projectId, siblings);
}
const projectStates = await mapBounded(
projects.filter((p) => !p.archivedAt),
allProjects.filter(
(project) =>
!project.archivedAt &&
(affectedProjectIds.has(project.projectId) || workspacesByProject.has(project.projectId)),
),
async (project) => ({ project, state: await this.inspectDirectory(project.rootPath) }),
);
await this.reconcileGitMetadataForProjects(
@@ -496,6 +520,7 @@ export class WorkspaceReconciliationService {
{ recursive: false },
(_event, filename) => {
if (filename === null || filename.toString() === ".git") {
this.changedRoots.add(project.rootPath);
this.scheduleObservedReconciliation();
}
},
@@ -539,28 +564,20 @@ export class WorkspaceReconciliationService {
}
return;
}
// Take the roots that changed so far. Events arriving during this pass
// land in a fresh set and queue one more pass for just those roots.
const rootPaths = [...this.changedRoots];
this.changedRoots.clear();
if (mode === "metadata" && rootPaths.length === 0) return;
this.reconciling = true;
try {
await this.syncProjectRootWatches();
const result = mode === "full" ? await this.runOnce() : await this.reconcileGitMetadata();
const workspaceIds = new Set<string>();
const projectIds = new Set<string>();
for (const change of result.changesApplied) {
if (change.kind === "workspace_updated" || change.kind === "workspace_archived") {
workspaceIds.add(change.workspaceId);
}
if (change.kind === "project_updated") projectIds.add(change.projectId);
}
if (projectIds.size > 0) {
const workspaces = await this.workspaceRegistry.listActive();
for (const workspaceId of workspaceIdsForProjects(workspaces, projectIds)) {
workspaceIds.add(workspaceId);
}
}
if (!this.disposed && workspaceIds.size > 0) {
await this.onWorkspacesChanged?.(Array.from(workspaceIds));
}
const result =
mode === "full" ? await this.runOnce() : await this.reconcileGitMetadata({ rootPaths });
await this.publishChangedWorkspaces(result);
} catch (error) {
// A failed pass keeps its roots pending for the next pass.
for (const rootPath of rootPaths) this.changedRoots.add(rootPath);
if (!this.disposed) {
this.logger.warn({ err: error }, "Workspace reconciliation failed");
}
@@ -574,6 +591,26 @@ export class WorkspaceReconciliationService {
}
}
private async publishChangedWorkspaces(result: ReconciliationResult): Promise<void> {
const workspaceIds = new Set<string>();
const projectIds = new Set<string>();
for (const change of result.changesApplied) {
if (change.kind === "workspace_updated" || change.kind === "workspace_archived") {
workspaceIds.add(change.workspaceId);
}
if (change.kind === "project_updated") projectIds.add(change.projectId);
}
if (projectIds.size > 0) {
const workspaces = await this.workspaceRegistry.listActive();
for (const workspaceId of workspaceIdsForProjects(workspaces, projectIds)) {
workspaceIds.add(workspaceId);
}
}
if (!this.disposed && workspaceIds.size > 0) {
await this.onWorkspacesChanged?.(Array.from(workspaceIds));
}
}
private async readCheckout(cwd: string): Promise<ProjectCheckoutLitePayload> {
if (!this.workspaceGitService) {
return {
@@ -0,0 +1,88 @@
import { execFileSync } from "node:child_process";
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
import { realpath } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { getCheckoutIdentity, getCheckoutStatus } from "./checkout-git.js";
import { createWorktree } from "./worktree.js";
import { startGitCommandMetrics, stopGitCommandMetrics } from "./run-git-command.js";
function git(cwd: string, ...args: string[]): void {
execFileSync("git", ["-c", "commit.gpgsign=false", ...args], { cwd, stdio: "ignore" });
}
describe("getCheckoutIdentity", () => {
let tempDir: string;
let paseoHome: string;
let repoDir: string;
let linkedDir: string;
let plainDir: string;
beforeEach(() => {
tempDir = realpathSync(mkdtempSync(join(tmpdir(), "checkout-identity-")));
paseoHome = join(tempDir, "paseo-home");
repoDir = join(tempDir, "repo");
linkedDir = join(tempDir, "linked");
plainDir = join(tempDir, "plain");
mkdirSync(paseoHome);
mkdirSync(repoDir);
mkdirSync(plainDir);
git(repoDir, "init", "-b", "main");
git(repoDir, "config", "user.email", "test@test.com");
git(repoDir, "config", "user.name", "Test");
writeFileSync(join(repoDir, "tracked.txt"), "tracked\n");
git(repoDir, "add", ".");
git(repoDir, "commit", "-m", "initial");
git(repoDir, "remote", "add", "origin", "https://github.com/acme/widgets.git");
git(repoDir, "worktree", "add", "-b", "feature", linkedDir);
});
afterEach(() => {
rmSync(tempDir, { recursive: true, force: true });
});
it("reports the same identity as the full status for a checkout, linked and Paseo worktrees and a plain folder", async () => {
const paseoWorktree = await createWorktree({
cwd: repoDir,
worktreeSlug: "alpha",
source: { kind: "branch-off", baseBranch: "main", branchName: "alpha" },
paseoHome,
});
for (const cwd of [repoDir, linkedDir, paseoWorktree.worktreePath]) {
const status = await getCheckoutStatus(cwd, { paseoHome });
const identity = await getCheckoutIdentity(cwd, { paseoHome });
if (!status.isGit) throw new Error(`${cwd} should be a git checkout`);
expect(identity).toEqual({
isGit: true,
repoRoot: status.repoRoot,
mainRepoRoot: status.mainRepoRoot,
currentBranch: status.currentBranch,
remoteUrl: status.remoteUrl,
isPaseoOwnedWorktree: status.isPaseoOwnedWorktree,
});
}
const mainRepoRoot = await realpath(repoDir);
expect(await getCheckoutIdentity(linkedDir, { paseoHome })).toMatchObject({
currentBranch: "feature",
mainRepoRoot,
});
expect(await getCheckoutIdentity(paseoWorktree.worktreePath, { paseoHome })).toMatchObject({
isPaseoOwnedWorktree: true,
mainRepoRoot,
});
expect(await getCheckoutIdentity(plainDir, { paseoHome })).toEqual({ isGit: false });
});
it("never scans the working tree or compares commits", async () => {
startGitCommandMetrics();
await getCheckoutIdentity(repoDir, { paseoHome });
await getCheckoutIdentity(linkedDir, { paseoHome });
const verbs = stopGitCommandMetrics().commands.map((command) => command.args[0]);
expect(verbs.length).toBeGreaterThan(0);
expect(
verbs.filter((verb) => ["status", "ls-files", "rev-list", "diff"].includes(verb)),
).toEqual([]);
});
});
+54
View File
@@ -2406,6 +2406,60 @@ async function getUntrackedDiffText(
};
}
export type CheckoutIdentity =
| { isGit: false }
| {
isGit: true;
repoRoot: string;
mainRepoRoot: string | null;
currentBranch: string | null;
remoteUrl: string | null;
isPaseoOwnedWorktree: boolean;
};
/**
* What a checkout is, without the state of its files. Reports the same identity fields as
* `getCheckoutStatus` but never scans the working tree (`status`), compares against a base, or
* counts commits, so reading many checkouts in the background stays cheap.
*/
export async function getCheckoutIdentity(
cwd: string,
context?: CheckoutContext,
): Promise<CheckoutIdentity> {
const inspected = await inspectCheckoutContext(cwd, context);
if (!inspected) {
return { isGit: false };
}
const { worktreeRoot, currentBranch, remoteUrl, paseoWorktree } = inspected;
const mainRepoRoot = await getMainRepoRootFromCommonDir(
cwd,
inspected.gitCommonDir,
context,
).catch(() => null);
// `getCheckoutStatus` reports a worktree as Paseo-owned only when it also resolves a base.
const isPaseoOwnedWorktree =
paseoWorktree.isPaseoOwnedWorktree &&
Boolean(
storedBaseRefFromMetadata(await readPaseoWorktreeMetadata(worktreeRoot)) ??
(await resolveBaseRef(cwd, context)),
);
const isLinkedCheckout = mainRepoRoot !== null && resolve(mainRepoRoot) !== resolve(worktreeRoot);
let reportedMainRepoRoot: string | null = null;
if (isPaseoOwnedWorktree) {
reportedMainRepoRoot = mainRepoRoot ?? worktreeRoot;
} else if (isLinkedCheckout) {
reportedMainRepoRoot = mainRepoRoot;
}
return {
isGit: true,
repoRoot: worktreeRoot,
mainRepoRoot: reportedMainRepoRoot,
currentBranch,
remoteUrl,
isPaseoOwnedWorktree,
};
}
export async function getCheckoutStatus(
cwd: string,
context?: CheckoutContext,
@@ -350,18 +350,10 @@ index b849f78..24c06f3 100644
factory: RendererFactory,
) {
diff --git a/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/renderer/ListRenderer.kt b/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/renderer/ListRenderer.kt
index 2bac5b1..021debd 100644
index 2bac5b1..ff2d2c2 100644
--- a/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/renderer/ListRenderer.kt
+++ b/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/renderer/ListRenderer.kt
@@ -6,6 +6,7 @@ import com.swmansion.enriched.markdown.spans.ListItemSpacingSpan
import com.swmansion.enriched.markdown.spans.MarginBottomSpan
import com.swmansion.enriched.markdown.styles.ListStyle
import com.swmansion.enriched.markdown.utils.text.span.SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE
+import com.swmansion.enriched.markdown.utils.text.span.SPAN_FLAGS_LINE_HEIGHT_PRIORITY
import com.swmansion.enriched.markdown.utils.text.span.applyLineHeightSkippingImages
import com.swmansion.enriched.markdown.utils.text.span.applyMarginTop
@@ -16,7 +17,7 @@ class ListRenderer(
@@ -16,7 +16,7 @@ class ListRenderer(
override fun render(
node: MarkdownASTNode,
builder: SpannableStringBuilder,
@@ -370,23 +362,6 @@ index 2bac5b1..021debd 100644
onLinkLongPress: ((String) -> Unit)?,
factory: RendererFactory,
) {
@@ -68,7 +69,15 @@ class ListRenderer(
// TODO: LineHeightSpan may also clip superscript/subscript glyphs that extend
// outside the normal line bounds. A similar "skip" strategy as for images may
// be needed here once super/subscript usage in practice is better understood.
- applyLineHeightSkippingImages(builder, start, builder.length, style.lineHeight)
+ // Priority flag so the list-wide line height iterates before inner block spacer
+ // spans (blockquote padding/margin, heading margin) instead of inflating them.
+ applyLineHeightSkippingImages(
+ builder,
+ start,
+ builder.length,
+ style.lineHeight,
+ SPAN_FLAGS_LINE_HEIGHT_PRIORITY,
+ )
// Item spacing and external bottom margin are only handled by the root-level list
if (depth == 0) {
diff --git a/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/renderer/NodeRenderer.kt b/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/renderer/NodeRenderer.kt
index 354b31a..77b1e14 100644
--- a/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/renderer/NodeRenderer.kt
@@ -3031,18 +3006,10 @@ index 0000000..11911c8
+ }
+}
diff --git a/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/MeasurementStore.kt b/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/MeasurementStore.kt
index f4840e4..6b7e61f 100644
index f4840e4..e36b444 100644
--- a/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/MeasurementStore.kt
+++ b/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/MeasurementStore.kt
@@ -45,6 +45,7 @@ import com.swmansion.enriched.markdown.utils.common.parseLinkPillContent
import com.swmansion.enriched.markdown.utils.common.parseLinkRecognition
import com.swmansion.enriched.markdown.utils.text.extensions.replaceMathSpansWithPlaceholders
import com.swmansion.enriched.markdown.utils.text.span.prepareWidthAwareSpans
+import com.swmansion.enriched.markdown.utils.text.view.wrapForInsertionOrderedLayout
import java.util.concurrent.ConcurrentHashMap
import kotlin.math.ceil
@@ -66,9 +67,11 @@ object MeasurementStore {
@@ -66,9 +66,11 @@ object MeasurementStore {
val spannable: CharSequence?,
val paintParams: PaintParams,
val markdownHash: Int,
@@ -3054,7 +3021,7 @@ index f4840e4..6b7e61f 100644
// Store font scaling settings per view ID
private data class FontScalingSettings(
@@ -133,7 +136,10 @@ object MeasurementStore {
@@ -133,7 +135,10 @@ object MeasurementStore {
YogaMeasureOutput.getHeight(newSize) + PixelUtil.toDIPFromPixel(trailingMarginBottomPx),
)
}
@@ -3066,7 +3033,7 @@ index f4840e4..6b7e61f 100644
return oldSize != newSize
}
@@ -144,7 +150,7 @@ object MeasurementStore {
@@ -144,7 +149,7 @@ object MeasurementStore {
}
fun invalidate(id: Int) {
@@ -3075,7 +3042,7 @@ index f4840e4..6b7e61f 100644
}
// Content-box width (px) the measure pass last wrapped at; the display view insets to match (#805).
@@ -212,7 +218,7 @@ object MeasurementStore {
@@ -212,7 +217,7 @@ object MeasurementStore {
val previous = fontScalingSettings[viewId]
fontScalingSettings[viewId] = FontScalingSettings(allowFontScaling, maxFontSizeMultiplier)
if (previous != null && (previous.allowFontScaling != allowFontScaling || previous.maxFontSizeMultiplier != maxFontSizeMultiplier)) {
@@ -3084,7 +3051,7 @@ index f4840e4..6b7e61f 100644
}
}
@@ -285,7 +291,43 @@ object MeasurementStore {
@@ -285,7 +290,43 @@ object MeasurementStore {
val fontScale = checkAndUpdateFontScale(context, allowFontScaling, maxFontSizeMultiplier)
@@ -3129,7 +3096,7 @@ index f4840e4..6b7e61f 100644
if (splitTableSegments) {
return measureAndCacheSplit(context, id, width, props, allowFontScaling, fontScale, maxFontSizeMultiplier)
}
@@ -295,7 +337,7 @@ object MeasurementStore {
@@ -295,7 +336,7 @@ object MeasurementStore {
val currentHash = computePropsHash(props, allowFontScaling, fontScale, maxFontSizeMultiplier)
@@ -3138,7 +3105,7 @@ index f4840e4..6b7e61f 100644
return measureAndCache(context, safeId, width, props, allowFontScaling, fontScale, maxFontSizeMultiplier)
}
@@ -332,8 +374,11 @@ object MeasurementStore {
@@ -332,8 +373,11 @@ object MeasurementStore {
val imageRequestHeaders = parseImageRequestHeaders(props.getArrayOrNull("imageRequestHeaders"))
val linkPillContent = parseLinkPillContent(props.getArrayOrNull("linkPillContent"))
var result = markdown.hashCode()
@@ -3152,7 +3119,7 @@ index f4840e4..6b7e61f 100644
result = 31 * result + parseLinkRecognition(props.getMapOrNull("linkRecognition")).hashCode()
result = 31 * result + fontScale.toBits()
result = 31 * result + allowFontScaling.hashCode()
@@ -356,6 +401,7 @@ object MeasurementStore {
@@ -356,6 +400,7 @@ object MeasurementStore {
if (lastKnownFontScale != 1.0f) {
lastKnownFontScale = 1.0f
data.clear()
@@ -3160,7 +3127,7 @@ index f4840e4..6b7e61f 100644
}
return 1.0f
}
@@ -368,6 +414,7 @@ object MeasurementStore {
@@ -368,6 +413,7 @@ object MeasurementStore {
if (currentFontScale != lastKnownFontScale) {
lastKnownFontScale = currentFontScale
data.clear()
@@ -3168,52 +3135,6 @@ index f4840e4..6b7e61f 100644
}
return currentFontScale
}
@@ -635,7 +682,7 @@ object MeasurementStore {
}
}
- private fun createStaticLayout(
+ internal fun createStaticLayout(
text: CharSequence,
fontSize: Float,
widthPx: Int,
@@ -643,8 +690,9 @@ object MeasurementStore {
): StaticLayout {
measurePaint.textSize = fontSize
prepareWidthAwareSpans(text, widthPx)
+ val measuredText = wrapForInsertionOrderedLayout(text)
return StaticLayout.Builder
- .obtain(text, 0, text.length, measurePaint, widthPx)
+ .obtain(measuredText, 0, measuredText.length, measurePaint, widthPx)
.setIncludePad(false)
.setLineSpacing(0f, 1f)
.apply {
@@ -730,10 +778,11 @@ object MeasurementStore {
val content = text ?: ""
val safeWidth = ceil(maxWidth).toInt().coerceAtLeast(1)
prepareWidthAwareSpans(content, safeWidth)
+ val measuredText = wrapForInsertionOrderedLayout(content)
val builder =
StaticLayout.Builder
- .obtain(content, 0, content.length, paint, safeWidth)
+ .obtain(measuredText, 0, measuredText.length, paint, safeWidth)
.setIncludePad(false)
.setLineSpacing(0f, 1f)
@@ -836,10 +885,11 @@ object MeasurementStore {
val content = text ?: ""
val widthPx = ceil(maxWidth).toInt().coerceAtLeast(1)
prepareWidthAwareSpans(content, widthPx)
+ val measuredText = wrapForInsertionOrderedLayout(content)
val layout =
StaticLayout.Builder
- .obtain(content, 0, content.length, paint, widthPx)
+ .obtain(measuredText, 0, measuredText.length, paint, widthPx)
.setIncludePad(false)
.setLineSpacing(0f, 1f)
.apply {
diff --git a/node_modules/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/MeasurementSizeCacheTest.kt b/node_modules/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/MeasurementSizeCacheTest.kt
new file mode 100644
index 0000000..b3394c4
@@ -4075,290 +3996,3 @@ diff --git a/node_modules/react-native-enriched-markdown/lib/module/web/utils.js
+}
//# sourceMappingURL=utils.js.map
\ No newline at end of file
diff --git a/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/TextViewSetup.kt b/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/TextViewSetup.kt
index 4b2ad01..8742c0c 100644
--- a/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/TextViewSetup.kt
+++ b/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/TextViewSetup.kt
@@ -11,6 +11,9 @@ import androidx.appcompat.widget.AppCompatTextView
import androidx.core.view.ViewCompat
import com.swmansion.enriched.markdown.accessibility.AccessibleMarkdownTextView
+internal fun wrapForInsertionOrderedLayout(source: CharSequence): CharSequence =
+ if (source is SpannableStringBuilder) InsertionOrderedSpannable(source) else source
+
/**
* Adopts the renderer's buffer instead of copying it: the default factory's copy is
* quadratic in span count. Safe because each segment's buffer is owned by one view.
diff --git a/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/segments/SegmentHeightMeasurer.kt b/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/segments/SegmentHeightMeasurer.kt
index 162ebfb..6e40bd8 100644
--- a/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/segments/SegmentHeightMeasurer.kt
+++ b/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/segments/SegmentHeightMeasurer.kt
@@ -9,6 +9,7 @@ import android.text.TextPaint
import com.swmansion.enriched.markdown.styles.StyleConfig
import com.swmansion.enriched.markdown.utils.text.extensions.replaceMathSpansWithPlaceholders
import com.swmansion.enriched.markdown.utils.text.span.prepareWidthAwareSpans
+import com.swmansion.enriched.markdown.utils.text.view.wrapForInsertionOrderedLayout
import kotlin.math.ceil
/**
@@ -105,8 +106,9 @@ object SegmentHeightMeasurer {
textSize = fontSizePx
}
prepareWidthAwareSpans(text, widthPx)
+ val measuredText = wrapForInsertionOrderedLayout(text)
return StaticLayout.Builder
- .obtain(text, 0, text.length, paint, widthPx)
+ .obtain(measuredText, 0, measuredText.length, paint, widthPx)
.setIncludePad(false)
.setLineSpacing(0f, 1f)
.apply {
diff --git a/b/node_modules/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/ListBlockquoteMeasurementTest.kt b/node_modules/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/ListBlockquoteMeasurementTest.kt
new file mode 100644
index 0000000..6115a30
--- /dev/null
+++ b/node_modules/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/ListBlockquoteMeasurementTest.kt
@@ -0,0 +1,244 @@
+package com.swmansion.enriched.markdown
+
+import android.graphics.Paint
+import android.text.Layout
+import android.text.SpannableStringBuilder
+import android.text.style.LineHeightSpan as AndroidLineHeightSpan
+import android.util.TypedValue
+import android.view.View.MeasureSpec
+import com.facebook.react.bridge.JavaOnlyArray
+import com.facebook.react.bridge.JavaOnlyMap
+import com.facebook.react.uimanager.DisplayMetricsHolder
+import com.swmansion.enriched.markdown.parser.MarkdownASTNode
+import com.swmansion.enriched.markdown.parser.MarkdownASTNode.NodeType
+import com.swmansion.enriched.markdown.renderer.Renderer
+import com.swmansion.enriched.markdown.segments.SegmentHeightMeasurer
+import com.swmansion.enriched.markdown.spans.LineHeightSpan
+import com.swmansion.enriched.markdown.styles.StyleConfig
+import com.swmansion.enriched.markdown.utils.text.span.SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE
+import org.junit.Assert.assertEquals
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.RuntimeEnvironment
+import org.robolectric.annotation.Config
+import org.robolectric.annotation.GraphicsMode
+
+@RunWith(RobolectricTestRunner::class)
+@GraphicsMode(GraphicsMode.Mode.NATIVE)
+@Config(manifest = Config.NONE, sdk = [34])
+class ListBlockquoteMeasurementTest {
+ private fun styleConfig(): StyleConfig {
+ val context = RuntimeEnvironment.getApplication()
+ DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(context)
+ val base =
+ JavaOnlyMap.of(
+ "fontFamily", "",
+ "fontWeight", "normal",
+ "fontStyle", "normal",
+ "fontSize", 16.0,
+ "lineHeight", 22.0,
+ "color", -16777216.0,
+ "backgroundColor", 0.0,
+ "borderColor", 0.0,
+ "borderWidth", 3.0,
+ "borderRadius", 0.0,
+ "padding", 12.0,
+ "gapWidth", 8.0,
+ "marginTop", 0.0,
+ "marginBottom", 12.0,
+ "marginLeft", 20.0,
+ "itemSpacing", 4.0,
+ "bulletColor", -16777216.0,
+ "bulletSize", 6.0,
+ "markerMinWidth", 0.0,
+ "markerColor", -16777216.0,
+ "markerFontWeight", "normal",
+ "textAlign", "left",
+ "underline", false,
+ "checkedColor", 0.0,
+ "checkmarkColor", 0.0,
+ "checkedTextColor", 0.0,
+ "checkboxSize", 18.0,
+ "checkboxBorderRadius", 2.0,
+ "checkedStrikethrough", false,
+ "particles", JavaOnlyMap.of("density", 1.0, "speed", 1.0),
+ "solid", JavaOnlyMap.of("borderRadius", 0.0),
+ "fontScale", 0.7,
+ "baselineOffsetScale", 0.3,
+ )
+ val styles = JavaOnlyMap()
+ listOf(
+ "paragraph",
+ "h1",
+ "h2",
+ "h3",
+ "h4",
+ "h5",
+ "h6",
+ "strong",
+ "em",
+ "strikethrough",
+ "underline",
+ "link",
+ "code",
+ "blockquote",
+ "list",
+ "codeBlock",
+ "thematicBreak",
+ "image",
+ "inlineImage",
+ "video",
+ "table",
+ "taskList",
+ "math",
+ "inlineMath",
+ "spoiler",
+ "superscript",
+ "subscript",
+ "highlight",
+ ).forEach { styles.putMap(it, base) }
+ styles.putArray("linkVariants", JavaOnlyArray())
+ return StyleConfig(styles, context, allowFontScaling = false, maxFontSizeMultiplier = 1f)
+ }
+
+ private fun measureTextView(
+ text: CharSequence,
+ fontSizePx: Float,
+ widthPx: Int,
+ ): EnrichedMarkdownInternalText {
+ val context = RuntimeEnvironment.getApplication()
+ return EnrichedMarkdownInternalText(context).apply {
+ setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSizePx)
+ breakStrategy = Layout.BREAK_STRATEGY_HIGH_QUALITY
+ applyStyledText(text)
+ measure(
+ MeasureSpec.makeMeasureSpec(widthPx, MeasureSpec.EXACTLY),
+ MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
+ )
+ }
+ }
+
+ @Test
+ fun listNestedBlockquotesMatchMeasurementAndKeepSpacerHeights() {
+ val context = RuntimeEnvironment.getApplication()
+ val style = styleConfig()
+ val widthPx = 640
+ val fontSizePx = style.paragraphStyle.fontSize
+
+ val ast =
+ MarkdownASTNode(
+ NodeType.Document,
+ children =
+ listOf(
+ MarkdownASTNode(
+ NodeType.OrderedList,
+ attributes = mapOf("start" to "1"),
+ children =
+ listOf(
+ MarkdownASTNode(
+ NodeType.ListItem,
+ children =
+ listOf(
+ MarkdownASTNode(NodeType.Paragraph, children = listOf(MarkdownASTNode(NodeType.Text, "First item"))),
+ MarkdownASTNode(
+ NodeType.Blockquote,
+ children =
+ listOf(
+ MarkdownASTNode(NodeType.Paragraph, children = listOf(MarkdownASTNode(NodeType.Text, "First quote"))),
+ ),
+ ),
+ ),
+ ),
+ MarkdownASTNode(
+ NodeType.ListItem,
+ children =
+ listOf(
+ MarkdownASTNode(NodeType.Paragraph, children = listOf(MarkdownASTNode(NodeType.Text, "Second item"))),
+ MarkdownASTNode(
+ NodeType.Blockquote,
+ children =
+ listOf(
+ MarkdownASTNode(NodeType.Paragraph, children = listOf(MarkdownASTNode(NodeType.Text, "Second quote"))),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ MarkdownASTNode(NodeType.Paragraph, children = listOf(MarkdownASTNode(NodeType.Text, "Trailing paragraph"))),
+ ),
+ )
+
+ val renderer = Renderer().apply { configure(style, context) }
+ val rendered = renderer.renderDocument(ast)
+
+ val storeLayout = MeasurementStore.createStaticLayout(rendered, fontSizePx, widthPx, null)
+ val segmentLayout =
+ SegmentHeightMeasurer.createStaticLayout(rendered, fontSizePx, widthPx, Layout.BREAK_STRATEGY_HIGH_QUALITY)
+ val textView = measureTextView(rendered, fontSizePx, widthPx)
+
+ assertEquals("MeasurementStore and TextView must agree on height", textView.measuredHeight, storeLayout.height)
+ assertEquals("SegmentHeightMeasurer and TextView must agree on height", textView.measuredHeight, segmentLayout.height)
+
+ // Verify blockquote top-padding and bottom-margin spacer lines keep their configured
+ // heights instead of being inflated to list.lineHeight (22dp).
+ val paddingPx = style.blockquoteStyle.padding.toInt()
+ val marginBottomPx = style.blockquoteStyle.marginBottom.toInt()
+ val itemSpacingPx = style.listStyle.itemSpacing.toInt()
+ val spacerLineHeights =
+ (0 until storeLayout.lineCount)
+ .filter { line ->
+ val start = storeLayout.getLineStart(line)
+ val end = storeLayout.getLineEnd(line)
+ end - start == 1 && rendered[start] == '\n'
+ }.map { line -> storeLayout.getLineBottom(line) - storeLayout.getLineTop(line) }
+
+ assertEquals(
+ listOf(paddingPx, marginBottomPx + itemSpacingPx, paddingPx, marginBottomPx, marginBottomPx),
+ spacerLineHeights,
+ )
+ }
+
+ @Test
+ fun measurementStaticLayoutUsesInsertionOrderLikeTextView() {
+ val context = RuntimeEnvironment.getApplication()
+ DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(context)
+ val widthPx = 400
+ val fontSizePx = 16f
+
+ // Inner priority-0 spacer inserted before outer priority-0 LineHeightSpan:
+ // SpannableStringBuilder's unsorted fast path orders by start offset (outer first),
+ // while InsertionOrderedSpannable orders by insertion order (inner first, so outer inflates it).
+ val builder = SpannableStringBuilder("first\n\nsecond")
+ builder.setSpan(
+ object : AndroidLineHeightSpan {
+ override fun chooseHeight(
+ text: CharSequence,
+ start: Int,
+ end: Int,
+ spanstartv: Int,
+ v: Int,
+ fm: Paint.FontMetricsInt,
+ ) {
+ fm.top = 0
+ fm.ascent = 0
+ fm.descent = 12
+ fm.bottom = 12
+ }
+ },
+ 6,
+ 7,
+ SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE,
+ )
+ builder.setSpan(LineHeightSpan(40f), 0, builder.length, SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE)
+
+ val storeLayout = MeasurementStore.createStaticLayout(builder, fontSizePx, widthPx, null)
+ val segmentLayout =
+ SegmentHeightMeasurer.createStaticLayout(builder, fontSizePx, widthPx, Layout.BREAK_STRATEGY_HIGH_QUALITY)
+ val textView = measureTextView(builder, fontSizePx, widthPx)
+
+ assertEquals(textView.measuredHeight, storeLayout.height)
+ assertEquals(textView.measuredHeight, segmentLayout.height)
+ }
+}