From 5dc350034e803732d9406506bbd2970039205b3f Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:05:12 +0000 Subject: [PATCH 001/173] Keep large Import Session lists responsive on Web (#7872) * Virtualize long Import Session Web lists while preserving native and short-list scrolling * fix(app): measure import list headers through the existing layout event Keep the virtualized import list usable in the existing component harness without introducing an observer mock. Import React for the unit JSX transform. Co-authored-by: royenheart --------- Co-authored-by: royenheart Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../e2e/browser/import-session-flow.spec.ts | 137 ++++++++ .../app/e2e/support/helpers/import-session.ts | 34 +- .../src/components/import-session-list.tsx | 4 + .../components/import-session-list.types.ts | 13 + .../components/import-session-list.web.tsx | 141 ++++++++ .../src/components/import-session-sheet.tsx | 320 +++++++++++++----- 6 files changed, 555 insertions(+), 94 deletions(-) create mode 100644 packages/app/src/components/import-session-list.tsx create mode 100644 packages/app/src/components/import-session-list.types.ts create mode 100644 packages/app/src/components/import-session-list.web.tsx diff --git a/packages/app/e2e/browser/import-session-flow.spec.ts b/packages/app/e2e/browser/import-session-flow.spec.ts index c6d34f38f2..fe2f57c67a 100644 --- a/packages/app/e2e/browser/import-session-flow.spec.ts +++ b/packages/app/e2e/browser/import-session-flow.spec.ts @@ -229,6 +229,143 @@ test("captures the desktop import sheet and command-center entry", async ({ page }); }); +test("large import lists keep mounted rows bounded and remain scrollable", async ({ + page, +}, testInfo) => { + const fixtureDirectory = path.join(claudeConfigDirectory, "projects", "virtualization-fixture"); + await mkdir(fixtureDirectory, { recursive: true }); + try { + const newest = Date.now(); + for (let index = 0; index < 200; index += 1) { + const id = `virtualized-${String(index).padStart(3, "0")}`; + const file = path.join(fixtureDirectory, `${id}.jsonl`); + await writeFile( + file, + `${JSON.stringify({ + type: "user", + sessionId: id, + cwd: index % 2 === 0 ? scenario.projectRoot : scenario.worktreeDirectory, + message: { + role: "user", + content: `Virtualized session ${index}${index % 3 === 0 ? " with a longer preview that wraps onto a second line in a compact sheet" : ""}`, + }, + })}\n`, + ); + const timestamp = new Date(newest - index * 10); + await utimes(file, timestamp, timestamp); + } + for (const width of [1280, 390]) { + const flow = new ImportSessionFlow(page); + await flow.openWorkspace(scenario.project.workspaceId, { width, height: 844 }); + await flow.openGlobally(); + const rows = page.locator('[data-testid^="import-session-session-"]'); + const scrollToEnd = async (end = true) => { + // Scroll the body's real overflow element. Virtual rows need not exist yet. + await rows.first().evaluate((row, atEnd) => { + let element = row.parentElement; + while (element && !["auto", "scroll"].includes(getComputedStyle(element).overflowY)) { + element = element.parentElement; + } + if (!element) throw new Error("Import list has no scroll owner"); + element.scrollTop = atEnd ? element.scrollHeight : 0; + element.dispatchEvent(new Event("scroll")); + }, end); + }; + for (let pageIndex = 0; pageIndex < 3; pageIndex += 1) { + const loadMore = page.getByTestId("import-session-load-more"); + await expect(async () => { + await scrollToEnd(); + await expect(loadMore).toBeInViewport({ timeout: 500 }); + }).toPass({ timeout: 10_000 }); + await loadMore.click(); + if (pageIndex < 2) await expect(loadMore).toBeEnabled(); + } + await expect(async () => { + await scrollToEnd(); + await expect( + page.getByTestId("import-session-session-claude-virtualized-199"), + ).toBeInViewport({ timeout: 500 }); + }).toPass({ timeout: 10_000 }); + await expect.poll(() => rows.count()).toBeLessThan(100); + await page.screenshot({ path: testInfo.outputPath(`virtualized-${width}.png`) }); + if (width === 1280) { + const row = (index: number) => + page.getByTestId( + `import-session-session-claude-virtualized-${String(index).padStart(3, "0")}`, + ); + await expect(async () => { + await scrollToEnd(false); + await expect(row(0)).toBeInViewport({ timeout: 500 }); + }).toPass({ timeout: 10_000 }); + await row(0).focus(); + for (let index = 1; index <= 30; index += 1) { + await page.keyboard.press("Tab"); + await expect(row(index)).toBeFocused(); + } + for (let index = 29; index >= 15; index -= 1) { + await page.keyboard.press("Shift+Tab"); + await expect(row(index)).toBeFocused(); + } + const list = page.getByTestId("import-session-list"); + const scrollWithKey = async (event: "scroll" | "scrollend", key: string) => { + const listener = await list.evaluateHandle((node, eventName) => { + const promise = new Promise((resolve) => { + node.addEventListener(eventName, () => resolve(), { once: true }); + }); + return { promise }; + }, event); + try { + await page.keyboard.press(key); + await listener.evaluate((value) => value.promise); + } finally { + await listener.dispose(); + } + }; + const beforePageDown = await list.evaluate((node) => node.scrollTop); + await scrollWithKey("scroll", "PageDown"); + await expect + .poll(() => list.evaluate((node) => node.scrollTop)) + .toBeGreaterThan(beforePageDown); + await expect(row(15)).toBeFocused(); + await page.keyboard.press("End"); + await expect(row(15)).toBeFocused(); + await expect(row(199)).toBeInViewport(); + // Home must remain at the first row after the native page scroll ends. + await scrollWithKey("scrollend", "Home"); + await expect(row(0)).toBeInViewport(); + await expect(row(15)).toBeFocused(); + + await page.keyboard.press("End"); + await expect(row(199)).toBeInViewport(); + await row(199).focus(); + await scrollWithKey("scroll", "PageUp"); + await page.keyboard.press("Home"); + await expect(row(0)).toBeInViewport(); + await scrollWithKey("scrollend", "End"); + await expect(row(199)).toBeInViewport(); + await expect(row(199)).toBeFocused(); + await testInfo.attach("keyboard-scroll-owner", { + body: JSON.stringify( + await list.evaluate((node) => ({ + focusedRow: document.activeElement?.getAttribute("data-testid"), + scrollTop: node.scrollTop, + scrollHeight: node.scrollHeight, + clientHeight: node.clientHeight, + })), + ), + contentType: "application/json", + }); + await page.screenshot({ path: testInfo.outputPath("virtualized-keyboard-end.png") }); + await page.keyboard.press("Home"); + await expect(row(0)).toBeInViewport(); + } + await flow.close(); + } + } finally { + await rm(fixtureDirectory, { recursive: true, force: true }); + } +}); + async function capture(page: Page, testInfo: TestInfo, name: string): Promise { const outputPath = testInfo.outputPath(name); await page.screenshot({ path: outputPath, fullPage: true }); diff --git a/packages/app/e2e/support/helpers/import-session.ts b/packages/app/e2e/support/helpers/import-session.ts index 718b0d5965..9caabc5edd 100644 --- a/packages/app/e2e/support/helpers/import-session.ts +++ b/packages/app/e2e/support/helpers/import-session.ts @@ -27,7 +27,7 @@ export class ImportSessionFlow { await expectMobileAgentSidebarVisible(this.page); } await openGlobalNewWorkspaceComposer(this.page); - const button = this.page.getByTestId("new-workspace-import-session"); + const button = this.page.getByTestId("new-workspace-import-session").filter({ visible: true }); await expect(button).toHaveAccessibleName("Import session"); await expect(button).toBeInViewport(); } @@ -36,7 +36,7 @@ export class ImportSessionFlow { await this.openFromNewWorkspace(); } async openFromNewWorkspace() { - await this.page.getByTestId("new-workspace-import-session").click(); + await this.page.getByTestId("new-workspace-import-session").filter({ visible: true }).click(); await this.expectSheetReady(); } async openFromWorkspaceHeader() { @@ -86,7 +86,29 @@ export class ImportSessionFlow { expect((bounds?.x ?? width) + (bounds?.width ?? 1)).toBeLessThanOrEqual(width); } async revealSession(id: string) { - await this.page.getByTestId(rowTestId(id)).scrollIntoViewIfNeeded(); + const target = this.page.getByTestId(rowTestId(id)); + if ((await target.count()) === 0) { + await this.scrollList(false); + await expect(async () => { + if ((await target.count()) === 0) await this.scrollList(true); + await expect(target).toHaveCount(1, { timeout: 100 }); + }).toPass({ timeout: 10_000 }); + } + await target.scrollIntoViewIfNeeded(); + await expect(target).toBeInViewport(); + } + private async scrollList(forward: boolean) { + await this.page + .locator('[data-testid^="import-session-session-"]') + .first() + .evaluate((row, advance) => { + let element = row.parentElement; + while (element && !["auto", "scroll"].includes(getComputedStyle(element).overflowY)) + element = element.parentElement; + if (!element) throw new Error("Import list has no scroll owner"); + element.scrollTop = advance ? element.scrollTop + element.clientHeight * 0.8 : 0; + element.dispatchEvent(new Event("scroll")); + }, forward); } async search(query: string) { await this.page.getByTestId("import-session-search").fill(query); @@ -100,7 +122,8 @@ export class ImportSessionFlow { } async loadMore() { await this.page.getByTestId("import-session-load-more").click(); - await expect(this.page.getByText("Root session 20", { exact: true })).toBeVisible(); + await this.revealSession("fixture-root-20"); + await expect(this.page.getByText("Root session 20", { exact: true })).toBeInViewport(); await expect(this.page.getByTestId("import-session-load-more")).toHaveCount(0); } async retryProvider(provider: string, label: string) { @@ -111,6 +134,7 @@ export class ImportSessionFlow { await expect(this.page.getByRole("progressbar")).toHaveCount(0); } async importSession(id: string) { + await this.revealSession(id); await this.page.getByTestId(rowTestId(id)).click(); await expect(this.page.getByTestId("import-session-sheet")).toHaveCount(0, { timeout: 30_000, @@ -138,7 +162,7 @@ export class ImportSessionFlow { ); } async close() { - await this.page.keyboard.press("Escape"); + await this.page.getByRole("button", { name: "Close", exact: true }).last().click(); await expect(this.page.getByTestId("import-session-sheet")).toHaveCount(0); } async expectCommandCenterMatch() { diff --git a/packages/app/src/components/import-session-list.tsx b/packages/app/src/components/import-session-list.tsx new file mode 100644 index 0000000000..d2ff037651 --- /dev/null +++ b/packages/app/src/components/import-session-list.tsx @@ -0,0 +1,4 @@ +import type { ImportSessionListComponent } from "./import-session-list.types"; + +// Native keeps the sheet-owned ScrollView until its gestures and keyboard are verified. +export const ImportSessionList: ImportSessionListComponent | null = null; diff --git a/packages/app/src/components/import-session-list.types.ts b/packages/app/src/components/import-session-list.types.ts new file mode 100644 index 0000000000..e62b31bccb --- /dev/null +++ b/packages/app/src/components/import-session-list.types.ts @@ -0,0 +1,13 @@ +import type { ReactElement, ReactNode } from "react"; + +export interface ImportSessionListProps { + data: ReadonlyArray; + keyExtractor: (item: Item) => string; + renderItem: (item: Item) => ReactNode; + header: ReactElement | null; + footer: ReactElement | null; +} + +export type ImportSessionListComponent = ( + props: ImportSessionListProps, +) => ReactElement; diff --git a/packages/app/src/components/import-session-list.web.tsx b/packages/app/src/components/import-session-list.web.tsx new file mode 100644 index 0000000000..aa8f74cd7c --- /dev/null +++ b/packages/app/src/components/import-session-list.web.tsx @@ -0,0 +1,141 @@ +import React, { + useCallback, + useMemo, + useRef, + useState, + type CSSProperties, + type FocusEvent, + type KeyboardEvent, +} from "react"; +import { View, type LayoutChangeEvent } from "react-native"; +import { defaultRangeExtractor, useVirtualizer, type Range } from "@tanstack/react-virtual"; +import type { ImportSessionListProps } from "./import-session-list.types"; + +const SCROLLER_STYLE: CSSProperties = { + flex: 1, + minHeight: 0, + overflowY: "auto", + overflowX: "hidden", + overscrollBehavior: "contain", +}; +const CONTENT_STYLE: CSSProperties = { width: "100%", position: "relative" }; + +export function ImportSessionList({ + data, + keyExtractor, + renderItem, + header, + footer, +}: ImportSessionListProps) { + const scrollRef = useRef(null); + const [headerHeight, setHeaderHeight] = useState(0); + const [focusedKey, setFocusedKey] = useState(null); + const indexByKey = useMemo( + () => new Map(data.map((item, index) => [keyExtractor(item), index])), + [data, keyExtractor], + ); + const focusedIndex = focusedKey === null ? undefined : indexByKey.get(focusedKey); + const rangeExtractor = useCallback( + (range: Range) => { + const visible = defaultRangeExtractor(range); + if (focusedIndex === undefined) return visible; + // Keep focus and its Tab neighbours mounted when PageDown/End moves the window. + const focused = [focusedIndex - 1, focusedIndex, focusedIndex + 1].filter( + (index) => index >= 0 && index < data.length, + ); + return [...new Set([...visible, ...focused])].sort((left, right) => left - right); + }, + [data.length, focusedIndex], + ); + const handleFocus = useCallback((event: FocusEvent) => { + const row = event.target.closest("[data-session-key]"); + setFocusedKey(row?.dataset.sessionKey ?? null); + }, []); + const handleBlur = useCallback((event: FocusEvent) => { + if (!event.currentTarget.contains(event.relatedTarget)) setFocusedKey(null); + }, []); + const handleHeaderLayout = useCallback((event: LayoutChangeEvent) => { + setHeaderHeight(event.nativeEvent.layout.height); + }, []); + const getScrollElement = useCallback(() => scrollRef.current, []); + const getItemKey = useCallback( + (index: number) => keyExtractor(data[index]!), + [data, keyExtractor], + ); + const estimateSize = useCallback(() => 88, []); + const virtualizer = useVirtualizer({ + count: data.length, + getScrollElement, + getItemKey, + estimateSize, + scrollMargin: headerHeight, + overscan: 5, + rangeExtractor, + }); + const handleKeyDown = useCallback( + (event: KeyboardEvent) => { + const target = event.target; + if ( + event.defaultPrevented || + !(target instanceof HTMLElement) || + !event.currentTarget.contains(target) || + target.isContentEditable || + target.closest("input, textarea, select") + ) + return; + if (event.key === "End") { + event.preventDefault(); + // Reconcile the landing position as variable-height rows are measured. + virtualizer.scrollToIndex(data.length - 1, { align: "end" }); + } else if (event.key === "Home") { + event.preventDefault(); + virtualizer.scrollToOffset(0); + } else if (event.key === "PageDown" || event.key === "PageUp") { + event.preventDefault(); + // Native page-scroll animations can keep moving after Home or End. + const direction = event.key === "PageDown" ? 1 : -1; + virtualizer.scrollBy(direction * event.currentTarget.clientHeight); + } + }, + [data.length, virtualizer], + ); + const virtualRows = virtualizer.getVirtualItems(); + const totalSize = virtualizer.getTotalSize(); + const contentStyle = useMemo(() => ({ ...CONTENT_STYLE, height: totalSize }), [totalSize]); + const rowStyle = useCallback( + (offset: number): CSSProperties => ({ + ...CONTENT_STYLE, + position: "absolute", + top: 0, + transform: `translateY(${offset}px)`, + }), + [], + ); + + return ( +
+ {header} +
+ {virtualRows.map((row) => ( +
+ {renderItem(data[row.index]!)} +
+ ))} +
+
{footer}
+
+ ); +} diff --git a/packages/app/src/components/import-session-sheet.tsx b/packages/app/src/components/import-session-sheet.tsx index 3be15c0892..21296e54e0 100644 --- a/packages/app/src/components/import-session-sheet.tsx +++ b/packages/app/src/components/import-session-sheet.tsx @@ -1,4 +1,4 @@ -import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import React, { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react"; import { Pressable, type PressableStateCallbackType, Text, View } from "react-native"; import { keepPreviousData, useMutation, useQueries, useQueryClient } from "@tanstack/react-query"; import { useTranslation } from "react-i18next"; @@ -11,6 +11,7 @@ import { ChevronDown, Inbox, Layers, RotateCw } from "lucide-react-native"; import { StyleSheet, useUnistyles } from "react-native-unistyles"; import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet"; import { Button } from "@/components/ui/button"; +import { ImportSessionList } from "@/components/import-session-list"; import { LoadingSpinner } from "@/components/ui/loading-spinner"; import { Combobox, ComboboxItem, type ComboboxOption } from "@/components/ui/combobox"; import { useProviderIcon, useProviderIcons } from "@/components/provider-icons"; @@ -371,7 +372,33 @@ function ImportSessionActivityTime({ date }: { date: string }) { return {label}; } +function getSessionRowKey(entry: FetchRecentProviderSessionEntry): string { + return `${entry.providerId}:${entry.providerHandleId}`; +} + +function hasListHeader( + input: SheetStatusMessagesProps & { + showFilter: boolean; + hasProviderErrors: boolean; + }, +): boolean { + return ( + input.showFilter || + !input.isClientReady || + input.isSnapshotUnsupported || + input.hasNoImportableProviders || + (input.isLoadingSessions && !input.hasRows) || + input.importErrored || + input.hasProviderErrors + ); +} + function SessionRows({ + visible, + onClose, + header, + listHeader, + listFooter, serverId, entries, disabled, @@ -379,6 +406,11 @@ function SessionRows({ resolveFolder, onImportSession, }: { + visible: boolean; + onClose: () => void; + header: SheetHeader; + listHeader: ReactNode; + listFooter: ReactNode; serverId: string | null; entries: ReadonlyArray; disabled: boolean; @@ -386,20 +418,69 @@ function SessionRows({ resolveFolder: (entry: FetchRecentProviderSessionEntry) => string | null; onImportSession: (entry: FetchRecentProviderSessionEntry) => void; }) { + // Keep short results content-sized; only long lists need a bounded viewport. + const virtualized = ImportSessionList !== null && entries.length > 8; + const renderSessionRow = useCallback( + (entry: FetchRecentProviderSessionEntry) => ( + + ), + [serverId, disabled, importingSessionKey, resolveFolder, onImportSession], + ); + const renderItem = useCallback( + (item: FetchRecentProviderSessionEntry) => ( + {renderSessionRow(item)} + ), + [renderSessionRow], + ); + const virtualHeader = useMemo( + () => (listHeader ? {listHeader} : null), + [listHeader], + ); + const virtualFooter = useMemo( + () => {listFooter}, + [listFooter], + ); + return ( - - {entries.map((entry) => ( - - ))} - + + {ImportSessionList && virtualized ? ( + + + + ) : ( + <> + {listHeader} + {entries.length > 0 ? ( + {entries.map(renderSessionRow)} + ) : null} + {listFooter} + + )} + ); } @@ -726,85 +807,124 @@ export function ImportSessionSheet({ }); const showFilter = filterProviders.length > 1; const showLoadMore = hasMoreSessions(queries, pageLimit); - + const showListHeader = hasListHeader({ + showFilter, + isClientReady: Boolean(client), + isSnapshotUnsupported, + hasNoImportableProviders, + isLoadingSessions, + hasRows: visibleEntries.length > 0, + importErrored: importMutation.isError, + hasProviderErrors: providerErrorRows.length > 0, + }); + const listHeader = useMemo( + () => + showListHeader ? ( + + {showFilter ? ( + + + {selectedProvider === ALL_FILTER_VALUE ? ( + + ) : ( + + )} + + {selectedProviderLabel} + + + + + + ) : null} + 0} + importErrored={importMutation.isError} + /> + {providerErrorRows.length > 0 ? ( + + ) : null} + + ) : null, + [ + showListHeader, + showFilter, + filterTriggerStyle, + handleFilterOpen, + selectedProvider, + theme.colors.foregroundMuted, + SelectedProviderIcon, + selectedProviderLabel, + filterComboboxOptions, + handleFilterSelect, + renderFilterOption, + isFilterOpen, + client, + isSnapshotUnsupported, + hasNoImportableProviders, + isLoadingSessions, + visibleEntries.length, + importMutation.isError, + providerErrorRows, + handleRetryProvider, + ], + ); + const listFooter = useMemo( + () => ( + <> + {showLoadMore ? ( + + + + ) : null} + {showEmptyState ? : null} + + ), + [showLoadMore, handleLoadMore, isRefreshing, t, showEmptyState, emptyStateTitle], + ); return ( - - {showFilter ? ( - - - {selectedProvider === ALL_FILTER_VALUE ? ( - - ) : ( - - )} - - {selectedProviderLabel} - - - - - - ) : null} - 0} - importErrored={importMutation.isError} - /> - {providerErrorRows.length > 0 ? ( - - ) : null} - {visibleEntries.length > 0 ? ( - - ) : null} - {showLoadMore ? ( - - - - ) : null} - {showEmptyState ? : null} - + listHeader={listHeader} + listFooter={listFooter} + serverId={serverId} + entries={visibleEntries} + disabled={importMutation.isPending} + importingSessionKey={importingSessionKey} + resolveFolder={resolveFolder} + onImportSession={handleImportSession} + /> ); } @@ -853,9 +973,31 @@ const styles = StyleSheet.create((theme) => ({ fontSize: theme.fontSize.base, fontWeight: theme.fontWeight.medium, }, + listBody: { + gap: 0, + }, list: { + flex: 1, + minHeight: 0, + marginHorizontal: -theme.spacing[2], + }, + listHeader: { + marginHorizontal: theme.spacing[2], + paddingBottom: theme.spacing[4], + }, + listHeaderContent: { + gap: theme.spacing[4], + }, + smallList: { gap: theme.spacing[1], }, + listFooter: { + marginHorizontal: theme.spacing[2], + }, + listRow: { + marginHorizontal: theme.spacing[2], + paddingBottom: theme.spacing[1], + }, footer: { paddingTop: theme.spacing[2], alignItems: "center", From d0fd2e532059eeaec4c9e9e510fd65e1a3c6e1ed Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:50:06 +0000 Subject: [PATCH 002/173] fix(client): close failed SSH tunnels without crashing callers (#7876) Route SSH stdin stream errors through the existing tunnel failure handler so pending writes cannot emit an unhandled EPIPE. Reproduce the peer abort using real OpenSSH in an isolated caller process. Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- packages/client/src/node/ssh-tunnel.test.ts | 55 +++++++++++++++++++++ packages/client/src/node/ssh-tunnel.ts | 6 ++- 2 files changed, 59 insertions(+), 2 deletions(-) create mode 100644 packages/client/src/node/ssh-tunnel.test.ts diff --git a/packages/client/src/node/ssh-tunnel.test.ts b/packages/client/src/node/ssh-tunnel.test.ts new file mode 100644 index 0000000000..6bdfe27fe4 --- /dev/null +++ b/packages/client/src/node/ssh-tunnel.test.ts @@ -0,0 +1,55 @@ +import { execFile, spawnSync } from "node:child_process"; +import { promisify } from "node:util"; +import { expect, test } from "vitest"; + +const run = promisify(execFile); +const hasSsh = !spawnSync("ssh", ["-V"]).error; + +test.skipIf(!hasSsh)( + "an SSH peer abort during a pending write closes the tunnel without crashing its caller", + async () => { + // Isolate the caller so an unhandled stream error fails this assertion instead + // of crashing the test worker. Both the TCP peer and OpenSSH are real. + const { stdout } = await run( + process.execPath, + [ + "--import", + "tsx", + "--input-type=module", + "-e", + ` + import { createServer, createConnection } from 'node:net'; + import { once } from 'node:events'; + import { createSshTunnel } from ${JSON.stringify(new URL("./ssh-tunnel.ts", import.meta.url).href)}; + + const remote = createServer(socket => socket.destroy()); + remote.listen(0, '127.0.0.1'); + await once(remote, 'listening'); + const tunnel = await createSshTunnel({ + host: '127.0.0.1', sshPort: remote.address().port, daemonPort: 6767, + }); + const [host, port] = tunnel.endpoint.split(':'); + const client = createConnection({ host, port: Number(port) }); + client.on('error', () => undefined); + try { + const closed = new Promise(resolve => client.once('close', resolve)); + await once(client, 'connect'); + client.write(Buffer.alloc(8 * 1024 * 1024, 65)); + await closed; + console.log(JSON.stringify({ closed: client.destroyed, failure: tunnel.failureDetail() })); + } finally { + client.destroy(); + tunnel.close(); + await new Promise(resolve => remote.close(resolve)); + } + `, + ], + { timeout: 10_000 }, + ); + expect(JSON.parse(stdout)).toEqual({ + closed: true, + failure: expect.any(String), + }); + expect(JSON.parse(stdout).failure).not.toBe(""); + }, +); diff --git a/packages/client/src/node/ssh-tunnel.ts b/packages/client/src/node/ssh-tunnel.ts index 33900d0baa..a67c0a91c4 100644 --- a/packages/client/src/node/ssh-tunnel.ts +++ b/packages/client/src/node/ssh-tunnel.ts @@ -54,10 +54,12 @@ export function createSshTunnel(target: SshTransportTarget): Promise child.stderr.on("data", (chunk: Buffer | string) => { stderr = `${stderr}${chunk.toString()}`.slice(-SSH_STDERR_LIMIT); }); - child.on("error", (error) => { + const fail = (error: Error) => { failure = error.message; acceptedSocket.destroy(error); - }); + }; + child.on("error", fail); + child.stdin.on("error", fail); child.on("exit", (code, signal) => { if (code !== 0 || signal) failure = formatSshFailure(stderr, code, signal); acceptedSocket.destroy(failure ? new Error(failure) : undefined); From 8c9499dac61927b0814a2bc3b9646e7eb3534f7c Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Mon, 26 Oct 2026 10:48:07 +0700 Subject: [PATCH 003/173] fix(app): dismiss file link tooltips when leaving their panel (#7842) Retained chats suspend while their tooltip portals remain mounted. Remove the surface before suspension and clear open state and pending hover timers so returning to the chat does not revive it. --- .../assistant-file-link-tooltip.spec.ts | 69 +++++++++++++++++++ packages/app/src/components/ui/tooltip.tsx | 14 +++- 2 files changed, 82 insertions(+), 1 deletion(-) create mode 100644 packages/app/e2e/browser/assistant-file-link-tooltip.spec.ts diff --git a/packages/app/e2e/browser/assistant-file-link-tooltip.spec.ts b/packages/app/e2e/browser/assistant-file-link-tooltip.spec.ts new file mode 100644 index 0000000000..69cccc52dd --- /dev/null +++ b/packages/app/e2e/browser/assistant-file-link-tooltip.spec.ts @@ -0,0 +1,69 @@ +import { writeFile } from "node:fs/promises"; +import path from "node:path"; +import { test, expect, type Page } from "../support/fixtures"; +import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent"; + +async function readFileLinkTooltip(page: Page): Promise { + const link = page.getByRole("link", { name: "the guide", exact: true }); + await link.hover(); + await expect(page.getByRole("tooltip")).toContainText("guide.md"); +} + +async function leaveFileLink(page: Page): Promise { + await page.mouse.move(5, 5); + await expect(page.getByRole("tooltip")).toHaveCount(0); +} + +async function openLinkedFile(page: Page): Promise { + await page.getByRole("link", { name: "the guide", exact: true }).click(); + await expect(page.getByTestId("markdown-preview-frame")).toContainText("Example guide"); + await leaveFileLink(page); +} + +async function returnToAgent(page: Page): Promise { + await page.getByRole("button", { name: "Tooltip regression", exact: true }).click(); + await expect(page.getByRole("link", { name: "the guide", exact: true })).toBeVisible(); + await leaveFileLink(page); +} + +async function switchToFileTab(page: Page): Promise { + await page.getByRole("button", { name: "guide.md", exact: true }).click(); + await expect(page.getByTestId("markdown-preview-frame")).toContainText("Example guide"); + await leaveFileLink(page); +} + +test("opening an assistant file link dismisses its tooltip over the file tab", async ({ + page, +}, testInfo) => { + testInfo.setTimeout(120_000); + const agent = await seedMockAgentWorkspace({ + repoPrefix: "tooltip-5811-", + title: "Tooltip regression", + featureValues: { + mockStreamingAssistantResponse: "Read [the guide](./guide.md).", + mockStreamingAssistantIntervalMs: 5, + }, + }); + try { + await writeFile( + path.join(agent.cwd, "guide.md"), + "# Example guide\n\n" + "Plain paragraph.\n\n".repeat(150), + ); + await openAgentRoute(page, agent); + await agent.client.sendAgentMessage(agent.agentId, "Show the file link."); + await agent.client.waitForFinish(agent.agentId, 30_000); + + await readFileLinkTooltip(page); + await leaveFileLink(page); + await readFileLinkTooltip(page); + await openLinkedFile(page); + await returnToAgent(page); + await readFileLinkTooltip(page); + await switchToFileTab(page); + await returnToAgent(page); + await readFileLinkTooltip(page); + await leaveFileLink(page); + } finally { + await agent.cleanup(); + } +}); diff --git a/packages/app/src/components/ui/tooltip.tsx b/packages/app/src/components/ui/tooltip.tsx index ae00768a34..697a80fdcf 100644 --- a/packages/app/src/components/ui/tooltip.tsx +++ b/packages/app/src/components/ui/tooltip.tsx @@ -27,6 +27,7 @@ import { FadeIn, FadeOut } from "react-native-reanimated"; import { StyleSheet } from "react-native-unistyles"; import { useIsCompactFormFactor } from "@/constants/layout"; import { FloatingSurface } from "@/components/ui/floating"; +import { useRetainedPanelActive } from "@/components/retained-panel"; import { isNative, isWeb } from "@/constants/platform"; import { getOverlayRoot, OVERLAY_Z } from "@/lib/overlay-root"; @@ -256,8 +257,15 @@ export function Tooltip({ }); const isCompact = useIsCompactFormFactor(); + const active = useRetainedPanelActive(); const opensOnPress = isNative || isCompact; - const enabled = opensOnPress ? enabledOnMobile : enabledOnDesktop; + const enabled = active && (opensOnPress ? enabledOnMobile : enabledOnDesktop); + + // Remove the portal in the inactive commit, before the retained chat freezes. + // Closing also prevents the tooltip from returning when its panel is shown again. + useEffect(() => { + if (!active && isOpen) setIsOpen(false); + }, [active, isOpen, setIsOpen]); const value = useMemo( () => ({ @@ -329,6 +337,10 @@ export function TooltipTrigger({ }; }, [clearOpenTimer]); + useEffect(() => { + if (!ctx.enabled) clearOpenTimer(); + }, [ctx.enabled, clearOpenTimer]); + const handleHoverIn = useCallback( (e?: unknown) => { if (isCallable(onHoverIn)) onHoverIn(e); From 4bbacfed4652e0d44677dc99f5b86836384cca2b Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Mon, 26 Oct 2026 10:50:16 +0700 Subject: [PATCH 004/173] feat(app): fold finished agent turns behind a summary line (#7785) Long agent turns bury the answer under intermediate messages, thoughts and tool calls. A new Chat display preference (Full / Collapse tool calls / Collapse turns) replaces the tool call detail level. Collapse turns folds everything a finished turn did before its final message into one summary line under the prompt; opening it shows those rows inline behind the same indent rail that expanded tool call groups now use. Expanded turns stay real timeline rows so virtualization, chat find and scroll-to-message keep working; find and outline jumps open the turn that holds their target. Opening or closing a turn stops following output so the summary stays under the pointer. Collapse turns is the default for new installs only. Existing settings were materialized on first launch, so stored blobs without the new field map from the legacy tool call detail level and otherwise stay on Full. Co-authored-by: Ready <127541578+akaready@users.noreply.github.com> Co-authored-by: Waishnav <86405648+Waishnav@users.noreply.github.com> Co-authored-by: Shreyan Dey <90114886+Dey11@users.noreply.github.com> Co-authored-by: Sebastian Parfitt <7753735+Sebeb@users.noreply.github.com> --- packages/app/e2e/browser/changes-pane.spec.ts | 4 +- .../browser/tool-call-overview-sheet.spec.ts | 2 +- .../app/e2e/browser/tool-call-shimmer.spec.ts | 2 +- .../app/e2e/browser/turn-collapse.spec.ts | 67 +++++++++ packages/app/e2e/support/fixtures.ts | 5 + .../e2e/support/helpers/plugin-timeline.ts | 2 +- .../support/helpers/sidebar-nav-settings.ts | 5 +- .../chat-find/viewport.browser.test.ts | 1 + .../chat-outline/use-chat-outline.test.tsx | 3 + .../app/src/agent-stream/presentation.test.ts | 9 +- packages/app/src/agent-stream/presentation.ts | 80 ++++++++-- .../app/src/agent-stream/strategy-native.tsx | 1 + .../app/src/agent-stream/strategy-web.tsx | 9 +- packages/app/src/agent-stream/strategy.ts | 2 + .../agent-stream/turn-collapse/model.test.ts | 134 +++++++++++++++++ .../src/agent-stream/turn-collapse/model.ts | 122 +++++++++++++++ .../turn-collapse/summary-line.tsx | 48 ++++++ .../agent-stream/use-scroll-to-message.web.ts | 3 +- .../agent-stream/use-stream-history-window.ts | 3 +- packages/app/src/agent-stream/view.tsx | 140 ++++++++++++++++-- packages/app/src/components/indent-rail.tsx | 32 ++++ packages/app/src/components/message.tsx | 9 +- packages/app/src/hooks/use-settings/index.ts | 2 + .../src/hooks/use-settings/storage.test.ts | 37 ++++- .../app/src/hooks/use-settings/storage.ts | 21 ++- packages/app/src/i18n/resources/ar.ts | 17 ++- packages/app/src/i18n/resources/en.ts | 17 ++- packages/app/src/i18n/resources/es.ts | 17 ++- packages/app/src/i18n/resources/fr.ts | 17 ++- packages/app/src/i18n/resources/ja.ts | 17 ++- packages/app/src/i18n/resources/ko.ts | 17 ++- packages/app/src/i18n/resources/pt-BR.ts | 17 ++- packages/app/src/i18n/resources/ru.ts | 17 ++- packages/app/src/i18n/resources/zh-CN.ts | 17 ++- .../screens/settings/chat/chat-section.tsx | 28 ++-- .../tool-calls/detail-level/overview/label.ts | 45 ++++++ .../tool-calls/detail-level/overview/model.ts | 19 ++- .../tool-calls/detail-level/overview/view.tsx | 46 +----- .../src/tool-calls/detail-level/projection.ts | 4 +- packages/app/src/types/stream.ts | 6 + 40 files changed, 874 insertions(+), 170 deletions(-) create mode 100644 packages/app/e2e/browser/turn-collapse.spec.ts create mode 100644 packages/app/src/agent-stream/turn-collapse/model.test.ts create mode 100644 packages/app/src/agent-stream/turn-collapse/model.ts create mode 100644 packages/app/src/agent-stream/turn-collapse/summary-line.tsx create mode 100644 packages/app/src/components/indent-rail.tsx create mode 100644 packages/app/src/tool-calls/detail-level/overview/label.ts diff --git a/packages/app/e2e/browser/changes-pane.spec.ts b/packages/app/e2e/browser/changes-pane.spec.ts index 61173613ea..1ff6059460 100644 --- a/packages/app/e2e/browser/changes-pane.spec.ts +++ b/packages/app/e2e/browser/changes-pane.spec.ts @@ -1415,12 +1415,14 @@ test("collapsing and expanding restores the real horizontal scroll offset", asyn async function useCodeFont(page: Page, codeFontSize: number): Promise { await page.addInitScript( ({ settingsKey, fontSize }) => { - if (localStorage.getItem(settingsKey)) { + const settings = JSON.parse(localStorage.getItem(settingsKey) ?? "{}"); + if (settings.codeFontSize !== undefined) { return; } localStorage.setItem( settingsKey, JSON.stringify({ + ...settings, theme: "dark", sendBehavior: "interrupt", serviceUrlBehavior: "ask", diff --git a/packages/app/e2e/browser/tool-call-overview-sheet.spec.ts b/packages/app/e2e/browser/tool-call-overview-sheet.spec.ts index 927585b545..42831fad8a 100644 --- a/packages/app/e2e/browser/tool-call-overview-sheet.spec.ts +++ b/packages/app/e2e/browser/tool-call-overview-sheet.spec.ts @@ -143,7 +143,7 @@ async function configureOverviewToolCalls(page: Page): Promise { await page.addInitScript(() => { localStorage.setItem( "@paseo:app-settings", - JSON.stringify({ toolCallDetailLevel: "overview" }), + JSON.stringify({ chatDisplay: "collapseToolCalls" }), ); }); } diff --git a/packages/app/e2e/browser/tool-call-shimmer.spec.ts b/packages/app/e2e/browser/tool-call-shimmer.spec.ts index 71ef6555e6..40dde0aa99 100644 --- a/packages/app/e2e/browser/tool-call-shimmer.spec.ts +++ b/packages/app/e2e/browser/tool-call-shimmer.spec.ts @@ -161,7 +161,7 @@ test("measures an overview heading that becomes loading after its idle mount", a await page.addInitScript(() => { localStorage.setItem( "@paseo:app-settings", - JSON.stringify({ toolCallDetailLevel: "overview" }), + JSON.stringify({ chatDisplay: "collapseToolCalls" }), ); }); const agent = await seedMockAgentWorkspace({ diff --git a/packages/app/e2e/browser/turn-collapse.spec.ts b/packages/app/e2e/browser/turn-collapse.spec.ts new file mode 100644 index 0000000000..1deb050fa8 --- /dev/null +++ b/packages/app/e2e/browser/turn-collapse.spec.ts @@ -0,0 +1,67 @@ +import type { Page } from "@playwright/test"; +import { test, expect } from "../support/fixtures"; +import { expectComposerVisible } from "../support/helpers/composer"; +import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent"; + +type ChatDisplay = "full" | "collapseToolCalls" | "collapseTurns"; + +async function useChatDisplay(page: Page, chatDisplay: ChatDisplay): Promise { + await page.addInitScript((value) => { + localStorage.setItem("@paseo:app-settings", JSON.stringify({ chatDisplay: value })); + }, chatDisplay); +} + +async function seedAnsweredAgent(title: string) { + const agent = await seedMockAgentWorkspace({ + repoPrefix: "turn-collapse-", + title, + model: "ten-second-stream", + initialPrompt: "Why does the chat stop following new output?", + }); + await agent.client.waitForFinish(agent.agentId, 30_000); + await agent.client.sendAgentMessage(agent.agentId, "Make the fix and run the burst script."); + await agent.client.waitForFinish(agent.agentId, 30_000); + return agent; +} + +/** Chat rows between the latest turn's summary line and its reply, in document order. */ +async function rowsBetweenLatestSummaryAndReply(page: Page): Promise { + return page.evaluate(() => { + const rows = [...document.querySelectorAll("[data-message-id]")]; + const summaryRow = rows.findLastIndex((row) => row.querySelector("[data-testid=turn-summary]")); + const replyRow = rows.findLastIndex((row) => + row.querySelector("[data-testid=assistant-message]"), + ); + return replyRow - summaryRow - 1; + }); +} + +test.describe("Turn collapse", () => { + test("folds each answered turn behind a summary line that opens it", async ({ page }) => { + test.setTimeout(120_000); + await useChatDisplay(page, "collapseTurns"); + const agent = await seedAnsweredAgent("Turn collapse"); + try { + await openAgentRoute(page, agent); + await expectComposerVisible(page); + + const summary = page.getByTestId("turn-summary").last().getByRole("button"); + await expect(summary).toHaveText(/^Wrote \d+ messages?, edited 1 file/); + // Text chunks that stream back to back merge into one message, so the reply holds + // at least the stream's last chunk. + await expect(page.getByTestId("assistant-message").last()).toHaveText( + /\(end of synthetic stream\)$/, + ); + await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(0); + + await summary.click(); + await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBeGreaterThan(0); + await expect(summary).toBeInViewport(); + + await summary.click(); + await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(0); + } finally { + await agent.cleanup(); + } + }); +}); diff --git a/packages/app/e2e/support/fixtures.ts b/packages/app/e2e/support/fixtures.ts index c621f43fce..89cfb6937d 100644 --- a/packages/app/e2e/support/fixtures.ts +++ b/packages/app/e2e/support/fixtures.ts @@ -180,6 +180,11 @@ const test = daemonTest.extend<{ localStorage.setItem("@paseo:daemon-registry", JSON.stringify([daemon, ...extraHosts])); localStorage.removeItem("@paseo:settings"); localStorage.setItem("@paseo:create-agent-preferences", JSON.stringify(preferences)); + // New installs collapse finished turns; specs assert on the rows inside them, so they + // start from the full chat unless they seed their own settings. + if (!localStorage.getItem("@paseo:app-settings")) { + localStorage.setItem("@paseo:app-settings", JSON.stringify({ chatDisplay: "full" })); + } }, { daemon: testDaemon, diff --git a/packages/app/e2e/support/helpers/plugin-timeline.ts b/packages/app/e2e/support/helpers/plugin-timeline.ts index 145addc2ef..533b546022 100644 --- a/packages/app/e2e/support/helpers/plugin-timeline.ts +++ b/packages/app/e2e/support/helpers/plugin-timeline.ts @@ -116,7 +116,7 @@ export async function withTimelinePlugin( await page.addInitScript(() => { localStorage.setItem( "@paseo:app-settings", - JSON.stringify({ toolCallDetailLevel: "overview" }), + JSON.stringify({ chatDisplay: "collapseToolCalls" }), ); }); const agent = await seedMockAgentWorkspace({ diff --git a/packages/app/e2e/support/helpers/sidebar-nav-settings.ts b/packages/app/e2e/support/helpers/sidebar-nav-settings.ts index e3eff916e7..2037783ded 100644 --- a/packages/app/e2e/support/helpers/sidebar-nav-settings.ts +++ b/packages/app/e2e/support/helpers/sidebar-nav-settings.ts @@ -63,8 +63,9 @@ export async function seedSidebarFooterPreferences( ): Promise { await page.addInitScript( ({ key, sidebarFooterItems }) => { - if (localStorage.getItem(key)) return; - localStorage.setItem(key, JSON.stringify({ sidebarFooterItems })); + const settings = JSON.parse(localStorage.getItem(key) ?? "{}"); + if (settings.sidebarFooterItems) return; + localStorage.setItem(key, JSON.stringify({ ...settings, sidebarFooterItems })); }, { key: APP_SETTINGS_KEY, sidebarFooterItems: preferences }, ); diff --git a/packages/app/src/agent-stream/chat-find/viewport.browser.test.ts b/packages/app/src/agent-stream/chat-find/viewport.browser.test.ts index a7cf29994c..1b4b8d18e8 100644 --- a/packages/app/src/agent-stream/chat-find/viewport.browser.test.ts +++ b/packages/app/src/agent-stream/chat-find/viewport.browser.test.ts @@ -24,6 +24,7 @@ function viewport(root: HTMLElement, capture: Capture) { const handle: StreamViewportHandle = { scrollToBottom() {}, prepareForViewportChange() {}, + holdReadingPosition() {}, scrollToMessage(_messageId, occurrence) { if (occurrence) capture.occurrence = occurrence; }, diff --git a/packages/app/src/agent-stream/chat-outline/use-chat-outline.test.tsx b/packages/app/src/agent-stream/chat-outline/use-chat-outline.test.tsx index bd5a73ce94..890f6eaae7 100644 --- a/packages/app/src/agent-stream/chat-outline/use-chat-outline.test.tsx +++ b/packages/app/src/agent-stream/chat-outline/use-chat-outline.test.tsx @@ -265,6 +265,7 @@ describe("useChatOutline", () => { const viewport: StreamViewportHandle = { scrollToBottom: vi.fn(), prepareForViewportChange: vi.fn(), + holdReadingPosition: vi.fn(), scrollToMessage, }; const viewportRef = { current: viewport }; @@ -316,6 +317,7 @@ describe("useChatOutline", () => { current: { scrollToBottom: vi.fn(), prepareForViewportChange: vi.fn(), + holdReadingPosition: vi.fn(), scrollToMessage, }, }; @@ -371,6 +373,7 @@ describe("useChatOutline", () => { const viewport: StreamViewportHandle = { scrollToBottom: vi.fn(), prepareForViewportChange: vi.fn(), + holdReadingPosition: vi.fn(), scrollToMessage, }; const livePrompt = { diff --git a/packages/app/src/agent-stream/presentation.test.ts b/packages/app/src/agent-stream/presentation.test.ts index ef3a30e5c5..357b6c079b 100644 --- a/packages/app/src/agent-stream/presentation.test.ts +++ b/packages/app/src/agent-stream/presentation.test.ts @@ -4,6 +4,7 @@ import { transformTimelineItem, type TimelineItemTransform } from "@/plugins/tim import type { InstalledPlugin } from "@/plugins/types"; import { applyStreamEvent, + getStreamItemMessageId, hydrateStreamState, type StreamItem, type ToolCallItem, @@ -13,7 +14,7 @@ import type { AgentStreamEventPayload } from "@getpaseo/protocol/messages"; import { QueryClient } from "@tanstack/react-query"; import { describe, expect, it } from "vitest"; import { buildAgentStreamRenderModel } from "./model"; -import { createStreamPresentation, getStreamItemMessageId } from "./presentation"; +import { createStreamPresentation } from "./presentation"; const runtime = { paseo: {}, @@ -97,7 +98,11 @@ function pluginData(items: StreamItem[]): unknown[] { return items.flatMap((item) => (item.kind === "plugin" ? [item.data] : [])); } -const presentationOptions = { level: "overview" as const, isTurnActive: true }; +const presentationOptions = { + display: "collapseToolCalls" as const, + expandedTurnHostIds: new Set(), + isTurnActive: true, +}; function streamHarness(transform?: TimelineItemTransform) { let state: { tail: StreamItem[]; head: StreamItem[] } = { tail: [], head: [] }; diff --git a/packages/app/src/agent-stream/presentation.ts b/packages/app/src/agent-stream/presentation.ts index 4459486a7b..9e8e5b430e 100644 --- a/packages/app/src/agent-stream/presentation.ts +++ b/packages/app/src/agent-stream/presentation.ts @@ -1,3 +1,4 @@ +import type { ChatDisplay } from "@/hooks/use-settings"; import type { TimelineItemTransform } from "@/plugins/timeline/model"; import { projectPluginTimelineItems } from "@/plugins/timeline/projection"; import { @@ -5,23 +6,32 @@ import { projectToolCallDetailLevel, type PreparedToolCallHistory, type ToolCallDetailLevel, + type ToolCallDetailProjection, } from "@/tool-calls/detail-level/projection"; import type { StreamItem, UserMessageItem } from "@/types/stream"; +import { collapseTurns, type TurnCollapse } from "./turn-collapse/model"; interface PresentationInput { tail: StreamItem[]; head: StreamItem[]; transform: TimelineItemTransform | undefined; - level: ToolCallDetailLevel; + display: ChatDisplay; + /** User messages whose collapsed turn the reader opened. */ + expandedTurnHostIds: ReadonlySet; isTurnActive: boolean; } -/** Find and scrolling address a plugin row by the source it replaces. */ -export function getStreamItemMessageId(item: StreamItem): string { - if (item.kind === "plugin") return item.sourceId ?? item.id; - return item.id; +export interface StreamPresentation extends ToolCallDetailProjection { + turns: Omit; } +const NO_COLLAPSED_TURNS: StreamPresentation["turns"] = collapseTurns({ + tail: [], + isLatestTurnOpen: false, + expandedHostIds: new Set(), + getGroupedCalls: () => undefined, +}); + /** Source messages reach plugins before display projection. */ export function createStreamPresentation() { const userMessageCache = new WeakMap(); @@ -47,12 +57,47 @@ export function createStreamPresentation() { let preparedTail: StreamItem[] | undefined; let preparedLevel: ToolCallDetailLevel | undefined; let preparedHistory: PreparedToolCallHistory | null = null; + let collapsedSource: StreamItem[] | undefined; + let collapsedIsLatestTurnOpen = false; + let collapsedExpandedHostIds: ReadonlySet | undefined; + let collapsed: TurnCollapse | undefined; function presentRows(item: StreamItem): StreamItem[] { return [item.kind === "user_message" ? presentUserMessage(item) : item]; } - return (input: PresentationInput) => { + function collapse( + projection: ToolCallDetailProjection, + input: PresentationInput, + ): StreamPresentation { + if (input.display !== "collapseTurns") { + return { ...projection, turns: NO_COLLAPSED_TURNS }; + } + // Live text updates reach the head only, so the folded history is reused until the + // retained rows, the latest turn's liveness, or the reader's expanded turns change. + const isLatestTurnOpen = input.isTurnActive || projection.head.length > 0; + if ( + !collapsed || + collapsedSource !== projection.tail || + collapsedIsLatestTurnOpen !== isLatestTurnOpen || + collapsedExpandedHostIds !== input.expandedTurnHostIds + ) { + collapsed = collapseTurns({ + tail: projection.tail, + isLatestTurnOpen, + expandedHostIds: input.expandedTurnHostIds, + getGroupedCalls: (itemId) => projection.groupsByHostId.get(itemId)?.run.calls, + }); + collapsedSource = projection.tail; + collapsedIsLatestTurnOpen = isLatestTurnOpen; + collapsedExpandedHostIds = input.expandedTurnHostIds; + } + const { tail, ...turns } = collapsed; + return { ...projection, tail, turns }; + } + + return (input: PresentationInput): StreamPresentation => { + const level: ToolCallDetailLevel = input.display === "full" ? "detailed" : "overview"; // Retained history is not reprojected or regrouped on each live text update. if (historySource !== input.tail || historyTransform !== input.transform) { historyRows = projectPluginTimelineItems(input.tail, input.transform).flatMap( @@ -66,17 +111,20 @@ export function createStreamPresentation() { const blocks = presentRows(item); head.push(...blocks); } - if (preparedTail !== historyRows || preparedLevel !== input.level) { - preparedHistory = prepareToolCallHistory(input.level, historyRows); + if (preparedTail !== historyRows || preparedLevel !== level) { + preparedHistory = prepareToolCallHistory(level, historyRows); preparedTail = historyRows; - preparedLevel = input.level; + preparedLevel = level; } - return projectToolCallDetailLevel({ - level: input.level, - tail: historyRows, - head, - preparedHistory, - isTurnActive: input.isTurnActive, - }); + return collapse( + projectToolCallDetailLevel({ + level, + tail: historyRows, + head, + preparedHistory, + isTurnActive: input.isTurnActive, + }), + input, + ); }; } diff --git a/packages/app/src/agent-stream/strategy-native.tsx b/packages/app/src/agent-stream/strategy-native.tsx index e7568edfe8..7dc6e8d521 100644 --- a/packages/app/src/agent-stream/strategy-native.tsx +++ b/packages/app/src/agent-stream/strategy-native.tsx @@ -361,6 +361,7 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat bottomAnchorController.prepareForStickyViewportChange(); markNativeViewportSettling(); }, + holdReadingPosition: () => bottomAnchorController.detachByUser(), }; viewportRef.current = handle; return () => { diff --git a/packages/app/src/agent-stream/strategy-web.tsx b/packages/app/src/agent-stream/strategy-web.tsx index e57fc98e48..8e8bdf7680 100644 --- a/packages/app/src/agent-stream/strategy-web.tsx +++ b/packages/app/src/agent-stream/strategy-web.tsx @@ -20,7 +20,7 @@ import { withUnistyles } from "react-native-unistyles"; import { useRetainedPanelActive } from "@/components/retained-panel"; import { LoadingSpinner } from "@/components/ui/loading-spinner"; import { useStableEvent } from "@/hooks/use-stable-event"; -import type { StreamItem } from "@/types/stream"; +import { getStreamItemMessageId, type StreamItem } from "@/types/stream"; import type { Theme } from "@/styles/theme"; import { WEB_SCROLLBAR_SIZE_PX } from "@/styles/web-scrollbar"; import { DomOverlayScrollbar } from "@/components/ui/overlay-scrollbar/dom-overlay-scrollbar"; @@ -44,7 +44,6 @@ import { type HistoryStartSettleScheduler, } from "./history-start-settle-scheduler"; import { useChatFindSelectedMessageId } from "@/agent-stream/chat-find"; -import { getStreamItemMessageId } from "./presentation"; import { useScrollToMessage } from "./use-scroll-to-message.web"; interface CreateWebStreamStrategyInput { @@ -1174,6 +1173,11 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool } scheduleStickToBottom(); }, + holdReadingPosition: () => { + cancelPendingStickToBottom(); + setFollowOutput(false); + readingAnchor.scroll(scrollContainerRef.current?.scrollTop ?? 0); + }, scrollToMessage, }; viewportRef.current = handle; @@ -1186,6 +1190,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool }, [ cancelPendingStickToBottom, forceStickToBottom, + readingAnchor, scheduleStickToBottom, scrollToMessage, viewportRef, diff --git a/packages/app/src/agent-stream/strategy.ts b/packages/app/src/agent-stream/strategy.ts index 7604b48cdd..3d9df4d201 100644 --- a/packages/app/src/agent-stream/strategy.ts +++ b/packages/app/src/agent-stream/strategy.ts @@ -55,6 +55,8 @@ export interface StreamViewportHandle { focus?: () => void; scrollToBottom: (reason?: BottomAnchorLocalRequest["reason"]) => void; prepareForViewportChange: () => void; + /** Stop following output so the rows on screen stay put while rows below them open or close. */ + holdReadingPosition: () => void; scrollToMessage?: (messageId: string, occurrence?: ScrollToMessageOccurrence) => void; } diff --git a/packages/app/src/agent-stream/turn-collapse/model.test.ts b/packages/app/src/agent-stream/turn-collapse/model.test.ts new file mode 100644 index 0000000000..4535b14d9e --- /dev/null +++ b/packages/app/src/agent-stream/turn-collapse/model.test.ts @@ -0,0 +1,134 @@ +import { describe, expect, it } from "vitest"; +import type { StreamItem, ToolCallItem } from "@/types/stream"; +import { collapseTurns, type CollapseTurnsInput } from "./model"; + +const at = new Date("2026-01-01T00:00:00.000Z"); + +function user(id: string): StreamItem { + return { kind: "user_message", id, text: id, timestamp: at }; +} + +function reply(id: string): StreamItem { + return { kind: "assistant_message", id, text: id, timestamp: at }; +} + +function thought(id: string): StreamItem { + return { kind: "thought", id, text: id, timestamp: at, status: "ready" }; +} + +function shell(id: string): ToolCallItem { + return { + kind: "tool_call", + id, + timestamp: at, + payload: { + source: "agent", + data: { + provider: "claude", + callId: id, + name: "Bash", + status: "completed", + error: null, + detail: { type: "shell", command: "ls" }, + }, + }, + }; +} + +function collapse(tail: StreamItem[], options: Partial = {}) { + return collapseTurns({ + tail, + isLatestTurnOpen: false, + expandedHostIds: new Set(), + getGroupedCalls: () => undefined, + ...options, + }); +} + +const ids = (items: StreamItem[]) => items.map((item) => item.id); + +describe("collapseTurns", () => { + it("folds a finished turn's work into its user message and keeps the reply", () => { + const result = collapse([ + user("u1"), + thought("t1"), + reply("early"), + shell("c1"), + shell("c2"), + reply("final"), + ]); + + expect(ids(result.tail)).toEqual(["u1", "final"]); + expect(result.turnsByHostId.get("u1")).toEqual({ + hostId: "u1", + expanded: false, + summary: { + messageCount: 1, + tools: expect.objectContaining({ commandCount: 2 }), + }, + }); + expect(result.hostIdByFoldedMessageId.get("early")).toBe("u1"); + }); + + it("shows an expanded turn's work as nested rows between the prompt and the reply", () => { + const result = collapse([user("u1"), thought("t1"), shell("c1"), reply("final")], { + expandedHostIds: new Set(["u1"]), + }); + + expect(ids(result.tail)).toEqual(["u1", "t1", "c1", "final"]); + expect([...result.nestedItemIds]).toEqual(["t1", "c1"]); + expect(result.turnsByHostId.get("u1")?.expanded).toBe(true); + }); + + it("leaves the latest turn alone while it is still producing output", () => { + const tail = [user("u1"), shell("c1"), reply("r1"), user("u2"), shell("c2"), reply("r2")]; + + const result = collapse(tail, { isLatestTurnOpen: true }); + + expect(ids(result.tail)).toEqual(["u1", "r1", "u2", "c2", "r2"]); + expect([...result.turnsByHostId.keys()]).toEqual(["u1"]); + }); + + it("keeps rows after the reply, and turns with no work before the reply, as they are", () => { + const result = collapse([ + user("u1"), + shell("c1"), + reply("r1"), + shell("after"), + user("u2"), + reply("r2"), + ]); + + expect(ids(result.tail)).toEqual(["u1", "r1", "after", "u2", "r2"]); + expect([...result.turnsByHostId.keys()]).toEqual(["u1"]); + }); + + it("does not fold a turn that only thought before its reply", () => { + const tail = [user("u1"), thought("t1"), reply("r1")]; + + const result = collapse(tail); + + expect(result.tail).toBe(tail); + expect(result.turnsByHostId.size).toBe(0); + }); + + it("does not fold a turn without a reply or whose prompt is above the loaded history", () => { + const tail = [shell("c0"), reply("r0"), user("u1"), shell("c1")]; + + const result = collapse(tail); + + expect(result.tail).toBe(tail); + expect(result.turnsByHostId.size).toBe(0); + }); + + it("counts every call a tool-call group row stands for", () => { + const group = [shell("c1"), shell("c2"), shell("c3")]; + const result = collapse([user("u1"), group[0]!, reply("final")], { + getGroupedCalls: (itemId) => (itemId === "c1" ? group : undefined), + }); + + expect(result.turnsByHostId.get("u1")?.summary).toMatchObject({ + tools: { commandCount: 3 }, + }); + }); +}); diff --git a/packages/app/src/agent-stream/turn-collapse/model.ts b/packages/app/src/agent-stream/turn-collapse/model.ts new file mode 100644 index 0000000000..d9f532ad73 --- /dev/null +++ b/packages/app/src/agent-stream/turn-collapse/model.ts @@ -0,0 +1,122 @@ +import { getStreamItemMessageId, type StreamItem, type ToolCallItem } from "@/types/stream"; +import { summarizeToolCalls, type OverviewSummary } from "@/tool-calls/detail-level/overview/model"; + +export interface TurnSummary { + messageCount: number; + tools: OverviewSummary; +} + +export interface CollapsedTurn { + /** The user message the turn answers. Its row carries the turn's summary line. */ + hostId: string; + expanded: boolean; + summary: TurnSummary; +} + +export interface TurnCollapse { + tail: StreamItem[]; + turnsByHostId: ReadonlyMap; + /** Rows of expanded turns, which render inside the turn's indent rail. */ + nestedItemIds: ReadonlySet; + /** The turn a folded message belongs to, for surfaces that must reveal it. */ + hostIdByFoldedMessageId: ReadonlyMap; +} + +export interface CollapseTurnsInput { + tail: StreamItem[]; + /** The latest turn is still producing output, so it stays unfolded. */ + isLatestTurnOpen: boolean; + expandedHostIds: ReadonlySet; + /** The calls a tool-call group row stands for; undefined for a single call. */ + getGroupedCalls: (itemId: string) => readonly ToolCallItem[] | undefined; +} + +const EMPTY_TURNS: ReadonlyMap = new Map(); +const EMPTY_IDS: ReadonlySet = new Set(); +const EMPTY_HOSTS: ReadonlyMap = new Map(); + +function summarizeTurn( + items: readonly StreamItem[], + getGroupedCalls: CollapseTurnsInput["getGroupedCalls"], +): TurnSummary { + const calls: ToolCallItem[] = []; + let messageCount = 0; + for (const item of items) { + if (item.kind === "assistant_message") messageCount += 1; + else if (item.kind === "tool_call") calls.push(...(getGroupedCalls(item.id) ?? [item])); + } + return { messageCount, tools: summarizeToolCalls(calls) }; +} + +function hasWork(summary: TurnSummary): boolean { + return summary.messageCount > 0 || Object.values(summary.tools).some((count) => count > 0); +} + +function findLastAssistantIndex(tail: StreamItem[], start: number, end: number): number { + for (let index = end - 1; index >= start; index -= 1) { + if (tail[index]?.kind === "assistant_message") return index; + } + return -1; +} + +/** + * Folds each answered turn into its user message: everything the agent did before its last + * message collapses into one summary line, and that message stays in the chat. A turn folds + * only once it is complete, its user message is loaded, and it sent messages or called tools + * before its reply. Thoughts fold with the turn but are not counted. + */ +export function collapseTurns(input: CollapseTurnsInput): TurnCollapse { + const { tail } = input; + const output: StreamItem[] = []; + const turnsByHostId = new Map(); + const nestedItemIds = new Set(); + const hostIdByFoldedMessageId = new Map(); + + let runStart = 0; + const flushRun = (runEnd: number) => { + const host = tail[runStart - 1]; + const isClosed = runEnd < tail.length || !input.isLatestTurnOpen; + const replyIndex = findLastAssistantIndex(tail, runStart, runEnd); + if (host?.kind !== "user_message" || !isClosed || replyIndex <= runStart) { + output.push(...tail.slice(runStart, runEnd)); + return; + } + const folded = tail.slice(runStart, replyIndex); + const summary = summarizeTurn(folded, input.getGroupedCalls); + if (!hasWork(summary)) { + output.push(...tail.slice(runStart, runEnd)); + return; + } + const expanded = input.expandedHostIds.has(host.id); + turnsByHostId.set(host.id, { hostId: host.id, expanded, summary }); + for (const item of folded) { + hostIdByFoldedMessageId.set(getStreamItemMessageId(item), host.id); + if (expanded) nestedItemIds.add(item.id); + } + if (expanded) output.push(...folded); + output.push(...tail.slice(replyIndex, runEnd)); + }; + + for (let index = 0; index < tail.length; index += 1) { + if (tail[index]?.kind !== "user_message") continue; + flushRun(index); + output.push(tail[index]!); + runStart = index + 1; + } + flushRun(tail.length); + + if (turnsByHostId.size === 0) { + return { + tail, + turnsByHostId: EMPTY_TURNS, + nestedItemIds: EMPTY_IDS, + hostIdByFoldedMessageId: EMPTY_HOSTS, + }; + } + return { + tail: output.length === tail.length ? tail : output, + turnsByHostId, + nestedItemIds, + hostIdByFoldedMessageId, + }; +} diff --git a/packages/app/src/agent-stream/turn-collapse/summary-line.tsx b/packages/app/src/agent-stream/turn-collapse/summary-line.tsx new file mode 100644 index 0000000000..9f73f1ac22 --- /dev/null +++ b/packages/app/src/agent-stream/turn-collapse/summary-line.tsx @@ -0,0 +1,48 @@ +import { memo, useCallback, useMemo } from "react"; +import { useTranslation } from "react-i18next"; +import { Summary } from "lucide-react-native"; +import { ExpandableBadge } from "@/components/message"; +import { useOverviewSummaryLabel } from "@/tool-calls/detail-level/overview/label"; +import type { CollapsedTurn } from "./model"; + +/** + * The row a collapsed turn leaves under its user message, styled like a tool-call group. + * Pressing it opens the turn's rows beneath it. + */ +export const TurnSummaryLine = memo(function TurnSummaryLine({ + turn, + onExpandedChange, +}: { + turn: CollapsedTurn; + onExpandedChange: (hostId: string, expanded: boolean) => void; +}) { + const { t } = useTranslation(); + const { messageCount, tools } = turn.summary; + const messageParts = useMemo( + () => + messageCount > 0 + ? [ + t(`turnSummary.messages.${messageCount === 1 ? "one" : "other"}`, { + count: messageCount, + }), + ] + : [], + [messageCount, t], + ); + const label = useOverviewSummaryLabel(tools, messageParts); + const toggle = useCallback( + () => onExpandedChange(turn.hostId, !turn.expanded), + [onExpandedChange, turn.expanded, turn.hostId], + ); + + return ( + + ); +}); diff --git a/packages/app/src/agent-stream/use-scroll-to-message.web.ts b/packages/app/src/agent-stream/use-scroll-to-message.web.ts index 6de7a3296c..e593f1d323 100644 --- a/packages/app/src/agent-stream/use-scroll-to-message.web.ts +++ b/packages/app/src/agent-stream/use-scroll-to-message.web.ts @@ -1,8 +1,7 @@ import type React from "react"; import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react"; import type { Virtualizer } from "@tanstack/react-virtual"; -import type { StreamItem } from "@/types/stream"; -import { getStreamItemMessageId } from "./presentation"; +import { getStreamItemMessageId, type StreamItem } from "@/types/stream"; import { createPromptJumpSettleController, PROMPT_JUMP_TOP_INSET_PX } from "./prompt-jump-settle"; import type { ScrollToMessageOccurrence } from "./strategy"; diff --git a/packages/app/src/agent-stream/use-stream-history-window.ts b/packages/app/src/agent-stream/use-stream-history-window.ts index 9874158dcc..340ecb4da4 100644 --- a/packages/app/src/agent-stream/use-stream-history-window.ts +++ b/packages/app/src/agent-stream/use-stream-history-window.ts @@ -1,7 +1,6 @@ import { useCallback, useEffect, useMemo, useState } from "react"; -import type { StreamItem } from "@/types/stream"; +import { getStreamItemMessageId, type StreamItem } from "@/types/stream"; import { findMountedWindowStart, getMountedRecentStreamItems } from "./history-window"; -import { getStreamItemMessageId } from "./presentation"; // Callers reveal a message, not a row: an assistant message is several block rows and // the window has to open at the first of them. diff --git a/packages/app/src/agent-stream/view.tsx b/packages/app/src/agent-stream/view.tsx index d662a2f345..67e08a6f82 100644 --- a/packages/app/src/agent-stream/view.tsx +++ b/packages/app/src/agent-stream/view.tsx @@ -41,7 +41,7 @@ import { type InlinePathTarget, } from "@/components/message"; import { PlanCard } from "@/components/plan-card"; -import type { StreamItem } from "@/types/stream"; +import { getStreamItemMessageId, type StreamItem } from "@/types/stream"; import type { PendingMessageSubmission } from "@/composer/submission/model"; import type { TurnPresentation } from "@/timeline/turn-liveness"; import type { PendingPermission } from "@/types/shared"; @@ -62,8 +62,10 @@ import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; import { ToolCallDetailsContent } from "@/components/tool-call-details"; import { QuestionFormCard } from "@/components/question-form-card"; import { ToolCallSheetProvider } from "@/components/tool-call-sheet"; -import { createStreamPresentation, getStreamItemMessageId } from "./presentation"; +import { createStreamPresentation } from "./presentation"; import { OverviewToolCallGroupView } from "@/tool-calls/detail-level/overview/view"; +import { IndentRail } from "@/components/indent-rail"; +import { TurnSummaryLine } from "./turn-collapse/summary-line"; import { type AgentStreamRenderModel, buildAgentStreamRenderModel } from "./model"; import { resolveStreamRenderStrategy } from "./strategy-resolver"; import { type StreamSegmentRenderers, type StreamViewportHandle } from "./strategy"; @@ -148,9 +150,16 @@ function renderPendingPermissionsNode(input: { ); } +/** + * Where a row sits in an opened turn: its summary line's row, a row inside the turn, or the + * turn's last row. The rail runs through the gaps between them so the turn reads as one block. + */ +type TurnIndent = "none" | "openedHost" | "nested" | "lastNested"; + function renderStreamItemWithTurnFooter(input: { content: ReactNode; layoutItem: StreamLayoutItem; + turnIndent: TurnIndent; strategy: TurnContentStrategy; supportsTimelineCursor: boolean; onForkAssistantTurn?: AssistantTurnForkHandler; @@ -171,7 +180,7 @@ function renderStreamItemWithTurnFooter(input: { /> ) : null; const content = ( - + {input.content} ); @@ -333,7 +342,7 @@ const AgentStreamViewComponent = forwardRef settings.autoExpandReasoning); - const toolCallDetailLevel = useSettings((settings) => settings.toolCallDetailLevel); + const chatDisplay = useSettings((settings) => settings.chatDisplay); const chatOutlineEnabled = useSettings((settings) => settings.chatOutlineEnabled); const contentMaxWidth = useSettings(resolveContentMaxWidth); const viewportRef = useRef(null); @@ -357,6 +366,7 @@ const AgentStreamViewComponent = forwardRef>( new Set(), ); + const [expandedTurnHostIds, setExpandedTurnHostIds] = useState>(new Set()); // Get serverId (fallback to agent's serverId if not provided) const resolvedServerId = serverId ?? context.serverId ?? ""; @@ -421,6 +431,7 @@ const AgentStreamViewComponent = forwardRef { + // A turn opens below its summary line; keep that line under the reader's pointer. + viewportRef.current?.holdReadingPosition(); + setExpandedTurnHostIds((previous) => { + if (previous.has(hostId) === expanded) return previous; + const next = new Set(previous); + if (expanded) { + next.add(hostId); + } else { + next.delete(hostId); + } + return next; + }); + }, []); + // Chat find reveals a match inside a collapsed turn by opening the turn first. + const revealLoadedMessage = useStableEvent((messageId: string): boolean => { + const hostId = presentation.turns.hostIdByFoldedMessageId.get(messageId); + if (hostId && !expandedTurnHostIds.has(hostId)) { + setTurnExpanded(hostId, true); + return true; + } + return revealLoadedHistory(messageId); + }); + // Read through stable events so a collapse rerun does not change the renderer identity; + // rows whose turn state changed are revised through `historyRowRevision`. + const getCollapsedTurn = useStableEvent((hostId: string) => + presentation.turns.turnsByHostId.get(hostId), + ); + const getTurnIndent = useStableEvent((layoutItem: StreamLayoutItem): TurnIndent => { + const { nestedItemIds } = presentation.turns; + if (nestedItemIds.has(layoutItem.item.id)) { + const below = layoutItem.belowItem; + return below && nestedItemIds.has(below.id) ? "nested" : "lastNested"; + } + return getCollapsedTurn(layoutItem.item.id)?.expanded ? "openedHost" : "none"; + }); + const setToolCallGroupExpanded = useCallback((groupId: string, expanded: boolean) => { setExpandedToolCallGroupIds((previous) => { const next = new Set(previous); @@ -665,7 +715,8 @@ const AgentStreamViewComponent = forwardRef) => { - return ( + const collapsedTurn = getCollapsedTurn(item.id); + const message = ( ); + if (!collapsedTurn) { + return message; + } + return ( + <> + {message} + + + ); }, - [context.capabilities, agentId, client, pendingClientMessageIds, resolvedServerId], + [ + context.capabilities, + agentId, + client, + getCollapsedTurn, + pendingClientMessageIds, + resolvedServerId, + setTurnExpanded, + ], ); const renderAssistantMessageItem = useCallback( @@ -893,12 +961,14 @@ const AgentStreamViewComponent = forwardRef ({ contentById: presentation.historyGroupUpdatesByHostId, - displayStateById: expandedToolCallGroupIds, + displayStateById: { + has: (id: string) => + expandedToolCallGroupIds.has(id) || + expandedTurnHostIds.has(id) || + nestedItemIds.has(id), + }, globalDisplayState: isMobile, }), - [expandedToolCallGroupIds, isMobile, presentation.historyGroupUpdatesByHostId], + [ + expandedToolCallGroupIds, + expandedTurnHostIds, + isMobile, + nestedItemIds, + presentation.historyGroupUpdatesByHostId, + ], ); const findItems = useMemo( @@ -1080,7 +1162,7 @@ const AgentStreamViewComponent = forwardRef @@ -1763,15 +1845,41 @@ const permissionStyles = StyleSheet.create((theme) => ({ })); interface StreamItemWrapperProps { - itemId: string; gapBelow: number; + turnIndent: TurnIndent; children: ReactNode; } -function StreamItemWrapper({ gapBelow, children }: StreamItemWrapperProps) { +function StreamItemWrapper({ gapBelow, turnIndent, children }: StreamItemWrapperProps) { const wrapperStyle = useMemo( - () => [stylesheet.streamItemWrapper, { marginBottom: gapBelow }], - [gapBelow], + () => [ + stylesheet.streamItemWrapper, + { marginBottom: turnIndent === "nested" || turnIndent === "openedHost" ? 0 : gapBelow }, + ], + [gapBelow, turnIndent], ); - return {children}; + const gapStyle = useMemo(() => ({ paddingBottom: gapBelow }), [gapBelow]); + switch (turnIndent) { + case "none": + return {children}; + case "openedHost": + return ( + + {children} + + + ); + case "nested": + return ( + + {children} + + ); + case "lastNested": + return ( + + {children} + + ); + } } diff --git a/packages/app/src/components/indent-rail.tsx b/packages/app/src/components/indent-rail.tsx new file mode 100644 index 0000000000..b54ac1ca9b --- /dev/null +++ b/packages/app/src/components/indent-rail.tsx @@ -0,0 +1,32 @@ +import type { ReactNode } from "react"; +import { View, type StyleProp, type ViewStyle } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; + +/** + * Collapsed chat rows badge their summary with an icon whose center sits 7px into the content + * column (`ExpandableBadge` bleeds 13px left, then 1px border, 8px padding, 22px icon). The rail + * hangs from that center so opened rows read as children of the line that opened them. + */ +const RAIL_LEFT = 7; +const RAIL_WIDTH = 1; +export const INDENT_RAIL_CONTENT_OFFSET = 21; + +/** Indents opened chat rows under the summary that collapsed them, behind a vertical line. */ +export function IndentRail({ + children, + style, +}: { + children?: ReactNode; + style?: StyleProp; +}) { + return {children}; +} + +const styles = StyleSheet.create((theme) => ({ + rail: { + marginLeft: RAIL_LEFT, + paddingLeft: INDENT_RAIL_CONTENT_OFFSET - RAIL_LEFT - RAIL_WIDTH, + borderLeftWidth: RAIL_WIDTH, + borderLeftColor: theme.colors.border, + }, +})); diff --git a/packages/app/src/components/message.tsx b/packages/app/src/components/message.tsx index d5a2244505..9430aa3a12 100644 --- a/packages/app/src/components/message.tsx +++ b/packages/app/src/components/message.tsx @@ -971,6 +971,10 @@ const expandableBadgeStylesheet = StyleSheet.create((theme) => ({ borderBottomLeftRadius: 0, borderBottomRightRadius: 0, }, + // Details that do not sit in a card leave the header as a lone highlighted pill. + pressableExpandedDetached: { + borderRadius: theme.borderRadius.full, + }, detailWrapperBorderless: { borderWidth: 0, }, @@ -2048,7 +2052,10 @@ export const ExpandableBadge = memo(function ExpandableBadge({ expandableBadgeStylesheet.pressable, isPressed && isInteractive ? expandableBadgeStylesheet.pressablePressed : null, isExpanded && expandableBadgeStylesheet.pressableExpanded, - isExpanded && !borderlessWhenExpanded && expandableBadgeStylesheet.pressableExpandedAttached, + isExpanded && + (borderlessWhenExpanded + ? expandableBadgeStylesheet.pressableExpandedDetached + : expandableBadgeStylesheet.pressableExpandedAttached), ], [borderlessWhenExpanded, isExpanded, isInteractive, isPressed], ); diff --git a/packages/app/src/hooks/use-settings/index.ts b/packages/app/src/hooks/use-settings/index.ts index 66a8e767b1..9f6f22fb23 100644 --- a/packages/app/src/hooks/use-settings/index.ts +++ b/packages/app/src/hooks/use-settings/index.ts @@ -42,6 +42,7 @@ import { saveAppSettings as saveAppSettingsPure, type AppSettings, type AppSettingsUpdate, + type ChatDisplay, type OpenInSidePanePreferences, type PullRequestOpenLocation, type DesktopSettingsBridge, @@ -84,6 +85,7 @@ export { export type { AppSettings, AppSettingsUpdate, + ChatDisplay, AppLanguage, OpenInSidePanePreferences, PullRequestOpenLocation, diff --git a/packages/app/src/hooks/use-settings/storage.test.ts b/packages/app/src/hooks/use-settings/storage.test.ts index dadb912a24..fe2ffdd2a0 100644 --- a/packages/app/src/hooks/use-settings/storage.test.ts +++ b/packages/app/src/hooks/use-settings/storage.test.ts @@ -185,6 +185,7 @@ describe("loadAppSettingsFromStorage", () => { expect(result).toEqual(DEFAULT_CLIENT_SETTINGS); expect(DEFAULT_CLIENT_SETTINGS.language).toBe("system"); + expect(DEFAULT_CLIENT_SETTINGS.chatDisplay).toBe("collapseTurns"); expect(JSON.parse(deps.storage.entries.get(APP_SETTINGS_KEY) ?? "null")).toEqual( DEFAULT_CLIENT_SETTINGS, ); @@ -454,6 +455,7 @@ describe("loadAppSettingsFromStorage", () => { ...DEFAULT_CLIENT_SETTINGS, theme: "dark", contentFontSize: DEFAULT_UI_BASE_FONT_SIZE, + chatDisplay: "full", }); expect(JSON.parse(deps.storage.entries.get(APP_SETTINGS_KEY) ?? "null")).toEqual({ manageBuiltInDaemon: false, @@ -592,6 +594,7 @@ describe("loadSettingsFromStorage", () => { ...DEFAULT_APP_SETTINGS, theme: "light", contentFontSize: DEFAULT_UI_BASE_FONT_SIZE, + chatDisplay: "full", }); }); @@ -636,6 +639,7 @@ describe("loadSettingsFromStorage", () => { ...DEFAULT_APP_SETTINGS, theme: "light", contentFontSize: DEFAULT_UI_BASE_FONT_SIZE, + chatDisplay: "full", manageBuiltInDaemon: false, releaseChannel: "beta", }); @@ -657,6 +661,7 @@ describe("loadSettingsFromStorage", () => { ...DEFAULT_APP_SETTINGS, theme: "light", contentFontSize: DEFAULT_UI_BASE_FONT_SIZE, + chatDisplay: "full", }); }); }); @@ -732,7 +737,7 @@ describe("saveAppSettings", () => { ...DEFAULT_CLIENT_SETTINGS, theme: "light", contentFontSize: DEFAULT_UI_BASE_FONT_SIZE, - toolCallDetailLevel: "overview", + chatDisplay: "collapseToolCalls", }); }); @@ -787,27 +792,45 @@ describe("appearance settings", () => { expect(result.contentFontSize).toBe(DEFAULT_UI_BASE_FONT_SIZE); expect(result.codeFontSize).toBe(DEFAULT_CODE_FONT_SIZE); expect(result.syntaxTheme).toBe("one"); - expect(result.toolCallDetailLevel).toBe("detailed"); + expect(result.chatDisplay).toBe("full"); }); - it("migrates the enabled compact tool call preference to overview", async () => { + it("migrates the enabled compact tool call preference to collapsed tool calls", async () => { const deps = makeDeps({ storage: createInMemoryKeyValueStorage({ [APP_SETTINGS_KEY]: JSON.stringify({ compactToolCalls: true }), }), }); - expect((await loadAppSettingsFromStorage(deps)).toolCallDetailLevel).toBe("overview"); + expect((await loadAppSettingsFromStorage(deps)).chatDisplay).toBe("collapseToolCalls"); }); - it("clears settings with an unrecognized tool call detail level", async () => { + it.each([ + ["overview", "collapseToolCalls"], + ["concise", "collapseToolCalls"], + ["detailed", "full"], + ["unknown", "full"], + ])("reads the %s tool call detail level as the %s chat display", async (legacy, display) => { const deps = makeDeps({ storage: createInMemoryKeyValueStorage({ - [APP_SETTINGS_KEY]: JSON.stringify({ toolCallDetailLevel: "unknown" }), + [APP_SETTINGS_KEY]: JSON.stringify({ toolCallDetailLevel: legacy }), }), }); - expect((await loadAppSettingsFromStorage(deps)).toolCallDetailLevel).toBe("detailed"); + expect((await loadAppSettingsFromStorage(deps)).chatDisplay).toBe(display); + }); + + it("keeps a stored chat display over the tool call detail level it replaced", async () => { + const deps = makeDeps({ + storage: createInMemoryKeyValueStorage({ + [APP_SETTINGS_KEY]: JSON.stringify({ + chatDisplay: "collapseTurns", + toolCallDetailLevel: "detailed", + }), + }), + }); + + expect((await loadAppSettingsFromStorage(deps)).chatDisplay).toBe("collapseTurns"); }); it("migrates a switched-off checks row item to the hidden checks display", async () => { diff --git a/packages/app/src/hooks/use-settings/storage.ts b/packages/app/src/hooks/use-settings/storage.ts index 4fe08bb6d5..3a5be63441 100644 --- a/packages/app/src/hooks/use-settings/storage.ts +++ b/packages/app/src/hooks/use-settings/storage.ts @@ -40,7 +40,8 @@ export type WorkspaceTitleSource = "title" | "branch"; export type PullRequestOpenLocation = "main" | "side" | "explorer"; /** What a sidebar workspace row shows in the space to the right of its title. */ export type SidebarWorkspaceTrailing = "diff" | "timestamp" | "none"; -export type ToolCallDetailLevel = "overview" | "detailed"; +/** How much of an agent's work the chat shows between the user's message and the reply. */ +export type ChatDisplay = "full" | "collapseToolCalls" | "collapseTurns"; const ThemePreferenceSchema = z.enum([ ...THEME_OPTIONS.map((option) => option.name), @@ -100,7 +101,7 @@ export interface AppSettings { /** How usage reads and which windows the sidebar summary shows. */ usage: UsagePreferences; autoExpandReasoning: boolean; - toolCallDetailLevel: ToolCallDetailLevel; + chatDisplay: ChatDisplay; chatOutlineEnabled: boolean; vimKeybindings: boolean; filePanelAssociations: Record; @@ -156,7 +157,7 @@ export const DEFAULT_CLIENT_SETTINGS: AppSettings = { sidebarFooterItems: [], usage: DEFAULT_USAGE_PREFERENCES, autoExpandReasoning: false, - toolCallDetailLevel: "detailed", + chatDisplay: "collapseTurns", chatOutlineEnabled: true, vimKeybindings: false, filePanelAssociations: {}, @@ -199,6 +200,7 @@ const SidebarRowItemsSchema = z type StoredAppSettingsFallback = AppSettings & { uiFontSize?: number; compactToolCalls?: boolean; + toolCallDetailLevel?: "overview" | "detailed"; manageBuiltInDaemon?: boolean; releaseChannel?: ReleaseChannel; needsWrite: boolean; @@ -251,11 +253,13 @@ const StoredAppSettingsSchema = z sidebarFooterItems: z.array(z.object({ key: z.string(), visible: z.boolean() })).catch([]), usage: UsagePreferencesSchema, autoExpandReasoning: z.boolean().catch(false), + chatDisplay: z.enum(["full", "collapseToolCalls", "collapseTurns"]).optional().catch("full"), + // COMPAT(toolCallDetailLevel): replaced by chatDisplay in v0.13, remove after 2027-04-24. toolCallDetailLevel: z .enum(["overview", "detailed"]) .or(z.literal("concise").transform(() => "overview" as const)) .optional() - .catch("detailed"), + .catch(undefined), // COMPAT(compactToolCalls): migrated in v0.1.105, remove after 2027-01-12. compactToolCalls: z.boolean().optional().catch(undefined), chatOutlineEnabled: z.boolean().catch(true), @@ -305,8 +309,10 @@ const StoredAppSettingsSchema = z (isChecksHiddenByLegacyRowItem(stored.sidebarRowItems) ? "none" : DEFAULT_SIDEBAR_CHECKS_DISPLAY); - const toolCallDetailLevel = - stored.toolCallDetailLevel ?? (stored.compactToolCalls ? "overview" : "detailed"); + const groupsToolCalls = stored.toolCallDetailLevel + ? stored.toolCallDetailLevel === "overview" + : stored.compactToolCalls === true; + const chatDisplay = stored.chatDisplay ?? (groupsToolCalls ? "collapseToolCalls" : "full"); return { ...stored, openInSidePane, @@ -321,7 +327,7 @@ const StoredAppSettingsSchema = z stored.sidebarRowItems.services ?? (stored.sidebarRowItems.scripts === false ? false : DEFAULT_SIDEBAR_ROW_ITEMS.services), }, - toolCallDetailLevel, + chatDisplay, needsWrite, }; }) @@ -449,6 +455,7 @@ export function normalizeAppSettings(value: unknown): AppSettings { manageBuiltInDaemon: _manageBuiltInDaemon, releaseChannel: _releaseChannel, compactToolCalls: _compactToolCalls, + toolCallDetailLevel: _toolCallDetailLevel, uiFontSize: _uiFontSize, ...settings } = StoredAppSettingsSchema.parse(value); diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index c765f3b835..3ff25adf40 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -2008,6 +2008,12 @@ export const ar: TranslationResources = { input: "مدخل", output: "الإخراج", }, + turnSummary: { + messages: { + one: "كتب {{count}} رسالة", + other: "كتب {{count}} رسائل", + }, + }, toolCallGroup: { editedFiles: { one: "حرّر {{count}} ملفًا", @@ -2312,12 +2318,13 @@ export const ar: TranslationResources = { label: "عرض التفكير دائماً", description: "إظهار تفكير الوكيل وخطوات الاستدلال بشكل كامل بشكل افتراضي", }, - toolCallDetail: { - label: "عرض استدعاءات الأدوات", - description: "كيفية ظهور استدعاءات الأدوات في المخطط الزمني", + chatDisplay: { + label: "عرض المحادثة", + description: "مقدار عمل الوكيل الذي تعرضه المحادثة", options: { - overview: "ملخص", - detailed: "التفاصيل الكاملة", + full: "كامل", + collapseToolCalls: "طيّ استدعاءات الأدوات", + collapseTurns: "طيّ الأدوار", }, }, language: { diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index 351fb33ac3..1d0d1da97a 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -2033,6 +2033,12 @@ export const en = { input: "Input", output: "Output", }, + turnSummary: { + messages: { + one: "wrote {{count}} message", + other: "wrote {{count}} messages", + }, + }, toolCallGroup: { editedFiles: { one: "edited {{count}} file", @@ -2400,12 +2406,13 @@ export const en = { label: "Always expand reasoning", description: "Show agent thinking and chain-of-thought blocks fully expanded by default", }, - toolCallDetail: { - label: "Tool call display", - description: "How tool calls appear in the timeline", + chatDisplay: { + label: "Chat display", + description: "How much of an agent's work the chat shows", options: { - overview: "Summary", - detailed: "Full detail", + full: "Full", + collapseToolCalls: "Collapse tool calls", + collapseTurns: "Collapse turns", }, }, language: { diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index fd195ce599..feafcd225f 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -2056,6 +2056,12 @@ export const es: TranslationResources = { input: "Aporte", output: "Producción", }, + turnSummary: { + messages: { + one: "escribió {{count}} mensaje", + other: "escribió {{count}} mensajes", + }, + }, toolCallGroup: { editedFiles: { one: "editó {{count}} archivo", @@ -2328,12 +2334,13 @@ export const es: TranslationResources = { description: "Mostrar los bloques de pensamiento y razonamiento del agente totalmente expandidos de forma predeterminada", }, - toolCallDetail: { - label: "Visualización de llamadas a herramientas", - description: "Cómo aparecen las llamadas a herramientas en la cronología", + chatDisplay: { + label: "Visualización del chat", + description: "Cuánto del trabajo del agente muestra el chat", options: { - overview: "Resumen", - detailed: "Detalle completo", + full: "Completo", + collapseToolCalls: "Contraer llamadas a herramientas", + collapseTurns: "Contraer turnos", }, }, language: { diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index 975d6a3736..6d8ee58400 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -2055,6 +2055,12 @@ export const fr: TranslationResources = { input: "Entrée", output: "Sortie", }, + turnSummary: { + messages: { + one: "{{count}} message écrit", + other: "{{count}} messages écrits", + }, + }, toolCallGroup: { editedFiles: { one: "{{count}} fichier modifié", @@ -2326,12 +2332,13 @@ export const fr: TranslationResources = { label: "Toujours afficher le raisonnement", description: "Afficher par défaut le raisonnement de l’agent entièrement déplié", }, - toolCallDetail: { - label: "Affichage des appels d’outils", - description: "Comment les appels d’outils apparaissent dans la chronologie", + chatDisplay: { + label: "Affichage du chat", + description: "La part du travail de l’agent affichée dans le chat", options: { - overview: "Résumé", - detailed: "Détails complets", + full: "Complet", + collapseToolCalls: "Réduire les appels d’outils", + collapseTurns: "Réduire les tours", }, }, language: { diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index 60a207e1e1..b8af6f91f6 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -2028,6 +2028,12 @@ export const ja: TranslationResources = { input: "入力", output: "出力", }, + turnSummary: { + messages: { + one: "{{count}}件のメッセージを送信", + other: "{{count}}件のメッセージを送信", + }, + }, toolCallGroup: { editedFiles: { one: "{{count}}個のファイルを編集", @@ -2296,12 +2302,13 @@ export const ja: TranslationResources = { label: "常に思考プロセスを展開", description: "デフォルトでAIのエージェント思考・推論ブロックを完全に展開して表示します", }, - toolCallDetail: { - label: "ツール呼び出しの表示", - description: "タイムラインでのツール呼び出しの表示方法", + chatDisplay: { + label: "チャットの表示", + description: "チャットに表示するエージェントの作業量", options: { - overview: "要約", - detailed: "すべての詳細", + full: "すべて", + collapseToolCalls: "ツール呼び出しを折りたたむ", + collapseTurns: "ターンを折りたたむ", }, }, language: { diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index 4773625327..1a9b36d9bd 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -2018,6 +2018,12 @@ export const ko: TranslationResources = { input: "입력", output: "출력", }, + turnSummary: { + messages: { + one: "{{count}} 메시지를 작성했습니다.", + other: "{{count}} 메시지를 작성했습니다.", + }, + }, toolCallGroup: { editedFiles: { one: "{{count}} 파일을 편집했습니다.", @@ -2287,12 +2293,13 @@ export const ko: TranslationResources = { label: "추론 항상 펼치기", description: "에이전트의 사고 및 추론 블록을 기본적으로 모두 펼쳐 표시합니다.", }, - toolCallDetail: { - label: "도구 호출 표시", - description: "타임라인에 도구 호출이 표시되는 방식", + chatDisplay: { + label: "채팅 표시", + description: "채팅에 표시할 에이전트 작업의 양", options: { - overview: "요약", - detailed: "전체 세부정보", + full: "전체", + collapseToolCalls: "도구 호출 접기", + collapseTurns: "턴 접기", }, }, language: { diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index 766c6d98ed..0d7e6acb89 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -2041,6 +2041,12 @@ export const ptBR: TranslationResources = { input: "Entrada", output: "Saída", }, + turnSummary: { + messages: { + one: "escreveu {{count}} mensagem", + other: "escreveu {{count}} mensagens", + }, + }, toolCallGroup: { editedFiles: { one: "editou {{count}} arquivo", @@ -2311,12 +2317,13 @@ export const ptBR: TranslationResources = { description: "Mostrar os blocos de pensamento e raciocínio do agente totalmente expandidos por padrão", }, - toolCallDetail: { - label: "Exibição de chamadas de ferramentas", - description: "Como as chamadas de ferramentas aparecem na linha do tempo", + chatDisplay: { + label: "Exibição do chat", + description: "Quanto do trabalho do agente o chat mostra", options: { - overview: "Resumo", - detailed: "Detalhes completos", + full: "Completo", + collapseToolCalls: "Recolher chamadas de ferramentas", + collapseTurns: "Recolher turnos", }, }, language: { diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index 23f3d810ee..09d46fa075 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -2041,6 +2041,12 @@ export const ru: TranslationResources = { input: "Входные данные", output: "Выходные данные", }, + turnSummary: { + messages: { + one: "написано {{count}} сообщение", + other: "написаны сообщения ({{count}})", + }, + }, toolCallGroup: { editedFiles: { one: "изменён {{count}} файл", @@ -2313,12 +2319,13 @@ export const ru: TranslationResources = { description: "По умолчанию полностью разворачивать блоки размышлений и хода рассуждений агента", }, - toolCallDetail: { - label: "Отображение вызовов инструментов", - description: "Как вызовы инструментов отображаются на временной шкале", + chatDisplay: { + label: "Отображение чата", + description: "Какую часть работы агента показывает чат", options: { - overview: "Сводка", - detailed: "Все подробности", + full: "Полностью", + collapseToolCalls: "Сворачивать вызовы инструментов", + collapseTurns: "Сворачивать ходы", }, }, language: { diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index 43d8ceeef2..374bef6e88 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -1986,6 +1986,12 @@ export const zhCN: TranslationResources = { input: "输入", output: "输出", }, + turnSummary: { + messages: { + one: "写了 {{count}} 条消息", + other: "写了 {{count}} 条消息", + }, + }, toolCallGroup: { editedFiles: { one: "编辑了 {{count}} 个文件", @@ -2251,12 +2257,13 @@ export const zhCN: TranslationResources = { label: "始终展开推理过程", description: "默认情况下完全展开 AI 的思考和推理过程", }, - toolCallDetail: { - label: "工具调用显示", - description: "工具调用在时间线中的显示方式", + chatDisplay: { + label: "聊天显示", + description: "聊天中显示多少智能体的工作", options: { - overview: "摘要", - detailed: "完整详情", + full: "完整", + collapseToolCalls: "折叠工具调用", + collapseTurns: "折叠轮次", }, }, language: { diff --git a/packages/app/src/screens/settings/chat/chat-section.tsx b/packages/app/src/screens/settings/chat/chat-section.tsx index 8a81d30073..4f4254cb8e 100644 --- a/packages/app/src/screens/settings/chat/chat-section.tsx +++ b/packages/app/src/screens/settings/chat/chat-section.tsx @@ -8,29 +8,25 @@ import { SettingsSwitch, } from "@/components/settings"; import { isNative } from "@/constants/platform"; -import { useAppSettings, type AppSettings } from "@/hooks/use-settings"; +import { useAppSettings, type ChatDisplay } from "@/hooks/use-settings"; -const TOOL_CALL_DETAIL_LEVELS: readonly AppSettings["toolCallDetailLevel"][] = [ - "detailed", - "overview", -]; +const CHAT_DISPLAYS: readonly ChatDisplay[] = ["full", "collapseToolCalls", "collapseTurns"]; export function ChatSection() { const { t } = useTranslation(); const { settings, updateSettings } = useAppSettings(); - const toolCallDetailOptions = useMemo( + const chatDisplayOptions = useMemo( () => - TOOL_CALL_DETAIL_LEVELS.map((value) => ({ + CHAT_DISPLAYS.map((value) => ({ value, - label: t(`settings.general.toolCallDetail.options.${value}`), + label: t(`settings.general.chatDisplay.options.${value}`), })), [t], ); - const changeToolCallDetailLevel = useCallback( - (toolCallDetailLevel: AppSettings["toolCallDetailLevel"]) => - void updateSettings({ toolCallDetailLevel }), + const changeChatDisplay = useCallback( + (chatDisplay: ChatDisplay) => void updateSettings({ chatDisplay }), [updateSettings], ); const changeAutoExpandReasoning = useCallback( @@ -53,11 +49,11 @@ export function ChatSection() { onValueChange={changeAutoExpandReasoning} /> {isNative ? null : ( 2) { + joined = `${parts.slice(0, -1).join(", ")}, ${conjunction} ${parts.at(-1)}`; + } + const firstCharacter = joined[0]; + return firstCharacter ? `${firstCharacter.toLocaleUpperCase()}${joined.slice(1)}` : joined; +} + +/** + * One sentence of what a stretch of agent work did, such as "Edited 2 files and ran 3 commands". + * Leading parts come first, for summaries that count more than tool calls. + */ +export function useOverviewSummaryLabel( + summary: OverviewSummary, + leadingParts: readonly string[] = [], +): string { + const { t } = useTranslation(); + return useMemo(() => { + const parts = [...leadingParts]; + const entries = [ + [summary.editedFileCount, "toolCallGroup.editedFiles"], + [summary.commandCount, "toolCallGroup.commands"], + [summary.readFileCount, "toolCallGroup.readFiles"], + [summary.searchCount, "toolCallGroup.searches"], + [summary.otherToolCount, "toolCallGroup.otherTools"], + [summary.paseoCallCount, "toolCallGroup.paseoCalls"], + ] as const; + for (const [count, key] of entries) { + if (count > 0) { + parts.push(t(`${key}.${count === 1 ? "one" : "other"}`, { count })); + } + } + return joinSummaryParts(parts, t("toolCallGroup.and")); + }, [leadingParts, summary, t]); +} diff --git a/packages/app/src/tool-calls/detail-level/overview/model.ts b/packages/app/src/tool-calls/detail-level/overview/model.ts index f41790461c..0fb638c012 100644 --- a/packages/app/src/tool-calls/detail-level/overview/model.ts +++ b/packages/app/src/tool-calls/detail-level/overview/model.ts @@ -1,4 +1,5 @@ import { isPaseoToolName } from "@getpaseo/protocol/tool-name-normalization"; +import type { ToolCallItem } from "@/types/stream"; import { describeToolCall, type ToolCallRun } from "../grouping"; const DIRECT_PASEO_TOOL_PREFIX = "paseo_"; @@ -28,19 +29,18 @@ function isSearchCall(name: string): boolean { return DIRECT_SEARCH_TOOL_SUFFIX_PATTERN.test(name); } -export function buildOverviewGroup(run: ToolCallRun): OverviewToolCallGroup { +/** Counts tool calls by what they did, for any summary of a stretch of agent work. */ +export function summarizeToolCalls(calls: readonly ToolCallItem[]): OverviewSummary { const editedFiles = new Set(); const readFiles = new Set(); - let isLoading = false; let commandCount = 0; let searchCount = 0; let otherToolCount = 0; let paseoCallCount = 0; - for (const call of run.calls) { + for (const call of calls) { const descriptor = describeToolCall(call); const normalizedName = descriptor.name.trim().toLowerCase(); - isLoading ||= descriptor.status === "running" || descriptor.status === "executing"; if (isPaseoCall(descriptor.name, normalizedName)) { paseoCallCount += 1; } else if (descriptor.detail.type === "edit" || descriptor.detail.type === "write") { @@ -56,7 +56,7 @@ export function buildOverviewGroup(run: ToolCallRun): OverviewToolCallGroup { } } - const summary = { + return { editedFileCount: editedFiles.size, commandCount, readFileCount: readFiles.size, @@ -64,10 +64,17 @@ export function buildOverviewGroup(run: ToolCallRun): OverviewToolCallGroup { otherToolCount, paseoCallCount, }; +} + +export function buildOverviewGroup(run: ToolCallRun): OverviewToolCallGroup { + const isLoading = run.calls.some((call) => { + const status = describeToolCall(call).status; + return status === "running" || status === "executing"; + }); return { mode: "overview", run, isLoading, - summary, + summary: summarizeToolCalls(run.calls), }; } diff --git a/packages/app/src/tool-calls/detail-level/overview/view.tsx b/packages/app/src/tool-calls/detail-level/overview/view.tsx index 326cc172b2..b11e82e4f7 100644 --- a/packages/app/src/tool-calls/detail-level/overview/view.tsx +++ b/packages/app/src/tool-calls/detail-level/overview/view.tsx @@ -1,11 +1,12 @@ -import React, { memo, useCallback, useMemo, useRef, type ReactNode } from "react"; +import React, { memo, useCallback, useRef, type ReactNode } from "react"; import { ScrollView } from "react-native"; -import { useTranslation } from "react-i18next"; import { Wrench } from "lucide-react-native"; import { StyleSheet } from "react-native-unistyles"; +import { IndentRail } from "@/components/indent-rail"; import { ExpandableBadge } from "@/components/message"; import { useIsCompactFormFactor } from "@/constants/layout"; -import { type OverviewSummary, type OverviewToolCallGroup } from "./model"; +import { useOverviewSummaryLabel } from "./label"; +import type { OverviewToolCallGroup } from "./model"; import { OverviewToolCallGroupSheet } from "./sheet"; interface OverviewGroupProps { @@ -18,41 +19,6 @@ interface OverviewGroupProps { const TOOL_CALL_GROUP_MAX_HEIGHT = 400; -function joinSummaryParts(parts: string[], conjunction: string): string { - if (parts.length === 0) { - return ""; - } - let joined = parts[0] ?? ""; - if (parts.length === 2) { - joined = `${parts[0]} ${conjunction} ${parts[1]}`; - } else if (parts.length > 2) { - joined = `${parts.slice(0, -1).join(", ")}, ${conjunction} ${parts.at(-1)}`; - } - const firstCharacter = joined[0]; - return firstCharacter ? `${firstCharacter.toLocaleUpperCase()}${joined.slice(1)}` : joined; -} - -function useOverviewSummary(summary: OverviewSummary): string { - const { t } = useTranslation(); - return useMemo(() => { - const parts: string[] = []; - const entries = [ - [summary.editedFileCount, "toolCallGroup.editedFiles"], - [summary.commandCount, "toolCallGroup.commands"], - [summary.readFileCount, "toolCallGroup.readFiles"], - [summary.searchCount, "toolCallGroup.searches"], - [summary.otherToolCount, "toolCallGroup.otherTools"], - [summary.paseoCallCount, "toolCallGroup.paseoCalls"], - ] as const; - for (const [count, key] of entries) { - if (count > 0) { - parts.push(t(`${key}.${count === 1 ? "one" : "other"}`, { count })); - } - } - return joinSummaryParts(parts, t("toolCallGroup.and")); - }, [summary, t]); -} - export const OverviewToolCallGroupView = memo(function OverviewToolCallGroupView({ group, expanded, @@ -62,7 +28,7 @@ export const OverviewToolCallGroupView = memo(function OverviewToolCallGroupView }: OverviewGroupProps) { const scrollRef = useRef(null); const isCompact = useIsCompactFormFactor(); - const aggregateSummary = useOverviewSummary(group.summary); + const aggregateSummary = useOverviewSummaryLabel(group.summary); const scrollToLatest = useCallback(() => { scrollRef.current?.scrollToEnd({ animated: false }); }, []); @@ -82,7 +48,7 @@ export const OverviewToolCallGroupView = memo(function OverviewToolCallGroupView showsVerticalScrollIndicator onContentSizeChange={scrollToLatest} > - {children} + {children} ), [children, scrollToLatest], diff --git a/packages/app/src/tool-calls/detail-level/projection.ts b/packages/app/src/tool-calls/detail-level/projection.ts index 5dc1067914..9d57391b2e 100644 --- a/packages/app/src/tool-calls/detail-level/projection.ts +++ b/packages/app/src/tool-calls/detail-level/projection.ts @@ -1,5 +1,4 @@ import type { StreamItem } from "@/types/stream"; -import type { ToolCallDetailLevel } from "@/hooks/use-settings/storage"; import { groupLiveToolCalls, prepareGroupedHistory, @@ -8,7 +7,8 @@ import { } from "./grouping"; import { buildOverviewGroup, type OverviewToolCallGroup } from "./overview/model"; -export type { ToolCallDetailLevel } from "@/hooks/use-settings/storage"; +/** Whether consecutive tool calls show one by one or as one summary row. */ +export type ToolCallDetailLevel = "overview" | "detailed"; export type ToolCallDetailGroup = OverviewToolCallGroup; export interface PreparedToolCallHistory { diff --git a/packages/app/src/types/stream.ts b/packages/app/src/types/stream.ts index 9425cabbed..657d218b35 100644 --- a/packages/app/src/types/stream.ts +++ b/packages/app/src/types/stream.ts @@ -771,6 +771,12 @@ export type AgentToolCallItem = ToolCallItem & { payload: { source: "agent"; data: AgentToolCallData }; }; +/** Find and scrolling address a plugin row by the source it replaces. */ +export function getStreamItemMessageId(item: StreamItem): string { + if (item.kind === "plugin") return item.sourceId ?? item.id; + return item.id; +} + export function isAgentToolCallItem(item: StreamItem): item is AgentToolCallItem { return item.kind === "tool_call" && item.payload.source === "agent"; } From 2a890208ce0b8b9e522f8326c043c158e46396f0 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Mon, 26 Oct 2026 10:51:19 +0700 Subject: [PATCH 005/173] feat(app): show a subagent's parent and a way back to it (#7784) A subagent pane now names its parent and takes you back to it. With a composer, a pill leads the rail above it; without one, a parent box takes the composer's place. Both open the parent through navigateToAgent. --- docs/agent-lifecycle.md | 2 +- .../browser/compact-workspace-sheet.spec.ts | 10 ++ .../browser/provider-subagents.real.spec.ts | 3 +- .../e2e/browser/subagent-origin-pane.spec.ts | 23 ++++ packages/app/src/composer/tracks.tsx | 6 +- packages/app/src/i18n/resources/ar.ts | 7 ++ packages/app/src/i18n/resources/en.ts | 7 ++ packages/app/src/i18n/resources/es.ts | 7 ++ packages/app/src/i18n/resources/fr.ts | 7 ++ packages/app/src/i18n/resources/ja.ts | 7 ++ packages/app/src/i18n/resources/ko.ts | 7 ++ packages/app/src/i18n/resources/pt-BR.ts | 7 ++ packages/app/src/i18n/resources/ru.ts | 7 ++ packages/app/src/i18n/resources/zh-CN.ts | 7 ++ packages/app/src/panels/agent-panel.tsx | 13 +- packages/app/src/panels/agent-tracks.tsx | 16 ++- .../src/panels/provider-subagent-panel.tsx | 47 +++---- packages/app/src/subagents/parent/callout.tsx | 116 ++++++++++++++++++ packages/app/src/subagents/parent/index.ts | 3 + packages/app/src/subagents/parent/pill.tsx | 79 ++++++++++++ .../src/subagents/parent/use-parent-agent.ts | 38 ++++++ 21 files changed, 392 insertions(+), 27 deletions(-) create mode 100644 packages/app/src/subagents/parent/callout.tsx create mode 100644 packages/app/src/subagents/parent/index.ts create mode 100644 packages/app/src/subagents/parent/pill.tsx create mode 100644 packages/app/src/subagents/parent/use-parent-agent.ts diff --git a/docs/agent-lifecycle.md b/docs/agent-lifecycle.md index 535a6dd712..e9ca2211c2 100644 --- a/docs/agent-lifecycle.md +++ b/docs/agent-lifecycle.md @@ -242,7 +242,7 @@ parentAgentId === thisAgent.id AND !archivedAt - **Provider subagents** are child executions owned by Claude, Codex, or OpenCode. They are not inserted into `AgentManager` as managed agents. Providers emit a separate descriptor and timeline stream through `agent.provider_subagents.*`; the client keeps that state outside the normal agent store and merges only the presentation rows into the track. A descriptor's optional `parentSubagentId` identifies its direct provider-subagent parent; an absent value identifies a direct child of the managed agent. -Clicking either kind opens a workspace tab. On compact layouts it opens in a [sheet](explorer-sidebar.md#sheets) over the subagents list instead; the sheet hides the composer and shows the agent's model and thinking as one line in its place (`PaneSubtitle`, the row provider subagents already use), and a Paseo subagent's sheet offers **Open as tab** (the full-screen glyph in the header) to get the composer back. A Paseo subagent tab is a normal interactive agent pane. A provider subagent tab is a read-only timeline pane with no composer, archive, detach, rewind, or fork actions. It shows its own direct children in a subagents track. Both panes use `AgentStreamView`, so message, reasoning, tool-call, and layout rendering stay identical. +Clicking either kind opens a workspace tab. On compact layouts it opens in a [sheet](explorer-sidebar.md#sheets) over the subagents list instead; the sheet hides the composer and shows the agent's model and thinking as one line in its place (`PaneSubtitle`, the row provider subagents already use), and a Paseo subagent's sheet offers **Open as tab** (the full-screen glyph in the header) to get the composer back. A Paseo subagent tab is a normal interactive agent pane. A provider subagent tab is a read-only timeline pane with no composer, archive, detach, rewind, or fork actions. It shows its own direct children in a subagents track. Every subagent pane links back to its parent (`packages/app/src/subagents/parent/`): a pill above the composer when there is one, a parent box in the composer's place when there is not. Both panes use `AgentStreamView`, so message, reasoning, tool-call, and layout rendering stay identical. Provider timelines use the same structural timeline item format but deliberately have a separate lifecycle and transport. A provider thread/session identifier is not a Paseo agent identifier, and closing its tab is always layout-only. diff --git a/packages/app/e2e/browser/compact-workspace-sheet.spec.ts b/packages/app/e2e/browser/compact-workspace-sheet.spec.ts index 990d490d9b..77d995eda7 100644 --- a/packages/app/e2e/browser/compact-workspace-sheet.spec.ts +++ b/packages/app/e2e/browser/compact-workspace-sheet.spec.ts @@ -99,6 +99,16 @@ test("compact opens files and subagents in a sheet, leaving the tabs for agents" await expectSubagentRowVisible(page, child.id); }); + await test.step("the parent box in a subagent's sheet closes it onto the parent", async () => { + await page.getByTestId(`subagents-track-row-${child.id}`).click(); + const childSheet = sheet(page, child.title); + await expectSheetAtSnap(page, child.title); + await expect(childSheet.getByTestId("composer-parent-agent-pill")).toHaveCount(0); + await childSheet.getByTestId("parent-agent-callout-open").click(); + await expect(childSheet).toHaveCount(0); + await expectOpenTabCount(page, 1); + }); + await test.step("Open as tab promotes the subagent to a full tab and ends the list", async () => { await page.getByTestId(`subagents-track-row-${child.id}`).click(); await expectSheetAtSnap(page, child.title); diff --git a/packages/app/e2e/browser/provider-subagents.real.spec.ts b/packages/app/e2e/browser/provider-subagents.real.spec.ts index 08d8a1afe1..b24ca9ba4e 100644 --- a/packages/app/e2e/browser/provider-subagents.real.spec.ts +++ b/packages/app/e2e/browser/provider-subagents.real.spec.ts @@ -136,7 +136,8 @@ test.describe("real provider subagent timelines", () => { panel.getByText("Start chatting with this agent...", { exact: true }), ).toHaveCount(0); - await page.getByTestId(`workspace-tab-agent_${handle.agentId}`).first().click(); + // A provider subagent has no composer; its callout is the way back to the parent. + await page.getByTestId("parent-agent-callout-open").click(); await expect( page.getByTestId("assistant-message").filter({ hasText: "ROOT_DONE" }).last(), ).toBeVisible({ timeout: 60_000 }); diff --git a/packages/app/e2e/browser/subagent-origin-pane.spec.ts b/packages/app/e2e/browser/subagent-origin-pane.spec.ts index 30b19e5099..545076ab06 100644 --- a/packages/app/e2e/browser/subagent-origin-pane.spec.ts +++ b/packages/app/e2e/browser/subagent-origin-pane.spec.ts @@ -125,6 +125,29 @@ test("opening an already-tabbed subagent reveals its left tab without a duplicat } }); +test("a subagent's parent pill returns to its parent", async ({ page }) => { + const workspace = await seedWorkspace({ repoPrefix: "subagent-parent-pill-" }); + try { + const pair = await seedParentWithSubagent(workspace, { + parentTitle: "Refactor auth flow", + childTitle: "Write session tests", + }); + await page.setViewportSize({ width: 1400, height: 900 }); + await openAgentRoute(page, { workspaceId: pair.workspaceId, agentId: pair.child.id }); + + const pill = page.getByTestId("composer-parent-agent-pill"); + await expect(pill).toHaveAccessibleName("Back to Refactor auth flow"); + await pill.click(); + + await expect(page.getByTestId(`workspace-tab-agent_${pair.parent.id}`)).toHaveAttribute( + "aria-selected", + "true", + ); + } finally { + await workspace.cleanup(); + } +}); + test("a preferred chat file link still opens beside its right-pane agent", async ({ page }) => { const target = "linked.ts:3"; const workspace = await seedMockAgentWorkspace({ diff --git a/packages/app/src/composer/tracks.tsx b/packages/app/src/composer/tracks.tsx index 3a4541d285..82bee6e3fa 100644 --- a/packages/app/src/composer/tracks.tsx +++ b/packages/app/src/composer/tracks.tsx @@ -276,7 +276,11 @@ export function ComposerTrackRow({ * knockout for marks that sit on top of an icon, and nothing sits under this one, so it comes off * too — leaving every mark's visible edge on the same rail whatever state it is in. */ -function ComposerTrackMark({ bucket }: { bucket: SidebarStateBucket | null }): ReactElement | null { +export function ComposerTrackMark({ + bucket, +}: { + bucket: SidebarStateBucket | null; +}): ReactElement | null { if (!bucket) { return null; } diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index 3ff25adf40..4fc0ff5277 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -1908,6 +1908,13 @@ export const ar: TranslationResources = { backdrop: "خلفية القائمة", }, subagents: { + parent: { + backToParent: "العودة إلى الوكيل الأصلي", + backTo: "العودة إلى {{label}}", + parent: "الأصل", + parentAgent: "الوكيل الأصلي", + openParent: "فتح الوكيل الأصلي", + }, title: "الوكلاء الفرعيون", pillLabelOne: "وكيل فرعي واحد", pillLabelMany: "{{count}} وكلاء فرعيين", diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index 1d0d1da97a..2e40707121 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -1933,6 +1933,13 @@ export const en = { backdrop: "Menu backdrop", }, subagents: { + parent: { + backToParent: "Back to parent", + backTo: "Back to {{label}}", + parent: "Parent", + parentAgent: "Parent agent", + openParent: "Open parent", + }, title: "Subagents", pillLabelOne: "1 subagent", pillLabelMany: "{{count}} subagents", diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index feafcd225f..b62913d268 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -1956,6 +1956,13 @@ export const es: TranslationResources = { backdrop: "Fondo del menú", }, subagents: { + parent: { + backToParent: "Volver al padre", + backTo: "Volver a {{label}}", + parent: "Padre", + parentAgent: "Agente padre", + openParent: "Abrir padre", + }, title: "Subagentes", pillLabelOne: "1 subagente", pillLabelMany: "{{count}} subagentes", diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index 6d8ee58400..cc3742abad 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -1954,6 +1954,13 @@ export const fr: TranslationResources = { backdrop: "Arrière-plan du menu", }, subagents: { + parent: { + backToParent: "Retour au parent", + backTo: "Retour à {{label}}", + parent: "Parent", + parentAgent: "Agent parent", + openParent: "Ouvrir le parent", + }, title: "Sous-agents", pillLabelOne: "1 sous-agent", pillLabelMany: "{{count}} sous-agents", diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index b8af6f91f6..67d46fe471 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -1927,6 +1927,13 @@ export const ja: TranslationResources = { backdrop: "メニューの背景", }, subagents: { + parent: { + backToParent: "親に戻る", + backTo: "{{label}} に戻る", + parent: "親", + parentAgent: "親エージェント", + openParent: "親を開く", + }, title: "サブエージェント", pillLabelOne: "サブエージェント 1 件", pillLabelMany: "サブエージェント {{count}} 件", diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index 1a9b36d9bd..d95899ec35 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -1918,6 +1918,13 @@ export const ko: TranslationResources = { backdrop: "메뉴 배경", }, subagents: { + parent: { + backToParent: "상위 에이전트로 돌아가기", + backTo: "{{label}}(으)로 돌아가기", + parent: "상위", + parentAgent: "상위 에이전트", + openParent: "상위 에이전트 열기", + }, title: "하위 에이전트", pillLabelOne: "하위 에이전트 1개", pillLabelMany: "하위 에이전트 {{count}}개", diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index 0d7e6acb89..fd41468395 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -1941,6 +1941,13 @@ export const ptBR: TranslationResources = { backdrop: "Fundo do menu", }, subagents: { + parent: { + backToParent: "Voltar ao pai", + backTo: "Voltar para {{label}}", + parent: "Pai", + parentAgent: "Agente pai", + openParent: "Abrir pai", + }, title: "Subagentes", pillLabelOne: "1 subagente", pillLabelMany: "{{count}} subagentes", diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index 09d46fa075..093fc60a51 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -1940,6 +1940,13 @@ export const ru: TranslationResources = { backdrop: "Фон меню", }, subagents: { + parent: { + backToParent: "Назад к родителю", + backTo: "Назад к {{label}}", + parent: "Родитель", + parentAgent: "Родительский агент", + openParent: "Открыть родителя", + }, title: "Субагенты", pillLabelOne: "1 субагент", pillLabelMany: "Субагентов: {{count}}", diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index 374bef6e88..d899a10fe8 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -1886,6 +1886,13 @@ export const zhCN: TranslationResources = { backdrop: "菜单背景", }, subagents: { + parent: { + backToParent: "返回父代理", + backTo: "返回 {{label}}", + parent: "父代理", + parentAgent: "父代理", + openParent: "打开父代理", + }, title: "Subagent", pillLabelOne: "1 个 subagent", pillLabelMany: "{{count}} 个 subagent", diff --git a/packages/app/src/panels/agent-panel.tsx b/packages/app/src/panels/agent-panel.tsx index af14b94229..ea7cc68b37 100644 --- a/packages/app/src/panels/agent-panel.tsx +++ b/packages/app/src/panels/agent-panel.tsx @@ -80,6 +80,7 @@ import { } from "@/screens/agent/agent-ready-screen-bottom-anchor"; import { WorkspaceDraftAgentTab } from "@/composer/draft/workspace-tab"; import { AgentTracks, hasAgentTracks } from "@/panels/agent-tracks"; +import { ParentAgentCallout, useParentAgentId } from "@/subagents/parent"; import { useCreateFlowStore } from "@/stores/create-flow-store"; import { buildDraftStoreKey, generateDraftId } from "@/stores/draft-keys"; import { @@ -1109,7 +1110,11 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({ }); const hasPluginComposerPills = useHasPluginComposerPills(serverId, workspaceId, agentId); const hasActiveComposer = !agentState.archivedAt && !isArchivingCurrentAgent; + const parentAgentId = useParentAgentId(serverId, agentId); + // With a composer the parent is a pill above it; without one, the box takes the composer's place. + const parentPillAgentId = showsComposer ? parentAgentId : null; const hasVisibleAgentTracks = hasAgentTracks({ + parentAgentId: parentPillAgentId, subagentRows, tasks, archiveFinishedStatus: archiveFinishedSubagents.status, @@ -1161,6 +1166,9 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({ composerState, ], ); + const parentCallout = parentAgentId ? ( + + ) : null; const composerSection = showsComposer ? ( - ) : null; + ) : ( + parentCallout + ); const streamContent = ( {showsComposer ? null : } @@ -1203,6 +1213,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({ serverId={serverId} workspaceId={workspaceId} agentId={agentId} + parentAgentId={parentPillAgentId} subagentRows={subagentRows} tasks={tasks} archiveFinishedStatus={archiveFinishedSubagents.status} diff --git a/packages/app/src/panels/agent-tracks.tsx b/packages/app/src/panels/agent-tracks.tsx index 3fc42030a7..f7c724133a 100644 --- a/packages/app/src/panels/agent-tracks.tsx +++ b/packages/app/src/panels/agent-tracks.tsx @@ -16,6 +16,7 @@ import { useSubagentOpensInSheet, type SubagentRow, } from "@/subagents"; +import { ParentAgentPill } from "@/subagents/parent"; import { SubagentsTrack } from "@/subagents/track"; import type { TodoEntry } from "@/types/stream"; import { navigateToAgent } from "@/utils/navigate-to-agent"; @@ -34,6 +35,7 @@ export const AgentTracks = memo(function AgentTracks({ serverId, workspaceId, agentId, + parentAgentId, subagentRows, tasks, archiveFinishedStatus, @@ -43,6 +45,7 @@ export const AgentTracks = memo(function AgentTracks({ serverId: string; workspaceId: string; agentId: string; + parentAgentId: string | null; subagentRows: SubagentRow[]; tasks: TodoEntry[] | undefined; archiveFinishedStatus: ArchiveFinishedStatus; @@ -88,8 +91,12 @@ export const AgentTracks = memo(function AgentTracks({ [openSubagentTarget, serverId, workspaceId], ); const handleOpenProviderSubagent = useCallback( - (parentAgentId: string, subagentId: string) => { - openSubagentTarget({ kind: "provider_subagent", parentAgentId, subagentId }); + (ownerAgentId: string, subagentId: string) => { + openSubagentTarget({ + kind: "provider_subagent", + parentAgentId: ownerAgentId, + subagentId, + }); }, [openSubagentTarget], ); @@ -108,6 +115,7 @@ export const AgentTracks = memo(function AgentTracks({ if ( !hasWorkspaceDiffStat && !hasAgentTracks({ + parentAgentId, subagentRows, tasks, archiveFinishedStatus, @@ -119,6 +127,7 @@ export const AgentTracks = memo(function AgentTracks({ return ( + {parentAgentId ? : null} 0 || Boolean(tasks?.length) || archiveFinishedStatus.kind !== "idle" || diff --git a/packages/app/src/panels/provider-subagent-panel.tsx b/packages/app/src/panels/provider-subagent-panel.tsx index ecd4a082bf..e36f7880ca 100644 --- a/packages/app/src/panels/provider-subagent-panel.tsx +++ b/packages/app/src/panels/provider-subagent-panel.tsx @@ -16,6 +16,7 @@ import { usePaneContext } from "@/panels/pane-context"; import { PaneSubtitle } from "@/panels/pane-subtitle"; import { definePanel, type PanelDescriptor } from "@/panels/panel-registry"; import { useSessionStore } from "@/stores/session-store"; +import { ParentAgentCallout } from "@/subagents/parent"; import { type SubagentRow, useSubagentsForParent } from "@/subagents/select"; import { useSubagentOpensInSheet } from "@/subagents/opens-in-sheet"; import { SubagentsTrack } from "@/subagents/track"; @@ -253,33 +254,37 @@ function ProviderSubagentPanel() { return ( {subtitle ? : null} - - + + + + + ); } const styles = StyleSheet.create((theme) => ({ container: { flex: 1, minHeight: 0 }, + stream: { flex: 1, minHeight: 0 }, unsupported: { flex: 1, alignItems: "center", justifyContent: "center", padding: 24 }, unsupportedText: { color: theme.colors.foregroundMuted, textAlign: "center" }, })); diff --git a/packages/app/src/subagents/parent/callout.tsx b/packages/app/src/subagents/parent/callout.tsx new file mode 100644 index 0000000000..f76e1267e3 --- /dev/null +++ b/packages/app/src/subagents/parent/callout.tsx @@ -0,0 +1,116 @@ +import type { ReactElement } from "react"; +import { Text, View } from "react-native"; +import { useTranslation } from "react-i18next"; +import { CornerUpLeft } from "lucide-react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { Button } from "@/components/ui/button"; +import { ComposerTrackMark } from "@/composer/tracks"; +import { FOOTER_HEIGHT } from "@/constants/layout"; +import type { Theme } from "@/styles/theme"; +import { useParentAgent, type ParentAgent } from "./use-parent-agent"; + +function ParentIcon({ + icon: Icon, + size, + color = "", +}: { + icon: ParentAgent["icon"]; + size: number; + color?: string; +}) { + return ; +} + +const ThemedParentIcon = withUnistyles(ParentIcon); +const foregroundColorMapping = (theme: Theme) => ({ color: theme.colors.foreground }); + +/** Stands in the composer's place on a subagent shown without one: who the parent is, and the way back. */ +export function ParentAgentCallout({ + serverId, + parentAgentId, +}: { + serverId: string; + parentAgentId: string; +}): ReactElement { + const { t } = useTranslation(); + const parent = useParentAgent(serverId, parentAgentId); + + return ( + + + + + + + {t("subagents.parent.parent")} + + + {parent.label ?? t("subagents.parent.parentAgent")} + + + + + + + + ); +} + +const styles = StyleSheet.create((theme) => ({ + rail: { + minHeight: FOOTER_HEIGHT, + alignItems: "center", + width: "100%", + padding: theme.spacing[4], + }, + callout: { + width: "100%", + maxWidth: theme.contentMaxWidth, + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[3], + backgroundColor: theme.colors.surface1, + borderWidth: theme.borderWidth[1], + borderColor: theme.colors.borderAccent, + borderRadius: theme.borderRadius["2xl"], + padding: theme.spacing[3], + paddingRight: { xs: theme.spacing[3], md: theme.spacing[4] }, + }, + avatar: { + width: 36, + height: 36, + borderRadius: theme.borderRadius.lg, + backgroundColor: theme.colors.surface2, + alignItems: "center", + justifyContent: "center", + }, + body: { + flex: 1, + minWidth: 0, + gap: theme.spacing[0.5], + }, + eyebrow: { + fontSize: theme.fontSize.sm, + color: theme.colors.foregroundMuted, + }, + titleRow: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[2], + minWidth: 0, + }, + title: { + flexShrink: 1, + fontSize: theme.fontSize.base, + fontWeight: theme.fontWeight.medium, + color: theme.colors.foreground, + }, +})); diff --git a/packages/app/src/subagents/parent/index.ts b/packages/app/src/subagents/parent/index.ts new file mode 100644 index 0000000000..daca7d3d16 --- /dev/null +++ b/packages/app/src/subagents/parent/index.ts @@ -0,0 +1,3 @@ +export { ParentAgentCallout } from "./callout"; +export { ParentAgentPill } from "./pill"; +export { useParentAgentId } from "./use-parent-agent"; diff --git a/packages/app/src/subagents/parent/pill.tsx b/packages/app/src/subagents/parent/pill.tsx new file mode 100644 index 0000000000..63f9407f8b --- /dev/null +++ b/packages/app/src/subagents/parent/pill.tsx @@ -0,0 +1,79 @@ +import { useCallback, useMemo, useState, type ReactElement } from "react"; +import { Text } from "react-native"; +import { useTranslation } from "react-i18next"; +import { ChevronLeft } from "lucide-react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { PressHighlight } from "@/components/ui/press-highlight"; +import { composerPillStyles } from "@/composer/pill-styles"; +import { ComposerTrackMark } from "@/composer/tracks"; +import type { Theme } from "@/styles/theme"; +import { useParentAgent } from "./use-parent-agent"; + +const ThemedChevronLeft = withUnistyles(ChevronLeft); +const mutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); +const foregroundColorMapping = (theme: Theme) => ({ color: theme.colors.foreground }); + +/** + * The way back from a subagent to the agent that started it. It leads the pill rail and names + * the parent rather than saying "parent": in a stack of subagents the title is what tells you + * where you will land. + */ +export function ParentAgentPill({ + serverId, + parentAgentId, +}: { + serverId: string; + parentAgentId: string; +}): ReactElement { + const { t } = useTranslation(); + const parent = useParentAgent(serverId, parentAgentId); + const [isHovered, setIsHovered] = useState(false); + const handleHoverIn = useCallback(() => setIsHovered(true), []); + const handleHoverOut = useCallback(() => setIsHovered(false), []); + const bodyStyle = useMemo( + () => [composerPillStyles.body, styles.body, isHovered && composerPillStyles.bodyActive], + [isHovered], + ); + const labelStyle = useMemo( + () => [composerPillStyles.label, styles.label, isHovered && composerPillStyles.labelActive], + [isHovered], + ); + const label = parent.label ?? t("subagents.parent.backToParent"); + + return ( + + + + + {label} + + + ); +} + +const styles = StyleSheet.create((theme) => ({ + // The chevron's box is wider than its stroke, so the pill pulls it toward the edge to keep the + // visible glyph on the same inset as other pills' leading marks. + body: { + flexShrink: 1, + minWidth: 0, + gap: theme.spacing[1.5], + paddingLeft: theme.spacing[2], + }, + label: { + flexShrink: 1, + maxWidth: { xs: 140, md: 240 }, + }, +})); diff --git a/packages/app/src/subagents/parent/use-parent-agent.ts b/packages/app/src/subagents/parent/use-parent-agent.ts new file mode 100644 index 0000000000..e3916e6bbe --- /dev/null +++ b/packages/app/src/subagents/parent/use-parent-agent.ts @@ -0,0 +1,38 @@ +import { useCallback } from "react"; +import { useAgentDescriptor } from "@/agent-presentation"; +import type { PanelDescriptor } from "@/panels/panel-registry"; +import { useSessionStore } from "@/stores/session-store"; +import type { SidebarStateBucket } from "@/utils/sidebar-agent-state"; +import { navigateToAgent } from "@/utils/navigate-to-agent"; + +export interface ParentAgent { + /** The parent's title, or null while it has none — callers fall back to a generic name. */ + label: string | null; + icon: PanelDescriptor["icon"]; + statusBucket: SidebarStateBucket | null; + open: () => void; +} + +/** The parent of a managed agent, or null for a root or detached agent. */ +export function useParentAgentId(serverId: string, agentId: string): string | null { + return useSessionStore((state) => { + const session = state.sessions[serverId]; + const agent = session?.agents.get(agentId) ?? session?.agentDetails.get(agentId); + return agent?.parentAgentId ?? null; + }); +} + +/** The parent as its own tab presents it, and the way back to it. */ +export function useParentAgent(serverId: string, parentAgentId: string): ParentAgent { + const descriptor = useAgentDescriptor({ kind: "agent", agentId: parentAgentId }, { serverId }); + // The parent may live in another workspace; navigateToAgent opens it wherever it is. + const open = useCallback(() => { + navigateToAgent({ serverId, agentId: parentAgentId }); + }, [parentAgentId, serverId]); + return { + label: descriptor.label || null, + icon: descriptor.icon, + statusBucket: descriptor.statusBucket, + open, + }; +} From 16fe07560f58ae0b35ccedaf40d04f426833b2b3 Mon Sep 17 00:00:00 2001 From: Alessio Re Date: Mon, 26 Oct 2026 04:51:44 +0100 Subject: [PATCH 006/173] fix(app): make question cards link-aware and selectable without accidental answers Render question bodies and option text with the shared Markdown renderer. Opening links or selecting question and description text leaves answers unchanged. Labels remain answer controls, and double-clicking a label advances only once. Add browser regression coverage and stabilize Markdown WASM loading in the test harness. Closes #3164. Co-authored-by: Alessio Re --- .../question-prompt-pagination.spec.ts | 212 +++++++++++++++++- .../app/src/components/markdown/renderer.tsx | 25 ++- .../app/src/components/markdown/styles.ts | 8 +- .../question-form-card.browser.test.tsx | 6 + .../app/src/components/question-form-card.tsx | 77 ++++--- packages/app/test-stubs/expo-clipboard.ts | 10 + .../app/test-stubs/lucide-react-native.ts | 5 + packages/app/vitest.config.ts | 19 ++ .../agent/providers/mock-load-test-agent.ts | 29 +++ 9 files changed, 348 insertions(+), 43 deletions(-) create mode 100644 packages/app/test-stubs/expo-clipboard.ts diff --git a/packages/app/e2e/browser/question-prompt-pagination.spec.ts b/packages/app/e2e/browser/question-prompt-pagination.spec.ts index b444a8cddf..90a87433ed 100644 --- a/packages/app/e2e/browser/question-prompt-pagination.spec.ts +++ b/packages/app/e2e/browser/question-prompt-pagination.spec.ts @@ -1,6 +1,6 @@ import { fork } from "node:child_process"; import path from "node:path"; -import { expect } from "@playwright/test"; +import { expect, type BrowserContext, type Locator, type Page } from "@playwright/test"; import { z } from "zod"; import { test } from "../support/fixtures"; import { expectVisibleAgentSurfacesIdle } from "../support/helpers/agent-stream"; @@ -34,8 +34,218 @@ const ROLLOUT_QUESTION = "Which rollout should we use?"; const SUCCESS_QUESTION = "What success criteria should we use?"; const REPO_URL_QUESTION = "What is the GitHub private repo URL to push to?"; const COMMIT_MESSAGE_QUESTION = "What should the first commit message be?"; +const LINKED_QUESTION = "Sign in at https://example.com/login, then follow the setup guide. Done?"; + +function selectedText(page: Page) { + return page.evaluate(() => window.getSelection()?.toString().trim()); +} + +const CHECKS_QUESTION = "Which checks should run?"; +const DONE_DESCRIPTION = "Logs are at https://example.com/logs if sign-in fails."; +const LINT_DESCRIPTION = "Rules: https://example.com/lint"; + +async function openLinkedQuestions(page: Page, context: BrowserContext) { + await context.route("https://example.com/**", (route) => + route.fulfill({ status: 200, body: "ok" }), + ); + const session = await seedMockAgentWorkspace({ + repoPrefix: "question-option-links-", + title: "Question option links e2e", + initialPrompt: "Emit synthetic questions with links.", + }); + await openAgentRoute(page, session); + await waitForQuestionPrompt(page, 120_000); + return { session, card: page.getByTestId("question-form-card").first() }; +} + +async function dragAcross(page: Page, target: Locator) { + const bounds = await target.boundingBox(); + if (!bounds) throw new Error("Text is not visible"); + const y = bounds.y + bounds.height / 2; + await page.mouse.move(bounds.x + 1, y); + await page.mouse.down(); + await page.mouse.move(bounds.x + bounds.width - 1, y, { steps: 12 }); + await page.mouse.up(); +} + +async function clickLinkAndExpectPage(context: BrowserContext, link: Locator, url: string) { + const popup = context.waitForEvent("page"); + await link.click(); + await expect.poll(async () => (await popup).url()).toBe(url); +} + +async function expectChecked(option: Locator, checked: boolean) { + await expect(option).toHaveAttribute("aria-checked", String(checked)); +} + +test.describe("Question option text", () => { + test("links in an option label or description open without answering", async ({ + page, + context, + }) => { + test.setTimeout(180_000); + const { session, card } = await openLinkedQuestions(page, context); + try { + const done = card.getByRole("radio", { name: "Done" }); + const notYet = card.getByRole("radio", { name: "Not yet" }); + + await clickLinkAndExpectPage( + context, + notYet.getByRole("link", { name: "status" }), + "https://example.com/status", + ); + await clickLinkAndExpectPage( + context, + done.getByRole("link", { name: "https://example.com/logs" }), + "https://example.com/logs", + ); + + await expectCurrentQuestion(page, { index: 1, total: 2, question: LINKED_QUESTION }); + await expectChecked(done, false); + await expectChecked(notYet, false); + } finally { + await session.cleanup(); + } + }); + + test("selecting description text never answers, and the label still does", async ({ + page, + context, + }) => { + test.setTimeout(180_000); + const { session, card } = await openLinkedQuestions(page, context); + try { + const done = card.getByRole("radio", { name: "Done" }); + const description = done.getByTestId("question-form-option-description"); + + await dragAcross(page, description); + await expect.poll(() => selectedText(page)).toBe(DONE_DESCRIPTION); + await expectChecked(done, false); + + await description.getByText("Logs are at", { exact: false }).dblclick({ + position: { x: 4, y: 4 }, + }); + await expect.poll(() => selectedText(page)).toBe("Logs"); + await expectCurrentQuestion(page, { index: 1, total: 2, question: LINKED_QUESTION }); + await expectChecked(done, false); + + await done.getByText("Done", { exact: true }).click(); + await expectCurrentQuestion(page, { index: 2, total: 2, question: CHECKS_QUESTION }); + await openQuestion(page, { index: 1, total: 2 }); + await expectChecked(done, true); + } finally { + await session.cleanup(); + } + }); + + test("double-clicking a single-select label answers once", async ({ page, context }) => { + test.setTimeout(180_000); + const { session, card } = await openLinkedQuestions(page, context); + try { + await card.getByRole("radio", { name: "Done" }).getByText("Done", { exact: true }).dblclick(); + + await expectCurrentQuestion(page, { index: 2, total: 2, question: CHECKS_QUESTION }); + await expectChecked(card.getByRole("checkbox", { name: "Lint" }), false); + await expectChecked(card.getByRole("checkbox", { name: "Typecheck" }), false); + await openQuestion(page, { index: 1, total: 2 }); + await expectChecked(card.getByRole("radio", { name: "Done" }), true); + } finally { + await session.cleanup(); + } + }); + + test("multi-select description links and selection leave the option unchanged", async ({ + page, + context, + }) => { + test.setTimeout(180_000); + const { session, card } = await openLinkedQuestions(page, context); + try { + await card.getByRole("radio", { name: "Done" }).getByText("Done", { exact: true }).click(); + await expectCurrentQuestion(page, { index: 2, total: 2, question: CHECKS_QUESTION }); + + const lint = card.getByRole("checkbox", { name: "Lint" }); + const typecheck = card.getByRole("checkbox", { name: "Typecheck" }); + const description = lint.getByTestId("question-form-option-description"); + + await clickLinkAndExpectPage( + context, + description.getByRole("link", { name: "https://example.com/lint" }), + "https://example.com/lint", + ); + await expectChecked(lint, false); + + await dragAcross(page, description); + await expect.poll(() => selectedText(page)).toBe(LINT_DESCRIPTION); + await expectChecked(lint, false); + + await description.getByText("Rules:", { exact: false }).dblclick({ + position: { x: 4, y: 4 }, + }); + await expect.poll(() => selectedText(page)).toBe("Rules"); + await expectChecked(lint, false); + + await typecheck.getByText("Typecheck", { exact: true }).dblclick(); + await expectChecked(typecheck, true); + await lint.getByText("Lint", { exact: true }).click(); + await expectChecked(lint, true); + } finally { + await session.cleanup(); + } + }); +}); test.describe("Question prompt pagination", () => { + test("question links open without answering, and the question text is selectable", async ({ + page, + context, + }) => { + test.setTimeout(180_000); + await context.route("https://example.com/**", (route) => + route.fulfill({ status: 200, body: "ok" }), + ); + + const session = await seedMockAgentWorkspace({ + repoPrefix: "question-links-", + title: "Question links e2e", + initialPrompt: "Emit synthetic questions with links.", + }); + + try { + await openAgentRoute(page, session); + await waitForQuestionPrompt(page, 120_000); + + const card = page.getByTestId("question-form-card").first(); + const question = card.getByTestId("question-form-current-question"); + await expect(question).toHaveText(LINKED_QUESTION); + await expect(question.getByRole("link", { name: "https://example.com/login" })).toBeVisible(); + await expect(question.getByRole("link", { name: "the setup guide" })).toBeVisible(); + + const bounds = await question.boundingBox(); + if (!bounds) throw new Error("Question text is not visible"); + const y = bounds.y + bounds.height / 2; + await page.mouse.move(bounds.x + 1, y); + await page.mouse.down(); + await page.mouse.move(bounds.x + bounds.width - 1, y, { steps: 12 }); + await page.mouse.up(); + await expect.poll(() => selectedText(page)).toBe(LINKED_QUESTION); + + const popup = context.waitForEvent("page"); + await question.getByRole("link", { name: "the setup guide" }).click(); + await expect.poll(async () => (await popup).url()).toBe("https://example.com/setup"); + + await expect(page.getByTestId("question-form-card")).toHaveCount(1); + for (const option of ["Done", "Not yet"]) { + await expect(card.getByRole("radio", { name: option })).toHaveAttribute( + "aria-checked", + "false", + ); + } + } finally { + await session.cleanup(); + } + }); + test("shows one question at a time with numbered navigation", async ({ page }) => { test.setTimeout(180_000); diff --git a/packages/app/src/components/markdown/renderer.tsx b/packages/app/src/components/markdown/renderer.tsx index 6d79beb01f..8e51495369 100644 --- a/packages/app/src/components/markdown/renderer.tsx +++ b/packages/app/src/components/markdown/renderer.tsx @@ -23,14 +23,29 @@ const ThemedMarkdown = withUnistyles(EnrichedMarkdownText); const MD4C_FLAGS = { latexMath: false, hardSoftBreaks: true, admonitions: true }; // Reading the breakpoint here makes Unistyles restyle the text when the layout crosses it. -const markdownStyle = (compact: boolean) => (theme: Theme, rt: { breakpoint?: string }) => - createMarkdownStyles(theme, { compact, blockGap: resolveDensity(rt, density.blockGap) }); +const markdownStyle = + (compact: boolean, muted = false) => + (theme: Theme, rt: { breakpoint?: string }) => + createMarkdownStyles(theme, { + compact, + muted, + blockGap: resolveDensity(rt, density.blockGap), + }); const regularStyle = markdownStyle(false); const compactStyle = markdownStyle(true); +const compactMutedStyle = markdownStyle(true, true); + +function pickMarkdownStyle(compact: boolean, muted: boolean) { + if (!compact) return regularStyle; + return muted ? compactMutedStyle : compactStyle; +} export interface MarkdownRendererProps extends MarkdownImageContext { text: string; compact?: boolean; + /** Muted text colour. Compact surfaces only. */ + muted?: boolean; + selectable?: boolean; streaming?: boolean; onLinkPress?: (url: string) => unknown; } @@ -56,6 +71,8 @@ export const MarkdownRenderer = memo(function MarkdownRenderer(props: MarkdownRe const MarkdownPart = memo(function MarkdownPart({ text, compact = false, + muted = false, + selectable = true, streaming = false, onLinkPress, ...imageContext @@ -98,9 +115,9 @@ const MarkdownPart = memo(function MarkdownPart({ ({ diff --git a/packages/app/src/components/question-form-card.browser.test.tsx b/packages/app/src/components/question-form-card.browser.test.tsx index 83120931d1..0b2a5df25d 100644 --- a/packages/app/src/components/question-form-card.browser.test.tsx +++ b/packages/app/src/components/question-form-card.browser.test.tsx @@ -10,6 +10,12 @@ import { QuestionFormCard } from "./question-form-card"; // Load translations so controls expose their real accessible names. void testI18n; +// The Markdown engine does not load in this harness; question and option text are covered by +// e2e/browser/question-prompt-pagination.spec.ts. Plain text keeps these tests on the answers. +vi.mock("@/components/markdown/renderer", () => ({ + MarkdownRenderer: ({ text }: { text: string }) => {text}, +})); + // App sources compile against the classic JSX runtime, which expects React on the global. beforeEach(() => vi.stubGlobal("React", React)); diff --git a/packages/app/src/components/question-form-card.tsx b/packages/app/src/components/question-form-card.tsx index 7014de89d1..8ff81963d1 100644 --- a/packages/app/src/components/question-form-card.tsx +++ b/packages/app/src/components/question-form-card.tsx @@ -1,7 +1,13 @@ import { Alert } from "@/components/ui/alert"; import { LoadingSpinner } from "@/components/ui/loading-spinner"; import { useState, useCallback, useMemo, useRef, type RefObject } from "react"; -import { View, Text, Pressable, type PressableStateCallbackType } from "react-native"; +import { + View, + Text, + Pressable, + type GestureResponderEvent, + type PressableStateCallbackType, +} from "react-native"; import { StyleSheet, useUnistyles } from "react-native-unistyles"; import { useIsCompactFormFactor } from "@/constants/layout"; import { Check, X } from "lucide-react-native"; @@ -12,6 +18,7 @@ import { isWeb } from "@/constants/platform"; import { EditingTextInput as TextInput } from "@/components/ui/text-input"; import type { EditingTextInputHandle } from "@/components/ui/text-input/types"; import { ScrollableCodeSurface } from "@/components/ui/scrollable-code-surface"; +import { MarkdownRenderer } from "@/components/markdown/renderer"; import { areQuestionsAnswered, buildQuestionFormAnswers, @@ -36,6 +43,20 @@ const IS_WEB = isWeb; // drag to the preview's nested scroll, so lines past a cap would be unreachable. const OPTION_PREVIEW_MAX_HEIGHT = IS_WEB ? 240 : undefined; +// Web clicks that must not answer: a link in the label, anything in the description, and the +// second click of a double-click, which would otherwise land on the next question's options. +function isNonAnsweringClick(event: GestureResponderEvent, description: View | null): boolean { + if (!IS_WEB) return false; + const click = event.nativeEvent as unknown as MouseEvent; + if (click.detail > 1) return true; + const target = click.target as Element | null; + const descriptionElement = description as unknown as Element | null; + return Boolean(target?.closest("a") || descriptionElement?.contains(target)); +} + +// The description is selectable text, so a touch on it belongs to the text, not the option. +const claimResponder = () => true; + function getQuestionInputPlaceholder({ question, answerPlaceholder, @@ -71,9 +92,14 @@ function QuestionOptionRow({ }: QuestionOptionRowProps) { const { theme } = useUnistyles(); - const handlePress = useCallback(() => { - onToggle(qIndex, optIndex, multiSelect); - }, [onToggle, qIndex, optIndex, multiSelect]); + const descriptionRef = useRef(null); + const handlePress = useCallback( + (event: GestureResponderEvent) => { + if (isNonAnsweringClick(event, descriptionRef.current)) return; + onToggle(qIndex, optIndex, multiSelect); + }, + [onToggle, qIndex, optIndex, multiSelect], + ); const pressableStyle = useCallback( ({ pressed, hovered }: PressableStateCallbackType & { hovered?: boolean }) => [ @@ -86,17 +112,6 @@ function QuestionOptionRow({ [isSelected, theme.colors.surface2], ); - const optionLabelStyle = useMemo( - () => [ - styles.optionLabel, - { color: isSelected ? theme.colors.foreground : theme.colors.foregroundMuted }, - ], - [isSelected, theme.colors.foreground, theme.colors.foregroundMuted], - ); - const optionDescriptionStyle = useMemo( - () => [styles.optionDescription, { color: theme.colors.foregroundMuted }], - [theme.colors.foregroundMuted], - ); const accessibilityState = useMemo(() => ({ checked: isSelected }), [isSelected]); // Static left-side control: square for multi-select, circle for single-select. @@ -135,9 +150,15 @@ function QuestionOptionRow({ {isSelected && !multiSelect ? : null} - {option.label} + {option.description ? ( - {option.description} + + + ) : null} {option.preview ? ( // Shown for every option at once so they can be compared before picking. @@ -522,10 +543,6 @@ export function QuestionFormCard({ ], [theme.colors.surface1, theme.colors.border], ); - const questionTextStyle = useMemo( - () => [styles.questionText, { color: theme.colors.foreground }], - [theme.colors.foreground], - ); // Single-select radios need a group; checkboxes are valid standalone. const optionsGroupAccessibility = useMemo( () => @@ -570,9 +587,9 @@ export function QuestionFormCard({ onSelect={handleSelectQuestion} /> - - {activeQuestion?.question} - + + + {activeQuestion ? ( @@ -675,9 +692,6 @@ const styles = StyleSheet.create((theme) => ({ }, questionText: { flex: 1, - fontSize: theme.fontSize.base, - fontWeight: theme.fontWeight.normal, - lineHeight: 22, }, optionsWrap: { gap: theme.spacing[1], @@ -723,15 +737,6 @@ const styles = StyleSheet.create((theme) => ({ flex: 1, gap: theme.spacing[1], }, - optionLabel: { - fontSize: theme.fontSize.base, - fontWeight: theme.fontWeight.normal, - lineHeight: 22, - }, - optionDescription: { - fontSize: theme.fontSize.base, - lineHeight: 20, - }, optionPreviewText: { lineHeight: 20, ...(isWeb ? { whiteSpace: "pre-wrap", overflowWrap: "break-word" } : null), diff --git a/packages/app/test-stubs/expo-clipboard.ts b/packages/app/test-stubs/expo-clipboard.ts new file mode 100644 index 0000000000..9663320efb --- /dev/null +++ b/packages/app/test-stubs/expo-clipboard.ts @@ -0,0 +1,10 @@ +// The package ships JSX in .js files, which the dependency optimizer cannot parse. +export async function setStringAsync(): Promise { + return true; +} +export async function getStringAsync(): Promise { + return ""; +} +export async function hasStringAsync(): Promise { + return false; +} diff --git a/packages/app/test-stubs/lucide-react-native.ts b/packages/app/test-stubs/lucide-react-native.ts index 200048ad53..a85976e1bf 100644 --- a/packages/app/test-stubs/lucide-react-native.ts +++ b/packages/app/test-stubs/lucide-react-native.ts @@ -111,3 +111,8 @@ export const Upload = StubIcon; export const Wrench = StubIcon; export const X = StubIcon; export const XCircle = StubIcon; +export const Code = StubIcon; +export const Maximize2 = StubIcon; +export const Workflow = StubIcon; +export const ZoomIn = StubIcon; +export const ZoomOut = StubIcon; diff --git a/packages/app/vitest.config.ts b/packages/app/vitest.config.ts index 2d7149442e..2b56646b2a 100644 --- a/packages/app/vitest.config.ts +++ b/packages/app/vitest.config.ts @@ -19,6 +19,20 @@ const resolvePackageEntry = (packageName: string) => { export default defineConfig({ plugins: [ + { + name: "markdown-wasm-commonjs-export", + transform(source, id) { + // The ESM package contains a CommonJS WASM factory. Metro handles the + // interop; Vite needs an ESM export instead of the CommonJS trailer. + if (!id.endsWith("/lib/module/web/wasm/md4c.js")) return; + const trailer = source.lastIndexOf("\nif (typeof exports === 'object'"); + if (trailer < 0) throw new Error("Markdown WASM CommonJS trailer was not found"); + return { + code: `${source.slice(0, trailer)}\nexport default createMd4cModule;`, + map: null, + }; + }, + }, { name: "compile-usage-components", enforce: "pre", @@ -151,6 +165,7 @@ export default defineConfig({ "react-native-gesture-handler > invariant", ], exclude: [ + "react-native-enriched-markdown", "react-native-reanimated", "react-native-gesture-handler", "react-native-keyboard-controller", @@ -254,6 +269,10 @@ export default defineConfig({ find: /^react-native-reanimated\/scripts\/validate-worklets-version$/, replacement: path.resolve(__dirname, "test-stubs/reanimated-validate-worklets-version.ts"), }, + { + find: /^expo-clipboard$/, + replacement: path.resolve(__dirname, "test-stubs/expo-clipboard.ts"), + }, { find: /^expo-linking$/, replacement: path.resolve(__dirname, "test-stubs/expo-linking.ts"), diff --git a/packages/server/src/server/agent/providers/mock-load-test-agent.ts b/packages/server/src/server/agent/providers/mock-load-test-agent.ts index b7b301540a..7055030dc0 100644 --- a/packages/server/src/server/agent/providers/mock-load-test-agent.ts +++ b/packages/server/src/server/agent/providers/mock-load-test-agent.ts @@ -295,6 +295,35 @@ function parseMockQuestionPrompt(prompt: AgentPromptInput): MockQuestionPromptRe return null; } + if (/with\s+links/i.test(text)) { + return { + questions: [ + { + question: + "Sign in at https://example.com/login, then follow [the setup guide](https://example.com/setup). Done?", + header: "signIn", + options: [ + { + label: "Done", + description: "Logs are at https://example.com/logs if sign-in fails.", + }, + { label: "Not yet, see [status](https://example.com/status)" }, + ], + multiSelect: false, + }, + { + question: "Which checks should run?", + header: "checks", + options: [ + { label: "Lint", description: "Rules: https://example.com/lint" }, + { label: "Typecheck" }, + ], + multiSelect: true, + }, + ], + }; + } + if (/free[-\s]?write|freeform|text[-\s]?only/i.test(text)) { return { questions: [ From 6f07b0de489932e1c1dbe3e42f243fc054335700 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Mon, 26 Oct 2026 11:18:47 +0700 Subject: [PATCH 007/173] feat(app): recall sent messages with Up and Down in an empty composer (#7710) Fixing a prompt after interrupting it, or retrying one after a provider error, meant scrolling up and copying it out of the chat. Up in an empty agent composer now fills the last message sent to that agent; Up walks older, Down walks newer and past the newest back to empty. History is read from the loaded timeline on key press, not kept in a separate store, so it follows rewinds, reloads and other devices and costs nothing while a turn streams. Recall only starts from an empty composer, so it never discards a half-written draft. While a recalled message is unedited the autocomplete stays hidden, otherwise a recalled `/command` would open the picker and Enter would pick an option instead of sending. --- .../app/e2e/browser/composer-recall.spec.ts | 81 +++++++++++++ packages/app/src/composer/index.tsx | 34 ++++-- packages/app/src/composer/input/input.tsx | 8 +- packages/app/src/composer/recall.test.ts | 109 ++++++++++++++++++ packages/app/src/composer/recall.ts | 68 +++++++++++ packages/app/src/stores/session-store.test.ts | 20 ++++ packages/app/src/stores/session-store.ts | 20 ++++ 7 files changed, 331 insertions(+), 9 deletions(-) create mode 100644 packages/app/e2e/browser/composer-recall.spec.ts create mode 100644 packages/app/src/composer/recall.test.ts create mode 100644 packages/app/src/composer/recall.ts diff --git a/packages/app/e2e/browser/composer-recall.spec.ts b/packages/app/e2e/browser/composer-recall.spec.ts new file mode 100644 index 0000000000..368d23409c --- /dev/null +++ b/packages/app/e2e/browser/composer-recall.spec.ts @@ -0,0 +1,81 @@ +import { expect, test, type Page } from "../support/fixtures"; +import { + composerLocator, + expectComposerDraft, + expectComposerVisible, + submitMessage, + typeIntoFocusedComposer, +} from "../support/helpers/composer"; +import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent"; + +function userMessages(page: Page) { + return page.getByTestId("user-message"); +} + +async function sendAndWaitForMessage(page: Page, text: string, expectedCount: number) { + await submitMessage(page, text); + await expect(userMessages(page)).toHaveCount(expectedCount, { timeout: 30_000 }); + await expectComposerDraft(page, ""); +} + +async function pressInComposer(page: Page, key: string) { + await composerLocator(page).press(key); +} + +test.describe("Composer recall", () => { + test("Up and Down walk sent messages from an empty composer", async ({ page }) => { + const session = await seedMockAgentWorkspace({ + repoPrefix: "composer-recall-", + title: "Composer recall", + }); + try { + await openAgentRoute(page, session); + await expectComposerVisible(page); + await sendAndWaitForMessage(page, "fix the auth bug", 1); + await sendAndWaitForMessage(page, "add tests", 2); + + await pressInComposer(page, "ArrowUp"); + await expectComposerDraft(page, "add tests"); + await pressInComposer(page, "ArrowUp"); + await expectComposerDraft(page, "fix the auth bug"); + await pressInComposer(page, "ArrowDown"); + await expectComposerDraft(page, "add tests"); + await pressInComposer(page, "ArrowDown"); + await expectComposerDraft(page, ""); + + await pressInComposer(page, "ArrowUp"); + await typeIntoFocusedComposer(page, " for login"); + await expectComposerDraft(page, "add tests for login"); + await pressInComposer(page, "ArrowUp"); + await expectComposerDraft(page, "add tests for login"); + + await pressInComposer(page, "Enter"); + await expect(userMessages(page)).toHaveCount(3, { timeout: 30_000 }); + await expect(userMessages(page).last()).toContainText("add tests for login"); + } finally { + await session.cleanup(); + } + }); + + test("a recalled slash message does not open the command picker", async ({ page }) => { + const session = await seedMockAgentWorkspace({ + repoPrefix: "composer-recall-slash-", + title: "Composer recall slash", + }); + try { + await openAgentRoute(page, session); + await expectComposerVisible(page); + await sendAndWaitForMessage(page, "/tdd", 1); + + const popover = page.getByTestId("composer-autocomplete-popover").filter({ visible: true }); + await pressInComposer(page, "ArrowUp"); + await expectComposerDraft(page, "/tdd"); + await expect(popover).toHaveCount(0); + + await typeIntoFocusedComposer(page, "x"); + await expect(popover.first()).toBeVisible({ timeout: 30_000 }); + } finally { + await session.cleanup(); + } + }); +}); diff --git a/packages/app/src/composer/index.tsx b/packages/app/src/composer/index.tsx index ed9ccca4f7..ba85de2516 100644 --- a/packages/app/src/composer/index.tsx +++ b/packages/app/src/composer/index.tsx @@ -55,7 +55,11 @@ import { } from "@/composer/agent-controls"; import { ContextWindowMeter } from "@/components/context-window-meter"; import { useImageAttachmentPicker } from "@/hooks/use-image-attachment-picker"; -import { selectAgentTurnPresentation, useSessionStore } from "@/stores/session-store"; +import { + selectAgentSentMessages, + selectAgentTurnPresentation, + useSessionStore, +} from "@/stores/session-store"; import { useFilePicker } from "@/hooks/use-file-picker"; import { useFileDrop } from "@/components/file-drop/use-file-drop"; import type { DroppedItem } from "@/components/file-drop/types"; @@ -118,6 +122,7 @@ import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler"; import type { KeyboardActionDefinition } from "@/keyboard/keyboard-action-dispatcher"; import type { MessageInputKeyboardActionKind } from "@/keyboard/actions"; import { submitAgentInput } from "@/composer/submit"; +import { ComposerRecall } from "@/composer/recall"; import { createMessageSubmissionWriter } from "@/composer/submission/writer"; import { ComposerKeyboardScopeProvider, useComposerKeyboardScope } from "@/composer/keyboard-scope"; import { useAppSettings } from "@/hooks/use-settings"; @@ -995,6 +1000,7 @@ interface ComposerAutocompleteHandle { function ComposerAutocompleteBinding({ text, cursor, + recall, configuration, inputRef, anchorRef, @@ -1003,6 +1009,7 @@ function ComposerAutocompleteBinding({ }: { text: ComposerTextSource; cursor: StoreApi; + recall: ComposerRecall; configuration: Omit< Parameters[0], "userInput" | "cursorIndex" | "onAutocompleteApplied" @@ -1020,9 +1027,11 @@ function ComposerAutocompleteBinding({ cursorIndex: Math.min(cursorIndex, userInput.length), onAutocompleteApplied: () => inputRef.current?.focus(), }); + // A recalled message is sent as is; its leading `/command` must not open the picker. + const isShown = show && !recall.isShowing(userInput); const handleKeyPress = autocomplete.onKeyPress; - useImperativeHandle(ref, () => ({ onKeyPress: (event) => show && handleKeyPress(event) }), [ - show, + useImperativeHandle(ref, () => ({ onKeyPress: (event) => isShown && handleKeyPress(event) }), [ + isShown, handleKeyPress, ]); const selectOption = autocomplete.onSelectOption; @@ -1032,7 +1041,7 @@ function ComposerAutocompleteBinding({ ); return ( () => cursorPublication.cancel(), [cursorPublication]); const autocompleteRef = useRef(null); + const recall = useMemo(() => new ComposerRecall(), []); const [isProcessing, setIsProcessing] = useState(false); const [pendingFiles, setPendingFiles] = useState([]); const nextPendingFileId = useRef(0); @@ -1981,10 +1991,19 @@ function ComposerContentImpl({ const hasSendableContent = hasText || selectedAttachments.length > 0; - // Handle keyboard navigation for command autocomplete. + // An open autocomplete owns the arrows; otherwise they may recall sent messages. const handleCommandKeyPress = useCallback( - (event: ComposerKeyPressEvent) => autocompleteRef.current?.onKeyPress(event) ?? false, - [], + (event: ComposerKeyPressEvent) => { + if (autocompleteRef.current?.onKeyPress(event)) return true; + const recalledText = recall.handleKeyPress(event, () => + selectAgentSentMessages(useSessionStore.getState().sessions[serverId], agentId), + ); + if (recalledText === null) return false; + event.preventDefault(); + replaceUserInput(recalledText); + return true; + }, + [agentId, recall, replaceUserInput, serverId], ); const cancelButtonStyle = useMemo( @@ -2423,6 +2442,7 @@ function ComposerContentImpl({ void; input: ComposerInputSnapshot; } @@ -210,6 +212,7 @@ type WebTextInputKeyPressEvent = NativeSyntheticEvent< metaKey?: boolean; ctrlKey?: boolean; shiftKey?: boolean; + altKey?: boolean; // Web-only: present on DOM KeyboardEvent during IME composition (CJK input). isComposing?: boolean; keyCode?: number; @@ -411,17 +414,18 @@ function handleDesktopKeyPressImpl( ): void { if (isImeComposingKeyboardEvent(event.nativeEvent)) return; + const { shiftKey, metaKey, ctrlKey, altKey } = event.nativeEvent; + if (ctx.onKeyPressCallback) { const handled = ctx.onKeyPressCallback({ key: event.nativeEvent.key, + hasModifier: Boolean(shiftKey || metaKey || ctrlKey || altKey), preventDefault: () => event.preventDefault(), input: ctx.input, }); if (handled) return; } - const { shiftKey, metaKey, ctrlKey } = event.nativeEvent; - if (event.nativeEvent.key !== "Enter") return; if (!ctx.submitOnEnter) return; if (shiftKey) return; diff --git a/packages/app/src/composer/recall.test.ts b/packages/app/src/composer/recall.test.ts new file mode 100644 index 0000000000..a1c6b618fc --- /dev/null +++ b/packages/app/src/composer/recall.test.ts @@ -0,0 +1,109 @@ +import { describe, expect, it } from "vitest"; +import type { ComposerKeyPressEvent } from "@/composer/input/input"; +import { ComposerRecall } from "@/composer/recall"; + +const SENT = ["add tests", "fix the auth bug"]; + +function press( + key: string, + text: string, + options: { caret?: number; selectionEnd?: number; hasModifier?: boolean } = {}, +): ComposerKeyPressEvent { + const caret = options.caret ?? text.length; + return { + key, + hasModifier: options.hasModifier ?? false, + preventDefault: () => undefined, + input: { text, selection: { start: caret, end: options.selectionEnd ?? caret } }, + }; +} + +/** Drives recall the way the composer does: each result becomes the composer text, caret at the end. */ +function composerWithRecall(sent: readonly string[] = SENT) { + const recall = new ComposerRecall(); + let text = ""; + return { + recall, + get text() { + return text; + }, + type(next: string) { + text = next; + }, + press(key: string, options: { caret?: number; hasModifier?: boolean } = {}) { + const result = recall.handleKeyPress(press(key, text, options), () => sent); + if (result !== null) text = result; + return result; + }, + }; +} + +describe("ComposerRecall", () => { + it("walks back through sent messages and forward to an empty composer", () => { + const composer = composerWithRecall(); + + expect(composer.press("ArrowUp")).toBe("add tests"); + expect(composer.press("ArrowUp")).toBe("fix the auth bug"); + expect(composer.press("ArrowDown")).toBe("add tests"); + expect(composer.press("ArrowDown")).toBe(""); + expect(composer.recall.isShowing(composer.text)).toBe(false); + }); + + it("leaves the caret to the input past the oldest message", () => { + const composer = composerWithRecall(); + composer.press("ArrowUp"); + composer.press("ArrowUp"); + + expect(composer.press("ArrowUp")).toBeNull(); + expect(composer.text).toBe("fix the auth bug"); + }); + + it("only starts from an empty composer", () => { + const composer = composerWithRecall(); + composer.type("half written"); + + expect(composer.press("ArrowUp")).toBeNull(); + expect(composer.press("ArrowDown")).toBeNull(); + }); + + it("ignores Down from an empty composer and Up with no history", () => { + expect(composerWithRecall().press("ArrowDown")).toBeNull(); + expect(composerWithRecall([]).press("ArrowUp")).toBeNull(); + }); + + it("hands the arrows back to the caret once the recalled message is edited", () => { + const composer = composerWithRecall(); + composer.press("ArrowUp"); + composer.type("add tests for login"); + + expect(composer.recall.isShowing(composer.text)).toBe(false); + expect(composer.press("ArrowUp")).toBeNull(); + expect(composer.press("ArrowDown")).toBeNull(); + }); + + it("moves between lines of a multi-line message before changing message", () => { + const composer = composerWithRecall(["first line\nsecond line", "older"]); + composer.press("ArrowUp"); + + expect(composer.press("ArrowUp", { caret: "first line\nsec".length })).toBeNull(); + expect(composer.press("ArrowUp", { caret: 3 })).toBe("older"); + expect(composer.press("ArrowDown")).toBe("first line\nsecond line"); + expect(composer.press("ArrowDown", { caret: 3 })).toBeNull(); + expect(composer.press("ArrowDown")).toBe(""); + }); + + it("ignores modified arrows, other keys, and a selection", () => { + const composer = composerWithRecall(); + + expect(composer.press("ArrowUp", { hasModifier: true })).toBeNull(); + expect(composer.press("Enter")).toBeNull(); + composer.press("ArrowUp"); + const recall = composer.recall; + expect( + recall.handleKeyPress( + press("ArrowUp", "add tests", { caret: 0, selectionEnd: 3 }), + () => SENT, + ), + ).toBeNull(); + }); +}); diff --git a/packages/app/src/composer/recall.ts b/packages/app/src/composer/recall.ts new file mode 100644 index 0000000000..24984d39e1 --- /dev/null +++ b/packages/app/src/composer/recall.ts @@ -0,0 +1,68 @@ +import type { ComposerKeyPressEvent } from "@/composer/input/input"; + +interface RecalledMessage { + index: number; + text: string; +} + +/** + * Walks the messages already sent to an agent from an empty composer, like a + * shell's Up/Down history. A message stays recalled only while the composer + * still holds its exact text; the first edit hands the arrows back to the caret. + */ +export class ComposerRecall { + private recalled: RecalledMessage | null = null; + + /** True while the composer shows a recalled message the user has not edited. */ + isShowing(text: string): boolean { + return this.recalled !== null && this.recalled.text === text; + } + + /** + * Returns the text the composer should show for this key press, or null to + * leave the key to the input. `readSentMessages` is newest first and is only + * read for keys recall acts on. + */ + handleKeyPress( + event: ComposerKeyPressEvent, + readSentMessages: () => readonly string[], + ): string | null { + if (event.key !== "ArrowUp" && event.key !== "ArrowDown") return null; + if (event.hasModifier) return null; + const { text, selection } = event.input; + if (selection.start !== selection.end) return null; + + const recalled = this.isShowing(text) ? this.recalled : null; + if (!recalled) { + this.recalled = null; + if (event.key !== "ArrowUp" || text.length > 0) return null; + return this.show(readSentMessages(), 0); + } + + if (event.key === "ArrowUp") { + if (!isCaretOnFirstLine(text, selection.start)) return null; + return this.show(readSentMessages(), recalled.index + 1); + } + if (!isCaretOnLastLine(text, selection.start)) return null; + if (recalled.index === 0) { + this.recalled = null; + return ""; + } + return this.show(readSentMessages(), recalled.index - 1); + } + + private show(messages: readonly string[], index: number): string | null { + const text = messages[index]; + if (text === undefined) return null; + this.recalled = { index, text }; + return text; + } +} + +function isCaretOnFirstLine(text: string, caret: number): boolean { + return !text.slice(0, caret).includes("\n"); +} + +function isCaretOnLastLine(text: string, caret: number): boolean { + return !text.slice(caret).includes("\n"); +} diff --git a/packages/app/src/stores/session-store.test.ts b/packages/app/src/stores/session-store.test.ts index 86ea81afc5..fb38605220 100644 --- a/packages/app/src/stores/session-store.test.ts +++ b/packages/app/src/stores/session-store.test.ts @@ -5,6 +5,7 @@ import type { WorkspaceDescriptorPayload } from "@getpaseo/protocol/messages"; import { normalizeWorkspaceDescriptor, + selectAgentSentMessages, selectAgentTurnPresentation, selectAgentTimelineState, useSessionStore, @@ -235,6 +236,25 @@ describe("agent timeline state", () => { ).toEqual({ status: "synced", items: [], range: null, older: "none", newer: "none" }); }); + it("lists sent messages newest first, including the live head", () => { + initializeTestSession(); + const sent = (id: string, text: string) => ({ ...submittedMessage(id), text }); + useSessionStore.getState().applyAgentTimelineResponseState("test-server", "agent-1", { + items: [sent("m1", "fix the auth bug"), sent("m2", "add tests"), sent("m3", "add tests")], + head: [sent("m4", " "), sent("m5", "refactor the wrong module")], + range: { epoch: "epoch-1", startSeq: 1, endSeq: 5 }, + older: "none", + newer: false, + synchronized: true, + acknowledgedClientMessageIds: [], + }); + + expect( + selectAgentSentMessages(useSessionStore.getState().sessions["test-server"], "agent-1"), + ).toEqual(["refactor the wrong module", "add tests", "fix the auth bug"]); + expect(selectAgentSentMessages(undefined, "agent-1")).toEqual([]); + }); + it("preserves older availability when an applied response leaves it unchanged", () => { initializeTestSession(); const store = useSessionStore.getState(); diff --git a/packages/app/src/stores/session-store.ts b/packages/app/src/stores/session-store.ts index aed06eef11..911573762f 100644 --- a/packages/app/src/stores/session-store.ts +++ b/packages/app/src/stores/session-store.ts @@ -332,6 +332,26 @@ export function selectAgentTimelineState( return items.length > 0 ? { status: "painted", items } : { status: "cold" }; } +/** Text of the loaded user messages, newest first, with back-to-back repeats collapsed. */ +export function selectAgentSentMessages( + session: SessionState | undefined, + agentId: string, +): string[] { + if (!session) return []; + const items = [ + ...(session.agentStreamTail.get(agentId) ?? []), + ...(session.agentStreamHead.get(agentId) ?? []), + ]; + const messages: string[] = []; + for (let index = items.length - 1; index >= 0; index -= 1) { + const item = items[index]; + if (item.kind !== "user_message" || item.text.trim().length === 0) continue; + if (messages[messages.length - 1] === item.text) continue; + messages.push(item.text); + } + return messages; +} + export function selectAgentTurnPresentation( session: SessionState | undefined, agentId: string, From 6521739947b30a3d0de950c4186310703998e2fd Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Mon, 26 Oct 2026 11:22:07 +0700 Subject: [PATCH 008/173] fix(markdown): preserve inline code formatting and heading sizes (#7889) Scale inline code with the enclosing block using theme tokens, and preserve its size and font through bold and links. Use contextual package patches so clean installs reproduce the verified native source. --- .../e2e/mobile/markdown-formatting/README.md | 25 + .../e2e/mobile/markdown-formatting/native.tsx | 52 ++ packages/app/package.json | 2 +- .../src/components/markdown/renderer.test.ts | 15 + .../app/src/components/markdown/styles.ts | 2 +- ...own+1.2.0-nightly-20261014-766fc0e67.patch | 508 ++++++++++++++++-- 6 files changed, 557 insertions(+), 47 deletions(-) create mode 100644 packages/app/e2e/mobile/markdown-formatting/README.md create mode 100644 packages/app/e2e/mobile/markdown-formatting/native.tsx diff --git a/packages/app/e2e/mobile/markdown-formatting/README.md b/packages/app/e2e/mobile/markdown-formatting/README.md new file mode 100644 index 0000000000..c2ab0ddc65 --- /dev/null +++ b/packages/app/e2e/mobile/markdown-formatting/README.md @@ -0,0 +1,25 @@ +# Inline code formatting + +This fixture renders the production `MarkdownRenderer` with plain, bold, italic, +combined emphasis, strikethrough and linked code, plus bold code in headings, +lists and quotes. Toggle regular/compact text. Inline code uses the theme’s +code-to-body size ratio at every heading level; fenced code keeps the code-size +token. Bold and links preserve the resulting size. Check the glyphs, not the background height: native backgrounds use +line metrics. + +Use a development client rebuilt from this checkout. Follow the temporary entry +point and Metro workflow in [status-ring](../status-ring/README.md), importing +`MarkdownFormattingRegression` from `./e2e/mobile/markdown-formatting/native`. +Open the same Metro URL in a browser to compare web. Restore `index.ts` afterward. + +The package patch contains `InlineCodeFormattingTest`, which exercises actual +Android spans in Robolectric native graphics mode, covering draw and measurement, +span order, code inside paragraph/heading sizes, bold/italic composition, and +links preserving code and emphasized prose fonts. +It runs in the existing `test:android` CI job. To run only this regression locally, +from `packages/app/android` after Expo prebuild: + +```sh +./gradlew :react-native-enriched-markdown:testDebugUnitTest \ + --tests '*InlineCodeFormattingTest' --no-daemon --max-workers=2 +``` diff --git a/packages/app/e2e/mobile/markdown-formatting/native.tsx b/packages/app/e2e/mobile/markdown-formatting/native.tsx new file mode 100644 index 0000000000..d5d9a64aa0 --- /dev/null +++ b/packages/app/e2e/mobile/markdown-formatting/native.tsx @@ -0,0 +1,52 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { useCallback, useState } from "react"; +import { Button, ScrollView, Text } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import { GestureHandlerRootView } from "react-native-gesture-handler"; +import { MarkdownRenderer } from "@/components/markdown/renderer"; + +const styles = StyleSheet.create((theme) => ({ + root: { flex: 1 }, + scroll: { backgroundColor: theme.colors.surface0 }, + content: { padding: 32, paddingTop: 60 }, + title: { color: theme.colors.foreground }, +})); + +const queryClient = new QueryClient(); + +const source = [ + "Plain: `MMMMiiii`", + "Bold: **`MMMMiiii`**", + "Italic: *`MMMMiiii`*", + "Both: ***`MMMMiiii`***", + "Strike: ~~`MMMMiiii`~~", + "Link: [`MMMMiiii`](https://example.com)", + "# Heading **`MMMMiiii`**", + "## Heading *`MMMMiiii`*", + "### Heading [`MMMMiiii`](https://example.com)", + "#### Heading ~~`MMMMiiii`~~", + "##### Heading ***`MMMMiiii`***", + "###### Heading `MMMMiiii`", + "- List **`MMMMiiii`**", + "> Quote **`MMMMiiii`**", + "Normal **bold** and *italic* prose.", +].join("\n\n"); + +export default function MarkdownFormattingRegression() { + const [compact, setCompact] = useState(false); + const toggleCompact = useCallback(() => setCompact((value) => !value), []); + return ( + + + + Inline code formatting regression + diff --git a/packages/app/src/components/settings/row-density.browser.test.tsx b/packages/app/src/components/settings/row-density.browser.test.tsx new file mode 100644 index 0000000000..d2742e3172 --- /dev/null +++ b/packages/app/src/components/settings/row-density.browser.test.tsx @@ -0,0 +1,77 @@ +import React, { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, describe, expect, it } from "vitest"; +import { Button } from "@/components/ui/button"; +import { SettingsCard, SettingsCollapsibleRow, SettingsRow } from "@/components/settings"; + +let root: Root | null = null; +let container: HTMLDivElement | null = null; + +afterEach(() => { + act(() => root?.unmount()); + container?.remove(); + root = null; + container = null; +}); + +function mountRows() { + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + act(() => + root?.render( + + + + + + + + + + + , + ), + ); +} + +function element(testID: string): HTMLElement { + const found = document.querySelector(`[data-testid="${testID}"]`); + if (!(found instanceof HTMLElement)) throw new Error(`Nothing rendered as ${testID}`); + return found; +} + +function heightOf(testID: string): number { + return element(testID).getBoundingClientRect().height; +} + +function titleFontSize(rowTestID: string, label: string): number { + const title = [...element(rowTestID).querySelectorAll("div")].find( + (node) => node.textContent === label && node.children.length === 0, + ); + if (!title) throw new Error(`No title ${label}`); + return Number.parseFloat(getComputedStyle(title).fontSize); +} + +describe("settings row density", () => { + it("lines up nested rows with and without a button, tighter than card rows", () => { + mountRows(); + + expect(heightOf("nested-with-button")).toBe(heightOf("nested-without-button")); + expect(heightOf("nested-with-button")).toBeLessThan(heightOf("card-row")); + expect(heightOf("group-toggle")).toBeGreaterThan(heightOf("nested-without-button")); + }); + + it("sizes nested text and controls one step below card rows", () => { + mountRows(); + + expect(heightOf("nested-button")).toBeLessThan(heightOf("card-button")); + expect(titleFontSize("nested-with-button", "Nested with a button")).toBeLessThan( + titleFontSize("card-row", "Card row"), + ); + }); +}); diff --git a/packages/app/src/components/settings/row-density.tsx b/packages/app/src/components/settings/row-density.tsx new file mode 100644 index 0000000000..d4bcdce33e --- /dev/null +++ b/packages/app/src/components/settings/row-density.tsx @@ -0,0 +1,57 @@ +import { createContext, useContext, useMemo, type ReactNode } from "react"; +import type { StyleProp, TextStyle, ViewStyle } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import { CONTROL_HEIGHTS } from "@/components/ui/control-geometry"; +import type { ContainedControlSize } from "@/components/ui/control-size"; +import { settingsStyles } from "@/styles/settings"; + +// Rows revealed under a collapsible row belong to it, so they sit one step smaller than the rows +// of the card: tighter padding, smaller text, smaller controls. The container decides; a row +// never knows on its own that it is nested. +const NestedRowsContext = createContext(false); + +export function NestedSettingsRows({ children }: { children: ReactNode }) { + return {children}; +} + +export interface SettingsRowLayout { + row: StyleProp; + title: StyleProp; + hint: StyleProp; + /** The size of the controls in the row's trailing slot. */ + controlSize: ContainedControlSize; +} + +/** How a row lays out where it is rendered: in a card, or nested under a collapsible row. */ +export function useSettingsRowLayout(): SettingsRowLayout { + const nested = useContext(NestedRowsContext); + return useMemo( + () => + nested + ? { + row: [settingsStyles.row, styles.nestedRow], + title: [settingsStyles.rowTitle, styles.nestedText], + hint: [settingsStyles.rowHint, styles.nestedText], + controlSize: "xs", + } + : { + row: settingsStyles.row, + title: settingsStyles.rowTitle, + hint: settingsStyles.rowHint, + controlSize: "sm", + }, + [nested], + ); +} + +const styles = StyleSheet.create((theme) => ({ + // Every nested row is as tall as one holding an `xs` control, so rows with and without a + // trailing button line up. + nestedRow: { + paddingVertical: theme.spacing[2], + minHeight: CONTROL_HEIGHTS.tight + theme.spacing[2] * 2, + }, + nestedText: { + fontSize: theme.fontSize.sm, + }, +})); diff --git a/packages/app/src/components/settings/row-header.tsx b/packages/app/src/components/settings/row-header.tsx new file mode 100644 index 0000000000..9c3c415c34 --- /dev/null +++ b/packages/app/src/components/settings/row-header.tsx @@ -0,0 +1,113 @@ +import { ChevronRight } from "lucide-react-native"; +import { useCallback, useMemo } from "react"; +import { Text, View, type AccessibilityState, type PressableStateCallbackType } from "react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { mutedIconColorMapping } from "@/components/ui/icon-color"; +import { PressHighlight } from "@/components/ui/press-highlight"; +import { settingsStyles } from "@/styles/settings"; +import { ICON_SIZE, type Theme } from "@/styles/theme"; +import { useSettingsRowLayout } from "./row-density"; + +const ThemedChevron = withUnistyles(ChevronRight); +const hoveredIconColorMapping = (theme: Theme) => ({ color: theme.colors.foreground }); + +type HoverState = PressableStateCallbackType & { hovered?: boolean }; + +export interface SettingsRowHeaderProps { + label: string; + /** A short status shown before the chevron. */ + summary?: string; + onPress: () => void; + disabled?: boolean; + /** Turns the chevron down, for a row whose children are revealed in place. */ + expanded?: boolean; + accessibilityState?: AccessibilityState; + /** Props React Native Web does not derive from `accessibilityState`, such as `aria-expanded`. */ + webAccessibilityProps?: Record | null; + testID?: string; +} + +/** + * The pressable line shared by settings rows that lead somewhere: a label, an optional summary and + * a trailing chevron. A collapsible row turns the chevron down; a row that opens a sheet keeps it + * pointing right. + */ +export function SettingsRowHeader({ + label, + summary, + onPress, + disabled, + expanded = false, + accessibilityState, + webAccessibilityProps, + testID, +}: SettingsRowHeaderProps) { + const layout = useSettingsRowLayout(); + const rowStyle = useCallback( + ({ hovered, pressed }: HoverState) => [ + layout.row, + !disabled && hovered && styles.hovered, + !disabled && pressed && styles.pressed, + ], + [disabled, layout], + ); + const chevronStyle = useMemo( + () => [styles.chevron, expanded && styles.chevronExpanded], + [expanded], + ); + return ( + + {({ hovered }: HoverState) => ( + <> + + {label} + + {summary ? ( + + {summary} + + ) : null} + {disabled ? null : ( + + + + )} + + )} + + ); +} + +const styles = StyleSheet.create((theme) => ({ + summary: { + flexShrink: 1, + color: theme.colors.foregroundMuted, + fontSize: theme.fontSize.sm, + marginRight: theme.spacing[2], + }, + hovered: { + backgroundColor: theme.colors.surface2, + }, + pressed: { + backgroundColor: theme.colors.surface3, + }, + // Optical: the chevron's ink sits about 4px inside its box whether it points right or down; this + // puts the ink on the card's trailing rail, where the switch and the reports' refresh buttons end. + chevron: { marginRight: -theme.spacing[1] }, + chevronExpanded: { + transform: [{ rotate: "90deg" }], + }, +})); diff --git a/packages/app/src/components/ui/button.tsx b/packages/app/src/components/ui/button.tsx index 707ce60648..abcaf240d6 100644 --- a/packages/app/src/components/ui/button.tsx +++ b/packages/app/src/components/ui/button.tsx @@ -1,4 +1,5 @@ import { LoadingSpinner } from "@/components/ui/loading-spinner"; +import { useContainedControlSize } from "@/components/ui/control-size"; import { default as React, useCallback, @@ -162,7 +163,7 @@ const styles = StyleSheet.create((theme) => { export function Button({ children, variant = "secondary", - size = "md", + size: sizeProp, leftIcon, trailing, style, @@ -185,6 +186,8 @@ export function Button({ } >) { const [hovered, setHovered] = useState(false); + const containedSize = useContainedControlSize(); + const size = sizeProp ?? containedSize ?? "md"; const isDisabled = disabled || loading; let variantStyle: ViewStyle; diff --git a/packages/app/src/components/ui/control-geometry.test.ts b/packages/app/src/components/ui/control-geometry.test.ts index 0b0675596f..3544d9f940 100644 --- a/packages/app/src/components/ui/control-geometry.test.ts +++ b/packages/app/src/components/ui/control-geometry.test.ts @@ -81,6 +81,8 @@ describe("control geometry", () => { it("keeps field text sizing tied to control size", () => { const geometry = createControlGeometry(theme); + expect(geometry.fieldTextXs.fontSize).toBe(12); + expect(geometry.fieldTextXs.lineHeight).toBe(17); expect(geometry.fieldTextSm.fontSize).toBe(14); expect(geometry.fieldTextSm.lineHeight).toBe(20); expect(geometry.fieldTextMd.fontSize).toBe(14); @@ -95,6 +97,13 @@ describe("control geometry", () => { const geometry = createControlGeometry(theme); const borderWidth = theme.borderWidth[1]; + expect(geometry.fieldControlXs.minHeight).toBe(28); + expect( + geometry.fieldTextXs.lineHeight + + geometry.fieldControlXs.paddingVertical * 2 + + borderWidth * 2, + ).toBe(geometry.fieldControlXs.minHeight); + expect(geometry.fieldControlSm.minHeight).toBe(32); expect(geometry.fieldControlSm.paddingVertical).toBe(5); expect( diff --git a/packages/app/src/components/ui/control-geometry.ts b/packages/app/src/components/ui/control-geometry.ts index d56200887e..0a41f80039 100644 --- a/packages/app/src/components/ui/control-geometry.ts +++ b/packages/app/src/components/ui/control-geometry.ts @@ -2,7 +2,7 @@ import type { StyleProp, ViewStyle } from "react-native"; import { ICON_SIZE, type Theme } from "@/styles/theme"; export type ButtonControlSize = "xs" | "sm" | "md" | "lg"; -export type FieldControlSize = "sm" | "md"; +export type FieldControlSize = "xs" | "sm" | "md"; export type SegmentedControlSize = "xs" | "sm" | "md"; export type ControlInteractionPhase = "rest" | "hover" | "active"; @@ -188,8 +188,19 @@ export function resolveControlInteractionStyles( export function createControlGeometry(theme: Theme) { const controlBorderWidth = theme.borderWidth[1]; + const fieldTextXsLineHeight = fieldLineHeight(theme.fontSize.sm); const fieldTextSmLineHeight = fieldLineHeight(theme.fontSize.base); const fieldTextMdLineHeight = fieldLineHeight(theme.fontSize.base); + const fieldControlXs = { + minHeight: CONTROL_HEIGHTS.tight, + paddingHorizontal: theme.spacing[2], + paddingVertical: fieldVerticalPadding( + CONTROL_HEIGHTS.tight, + fieldTextXsLineHeight, + controlBorderWidth, + ), + borderRadius: theme.borderRadius.md, + }; const fieldControlSm = { minHeight: CONTROL_HEIGHTS.compact, paddingHorizontal: theme.spacing[3], @@ -210,6 +221,10 @@ export function createControlGeometry(theme: Theme) { ), borderRadius: theme.borderRadius.lg, }; + const fieldTextXs = { + fontSize: theme.fontSize.sm, + lineHeight: fieldTextXsLineHeight, + }; const fieldTextSm = { fontSize: theme.fontSize.base, lineHeight: fieldTextSmLineHeight, @@ -252,6 +267,10 @@ export function createControlGeometry(theme: Theme) { fontSize: theme.fontSize.sm, }, alert, + formTextInputXs: { + ...fieldControlXs, + ...fieldTextXs, + }, formTextInputSm: { ...fieldControlSm, ...fieldTextSm, @@ -264,8 +283,10 @@ export function createControlGeometry(theme: Theme) { ...fieldControlMd, ...fieldTextMd, }, + fieldControlXs, fieldControlSm, fieldControlMd, + fieldTextXs, fieldTextSm, fieldTextMd, controlRest: { diff --git a/packages/app/src/components/ui/control-size.tsx b/packages/app/src/components/ui/control-size.tsx new file mode 100644 index 0000000000..c6bcbbea78 --- /dev/null +++ b/packages/app/src/components/ui/control-size.tsx @@ -0,0 +1,23 @@ +import { createContext, useContext, type ReactNode } from "react"; + +/** The control sizes a container can ask of the controls placed in it. */ +export type ContainedControlSize = "xs" | "sm"; + +// A row decides how big its controls are, so a button or field placed in it needs no size of +// its own. A size passed to the control still wins. +const ControlSizeContext = createContext(null); + +export function ControlSizeProvider({ + size, + children, +}: { + size: ContainedControlSize; + children: ReactNode; +}) { + return {children}; +} + +/** The size the surrounding container asks for, or null outside one. */ +export function useContainedControlSize(): ContainedControlSize | null { + return useContext(ControlSizeContext); +} diff --git a/packages/app/src/components/ui/dropdown-trigger.tsx b/packages/app/src/components/ui/dropdown-trigger.tsx index 2fc1eb26ac..a276e40652 100644 --- a/packages/app/src/components/ui/dropdown-trigger.tsx +++ b/packages/app/src/components/ui/dropdown-trigger.tsx @@ -9,6 +9,7 @@ import { } from "@/components/ui/control-geometry"; import type { Theme } from "@/styles/theme"; import { DropdownMenuTrigger, type DropdownMenuTriggerProps } from "@/components/ui/dropdown-menu"; +import { useContainedControlSize } from "@/components/ui/control-size"; const ThemedChevronDown = withUnistyles(ChevronDown); @@ -32,10 +33,12 @@ interface DropdownTriggerProps extends Omit; +const FIELD_TEXT = { xs: "inputXs", sm: "inputSm", md: "inputMd" } as const satisfies Record< + FieldControlSize, + string +>; interface FieldProps { label: string; @@ -159,11 +169,13 @@ function assignTextInputRef( } export const FormTextInput = forwardRef( - function FormTextInput({ size = "md", style, onFocus, onBlur, editable, ...props }, ref) { + function FormTextInput({ size: sizeProp, style, onFocus, onBlur, editable, ...props }, ref) { const [focused, setFocused] = useState(false); + const containedSize = useContainedControlSize(); + const size = sizeProp ?? containedSize ?? "md"; const isDisabled = editable === false; - const chromeSizeStyle = size === "sm" ? formInputStyles.chromeSm : formInputStyles.chromeMd; - const inputSizeStyle = size === "sm" ? formInputStyles.inputSm : formInputStyles.inputMd; + const chromeSizeStyle = formInputStyles[FIELD_CHROME[size]]; + const inputSizeStyle = formInputStyles[FIELD_TEXT[size]]; const splitStyle = useMemo(() => splitFormTextInputStyle(style), [style]); const setInputRef = useCallback( (node: EditingTextInputHandle | null) => { @@ -262,6 +274,9 @@ const formInputStyles = StyleSheet.create((theme) => { chrome: { backgroundColor: theme.colors.surface2, }, + chromeXs: { + ...geometry.fieldControlXs, + }, chromeSm: { ...geometry.fieldControlSm, }, @@ -289,6 +304,9 @@ const formInputStyles = StyleSheet.create((theme) => { outlineColor: "transparent", outlineWidth: 0, }, + inputXs: { + ...geometry.fieldTextXs, + }, inputSm: { ...geometry.fieldTextSm, }, diff --git a/packages/app/src/components/ui/icon-color.ts b/packages/app/src/components/ui/icon-color.ts index 1093064423..f7891dabc4 100644 --- a/packages/app/src/components/ui/icon-color.ts +++ b/packages/app/src/components/ui/icon-color.ts @@ -1,5 +1,9 @@ import type { Theme } from "@/styles/theme"; +export const foregroundIconColorMapping = (theme: Theme) => ({ + color: theme.colors.foreground, +}); + export const mutedIconColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted, }); diff --git a/packages/app/src/components/ui/segmented-control.tsx b/packages/app/src/components/ui/segmented-control.tsx index e0bbdf3f7b..d828c26c4d 100644 --- a/packages/app/src/components/ui/segmented-control.tsx +++ b/packages/app/src/components/ui/segmented-control.tsx @@ -7,6 +7,7 @@ import { segmentedIconSize, type SegmentedControlSize, } from "@/components/ui/control-geometry"; +import { useContainedControlSize } from "@/components/ui/control-size"; import type { Theme } from "@/styles/theme"; type SegmentedControlIconRenderer = (props: { color: string; size: number }) => ReactNode; @@ -48,11 +49,13 @@ export function SegmentedControl({ options, value, onValueChange, - size = "md", + size: sizeProp, hideLabels = false, style, testID, }: SegmentedControlProps) { + const containedSize = useContainedControlSize(); + const size = sizeProp ?? containedSize ?? "md"; const sizeStyles = { xs: { container: styles.containerXs, segment: styles.segmentXs, label: styles.labelXs }, sm: { container: styles.containerSm, segment: styles.segmentSm, label: styles.labelSm }, diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index da49bcec67..108fad41d4 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -2260,6 +2260,7 @@ export const ar: TranslationResources = { connections: "اتصالات", agents: "Agents", metadata: "البيانات الوصفية", + voice: "الصوت", workspaces: "Workspaces", providers: "مقدمي الخدمات", usage: "الاستخدام", @@ -2282,6 +2283,69 @@ export const ar: TranslationResources = { docs: "الوثائق", saveError: "تعذر تحديث إنشاء البيانات الوصفية", }, + voice: { + offline: "اتصل بهذا المضيف لضبط الصوت.", + updateHost: "حدّث المضيف لضبط الصوت.", + saveError: "تعذّر تحديث إعدادات الصوت", + provider: "المزوّد", + providers: { + local: "محلي", + openai: "OpenAI", + }, + voice: "الصوت", + save: "حفظ", + retry: "إعادة المحاولة", + cancel: "إلغاء", + model: "النموذج", + language: "اللغة", + languagePlaceholder: "اكتشاف تلقائي", + setBy: "محدد بواسطة {{name}}", + unknownProvider: "حدّث التطبيق لإعداد {{provider}}", + sites: { + dictationStt: "تحويل الكلام إلى نص", + voiceModeStt: "الاستماع", + voiceModeTts: "التحدث", + }, + dictation: { + title: "الإملاء", + enabled: "الإملاء", + enabledHint: "تحدّث في مربع الرسالة بدلًا من الكتابة", + }, + voiceMode: { + title: "وضع الصوت", + info: "يحوّل وضع الصوت كلامك إلى نص ويقرأ ردود الوكيل بصوت عالٍ.", + enabled: "وضع الصوت", + enabledHint: "تحدّث مع وكلائك دون استخدام يديك", + }, + openai: { + apiKey: "مفتاح API", + apiKeyHint: "يُحفظ على المضيف ولا يُعرض مرة أخرى.", + keyPlaceholder: "sk-...", + savedKeyPlaceholder: "محفوظ", + missingKey: "مفتاح API مفقود", + baseUrl: "عنوان URL الأساسي", + baseUrlHint: "للخوادم المتوافقة مع OpenAI. اتركه فارغًا لاستخدام OpenAI.", + }, + models: { + loading: "جارٍ تحميل النماذج...", + loadError: "تعذّر تحميل النماذج المحلية", + none: "لا توجد نماذج متاحة", + downloaded: "منزّل", + inUse: "قيد الاستخدام", + recommended: "موصى به", + download: "تنزيل", + downloadAction: "تنزيل {{label}}", + downloading: "جارٍ التنزيل...", + downloadingPercent: "جارٍ التنزيل {{percent}}%", + extracting: "جارٍ الاستخراج...", + delete: "حذف", + deleteAction: "حذف {{label}}", + deleteTitle: "حذف {{label}}؟", + deleteMessage: "سيؤدي هذا إلى تحرير {{size}}. يمكنك تنزيله مرة أخرى لاحقًا.", + languages: "لغات {{label}}", + moreLanguages: "{{languages}} و{{count}} أخرى", + }, + }, general: { title: "عام", sending: "الإرسال", diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index 57768f0ac0..16bddd9cf9 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -2287,6 +2287,7 @@ export const en = { connections: "Connections", agents: "Agents", metadata: "Metadata", + voice: "Voice", workspaces: "Workspaces", providers: "Providers", usage: "Usage", @@ -2371,6 +2372,69 @@ export const en = { docs: "Docs", saveError: "Unable to update metadata generation", }, + voice: { + offline: "Connect to this host to configure voice.", + updateHost: "Update the host to configure voice.", + saveError: "Unable to update voice settings", + provider: "Provider", + providers: { + local: "Local", + openai: "OpenAI", + }, + voice: "Voice", + save: "Save", + retry: "Retry", + cancel: "Cancel", + model: "Model", + language: "Language", + languagePlaceholder: "Auto-detect", + setBy: "Set by {{name}}", + unknownProvider: "Update the app to configure {{provider}}", + sites: { + dictationStt: "Speech-to-text", + voiceModeStt: "Listening", + voiceModeTts: "Speaking", + }, + dictation: { + title: "Dictation", + enabled: "Dictation", + enabledHint: "Speak into the message box instead of typing", + }, + voiceMode: { + title: "Voice mode", + info: "Voice mode transcribes what you say and reads agent replies aloud.", + enabled: "Voice mode", + enabledHint: "Talk with your agents hands-free", + }, + openai: { + apiKey: "API key", + apiKeyHint: "Saved on the host and never shown again.", + keyPlaceholder: "sk-...", + savedKeyPlaceholder: "Saved", + missingKey: "API key missing", + baseUrl: "Base URL", + baseUrlHint: "For OpenAI-compatible servers. Leave empty to use OpenAI.", + }, + models: { + loading: "Loading models...", + loadError: "Couldn't load local models", + none: "No models available", + downloaded: "Downloaded", + inUse: "In use", + recommended: "Recommended", + download: "Download", + downloadAction: "Download {{label}}", + downloading: "Downloading...", + downloadingPercent: "Downloading {{percent}}%", + extracting: "Extracting...", + delete: "Delete", + deleteAction: "Delete {{label}}", + deleteTitle: "Delete {{label}}?", + deleteMessage: "This frees {{size}}. You can download it again later.", + languages: "{{label}} languages", + moreLanguages: "{{languages}} and {{count}} more", + }, + }, general: { title: "General", sending: "Sending", diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index 51839eaf16..2226583781 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -2272,6 +2272,7 @@ export const es: TranslationResources = { connections: "Conexiones", agents: "Agents", metadata: "Metadatos", + voice: "Voz", workspaces: "Workspaces", providers: "Proveedores", usage: "Uso", @@ -2294,6 +2295,69 @@ export const es: TranslationResources = { docs: "Documentación", saveError: "No se pudo actualizar la generación de metadatos", }, + voice: { + offline: "Conéctate a este host para configurar la voz.", + updateHost: "Actualiza el host para configurar la voz.", + saveError: "No se pudo actualizar la configuración de voz", + provider: "Proveedor", + providers: { + local: "Local", + openai: "OpenAI", + }, + voice: "Voz", + save: "Guardar", + retry: "Reintentar", + cancel: "Cancelar", + model: "Modelo", + language: "Idioma", + languagePlaceholder: "Detección automática", + setBy: "Definido por {{name}}", + unknownProvider: "Actualiza la app para configurar {{provider}}", + sites: { + dictationStt: "Voz a texto", + voiceModeStt: "Escucha", + voiceModeTts: "Habla", + }, + dictation: { + title: "Dictado", + enabled: "Dictado", + enabledHint: "Habla en el cuadro de mensaje en lugar de escribir", + }, + voiceMode: { + title: "Modo de voz", + info: "El modo de voz transcribe lo que dices y lee en voz alta las respuestas del agente.", + enabled: "Modo de voz", + enabledHint: "Habla con tus agentes sin usar las manos", + }, + openai: { + apiKey: "Clave de API", + apiKeyHint: "Se guarda en el host y no se vuelve a mostrar.", + keyPlaceholder: "sk-...", + savedKeyPlaceholder: "Guardada", + missingKey: "Falta la clave de API", + baseUrl: "URL base", + baseUrlHint: "Para servidores compatibles con OpenAI. Déjala vacía para usar OpenAI.", + }, + models: { + loading: "Cargando modelos...", + loadError: "No se pudieron cargar los modelos locales", + none: "No hay modelos disponibles", + downloaded: "Descargado", + inUse: "En uso", + recommended: "Recomendado", + download: "Descargar", + downloadAction: "Descargar {{label}}", + downloading: "Descargando...", + downloadingPercent: "Descargando {{percent}} %", + extracting: "Extrayendo...", + delete: "Eliminar", + deleteAction: "Eliminar {{label}}", + deleteTitle: "¿Eliminar {{label}}?", + deleteMessage: "Esto libera {{size}}. Puedes volver a descargarlo más tarde.", + languages: "Idiomas de {{label}}", + moreLanguages: "{{languages}} y {{count}} más", + }, + }, general: { title: "General", sending: "Envío", diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index 4f7c9be2aa..65d72d405b 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -2272,6 +2272,7 @@ export const fr: TranslationResources = { connections: "Connexions", agents: "Agents", metadata: "Métadonnées", + voice: "Voix", workspaces: "Espaces de travail", providers: "Fournisseurs", usage: "Utilisation", @@ -2294,6 +2295,69 @@ export const fr: TranslationResources = { docs: "Documentation", saveError: "Impossible de mettre à jour la génération de métadonnées", }, + voice: { + offline: "Connectez-vous à cet hôte pour configurer la voix.", + updateHost: "Mettez à jour l'hôte pour configurer la voix.", + saveError: "Impossible de mettre à jour les réglages vocaux", + provider: "Fournisseur", + providers: { + local: "Local", + openai: "OpenAI", + }, + voice: "Voix", + save: "Enregistrer", + retry: "Réessayer", + cancel: "Annuler", + model: "Modèle", + language: "Langue", + languagePlaceholder: "Détection automatique", + setBy: "Défini par {{name}}", + unknownProvider: "Mettez à jour l'app pour configurer {{provider}}", + sites: { + dictationStt: "Transcription", + voiceModeStt: "Écoute", + voiceModeTts: "Parole", + }, + dictation: { + title: "Dictée", + enabled: "Dictée", + enabledHint: "Parlez dans la zone de message au lieu de taper", + }, + voiceMode: { + title: "Mode vocal", + info: "Le mode vocal transcrit ce que vous dites et lit à voix haute les réponses de l'agent.", + enabled: "Mode vocal", + enabledHint: "Parlez à vos agents sans les mains", + }, + openai: { + apiKey: "Clé d'API", + apiKeyHint: "Enregistrée sur l'hôte, jamais réaffichée.", + keyPlaceholder: "sk-...", + savedKeyPlaceholder: "Enregistrée", + missingKey: "Clé d'API manquante", + baseUrl: "URL de base", + baseUrlHint: "Pour les serveurs compatibles OpenAI. Laissez vide pour utiliser OpenAI.", + }, + models: { + loading: "Chargement des modèles...", + loadError: "Impossible de charger les modèles locaux", + none: "Aucun modèle disponible", + downloaded: "Téléchargé", + inUse: "Utilisé", + recommended: "Recommandé", + download: "Télécharger", + downloadAction: "Télécharger {{label}}", + downloading: "Téléchargement...", + downloadingPercent: "Téléchargement {{percent}} %", + extracting: "Extraction...", + delete: "Supprimer", + deleteAction: "Supprimer {{label}}", + deleteTitle: "Supprimer {{label}} ?", + deleteMessage: "Cela libère {{size}}. Vous pourrez le retélécharger plus tard.", + languages: "Langues de {{label}}", + moreLanguages: "{{languages}} et {{count}} autres", + }, + }, general: { title: "Général", sending: "Envoi", diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index c0f22ffde5..5829bf4fa3 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -2245,6 +2245,7 @@ export const ja: TranslationResources = { connections: "接続", agents: "エージェント", metadata: "メタデータ", + voice: "音声", workspaces: "ワークスペース", providers: "プロバイダー", usage: "使用状況", @@ -2267,6 +2268,69 @@ export const ja: TranslationResources = { docs: "ドキュメント", saveError: "メタデータ生成を更新できません", }, + voice: { + offline: "音声を設定するには、このホストに接続してください。", + updateHost: "音声を設定するには、ホストを更新してください。", + saveError: "音声設定を更新できませんでした", + provider: "プロバイダー", + providers: { + local: "ローカル", + openai: "OpenAI", + }, + voice: "ボイス", + save: "保存", + retry: "再試行", + cancel: "キャンセル", + model: "モデル", + language: "言語", + languagePlaceholder: "自動検出", + setBy: "{{name}} で設定", + unknownProvider: "{{provider}} を設定するにはアプリを更新してください", + sites: { + dictationStt: "音声入力", + voiceModeStt: "聞き取り", + voiceModeTts: "読み上げ", + }, + dictation: { + title: "音声入力", + enabled: "音声入力", + enabledHint: "入力する代わりにメッセージ欄に話しかけます", + }, + voiceMode: { + title: "ボイスモード", + info: "ボイスモードは話した内容を文字起こしし、エージェントの返答を読み上げます。", + enabled: "ボイスモード", + enabledHint: "ハンズフリーでエージェントと会話します", + }, + openai: { + apiKey: "API キー", + apiKeyHint: "ホストに保存され、再表示されません。", + keyPlaceholder: "sk-...", + savedKeyPlaceholder: "保存済み", + missingKey: "API キーがありません", + baseUrl: "ベース URL", + baseUrlHint: "OpenAI 互換サーバー用です。OpenAI を使う場合は空欄のままにします。", + }, + models: { + loading: "モデルを読み込み中...", + loadError: "ローカルモデルを読み込めませんでした", + none: "利用できるモデルがありません", + downloaded: "ダウンロード済み", + inUse: "使用中", + recommended: "おすすめ", + download: "ダウンロード", + downloadAction: "{{label}} をダウンロード", + downloading: "ダウンロード中...", + downloadingPercent: "ダウンロード中 {{percent}}%", + extracting: "展開中...", + delete: "削除", + deleteAction: "{{label}} を削除", + deleteTitle: "{{label}} を削除しますか?", + deleteMessage: "{{size}} が解放されます。後で再ダウンロードできます。", + languages: "{{label}} の対応言語", + moreLanguages: "{{languages}} ほか {{count}} 言語", + }, + }, general: { title: "一般", sending: "送信", diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index df571aae4d..36a27fc84e 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -2234,6 +2234,7 @@ export const ko: TranslationResources = { connections: "연결", agents: "에이전트", metadata: "메타데이터", + voice: "음성", workspaces: "워크스페이스", providers: "프로바이더", usage: "사용량", @@ -2256,6 +2257,69 @@ export const ko: TranslationResources = { docs: "문서", saveError: "메타데이터 생성을 업데이트할 수 없습니다", }, + voice: { + offline: "음성을 설정하려면 이 호스트에 연결하세요.", + updateHost: "음성을 설정하려면 호스트를 업데이트하세요.", + saveError: "음성 설정을 업데이트할 수 없습니다", + provider: "제공자", + providers: { + local: "로컬", + openai: "OpenAI", + }, + voice: "목소리", + save: "저장", + retry: "다시 시도", + cancel: "취소", + model: "모델", + language: "언어", + languagePlaceholder: "자동 감지", + setBy: "{{name}}에서 설정됨", + unknownProvider: "{{provider}}을(를) 설정하려면 앱을 업데이트하세요", + sites: { + dictationStt: "음성 텍스트 변환", + voiceModeStt: "듣기", + voiceModeTts: "말하기", + }, + dictation: { + title: "받아쓰기", + enabled: "받아쓰기", + enabledHint: "입력하는 대신 메시지 상자에 말하세요", + }, + voiceMode: { + title: "음성 모드", + info: "음성 모드는 말한 내용을 텍스트로 옮기고 에이전트의 답변을 소리 내어 읽어 줍니다.", + enabled: "음성 모드", + enabledHint: "손을 쓰지 않고 에이전트와 대화하세요", + }, + openai: { + apiKey: "API 키", + apiKeyHint: "호스트에 저장되며 다시 표시되지 않습니다.", + keyPlaceholder: "sk-...", + savedKeyPlaceholder: "저장됨", + missingKey: "API 키 없음", + baseUrl: "기본 URL", + baseUrlHint: "OpenAI 호환 서버용입니다. OpenAI를 사용하려면 비워 두세요.", + }, + models: { + loading: "모델을 불러오는 중...", + loadError: "로컬 모델을 불러올 수 없습니다", + none: "사용 가능한 모델 없음", + downloaded: "다운로드됨", + inUse: "사용 중", + recommended: "추천", + download: "다운로드", + downloadAction: "{{label}} 다운로드", + downloading: "다운로드 중...", + downloadingPercent: "다운로드 중 {{percent}}%", + extracting: "압축 해제 중...", + delete: "삭제", + deleteAction: "{{label}} 삭제", + deleteTitle: "{{label}}을(를) 삭제할까요?", + deleteMessage: "{{size}}가 확보됩니다. 나중에 다시 다운로드할 수 있습니다.", + languages: "{{label}} 지원 언어", + moreLanguages: "{{languages}} 외 {{count}}개", + }, + }, general: { title: "일반", sending: "전송", diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index 6ba6ec46bb..5a83b4345c 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -2257,6 +2257,7 @@ export const ptBR: TranslationResources = { connections: "Conexões", agents: "Agentes", metadata: "Metadados", + voice: "Voz", workspaces: "Workspaces", providers: "Provedores", usage: "Uso", @@ -2279,6 +2280,69 @@ export const ptBR: TranslationResources = { docs: "Documentação", saveError: "Não foi possível atualizar a geração de metadados", }, + voice: { + offline: "Conecte-se a este host para configurar a voz.", + updateHost: "Atualize o host para configurar a voz.", + saveError: "Não foi possível atualizar as configurações de voz", + provider: "Provedor", + providers: { + local: "Local", + openai: "OpenAI", + }, + voice: "Voz", + save: "Salvar", + retry: "Tentar novamente", + cancel: "Cancelar", + model: "Modelo", + language: "Idioma", + languagePlaceholder: "Detecção automática", + setBy: "Definido por {{name}}", + unknownProvider: "Atualize o app para configurar {{provider}}", + sites: { + dictationStt: "Fala para texto", + voiceModeStt: "Escuta", + voiceModeTts: "Fala", + }, + dictation: { + title: "Ditado", + enabled: "Ditado", + enabledHint: "Fale na caixa de mensagem em vez de digitar", + }, + voiceMode: { + title: "Modo de voz", + info: "O modo de voz transcreve o que você diz e lê em voz alta as respostas do agente.", + enabled: "Modo de voz", + enabledHint: "Converse com seus agentes sem usar as mãos", + }, + openai: { + apiKey: "Chave de API", + apiKeyHint: "Salva no host e nunca mostrada novamente.", + keyPlaceholder: "sk-...", + savedKeyPlaceholder: "Salva", + missingKey: "Chave de API ausente", + baseUrl: "URL base", + baseUrlHint: "Para servidores compatíveis com a OpenAI. Deixe vazio para usar a OpenAI.", + }, + models: { + loading: "Carregando modelos...", + loadError: "Não foi possível carregar os modelos locais", + none: "Nenhum modelo disponível", + downloaded: "Baixado", + inUse: "Em uso", + recommended: "Recomendado", + download: "Baixar", + downloadAction: "Baixar {{label}}", + downloading: "Baixando...", + downloadingPercent: "Baixando {{percent}}%", + extracting: "Extraindo...", + delete: "Excluir", + deleteAction: "Excluir {{label}}", + deleteTitle: "Excluir {{label}}?", + deleteMessage: "Isso libera {{size}}. Você pode baixá-lo de novo depois.", + languages: "Idiomas do {{label}}", + moreLanguages: "{{languages}} e mais {{count}}", + }, + }, general: { title: "Geral", sending: "Envio", diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index f8f9969bf9..135d5fe2f9 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -2257,6 +2257,7 @@ export const ru: TranslationResources = { connections: "Подключения", agents: "Агенты", metadata: "Метаданные", + voice: "Голос", workspaces: "Рабочие пространства", providers: "Провайдеры", usage: "Использование", @@ -2280,6 +2281,70 @@ export const ru: TranslationResources = { docs: "Документация", saveError: "Не удалось обновить настройки генерации метаданных", }, + voice: { + offline: "Подключитесь к этому хосту, чтобы настроить голос.", + updateHost: "Обновите хост, чтобы настроить голос.", + saveError: "Не удалось обновить голосовые настройки", + provider: "Провайдер", + providers: { + local: "Локально", + openai: "OpenAI", + }, + voice: "Голос", + save: "Сохранить", + retry: "Повторить", + cancel: "Отмена", + model: "Модель", + language: "Язык", + languagePlaceholder: "Автоопределение", + setBy: "Задано через {{name}}", + unknownProvider: "Обновите приложение, чтобы настроить {{provider}}", + sites: { + dictationStt: "Распознавание речи", + voiceModeStt: "Прослушивание", + voiceModeTts: "Озвучивание", + }, + dictation: { + title: "Диктовка", + enabled: "Диктовка", + enabledHint: "Говорите в поле сообщения вместо набора текста", + }, + voiceMode: { + title: "Голосовой режим", + info: "Голосовой режим расшифровывает вашу речь и зачитывает ответы агента вслух.", + enabled: "Голосовой режим", + enabledHint: "Общайтесь с агентами без рук", + }, + openai: { + apiKey: "API-ключ", + apiKeyHint: "Хранится на хосте и больше не показывается.", + keyPlaceholder: "sk-...", + savedKeyPlaceholder: "Сохранён", + missingKey: "Нет API-ключа", + baseUrl: "Базовый URL", + baseUrlHint: + "Для серверов, совместимых с OpenAI. Оставьте пустым, чтобы использовать OpenAI.", + }, + models: { + loading: "Загрузка моделей...", + loadError: "Не удалось загрузить локальные модели", + none: "Нет доступных моделей", + downloaded: "Скачана", + inUse: "Используется", + recommended: "Рекомендуется", + download: "Скачать", + downloadAction: "Скачать {{label}}", + downloading: "Скачивание...", + downloadingPercent: "Скачивание {{percent}}%", + extracting: "Распаковка...", + delete: "Удалить", + deleteAction: "Удалить {{label}}", + deleteTitle: "Удалить {{label}}?", + deleteMessage: "Освободится {{size}}. Позже её можно скачать снова.", + languages: "Языки {{label}}", + moreLanguages: "{{languages}} и ещё {{count}}", + }, + }, general: { title: "Основные", sending: "Отправка", diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index 9954bdb61b..78b0f06442 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -2202,6 +2202,7 @@ export const zhCN: TranslationResources = { connections: "连接", agents: "Agents", metadata: "元数据", + voice: "语音", workspaces: "Workspaces", providers: "Providers", usage: "使用情况", @@ -2223,6 +2224,69 @@ export const zhCN: TranslationResources = { docs: "文档", saveError: "无法更新元数据生成设置", }, + voice: { + offline: "连接到此主机以配置语音。", + updateHost: "请更新主机以配置语音。", + saveError: "无法更新语音设置", + provider: "提供方", + providers: { + local: "本地", + openai: "OpenAI", + }, + voice: "音色", + save: "保存", + retry: "重试", + cancel: "取消", + model: "模型", + language: "语言", + languagePlaceholder: "自动检测", + setBy: "由 {{name}} 设置", + unknownProvider: "更新应用以配置 {{provider}}", + sites: { + dictationStt: "语音转文字", + voiceModeStt: "聆听", + voiceModeTts: "朗读", + }, + dictation: { + title: "听写", + enabled: "听写", + enabledHint: "对着消息框说话,无需打字", + }, + voiceMode: { + title: "语音模式", + info: "语音模式会转写你说的话,并朗读智能体的回复。", + enabled: "语音模式", + enabledHint: "免手动与智能体对话", + }, + openai: { + apiKey: "API 密钥", + apiKeyHint: "保存在主机上,不会再次显示。", + keyPlaceholder: "sk-...", + savedKeyPlaceholder: "已保存", + missingKey: "缺少 API 密钥", + baseUrl: "基础 URL", + baseUrlHint: "用于兼容 OpenAI 的服务器。留空则使用 OpenAI。", + }, + models: { + loading: "正在加载模型...", + loadError: "无法加载本地模型", + none: "没有可用的模型", + downloaded: "已下载", + inUse: "使用中", + recommended: "推荐", + download: "下载", + downloadAction: "下载 {{label}}", + downloading: "正在下载...", + downloadingPercent: "正在下载 {{percent}}%", + extracting: "正在解压...", + delete: "删除", + deleteAction: "删除 {{label}}", + deleteTitle: "删除 {{label}}?", + deleteMessage: "这将释放 {{size}}。之后可以重新下载。", + languages: "{{label}} 支持的语言", + moreLanguages: "{{languages}} 等另外 {{count}} 种", + }, + }, general: { title: "通用", sending: "发送", diff --git a/packages/app/src/screens/settings-screen.tsx b/packages/app/src/screens/settings-screen.tsx index 10d87cdcba..b45b745212 100644 --- a/packages/app/src/screens/settings-screen.tsx +++ b/packages/app/src/screens/settings-screen.tsx @@ -37,6 +37,7 @@ import { Files, Smartphone, Sparkles, + Mic, Blocks, Globe, PanelLeft, @@ -118,6 +119,7 @@ import { PluginSettingsContent } from "@/plugins/settings"; import { useInstalledPlugins } from "@/plugins/registry"; import { HostPluginsPage } from "@/screens/settings/plugins-page"; import { MetadataGenerationPage } from "@/screens/settings/metadata-generation-page"; +import { HostVoicePage } from "@/screens/settings/voice/voice-page"; import ProjectsScreen from "@/screens/projects-screen"; import ProjectSettingsScreen from "@/screens/project-settings-screen"; import { SETTINGS_DESKTOP_SIDEBAR_WIDTH, useIsCompactFormFactor } from "@/constants/layout"; @@ -240,6 +242,7 @@ const HOST_SECTION_ITEMS: HostSectionItem[] = [ { id: "pair-device", labelKey: "openProject.tiles.pairDevice.title", icon: Smartphone }, { id: "agents", labelKey: "settings.hostSections.agents", icon: Bot }, { id: "metadata", labelKey: "settings.hostSections.metadata", icon: Sparkles }, + { id: "voice", labelKey: "settings.hostSections.voice", icon: Mic }, { id: "workspaces", labelKey: "settings.hostSections.workspaces", icon: FolderGit2 }, { id: "providers", labelKey: "settings.hostSections.providers", icon: Boxes }, { id: "usage", labelKey: "settings.hostSections.usage", icon: Gauge }, @@ -262,6 +265,8 @@ function renderHostSettingsContent( return ; case "metadata": return ; + case "voice": + return ; case "workspaces": return ; case "providers": diff --git a/packages/app/src/screens/settings/voice/speech-provider-form.test.ts b/packages/app/src/screens/settings/voice/speech-provider-form.test.ts new file mode 100644 index 0000000000..db88fc9bdd --- /dev/null +++ b/packages/app/src/screens/settings/voice/speech-provider-form.test.ts @@ -0,0 +1,174 @@ +import { describe, expect, it } from "vitest"; +import type { SpeechSettingsPatch } from "@getpaseo/protocol/speech/rpc-schemas"; +import { openSpeechProviderForm, type SpeechProviderFormSnapshot } from "./speech-provider-form"; + +function open(overrides: Partial = {}) { + return openSpeechProviderForm({ + siteId: "voiceMode.stt", + site: { provider: "local" }, + envOverrides: {}, + ...overrides, + }); +} + +async function savedPatch( + model: ReturnType, +): Promise { + let sent: SpeechSettingsPatch | undefined; + const result = await model.save(async (patch) => { + sent = patch; + }); + expect(result).toEqual({ status: "saved" }); + return sent; +} + +describe("speech provider form", () => { + it("edits and clears local STT language from the saved snapshot", async () => { + const form = open({ site: { provider: "local", language: "fr" } }); + expect(form.getState()).toMatchObject({ language: "fr", canSave: false }); + form.setLanguage(" de "); + expect(await savedPatch(form)).toEqual({ + voiceMode: { stt: { provider: "local", language: "de" } }, + }); + const clear = open({ site: { provider: "local", language: "fr" } }); + clear.setLanguage(""); + expect(await savedPatch(clear)).toEqual({ + voiceMode: { stt: { provider: "local", language: null } }, + }); + }); + + it("keeps STT language when switching either provider", async () => { + for (const provider of ["local", "openai"] as const) { + const form = open({ + site: + provider === "local" + ? { provider, language: "fr" } + : { provider, hasApiKey: false, language: "fr" }, + }); + form.setProvider(provider === "local" ? "openai" : "local"); + expect(await savedPatch(form)).toEqual({ + voiceMode: { stt: { provider: provider === "local" ? "openai" : "local", language: "fr" } }, + }); + } + }); + + it("keeps env-controlled language read-only after switching providers", async () => { + const form = open({ + site: { provider: "local", language: "fr" }, + envOverrides: { "features.voiceMode.stt.language": "PASEO_VOICE_LANGUAGE" }, + }); + form.setProvider("openai"); + expect(form.getState().fields.language).toEqual({ + envVar: "PASEO_VOICE_LANGUAGE", + readOnly: true, + }); + expect(await savedPatch(form)).toEqual({ voiceMode: { stt: { provider: "openai" } } }); + }); + + it("switches a site to OpenAI with a key and base URL", async () => { + const form = open(); + expect(form.getState().canSave).toBe(false); + + form.setProvider("openai"); + form.setApiKey(" sk-test "); + form.setBaseUrl("http://127.0.0.1:9999/v1"); + + expect(await savedPatch(form)).toEqual({ + voiceMode: { + stt: { provider: "openai", apiKey: "sk-test", baseUrl: "http://127.0.0.1:9999/v1" }, + }, + }); + }); + + it("re-saves OpenAI settings without touching the saved key", async () => { + const form = open({ + siteId: "dictation.stt", + site: { provider: "openai", hasApiKey: true, baseUrl: "https://a.example/v1" }, + }); + expect(form.getState()).toMatchObject({ apiKey: "", hasSavedApiKey: true, canSave: false }); + + form.setOpenAiModel("gpt-4o-transcribe"); + form.setBaseUrl(""); + + expect(await savedPatch(form)).toEqual({ + dictation: { stt: { provider: "openai", model: "gpt-4o-transcribe", baseUrl: null } }, + }); + }); + + it("selects a local model", async () => { + const form = open({ + siteId: "dictation.stt", + site: { provider: "local", model: "whisper-tiny" }, + }); + form.setLocalModel("whisper-tiny"); + expect(form.getState().canSave).toBe(false); + + form.setLocalModel("whisper-base"); + + expect(await savedPatch(form)).toEqual({ + dictation: { stt: { provider: "local", model: "whisper-base" } }, + }); + }); + + it("locks fields an env var decides and keeps fallback fields editable", async () => { + const form = open({ + site: { provider: "openai", hasApiKey: false }, + envOverrides: { + "features.voiceMode.stt.provider": "PASEO_VOICE_STT_PROVIDER", + "features.voiceMode.stt.model": "STT_MODEL", + "features.voiceMode.stt.apiKey": "OPENAI_API_KEY", + }, + }); + expect(form.getState().fields).toMatchObject({ + provider: { envVar: "PASEO_VOICE_STT_PROVIDER", readOnly: true }, + model: { envVar: "STT_MODEL", readOnly: true }, + apiKey: { envVar: "OPENAI_API_KEY", readOnly: false }, + baseUrl: { envVar: null, readOnly: false }, + }); + + form.setProvider("local"); + form.setOpenAiModel("gpt-4o-transcribe"); + form.setApiKey("sk-saved"); + + expect(form.getState().provider).toBe("openai"); + expect(await savedPatch(form)).toEqual({ + voiceMode: { stt: { provider: "openai", apiKey: "sk-saved" } }, + }); + }); + + it("does not apply the saved provider's env vars to another provider", () => { + const form = open({ + envOverrides: { "features.voiceMode.stt.model": "PASEO_VOICE_LOCAL_STT_MODEL" }, + }); + expect(form.getState().fields.model.readOnly).toBe(true); + + form.setProvider("openai"); + + expect(form.getState().fields.model).toEqual({ envVar: null, readOnly: false }); + }); + + it("keeps the input and allows a retry after a failed save", async () => { + const form = open({ siteId: "voiceMode.tts" }); + form.setProvider("openai"); + form.setApiKey("sk-test"); + form.setVoice("nova"); + const failure = new Error("disk full"); + + const result = await form.save(async () => { + expect(form.getState()).toMatchObject({ saving: true, canSave: false }); + throw failure; + }); + + expect(result).toEqual({ status: "failed", error: failure }); + expect(form.getState()).toMatchObject({ + provider: "openai", + apiKey: "sk-test", + voice: "nova", + saving: false, + canSave: true, + }); + expect(await savedPatch(form)).toEqual({ + voiceMode: { tts: { provider: "openai", apiKey: "sk-test", voice: "nova" } }, + }); + }); +}); diff --git a/packages/app/src/screens/settings/voice/speech-provider-form.ts b/packages/app/src/screens/settings/voice/speech-provider-form.ts new file mode 100644 index 0000000000..b8230104e5 --- /dev/null +++ b/packages/app/src/screens/settings/voice/speech-provider-form.ts @@ -0,0 +1,240 @@ +import type { SpeechSettingsPatch } from "@getpaseo/protocol/speech/rpc-schemas"; +import { + SPEECH_SITE_KIND, + buildSpeechSitePatch, + resolveOpenAiModel, + resolveOpenAiVoice, + speechSiteFieldPath, + type SpeechModelKind, + type SpeechProvider, + type SpeechSite, + type SpeechSiteId, + type SpeechSitePatch, +} from "./voice-settings"; + +// The provider sheet's form: one speech site, its provider and that provider's fields. +// Plain TypeScript so the save rules are testable without rendering (docs/forms.md). + +export interface SpeechProviderFormSnapshot { + siteId: SpeechSiteId; + site: Extract; + envOverrides: Record; +} + +export type SpeechProviderField = + | "provider" + | "model" + | "apiKey" + | "baseUrl" + | "language" + | "voice"; + +// An env var set for one of these is only a fallback: a value saved in the sheet wins, +// so the field stays editable. Every other field is decided by its env var. +const FALLBACK_FIELDS: ReadonlySet = new Set(["apiKey", "baseUrl"]); + +export interface SpeechProviderFieldSource { + /** The env var that decides this field's effective value, when one does. */ + envVar: string | null; + readOnly: boolean; +} + +export interface SpeechProviderFormState { + kind: SpeechModelKind; + provider: SpeechProvider; + /** The local model the user picked in this sheet; null keeps the saved or default model. */ + localModel: string | null; + savedLocalModel: string | undefined; + apiKey: string; + hasSavedApiKey: boolean; + baseUrl: string; + openAiModel: string; + language: string; + voice: string; + fields: Record; + saving: boolean; + canSave: boolean; +} + +export type SpeechProviderSaveResult = + | { status: "saved" } + | { status: "skipped" } + | { status: "failed"; error: unknown }; + +export interface SpeechProviderFormModel { + getState: () => SpeechProviderFormState; + subscribe: (listener: () => void) => () => void; + close: () => void; + setProvider: (provider: SpeechProvider) => void; + setLocalModel: (modelId: string) => void; + setApiKey: (value: string) => void; + setBaseUrl: (value: string) => void; + setOpenAiModel: (value: string) => void; + setLanguage: (value: string) => void; + setVoice: (value: string) => void; + /** Sends the changed fields through `save`; the inputs survive a failed save. */ + save: ( + save: (patch: SpeechSettingsPatch) => Promise, + ) => Promise; +} + +interface OpenAiValues { + baseUrl: string; + openAiModel: string; + voice: string; +} + +export function openSpeechProviderForm( + snapshot: SpeechProviderFormSnapshot, +): SpeechProviderFormModel { + const { siteId, site, envOverrides } = snapshot; + const kind = SPEECH_SITE_KIND[siteId]; + const savedOpenAi = site.provider === "openai" ? site : undefined; + const initialOpenAi: OpenAiValues = { + baseUrl: savedOpenAi?.baseUrl ?? "", + openAiModel: resolveOpenAiModel(kind, savedOpenAi?.model), + voice: resolveOpenAiVoice(savedOpenAi?.voice), + }; + const initialLanguage = site.language ?? ""; + // The daemon reports env vars for the provider that is in effect, so they only describe the + // provider-specific fields while that provider is selected. Language applies to either STT provider. + const savedFields = buildFieldSources(siteId, envOverrides); + const switchedFields = { + ...buildFieldSources(siteId, {}), + provider: savedFields.provider, + language: savedFields.language, + }; + const listeners = new Set<() => void>(); + let closed = false; + + let state: SpeechProviderFormState = derive({ + kind, + provider: site.provider, + localModel: null, + savedLocalModel: site.provider === "local" ? site.model : undefined, + apiKey: "", + hasSavedApiKey: savedOpenAi?.hasApiKey ?? false, + ...initialOpenAi, + language: initialLanguage, + fields: savedFields, + saving: false, + canSave: false, + }); + + function derive(next: SpeechProviderFormState): SpeechProviderFormState { + return { + ...next, + fields: next.provider === site.provider ? savedFields : switchedFields, + canSave: !next.saving && isChanged(next), + }; + } + + function isChanged(next: SpeechProviderFormState): boolean { + if (next.provider !== site.provider) return true; + if (kind === "stt" && next.language.trim() !== initialLanguage) return true; + if (next.provider === "local") { + return next.localModel !== null && next.localModel !== next.savedLocalModel; + } + return next.apiKey.trim().length > 0 || changedOpenAiFields(next).length > 0; + } + + function changedOpenAiFields(next: SpeechProviderFormState): (keyof OpenAiValues)[] { + const keys: (keyof OpenAiValues)[] = + kind === "stt" ? ["baseUrl", "openAiModel"] : ["baseUrl", "openAiModel", "voice"]; + return keys.filter((key) => next[key].trim() !== initialOpenAi[key]); + } + + function buildSitePatch(next: SpeechProviderFormState): SpeechSitePatch { + const language = next.language.trim(); + const languagePatch: Record = + kind === "stt" && + !next.fields.language.readOnly && + (language !== initialLanguage || (next.provider !== site.provider && language.length > 0)) + ? { language: language || null } + : {}; + if (next.provider === "local") { + return { + provider: "local", + ...languagePatch, + ...(next.localModel !== null && !next.fields.model.readOnly + ? { model: next.localModel } + : {}), + }; + } + const patch: Record = { provider: "openai", ...languagePatch }; + const apiKey = next.apiKey.trim(); + if (apiKey) patch.apiKey = apiKey; + for (const key of changedOpenAiFields(next)) { + const field = key === "openAiModel" ? "model" : key; + if (next.fields[field].readOnly) continue; + patch[field] = next[key].trim() || null; + } + return patch as SpeechSitePatch; + } + + function publish(next: SpeechProviderFormState): void { + if (closed) return; + state = derive(next); + for (const listener of listeners) listener(); + } + + function edit(change: Partial): void { + if (state.saving) return; + publish({ ...state, ...change }); + } + + return { + getState: () => state, + subscribe(listener) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + close() { + closed = true; + listeners.clear(); + }, + setProvider: (provider) => { + if (!state.fields.provider.readOnly) edit({ provider }); + }, + setLocalModel: (localModel) => { + if (!state.fields.model.readOnly) edit({ localModel }); + }, + setApiKey: (apiKey) => edit({ apiKey }), + setBaseUrl: (baseUrl) => edit({ baseUrl }), + setOpenAiModel: (openAiModel) => edit({ openAiModel }), + setLanguage: (language) => edit({ language }), + setVoice: (voice) => edit({ voice }), + async save(save) { + if (!state.canSave) return { status: "skipped" }; + const patch = buildSpeechSitePatch(siteId, buildSitePatch(state)); + publish({ ...state, saving: true }); + try { + await save(patch); + return { status: "saved" }; + } catch (error) { + publish({ ...state, saving: false }); + return { status: "failed", error }; + } + }, + }; +} + +function buildFieldSources( + siteId: SpeechSiteId, + envOverrides: Record, +): Record { + const source = (field: SpeechProviderField): SpeechProviderFieldSource => { + const envVar = envOverrides[speechSiteFieldPath(siteId, field)] ?? null; + return { envVar, readOnly: envVar !== null && !FALLBACK_FIELDS.has(field) }; + }; + return { + provider: source("provider"), + model: source("model"), + apiKey: source("apiKey"), + baseUrl: source("baseUrl"), + language: source("language"), + voice: source("voice"), + }; +} diff --git a/packages/app/src/screens/settings/voice/speech-provider-sheet.tsx b/packages/app/src/screens/settings/voice/speech-provider-sheet.tsx new file mode 100644 index 0000000000..7c842053b3 --- /dev/null +++ b/packages/app/src/screens/settings/voice/speech-provider-sheet.tsx @@ -0,0 +1,585 @@ +import { + useCallback, + useEffect, + useMemo, + useState, + useSyncExternalStore, + type ReactNode, +} from "react"; +import { Text, View, type PressableStateCallbackType } from "react-native"; +import { useTranslation } from "react-i18next"; +import type { TFunction } from "i18next"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { Check, Download, Languages, Trash2 } from "lucide-react-native"; +import type { LocalSpeechModel, SpeechSettingsPatch } from "@getpaseo/protocol/speech/rpc-schemas"; +import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet"; +import { + SettingsCard, + SettingsInfoTip, + SettingsInput, + SettingsRow, + SettingsSelect, +} from "@/components/settings"; +import { Button } from "@/components/ui/button"; +import { buttonControlHeight } from "@/components/ui/control-geometry"; +import { useContainedControlSize } from "@/components/ui/control-size"; +import { foregroundIconColorMapping } from "@/components/ui/icon-color"; +import { PressHighlight } from "@/components/ui/press-highlight"; +import { LoadingSpinner } from "@/components/ui/loading-spinner"; +import { SegmentedControl } from "@/components/ui/segmented-control"; +import { StatusBadge } from "@/components/ui/status-badge"; +import { useIsCompactFormFactor } from "@/constants/layout"; +import { useToast } from "@/contexts/toast-api-context"; +import { ICON_SIZE } from "@/styles/theme"; +import { confirmDialog } from "@/utils/confirm-dialog"; +import type { LocalSpeechModels } from "./use-local-speech-models"; +import { + openSpeechProviderForm, + type SpeechProviderFieldSource, + type SpeechProviderFormModel, + type SpeechProviderFormSnapshot, + type SpeechProviderFormState, +} from "./speech-provider-form"; +import { + SPEECH_PROVIDERS, + buildOpenAiModelOptions, + buildOpenAiVoiceOptions, + formatLanguages, + formatModelSize, + getLocalModelState, + resolveLocalModel, + type LocalModelState, + type SpeechProvider, +} from "./voice-settings"; + +const ThemedCheck = withUnistyles(Check); + +export interface SpeechProviderSheetProps extends SpeechProviderFormSnapshot { + title: string; + localModels: LocalSpeechModels; + visible: boolean; + onClose: () => void; + onDismiss: () => void; + save: (patch: SpeechSettingsPatch) => Promise; +} + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +// The form opens from the props of the first render; later config changes do not reset input. +function useSpeechProviderForm(snapshot: SpeechProviderFormSnapshot): SpeechProviderFormModel { + const [model] = useState(() => openSpeechProviderForm(snapshot)); + useEffect(() => () => model.close(), [model]); + return model; +} + +/** One speech site's provider and that provider's settings. Mount it fresh for each open. */ +export function SpeechProviderSheet({ + title, + siteId, + site, + envOverrides, + localModels, + visible, + onClose, + onDismiss, + save, +}: SpeechProviderSheetProps) { + const { t } = useTranslation(); + const toast = useToast(); + const model = useSpeechProviderForm({ siteId, site, envOverrides }); + const state = useSyncExternalStore(model.subscribe, model.getState, model.getState); + + const submit = useCallback(() => { + void model.save(save).then((result) => { + if (result.status === "saved") onClose(); + if (result.status === "failed") { + toast.error(`${t("settings.voice.saveError")}: ${errorMessage(result.error)}`); + } + return undefined; + }); + }, [model, onClose, save, t, toast]); + + const header = useMemo(() => ({ title }), [title]); + const footer = useMemo( + () => ( + + + + + ), + [onClose, state.canSave, state.saving, submit, t], + ); + + return ( + + + + + {state.provider === "local" ? ( + <> + {state.kind === "stt" ? ( + + + + ) : null} + + + ) : ( + + )} + + ); +} + +interface FormProps { + state: SpeechProviderFormState; + model: SpeechProviderFormModel; +} + +function setByHint(t: TFunction, source: SpeechProviderFieldSource): string | undefined { + return source.envVar ? t("settings.voice.setBy", { name: source.envVar }) : undefined; +} + +function ProviderRow({ state, model }: FormProps) { + const { t } = useTranslation(); + const source = state.fields.provider; + const options = useMemo( + () => + SPEECH_PROVIDERS.map((provider) => ({ + value: provider, + label: t(`settings.voice.providers.${provider}`), + disabled: source.readOnly, + })), + [source.readOnly, t], + ); + return ( + + + options={options} + value={state.provider} + onValueChange={model.setProvider} + testID="voice-provider-picker" + /> + + ); +} + +function LanguageField({ state, model }: FormProps) { + const { t } = useTranslation(); + return ( + + ); +} + +// --------------------------------------------------------------------------- +// OpenAI +// --------------------------------------------------------------------------- + +function OpenAiFields({ state, model }: FormProps) { + const { t } = useTranslation(); + const modelOptions = useMemo( + () => buildOpenAiModelOptions(state.kind, state.openAiModel), + [state.kind, state.openAiModel], + ); + const voiceOptions = useMemo(() => buildOpenAiVoiceOptions(state.voice), [state.voice]); + const apiKeyInfo = useMemo( + () => ( + + ), + [t], + ); + const baseUrlInfo = useMemo( + () => ( + + ), + [t], + ); + + return ( + + + + + {state.kind === "stt" ? ( + + ) : ( + + )} + + ); +} + +// --------------------------------------------------------------------------- +// Local: the catalog, with the selected model checked +// --------------------------------------------------------------------------- + +function LocalModelList({ + state, + model, + localModels, +}: FormProps & { localModels: LocalSpeechModels }) { + const { t } = useTranslation(); + const { models, isLoading, error, refresh, download, remove } = localModels; + const kindModels = useMemo( + () => models.filter((entry) => entry.kind === state.kind), + [models, state.kind], + ); + const selectedId = + state.localModel ?? + resolveLocalModel({ kind: state.kind, model: state.savedLocalModel, localModels: models })?.id; + const source = state.fields.model; + + if (kindModels.length === 0) { + if (error) { + return ( + + + + + + ); + } + return ( + + + + ); + } + return ( + + {kindModels.map((entry) => ( + + ))} + + ); +} + +function progressLabel( + t: TFunction, + state: Extract, +): string { + if (state.kind === "extracting") return t("settings.voice.models.extracting"); + if (state.percent === null) return t("settings.voice.models.downloading"); + return t("settings.voice.models.downloadingPercent", { percent: state.percent }); +} + +type HoverState = PressableStateCallbackType & { hovered?: boolean }; + +function LocalModelRow({ + model, + selected, + selectionLocked, + hint, + onSelect, + onDownload, + onDelete, +}: { + model: LocalSpeechModel; + selected: boolean; + selectionLocked: boolean; + /** Why the selection is fixed, shown on the selected row. */ + hint: string | undefined; + onSelect: (modelId: string) => void; + onDownload: (modelId: string) => Promise; + onDelete: (modelId: string) => Promise; +}) { + const { t, i18n } = useTranslation(); + const state = getLocalModelState(model); + const [actionError, setActionError] = useState(null); + + const select = useCallback(() => onSelect(model.id), [model.id, onSelect]); + const download = useCallback(() => { + setActionError(null); + onDownload(model.id).catch((error: unknown) => setActionError(errorMessage(error))); + }, [model.id, onDownload]); + const remove = useCallback(() => { + void confirmDialog({ + title: t("settings.voice.models.deleteTitle", { label: model.label }), + message: t("settings.voice.models.deleteMessage", { + size: formatModelSize(model.downloadSizeBytes), + }), + confirmLabel: t("settings.voice.models.delete"), + destructive: true, + }) + .then((confirmed) => { + if (!confirmed) return undefined; + setActionError(null); + return onDelete(model.id); + }) + .catch((error: unknown) => setActionError(errorMessage(error))); + }, [model.downloadSizeBytes, model.id, model.label, onDelete, t]); + + const languages = formatLanguages({ + languages: model.languages, + locale: i18n.language, + formatMore: (listed, count) => + t("settings.voice.models.moreLanguages", { languages: listed, count }), + }); + const details = useMemo( + () => ( + + + + {formatModelSize(model.downloadSizeBytes)} + {state.kind === "installed" ? ( + + ) : null} + {hint ? {hint} : null} + + ), + [ + hint, + languages, + model.description, + model.downloadSizeBytes, + model.id, + model.inUse, + model.label, + state.kind, + t, + ], + ); + + const recommended = useMemo( + () => + model.isDefault ? ( + + ) : undefined, + [model.isDefault, t], + ); + + // Phone rows have no room beside the label for a labelled button, so actions show their icon. + const compact = useIsCompactFormFactor(); + const downloadLabel = + state.kind === "failed" ? t("settings.voice.retry") : t("settings.voice.models.download"); + let control = null; + if (state.kind === "downloading" || state.kind === "extracting") { + control = ( + + + {progressLabel(t, state)} + + ); + } else if (state.kind === "installed") { + control = model.inUse ? null : ( + + ); + } else { + control = ( + + ); + } + + const rowStyle = useCallback( + ({ hovered, pressed }: HoverState) => [ + !selectionLocked && hovered && styles.rowHovered, + !selectionLocked && pressed && styles.rowPressed, + ], + [selectionLocked], + ); + const accessibilityState = useMemo( + () => ({ checked: selected, disabled: selectionLocked }), + [selected, selectionLocked], + ); + + return ( + + + + {control} + + {selected ? ( + + ) : null} + + + + + ); +} + +// Every catalog row is as tall as one holding a button, so a row does not shrink when its +// download finishes and the button goes away. +function TrailingControls({ children }: { children: ReactNode }) { + const size = useContainedControlSize() ?? "sm"; + const style = useMemo(() => [styles.trailing, { minHeight: buttonControlHeight[size] }], [size]); + return {children}; +} + +const styles = StyleSheet.create((theme) => ({ + footer: { + flex: 1, + flexDirection: "row", + gap: theme.spacing[3], + }, + footerButton: { + flex: 1, + }, + rowHovered: { + backgroundColor: theme.colors.surface2, + }, + rowPressed: { + backgroundColor: theme.colors.surface3, + }, + // The model's details sit on the hint line, so every catalog row has the same two lines. + details: { + flexDirection: "row", + flexWrap: "wrap", + alignItems: "center", + gap: theme.spacing[2], + marginTop: theme.spacing[1], + }, + metaText: { + color: theme.colors.foregroundMuted, + fontSize: theme.fontSize.sm, + fontVariant: ["tabular-nums"], + }, + trailing: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[2], + }, + checkSlot: { + width: ICON_SIZE.sm, + alignItems: "center", + }, + progress: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[2], + }, + spinnerColor: { + color: theme.colors.foregroundMuted, + }, +})); diff --git a/packages/app/src/screens/settings/voice/use-local-speech-models.ts b/packages/app/src/screens/settings/voice/use-local-speech-models.ts new file mode 100644 index 0000000000..b68a7b8135 --- /dev/null +++ b/packages/app/src/screens/settings/voice/use-local-speech-models.ts @@ -0,0 +1,71 @@ +import { useCallback } from "react"; +import { useTranslation } from "react-i18next"; +import type { LocalSpeechModel } from "@getpaseo/protocol/speech/rpc-schemas"; +import { useFetchQuery } from "@/data/query"; +import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime"; +import { isLocalModelBusy } from "./voice-settings"; + +const DOWNLOAD_POLL_INTERVAL_MS = 1000; + +const localSpeechModelsQueryKey = (serverId: string) => ["speech-local-models", serverId] as const; + +export interface LocalSpeechModels { + models: LocalSpeechModel[]; + isLoading: boolean; + error: Error | null; + refresh: () => void; + download: (modelId: string) => Promise; + remove: (modelId: string) => Promise; +} + +// The daemon reports download progress through the list, so the list polls while any +// model is downloading or extracting. +export function useLocalSpeechModels(serverId: string): LocalSpeechModels { + const { t } = useTranslation(); + const client = useHostRuntimeClient(serverId); + const isConnected = useHostRuntimeIsConnected(serverId); + const query = useFetchQuery({ + queryKey: localSpeechModelsQueryKey(serverId), + enabled: Boolean(client && isConnected), + dataShape: "list", + staleTimeMs: 0, + queryFn: () => { + if (!client) throw new Error(t("workspace.terminal.hostDisconnected")); + return client.listLocalSpeechModels(); + }, + refetchInterval: (current) => + current.state.data?.some(isLocalModelBusy) ? DOWNLOAD_POLL_INTERVAL_MS : false, + }); + const { refetch } = query; + + const refresh = useCallback(() => { + void refetch(); + }, [refetch]); + + const download = useCallback( + async (modelId: string) => { + if (!client) return; + await client.downloadLocalSpeechModel(modelId); + await refetch(); + }, + [client, refetch], + ); + + const remove = useCallback( + async (modelId: string) => { + if (!client) return; + await client.deleteLocalSpeechModel(modelId); + await refetch(); + }, + [client, refetch], + ); + + return { + models: query.data ?? [], + isLoading: query.isLoading, + error: query.error, + refresh, + download, + remove, + }; +} diff --git a/packages/app/src/screens/settings/voice/voice-page.tsx b/packages/app/src/screens/settings/voice/voice-page.tsx new file mode 100644 index 0000000000..b8b6402b76 --- /dev/null +++ b/packages/app/src/screens/settings/voice/voice-page.tsx @@ -0,0 +1,252 @@ +import { useCallback, useState } from "react"; +import { View } from "react-native"; +import { useTranslation } from "react-i18next"; +import type { TFunction } from "i18next"; +import { StyleSheet } from "react-native-unistyles"; +import type { SpeechSettingsPatch } from "@getpaseo/protocol/speech/rpc-schemas"; +import { + SettingsCard, + SettingsDetailRow, + SettingsRow, + SettingsSection, +} from "@/components/settings"; +import { Alert } from "@/components/ui/alert"; +import { LoadingSpinner } from "@/components/ui/loading-spinner"; +import { Switch } from "@/components/ui/switch"; +import { useToast } from "@/contexts/toast-api-context"; +import { useDaemonConfig } from "@/hooks/use-daemon-config"; +import { useHostFeature } from "@/runtime/host-features"; +import { useHostRuntimeIsConnected } from "@/runtime/host-runtime"; +import { SpeechProviderSheet } from "./speech-provider-sheet"; +import { useLocalSpeechModels } from "./use-local-speech-models"; +import { + getSpeechSite, + summarizeSpeechSite, + type SpeechSiteId, + type SpeechSiteSummary, +} from "./voice-settings"; + +type SavePatch = (patch: SpeechSettingsPatch) => Promise; +const EMPTY_ENV_OVERRIDES: Record = {}; + +// The sheet mounts fresh for every open (docs/forms.md); `openCount` keys each mount. +interface OpenSheet { + siteId: SpeechSiteId; + visible: boolean; + openCount: number; +} + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +export function HostVoicePage({ serverId }: { serverId: string }) { + const { t } = useTranslation(); + const toast = useToast(); + const isConnected = useHostRuntimeIsConnected(serverId); + const supported = useHostFeature(serverId, "speechSettings"); + const { config, patchConfig } = useDaemonConfig(serverId); + const localModels = useLocalSpeechModels(serverId); + const { refresh: refreshModels } = localModels; + const [sheet, setSheet] = useState(null); + + // Selecting a model changes which models are in use, so the catalog is re-read after a save. + const save = useCallback( + async (patch) => { + await patchConfig({ features: patch }); + refreshModels(); + }, + [patchConfig, refreshModels], + ); + const saveSwitch = useCallback( + (patch: SpeechSettingsPatch) => { + save(patch).catch((error: unknown) => { + toast.error(`${t("settings.voice.saveError")}: ${errorMessage(error)}`); + }); + }, + [save, t, toast], + ); + const setDictationEnabled = useCallback( + (enabled: boolean) => saveSwitch({ dictation: { enabled } }), + [saveSwitch], + ); + const setVoiceModeEnabled = useCallback( + (enabled: boolean) => saveSwitch({ voiceMode: { enabled } }), + [saveSwitch], + ); + const openSheet = useCallback((siteId: SpeechSiteId) => { + setSheet((current) => ({ + siteId, + visible: true, + openCount: (current?.openCount ?? 0) + 1, + })); + }, []); + const closeSheet = useCallback(() => { + setSheet((current) => (current ? { ...current, visible: false } : null)); + }, []); + const dismissSheet = useCallback(() => setSheet(null), []); + + if (!isConnected) { + return ; + } + if (!supported) { + return ; + } + const features = config?.features; + if (!features) { + return ( + + + + ); + } + const envOverrides = config?.envOverrides ?? EMPTY_ENV_OVERRIDES; + const siteRow = (siteId: SpeechSiteId, label: string) => ( + + ); + const sheetSite = sheet ? getSpeechSite(features, sheet.siteId) : null; + + return ( + + + + + {siteRow("dictation.stt", t("settings.voice.sites.dictationStt"))} + + + + + + {siteRow("voiceMode.stt", t("settings.voice.sites.voiceModeStt"))} + {siteRow("voiceMode.tts", t("settings.voice.sites.voiceModeTts"))} + + + {sheet && sheetSite && sheetSite.provider !== "unknown" ? ( + + ) : null} + + ); +} + +function siteLabel(t: TFunction, siteId: SpeechSiteId): string { + switch (siteId) { + case "dictation.stt": + return t("settings.voice.sites.dictationStt"); + case "voiceMode.stt": + return t("settings.voice.sites.voiceModeStt"); + case "voiceMode.tts": + return t("settings.voice.sites.voiceModeTts"); + } +} + +function FeatureSwitchRow({ + label, + hint, + envVar, + value, + onChange, +}: { + label: string; + hint: string; + envVar: string | undefined; + value: boolean; + onChange: (value: boolean) => void; +}) { + const { t } = useTranslation(); + return ( + + + + ); +} + +function SpeechSiteRow({ + siteId, + label, + summary, + onOpen, +}: { + siteId: SpeechSiteId; + label: string; + summary: SpeechSiteSummary; + onOpen: (siteId: SpeechSiteId) => void; +}) { + const { t } = useTranslation(); + const open = useCallback(() => onOpen(siteId), [onOpen, siteId]); + return ( + + ); +} + +function summaryLabel(t: TFunction, summary: SpeechSiteSummary): string { + switch (summary.kind) { + case "local": + return summary.model + ? `${t("settings.voice.providers.local")} · ${summary.model}` + : t("settings.voice.providers.local"); + case "openai": + return `${t("settings.voice.providers.openai")} · ${ + summary.missingKey ? t("settings.voice.openai.missingKey") : summary.model + }`; + case "unknown": + return t("settings.voice.unknownProvider", { provider: summary.provider }); + } +} + +const styles = StyleSheet.create((theme) => ({ + loading: { + paddingVertical: theme.spacing[8], + alignItems: "center", + }, + spinnerColor: { + color: theme.colors.foregroundMuted, + }, +})); diff --git a/packages/app/src/screens/settings/voice/voice-settings.test.ts b/packages/app/src/screens/settings/voice/voice-settings.test.ts new file mode 100644 index 0000000000..2541c4892c --- /dev/null +++ b/packages/app/src/screens/settings/voice/voice-settings.test.ts @@ -0,0 +1,122 @@ +import { describe, expect, it } from "vitest"; +import type { LocalSpeechModel } from "@getpaseo/protocol/speech/rpc-schemas"; +import { + buildOpenAiModelOptions, + getSpeechSite, + formatLanguages, + formatModelSize, + getLocalModelState, + summarizeSpeechSite, +} from "./voice-settings"; + +function model(overrides: Partial): LocalSpeechModel { + return { + id: "parakeet-tdt-0.6b-v2-int8", + kind: "stt", + label: "Parakeet v2", + description: "Accurate English transcription.", + languages: ["en"], + downloadSizeBytes: 482_468_385, + isDefault: true, + inUse: true, + status: "installed", + ...overrides, + }; +} + +const catalog = [ + model({}), + model({ + id: "parakeet-tdt-110m-en-int8", + label: "Parakeet Small", + isDefault: false, + status: "not_installed", + inUse: false, + }), + model({ id: "kokoro-en-v0_19", kind: "tts", label: "Kokoro", inUse: false }), +]; + +describe("voice settings", () => { + it("keeps local STT language from the wire when opening a provider sheet", () => { + const features = { + dictation: { enabled: true, stt: { provider: "local", language: "fr" } }, + voiceMode: { + enabled: false, + stt: { provider: "local", language: "de" }, + tts: { provider: "local" }, + }, + }; + expect(getSpeechSite(features, "dictation.stt")).toMatchObject({ + provider: "local", + language: "fr", + }); + expect(getSpeechSite(features, "voiceMode.stt")).toMatchObject({ + provider: "local", + language: "de", + }); + }); + + it("summarizes a local site by its model, falling back to the catalog default", () => { + const summary = (modelId?: string) => + summarizeSpeechSite({ + siteId: "dictation.stt", + site: { provider: "local", model: modelId }, + envOverrides: {}, + localModels: catalog, + }); + expect(summary()).toEqual({ kind: "local", model: "Parakeet v2" }); + expect(summary("parakeet-tdt-110m-en-int8")).toEqual({ + kind: "local", + model: "Parakeet Small", + }); + }); + + it("flags an OpenAI site with no saved key and no env key", () => { + const summary = (envOverrides: Record) => + summarizeSpeechSite({ + siteId: "voiceMode.tts", + site: { provider: "openai", hasApiKey: false }, + envOverrides, + localModels: catalog, + }); + expect(summary({})).toEqual({ kind: "openai", model: "tts-1", missingKey: true }); + expect(summary({ "features.voiceMode.tts.apiKey": "OPENAI_API_KEY" })).toEqual({ + kind: "openai", + model: "tts-1", + missingKey: false, + }); + }); + + it("keeps a custom OpenAI-compatible model id selectable", () => { + expect(buildOpenAiModelOptions("stt", "my-whisper").at(-1)).toEqual({ + value: "my-whisper", + label: "my-whisper", + }); + }); + + it("reports download progress as a percentage", () => { + expect( + getLocalModelState(model({ status: "downloading", receivedBytes: 241, totalBytes: 482 })), + ).toEqual({ kind: "downloading", percent: 50 }); + expect(getLocalModelState(model({ status: "downloading" }))).toEqual({ + kind: "downloading", + percent: null, + }); + }); + + it("formats download sizes", () => { + expect(formatModelSize(482_468_385)).toBe("482 MB"); + expect(formatModelSize(1_250_000_000)).toBe("1.3 GB"); + }); + + it("names a short language list and counts the rest of a long one", () => { + const formatMore = (languages: string, count: number) => `${languages} and ${count} more`; + expect(formatLanguages({ languages: ["en", "de"], locale: "en", formatMore })).toBe( + "English, German", + ); + const whisper = ["en", "zh", "de", "es", "ru", "ko", "fr", "ja", "pt", "tr", "pl", "ca"]; + expect(formatLanguages({ languages: whisper, locale: "en", formatMore })).toBe( + "English, Chinese, German, Spanish, Russian, Korean, French, Japanese, Portuguese, Turkish and 2 more", + ); + }); +}); diff --git a/packages/app/src/screens/settings/voice/voice-settings.ts b/packages/app/src/screens/settings/voice/voice-settings.ts new file mode 100644 index 0000000000..79c1062b49 --- /dev/null +++ b/packages/app/src/screens/settings/voice/voice-settings.ts @@ -0,0 +1,240 @@ +import type { + LocalSpeechModel, + SpeechSettings, + SpeechSettingsPatch, +} from "@getpaseo/protocol/speech/rpc-schemas"; + +// What the Voice page needs to know about speech providers and models, kept free of React +// so the option lists and model states are testable on their own. + +export type SpeechProvider = "local" | "openai"; +export type SpeechModelKind = "stt" | "tts"; + +export const SPEECH_PROVIDERS: readonly SpeechProvider[] = ["local", "openai"]; + +// The three places that use speech. Each carries its own provider settings in config.json +// under `features.`. +export type SpeechSiteId = "dictation.stt" | "voiceMode.stt" | "voiceMode.tts"; + +export const SPEECH_SITE_KIND: Record = { + "dictation.stt": "stt", + "voiceMode.stt": "stt", + "voiceMode.tts": "tts", +}; + +/** The config path the daemon names in `envOverrides` for a field of a site. */ +export function speechSiteFieldPath(siteId: SpeechSiteId, field: string): string { + return `features.${siteId}.${field}`; +} + +/** One site's settings as the daemon reports them, narrowed to what the app can edit. */ +export type SpeechSite = + | { provider: "local"; model?: string; language?: string } + | { + provider: "openai"; + hasApiKey: boolean; + baseUrl?: string; + model?: string; + language?: string; + voice?: string; + } + | { provider: "unknown"; id: string }; + +type SpeechSiteSettings = SpeechSettings["dictation"]["stt"] | SpeechSettings["voiceMode"]["tts"]; + +export function getSpeechSite(features: SpeechSettings, siteId: SpeechSiteId): SpeechSite { + switch (siteId) { + case "dictation.stt": + return toSpeechSite(features.dictation.stt); + case "voiceMode.stt": + return toSpeechSite(features.voiceMode.stt); + case "voiceMode.tts": + return toSpeechSite(features.voiceMode.tts); + } +} + +function toSpeechSite(settings: SpeechSiteSettings): SpeechSite { + const text = (value: unknown) => (typeof value === "string" && value ? value : undefined); + if (settings.provider === "local") + return { provider: "local", model: text(settings.model), language: text(settings.language) }; + if (settings.provider === "openai") { + return { + provider: "openai", + hasApiKey: settings.hasApiKey === true, + baseUrl: text(settings.baseUrl), + model: text(settings.model), + language: text(settings.language), + voice: text(settings.voice), + }; + } + return { provider: "unknown", id: settings.provider }; +} + +export type SpeechSitePatch = NonNullable< + | NonNullable["stt"] + | NonNullable["tts"] +>; + +export function buildSpeechSitePatch( + siteId: SpeechSiteId, + patch: SpeechSitePatch, +): SpeechSettingsPatch { + switch (siteId) { + case "dictation.stt": + return { dictation: { stt: patch } }; + case "voiceMode.stt": + return { voiceMode: { stt: patch } }; + case "voiceMode.tts": + return { voiceMode: { tts: patch } }; + } +} + +// OpenAI accepts free-form ids so self-hosted servers can use their own; these are the +// ones the page offers. A saved id outside the list is still shown as an option. +const OPENAI_MODELS: Record = { + stt: { + ids: ["whisper-1", "gpt-4o-transcribe", "gpt-4o-mini-transcribe"], + defaultId: "whisper-1", + }, + tts: { ids: ["tts-1", "tts-1-hd", "gpt-4o-mini-tts"], defaultId: "tts-1" }, +}; + +const OPENAI_VOICES = ["alloy", "ash", "coral", "echo", "fable", "nova", "onyx", "sage", "shimmer"]; +const DEFAULT_OPENAI_VOICE = "alloy"; + +export interface SpeechModelOption { + value: string; + label: string; +} + +export function resolveOpenAiModel(kind: SpeechModelKind, model: string | undefined): string { + return model ?? OPENAI_MODELS[kind].defaultId; +} + +export function resolveLocalModel(input: { + kind: SpeechModelKind; + model: string | undefined; + localModels: readonly LocalSpeechModel[]; +}): LocalSpeechModel | undefined { + const kindModels = input.localModels.filter((model) => model.kind === input.kind); + if (input.model) return kindModels.find((model) => model.id === input.model); + return kindModels.find((model) => model.isDefault); +} + +export function buildOpenAiModelOptions( + kind: SpeechModelKind, + selected: string, +): SpeechModelOption[] { + return withSelected( + OPENAI_MODELS[kind].ids.map((id) => ({ value: id, label: id })), + selected, + ); +} + +export function resolveOpenAiVoice(voice: string | undefined): string { + return voice ?? DEFAULT_OPENAI_VOICE; +} + +export function buildOpenAiVoiceOptions(selected: string): SpeechModelOption[] { + return withSelected( + OPENAI_VOICES.map((voice) => ({ value: voice, label: voice })), + selected, + ); +} + +function withSelected(options: SpeechModelOption[], selected: string): SpeechModelOption[] { + if (!selected || options.some((option) => option.value === selected)) return options; + return [...options, { value: selected, label: selected }]; +} + +// What a page row says about a site before it is opened. +export type SpeechSiteSummary = + | { kind: "local"; model: string | null } + | { kind: "openai"; model: string; missingKey: boolean } + | { kind: "unknown"; provider: string }; + +export function summarizeSpeechSite(input: { + siteId: SpeechSiteId; + site: SpeechSite; + envOverrides: Record; + localModels: readonly LocalSpeechModel[]; +}): SpeechSiteSummary { + const { site, siteId } = input; + const kind = SPEECH_SITE_KIND[siteId]; + switch (site.provider) { + case "local": { + const model = resolveLocalModel({ kind, model: site.model, localModels: input.localModels }); + return { kind: "local", model: model?.label ?? site.model ?? null }; + } + case "openai": + return { + kind: "openai", + model: resolveOpenAiModel(kind, site.model), + missingKey: !site.hasApiKey && !input.envOverrides[speechSiteFieldPath(siteId, "apiKey")], + }; + case "unknown": + return { kind: "unknown", provider: site.id }; + } +} + +export type LocalModelState = + | { kind: "installed" } + | { kind: "not_installed" } + | { kind: "downloading"; percent: number | null } + | { kind: "extracting" } + | { kind: "failed"; error: string }; + +export function getLocalModelState(model: LocalSpeechModel): LocalModelState { + switch (model.status) { + case "installed": + return { kind: "installed" }; + case "downloading": { + const total = model.totalBytes ?? 0; + const received = model.receivedBytes ?? 0; + return { + kind: "downloading", + percent: total > 0 ? Math.min(100, Math.floor((received / total) * 100)) : null, + }; + } + case "extracting": + return { kind: "extracting" }; + case "failed": + return { kind: "failed", error: model.error ?? "" }; + default: + return { kind: "not_installed" }; + } +} + +export function isLocalModelBusy(model: LocalSpeechModel): boolean { + return model.status === "downloading" || model.status === "extracting"; +} + +export function formatModelSize(bytes: number): string { + const megabytes = bytes / 1_000_000; + if (megabytes >= 1000) return `${(megabytes / 1000).toFixed(1)} GB`; + return `${Math.round(megabytes)} MB`; +} + +// Multilingual models list close to a hundred languages; past this many the tooltip names +// the first ones and counts the rest. +const MAX_LISTED_LANGUAGES = 10; + +export function formatLanguages(input: { + languages: readonly string[]; + locale: string; + formatMore: (languages: string, count: number) => string; +}): string { + const names = languageNames(input.locale); + const listed = input.languages + .slice(0, MAX_LISTED_LANGUAGES) + .map((code) => names?.of(code) ?? code.toUpperCase()) + .join(", "); + const hidden = input.languages.length - MAX_LISTED_LANGUAGES; + return hidden > 0 ? input.formatMore(listed, hidden) : listed; +} + +// Hermes ships without Intl.DisplayNames; the language code is the fallback label there. +function languageNames(locale: string): Intl.DisplayNames | null { + if (typeof Intl.DisplayNames !== "function") return null; + return new Intl.DisplayNames([locale], { type: "language" }); +} diff --git a/packages/app/src/utils/host-routes.ts b/packages/app/src/utils/host-routes.ts index cb828f9e5a..c5913366d2 100644 --- a/packages/app/src/utils/host-routes.ts +++ b/packages/app/src/utils/host-routes.ts @@ -518,6 +518,7 @@ export const HOST_SECTION_SLUGS = [ "pair-device", "agents", "metadata", + "voice", "workspaces", "providers", "usage", diff --git a/packages/app/vitest.config.ts b/packages/app/vitest.config.ts index 2b56646b2a..3254fc5e0c 100644 --- a/packages/app/vitest.config.ts +++ b/packages/app/vitest.config.ts @@ -161,6 +161,7 @@ export default defineConfig({ "i18next", "@marijn/find-cluster-break", "tiny-invariant", + "react/jsx-dev-runtime", "react-native-gesture-handler > hoist-non-react-statics", "react-native-gesture-handler > invariant", ], @@ -171,6 +172,8 @@ export default defineConfig({ "react-native-keyboard-controller", ], }, + // babel-preset-expo compiles JSX with the automatic runtime, so app modules don't import React. + esbuild: { jsx: "automatic" }, // The globals a React Native bundler defines, which esbuild is no longer there to supply for // the package excluded above. define: { diff --git a/packages/client/src/daemon-client.ts b/packages/client/src/daemon-client.ts index 524df56704..59d928283f 100644 --- a/packages/client/src/daemon-client.ts +++ b/packages/client/src/daemon-client.ts @@ -19,6 +19,7 @@ import { CreationClient } from "./creation/index.js"; import type { CreationSnapshot } from "@getpaseo/protocol/messages"; import type { z } from "zod"; import type { SessionEventSubscription } from "@getpaseo/protocol/messages"; +import type { LocalSpeechModel } from "@getpaseo/protocol/speech/rpc-schemas"; import { CLIENT_CAPS, type ClientCapability } from "@getpaseo/protocol/client-capabilities"; import type { AgentAttentionNotificationPayload } from "@getpaseo/protocol/agent-attention-notification"; import { MAX_WEBSOCKET_MESSAGE_BYTES } from "@getpaseo/protocol/websocket-message-limit"; @@ -5547,6 +5548,34 @@ export class DaemonClient { }); } + async listLocalSpeechModels(requestId?: string): Promise { + const payload = await this.sendCorrelatedSessionRequest({ + requestId, + message: { type: "speech.local_models.list.request" }, + responseType: "speech.local_models.list.response", + }); + if (payload.error) throw new Error(payload.error); + return payload.models; + } + + async downloadLocalSpeechModel(modelId: string, requestId?: string): Promise { + const payload = await this.sendCorrelatedSessionRequest({ + requestId, + message: { type: "speech.local_models.download.request", modelId }, + responseType: "speech.local_models.download.response", + }); + if (payload.error) throw new Error(payload.error); + } + + async deleteLocalSpeechModel(modelId: string, requestId?: string): Promise { + const payload = await this.sendCorrelatedSessionRequest({ + requestId, + message: { type: "speech.local_models.delete.request", modelId }, + responseType: "speech.local_models.delete.response", + }); + if (payload.error) throw new Error(payload.error); + } + sendBrowserAutomationExecuteResponse(response: BrowserAutomationExecuteResponse): void { this.sendSessionMessageStrict(response); } diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index bc158a6322..3034598f1e 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -82,6 +82,16 @@ import { ScheduleRunOnceResponseSchema, ScheduleUpdateResponseSchema, } from "./schedule/rpc-schemas.js"; +import { + SpeechLocalModelsDeleteRequestSchema, + SpeechLocalModelsDeleteResponseSchema, + SpeechLocalModelsDownloadRequestSchema, + SpeechLocalModelsDownloadResponseSchema, + SpeechLocalModelsListRequestSchema, + SpeechLocalModelsListResponseSchema, + SpeechSettingsPatchSchema, + SpeechSettingsSchema, +} from "./speech/rpc-schemas.js"; import { LoopRunRequestSchema, LoopListRequestSchema, @@ -233,6 +243,9 @@ export const MutableDaemonConfigSchema = z skills: z.object({ selection: AgentSkillSelectionSchema.optional() }).strict().optional(), pluginsEnabled: z.boolean().optional(), plugins: z.record(PluginIdSchema, PluginSourceSchema).optional(), + // COMPAT(speechSettings): added in v0.12.0, optional because older daemons omit it. + features: SpeechSettingsSchema.optional(), + envOverrides: z.record(z.string(), z.string()).optional(), }) .passthrough(); @@ -254,6 +267,7 @@ export const MutableDaemonConfigPatchSchema = z agentProfiles: z.array(AgentProfileSchema).optional(), pluginsEnabled: z.boolean().optional(), plugins: z.record(PluginIdSchema, PluginSourceSchema).optional(), + features: SpeechSettingsPatchSchema.optional(), }) .partial() .passthrough(); @@ -3440,6 +3454,9 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [ ChatWaitRequestSchema, ScheduleCreateRequestSchema, ScheduleListRequestSchema, + SpeechLocalModelsListRequestSchema, + SpeechLocalModelsDownloadRequestSchema, + SpeechLocalModelsDeleteRequestSchema, ScheduleInspectRequestSchema, ScheduleLogsRequestSchema, SchedulePauseRequestSchema, @@ -3674,6 +3691,8 @@ export const ServerInfoStatusPayloadSchema = z daemonStatusRpc: z.boolean().optional(), // COMPAT(daemonConfigReload): added in v0.4.0, remove gate after 2027-02-14. daemonConfigReload: z.boolean().optional(), + // COMPAT(speechSettings): added in v0.12.0, remove gate after 2027-04-18. + speechSettings: z.boolean().optional(), // COMPAT(relayConfig): added in v0.2.6, remove gate after 2027-01-31. relayConfig: z.boolean().optional(), // COMPAT(pushTokenRevocation): added in v0.3.2, remove gate after 2027-02-10. @@ -7152,6 +7171,9 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [ ChatWaitResponseSchema, ScheduleCreateResponseSchema, ScheduleListResponseSchema, + SpeechLocalModelsListResponseSchema, + SpeechLocalModelsDownloadResponseSchema, + SpeechLocalModelsDeleteResponseSchema, ScheduleInspectResponseSchema, ScheduleLogsResponseSchema, SchedulePauseResponseSchema, diff --git a/packages/protocol/src/messages.wire-compat.test.ts b/packages/protocol/src/messages.wire-compat.test.ts index d3b3ce26df..d6b2bc02ff 100644 --- a/packages/protocol/src/messages.wire-compat.test.ts +++ b/packages/protocol/src/messages.wire-compat.test.ts @@ -1,6 +1,8 @@ import { describe, expect, test } from "vitest"; import { z } from "zod"; import { + MutableDaemonConfigSchema, + MutableDaemonConfigPatchSchema, UsageReportEntrySchema, AgentSnapshotPayloadSchema, AgentTimelineItemPayloadSchema, @@ -525,3 +527,50 @@ test("released setup clients parse empty combined logs and retain command output }).detail.log, ).toBe("old daemon combined output"); }); + +test("local STT language survives wire reads and patches", () => { + const patch = { + features: { + dictation: { stt: { provider: "local", language: "fr" } }, + voiceMode: { stt: { provider: "local", language: null } }, + }, + }; + expect(MutableDaemonConfigPatchSchema.parse(patch)).toEqual(patch); +}); + +test("speech config reads remain compatible with clients before features and future providers", () => { + const oldSchema = MutableDaemonConfigSchema.omit({ features: true, envOverrides: true }); + const oldRead = oldSchema.parse({ + providers: {}, + relay: { enabled: false }, + mcp: { enabled: true, injectIntoAgents: true }, + }); + const read = { + ...oldRead, + features: { + dictation: { enabled: true, stt: { provider: "local", language: "fr" } }, + voiceMode: { + enabled: false, + stt: { provider: "future", model: "future-model", region: "eu" }, + tts: { provider: "openai", hasApiKey: false }, + }, + }, + envOverrides: { "features.voiceMode.stt.provider": "PASEO_VOICE_STT_PROVIDER" }, + }; + expect(oldSchema.parse(read)).toEqual(read); + expect(MutableDaemonConfigSchema.parse(oldRead)).toEqual(oldRead); + expect(MutableDaemonConfigSchema.parse(read).features?.dictation.stt).toEqual( + read.features.dictation.stt, + ); + expect(MutableDaemonConfigSchema.parse(read).features?.voiceMode.stt).toEqual( + read.features.voiceMode.stt, + ); + const oldPatchSchema = MutableDaemonConfigPatchSchema.omit({ features: true }); + const oldPatch = oldPatchSchema.parse({ relay: { enabled: true } }); + expect(MutableDaemonConfigPatchSchema.parse(oldPatch)).toEqual(oldPatch); + expect( + MutableDaemonConfigPatchSchema.parse({ + features: { voiceMode: { stt: { provider: "future", region: "eu" } } }, + }).features?.voiceMode?.stt, + ).toEqual({ provider: "future", region: "eu" }); +}); diff --git a/packages/protocol/src/speech/rpc-schemas.ts b/packages/protocol/src/speech/rpc-schemas.ts new file mode 100644 index 0000000000..437560c7e8 --- /dev/null +++ b/packages/protocol/src/speech/rpc-schemas.ts @@ -0,0 +1,202 @@ +import { z } from "zod"; + +// Per-site settings mirror config.json. Unknown providers remain parseable by older +// clients; the feature UI decides whether it knows how to edit them. +const ModelFields = { model: z.string().optional() }; +const OpenAiReadFields = { + ...ModelFields, + hasApiKey: z.boolean(), + baseUrl: z.string().optional(), +}; +const SttReadFields = { + language: z.string().optional(), + confidenceThreshold: z.number().optional(), +}; +const LocalTtsFields = { speakerId: z.number().int().optional(), speed: z.number().optional() }; + +export const SpeechSttSettingsSchema = z.union([ + z + .object({ provider: z.literal("local"), ...ModelFields, language: z.string().optional() }) + .passthrough(), + z.object({ provider: z.literal("openai"), ...OpenAiReadFields, ...SttReadFields }).passthrough(), + z.object({ provider: z.string(), ...ModelFields }).passthrough(), +]); +export const SpeechTtsSettingsSchema = z.union([ + z.object({ provider: z.literal("local"), ...ModelFields, ...LocalTtsFields }).passthrough(), + z + .object({ provider: z.literal("openai"), ...OpenAiReadFields, voice: z.string().optional() }) + .passthrough(), + z.object({ provider: z.string(), ...ModelFields }).passthrough(), +]); + +export const SpeechSettingsSchema = z + .object({ + dictation: z.object({ enabled: z.boolean(), stt: SpeechSttSettingsSchema }).passthrough(), + voiceMode: z + .object({ + enabled: z.boolean(), + stt: SpeechSttSettingsSchema, + tts: SpeechTtsSettingsSchema, + llm: z + .object({ provider: z.string().optional(), model: z.string().optional() }) + .passthrough() + .optional(), + turnDetection: z.object({ provider: z.string().optional() }).passthrough().optional(), + }) + .passthrough(), + }) + .passthrough(); + +const ModelPatchFields = { model: z.string().nullable().optional() }; +const OpenAiPatchFields = { + ...ModelPatchFields, + apiKey: z.string().nullable().optional(), + baseUrl: z.string().nullable().optional(), +}; +const SttPatchFields = { + language: z.string().nullable().optional(), + confidenceThreshold: z.number().nullable().optional(), +}; +const LocalTtsPatchFields = { + speakerId: z.number().int().nullable().optional(), + speed: z.number().nullable().optional(), +}; +const SpeechSttSettingsPatchSchema = z.union([ + z + .object({ + provider: z.literal("local"), + ...ModelPatchFields, + language: z.string().nullable().optional(), + }) + .passthrough(), + z + .object({ provider: z.literal("openai"), ...OpenAiPatchFields, ...SttPatchFields }) + .passthrough(), + z.object({ provider: z.string().nullable() }).passthrough(), + z + .object({ provider: z.undefined().optional(), ...OpenAiPatchFields, ...SttPatchFields }) + .passthrough(), +]); +const SpeechTtsSettingsPatchSchema = z.union([ + z + .object({ provider: z.literal("local"), ...ModelPatchFields, ...LocalTtsPatchFields }) + .passthrough(), + z + .object({ + provider: z.literal("openai"), + ...OpenAiPatchFields, + voice: z.string().nullable().optional(), + }) + .passthrough(), + z.object({ provider: z.string().nullable() }).passthrough(), + z + .object({ + provider: z.undefined().optional(), + ...OpenAiPatchFields, + ...LocalTtsPatchFields, + voice: z.string().nullable().optional(), + }) + .passthrough(), +]); +export const SpeechSettingsPatchSchema = z + .object({ + dictation: z + .object({ + enabled: z.boolean().nullable().optional(), + stt: SpeechSttSettingsPatchSchema.optional(), + }) + .passthrough() + .optional(), + voiceMode: z + .object({ + enabled: z.boolean().nullable().optional(), + stt: SpeechSttSettingsPatchSchema.optional(), + tts: SpeechTtsSettingsPatchSchema.optional(), + llm: z + .object({ + provider: z.string().nullable().optional(), + model: z.string().nullable().optional(), + }) + .passthrough() + .optional(), + turnDetection: z + .object({ provider: z.string().nullable().optional() }) + .passthrough() + .optional(), + }) + .passthrough() + .optional(), + }) + .passthrough(); + +export type SpeechSettings = z.infer; +export type SpeechSettingsPatch = z.infer; + +// --------------------------------------------------------------------------- +// Local speech models: catalog, install state, download, delete. +// --------------------------------------------------------------------------- + +export const LocalSpeechModelSchema = z + .object({ + id: z.string(), + // "stt" or "tts". + kind: z.string(), + label: z.string(), + description: z.string(), + languages: z.array(z.string()), + downloadSizeBytes: z.number(), + isDefault: z.boolean(), + // Selected by an enabled feature; the daemon keeps it installed. + inUse: z.boolean(), + // "installed" | "not_installed" | "downloading" | "extracting" | "failed". + status: z.string(), + receivedBytes: z.number().optional(), + totalBytes: z.number().optional(), + error: z.string().optional(), + }) + .passthrough(); + +export type LocalSpeechModel = z.infer; + +export const SpeechLocalModelsListRequestSchema = z.object({ + type: z.literal("speech.local_models.list.request"), + requestId: z.string(), +}); + +export const SpeechLocalModelsDownloadRequestSchema = z.object({ + type: z.literal("speech.local_models.download.request"), + requestId: z.string(), + modelId: z.string(), +}); + +export const SpeechLocalModelsDeleteRequestSchema = z.object({ + type: z.literal("speech.local_models.delete.request"), + requestId: z.string(), + modelId: z.string(), +}); + +export const SpeechLocalModelsListResponseSchema = z.object({ + type: z.literal("speech.local_models.list.response"), + payload: z.object({ + requestId: z.string(), + models: z.array(LocalSpeechModelSchema), + error: z.string().nullable(), + }), +}); + +// Resolves once the download starts; poll the list for progress. +export const SpeechLocalModelsDownloadResponseSchema = z.object({ + type: z.literal("speech.local_models.download.response"), + payload: z.object({ + requestId: z.string(), + error: z.string().nullable(), + }), +}); + +export const SpeechLocalModelsDeleteResponseSchema = z.object({ + type: z.literal("speech.local_models.delete.response"), + payload: z.object({ + requestId: z.string(), + error: z.string().nullable(), + }), +}); diff --git a/packages/server/src/server/agent/stt-manager.test.ts b/packages/server/src/server/agent/stt-manager.test.ts index e3f6fb7d9c..5b1c036bc7 100644 --- a/packages/server/src/server/agent/stt-manager.test.ts +++ b/packages/server/src/server/agent/stt-manager.test.ts @@ -1,9 +1,12 @@ +import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; import { describe, expect, it } from "vitest"; import pino from "pino"; import { EventEmitter } from "node:events"; import { STTManager } from "./stt-manager.js"; -import { PersistedConfigSchema } from "../persisted-config.js"; +import { loadPersistedConfig } from "../persisted-config.js"; import { resolveSpeechConfig } from "../speech/speech-config-resolver.js"; import type { SpeechToTextProvider, @@ -97,12 +100,18 @@ class SequencedFakeStt implements SpeechToTextProvider { describe("STTManager", () => { function resolveVoiceLanguage(params: { env?: NodeJS.ProcessEnv; persisted?: unknown }): string { - const result = resolveSpeechConfig({ - paseoHome: "/tmp/paseo-home", - env: params.env ?? ({} as NodeJS.ProcessEnv), - persisted: PersistedConfigSchema.parse(params.persisted ?? {}), - }); - return result.speech.sttLanguages.voice; + const home = mkdtempSync(path.join(tmpdir(), "stt-language-")); + try { + writeFileSync(path.join(home, "config.json"), JSON.stringify(params.persisted ?? {})); + const result = resolveSpeechConfig({ + paseoHome: home, + env: params.env ?? {}, + persisted: loadPersistedConfig(home), + }); + return result.speech.sttLanguages.voice; + } finally { + rmSync(home, { recursive: true, force: true }); + } } async function transcribeWithResolvedVoiceLanguage(params: { diff --git a/packages/server/src/server/authorization/operation-permissions.ts b/packages/server/src/server/authorization/operation-permissions.ts index 80599a74a3..f7a5b17857 100644 --- a/packages/server/src/server/authorization/operation-permissions.ts +++ b/packages/server/src/server/authorization/operation-permissions.ts @@ -182,6 +182,9 @@ const INBOUND_PERMISSION = { set_agent_model_request: "workspace.write", set_agent_thinking_request: "workspace.write", set_daemon_config_request: "daemon.manage", + "speech.local_models.list.request": "daemon.read", + "speech.local_models.download.request": "daemon.manage", + "speech.local_models.delete.request": "daemon.manage", set_voice_mode: "workspace.write", shutdown_server_request: "daemon.manage", start_workspace_script_request: "workspace.write", @@ -417,6 +420,9 @@ const OUTBOUND_PERMISSION = { set_agent_model_response: "workspace.write", set_agent_thinking_response: "workspace.write", set_daemon_config_response: "daemon.manage", + "speech.local_models.list.response": "daemon.read", + "speech.local_models.download.response": "daemon.manage", + "speech.local_models.delete.response": "daemon.manage", set_voice_mode_response: "workspace.write", start_workspace_script_response: "workspace.write", stash_list_response: "workspace.read", diff --git a/packages/server/src/server/bootstrap.ts b/packages/server/src/server/bootstrap.ts index 9419694043..2eeccfb653 100644 --- a/packages/server/src/server/bootstrap.ts +++ b/packages/server/src/server/bootstrap.ts @@ -138,6 +138,7 @@ import type { OpenAiSpeechProviderConfig } from "./speech/providers/openai/confi import type { LocalSpeechProviderConfig } from "./speech/providers/local/config.js"; import type { RequestedSpeechProviders } from "./speech/speech-types.js"; import { createSpeechService } from "./speech/speech-runtime.js"; +import { createSpeechSettingsOwner } from "./speech/speech-settings.js"; import { AgentManager } from "./agent/agent-manager.js"; import { AgentStorage } from "./agent/agent-storage.js"; import { attachAgentStoragePersistence } from "./persistence-hooks.js"; @@ -379,6 +380,8 @@ export interface PaseoSpeechSttLanguages { export interface PaseoSpeechConfig { providers: RequestedSpeechProviders; + // Where local models live, whether or not a feature currently uses the local provider. + localModelsDir: string; sttLanguages?: PaseoSpeechSttLanguages; local?: PaseoLocalSpeechConfig; } @@ -555,6 +558,10 @@ function createInitialRelayConfig(config: PaseoDaemonConfig): MutableDaemonConfi }; } +function resolveReloadEnv(config: PaseoDaemonConfig): NodeJS.ProcessEnv { + return config.configReload?.env ?? process.env; +} + function createInitialMutableDaemonConfig(config: PaseoDaemonConfig): MutableDaemonConfig { const providers = config.providerOverrides ?? {}; @@ -615,13 +622,24 @@ export async function createPaseoDaemon( const elapsed = () => `${(performance.now() - bootstrapStart).toFixed(0)}ms`; const daemonVersion = config.daemonVersion ?? resolveDaemonVersion(import.meta.url); const initialMutableConfig = createInitialMutableDaemonConfig(config); + const speechService = createSpeechService({ + logger, + openaiConfig: config.openai, + speechConfig: config.speech, + }); + logger.info({ elapsed: elapsed() }, "Speech service created"); const daemonConfigStore = new DaemonConfigStore(config.paseoHome, initialMutableConfig, logger, { relayEnabledMutable: config.relayEnabledMutable ?? true, startupPersisted: config.configReload?.startupPersisted, + speech: createSpeechSettingsOwner({ + paseoHome: config.paseoHome, + env: resolveReloadEnv(config), + speechService, + }), reloadSource: { resolve: (persisted) => { const reloaded = resolveConfigFromPersisted(config.paseoHome, persisted, { - env: config.configReload?.env ?? process.env, + env: resolveReloadEnv(config), cli: config.configReload?.cli, relayEnabledFallback: config.configReload?.relayEnabledFallback, }); @@ -1677,13 +1695,6 @@ export async function createPaseoDaemon( logger.info({ route: agentMcpRoute, enabled: mcpEnabled }, "Agent MCP route mounted"); } - const speechService = createSpeechService({ - logger, - openaiConfig: config.openai, - speechConfig: config.speech, - }); - logger.info({ elapsed: elapsed() }, "Speech service created"); - logger.info({ elapsed: elapsed() }, "Bootstrap complete, ready to start listening"); const start = async () => { diff --git a/packages/server/src/server/config.test.ts b/packages/server/src/server/config.test.ts index 864ad14100..e8c5f2faa0 100644 --- a/packages/server/src/server/config.test.ts +++ b/packages/server/src/server/config.test.ts @@ -115,9 +115,13 @@ describe("server config", () => { name: "OpenAI speech providers", providers: { dictation: "openai", voiceStt: "openai", voiceTts: "openai" }, expected: [ + "features.dictation.stt.apiKey", "features.dictation.stt.confidenceThreshold", "features.dictation.stt.model", + "features.voiceMode.stt.apiKey", + "features.voiceMode.stt.confidenceThreshold", "features.voiceMode.stt.model", + "features.voiceMode.tts.apiKey", "features.voiceMode.tts.model", "features.voiceMode.tts.voice", ], @@ -126,8 +130,9 @@ describe("server config", () => { name: "mixed local and OpenAI speech providers", providers: { dictation: "local", voiceStt: "openai", voiceTts: "local" }, expected: [ - "features.dictation.stt.confidenceThreshold", "features.dictation.stt.model", + "features.voiceMode.stt.apiKey", + "features.voiceMode.stt.confidenceThreshold", "features.voiceMode.stt.model", "features.voiceMode.tts.model", ], diff --git a/packages/server/src/server/config.ts b/packages/server/src/server/config.ts index 8187ce03c6..74a8037d07 100644 --- a/packages/server/src/server/config.ts +++ b/packages/server/src/server/config.ts @@ -22,7 +22,7 @@ import { ProviderOverrideSchema } from "./agent/provider-launch-config.js"; import { AgentProviderSchema } from "@getpaseo/protocol/provider-manifest"; import { hashDaemonPassword } from "./auth.js"; import { resolveSpeechConfig } from "./speech/speech-config-resolver.js"; -import type { RequestedSpeechProviders } from "./speech/speech-types.js"; +import { readSpeechSettings } from "./speech/speech-settings.js"; import { mergeHostnames, parseHostnamesEnv, type HostnamesConfig } from "./hostnames.js"; import { resolveGitProcessPolicy } from "../utils/git-process-scheduler.js"; @@ -614,7 +614,7 @@ export function resolveConfigFromPersisted( persisted.agents?.providers as Record | undefined, ); - const overrideControlledPaths = resolveOverrideControlledPaths(env, cli, speech.providers); + const overrideControlledPaths = resolveOverrideControlledPaths(env, cli, persisted); return { listen, @@ -692,13 +692,13 @@ function parsePositiveGitOverride(value: string | undefined): boolean { function resolveOverrideControlledPaths( env: NodeJS.ProcessEnv, cli: CliConfigOverrides | undefined, - speechProviders: RequestedSpeechProviders, + persisted: PersistedConfig, ): string[] { return Array.from( new Set([ ...resolveDaemonOverrideControlledPaths(env, cli), ...resolveLogOverrideControlledPaths(env), - ...resolveSpeechOverrideControlledPaths(env, speechProviders), + ...resolveSpeechOverrideControlledPaths(env, persisted), ]), ).sort(); } @@ -807,67 +807,12 @@ function resolveLogOverrideControlledPaths(env: NodeJS.ProcessEnv): string[] { return paths; } -function isEnabledSpeechProvider( - provider: RequestedSpeechProviders[keyof RequestedSpeechProviders], - expected: "local" | "openai", -): boolean { - return provider.enabled !== false && provider.provider === expected; -} - function resolveSpeechOverrideControlledPaths( env: NodeJS.ProcessEnv, - providers: RequestedSpeechProviders, + persisted: PersistedConfig, ): string[] { - const paths: string[] = []; - const add = (envName: string, ...configPaths: string[]) => { - if (env[envName] !== undefined) paths.push(...configPaths); - }; - - add("PASEO_DICTATION_ENABLED", "features.dictation.enabled"); - add("PASEO_DICTATION_STT_PROVIDER", "features.dictation.stt.provider"); - if ( - env.PASEO_DICTATION_LOCAL_STT_MODEL !== undefined && - isEnabledSpeechProvider(providers.dictationStt, "local") - ) { - paths.push("features.dictation.stt.model"); - } - add("PASEO_DICTATION_LANGUAGE", "features.dictation.stt.language"); - add("PASEO_VOICE_MODE_ENABLED", "features.voiceMode.enabled"); - add("PASEO_VOICE_LLM_PROVIDER", "features.voiceMode.llm.provider"); - add("PASEO_VOICE_STT_PROVIDER", "features.voiceMode.stt.provider"); - if ( - env.PASEO_VOICE_LOCAL_STT_MODEL !== undefined && - isEnabledSpeechProvider(providers.voiceStt, "local") - ) { - paths.push("features.voiceMode.stt.model"); - } - add("PASEO_VOICE_LANGUAGE", "features.voiceMode.stt.language"); - add("PASEO_VOICE_TURN_DETECTION_PROVIDER", "features.voiceMode.turnDetection.provider"); - add("PASEO_VOICE_TTS_PROVIDER", "features.voiceMode.tts.provider"); - if ( - env.PASEO_VOICE_LOCAL_TTS_MODEL !== undefined && - isEnabledSpeechProvider(providers.voiceTts, "local") - ) { - paths.push("features.voiceMode.tts.model"); - } - add("PASEO_VOICE_LOCAL_TTS_SPEAKER_ID", "features.voiceMode.tts.speakerId"); - add("PASEO_VOICE_LOCAL_TTS_SPEED", "features.voiceMode.tts.speed"); - add("PASEO_LOCAL_MODELS_DIR", "providers.local.modelsDir"); - const openAiDictationStt = isEnabledSpeechProvider(providers.dictationStt, "openai"); - const openAiVoiceStt = isEnabledSpeechProvider(providers.voiceStt, "openai"); - if (env.STT_CONFIDENCE_THRESHOLD !== undefined && (openAiDictationStt || openAiVoiceStt)) { - paths.push("features.dictation.stt.confidenceThreshold"); - } - if (env.STT_MODEL !== undefined) { - if (openAiDictationStt) paths.push("features.dictation.stt.model"); - if (openAiVoiceStt) paths.push("features.voiceMode.stt.model"); - } - if (isEnabledSpeechProvider(providers.voiceTts, "openai")) { - add("TTS_MODEL", "features.voiceMode.tts.model"); - add("TTS_VOICE", "features.voiceMode.tts.voice"); - } - if (env.PASEO_DICTATION_LANGUAGE !== undefined && env.PASEO_VOICE_LANGUAGE === undefined) { - paths.push("features.voiceMode.stt.language"); - } + const paths = Object.keys(readSpeechSettings(persisted, env).envOverrides); + if (env.PASEO_VOICE_LLM_PROVIDER !== undefined) paths.push("features.voiceMode.llm.provider"); + if (env.PASEO_LOCAL_MODELS_DIR !== undefined) paths.push("providers.local.modelsDir"); return paths; } diff --git a/packages/server/src/server/daemon-client.e2e.test.ts b/packages/server/src/server/daemon-client.e2e.test.ts index b6518d773d..a442dfe6a9 100644 --- a/packages/server/src/server/daemon-client.e2e.test.ts +++ b/packages/server/src/server/daemon-client.e2e.test.ts @@ -1318,9 +1318,9 @@ test("emits disabled voice capability reasons on fresh daemon startup", async () expect(voice).toBeTruthy(); expect(voice?.dictation.enabled).toBe(false); - expect(voice?.dictation.reason).toBe("Dictation is disabled in daemon config."); + expect(voice?.dictation.reason).toBe("Dictation is off. Turn it on in Settings > Voice."); expect(voice?.voice.enabled).toBe(false); - expect(voice?.voice.reason).toBe("Realtime voice is disabled in daemon config."); + expect(voice?.voice.reason).toBe("Voice mode is off. Turn it on in Settings > Voice."); } finally { await client.close().catch(() => undefined); await isolatedCtx.cleanup(); diff --git a/packages/server/src/server/daemon-config-store.test.ts b/packages/server/src/server/daemon-config-store.test.ts index 095ae3b14b..f4c1a02de9 100644 --- a/packages/server/src/server/daemon-config-store.test.ts +++ b/packages/server/src/server/daemon-config-store.test.ts @@ -1,4 +1,4 @@ -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { afterEach, describe, expect, test } from "vitest"; @@ -6,6 +6,7 @@ import { afterEach, describe, expect, test } from "vitest"; import { DaemonConfigStore, applyMutableProviderConfigToOverrides } from "./daemon-config-store.js"; import { loadConfig } from "./config.js"; import { loadPersistedConfig } from "./persisted-config.js"; +import { readSpeechSettings } from "./speech/speech-settings.js"; import type { PersistedConfig } from "./persisted-config.js"; import type { MutableDaemonConfig } from "@getpaseo/protocol/messages"; @@ -1284,3 +1285,239 @@ describe("DaemonConfigStore reload", () => { }); }); }); + +describe("DaemonConfigStore speech settings", () => { + const tempDirs: string[] = []; + + afterEach(() => { + for (const dir of tempDirs) rmSync(dir, { recursive: true, force: true }); + }); + + function createSpeechStore(initialPersisted?: unknown, env: NodeJS.ProcessEnv = {}) { + const paseoHome = mkdtempSync(path.join(tmpdir(), "paseo-daemon-config-speech-")); + tempDirs.push(paseoHome); + if (initialPersisted) { + writeFileSync( + path.join(paseoHome, "config.json"), + `${JSON.stringify(initialPersisted, null, 2)}\n`, + ); + } + const persisted = loadPersistedConfig(paseoHome); + const applied: PersistedConfig[] = []; + const speech = { + read: (next: PersistedConfig) => readSpeechSettings(next, env), + apply: (next: PersistedConfig) => applied.push(next), + }; + const store = new DaemonConfigStore(paseoHome, reloadableConfig(persisted), undefined, { + speech, + reloadSource: { + resolve: (next) => ({ mutable: reloadableConfig(next), overrideControlledPaths: [] }), + }, + }); + return { paseoHome, store, applied, persisted }; + } + + test("reads, patches, and clears local STT language without losing it on other saves", () => { + const { paseoHome, store } = createSpeechStore({ + features: { dictation: { stt: { language: "fr" } } }, + }); + expect(store.get().features?.dictation.stt).toEqual({ provider: "local", language: "fr" }); + store.patch({ features: { voiceMode: { enabled: true } } }); + expect(loadPersistedConfig(paseoHome).features?.dictation?.stt).toEqual({ + provider: "local", + language: "fr", + }); + const patched = store.patch({ + features: { dictation: { stt: { provider: "local", language: "de" } } }, + }); + expect(patched.features?.dictation.stt).toEqual({ provider: "local", language: "de" }); + store.patch({ features: { dictation: { stt: { language: null } } } }); + expect(loadPersistedConfig(paseoHome).features?.dictation?.stt).toEqual({ provider: "local" }); + }); + + test("reports language env overrides for both local STT sites", () => { + const { store } = createSpeechStore( + {}, + { PASEO_DICTATION_LANGUAGE: "fr", PASEO_VOICE_LANGUAGE: "de" }, + ); + expect(store.get().envOverrides).toMatchObject({ + "features.dictation.stt.language": "PASEO_DICTATION_LANGUAGE", + "features.voiceMode.stt.language": "PASEO_VOICE_LANGUAGE", + }); + }); + + test("keeps voice mode off until it is turned on", () => { + const { paseoHome, store } = createSpeechStore(); + + expect(store.get().features?.dictation.enabled).toBe(true); + expect(store.get().features?.voiceMode.enabled).toBe(false); + + const result = store.patch({ features: { voiceMode: { enabled: true } } }); + + expect(result.features?.voiceMode.enabled).toBe(true); + expect(loadPersistedConfig(paseoHome).features?.voiceMode?.enabled).toBe(true); + }); + + test("stores the OpenAI key without ever returning it", () => { + const { paseoHome, store, applied } = createSpeechStore(); + + const result = store.patch({ + features: { dictation: { stt: { provider: "openai", apiKey: " sk-test " } } }, + }); + + expect(result.features?.dictation.stt).toEqual({ provider: "openai", hasApiKey: true }); + expect(JSON.stringify(result)).not.toContain("sk-test"); + expect(loadPersistedConfig(paseoHome).features?.dictation?.stt).toMatchObject({ + apiKey: "sk-test", + }); + expect(applied).toHaveLength(1); + }); + + test("applies a replaced key even though the visible settings do not change", () => { + const { store, applied } = createSpeechStore({ + version: 1, + features: { dictation: { stt: { provider: "openai", apiKey: "sk-old" } } }, + }); + + store.patch({ features: { dictation: { stt: { apiKey: "sk-new" } } } }); + + expect(applied.map((next) => next.features?.dictation?.stt)).toEqual([ + { provider: "openai", apiKey: "sk-new" }, + ]); + }); + + test("switching provider clears the previous provider's model", () => { + const { paseoHome, store } = createSpeechStore({ + version: 1, + features: { dictation: { stt: { provider: "local", model: "parakeet-tdt-0.6b-v3-int8" } } }, + }); + + const result = store.patch({ features: { dictation: { stt: { provider: "openai" } } } }); + + expect(result.features?.dictation.stt).toEqual({ provider: "openai", hasApiKey: false }); + expect(loadPersistedConfig(paseoHome).features?.dictation?.stt).toEqual({ + provider: "openai", + }); + }); + + test("rejects a local model id outside the catalog without persisting it", () => { + const { paseoHome, store, applied } = createSpeechStore(); + + expect(() => + store.patch({ features: { voiceMode: { tts: { provider: "local", model: "nope" } } } }), + ).toThrow("Unknown local voice model: nope"); + expect(loadPersistedConfig(paseoHome).features?.voiceMode).toBeUndefined(); + expect(applied).toEqual([]); + }); + + test("reload applies hand-edited speech settings without a restart", () => { + const { paseoHome, store, applied, persisted } = createSpeechStore(); + writeFileSync( + path.join(paseoHome, "config.json"), + `${JSON.stringify({ ...persisted, features: { voiceMode: { enabled: false } } }, null, 2)}\n`, + ); + + const result = store.reload(); + + expect(result.appliedPaths).toContain("features.voiceMode"); + expect(result.restartRequiredPaths).toEqual([]); + expect(store.get().features?.voiceMode.enabled).toBe(false); + expect(applied).toHaveLength(1); + }); + test("merges same-provider fields and replaces the whole variant when provider changes", () => { + const { paseoHome, store } = createSpeechStore(); + store.patch({ + features: { + voiceMode: { + stt: { provider: "openai", apiKey: "secret", baseUrl: "https://site/v1", model: "first" }, + }, + }, + }); + store.patch({ features: { voiceMode: { stt: { model: "second", baseUrl: null } } } }); + expect(loadPersistedConfig(paseoHome).features?.voiceMode?.stt).toEqual({ + provider: "openai", + apiKey: "secret", + model: "second", + }); + store.patch({ features: { voiceMode: { stt: { provider: "openai", model: "third" } } } }); + expect(store.get().features?.voiceMode.stt).toEqual({ + provider: "openai", + model: "third", + hasApiKey: true, + }); + store.patch({ features: { voiceMode: { stt: { apiKey: "new-secret" } } } }); + store.patch({ features: { voiceMode: { stt: { provider: "local" } } } }); + store.patch({ features: { voiceMode: { stt: { provider: "openai" } } } }); + expect(store.get().features?.voiceMode.stt).toEqual({ provider: "openai", hasApiKey: false }); + }); + + test("keeps a saved OpenAI key when a full variant patch omits the write-only key", () => { + const { paseoHome, store } = createSpeechStore({ + features: { voiceMode: { stt: { provider: "openai", apiKey: "saved-secret" } } }, + }); + const result = store.patch({ + features: { voiceMode: { stt: { provider: "openai", model: "whisper-1" } } }, + }); + expect(result.features?.voiceMode.stt).toEqual({ + provider: "openai", + model: "whisper-1", + hasApiKey: true, + }); + expect(loadPersistedConfig(paseoHome).features?.voiceMode?.stt).toEqual({ + provider: "openai", + apiKey: "saved-secret", + model: "whisper-1", + }); + expect(JSON.stringify(result)).not.toContain("saved-secret"); + }); + + test("loads a legacy host, redacts its key and writes the normalized config after any save", () => { + const { paseoHome, store } = createSpeechStore({ + providers: { openai: { apiKey: "legacy-secret", stt: { baseUrl: "https://old/v1" } } }, + features: { voiceMode: { enabled: true, stt: { provider: "openai" } } }, + }); + expect(store.get().features?.voiceMode.stt).toEqual({ + provider: "openai", + baseUrl: "https://old/v1", + hasApiKey: true, + }); + expect(JSON.stringify(store.get())).not.toContain("legacy-secret"); + store.patch({ autoArchiveAfterMerge: true }); + const disk = JSON.parse(readFileSync(path.join(paseoHome, "config.json"), "utf8")); + expect(disk.providers).not.toHaveProperty("openai"); + expect(disk.features.voiceMode.stt.apiKey).toBe("legacy-secret"); + }); + + test("reports env overrides and removes fallback provenance after saving a key", () => { + const { store } = createSpeechStore( + { features: { voiceMode: { stt: { provider: "openai", model: "configured" } } } }, + { + PASEO_VOICE_STT_PROVIDER: "local", + OPENAI_API_KEY: "env-secret", + }, + ); + expect(store.get().features?.voiceMode.stt.provider).toBe("local"); + expect(store.get().envOverrides).toEqual({ + "features.voiceMode.stt.provider": "PASEO_VOICE_STT_PROVIDER", + }); + const other = createSpeechStore( + { features: { voiceMode: { stt: { provider: "openai" } } } }, + { + OPENAI_API_KEY: "env-secret", + OPENAI_STT_BASE_URL: "https://env/v1", + STT_MODEL: "override", + }, + ).store; + expect(other.get().envOverrides).toEqual({ + "features.voiceMode.stt.apiKey": "OPENAI_API_KEY", + "features.voiceMode.stt.baseUrl": "OPENAI_STT_BASE_URL", + "features.voiceMode.stt.model": "STT_MODEL", + }); + expect(other.get().features?.voiceMode.stt.hasApiKey).toBe(false); + other.patch({ + features: { voiceMode: { stt: { apiKey: "saved-secret", baseUrl: "https://saved/v1" } } }, + }); + expect(other.get().envOverrides).toEqual({ "features.voiceMode.stt.model": "STT_MODEL" }); + expect(JSON.stringify(other.get())).not.toContain("secret"); + }); +}); diff --git a/packages/server/src/server/daemon-config-store.ts b/packages/server/src/server/daemon-config-store.ts index 2241193e50..51957e15f6 100644 --- a/packages/server/src/server/daemon-config-store.ts +++ b/packages/server/src/server/daemon-config-store.ts @@ -9,6 +9,8 @@ import { MutableDaemonConfigPatchSchema, } from "@getpaseo/protocol/messages"; import type { AgentSkillSelection } from "@getpaseo/protocol/messages"; +import type { SpeechSettingsPatch } from "@getpaseo/protocol/speech/rpc-schemas"; +import { mergeSpeechSettingsPatch, type SpeechSettingsOwner } from "./speech/speech-settings.js"; export type { MutableDaemonConfig, MutableDaemonConfigPatch } from "@getpaseo/protocol/messages"; @@ -32,8 +34,11 @@ interface SupportedMutableConfigPatch { skills?: MutableDaemonConfig["skills"]; pluginsEnabled?: boolean; plugins?: MutableDaemonConfig["plugins"]; + features?: SpeechSettingsPatch; } +const SPEECH_PERSISTED_PATHS = ["features.dictation", "features.voiceMode"]; + interface LoggerLike { child(bindings: Record): LoggerLike; info(...args: unknown[]): void; @@ -296,6 +301,7 @@ function pickSupportedPatchFields(patch: MutableDaemonConfigPatch): SupportedMut ...(patch.agentProfiles !== undefined ? { agentProfiles: patch.agentProfiles } : {}), ...(patch.pluginsEnabled !== undefined ? { pluginsEnabled: patch.pluginsEnabled } : {}), ...(patch.plugins !== undefined ? { plugins: patch.plugins } : {}), + ...(patch.features !== undefined ? { features: patch.features } : {}), }; } @@ -338,6 +344,7 @@ export class DaemonConfigStore { private readonly relayEnabledMutable: boolean; private readonly reloadSource: DaemonConfigReloadSource | undefined; private readonly startupPersisted: PersistedConfig; + private readonly speechOwner: SpeechSettingsOwner | undefined; private lastKnownPersisted: PersistedConfig; constructor( @@ -348,18 +355,21 @@ export class DaemonConfigStore { relayEnabledMutable?: boolean; reloadSource?: DaemonConfigReloadSource; startupPersisted?: PersistedConfig; + speech?: SpeechSettingsOwner; } = {}, ) { this.paseoHome = paseoHome; this.logger = getLogger(logger); + this.relayEnabledMutable = options.relayEnabledMutable ?? true; + this.reloadSource = options.reloadSource; + this.speechOwner = options.speech; + this.startupPersisted = options.startupPersisted ?? loadPersistedConfig(paseoHome, this.logger); + this.lastKnownPersisted = this.startupPersisted; this.current = MutableDaemonConfigSchema.parse({ ...initial, relay: initial.relay ?? { enabled: true }, + ...this.readSpeech(this.startupPersisted), }); - this.relayEnabledMutable = options.relayEnabledMutable ?? true; - this.reloadSource = options.reloadSource; - this.startupPersisted = options.startupPersisted ?? loadPersistedConfig(paseoHome, this.logger); - this.lastKnownPersisted = this.startupPersisted; } public get(): MutableDaemonConfig { @@ -381,9 +391,11 @@ export class DaemonConfigStore { "Relay is controlled by a daemon launch override. Remove PASEO_RELAY_ENABLED or the relay CLI flag before changing it here.", ); } - const { removeProviders = [], ...configPatch } = parsedPatch; + const { removeProviders = [], ...patch } = parsedPatch; + const { features: speechPatch, ...configPatch } = patch; const removedProviders = Array.from(new Set(removeProviders)); const merged = deepMerge(this.current, configPatch); + if (speechPatch !== undefined) Object.assign(merged, this.readPatchedSpeech(speechPatch)); if (parsedPatch.skills?.selection !== undefined) { merged.skills = { selection: parsedPatch.skills.selection }; } @@ -397,30 +409,51 @@ export class DaemonConfigStore { const configChanged = !isEqualValue(this.current, next); - if (!configChanged && removedProviders.length === 0) { + // A replaced API key leaves the speech view unchanged, so a speech patch always persists. + if (!configChanged && removedProviders.length === 0 && speechPatch === undefined) { return this.current; } const { previous: persistedBeforePatch, knownNext } = this.persistConfig( - configPatch, + patch, removedProviders, ); - if (!configChanged) { - this.lastKnownPersisted = knownNext; - return this.current; - } - - try { - this.applyReplacement(next, { removedProviders }); - this.lastKnownPersisted = knownNext; - } catch (error) { - savePersistedConfig(this.paseoHome, persistedBeforePatch, this.logger); - throw error; + const speechChanged = this.speechPersistedChanged(this.lastKnownPersisted, knownNext); + if (configChanged) { + try { + this.applyReplacement(next, { removedProviders }); + } catch (error) { + savePersistedConfig(this.paseoHome, persistedBeforePatch, this.logger); + throw error; + } } + this.lastKnownPersisted = knownNext; + if (speechChanged) this.speechOwner?.apply(knownNext); return this.current; } + private readSpeech( + persisted: PersistedConfig, + ): Pick { + return this.speechOwner ? this.speechOwner.read(persisted) : {}; + } + + private readPatchedSpeech( + speechPatch: SpeechSettingsPatch, + ): Pick { + if (!this.speechOwner) { + throw new Error("Speech settings are unavailable for this daemon instance"); + } + return this.speechOwner.read(mergeSpeechSettingsPatch(this.lastKnownPersisted, speechPatch)); + } + + private speechPersistedChanged(previous: PersistedConfig, next: PersistedConfig): boolean { + return diffPaths(previous, next).some((path) => + SPEECH_PERSISTED_PATHS.some((owner) => pathBelongsTo(path, owner)), + ); + } + public reload(): DaemonConfigReloadResult { if (!this.reloadSource) { throw new Error("Daemon config reload is unavailable for this daemon instance"); @@ -433,6 +466,7 @@ export class DaemonConfigStore { const desired = MutableDaemonConfigSchema.parse({ ...resolved.mutable, plugins: this.current.plugins, + ...this.readSpeech(persisted), }); const changedSinceLastApply = diffPaths(this.lastKnownPersisted, persisted); const overrideControlledPaths = compactOwnedPaths( @@ -441,7 +475,7 @@ export class DaemonConfigStore { ), resolved.overrideControlledPaths, ); - const appliedPaths = RELOADABLE_PATHS.filter((persistedPath) => { + const appliedPaths: string[] = RELOADABLE_PATHS.filter((persistedPath) => { if (resolved.overrideControlledPaths.some((owner) => pathBelongsTo(persistedPath, owner))) { return false; } @@ -458,6 +492,8 @@ export class DaemonConfigStore { diffPaths(this.startupPersisted, persisted).filter((path) => { if (path === "$schema" || path === "version") return false; if (RELOADABLE_PATHS.some((owner) => pathBelongsTo(path, owner))) return false; + if (this.speechOwner && SPEECH_PERSISTED_PATHS.some((owner) => pathBelongsTo(path, owner))) + return false; return !resolved.overrideControlledPaths.some((owner) => pathBelongsTo(path, owner)); }), [], @@ -466,8 +502,17 @@ export class DaemonConfigStore { const removedProviders = Object.keys(this.current.providers).filter( (provider) => !(provider in desired.providers), ); + const speechChanged = this.speechPersistedChanged(this.lastKnownPersisted, persisted); this.applyReplacement(desired, { removedProviders }); this.lastKnownPersisted = persisted; + if (speechChanged && this.speechOwner) { + this.speechOwner.apply(persisted); + appliedPaths.push( + ...SPEECH_PERSISTED_PATHS.filter((owner) => + changedSinceLastApply.some((path) => pathBelongsTo(path, owner)), + ), + ); + } return { appliedPaths: [...appliedPaths].sort(), @@ -604,8 +649,11 @@ function mergeMutablePatchIntoPersistedConfig(params: { const { persisted, patch, removeProviders, persistRelayEnabled } = params; const daemon = mergeMutableDaemonPatch(persisted.daemon, patch, persistRelayEnabled); const agents = mergeMutableAgentPatch(persisted.agents, patch, removeProviders); + const withSpeech = patch.features + ? mergeSpeechSettingsPatch(persisted, patch.features) + : persisted; return { - ...persisted, + ...withSpeech, ...(patch.pluginsEnabled !== undefined ? { pluginsEnabled: patch.pluginsEnabled } : {}), ...(patch.plugins !== undefined ? { plugins: patch.plugins } : {}), ...(daemon ? { daemon } : { daemon: undefined }), diff --git a/packages/server/src/server/dictation/dictation-stream-manager.test.ts b/packages/server/src/server/dictation/dictation-stream-manager.test.ts index 975d6677b8..1d258553ca 100644 --- a/packages/server/src/server/dictation/dictation-stream-manager.test.ts +++ b/packages/server/src/server/dictation/dictation-stream-manager.test.ts @@ -1,9 +1,12 @@ +import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; import { EventEmitter } from "node:events"; import pino from "pino"; import { DictationStreamManager } from "./dictation-stream-manager.js"; -import { PersistedConfigSchema } from "../persisted-config.js"; +import { loadPersistedConfig } from "../persisted-config.js"; import { resolveSpeechConfig } from "../speech/speech-config-resolver.js"; import type { SpeechToTextProvider, @@ -131,12 +134,18 @@ describe("DictationStreamManager (provider-agnostic provider)", () => { env?: NodeJS.ProcessEnv; persisted?: unknown; }): string { - const result = resolveSpeechConfig({ - paseoHome: "/tmp/paseo-home", - env: params.env ?? ({} as NodeJS.ProcessEnv), - persisted: PersistedConfigSchema.parse(params.persisted ?? {}), - }); - return result.speech.sttLanguages.dictation; + const home = mkdtempSync(path.join(tmpdir(), "stt-language-")); + try { + writeFileSync(path.join(home, "config.json"), JSON.stringify(params.persisted ?? {})); + const result = resolveSpeechConfig({ + paseoHome: home, + env: params.env ?? {}, + persisted: loadPersistedConfig(home), + }); + return result.speech.sttLanguages.dictation; + } finally { + rmSync(home, { recursive: true, force: true }); + } } async function startWithResolvedDictationLanguage(params: { diff --git a/packages/server/src/server/persisted-config-edit.test.ts b/packages/server/src/server/persisted-config-edit.test.ts index 4b4bf4c0db..c838601255 100644 --- a/packages/server/src/server/persisted-config-edit.test.ts +++ b/packages/server/src/server/persisted-config-edit.test.ts @@ -43,3 +43,19 @@ test("configuration edits validate before writing and preserve unrelated setting await rm(root, { recursive: true, force: true }); } }); + +test("configuration paths edit fields inside speech provider variants", async () => { + const home = await mkdtemp(path.join(tmpdir(), "paseo-speech-edit-")); + try { + editPersistedConfig(home, "features.voiceMode.stt", { value: { provider: "openai" } }); + editPersistedConfig(home, "features.voiceMode.stt.apiKey", { value: "site-secret" }); + const config = readPersistedConfig(home); + expect(getPersistedConfigValue(config, "features.voiceMode.stt.apiKey")).toBe("site-secret"); + editPersistedConfig(home, "features.voiceMode.stt.apiKey", { unset: true }); + expect( + getPersistedConfigValue(readPersistedConfig(home), "features.voiceMode.stt.apiKey"), + ).toBeUndefined(); + } finally { + await rm(home, { recursive: true, force: true }); + } +}); diff --git a/packages/server/src/server/persisted-config.test.ts b/packages/server/src/server/persisted-config.test.ts index 6b23a6f365..019bcbb0f8 100644 --- a/packages/server/src/server/persisted-config.test.ts +++ b/packages/server/src/server/persisted-config.test.ts @@ -1,3 +1,4 @@ +import { resolveSpeechConfig } from "./speech/speech-config-resolver.js"; import { chmodSync, lstatSync, @@ -149,26 +150,33 @@ describe("PersistedConfigSchema worktrees config", () => { }); describe("PersistedConfigSchema provider credentials", () => { - test("accepts separate OpenAI STT and TTS credentials", () => { + test("accepts separate inline STT and TTS credentials", () => { const parsed = PersistedConfigSchema.parse({ - providers: { - openai: { + features: { + voiceMode: { stt: { + provider: "openai", apiKey: " stt-secret ", baseUrl: " https://stt.example.com/v1 ", }, tts: { + provider: "openai", apiKey: " tts-secret ", baseUrl: " https://tts.example.com/v1 ", }, }, }, }); - - expect(parsed.providers?.openai?.stt?.apiKey).toBe("stt-secret"); - expect(parsed.providers?.openai?.stt?.baseUrl).toBe("https://stt.example.com/v1"); - expect(parsed.providers?.openai?.tts?.apiKey).toBe("tts-secret"); - expect(parsed.providers?.openai?.tts?.baseUrl).toBe("https://tts.example.com/v1"); + expect(parsed.features?.voiceMode?.stt).toEqual({ + provider: "openai", + apiKey: "stt-secret", + baseUrl: "https://stt.example.com/v1", + }); + expect(parsed.features?.voiceMode?.tts).toEqual({ + provider: "openai", + apiKey: "tts-secret", + baseUrl: "https://tts.example.com/v1", + }); }); }); @@ -660,19 +668,21 @@ describe("PersistedConfigSchema voice mode config", () => { features: { dictation: { stt: { + provider: "openai", language: " fr ", }, }, voiceMode: { stt: { + provider: "openai", language: " de ", }, }, }, }); - expect(parsed.features?.dictation?.stt?.language).toBe("fr"); - expect(parsed.features?.voiceMode?.stt?.language).toBe("de"); + expect(parsed.features?.dictation?.stt).toMatchObject({ language: "fr" }); + expect(parsed.features?.voiceMode?.stt).toMatchObject({ language: "de" }); }); test("accepts a voice and model from a self-hosted OpenAI-compatible server", () => { @@ -685,7 +695,7 @@ describe("PersistedConfigSchema voice mode config", () => { }); expect(parsed.features?.voiceMode?.tts?.model).toBe("kokoro-v1:Q8_0"); - expect(parsed.features?.voiceMode?.tts?.voice).toBe("aiden"); + expect(parsed.features?.voiceMode?.tts).toMatchObject({ voice: "aiden" }); }); }); @@ -754,10 +764,7 @@ describe("loadPersistedConfig", () => { const config = loadPersistedConfig(home); - expect(config.providers?.openai?.apiKey).toBe("global-key"); - expect((config.providers?.openai as Record)?.voice).toBeUndefined(); - expect(config.providers?.openai?.stt).toBeUndefined(); - expect(config.providers?.openai?.tts).toBeUndefined(); + expect(config.providers).not.toHaveProperty("openai"); } finally { rmSync(home, { recursive: true, force: true }); } @@ -852,11 +859,7 @@ describe.skipIf(process.platform === "win32")("persisted config file permissions const home = path.join(parent, "home"); try { savePersistedConfig(home, { - providers: { - openai: { - apiKey: "secret", - }, - }, + features: { dictation: { stt: { provider: "openai", apiKey: "secret" } } }, }); expect(modeOf(home)).toBe(PRIVATE_DIRECTORY_MODE); @@ -898,3 +901,173 @@ describe.skipIf(process.platform === "win32")( }); }, ); + +describe("speech provider config normalization", () => { + test.each([undefined, "local"])( + "preserves local STT language on load and save (provider: %s)", + (provider) => { + const home = createTempHome(); + try { + writeFileSync( + path.join(home, "config.json"), + JSON.stringify({ + features: { dictation: { stt: { provider, language: "fr" } } }, + }), + ); + const loaded = loadPersistedConfig(home); + expect(loaded.features?.dictation?.stt).toEqual({ provider: "local", language: "fr" }); + expect( + resolveSpeechConfig({ paseoHome: home, env: {}, persisted: loaded }).speech.sttLanguages + .dictation, + ).toBe("fr"); + savePersistedConfig(home, loaded); + expect(loadPersistedConfig(home).features?.dictation?.stt).toEqual({ + provider: "local", + language: "fr", + }); + expect( + JSON.parse(readFileSync(path.join(home, "config.json"), "utf8")).features.dictation.stt, + ).toEqual({ provider: "local", language: "fr" }); + } finally { + rmSync(home, { recursive: true, force: true }); + } + }, + ); + + test("loads and resolves legacy fields ignored by each site's provider", () => { + const home = mkdtempSync(path.join(tmpdir(), "speech-unused-options-")); + try { + const legacy = { + features: { + dictation: { stt: { provider: "local", language: "fr", confidenceThreshold: -1 } }, + voiceMode: { + enabled: true, + tts: { provider: "local", voice: "alloy", speakerId: 3, speed: 1.2 }, + }, + }, + }; + writeFileSync(path.join(home, "config.json"), JSON.stringify(legacy)); + const local = loadPersistedConfig(home); + expect(local.features?.dictation?.stt).toEqual({ provider: "local", language: "fr" }); + expect(local.features?.voiceMode?.tts).toEqual({ + provider: "local", + speakerId: 3, + speed: 1.2, + }); + expect( + resolveSpeechConfig({ paseoHome: home, env: {}, persisted: local }).speech.local?.models, + ).toMatchObject({ voiceTtsSpeakerId: 3, voiceTtsSpeed: 1.2 }); + writeFileSync( + path.join(home, "config.json"), + JSON.stringify({ + features: { + voiceMode: { + enabled: true, + tts: { provider: "openai", apiKey: "key", voice: "alloy", speakerId: 3, speed: 1.2 }, + }, + }, + }), + ); + const openai = loadPersistedConfig(home); + expect(openai.features?.voiceMode?.tts).toEqual({ + provider: "openai", + apiKey: "key", + voice: "alloy", + }); + expect( + resolveSpeechConfig({ paseoHome: home, env: {}, persisted: openai }).openai?.tts, + ).toMatchObject({ apiKey: "key", voice: "alloy" }); + } finally { + rmSync(home, { recursive: true, force: true }); + } + }); + + test("warns with the path, never the discarded legacy key", () => { + const home = mkdtempSync(path.join(tmpdir(), "speech-warning-")); + try { + writeFileSync( + path.join(home, "config.json"), + JSON.stringify({ + providers: { openai: { apiKey: "discarded-secret" } }, + features: { voiceMode: { enabled: true, tts: { provider: "local" } } }, + }), + ); + const warnings: unknown[][] = []; + const logger = { + child: () => logger, + info: () => {}, + warn: (...args: unknown[]) => { + warnings.push(args); + }, + }; + const config = loadPersistedConfig(home, logger); + expect(config.providers).not.toHaveProperty("openai"); + expect(warnings).toHaveLength(1); + expect(JSON.stringify(warnings)).toContain("providers.openai.apiKey"); + expect(JSON.stringify(warnings)).toContain("no use site in config.json selects OpenAI"); + const resolved = resolveSpeechConfig({ + paseoHome: home, + persisted: config, + env: { PASEO_VOICE_TTS_PROVIDER: "openai" }, + }); + expect(resolved.speech.providers.voiceTts.provider).toBe("openai"); + expect(resolved.openai).toBeUndefined(); + expect(JSON.stringify(warnings)).not.toContain("discarded-secret"); + } finally { + rmSync(home, { recursive: true, force: true }); + } + }); + + test("folds legacy endpoint credentials into OpenAI sites on load and saves inline", () => { + const home = mkdtempSync(path.join(tmpdir(), "speech-normalize-")); + try { + writeFileSync( + path.join(home, "config.json"), + JSON.stringify({ + providers: { + openai: { + apiKey: "global-key", + baseUrl: "https://global/v1", + stt: { apiKey: "stt-key" }, + }, + }, + features: { + dictation: { stt: { model: "whisper-base", language: "en" } }, + voiceMode: { + enabled: true, + stt: { provider: "OPENAI", baseUrl: "https://site/v1" }, + tts: { provider: "openai" }, + }, + }, + }), + ); + const config = loadPersistedConfig(home); + expect(config.features?.dictation?.stt).toEqual({ + provider: "local", + model: "whisper-base", + language: "en", + }); + expect(config.features?.voiceMode?.stt).toEqual({ + provider: "openai", + apiKey: "stt-key", + baseUrl: "https://site/v1", + }); + expect(config.features?.voiceMode?.tts).toEqual({ + provider: "openai", + apiKey: "global-key", + baseUrl: "https://global/v1", + }); + expect(config.providers).not.toHaveProperty("openai"); + const resolved = resolveSpeechConfig({ paseoHome: home, env: {}, persisted: config }); + expect(resolved.openai?.stt?.apiKey).toBe("stt-key"); + expect(resolved.speech.providers.voiceStt).toMatchObject({ + provider: "openai", + enabled: true, + }); + savePersistedConfig(home, config); + expect(JSON.parse(readFileSync(path.join(home, "config.json"), "utf8"))).toEqual(config); + } finally { + rmSync(home, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/server/src/server/persisted-config.ts b/packages/server/src/server/persisted-config.ts index 8b99a1ac45..c6c3f9c7e1 100644 --- a/packages/server/src/server/persisted-config.ts +++ b/packages/server/src/server/persisted-config.ts @@ -49,22 +49,6 @@ const LogConfigSchema = z }) .strict(); -const OpenAiSpeechEndpointSchema = z - .object({ - apiKey: z.string().trim().min(1).optional(), - baseUrl: z.string().trim().min(1).optional(), - }) - .strict(); - -const OpenAiProviderSchema = z - .object({ - apiKey: z.string().min(1).optional(), - baseUrl: z.string().trim().min(1).optional(), - stt: OpenAiSpeechEndpointSchema.optional(), - tts: OpenAiSpeechEndpointSchema.optional(), - }) - .strict(); - const LocalSpeechProviderSchema = z .object({ modelsDir: z.string().min(1).optional(), @@ -73,7 +57,6 @@ const LocalSpeechProviderSchema = z const ProvidersSchema = z .object({ - openai: OpenAiProviderSchema.optional(), local: LocalSpeechProviderSchema.optional(), }) .strict(); @@ -101,18 +84,54 @@ const SpeechProviderIdSchema = z .toLowerCase() .pipe(z.enum(["openai", "local"])); +const SpeechModelSchema = z.string().min(1).optional(); +const OpenAiConnectionFields = { + apiKey: z.string().trim().min(1).optional(), + baseUrl: z.string().trim().min(1).optional(), +}; + +export const SpeechSttConfigSchema = z.discriminatedUnion("provider", [ + z + .object({ + provider: z.literal("local"), + model: SpeechModelSchema, + language: z.string().trim().min(1).optional(), + }) + .strict(), + z + .object({ + provider: z.literal("openai"), + ...OpenAiConnectionFields, + model: SpeechModelSchema, + language: z.string().trim().min(1).optional(), + confidenceThreshold: z.number().optional(), + }) + .strict(), +]); + +export const SpeechTtsConfigSchema = z.discriminatedUnion("provider", [ + z + .object({ + provider: z.literal("local"), + model: SpeechModelSchema, + speakerId: z.number().int().optional(), + speed: z.number().optional(), + }) + .strict(), + z + .object({ + provider: z.literal("openai"), + ...OpenAiConnectionFields, + model: SpeechModelSchema, + voice: z.string().trim().min(1).optional(), + }) + .strict(), +]); + const FeatureDictationSchema = z .object({ enabled: z.boolean().optional(), - stt: z - .object({ - provider: SpeechProviderIdSchema.optional(), - model: z.string().min(1).optional(), - language: z.string().trim().min(1).optional(), - confidenceThreshold: z.number().optional(), - }) - .strict() - .optional(), + stt: SpeechSttConfigSchema.optional(), }) .strict(); @@ -126,31 +145,14 @@ const FeatureVoiceModeSchema = z }) .strict() .optional(), - stt: z - .object({ - provider: SpeechProviderIdSchema.optional(), - model: z.string().min(1).optional(), - language: z.string().trim().min(1).optional(), - }) - .strict() - .optional(), + stt: SpeechSttConfigSchema.optional(), turnDetection: z .object({ provider: SpeechProviderIdSchema.optional(), }) .strict() .optional(), - tts: z - .object({ - provider: SpeechProviderIdSchema.optional(), - model: z.string().min(1).optional(), - // Free-form: self-hosted OpenAI-compatible servers expose their own voice names. - voice: z.string().trim().min(1).optional(), - speakerId: z.number().int().optional(), - speed: z.number().optional(), - }) - .strict() - .optional(), + tts: SpeechTtsConfigSchema.optional(), }) .strict(); @@ -387,6 +389,7 @@ const DEFAULT_PERSISTED_CONFIG = PersistedConfigSchema.parse({ interface LoggerLike { child(bindings: Record): LoggerLike; info(...args: unknown[]): void; + warn?(...args: unknown[]): void; } function getConfigPath(paseoHome: string): string { @@ -397,45 +400,96 @@ function getLogger(logger: LoggerLike | undefined): LoggerLike | undefined { return logger?.child({ module: "config" }); } -// Removed config fields are stripped before parsing so the strict schema does not -// reject a config written by an older release. The stripped values are discarded, -// not migrated — there is no back-compat for the removed `providers.openai.voice` -// block (use `providers.openai.stt` / `providers.openai.tts`). -function stripRemovedConfigFields(parsed: unknown): unknown { - if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { - return parsed; +function isConfigRecord(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +function configRecord(value: unknown): Record | undefined { + return isConfigRecord(value) ? value : undefined; +} + +// COMPAT(speechProviderConfig): added in v0.12.0, remove after 2027-04-26. +// Fold shared credentials once at the file boundary; consumers see only the strict +// per-site shape. Never include credential values in diagnostics. +function normalizeSpeechProviderConfig(parsed: unknown, logger?: LoggerLike): unknown { + if (!isConfigRecord(parsed)) return parsed; + const root = structuredClone(parsed); + const providers = configRecord(root.providers); + const legacy = configRecord(providers?.openai); + const features = configRecord(root.features); + const foldedKeys = new Set(); + for (const [feature, kind] of [ + ["dictation", "stt"], + ["voiceMode", "stt"], + ["voiceMode", "tts"], + ] as const) { + const site = configRecord(configRecord(features?.[feature])?.[kind]); + if (site) normalizeSpeechSite(site, kind, legacy, foldedKeys); } - - const root = { ...(parsed as Record) }; - const providers = root.providers; - if (!providers || typeof providers !== "object" || Array.isArray(providers)) { - return root; + if (legacy) warnDiscardedSpeechKeys(legacy, foldedKeys, logger); + if (providers) { + delete providers.openai; + const local = configRecord(providers.local); + if (local) delete local.autoDownload; } - - const providersRecord = { ...(providers as Record) }; - - const local = providersRecord.local; - if (local && typeof local === "object" && !Array.isArray(local)) { - const localRecord = { ...(local as Record) }; - delete localRecord.autoDownload; - providersRecord.local = localRecord; - } - - const openai = providersRecord.openai; - if (openai && typeof openai === "object" && !Array.isArray(openai)) { - const openaiRecord = { ...(openai as Record) }; - // COMPAT(openaiVoiceConfig): added 2026-06-30, remove after 2026-12-30. - // Drop a `providers.openai.voice` block left by an older release so the strict - // schema doesn't reject it. The value is discarded, not migrated — there is no - // back-compat; configure `providers.openai.stt` / `providers.openai.tts` instead. - delete openaiRecord.voice; - providersRecord.openai = openaiRecord; - } - - root.providers = providersRecord; return root; } +function normalizeSpeechSite( + site: Record, + kind: "stt" | "tts", + legacy: Record | undefined, + foldedKeys: Set, +) { + site.provider = + typeof site.provider === "string" + ? site.provider.trim().toLowerCase() + : (site.provider ?? "local"); + if (kind === "stt" && site.provider === "local") { + delete site.confidenceThreshold; + } + if (kind === "tts") { + if (site.provider === "local") delete site.voice; + if (site.provider === "openai") { + delete site.speakerId; + delete site.speed; + } + } + if (site.provider !== "openai" || !legacy) return; + const endpoint = configRecord(legacy[kind]); + for (const field of ["apiKey", "baseUrl"] as const) { + if (site[field] !== undefined) continue; + if (endpoint?.[field] !== undefined) { + site[field] = endpoint[field]; + foldedKeys.add(`providers.openai.${kind}.${field}`); + } else if (legacy[field] !== undefined) { + site[field] = legacy[field]; + foldedKeys.add(`providers.openai.${field}`); + } + } +} + +function warnDiscardedSpeechKeys( + legacy: Record, + foldedKeys: Set, + logger?: LoggerLike, +) { + const keys = [ + ["providers.openai.apiKey", legacy.apiKey], + ...["stt", "tts"].map((kind) => [ + `providers.openai.${kind}.apiKey`, + configRecord(legacy[kind])?.apiKey, + ]), + ] as const; + for (const [keyPath, key] of keys) { + if (key && typeof keyPath === "string" && !foldedKeys.has(keyPath)) { + const message = `Dropped ${keyPath}: no use site in config.json selects OpenAI; re-enter it when selecting OpenAI.`; + if (logger?.warn) logger.warn(message); + else console.warn(message); + } + } +} + export function loadPersistedConfig(paseoHome: string, logger?: LoggerLike): PersistedConfig { const log = getLogger(logger); const configPath = getConfigPath(paseoHome); @@ -464,7 +518,7 @@ export function loadPersistedConfig(paseoHome: string, logger?: LoggerLike): Per }); } - const config = parseConfigFile(configPath, raw); + const config = parseConfigFile(configPath, raw, log); log?.info(`Loaded from ${configPath}`); return config; } @@ -486,7 +540,7 @@ export function readPersistedConfig( return parseConfigFile(configPath, raw); } -function parseConfigFile(configPath: string, raw: string): PersistedConfig { +function parseConfigFile(configPath: string, raw: string, logger?: LoggerLike): PersistedConfig { let parsed: unknown; try { parsed = parseConfigText(raw); @@ -497,7 +551,7 @@ function parseConfigFile(configPath: string, raw: string): PersistedConfig { }); } - const result = PersistedConfigSchema.safeParse(stripRemovedConfigFields(parsed)); + const result = PersistedConfigSchema.safeParse(normalizeSpeechProviderConfig(parsed, logger)); if (!result.success) { const issues = result.error.issues .map((i) => ` - ${i.path.join(".")}: ${i.message}`) @@ -525,6 +579,12 @@ function configPathParts(field: string): string[] { schema instanceof z.ZodPipe ) schema = (schema instanceof z.ZodPipe ? schema.in : schema.unwrap()) as z.ZodType; + if (schema instanceof z.ZodUnion) { + const variant = schema.options.find( + (option) => option instanceof z.ZodObject && Object.hasOwn(option.shape, part), + ); + if (variant instanceof z.ZodObject) schema = variant; + } if (!(schema instanceof z.ZodObject) || !Object.hasOwn(schema.shape, part)) { throw new Error( `Unknown configuration path: ${field}. Replace its containing object with JSON for dynamic keys.`, diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index 9a2b2c0820..f573b1dd95 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -182,6 +182,10 @@ import { import { ScheduleSession } from "./session/schedule/schedule-session.js"; import { ProviderCatalogSession } from "./session/provider/provider-catalog-session.js"; import { UsageSession } from "./session/usage/usage-session.js"; +import { + SpeechModelsSession, + type SpeechModelsSessionOptions, +} from "./session/speech/speech-models-session.js"; import { WorkspaceFilesSession } from "./session/files/workspace-files-session.js"; import { AgentConfigSession } from "./session/agent-config/agent-config-session.js"; import { ProjectConfigSession } from "./session/project-config/project-config-session.js"; @@ -528,6 +532,7 @@ export interface SessionOptions { stt: Resolvable; sttLanguage?: string; tts: Resolvable; + speechModels?: SpeechModelsSessionOptions["runtime"]; terminalManager: TerminalManager | null; providerSnapshotManager: ProviderSnapshotManager; hubExecutionAgents?: HubExecutionAgents; @@ -811,6 +816,7 @@ export class Session { private readonly scheduleSession: ScheduleSession; private readonly providerCatalogSession: ProviderCatalogSession; private readonly usageSession: UsageSession; + private readonly speechModelsSession: SpeechModelsSession; private readonly workspaceFilesSession: WorkspaceFilesSession; private readonly agentConfigSession: AgentConfigSession; private readonly projectConfigSession: ProjectConfigSession; @@ -861,6 +867,7 @@ export class Session { stt, sttLanguage, tts, + speechModels, terminalManager, providerSnapshotManager, serviceProxy, @@ -1037,6 +1044,10 @@ export class Session { runtime: pluginRuntime, logger: this.sessionLogger, }); + this.speechModelsSession = new SpeechModelsSession({ + emit: (msg) => this.emit(msg), + runtime: speechModels, + }); this.agentConfigSession = new AgentConfigSession({ host: { emit: (msg) => this.emit(msg), @@ -2421,8 +2432,7 @@ export class Session { this.dispatchOrchestrationSkillsMessage(msg) ?? this.dispatchPluginDirectoryMessage(msg) ?? this.dispatchPluginMessage(msg) ?? - this.dispatchTerminalMessage(msg) ?? - this.dispatchScheduleMessage(msg) ?? + this.dispatchHostServiceMessage(msg) ?? this.dispatchMiscMessage(msg); if (promise) await promise; } @@ -2438,6 +2448,14 @@ export class Session { ); } + private dispatchHostServiceMessage(msg: SessionInboundMessage): Promise | undefined { + return ( + this.dispatchTerminalMessage(msg) ?? + this.dispatchScheduleMessage(msg) ?? + this.speechModelsSession.dispatch(msg) + ); + } + private dispatchWorkspaceLifecycleMessage(msg: SessionInboundMessage): Promise | undefined { return ( this.dispatchWorkspaceStateMessage(msg) ?? diff --git a/packages/server/src/server/session/speech/speech-models-session.test.ts b/packages/server/src/server/session/speech/speech-models-session.test.ts new file mode 100644 index 0000000000..9624475ad4 --- /dev/null +++ b/packages/server/src/server/session/speech/speech-models-session.test.ts @@ -0,0 +1,106 @@ +import { describe, expect, test } from "vitest"; + +import type { SessionOutboundMessage } from "../../messages.js"; +import { + listLocalSpeechModels, + type LocalSpeechModelId, +} from "../../speech/providers/local/models.js"; +import { + LocalSpeechModelInUseError, + type LocalSpeechModelStatus, +} from "../../speech/speech-runtime.js"; +import { SpeechModelsSession } from "./speech-models-session.js"; + +const [firstModel] = listLocalSpeechModels(); + +function createSession(models: LocalSpeechModelStatus[], inUse: LocalSpeechModelId[] = []) { + const emitted: SessionOutboundMessage[] = []; + const downloads: LocalSpeechModelId[] = []; + const session = new SpeechModelsSession({ + emit: (message) => emitted.push(message), + runtime: { + listLocalModels: async () => models, + downloadLocalModel: (modelId) => { + downloads.push(modelId); + }, + deleteLocalModel: async (modelId) => { + if (inUse.includes(modelId)) throw new LocalSpeechModelInUseError(modelId); + }, + }, + }); + return { session, emitted, downloads }; +} + +describe("SpeechModelsSession", () => { + test("lists catalog details and download progress before anything is installed", async () => { + const { session, emitted } = createSession([ + { + spec: firstModel, + state: { status: "downloading", receivedBytes: 10, totalBytes: 40 }, + inUse: true, + }, + ]); + + await session.dispatch({ type: "speech.local_models.list.request", requestId: "r1" }); + + expect(emitted).toEqual([ + { + type: "speech.local_models.list.response", + payload: { + requestId: "r1", + error: null, + models: [ + { + id: firstModel.id, + kind: "stt", + label: firstModel.label, + description: firstModel.description, + languages: [...firstModel.languages], + downloadSizeBytes: firstModel.downloadSizeBytes, + isDefault: true, + inUse: true, + status: "downloading", + receivedBytes: 10, + totalBytes: 40, + }, + ], + }, + }, + ]); + }); + + test("rejects a model id outside the catalog without starting a download", () => { + const { session, emitted, downloads } = createSession([]); + + void session.dispatch({ + type: "speech.local_models.download.request", + requestId: "r2", + modelId: "../../etc", + }); + + expect(downloads).toEqual([]); + expect(emitted).toEqual([ + { + type: "speech.local_models.download.response", + payload: { requestId: "r2", error: "Unknown local speech model: ../../etc" }, + }, + ]); + }); + + test("reports why an in-use model cannot be deleted", async () => { + const { session, emitted } = createSession([], [firstModel.id]); + + await session.dispatch({ + type: "speech.local_models.delete.request", + requestId: "r3", + modelId: firstModel.id, + }); + + expect(emitted).toEqual([ + { + type: "speech.local_models.delete.response", + payload: { requestId: "r3", error: new LocalSpeechModelInUseError(firstModel.id).message }, + }, + ]); + }); +}); diff --git a/packages/server/src/server/session/speech/speech-models-session.ts b/packages/server/src/server/session/speech/speech-models-session.ts new file mode 100644 index 0000000000..d987623a8d --- /dev/null +++ b/packages/server/src/server/session/speech/speech-models-session.ts @@ -0,0 +1,124 @@ +import type { LocalSpeechModel } from "@getpaseo/protocol/speech/rpc-schemas"; + +import type { SessionInboundMessage, SessionOutboundMessage } from "../../messages.js"; +import { LocalSpeechModelIdSchema } from "../../speech/providers/local/models.js"; +import type { LocalSpeechModelStatus, SpeechService } from "../../speech/speech-runtime.js"; + +type SpeechModelsRuntime = Pick< + SpeechService, + "listLocalModels" | "downloadLocalModel" | "deleteLocalModel" +>; + +export interface SpeechModelsSessionOptions { + emit(message: SessionOutboundMessage): void; + // Absent when the daemon runs without speech. + runtime?: SpeechModelsRuntime | null; +} + +export class SpeechModelsSession { + constructor(private readonly options: SpeechModelsSessionOptions) {} + + // Handles the speech.local_models.* requests; returns undefined for any other message. + dispatch(msg: SessionInboundMessage): Promise | undefined { + switch (msg.type) { + case "speech.local_models.list.request": + return this.handleList(msg); + case "speech.local_models.download.request": + this.handleDownload(msg); + return Promise.resolve(); + case "speech.local_models.delete.request": + return this.handleDelete(msg); + default: + return undefined; + } + } + + private async handleList( + msg: Extract, + ): Promise { + try { + const models = await this.requireRuntime().listLocalModels(); + this.options.emit({ + type: "speech.local_models.list.response", + payload: { requestId: msg.requestId, models: models.map(toWireModel), error: null }, + }); + } catch (error) { + this.options.emit({ + type: "speech.local_models.list.response", + payload: { requestId: msg.requestId, models: [], error: describeError(error) }, + }); + } + } + + private handleDownload( + msg: Extract, + ): void { + try { + this.requireRuntime().downloadLocalModel(parseModelId(msg.modelId)); + this.options.emit({ + type: "speech.local_models.download.response", + payload: { requestId: msg.requestId, error: null }, + }); + } catch (error) { + this.options.emit({ + type: "speech.local_models.download.response", + payload: { requestId: msg.requestId, error: describeError(error) }, + }); + } + } + + private async handleDelete( + msg: Extract, + ): Promise { + try { + await this.requireRuntime().deleteLocalModel(parseModelId(msg.modelId)); + this.options.emit({ + type: "speech.local_models.delete.response", + payload: { requestId: msg.requestId, error: null }, + }); + } catch (error) { + this.options.emit({ + type: "speech.local_models.delete.response", + payload: { requestId: msg.requestId, error: describeError(error) }, + }); + } + } + + private requireRuntime(): SpeechModelsRuntime { + if (!this.options.runtime) { + throw new Error("Speech is unavailable on this daemon"); + } + return this.options.runtime; + } +} + +function parseModelId(modelId: string) { + const parsed = LocalSpeechModelIdSchema.safeParse(modelId); + if (!parsed.success) { + throw new Error(`Unknown local speech model: ${modelId}`); + } + return parsed.data; +} + +function toWireModel(model: LocalSpeechModelStatus): LocalSpeechModel { + const { spec, state, inUse } = model; + return { + id: spec.id, + kind: spec.kind === "tts" ? "tts" : "stt", + label: spec.label, + description: spec.description, + languages: [...spec.languages], + downloadSizeBytes: spec.downloadSizeBytes, + isDefault: spec.defaultFor !== undefined, + inUse, + status: state.status, + ...(state.status === "downloading" + ? { receivedBytes: state.receivedBytes, totalBytes: state.totalBytes } + : {}), + ...(state.status === "failed" ? { error: state.error } : {}), + }; +} + +function describeError(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} diff --git a/packages/server/src/server/speech/providers/local/config.ts b/packages/server/src/server/speech/providers/local/config.ts index 8e7d500dc2..dd52537796 100644 --- a/packages/server/src/server/speech/providers/local/config.ts +++ b/packages/server/src/server/speech/providers/local/config.ts @@ -29,6 +29,7 @@ export interface LocalSpeechProviderConfig { export interface ResolvedLocalSpeechConfig { local: LocalSpeechProviderConfig | undefined; + modelsDir: string; sttLanguages: LocalSpeechSttLanguageConfig; } @@ -68,12 +69,12 @@ const LocalSpeechResolutionSchema = z.object({ function persistedLocalFeatureModel( provider: RequestedSpeechProviders[keyof RequestedSpeechProviders]["provider"], enabled: boolean | undefined, - model: string | undefined, + site: { provider: string; model?: string } | undefined, ): string | undefined { if (provider !== "local" || enabled === false) { return undefined; } - return model; + return site?.provider === "local" ? site.model : undefined; } function shouldIncludeLocalProviderConfig(params: { @@ -143,6 +144,8 @@ function buildLocalSpeechResolutionInput(params: { includeProviderConfig: boolean; }): Record { const { paseoHome, env, persisted, providers, includeProviderConfig } = params; + const tts = persisted.features?.voiceMode?.tts; + const localTts = tts?.provider === "local" ? tts : undefined; return { includeProviderConfig, modelsDir: firstDefinedValue([ @@ -155,7 +158,7 @@ function buildLocalSpeechResolutionInput(params: { persistedLocalFeatureModel( providers.dictationStt.provider, providers.dictationStt.enabled, - persisted.features?.dictation?.stt?.model, + persisted.features?.dictation?.stt, ), DEFAULT_LOCAL_STT_MODEL, ]), @@ -164,7 +167,7 @@ function buildLocalSpeechResolutionInput(params: { persistedLocalFeatureModel( providers.voiceStt.provider, providers.voiceStt.enabled, - persisted.features?.voiceMode?.stt?.model, + persisted.features?.voiceMode?.stt, ), DEFAULT_LOCAL_STT_MODEL, ]), @@ -173,18 +176,18 @@ function buildLocalSpeechResolutionInput(params: { persistedLocalFeatureModel( providers.voiceTts.provider, providers.voiceTts.enabled, - persisted.features?.voiceMode?.tts?.model, + persisted.features?.voiceMode?.tts, ), DEFAULT_LOCAL_TTS_MODEL, ]), ...buildLocalSpeechLanguageResolutionInput({ env, persisted }), voiceLocalTtsSpeakerId: firstDefinedValue([ env.PASEO_VOICE_LOCAL_TTS_SPEAKER_ID, - persisted.features?.voiceMode?.tts?.speakerId, + localTts?.speakerId, ]), voiceLocalTtsSpeed: firstDefinedValue([ env.PASEO_VOICE_LOCAL_TTS_SPEED, - persisted.features?.voiceMode?.tts?.speed, + localTts?.speed, ]), }; } @@ -200,11 +203,10 @@ export function resolveLocalSpeechConfig(params: { buildLocalSpeechResolutionInput({ ...params, includeProviderConfig }), ); - const resolvedVoiceTtsSpeakerId = - parsed.voiceLocalTtsSpeakerId ?? - (parsed.voiceLocalTtsModel === "kokoro-en-v0_19" ? 0 : undefined); + const resolvedVoiceTtsSpeakerId = parsed.voiceLocalTtsSpeakerId ?? 0; return { + modelsDir: parsed.modelsDir, sttLanguages: { dictation: parsed.dictationLanguage, voice: parsed.voiceLanguage, diff --git a/packages/server/src/server/speech/providers/local/model-library.ts b/packages/server/src/server/speech/providers/local/model-library.ts new file mode 100644 index 0000000000..4ef19e3fa9 --- /dev/null +++ b/packages/server/src/server/speech/providers/local/model-library.ts @@ -0,0 +1,137 @@ +import type { Logger } from "pino"; + +import { + deleteSherpaOnnxModel, + ensureSherpaOnnxModel, + isSherpaOnnxModelInstalled, +} from "./sherpa/model-downloader.js"; +import { + listLocalSpeechModels, + type LocalSpeechModelId, + type LocalSpeechModelSpec, +} from "./models.js"; + +export type LocalSpeechModelInstallState = + | { status: "installed" } + | { status: "not_installed" } + | { status: "downloading"; receivedBytes: number; totalBytes: number } + | { status: "extracting" } + | { status: "failed"; error: string }; + +export interface LocalSpeechModelEntry { + spec: LocalSpeechModelSpec; + state: LocalSpeechModelInstallState; +} + +type InFlightState = Extract< + LocalSpeechModelInstallState, + { status: "downloading" | "extracting" } +>; + +interface InFlightDownload { + promise: Promise; + state: InFlightState; +} + +export class LocalSpeechModelBusyError extends Error { + constructor(public readonly modelId: LocalSpeechModelId) { + super(`${modelId} is downloading. Wait for the download to finish before deleting it.`); + this.name = "LocalSpeechModelBusyError"; + } +} + +// Owns the models directory: which catalog models are installed, which are downloading, +// and the last failure per model. Concurrent downloads of one model share a single transfer. +export class LocalSpeechModelLibrary { + private readonly inFlight = new Map(); + private readonly failures = new Map(); + private readonly abortController = new AbortController(); + private readonly logger: Logger; + + constructor( + private readonly modelsDir: string, + logger: Logger, + ) { + this.logger = logger.child({ module: "speech", component: "local-model-library" }); + } + + getModelsDir(): string { + return this.modelsDir; + } + + async list(): Promise { + return Promise.all( + listLocalSpeechModels().map(async (spec) => ({ spec, state: await this.getState(spec.id) })), + ); + } + + async listMissing(modelIds: LocalSpeechModelId[]): Promise { + const installed = await Promise.all( + modelIds.map((modelId) => isSherpaOnnxModelInstalled(this.modelsDir, modelId)), + ); + return modelIds.filter((_modelId, index) => !installed[index]); + } + + download(modelId: LocalSpeechModelId): Promise { + const existing = this.inFlight.get(modelId); + if (existing) { + return existing.promise; + } + this.failures.delete(modelId); + const entry: InFlightDownload = { + state: { status: "downloading", receivedBytes: 0, totalBytes: 0 }, + promise: Promise.resolve(""), + }; + entry.promise = ensureSherpaOnnxModel({ + modelsDir: this.modelsDir, + modelId, + logger: this.logger, + signal: this.abortController.signal, + onProgress: (progress) => { + entry.state = + progress.phase === "downloading" + ? { + status: "downloading", + receivedBytes: progress.receivedBytes, + totalBytes: progress.totalBytes, + } + : { status: "extracting" }; + }, + }) + .catch((error: unknown) => { + this.failures.set(modelId, error instanceof Error ? error.message : String(error)); + throw error; + }) + .finally(() => { + this.inFlight.delete(modelId); + }); + this.inFlight.set(modelId, entry); + return entry.promise; + } + + async delete(modelId: LocalSpeechModelId): Promise { + if (this.inFlight.has(modelId)) { + throw new LocalSpeechModelBusyError(modelId); + } + this.failures.delete(modelId); + await deleteSherpaOnnxModel(this.modelsDir, modelId); + this.logger.info({ modelId }, "Deleted local speech model"); + } + + async stop(): Promise { + this.abortController.abort(); + await Promise.allSettled(Array.from(this.inFlight.values(), (entry) => entry.promise)); + } + + private async getState(modelId: LocalSpeechModelId): Promise { + const inFlight = this.inFlight.get(modelId); + if (inFlight) { + return inFlight.state; + } + if (await isSherpaOnnxModelInstalled(this.modelsDir, modelId)) { + return { status: "installed" }; + } + const failure = this.failures.get(modelId); + return failure ? { status: "failed", error: failure } : { status: "not_installed" }; + } +} diff --git a/packages/server/src/server/speech/providers/local/models.test.ts b/packages/server/src/server/speech/providers/local/models.test.ts index e40cc25384..be010dcae9 100644 --- a/packages/server/src/server/speech/providers/local/models.test.ts +++ b/packages/server/src/server/speech/providers/local/models.test.ts @@ -13,12 +13,8 @@ import path from "node:path"; import pino from "pino"; import { describe, expect, onTestFinished, test } from "vitest"; -import { - ensureLocalSpeechModels, - getLocalSpeechModelDir, - listLocalSpeechModels, - listMissingLocalSpeechModels, -} from "./models.js"; +import { LocalSpeechModelLibrary } from "./model-library.js"; +import { getLocalSpeechModelDir, listLocalSpeechModels } from "./models.js"; const logger = pino({ level: "silent" }); const modelId = "parakeet-tdt-0.6b-v2-int8"; @@ -55,16 +51,31 @@ describe("local speech models", () => { const encoder = path.join(modelDir, spec.requiredFiles[0]); truncateSync(encoder, 1_000); - expect(await listMissingLocalSpeechModels({ modelsDir, modelIds: [modelId] })).toEqual([ - modelId, - ]); + const library = new LocalSpeechModelLibrary(modelsDir, logger); + expect(await library.listMissing([modelId])).toEqual([modelId]); - await ensureLocalSpeechModels({ modelsDir, modelIds: [modelId], logger }); + await library.download(modelId); expect(readFileSync(encoder, "utf8")).toBe( `complete ${spec.requiredFiles[0]}`.padEnd(64_000, "."), ); expect(existsSync(archive)).toBe(false); - expect(await listMissingLocalSpeechModels({ modelsDir, modelIds: [modelId] })).toEqual([]); + expect(await library.listMissing([modelId])).toEqual([]); + }); + + test("lists install state and deletes an installed model", async () => { + const { modelsDir } = setupModelsDirWithArchive(); + const library = new LocalSpeechModelLibrary(modelsDir, logger); + const stateOf = async () => + (await library.list()).find((entry) => entry.spec.id === modelId)?.state; + + expect(await stateOf()).toEqual({ status: "not_installed" }); + await library.download(modelId); + expect(await stateOf()).toEqual({ status: "installed" }); + + await library.delete(modelId); + + expect(await stateOf()).toEqual({ status: "not_installed" }); + expect(existsSync(getLocalSpeechModelDir(modelsDir, modelId))).toBe(false); }); }); diff --git a/packages/server/src/server/speech/providers/local/models.ts b/packages/server/src/server/speech/providers/local/models.ts index a884be86d7..7d4c7f56b5 100644 --- a/packages/server/src/server/speech/providers/local/models.ts +++ b/packages/server/src/server/speech/providers/local/models.ts @@ -1,11 +1,8 @@ -import { - ensureSherpaOnnxModels, - getSherpaOnnxModelDir, - isSherpaOnnxModelInstalled, -} from "./sherpa/model-downloader.js"; +import { ensureSherpaOnnxModels, getSherpaOnnxModelDir } from "./sherpa/model-downloader.js"; import { DEFAULT_LOCAL_STT_MODEL, DEFAULT_LOCAL_TTS_MODEL, + LocalSpeechModelIdSchema, LocalSttModelIdSchema, LocalTtsModelIdSchema, listSherpaOnnxModels, @@ -17,6 +14,7 @@ import { export { DEFAULT_LOCAL_STT_MODEL, DEFAULT_LOCAL_TTS_MODEL, + LocalSpeechModelIdSchema, LocalSttModelIdSchema, LocalTtsModelIdSchema, type LocalSpeechModelId, @@ -34,16 +32,6 @@ export function getLocalSpeechModelDir(modelsDir: string, modelId: LocalSpeechMo return getSherpaOnnxModelDir(modelsDir, modelId); } -export async function listMissingLocalSpeechModels(options: { - modelsDir: string; - modelIds: LocalSpeechModelId[]; -}): Promise { - const installed = await Promise.all( - options.modelIds.map((modelId) => isSherpaOnnxModelInstalled(options.modelsDir, modelId)), - ); - return options.modelIds.filter((_modelId, index) => !installed[index]); -} - export async function ensureLocalSpeechModels(options: { modelsDir: string; modelIds: LocalSpeechModelId[]; diff --git a/packages/server/src/server/speech/providers/local/sherpa/model-catalog.ts b/packages/server/src/server/speech/providers/local/sherpa/model-catalog.ts index 06d838c49a..b142f52dd6 100644 --- a/packages/server/src/server/speech/providers/local/sherpa/model-catalog.ts +++ b/packages/server/src/server/speech/providers/local/sherpa/model-catalog.ts @@ -4,43 +4,467 @@ export type SherpaOnnxModelKind = "stt-offline" | "tts"; type DefaultModelRole = "stt" | "tts"; -interface SherpaOnnxCatalogEntry { - kind: SherpaOnnxModelKind; +// How sherpa-onnx loads a model, with file names relative to the extracted directory. +export type SttEngine = + | { family: "transducer"; encoder: string; decoder: string; joiner: string; tokens: string } + | { family: "whisper"; encoder: string; decoder: string; tokens: string } + | { family: "sense_voice"; model: string; tokens: string } + | { family: "dolphin"; model: string; tokens: string } + | { family: "nemo_ctc"; model: string; tokens: string }; + +export type TtsEngine = + | { + family: "kokoro"; + model: string; + voices: string; + tokens: string; + dataDir: string; + // Multi-language Kokoro models read pronunciations from these instead of espeak alone. + lexicons?: readonly string[]; + dictDir?: string; + ruleFsts?: readonly string[]; + } + | { family: "kitten"; model: string; voices: string; tokens: string; dataDir: string } + | { family: "vits"; model: string; tokens: string; dataDir: string }; + +interface SherpaOnnxCatalogEntryBase { + label: string; + // One user-facing sentence shown before download. + description: string; + // BCP 47 language tags the model transcribes or speaks. + languages: readonly string[]; + // Exact size of the release archive. The downloader rejects any other size. + downloadSizeBytes: number; archiveUrl: string; extractedDir: string; - requiredFiles: string[]; - description: string; defaultFor?: DefaultModelRole; } +type SherpaOnnxCatalogEntry = + | (SherpaOnnxCatalogEntryBase & { kind: "stt-offline"; engine: SttEngine }) + | (SherpaOnnxCatalogEntryBase & { kind: "tts"; engine: TtsEngine }); + +// Every sherpa-onnx release archive extracts to a directory named after the archive. +function releaseArchive(tag: "asr-models" | "tts-models", name: string) { + return { + archiveUrl: `https://github.com/k2-fsa/sherpa-onnx/releases/download/${tag}/${name}.tar.bz2`, + extractedDir: name, + }; +} + +const PARAKEET_INT8_ENGINE = { + family: "transducer", + encoder: "encoder.int8.onnx", + decoder: "decoder.int8.onnx", + joiner: "joiner.int8.onnx", + tokens: "tokens.txt", +} as const satisfies SttEngine; + +function whisperEngine(size: string): SttEngine { + return { + family: "whisper", + encoder: `${size}-encoder.int8.onnx`, + decoder: `${size}-decoder.int8.onnx`, + tokens: `${size}-tokens.txt`, + }; +} + +function piperEngine(voice: string): TtsEngine { + return { + family: "vits", + model: `${voice}.onnx`, + tokens: "tokens.txt", + dataDir: "espeak-ng-data", + }; +} + +// Parakeet TDT v3 transcribes these 25 European languages and detects which one is spoken. +const PARAKEET_V3_LANGUAGES = [ + "bg", + "hr", + "cs", + "da", + "nl", + "en", + "et", + "fi", + "fr", + "de", + "el", + "hu", + "it", + "lv", + "lt", + "mt", + "pl", + "pt", + "ro", + "sk", + "sl", + "es", + "sv", + "ru", + "uk", +] as const; + +// The 99 languages multilingual Whisper models transcribe, detecting which one is spoken. +const WHISPER_LANGUAGES = [ + "en", + "zh", + "de", + "es", + "ru", + "ko", + "fr", + "ja", + "pt", + "tr", + "pl", + "ca", + "nl", + "ar", + "sv", + "it", + "id", + "hi", + "fi", + "vi", + "he", + "uk", + "el", + "ms", + "cs", + "ro", + "da", + "hu", + "ta", + "no", + "th", + "ur", + "hr", + "bg", + "lt", + "la", + "mi", + "ml", + "cy", + "sk", + "te", + "fa", + "lv", + "bn", + "sr", + "az", + "sl", + "kn", + "et", + "mk", + "br", + "eu", + "is", + "hy", + "ne", + "mn", + "bs", + "kk", + "sq", + "sw", + "gl", + "mr", + "pa", + "si", + "km", + "sn", + "yo", + "so", + "af", + "oc", + "ka", + "be", + "tg", + "sd", + "gu", + "am", + "yi", + "lo", + "uz", + "fo", + "ht", + "ps", + "tk", + "nn", + "mt", + "sa", + "lb", + "my", + "bo", + "tl", + "mg", + "as", + "tt", + "haw", + "ln", + "ha", + "ba", + "jv", + "su", +] as const; + +// Dolphin's 40 Eastern languages. It also covers 22 Chinese dialects under "zh". +const DOLPHIN_LANGUAGES = [ + "zh", + "ja", + "th", + "ru", + "ko", + "id", + "vi", + "yue", + "hi", + "ur", + "ms", + "uz", + "ar", + "fa", + "bn", + "ta", + "te", + "ug", + "gu", + "my", + "tl", + "kk", + "or", + "ne", + "mn", + "km", + "jv", + "lo", + "si", + "fil", + "ps", + "pa", + "kab", + "ba", + "ks", + "tg", + "su", + "mr", + "ky", + "az", +] as const; + export const SHERPA_ONNX_MODEL_CATALOG = { "parakeet-tdt-0.6b-v2-int8": { kind: "stt-offline", - archiveUrl: - "https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-nemo-parakeet-tdt-0.6b-v2-int8.tar.bz2", - extractedDir: "sherpa-onnx-nemo-parakeet-tdt-0.6b-v2-int8", - requiredFiles: ["encoder.int8.onnx", "decoder.int8.onnx", "joiner.int8.onnx", "tokens.txt"], - description: "NVIDIA Parakeet TDT v2 (offline NeMo transducer, English).", + label: "Parakeet v2", + description: "Accurate English transcription that runs well on a laptop CPU.", + languages: ["en"], + downloadSizeBytes: 482_468_385, + ...releaseArchive("asr-models", "sherpa-onnx-nemo-parakeet-tdt-0.6b-v2-int8"), + engine: PARAKEET_INT8_ENGINE, defaultFor: "stt", }, + "parakeet-tdt-110m-en-int8": { + kind: "stt-offline", + label: "Parakeet Small", + description: "Small, fast English model with punctuation. A quick download for any laptop.", + languages: ["en"], + downloadSizeBytes: 108_035_095, + ...releaseArchive("asr-models", "sherpa-onnx-nemo-parakeet_tdt_transducer_110m-en-36000-int8"), + engine: PARAKEET_INT8_ENGINE, + }, "parakeet-tdt-0.6b-v3-int8": { kind: "stt-offline", - archiveUrl: - "https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-nemo-parakeet-tdt-0.6b-v3-int8.tar.bz2", - extractedDir: "sherpa-onnx-nemo-parakeet-tdt-0.6b-v3-int8", - requiredFiles: ["encoder.int8.onnx", "decoder.int8.onnx", "joiner.int8.onnx", "tokens.txt"], - description: - "NVIDIA Parakeet TDT v3 (offline NeMo transducer, 25 European languages, auto-detected).", + label: "Parakeet v3", + description: "Parakeet for 25 European languages, detecting which one you speak.", + languages: PARAKEET_V3_LANGUAGES, + downloadSizeBytes: 487_170_055, + ...releaseArchive("asr-models", "sherpa-onnx-nemo-parakeet-tdt-0.6b-v3-int8"), + engine: PARAKEET_INT8_ENGINE, + }, + "whisper-tiny-en": { + kind: "stt-offline", + label: "Whisper Tiny (English)", + description: "Small English Whisper model. Quick to download, less accurate than Parakeet.", + languages: ["en"], + downloadSizeBytes: 118_071_777, + ...releaseArchive("asr-models", "sherpa-onnx-whisper-tiny.en"), + engine: whisperEngine("tiny.en"), + }, + "whisper-base": { + kind: "stt-offline", + label: "Whisper Base", + description: "Compact Whisper model for 99 languages, detecting which one you speak.", + languages: WHISPER_LANGUAGES, + downloadSizeBytes: 207_557_382, + ...releaseArchive("asr-models", "sherpa-onnx-whisper-base"), + engine: whisperEngine("base"), + }, + "whisper-turbo": { + kind: "stt-offline", + label: "Whisper Turbo", + description: "Whisper's most accurate model for 99 languages and Cantonese. Slower on a CPU.", + languages: [...WHISPER_LANGUAGES, "yue"], + downloadSizeBytes: 563_790_207, + ...releaseArchive("asr-models", "sherpa-onnx-whisper-turbo"), + engine: whisperEngine("turbo"), + }, + "sense-voice-int8": { + kind: "stt-offline", + label: "SenseVoice", + description: "Chinese, Cantonese, English, Japanese and Korean, detecting which one you speak.", + languages: ["zh", "yue", "en", "ja", "ko"], + downloadSizeBytes: 165_783_878, + ...releaseArchive("asr-models", "sherpa-onnx-sense-voice-zh-en-ja-ko-yue-int8-2025-09-09"), + engine: { family: "sense_voice", model: "model.int8.onnx", tokens: "tokens.txt" }, + }, + "dolphin-base-int8": { + kind: "stt-offline", + label: "Dolphin", + description: "Small model for 40 Asian and Middle Eastern languages and Chinese dialects.", + languages: DOLPHIN_LANGUAGES, + downloadSizeBytes: 80_671_385, + ...releaseArchive("asr-models", "sherpa-onnx-dolphin-base-ctc-multi-lang-int8-2025-04-02"), + engine: { family: "dolphin", model: "model.int8.onnx", tokens: "tokens.txt" }, + }, + "giga-am-v3-ru": { + kind: "stt-offline", + label: "GigaAM v3 (Russian)", + description: "Russian transcription with punctuation.", + languages: ["ru"], + downloadSizeBytes: 170_197_019, + ...releaseArchive( + "asr-models", + "sherpa-onnx-nemo-transducer-punct-giga-am-v3-russian-2025-12-16", + ), + engine: { + family: "transducer", + encoder: "encoder.int8.onnx", + decoder: "decoder.onnx", + joiner: "joiner.onnx", + tokens: "tokens.txt", + }, + }, + "parakeet-tdt-ctc-0.6b-ja-int8": { + kind: "stt-offline", + label: "Parakeet (Japanese)", + description: "Japanese transcription with punctuation.", + languages: ["ja"], + downloadSizeBytes: 489_389_564, + ...releaseArchive("asr-models", "sherpa-onnx-nemo-parakeet-tdt_ctc-0.6b-ja-35000-int8"), + engine: { family: "nemo_ctc", model: "model.int8.onnx", tokens: "tokens.txt" }, }, "kokoro-en-v0_19": { kind: "tts", - archiveUrl: - "https://github.com/k2-fsa/sherpa-onnx/releases/download/tts-models/kokoro-en-v0_19.tar.bz2", - extractedDir: "kokoro-en-v0_19", - requiredFiles: ["model.onnx", "voices.bin", "tokens.txt", "espeak-ng-data"], - description: "Kokoro TTS (higher quality; larger).", + label: "Kokoro (English)", + description: "Natural-sounding English voice for voice mode replies.", + languages: ["en"], + downloadSizeBytes: 319_625_534, + ...releaseArchive("tts-models", "kokoro-en-v0_19"), + engine: { + family: "kokoro", + model: "model.onnx", + voices: "voices.bin", + tokens: "tokens.txt", + dataDir: "espeak-ng-data", + }, defaultFor: "tts", }, + "kokoro-int8-en-v0_19": { + kind: "tts", + label: "Kokoro Lite (English)", + description: "The same Kokoro English voices, quantized to a third of the download.", + languages: ["en"], + downloadSizeBytes: 103_248_205, + ...releaseArchive("tts-models", "kokoro-int8-en-v0_19"), + engine: { + family: "kokoro", + model: "model.int8.onnx", + voices: "voices.bin", + tokens: "tokens.txt", + dataDir: "espeak-ng-data", + }, + }, + "kokoro-int8-multi-lang-v1_1": { + kind: "tts", + label: "Kokoro (Chinese and English)", + description: "Kokoro voices that speak both Mandarin Chinese and English.", + languages: ["zh", "en"], + downloadSizeBytes: 147_031_220, + ...releaseArchive("tts-models", "kokoro-int8-multi-lang-v1_1"), + engine: { + family: "kokoro", + model: "model.int8.onnx", + voices: "voices.bin", + tokens: "tokens.txt", + dataDir: "espeak-ng-data", + lexicons: ["lexicon-us-en.txt", "lexicon-zh.txt"], + dictDir: "dict", + ruleFsts: ["date-zh.fst", "phone-zh.fst", "number-zh.fst"], + }, + }, + // Kitten v0.8 needs a newer sherpa-onnx than we pin; v0.2 loads on 1.12.28. + "kitten-nano-en-v0_2-fp16": { + kind: "tts", + label: "Kitten Nano (English)", + description: "Tiny, very fast English voice.", + languages: ["en"], + downloadSizeBytes: 26_586_708, + ...releaseArchive("tts-models", "kitten-nano-en-v0_2-fp16"), + engine: { + family: "kitten", + model: "model.fp16.onnx", + voices: "voices.bin", + tokens: "tokens.txt", + dataDir: "espeak-ng-data", + }, + }, + "piper-en-us-libritts-r": { + kind: "tts", + label: "Piper LibriTTS (US English)", + description: "Lightweight American English voice.", + languages: ["en-US"], + downloadSizeBytes: 23_398_348, + ...releaseArchive("tts-models", "vits-piper-en_US-libritts_r-medium-int8"), + engine: piperEngine("en_US-libritts_r-medium"), + }, + "piper-en-gb-alba": { + kind: "tts", + label: "Piper Alba (British English)", + description: "Lightweight British English voice.", + languages: ["en-GB"], + downloadSizeBytes: 21_104_326, + ...releaseArchive("tts-models", "vits-piper-en_GB-alba-medium-int8"), + engine: piperEngine("en_GB-alba-medium"), + }, + "piper-de-thorsten": { + kind: "tts", + label: "Piper Thorsten (German)", + description: "Lightweight German voice.", + languages: ["de"], + downloadSizeBytes: 20_949_833, + ...releaseArchive("tts-models", "vits-piper-de_DE-thorsten-medium-int8"), + engine: piperEngine("de_DE-thorsten-medium"), + }, + "piper-fr-siwis": { + kind: "tts", + label: "Piper Siwis (French)", + description: "Lightweight French voice.", + languages: ["fr"], + downloadSizeBytes: 20_914_888, + ...releaseArchive("tts-models", "vits-piper-fr_FR-siwis-medium-int8"), + engine: piperEngine("fr_FR-siwis-medium"), + }, + "piper-es-davefx": { + kind: "tts", + label: "Piper Davefx (Spanish)", + description: "Lightweight Spanish voice.", + languages: ["es"], + downloadSizeBytes: 21_171_632, + ...releaseArchive("tts-models", "vits-piper-es_ES-davefx-medium-int8"), + engine: piperEngine("es_ES-davefx-medium"), + }, } as const satisfies Record; export type SherpaOnnxModelId = keyof typeof SHERPA_ONNX_MODEL_CATALOG; @@ -97,24 +521,44 @@ function createModelIdSchema(modelIds: readonly T[]): z.ZodTyp .transform((value) => value as T); } +export const LocalSpeechModelIdSchema = createModelIdSchema(ALL_MODEL_IDS); export const LocalSttModelIdSchema = createModelIdSchema(LOCAL_STT_MODEL_IDS); export const LocalTtsModelIdSchema = createModelIdSchema(LOCAL_TTS_MODEL_IDS); export type SherpaOnnxModelSpec = SherpaOnnxCatalogEntry & { id: SherpaOnnxModelId; + // Every file and directory that must exist for the model to count as installed. + requiredFiles: string[]; }; export function listSherpaOnnxModels(): SherpaOnnxModelSpec[] { - return ALL_MODEL_IDS.map((id) => Object.assign({ id }, SHERPA_ONNX_MODEL_CATALOG[id])); + return ALL_MODEL_IDS.map(getSherpaOnnxModelSpec); } export function getSherpaOnnxModelSpec(id: SherpaOnnxModelId): SherpaOnnxModelSpec { - const spec = SHERPA_ONNX_MODEL_CATALOG[id]; + const spec: SherpaOnnxCatalogEntry | undefined = SHERPA_ONNX_MODEL_CATALOG[id]; if (!spec) { throw new Error(`Unknown local speech model id: ${id}`); } return { id, ...spec, + requiredFiles: engineFiles(spec.engine), }; } + +// Every path an engine names, so the downloader can verify an install. +export function engineFiles(engine: SttEngine | TtsEngine): string[] { + return Object.entries(engine).flatMap(([key, value]) => { + if (key === "family") return []; + return typeof value === "string" ? [value] : (value as readonly string[]); + }); +} + +export function getLocalSttEngine(id: LocalSttModelId): SttEngine { + return SHERPA_ONNX_MODEL_CATALOG[id].engine; +} + +export function getLocalTtsEngine(id: LocalTtsModelId): TtsEngine { + return SHERPA_ONNX_MODEL_CATALOG[id].engine; +} diff --git a/packages/server/src/server/speech/providers/local/sherpa/model-downloader.ts b/packages/server/src/server/speech/providers/local/sherpa/model-downloader.ts index cdd286389f..b7ba511224 100644 --- a/packages/server/src/server/speech/providers/local/sherpa/model-downloader.ts +++ b/packages/server/src/server/speech/providers/local/sherpa/model-downloader.ts @@ -8,11 +8,16 @@ import type pino from "pino"; import { getSherpaOnnxModelSpec, type SherpaOnnxModelId } from "./model-catalog.js"; import { spawnProcess } from "../../../../../utils/spawn.js"; +export type SherpaOnnxModelInstallProgress = + | { phase: "downloading"; receivedBytes: number; totalBytes: number } + | { phase: "extracting" }; + export interface EnsureSherpaOnnxModelOptions { modelsDir: string; modelId: SherpaOnnxModelId; logger: pino.Logger; signal?: AbortSignal; + onProgress?: (progress: SherpaOnnxModelInstallProgress) => void; } export function getSherpaOnnxModelDir(modelsDir: string, modelId: SherpaOnnxModelId): string { @@ -41,7 +46,9 @@ async function hasRequiredFiles(modelDir: string, requiredFiles: string[]): Prom interface DownloadToFileOptions { url: string; outputPath: string; + expectedBytes: number; signal?: AbortSignal; + onProgress?: (receivedBytes: number, totalBytes: number) => void; } async function downloadToFile(options: DownloadToFileOptions): Promise { @@ -60,6 +67,13 @@ async function downloadToFile(options: DownloadToFileOptions): Promise { // The fetch ReadableStream type is slightly different from what Readable.fromWeb expects // eslint-disable-next-line @typescript-eslint/no-explicit-any const nodeStream = Readable.fromWeb(res.body as any); + const contentLength = Number(res.headers.get("content-length")); + const totalBytes = contentLength > 0 ? contentLength : options.expectedBytes; + let receivedBytes = 0; + nodeStream.on("data", (chunk: Buffer) => { + receivedBytes += chunk.length; + options.onProgress?.(receivedBytes, totalBytes); + }); try { await pipeline(nodeStream, createWriteStream(tmpPath), { signal: options.signal }); @@ -157,9 +171,13 @@ export async function ensureSherpaOnnxModel( await downloadToFile({ url: spec.archiveUrl, outputPath: archivePath, + expectedBytes: spec.downloadSizeBytes, signal: options.signal, + onProgress: (receivedBytes, totalBytes) => + options.onProgress?.({ phase: "downloading", receivedBytes, totalBytes }), }); } + options.onProgress?.({ phase: "extracting" }); logger.info( { @@ -213,6 +231,16 @@ export async function ensureSherpaOnnxModel( } } +export async function deleteSherpaOnnxModel( + modelsDir: string, + modelId: SherpaOnnxModelId, +): Promise { + const { modelDir, archivePath, extractionDir } = getSherpaOnnxModelPaths(modelsDir, modelId); + await rm(modelDir, { recursive: true, force: true }); + await rm(archivePath, { force: true }); + await rm(extractionDir, { recursive: true, force: true }); +} + export async function ensureSherpaOnnxModels(options: { modelsDir: string; modelIds: SherpaOnnxModelId[]; diff --git a/packages/server/src/server/speech/providers/local/sherpa/sherpa-offline-recognizer.ts b/packages/server/src/server/speech/providers/local/sherpa/sherpa-offline-recognizer.ts index cfde73addf..5137f51810 100644 --- a/packages/server/src/server/speech/providers/local/sherpa/sherpa-offline-recognizer.ts +++ b/packages/server/src/server/speech/providers/local/sherpa/sherpa-offline-recognizer.ts @@ -1,6 +1,8 @@ import { existsSync } from "node:fs"; +import path from "node:path"; import type pino from "pino"; +import { engineFiles, type SttEngine } from "./model-catalog.js"; import { loadSherpaOnnxNode } from "./sherpa-onnx-node-loader.js"; function assertFileExists(filePath: string, label: string): void { @@ -9,16 +11,43 @@ function assertFileExists(filePath: string, label: string): void { } } -export interface SherpaOfflineRecognizerModel { - kind: "nemo_transducer"; - encoder: string; - decoder: string; - joiner: string; - tokens: string; +// Each engine family takes its own block under sherpa's modelConfig. +function buildModelConfig(modelDir: string, engine: SttEngine): Record { + const file = (name: string) => path.join(modelDir, name); + switch (engine.family) { + case "transducer": + return { + transducer: { + encoder: file(engine.encoder), + decoder: file(engine.decoder), + joiner: file(engine.joiner), + }, + modelType: "nemo_transducer", + }; + case "whisper": + // An empty language makes Whisper detect the spoken language. + return { + whisper: { + encoder: file(engine.encoder), + decoder: file(engine.decoder), + language: "", + task: "transcribe", + }, + }; + case "sense_voice": + return { + senseVoice: { model: file(engine.model), language: "", useInverseTextNormalization: 1 }, + }; + case "dolphin": + return { dolphin: { model: file(engine.model) } }; + case "nemo_ctc": + return { nemoCtc: { model: file(engine.model) } }; + } } export interface SherpaOfflineRecognizerConfig { - model: SherpaOfflineRecognizerModel; + modelDir: string; + engine: SttEngine; numThreads?: number; provider?: "cpu"; debug?: 0 | 1; @@ -54,10 +83,9 @@ export class SherpaOfflineRecognizerEngine { component: "offline-recognizer", }); - assertFileExists(config.model.encoder, "offline encoder"); - assertFileExists(config.model.decoder, "offline decoder"); - assertFileExists(config.model.joiner, "offline joiner"); - assertFileExists(config.model.tokens, "tokens"); + for (const name of engineFiles(config.engine)) { + assertFileExists(path.join(config.modelDir, name), `${config.engine.family} model file`); + } const sherpa = loadSherpaOnnxNode(); @@ -67,13 +95,8 @@ export class SherpaOfflineRecognizerEngine { featureDim: config.featureDim ?? 80, }, modelConfig: { - transducer: { - encoder: config.model.encoder, - decoder: config.model.decoder, - joiner: config.model.joiner, - }, - tokens: config.model.tokens, - modelType: "nemo_transducer", + ...buildModelConfig(config.modelDir, config.engine), + tokens: path.join(config.modelDir, config.engine.tokens), numThreads: config.numThreads ?? 1, provider: config.provider ?? "cpu", debug: config.debug ?? 0, diff --git a/packages/server/src/server/speech/providers/local/sherpa/sherpa-tts.test.ts b/packages/server/src/server/speech/providers/local/sherpa/sherpa-tts.test.ts index 06d4a5b41d..0ae51f86ee 100644 --- a/packages/server/src/server/speech/providers/local/sherpa/sherpa-tts.test.ts +++ b/packages/server/src/server/speech/providers/local/sherpa/sherpa-tts.test.ts @@ -3,6 +3,7 @@ import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import pino from "pino"; +import { engineFiles, getLocalTtsEngine, type LocalTtsModelId } from "./model-catalog.js"; import { SherpaOnnxTTS } from "./sherpa-tts.js"; const directories: string[] = []; @@ -11,17 +12,28 @@ afterEach(() => { rmSync(directory, { recursive: true, force: true }); }); -function createTts(numThreads?: number, beforeGenerate?: () => Promise) { +function createTts( + numThreads?: number, + beforeGenerate?: () => Promise, + modelId: LocalTtsModelId = "kokoro-en-v0_19", +) { const modelDir = mkdtempSync(join(tmpdir(), "paseo-tts-")); directories.push(modelDir); - for (const name of ["model.onnx", "voices.bin", "tokens.txt"]) - writeFileSync(join(modelDir, name), ""); - mkdirSync(join(modelDir, "espeak-ng-data")); + // Data directories have no extension; everything else is a model file. + for (const name of engineFiles(getLocalTtsEngine(modelId))) { + if (name.includes(".")) writeFileSync(join(modelDir, name), ""); + else mkdirSync(join(modelDir, name)); + } let nativeConfig: unknown; const requests: unknown[] = []; const released: boolean[] = []; const tts = new SherpaOnnxTTS( - { preset: "kokoro-en-v0_19", modelDir, numThreads }, + { + modelId, + modelDir, + engine: getLocalTtsEngine(modelId), + numThreads, + }, pino({ level: "silent" }), () => ({ OfflineTts: class { @@ -138,4 +150,31 @@ describe("SherpaOnnxTTS", () => { expect(nativeConfig).not.toHaveProperty("provider"); }, ); + + it("loads Piper voices through the vits engine", () => { + const { nativeConfig } = createTts(undefined, undefined, "piper-de-thorsten"); + expect(nativeConfig).toMatchObject({ + model: { + vits: { + model: expect.stringMatching(/de_DE-thorsten-medium\.onnx$/), + tokens: expect.stringMatching(/tokens\.txt$/), + dataDir: expect.stringMatching(/espeak-ng-data$/), + }, + }, + }); + expect(nativeConfig).not.toHaveProperty("model.kokoro"); + }); + + it("gives multi-language Kokoro its lexicons, dictionary and number rules", () => { + const { nativeConfig } = createTts(undefined, undefined, "kokoro-int8-multi-lang-v1_1"); + expect(nativeConfig).toMatchObject({ + model: { + kokoro: { + lexicon: expect.stringMatching(/lexicon-us-en\.txt,.*lexicon-zh\.txt$/), + dictDir: expect.stringMatching(/dict$/), + }, + }, + ruleFsts: expect.stringMatching(/date-zh\.fst,.*phone-zh\.fst,.*number-zh\.fst$/), + }); + }); }); diff --git a/packages/server/src/server/speech/providers/local/sherpa/sherpa-tts.ts b/packages/server/src/server/speech/providers/local/sherpa/sherpa-tts.ts index a078f81f51..12c86b8777 100644 --- a/packages/server/src/server/speech/providers/local/sherpa/sherpa-tts.ts +++ b/packages/server/src/server/speech/providers/local/sherpa/sherpa-tts.ts @@ -1,16 +1,17 @@ import type pino from "pino"; import { Readable } from "node:stream"; import { existsSync } from "node:fs"; +import path from "node:path"; import type { SpeechStreamResult, TextToSpeechProvider } from "../../../speech-provider.js"; import { chunkBuffer, float32ToPcm16le } from "../../../audio.js"; import { loadSherpaOnnxNode } from "./sherpa-onnx-node-loader.js"; - -export type SherpaTtsPreset = "kokoro-en-v0_19"; +import { engineFiles, type LocalTtsModelId, type TtsEngine } from "./model-catalog.js"; export interface SherpaTtsConfig { - preset: SherpaTtsPreset; + modelId: LocalTtsModelId; modelDir: string; + engine: TtsEngine; speakerId?: number; speed?: number; lengthScale?: number; @@ -23,6 +24,53 @@ function assertFileExists(filePath: string, label: string): void { } } +// Each engine family takes its own block under sherpa's TTS model config. +function buildTtsModelConfig( + modelDir: string, + engine: TtsEngine, + lengthScale: number, +): Record { + const file = (name: string) => path.join(modelDir, name); + switch (engine.family) { + case "kokoro": + return { + kokoro: { + model: file(engine.model), + voices: file(engine.voices), + tokens: file(engine.tokens), + dataDir: file(engine.dataDir), + lexicon: (engine.lexicons ?? []).map(file).join(","), + dictDir: engine.dictDir ? file(engine.dictDir) : "", + lengthScale, + }, + }; + case "kitten": + return { + kitten: { + model: file(engine.model), + voices: file(engine.voices), + tokens: file(engine.tokens), + dataDir: file(engine.dataDir), + lengthScale, + }, + }; + case "vits": + return { + vits: { + model: file(engine.model), + tokens: file(engine.tokens), + dataDir: file(engine.dataDir), + lengthScale, + }, + }; + } +} + +function ruleFsts(modelDir: string, engine: TtsEngine): string { + if (engine.family !== "kokoro" || !engine.ruleFsts) return ""; + return engine.ruleFsts.map((name) => path.join(modelDir, name)).join(","); +} + interface SherpaOfflineTtsNative { sampleRate?: number; generateAsync: (args: { @@ -59,39 +107,28 @@ export class SherpaOnnxTTS implements TextToSpeechProvider { throw new Error("sherpa-onnx-node OfflineTts is unavailable"); } - const modelPath = `${config.modelDir}/model.onnx`; - const voicesPath = `${config.modelDir}/voices.bin`; - const tokensPath = `${config.modelDir}/tokens.txt`; - const dataDir = `${config.modelDir}/espeak-ng-data`; - - assertFileExists(modelPath, "TTS model"); - assertFileExists(voicesPath, "TTS voices"); - assertFileExists(tokensPath, "TTS tokens"); - assertFileExists(dataDir, "TTS espeak-ng dataDir"); + for (const name of engineFiles(config.engine)) { + assertFileExists(path.join(config.modelDir, name), `${config.engine.family} TTS file`); + } const modelConfig = { // The native parser reads these under model, despite the upstream JS typedef. numThreads: config.numThreads ?? 2, provider: "cpu", - kokoro: { - model: modelPath, - voices: voicesPath, - tokens: tokensPath, - dataDir, - lengthScale: config.lengthScale ?? 1.0, - }, + ...buildTtsModelConfig(config.modelDir, config.engine, config.lengthScale ?? 1.0), }; const offlineTtsConfig = { model: modelConfig, maxNumSentences: 1, + ruleFsts: ruleFsts(config.modelDir, config.engine), }; this.tts = new ( sherpa as unknown as { OfflineTts: new (config: unknown) => SherpaOfflineTtsNative } ).OfflineTts(offlineTtsConfig); this.logger.info( - { preset: config.preset, modelDir: config.modelDir }, + { modelId: config.modelId, modelDir: config.modelDir }, "Sherpa offline TTS initialized", ); } diff --git a/packages/server/src/server/speech/providers/local/sherpa/speech-download.e2e.test.ts b/packages/server/src/server/speech/providers/local/sherpa/speech-download.e2e.test.ts index ab2eefef55..43ab8af01a 100644 --- a/packages/server/src/server/speech/providers/local/sherpa/speech-download.e2e.test.ts +++ b/packages/server/src/server/speech/providers/local/sherpa/speech-download.e2e.test.ts @@ -7,6 +7,7 @@ import pino from "pino"; import { ensureSherpaOnnxModels, getSherpaOnnxModelDir } from "./model-downloader.js"; import { createDaemonTestContext } from "../../../../test-utils/index.js"; import { parsePcm16MonoWav, wordSimilarity } from "../../../../test-utils/dictation-e2e.js"; +import { getLocalSttEngine, getLocalTtsEngine } from "./model-catalog.js"; import { SherpaOnnxTTS } from "./sherpa-tts.js"; import { SherpaOfflineRecognizerEngine } from "./sherpa-offline-recognizer.js"; import { SherpaOnnxParakeetSTT } from "./sherpa-parakeet-stt.js"; @@ -192,7 +193,12 @@ downloadTest( const ttsText = "This is a voice note."; const ttsModelDir = getSherpaOnnxModelDir(modelsDir, "kokoro-en-v0_19"); const tts = new SherpaOnnxTTS( - { preset: "kokoro-en-v0_19", modelDir: ttsModelDir, speakerId: 0 }, + { + modelId: "kokoro-en-v0_19", + modelDir: ttsModelDir, + engine: getLocalTtsEngine("kokoro-en-v0_19"), + speakerId: 0, + }, logger, ); const { stream, format: ttsFormat } = await tts.synthesizeSpeech(ttsText); @@ -206,13 +212,8 @@ downloadTest( const sttModelDir = getSherpaOnnxModelDir(modelsDir, "parakeet-tdt-0.6b-v2-int8"); const engine = new SherpaOfflineRecognizerEngine( { - model: { - kind: "nemo_transducer", - encoder: `${sttModelDir}/encoder.int8.onnx`, - decoder: `${sttModelDir}/decoder.int8.onnx`, - joiner: `${sttModelDir}/joiner.int8.onnx`, - tokens: `${sttModelDir}/tokens.txt`, - }, + modelDir: sttModelDir, + engine: getLocalSttEngine("parakeet-tdt-0.6b-v2-int8"), numThreads: 2, debug: 0, }, diff --git a/packages/server/src/server/speech/providers/local/worker-process.ts b/packages/server/src/server/speech/providers/local/worker-process.ts index 957ee6aaa2..2afa3d336a 100644 --- a/packages/server/src/server/speech/providers/local/worker-process.ts +++ b/packages/server/src/server/speech/providers/local/worker-process.ts @@ -3,6 +3,7 @@ import pino from "pino"; import type { StreamingTranscriptionSession } from "../../speech-provider.js"; import type { TurnDetectionSession } from "../../turn-detection-provider.js"; import { getLocalSpeechModelDir, type LocalSttModelId, type LocalTtsModelId } from "./models.js"; +import { getLocalSttEngine, getLocalTtsEngine } from "./sherpa/model-catalog.js"; import { SherpaOfflineRecognizerEngine } from "./sherpa/sherpa-offline-recognizer.js"; import { SherpaOnnxParakeetSTT } from "./sherpa/sherpa-parakeet-stt.js"; import { SherpaParakeetRealtimeTranscriptionSession } from "./sherpa/sherpa-parakeet-realtime-session.js"; @@ -85,13 +86,8 @@ function getSttEngine( const modelDir = getLocalSpeechModelDir(config.modelsDir, modelId); const created = new SherpaOfflineRecognizerEngine( { - model: { - kind: "nemo_transducer", - encoder: `${modelDir}/encoder.int8.onnx`, - decoder: `${modelDir}/decoder.int8.onnx`, - joiner: `${modelDir}/joiner.int8.onnx`, - tokens: `${modelDir}/tokens.txt`, - }, + modelDir, + engine: getLocalSttEngine(modelId), numThreads: 2, debug: 0, }, @@ -125,8 +121,9 @@ function getTtsProvider(config: LocalSpeechWorkerConfig): SherpaOnnxTTS { const modelDir = getLocalSpeechModelDir(config.modelsDir, ttsModelId(config)); const created = new SherpaOnnxTTS( { - preset: ttsModelId(config), + modelId: ttsModelId(config), modelDir, + engine: getLocalTtsEngine(ttsModelId(config)), speakerId: config.voiceTtsSpeakerId, speed: config.voiceTtsSpeed, }, diff --git a/packages/server/src/server/speech/providers/openai/config.test.ts b/packages/server/src/server/speech/providers/openai/config.test.ts index 1f3433a347..dd465dd2f9 100644 --- a/packages/server/src/server/speech/providers/openai/config.test.ts +++ b/packages/server/src/server/speech/providers/openai/config.test.ts @@ -1,5 +1,4 @@ import { describe, expect, test } from "vitest"; - import { PersistedConfigSchema } from "../../../persisted-config.js"; import { resolveOpenAiSpeechConfig } from "./config.js"; import type { RequestedSpeechProviders } from "../../speech-types.js"; @@ -10,233 +9,139 @@ const ALL_OPENAI: RequestedSpeechProviders = { voiceStt: { provider: "openai", explicit: true }, voiceTts: { provider: "openai", explicit: true }, }; +function resolve(input: unknown, env: NodeJS.ProcessEnv = {}) { + return resolveOpenAiSpeechConfig({ + persisted: PersistedConfigSchema.parse(input), + env, + providers: ALL_OPENAI, + }); +} describe("resolveOpenAiSpeechConfig", () => { - test("treats empty OPENAI_API_KEY as unset", () => { - const persisted = PersistedConfigSchema.parse({}); - const env = { - OPENAI_API_KEY: "", - } as NodeJS.ProcessEnv; - - const resolved = resolveOpenAiSpeechConfig({ - env, - persisted, - providers: { - ...ALL_OPENAI, - dictationStt: { provider: "local", explicit: false }, - voiceStt: { provider: "local", explicit: false }, - voiceTts: { provider: "local", explicit: false }, + test("treats empty credentials as unset", () => { + expect(resolve({}, { OPENAI_API_KEY: "", OPENAI_STT_API_KEY: " " })).toBeUndefined(); + }); + test("uses endpoint env before global env and ignores empty fallbacks", () => { + const result = resolve( + {}, + { + OPENAI_API_KEY: " global ", + OPENAI_BASE_URL: " https://global/v1 ", + OPENAI_STT_API_KEY: " stt ", + OPENAI_STT_BASE_URL: " https://stt/v1 ", + OPENAI_TTS_API_KEY: " ", + OPENAI_TTS_BASE_URL: "", }, + ); + expect(result?.dictationStt).toEqual({ apiKey: "stt", baseUrl: "https://stt/v1" }); + expect(result?.stt).toEqual({ apiKey: "stt", baseUrl: "https://stt/v1" }); + expect(result?.tts).toEqual({ + apiKey: "global", + baseUrl: "https://global/v1", + model: "tts-1", + voice: "alloy", + responseFormat: "pcm", }); - - expect(resolved).toBeUndefined(); }); - - test("applies trimmed OPENAI_API_KEY to both STT and TTS", () => { - const persisted = PersistedConfigSchema.parse({}); - const env = { - OPENAI_API_KEY: " sk-test ", - } as NodeJS.ProcessEnv; - - const resolved = resolveOpenAiSpeechConfig({ env, persisted, providers: ALL_OPENAI }); - - expect(resolved?.stt?.apiKey).toBe("sk-test"); - expect(resolved?.tts?.apiKey).toBe("sk-test"); - }); - - test("resolves distinct endpoints for STT and TTS", () => { - const persisted = PersistedConfigSchema.parse({ - providers: { - openai: { - stt: { - apiKey: "stt-key", - baseUrl: " https://stt.example.com/v1 ", + test("each site wins over endpoint and global env credentials and URL", () => { + const result = resolve( + { + features: { + dictation: { + stt: { + provider: "openai", + apiKey: "dictation", + baseUrl: "https://dictation/v1", + model: "dictation-model", + confidenceThreshold: -1, + }, }, - tts: { - apiKey: "tts-key", - baseUrl: " https://tts.example.com/v1 ", + voiceMode: { + stt: { + provider: "openai", + apiKey: "voice", + baseUrl: "https://voice/v1", + model: "voice-model", + confidenceThreshold: -2, + }, + tts: { + provider: "openai", + apiKey: "tts", + baseUrl: "https://tts/v1", + model: "kokoro-v1:Q8_0", + voice: "Aiden", + }, }, }, }, + { + OPENAI_API_KEY: "global", + OPENAI_BASE_URL: "https://global/v1", + OPENAI_STT_API_KEY: "endpoint", + OPENAI_STT_BASE_URL: "https://endpoint/v1", + OPENAI_TTS_API_KEY: "endpoint", + OPENAI_TTS_BASE_URL: "https://endpoint/v1", + }, + ); + expect(result?.dictationStt).toEqual({ + apiKey: "dictation", + baseUrl: "https://dictation/v1", + model: "dictation-model", + confidenceThreshold: -1, }); - - const resolved = resolveOpenAiSpeechConfig({ - env: {} as NodeJS.ProcessEnv, - persisted, - providers: ALL_OPENAI, + expect(result?.stt).toEqual({ + apiKey: "voice", + baseUrl: "https://voice/v1", + model: "voice-model", + confidenceThreshold: -2, + }); + expect(result?.tts).toEqual({ + apiKey: "tts", + baseUrl: "https://tts/v1", + model: "kokoro-v1:Q8_0", + voice: "Aiden", + responseFormat: "pcm", }); - - expect(resolved?.stt?.apiKey).toBe("stt-key"); - expect(resolved?.stt?.baseUrl).toBe("https://stt.example.com/v1"); - expect(resolved?.tts?.apiKey).toBe("tts-key"); - expect(resolved?.tts?.baseUrl).toBe("https://tts.example.com/v1"); }); - - test("prefers nested STT/TTS config over env and global fallbacks", () => { - const persisted = PersistedConfigSchema.parse({ - providers: { - openai: { - apiKey: "fallback-config-key", - baseUrl: "https://global-config.example.com/v1", - stt: { apiKey: "stt-config-key", baseUrl: " https://stt.example.com/v1 " }, - tts: { apiKey: "tts-config-key", baseUrl: " https://tts.example.com/v1 " }, + test("env overrides model, voice and threshold at every OpenAI site", () => { + const result = resolve( + { + features: { + dictation: { stt: { provider: "openai", model: "dictation", confidenceThreshold: -1 } }, + voiceMode: { + stt: { provider: "openai", model: "voice", confidenceThreshold: -2 }, + tts: { provider: "openai", model: "configured", voice: "Aiden" }, + }, }, }, - }); - const env = { - OPENAI_API_KEY: "env-key", - OPENAI_STT_API_KEY: "stt-env-key", - OPENAI_STT_BASE_URL: "https://stt-env.example.com/v1", - OPENAI_TTS_API_KEY: "tts-env-key", - OPENAI_TTS_BASE_URL: "https://tts-env.example.com/v1", - OPENAI_BASE_URL: "https://env.example.com/v1", - } as NodeJS.ProcessEnv; - - const resolved = resolveOpenAiSpeechConfig({ env, persisted, providers: ALL_OPENAI }); - - expect(resolved?.stt?.apiKey).toBe("stt-config-key"); - expect(resolved?.stt?.baseUrl).toBe("https://stt.example.com/v1"); - expect(resolved?.tts?.apiKey).toBe("tts-config-key"); - expect(resolved?.tts?.baseUrl).toBe("https://tts.example.com/v1"); - }); - - test("uses STT/TTS env config when nested config is unset", () => { - const persisted = PersistedConfigSchema.parse({}); - const env = { - OPENAI_API_KEY: "sk-test", - OPENAI_STT_API_KEY: "stt-env-key", - OPENAI_STT_BASE_URL: " https://stt-env.example.com/v1 ", - OPENAI_TTS_API_KEY: "tts-env-key", - OPENAI_TTS_BASE_URL: " https://tts-env.example.com/v1 ", - OPENAI_BASE_URL: "https://env.example.com/v1", - } as NodeJS.ProcessEnv; - - const resolved = resolveOpenAiSpeechConfig({ env, persisted, providers: ALL_OPENAI }); - - expect(resolved?.stt?.apiKey).toBe("stt-env-key"); - expect(resolved?.stt?.baseUrl).toBe("https://stt-env.example.com/v1"); - expect(resolved?.tts?.apiKey).toBe("tts-env-key"); - expect(resolved?.tts?.baseUrl).toBe("https://tts-env.example.com/v1"); - }); - - test("falls back to global OpenAI config for both STT and TTS", () => { - const persisted = PersistedConfigSchema.parse({ - providers: { - openai: { - apiKey: "fallback-config-key", - baseUrl: " https://global-config.example.com/v1 ", - }, + { + OPENAI_API_KEY: "key", + STT_MODEL: "override", + TTS_MODEL: "tts-override", + TTS_VOICE: "Nova", + STT_CONFIDENCE_THRESHOLD: "-3", }, + ); + expect(result?.dictationStt).toEqual({ + apiKey: "key", + model: "override", + confidenceThreshold: -3, }); - const env = {} as NodeJS.ProcessEnv; - - const resolved = resolveOpenAiSpeechConfig({ env, persisted, providers: ALL_OPENAI }); - - expect(resolved?.stt?.apiKey).toBe("fallback-config-key"); - expect(resolved?.stt?.baseUrl).toBe("https://global-config.example.com/v1"); - expect(resolved?.tts?.apiKey).toBe("fallback-config-key"); - expect(resolved?.tts?.baseUrl).toBe("https://global-config.example.com/v1"); + expect(result?.stt).toEqual({ apiKey: "key", model: "override", confidenceThreshold: -3 }); + expect(result?.tts).toMatchObject({ model: "tts-override", voice: "Nova" }); }); - - test("falls back to global OpenAI env config when feature inputs are unset", () => { - const persisted = PersistedConfigSchema.parse({}); - const env = { - OPENAI_API_KEY: "env-key", - OPENAI_BASE_URL: " https://env.example.com/v1 ", - } as NodeJS.ProcessEnv; - - const resolved = resolveOpenAiSpeechConfig({ env, persisted, providers: ALL_OPENAI }); - - expect(resolved?.stt?.apiKey).toBe("env-key"); - expect(resolved?.stt?.baseUrl).toBe("https://env.example.com/v1"); - expect(resolved?.tts?.apiKey).toBe("env-key"); - expect(resolved?.tts?.baseUrl).toBe("https://env.example.com/v1"); + test("only configures endpoints with credentials and ignores unused TTS options", () => { + const result = resolve( + { features: { dictation: { stt: { provider: "openai", apiKey: "dictation" } } } }, + { TTS_VOICE: "arbitrary", TTS_MODEL: "arbitrary" }, + ); + expect(result).toEqual({ dictationStt: { apiKey: "dictation" } }); }); - - test("ignores empty endpoint env vars and falls back to OPENAI_API_KEY", () => { - const persisted = PersistedConfigSchema.parse({}); - const env = { - OPENAI_API_KEY: "global-key", - OPENAI_STT_API_KEY: "", - OPENAI_STT_BASE_URL: " ", - OPENAI_TTS_API_KEY: "", - OPENAI_TTS_BASE_URL: "", - } as NodeJS.ProcessEnv; - - const resolved = resolveOpenAiSpeechConfig({ env, persisted, providers: ALL_OPENAI }); - - expect(resolved?.stt?.apiKey).toBe("global-key"); - expect(resolved?.tts?.apiKey).toBe("global-key"); - }); - - test("omits TTS when only an STT key is configured", () => { - const persisted = PersistedConfigSchema.parse({ - providers: { - openai: { - stt: { apiKey: "stt-only-key" }, - }, - }, + test("does not borrow another site's key", () => { + const result = resolve({ + features: { voiceMode: { stt: { provider: "openai", apiKey: "voice-only" } } }, }); - - const resolved = resolveOpenAiSpeechConfig({ - env: {} as NodeJS.ProcessEnv, - persisted, - providers: ALL_OPENAI, - }); - - expect(resolved?.stt?.apiKey).toBe("stt-only-key"); - expect(resolved?.tts).toBeUndefined(); - }); - - test("resolves STT even when an unused TTS env var is invalid", () => { - const persisted = PersistedConfigSchema.parse({ - providers: { - openai: { - stt: { apiKey: "stt-only-key" }, - }, - }, - }); - const env = { TTS_VOICE: "not-a-real-voice", TTS_MODEL: "bogus-model" } as NodeJS.ProcessEnv; - - const resolved = resolveOpenAiSpeechConfig({ env, persisted, providers: ALL_OPENAI }); - - expect(resolved?.stt?.apiKey).toBe("stt-only-key"); - expect(resolved?.tts).toBeUndefined(); - }); - - test("sends the model and voice an OpenAI-compatible server serves, as written", () => { - const persisted = PersistedConfigSchema.parse({ - providers: { - openai: { tts: { apiKey: "tts-key", baseUrl: "https://tts.example.com/v1" } }, - }, - features: { - voiceMode: { tts: { provider: "openai", model: "kokoro-v1:Q8_0", voice: "Aiden" } }, - }, - }); - - const resolved = resolveOpenAiSpeechConfig({ - env: {} as NodeJS.ProcessEnv, - persisted, - providers: ALL_OPENAI, - }); - - expect(resolved?.tts?.model).toBe("kokoro-v1:Q8_0"); - expect(resolved?.tts?.voice).toBe("Aiden"); - }); - - test("accepts OpenAI's own gpt-4o-mini-tts model", () => { - const persisted = PersistedConfigSchema.parse({ - providers: { openai: { tts: { apiKey: "tts-key" } } }, - features: { voiceMode: { tts: { provider: "openai", model: "gpt-4o-mini-tts" } } }, - }); - - const resolved = resolveOpenAiSpeechConfig({ - env: {} as NodeJS.ProcessEnv, - persisted, - providers: ALL_OPENAI, - }); - - expect(resolved?.tts?.model).toBe("gpt-4o-mini-tts"); - expect(resolved?.tts?.voice).toBe("alloy"); + expect(result?.dictationStt).toBeUndefined(); + expect(result?.stt).toEqual({ apiKey: "voice-only" }); }); }); diff --git a/packages/server/src/server/speech/providers/openai/config.ts b/packages/server/src/server/speech/providers/openai/config.ts index efb25bffaf..37813571f4 100644 --- a/packages/server/src/server/speech/providers/openai/config.ts +++ b/packages/server/src/server/speech/providers/openai/config.ts @@ -6,147 +6,61 @@ import type { STTConfig } from "./stt.js"; import type { TTSConfig } from "./tts.js"; export const DEFAULT_OPENAI_TTS_MODEL = "tts-1"; +export type OpenAiSttFeature = "dictation" | "voiceMode"; export interface OpenAiSpeechProviderConfig { - stt?: Partial & { apiKey?: string }; - tts?: Partial & { apiKey?: string }; + dictationStt?: Partial; + stt?: Partial; + tts?: Partial; } -const NumberLikeSchema = z.union([z.number(), z.string().trim().min(1)]); +const OptionalFiniteNumberSchema = z + .union([z.number(), z.string().trim().min(1)]) + .pipe(z.coerce.number().finite()) + .optional(); -const OptionalFiniteNumberSchema = NumberLikeSchema.pipe( - z.coerce.number().finite(), -).optional(); - -const OptionalTrimmedStringSchema = z - .string() - .trim() - .optional() - .transform((value) => (value && value.length > 0 ? value : undefined)); - -// Endpoint credentials only — plain trimmed strings, so this never throws on a -// malformed value. The STT/TTS option groups parse separately and only for the -// endpoint that is actually configured, so a stale env var for an unused endpoint -// (e.g. a leftover TTS_VOICE in an STT-only setup) can't break the other one. -const OpenAiEndpointKeysSchema = z.object({ - sttApiKey: OptionalTrimmedStringSchema, - sttBaseUrl: OptionalTrimmedStringSchema, - ttsApiKey: OptionalTrimmedStringSchema, - ttsBaseUrl: OptionalTrimmedStringSchema, -}); - -const OpenAiSttOptionsSchema = z.object({ - sttConfidenceThreshold: OptionalFiniteNumberSchema, - sttModel: OptionalTrimmedStringSchema, -}); - -// Voice and model are free-form so a self-hosted server can use its own ids; the -// OpenAI catalog is only the default. Both are sent as written, because the -// server owns those ids and their case (rosters use ids like kokoro-v1:Q8_0). -const OpenAiTtsOptionsSchema = z.object({ - ttsVoice: z.string().trim().default("alloy"), - ttsModel: z.string().trim().default(DEFAULT_OPENAI_TTS_MODEL), -}); - -function isOpenAiProviderActive(provider: { enabled?: boolean; provider: string }): boolean { - return provider.enabled !== false && provider.provider === "openai"; +function firstString(...values: (string | undefined)[]): string | undefined { + return values.map((value) => value?.trim()).find((value) => Boolean(value)); } -function pickIfOpenAi( - provider: { enabled?: boolean; provider: string }, - value: T | undefined, -): T | undefined { - return isOpenAiProviderActive(provider) ? value : undefined; -} +type Features = NonNullable; +type SttSite = NonNullable["stt"]>; +type TtsSite = NonNullable["tts"]>; -function firstDefined(values: Array): T | undefined { - for (const value of values) { - if (value === undefined || value === null) { - continue; - } - // Empty/whitespace env vars (e.g. a copied .env.example with OPENAI_STT_API_KEY=) - // must not shadow a later fallback such as OPENAI_API_KEY. - if (typeof value === "string" && value.trim().length === 0) { - continue; - } - return value; - } - return undefined; -} - -function buildOpenAiSttInput(params: { - env: NodeJS.ProcessEnv; - persisted: PersistedConfig; - providers: RequestedSpeechProviders; -}): Record { - const { env, persisted, providers } = params; +function resolveStt( + site: SttSite | undefined, + env: NodeJS.ProcessEnv, +): Partial | undefined { + const config = site?.provider === "openai" ? site : undefined; + const apiKey = firstString(config?.apiKey, env.OPENAI_STT_API_KEY, env.OPENAI_API_KEY); + if (!apiKey) return undefined; + const baseUrl = firstString(config?.baseUrl, env.OPENAI_STT_BASE_URL, env.OPENAI_BASE_URL); + const model = firstString(env.STT_MODEL, config?.model); + const confidenceThreshold = OptionalFiniteNumberSchema.parse( + firstString(env.STT_CONFIDENCE_THRESHOLD) ?? config?.confidenceThreshold, + ); return { - sttConfidenceThreshold: firstDefined([ - env.STT_CONFIDENCE_THRESHOLD, - persisted.features?.dictation?.stt?.confidenceThreshold, - ]), - sttModel: firstDefined([ - env.STT_MODEL, - pickIfOpenAi(providers.voiceStt, persisted.features?.voiceMode?.stt?.model), - pickIfOpenAi(providers.dictationStt, persisted.features?.dictation?.stt?.model), - ]), + apiKey, + ...(baseUrl ? { baseUrl } : {}), + ...(model ? { model } : {}), + ...(confidenceThreshold !== undefined ? { confidenceThreshold } : {}), }; } -function buildOpenAiTtsInput(params: { - env: NodeJS.ProcessEnv; - persisted: PersistedConfig; - providers: RequestedSpeechProviders; -}): Record { - const { env, persisted, providers } = params; +function resolveTts( + site: TtsSite | undefined, + env: NodeJS.ProcessEnv, +): Partial | undefined { + const config = site?.provider === "openai" ? site : undefined; + const apiKey = firstString(config?.apiKey, env.OPENAI_TTS_API_KEY, env.OPENAI_API_KEY); + if (!apiKey) return undefined; + const baseUrl = firstString(config?.baseUrl, env.OPENAI_TTS_BASE_URL, env.OPENAI_BASE_URL); return { - ttsVoice: firstDefined([ - env.TTS_VOICE, - pickIfOpenAi(providers.voiceTts, persisted.features?.voiceMode?.tts?.voice), - "alloy", - ]), - ttsModel: firstDefined([ - env.TTS_MODEL, - pickIfOpenAi(providers.voiceTts, persisted.features?.voiceMode?.tts?.model), - DEFAULT_OPENAI_TTS_MODEL, - ]), - }; -} - -function buildOpenAiResolutionInput(params: { - env: NodeJS.ProcessEnv; - persisted: PersistedConfig; - providers: RequestedSpeechProviders; -}): Record { - const { env } = params; - const openai = params.persisted.providers?.openai; - return { - sttApiKey: firstDefined([ - openai?.stt?.apiKey, - env.OPENAI_STT_API_KEY, - openai?.apiKey, - env.OPENAI_API_KEY, - ]), - sttBaseUrl: firstDefined([ - openai?.stt?.baseUrl, - env.OPENAI_STT_BASE_URL, - openai?.baseUrl, - env.OPENAI_BASE_URL, - ]), - ttsApiKey: firstDefined([ - openai?.tts?.apiKey, - env.OPENAI_TTS_API_KEY, - openai?.apiKey, - env.OPENAI_API_KEY, - ]), - ttsBaseUrl: firstDefined([ - openai?.tts?.baseUrl, - env.OPENAI_TTS_BASE_URL, - openai?.baseUrl, - env.OPENAI_BASE_URL, - ]), - ...buildOpenAiSttInput(params), - ...buildOpenAiTtsInput(params), + apiKey, + ...(baseUrl ? { baseUrl } : {}), + model: firstString(env.TTS_MODEL, config?.model) ?? DEFAULT_OPENAI_TTS_MODEL, + voice: firstString(env.TTS_VOICE, config?.voice) ?? "alloy", + responseFormat: "pcm", }; } @@ -155,46 +69,14 @@ export function resolveOpenAiSpeechConfig(params: { persisted: PersistedConfig; providers: RequestedSpeechProviders; }): OpenAiSpeechProviderConfig | undefined { - const input = buildOpenAiResolutionInput(params); - const keys = OpenAiEndpointKeysSchema.parse(input); - - if (!keys.sttApiKey && !keys.ttsApiKey) { - return undefined; - } - + const { env, persisted } = params; + const dictationStt = resolveStt(persisted.features?.dictation?.stt, env); + const stt = resolveStt(persisted.features?.voiceMode?.stt, env); + const tts = resolveTts(persisted.features?.voiceMode?.tts, env); + if (!dictationStt && !stt && !tts) return undefined; return { - ...(keys.sttApiKey ? { stt: buildSttConfig(keys.sttApiKey, keys.sttBaseUrl, input) } : {}), - ...(keys.ttsApiKey ? { tts: buildTtsConfig(keys.ttsApiKey, keys.ttsBaseUrl, input) } : {}), - }; -} - -function buildSttConfig( - apiKey: string, - baseUrl: string | undefined, - input: Record, -): OpenAiSpeechProviderConfig["stt"] { - const options = OpenAiSttOptionsSchema.parse(input); - return { - apiKey, - ...(baseUrl ? { baseUrl } : {}), - ...(options.sttConfidenceThreshold !== undefined - ? { confidenceThreshold: options.sttConfidenceThreshold } - : {}), - ...(options.sttModel ? { model: options.sttModel } : {}), - }; -} - -function buildTtsConfig( - apiKey: string, - baseUrl: string | undefined, - input: Record, -): OpenAiSpeechProviderConfig["tts"] { - const options = OpenAiTtsOptionsSchema.parse(input); - return { - apiKey, - ...(baseUrl ? { baseUrl } : {}), - voice: options.ttsVoice, - model: options.ttsModel, - responseFormat: "pcm", + ...(dictationStt ? { dictationStt } : {}), + ...(stt ? { stt } : {}), + ...(tts ? { tts } : {}), }; } diff --git a/packages/server/src/server/speech/providers/openai/runtime.test.ts b/packages/server/src/server/speech/providers/openai/runtime.test.ts index c947d86600..81b14ecaa0 100644 --- a/packages/server/src/server/speech/providers/openai/runtime.test.ts +++ b/packages/server/src/server/speech/providers/openai/runtime.test.ts @@ -1,6 +1,12 @@ +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; import pino from "pino"; -import { describe, expect, test } from "vitest"; +import { afterEach, describe, expect, test } from "vitest"; +import { mergeSpeechSettingsPatch } from "../../speech-settings.js"; +import { PersistedConfigSchema } from "../../../persisted-config.js"; +import type { SpeechToTextProvider } from "../../speech-provider.js"; +import { resolveOpenAiSpeechConfig } from "./config.js"; import { initializeOpenAiSpeechServices } from "./runtime.js"; import { OpenAISTT } from "./stt.js"; import { OpenAITTS } from "./tts.js"; @@ -16,6 +22,7 @@ describe("initializeOpenAiSpeechServices", () => { }, openaiConfig: { stt: { apiKey: "sk-test" }, + dictationStt: { apiKey: "sk-test" }, tts: { apiKey: "sk-test" }, }, existing: { @@ -32,3 +39,116 @@ describe("initializeOpenAiSpeechServices", () => { expect(services.ttsService).toBeInstanceOf(OpenAITTS); }); }); + +// An OpenAI-compatible transcription endpoint that records the model each request asks for. +async function startTranscriptionServer(): Promise<{ + server: Server; + baseUrl: string; + models: string[]; + keys: (string | undefined)[]; + paths: (string | undefined)[]; +}> { + const models: string[] = []; + const keys: (string | undefined)[] = []; + const paths: (string | undefined)[] = []; + const server = createServer((request, response) => { + let body = ""; + request.on("data", (chunk: Buffer) => { + body += chunk.toString("latin1"); + }); + request.on("end", () => { + const model = /name="model"\r\n\r\n([^\r]*)/.exec(body)?.[1]; + models.push(model ?? ""); + keys.push(request.headers.authorization); + paths.push(request.url); + response.writeHead(200, { "content-type": "application/json" }); + response.end(JSON.stringify({ text: "hello" })); + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as AddressInfo; + return { server, baseUrl: `http://127.0.0.1:${port}/v1`, models, keys, paths }; +} + +async function transcribeOnce(stt: SpeechToTextProvider | null): Promise { + if (!stt) throw new Error("STT service was not created"); + const session = stt.createSession({ logger: pino({ level: "silent" }), language: "en" }); + const transcript = new Promise((resolve, reject) => { + session.on("transcript", (event) => { + if (event.isFinal) resolve(); + }); + session.on("error", (error) => + reject(error instanceof Error ? error : new Error(String(error))), + ); + }); + await session.connect(); + session.appendPcm16(Buffer.alloc(3200)); + session.commit(); + await transcript; + session.close(); +} + +describe("OpenAI speech-to-text models", () => { + let server: Server | null = null; + + afterEach(async () => { + await new Promise((resolve) => (server ? server.close(() => resolve()) : resolve())); + server = null; + }); + + test("dictation and voice mode each transcribe with the model chosen for them", async () => { + const endpoint = await startTranscriptionServer(); + server = endpoint.server; + let persisted = PersistedConfigSchema.parse({ + features: { + dictation: { + stt: { + provider: "openai", + apiKey: "dictation-key", + baseUrl: `${endpoint.baseUrl}/dictation`, + model: "gpt-4o-mini-transcribe", + }, + }, + voiceMode: { + enabled: true, + stt: { + provider: "openai", + apiKey: "listening-key", + baseUrl: `${endpoint.baseUrl}/listening`, + model: "whisper-1", + }, + }, + }, + }); + persisted = mergeSpeechSettingsPatch(persisted, { + voiceMode: { stt: { provider: "openai", model: "whisper-1" } }, + }); + const providers = { + dictationStt: { provider: "openai", explicit: true }, + voiceTurnDetection: { provider: "local", explicit: false, enabled: false }, + voiceStt: { provider: "openai", explicit: true }, + voiceTts: { provider: "local", explicit: false }, + } as const; + + const services = initializeOpenAiSpeechServices({ + providers, + openaiConfig: resolveOpenAiSpeechConfig({ env: {}, persisted, providers }), + existing: { + turnDetectionService: null, + sttService: null, + ttsService: null, + dictationSttService: null, + }, + logger: pino({ level: "silent" }), + }); + await transcribeOnce(services.dictationSttService); + await transcribeOnce(services.sttService); + + expect(endpoint.models).toEqual(["gpt-4o-mini-transcribe", "whisper-1"]); + expect(endpoint.keys).toEqual(["Bearer dictation-key", "Bearer listening-key"]); + expect(endpoint.paths).toEqual([ + "/v1/dictation/audio/transcriptions", + "/v1/listening/audio/transcriptions", + ]); + }); +}); diff --git a/packages/server/src/server/speech/providers/openai/runtime.ts b/packages/server/src/server/speech/providers/openai/runtime.ts index a1231ddbe6..ce11c8879c 100644 --- a/packages/server/src/server/speech/providers/openai/runtime.ts +++ b/packages/server/src/server/speech/providers/openai/runtime.ts @@ -3,7 +3,11 @@ import type { Logger } from "pino"; import type { SpeechToTextProvider, TextToSpeechProvider } from "../../speech-provider.js"; import type { RequestedSpeechProviders } from "../../speech-types.js"; import type { TurnDetectionProvider } from "../../turn-detection-provider.js"; -import { DEFAULT_OPENAI_TTS_MODEL, type OpenAiSpeechProviderConfig } from "./config.js"; +import { + DEFAULT_OPENAI_TTS_MODEL, + type OpenAiSpeechProviderConfig, + type OpenAiSttFeature, +} from "./config.js"; import { OpenAISTT } from "./stt.js"; import { OpenAITTS } from "./tts.js"; @@ -33,7 +37,7 @@ function resolveOpenAiCredentials( return { openaiSttApiKey: sttApiKey, openaiTtsApiKey: openaiConfig?.tts?.apiKey, - openaiDictationApiKey: sttApiKey, + openaiDictationApiKey: openaiConfig?.dictationStt?.apiKey, }; } @@ -94,13 +98,16 @@ export function validateOpenAiCredentialRequirements(params: { } } -function createOpenAiStt( - apiKey: string, - openaiConfig: OpenAiSpeechProviderConfig | undefined, - logger: Logger, -): SpeechToTextProvider { - const { apiKey: _sttApiKey, ...sttConfig } = openaiConfig?.stt ?? {}; - return new OpenAISTT({ apiKey, ...sttConfig }, logger); +function createOpenAiStt(params: { + apiKey: string; + openaiConfig: OpenAiSpeechProviderConfig | undefined; + feature: OpenAiSttFeature; + logger: Logger; +}): SpeechToTextProvider { + const site = + params.feature === "dictation" ? params.openaiConfig?.dictationStt : params.openaiConfig?.stt; + const { apiKey: _sttApiKey, ...sttConfig } = site ?? {}; + return new OpenAISTT({ apiKey: params.apiKey, ...sttConfig }, params.logger); } function createOpenAiTts( @@ -154,7 +161,12 @@ export function initializeOpenAiSpeechServices(params: { logger.info("OpenAI speech provider initialized"); if (needsOpenAiStt && openAiCredentials.openaiSttApiKey) { - sttService = createOpenAiStt(openAiCredentials.openaiSttApiKey, openaiConfig, logger); + sttService = createOpenAiStt({ + apiKey: openAiCredentials.openaiSttApiKey, + openaiConfig, + feature: "voiceMode", + logger, + }); } if (needsOpenAiTts && openAiCredentials.openaiTtsApiKey) { @@ -162,11 +174,12 @@ export function initializeOpenAiSpeechServices(params: { } if (needsOpenAiDictation && openAiCredentials.openaiDictationApiKey) { - dictationSttService = createOpenAiStt( - openAiCredentials.openaiDictationApiKey, + dictationSttService = createOpenAiStt({ + apiKey: openAiCredentials.openaiDictationApiKey, openaiConfig, + feature: "dictation", logger, - ); + }); } } else if (needsAnyOpenAi) { // validateOpenAiCredentialRequirements already warned about missing credentials diff --git a/packages/server/src/server/speech/speech-config-resolver.test.ts b/packages/server/src/server/speech/speech-config-resolver.test.ts index 0ee9df888a..c83d2c45fa 100644 --- a/packages/server/src/server/speech/speech-config-resolver.test.ts +++ b/packages/server/src/server/speech/speech-config-resolver.test.ts @@ -6,7 +6,7 @@ import { PersistedConfigSchema } from "../persisted-config.js"; import { resolveSpeechConfig } from "./speech-config-resolver.js"; describe("resolveSpeechConfig", () => { - test("resolves local-first defaults without env overrides", () => { + test("resolves local-first defaults with voice mode off until turned on", () => { const paseoHome = "/tmp/paseo-home"; const persisted = PersistedConfigSchema.parse({}); const env = {} as NodeJS.ProcessEnv; @@ -26,17 +26,17 @@ describe("resolveSpeechConfig", () => { expect(result.speech.providers.voiceTurnDetection).toEqual({ provider: "local", explicit: false, - enabled: true, + enabled: false, }); expect(result.speech.providers.voiceStt).toEqual({ provider: "local", explicit: false, - enabled: true, + enabled: false, }); expect(result.speech.providers.voiceTts).toEqual({ provider: "local", explicit: false, - enabled: true, + enabled: false, }); expect(result.speech.local).toEqual({ modelsDir: path.join(paseoHome, "models", "local-speech"), @@ -61,13 +61,11 @@ describe("resolveSpeechConfig", () => { const persisted = PersistedConfigSchema.parse({ features: { voiceMode: { + enabled: true, turnDetection: { provider: "local" }, - stt: { provider: "openai", model: "gpt-4o-transcribe" }, + stt: { provider: "openai", apiKey: "persisted-key", model: "gpt-4o-transcribe" }, }, }, - providers: { - openai: { apiKey: "persisted-key" }, - }, }); const env = { PASEO_DICTATION_LOCAL_STT_MODEL: "parakeet-tdt-0.6b-v2-int8", @@ -130,40 +128,45 @@ describe("resolveSpeechConfig", () => { voice: "pt", }); expect(result.openai?.stt?.apiKey).toBe("persisted-key"); - expect(result.openai?.tts?.apiKey).toBe("persisted-key"); + expect(result.openai?.tts?.apiKey).toBe("env-key"); expect(result.openai?.stt?.model).toBe("gpt-4o-transcribe"); }); - test("resolves STT language from env, settings, and voice-to-dictation fallback", () => { - const persisted = PersistedConfigSchema.parse({ - features: { - dictation: { - stt: { - language: "fr", + test.each(["local", "openai"])( + "resolves STT language from env, settings, and voice-to-dictation fallback (%s)", + (provider) => { + const persisted = PersistedConfigSchema.parse({ + features: { + dictation: { + stt: { + provider, + language: "fr", + }, + }, + voiceMode: { + stt: { + provider, + language: "de", + }, }, }, - voiceMode: { - stt: { - language: "de", - }, - }, - }, - }); + }); - const result = resolveSpeechConfig({ - paseoHome: "/tmp/paseo-home", - env: { - PASEO_DICTATION_LANGUAGE: "es", - PASEO_VOICE_LANGUAGE: " ", - } as NodeJS.ProcessEnv, - persisted, - }); + const result = resolveSpeechConfig({ + paseoHome: "/tmp/paseo-home", + env: { + PASEO_DICTATION_LANGUAGE: "es", + PASEO_VOICE_LANGUAGE: " ", + } as NodeJS.ProcessEnv, + persisted, + }); - expect(result.speech.sttLanguages).toEqual({ - dictation: "es", - voice: "es", - }); - }); + expect(result.speech.sttLanguages).toEqual({ + dictation: "es", + voice: "es", + }); + }, + ); test("respects disabled dictation and voice mode feature flags", () => { const persisted = PersistedConfigSchema.parse({ diff --git a/packages/server/src/server/speech/speech-config-resolver.ts b/packages/server/src/server/speech/speech-config-resolver.ts index 95c78707a5..1257f46d4d 100644 --- a/packages/server/src/server/speech/speech-config-resolver.ts +++ b/packages/server/src/server/speech/speech-config-resolver.ts @@ -43,8 +43,13 @@ const RequestedSpeechProvidersSchema = z.object({ voiceTts: OptionalSpeechProviderSchema.default("local"), }); -function resolveOptionalBooleanFlag(value: unknown): boolean { - return OptionalBooleanFlagSchema.parse(value) ?? true; +// Dictation is on unless turned off. Voice mode is opt-in: it downloads its own models and +// runs a hidden agent, so a host only pays for it once someone turns it on. +export const DICTATION_ENABLED_BY_DEFAULT = true; +export const VOICE_MODE_ENABLED_BY_DEFAULT = false; + +function resolveOptionalBooleanFlag(value: unknown, fallback: boolean): boolean { + return OptionalBooleanFlagSchema.parse(value) ?? fallback; } interface FeatureProviderInputs { @@ -70,6 +75,7 @@ function buildFeatureProviderInputs(params: { params.env.PASEO_VOICE_MODE_ENABLED, params.persisted.features?.voiceMode?.enabled, ]), + VOICE_MODE_ENABLED_BY_DEFAULT, ); return { dictationStt: { @@ -82,6 +88,7 @@ function buildFeatureProviderInputs(params: { params.env.PASEO_DICTATION_ENABLED, params.persisted.features?.dictation?.enabled, ]), + DICTATION_ENABLED_BY_DEFAULT, ), }, voiceTurnDetection: { @@ -119,7 +126,7 @@ function buildRequestedFeatureProvider( }; } -function resolveRequestedSpeechProviders(params: { +export function resolveRequestedSpeechProviders(params: { env: NodeJS.ProcessEnv; persisted: PersistedConfig; }): RequestedSpeechProviders { @@ -173,6 +180,7 @@ export function resolveSpeechConfig(params: { openai, speech: { providers, + localModelsDir: local.modelsDir, sttLanguages: local.sttLanguages, ...(local.local ? { local: local.local } : {}), }, diff --git a/packages/server/src/server/speech/speech-runtime.test.ts b/packages/server/src/server/speech/speech-runtime.test.ts index c9c21b3e89..cd3580e64a 100644 --- a/packages/server/src/server/speech/speech-runtime.test.ts +++ b/packages/server/src/server/speech/speech-runtime.test.ts @@ -2,13 +2,14 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import pino from "pino"; import type { PaseoSpeechConfig } from "../bootstrap.js"; +import type { LocalSpeechModelId } from "./providers/local/models.js"; import type { InitializedLocalSpeech } from "./providers/local/runtime.js"; import type { SpeechToTextProvider, TextToSpeechProvider } from "./speech-provider.js"; import type { TurnDetectionProvider } from "./turn-detection-provider.js"; -import { createSpeechService } from "./speech-runtime.js"; +import { createSpeechService, LocalSpeechModelInUseError } from "./speech-runtime.js"; -const { ensureLocalSpeechModelsMock, initializeLocalSpeechServicesMock } = vi.hoisted(() => ({ - ensureLocalSpeechModelsMock: vi.fn(async () => ({})), +const { ensureSherpaOnnxModelMock, initializeLocalSpeechServicesMock } = vi.hoisted(() => ({ + ensureSherpaOnnxModelMock: vi.fn(async (_options: { signal?: AbortSignal }) => ""), initializeLocalSpeechServicesMock: vi.fn<(args: unknown) => Promise>(), })); @@ -34,9 +35,10 @@ vi.mock("./providers/openai/runtime.js", () => ({ validateOpenAiCredentialRequirements: () => {}, })); -vi.mock("./providers/local/models.js", () => ({ - ensureLocalSpeechModels: ensureLocalSpeechModelsMock, - listMissingLocalSpeechModels: vi.fn(async ({ modelIds }: { modelIds: string[] }) => modelIds), +vi.mock("./providers/local/sherpa/model-downloader.js", () => ({ + ensureSherpaOnnxModel: ensureSherpaOnnxModelMock, + isSherpaOnnxModelInstalled: vi.fn(async () => false), + deleteSherpaOnnxModel: vi.fn(async () => {}), })); function createStubStt(id: string): SpeechToTextProvider { @@ -75,6 +77,7 @@ function rejectWhenAborted(signal?: AbortSignal): Promise { function createSpeechConfig(providers: PaseoSpeechConfig["providers"]): PaseoSpeechConfig { return { providers, + localModelsDir: "/tmp/missing-local-speech-models", sttLanguages: { dictation: "en", voice: "en", @@ -84,8 +87,8 @@ function createSpeechConfig(providers: PaseoSpeechConfig["providers"]): PaseoSpe describe("createSpeechService readiness", () => { beforeEach(() => { - ensureLocalSpeechModelsMock.mockReset(); - ensureLocalSpeechModelsMock.mockResolvedValue({}); + ensureSherpaOnnxModelMock.mockReset(); + ensureSherpaOnnxModelMock.mockResolvedValue(""); initializeLocalSpeechServicesMock.mockReset(); }); @@ -169,7 +172,7 @@ describe("createSpeechService readiness", () => { it("aborts and joins an in-flight model download when stopped", async () => { let downloadSignal: AbortSignal | undefined; - ensureLocalSpeechModelsMock.mockImplementation(({ signal }: { signal?: AbortSignal }) => { + ensureSherpaOnnxModelMock.mockImplementation(({ signal }: { signal?: AbortSignal }) => { downloadSignal = signal; return rejectWhenAborted(signal); }); @@ -201,10 +204,104 @@ describe("createSpeechService readiness", () => { }); runtime.start(); await runtime.ready; - expect(ensureLocalSpeechModelsMock).toHaveBeenCalledOnce(); + expect(ensureSherpaOnnxModelMock).toHaveBeenCalledOnce(); await runtime.stop(); expect(downloadSignal?.aborted).toBe(true); }); }); + +describe("createSpeechService settings changes", () => { + const dictationOnly = createSpeechConfig({ + dictationStt: { provider: "local", enabled: true, explicit: true }, + voiceTurnDetection: { provider: "local", enabled: false, explicit: true }, + voiceStt: { provider: "local", enabled: false, explicit: true }, + voiceTts: { provider: "local", enabled: false, explicit: true }, + }); + const nothingEnabled = createSpeechConfig({ + dictationStt: { provider: "local", enabled: false, explicit: true }, + voiceTurnDetection: { provider: "local", enabled: false, explicit: true }, + voiceStt: { provider: "local", enabled: false, explicit: true }, + voiceTts: { provider: "local", enabled: false, explicit: true }, + }); + + function localSpeech(input: { + dictationStt: SpeechToTextProvider | null; + defaultModelIds: LocalSpeechModelId[]; + }): InitializedLocalSpeech { + return { + turnDetectionService: null, + sttService: null, + ttsService: null, + dictationSttService: input.dictationStt, + localVoiceTtsProvider: null, + localModelConfig: { + modelsDir: "/tmp/missing-local-speech-models", + defaultModelIds: input.defaultModelIds, + }, + availability: { configured: true, modelsDir: "/tmp/missing-local-speech-models" }, + cleanup: () => {}, + }; + } + + beforeEach(() => { + ensureSherpaOnnxModelMock.mockReset(); + ensureSherpaOnnxModelMock.mockResolvedValue(""); + initializeLocalSpeechServicesMock.mockReset(); + }); + + it("applies new providers without a restart", async () => { + initializeLocalSpeechServicesMock.mockResolvedValue( + localSpeech({ dictationStt: createStubStt("dictation-local"), defaultModelIds: [] }), + ); + const runtime = createSpeechService({ + logger: pino({ level: "silent" }), + speechConfig: dictationOnly, + }); + runtime.start(); + await runtime.ready; + expect(runtime.getReadiness().dictation.available).toBe(true); + + const disabled = new Promise((resolve) => { + runtime.onReadinessChange((snapshot) => { + if (snapshot.dictation.reasonCode === "disabled") resolve(); + }); + }); + initializeLocalSpeechServicesMock.mockResolvedValue( + localSpeech({ dictationStt: null, defaultModelIds: [] }), + ); + runtime.reconfigure({ speechConfig: nothingEnabled }); + await disabled; + + expect(runtime.resolveDictationStt()).toBeNull(); + await runtime.stop(); + }); + + it("refuses to delete a model an enabled feature uses", async () => { + initializeLocalSpeechServicesMock.mockResolvedValue( + localSpeech({ + dictationStt: createStubStt("dictation-local"), + defaultModelIds: ["parakeet-tdt-0.6b-v2-int8"], + }), + ); + ensureSherpaOnnxModelMock.mockImplementation(({ signal }) => rejectWhenAborted(signal)); + const runtime = createSpeechService({ + logger: pino({ level: "silent" }), + speechConfig: dictationOnly, + }); + runtime.start(); + await runtime.ready; + + const models = await runtime.listLocalModels(); + expect(models.filter((model) => model.inUse).map((model) => model.spec.id)).toEqual([ + "parakeet-tdt-0.6b-v2-int8", + ]); + await expect(runtime.deleteLocalModel("parakeet-tdt-0.6b-v2-int8")).rejects.toBeInstanceOf( + LocalSpeechModelInUseError, + ); + await expect(runtime.deleteLocalModel("kokoro-int8-en-v0_19")).resolves.toBeUndefined(); + + await runtime.stop(); + }); +}); diff --git a/packages/server/src/server/speech/speech-runtime.ts b/packages/server/src/server/speech/speech-runtime.ts index 932f87c077..270b13b03c 100644 --- a/packages/server/src/server/speech/speech-runtime.ts +++ b/packages/server/src/server/speech/speech-runtime.ts @@ -2,7 +2,10 @@ import type { Logger } from "pino"; import type { PaseoOpenAIConfig, PaseoSpeechConfig } from "../bootstrap.js"; import type { LocalSpeechModelId } from "./providers/local/config.js"; -import { ensureLocalSpeechModels, listMissingLocalSpeechModels } from "./providers/local/models.js"; +import { + LocalSpeechModelLibrary, + type LocalSpeechModelEntry, +} from "./providers/local/model-library.js"; import { initializeLocalSpeechServices } from "./providers/local/runtime.js"; import { getOpenAiSpeechAvailability, @@ -92,7 +95,7 @@ function buildRealtimeVoiceReadiness(params: { enabled: false, available: false, reasonCode: "disabled", - message: "Realtime voice is disabled in daemon config.", + message: "Voice mode is off. Turn it on in Settings > Voice.", retryable: false, missingModelIds: [], }; @@ -147,7 +150,7 @@ function buildDictationReadiness(params: { enabled: false, available: false, reasonCode: "disabled", - message: "Dictation is disabled in daemon config.", + message: "Dictation is off. Turn it on in Settings > Voice.", retryable: false, missingModelIds: [], }; @@ -292,6 +295,23 @@ function resolveEffectiveProviderIds(params: { }; } +export interface LocalSpeechModelStatus extends LocalSpeechModelEntry { + // Selected by an enabled feature, so the runtime keeps it installed. + inUse: boolean; +} + +export class LocalSpeechModelInUseError extends Error { + constructor(public readonly modelId: LocalSpeechModelId) { + super(`${modelId} is selected for dictation or voice mode. Choose another model first.`); + this.name = "LocalSpeechModelInUseError"; + } +} + +export interface SpeechServiceConfig { + openaiConfig?: PaseoOpenAIConfig; + speechConfig?: PaseoSpeechConfig; +} + export interface SpeechService { resolveStt: () => SpeechToTextProvider | null; resolveSttLanguage: () => string; @@ -301,37 +321,49 @@ export interface SpeechService { resolveDictationSttLanguage: () => string; getReadiness: () => SpeechReadinessSnapshot; onReadinessChange: (listener: (snapshot: SpeechReadinessSnapshot) => void) => () => void; + // Applies new provider/model settings without restarting the daemon. + reconfigure: (config: SpeechServiceConfig) => void; + listLocalModels: () => Promise; + downloadLocalModel: (modelId: LocalSpeechModelId) => void; + deleteLocalModel: (modelId: LocalSpeechModelId) => Promise; start: () => void; stop: () => Promise; ready: Promise; } -export function createSpeechService(params: { - logger: Logger; - openaiConfig?: PaseoOpenAIConfig; - speechConfig?: PaseoSpeechConfig; -}): SpeechService { +export function createSpeechService( + params: SpeechServiceConfig & { + logger: Logger; + }, +): SpeechService { const logger = params.logger.child({ module: "speech-runtime" }); - const speechConfig = params.speechConfig ?? null; - const openaiConfig = params.openaiConfig; - const providers = resolveRequestedSpeechProviders(speechConfig); - const requestedProviders = describeRequestedProviders(providers); + let speechConfig = params.speechConfig ?? null; + let openaiConfig = params.openaiConfig; + let providers = resolveRequestedSpeechProviders(speechConfig); + let requestedProviders = describeRequestedProviders(providers); + // The models directory is fixed for the daemon's lifetime; settings changes only pick + // which of its models are used. + const modelLibrary = speechConfig + ? new LocalSpeechModelLibrary(speechConfig.localModelsDir, logger) + : null; - validateOpenAiCredentialRequirements({ - providers, - openaiConfig, - logger, - }); - - logger.info( - { - requestedProviders, - availability: { - openai: getOpenAiSpeechAvailability(openaiConfig), + const logReconciliationStart = (): void => { + validateOpenAiCredentialRequirements({ + providers, + openaiConfig, + logger, + }); + logger.info( + { + requestedProviders, + availability: { + openai: getOpenAiSpeechAvailability(openaiConfig), + }, }, - }, - "Speech provider reconciliation started", - ); + "Speech provider reconciliation started", + ); + }; + logReconciliationStart(); let sttService: SpeechToTextProvider | null = null; let ttsService: TextToSpeechProvider | null = null; @@ -346,12 +378,11 @@ export function createSpeechService(params: { let missingLocalModelIds: LocalSpeechModelId[] = []; let backgroundDownloadInProgress = false; - let backgroundDownloadAbortController: AbortController | null = null; let backgroundDownloadPromise: Promise | null = null; let backgroundDownloadError: string | null = null; let stopped = false; let monitorTimeout: ReturnType | null = null; - let reconcileInFlight: Promise | null = null; + let reconcileQueue: Promise = Promise.resolve(); const readinessListeners = new Set<(snapshot: SpeechReadinessSnapshot) => void>(); let lastReadinessFingerprint: string | null = null; let lastPublishedReadinessSnapshot: SpeechReadinessSnapshot | null = null; @@ -445,12 +476,10 @@ export function createSpeechService(params: { }; const refreshMissingLocalModels = async (): Promise => { - missingLocalModelIds = localModelConfig - ? await listMissingLocalSpeechModels({ - modelsDir: localModelConfig.modelsDir, - modelIds: localModelConfig.defaultModelIds, - }) - : []; + missingLocalModelIds = + localModelConfig && modelLibrary + ? await modelLibrary.listMissing(localModelConfig.defaultModelIds) + : []; }; const reconcileServices = async (): Promise => { @@ -520,16 +549,12 @@ export function createSpeechService(params: { } }; + // Reconciles run one after another, and each starts after it was requested, so a + // reconfigure that lands mid-reconcile is applied instead of joining the stale run. const runReconcile = async (): Promise => { - if (reconcileInFlight) { - await reconcileInFlight; - publishReadinessIfChanged(); - return; - } - reconcileInFlight = reconcileServices().finally(() => { - reconcileInFlight = null; - }); - await reconcileInFlight; + const next = reconcileQueue.catch(() => undefined).then(reconcileServices); + reconcileQueue = next; + await next; publishReadinessIfChanged(); }; @@ -544,12 +569,12 @@ export function createSpeechService(params: { }; const startBackgroundDownload = (): void => { - if (stopped || backgroundDownloadInProgress) { + if (stopped || backgroundDownloadInProgress || !modelLibrary) { return; } - const modelsDir = localModelConfig?.modelsDir ?? null; + const modelsDir = modelLibrary.getModelsDir(); const modelIds = [...missingLocalModelIds]; - if (!modelsDir || modelIds.length === 0) { + if (modelIds.length === 0) { return; } @@ -565,16 +590,9 @@ export function createSpeechService(params: { "Starting background download for missing local speech models", ); - const abortController = new AbortController(); - backgroundDownloadAbortController = abortController; backgroundDownloadPromise = (async () => { try { - await ensureLocalSpeechModels({ - modelsDir, - modelIds, - logger, - signal: abortController.signal, - }); + await Promise.all(modelIds.map((modelId) => modelLibrary.download(modelId))); await runReconcile(); backgroundDownloadError = null; } catch (error) { @@ -588,7 +606,6 @@ export function createSpeechService(params: { "Background local speech model download failed", ); } finally { - backgroundDownloadAbortController = null; backgroundDownloadInProgress = false; await refreshMissingLocalModels().catch((error) => { logger.warn({ err: error }, "Failed to refresh local speech model status after download"); @@ -630,6 +647,62 @@ export function createSpeechService(params: { } }; + const reconcileAndFetchMissingModels = async (): Promise => { + await runReconcile(); + const snapshot = computeReadinessSnapshot(); + if (snapshot.voiceFeature.enabled && !snapshot.voiceFeature.available) { + if (missingLocalModelIds.length > 0) { + startBackgroundDownload(); + } + scheduleMonitor(); + } + }; + + const reconfigure = (next: SpeechServiceConfig): void => { + speechConfig = next.speechConfig ?? null; + openaiConfig = next.openaiConfig; + providers = resolveRequestedSpeechProviders(speechConfig); + requestedProviders = describeRequestedProviders(providers); + // A failure for the previous selection must not block downloading the new one. + backgroundDownloadError = null; + logReconciliationStart(); + if (!started || stopped) { + return; + } + void reconcileAndFetchMissingModels().catch((error) => { + logger.error({ err: error }, "Speech runtime failed to apply new configuration"); + }); + }; + + const requireModelLibrary = (): LocalSpeechModelLibrary => { + if (!modelLibrary) { + throw new Error("Local speech models are unavailable on this daemon"); + } + return modelLibrary; + }; + + const listLocalModels = async (): Promise => { + const inUse = new Set(localModelConfig?.defaultModelIds ?? []); + const entries = await requireModelLibrary().list(); + return entries.map(({ spec, state }) => ({ spec, state, inUse: inUse.has(spec.id) })); + }; + + const downloadLocalModel = (modelId: LocalSpeechModelId): void => { + void requireModelLibrary() + .download(modelId) + .then(() => runMonitorTick()) + .catch((error) => { + logger.warn({ err: error, modelId }, "Local speech model download failed"); + }); + }; + + const deleteLocalModel = async (modelId: LocalSpeechModelId): Promise => { + if (localModelConfig?.defaultModelIds.includes(modelId)) { + throw new LocalSpeechModelInUseError(modelId); + } + await requireModelLibrary().delete(modelId); + }; + const start = (): void => { if (started || stopped) { return; @@ -637,14 +710,7 @@ export function createSpeechService(params: { started = true; void (async () => { try { - await runReconcile(); - const snapshot = computeReadinessSnapshot(); - if (snapshot.voiceFeature.enabled && !snapshot.voiceFeature.available) { - if (missingLocalModelIds.length > 0) { - startBackgroundDownload(); - } - scheduleMonitor(); - } + await reconcileAndFetchMissingModels(); if (!readySettled) { readySettled = true; resolveReady(); @@ -666,7 +732,7 @@ export function createSpeechService(params: { monitorTimeout = null; } localCleanup(); - backgroundDownloadAbortController?.abort(); + await modelLibrary?.stop(); await backgroundDownloadPromise?.catch(() => undefined); backgroundDownloadPromise = null; }; @@ -680,6 +746,10 @@ export function createSpeechService(params: { resolveDictationSttLanguage: () => speechConfig?.sttLanguages?.dictation ?? "en", getReadiness: () => lastPublishedReadinessSnapshot ?? computeReadinessSnapshot(), onReadinessChange: subscribeSpeechReadiness, + reconfigure, + listLocalModels, + downloadLocalModel, + deleteLocalModel, start, stop, ready, diff --git a/packages/server/src/server/speech/speech-settings.ts b/packages/server/src/server/speech/speech-settings.ts new file mode 100644 index 0000000000..31995c46f6 --- /dev/null +++ b/packages/server/src/server/speech/speech-settings.ts @@ -0,0 +1,202 @@ +import type { SpeechSettings, SpeechSettingsPatch } from "@getpaseo/protocol/speech/rpc-schemas"; + +import { + PersistedConfigSchema, + SpeechSttConfigSchema, + SpeechTtsConfigSchema, + type PersistedConfig, +} from "../persisted-config.js"; +import { resolveRequestedSpeechProviders, resolveSpeechConfig } from "./speech-config-resolver.js"; +import type { SpeechService } from "./speech-runtime.js"; +import { LocalSttModelIdSchema, LocalTtsModelIdSchema } from "./providers/local/models.js"; + +interface SpeechRead { + features: SpeechSettings; + envOverrides: Record; +} + +// Owns the per-site wire boundary: credential redaction, env provenance and patch +// semantics. The store never assembles or merges provider objects itself. +export interface SpeechSettingsOwner { + read(persisted: PersistedConfig): SpeechRead; + apply(persisted: PersistedConfig): void; +} + +export function createSpeechSettingsOwner(params: { + paseoHome: string; + env: NodeJS.ProcessEnv; + speechService: Pick; +}): SpeechSettingsOwner { + const { paseoHome, env, speechService } = params; + return { + read: (persisted) => readSpeechSettings(persisted, env), + apply: (persisted) => { + const resolved = resolveSpeechConfig({ paseoHome, env, persisted }); + speechService.reconfigure({ openaiConfig: resolved.openai, speechConfig: resolved.speech }); + }, + }; +} + +export function readSpeechSettings(persisted: PersistedConfig, env: NodeJS.ProcessEnv): SpeechRead { + const dictation = persisted.features?.dictation; + const voiceMode = persisted.features?.voiceMode; + const providers = resolveRequestedSpeechProviders({ persisted, env }); + const envOverrides: Record = {}; + const recordOverride = (path: string, names: string[], fallback?: unknown) => { + if (fallback !== undefined) return; + const name = names.find((candidate) => env[candidate]?.trim()); + if (name) envOverrides[path] = name; + }; + recordOverride("features.dictation.enabled", ["PASEO_DICTATION_ENABLED"]); + recordOverride("features.voiceMode.enabled", ["PASEO_VOICE_MODE_ENABLED"]); + recordOverride("features.voiceMode.turnDetection.provider", [ + "PASEO_VOICE_TURN_DETECTION_PROVIDER", + ]); + + function readSite( + site: Record | undefined, + provider: string, + path: string, + kind: "stt" | "tts", + providerEnv: string, + localModelEnv: string, + ) { + recordOverride(`${path}.provider`, [providerEnv]); + const configured = site?.provider === provider ? site : undefined; + const { apiKey, ...fields } = configured ?? {}; + const openaiModelEnv = kind === "stt" ? "STT_MODEL" : "TTS_MODEL"; + recordOverride(`${path}.model`, [provider === "openai" ? openaiModelEnv : localModelEnv]); + if (kind === "stt") { + const languageVars = + path === "features.dictation.stt" + ? ["PASEO_DICTATION_LANGUAGE"] + : ["PASEO_VOICE_LANGUAGE", "PASEO_DICTATION_LANGUAGE"]; + recordOverride(`${path}.language`, languageVars); + } + if (provider === "openai") { + for (const [field, suffix] of [ + ["apiKey", "API_KEY"], + ["baseUrl", "BASE_URL"], + ] as const) { + recordOverride( + `${path}.${field}`, + [`OPENAI_${kind.toUpperCase()}_${suffix}`, `OPENAI_${suffix}`], + configured?.[field], + ); + } + if (kind === "stt") { + recordOverride(`${path}.confidenceThreshold`, ["STT_CONFIDENCE_THRESHOLD"]); + } else recordOverride(`${path}.voice`, ["TTS_VOICE"]); + } else if (kind === "tts") { + recordOverride(`${path}.speakerId`, ["PASEO_VOICE_LOCAL_TTS_SPEAKER_ID"]); + recordOverride(`${path}.speed`, ["PASEO_VOICE_LOCAL_TTS_SPEED"]); + } + return { + ...fields, + provider, + ...(provider === "openai" + ? { hasApiKey: typeof apiKey === "string" && apiKey.trim().length > 0 } + : {}), + }; + } + + return { + features: { + dictation: { + enabled: providers.dictationStt.enabled !== false, + stt: readSite( + dictation?.stt, + providers.dictationStt.provider, + "features.dictation.stt", + "stt", + "PASEO_DICTATION_STT_PROVIDER", + "PASEO_DICTATION_LOCAL_STT_MODEL", + ), + }, + voiceMode: { + enabled: providers.voiceStt.enabled !== false, + ...(voiceMode?.llm ? { llm: voiceMode.llm } : {}), + ...(voiceMode?.turnDetection + ? { + turnDetection: { + ...voiceMode.turnDetection, + provider: providers.voiceTurnDetection.provider, + }, + } + : {}), + stt: readSite( + voiceMode?.stt, + providers.voiceStt.provider, + "features.voiceMode.stt", + "stt", + "PASEO_VOICE_STT_PROVIDER", + "PASEO_VOICE_LOCAL_STT_MODEL", + ), + tts: readSite( + voiceMode?.tts, + providers.voiceTts.provider, + "features.voiceMode.tts", + "tts", + "PASEO_VOICE_TTS_PROVIDER", + "PASEO_VOICE_LOCAL_TTS_MODEL", + ), + }, + }, + envOverrides, + }; +} + +function mergeFields(current: Record | undefined, patch: Record) { + const next = { ...current }; + for (const [key, value] of Object.entries(patch)) { + if (value === undefined) continue; + if (value === null || (typeof value === "string" && !value.trim())) delete next[key]; + else next[key] = typeof value === "string" ? value.trim() : value; + } + return next; +} + +function mergeSite( + current: Record | undefined, + patch: Record, + kind: "stt" | "tts", +) { + const providerChanged = + patch.provider !== undefined && patch.provider !== (current?.provider ?? "local"); + const next = mergeFields(providerChanged ? undefined : current, patch); + next.provider ??= "local"; + const site = (kind === "stt" ? SpeechSttConfigSchema : SpeechTtsConfigSchema).parse(next); + if (site.provider === "local" && site.model !== undefined) { + const schema = kind === "stt" ? LocalSttModelIdSchema : LocalTtsModelIdSchema; + if (!schema.safeParse(site.model).success) { + throw new Error( + `Unknown local ${kind === "stt" ? "speech-to-text" : "voice"} model: ${site.model}`, + ); + } + } + return site; +} + +export function mergeSpeechSettingsPatch( + persisted: PersistedConfig, + patch: SpeechSettingsPatch, +): PersistedConfig { + const features = { ...persisted.features }; + if (patch.dictation) { + const { stt, ...rest } = patch.dictation; + const next = mergeFields(features.dictation, rest); + if (stt) next.stt = mergeSite(features.dictation?.stt, stt, "stt"); + features.dictation = PersistedConfigSchema.shape.features.unwrap().shape.dictation.parse(next); + } + if (patch.voiceMode) { + const { stt, tts, llm, turnDetection, ...rest } = patch.voiceMode; + const next = mergeFields(features.voiceMode, rest); + if (stt) next.stt = mergeSite(features.voiceMode?.stt, stt, "stt"); + if (tts) next.tts = mergeSite(features.voiceMode?.tts, tts, "tts"); + if (llm) next.llm = mergeFields(features.voiceMode?.llm, llm); + if (turnDetection) + next.turnDetection = mergeFields(features.voiceMode?.turnDetection, turnDetection); + features.voiceMode = PersistedConfigSchema.shape.features.unwrap().shape.voiceMode.parse(next); + } + return { ...persisted, features }; +} diff --git a/packages/server/src/server/test-utils/paseo-daemon.ts b/packages/server/src/server/test-utils/paseo-daemon.ts index 289d556bec..a1f8369b59 100644 --- a/packages/server/src/server/test-utils/paseo-daemon.ts +++ b/packages/server/src/server/test-utils/paseo-daemon.ts @@ -39,7 +39,8 @@ interface TestPaseoDaemonOptions { staticDir?: string; cleanup?: boolean; openai?: PaseoOpenAIConfig; - speech?: PaseoSpeechConfig; + // localModelsDir defaults to the local provider's modelsDir, then to a dir under paseoHome. + speech?: Omit & { localModelsDir?: string }; voiceLlmProvider?: PaseoDaemonConfig["voiceLlmProvider"]; voiceLlmProviderExplicit?: boolean; voiceLlmModel?: string | null; @@ -209,7 +210,15 @@ async function prepareTestDaemonConfig( webUi: options.webUi, trustedProxies: options.trustedProxies, openai: options.openai, - speech: options.speech, + speech: options.speech + ? { + ...options.speech, + localModelsDir: + options.speech.localModelsDir ?? + options.speech.local?.modelsDir ?? + path.join(paseoHome, "models", "local-speech"), + } + : undefined, voiceLlmProvider: options.voiceLlmProvider ?? null, voiceLlmProviderExplicit: options.voiceLlmProviderExplicit ?? false, voiceLlmModel: options.voiceLlmModel ?? null, diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index 69f116f25b..53172b2835 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -1620,6 +1620,7 @@ export class VoiceAssistantWebSocketServer { stt: () => this.speech?.resolveStt() ?? null, sttLanguage: this.speech?.resolveSttLanguage() ?? "en", tts: () => this.speech?.resolveTts() ?? null, + speechModels: this.speech, terminalManager: this.terminalManager, providerSnapshotManager: this.providerSnapshotManager, hubExecutionAgents: options.hubExecutionAgents, @@ -1991,6 +1992,8 @@ export class VoiceAssistantWebSocketServer { ...(this.advertiseDaemonStatusRpc ? { daemonStatusRpc: true } : {}), // COMPAT(daemonConfigReload): added in v0.4.0, remove gate after 2027-02-14. daemonConfigReload: true, + // COMPAT(speechSettings): added in v0.12.0, remove gate after 2027-04-18. + speechSettings: true, // COMPAT(relayConfig): added in v0.2.6, remove gate after 2027-01-31. ...(this.advertiseRelayConfig ? { relayConfig: true } : {}), // COMPAT(pushTokenRevocation): added in v0.3.2, remove gate after 2027-02-10. diff --git a/packages/website/public/schemas/paseo.config.v1.json b/packages/website/public/schemas/paseo.config.v1.json index a6d0ed4541..c1c32ed20a 100644 --- a/packages/website/public/schemas/paseo.config.v1.json +++ b/packages/website/public/schemas/paseo.config.v1.json @@ -257,48 +257,6 @@ "providers": { "type": "object", "properties": { - "openai": { - "type": "object", - "properties": { - "apiKey": { - "type": "string", - "minLength": 1 - }, - "baseUrl": { - "type": "string", - "minLength": 1 - }, - "stt": { - "type": "object", - "properties": { - "apiKey": { - "type": "string", - "minLength": 1 - }, - "baseUrl": { - "type": "string", - "minLength": 1 - } - }, - "additionalProperties": false - }, - "tts": { - "type": "object", - "properties": { - "apiKey": { - "type": "string", - "minLength": 1 - }, - "baseUrl": { - "type": "string", - "minLength": 1 - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, "local": { "type": "object", "properties": { @@ -639,24 +597,57 @@ "type": "boolean" }, "stt": { - "type": "object", - "properties": { - "provider": { - "type": "string" + "oneOf": [ + { + "type": "object", + "properties": { + "provider": { + "type": "string", + "const": "local" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "language": { + "type": "string", + "minLength": 1 + } + }, + "required": ["provider"], + "additionalProperties": false }, - "model": { - "type": "string", - "minLength": 1 - }, - "language": { - "type": "string", - "minLength": 1 - }, - "confidenceThreshold": { - "type": "number" + { + "type": "object", + "properties": { + "provider": { + "type": "string", + "const": "openai" + }, + "apiKey": { + "type": "string", + "minLength": 1 + }, + "baseUrl": { + "type": "string", + "minLength": 1 + }, + "model": { + "type": "string", + "minLength": 1 + }, + "language": { + "type": "string", + "minLength": 1 + }, + "confidenceThreshold": { + "type": "number" + } + }, + "required": ["provider"], + "additionalProperties": false } - }, - "additionalProperties": false + ] } }, "additionalProperties": false @@ -681,21 +672,57 @@ "additionalProperties": false }, "stt": { - "type": "object", - "properties": { - "provider": { - "type": "string" + "oneOf": [ + { + "type": "object", + "properties": { + "provider": { + "type": "string", + "const": "local" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "language": { + "type": "string", + "minLength": 1 + } + }, + "required": ["provider"], + "additionalProperties": false }, - "model": { - "type": "string", - "minLength": 1 - }, - "language": { - "type": "string", - "minLength": 1 + { + "type": "object", + "properties": { + "provider": { + "type": "string", + "const": "openai" + }, + "apiKey": { + "type": "string", + "minLength": 1 + }, + "baseUrl": { + "type": "string", + "minLength": 1 + }, + "model": { + "type": "string", + "minLength": 1 + }, + "language": { + "type": "string", + "minLength": 1 + }, + "confidenceThreshold": { + "type": "number" + } + }, + "required": ["provider"], + "additionalProperties": false } - }, - "additionalProperties": false + ] }, "turnDetection": { "type": "object", @@ -707,29 +734,58 @@ "additionalProperties": false }, "tts": { - "type": "object", - "properties": { - "provider": { - "type": "string" + "oneOf": [ + { + "type": "object", + "properties": { + "provider": { + "type": "string", + "const": "local" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "speakerId": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "speed": { + "type": "number" + } + }, + "required": ["provider"], + "additionalProperties": false }, - "model": { - "type": "string", - "minLength": 1 - }, - "voice": { - "type": "string", - "minLength": 1 - }, - "speakerId": { - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991 - }, - "speed": { - "type": "number" + { + "type": "object", + "properties": { + "provider": { + "type": "string", + "const": "openai" + }, + "apiKey": { + "type": "string", + "minLength": 1 + }, + "baseUrl": { + "type": "string", + "minLength": 1 + }, + "model": { + "type": "string", + "minLength": 1 + }, + "voice": { + "type": "string", + "minLength": 1 + } + }, + "required": ["provider"], + "additionalProperties": false } - }, - "additionalProperties": false + ] } }, "additionalProperties": false diff --git a/public-docs/configuration.md b/public-docs/configuration.md index d9b3d59f8d..f89a12dcf7 100644 --- a/public-docs/configuration.md +++ b/public-docs/configuration.md @@ -116,7 +116,7 @@ Relative paths are resolved against `PASEO_HOME`. Existing worktrees remain wher ## Voice -Voice is configured through `features.dictation` and `features.voiceMode`, with provider credentials under `providers`. +Voice is configured through `features.dictation` and `features.voiceMode`. Provider credentials and options live inline at `features.dictation.stt`, `features.voiceMode.stt`, and `features.voiceMode.tts`. For voice philosophy, architecture, and complete local/OpenAI setup examples, see [Voice docs](/docs/voice). @@ -269,9 +269,9 @@ Set the persisted value in `config.json`: - `PASEO_LOG_FILE_ROTATE_SIZE`, override `log.file.rotate.maxSize` - `PASEO_LOG_FILE_ROTATE_COUNT`, override `log.file.rotate.maxFiles` - `PASEO_LOG`, `PASEO_LOG_FORMAT`, legacy log overrides (still supported) -- `OPENAI_API_KEY`, override OpenAI provider key -- `OPENAI_STT_API_KEY`, `OPENAI_STT_BASE_URL`, OpenAI speech-to-text endpoint (dictation + voice mode STT) -- `OPENAI_TTS_API_KEY`, `OPENAI_TTS_BASE_URL`, OpenAI text-to-speech endpoint (voice mode TTS) +- `OPENAI_API_KEY`, `OPENAI_BASE_URL`, fallback speech credentials and base URL when neither a site value nor an endpoint env value is set +- `OPENAI_STT_API_KEY`, `OPENAI_STT_BASE_URL`, speech-to-text key and base URL fallbacks when no value is saved at the dictation or voice-mode STT site +- `OPENAI_TTS_API_KEY`, `OPENAI_TTS_BASE_URL`, text-to-speech key and base URL fallbacks when no value is saved at the voice-mode TTS site - `PASEO_VOICE_LLM_PROVIDER`, override voice LLM provider (`claude`, `codex`, `opencode`) - `PASEO_DICTATION_STT_PROVIDER`, `PASEO_VOICE_STT_PROVIDER`, `PASEO_VOICE_TTS_PROVIDER`, override voice provider selection (`local` or `openai`) - `PASEO_LOCAL_MODELS_DIR`, control local model directory diff --git a/public-docs/voice.md b/public-docs/voice.md index 79022c15ad..c90e5196bc 100644 --- a/public-docs/voice.md +++ b/public-docs/voice.md @@ -27,27 +27,24 @@ This keeps credentials and execution in your environment and avoids introducing Local speech defaults to model IDs `parakeet-tdt-0.6b-v2-int8` (STT) and `kokoro-en-v0_19` (TTS, speaker 0 / voice 00). -Missing models are downloaded at daemon startup into `$PASEO_HOME/models/local-speech`. Downloads happen only for missing files. +Dictation is on by default. Voice mode is off until you turn it on in **Settings > Voice** or set `features.voiceMode.enabled: true`. + +Missing models for enabled features are downloaded at daemon startup into `$PASEO_HOME/models/local-speech`. Downloads happen only for missing files. **Settings > Voice** lists every local model with its size and languages, and lets you download or delete each one. ### Local STT models and language support -| Model ID | Languages | -| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `parakeet-tdt-0.6b-v2-int8` | English only (default). Includes punctuation and capitalization. | -| `parakeet-tdt-0.6b-v3-int8` | 25 European languages, auto-detected: Bulgarian, Croatian, Czech, Danish, Dutch, English, Estonian, Finnish, French, German, Greek, Hungarian, Italian, Latvian, Lithuanian, Maltese, Polish, Portuguese, Romanian, Russian, Slovak, Slovenian, Spanish, Swedish, Ukrainian. | - -**To use a non-English language, switch the local STT model to `parakeet-tdt-0.6b-v3-int8`.** v3 detects the spoken language automatically — there is no per-language setting for it. The `language` field below does **not** steer the local Parakeet model (v2 is English-only, v3 auto-detects); it only applies to the OpenAI STT provider. +**Settings > Voice** lists every local STT model with the languages it supports. The default, `parakeet-tdt-0.6b-v2-int8`, is English-only. For other languages, pick a multilingual model such as `parakeet-tdt-0.6b-v3-int8` (25 European languages) or `whisper-base` (99 languages). The `language` field is passed to STT sessions for both providers. Local recognizers currently detect the spoken language themselves; setting `language` does not expand a model’s supported languages. ```json { "version": 1, "features": { "dictation": { - "stt": { "provider": "local", "model": "parakeet-tdt-0.6b-v2-int8", "language": "en" } + "stt": { "provider": "local", "model": "parakeet-tdt-0.6b-v2-int8" } }, "voiceMode": { "llm": { "provider": "claude", "model": "haiku" }, - "stt": { "provider": "local", "model": "parakeet-tdt-0.6b-v2-int8", "language": "en" }, + "stt": { "provider": "local", "model": "parakeet-tdt-0.6b-v2-int8" }, "tts": { "provider": "local", "model": "kokoro-en-v0_19", "speakerId": 0 } } }, @@ -59,7 +56,7 @@ Missing models are downloaded at daemon startup into `$PASEO_HOME/models/local-s } ``` -For multilingual local dictation, set the model to v3 — it auto-detects the language, so no `language` field is needed: +For multilingual local dictation, set a multilingual model. No `language` field is needed: ```json { @@ -72,38 +69,53 @@ For multilingual local dictation, set the model to v3 — it auto-detects the la } ``` -The `language` field applies only to the OpenAI STT provider: set `features.dictation.stt.language` for dictation and `features.voiceMode.stt.language` for voice mode. If voice language is omitted, Paseo uses the dictation language before falling back to `en`. It has no effect on the local Parakeet models. +For either STT provider, set `features.dictation.stt.language` for dictation and `features.voiceMode.stt.language` for voice mode. If voice language is omitted, Paseo uses the dictation language before falling back to `en`. ## OpenAI Voice Option -You can switch dictation, voice STT, and voice TTS to OpenAI by setting provider fields to `openai` and providing OpenAI credentials. +Set `provider` to `openai` and enter credentials at each use site that needs them. +Dictation, listening and speaking each own their key, base URL and model: ```json { "version": 1, "features": { - "dictation": { "stt": { "provider": "openai" } }, + "dictation": { + "stt": { "provider": "openai", "apiKey": "sk-...", "model": "gpt-4o-mini-transcribe" } + }, "voiceMode": { - "stt": { "provider": "openai" }, - "tts": { "provider": "openai" } - } - }, - "providers": { - "openai": { + "enabled": true, "stt": { - "apiKey": "...", - "baseUrl": "https://api.openai.com/v1" + "provider": "openai", + "apiKey": "sk-...", + "baseUrl": "https://api.openai.com/v1", + "model": "gpt-4o-transcribe", + "language": "en" }, - "tts": { - "apiKey": "...", - "baseUrl": "https://api.openai.com/v1" - } + "tts": { "provider": "openai", "apiKey": "sk-...", "model": "tts-1", "voice": "alloy" } } } } ``` -`providers.openai.stt` covers dictation and voice mode speech-to-text, and `providers.openai.tts` covers voice mode text-to-speech. Because they resolve independently, you can point STT and TTS at different endpoints. Each falls back to `providers.openai.apiKey`/`baseUrl`, then `OPENAI_API_KEY`/`OPENAI_BASE_URL`, when unset. These settings configure only Paseo OpenAI speech traffic, without changing Codex or other OpenAI-backed tools. +| Provider | Speech-to-text fields | Text-to-speech fields | +| -------- | --------------------------------------------------------------- | ------------------------------------- | +| `local` | `model`, `language` | `model`, `speakerId`, `speed` | +| `openai` | `apiKey`, `baseUrl`, `model`, `language`, `confidenceThreshold` | `apiKey`, `baseUrl`, `model`, `voice` | + +Fields other than `provider` are optional. Omit `model` to use the provider's default. +OpenAI model and voice names accept custom IDs from compatible servers. Keys saved +on the host are write-only in the app. + +A saved `apiKey` or `baseUrl` wins over env settings. Without a saved value, STT +uses `OPENAI_STT_API_KEY` / `OPENAI_STT_BASE_URL`, TTS uses +`OPENAI_TTS_API_KEY` / `OPENAI_TTS_BASE_URL`, and both fall back to +`OPENAI_API_KEY` / `OPENAI_BASE_URL`. These settings affect Paseo speech traffic. + +Existing `providers.openai` settings load automatically into OpenAI use sites that +lack inline values. Endpoint settings take precedence over the old shared settings. +The next save writes the inline shape. A legacy key without an OpenAI site to +receive it is dropped with a warning; enter a key when you later select OpenAI. Paseo uses these paths under the configured OpenAI base URL: @@ -113,6 +125,14 @@ Paseo uses these paths under the configured OpenAI base URL: ## Environment Variables +Provider, enablement, model, language, voice and tuning env vars override config. +Keys and base URLs follow the fallback rule above. + +- `PASEO_DICTATION_ENABLED`, `PASEO_VOICE_MODE_ENABLED`, feature enablement +- `STT_MODEL`, model override for both OpenAI STT sites +- `STT_CONFIDENCE_THRESHOLD`, confidence threshold for both OpenAI STT sites +- `TTS_MODEL`, `TTS_VOICE`, OpenAI speaking model and voice + - `PASEO_VOICE_LLM_PROVIDER`, voice agent provider override - `PASEO_DICTATION_STT_PROVIDER`, `PASEO_VOICE_STT_PROVIDER`, `PASEO_VOICE_TTS_PROVIDER`, speech provider selection (`local` or `openai`) - `OPENAI_STT_API_KEY`, `OPENAI_STT_BASE_URL`, OpenAI speech-to-text endpoint (dictation + voice mode STT) @@ -120,8 +140,8 @@ Paseo uses these paths under the configured OpenAI base URL: - `PASEO_LOCAL_MODELS_DIR`, local model storage directory - `PASEO_DICTATION_LOCAL_STT_MODEL`, local dictation STT model ID - `PASEO_VOICE_LOCAL_STT_MODEL`, `PASEO_VOICE_LOCAL_TTS_MODEL`, local voice STT/TTS model IDs -- `PASEO_DICTATION_LANGUAGE`, dictation STT language (OpenAI STT only; ignored by local Parakeet) -- `PASEO_VOICE_LANGUAGE`, voice mode STT language; falls back to `PASEO_DICTATION_LANGUAGE` when unset (OpenAI STT only; ignored by local Parakeet) +- `PASEO_DICTATION_LANGUAGE`, dictation STT language +- `PASEO_VOICE_LANGUAGE`, voice mode STT language; falls back to `PASEO_DICTATION_LANGUAGE` when unset - `PASEO_VOICE_LOCAL_TTS_SPEAKER_ID`, `PASEO_VOICE_LOCAL_TTS_SPEED`, optional local voice TTS tuning ## Operational Notes From 033b2cdfc2b85e4e67a7f9d22b3af25200cf54a0 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Mon, 26 Oct 2026 14:24:38 +0700 Subject: [PATCH 021/173] fix(app): keep command suggestions visible as the composer grows (#7910) Long command descriptions exhausted the available space above a tall draft, leaving no complete selectable row. Bound the preview and reserve list space. Let the popover own its composer anchor so layout changes refresh its position while suggestions remain open. --- docs/mobile-testing.md | 6 + .../autocomplete-placement.mjs | 9 +- .../app/e2e/mobile/composer-keyboard/ios.mjs | 161 +++++++++++++++--- .../components/ui/autocomplete-popover.tsx | 49 +++--- .../app/src/components/ui/autocomplete.tsx | 14 +- packages/app/src/composer/index.tsx | 36 ++-- 6 files changed, 207 insertions(+), 68 deletions(-) diff --git a/docs/mobile-testing.md b/docs/mobile-testing.md index 917ebf9b53..169803c0eb 100644 --- a/docs/mobile-testing.md +++ b/docs/mobile-testing.md @@ -94,6 +94,12 @@ and its Claude provider available. Set `PASEO_COMPOSER_KEYBOARD_SERVER_ID`, `_AGENT_ID` (an idle mock chat), and `_WORKSPACE_ID` (its workspace); `_DEVICE`, `_SESSION`, and `_DRAFT_ID` are optional. Artifacts go to `.dev/agent-device-artifacts/composer-keyboard-ios`. +With a Codex draft selected, set `_SCENARIO=growth` on a 402pt-wide iPhone to +check live wrapping, shrinking, the 12pt anchor gap, and command insertion. Set +`_SCENARIO=previews` on an SE-sized iPhone to check long and short descriptions +under an eight-line draft, selection with the keyboard shown and hidden, and +file mentions. These scenarios only need `_SERVER_ID` and `_WORKSPACE_ID`; +`_UDID` selects an exact simulator and `_ARTIFACTS_DIR` overrides the output path. The Android sidebar scroll-retention flow requires a connected host with enough workspaces to overflow the compact sidebar. Pass `TOP_WORKSPACE` and diff --git a/packages/app/e2e/mobile/composer-keyboard/autocomplete-placement.mjs b/packages/app/e2e/mobile/composer-keyboard/autocomplete-placement.mjs index 22c0b42e8f..a8450838eb 100644 --- a/packages/app/e2e/mobile/composer-keyboard/autocomplete-placement.mjs +++ b/packages/app/e2e/mobile/composer-keyboard/autocomplete-placement.mjs @@ -28,7 +28,10 @@ function contains(outer, inner) { * while suggestions are open, so its callers read the composer from `reference`: a * snapshot in the same keyboard state with an empty input. */ -export function resolveAutocompletePlacement(snapshot, { expected, keyboardTop, reference }) { +export function resolveAutocompletePlacement( + snapshot, + { expected, keyboardTop, reference, anchorGap }, +) { if (!snapshot.success || !snapshot.data?.nodes?.length) throw new Error("Empty device snapshot"); const nodes = snapshot.data.nodes; const popover = findById(nodes, "composer-autocomplete-popover").rect; @@ -40,6 +43,10 @@ export function resolveAutocompletePlacement(snapshot, { expected, keyboardTop, const keyboardY = keyboardTop ?? nodes.find((node) => node.type === "Keyboard" && node.rect)?.rect.y; const popoverBottom = bottomOf(popover); + const gap = composer.y - popoverBottom; + if (anchorGap !== undefined && Math.abs(gap - anchorGap) > 1) { + throw new Error(`Autocomplete lost its anchor gap: gap=${gap}, expected=${anchorGap}`); + } if (popoverBottom > composer.y + 1) { throw new Error( `Autocomplete overlaps the composer: popover bottom=${popoverBottom}, composer top=${composer.y}`, diff --git a/packages/app/e2e/mobile/composer-keyboard/ios.mjs b/packages/app/e2e/mobile/composer-keyboard/ios.mjs index e3fc4af072..513d68623e 100644 --- a/packages/app/e2e/mobile/composer-keyboard/ios.mjs +++ b/packages/app/e2e/mobile/composer-keyboard/ios.mjs @@ -14,7 +14,8 @@ const env = (name, fallback) => process.env[`PASEO_COMPOSER_KEYBOARD_${name}`] ? const serverId = env("SERVER_ID"); const agentId = env("AGENT_ID"); const workspaceId = env("WORKSPACE_ID"); -if (!serverId || !agentId || !workspaceId) { +const scenario = env("SCENARIO", "all"); +if (!serverId || !workspaceId || (scenario === "all" && !agentId)) { throw new Error( "Set PASEO_COMPOSER_KEYBOARD_SERVER_ID, _AGENT_ID (an idle chat) and _WORKSPACE_ID (its workspace)", ); @@ -22,7 +23,12 @@ if (!serverId || !agentId || !workspaceId) { const draftId = env("DRAFT_ID", "composer-keyboard"); const session = env("SESSION", "composer-keyboard-ios"); const device = env("DEVICE", "iPhone 16 Pro"); -const artifactsDir = path.join(repoRoot, ".dev/agent-device-artifacts/composer-keyboard-ios"); +const udid = env("UDID"); +const deviceArgs = udid ? ["--udid", udid] : ["--device", device]; +const artifactsDir = env( + "ARTIFACTS_DIR", + path.join(repoRoot, ".dev/agent-device-artifacts/composer-keyboard-ios"), +); const grownPrefix = "grown line one\ngrown line two\ngrown line three\n"; // Partial queries with known best matches. `inserted` is the composer text after // tapping the best match. @@ -35,7 +41,7 @@ const chatCommandCase = { text: "/mo", expected: "/mock", inserted: "/mock " }; fs.mkdirSync(artifactsDir, { recursive: true }); function ad(...args) { - return execFileSync("agent-device", [...args, "--session", session], { + return execFileSync("agent-device", [args[0], "--session", session, ...args.slice(1)], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024, }); @@ -77,7 +83,7 @@ async function settledPlacement(name, keyboard) { } function assertPlacement(name, snap, expected) { - const placement = resolveAutocompletePlacement(snap, { expected }); + const placement = resolveAutocompletePlacement(snap, { expected, anchorGap: 12 }); process.stdout.write( `PASS ${name}: popover ${Math.round(placement.popover.y)}-${Math.round( placement.popover.y + placement.popover.height, @@ -123,21 +129,34 @@ async function clearInput(name) { )?.rect; if (!deleteKey) throw new Error("Missing keyboard delete key"); const length = composerText(keyboard).length; - ad( - "press", - String(Math.round(deleteKey.x + deleteKey.width / 2)), - String(Math.round(deleteKey.y + deleteKey.height / 2)), - "--count", - String(length + 2), - "--interval-ms", - "40", - ); + for (let remaining = length + 2; remaining > 0; remaining -= 100) { + ad( + "press", + String(Math.round(deleteKey.x + deleteKey.width / 2)), + String(Math.round(deleteKey.y + deleteKey.height / 2)), + "--count", + String(Math.min(remaining, 100)), + "--interval-ms", + "40", + ); + } } // The accessibility value drops a trailing space. const sameText = (actual, expected) => actual.trimEnd() === expected.trimEnd(); -async function runCase(host, kind, { text, expected, inserted }) { +async function selectRow(name, row, inserted) { + ad("press", String(row.x), String(row.y)); + const selected = await waitFor(`${name}-selected`, (snap) => + sameText(composerText(snap), inserted), + ); + if (!keyboardShown(selected)) throw new Error(`Selecting ${row.label} closed the keyboard`); + process.stdout.write( + `PASS ${name}: tapped ${row.label}, composer now ${JSON.stringify(inserted)}\n`, + ); +} + +async function runCase(host, kind, { text, expected, inserted, selectionKeyboard = "reopened" }) { const name = `${host}-${kind}`; await clearInput(name); await dismissKeyboard(snapshot(`${name}-empty`)); @@ -151,31 +170,32 @@ async function runCase(host, kind, { text, expected, inserted }) { await clearInput(`${name}-settled`); await waitFor(`${name}-settled-empty`, (snap) => composerText(snap) === ""); ad("type", text); - assertPlacement( + const opened = assertPlacement( `${name} opened after keyboard settled`, await settledPlacement(`${name}-open`, true), expected, ); + if (selectionKeyboard === "shown") { + await selectRow(name, opened, inserted); + return; + } await dismissKeyboard(snapshot(`${name}-before-close`)); - assertPlacement( + const closed = assertPlacement( `${name} keyboard closed`, await settledPlacement(`${name}-closed`, false), expected, ); + if (selectionKeyboard === "hidden") { + await selectRow(name, closed, inserted); + return; + } focusAtEnd(snapshot(`${name}-before-reopen`)); const reopened = assertPlacement( `${name} keyboard opened under open suggestions`, await settledPlacement(`${name}-reopened`, true), expected, ); - ad("press", String(reopened.x), String(reopened.y)); - const selected = await waitFor(`${name}-selected`, (snap) => - sameText(composerText(snap), inserted), - ); - if (!keyboardShown(selected)) throw new Error(`Selecting ${expected} closed the keyboard`); - process.stdout.write( - `PASS ${name}: tapped ${expected}, composer now ${JSON.stringify(inserted)}\n`, - ); + await selectRow(name, reopened, inserted); } // Drafts list commands for their selected provider, and a fresh install selects none. @@ -216,13 +236,104 @@ async function runHost(host) { await dismissKeyboard(snapshot(`${host}-done`)); } +// These cases use the selected draft provider's real skills. Run on a 402pt-wide +// iPhone for growth and a small phone (SE) for previews, with Codex selected. +async function runLiveGrowth() { + await clearInput("live-growth"); + ad("type", "Please do the following now /paseo"); + const before = await settledPlacement("live-growth-before", true); + assertPlacement("before growth", before, "/paseo"); + const inputHeight = (snap) => + snap.data.nodes.find((node) => node.type === "TextView").rect.height; + ad("type", "--", "-committee"); + const grown = await settledPlacement("live-growth-after", true); + if (inputHeight(grown) <= inputHeight(before)) + throw new Error("Draft did not wrap onto a new line"); + assertPlacement("live growth without reopening", grown, "/paseo-committee"); + const deleteKey = grown.data.nodes.find( + (node) => node.type === "Key" && node.label === "delete", + ).rect; + ad( + "press", + String(deleteKey.x + deleteKey.width / 2), + String(deleteKey.y + deleteKey.height / 2), + "--count", + "10", + "--interval-ms", + "40", + ); + const shrunk = await settledPlacement("live-growth-shrunk", true); + if (inputHeight(shrunk) !== inputHeight(before)) + throw new Error("Draft did not shrink back to one line"); + assertPlacement("live shrink without reopening", shrunk, "/paseo"); + ad("type", "--", "-committ"); + const partial = await settledPlacement("live-growth-partial", true); + if (!sameText(composerText(partial), "Please do the following now /paseo-committ")) { + throw new Error("Could not prepare a partial command for selection"); + } + const row = assertPlacement("partial command after growth", partial, "/paseo-committee"); + ad("press", String(row.x), String(row.y)); + await waitFor("live-growth-selected", (snap) => + sameText(composerText(snap), "Please do the following now /paseo-committee "), + ); + await clearInput("live-growth-done"); +} + +async function runBoundedPreview() { + const prefix = + "Please do the following / testing inline selection.\n" + + "Line two with details.\nLine three with details.\nLine four with details.\n" + + "Line five with details.\nLine six with details.\nLine seven with details.\nPlease use "; + await runCase("preview", "long", { + text: `${prefix}/openai`, + expected: "/openai-docs", + inserted: `${prefix}/openai-docs `, + selectionKeyboard: "shown", + }); + await runCase("preview", "long-hidden", { + text: `${prefix}/openai`, + expected: "/openai-docs", + inserted: `${prefix}/openai-docs `, + selectionKeyboard: "hidden", + }); + await runCase("preview", "longest", { + text: `${prefix}/paseo-plug`, + expected: "/paseo-plugin", + inserted: `${prefix}/paseo-plugin `, + selectionKeyboard: "shown", + }); + await runCase("preview", "short", { + text: `${prefix}/com`, + expected: "/commit", + inserted: `${prefix}/commit `, + selectionKeyboard: "shown", + }); + await runCase("preview", "files", fileCase); +} + +if (scenario !== "all") { + ad( + "open", + `paseo://h/${serverId}/workspace/${workspaceId}?open=draft%3A${draftId}`, + "--platform", + "ios", + ...deviceArgs, + ); + await waitFor("draft", (snap) => Boolean(nodeById(snap, "message-input-root")), 60_000); + if (scenario === "growth") await runLiveGrowth(); + else if (scenario === "previews") await runBoundedPreview(); + else throw new Error(`Unknown scenario: ${scenario}`); + process.stdout.write(`Composer ${scenario} regression passed. Artifacts: ${artifactsDir}\n`); + process.exit(0); +} + const hosts = [ ["chat", `paseo://h/${serverId}/agent/${agentId}`], ["workspace-draft", `paseo://h/${serverId}/workspace/${workspaceId}?open=draft%3A${draftId}`], ["new-workspace", `paseo://new?serverId=${serverId}`], ]; for (const [host, url] of hosts) { - ad("open", url, "--platform", "ios", "--device", device); + ad("open", url, "--platform", "ios", ...deviceArgs); await waitFor(host, (snap) => Boolean(nodeById(snap, "message-input-root")), 60_000); await runHost(host); } diff --git a/packages/app/src/components/ui/autocomplete-popover.tsx b/packages/app/src/components/ui/autocomplete-popover.tsx index fa5e724944..e74c068658 100644 --- a/packages/app/src/components/ui/autocomplete-popover.tsx +++ b/packages/app/src/components/ui/autocomplete-popover.tsx @@ -5,9 +5,9 @@ import { useRef, useState, type ReactElement, - type RefObject, + type ReactNode, } from "react"; -import { View, useWindowDimensions } from "react-native"; +import { View, useWindowDimensions, type StyleProp, type ViewStyle } from "react-native"; import { Portal } from "@gorhom/portal"; import Animated, { useAnimatedReaction, useAnimatedStyle } from "react-native-reanimated"; import { scheduleOnRN } from "react-native-worklets"; @@ -32,7 +32,8 @@ interface RelativeAnchorRect { interface AutocompletePopoverProps { visible: boolean; - anchorRef: RefObject; + children: ReactNode; + anchorStyle?: StyleProp; options: readonly AutocompleteOption[]; selectedIndex: number; onSelect: (option: AutocompleteOption) => void; @@ -44,7 +45,8 @@ interface AutocompletePopoverProps { export function AutocompletePopover({ visible, - anchorRef, + children, + anchorStyle, options, selectedIndex, onSelect, @@ -55,6 +57,7 @@ export function AutocompletePopover({ }: AutocompletePopoverProps): ReactElement | null { "use no memo"; // React Compiler memoizes effect captures by reading SharedValue.value during render. + const anchorRef = useRef(null); const [relativeAnchorRect, setRelativeAnchorRect] = useState(null); const windowDimensions = useWindowDimensions(); const safeAreaInsets = useSafeAreaInsets(); @@ -137,25 +140,29 @@ export function AutocompletePopover({ [anchorY, reservedLift, safeAreaInsets.top], ); - if (!visible || !relativeAnchorRect || !baseStyle) return null; - if (options.length > 0 && selectedIndex < 0) return null; + const showPopover = canMeasure && relativeAnchorRect && baseStyle; // The translate view is the popover's own frame, so it lifts only the popover. return ( - - - - - - - + + {children} + {showPopover ? ( + + + + + + + + ) : null} + ); } diff --git a/packages/app/src/components/ui/autocomplete.tsx b/packages/app/src/components/ui/autocomplete.tsx index 7b5b99b316..a9cb10f33e 100644 --- a/packages/app/src/components/ui/autocomplete.tsx +++ b/packages/app/src/components/ui/autocomplete.tsx @@ -247,14 +247,16 @@ export function Autocomplete({ {selectedOption?.kind === "command" && selectedOption.description ? ( - + {removeBoltGlyphs(selectedOption.label) ?? selectedOption.label} - + {removeBoltGlyphs(selectedOption.description)} {selectedOption.detail ? ( - {removeBoltGlyphs(selectedOption.detail)} + + {removeBoltGlyphs(selectedOption.detail)} + ) : null} ) : null} @@ -293,6 +295,9 @@ const styles = StyleSheet.create((theme: Theme) => ({ gap: theme.spacing[1], }, detailCard: { + flexShrink: 1, + minHeight: 0, + overflow: "hidden", backgroundColor: theme.colors.surface1, borderWidth: theme.borderWidth[1], borderColor: theme.colors.borderAccent, @@ -318,7 +323,8 @@ const styles = StyleSheet.create((theme: Theme) => ({ }, container: { flexShrink: 1, - minHeight: 0, + // Keep a complete selectable row (36), list padding (8), and borders (2). + minHeight: 46, backgroundColor: theme.colors.surface1, borderWidth: theme.borderWidth[1], borderColor: theme.colors.borderAccent, diff --git a/packages/app/src/composer/index.tsx b/packages/app/src/composer/index.tsx index ba85de2516..d000c269af 100644 --- a/packages/app/src/composer/index.tsx +++ b/packages/app/src/composer/index.tsx @@ -1003,7 +1003,8 @@ function ComposerAutocompleteBinding({ recall, configuration, inputRef, - anchorRef, + children, + anchorStyle, show, ref, }: { @@ -1015,7 +1016,8 @@ function ComposerAutocompleteBinding({ "userInput" | "cursorIndex" | "onAutocompleteApplied" >; inputRef: React.RefObject; - anchorRef: React.RefObject; + children: React.ReactNode; + anchorStyle: React.ComponentProps["style"]; show: boolean; ref: React.Ref; }) { @@ -1042,7 +1044,7 @@ function ComposerAutocompleteBinding({ return ( + > + {children} + ); } @@ -2379,7 +2383,6 @@ function ComposerContentImpl({ pluginClientSlashCommands, ], ); - const messageInputContainerRef = useRef(null); const isSubmitLoadingVisible = isProcessing || isSubmitLoading || isUploadingFile || pendingNativeImagePastes > 0; @@ -2438,17 +2441,16 @@ function ComposerContentImpl({ {isFullscreen ? null : queueList} {!isFullscreen && sendErrorNode} - - + {pluginAttachments.picker} - + From e958540b0a53604d63afcaebdf028f49f3575b2a Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Mon, 26 Oct 2026 15:06:02 +0700 Subject: [PATCH 022/173] fix(app): remove SVG prop and nested button warnings on web (#7915) * fix(app): prevent web SVG prop and nested button warnings Consume Unistyles mapping props at the wrapper boundary and use web accessibility attributes for decorative rings. Register composer track rows as menu items so nested actions stay valid and keyboard selection remains available. * test(app): select archive actions by their menu role --- .../e2e/browser/context-window-meter.spec.ts | 9 + packages/app/e2e/support/helpers/subagents.ts | 6 +- .../src/components/context-window-meter.tsx | 5 +- .../composer/tracks-panel.browser.test.tsx | 22 +++ packages/app/src/composer/tracks.tsx | 8 +- .../git/pull-request-panel/checks-ring.tsx | 6 +- .../app/src/styles/unistyles-props.test.ts | 86 ++++++++++ patches/react-native-unistyles+3.2.4.patch | 157 ++++++++++++++++++ scripts/postinstall-patches.mjs | 3 +- 9 files changed, 293 insertions(+), 9 deletions(-) create mode 100644 packages/app/src/styles/unistyles-props.test.ts diff --git a/packages/app/e2e/browser/context-window-meter.spec.ts b/packages/app/e2e/browser/context-window-meter.spec.ts index 79a572a24b..be0835b116 100644 --- a/packages/app/e2e/browser/context-window-meter.spec.ts +++ b/packages/app/e2e/browser/context-window-meter.spec.ts @@ -42,6 +42,14 @@ const test = base.extend<{ agent: MockAgentSession }>({ }, }); +// The outer meter owns the accessible usage label; its SVG is decorative. +async function expectDecorativeContextRing(meter: Locator): Promise { + const ring = meter.locator("svg"); + await expect(ring).toHaveAttribute("aria-hidden", "true"); + await expect(ring).not.toHaveAttribute("accessibilityElementsHidden"); + await expect(ring).not.toHaveAttribute("importantForAccessibility"); +} + // Where the progress arc is painted, as its centroid relative to the ring's centre in pixels. // Reads the rendered pixels, so any rotation that does not reach the screen counts as none. async function progressArcCentroid(meter: Locator): Promise<{ x: number; y: number }> { @@ -100,6 +108,7 @@ test.describe("context window meter", () => { const meter = page.getByTestId("context-window-meter"); await expect(meter).toHaveAccessibleName(/25%/, { timeout: 30_000 }); + await expectDecorativeContextRing(meter); const centroid = await progressArcCentroid(meter); expect(centroid.x).toBeGreaterThan(1); expect(centroid.y).toBeLessThan(-1); diff --git a/packages/app/e2e/support/helpers/subagents.ts b/packages/app/e2e/support/helpers/subagents.ts index 3354bf3dd8..a6fc5bcf21 100644 --- a/packages/app/e2e/support/helpers/subagents.ts +++ b/packages/app/e2e/support/helpers/subagents.ts @@ -188,7 +188,7 @@ export async function expectManagedSubagentArchived( } export async function archiveFinishedSubagents(page: Page): Promise { - await page.getByRole("button", { name: "Archive finished subagents" }).click(); + await page.getByRole("menuitem", { name: "Archive finished subagents" }).click(); } export async function expectArchiveFinishedInProgress( @@ -196,7 +196,7 @@ export async function expectArchiveFinishedInProgress( completed: number, total: number, ): Promise { - await expect(page.getByRole("button", { name: "Archive finished subagents" })).toBeDisabled(); + await expect(page.getByRole("menuitem", { name: "Archive finished subagents" })).toBeDisabled(); await expect(page.getByText(`${completed}/${total}`, { exact: true })).toBeVisible(); } @@ -206,7 +206,7 @@ export async function expectArchiveFinishedRetry( total: number, ): Promise { await expect(page.getByText(`Retry (${failed}/${total})`, { exact: true })).toBeVisible(); - await expect(page.getByRole("button", { name: "Archive finished subagents" })).toBeEnabled(); + await expect(page.getByRole("menuitem", { name: "Archive finished subagents" })).toBeEnabled(); } export async function holdManagedSubagentArchiveRequest( diff --git a/packages/app/src/components/context-window-meter.tsx b/packages/app/src/components/context-window-meter.tsx index f9cfabcf8d..32c739c073 100644 --- a/packages/app/src/components/context-window-meter.tsx +++ b/packages/app/src/components/context-window-meter.tsx @@ -112,8 +112,9 @@ const ContextWindowRing = withUnistyles(function ContextWindowRing({ width={size} height={size} viewBox={`0 0 ${size} ${size}`} - accessibilityElementsHidden - importantForAccessibility="no-hide-descendants" + {...(isNative + ? { accessibilityElementsHidden: true, importantForAccessibility: "no-hide-descendants" } + : { "aria-hidden": true })} > { ); openPanel(); + expect(document.querySelector("button button")).toBeNull(); + expect(row("row")?.getAttribute("role")).toBe("menuitem"); click(row("row-archive") as Element); expect(onAction).toHaveBeenCalledTimes(1); expect(onPress).not.toHaveBeenCalled(); expect(isPanelOpen()).toBe(true); }); + + it.each(["Enter", " "])("selects a track row with %j", (key) => { + const select = vi.fn(); + mount( + + + Subagent one + + , + ); + openPanel(); + const target = row("row") as HTMLElement; + act(() => { + target.focus(); + target.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true })); + target.dispatchEvent(new KeyboardEvent("keyup", { key, bubbles: true })); + }); + expect(select).toHaveBeenCalledTimes(1); + expect(isPanelOpen()).toBe(false); + }); }); describe("composer track pill status mark", () => { diff --git a/packages/app/src/composer/tracks.tsx b/packages/app/src/composer/tracks.tsx index 82bee6e3fa..4e06266058 100644 --- a/packages/app/src/composer/tracks.tsx +++ b/packages/app/src/composer/tracks.tsx @@ -233,6 +233,11 @@ export function ComposerTrackRow({ [closeOnSelect, onPress, selectItem], ); + const itemDataSet = useMemo( + () => ({ menuItem: "true", menuDisabled: disabled ? "true" : "false" }), + [disabled], + ); + const renderRow = useCallback( (active: boolean) => ( @@ -253,7 +258,8 @@ export function ComposerTrackRow({ return ( { + it("consumes uniProps while preserving mapped colors and explicit overrides", async () => { + const result = await renderWebProbe(` + import React from 'react'; + import { renderToStaticMarkup } from 'react-dom/server'; + import { StyleSheet, UnistylesRuntime, withUnistyles } from 'react-native-unistyles'; + import { Server } from 'lucide-react-native'; + StyleSheet.configure({ + themes: { light: { color: 'red' }, dark: { color: 'blue' } }, + settings: { initialTheme: 'light' }, + }); + const Icon = withUnistyles(Server); + const mapping = theme => ({ color: theme.color }); + const render = props => renderToStaticMarkup(React.createElement(Icon, { uniProps: mapping, ...props })); + const light = render(); + UnistylesRuntime.setTheme('dark'); + const dark = render(); + const overridden = render({ color: 'green' }); + const received = []; + const Probe = withUnistyles(props => { received.push(props); return null; }); + renderToStaticMarkup(React.createElement(Probe, { uniProps: mapping, id: 'probe' })); + console.log(JSON.stringify({ light, dark, overridden, keys: Object.keys(received[0]).sort() })); + `); + expect(result.status, result.stderr).toBe(0); + expect(result.stderr).not.toContain("React does not recognize"); + const rendered = JSON.parse(result.stdout); + expect(rendered.keys).toEqual(["color", "id", "ref"]); + expect(rendered.light).toContain('stroke="red"'); + expect(rendered.dark).toContain('stroke="blue"'); + expect(rendered.overridden).toContain('stroke="green"'); + }); +}); + +describe("decorative checks ring", () => { + it("hides its SVG from web accessibility without forwarding native props", async () => { + const result = await renderWebProbe(` + import React from 'react'; + import { renderToStaticMarkup } from 'react-dom/server'; + import { StyleSheet } from 'react-native-unistyles'; + import { ChecksRing } from './src/git/pull-request-panel/checks-ring'; + StyleSheet.configure({ + themes: { light: { colors: { surface3: 'gray', statusSuccess: 'green' } } }, + settings: { initialTheme: 'light' }, + }); + console.log(renderToStaticMarkup(React.createElement(ChecksRing, { + size: 20, summary: { total: 1, parts: [{ status: 'success', count: 1 }] }, + }))); + `); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toContain('aria-hidden="true"'); + expect(result.stdout).not.toContain("importantForAccessibility"); + expect(result.stdout).not.toContain("accessibilityElementsHidden"); + expect(result.stdout).toContain('stroke="green"'); + expect(result.stderr).not.toContain("React does not recognize"); + }); +}); diff --git a/patches/react-native-unistyles+3.2.4.patch b/patches/react-native-unistyles+3.2.4.patch index 0195868340..7f40053f19 100644 --- a/patches/react-native-unistyles+3.2.4.patch +++ b/patches/react-native-unistyles+3.2.4.patch @@ -329,3 +329,160 @@ index 195954b..c4ac28c 100644 namespace "com.unistyles" defaultConfig { +diff --git a/node_modules/react-native-unistyles/src/core/withUnistyles/withUnistyles.tsx b/node_modules/react-native-unistyles/src/core/withUnistyles/withUnistyles.tsx +--- a/node_modules/react-native-unistyles/src/core/withUnistyles/withUnistyles.tsx ++++ b/node_modules/react-native-unistyles/src/core/withUnistyles/withUnistyles.tsx +@@ -28,13 +28,14 @@ + + return forwardRef, PropsWithUnistyles>((props, ref) => { + const narrowedProps = props as PropsWithUnistyles & UnistyleStyles ++ const { uniProps, ...componentProps } = narrowedProps + const styleClassNames = getClassName(narrowedProps.style, true) + const contentContainerStyleClassNames = getClassName(narrowedProps.contentContainerStyle) + const { proxifiedRuntime, proxifiedTheme } = useProxifiedUnistyles() + + const { key: mappingsKey, ...mappingsProps } = mappings ? mappings(proxifiedTheme, proxifiedRuntime) : {} +- const { key: uniPropsKey, ...unistyleProps } = narrowedProps.uniProps +- ? narrowedProps.uniProps(proxifiedTheme, proxifiedRuntime) ++ const { key: uniPropsKey, ...unistyleProps } = uniProps ++ ? uniProps(proxifiedTheme, proxifiedRuntime) + : {} + + const emptyStyles = narrowedProps.style +@@ -46,7 +47,7 @@ + : undefined + + const combinedProps = { +- ...deepMergeObjects(mappingsProps, unistyleProps, props), ++ ...deepMergeObjects(mappingsProps, unistyleProps, componentProps), + ...(narrowedProps.style + ? { + // Override default component styles with undefined values to reset them +diff --git a/node_modules/react-native-unistyles/src/core/withUnistyles/withUnistyles.native.tsx b/node_modules/react-native-unistyles/src/core/withUnistyles/withUnistyles.native.tsx +--- a/node_modules/react-native-unistyles/src/core/withUnistyles/withUnistyles.native.tsx ++++ b/node_modules/react-native-unistyles/src/core/withUnistyles/withUnistyles.native.tsx +@@ -63,6 +63,7 @@ + + return forwardRef, PropsWithUnistyles>((props, ref) => { + const narrowedProps = props as PropsWithUnistyles & UnistyleStyles ++ const { uniProps, ...componentProps } = narrowedProps + const NativeComponent = Component as ComponentType + + // @ts-ignore we don't know the type of the component +@@ -89,15 +90,15 @@ + }, [narrowedProps.style, narrowedProps.contentContainerStyle]) + + const { key: mappingsKey, ...mappingsProps } = mappings ? mappings(proxifiedTheme, proxifiedRuntime) : {} +- const { key: uniPropsKey, ...unistyleProps } = narrowedProps.uniProps +- ? narrowedProps.uniProps(proxifiedTheme, proxifiedRuntime) ++ const { key: uniPropsKey, ...unistyleProps } = uniProps ++ ? uniProps(proxifiedTheme, proxifiedRuntime) + : {} + + const styleSecrets = getSecrets(narrowedProps.style) + const contentContainerStyleSecrets = getSecrets(narrowedProps.contentContainerStyle) + + const finalProps = { +- ...deepMergeObjects(mappingsProps, unistyleProps, props), ++ ...deepMergeObjects(mappingsProps, unistyleProps, componentProps), + ...(narrowedProps.style + ? { + style: styleSecrets.styles, +diff --git a/node_modules/react-native-unistyles/lib/module/core/withUnistyles/withUnistyles.js b/node_modules/react-native-unistyles/lib/module/core/withUnistyles/withUnistyles.js +--- a/node_modules/react-native-unistyles/lib/module/core/withUnistyles/withUnistyles.js ++++ b/node_modules/react-native-unistyles/lib/module/core/withUnistyles/withUnistyles.js +@@ -13,6 +13,7 @@ + export const withUnistyles = (Component, mappings) => { + return /*#__PURE__*/forwardRef((props, ref) => { + const narrowedProps = props; ++ const { uniProps, ...componentProps } = narrowedProps; + const styleClassNames = getClassName(narrowedProps.style, true); + const contentContainerStyleClassNames = getClassName(narrowedProps.contentContainerStyle); + const { +@@ -26,10 +27,10 @@ + const { + key: uniPropsKey, + ...unistyleProps +- } = narrowedProps.uniProps ? narrowedProps.uniProps(proxifiedTheme, proxifiedRuntime) : {}; ++ } = uniProps ? uniProps(proxifiedTheme, proxifiedRuntime) : {}; + const emptyStyles = narrowedProps.style ? Object.fromEntries(Object.entries(Object.getOwnPropertyDescriptors(narrowedProps.style)).filter(([key]) => !key.startsWith('unistyles') && !key.startsWith('_')).map(([key]) => [key, undefined])) : undefined; + const combinedProps = { +- ...deepMergeObjects(mappingsProps, unistyleProps, props), ++ ...deepMergeObjects(mappingsProps, unistyleProps, componentProps), + ...(narrowedProps.style ? { + // Override default component styles with undefined values to reset them + style: emptyStyles +diff --git a/node_modules/react-native-unistyles/lib/module/core/withUnistyles/withUnistyles.native.js b/node_modules/react-native-unistyles/lib/module/core/withUnistyles/withUnistyles.native.js +--- a/node_modules/react-native-unistyles/lib/module/core/withUnistyles/withUnistyles.native.js ++++ b/node_modules/react-native-unistyles/lib/module/core/withUnistyles/withUnistyles.native.js +@@ -27,6 +27,7 @@ + }; + return /*#__PURE__*/forwardRef((props, ref) => { + const narrowedProps = props; ++ const { uniProps, ...componentProps } = narrowedProps; + const NativeComponent = Component; + + // @ts-ignore we don't know the type of the component +@@ -57,11 +58,11 @@ + const { + key: uniPropsKey, + ...unistyleProps +- } = narrowedProps.uniProps ? narrowedProps.uniProps(proxifiedTheme, proxifiedRuntime) : {}; ++ } = uniProps ? uniProps(proxifiedTheme, proxifiedRuntime) : {}; + const styleSecrets = getSecrets(narrowedProps.style); + const contentContainerStyleSecrets = getSecrets(narrowedProps.contentContainerStyle); + const finalProps = { +- ...deepMergeObjects(mappingsProps, unistyleProps, props), ++ ...deepMergeObjects(mappingsProps, unistyleProps, componentProps), + ...(narrowedProps.style ? { + style: styleSecrets.styles + } : {}), +diff --git a/node_modules/react-native-unistyles/lib/commonjs/core/withUnistyles/withUnistyles.js b/node_modules/react-native-unistyles/lib/commonjs/core/withUnistyles/withUnistyles.js +--- a/node_modules/react-native-unistyles/lib/commonjs/core/withUnistyles/withUnistyles.js ++++ b/node_modules/react-native-unistyles/lib/commonjs/core/withUnistyles/withUnistyles.js +@@ -18,6 +18,7 @@ + const withUnistyles = (Component, mappings) => { + return /*#__PURE__*/(0, _react.forwardRef)((props, ref) => { + const narrowedProps = props; ++ const { uniProps, ...componentProps } = narrowedProps; + const styleClassNames = (0, _getClassname.getClassName)(narrowedProps.style, true); + const contentContainerStyleClassNames = (0, _getClassname.getClassName)(narrowedProps.contentContainerStyle); + const { +@@ -31,10 +32,10 @@ + const { + key: uniPropsKey, + ...unistyleProps +- } = narrowedProps.uniProps ? narrowedProps.uniProps(proxifiedTheme, proxifiedRuntime) : {}; ++ } = uniProps ? uniProps(proxifiedTheme, proxifiedRuntime) : {}; + const emptyStyles = narrowedProps.style ? Object.fromEntries(Object.entries(Object.getOwnPropertyDescriptors(narrowedProps.style)).filter(([key]) => !key.startsWith('unistyles') && !key.startsWith('_')).map(([key]) => [key, undefined])) : undefined; + const combinedProps = { +- ...(0, _utils.deepMergeObjects)(mappingsProps, unistyleProps, props), ++ ...(0, _utils.deepMergeObjects)(mappingsProps, unistyleProps, componentProps), + ...(narrowedProps.style ? { + // Override default component styles with undefined values to reset them + style: emptyStyles +diff --git a/node_modules/react-native-unistyles/lib/commonjs/core/withUnistyles/withUnistyles.native.js b/node_modules/react-native-unistyles/lib/commonjs/core/withUnistyles/withUnistyles.native.js +--- a/node_modules/react-native-unistyles/lib/commonjs/core/withUnistyles/withUnistyles.native.js ++++ b/node_modules/react-native-unistyles/lib/commonjs/core/withUnistyles/withUnistyles.native.js +@@ -32,6 +32,7 @@ + }; + return /*#__PURE__*/(0, _react.forwardRef)((props, ref) => { + const narrowedProps = props; ++ const { uniProps, ...componentProps } = narrowedProps; + const NativeComponent = Component; + + // @ts-ignore we don't know the type of the component +@@ -62,11 +63,11 @@ + const { + key: uniPropsKey, + ...unistyleProps +- } = narrowedProps.uniProps ? narrowedProps.uniProps(proxifiedTheme, proxifiedRuntime) : {}; ++ } = uniProps ? uniProps(proxifiedTheme, proxifiedRuntime) : {}; + const styleSecrets = getSecrets(narrowedProps.style); + const contentContainerStyleSecrets = getSecrets(narrowedProps.contentContainerStyle); + const finalProps = { +- ...(0, _utils.deepMergeObjects)(mappingsProps, unistyleProps, props), ++ ...(0, _utils.deepMergeObjects)(mappingsProps, unistyleProps, componentProps), + ...(narrowedProps.style ? { + style: styleSecrets.styles + } : {}), diff --git a/scripts/postinstall-patches.mjs b/scripts/postinstall-patches.mjs index b009be9841..09ff2919b6 100644 --- a/scripts/postinstall-patches.mjs +++ b/scripts/postinstall-patches.mjs @@ -19,8 +19,9 @@ const patchedPackages = [ patchPrefix: "react-native-enriched-markdown+", cwd: "packages/app", }, - // Remove after react-native-unistyles ships + // Registry cleanup: remove after react-native-unistyles ships // https://github.com/jpudysz/react-native-unistyles/pull/1203. + // withUnistyles: also keep the uniProps filter until upstream consumes its control prop. { nodeModulesPath: "node_modules/react-native-unistyles", patchPrefix: "react-native-unistyles+", From e277656cbdda4f84320fd3cbf2f806e67d2bb742 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Mon, 26 Oct 2026 15:46:04 +0700 Subject: [PATCH 023/173] fix(app): clean up native animation and layout lifecycles (#7914) Worklets 0.10.4 and Reanimated 4.5.5 while keeping the stale-view guard from #7907; backport the Enriched Markdown settled-row measurement fix (upstream #924); release each bottom sheet's Dimensions subscription on unmount. --- package-lock.json | 51 ++------ package.json | 4 +- packages/app/package.json | 12 +- .../index.test.tsx | 33 ++++++ patches/@gorhom+bottom-sheet+5.2.14.patch | 62 ++++++++++ ...own+1.2.0-nightly-20261014-766fc0e67.patch | 109 +++++++++++++++++- ...ch => react-native-reanimated+4.5.5.patch} | 0 scripts/postinstall-patches.mjs | 6 + 8 files changed, 226 insertions(+), 51 deletions(-) rename patches/{react-native-reanimated+4.5.1.patch => react-native-reanimated+4.5.5.patch} (100%) diff --git a/package-lock.json b/package-lock.json index 64d1415515..1f5cce1657 100644 --- a/package-lock.json +++ b/package-lock.json @@ -30269,9 +30269,9 @@ } }, "node_modules/react-native-reanimated": { - "version": "4.5.1", - "resolved": "https://registry.npmjs.org/react-native-reanimated/-/react-native-reanimated-4.5.1.tgz", - "integrity": "sha512-RnMvtDuR+68ig864gAvZCOdZehqhC5rFmMo0kn+ARfgVSTvFeF6IFLBVgMPUu0KwihaapEyW24WRi6nEyy1kSA==", + "version": "4.5.5", + "resolved": "https://registry.npmjs.org/react-native-reanimated/-/react-native-reanimated-4.5.5.tgz", + "integrity": "sha512-xtJXZRZ1vkec1AIUVG02St2sbyZS5jc7227TlDu/HonqUYPeZAfiC4RI2jqL1dVMNBu1+7oBx/c9QkjF2kg6Lg==", "license": "MIT", "dependencies": { "react-native-is-edge-to-edge": "^1.3.1", @@ -30280,7 +30280,7 @@ "peerDependencies": { "react": "*", "react-native": "0.83 - 0.86", - "react-native-worklets": "0.10.x" + "react-native-worklets": "0.10.x - 0.11.x" } }, "node_modules/react-native-safe-area-context": { @@ -30406,9 +30406,9 @@ } }, "node_modules/react-native-worklets": { - "version": "0.10.1", - "resolved": "https://registry.npmjs.org/react-native-worklets/-/react-native-worklets-0.10.1.tgz", - "integrity": "sha512-62mRM19bDpfpdI8HLkEErcdOsrAPDtE9lA/sw+5lLRpzBHNhxaoj9QyY2KjXqUmirelxkX4zuPGTC3VdA0feJA==", + "version": "0.10.4", + "resolved": "https://registry.npmjs.org/react-native-worklets/-/react-native-worklets-0.10.4.tgz", + "integrity": "sha512-gbk0CxMrGywEp3SJAHO+2JVaCWtl4WyAYBIxLZy6Y113+mHHuq3FuT6iV+VcaBuJzuuN34mtdZ4j5JIlBDzmeA==", "license": "MIT", "dependencies": { "@babel/plugin-transform-arrow-functions": "^7.27.1", @@ -35780,14 +35780,14 @@ "react-native-gesture-handler": "~2.32.0", "react-native-keyboard-controller": "1.21.12", "react-native-nitro-modules": "0.35.5", - "react-native-reanimated": "4.5.1", + "react-native-reanimated": "4.5.5", "react-native-safe-area-context": "~5.7.0", "react-native-screens": "~4.26.0", "react-native-svg": "15.15.4", "react-native-unistyles": "^3.2.4", "react-native-web": "~0.21.0", "react-native-webview": "13.16.1", - "react-native-worklets": "0.10.1", + "react-native-worklets": "0.10.4", "tiny-invariant": "^1.3.3", "turndown": "^7.2.4", "turndown-plugin-gfm": "^1.0.2", @@ -41012,39 +41012,6 @@ } } }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/react-native-worklets": { - "version": "0.13.0", - "resolved": "https://registry.npmjs.org/react-native-worklets/-/react-native-worklets-0.13.0.tgz", - "integrity": "sha512-1OrhAeAKaZF4XrBa4YbPQbKzNOpjh52HDlId8e6ete1OCHNdAlrQHzG4gznJ225EAj3dgQXHViJvK51M9B52jQ==", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "@babel/generator": "^7.27.1", - "@babel/plugin-transform-arrow-functions": "^7.27.1", - "@babel/plugin-transform-class-properties": "^7.28.6", - "@babel/plugin-transform-classes": "^7.28.6", - "@babel/plugin-transform-nullish-coalescing-operator": "^7.28.6", - "@babel/plugin-transform-optional-chaining": "^7.28.6", - "@babel/plugin-transform-shorthand-properties": "^7.27.1", - "@babel/plugin-transform-template-literals": "^7.27.1", - "@babel/plugin-transform-unicode-regex": "^7.27.1", - "@babel/preset-typescript": "^7.28.5", - "@babel/traverse": "^7.27.1", - "@babel/types": "^7.27.1", - "@jridgewell/remapping": "^2.3.5", - "convert-source-map": "^2.0.0", - "semver": "^7.7.4", - "whatwg-fetch": "^3.6.20" - }, - "peerDependencies": { - "@babel/core": "*", - "@react-native/metro-config": "*", - "react": "*", - "react-native": "0.86 - 0.88" - } - }, "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/react-native/node_modules/pretty-format": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", diff --git a/package.json b/package.json index 9c18bb0db8..904e7e6af8 100644 --- a/package.json +++ b/package.json @@ -154,7 +154,7 @@ "react-dom": "19.2.3", "react-native": "0.86.3", "react-native-gesture-handler": "~2.32.0", - "react-native-reanimated": "4.5.1", - "react-native-worklets": "0.10.1" + "react-native-reanimated": "4.5.5", + "react-native-worklets": "0.10.4" } } diff --git a/packages/app/package.json b/packages/app/package.json index d72685bbec..e2e39ec03d 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -126,14 +126,14 @@ "react-native-gesture-handler": "~2.32.0", "react-native-keyboard-controller": "1.21.12", "react-native-nitro-modules": "0.35.5", - "react-native-reanimated": "4.5.1", + "react-native-reanimated": "4.5.5", "react-native-safe-area-context": "~5.7.0", "react-native-screens": "~4.26.0", "react-native-svg": "15.15.4", "react-native-unistyles": "^3.2.4", "react-native-web": "~0.21.0", "react-native-webview": "13.16.1", - "react-native-worklets": "0.10.1", + "react-native-worklets": "0.10.4", "tiny-invariant": "^1.3.3", "turndown": "^7.2.4", "turndown-plugin-gfm": "^1.0.2", @@ -198,6 +198,14 @@ ], "enableVideo": false }, + "expo": { + "install": { + "exclude": [ + "react-native-reanimated", + "react-native-worklets" + ] + } + }, "reanimated": { "staticFeatureFlags": { "FORCE_REACT_RENDER_FOR_SETTLED_ANIMATIONS": false diff --git a/packages/app/src/components/ui/isolated-bottom-sheet-modal/index.test.tsx b/packages/app/src/components/ui/isolated-bottom-sheet-modal/index.test.tsx index cf820ac86c..6637c5e339 100644 --- a/packages/app/src/components/ui/isolated-bottom-sheet-modal/index.test.tsx +++ b/packages/app/src/components/ui/isolated-bottom-sheet-modal/index.test.tsx @@ -58,6 +58,7 @@ vi.mock("@gorhom/bottom-sheet", async () => { }); import { IsolatedBottomSheetModal, type ContextBridge } from "."; +import { useAnimatedLayout } from "@gorhom/bottom-sheet/src/hooks/useAnimatedLayout"; import { useIsInsideBottomSheet } from "@/components/ui/bottom-sheet-scope"; /** Renders whatever the portal is currently holding, from its own place in the tree. */ @@ -200,3 +201,35 @@ describe("IsolatedBottomSheetModal context bridging", () => { ).toEqual(["false", "true"]); }); }); + +describe("bottom sheet layout subscription", () => { + it("stops updating a dismissed sheet when the window resizes", () => { + const container = document.createElement("div"); + const root = createRoot(container); + let layout: ReturnType | undefined; + const viewport = document.documentElement; + const originalWidth = Object.getOwnPropertyDescriptor(viewport, "clientWidth"); + function resize(width: number) { + Object.defineProperty(viewport, "clientWidth", { configurable: true, value: width }); + act(() => window.dispatchEvent(new Event("resize"))); + } + function LayoutProbe() { + layout = useAnimatedLayout(undefined, 0, 0); + return null; + } + try { + act(() => root.render()); + if (!layout) throw new Error("Sheet layout did not mount"); + const mountedLayout = layout; + resize(640); + expect(mountedLayout.get().window.width).toBe(640); + act(() => root.render(null)); + resize(960); + expect(mountedLayout.get().window.width).toBe(640); + } finally { + act(() => root.unmount()); + if (originalWidth) Object.defineProperty(viewport, "clientWidth", originalWidth); + else Reflect.deleteProperty(viewport, "clientWidth"); + } + }); +}); diff --git a/patches/@gorhom+bottom-sheet+5.2.14.patch b/patches/@gorhom+bottom-sheet+5.2.14.patch index f84d46f8fd..e0af7b8dcb 100644 --- a/patches/@gorhom+bottom-sheet+5.2.14.patch +++ b/patches/@gorhom+bottom-sheet+5.2.14.patch @@ -13,6 +13,27 @@ index ee51e76..dc1bc17 100644 if (_providedOnChange) { _providedOnChange(_index, _position, _type); } +diff --git a/node_modules/@gorhom/bottom-sheet/lib/commonjs/hooks/useAnimatedLayout.js b/node_modules/@gorhom/bottom-sheet/lib/commonjs/hooks/useAnimatedLayout.js +index 973d05c..b484b5f 100644 +--- a/node_modules/@gorhom/bottom-sheet/lib/commonjs/hooks/useAnimatedLayout.js ++++ b/node_modules/@gorhom/bottom-sheet/lib/commonjs/hooks/useAnimatedLayout.js +@@ -86,7 +86,7 @@ function useAnimatedLayout(containerLayoutState, topInset, bottomInset, modal, s + }); + }, [state, verticalInset, modal]); + (0, _react.useEffect)(() => { +- _reactNative.Dimensions.addEventListener('change', ({ ++ const subscription = _reactNative.Dimensions.addEventListener('change', ({ + window + }) => { + state.modify(_state => { +@@ -96,6 +96,7 @@ function useAnimatedLayout(containerLayoutState, topInset, bottomInset, modal, s + return _state; + }); + }); ++ return () => subscription.remove(); + }, [state]); + //#endregion + diff --git a/node_modules/@gorhom/bottom-sheet/lib/commonjs/index.js b/node_modules/@gorhom/bottom-sheet/lib/commonjs/index.js index e44ad86..96555ef 100644 --- a/node_modules/@gorhom/bottom-sheet/lib/commonjs/index.js @@ -54,6 +75,27 @@ index 94fabdb..60ca66a 100644 if (_providedOnChange) { _providedOnChange(_index, _position, _type); } +diff --git a/node_modules/@gorhom/bottom-sheet/lib/module/hooks/useAnimatedLayout.js b/node_modules/@gorhom/bottom-sheet/lib/module/hooks/useAnimatedLayout.js +index b0eec93..67713a2 100644 +--- a/node_modules/@gorhom/bottom-sheet/lib/module/hooks/useAnimatedLayout.js ++++ b/node_modules/@gorhom/bottom-sheet/lib/module/hooks/useAnimatedLayout.js +@@ -82,7 +82,7 @@ export function useAnimatedLayout(containerLayoutState, topInset, bottomInset, m + }); + }, [state, verticalInset, modal]); + useEffect(() => { +- Dimensions.addEventListener('change', ({ ++ const subscription = Dimensions.addEventListener('change', ({ + window + }) => { + state.modify(_state => { +@@ -92,6 +92,7 @@ export function useAnimatedLayout(containerLayoutState, topInset, bottomInset, m + return _state; + }); + }); ++ return () => subscription.remove(); + }, [state]); + //#endregion + diff --git a/node_modules/@gorhom/bottom-sheet/lib/module/index.js b/node_modules/@gorhom/bottom-sheet/lib/module/index.js index 8259637..eb057fe 100644 --- a/node_modules/@gorhom/bottom-sheet/lib/module/index.js @@ -101,6 +143,26 @@ index 2954b3f..7260656 100644 if (_providedOnChange) { _providedOnChange(_index, _position, _type); +diff --git a/node_modules/@gorhom/bottom-sheet/src/hooks/useAnimatedLayout.ts b/node_modules/@gorhom/bottom-sheet/src/hooks/useAnimatedLayout.ts +index 68c674d..564833c 100644 +--- a/node_modules/@gorhom/bottom-sheet/src/hooks/useAnimatedLayout.ts ++++ b/node_modules/@gorhom/bottom-sheet/src/hooks/useAnimatedLayout.ts +@@ -106,13 +106,14 @@ export function useAnimatedLayout( + [state, verticalInset, modal] + ); + useEffect(() => { +- Dimensions.addEventListener('change', ({ window }) => { ++ const subscription = Dimensions.addEventListener('change', ({ window }) => { + state.modify(_state => { + 'worklet'; + _state.window = window; + return _state; + }); + }); ++ return () => subscription.remove(); + }, [state]); + //#endregion + diff --git a/node_modules/@gorhom/bottom-sheet/src/index.ts b/node_modules/@gorhom/bottom-sheet/src/index.ts index 7aaea57..6a5f5a4 100644 --- a/node_modules/@gorhom/bottom-sheet/src/index.ts diff --git a/patches/react-native-enriched-markdown+1.2.0-nightly-20261014-766fc0e67.patch b/patches/react-native-enriched-markdown+1.2.0-nightly-20261014-766fc0e67.patch index 737578cd69..7ec1ec33b5 100644 --- a/patches/react-native-enriched-markdown+1.2.0-nightly-20261014-766fc0e67.patch +++ b/patches/react-native-enriched-markdown+1.2.0-nightly-20261014-766fc0e67.patch @@ -39,9 +39,10 @@ index 0a1c6c2..5935112 100644 struct OnLinkLongPress { diff --git a/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/EnrichedMarkdown.kt b/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/EnrichedMarkdown.kt +index c12937c..8105833 100644 --- a/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/EnrichedMarkdown.kt +++ b/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/EnrichedMarkdown.kt -@@ -95,7 +95,7 @@ +@@ -95,7 +95,7 @@ class EnrichedMarkdown( private var accessibilityLabels = AccessibilityLabels() private var textBreakStrategy: String = BreakStrategyUtils.DEFAULT_STRATEGY @@ -50,7 +51,7 @@ diff --git a/node_modules/react-native-enriched-markdown/android/src/main/java/c private var onLinkLongPressCallback: ((String) -> Unit)? = null private var onTaskListItemPressCallback: ((Int, Boolean, String) -> Unit)? = null private var onLatexErrorCallback: LatexErrorReporter? = null -@@ -296,7 +296,7 @@ +@@ -296,7 +296,7 @@ class EnrichedMarkdown( } } @@ -59,7 +60,7 @@ diff --git a/node_modules/react-native-enriched-markdown/android/src/main/java/c onLinkPressCallback = callback } -@@ -405,7 +405,7 @@ +@@ -405,7 +405,7 @@ class EnrichedMarkdown( val codeLinkRegex = inlineCodeLinkRegex val renderId = ++currentRenderId @@ -68,7 +69,7 @@ diff --git a/node_modules/react-native-enriched-markdown/android/src/main/java/c try { val filtered = if (isStreaming) { -@@ -418,13 +418,13 @@ +@@ -418,13 +418,13 @@ class EnrichedMarkdown( if (renderableMarkdown.isEmpty()) { postToMain(renderId) { applyRenderedSegments(emptyList(), false) } @@ -84,7 +85,19 @@ diff --git a/node_modules/react-native-enriched-markdown/android/src/main/java/c } val segments = splitASTIntoSegments(ast) -@@ -646,8 +646,12 @@ +@@ -478,6 +478,11 @@ class EnrichedMarkdown( + if (forceHeight || topologyChanged || heightBefore != heightAfter) { + MeasurementStore.invalidate(id) + requestLayout() ++ stateWrapper?.let { ++ val state = Arguments.createMap() ++ state.putInt("forceHeightRecalculationCounter", ++forceHeightRecalculationCounter) ++ it.updateState(state) ++ } + } + } + } +@@ -646,8 +651,12 @@ class EnrichedMarkdown( renderId: Long, action: () -> Unit, ) { @@ -3671,3 +3684,89 @@ diff --git a/node_modules/react-native-enriched-markdown/android/src/main/java/c val preservedStyle = (paint.typeface?.style ?: 0) and (Typeface.BOLD or Typeface.ITALIC) paint.typeface = if (styleCache.codeFontFamily.isNotEmpty()) { +diff --git a/node_modules/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownContainerShadowNode.cpp b/node_modules/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownContainerShadowNode.cpp +index a430d1a..b30a017 100644 +--- a/node_modules/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownContainerShadowNode.cpp ++++ b/node_modules/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownContainerShadowNode.cpp +@@ -22,6 +22,14 @@ void MarkdownContainerShadowNode::dirtyLayoutIfNeeded() { + } + } + ++// Only new props change the rendered markdown. When a parent is cloned, React Native's adoptYogaChild ++// re-clones its children without new props, and dirtying those clones re-measures every settled message ++// whenever the list above grows. ++bool MarkdownContainerShadowNode::shouldNewRevisionDirtyMeasurement(const ShadowNode & /*sourceShadowNode*/, ++ const ShadowNodeFragment &fragment) const { ++ return fragment.props != nullptr; ++} ++ + Size MarkdownContainerShadowNode::measureContent(const LayoutContext &layoutContext, + const LayoutConstraints &layoutConstraints) const { + return measurementsManager_->measure(getSurfaceId(), getTag(), getConcreteProps(), layoutConstraints); +diff --git a/node_modules/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownContainerShadowNode.h b/node_modules/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownContainerShadowNode.h +index dea8bb2..6c4bd20 100644 +--- a/node_modules/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownContainerShadowNode.h ++++ b/node_modules/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownContainerShadowNode.h +@@ -19,6 +19,8 @@ public: + + MarkdownContainerShadowNode(ShadowNode const &sourceShadowNode, ShadowNodeFragment const &fragment) + : ConcreteViewShadowNode(sourceShadowNode, fragment) { ++ forceHeightRecalculationCounter_ = ++ static_cast(sourceShadowNode).forceHeightRecalculationCounter_; + dirtyLayoutIfNeeded(); + } + +@@ -35,6 +37,10 @@ public: + + Size measureContent(const LayoutContext &layoutContext, const LayoutConstraints &layoutConstraints) const override; + ++protected: ++ bool shouldNewRevisionDirtyMeasurement(const ShadowNode &sourceShadowNode, ++ const ShadowNodeFragment &fragment) const override; ++ + private: + int forceHeightRecalculationCounter_{0}; + std::shared_ptr measurementsManager_; +diff --git a/node_modules/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextShadowNode.cpp b/node_modules/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextShadowNode.cpp +index 3ca259b..ab51055 100644 +--- a/node_modules/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextShadowNode.cpp ++++ b/node_modules/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextShadowNode.cpp +@@ -22,6 +22,14 @@ void MarkdownTextShadowNode::dirtyLayoutIfNeeded() { + } + } + ++// Only new props change the rendered markdown. When a parent is cloned, React Native's adoptYogaChild ++// re-clones its children without new props, and dirtying those clones re-measures every settled message ++// whenever the list above grows. ++bool MarkdownTextShadowNode::shouldNewRevisionDirtyMeasurement(const ShadowNode & /*sourceShadowNode*/, ++ const ShadowNodeFragment &fragment) const { ++ return fragment.props != nullptr; ++} ++ + Size MarkdownTextShadowNode::measureContent(const LayoutContext &layoutContext, + const LayoutConstraints &layoutConstraints) const { + return measurementsManager_->measure(getSurfaceId(), getTag(), getConcreteProps(), layoutConstraints); +diff --git a/node_modules/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextShadowNode.h b/node_modules/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextShadowNode.h +index eaa3279..05a02eb 100644 +--- a/node_modules/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextShadowNode.h ++++ b/node_modules/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextShadowNode.h +@@ -22,6 +22,8 @@ public: + + MarkdownTextShadowNode(ShadowNode const &sourceShadowNode, ShadowNodeFragment const &fragment) + : ConcreteViewShadowNode(sourceShadowNode, fragment) { ++ forceHeightRecalculationCounter_ = ++ static_cast(sourceShadowNode).forceHeightRecalculationCounter_; + dirtyLayoutIfNeeded(); + } + +@@ -39,6 +41,10 @@ public: + + Size measureContent(const LayoutContext &layoutContext, const LayoutConstraints &layoutConstraints) const override; + ++protected: ++ bool shouldNewRevisionDirtyMeasurement(const ShadowNode &sourceShadowNode, ++ const ShadowNodeFragment &fragment) const override; ++ + private: + int forceHeightRecalculationCounter_{0}; + std::shared_ptr measurementsManager_; diff --git a/patches/react-native-reanimated+4.5.1.patch b/patches/react-native-reanimated+4.5.5.patch similarity index 100% rename from patches/react-native-reanimated+4.5.1.patch rename to patches/react-native-reanimated+4.5.5.patch diff --git a/scripts/postinstall-patches.mjs b/scripts/postinstall-patches.mjs index 09ff2919b6..435f6331e0 100644 --- a/scripts/postinstall-patches.mjs +++ b/scripts/postinstall-patches.mjs @@ -14,6 +14,9 @@ const patchedPackages = [ nodeModulesPath: "node_modules/expo-modules-core", patchPrefix: "expo-modules-core+", }, + // Backport https://github.com/software-mansion/enriched-markdown/pull/924: preserve settled + // Android measurements across parent clones. Remove those hunks when upgrading past + // 1.2.0-nightly-20261019-926ef06f0; reconcile the other local patch hunks separately. { nodeModulesPath: "packages/app/node_modules/react-native-enriched-markdown", patchPrefix: "react-native-enriched-markdown+", @@ -46,6 +49,9 @@ const patchedPackages = [ // modal stack (see packages/app/src/components/ui/isolated-bottom-sheet-modal/host-scope.tsx), and // keeps a dismissing modal's status through its final onChange(-1), so a modal with // enableDismissOnClose=false that unmounts while presented still leaves the portal. + // Dimensions subscription cleanup: https://github.com/gorhom/react-native-bottom-sheet/issues/2734 + // and https://github.com/gorhom/react-native-bottom-sheet/pull/2751. Remove the useAnimatedLayout + // hunks once an installed release includes the cleanup; retain the other local hunks. { nodeModulesPath: "node_modules/@gorhom/bottom-sheet", patchPrefix: "@gorhom+bottom-sheet+", From 428ef707adc5c3c7e0396c19d21569b2e48ce5b6 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Mon, 26 Oct 2026 15:46:10 +0700 Subject: [PATCH 024/173] fix(app): demand the host directory from the workspace route (#7918) A workspace restored at launch with no open chat had nothing demanding its host's directory on a phone, so the deck waited on hydration that never started. The workspace route now keeps its host's directory demanded while mounted, through the same hook the agent route uses. --- .../src/app/h/[serverId]/agent/[agentId].tsx | 7 +--- .../workspace/[workspaceId]/index.tsx | 5 +++ .../src/hooks/use-directory-demand.test.tsx | 40 +++++++++++++++++++ .../app/src/hooks/use-directory-demand.ts | 16 ++++++++ 4 files changed, 63 insertions(+), 5 deletions(-) create mode 100644 packages/app/src/hooks/use-directory-demand.test.tsx create mode 100644 packages/app/src/hooks/use-directory-demand.ts diff --git a/packages/app/src/app/h/[serverId]/agent/[agentId].tsx b/packages/app/src/app/h/[serverId]/agent/[agentId].tsx index 008999a540..551e3b604d 100644 --- a/packages/app/src/app/h/[serverId]/agent/[agentId].tsx +++ b/packages/app/src/app/h/[serverId]/agent/[agentId].tsx @@ -5,6 +5,7 @@ import { useFetchQuery } from "@/data/query"; import { resolveAgentRoute, type AgentRouteLookup } from "@/navigation/agent-route-resolution"; import { AgentRouteResolutionView } from "@/navigation/agent-route-resolution-view"; import { useHasHydratedWorkspaces } from "@/stores/session-store-hooks"; +import { useDirectoryDemand } from "@/hooks/use-directory-demand"; import { useWorkspaceLayoutStoreHydrated } from "@/stores/workspace-layout-store"; import { useSessionStore } from "@/stores/session-store"; import { getHostRuntimeStore, useHostRuntimeSnapshot, useHosts } from "@/runtime/host-runtime"; @@ -87,11 +88,7 @@ function HostAgentReadyRouteContent() { ]); const hasHydratedWorkspaces = useHasHydratedWorkspaces(serverId); const hasHydratedLayout = useWorkspaceLayoutStoreHydrated(); - useEffect(() => { - if (!serverId) return; - // A compact app can open this route before its sidebar has demanded the directory. - return getHostRuntimeStore().acquireDirectoryDemand(serverId); - }, [serverId]); + useDirectoryDemand(serverId); const resolution = resolveAgentRoute({ hasHydratedWorkspaces, hasHydratedLayout, diff --git a/packages/app/src/app/h/[serverId]/workspace/[workspaceId]/index.tsx b/packages/app/src/app/h/[serverId]/workspace/[workspaceId]/index.tsx index 8f80f185c7..2ea41196aa 100644 --- a/packages/app/src/app/h/[serverId]/workspace/[workspaceId]/index.tsx +++ b/packages/app/src/app/h/[serverId]/workspace/[workspaceId]/index.tsx @@ -9,6 +9,7 @@ import { useActiveWorkspaceSelection, } from "@/stores/navigation-active-workspace-store"; import { useHasHydratedWorkspaces, useWorkspaceExists } from "@/stores/session-store-hooks"; +import { useDirectoryDemand } from "@/hooks/use-directory-demand"; import type { WorkspaceTabTarget } from "@/workspace-tabs/model"; import { WorkspaceScreen } from "@/screens/workspace/workspace-screen"; import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store"; @@ -110,6 +111,10 @@ function HostWorkspaceRouteContent() { ? (decodeWorkspaceIdFromPathSegment(workspaceValue) ?? "") : ""; const openValue = getParamValue(params.open); + // A restored workspace with no open chat has nothing else demanding its host's directory on a + // phone, where the sidebar only demands while its panel is active. Without demand the deck + // waits on workspace hydration that never starts. + useDirectoryDemand(serverId); useEffect(() => { if (!serverId || !workspaceId) { return; diff --git a/packages/app/src/hooks/use-directory-demand.test.tsx b/packages/app/src/hooks/use-directory-demand.test.tsx new file mode 100644 index 0000000000..7a03d83471 --- /dev/null +++ b/packages/app/src/hooks/use-directory-demand.test.tsx @@ -0,0 +1,40 @@ +/** + * @vitest-environment jsdom + */ +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { getHostRuntimeStore } from "@/runtime/host-runtime"; +import { useDirectoryDemand } from "./use-directory-demand"; + +function Probe({ serverId }: { serverId: string | null }) { + useDirectoryDemand(serverId); + return null; +} + +describe("useDirectoryDemand", () => { + let root: Root | null = null; + afterEach(() => { + act(() => root?.unmount()); + root = null; + vi.restoreAllMocks(); + }); + + it("demands the host directory while mounted and releases it on unmount", () => { + const release = vi.fn(); + const acquire = vi + .spyOn(getHostRuntimeStore(), "acquireDirectoryDemand") + .mockImplementation(() => release); + const container = document.createElement("div"); + root = createRoot(container); + + act(() => root?.render()); + expect(acquire).toHaveBeenCalledTimes(1); + expect(acquire).toHaveBeenCalledWith("srv_a"); + expect(release).not.toHaveBeenCalled(); + + act(() => root?.render()); + expect(release).toHaveBeenCalledTimes(1); + expect(acquire).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/app/src/hooks/use-directory-demand.ts b/packages/app/src/hooks/use-directory-demand.ts new file mode 100644 index 0000000000..f4d2953ab0 --- /dev/null +++ b/packages/app/src/hooks/use-directory-demand.ts @@ -0,0 +1,16 @@ +import { useEffect } from "react"; +import { getHostRuntimeStore } from "@/runtime/host-runtime"; + +/** + * Keeps a host's directory demanded while the caller is mounted. + * + * The sidebar only demands the directory while its panel is active, so a compact app that + * restores straight into a workspace or agent route has nothing else asking the host for + * workspaces and agents. Without demand the route waits on hydration that never starts. + */ +export function useDirectoryDemand(serverId: string | null | undefined): void { + useEffect(() => { + if (!serverId) return; + return getHostRuntimeStore().acquireDirectoryDemand(serverId); + }, [serverId]); +} From 902b0c7a1637cc7a6c2ee268dca8161965a35def Mon Sep 17 00:00:00 2001 From: "paseo-ai[bot]" <266920839+paseo-ai[bot]@users.noreply.github.com> Date: Mon, 26 Oct 2026 08:55:29 +0000 Subject: [PATCH 025/173] fix: update lockfile signatures and Nix hash [skip ci] --- nix/npm-deps.hash | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nix/npm-deps.hash b/nix/npm-deps.hash index e99d4da9b6..05bf98631a 100644 --- a/nix/npm-deps.hash +++ b/nix/npm-deps.hash @@ -1 +1 @@ -sha256-SKL7TMIuuV3imTIaQc66UDf3n6V3FB0nGSBucJ6rlA0= +sha256-zXSLA7FJHhIW63kkY3HbWaTsCTtJ30l71O9/Gx5F7QM= From 287ca547494f89076acb5a282e7f337420407fd9 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Mon, 26 Oct 2026 18:12:56 +0700 Subject: [PATCH 026/173] fix(app): enlarge sidebar kebab tap targets on compact layouts (#7928) On phones the project and workspace row kebabs were 24px and 18px boxes with a 14px glyph, too small to hit reliably. Compact layouts now use a 32px box and the density-sized glyph (18px); desktop sizes are unchanged. Negative margins keep the dots on the existing right rail and the rows at their 44px compact height. --- .../src/components/sidebar-workspace-list.tsx | 18 +++++++++------- .../sidebar/sidebar-workspace-menu.tsx | 21 ++++++++++++------- 2 files changed, 24 insertions(+), 15 deletions(-) diff --git a/packages/app/src/components/sidebar-workspace-list.tsx b/packages/app/src/components/sidebar-workspace-list.tsx index 16294e0a03..333eb68221 100644 --- a/packages/app/src/components/sidebar-workspace-list.tsx +++ b/packages/app/src/components/sidebar-workspace-list.tsx @@ -30,7 +30,7 @@ import { type ActiveWorkspaceSelection, } from "@/stores/navigation-active-workspace-store"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; -import { density, densityIconBox } from "@/styles/density"; +import { density, densityIconBox, densityIconProps } from "@/styles/density"; import type { Theme } from "@/styles/theme"; import type { SidebarSurfaceBackdrop } from "@/styles/surface-backdrop"; import { getSidebarRowBackdrop } from "@/components/sidebar/sidebar-row-backdrop"; @@ -463,12 +463,12 @@ const openInNewWindowLeadingIcon = ( ); +const kebabTriggerIconProps = densityIconProps("sm", foregroundMutedColorMapping); +const kebabTriggerIconHoveredProps = densityIconProps("sm", foregroundColorMapping); + function renderKebabTriggerIcon({ hovered }: { hovered?: boolean }) { return ( - + ); } @@ -2705,8 +2705,12 @@ const styles = StyleSheet.create((theme) => ({ marginRight: -6, }, projectKebabButton: { - width: 24, - height: 24, + // Larger on compact so the kebab is an easy tap target. The negative margins keep its + // dots on the same rail as the 24px desktop box and the row at its 44px height. + width: { xs: 32, md: 24 }, + height: { xs: 32, md: 24 }, + marginRight: { xs: -4, md: 0 }, + marginVertical: { xs: -4, md: 0 }, borderRadius: theme.borderRadius.md, alignItems: "center", justifyContent: "center", diff --git a/packages/app/src/components/sidebar/sidebar-workspace-menu.tsx b/packages/app/src/components/sidebar/sidebar-workspace-menu.tsx index e1543fac41..f74c43c980 100644 --- a/packages/app/src/components/sidebar/sidebar-workspace-menu.tsx +++ b/packages/app/src/components/sidebar/sidebar-workspace-menu.tsx @@ -17,6 +17,7 @@ import { isWeb } from "@/constants/platform"; import { getForgePresentation, normalizeForge } from "@/git/forge"; import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list"; import { useAppSettings } from "@/hooks/use-settings"; +import { densityIconProps } from "@/styles/density"; import type { Theme } from "@/styles/theme"; import type { ShortcutKey } from "@/utils/format-shortcut"; import { @@ -70,13 +71,11 @@ const archiveLeadingIcon = ; const unpinLeadingIcon = ; +const triggerIconProps = densityIconProps("sm", foregroundMutedColorMapping); +const triggerIconHoveredProps = densityIconProps("sm", foregroundColorMapping); + function renderTriggerIcon({ hovered }: { hovered?: boolean }) { - return ( - - ); + return ; } export interface SidebarWorkspaceMenuProps { @@ -439,12 +438,18 @@ function triggerStyle({ hovered = false }: PressableStateCallbackType & { hovere const styles = StyleSheet.create((theme) => ({ trigger: { - padding: 2, + // Larger on compact so the kebab is an easy tap target. + width: { xs: 32, md: 18 }, + height: { xs: 32, md: 18 }, + alignItems: "center", + justifyContent: "center", borderRadius: 4, marginLeft: 2, + // Center the compact box on the 20px title line it is anchored to. + marginTop: { xs: -6, md: 0 }, // MoreVertical paints only around the center of its SVG. Keep the padded hit box, but // pull the painted dots through that unused view-box space onto the trailing-content rail. - marginRight: -7, + marginRight: { xs: -14, md: -7 }, }, triggerHovered: { backgroundColor: theme.colors.surface2, From 678fe308db3acfa3b58866cb7ae603a9a331a07b Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Mon, 26 Oct 2026 18:35:29 +0700 Subject: [PATCH 027/173] chore(release): reconcile 0.13.2 metadata with main (#7931) * docs(release): add 0.13.2 native patch notes (cherry picked from commit 870c969fdb927f422b892841dd4b941ee7ce1aaa) * chore(release): cut 0.13.2 (cherry picked from commit d2941157a8f91512daf54fc688241d416e8f5ebd) * chore(release): refresh Nix dependency hash for 0.13.2 --- CHANGELOG.md | 9 +++ CHANGELOG.zh-CN.md | 9 +++ .../android/en-US/changelogs/130021.txt | 7 +++ .../android/en-US/changelogs/130022.txt | 7 +++ .../android/en-US/changelogs/130023.txt | 7 +++ .../android/en-US/changelogs/130024.txt | 7 +++ nix/npm-deps.hash | 2 +- package-lock.json | 56 +++++++++---------- package.json | 2 +- packages/app/package.json | 2 +- packages/cli/package.json | 8 +-- packages/client/package.json | 6 +- packages/desktop/package.json | 2 +- packages/expo-two-way-audio/package.json | 2 +- packages/highlight/package.json | 2 +- packages/plugin/package.json | 10 ++-- packages/protocol/package.json | 2 +- packages/relay/package.json | 2 +- packages/server/package.json | 12 ++-- packages/website/package.json | 2 +- plugins/package.json | 2 +- 21 files changed, 102 insertions(+), 56 deletions(-) create mode 100644 fastlane/metadata/android/en-US/changelogs/130021.txt create mode 100644 fastlane/metadata/android/en-US/changelogs/130022.txt create mode 100644 fastlane/metadata/android/en-US/changelogs/130023.txt create mode 100644 fastlane/metadata/android/en-US/changelogs/130024.txt diff --git a/CHANGELOG.md b/CHANGELOG.md index 6cab484e81..98d1c76900 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 0.13.2 - 2026-10-26 + +### Fixed + +- Fixed repeated Android animation exceptions for views that have already unmounted ([#7907](https://github.com/getpaseo/paseo/pull/7907)) +- Fixed the Android animation run loop continuing while the app is in the background ([#7914](https://github.com/getpaseo/paseo/pull/7914)) +- Fixed finished Android chat messages being remeasured during streaming updates ([#7914](https://github.com/getpaseo/paseo/pull/7914)) +- Fixed bottom sheets retaining window-size listeners after closing ([#7914](https://github.com/getpaseo/paseo/pull/7914)) + ## 0.13.1 - 2026-10-26 ### Fixed diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index a46d3ea21a..421da176dd 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -1,5 +1,14 @@ # 更新日志 +## 0.13.2 - 2026-10-26 + +### 修复 + +- 修复 Android 对已卸载视图反复抛出动画异常的问题 ([#7907](https://github.com/getpaseo/paseo/pull/7907)) +- 修复 Android 应用进入后台后动画运行循环仍持续执行的问题 ([#7914](https://github.com/getpaseo/paseo/pull/7914)) +- 修复 Android 在流式更新时反复测量已完成聊天消息的问题 ([#7914](https://github.com/getpaseo/paseo/pull/7914)) +- 修复底部面板关闭后仍保留窗口尺寸监听器的问题 ([#7914](https://github.com/getpaseo/paseo/pull/7914)) + ## 0.13.1 - 2026-10-26 ### 修复 diff --git a/fastlane/metadata/android/en-US/changelogs/130021.txt b/fastlane/metadata/android/en-US/changelogs/130021.txt new file mode 100644 index 0000000000..e08d39f767 --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/130021.txt @@ -0,0 +1,7 @@ +Fixed +- Fixed repeated Android animation exceptions for views that have already unmounted +- Fixed the Android animation run loop continuing while the app is in the background +- Fixed finished Android chat messages being remeasured during streaming updates +- Fixed bottom sheets retaining window-size listeners after closing + +Full notes: https://paseo.sh/changelog diff --git a/fastlane/metadata/android/en-US/changelogs/130022.txt b/fastlane/metadata/android/en-US/changelogs/130022.txt new file mode 100644 index 0000000000..e08d39f767 --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/130022.txt @@ -0,0 +1,7 @@ +Fixed +- Fixed repeated Android animation exceptions for views that have already unmounted +- Fixed the Android animation run loop continuing while the app is in the background +- Fixed finished Android chat messages being remeasured during streaming updates +- Fixed bottom sheets retaining window-size listeners after closing + +Full notes: https://paseo.sh/changelog diff --git a/fastlane/metadata/android/en-US/changelogs/130023.txt b/fastlane/metadata/android/en-US/changelogs/130023.txt new file mode 100644 index 0000000000..e08d39f767 --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/130023.txt @@ -0,0 +1,7 @@ +Fixed +- Fixed repeated Android animation exceptions for views that have already unmounted +- Fixed the Android animation run loop continuing while the app is in the background +- Fixed finished Android chat messages being remeasured during streaming updates +- Fixed bottom sheets retaining window-size listeners after closing + +Full notes: https://paseo.sh/changelog diff --git a/fastlane/metadata/android/en-US/changelogs/130024.txt b/fastlane/metadata/android/en-US/changelogs/130024.txt new file mode 100644 index 0000000000..e08d39f767 --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/130024.txt @@ -0,0 +1,7 @@ +Fixed +- Fixed repeated Android animation exceptions for views that have already unmounted +- Fixed the Android animation run loop continuing while the app is in the background +- Fixed finished Android chat messages being remeasured during streaming updates +- Fixed bottom sheets retaining window-size listeners after closing + +Full notes: https://paseo.sh/changelog diff --git a/nix/npm-deps.hash b/nix/npm-deps.hash index 05bf98631a..3e19f893c2 100644 --- a/nix/npm-deps.hash +++ b/nix/npm-deps.hash @@ -1 +1 @@ -sha256-zXSLA7FJHhIW63kkY3HbWaTsCTtJ30l71O9/Gx5F7QM= +sha256-eNiKmiZ3XXZMRZRSoGxUbMn2RtY6AX079vUatBYM+qE= diff --git a/package-lock.json b/package-lock.json index 1f5cce1657..847bd24eb7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "paseo", - "version": "0.13.1", + "version": "0.13.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "paseo", - "version": "0.13.1", + "version": "0.13.2", "hasInstallScript": true, "license": "Apache-2.0", "workspaces": [ @@ -35695,7 +35695,7 @@ }, "packages/app": { "name": "@getpaseo/app", - "version": "0.13.1", + "version": "0.13.2", "dependencies": { "@codemirror/commands": "6.10.4", "@codemirror/language": "6.12.4", @@ -37961,12 +37961,12 @@ }, "packages/cli": { "name": "@getpaseo/cli", - "version": "0.13.1", + "version": "0.13.2", "dependencies": { "@clack/prompts": "^1.0.0", - "@getpaseo/client": "0.13.1", - "@getpaseo/protocol": "0.13.1", - "@getpaseo/server": "0.13.1", + "@getpaseo/client": "0.13.2", + "@getpaseo/protocol": "0.13.2", + "@getpaseo/server": "0.13.2", "chalk": "^5.3.0", "commander": "^12.0.0", "mime-types": "^2.1.35", @@ -38213,10 +38213,10 @@ }, "packages/client": { "name": "@getpaseo/client", - "version": "0.13.1", + "version": "0.13.2", "dependencies": { - "@getpaseo/protocol": "0.13.1", - "@getpaseo/relay": "0.13.1", + "@getpaseo/protocol": "0.13.2", + "@getpaseo/relay": "0.13.2", "ws": "^8.20.0", "zod": "^4.4.3" }, @@ -38228,7 +38228,7 @@ }, "packages/desktop": { "name": "@getpaseo/desktop", - "version": "0.13.1", + "version": "0.13.2", "license": "Apache-2.0", "dependencies": { "@getpaseo/cli": "*", @@ -38472,7 +38472,7 @@ }, "packages/expo-two-way-audio": { "name": "@getpaseo/expo-two-way-audio", - "version": "0.13.1", + "version": "0.13.2", "license": "MIT", "devDependencies": { "@types/jest": "^29.5.14", @@ -42091,7 +42091,7 @@ }, "packages/highlight": { "name": "@getpaseo/highlight", - "version": "0.13.1", + "version": "0.13.2", "dependencies": { "@codemirror/language": "6.12.4", "@codemirror/legacy-modes": "^6.5.3", @@ -42120,15 +42120,15 @@ }, "packages/plugin": { "name": "@getpaseo/plugin", - "version": "0.13.1", + "version": "0.13.2", "dependencies": { "@agentclientprotocol/sdk": "^1.4.0", "i18next": "^26.3.0", "use-sync-external-store": "^1.6.0" }, "devDependencies": { - "@getpaseo/client": "0.13.1", - "@getpaseo/protocol": "0.13.1", + "@getpaseo/client": "0.13.2", + "@getpaseo/protocol": "0.13.2", "@types/node": "^20.9.0", "@types/react": "~19.2.0", "react": "19.2.3", @@ -42138,8 +42138,8 @@ "zod": "^4.4.3" }, "peerDependencies": { - "@getpaseo/client": "0.13.1", - "@getpaseo/protocol": "0.13.1", + "@getpaseo/client": "0.13.2", + "@getpaseo/protocol": "0.13.2", "react": ">=19.1.0 <20", "react-native": ">=0.81.5", "zod": "^4.4.3" @@ -42161,7 +42161,7 @@ }, "packages/protocol": { "name": "@getpaseo/protocol", - "version": "0.13.1", + "version": "0.13.2", "dependencies": { "semver": "^7.8.5", "zod": "^4.4.3" @@ -42188,7 +42188,7 @@ }, "packages/relay": { "name": "@getpaseo/relay", - "version": "0.13.1", + "version": "0.13.2", "dependencies": { "@noble/ciphers": "^2.4.0", "@noble/curves": "^2.4.0", @@ -42409,16 +42409,16 @@ }, "packages/server": { "name": "@getpaseo/server", - "version": "0.13.1", + "version": "0.13.2", "dependencies": { "@agentclientprotocol/sdk": "^0.17.1", "@anthropic-ai/claude-agent-sdk": "0.3.246", "@anthropic-ai/sdk": "^0.104.2", - "@getpaseo/client": "0.13.1", - "@getpaseo/highlight": "0.13.1", - "@getpaseo/plugin": "0.13.1", - "@getpaseo/protocol": "0.13.1", - "@getpaseo/relay": "0.13.1", + "@getpaseo/client": "0.13.2", + "@getpaseo/highlight": "0.13.2", + "@getpaseo/plugin": "0.13.2", + "@getpaseo/protocol": "0.13.2", + "@getpaseo/relay": "0.13.2", "@isaacs/ttlcache": "^2.1.4", "@modelcontextprotocol/sdk": "1.29.0", "@opencode-ai/sdk": "1.14.46", @@ -43339,7 +43339,7 @@ }, "packages/website": { "name": "@getpaseo/website", - "version": "0.13.1", + "version": "0.13.2", "dependencies": { "@cloudflare/vite-plugin": "^1.29.1", "@cloudflare/workers-types": "^4.20260317.1", @@ -44949,7 +44949,7 @@ }, "plugins": { "name": "@getpaseo/builtin-plugins", - "version": "0.13.1", + "version": "0.13.2", "dependencies": { "@getpaseo/plugin": "*", "zod": "^4.4.3" diff --git a/package.json b/package.json index 904e7e6af8..beeff7c613 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "paseo", - "version": "0.13.1", + "version": "0.13.2", "private": true, "description": "Paseo: voice-controlled development environment for local AI coding agents", "keywords": [ diff --git a/packages/app/package.json b/packages/app/package.json index e2e39ec03d..3eddd9b53f 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/app", - "version": "0.13.1", + "version": "0.13.2", "private": true, "main": "index.ts", "scripts": { diff --git a/packages/cli/package.json b/packages/cli/package.json index f4eef852fa..be8188fff3 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/cli", - "version": "0.13.1", + "version": "0.13.2", "description": "Paseo CLI - control your AI coding agents from the command line", "bin": { "paseo": "bin/paseo" @@ -28,9 +28,9 @@ }, "dependencies": { "@clack/prompts": "^1.0.0", - "@getpaseo/client": "0.13.1", - "@getpaseo/protocol": "0.13.1", - "@getpaseo/server": "0.13.1", + "@getpaseo/client": "0.13.2", + "@getpaseo/protocol": "0.13.2", + "@getpaseo/server": "0.13.2", "chalk": "^5.3.0", "commander": "^12.0.0", "mime-types": "^2.1.35", diff --git a/packages/client/package.json b/packages/client/package.json index 2a0927de17..df80ba532c 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/client", - "version": "0.13.1", + "version": "0.13.2", "description": "Paseo client SDK package", "files": [ "dist", @@ -47,8 +47,8 @@ "test": "vitest run" }, "dependencies": { - "@getpaseo/protocol": "0.13.1", - "@getpaseo/relay": "0.13.1", + "@getpaseo/protocol": "0.13.2", + "@getpaseo/relay": "0.13.2", "ws": "^8.20.0", "zod": "^4.4.3" }, diff --git a/packages/desktop/package.json b/packages/desktop/package.json index b4af89d742..4735fb5192 100644 --- a/packages/desktop/package.json +++ b/packages/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/desktop", - "version": "0.13.1", + "version": "0.13.2", "private": true, "description": "Paseo desktop app (Electron wrapper)", "homepage": "https://paseo.sh", diff --git a/packages/expo-two-way-audio/package.json b/packages/expo-two-way-audio/package.json index c60fbe6eb3..1a38528c25 100644 --- a/packages/expo-two-way-audio/package.json +++ b/packages/expo-two-way-audio/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/expo-two-way-audio", - "version": "0.13.1", + "version": "0.13.2", "description": "Native module for two way audio streaming", "keywords": [ "ExpoTwoWayAudio", diff --git a/packages/highlight/package.json b/packages/highlight/package.json index 5d9aed78cf..d7708e5925 100644 --- a/packages/highlight/package.json +++ b/packages/highlight/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/highlight", - "version": "0.13.1", + "version": "0.13.2", "files": [ "dist", "!dist/**/*.map", diff --git a/packages/plugin/package.json b/packages/plugin/package.json index b40268e537..18421b41e1 100644 --- a/packages/plugin/package.json +++ b/packages/plugin/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/plugin", - "version": "0.13.1", + "version": "0.13.2", "description": "Paseo plugin SDK package", "files": [ "dist", @@ -72,8 +72,8 @@ "use-sync-external-store": "^1.6.0" }, "devDependencies": { - "@getpaseo/client": "0.13.1", - "@getpaseo/protocol": "0.13.1", + "@getpaseo/client": "0.13.2", + "@getpaseo/protocol": "0.13.2", "@types/node": "^20.9.0", "@types/react": "~19.2.0", "react": "19.2.3", @@ -83,8 +83,8 @@ "zod": "^4.4.3" }, "peerDependencies": { - "@getpaseo/client": "0.13.1", - "@getpaseo/protocol": "0.13.1", + "@getpaseo/client": "0.13.2", + "@getpaseo/protocol": "0.13.2", "react": ">=19.1.0 <20", "react-native": ">=0.81.5", "zod": "^4.4.3" diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 99da1fc5bd..e463e681e7 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/protocol", - "version": "0.13.1", + "version": "0.13.2", "description": "Paseo shared protocol schemas and wire types", "files": [ "dist", diff --git a/packages/relay/package.json b/packages/relay/package.json index 82822177c1..b2e0c5187f 100644 --- a/packages/relay/package.json +++ b/packages/relay/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/relay", - "version": "0.13.1", + "version": "0.13.2", "description": "Paseo relay for bridging daemon and client connections", "files": [ "dist", diff --git a/packages/server/package.json b/packages/server/package.json index 5b8017659e..4aeb01dc3f 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/server", - "version": "0.13.1", + "version": "0.13.2", "description": "Paseo backend server", "files": [ "dist/server", @@ -107,11 +107,11 @@ "@agentclientprotocol/sdk": "^0.17.1", "@anthropic-ai/claude-agent-sdk": "0.3.246", "@anthropic-ai/sdk": "^0.104.2", - "@getpaseo/client": "0.13.1", - "@getpaseo/highlight": "0.13.1", - "@getpaseo/plugin": "0.13.1", - "@getpaseo/protocol": "0.13.1", - "@getpaseo/relay": "0.13.1", + "@getpaseo/client": "0.13.2", + "@getpaseo/highlight": "0.13.2", + "@getpaseo/plugin": "0.13.2", + "@getpaseo/protocol": "0.13.2", + "@getpaseo/relay": "0.13.2", "@isaacs/ttlcache": "^2.1.4", "@modelcontextprotocol/sdk": "1.29.0", "@opencode-ai/sdk": "1.14.46", diff --git a/packages/website/package.json b/packages/website/package.json index 5574ad4a46..2166f1a22e 100644 --- a/packages/website/package.json +++ b/packages/website/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/website", - "version": "0.13.1", + "version": "0.13.2", "private": true, "type": "module", "scripts": { diff --git a/plugins/package.json b/plugins/package.json index fd0a74d13b..30d9929eef 100644 --- a/plugins/package.json +++ b/plugins/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/builtin-plugins", - "version": "0.13.1", + "version": "0.13.2", "private": true, "type": "module", "scripts": { From 42d74c254652c43c03cf9bcdf7c0bb253e4706c0 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Mon, 26 Oct 2026 19:20:17 +0700 Subject: [PATCH 028/173] fix(ci): retry transient Apple staple connection failures (#7933) --- .github/workflows/desktop-release.yml | 28 +++++++ scripts/ci-workflow.test.mjs | 113 +++++++++++++++++++++++++- 2 files changed, 140 insertions(+), 1 deletion(-) diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.yml index f6b07c8b37..d81c036e62 100644 --- a/.github/workflows/desktop-release.yml +++ b/.github/workflows/desktop-release.yml @@ -169,6 +169,34 @@ jobs: NODE_OPTIONS: --max-old-space-size=${{ matrix.node_heap_mb }} run: | set -euo pipefail + export PASEO_REAL_XCRUN="$(command -v xcrun)" + stapler_bin="$(mktemp -d)" + trap 'rm -rf "$stapler_bin"' EXIT + cat > "$stapler_bin/xcrun" <<'STAPLER' + #!/bin/bash + if [[ "${1:-}" != stapler || "${2:-}" != staple ]]; then + exec "$PASEO_REAL_XCRUN" "$@" + fi + output="$(mktemp)" + trap 'rm -f "$output"' EXIT + for attempt in 1 2 3 4; do + if "$PASEO_REAL_XCRUN" "$@" >"$output" 2>&1; then + cat "$output" + exit 0 + else + status=$? + fi + cat "$output" + if [[ "$status" != 68 || "$attempt" == 4 ]] || + ! grep -Fq 'NSURLErrorDomain Code=-1005' "$output"; then + exit "$status" + fi + echo "::warning::Apple staple connection lost; retrying the same signed app ($attempt/4)" >&2 + sleep 30 + done + STAPLER + chmod +x "$stapler_bin/xcrun" + export PATH="$stapler_bin:$PATH" build_args=(-- --publish never --mac --${{ matrix.electron_arch }}) build_args+=("-c.publish.releaseType=$RELEASE_TYPE") build_args+=("-c.publish.channel=$RELEASE_CHANNEL") diff --git a/scripts/ci-workflow.test.mjs b/scripts/ci-workflow.test.mjs index c16e772172..4842870cc3 100644 --- a/scripts/ci-workflow.test.mjs +++ b/scripts/ci-workflow.test.mjs @@ -1,5 +1,8 @@ import assert from "node:assert/strict"; -import { readFileSync, readdirSync } from "node:fs"; +import { readFileSync, readdirSync, mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { spawnSync } from "node:child_process"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { relative as relativePath } from "node:path"; import test from "node:test"; import { runInNewContext } from "node:vm"; @@ -530,3 +533,111 @@ test("Windows units and integration run independently with complete routed cover assert.equal(selected(integrationCondition, outputs, true), false); } }); + +test("macOS release retries only transient stapling failures without rebuilding the signed app", async (t) => { + const workflow = readFileSync(new URL(".github/workflows/desktop-release.yml", repoRoot), "utf8"); + const wrapper = workflow + .match(/<<'STAPLER'\n([\s\S]*?)\n STAPLER/)[1] + .replace(/^ /gm, ""); + const networkError = + 'Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."'; + const cases = [ + { + name: "success", + outcomes: [0], + output: "stapled", + command: "stapler", + expected: 0, + attempts: 1, + }, + { + name: "transient then success", + outcomes: [68, 0], + output: networkError, + command: "stapler", + expected: 0, + attempts: 2, + }, + { + name: "exhausted network retries", + outcomes: [68, 68, 68, 68, 0], + output: networkError, + command: "stapler", + expected: 68, + attempts: 4, + }, + { + name: "non-network staple error", + outcomes: [68, 0], + output: "ticket not found", + command: "stapler", + expected: 68, + attempts: 1, + }, + { + name: "different exit code", + outcomes: [1, 0], + output: networkError, + command: "stapler", + expected: 1, + attempts: 1, + }, + { + name: "notary submission is not retried", + outcomes: [68, 0], + output: networkError, + command: "notarytool", + expected: 68, + attempts: 1, + }, + ]; + for (const scenario of cases) { + await t.test(scenario.name, () => { + const directory = mkdtempSync(join(tmpdir(), "stapler-retry-")); + try { + const statePath = join(directory, "state.json"); + const realXcrun = join(directory, "real-xcrun"); + const wrapperPath = join(directory, "xcrun"); + writeFileSync(wrapperPath, wrapper, { mode: 0o755 }); + writeFileSync(join(directory, "sleep"), "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + writeFileSync( + statePath, + JSON.stringify({ outcomes: scenario.outcomes, output: scenario.output, calls: [] }), + ); + writeFileSync( + realXcrun, + `#!/usr/bin/env node +const fs = require("node:fs"); +const state = JSON.parse(fs.readFileSync(process.env.STAPLER_STATE, "utf8")); +state.calls.push(process.argv.slice(2)); +const code = state.outcomes.shift(); +fs.writeFileSync(process.env.STAPLER_STATE, JSON.stringify(state)); +console.log(state.output); +process.exit(code); +`, + { mode: 0o755 }, + ); + const args = [scenario.command, "staple", "-v", "Paseo signed.app"]; + const result = spawnSync("bash", [wrapperPath, ...args], { + encoding: "utf8", + env: { + ...process.env, + PASEO_REAL_XCRUN: realXcrun, + STAPLER_STATE: statePath, + PATH: `${directory}:${process.env.PATH}`, + }, + timeout: 5000, + }); + assert.equal(result.status, scenario.expected, result.stdout + result.stderr); + const state = JSON.parse(readFileSync(statePath, "utf8")); + assert.deepEqual( + state.calls, + Array.from({ length: scenario.attempts }, () => args), + ); + assert.match(result.stdout, /stapled|network connection was lost|ticket not found/); + } finally { + rmSync(directory, { recursive: true, force: true }); + } + }); + } +}); From e3bbed3c73fac7cbd2b5e340037ff6a9201206b8 Mon Sep 17 00:00:00 2001 From: Simon Gurcke Date: Tue, 27 Oct 2026 00:02:44 +1000 Subject: [PATCH 029/173] fix(pi): queue prompts until manual compaction finishes (#7848) * fix(pi): wait for manual compaction before sending prompts * test(pi): simplify compaction regressions and stabilize live smoke --- .../server/agent/providers/pi/agent.test.ts | 75 +++++++++++++++++++ .../src/server/agent/providers/pi/agent.ts | 14 +++- .../agent/providers/pi/test-utils/fake-pi.ts | 4 + .../src/server/daemon-e2e/pi.real.e2e.test.ts | 21 ++++-- 4 files changed, 106 insertions(+), 8 deletions(-) diff --git a/packages/server/src/server/agent/providers/pi/agent.test.ts b/packages/server/src/server/agent/providers/pi/agent.test.ts index 1bad16ba30..b9f31b61b2 100644 --- a/packages/server/src/server/agent/providers/pi/agent.test.ts +++ b/packages/server/src/server/agent/providers/pi/agent.test.ts @@ -3063,6 +3063,81 @@ describe("PiRpcAgentClient", () => { ]); }); + test.each([ + { outcome: "successful", error: null }, + { outcome: "failed", error: new Error("summarizer failed") }, + ])("waits for $outcome manual compaction before sending a new prompt", async ({ error }) => { + const { pi, session, events } = await createSession(); + onTestFinished(() => session.close()); + const fakeSession = pi.latestSession(); + fakeSession.compactError = error; + const compactionFinished = Promise.withResolvers(); + fakeSession.compactCompletion = compactionFinished.promise; + const handler = session.tryHandleOutOfBand("/compact"); + const compaction = handler!.run({ emit: () => {} }); + + const { turnId } = await session.startTurn("continue after compaction"); + await flushTurnScheduling(); + expect(fakeSession.compactRequests).toEqual([{}]); + expect(fakeSession.prompts).toEqual([]); + + compactionFinished.resolve(); + await compaction; + await flushTurnScheduling(); + expect(fakeSession.prompts).toEqual([{ message: "continue after compaction", imageCount: 0 }]); + + fakeSession.finishTurn(); + await events.nextTurnCompletion(); + expect(events.turnLifecycleEvents()).toContainEqual({ type: "turn_completed", turnId }); + expect(events.eventTypes()).not.toContain("turn_failed"); + }); + + test.each(["interrupt", "close"] as const)( + "does not send a prompt waiting on compaction after %s", + async (action) => { + const { pi, session } = await createSession(); + onTestFinished(() => session.close()); + const fakeSession = pi.latestSession(); + const compactionFinished = Promise.withResolvers(); + fakeSession.compactCompletion = compactionFinished.promise; + const handler = session.tryHandleOutOfBand("/compact"); + const compaction = handler!.run({ emit: () => {} }); + + await session.startTurn("do not send this prompt"); + await session[action](); + compactionFinished.resolve(); + await compaction; + await flushTurnScheduling(); + + expect(fakeSession.prompts).toEqual([]); + }, + ); + + test("does not send a prompt when compaction finishes during interruption", async () => { + const { pi, session, events } = await createSession(); + onTestFinished(() => session.close()); + const fakeSession = pi.latestSession(); + const compactionFinished = Promise.withResolvers(); + fakeSession.compactCompletion = compactionFinished.promise; + const clearQueueFinished = Promise.withResolvers(); + fakeSession.clearQueueCompletion = clearQueueFinished.promise; + const handler = session.tryHandleOutOfBand("/compact"); + const compaction = handler!.run({ emit: () => {} }); + const { turnId } = await session.startTurn("do not send this prompt"); + + const interruption = session.interrupt(); + compactionFinished.resolve(); + await compaction; + await flushTurnScheduling(); + expect(fakeSession.controlRequests).toEqual(["clear_queue"]); + expect(fakeSession.prompts).toEqual([]); + + clearQueueFinished.resolve(); + await interruption; + expect(events.turnLifecycleEvents()).toEqual([{ type: "turn_canceled", turnId }]); + expect(fakeSession.prompts).toEqual([]); + }); + test("closes Pi compact loading marker when RPC rejects after compaction starts", async () => { const { pi, session } = await createSession(); const fakeSession = pi.latestSession(); diff --git a/packages/server/src/server/agent/providers/pi/agent.ts b/packages/server/src/server/agent/providers/pi/agent.ts index cf193e213b..881f8cbb29 100644 --- a/packages/server/src/server/agent/providers/pi/agent.ts +++ b/packages/server/src/server/agent/providers/pi/agent.ts @@ -1189,6 +1189,7 @@ export class PiRpcAgentSession implements AgentSession { private readonly contextUserEntries: PiCapturedEntry[] = []; private readonly treeUserEntriesById = new Map(); private readonly pendingExtensionResults = new Map(); + private compactionPromise: Promise | null = null; private outOfBandCompactionEmit: ((event: AgentStreamEvent) => void) | null = null; private outOfBandCompactionStarted = false; private outOfBandCompactionCompleted = false; @@ -1296,6 +1297,15 @@ export class PiRpcAgentSession implements AgentSession { void (async () => { try { + if (this.compactionPromise) { + // Pi RPC rejects prompts until the manual compaction request settles. + await this.compactionPromise.catch(() => undefined); + const turnCanceled = + this.closed || this.activeTurnId !== turnId || this.interruptingTurn?.turnId === turnId; + if (turnCanceled) { + return; + } + } const ack = await this.runtimeSession.prompt(payload.text, payload.images); this.activePromptRequestId = ack.requestId ?? null; const correlatedResult = ack.requestId @@ -1804,7 +1814,8 @@ export class PiRpcAgentSession implements AgentSession { this.outOfBandCompactionStarted = false; this.outOfBandCompactionCompleted = false; try { - await this.runtimeSession.compact(customInstructions); + this.compactionPromise = this.runtimeSession.compact(customInstructions); + await this.compactionPromise; } catch (error) { const message = error instanceof Error ? error.message : String(error); if ( @@ -1830,6 +1841,7 @@ export class PiRpcAgentSession implements AgentSession { }, }); } finally { + this.compactionPromise = null; if (this.outOfBandCompactionEmit === emit && !this.outOfBandCompactionStarted) { this.outOfBandCompactionEmit = null; this.outOfBandCompactionStarted = false; diff --git a/packages/server/src/server/agent/providers/pi/test-utils/fake-pi.ts b/packages/server/src/server/agent/providers/pi/test-utils/fake-pi.ts index b8c7930bc4..983b86c19d 100644 --- a/packages/server/src/server/agent/providers/pi/test-utils/fake-pi.ts +++ b/packages/server/src/server/agent/providers/pi/test-utils/fake-pi.ts @@ -108,6 +108,7 @@ export class FakePiSession implements PiRuntimeSession { steerError: Error | null = null; readonly controlRequests: string[] = []; clearQueueError: Error | null = null; + clearQueueCompletion: Promise | null = null; readonly compactRequests: Array<{ customInstructions?: string }> = []; readonly setAutoCompactionRequests: boolean[] = []; readonly subagentSubscriptionRequests: FakePiSubagentSubscriptionLevel[] = []; @@ -140,6 +141,7 @@ export class FakePiSession implements PiRuntimeSession { subagentSubscriptionError: Error | null = null; setSessionNameError: Error | null = null; compactError: Error | null = null; + compactCompletion: Promise | null = null; emitCompactEnd = true; getStateError: Error | null = null; getSessionStatsError: Error | null = null; @@ -233,6 +235,7 @@ export class FakePiSession implements PiRuntimeSession { async clearQueue(): Promise { this.controlRequests.push("clear_queue"); + await this.clearQueueCompletion; if (this.clearQueueError) { throw this.clearQueueError; } @@ -241,6 +244,7 @@ export class FakePiSession implements PiRuntimeSession { async compact(customInstructions?: string): Promise { this.compactRequests.push(customInstructions === undefined ? {} : { customInstructions }); this.emit({ type: "compaction_start", reason: "manual" }); + await this.compactCompletion; if (this.emitCompactEnd) { this.emit({ type: "compaction_end", reason: "manual" }); } diff --git a/packages/server/src/server/daemon-e2e/pi.real.e2e.test.ts b/packages/server/src/server/daemon-e2e/pi.real.e2e.test.ts index 984aa2fdcc..d2d839122e 100644 --- a/packages/server/src/server/daemon-e2e/pi.real.e2e.test.ts +++ b/packages/server/src/server/daemon-e2e/pi.real.e2e.test.ts @@ -219,7 +219,7 @@ test( ); test( - "real Pi daemon executes manual compact out-of-band instead of prompt text", + "real Pi daemon accepts a prompt after manual compact", async () => { const cwd = tmpCwd("pi-manual-compact-"); @@ -234,20 +234,24 @@ test( cwd, title: "pi-manual-compact", provider: "pi", - model: PI_COMPACTION_TEST_MODEL, + model: PI_REAL_TEST_MODEL, }); await client.sendMessage(agent.id, "Reply exactly: compact-ready"); const finish = await client.waitForFinish(agent.id, PI_TEST_TIMEOUT_MS); - expect(finish.status).toBe("idle"); + expect(finish.status, JSON.stringify(await fetchCanonicalTimeline(client, agent.id))).toBe( + "idle", + ); await client.sendMessage(agent.id, "/compact summarize this e2e run"); - await waitForTimelineItem( client, agent.id, (item) => item.type === "compaction" && item.status === "completed", ); + await client.sendMessage(agent.id, "Reply exactly: after-compaction"); + const followUpFinish = await client.waitForFinish(agent.id, PI_TEST_TIMEOUT_MS); + expect(followUpFinish.status).toBe("idle"); const items = await fetchCanonicalTimeline(client, agent.id); expect(items).toEqual( @@ -263,9 +267,12 @@ test( }), ]), ); - expect( - items.some((item) => item.type === "user_message" && item.text.includes("/compact")), - ).toBe(false); + expect(items).toContainEqual( + expect.objectContaining({ + type: "assistant_message", + text: "after-compaction", + }), + ); expect( items .filter((item) => item.type === "assistant_message") From 28834a91aeb31c4058bfa92558f9b45b5e5121c0 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Mon, 26 Oct 2026 23:13:25 +0700 Subject: [PATCH 030/173] fix(server): tolerate brief Windows atomic replace failures (#7955) A receipt could remain pending after provider delivery when Windows rejected the completed-state rename with EPERM. Retry transient replace errors within a one-second budget while retaining the original file and cleanup semantics. --- .../server/src/server/atomic-file.test.ts | 147 ++++++++++++++++++ packages/server/src/server/atomic-file.ts | 57 ++++++- 2 files changed, 201 insertions(+), 3 deletions(-) create mode 100644 packages/server/src/server/atomic-file.test.ts diff --git a/packages/server/src/server/atomic-file.test.ts b/packages/server/src/server/atomic-file.test.ts new file mode 100644 index 0000000000..a521a1cc3c --- /dev/null +++ b/packages/server/src/server/atomic-file.test.ts @@ -0,0 +1,147 @@ +import { promises as fs } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, expect, it } from "vitest"; +import { writeFileAtomic, writeJsonFileAtomic } from "./atomic-file.js"; + +let directory: string; +beforeEach(async () => { + directory = await fs.mkdtemp(path.join(os.tmpdir(), "paseo-atomic-file-")); +}); +afterEach(async () => { + await fs.rm(directory, { recursive: true, force: true }); +}); + +it.each(["EPERM", "EACCES", "EBUSY"])( + "commits a completed receipt after transient Windows %s replace failures", + async (code) => { + const file = path.join(directory, "receipt.json"); + await writeJsonFileAtomic(file, { state: "pending" }); + let failures = 3; + let elapsed = 0; + await writeJsonFileAtomic( + file, + { state: "completed" }, + { + platform: "win32", + now: () => elapsed, + sleep: async (milliseconds) => { + elapsed += milliseconds; + }, + rename: async (source, destination) => { + if (failures-- > 0) { + expect(JSON.parse(await fs.readFile(destination, "utf8"))).toEqual({ + state: "pending", + }); + expect(JSON.parse(await fs.readFile(source, "utf8"))).toEqual({ state: "completed" }); + throw Object.assign(new Error("destination held open"), { code }); + } + await fs.rename(source, destination); + }, + }, + ); + expect(JSON.parse(await fs.readFile(file, "utf8"))).toEqual({ state: "completed" }); + expect(await fs.readdir(directory)).toEqual(["receipt.json"]); + expect(elapsed).toBeGreaterThan(0); + }, +); + +it.each(["EPERM", "EACCES", "EBUSY"])( + "preserves the previous file and removes the temp file when Windows %s persists", + async (code) => { + const file = path.join(directory, "receipt.json"); + await writeJsonFileAtomic(file, { state: "pending" }); + const error = Object.assign(new Error("destination held open"), { code }); + const waits: number[] = []; + let elapsed = 0; + const attempts: number[] = []; + await expect( + writeJsonFileAtomic( + file, + { state: "completed" }, + { + platform: "win32", + now: () => elapsed, + sleep: async (milliseconds) => { + waits.push(milliseconds); + elapsed += milliseconds; + }, + rename: async () => { + attempts.push(elapsed); + throw error; + }, + }, + ), + ).rejects.toBe(error); + expect(elapsed).toBe(1000); + expect(waits.slice(0, 5)).toEqual([10, 20, 40, 80, 100]); + expect(Math.max(...waits)).toBe(100); + expect(attempts.every((time) => time < 1000)).toBe(true); + expect(JSON.parse(await fs.readFile(file, "utf8"))).toEqual({ state: "pending" }); + expect(await fs.readdir(directory)).toEqual(["receipt.json"]); + }, +); + +it.each([ + ["linux", "EPERM"], + ["darwin", "EACCES"], + ["linux", "EBUSY"], + ["win32", "ENOENT"], + ["win32", "ENOSPC"], + ["win32", "EXDEV"], +] as const)("does not retry %s %s failures", async (platform, code) => { + const file = path.join(directory, "receipt.json"); + await writeJsonFileAtomic(file, { state: "pending" }); + const error = Object.assign(new Error("rename failed"), { code }); + let attempts = 0; + const waits: number[] = []; + await expect( + writeFileAtomic(file, "replacement", { + platform, + now: () => 0, + sleep: async (milliseconds) => { + waits.push(milliseconds); + }, + rename: async () => { + attempts++; + throw error; + }, + }), + ).rejects.toBe(error); + expect(attempts).toBe(1); + expect(waits).toEqual([]); + expect(JSON.parse(await fs.readFile(file, "utf8"))).toEqual({ state: "pending" }); + expect(await fs.readdir(directory)).toEqual(["receipt.json"]); +}); + +it("does not retry after a rename consumes the Windows retry budget", async () => { + const file = path.join(directory, "receipt.json"); + const error = Object.assign(new Error("slow rename failed"), { code: "EPERM" }); + let elapsed = 0; + const waits: number[] = []; + await expect( + writeFileAtomic(file, "replacement", { + platform: "win32", + now: () => elapsed, + sleep: async (milliseconds) => { + waits.push(milliseconds); + }, + rename: async () => { + elapsed += 1000; + throw error; + }, + }), + ).rejects.toBe(error); + expect(waits).toEqual([]); + expect(await fs.readdir(directory)).toEqual([]); +}); + +it("creates parent directories and replaces binary and JSON files through the default runtime", async () => { + const file = path.join(directory, "nested", "file"); + const bytes = Buffer.from([0, 255, 128, 1]); + await writeFileAtomic(file, bytes); + expect(await fs.readFile(file)).toEqual(bytes); + await writeJsonFileAtomic(file, { state: "completed" }); + expect(await fs.readFile(file, "utf8")).toBe('{\n "state": "completed"\n}'); + expect(await fs.readdir(path.dirname(file))).toEqual(["file"]); +}); diff --git a/packages/server/src/server/atomic-file.ts b/packages/server/src/server/atomic-file.ts index cedc8d51ea..9f9c9f9568 100644 --- a/packages/server/src/server/atomic-file.ts +++ b/packages/server/src/server/atomic-file.ts @@ -1,10 +1,26 @@ import { randomUUID } from "node:crypto"; import { promises as fs } from "node:fs"; import path from "node:path"; +import { setTimeout as sleep } from "node:timers/promises"; + +interface AtomicFileRuntime { + platform: NodeJS.Platform; + rename: (source: string, destination: string) => Promise; + now: () => number; + sleep: (milliseconds: number) => Promise; +} + +const runtime: AtomicFileRuntime = { + platform: process.platform, + rename: fs.rename, + now: () => performance.now(), + sleep, +}; export async function writeFileAtomic( filePath: string, data: string | NodeJS.ArrayBufferView, + operations: AtomicFileRuntime = runtime, ): Promise { await fs.mkdir(path.dirname(filePath), { recursive: true }); const tempPath = path.join( @@ -13,13 +29,48 @@ export async function writeFileAtomic( ); try { await fs.writeFile(tempPath, data, "utf8"); - await fs.rename(tempPath, filePath); + await replaceFile(tempPath, filePath, operations); } catch (error) { await fs.rm(tempPath, { force: true }); throw error; } } -export async function writeJsonFileAtomic(filePath: string, value: unknown): Promise { - await writeFileAtomic(filePath, JSON.stringify(value, null, 2)); +async function replaceFile( + source: string, + destination: string, + operations: AtomicFileRuntime, +): Promise { + // Windows readers/scanners can briefly deny replacement. Yield with backoff, + // but keep interactive persistence failures bounded to a one-second retry budget. + const deadline = operations.now() + 1000; + let delay = 10; + for (;;) { + try { + await operations.rename(source, destination); + return; + } catch (error) { + if ( + operations.platform !== "win32" || + !(error instanceof Error) || + !("code" in error) || + !["EPERM", "EACCES", "EBUSY"].includes(String(error.code)) + ) { + throw error; + } + const remaining = deadline - operations.now(); + if (remaining <= 0) throw error; + await operations.sleep(Math.min(delay, remaining)); + if (operations.now() >= deadline) throw error; + delay = Math.min(delay * 2, 100); + } + } +} + +export async function writeJsonFileAtomic( + filePath: string, + value: unknown, + operations: AtomicFileRuntime = runtime, +): Promise { + await writeFileAtomic(filePath, JSON.stringify(value, null, 2), operations); } From 1f3266e2ba0292a63f19c8d37c978702b055b90d Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Mon, 26 Oct 2026 23:56:19 +0700 Subject: [PATCH 031/173] test(server): remove connected-host delivery timing assumptions (#7961) CLI startup is not bounded by the recipient quiet window. Exercise the three delivery sources in separate windows and retain exact timeline and durable receipt assertions. Await permission-finish cleanup after dispatch acknowledgment using the integration cleanup budget. --- .../server/connected-hosts/hosts.e2e.test.ts | 30 ++++++++++++------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/packages/server/src/server/connected-hosts/hosts.e2e.test.ts b/packages/server/src/server/connected-hosts/hosts.e2e.test.ts index d8d5533cf6..b6765051f6 100644 --- a/packages/server/src/server/connected-hosts/hosts.e2e.test.ts +++ b/packages/server/src/server/connected-hosts/hosts.e2e.test.ts @@ -1544,7 +1544,7 @@ test( ); test( - "remote agent reports, local CLI sends and automatic completion share the recipient batch", + "remote agent reports, local CLI sends and automatic completion reach the same recipient", { timeout: 30000 }, async () => { const parentPrompts: string[] = []; @@ -1633,7 +1633,10 @@ test( }); expect(report.isError).not.toBe(true); expect(report.structuredContent).toMatchObject({ deliveryStatus: "queued", serverId: aId }); - expect(parentPrompts).toEqual([]); + // A CLI process can take longer than the two-second quiet window to start. + // Exercise each delivery across windows; delivery.test.ts owns batching with a clock. + await expect.poll(() => parentPrompts, { timeout: 10000 }).toHaveLength(1); + expect(parentPrompts[0]).toContain("REMOTE_REPORT <ready>"); const cli = await promisify(execFile)( process.execPath, @@ -1656,7 +1659,8 @@ test( }, ); expect(JSON.parse(cli.stdout)).toMatchObject({ status: "queued" }); - expect(parentPrompts).toEqual([]); + await expect.poll(() => parentPrompts, { timeout: 10000 }).toHaveLength(2); + expect(parentPrompts[1]).toContain("LOCAL_CLI_REPORT"); const receiptStates = async () => { const directory = join(a.paseoHome, "agent-requests"); const receipts = await Promise.all( @@ -1671,13 +1675,10 @@ test( .map((receipt) => receipt.state) .sort(); }; - expect(await receiptStates()).toEqual(["pending", "pending"]); finishChild.resolve(); - await expect.poll(() => parentPrompts, { timeout: 10000 }).toHaveLength(1); - expect(parentPrompts[0]).toContain("REMOTE_REPORT <ready>"); - expect(parentPrompts[0]).toContain("LOCAL_CLI_REPORT"); - expect(parentPrompts[0]).toContain('event="finished"'); - expect(parentPrompts[0]).toContain(`source-agent-id="${child.id}"`); + await expect.poll(() => parentPrompts, { timeout: 10000 }).toHaveLength(3); + expect(parentPrompts[2]).toContain('event="finished"'); + expect(parentPrompts[2]).toContain(`source-agent-id="${child.id}"`); await expect .poll(receiptStates, { timeout: 10000, @@ -1870,6 +1871,7 @@ test( }); const a = await daemon({ mcpEnabled: true, + logger: completionLogger(), agentClients: createTestAgentClients({ onStartTurn: (prompt) => { if (String(prompt).includes('kind="agent-notification"')) @@ -1931,8 +1933,14 @@ test( await expect.poll(() => parentPrompts, { timeout: 10000 }).toHaveLength(2); expect(parentPrompts[1]).toContain('event="finished"'); await expect - .poll(async () => - JSON.parse(await readFile(join(a.paseoHome, "finish-subscriptions.json"), "utf8")), + // Provider start precedes dispatch acknowledgment and the durable removal commit. + .poll( + async () => + JSON.parse(await readFile(join(a.paseoHome, "finish-subscriptions.json"), "utf8")), + { + timeout: 10000, + message: "Parent accepted completion; waiting for durable intent removal", + }, ) .toEqual([]); }, From 4f9d9d6de2236486ecc2ad886a2c37f4b92271e0 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:04:42 +0000 Subject: [PATCH 032/173] Keep ACP terminal output from stalling daemon requests (#7953) * fix(acp): trim terminal output in linear time * test(acp): reproduce terminal output stalls with a larger workload The 128 KiB workload completes inside the regression deadline on faster machines even with quadratic trimming. One MiB exceeds that deadline on the old implementation while the bounded UTF-8 suffix implementation finishes promptly. Co-authored-by: liyang --------- Co-authored-by: liyang Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../server/agent/providers/acp-agent.test.ts | 40 +++++++++++++++++++ .../src/server/agent/providers/acp-agent.ts | 12 ++++-- 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/packages/server/src/server/agent/providers/acp-agent.test.ts b/packages/server/src/server/agent/providers/acp-agent.test.ts index 3deaa60c11..e902493dcb 100644 --- a/packages/server/src/server/agent/providers/acp-agent.test.ts +++ b/packages/server/src/server/agent/providers/acp-agent.test.ts @@ -811,6 +811,46 @@ describe("ACPAgentSession terminal tools", () => { truncated: false, }); }); + + test("trims large terminal output without rescanning the retained suffix", async () => { + const session = createSession(); + const terminal = await session.createTerminal({ + sessionId: "session-1", + command: process.execPath, + args: ["-e", 'process.stdout.write("x".repeat(1024 * 1024))'], + cwd: process.cwd(), + outputByteLimit: 1024, + }); + await session.waitForTerminalExit({ sessionId: "session-1", terminalId: terminal.terminalId }); + + await expect( + session.terminalOutput({ sessionId: "session-1", terminalId: terminal.terminalId }), + ).resolves.toEqual({ + output: "x".repeat(1024), + truncated: true, + exitStatus: { exitCode: 0, signal: null }, + }); + }, 1000); + + test("trims terminal output at a UTF-8 character boundary", async () => { + const session = createSession(); + const terminal = await session.createTerminal({ + sessionId: "session-1", + command: process.execPath, + args: ["-e", 'process.stdout.write("😀ab")'], + cwd: process.cwd(), + outputByteLimit: 3, + }); + await session.waitForTerminalExit({ sessionId: "session-1", terminalId: terminal.terminalId }); + + await expect( + session.terminalOutput({ sessionId: "session-1", terminalId: terminal.terminalId }), + ).resolves.toEqual({ + output: "ab", + truncated: true, + exitStatus: { exitCode: 0, signal: null }, + }); + }); }); describe("mapACPUsage", () => { diff --git a/packages/server/src/server/agent/providers/acp-agent.ts b/packages/server/src/server/agent/providers/acp-agent.ts index ae765ecd2e..e26b6e4ade 100644 --- a/packages/server/src/server/agent/providers/acp-agent.ts +++ b/packages/server/src/server/agent/providers/acp-agent.ts @@ -4093,10 +4093,16 @@ function appendTerminalOutput(entry: TerminalEntry, chunk: string): void { if (!limit) { return; } - while (Buffer.byteLength(entry.output, "utf8") > limit && entry.output.length > 0) { - entry.output = entry.output.slice(1); - entry.truncated = true; + const output = Buffer.from(entry.output, "utf8"); + if (output.length <= limit) { + return; } + let start = output.length - limit; + while (start < output.length && (output[start] & 0xc0) === 0x80) { + start += 1; + } + entry.output = output.subarray(start).toString("utf8"); + entry.truncated = true; } function readRecord(value: unknown): Record | null { From 65ce4b590a09106372c555cb7322f6da73b9d419 Mon Sep 17 00:00:00 2001 From: odoo-mvds <59664044+odoo-mvds@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:54:25 +0100 Subject: [PATCH 033/173] fix(app): remove restored agent tabs from foreign workspaces (#7956) A persisted explicit pin outlives archive recovery because its agent never joins the unrelated workspace directory. Drop positively foreign pins after hydration and let existing reconciliation remove only the misplaced view. Preserve unknown ownership and legitimate historical opens. Adapts the repair proposed by kaicot in getpaseo/paseo#6901 to current main, with persisted-store and real-browser regression evidence. Refs getpaseo/paseo#6900. --- docs/qa-evidence/foreign-agent-tabs/after.png | Bin 0 -> 60096 bytes .../qa-evidence/foreign-agent-tabs/before.png | Bin 0 -> 59333 bytes .../workspace-navigation-regression.spec.ts | 82 +++++++++- .../e2e/support/helpers/workspace-layout.ts | 35 +++++ .../src/stores/workspace-layout-actions.ts | 16 +- .../workspace-tabs/agent-visibility.test.ts | 144 ++++++++++++++++++ .../src/workspace-tabs/agent-visibility.ts | 30 +++- 7 files changed, 292 insertions(+), 15 deletions(-) create mode 100644 docs/qa-evidence/foreign-agent-tabs/after.png create mode 100644 docs/qa-evidence/foreign-agent-tabs/before.png diff --git a/docs/qa-evidence/foreign-agent-tabs/after.png b/docs/qa-evidence/foreign-agent-tabs/after.png new file mode 100644 index 0000000000000000000000000000000000000000..77f3c92d8be4380a1d6b47249a6e99249e5cd433 GIT binary patch literal 60096 zcmce;by!sU8!tNcwqT1QB4yAiARw*MjdUYOY`Qx}ML12wPvmF_kBP0j*qOg$n6^sZy*qe+hU@EatOo~`14}NUl-xw zC7JjI1mbUmnBXe~$EcOjYmWD3hw3)Pyzg}pEq?e!>bzdzkU%>ilpROvvOgfJpm141 zHi))jf6T@Ep6H{?a$@VA>w_et!A$<-&vi~QCQQ+84s+2C2Ep0;Jgj+1Mn;P_-XF=z z$@zMFN1h+=hpQw$JRlIy-y?3FKXzQc`0V`g<=wxk&L0s{j}Vv6AD@5tzwv^NM}7eT zs@ZRiqPYrC!SXYynPvqwXf>5@{prfXgM(u59TBIaGnZClc)fXfMs9Ez=;<{f85q*P zfB)|2q=;5(OdJ!NF%V`o3DJ2NyjI zOiJ0+Gg9@+PXQ0ij`I3V~*S%W@ct>*G;44zRZLv+pU>YGWT!y2??>)*Vbw9pX=0Y zM{=MYtfwxUj_~%QwPTs5i`w~I+G}cFmz;@_93;oOn{~!5nxJ`^uKg@DAKhI>+fYio zcK!M#h!d=wsb<&lqtYvagm~p10Ud&7BWY^Q@%TxPS54`y0W5{RRdGES=>} zdHdr?hmIdVjS+kQ^|5P~JX*(}^-e>rpzTF;$Z7z4Z+11@0$!>N$Xm}Rt zVdHkVBO@xh&~5lK&p;|k>gd&+YK3#_${@zuQ}dsp{Kf<^rd~9f`^!FdUb`<1zt|Pq zG+MU5GFDMLI%?MXy#RB}vfPy@k*QwfzCT(tI--Gp64A&q-xQke@9(eWI9W1vsnT+? zCS2Q{_g&p{A!P19`)d_?i3KM8sAT@r1Nq&hHIHk!TsCtn{n|*Iodsqj5+g!J!twSc zzmwf`om3YpJiO>_b+K%(lMOw&{)^uew9BS`mf85H->W!^X!wOU7w{qv*p^*^{qqD8%cJdVJ zQu#i4zQY9!x5F9>D=P_$UiQl6f-J2eEe1wL#>sx|Gso2ef|=W>)+iqA(dmgx>a|zl zOxo`(EU4ICHVV-xXWhoZNtgQ__sYY$!o?xDfSi(2DspeRQ44#^y(*e~m6T?mfIqCEdKYw>m6PLdZ$U zhCH2uP2JRPHs7{N^gJcKP`kt$ZdfJ(lW=iqX}(c+oKd&1(0zI{p=&tAo12?U-N|K# z3S-qZ5{j8>iNd$Fp@QG5VXH!zH#P=SQG9C@)YYA0ZRg>(p7~tsz0ZGk{A)fIx!4p+ z*HvjYY=6BdU72aT%)t=0{cT>?LF)~+leKZ=%ZoGKWR+CSI7I9-ja0Eg z2%1&Y%OvTO$;ISY9*4CMJr4nI9OUM230(Hq&MKV5 ze5|u^`Q@$SCc(bh#6fl+RUAd|7{`7f-BBQl|a0ZBliN$m%9_;N zkIcq)m&M-I@$@9i;9k!%={Hx{!HU}#2v)C+a^qjOmI%*6g_9FD$@XWB+ODeYe7Y_Z zK*S;Ltkj+zs`#qcd%Y+!Bp|@l z5?Q43WDV{dE$47E!aS}8?kx50PI`MM zCnU7R@G5H-My0Fd8N`2@ul6|df57axK6c5p>l zC56tuh?p2(WLJ3q^lAKzM^Lh%-Ry_EL`3ScmI4gS7oPov8~F9cH$5IPpY6F;DMhGhm-7}Nz7EgwjpMJ zYI-5+sVoH7q9s?*h#SvKMC><>i=T z*i2ymsrTfi@*i)U6q<40C(Q0aM6#LKPyG_3i4`x{<3DqF`0 zZnxa0=wB>{3H?~u6G1W3B(JSKZZ%E%<|t??A&!ZG?_|f3=1$;)&98BO-@~J#qmPeW z^-FE$rJJ%MvvAHC!qjRNa3%^UW`2U4980;Dao2(>QqBTrl;pgVs^SN z+gVT_M#_oCg-t*7tz3HHcDVB4l1t?G@5l4}OyUXQ!c0to&{jkQHSBF|zrG#J(oDx8 zv0YF7(%qHYw7cxXLVCRlk4gWyi_cn5@p>Jek_6qw=8u=Iox1V7meWp_UR5vX!mp#K zci*U<4`?WJ|= z)(%=-*&*xK;qLH^|JqnZyuZJqoZQyh=rujECi!z9(`5Enm2#F~WBunFS0*s0YLESH zk?}QjJUPpdj^&f!JGqDb9_F$SS9oO<%#2Xk-$vVyj-2yM?(8n zSPfy}!!LyV>D!;Yz0>jgp`6_!<&mTfqx{Df2twbOyVnp0M1p zst*EJZ$ErQL_MopplKf@Xkw?9D>YqrTmKmEy?)BipFi=oC|pE@gi?jr2fx<&6A=ac zrGQ?`+S7*CF7@)I|JSeC0VKmsS}043Zag=N9q|-aR@O4--S2*WdEedfHA%O_R>(bd z2aUG!8>;zy3;|J&JIyQB&gL4sv2bxI;k}WSbt57&DbU>W`tI(jpgP-LX8PUqBfaCw zK;y!~w=ZAlY5p=aoTn~DvSbw)b$4Z}_Z%>=IXUglH0Bv^%Dd1|a1_af}5#j7=9tQ`@TdY6oG=<1U6V-iMjhm&EbpoOjo&S4l~UrM%WVkeJI>C$710rE~>XPh^ z@={;QB*t>`Nh(!35o5J=XB^gLZ)LRHNdn{Uak#UXh-oWXc$R=HXor4mv^hm_>FQ3n zJ2_(-m8rzHqHO9(uYttX-mc46`$meb(q~FPeG=q+E}O3OQncYp>Sgg~N;~^6*;$Xq zW8LnG+11r?a+Vk)7+>$%?=G364(kF)QVScjO*#9VW*RmDs4!@j9(Ia|q!(15jVI>} zCF>0VnHlWttOUq|ML!mrpPjugqidWN?$9@IuwKCsD#zAS@K0yYv&eh=eu45~p>F9) zJ@}(R0ZMCYS^8i4UhbjFOO|GvXa{kZ#CB&@h0L?eH*1FDv>u=rd>hvo)Y<9Av<_nC zyHdvDrM+~%y&BIV5}0I-XjTa#cDA&)XR)PQ&!wlH)W9n^G~Qo}4rxkLX6k5fZ?-H> zFl?9h3ZHqVlq_wQa4+M}O*Z7HMqR=J@CdJ+Y->B?MwuN@X{Rw;U*=_G{3(1Jqg7Gb zRF45D==n**b>Zg+-_wNU-+szGCp#*1bfexi5v<7N-t@?#qU4`sG?e?R!`;oz0-ef{ ztE*;ZcFPG1m20ytgL#ji3f~IDZxo4RHT*a$Z_)bQo!7-)o?q_lczZoljV-vw0$Rzi z#TkYv_J!p{b_>68k1X~cP{a>_2Y~mAdaaLRif%E{&^Ya_l+=3TYULStxDQnFGS9e; z|3?dOu~(FMBIh0?oLbc|kNNS#8Q6jXzf7};9HD^VFMTX|XQ5fM*KMMZ!qpoa7Q1ti zXdooPfD?nVm5a zr&5ts{JGR_S=6dnH807NC{c|%_JBg@fo@fa%{=+qebv7Hekw{zgZ3CVW83wCoZ2kS zGKyaT#MlCN#BN(OH^5pZyE(vus^M~Y*b4WP-G1`V0c8AEqouvZuhiXB_5HWLhN~4A z@6QAWHftwCX;|(@bH8|T%$l~%>$3M%>U1%gkccBIQ%lpK?@LI>ZI`!;UHV=HqEjfm ztmk1l$`Ug(Gmm`MHYTUHt_ccLIH{Z_{Hm)Gu6<2kyC%~|Q6?(>Yl%=YS3SWpQ|ViCp6`gpDB(nZ*6)5E52X&Fp3x12?U5*uK?SGyO&F85uU$feE$+_JT&9pvx`#d#_ihf$H1A2N{>F@pe{Y6K zC0meBx{)e$dtRU?0z?okOpGHG4k0q8*>{3L?UIFsy?Ua)ryd_&QA#qb-AoU%+*t++ z&E`AfsY-2)n0(ZlI+th@G_6;>ZmYwsVsqZvs38%z4wJFCbZswe$K}*D#l5usuFRKE z8Pn$Q<*fbS-}<5~3|Oa~1@D9w-36P@IQ^|RbCcd84fAQRMt!Ei|&7kSEw771MYtxR?2Ft5F`V|+r(eLvV6 zhlEi~aZ3v}gT9qr%$1w>Dagq~ScbfSVl4Eedc-j$t_>IQv#}{M&^ArXw`)HjBurhP zvpzdnH)J7Cw2kI=c*teDag(V$f&Y7Ut6?LV7{=W=+*-f; z=L+Ta%H^`_xeQWsQbVVqIFdKc#513Dj7`)J{q>97C`bo(X#Lk5kVx|Nn**A|(W3lY z`<6rb+WN1>(blfAbx-5vn4C@~JlZAb>+bg#TXod=56?dO{Dqe1xT|daRGEv(EFZ6M z_SziKF{6;{J|kOH%5{{;d}Z|5qk7o{O6@kq1|m(gmYJQ^qV`o}H<2s}r}gX8D?yJN z`3>QkhZfM4)>hli@}iKa9sy1w4)b8-y&Fu5b-qJI7Eg5?_t)II43(7jP!x2t423z9 z*)#}5Vw&C+6~485hvBDQO&bYO(V}9n_%4gyhs`Sw8>L7CC!fQlPob(|A4X+DM05PW^FI7it>*_KZgR!1XbKVaJktwzR@iBQ_vny_6w2HGX+R;PA_S*T)R+KP2ZR_OX*`1rK4Uj_{;Hz z@zShr>Ad0P$o*xuzq>2<-ZwA%8Ph81>#KO)w~AQOqRx)zL#sW!{Rvr1l`^XW`3@&K zMPk1`ds>ewwO{3NEnXviGhN5KwbhKaU+QTc9He>rbQ(@nmcVt&r+&?npXxaVK+_)OJCq+87!n;c9TOtBnZ`NfK7utw%4p#DHNRh`hckgz8`Lgp^;A$W- zXZgzQ*yoFh%(tJ|9 z|JSXI$Mr+TyrZqm=UDD|-~<&8kEQv%N7)D(G;;*+RjtlNRkXqL%P{^np_HJR&%=L`on z&miS zg1}xq*)~6RhVI?F_$*ECu^p`kyw0{`**eWo9v)*H+zxHg@*?{JjLV_Cg$Aux34K<+ zDrJ5zvKTLI_?Va}IyMNT?CDKty<)UoENN7+#OVmc#v>Lswvt6EbsL+!NG$~uaQ5E5eL}n_JqBR*_@g<9Ah1x`ZKx5tc(?x)8Tz_-43X{e|a6UWF| z%#p2UVv_zOJXE~#ObRbi%Y=MsBvdvhZX^Mt76dH1RH0 zjApuJn5BW=5brO)6NO_;XIhU(p%+pR3g(W=6x+b8s^_hNU%!fvE&NY?_i2T=-gwil z>eH(X`RW~Sp<|9CI`m;#xGim*d=}tiz(M+ox$1A2AFfx{|=cK%;-QSv}7E6#z3ym@| zHGLBM*VCs@Z;mT>cVrSj{v3#5{Lnolw|DJU%LHo^5aw6;1gx#-LtEWWab_BFJYoJ2TVhT{4(A56hRCmsfzV zyh*^V;MZ_fNY3g@iiXax&Uo)e+@G#};o3KxoTtx%i>-&d(Q%kp(wprITiY5_5fMUZ zuCupd@kspUz0(xa$8--F&Je!A&-FzyLPHWOdB1kj7Xrjp?#p1rXlL8Hg)07-Cn8eK2VVNE3Pl;5@ z@7ks4GyS>TSy^of+K4I-D58;tW{Jh$n7ngu@|&7vrYi>jauEplYy9~M?fwR(%2m0i zyhuJl<4mvnV&8t#L3*>d5+aZ=8$_3abA zb%%uxVNxpTD78{syZV6Dp1p719+;Q_Jp^3cml+8!qOWDVevL zr662fT<}kms(n%PT#lA!65&s7Gr)7B;5ymbeo;tCIN5H;1U*Pyu&AVEjeTJyOk3*9 zh&Y0_Ez@P;GyhRSZLGiq6C1l`Pid{8aemfHCcou$Qk2mF3i=eJATF4W6ieN>7ZXF8 zcw080SYoHb^0DsOslb-&$zdzzgk9$3wFJ%0=6a3V$5^SzLWwtOX~n1_{a08G>RF9c zjF5;(bD>8019w2AT!y2iA99UE0v6VspX7ipQ?jJVD=}=3*e9Tw8QYPFreL8C zKIF!_0}*YNT#kadKlyMBZ&{XFfwbFDu6}oZe*QQzHZ~&lNVf&5G@<#yV~UZDjpn8P zo7h8Vkha42ZWErKx;Hka-%{ogSL3ssNYP30xVEpEtJm9;+P%Gfb7WML%t=qshl7uX zrv@}$2DN-iYwO{{%rHhx(8A^Q?lks7+irLkS^gY!zm^tBDyrl+@m^`wWo}1(n6t{N zfq{nldOGS9cVS_#xU%bo%L2H!$BM0%n?g+}_>2DO6s#cmhj17Nz6YWhzi5(D#X;Jq zh^WNB2{|1+rB{7?%tN!0Ces`Fwqm=@L{2hnMQuhcgT;JVZfI0?ZKrVhf@OE)+jBdX zdSy)elE&3qhWNFwTjK`_FIZW-@hmRIpP}00UKM>AE)D5(Pc9-kKT!UhHp%<-r(t1X zz;tJ&|M)Dl}B;(5ife(k;mBLY#yF!k{5#0NRqm%`3(H|OB3BXLcaCr*xVdovc- zXJ)>Igb?H5-6tSGQwuXPO8XOCvr3nn7@G=f$9*=Yaeg3$2>BmO+5t^1EnM!$JwpXV zd3iR*eHm}^lC%N-2J)X;&o(K}hG~{T=_ZMXa{vY7NMY;Y1n^E!?mgc${{D{^AROqP z0;{8~EkIgYnq?EJ?EWe@`6`FzF&d*p{K7KDQbJAbFocGmk}A1jr_Nu!$aL^c-4yW8 zU%x4+5wt=$&os*)FyhXBusk{31>eAf8L>Xi2^Q~fKY~#1 z2@oQJDJ#-O2tjalJ6hcjIf_009p(+!`-fR*iQYblQDB{%RJi8&xf8J&TY@$T;FmfS zd{I()`MkF1;pUyOifdrld=CnmoSyE*AlHq1P2JDjPG_5g>gp)x+r7V#aCdcfPA>KS zJiO?2o6BodG>m~ErBb5LxRGSzShSyVbTPygmbo*si)+46nYPwrKB(#g!^=j41 z@@Z|P#9^X}PlkuNZ(zU?yVct@Q0AbFeL(U+#pYn6x;ITxLQE{0)$pgkRDm}c>79ED z$ltyNj~^506=q~aZEQ&B=uGB1o*dehSMXAVjUUXDvOwkC+uD*v`1^eR{7+ZHV6jzT z<2xXwucO_8W4A|hD-X%7t*uE#vIo^qRA16Yp72AuKuombB%qn;RNbPYyU@)0v49tY zMsdTlv#|=7Yq+F+#a4MbwO(YrY22#QoAt3H1t$9_3JK83?%eq)F>2Tr<+L~G1NHAA zn{kUTK3&h1__#PdFQC=CtK1WSjl*+%FI~g=LUN=MOxYUivgTQXMBV}`JDC6UTfB7h zulPW|pVA`2!h1`-$_%<_)jVP2Ar`OA=~!N?sRXWCpx>L_GOT)uT_r!?P&8tYXCLI6 z7_EqUt7EzBoPT|O1OC42q-VIE=6N+Zm7{Jb{%#n@7*Gy@uu+f&`=_CH2(i+MAn$)6gwXBUF9s-qqbwMldusG#s=e z$Ih*NAm?cdl?v=K?jkKME%#1VJ;xoVcOzI08(t;ma+f%6##ICeyn0nlhc2h(1!NqO zt{l&IF!2t6GYD9el$5;K8CEj4omb6a3}H;#*cR4y5UB-jVBr6>v9oR~IacQ8=Fsjz zATbRj9o6?oQH{IpyK!?L1(0yh%*}}fVe83~rM^7_S@*0<$!d407u@O`nOHv9i?%xp zo!~ph9lV%b2YtA#F2GGNiNkEjdSjxxxcCJ$?WZCEL&L+WDk|WU%(rrkpSB~lOges4 z12T(sGN{SbM~d|X2FgHAU~r<^19@zf78|<`8@30hwx)(Wr`f(YQ$6{YnZmWRz2SAx zUV|AKvp|$_gquac7-eW~o&`5-VlPO>M~*CWK_ac`@>>Fe`ktPh8V0CG)GREt&v!mv zp7{3d1pz^Fr2P|Y$(#7AUda&=s@wBSj4U$ITpwWd#xlRNA1y5aACN+)*pVNKp(Ef| z&wnOYSKSsm#>1~Q9~&Pk?j##a;Lf*SlR$*kRuq@2@Xcta_!{@WKn-PP4~40)z$x7pA@XVRa=z%mC#2MMMU%iPKeabuR-(Ozhr z6~_I9{8^FtsJOwwY7sxF(@YRlh4_V2;w#b6tp{`Q@ycgY1*e|CH@y}1>!^*}0zw#4 zF=562OHndBo8K~oD2;n>fVUi(k)@cf)WnNNh8(rTyu>zZ98h3cwWhQcpr0WzpqnHm z>Vu!H%6EHh*x}%CcLsRTx5!8mZhKl<+9aEKb|s~-LOUwd#jL}s8g}FZ5#Z)lx_Q@S$xMoFwkP8_zl>w`>XPoHmt6X8K3W%=Plz2V($uUPI51J zmWfM9AXjpzz+!&NEpA5hjtE50Ea`@rTeoigg@aS#eWCbs4UzyWt^=6h3?;)N=YBBX z{bTKHDItHE>PwSKAFdV zokIo7g=WK$27Cyyt(r{qp@6u!I7q;1T5U~DS!%myb|~1}y8J#q{S+rz8YRXp-`;?35E_P8 zv>EH}yAzQ(!YwV0Bg80?Do^ziz+rJaRGXTw0_sKP#{XD!CA@m|s$v*vzEpV=@D#vI$x=p3YiJx7nz6c z=$__{w3EGIi?me>%!yY)!CJndgTwxOOyt7iqN*?zXmZEU=QiP$JsGOaggxPUxpad!jc5Ay=lCCUzY4dcv5xuC5ww~#%2C|72mIdu|J=v!4)wLR}~TSlVH z4V24F078G0l5YMch~?(wY)B( zFo^!){rg%4#-Y$S4%w5m!HuHBjvN8Q;X6ByguX5@sA{H+SrC0lVOLgGCcZRQ>9#LI z=7t@%*oMqUPnzO(7uT&DX>|A#;BDRb!3&}uv;p5r@x_&u40drAh4fU|`W(Crg;0|K zMI7u6r~010R;8nBZVbkV_q&|za>TePDN~GrRXX1`%BWeIu^>arNKGv(PyqdAbGp8l zo84h`$Zmb?BwZ=9skN2YVeJ@~Uvj-4EwkAhT6ja%b$^W)5^y2E14+0~=VQ0UiOnL} zGod<0e)~q9u4F56V;DSPP5-Gli}6ZO|6KQ02FuHNQfJo&av*0wD&BY`MSy|k&0knp zXi>2%O*l+ld1&l=FM^eYrSjC-m!8^5y;Hm8xQ@s|{9E`UECKV@hojerA^54~wrfWi zbAEx#5>fbXJt(Cf(&FzQOuzHZ9~e+U9&ZjW?Mzgk-0}xuv8}bW8H65PJLiOY0>%0BqUjhOcw@_te z>i!Q;D=Wu1Rt0^l;)VS=owgKYWj!KTlQElh>X~W51N_y!wI?USF$0_dU|qA zMQur16Xf3g^73*$-HECTNBd;|4CVq{pi8`XyxSj)IX#Soo#C9H&gZ~D z(hxJ6>G=6nP7ZZ)d<+S> zzOgas&QMPQh_`JGnV?^AahZ*kvq4vY5F5lCVQp;7%kY}RejIUPWDL;QzllJ+C7-=1 zbSXhF&tkkbOwRNtCK$~c<(I=y->k&~P_7^%q zf30O{o0+-CcKGnYT7&jM-!Vsp6w*q6r0Z{hIUIKB_!CE-u9Y%kVh}|Yko|if>6H|k z+@k(iE}3EMA6;EJo)g+bF5}7MS;-iRtk)x9Lq@Y*Xt_gn@gxS6d+6)%_s4EC3LMtWZy-hp@tn0?R(qdZCxfTXXw^8cJapU$alBzGEPOTGnJ?wb7h8we zb5bs=8uk7fkL(wJi{T>6>2WU(f^$NA2MDomM1)e7Nynpq8Li+sb*6L%+FYIoZz~Fb zIPpL9^u@T{mp&H(lbqI-zoyFV1j)@ z0Dt2xORqe93gXzKz5e|1e-I8v>f_?#{^ZnWfv~T=BPE4z1bb!c@&78DZcc-^cFkK0 z=a4$zvTI0%&IRW!EB-CBg$BCCg%_uaDiReVTYLqcS8YsKjbIY+~YOVIe!DPQ$#1 z+&3mVLBB{!NPvXp-uieqaGHnxnZu?=s%*^6n>&l!fqYy;-Fb&VigAfw;E|9l&&>@b z%WydCV=xqKe0=WU>*nNa^6|w8c-{J%c+P4O@52<5E=EO0&abQ}Oi4hLk=uUdjd_xR z6s9$@D4NSosp5J6$Vf|dwH75Hyd1~Pt(lpgJ5R3yUOm_N=G#1}53A_AVQK(m1%(3R z-nkalguURfuu6yZ3pf2}<3(`otgVY3nOz%EiqP~Qa@!~P`E5g}OiZR-c77yR-w=@2 zwcAUPU%wXHuTuVdv6(|t5de;6fyd$E?oTmsa&lh1+E;Fb3y`p>S-s40^9I~Ve*Rd9 z+%NT`>AIEC!rG;_vyecnhG@Higp|}c=FAd^gq%vubEA*vBJI$S(z*F)ZSCtUg}xOJ zd(61VWsex@q3UuUgPvMiby(PaF|kH_`@*e!0q;V{ak2zOMbW#_o?j<~f2t%R>rL(1 zLg)1FVR`xPxVS8kQn!WTDtPP?;I9s(h^ZX27@J2gx=OF zKZiT5uct@-U(cY0rXwb1jm`J~>itj4cR(@MG3`WruCmypoZMVUYE~Cp#X}Ahs9q41 z{HQ2Xn4<7QimI6PreXbwIND-vLsmmuK%iDqQZhQ4L}K|FKYx2qPr|S8TSec(-a-fm z{^cj5v^^BiTB{=?BlvWEYO1QGB_$fAwiLjSW*T(z4BMjtGY>Y4i`j#?0g-|?GDi2I zHKDBk)lav#wz%z0)yb1cUsxtMZBqh?30(yBe0RAhWFRjxGV7G%v{?+Szt*<4p!%*vy7{)=(e*UrUfP@-D^9sbZEa)uMlMFY9HuJB{;Uef z#fMt&q{>hi(UxcObHHc)V?~wY`0E>Hg@iFFi-PX#V}c5vKo*B71(w|93+||MO3% zRw=mxVns=b(~>PfK2y_k*m+*H3{Ub=Cz+Nd;}vxzy*TzOy0d?m@N5I{u7fnA;tmpLcc4)M?6tbMC5F@e~V*0N@3`h zs_G!}v}B`KIku=EGwJ+b2vWh&>s5n;gJ7jDL0|SNDan)sMxDM`1glR=tG9Vg2edsO zpGIg9cDA;k{UioT?T&o$O|Iguq5ph>rJ(}ldFmEKueq8l5)nY*4dBJOc{U$C1n%PD zUAlNoaTT~g*rh+woad~pq1Ufna}h!s@6>oUn~yY*v75f%$usJd5V{6iu<7BXi0JO zdT&-1qZjX=8+Nc?*1LWo>{f}}Q5KLVN)8SVxck38KL)#cq})jaX{S zz@+t9QRCk}MV`@=uP4!%ejarIA+p85#KdLt^`}x%bMr9>oRcd{j2_f@Zk$Jc5HR@> z5+7fo;GuujC;rVFWtpfKqp9-TSTwmYp~nu*YCoDPmd{O?CKjS21!lwI3>!-5HFl@1 zo`#0>u`yEEjgU?Vvt_`wSf4+aD9=y4>SS8!lBK0(ih`B?6HZS3(NYGWCdM5<)&fXe zV4@6ef`q!bcqK@5*)p+NAVR~vSIhsW6Mj)B<;tl%Dhr)3h4&#QfSLc zNWn@kjtmV2HTix4FE8&?E-v9tw^vqCA@R58rH`;qq5KF5TuRD1FFyY-U*75J zy1G?-{J12hSn|q)>%s*#lioBMHl6>ho0k4Z_+eiyH7i#7nwsQTbWBa7Qd5l#4Elne zQkj=#gofHdZU<2PXuL=`WYcCAXTE-EUC4utS68lZC}n9JwQ_Xh-3|V4mx`{+ z-JMS)Fy^nnQr-Zp0gEq&(?{}yBZuX_ zXp{$q5ZxjAEcBtp%lAklO=#m_W!NtDWQmrgr~9ehP!iKojef?;N=HpCDki45ZW8+a zyH>dj2Zu7?9mqH18-@3PUm#Bkd0!YtiZr!@2*4jaUF8DHq^&$vC9_}uO>nQPuBp*LB_~W3m~a^A z>q{KLHj{~_UGACXvNQJd@;b+Rx@HjMhqMV$Wu{fR8#p&_@>@+QKwRp}cGZX4vo9mB zuF~|*0W|pZ>DRmZ0D^V-s~EQ<(#CdFBa@~t1Vb!9;i2^i^0AqJeQz{6-*#nn^}k-! zcmTtUnnMzLuxfvVhp!O@f<9g1w7s{x%+a5w$jWmpCo6jb-#%=#_J8QTkRLrbJp2Ly zl1^=+V+bII(W_!-!^g#6sThN-Y0nT(=HO5SIVaP>T+RDI$>4(+_lhe!?d|l8W;spQ znL$YpyJNrD^=j_T&K5g7ymHW!$_jB!BgaG7yfERLE)79vx8u#3j~_oq+T-25TLvZRierb^Vf2g5#`zc* z<3QW}iBO3TuueooHfn4? zf};VG7~|X6*hGMoEbQv~TKDnbpz5C!E=#FNeyOgm4lqCis^sLP`{q<4;Fq@On~m-5 z&>Tu^X}a3mMdnJ}d97N%-$r?#x8Kn+K*A<4U7T-(ffTfEa~R1}5gaxa7CD#TM-`Tn zxiBf5K$gm2F;>n>N0%oZtp?l&S|mg^Ja0ej8O}3A!rXJM*Dj1W)7}(MQOVKO6czmz z8miczwd(P4NrIo{J*>`HZUS1TcoLzV=M-hY3=O>YM8HM_-_{qcd( zVzSwA7-Y6&-*ea1)Wj*K-)A*EH84^I88!ei{(k`a2zO{|-{H}bSXzkB#>Pff)px)* zXbm4!au+p|SW+~{IujY$dboDXz>im>U?Zb;=+Knp8i9Ti5BN{5WMps!l;MgN78Ql= zL`FyF>HZ#q3n}@1CrZ-W%d0UR<>Ih5!fm@yl^jb-XEz7)Qxeks2q^~yh)YVIPWi3(2oru2oO0e>(kQ*hX18R!mCi-& znwWqBW$;ZkDKXKJs_TXI%-6xZvz@&?YX^tWu(?(uNEnOyzJrl#4t92!MU8gf>_Hxi zg2gxy8C#o5F@w)^_7}Kfa5DWB>2=k3%__?(OeGQgW%y|M(EH5XvD?B+06!ljg+F$3-aJR5DFi4`OUQ{+NHx(o&K>NW3@;unqig541BgESx)Kc=cd zl#t8zeQ0Q?Gg-zIIA@N)>jbqU7&tf_nnK7jGczTnTD@?|651Y#9SvI~H%s)UmqGb{ zqXq$042U+1@^QJP!px9G!)_BGPj+#0pQMt**s}OE7M@P%mA7$<5ddCW69(t35DGEFGyS!J53E=Xz zwps|RDmOL!H?1;N?@BQb?RR$}pOXBB(Y&6psl}pvHZ>KM5JUEftP+Mr&{+{Lg$Pd~ zF##03ycIxcLX1D)y}59{nrUZnl-^rJhvF-X{y`1qfk->V`4fl<`~Rf~`k#jQ|3lCH zKRpC6xJu&E^@ErzK30>QgNqbxZ_Rb|*H`*eRz=s}_nogB;O!TM;TKBq)gDb9uSxlh zGtIY*db=&CmqlNkz!Ci;$N%XaA%Qt^uc-DIiUnBz{4|N>yuu3vRh?$30IRaJySuxk zrHZ-vzv$}aBD7;08mQd)r+w-wESy|Q&d`TbNBw&nWnXQL-RWn9Z@K>TmC6)$$ zo}dF26}5G;&stMM+j0H;oJQ2~ajMSLy9R!x3(MOL{f-X{^$(VOu=p^N=AdY(#3q)Q zz9FpkDrd>8c2j?UeS5pfWDUiV94Npl<&K`--Yzf@_UGG;P)UwCFR$KUu(X{gTl$pn z!~Go}ubri*|#p<1~$~-kW!g5n{#iP9q3s6NWPYyo?or4LR!3#CIl)>@w+t^BUm@F zwpQq}U&(H!rj)7+f)J<69?#RK?;ITZK}Z8~o~c!Fy3iR6*%jDf%Pyy*U0v3|J3y4e zxmiY?ZfTjVTyFz<@o&Fyi=liNGl+xoLPtkuM+9l5x0qJ}05 zOpxoregsUQUY#5D<5ZwyQ{cex$=`!tA?5C}(2)a30g`XO!y&g;-s5s|awc5}+C3QG zDxexC%x+A^gG^_)blH5oa(-);4&pX|nSz|eT_b7p!(}-^b?Hr0r8~c~P03sMZ|~g2 zUs+hPc+*QsK{M2w7m)9G$W}@0oXyiLF3IJ#(!7SPXA$M#{3$zH9a_6aEgiK7DQS2NXAQFET+_zh1UmvS*0IkAUmub~3 ztwZa)G`%nT!7_fy)RJ@OJ^9#|{N+2b~NS9@jUd04}ShKBX^+JT>ox9W(P#AEsRe18pr zMlc<_lVJKeF-X=Q%2gQG{L6aBF)iH5bbS*S5R=lFGM`iH}gr7 z%MJTGJwUq@B{-BSU-slEK@jAi5UF&~m3*e3)6;S5EOxD=q?qK&=uwF_DrYJz*RRtq zL+V(hJw{Vs&FsIh_tsHW?*F$hwqm1*fQleUgQAGEg|tX_DTsu0r-cZD(uk7EqC=4m zQ3+|J8>Bl#O7hO7zwf!{oH6b=|DAEhxMz?3hkHw|^*o>F9do{>fWw@Wr&+*cr{y#Q z@mkH{H)SW$zTBn%(-?=R6Ho0$F0REr_YL(-`~x&oS7pVu=9ZT7o&TUme}AJAV3um& zB|6YTC(0Hp*GEpUUX{HkKeDvA7%Y~2tBOvFUoI~f@n32_r-Hqc~cKsdJiXI-!eEdpj#3)^0t zzi=Q&{VO_E^K+_^kH(%acK{K?{O5lEAK*s3K;gd@O{;xV@7DuC{%5 zgTs=Q67?hXApdUrAo4&4iyYQsk;Mvc%1;c9iH)$wW54b*8K#-PDDbO9g+T8f!p+Sc zR6>2?1l<-Dxoq$64e5z1{`1TWM(x>{#&ff&cXTRr{JR*PhJv@6+ulnIbs#??|EYSu zL^67Hm-l+&Y;zG0L!ZQWr2l7nIvh1`ULR*EIIN@j9F#s`-i}Ugiy$*uouxv*KalIdOKOHS2%)$Ka8@>J``Yu**5OvMM{4>Om8TRjm;WEM68xJ=9?4u7wx-!q% z(4AqgZ)+Qr8+|m#$@<7@b+H@Gd(+!Jt;woqE?-uV2!|ryYno11Ie~-f-b+u*Cqw$X-^x-Mp(1`m`XYT_rsInEdG@zjhO&-VmYUqh=SS0)Vg0PZ*-V+>}tKS#5 zdZ{MRgHLeALo`iONVBY3L`+<%q2BX|0leGSqk4fKf||D3pNKc((0G2?Va}UgMm!o4 zXWU21YRU~VkQ(CjP1pJAKRG#>kuhH<^!8nkjrg&UcS&j+iq>{cLY8B4F?#jDO@s?` z>Q}3IO&=XiBrcd7F;P$+2{d{D$!<$>`{}E)y`Qngkd|u>3^X=1#k@etW&_=8ZFqis ziLCg+g>mtN)C_`^Vd>A=;(O#1Cm(S7cwf4BaS~HEF4u(Pka1#6Zh6we*Krxt6CHaM zb@lzHy4*&8Y+NSozN5&Y5dG3igJjYBo14@_;NG2JABd>4(>DD3s1E>Yrl97|`ei8-Bk(2|8h+}e zkt_-Sb#P!EIIbBr!}*L;{BPrN-zV$80D+(WPiimzm;J~8@&nE(ZJZ=_y%DrLJWEi$ zV-2WZ9q{@!OtRvHepGyDgp;}`@qo#7{^S4mwaAH^wjhCCe|;!Km9ucZk|^C9ers0u zmPZ&9#}eM+;xnKB46mjK3<8V*;nFTb|Fvt64Qkg!axXv)o$k7R^WUCArn?I65UqWH zxK$8AF~gy87>U!-(Lu1c`gIpg;jglZ#YJ0@dk6OIdwprjqkqbMVWu|?Se}1>8k z<_)SZf7JGgRZzzhC0&xiY|_%wV2&wL>^pEEl+R`yn37z#%`MJ|)7KYy+8HRT$tKovieg09e!vDvQ+wEHI+r~d^ z+qSJ}-FCby_xB*lqoSfnOdZ%>`}&@H&@tZ&y4dgG2h7aO<6<`)9ar!zX`L(^W7$1D z#T!iZ^ysJ3ZRFHKY`~Kw#r{SuGx2dJ`=v{LlkL7aIZvS(V`Lz-b#{XGDDGr!9hMO$ zL>UstOOeKPsJ3$|(cg9rb(#on+Ri`!Z3u9j^Dy}AA1UG5aocvGPWR(L-wB%xIb9lw_`_M9FOVf zz0Pd2P5fd|xo<%Armq)+VVcnS^Qs*exY7p(j_j-A&??Ydp6$C^=H2tj0NxgUa!n1X z)wSQ8j~`Rvu;jAz?-Qd{@>{HN<4i|{9~y{M9Xn4T7Xb7*j6L_|b{pRWUp7TE** zVo{3o9`y90z+mf*1B&I=Qc?veDL%y8`KM`a zvwRe6S(Wx`J1h3=+0!a0m_%W?G&_6Qe)dD(*qK)X8lUd%7t!9zeG%fN1h>r%tdac; z9TwJ?gqbYJvFT(xckW7k_cNAp;DZXCmM&emK*TbJhldkny^^rC#yw$cVZmWx!Q2zU zXOpfi%y98yGNz$^ezN}R*lfi-TU#D@Rk2U*o68u1g8I@ve?uCYG$K0ioBNA#s`d4C z8drNMJWe76xN!$$_c%7zNK-@*&Z%PvJ*E^(#Izl?*>8m+R+OcWt8Z$(3&0AtB#beq zOFZi&*wwZwUb#{OcSZRJh-x@RN%i_YXkt6sMlA!Y&4;TgLsc@36nj6r0Gg6)I*dfVC~LqmjB%EjNmc`f?APt^ITOkn&s9J?BA)b?RIQSt5IW%m~^?t(KU zl0ZAukGr+3Ov}#N8gm<4Thn;rLncRkx}E!rVxj^@;gXV7Obrol-pDN{--7v}Gz81s z6TnsW8A6SOYwJbbJ(ZT;UW1WaniWj|T(+dDT}qX`ADP<87Etl##X5fBjI=3anB*GRY_MJj$wxrkOCu6fSTitUmv!>UD_wg!&+rmCv^NqvTr zdj^{`_v#7Vmpjb4(;Zcl-{oJvFbpYg;8siQQJWsIvn4VStnBP~E?fwR!YHI295FG1 z@>X*(vHLnYQ5hqHdg7aM{@m4OMv2C3ACpE$anLf{;;brP=AU(PT9pc&%hc;Ht9&&c|DLZw58C&>W===AK z!!@1#pwkb_tNVWa<52xKSw&R+92vo3=4!(yD7fDCaX{kFWN%R~JbO4o@E+g51-h4% zv@$|lZUPejG;Nu{WG(EXASHw5GoB}EZg%$KrAu7f?Z;q5sr>#uyTny3%j6ei$C4LW z*7POu&;d3J_B}gBspCbE))c$?t~}@yBD{9)`&Rn=`E%%sbs$enf8M9mmd+RY^@EOF zL$CG|winB*t;YrIefy##jD7OIR8-KijK6VYzhZB%mub`z8+(>(s=wcQS|k3&3yyg{ zz7D|ce2@Lzp=eqsZBZf3m20xJu?hB&DsPx;h#1N(rxk4~*?|on}S9(Zr7_ zQ=$ft^Y4MBO~|b0F{ION&}K5zNJ=I>eL6vQln{%Kup=g>Bz+`JIc)=Y+KHBCf@s1| z@z?D*ROxj^+=^0Ri`?8;jl?5N?lD{{k8*QG4C^%|e#j-d0NRPBpb(Bn!%!Zx4V=xX zEvdLp(W&gu>;f65lHgXG6W1{GX~>bPOVP*$-3~7g{$j zpe#9ZR;s#=b2q6`RF6ZF(^9IZr)Q*_5HCBsbmbfXUqyzpCxbAPWjScmQC5~{H&Z*F z0kfF^wk@QQw44?&^?x4Ec>DJE&##65?wSx;HMKm;G@uhoN=wC)xiym2v(P#MS;%A9 zpyIMp%Rh6;q-`|X;~C4)85`w_wsE_~9zO9Ru8m5U`cyV($c%FgfV8XzV1&!Kr4DDX zU;2l^o^KZ5Cc;3sUzP67L;;sV-gT?O{;BjwA`NNpgvavCMLvFL*m(u)D*W@r zO=L$78DJDbmV;O`c{TaK`>~=!UpPOXff8f^uluzSx$B?e|EjvlEsJ*QkZjk%Cq`Y{ zAdkE9Z`L38SJFU2^5)9F{m1>STaFXIc+{T1A4>A@>>;A&;s1Xha7};f?B~4(6errK z{LI+}`IAa0li3oN`SMYz;8f(oGlMQG{C6Z4H+1~VPpE?$K713W>k&ktY6QyU=O0toxD%B_%uOm1=-rV0C&cBpt z+Wk&E;Mp@Fl+T-MRxv}wt?Ub7M`_Ci2=mgkbR6+dB!+s;| zKeGV4iKYZiA1c@Jbh+ZL?3pVP5^wVJJ0ET-)X=ad$TCY}Q?fcgW`)WJ^#qoj=^4o^ zQ?S@kUotsx;Iodg@fpFS@DQ;UXiYDSX&6P%6#RbE5xwuUuyB!Sw;F~zvXW6098Xc; zz!h+{r8D2o&djVXMcoc8f*W2Rfe)JK$b4dwpKQIpB8}yUoDgnyTdb2&@>Ld*x(s)b z9kWF{Br6whd4Ws~WBlvA-^W(Z}(vv;yH zDr&QPC!AX@sKt$%#O&lRs*ZpBUUpOq4zFgcn*Qsp`qoN9am;xty-3pLElY5HMeBsZ zlHW1r%~J*TsRC6{q=)fSsNKGOx)C;tBS(&KYI)zD=asfhOG<(bXgrK}?*o%W!MSoV zPq%-op3@if^oPpB{4v;^lrM5UdEEo539DhY*~LZQc~%*8qWwR0cr5zm@$zUDIzG`e zaT%#V86NU{b@cuFp(0q5gI~wdT*)~~4^;c*ow_mLZcd3X`BUEer-1%RpausPVZZL{^VW5nNM|1&xDK-BxV#;4e#NhZn%ckax6(A@@~KHDE#biqT~ z?rebE%X$8KFDl#ws3bJ|EIem^Uj!x_12>?@9DW~5qS$BFne`hsUb6C`auFk=HyM)E z90dw;a_QcUh<8|wdG%@pKkI(Z((l?K*@|khx57D`mM7bP|J#I$1f`L@*hWz+(O(!5 zkVM;x(k&#yO}fnmtqW< zU13zO7zk312sqHZuygw|9<*v_V`RiTpiPA==Dml|!brnMu zqp2Pj^QL&(EnD*JuJ+`>6d4dfY+)qDbx}D-!)HF858KEbu<+#FHl^)kMFcLkd}X87 zbargQsn6ee-W1=w1Hk-y`U`gFRgJ2~hyR}Y53D7(EYFtyY+ZRNQ3pr+gP@OovUt0s zynQaDf2#bHyqz8?2asZ2=H-=$0nzpg@CStT20}dMSmf*L0dPn*e{y!u&d$DZ$42d# zY-8Hj|8DgZq;mYIf{cV8w%UYPwIn6!;x!>5p=Si*=E;ddGO+-~-`6KN9K^@Q@@|A9 zP=h@;m)FSuC>Xl_6Z3z!PJV20S&a1b5?M`CKE>a02N{hzPqxV#by!~JjEbhNbCHpNG8PR19FVC5BXxbmg{O3LIRn#dv#Mp_LuJ+q^y z%%!Bl1h@-~U0t<|NP>AZG;j3W4<&Mrsy{g`xn3s;mIj7PJ`SStzvW#{H|%P0_w*Ic zU*NgGEiEO}O=G*5Bzt7>Sp>&sKbbXQku~=gSC9g~w3IivYVaz-zaBk$CO))%^BH5P ze0tYrk@D=OSh_#G?dXqspbHb(|A#HrnZwhbjHmp36Bh5PR5mq9txH6FGI)Z6wr^&J zRZ-etq^MXAtA(c*GfUJ|Zr#eVzOSnrEfi$Vbdd6Oe!g+QSszjxE$iNU1{1Y(!ADtk zXl05RMK=T;b;b1k7yQ#O>`%8}P+lxM^U9kk-5yw)zGD@?xz1JO4QYsIX_@ww5=zfO zfZSL!HIpx+m|~=RKV-$Z?}6V*h9uVX>w3pUKC_Dtv#h07oKhlc^o9fzRU3O}{iSBQ zoo+9_eG^QWuHpVdydJ0H)k(k5u?>6i(Nd~#wLjWxP*s$?y>_b8uCrY+NmbsCG4Tzz z@pf4MiXukG5?1?Z#P#L2U#dQFAIBhMS;{U6Pk*c~-i2MrC39Ouya;46KQb>A&G? z2^7)~z<91%kgc$^w6w~VDV;9!l<8>956RSYn`d!c?4p7aPS=SKyPsJ}v(g{fYS>AI z!*RC?G>wTGxZ18r*i&Ahpk+|45C;84)~uB6ynSn`3*;3>VoCCGEeJ3e@AhVp2SAaZ zDPGG^Q(PG15YwK53Y<6T@Od{h2(OxWIhwJkY9t04{ZX#(p88Wxkn|(#!Nb{Z!})o# zNWG#^QdwEq&?sC=n&I-5Z~f_8liPj6!r+%i7|hv(aEZ#Gg1rB3fhESgE8%_RX{-?= z-@G}y&9@1Y^j>j&#j-yOt-|ry1O8tn(-lRNB2I8jHPEpJT}{<45@}(2A<5`3wwJ=P zO3VEOg|Ght9yIzE?P2?=v%0M_)U&7I5aP&(eM1lxjsKdyM^h3bzusL5iNyIcPFEJ6 zgoGIM5%d&Lh~Sk7?mk6HY4h_7ZLuU-5NwVt{Mz;1cUJPY&v9{t5%pCMJ5#@r>(DS} zTPbq}xeccq{D|D)qFUnwhZ>niXNF<)=fUY|J_suSB;!y`mrK`1d8VG3SK;G_X4MhP zN1S%V2nZMq^sAKE)ni!|E}0zH+YQW4c8D{Rz7#C%pIw|1l`|l1)9ooJ5?Z(R%FR`c z6cWT_{(Y^0xlS)W5g3y*oSZVG-(Z0Zh+$7Kn{4y*cS0ZvwWkBD1zfiX&M*Nnz6CHu zcxYqH8G!KkAN-6H@u5&TFut^Yi`GRw}0Kv#hM@TyN!=F^vljR@^_*j*(}k+a>^V zyY%$*j%{vLHw+{vFB(;*%Q$-N1-+n%n`Y|d6;CUP9pWaz+wbSR57K2%CzOgZOx<*R z7W8IR@eaAy25X2Ob(KT^M}-Le4KfdU(e3+qS~z4qomBp;PT%o7aNvMDC;81GdIo~M zeGWLZM1{~d+8bM^zCVdnG1oD^@hx*+&UD#CU$(Th-bJs9BgME$(NvYtm}W|^6wHtn z^14RCL}7j@khp7G2iAii=A5F|9J8z@apH>K6|LH!;2cuSW{e44^o${wV%{EjpApVH zbblewnE1_ds#r9(d`>$lU>|c&+HKda&-%L#ZvC$v-2I7*3dJGxfBV{uXA|fC{^5UT z2Yf9TG78&UYHDh?ZfX5hC-2|!<)n^@36KMD>0vsoudAE-_t!`km zg!v=<&h70Yx!th%)`tH6{+-6{UDuYrzCH-{T!DZ3dn0@ax8vMq4(-#^9^8{v*4M6m zix70e+I$`~Cnj=Y8ilB+$Chn7S%@z&Nnk&`SHPH{2!cW-l~cZvMKSR>werslBPS<* zVPWA=-%S|9iL3@gLqiC*aU0>=@wshizCBxwDwvUpooA2^vfj@%* zgcLe9HWNfxg>Z`Q+_{su99e#iq!EmWx}vW;h4$oHwPG+?_KF4~>@^%VYrv<89bRqw zco)Mq=t+X7#xWjz_3Bmi2g@N+j5(K=pMuKoO|!Xa`I&wbSP96@WlxPnC_>E(#q9OsDC_MuM z<)nM4)tH6Dz+A^98_Hy^3!gZ&yyN8=Z@WtO_mjc5+udcl8TwaPBVnD?N_3yr)Z|-S z_rtJPo{)a$?%kAmyfBd2MWUD``@?5FieI*}F;0ec;<-Xj8(%!&!J=_TokUIuvZLIr~)0 ze*XNq3}TW*wwDm+gWk_I$d?&-C44sNoHY~g9|Zj@Ot#B|(F~v ze4$sad$TZsGKpNF#fN$a#z17o6D|8Ma^=xJQles5x_RS9UVeT{ih5OB8$DgW*F|Wh zV`5`jS0W#Ug%x;vORZbO0&JJKgp?wUv2G@Jc z(~5&a%UA9^31ni>lHkrnV^Lq<8e`h>LHCSdNDll|q3ty_Dfo(VMzD4IyS_Zpu5V^0 zY(08AG&s-L(sB-iPI~dgq=1a%V|OLhOZ$pN!@@Q9y^x%Q%237c{I2cW(UEJ_D{DiZ z56T^z$iP|YH)0-h{uxzNotYD-brq)u5dj7&dhkznnZiOBudqb+cKhM#NbvKTqONXp zQ0u>xXa%RYcnjST44Sb!_sq+~e%)reOLg(#ySnW0FM2+63Y}V4+8rT+2LXKLRmf%9y7#+?yC;_M*ck6D}%6p zG}-RC`|MG)C9nxid;VBd*0r8o_gg7&q|5NVOW6<+6lDBBlbeoi6*EjI@OpX<96lUk zWjR@0BTcxGOgv|E)J?fb;1hw?k=!*=;i&>Q!%}4l5}qPozmC5oAr|m7L92>IU_tL& zSJ&E5h<5M|$Cdf^ll-ybd@lW-j9y*be6UtlR~P)Smm=I!cP=EPyesb~bo;CM#|5gO zmD{>)8~!CsL%Zexy;o)dn=xBKl$2yP!{V947f+v_9j!lu`|Q^&lMVG|d+;}xH%TrM zZv^dUuKWM?7rmPOe`-Cn1?Qto?ii-q1 z26D(00F22s#kp1euLgSho%;SSD;F0wO&=2!yqa9W=c*@28YnAgk2fdb$sA&D zlsZ^^j9snr3@vTn?>ga-$~ecCkMyKAJ7r{E;rX!tx2ULgK#$jwd*>~+UxzcYXH|z*5*v=8-H?j-Tv$DKBJ%7(7{;O49m@b@E zK@9?wZS%a|yKC7GIi%QwzhUI1EyMt1?Ar70LEDX@eA%EF-9_PbO_YQ7%0m+c>LTITMT~o zR<_;zh_0ffWI}FP6Mcps2ul+Ncka;b=q|@>vcx|as(^&rv7sSFjIFSXLvA1adM%`? zZRfi^yD)kZwwn&yC%!W{Fz~W|W#Ck2Hfv5waxxpk5QNJ(cpUb8fg>n>3i$|_w~{?s zXuJe%+ke~7ea95_tjJG<0Bzul``<#Dkbo^X*62=T&9Jrc8a3Syy*eI7OG_KT=ti3$ z6LH`qpTasz6v9xSxx0hbpPyE^_~s}t#6`NE&oQ~j0?r6pNd<`)X_7`+02(O?LIuoi ztW*~%tooIBE&7Zr?!ktl-&9Z5?!T zybLb%)s=}fyb#S<58n279;cw-Y=o@v4|W3>pwrI+^yutQiAx%h828lG^8t%8fxfc7 z)fcNpL-B=~B2IPX)2q^4S?`keIaTVkfHhz@t>Mst6NSv~KxIWs)*E!yiHhu07vocI zVHQ|<-8FS^x4Z5=hoU!^_OBRReG7coU&_if$9srB$+U66DNJ)SKcb?f6c1zVVrs6f zuHMI*^sZHAcxb(7uQmgdgzCaQVxvGS+fTnc0P!At}VZ$HXvOp2cP2@}Fb) z+=s(!N!!jT_$#k2OepvJg#Rsxhi=5?9Ta28#nt|Ij7y{>|NVW9pN=nKKvv>bh zxBoqIp~*&9aMH<1{qqLtmm>Mk5tgll*w|<8nhK@?FoQ$89>~weGLB=azO<9|BYS=Q zc?Me)a*m*XZzahIO`lG?YiwLR7V@Q#uE+%#L?)71POCq2L6CQi`S1t@en(j1E3drR zEHF$lFgk`?E#?y`C;2H?2c(-yZ-WfiS2CY|KZ zQk?#PMgVzZ<^TvE zkfEur0$66?ruHKc^i|s2VPmQ2CBRHcJXhrzF@-mS>j<;s&UF3nAR`+$lb++o@KWjx z*N`Yktg4@eBLu10+Si6d|}vPQG#L*0rI7ccr8>%*|hi1Etdb z8@FL_SQwpPlG`}~AD`XyJ8t7k@Y45BO&LCT;4-aY-nT(MbknaH9;h%NozdChsgh|s z67kXJrtRAuv$B z?(T4P94^o4(4AbUM00A=b?dt?jpA|ye%)OxT{g%WteniC_WyA^^t)JnTHkt zb#sMBMn?LYyMRmsRRp9be)=!i^rM7@9bB(o-9SE61r=e}o@Z!{d_!9#gos}b8`7?g^raX1Z z)$q?8H^x!^>;wH|^x;|1He&ODvPz#75IC>NBkf)=+_^XxVDSl-BC8A*j~r86^qwtV z(`voeke&1Dox_?bA<_MCUCZ3&lMst_7$ibfpa5#mu)f+$D_lB(ealpB&4|m1c zv#cxccS29N@#FdvJ#rM+#96NJ@=s}4I9z(Fs;l4dTG;{$hQB#|Ca@NYFuk~nb4tl7 zJoe_o?crU$ z24L9I`go`2>l0A|8B=aN?CxY9Z0t$cBbM(2Q;W#B+*2P<@;_KS@j|szu5GKBg4R{-p8n z-wcmkm-{HtA92aX0MHyaYBs@ewF#lxWoLPnEMsqcg(jz>8lE#h%9wA=A{|&tQmCE- z+Q4xei+H)^!_$0xmlzlnNvpUvJWf&Fe_aEli$ol%^wi2=3e=^{+OEU= zNwVZYW2}3}r@jVL@p|A_$4~hRp3$GhPX;+=Zib+eGtMP#cVdP-OO#e2G3mv>iGByj z$Ok2MI`z5#BJ+L$h>g1Ru%AcF)rzM8`9BNUH_{b+b?fWE=gsr1^fZ;lKR&%la`zBj z03zt9i<0*%naeigCJ+m%sXfbxCv?vR9A{Ro{gJW}XxM!&=7ZsD(YXh|NKPEOE$_1w z9Zi7~Djvt-{ZV(o5Evd&mub8q%O;pSD`dQ?eC?iJr?i8EV#vi+jG(y<$rO+w{q2b| zQnkc`gB=m!Cw22?@X@Eu*|z!d zCS;d=AL&Z!zmp*U4J&(-DEbgQRDairc~>6aL$b#I*MK~f3IFKY+ScOm06f-#<(d1v zN%4`C)Y`79x~?vSm&V1~+fkb}fed+0S>C421kwPn{*{Hd3p_Kpt+Kw~>`!9#ft_?L7j}TemE%tP+%J z?k$Y(M=#N!(qB!!9ve@(U!~sQC*UrX*B6QG_amoV#S583#@jy1FD_o?EcrP23b`@{Svq{y#e;>2-MK>##?^#?yR z8!E4-3$z_7zJBe&U1szFnmY+*^3w8hrclv4Z2%leOnjJ?bMM4qLVtbSj4z0NYzgaj z2?5r-Iv7`@|BrdbOkRa2Sa6G*VG^q}5eaymxC9SXB2DDwWpF#`M_&zv1kxkoUY3AN zl-TcnH|`OZf@0na!W_DoJ|7!L*G|OdmI{o`?duj&By6{zH4Gm|? zMiO%#qK4{jShL4!FHks)GYT9k zp2F8k3`t39nG(N1pVlrL_wpqh!afbcVp#(aNV|usl%Y&y9%>O=Xf|JspJUp5s3@0G zQ(f&ZsNJzoj**9pE7;!bzMsVBNuxb=?>e*9WX5XU;o$6{ziY(tg z_=qezdlJ9n?JYZ}l@%Ut`N;v2DWB!w4QJ=ag@u|^9a}g!f^tjeU9MJk<6QwI6AU%1 z=uF!WQ;|%|Z`b+hDnjxXUhq^t>R+R9E=7&g%f8q2*ImuLdUuFr%*{faf}>w?O*EG|6URHan|h9f`Xd4n_vwR z<2rI_!T<$vrDXBKyjI*V7zjl+gdY>HEOTXGQ8CVTS!|~O=iz==j%vQ`N$lGu;5|>L zXfJYegEMn3?V{VpH{p%f@&)Tqv0(wCupxa`W@81;3|6NIx4sY27($LBS&J$H<04{8 zB_L~x#8;$?9OPCcxO|RD#&pzlb3+iWLU3_8#Guze?i*>fBl6B zmqpbDLQKpc9AKhe#o%wN=a?fx>g-wDiIy|GyhCu*LA`75m#R06*ly~Gmz2ND(Q4^m zW2r`P0U}a`GfdiJWg<7Mh68U$pX8gTt>_t_j}cFE`CXGeK96sstPPjpnMSioOHpPiW|e+%!9%LsfLZmL;x+WbHE(`KK5f6j5EK@)vJ)BbOui+KAtJG zE!Qe!esR8WK(b4&87tsO7u!28j-|wST=zIYL9>Xd(IA7WO`4VqDJN*%eC=!ZYSb#f z!~~Fe@ZBw|R{i8EZxC^=FBf%QRlMGW(Aw+(#y*CeTqcHo>%8`}=MtK$YK0x=Uq5z| zuK9v+MyQ{rlcY#Yu@Zna5&4orkdZ{7=L7UfvYsLngpg*~pAa(3W!iNH*`h;8Xf-i0 ziIFhT*I#IomqEoXDw2l{qO`d9c>y1N%7;hh203ezO<2fd#R(q6sFmJ(ahgn#vSoy^(_lIT8KVDWti;EZ>#qO@KA zC_>0g_)W~wh9R;Hnt=Pp#;XVk+qGkd4YZ3pXNHG^-@avh^5@rgL!|2xvv$d{6&%IH zp3?}sKF-cwst&zC#bbKWqTeb#m9E%zI+p^?2!IqT4U(L$Yrou@_i>(IfJ+RaOdcns zVO!v1VX~P)$&U4H5n~13NJdE~KV3{zh=Ee@ib7r4)-iE=z|0h6OC(A#G^`?w+Y1(S_CWxIb=%=Rqx>XxMnx zE44{rrO$(gqpNee+bL#Jz-f_9Tbss#>d+w_WAz$n%y*i-CWchqhlEoqjL#;ogk3Ys z#63n^JeuoOHFJ{s$2-liJyJQsN_}w89*3z+@d!uhHy0DowP!$OoWIX-vQ4yUhkmni z>J3neLM|%=J?%tm60cR5C)L@eBD~lZU{>%;%}noG&vI1_Dw0W~s!y#mh@&ks0VVR@E%yBNUtHc-lJ zD7X~s*TDItTardWPgV7v!Nl#dS(wU^2ZuGYM1D>Vd~#_3J3>%r3IXTf_PrGF5HSEaF!1wIsg98EMV!^cbakm{e2a)MuzH+n6@H8Fhu*7QYS$N zoE43nT}O@tU}G+TeT!xJ6@Q13+Hedro3?nL;FSv(J-{Gl(e^>iFPcisRS8+GRn*NTw-(q0KDmnoeS^YW)t`p64s=>GUEO1+PSI}3!4U!J zVmFM?AMY~8B(scNg#5-ohKf^hc(~!UV!tCIxs%Jr0D>c&kmzji_P%IrxExoARR$UV z3pR`lBc(&<6fqRVZoM}}y$rO020|6_ zKeCUzp6(f7a5$!Yn@;=JP3T^5X4>#UzH|OpULWCGrhGyglB*lra_(!Gb*tGOvqsEn z)4lMpFk+a@nlcr+W?#m$Ky}2ZVPF$yd+M02E_PM=j@f>k<*h5NPy#<#_LRRetN@wTW9jg+MMHujw>_9Ii?0rwR?K*AP_Bcu zNGmADtrg3uRR9+m_3`7ko!k5${S6}$?*RHs&~g4gf`-VuZ06o`IWPb0pTZ+i_V3e+ zoX8C6>;&t19Snog@86m8@)b*6HrEg0h6>Izc(QXpMjHSrv1k&bX)qZmn$QHk4blNt zE!V*6EaTQ`U*AI&L}^i7MFn>Oe&R9V%`jG8dH-1?W-1JB)d|we#W9{K^5WjgBgn$q zL1%zKY7Aj%FKX`woiJX2`yem3uwaQ#jEmBdqF7Pxg?( zhnf^<)+}UYoa@RO|5UdzF*(_gq)bEkNUFt_X-bs>yWn zH0>w-s+Qn&!ID9Af0urwjZ~ zwAIKhP`B*@W6DLj_6;MI4xqv{| zU)j-+JkY2~^wvR(nKuc9ng)M8O8543ZMZB|8)}C-Q&0azr*D71KSq7^@g-$t z&CSh*G>5M3rhR(o+MB?Yy+4CkTU~#Z%H36VTh?_kG)#CofF#$66uR2TSA~w;niu6c zG$lY{h`&D_CP-~H-b8uwd*?g-#>TXhm(5Gwoo;1sMOKHgkx|CMzh84Vt+a&T4s(5d zeW=b+<@fjBvABM}XKN0Fm3oFrXO`augC1kqLyIc^egsqQ@jnM)Q2i{xw^c(Eyu#x(eY+$YWTuHLQ+!aXP4Fl`4N;cJNJ#AdHQTzpXFHtoFY!W0a;sBeJIs(1Do_Za%K`1-o9C z-dwBixa2909V^zKA3gkBo<9Ya0w~&JVq#X7?WMymm-Y4@dw(b_0C2K z3eh2mFE>38_5B)%Gcq=YI@^2g4E64Yk9V6k)k#Hh*4%mrZhE2~(cTsQc@g;;`Z!lTri%ipz;OSSg} zc69rN;mm3=RUJGg2Q%~;&Ac11_Z$!UWHk~|Q1Ezk^Z=Ogf%}2Y??XA8q>zXVW9+Il z7e4|?4=wS|?c1e7xoW$+YpnC%_TD7DKlENyrpswYuU!zga&3g*t2@|uHWe3Z7ByQt zn%unEA|w3ZrVHJ{@@OnhPvgqOrPO6UZn)*yw7c49Q^K|bF_Pf4!*M{%A8Ft3hZZb7 zoh$mV8mrRUaZ1Wu^S-SI4`#zbI##mH{Rlv#D+!Y^pZ zxIN*MNqeHNZxG`a~gqXAnRDJfj$4!Kwblhn8@s5xEMOOqrg%iSRuiP9Sp-5K!-573nAXM1x zmZ|A9bOb+X&kpzh8ZbaZdfsIP&Bn}k4U!YluDE*LjSRc_q!PrBOqse;Gb<=7zmKaR z3m0~yy?AjHrEV#6OwL!OMrMk1ul7)p7ZK0BjNm7%d;IS_vb+%giiCre)k82v`t9!5 z9J-ZHw8*IT|45K`dOf3|p>gxo=Of>)$17S~I`C}Y*g^I4$uA-zBKTyl?)|#0WM{JN z-eUq=`B_e&2@<|ny}P6_`a1vpn5L#A!~(LAPd>k7YioO!3rGR8-Mr5;z%nQ)DKXT3 zZ0lZ1{&+htT#fMCK8L=N%XX6K__?8^*C2Vz%0BSha{u_zMnH_~>KIRd zp~;e_R8P~gyYk$2;+W56+Gd@DCDtT2s5q_~U)}MQWpru^Dk$SoampCGnTXWX6rBtE zNatiE^4OZxX*8)W+|x@^;y9-*Dr(0iOG`>_#FCVlc=*E6oMhW4B0p{l8?IB`%u3U& zdVKk*2i|OPGiGMP55J8?cesbXdBf6ltiB3mkcXzi{fllYD)F9`lg&x|T&M5Gr#_?8 z^a;i?PVm-(`mx3>_iunRA{jzQ>Vq0K;{+80-75eRq zzO>tZETwi%4`=&bMdB1xAWxqm9p-Hq^A9ubaLcdOU2!rpP*g?;=Cf2B{;z}k+=A-X z{j6a=J~a@LKUMqEb|qlnsV=k-b&ZXZjt|?usA$LUFpmfc@gO@SA;-wl=F6%5d8NmR z=6VAHee#`_YCqhB9?p68>qx`(2M_iu#GgA@s^R$rqlPKTbGMD-AUvnLI4)K{$n^Zv zr%!=7hcX)KDlSrEZ9oA8Q=Bb7wH|5ua+OdDjP8sB5R*gtbbzz?P1VDT@f?#RCFP_Y8ym z`?B&wALy}pc=1%9KFwlLsB~mpy0%|;`!l~2ESif){=L}cK5;@@i9X)jRHsgj^RVmw zDPi7zPQf>w_Lx-Qhw?s>mm(rXGyXf8V~&t3)GYscf7(N58o8@y`uFYK`{<2Yj=9hV zckq^=O42-$Q^iqnITYmURBjd)es?Sbzg$#SiO<&#$#-HcJ^U^eLbm8Axf|Qs@|S?< z9_z|IsC!HY2J*53UOv7nd!vKRPhXrcD@_w=OgS{PphJ>0kgVExczm#;QQNI>^3TYo z$%ox%FT~&K(Aj@o>RM@Z;caDF+OMyNzg&Fwvf^Y1x#L_{?%od`*BO))6~FCfQ;ZJ{ zY9~m3fBqa|9_P>RuJoq4^g+f+T4Pkd;U z_`ZjzELIz3-VW`uq%DK*K%Z&Z`-SA8H|stb0|J(Vmy;iht<3ff9BSy;L(Ax^XJO%a z`Q}roE-&r-(ATF6W4f;cF%Jk~O@`w44q!=GekzbWu_jWy=0CFlk+TMeq|ZMY+M85< zTq?Yb<-j6w-+YqoPgXukXT9mcSxRdtii^Z9LU zFK-2H(*65+&3_)+N}5T^&C2*=7KihrFIw5ApRDUmRUiC#JW}`lo#oSegr%$p{M-p1 zv?J+u(eI!LdT~rU(@68`)o6gTLpbWeTIldQZen+#v)p-K)*HE0FVf7Qw%%SEZnyC! z-mCu#ylPzT`ML4VB%XaWO@ACcSl~&0NrU98}k?S}1jNu^7N0 zh@-aj=(cuA zLnWSfed~VyymBK`uR^&zA|PPEn^Ion$yoR5ONi8f$a=i7=fDB3KC8JwVpP~Q=E2I+CgCT{N9wd&>N<#)#8nr=(l?w!V$nV3k9kXj0!Bl{Lp*7ottLNT4> zk9WB0uB8MNNB3R7)?~H+*pMC`*pk7{7L#oiI4_N}ld~dGIBeOr@`bwNfCY4ZhhKt% zR8v{0TCnWW{vPGy)(K-Vv7aa(_PjVB1Nzt9%rocPh=+0LaTD$-OX!#f!tI2<(TG@E z@A`jV`-;K`)O%kKBqkXjbx6j~9sS$k)Pw)0wzrI`GV0oe0qO2em5@e2L8L*EMp_!A zyQI4tl@e51kVd*o0SW1l5Rj0N25C4GeV%uGV|?d~asHftTiI;(zW2JYJ zvASVgW`?a1j)WOY|A5Y;;4uOAxI@QB15>M-BHRZ!9DEH?H#XG_i5@AeyN^6-neDf~ z#mh5kC0oZA^{3dzcH?A$CkTR*P*F~>{%u*|9(*efx)%DOl@+}7Ci3|PhC8kXK{sV} zZc(TSrD9LMk?;M{S4kOo($izupW=R{O@7B+IC5|`*G{IgbF`FOP2XoWb`61OU6b7E zs8hYAU8eBP@~gDm{~kX#V{8zcBN7sbg#-ld)eFCl*CBo8kMZ}$FAslIjW8z#DiLIc z9Boxi%{-3*iHiahUw;0op02NdS8ul~WG#NG)_~AZYhTukeKXUFyc2Xo37P#5m6dP? z5*}I1d<4PK@83o0tU5E5|F#sKIFPLiB5DNh?WI2Bca4qxqo{~;LHx}&_)EI@FayWt zGq{B;Ji-17a673W@!Na75AKI{_WX%~@||7qB(gRDI*WU0(#JV#{vYpim7=>@kddLC zzXfxaO#^@6MQjT*L@JB$F6bja;M3YB__#f<%%qDoI=tWe1wGWpm%ORB%ax zVmksA@^do*ZFJ1GD6+W^MAQ%IqI7I=;6Mn{Uj{pR=<^koS{(bu?H(H*bFj0!x~N6{ zNUD|!yWSvkp0v&Pw6%>74OM4kY$J38UaO1Ax8SBJ63A-4XLEeg9wNZS6$g1+ zVId){yMXS2FT*0VL|9l+4KHG7g*}7$=E0}rxclWIYhr=ll?Vhtg@H@b?=B$7K^mSJ z>_UKORh6s!vh9jBfURP4byWaD;~0yNk3WMu%hEE5)MGbtp%=G*O0`0r52832L(!g+ zwt?&T0xu^gkYj{_DFWN2QYzoKp&?*~(t+VQ9W}KDcLxh4b~R{EKr*QMAsS5FR0)fr zsjRYw!0P{YX7n->SvG9sMWj->UmY5&ssIz>h4vDJd9PAENhs0;9HXP6qS&+3bP7Ad zl#Wk5<0yCubH(CQQlj9Z!xD%MM{hXW!pKKHehAKe&~()~^ISJsd;3@}Sx=puR{8{= zR}~a^?*2SV_w{`5B4q=ojMR5%7r>Ixw5**Ur6w{?379Y7?%)@Nr`3~A&y^kL-G5y+u%i~K2bHRBtK?Ly3pr9b==|o%_eAO@^VvYQPi($iy zm-+Ya%#I9~c(}WRB+~@aW}yP*)mZ4>j3CNmQlvf`l;j1IB)65m6BI1kfLCF$U&i+K zB7wj>kjj7Y#++15O-;X^*uJQp5u~7Xbti&?9s->$2-^IUO7eX8mSzb_N!B783jg*6 zr=ZqBERB+tCekTm#JBI>;dtDG2xCCn;B;v}V4h_N=!~X7+_=f^TQ=MFgJl-1ka2iG za485!WJ-!aW;ISHHq8_rr^7ZhJAkw{Cxi*LRqKoc*N|-b00TFZ{J2=Ckr(tmxjg|=XI&{_i^!-X9&+ZdO{*YLMrO( zG0l{yuMvhRs=I`=&;Wq#3v!o;kLS<1%1Ue~E-WU(!P(+ z+YzSau8h#z^!7>$9{$n5GL(4--o${m=sp0QZ)-kF9D`xPb?-v`+|<;5G9FOa7cm1< z__UZQjIV`vQwSh1}AkBq&BkRDds~)0|VS+$C6fRNvW} zy@QB37Ay{WV`&<)v!=jL0HQ_IF#-j^P7k-kJ~0$x2DB4wX$}fez^LLnwnIRnyI5=DL zTaA{%tRv-RQq-#?Cxrfy!U-C;S^l5(ux0D+?_v98eboxhWF}*Gzsu#rzUX+5e{9zl|;P$_}~wl54;z3 zT`v+;(GET#DZ%+Y00&HiCqIDa>FTU$a0$sb7+z&$ASAGewjjJlf7(g)o0*9+oR3OY zuGiMKxNd{w`jd7mAa-z{%gV8(E*}MO&>CO23Zws81&Iapm^ChTb`aYU34lv4WHR?p zlw6$JQg!nl9wlz90|k)Nwv2$lXa|Fg8iW$7;0)h6jERNyx~&ZYntYwH1^q-ce0%SU zh&WDHzv~PP3kw6~#Vy8DK3&H4J^(Q=qbnVun@bQ$fyg&=rCOqrc8PdVnh`OHkrpUx?SUHszawR_] +// Default output: dist/server/terminal-worker/ + +import { cp, mkdir, rm } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +import { build } from "esbuild"; + +const packageRoot = fileURLToPath(new URL("..", import.meta.url)); + +export const TERMINAL_WORKER_BUNDLE_NAME = "terminal-worker.mjs"; + +export async function buildTerminalWorkerBundle({ outDir }) { + await rm(outDir, { recursive: true, force: true }); + await mkdir(outDir, { recursive: true }); + await build({ + entryPoints: [path.join(packageRoot, "src/terminal/terminal-worker-process.ts")], + bundle: true, + format: "esm", + platform: "node", + target: "node20", + // Loaded from the copy's own node_modules/ at run time. + external: ["node-pty"], + // Bundled CommonJS dependencies call require() for Node built-ins. + banner: { + js: 'import { createRequire as __terminalWorkerCreateRequire } from "node:module"; const require = __terminalWorkerCreateRequire(import.meta.url);', + }, + outfile: path.join(outDir, TERMINAL_WORKER_BUNDLE_NAME), + logLevel: "warning", + }); + // terminal.ts resolves the zsh integration relative to its own module, which is the bundle. + await cp( + path.join(packageRoot, "src/terminal/shell-integration"), + path.join(outDir, "shell-integration"), + { recursive: true }, + ); +} + +function readOutDir(argv) { + const index = argv.indexOf("--outdir"); + if (index === -1) return path.join(packageRoot, "dist/server/terminal-worker"); + const value = argv[index + 1]; + if (!value) throw new Error("--outdir requires a directory"); + return path.resolve(value); +} + +if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) { + await buildTerminalWorkerBundle({ outDir: readOutDir(process.argv.slice(2)) }); +} diff --git a/packages/server/scripts/supervisor-entrypoint.ts b/packages/server/scripts/supervisor-entrypoint.ts index ee3746accf..7d0e7f50aa 100644 --- a/packages/server/scripts/supervisor-entrypoint.ts +++ b/packages/server/scripts/supervisor-entrypoint.ts @@ -12,6 +12,7 @@ import { resolvePaseoHome } from "../src/server/paseo-home.js"; import { daemonLogPath } from "../src/server/daemon-instance.js"; import { PRIVATE_FILE_MODE } from "../src/server/private-files.js"; import { loadPersistedConfig } from "../src/server/persisted-config.js"; +import { reapTerminalWorkers } from "../src/terminal/terminal-worker-reaper.js"; import { runSupervisor } from "./supervisor.js"; import { resolveSupervisorLogFile } from "./supervisor-log-config.js"; @@ -175,6 +176,10 @@ async function main(): Promise { onWorkerExit: () => updatePidLock(paseoHome, { listen: null, serverId: null }, { ownerPid: process.pid }), onSupervisorExit: releaseLock, + cleanupTerminals: async (log) => { + const result = await reapTerminalWorkers({ paseoHome, log }); + log("Terminal worker cleanup result", { ...result }); + }, }); requestSupervisorShutdown = supervisor.requestShutdown; } diff --git a/packages/server/scripts/supervisor.terminal-cleanup.test.ts b/packages/server/scripts/supervisor.terminal-cleanup.test.ts new file mode 100644 index 0000000000..224a0788d3 --- /dev/null +++ b/packages/server/scripts/supervisor.terminal-cleanup.test.ts @@ -0,0 +1,180 @@ +import { spawn } from "node:child_process"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { describe, expect, test } from "vitest"; + +// A real supervisor with scripted workers. Each worker generation logs what it sees to an +// events file; `cleanupTerminals` logs "cleanup". The order of events is the contract: a kill +// intent cleans up before the next worker starts, a keep intent or a crash never cleans up. + +async function runSupervisorWith(workerScript: string, timeoutMs = 8_000) { + const home = await mkdtemp(path.join(tmpdir(), "paseo-terminal-cleanup-")); + const workerPath = path.join(home, "worker.mjs"); + const runnerPath = path.join(home, "runner.mjs"); + const eventsPath = path.join(home, "events.jsonl"); + const supervisor = new URL("./supervisor.ts", import.meta.url).href; + await writeFile( + workerPath, + ` + import { appendFileSync, existsSync, readFileSync, writeFileSync } from "node:fs"; + const counter = ${JSON.stringify(path.join(home, "generation"))}; + const generation = existsSync(counter) ? Number(readFileSync(counter, "utf8")) + 1 : 1; + writeFileSync(counter, String(generation)); + const record = (event) => + appendFileSync(${JSON.stringify(eventsPath)}, JSON.stringify(event) + "\\n"); + record({ started: generation }); + ${workerScript} + `, + ); + await writeFile( + runnerPath, + ` + import { appendFileSync } from "node:fs"; + import { runSupervisor } from ${JSON.stringify(supervisor)}; + runSupervisor({ + name: "TerminalCleanupTest", startupMessage: "starting", restartOnCrash: true, + resolveWorkerEntry: () => ${JSON.stringify(workerPath)}, workerArgs: [], workerExecArgv: [], + cleanupTerminals: async () => { + appendFileSync(${JSON.stringify(eventsPath)}, JSON.stringify("cleanup") + "\\n"); + }, + }); + `, + ); + const env = Object.fromEntries( + Object.entries(process.env).filter(([key]) => !key.startsWith("PASEO_")), + ); + const child = spawn(process.execPath, ["--import", "tsx", runnerPath], { + cwd: fileURLToPath(new URL("../../../", import.meta.url)), + env: { ...env, HOME: home, PASEO_HOME: home }, + stdio: ["ignore", "pipe", "pipe"], + }); + let output = ""; + child.stdout.on("data", (chunk) => (output += chunk)); + child.stderr.on("data", (chunk) => (output += chunk)); + try { + const code = await new Promise((resolve, reject) => { + const timer = setTimeout(() => { + child.kill("SIGKILL"); + reject(new Error(output)); + }, timeoutMs); + child.once("error", reject); + child.once("close", (exitCode) => { + clearTimeout(timer); + resolve(exitCode); + }); + }); + const events = (await readFile(eventsPath, "utf8").catch(() => "")) + .trim() + .split("\n") + .filter(Boolean) + .map((line) => JSON.parse(line) as unknown); + return { code, output, events }; + } finally { + await rm(home, { recursive: true, force: true }); + } +} + +// Generation 1 asks for `firstIntent`; generation 2 (if any) stops with `secondIntent`. +function scriptedWorker(firstIntent: string, secondIntent = "") { + return ` + process.on("message", (message) => { + if (message.type !== "paseo:graceful-shutdown") return; + record({ graceful: generation, keepTerminals: message.keepTerminals }); + process.exit(0); + }); + process.send({ type: "paseo:ready", listen: "endpoint-" + generation, serverId: "srv" }); + if (generation === 1) { ${firstIntent} } + else { ${secondIntent} } + `; +} + +const stopKeeping = `process.send({ type: "paseo:shutdown", reason: "test", keepTerminals: true });`; + +describe("supervisor terminal cleanup", () => { + test("a keep restart passes keepTerminals and never cleans up", async () => { + const result = await runSupervisorWith( + scriptedWorker( + `process.send({ type: "paseo:restart", reason: "test", keepTerminals: true });`, + stopKeeping, + ), + ); + expect(result.code, result.output).toBe(0); + expect(result.events).toEqual([ + { started: 1 }, + { graceful: 1, keepTerminals: true }, + { started: 2 }, + { graceful: 2, keepTerminals: true }, + ]); + }); + + test("a kill restart cleans up after the worker exits and before the respawn", async () => { + const result = await runSupervisorWith( + scriptedWorker( + `process.send({ type: "paseo:restart", reason: "test", keepTerminals: false });`, + stopKeeping, + ), + ); + expect(result.code, result.output).toBe(0); + expect(result.events).toEqual([ + { started: 1 }, + { graceful: 1, keepTerminals: false }, + "cleanup", + { started: 2 }, + { graceful: 2, keepTerminals: true }, + ]); + }); + + test("a kill restart whose worker hangs cleans up after the forced kill, before the respawn", async () => { + const result = await runSupervisorWith( + ` + process.on("message", (message) => { + if (message.type !== "paseo:graceful-shutdown") return; + record({ graceful: generation, keepTerminals: message.keepTerminals }); + if (generation === 2) process.exit(0); + }); + process.send({ type: "paseo:ready", listen: "endpoint-" + generation, serverId: "srv" }); + if (generation === 1) { + process.send({ type: "paseo:restart", reason: "test", keepTerminals: false }); + setInterval(() => {}, 1000); + } else { + ${stopKeeping} + } + `, + 20_000, + ); + expect(result.code, result.output).toBe(0); + expect(result.events).toEqual([ + { started: 1 }, + { graceful: 1, keepTerminals: false }, + "cleanup", + { started: 2 }, + { graceful: 2, keepTerminals: true }, + ]); + }, 30_000); + + test("a crash restart keeps terminals", async () => { + const result = await runSupervisorWith(scriptedWorker(`process.exit(1);`, stopKeeping)); + expect(result.code, result.output).toBe(0); + expect(result.events).toEqual([ + { started: 1 }, + { started: 2 }, + { graceful: 2, keepTerminals: true }, + ]); + }); + + test("a kill stop cleans up when the supervisor exits", async () => { + const result = await runSupervisorWith( + scriptedWorker( + `process.send({ type: "paseo:shutdown", reason: "test", keepTerminals: false });`, + ), + ); + expect(result.code, result.output).toBe(0); + expect(result.events).toEqual([ + { started: 1 }, + { graceful: 1, keepTerminals: false }, + "cleanup", + ]); + }); +}); diff --git a/packages/server/scripts/supervisor.ts b/packages/server/scripts/supervisor.ts index ec56822619..fac28946d5 100644 --- a/packages/server/scripts/supervisor.ts +++ b/packages/server/scripts/supervisor.ts @@ -21,6 +21,7 @@ type WorkerLifecycleMessage = | { type: "paseo:shutdown"; reason?: string; + keepTerminals: boolean; } | { type: "paseo:ready"; @@ -30,6 +31,7 @@ type WorkerLifecycleMessage = | { type: "paseo:restart"; reason?: string; + keepTerminals: boolean; }; interface SupervisorHeartbeatMessage { @@ -39,8 +41,11 @@ interface SupervisorHeartbeatMessage { interface SupervisorGracefulShutdownMessage { type: "paseo:graceful-shutdown"; reason: string; + keepTerminals: boolean; } +export type SupervisorLifecycleLog = (message: string, fields?: Record) => void; + interface SupervisorOptions { name: string; startupMessage: string; @@ -57,11 +62,15 @@ interface SupervisorOptions { onWorkerExit?: () => Promise | void; restartOnCrash?: boolean; onSupervisorExit?: () => Promise | void; + // Closes every terminal the worker left. Runs after a kill-intent restart or stop once the + // worker has exited (also after a forced kill), before a respawn, and on any supervisor + // exit except a keep-terminals stop. A crash restart keeps terminals and skips it. + cleanupTerminals?: (log: SupervisorLifecycleLog) => Promise; logFile?: SupervisorLogFileOptions; } export interface SupervisorController { - requestShutdown(reason: string): void; + requestShutdown(reason: string, options?: { keepTerminals?: boolean }): void; } function describeExit(code: number | null, signal: NodeJS.Signals | null): string { @@ -74,10 +83,11 @@ function parseLifecycleMessage(msg: unknown): WorkerLifecycleMessage | null { } const type = (msg as { type?: unknown }).type; if (type === "paseo:shutdown") { - const reason = (msg as { reason?: unknown }).reason; + const { reason, keepTerminals } = msg as { reason?: unknown; keepTerminals?: unknown }; return { type: "paseo:shutdown", ...(typeof reason === "string" && reason.trim().length > 0 ? { reason } : {}), + keepTerminals: keepTerminals === true, }; } if (type === "paseo:ready") { @@ -91,10 +101,11 @@ function parseLifecycleMessage(msg: unknown): WorkerLifecycleMessage | null { return { type: "paseo:ready", listen, serverId }; } if (type === "paseo:restart") { - const reason = (msg as { reason?: unknown }).reason; + const { reason, keepTerminals } = msg as { reason?: unknown; keepTerminals?: unknown }; return { type: "paseo:restart", ...(typeof reason === "string" && reason.trim().length > 0 ? { reason } : {}), + keepTerminals: keepTerminals === true, }; } return null; @@ -185,6 +196,9 @@ export function runSupervisor(options: SupervisorOptions): SupervisorController let child: ChildProcess | null = null; let restarting = false; let shuttingDown = false; + // The resolved terminal decision of the pending restart or stop. It survives the force-kill + // path, so a hung kill restart still closes terminals before the respawn. + let pendingKeepTerminals = false; let exiting = false; let lifecycleFailed = false; let publication = Promise.resolve(); @@ -217,12 +231,31 @@ export function runSupervisor(options: SupervisorOptions): SupervisorController const closeLogStream = (): Promise => durableLog.close(); - const exitSupervisor = (code: number): void => { + const runTerminalCleanup = async (when: string): Promise => { + if (!options.cleanupTerminals) { + return; + } + writeLifecycleLog("Closing terminals", { when }); + try { + await options.cleanupTerminals(writeLifecycleLog); + writeLifecycleLog("Terminal cleanup finished", { when }); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + log(`Terminal cleanup not confirmed (${when}): ${message}`); + } + }; + + const exitSupervisor = (code: number, exitOptions: { keepTerminals?: boolean } = {}): void => { if (exiting) { return; } exiting = true; - Promise.resolve(options.onSupervisorExit?.()) + const cleanup = + exitOptions.keepTerminals === true + ? Promise.resolve() + : runTerminalCleanup("supervisor_exit"); + cleanup + .then(() => options.onSupervisorExit?.()) .catch((error) => { const message = error instanceof Error ? error.message : String(error); log(`Supervisor exit cleanup failed: ${message}`); @@ -357,14 +390,20 @@ export function runSupervisor(options: SupervisorOptions): SupervisorController if (lifecycleMessage.type === "paseo:shutdown") { const reason = lifecycleMessage.reason ?? "worker_requested_shutdown"; - writeLifecycleLog("Worker requested shutdown", { reason }); - requestShutdown(reason); + writeLifecycleLog("Worker requested shutdown", { + reason, + keepTerminals: lifecycleMessage.keepTerminals, + }); + requestShutdown(reason, { keepTerminals: lifecycleMessage.keepTerminals }); return; } const reason = lifecycleMessage.reason ?? "worker_requested_restart"; - writeLifecycleLog("Worker requested restart", { reason }); - requestRestart(reason); + writeLifecycleLog("Worker requested restart", { + reason, + keepTerminals: lifecycleMessage.keepTerminals, + }); + requestRestart(reason, lifecycleMessage.keepTerminals); }); child.on("error", (error) => { @@ -395,7 +434,7 @@ export function runSupervisor(options: SupervisorOptions): SupervisorController if (shuttingDown) { log(`Worker exited (${exitDescriptor}). Supervisor shutting down.`); - exitSupervisor(0); + exitSupervisor(0, { keepTerminals: pendingKeepTerminals }); return; } @@ -404,13 +443,25 @@ export function runSupervisor(options: SupervisorOptions): SupervisorController ((code !== 0 && code !== null) || (signal !== null && signal !== "SIGTERM")); if (restarting || crashed) { + const closeTerminals = restarting && !pendingKeepTerminals; restarting = false; + pendingKeepTerminals = false; log( - crashed + crashed && !closeTerminals ? `Worker crashed (${exitDescriptor}). Restarting worker...` : `Worker exited (${exitDescriptor}). Restarting worker...`, ); - spawnWorker(); + if (!closeTerminals) { + spawnWorker(); + return; + } + // The replacement daemon must never adopt terminals the user asked to close. + void runTerminalCleanup("before_respawn").then(() => { + if (!shuttingDown) { + spawnWorker(); + } + return; + }); return; } @@ -429,9 +480,11 @@ export function runSupervisor(options: SupervisorOptions): SupervisorController const message: SupervisorGracefulShutdownMessage = { type: "paseo:graceful-shutdown", reason, + keepTerminals: pendingKeepTerminals, }; writeLifecycleLog("Supervisor requesting graceful worker shutdown", { reason, + keepTerminals: pendingKeepTerminals, supervisorPid: process.pid, workerPid: currentChild.pid ?? null, }); @@ -455,28 +508,33 @@ export function runSupervisor(options: SupervisorOptions): SupervisorController }); }; - const requestRestart = (reason: string) => { + const requestRestart = (reason: string, keepTerminals: boolean) => { if (!child || restarting || shuttingDown) { return; } restarting = true; - writeLifecycleLog("Restart requested", { reason }); + pendingKeepTerminals = keepTerminals; + writeLifecycleLog("Restart requested", { reason, keepTerminals }); log(`${reason}. Stopping worker for restart...`); requestWorkerShutdown(reason); scheduleForceKill(reason); }; - const requestShutdown = (reason: string) => { + const requestShutdown = (reason: string, shutdownOptions: { keepTerminals?: boolean } = {}) => { if (shuttingDown) { return; } shuttingDown = true; restarting = false; - writeLifecycleLog("Supervisor shutdown requested", { reason }); + pendingKeepTerminals = shutdownOptions.keepTerminals === true; + writeLifecycleLog("Supervisor shutdown requested", { + reason, + keepTerminals: pendingKeepTerminals, + }); log(`${reason}. Stopping worker...`); if (!child) { void publication.then(() => { - exitSupervisor(lifecycleFailed ? 1 : 0); + exitSupervisor(lifecycleFailed ? 1 : 0, { keepTerminals: pendingKeepTerminals }); return; }); return; diff --git a/packages/server/src/executable-resolution/executable-resolution.ts b/packages/server/src/executable-resolution/executable-resolution.ts index 97bb8af3a3..064dcec64e 100644 --- a/packages/server/src/executable-resolution/executable-resolution.ts +++ b/packages/server/src/executable-resolution/executable-resolution.ts @@ -1,17 +1,10 @@ -import { createRequire } from "node:module"; import { existsSync } from "node:fs"; import { delimiter, resolve } from "node:path"; import type { ProcessEnvRecord } from "../server/paseo-env.js"; import { execCommand } from "../utils/spawn.js"; +import which from "which"; import { windowsExecutableResolution } from "./windows.js"; -type Which = ( - command: string, - options: { all: true; path?: string; pathExt?: string }, -) => Promise; - -const require = createRequire(import.meta.url); -const which = require("which") as Which; const PROBE_TIMEOUT_MS = 2000; function hasPathSeparator(value: string): boolean { diff --git a/packages/server/src/executable-resolution/which.d.ts b/packages/server/src/executable-resolution/which.d.ts new file mode 100644 index 0000000000..e7fd869f25 --- /dev/null +++ b/packages/server/src/executable-resolution/which.d.ts @@ -0,0 +1,10 @@ +// `which` ships no types. Imported statically (not through createRequire) so the terminal +// worker bundle includes it: the worker runs from a copy that has only node-pty beside it. +// Listed in the tsconfig includes, since nothing imports a declaration file. +declare module "which" { + function which( + command: string, + options: { all: true; path?: string; pathExt?: string }, + ): Promise; + export default which; +} diff --git a/packages/server/src/server/agent/mcp-server.test.ts b/packages/server/src/server/agent/mcp-server.test.ts index f2c7da8574..3b72c8805a 100644 --- a/packages/server/src/server/agent/mcp-server.test.ts +++ b/packages/server/src/server/agent/mcp-server.test.ts @@ -76,7 +76,7 @@ import type { GeneratedWorkspaceName } from "../worktree-branch-name-generator.j import type { ForgeService } from "../../services/forge-service.js"; import { areEquivalentPaths } from "../../utils/path.js"; import { createTerminalManager, type TerminalManager } from "../../terminal/terminal-manager.js"; -import { createWorkerTerminalManager } from "../../terminal/worker-terminal-manager.js"; +import { startWorkerTerminalManager } from "../../terminal/worker-terminal-manager.js"; import { PARENT_AGENT_ID_LABEL } from "@getpaseo/protocol/agent-labels"; import { PASEO_TOOL_NAMES } from "@getpaseo/protocol/paseo-tool-presentation/index"; import { MutableDaemonConfigSchema, type AgentProfile } from "@getpaseo/protocol/messages"; @@ -1384,13 +1384,24 @@ describe("terminal MCP tools", () => { ); it.each([ - ["in-process", createTerminalManager], - ["worker", createWorkerTerminalManager], + ["in-process", async () => ({ manager: createTerminalManager(), home: null })], + [ + "worker", + async () => { + const home = await mkdtemp(join(tmpdir(), "mcp-terminal-keys-home-")); + const manager = await startWorkerTerminalManager({ + paseoHome: home, + paseoVersion: "0.0.0-test", + logger, + }); + return { manager, home }; + }, + ], ] as const)( "delivers MCP key tokens through %s after terminal input modes change", async (_name, createManager) => { const { agentManager, agentStorage } = createTestDeps(); - const terminalManager = createManager(); + const { manager: terminalManager, home } = await createManager(); const terminal = await terminalManager.createTerminal({ cwd: process.cwd(), workspaceId: "ws-terminal-keys", @@ -1420,15 +1431,15 @@ describe("terminal MCP tools", () => { logger, }); + // Every step is a round trip through a real PTY. A loaded Windows runner (ConPTY) has + // taken over 3 s to reach READY, so each step gets the same window rather than 1 s. + const roundTrip = { timeout: 5000 }; let output = ""; const unsubscribe = terminal.subscribe((message) => { if (message.type === "output") { output += message.data; } }); - // Every key travels through the PTY and back; on loaded Windows runners one round - // trip can take seconds, so each wait gets the same budget as the first. - const roundTrip = { timeout: 5000 }; try { await vi.waitFor(async () => { const capture = await terminalManager.captureTerminal(terminal.id); @@ -1465,6 +1476,7 @@ describe("terminal MCP tools", () => { await server.close(); await terminalManager.killTerminalAndWait(terminal.id); terminalManager.killAll(); + if (home) await rm(home, { recursive: true, force: true }); } }, ); diff --git a/packages/server/src/server/agent/providers/opencode-bridge.local.e2e.test.ts b/packages/server/src/server/agent/providers/opencode-bridge.local.e2e.test.ts index 843ef21ebb..aeb87388fd 100644 --- a/packages/server/src/server/agent/providers/opencode-bridge.local.e2e.test.ts +++ b/packages/server/src/server/agent/providers/opencode-bridge.local.e2e.test.ts @@ -455,9 +455,15 @@ test.each([ let original: Awaited> | undefined; let resumed: Awaited> | undefined; try { + // Windows invokes the platform binary directly. Installing its wrapper also runs an + // unused postinstall binary probe, which has no timeout and can hold the fixture open. + const installPackage = + process.platform === "win32" + ? `${windowsPackage}-${process.arch}@${cliPackage.slice(cliPackage.lastIndexOf("@") + 1)}` + : cliPackage; await execCommand( "npm", - ["install", "--prefix", root, "--no-audit", "--no-fund", cliPackage], + ["install", "--prefix", root, "--no-audit", "--no-fund", installPackage], { cwd: root, timeout: 180_000, diff --git a/packages/server/src/server/bootstrap.ts b/packages/server/src/server/bootstrap.ts index b3eb6f0f66..36ba9e2b06 100644 --- a/packages/server/src/server/bootstrap.ts +++ b/packages/server/src/server/bootstrap.ts @@ -180,7 +180,7 @@ import { import { setupAutoArchiveOnMerge } from "./auto-archive-on-merge/index.js"; import { wrapSessionMessage, type SessionOutboundMessage } from "./messages.js"; import type { TerminalManager } from "../terminal/terminal-manager.js"; -import { createConfiguredTerminalManager } from "../terminal/terminal-manager-factory.js"; +import { startWorkerTerminalManager } from "../terminal/worker-terminal-manager.js"; import { applyTerminalAgentHookSetting } from "../terminal/agent-hooks/terminal-agent-hook-setting.js"; import { loadOrCreateDaemonKeyPair } from "./daemon-keypair.js"; import { createRelayRuntime, type RelayRuntime } from "./relay-runtime.js"; @@ -396,12 +396,14 @@ export type DaemonLifecycleIntent = clientId: string; requestId: string; reason: string; + keepTerminals: boolean; } | { type: "restart"; clientId: string; requestId: string; reason: string; + keepTerminals: boolean; }; export interface PaseoDaemonConfig { @@ -493,7 +495,8 @@ export interface PaseoDaemon { scriptRuntimeStore: WorkspaceScriptRuntimeStore; browserToolsBroker: BrowserToolsBroker; start(): Promise; - stop(): Promise; + /** Stops the daemon. Terminals keep running for the next daemon only with keepTerminals. */ + stop(options?: { keepTerminals?: boolean }): Promise; getListenTarget(): ListenTarget | null; getServerId(): string; } @@ -709,7 +712,10 @@ export async function createPaseoDaemon( }); let boundListenTarget: ListenTarget | null = null; let workspaceRegistry: FileBackedWorkspaceRegistry | null = null; - const terminalManager = createConfiguredTerminalManager({ + const terminalManager = await startWorkerTerminalManager({ + paseoHome: config.paseoHome, + paseoVersion: daemonVersion, + logger, getTerminalActivityUrl: () => createTerminalActivityUrl(boundListenTarget), }); applyTerminalAgentHookSetting({ store: daemonConfigStore, logger }); @@ -1936,7 +1942,9 @@ export async function createPaseoDaemon( } }; - const stop = async () => { + const stop = async (options?: { keepTerminals?: boolean }) => { + const keepTerminals = options?.keepTerminals === true; + let terminalShutdownError: unknown = null; localCredential = null; await deleteLocalCredential(config.paseoHome); // Stop tracking plugin provider registrations before anything tears plugins @@ -1966,7 +1974,19 @@ export async function createPaseoDaemon( await agentStorage.flush().catch(() => undefined); await agentProviderRuntime.shutdown(); await pluginRuntime.stopAllPlugins(); - terminalManager.killAll(); + try { + if (keepTerminals) { + await terminalManager.detach(); + logger.info("Terminals left running for the next daemon"); + } else { + await terminalManager.closeTerminals(); + } + } catch (error) { + // Finish the rest of the shutdown, then report it: the supervisor and `daemon stop` + // retry the cleanup from the record the reaper kept. + terminalShutdownError = error; + logger.error({ err: error }, "Terminal shutdown failed"); + } await speechService.stop(); await scheduleService.stop().catch(() => undefined); await relayRuntime?.stop().catch(() => undefined); @@ -1989,6 +2009,9 @@ export async function createPaseoDaemon( if (listenTarget.type === "socket" && existsSync(listenTarget.path)) { unlinkSync(listenTarget.path); } + if (terminalShutdownError) { + throw terminalShutdownError; + } }; return { diff --git a/packages/server/src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts b/packages/server/src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts new file mode 100644 index 0000000000..d606b4d4d9 --- /dev/null +++ b/packages/server/src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts @@ -0,0 +1,688 @@ +import { afterEach, describe, expect, test } from "vitest"; +import { spawn, type ChildProcess } from "node:child_process"; +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { createServer } from "node:net"; +import { createRequire } from "node:module"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; +import { DaemonClient } from "../test-utils/daemon-client.js"; +import { resolveDaemonVersion } from "../daemon-version.js"; +import { readDaemonInstance, stopDaemonInstance } from "../daemon-instance.js"; +import { currentBootId } from "../pid-lock.js"; +import { connectTerminalWorker } from "../../terminal/terminal-worker-client.js"; +import { createTerminalWorkerProcessInspector } from "../../terminal/terminal-worker-processes.js"; +import { reapTerminalWorkers } from "../../terminal/terminal-worker-reaper.js"; +import { launchTerminalWorker } from "../../terminal/terminal-worker-launch.js"; +import { prepareTerminalWorkerRuntime } from "../../terminal/terminal-worker-runtime.js"; +import { createWorkerTerminalManager } from "../../terminal/worker-terminal-manager.js"; +import { + listTerminalWorkerRecords, + writeTerminalWorkerRecord, + type TerminalWorkerRecord, +} from "../../terminal/terminal-worker-record.js"; + +// Real supervisors started through scripts/supervisor-entrypoint.ts, driven by DaemonClient the +// way the app drives them. Every daemon, worker and program here lives in a throwaway home and +// is killed in afterEach; nothing touches another daemon. + +const SERVER_ROOT = path.resolve(import.meta.dirname, "../../.."); +const SUPERVISOR_ENTRY = path.join(SERVER_ROOT, "scripts/supervisor-entrypoint.ts"); +const READY_TIMEOUT_MS = 90_000; +const POSIX = process.platform !== "win32"; +const inspector = createTerminalWorkerProcessInspector(); + +interface Harness { + home: string; + workDir: string; + port: number; + supervisor: ChildProcess; + output: () => string; +} + +const harnesses: Harness[] = []; +const extraPids = new Set(); +const extraDirs: string[] = []; + +function isAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +async function waitFor( + probe: () => Promise | T | null | undefined | false, + message: string, + timeoutMs = READY_TIMEOUT_MS, +): Promise { + const deadline = Date.now() + timeoutMs; + let lastError: unknown = null; + while (Date.now() < deadline) { + try { + const value = await probe(); + if (value) return value; + } catch (error) { + lastError = error; + } + await delay(100); + } + throw new Error(`${message}${lastError ? ` (last error: ${String(lastError)})` : ""}`); +} + +async function getAvailablePort(): Promise { + const server = createServer(); + await new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve())); + const address = server.address(); + await new Promise((resolve) => server.close(() => resolve())); + if (!address || typeof address === "string") throw new Error("no port"); + return address.port; +} + +async function startSupervisor( + options: { home?: string; port?: number; pathPrefix?: string } = {}, +): Promise { + const home = options.home ?? mkdtempSync(path.join(tmpdir(), "tw-life-")); + const workDir = path.join(home, "work"); + mkdirSync(workDir, { recursive: true }); + const port = options.port ?? (await getAvailablePort()); + const env: NodeJS.ProcessEnv = { + ...Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("PASEO_"))), + HOME: home, + USERPROFILE: home, + PASEO_HOME: home, + PASEO_LISTEN: `127.0.0.1:${port}`, + PASEO_RELAY_ENABLED: "false", + PASEO_NODE_INSPECT: "0", + PASEO_LOCAL_SPEECH_AUTO_DOWNLOAD: "0", + PASEO_DICTATION_ENABLED: "0", + PASEO_VOICE_MODE_ENABLED: "0", + CI: "true", + }; + if (options.pathPrefix) { + env.PATH = `${options.pathPrefix}${path.delimiter}${env.PATH ?? ""}`; + } + let output = ""; + const supervisor = spawn( + process.execPath, + ["--import", "tsx", SUPERVISOR_ENTRY, "--dev", "--no-relay"], + { cwd: SERVER_ROOT, env, stdio: ["ignore", "pipe", "pipe"] }, + ); + supervisor.stdout?.on("data", (chunk) => (output = (output + String(chunk)).slice(-20_000))); + supervisor.stderr?.on("data", (chunk) => (output = (output + String(chunk)).slice(-20_000))); + const harness: Harness = { home, workDir, port, supervisor, output: () => output }; + harnesses.push(harness); + await waitFor(async () => { + const instance = await readDaemonInstance(home); + return instance?.pid === supervisor.pid && instance.listen ? instance : null; + }, `supervisor did not become ready:\n${output}`); + return harness; +} + +async function connect(harness: Harness): Promise { + return waitFor(async () => { + const client = new DaemonClient({ + url: `ws://127.0.0.1:${harness.port}/ws`, + connectTimeoutMs: 5_000, + }); + try { + await client.connect(); + return client; + } catch (error) { + await client.close().catch(() => undefined); + throw error; + } + }, "cannot connect to the daemon"); +} + +// A plain `paseo daemon stop`: SIGTERM on POSIX, the shutdown RPC where there is no signal +// for it (Windows refuses a graceful stop without one). +async function stopDaemon(harness: Harness): Promise { + await stopDaemonInstance(harness.home, { + requestShutdown: async () => { + const client = await connect(harness); + try { + await client.shutdownServer(); + } finally { + await client.close(); + } + }, + }); +} + +async function daemonWorkerPid(client: DaemonClient): Promise { + return (await client.getDaemonStatus()).pid; +} + +async function waitForReplacement(harness: Harness, previousPid: number): Promise { + return waitFor(async () => { + const client = await connect(harness); + const pid = await daemonWorkerPid(client).catch(() => previousPid); + if (pid !== previousPid) return client; + await client.close(); + return null; + }, "the daemon worker was not replaced"); +} + +async function createWorkspace(client: DaemonClient, harness: Harness): Promise { + const result = await client.createWorkspace({ + source: { kind: "directory", path: harness.workDir }, + title: "lifecycle", + }); + if (!result.workspace) throw new Error(result.error ?? "workspace creation failed"); + return result.workspace.id; +} + +interface MarkedTerminal { + id: string; + programPid: number; +} + +// A terminal whose program writes its pid, prints a marker and echoes each input line. +async function createMarkedTerminal( + client: DaemonClient, + harness: Harness, + workspaceId: string, + marker: string, +): Promise { + const pidFile = path.join(harness.workDir, `${marker}.pid`); + const created = await client.createTerminal(harness.workDir, marker, undefined, { + workspaceId, + command: process.execPath, + args: [ + "-e", + `require("node:fs").writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)); + console.log(${JSON.stringify(marker)}); + process.stdin.on("data", (data) => console.log("ECHO:" + data.toString().trim()));`, + ], + }); + if (!created.terminal) throw new Error(created.error ?? "terminal creation failed"); + const programPid = await waitFor( + () => (existsSync(pidFile) ? Number(readFileSync(pidFile, "utf8")) : null), + "terminal program did not start", + 10_000, + ); + await waitForScreen(client, created.terminal.id, marker); + return { id: created.terminal.id, programPid }; +} + +// A shell program that ignores SIGHUP. With `exec`, the shell becomes `sleep`: same pid and +// birth time, another command line. Without it, `sleep` runs as the shell's child. +async function createHupResistantTerminal( + client: DaemonClient, + harness: Harness, + workspaceId: string, + name: string, + mode: "exec" | "child", +): Promise<{ id: string; shellPid: number; sleepPid: number }> { + const shellPidFile = path.join(harness.workDir, `${name}.shell.pid`); + const sleepPidFile = path.join(harness.workDir, `${name}.sleep.pid`); + const script = + mode === "exec" + ? `trap '' HUP; echo $$ > '${shellPidFile}'; echo $$ > '${sleepPidFile}'; exec sleep 100000` + : `trap '' HUP; echo $$ > '${shellPidFile}'; sleep 100000 & echo $! > '${sleepPidFile}'; wait`; + const created = await client.createTerminal(harness.workDir, name, undefined, { + workspaceId, + command: "/bin/sh", + args: ["-c", script], + }); + if (!created.terminal) throw new Error(created.error ?? "terminal creation failed"); + const read = (file: string) => + existsSync(file) && readFileSync(file, "utf8").trim() + ? Number(readFileSync(file, "utf8").trim()) + : null; + const shellPid = await waitFor(() => read(shellPidFile), "shell did not start", 10_000); + const sleepPid = await waitFor(() => read(sleepPidFile), "sleep did not start", 10_000); + extraPids.add(shellPid); + extraPids.add(sleepPid); + // `exec` replaces the shell; wait until the process really is `sleep`. + await waitFor( + async () => { + const inspection = await inspector.inspect(sleepPid); + return inspection.status === "alive" && inspection.snapshot.commandLine?.startsWith("sleep"); + }, + "sleep did not start", + 10_000, + ); + return { id: created.terminal.id, shellPid, sleepPid }; +} + +async function screen(client: DaemonClient, terminalId: string): Promise { + return (await client.captureTerminal(terminalId, { stripAnsi: true })).lines.join("\n"); +} + +async function waitForScreen(client: DaemonClient, terminalId: string, text: string) { + await waitFor( + async () => (await screen(client, terminalId)).includes(text), + `terminal ${terminalId} never showed ${text}`, + 15_000, + ); +} + +async function expectKept( + client: DaemonClient, + terminal: MarkedTerminal, + marker: string, + trigger: string, +) { + const listed = await client.listTerminals(undefined, undefined, {}); + expect(listed.terminals.map((entry) => entry.id)).toContain(terminal.id); + expect(isAlive(terminal.programPid)).toBe(true); + expect(await screen(client, terminal.id)).toContain(marker); + client.sendTerminalInput(terminal.id, { type: "input", data: `after-${trigger}\r` }); + await waitForScreen(client, terminal.id, `ECHO:after-${trigger}`); +} + +async function waitUntilGone(pid: number, what: string) { + await waitFor(() => !isAlive(pid), `${what} (pid ${pid}) is still alive`, 15_000); +} + +async function liveRecords(home: string): Promise { + return (await listTerminalWorkerRecords(home)).flatMap((file) => + "record" in file ? [file.record] : [], + ); +} + +async function currentWorkerRecord(home: string): Promise { + const records = await liveRecords(home); + if (records.length !== 1) throw new Error(`expected one worker record, found ${records.length}`); + return records[0]!; +} + +async function expectAllClosed(home: string, pids: number[]) { + for (const pid of pids) { + await waitUntilGone(pid, "a process that should be closed"); + } + expect(await liveRecords(home)).toEqual([]); +} + +function spawnUnrelated(): ChildProcess { + const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1e9)"], { + detached: true, + stdio: "ignore", + }); + child.unref(); + extraPids.add(child.pid!); + return child; +} + +async function birthOf(pid: number): Promise { + const inspection = await inspector.inspect(pid); + if (inspection.status !== "alive" || !inspection.snapshot.startedAt) { + throw new Error(`no birth time for ${pid}`); + } + return inspection.snapshot.startedAt; +} + +afterEach(async () => { + for (const harness of harnesses.splice(0)) { + const pid = harness.supervisor.pid; + if (pid && isAlive(pid)) { + try { + process.kill(pid, "SIGCONT"); + } catch { + // gone + } + } + await stopDaemonInstance(harness.home, { force: true, timeoutMs: 15_000 }).catch( + () => undefined, + ); + if (pid && isAlive(pid)) process.kill(pid, "SIGKILL"); + for (const record of await liveRecords(harness.home)) { + if (isAlive(record.pid)) { + try { + process.kill(record.pid, "SIGCONT"); + } catch { + // gone + } + } + } + await reapTerminalWorkers({ paseoHome: harness.home, gracefulMs: 0 }).catch(() => undefined); + rmSync(harness.home, { recursive: true, force: true }); + } + for (const pid of extraPids) { + if (isAlive(pid)) { + try { + process.kill(pid, "SIGKILL"); + } catch { + // gone + } + } + } + extraPids.clear(); + for (const dir of extraDirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +describe("terminals across daemon restarts", { timeout: 240_000 }, () => { + test("Settings restart keeps the terminal; Settings restart and close terminals kills it", async () => { + const harness = await startSupervisor(); + let client = await connect(harness); + const workspaceId = await createWorkspace(client, harness); + const terminal = await createMarkedTerminal(client, harness, workspaceId, "MARKER-SETTINGS"); + const workerPid = (await currentWorkerRecord(harness.home)).pid; + + // Exactly what the app sends from Settings: no killTerminals. + let daemonPid = await daemonWorkerPid(client); + await client.restartServer("settings_update"); + await client.close(); + client = await waitForReplacement(harness, daemonPid); + await expectKept(client, terminal, "MARKER-SETTINGS", "settings-restart"); + expect((await currentWorkerRecord(harness.home)).pid).toBe(workerPid); + + daemonPid = await daemonWorkerPid(client); + await client.restartServer("settings_update", undefined, { killTerminals: true }); + await client.close(); + client = await waitForReplacement(harness, daemonPid); + await waitUntilGone(terminal.programPid, "terminal program"); + await waitUntilGone(workerPid, "old terminal worker"); + expect((await client.listTerminals(undefined, undefined, {})).terminals).toEqual([]); + expect((await liveRecords(harness.home)).every((record) => record.pid !== workerPid)).toBe( + true, + ); + await client.close(); + }); + + test("a daemon crash keeps the terminal; the restarted daemon lists it", async () => { + const harness = await startSupervisor(); + let client = await connect(harness); + const workspaceId = await createWorkspace(client, harness); + const terminal = await createMarkedTerminal(client, harness, workspaceId, "MARKER-CRASH"); + const daemonPid = await daemonWorkerPid(client); + process.kill(daemonPid, "SIGKILL"); + await client.close(); + client = await waitForReplacement(harness, daemonPid); + await expectKept(client, terminal, "MARKER-CRASH", "crash"); + await client.close(); + }); + + test("daemon.update.request restarts the daemon and keeps the terminal", async () => { + // Fake npm only: `ls` reports this checkout as the global install at the daemon's + // version, `install -g` does nothing, and anything else fails so real npm never runs. + const fakeBin = mkdtempSync(path.join(tmpdir(), "tw-npm-")); + extraDirs.push(fakeBin); + const listing = JSON.stringify({ + path: path.join(fakeBin, "global"), + dependencies: { + "@getpaseo/cli": { + version: resolveDaemonVersion(import.meta.url), + path: SERVER_ROOT, + }, + }, + }); + const fakeNpm = path.join(fakeBin, "fake-npm.cjs"); + writeFileSync( + fakeNpm, + `const args = process.argv.slice(2); +const has = (...tokens) => tokens.every((token) => args.includes(token)); +if (has("-g", "ls", "@getpaseo/cli", "--json", "--depth=0", "--long")) { + process.stdout.write(${JSON.stringify(listing)} + "\\n"); +} else if (args[0] === "install" && has("-g", "@getpaseo/cli@latest")) { + // The installed version is already the running one: nothing to do. +} else { + process.stderr.write("unexpected npm call: " + args.join(" ") + "\\n"); + process.exit(1); +} +`, + ); + const npmScript = path.join(fakeBin, "npm"); + writeFileSync(npmScript, `#!/bin/sh\nexec "${process.execPath}" "${fakeNpm}" "$@"\n`); + chmodSync(npmScript, 0o755); + writeFileSync(path.join(fakeBin, "npm.cmd"), `@"${process.execPath}" "${fakeNpm}" %*\r\n`); + const harness = await startSupervisor({ pathPrefix: fakeBin }); + let client = await connect(harness); + const workspaceId = await createWorkspace(client, harness); + const terminal = await createMarkedTerminal(client, harness, workspaceId, "MARKER-UPDATE"); + const daemonPid = await daemonWorkerPid(client); + + const update = await client.updateDaemon(); + expect(update).toMatchObject({ success: true }); + await client.close(); + client = await waitForReplacement(harness, daemonPid); + await expectKept(client, terminal, "MARKER-UPDATE", "update"); + await client.close(); + }); + + test.skipIf(!POSIX)( + "POSIX: a kill restart whose shutdown hangs closes terminals before the respawn", + async () => { + const harness = await startSupervisor(); + let client = await connect(harness); + const workspaceId = await createWorkspace(client, harness); + const terminal = await createMarkedTerminal(client, harness, workspaceId, "MARKER-HUNG"); + const daemonPid = await daemonWorkerPid(client); + const supervisorPid = harness.supervisor.pid!; + const logPath = path.join(harness.home, "daemon.log"); + + // Barrier: the supervisor is paused, so the restart intent waits in its IPC channel. + // The daemon's own log line marks the intent dispatched; then the daemon is paused, so + // its graceful shutdown can never run and the supervisor's force path must. + process.kill(supervisorPid, "SIGSTOP"); + await client.restartServer("settings_update", undefined, { killTerminals: true }); + await waitFor( + () => readFileSync(logPath, "utf8").includes("Lifecycle intent dispatched"), + "the daemon never dispatched the restart intent", + 15_000, + ); + process.kill(daemonPid, "SIGSTOP"); + expect(isAlive(terminal.programPid)).toBe(true); + process.kill(supervisorPid, "SIGCONT"); + await client.close(); + + client = await waitForReplacement(harness, daemonPid); + const log = readFileSync(logPath, "utf8"); + const forced = log.indexOf("forcing process tree kill"); + const cleaned = log.indexOf('"msg":"Terminal cleanup finished","when":"before_respawn"'); + const respawned = log.indexOf('"msg":"Spawning worker"', forced); + expect(forced).toBeGreaterThan(-1); + expect(cleaned).toBeGreaterThan(forced); + expect(respawned).toBeGreaterThan(cleaned); + expect(isAlive(terminal.programPid)).toBe(false); + expect((await client.listTerminals(undefined, undefined, {})).terminals).toEqual([]); + await client.close(); + }, + ); +}); + +describe("terminals when the daemon stops", { timeout: 240_000 }, () => { + test.skipIf(!POSIX)( + "POSIX: stop closes a terminal whose program ignores HUP, child process included", + async () => { + const harness = await startSupervisor(); + const client = await connect(harness); + const workspaceId = await createWorkspace(client, harness); + const terminal = await createHupResistantTerminal( + client, + harness, + workspaceId, + "hup", + "child", + ); + const workerPid = (await currentWorkerRecord(harness.home)).pid; + await client.close(); + await stopDaemon(harness); + await expectAllClosed(harness.home, [terminal.shellPid, terminal.sleepPid, workerPid]); + }, + ); + + for (const force of [false, true]) { + test.skipIf(!POSIX)( + `POSIX: worker death reaps an exec'd HUP-resistant program and ${force ? "stop --force" : "stop"} closes its replacement`, + async () => { + const harness = await startSupervisor(); + const client = await connect(harness); + const workspaceId = await createWorkspace(client, harness); + const terminal = await createHupResistantTerminal( + client, + harness, + workspaceId, + "orphan", + "exec", + ); + const workerPid = (await currentWorkerRecord(harness.home)).pid; + const daemonPid = await daemonWorkerPid(client); + process.kill(workerPid, "SIGKILL"); + await waitUntilGone(workerPid, "terminal worker"); + await waitUntilGone(terminal.sleepPid, "orphaned terminal program"); + await waitFor( + async () => (await client.listTerminals(undefined, undefined, {})).terminals.length === 0, + "dead terminal was not removed", + ); + expect(await daemonWorkerPid(client)).toBe(daemonPid); + const replacement = await createMarkedTerminal(client, harness, workspaceId, "RECOVERED"); + await expectKept(client, replacement, "RECOVERED", "worker-death"); + await client.close(); + await stopDaemonInstance(harness.home, { force }); + await expectAllClosed(harness.home, [terminal.sleepPid, replacement.programPid]); + }, + ); + } + + test.skipIf(!POSIX)( + "POSIX: stop --force kills a stopped (SIGSTOP) worker and its terminal", + async () => { + const harness = await startSupervisor(); + const client = await connect(harness); + const workspaceId = await createWorkspace(client, harness); + const terminal = await createMarkedTerminal(client, harness, workspaceId, "MARKER-STOPPED"); + const workerPid = (await currentWorkerRecord(harness.home)).pid; + await client.close(); + process.kill(workerPid, "SIGSTOP"); + await stopDaemonInstance(harness.home, { force: true }); + await expectAllClosed(harness.home, [workerPid, terminal.programPid]); + }, + ); + + test("the worker socket rejects a wrong secret and leaves its terminals alone", async () => { + const harness = await startSupervisor(); + const client = await connect(harness); + const workspaceId = await createWorkspace(client, harness); + const terminal = await createMarkedTerminal(client, harness, workspaceId, "MARKER-AUTH"); + const record = await currentWorkerRecord(harness.home); + await expect( + connectTerminalWorker({ socketPath: record.socketPath, secret: "not-the-secret" }), + ).rejects.toThrow(); + await expectKept(client, terminal, "MARKER-AUTH", "auth"); + await client.close(); + }); + + test("stop and stop --force never signal processes a stale or earlier-boot record names", async () => { + const harness = await startSupervisor(); + const client = await connect(harness); + await client.close(); + const reused = spawnUnrelated(); + const earlierBoot = spawnUnrelated(); + const base = await currentWorkerRecord(harness.home); + // Same pid, another birth time: what a reused pid looks like, whatever its command line. + writeTerminalWorkerRecord(harness.home, { + ...base, + recordId: "stale-record", + pid: reused.pid!, + identity: { startedAt: "Thu Jan 1 00:00:00 1970", commandLine: "node -e setInterval" }, + terminals: [{ id: "t-stale", pid: reused.pid!, startedAt: "Thu Jan 1 00:00:00 1970" }], + }); + // The right birth time, but written before this boot. + writeTerminalWorkerRecord(harness.home, { + ...base, + recordId: "earlier-boot-record", + pid: earlierBoot.pid!, + bootId: currentBootId() ? "another-boot" : null, + createdAt: "2000-01-01T00:00:00.000Z", + identity: { + startedAt: await birthOf(earlierBoot.pid!), + commandLine: `node --paseo-terminal-worker earlier-boot-record`, + }, + terminals: [ + { id: "t-boot", pid: earlierBoot.pid!, startedAt: await birthOf(earlierBoot.pid!) }, + ], + }); + + await stopDaemon(harness); + expect(isAlive(reused.pid!)).toBe(true); + expect(isAlive(earlierBoot.pid!)).toBe(true); + expect(await liveRecords(harness.home)).toEqual([]); + + // A second round through --force, with the stale record put back. + writeTerminalWorkerRecord(harness.home, { + ...base, + recordId: "stale-record", + pid: reused.pid!, + identity: { startedAt: "Thu Jan 1 00:00:00 1970", commandLine: "node -e setInterval" }, + terminals: [{ id: "t-stale", pid: reused.pid!, startedAt: "Thu Jan 1 00:00:00 1970" }], + }); + await stopDaemonInstance(harness.home, { force: true }); + expect(isAlive(reused.pid!)).toBe(true); + expect(await liveRecords(harness.home)).toEqual([]); + }); +}); + +describe("a worker launched from its own copy", { timeout: 240_000 }, () => { + // What a built daemon does: bundle the worker, copy bundle + shell integration + node-pty into + // the home, launch from the copy. Here the copy's node-pty (ConPTY on Windows) opens a real + // terminal; nothing is loaded from this checkout once the worker runs. + test("opens a terminal and runs a command from the copied bundle and node-pty", async () => { + const home = mkdtempSync(path.join(tmpdir(), "tw-copy-home-")); + const bundleDirectory = mkdtempSync(path.join(tmpdir(), "tw-copy-bundle-")); + extraDirs.push(home, bundleDirectory); + const buildScript = path.join(SERVER_ROOT, "scripts/build-terminal-worker.mjs"); + const { buildTerminalWorkerBundle } = (await import(buildScript)) as { + buildTerminalWorkerBundle(input: { outDir: string }): Promise; + }; + await buildTerminalWorkerBundle({ outDir: bundleDirectory }); + const nodePtyDirectory = path.dirname( + createRequire(import.meta.url).resolve("node-pty/package.json"), + ); + const entry = prepareTerminalWorkerRuntime({ + paseoHome: home, + paseoVersion: "0.0.0-copy", + bundleDirectory, + nodePtyDirectory, + }); + + const launched = await launchTerminalWorker({ + paseoHome: home, + paseoVersion: "0.0.0-copy", + entry, + }); + extraPids.add(launched.record.pid); + expect(launched.record.runtime).toBe(entry.runtime); + const manager = createWorkerTerminalManager({ + worker: await connectTerminalWorker({ + socketPath: launched.record.socketPath, + secret: launched.record.secret, + }), + closeTerminals: async () => { + await reapTerminalWorkers({ paseoHome: home }); + }, + }); + try { + const session = await manager.createTerminal({ + workspaceId: "ws-copy", + cwd: home, + command: process.execPath, + args: ["-e", "console.log('COPY-' + 'OK'); setInterval(() => {}, 1000);"], + }); + await waitFor( + async () => + (await manager.captureTerminal(session.id, { stripAnsi: true })).lines + .join("\n") + .includes("COPY-OK"), + "the terminal in the copied worker never printed its marker", + 30_000, + ); + } finally { + await manager.closeTerminals(); + } + expect(isAlive(launched.record.pid)).toBe(false); + expect(existsSync(path.dirname(entry.scriptPath))).toBe(false); + }); +}); diff --git a/packages/server/src/server/daemon-instance.ts b/packages/server/src/server/daemon-instance.ts index 02f4446795..b3b07e7ff0 100644 --- a/packages/server/src/server/daemon-instance.ts +++ b/packages/server/src/server/daemon-instance.ts @@ -11,6 +11,7 @@ import { } from "./pid-lock.js"; import { daemonLaunchEnvironment } from "./config-environment.js"; import { readPersistedConfig } from "./persisted-config.js"; +import { reapTerminalWorkers } from "../terminal/terminal-worker-reaper.js"; import treeKill from "tree-kill"; const killTree = (pid: number, signal: string): Promise => new Promise((resolve, reject) => @@ -29,6 +30,10 @@ export { resolvePaseoHome } from "./paseo-home.js"; export { ensurePrivateDirectory } from "./private-files.js"; export { daemonLaunchEnvironment } from "./config-environment.js"; export { readLocalCredentialForTarget } from "./local-credential.js"; +export { + TerminalCleanupNotConfirmedError, + retryUnconfirmedTerminalCleanup, +} from "../terminal/terminal-worker-reaper.js"; export { isSamePidLock as isSameDaemonInstance, type PidLockInfo as DaemonInstance, @@ -97,11 +102,23 @@ async function requestInstanceStop( instance: PidLockInfo, options: { force?: boolean; + keepTerminals?: boolean; requestShutdown?: (instance: PidLockInfo & { listen: string }) => Promise; }, ) { let forced = false; let usedLifecycleRpc = false; + if (options.keepTerminals) { + // SIGTERM means "stop and close terminals"; keeping them always goes over the RPC. + if (!instance.listen || !options.requestShutdown) { + throw new DaemonInstanceError( + "STOP_NO_GRACEFUL_CHANNEL", + `PID ${instance.pid} for ${home} has no listen address, so it cannot be asked to keep its terminals.`, + ); + } + await options.requestShutdown({ ...instance, listen: instance.listen }); + return { forced, usedLifecycleRpc: true }; + } if (process.platform === "win32") { if (instance.listen && options.requestShutdown) { try { @@ -142,6 +159,8 @@ export async function stopDaemonInstance( options: { instance?: PidLockInfo; force?: boolean; + // Leave the terminal worker running so the next daemon adopts it. Not valid with force. + keepTerminals?: boolean; timeoutMs?: number; killTimeoutMs?: number; requestShutdown?: (instance: PidLockInfo & { listen: string }) => Promise; @@ -153,6 +172,7 @@ export async function stopDaemonInstance( usedLifecycleRpc: boolean; }> { const { timeoutMs = 15_000, killTimeoutMs = 3_000 } = options; + assertStopOptions(options); const deadline = Date.now() + timeoutMs; const instance = await getPidLockInfo(home); if (options.instance && instance && !isSamePidLock(instance, options.instance)) { @@ -164,6 +184,9 @@ export async function stopDaemonInstance( if (!instance || !isPidLockOwnerRunning(instance)) { if (instance) await releasePidLock(home, { ownerPid: instance.pid, startedAt: instance.startedAt }); + // Terminals a `stop --keep-terminals` left behind belong to no daemon now; a plain stop + // closes them. + await closeLeftoverTerminals(home, { keepTerminals: options.keepTerminals, forced: false }); return { action: "not_running", pid: instance?.pid ?? null, @@ -200,9 +223,29 @@ export async function stopDaemonInstance( `Timed out waiting for supervisor PID ${instance.pid} in ${home} to exit${options.force ? "" : "; use --force to permit forced cleanup"}.`, ); await releasePidLock(home, { ownerPid: instance.pid, startedAt: instance.startedAt }); + // The supervisor already closed the terminals unless it was killed; this confirms it, and + // after --force (no graceful shutdown happened) does it at once. + await closeLeftoverTerminals(home, { keepTerminals: options.keepTerminals, forced }); return { action: "stopped", pid: instance.pid, forced, usedLifecycleRpc }; } +function assertStopOptions(options: { force?: boolean; keepTerminals?: boolean }): void { + if (options.force && options.keepTerminals) { + throw new DaemonInstanceError( + "INVALID_STOP_OPTIONS", + "--force kills terminals; it cannot be combined with --keep-terminals.", + ); + } +} + +async function closeLeftoverTerminals( + home: string, + options: { keepTerminals?: boolean; forced: boolean }, +): Promise { + if (options.keepTerminals) return; + await reapTerminalWorkers({ paseoHome: home, gracefulMs: options.forced ? 0 : undefined }); +} + export async function startDaemonInstance(input: { home: string; command: string; diff --git a/packages/server/src/server/daemon-worker.ts b/packages/server/src/server/daemon-worker.ts index bc5acbc404..317903a592 100644 --- a/packages/server/src/server/daemon-worker.ts +++ b/packages/server/src/server/daemon-worker.ts @@ -13,6 +13,7 @@ type SupervisorLifecycleMessage = | { type: "paseo:shutdown"; reason: string; + keepTerminals: boolean; } | { type: "paseo:ready"; @@ -22,6 +23,7 @@ type SupervisorLifecycleMessage = | { type: "paseo:restart"; reason?: string; + keepTerminals: boolean; }; interface BootstrapResult { @@ -151,12 +153,15 @@ async function main() { options?: { reason?: string; successExitCode?: number; + keepTerminals?: boolean; }, ) => { const reason = options?.reason ?? `worker_received_${signal}`; + // Signals mean "stop and close terminals"; only an explicit keep request keeps them. + const keepTerminals = options?.keepTerminals === true; if (!shutdownPromise) { logger.info( - { signal, reason, ...getProcessDiagnostics() }, + { signal, reason, keepTerminals, ...getProcessDiagnostics() }, `${signal} received, shutting down gracefully...`, ); @@ -175,7 +180,7 @@ async function main() { clearTimeout(forceExit); return 1; } - await daemon.stop(); + await daemon.stop({ keepTerminals }); clearTimeout(forceExit); logger.info("Server closed"); return options?.successExitCode ?? 0; @@ -209,36 +214,53 @@ async function main() { }; const handleLifecycleIntent = (intent: DaemonLifecycleIntent) => { + const fields = { + clientId: intent.clientId, + requestId: intent.requestId, + reason: intent.reason, + keepTerminals: intent.keepTerminals, + }; if (intent.type === "shutdown") { - logger.warn( - { clientId: intent.clientId, requestId: intent.requestId, reason: intent.reason }, - "Shutdown requested via websocket", - ); - if (sendSupervisorLifecycleMessage({ type: "paseo:shutdown", reason: intent.reason })) { + logger.warn(fields, "Shutdown requested via websocket"); + const sent = sendSupervisorLifecycleMessage({ + type: "paseo:shutdown", + reason: intent.reason, + keepTerminals: intent.keepTerminals, + }); + recordLifecycleIntentDispatched(intent.type, fields); + if (sent) { return; } - beginShutdown("shutdown lifecycle intent", { reason: intent.reason }); + beginShutdown("shutdown lifecycle intent", { + reason: intent.reason, + keepTerminals: intent.keepTerminals, + }); return; } - logger.warn( - { clientId: intent.clientId, requestId: intent.requestId, reason: intent.reason }, - "Restart requested via websocket", - ); - if ( - sendSupervisorLifecycleMessage({ - type: "paseo:restart", - ...(intent.reason ? { reason: intent.reason } : {}), - }) - ) { + logger.warn(fields, "Restart requested via websocket"); + const sent = sendSupervisorLifecycleMessage({ + type: "paseo:restart", + ...(intent.reason ? { reason: intent.reason } : {}), + keepTerminals: intent.keepTerminals, + }); + recordLifecycleIntentDispatched(intent.type, fields); + if (sent) { return; } beginShutdown("restart lifecycle intent", { reason: intent.reason, successExitCode: 0, + keepTerminals: intent.keepTerminals, }); }; + // Written straight to daemon.log: the pino stream goes through the supervisor's pipe, which + // a paused or busy supervisor does not drain. Tests synchronize on this line. + const recordLifecycleIntentDispatched = (type: string, fields: Record) => { + writeWorkerLifecycleLog(paseoHome, "Lifecycle intent dispatched", { type, ...fields }); + }; + const installSupervisorLivenessGuard = () => { if (typeof process.send !== "function") { return; @@ -278,9 +300,10 @@ async function main() { return; } if (type === "paseo:graceful-shutdown") { - const reason = (message as { reason?: unknown }).reason; + const { reason, keepTerminals } = message as { reason?: unknown; keepTerminals?: unknown }; beginShutdown("Supervisor shutdown request", { reason: typeof reason === "string" ? reason : "supervisor_requested_shutdown", + keepTerminals: keepTerminals === true, }); } }); diff --git a/packages/server/src/server/managed-processes/managed-processes.test.ts b/packages/server/src/server/managed-processes/managed-processes.test.ts index e247db027f..b4be4d16bd 100644 --- a/packages/server/src/server/managed-processes/managed-processes.test.ts +++ b/packages/server/src/server/managed-processes/managed-processes.test.ts @@ -12,6 +12,7 @@ import { type ManagedProcessInspection, type ManagedProcessSnapshot, type ManagedProcessTable, + windowsPowerShellPath, } from "./managed-processes.js"; import { spawnProcess } from "../../utils/spawn.js"; import { @@ -333,7 +334,7 @@ describe("system managed process table", () => { }); expect(commandRunner.commands).toEqual([ { - command: "powershell.exe", + command: windowsPowerShellPath(), args: [ "-NoProfile", "-NonInteractive", @@ -345,6 +346,17 @@ describe("system managed process table", () => { }); }); +describe("windowsPowerShellPath", () => { + test("names Windows PowerShell under SystemRoot, whatever PATH holds", () => { + expect(windowsPowerShellPath({ SystemRoot: "D:\\Win", PATH: "" })).toBe( + "D:\\Win\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", + ); + expect(windowsPowerShellPath({})).toBe( + "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", + ); + }); +}); + class FakeProcessTable implements ManagedProcessTable { private readonly snapshots: Map; private readonly errorPids: Set; diff --git a/packages/server/src/server/managed-processes/managed-processes.ts b/packages/server/src/server/managed-processes/managed-processes.ts index 0031080c67..43c1b3c810 100644 --- a/packages/server/src/server/managed-processes/managed-processes.ts +++ b/packages/server/src/server/managed-processes/managed-processes.ts @@ -7,6 +7,20 @@ import { writeJsonFileAtomic } from "../atomic-file.js"; import { execCommand } from "../../utils/spawn.js"; import type { ProcessTerminator, TreeKillTarget } from "../../utils/tree-kill.js"; +/** + * Windows PowerShell by its install path. Process identity must not depend on the caller's + * PATH: a daemon or terminal worker can run with a PATH that does not reach System32. + */ +export function windowsPowerShellPath(env: NodeJS.ProcessEnv = process.env): string { + return path.win32.join( + env.SystemRoot ?? env.SYSTEMROOT ?? "C:\\Windows", + "System32", + "WindowsPowerShell", + "v1.0", + "powershell.exe", + ); +} + const MANAGED_PROCESS_GRACEFUL_SHUTDOWN_TIMEOUT_MS = 5_000; const MANAGED_PROCESS_FORCE_SHUTDOWN_TIMEOUT_MS = 1_000; const MANAGED_PROCESS_EXIT_POLL_INTERVAL_MS = 50; @@ -183,7 +197,7 @@ class SystemManagedProcessTable implements ManagedProcessTable { `$process = Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}';`, "if ($process) { $process | Select-Object ProcessId,CommandLine,CreationDate | ConvertTo-Json -Compress }", ].join(" "); - const { stdout } = await this.commandRunner.exec("powershell.exe", [ + const { stdout } = await this.commandRunner.exec(windowsPowerShellPath(), [ "-NoProfile", "-NonInteractive", "-Command", diff --git a/packages/server/src/server/pid-lock.ts b/packages/server/src/server/pid-lock.ts index 314b44ea47..6f3e7135d9 100644 --- a/packages/server/src/server/pid-lock.ts +++ b/packages/server/src/server/pid-lock.ts @@ -30,13 +30,16 @@ function isErrnoException(err: unknown): err is NodeJS.ErrnoException { return err instanceof Error && "code" in err; } +// The field is assigned explicitly rather than declared as a constructor parameter property: +// the terminal worker loads this module under --experimental-strip-types, which cannot emit +// the assignment a parameter property implies. export class PidLockError extends Error { - constructor( - message: string, - public readonly existingLock?: PidLockInfo, - ) { + readonly existingLock?: PidLockInfo; + + constructor(message: string, existingLock?: PidLockInfo) { super(message); this.name = "PidLockError"; + this.existingLock = existingLock; } } @@ -69,7 +72,7 @@ let cachedBootId: string | null | undefined; // Linux names each boot. The wall-clock boot instant is not enough there: a VM paused while // its host sleeps keeps its uptime, so after it resumes the instant lands after locks its // running supervisor wrote. -function currentBootId(): string | null { +export function currentBootId(): string | null { if (cachedBootId === undefined) { try { cachedBootId = readFileSync("/proc/sys/kernel/random/boot_id", "utf-8").trim() || null; @@ -80,10 +83,17 @@ function currentBootId(): string | null { return cachedBootId; } -function writtenDuringThisBoot(lock: PidLockInfo): boolean { +/** + * Whether a record stamped with `startedAt` (and, on Linux, `bootId`) was written during the + * current boot. Daemon locks and terminal worker records share this rule. + */ +export function writtenDuringThisBoot(stamp: { + startedAt: string; + bootId?: string | null; +}): boolean { const thisBoot = currentBootId(); - if (lock.bootId && thisBoot) return lock.bootId === thisBoot; - return !precedesThisBoot(lock.startedAt); + if (stamp.bootId && thisBoot) return stamp.bootId === thisBoot; + return !precedesThisBoot(stamp.startedAt); } /** diff --git a/packages/server/src/server/plugins/index.posix.test.ts b/packages/server/src/server/plugins/index.posix.test.ts index 4ca5aeefd5..17f25fce3b 100644 --- a/packages/server/src/server/plugins/index.posix.test.ts +++ b/packages/server/src/server/plugins/index.posix.test.ts @@ -15,7 +15,7 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { pathToFileURL } from "node:url"; import pino from "pino"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, beforeAll, describe, expect, it } from "vitest"; import { DaemonConfigStore } from "../daemon-config-store.js"; import { PluginService } from "./index.js"; import { BuiltinPluginLoader } from "./builtin/index.js"; @@ -1321,7 +1321,11 @@ export default function contribute(plugin: unknown) { }); describe("npm plugin installation", () => { - it("preserves dependencies and metadata, and reloads without npm", async () => { + let registry: Awaited>; + + // Packing the registry starts eleven real npm processes. Give fixture construction its + // own setup budget so Windows process startup does not consume the installation journey. + beforeAll(async () => { const packages = npmPluginPackages(); const fixture = packages[1]; packages.push({ ...fixture, version: "2.0.0", tags: ["future"] }); @@ -1356,7 +1360,7 @@ describe("npm plugin installation", () => { for (const [name, overrides] of failures) { failedPackages.push({ ...fixture, name, files: { ...fixture.files, ...overrides } }); } - const registry = await startNpmRegistry([ + registry = await startNpmRegistry([ ...packages, { name: "paseo-prepared-plugin", @@ -1386,6 +1390,9 @@ export default function contribute() { }, ...failedPackages, ]); + }, 120_000); + + it("preserves dependencies and metadata, and reloads without npm", async () => { const home = await mkdtemp(path.join(tmpdir(), "paseo-npm-service-")); roots.push(home); const previousConfig = process.env.npm_config_userconfig; diff --git a/packages/server/src/server/session.test.ts b/packages/server/src/server/session.test.ts index 3cdef95a83..d1408f9880 100644 --- a/packages/server/src/server/session.test.ts +++ b/packages/server/src/server/session.test.ts @@ -8,7 +8,15 @@ import { createTestCreationService, } from "./test-utils/session-stubs.js"; import { execSync } from "child_process"; -import { existsSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "fs"; +import { + existsSync, + mkdirSync, + mkdtempSync, + realpathSync, + rmSync, + symlinkSync, + writeFileSync, +} from "fs"; import { tmpdir } from "os"; import { join, resolve as resolvePath } from "path"; import pino from "pino"; @@ -28,6 +36,11 @@ import { type FileTransferFrame, } from "@getpaseo/protocol/binary-frames/index"; import { Session } from "./session.js"; +import { + terminalCleanupRecordPath, + terminalWorkerDirectory, + writeTerminalCleanupRecord, +} from "../terminal/terminal-worker-record.js"; import { OWNER_PERMISSIONS, type DaemonPermission } from "./authorization/index.js"; import { DownloadTokenStore } from "./file-download/token-store.js"; import { StructuredAgentFallbackError } from "./agent/agent-response-loop.js"; @@ -2071,11 +2084,84 @@ describe("daemon status + pairing RPC", () => { { provider: "claude", available: true, error: null }, { provider: "codex", available: false, error: "boom" }, ], + terminalCleanupUnconfirmed: [], }, }, ]); }); + test("daemon.get_status.request reports what a terminal cleanup could not confirm gone", async () => { + const messages: unknown[] = []; + const paseoHome = makeHome(); + const unresolved = { + pid: 4242, + role: "terminal program" as const, + reason: "still alive" as const, + detail: "survived SIGKILL", + }; + await writeTerminalCleanupRecord(paseoHome, { + recordId: "closing-record", + pid: 4241, + bootId: null, + createdAt: new Date().toISOString(), + identity: { startedAt: "Thu Jan 1 00:00:00 1970", commandLine: "worker" }, + protocolVersion: 1, + paseoVersion: "0.0.0-test", + socketPath: join(paseoHome, "closing.sock"), + secret: "closing-secret", + terminals: [{ id: "t1", pid: 4242, startedAt: "Thu Jan 1 00:00:00 1970" }], + closing: { unresolved: [unresolved] }, + }); + const session = createSessionForTest({ + messages, + paseoHome, + serverId: "srv-test", + daemonVersion: "9.9.9", + daemonRuntimeConfig: { listen: "127.0.0.1:6767", getRelayConfig: () => null }, + agentManager: { listProviderAvailability: vi.fn().mockResolvedValue([]) }, + }); + + await session.handleMessage({ type: "daemon.get_status.request", requestId: "status-2" }); + + expect(messages).toEqual([ + expect.objectContaining({ + type: "daemon.get_status.response", + payload: expect.objectContaining({ terminalCleanupUnconfirmed: [unresolved] }), + }), + ]); + }); + + test("daemon.get_status.request fails when a terminal cleanup record cannot be read", async () => { + const messages: unknown[] = []; + const paseoHome = makeHome(); + mkdirSync(terminalWorkerDirectory(paseoHome), { recursive: true }); + const cleanupPath = terminalCleanupRecordPath(paseoHome, "closing-record"); + writeFileSync(cleanupPath, "{ not json"); + const session = createSessionForTest({ + messages, + paseoHome, + serverId: "srv-test", + daemonVersion: "9.9.9", + daemonRuntimeConfig: { listen: "127.0.0.1:6767", getRelayConfig: () => null }, + agentManager: { listProviderAvailability: vi.fn().mockResolvedValue([]) }, + }); + + await session.handleMessage({ type: "daemon.get_status.request", requestId: "status-3" }); + + expect(messages).toContainEqual( + expect.objectContaining({ + type: "rpc_error", + payload: expect.objectContaining({ + requestId: "status-3", + error: expect.stringContaining(cleanupPath), + }), + }), + ); + expect(messages).not.toContainEqual( + expect.objectContaining({ type: "daemon.get_status.response" }), + ); + }); + test("daemon.get_status.request falls back to a null/empty status when provider listing fails", async () => { const messages: unknown[] = []; const session = createSessionForTest({ @@ -2107,6 +2193,7 @@ describe("daemon status + pairing RPC", () => { listen: null, relay: null, providers: [], + terminalCleanupUnconfirmed: [], }, }, ]); diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index 2ff8e917ab..3eac37cb7b 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -577,12 +577,14 @@ export type SessionLifecycleIntent = clientId: string; requestId: string; reason: string; + keepTerminals: boolean; } | { type: "restart"; clientId: string; requestId: string; reason: string; + keepTerminals: boolean; }; function parseClientCapabilities( @@ -1105,6 +1107,7 @@ export class Session { "Terminal output": this.terminalController.getMetrics().streamSubscriptionCount, }), listProviderAvailability: () => this.agentManager.listProviderAvailability(), + getTerminalsUnavailable: () => terminalManager?.getUnavailableError?.()?.message ?? null, listAgents: () => this.agentManager.listAgents(), listProjects: () => this.projectRegistry.list(), listWorkspaces: () => this.workspaceRegistry.list(), @@ -2728,9 +2731,13 @@ export class Session { case "dictation_stream_cancel": return this.voiceSessions.handleMessage(msg); case "restart_server_request": - return this.handleRestartServerRequest(msg.requestId, msg.reason); + return this.handleRestartServerRequest(msg.requestId, msg.reason, { + keepTerminals: msg.killTerminals !== true, + }); case "shutdown_server_request": - return this.handleShutdownServerRequest(msg.requestId); + return this.handleShutdownServerRequest(msg.requestId, { + keepTerminals: msg.keepTerminals === true, + }); case "client_heartbeat": this.handleClientHeartbeat(msg); return undefined; @@ -3256,7 +3263,11 @@ export class Session { this.terminalController.handleBinaryFrame(binaryFrame.frame, source); } - private async handleRestartServerRequest(requestId: string, reason?: string): Promise { + private async handleRestartServerRequest( + requestId: string, + reason: string | undefined, + options: { keepTerminals: boolean }, + ): Promise { const lifecycleReason = normalizeClientRestartRpcReason(reason); const payload: { status: string } & Record = { status: "restart_requested", @@ -3267,7 +3278,10 @@ export class Session { } payload.requestId = requestId; - this.sessionLogger.warn({ reason: lifecycleReason }, "Restart requested via websocket"); + this.sessionLogger.warn( + { reason: lifecycleReason, keepTerminals: options.keepTerminals }, + "Restart requested via websocket", + ); this.emit({ type: "status", payload, @@ -3278,12 +3292,19 @@ export class Session { clientId: this.clientId, requestId, reason: lifecycleReason, + keepTerminals: options.keepTerminals, }); } - private async handleShutdownServerRequest(requestId: string): Promise { + private async handleShutdownServerRequest( + requestId: string, + options: { keepTerminals: boolean }, + ): Promise { const reason = CLIENT_SHUTDOWN_RPC_REASON; - this.sessionLogger.warn({ reason }, "Shutdown requested via websocket"); + this.sessionLogger.warn( + { reason, keepTerminals: options.keepTerminals }, + "Shutdown requested via websocket", + ); this.emit({ type: "status", payload: { @@ -3298,6 +3319,7 @@ export class Session { clientId: this.clientId, requestId, reason, + keepTerminals: options.keepTerminals, }); } diff --git a/packages/server/src/server/session/daemon/daemon-self-update-session-controller.test.ts b/packages/server/src/server/session/daemon/daemon-self-update-session-controller.test.ts index 81c41f3421..e9bcf94b65 100644 --- a/packages/server/src/server/session/daemon/daemon-self-update-session-controller.test.ts +++ b/packages/server/src/server/session/daemon/daemon-self-update-session-controller.test.ts @@ -118,6 +118,7 @@ describe("DaemonSelfUpdateSessionController", () => { clientId: "client-1", requestId: "update-1", reason: "daemon_update", + keepTerminals: true, }, ]); }); diff --git a/packages/server/src/server/session/daemon/daemon-self-update-session-controller.ts b/packages/server/src/server/session/daemon/daemon-self-update-session-controller.ts index 461a97277b..bb75f008bd 100644 --- a/packages/server/src/server/session/daemon/daemon-self-update-session-controller.ts +++ b/packages/server/src/server/session/daemon/daemon-self-update-session-controller.ts @@ -19,6 +19,7 @@ interface DaemonSelfUpdateRestartIntent { clientId: string; requestId: string; reason: string; + keepTerminals: boolean; } export interface DaemonSelfUpdateSessionControllerOptions { @@ -88,6 +89,8 @@ export class DaemonSelfUpdateSessionController { clientId: this.clientId, requestId: msg.requestId, reason: "daemon_update", + // A self-update restart keeps terminals: the worker outlives the daemon. + keepTerminals: true, }); } catch (error) { if (error instanceof DaemonSelfUpdateInProgressError) { diff --git a/packages/server/src/server/session/daemon/daemon-session.test.ts b/packages/server/src/server/session/daemon/daemon-session.test.ts index e96256c4cf..cb6da8777b 100644 --- a/packages/server/src/server/session/daemon/daemon-session.test.ts +++ b/packages/server/src/server/session/daemon/daemon-session.test.ts @@ -212,6 +212,7 @@ describe("DaemonSession", () => { { provider: "claude", available: true, error: null }, { provider: "codex", available: false, error: "boom" }, ], + terminalCleanupUnconfirmed: [], }, }, ]); @@ -242,6 +243,7 @@ describe("DaemonSession", () => { listen: null, relay: null, providers: [], + terminalCleanupUnconfirmed: [], }, }, ]); diff --git a/packages/server/src/server/session/daemon/daemon-session.ts b/packages/server/src/server/session/daemon/daemon-session.ts index ccc9e66e6d..585fa45573 100644 --- a/packages/server/src/server/session/daemon/daemon-session.ts +++ b/packages/server/src/server/session/daemon/daemon-session.ts @@ -2,6 +2,7 @@ import type pino from "pino"; import type { ProviderAvailability } from "../../agent/agent-manager.js"; import type { SessionInboundMessage, SessionOutboundMessage } from "../../messages.js"; import { getPidLockInfo } from "../../pid-lock.js"; +import { readUnconfirmedTerminalCleanup } from "../../../terminal/terminal-worker-reaper.js"; import { generateLocalPairingOffer } from "../../pairing-offer.js"; import { collectDaemonDiagnostics, @@ -35,6 +36,7 @@ export interface DaemonSessionHost { clientId: string; requestId: string; reason: string; + keepTerminals: boolean; }): void; } @@ -49,6 +51,8 @@ export interface DaemonSessionOptions { listProjects: () => Promise; listWorkspaces: () => Promise; listProviderAvailability: () => Promise; + /** Why this host's terminals cannot be served (held by a newer Paseo's worker), if so. */ + getTerminalsUnavailable?: () => string | null; getWebSocketRuntimeMetrics?: () => DaemonWebSocketRuntimeDiagnosticSnapshot | null; getObservationMetrics?: () => Record; logger: pino.Logger; @@ -74,6 +78,7 @@ export class DaemonSession { private readonly listProjects: () => Promise; private readonly listWorkspaces: () => Promise; private readonly listProviderAvailability: () => Promise; + private readonly getTerminalsUnavailable: () => string | null; private readonly getWebSocketRuntimeMetrics: () => DaemonWebSocketRuntimeDiagnosticSnapshot | null; private readonly getObservationMetrics: DaemonSessionOptions["getObservationMetrics"]; private readonly logger: pino.Logger; @@ -92,6 +97,7 @@ export class DaemonSession { this.listProjects = options.listProjects; this.listWorkspaces = options.listWorkspaces; this.listProviderAvailability = options.listProviderAvailability; + this.getTerminalsUnavailable = options.getTerminalsUnavailable ?? (() => null); this.getWebSocketRuntimeMetrics = options.getWebSocketRuntimeMetrics ?? (() => null); this.getObservationMetrics = options.getObservationMetrics; this.logger = options.logger; @@ -173,6 +179,12 @@ export class DaemonSession { async handleGetStatusRequest( msg: Extract, ): Promise { + // Read outside the degraded-status fallback below: a status that cannot say whether + // terminal cleanup finished must fail the request, not report that nothing is left. + const terminalCleanupUnconfirmed = (await readUnconfirmedTerminalCleanup(this.paseoHome)).map( + ({ pid, role, reason, detail }) => ({ pid, role, reason, detail }), + ); + const terminalsUnavailable = this.getTerminalsUnavailable(); try { const pidInfo = await getPidLockInfo(this.paseoHome); const providers = (await this.listProviderAvailability()).map((p) => ({ @@ -192,6 +204,8 @@ export class DaemonSession { listen: this.daemonRuntimeConfig?.listen ?? null, relay: this.daemonRuntimeConfig?.getRelayConfig() ?? null, providers, + terminalCleanupUnconfirmed, + ...(terminalsUnavailable ? { terminalsUnavailable } : {}), }, }); } catch (error) { @@ -208,6 +222,8 @@ export class DaemonSession { listen: null, relay: null, providers: [], + terminalCleanupUnconfirmed, + ...(terminalsUnavailable ? { terminalsUnavailable } : {}), }, }); } diff --git a/packages/server/src/server/test-utils/paseo-daemon.test.ts b/packages/server/src/server/test-utils/paseo-daemon.test.ts index 4ee417c221..3fbb0b5232 100644 --- a/packages/server/src/server/test-utils/paseo-daemon.test.ts +++ b/packages/server/src/server/test-utils/paseo-daemon.test.ts @@ -45,7 +45,15 @@ describe("createTestPaseoDaemon", () => { createTestPaseoDaemon({ listenPort: takenPort, cleanup: false, mcpEnabled: false }), ).rejects.toMatchObject({ code: "EADDRINUSE" }); - expect(await readdir(scratchTmp)).toEqual([]); + // A home under this scratch dir is too long for a unix socket path, so the terminal worker + // listens in the per-user `paseo-` directory of the temp root. Like tmux's, that + // owner-only directory is shared by every worker and outlives them; it must be empty. + const sharedSocketDir = `paseo-${process.getuid?.() ?? 0}`; + const leftovers = await readdir(scratchTmp); + expect(leftovers.filter((name) => name !== sharedSocketDir)).toEqual([]); + if (leftovers.includes(sharedSocketDir)) { + expect(await readdir(path.join(scratchTmp, sharedSocketDir))).toEqual([]); + } }, 60_000); }); diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index dfa324315c..6705c1cdd9 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -2054,6 +2054,8 @@ export class VoiceAssistantWebSocketServer { daemonDiagnostics: true, // COMPAT(daemonSelfUpdate): added in v0.1.93, remove gate after 2026-12-13. daemonSelfUpdate: this.daemonRuntimeConfig?.desktopManaged !== true, + // COMPAT(terminalsSurviveRestart): added in v0.12.0, remove gate after 2027-04-21. + terminalsSurviveRestart: true, // COMPAT(agentForkContext): added in v0.1.102, remove gate after 2026-12-28. agentForkContext: true, // COMPAT(agentForkContextCursor): added in v0.1.108, remove gate after 2027-01-14. diff --git a/packages/server/src/server/workspace-git-service.test.ts b/packages/server/src/server/workspace-git-service.test.ts index b3fab7b89a..f3571f9932 100644 --- a/packages/server/src/server/workspace-git-service.test.ts +++ b/packages/server/src/server/workspace-git-service.test.ts @@ -796,17 +796,21 @@ describe("WorkspaceGitServiceImpl", () => { const service = createService({ getCheckoutStatus, subscribe, runGitCommand }); cwds.forEach((cwd) => service.registerWorkspace({ cwd }, vi.fn())); - await vi.waitFor(() => { - // Admission precedes async path resolution; disposal must race pending subscriptions. - expect(subscribe).toHaveBeenCalledTimes(WORKSPACE_GIT_OBSERVATION_SETUP_CONCURRENCY); - expect(service.getMetrics()).toMatchObject({ - workspaceRefreshAdmissionActiveCount: WORKSPACE_GIT_REFRESH_CONCURRENCY, - workspaceRefreshAdmissionPendingCount: 1, - workspaceObservationSetupAdmissionActiveCount: WORKSPACE_GIT_OBSERVATION_SETUP_CONCURRENCY, - workspaceObservationSetupAdmissionPendingCount: - cwds.length - WORKSPACE_GIT_OBSERVATION_SETUP_CONCURRENCY, - }); - }); + await vi.waitFor( + () => { + expect(service.getMetrics()).toMatchObject({ + workspaceRefreshAdmissionActiveCount: WORKSPACE_GIT_REFRESH_CONCURRENCY, + workspaceRefreshAdmissionPendingCount: 1, + workspaceObservationSetupAdmissionActiveCount: + WORKSPACE_GIT_OBSERVATION_SETUP_CONCURRENCY, + workspaceObservationSetupAdmissionPendingCount: + cwds.length - WORKSPACE_GIT_OBSERVATION_SETUP_CONCURRENCY, + }); + // Admission precedes asynchronous path setup; dispose only once watchers are pending. + expect(subscribe).toHaveBeenCalledTimes(WORKSPACE_GIT_OBSERVATION_SETUP_CONCURRENCY); + }, + { timeout: 10_000 }, + ); const queuedRefreshSettlement = service.getSnapshot(cwds.at(-1)!).then( () => ({ status: "fulfilled" as const, error: null }), (error: unknown) => ({ status: "rejected" as const, error }), diff --git a/packages/server/src/terminal/paseo-cli-path.ts b/packages/server/src/terminal/paseo-cli-path.ts new file mode 100644 index 0000000000..18dff56f1b --- /dev/null +++ b/packages/server/src/terminal/paseo-cli-path.ts @@ -0,0 +1,83 @@ +import { existsSync } from "node:fs"; +import { createRequire } from "node:module"; +import { dirname, join, resolve as resolvePath } from "node:path"; + +// Where the Paseo CLI lives, for the PATH entry and PASEO_HOOK_CLI every terminal gets. Kept +// apart from terminal.ts so the daemon can resolve it without loading node-pty. + +const require = createRequire(import.meta.url); +const PASEO_CLI_BIN_ENTRY = "@getpaseo/cli/bin/paseo"; + +export function resolveExternalProcessPath(filePath: string): string { + return filePath.replace(/\.asar(?=[/\\]|$)/, ".asar.unpacked"); +} + +export function resolvePaseoCliBinDir(): string | null { + const cliExecutable = resolvePaseoCliExecutablePath(); + return cliExecutable ? dirname(cliExecutable) : null; +} + +export function resolvePaseoCliExecutablePath(): string | null { + const configuredCli = process.env.PASEO_CLI?.trim(); + if (configuredCli) { + return resolvePath(configuredCli); + } + + const cliEntrypoint = resolvePaseoCliBinEntrypoint(); + if (!cliEntrypoint) { + return null; + } + + const externalCliEntrypoint = resolveExternalProcessPath(cliEntrypoint); + const npmBinDir = findNpmBinDir(dirname(externalCliEntrypoint)); + if (npmBinDir) { + const shim = resolvePaseoCliShim(npmBinDir); + if (shim) { + return shim; + } + } + + return externalCliEntrypoint; +} + +function resolvePaseoCliBinEntrypoint(): string | null { + try { + return require.resolve(PASEO_CLI_BIN_ENTRY); + } catch { + return null; + } +} + +function findNpmBinDir(startPath: string): string | null { + let current = startPath; + while (true) { + const candidate = join(current, "node_modules", ".bin"); + if (hasPaseoCliShim(candidate)) { + return candidate; + } + + const parent = dirname(current); + if (parent === current) { + return null; + } + current = parent; + } +} + +function hasPaseoCliShim(binDir: string): boolean { + return resolvePaseoCliShim(binDir) !== null; +} + +function resolvePaseoCliShim(binDir: string): string | null { + for (const name of paseoCliShimNames()) { + const candidate = join(binDir, name); + if (existsSync(candidate)) { + return candidate; + } + } + return null; +} + +function paseoCliShimNames(): string[] { + return process.platform === "win32" ? ["paseo.cmd", "paseo.exe", "paseo"] : ["paseo"]; +} diff --git a/packages/server/src/terminal/terminal-manager-factory.ts b/packages/server/src/terminal/terminal-manager-factory.ts deleted file mode 100644 index 88dcc2d692..0000000000 --- a/packages/server/src/terminal/terminal-manager-factory.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { TerminalManager } from "./terminal-manager.js"; -import { createWorkerTerminalManager } from "./worker-terminal-manager.js"; - -export interface ConfiguredTerminalManagerOptions { - getTerminalActivityUrl?: () => string | null; -} - -export function createConfiguredTerminalManager( - options: ConfiguredTerminalManagerOptions = {}, -): TerminalManager { - return createWorkerTerminalManager(options); -} diff --git a/packages/server/src/terminal/terminal-manager.ts b/packages/server/src/terminal/terminal-manager.ts index df4ced389b..86b4cdb662 100644 --- a/packages/server/src/terminal/terminal-manager.ts +++ b/packages/server/src/terminal/terminal-manager.ts @@ -1,5 +1,6 @@ import { createTerminal, + type LocalTerminalSession, type TerminalActivityTransition, type TerminalSession, type TerminalStateSnapshot, @@ -50,6 +51,11 @@ export type TerminalWorkspaceContributionChangedListener = ( ) => void; export interface TerminalManager { + /** + * Set when this host's terminals cannot be served at all (a worker from a newer Paseo holds + * them). Callers that answer terminal requests report it instead of an empty list. + */ + getUnavailableError?(): Error | null; getTerminals(cwd: string, options?: { workspaceId?: string }): Promise; createTerminal(options: { id?: string; @@ -64,6 +70,8 @@ export interface TerminalManager { cols?: number; activityToken?: string; activityUrl?: string | null; + baseEnv?: Record; + paseoCliPath?: string | null; }): Promise; registerCwdEnv(options: { cwd: string; env: Record }): void; validateTerminalActivityToken(terminalId: string, token: string): "valid" | "unknown" | "invalid"; @@ -97,15 +105,21 @@ export interface TerminalManagerOptions { getTerminalActivityUrl?: () => string | null; } +/** The in-process manager the terminal worker runs: it owns each PTY, so it knows its pid. */ +export interface LocalTerminalManager extends TerminalManager { + getTerminalProcessId(id: string): number | null; + getTerminalActivityToken(id: string): string | null; +} + function createActivityToken(): string { return randomBytes(32).toString("base64url"); } export function createTerminalManager( managerOptions: TerminalManagerOptions = {}, -): TerminalManager { +): LocalTerminalManager { const terminalsByCwd = new Map(); - const terminalsById = new Map(); + const terminalsById = new Map(); const terminalExitUnsubscribeById = new Map void>(); const terminalTitleUnsubscribeById = new Map void>(); const terminalActivityUnsubscribeById = new Map void>(); @@ -186,7 +200,7 @@ export function createTerminalManager( return bestMatchRoot ? defaultEnvByRootCwd.get(bestMatchRoot) : undefined; } - function registerSession(session: TerminalSession): TerminalSession { + function registerSession(session: LocalTerminalSession): LocalTerminalSession { terminalsById.set(session.id, session); const unsubscribeExit = session.onExit(() => { removeSessionById(session.id, { kill: false }); @@ -321,6 +335,8 @@ export function createTerminalManager( cols?: number; activityToken?: string; activityUrl?: string | null; + baseEnv?: Record; + paseoCliPath?: string | null; }): Promise { assertAbsolutePath(options.cwd); @@ -355,6 +371,8 @@ export function createTerminalManager( ...(options.rows !== undefined ? { rows: options.rows } : {}), ...(options.cols !== undefined ? { cols: options.cols } : {}), ...(mergedEnv ? { env: mergedEnv } : {}), + ...(options.baseEnv ? { baseEnv: options.baseEnv } : {}), + ...(options.paseoCliPath === undefined ? {} : { paseoCliPath: options.paseoCliPath }), activityEnv, }), ); @@ -390,6 +408,14 @@ export function createTerminalManager( return terminalsById.get(id); }, + getTerminalProcessId(id: string): number | null { + return terminalsById.get(id)?.pid ?? null; + }, + + getTerminalActivityToken(id: string): string | null { + return terminalActivityTokenById.get(id) ?? null; + }, + async getTerminalState( id: string, options?: TerminalStateSnapshotOptions, diff --git a/packages/server/src/terminal/terminal-session-controller.test.ts b/packages/server/src/terminal/terminal-session-controller.test.ts index b438af8381..27f69cb44d 100644 --- a/packages/server/src/terminal/terminal-session-controller.test.ts +++ b/packages/server/src/terminal/terminal-session-controller.test.ts @@ -17,6 +17,7 @@ import { SessionDelivery } from "../server/session/owned-subscriptions/index.js" import type { TerminalManager, TerminalsChangedEvent } from "./terminal-manager.js"; import { isSameOrDescendantPath } from "../server/path-utils.js"; import { PluginSessionSocket } from "../server/plugins/session-socket.js"; +import { TerminalWorkerIncompatibleError } from "./terminal-worker-pool.js"; function createController( options: TerminalSessionControllerOptions & { emitBinary(frame: Uint8Array): void }, @@ -347,6 +348,76 @@ describe("terminal-session-controller legacy terminal creation", () => { }); }); +describe("terminal-session-controller with terminals held by a newer Paseo", () => { + const incompatible = new TerminalWorkerIncompatibleError({ + paseoVersion: "9.9.9", + protocolVersion: 7, + }); + + function incompatibleManager(): TerminalManager { + return { + getUnavailableError: () => incompatible, + getTerminals: vi.fn(async () => Promise.reject(incompatible)), + createTerminal: vi.fn(async () => Promise.reject(incompatible)), + registerCwdEnv: vi.fn(), + validateTerminalActivityToken: vi.fn(() => "unknown"), + getTerminal: vi.fn(), + getTerminalState: vi.fn(), + setTerminalTitle: vi.fn(), + setTerminalActivity: vi.fn(), + clearTerminalAttention: vi.fn(), + killTerminal: vi.fn(), + killTerminalAndWait: vi.fn(), + captureTerminal: vi.fn(), + // The incompatible worker's terminals are not in this daemon's view. + listDirectories: vi.fn(() => []), + killAll: vi.fn(), + subscribeTerminalsChanged: vi.fn(() => vi.fn()), + subscribeTerminalActivity: vi.fn(() => vi.fn()), + subscribeTerminalWorkspaceContributionChanged: vi.fn(() => vi.fn()), + }; + } + + test.each([ + { type: "list_terminals_request" as const, requestId: "req-list" }, + { type: "list_terminals_request" as const, requestId: "req-list-cwd", cwd: "/work/repo" }, + { + type: "create_terminal_request" as const, + requestId: "req-create", + cwd: "/work/repo", + workspaceId: "ws-1", + }, + ])( + "answers $type ($requestId) with a terminal_worker_incompatible rpc_error", + async (request) => { + const outboundMessages: SessionOutboundMessage[] = []; + const controller = createController({ + terminalManager: incompatibleManager(), + emit: (message) => outboundMessages.push(message), + emitBinary: vi.fn(), + hasBinaryChannel: () => true, + isPathWithinRoot: isSameOrDescendantPath, + sessionLogger: createLogger(), + listTerminalWorkspaceRefs: async () => [{ workspaceId: "ws-1", cwd: "/work/repo" }], + }); + + await controller.dispatch(request); + + expect(outboundMessages).toEqual([ + { + type: "rpc_error", + payload: { + requestId: request.requestId, + requestType: request.type, + error: incompatible.message, + code: "terminal_worker_incompatible", + }, + }, + ]); + }, + ); +}); + async function flushMicrotasks(): Promise { await new Promise((resolve) => setTimeout(resolve, 0)); } diff --git a/packages/server/src/terminal/terminal-session-controller.ts b/packages/server/src/terminal/terminal-session-controller.ts index 4f46dbc88c..e41186fdb1 100644 --- a/packages/server/src/terminal/terminal-session-controller.ts +++ b/packages/server/src/terminal/terminal-session-controller.ts @@ -38,6 +38,7 @@ import { import type { TerminalSession } from "./terminal.js"; import type { TerminalManager, TerminalsChangedEvent } from "./terminal-manager.js"; import { applyTerminalSize } from "./terminal-size-ownership.js"; +import { TerminalWorkerIncompatibleError } from "./terminal-worker-pool.js"; import type { TerminalActivity } from "@getpaseo/protocol/terminal-activity"; import { terminalSubscriptionKey } from "@getpaseo/protocol/terminal-subscription-key"; @@ -427,6 +428,8 @@ export class TerminalSessionController { } try { + const unavailable = this.terminalManager.getUnavailableError?.(); + if (unavailable) throw unavailable; let terminals: TerminalSession[]; if (msg.workspaceId !== undefined) { terminals = (await this.getAllTerminalSessions()).filter( @@ -449,6 +452,10 @@ export class TerminalSessionController { }); } catch (error) { this.sessionLogger.error({ err: error, cwd: msg.cwd }, "Failed to list terminals"); + if (error instanceof TerminalWorkerIncompatibleError) { + this.emitIncompatible(msg, error); + return; + } this.emit({ type: "list_terminals_response", payload: { @@ -460,6 +467,23 @@ export class TerminalSessionController { } } + // An empty list or a generic failure would read as "no terminals"; the client needs to know + // they exist and why it cannot reach them. + private emitIncompatible( + msg: { type: string; requestId: string }, + error: TerminalWorkerIncompatibleError, + ): void { + this.emit({ + type: "rpc_error", + payload: { + requestId: msg.requestId, + requestType: msg.type, + error: error.message, + code: error.code, + }, + }); + } + private async getAllTerminalSessions(): Promise { if (!this.terminalManager) { return []; @@ -597,6 +621,10 @@ export class TerminalSessionController { }); } catch (error) { this.sessionLogger.error({ err: error, cwd: msg.cwd }, "Failed to create terminal"); + if (error instanceof TerminalWorkerIncompatibleError) { + this.emitIncompatible(msg, error); + return; + } this.emit({ type: "create_terminal_response", payload: { diff --git a/packages/server/src/terminal/terminal-worker-client.test.ts b/packages/server/src/terminal/terminal-worker-client.test.ts new file mode 100644 index 0000000000..a363ab500d --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-client.test.ts @@ -0,0 +1,74 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { existsSync, mkdtempSync, rmSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { isPlatform } from "../test-utils/platform.js"; +import { encodeFrame, FrameDecoder, TerminalWorkerFrameError } from "./terminal-worker-frames.js"; +import { connectTerminalWorker, TerminalWorkerConnectError } from "./terminal-worker-client.js"; +import { launchTerminalWorker } from "./terminal-worker-launch.js"; +import { terminalWorkerRecordPath } from "./terminal-worker-record.js"; + +const temporaryDirs: string[] = []; + +afterEach(() => { + for (const dir of temporaryDirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }); + } +}); + +async function waitUntil(predicate: () => boolean, timeoutMs: number): Promise { + const deadline = Date.now() + timeoutMs; + while (!predicate()) { + if (Date.now() > deadline) throw new Error("condition not met in time"); + await new Promise((resolve) => setTimeout(resolve, 50)); + } +} + +describe("terminal worker frames", () => { + it("decodes frames split across chunks and several frames in one chunk", () => { + const first = encodeFrame({ type: "a", data: new Map([["k", 1]]) }); + const second = encodeFrame({ type: "b" }); + const joined = Buffer.concat([first, second]); + const decoder = new FrameDecoder(); + expect(decoder.push(joined.subarray(0, 3))).toEqual([]); + expect(decoder.push(joined.subarray(3, first.length + 2))).toEqual([ + { type: "a", data: new Map([["k", 1]]) }, + ]); + expect(decoder.push(joined.subarray(first.length + 2))).toEqual([{ type: "b" }]); + }); + + it("rejects a frame header announcing an oversized payload", () => { + const header = Buffer.alloc(4); + header.writeUInt32BE(0xffffffff, 0); + expect(() => new FrameDecoder().push(header)).toThrow(TerminalWorkerFrameError); + }); +}); + +describe("terminal worker authentication", () => { + it("closes a connection with the wrong secret and accepts the record's secret", async () => { + const paseoHome = mkdtempSync(path.join(tmpdir(), "tw-auth-")); + temporaryDirs.push(paseoHome); + const { record, recordPath } = await launchTerminalWorker({ + paseoHome, + paseoVersion: "0.0.0-test", + }); + expect(recordPath).toBe(terminalWorkerRecordPath(paseoHome, record.pid)); + if (!isPlatform("win32")) { + expect(statSync(recordPath).mode & 0o777).toBe(0o600); + expect(statSync(record.socketPath).mode & 0o777).toBe(0o600); + } + + await expect( + connectTerminalWorker({ socketPath: record.socketPath, secret: "wrong-secret" }), + ).rejects.toBeInstanceOf(TerminalWorkerConnectError); + + const connection = await connectTerminalWorker({ + socketPath: record.socketPath, + secret: record.secret, + }); + expect(connection.workerPid).toBe(record.pid); + // With no terminals, a worker whose controller leaves exits and removes its record. + connection.disconnect(); + await waitUntil(() => !existsSync(recordPath), 10_000); + }); +}); diff --git a/packages/server/src/terminal/terminal-worker-client.ts b/packages/server/src/terminal/terminal-worker-client.ts new file mode 100644 index 0000000000..532f3075c6 --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-client.ts @@ -0,0 +1,141 @@ +import { EventEmitter } from "node:events"; +import { createConnection } from "node:net"; +import { attachFramedSocket, type FramedSocket } from "./terminal-worker-frames.js"; +import { + TERMINAL_WORKER_PROTOCOL_VERSION, + type TerminalWorkerHello, + type TerminalWorkerHelloAck, + type TerminalWorkerRequest, + type TerminalWorkerToParentMessage, +} from "./terminal-worker-protocol.js"; + +const DEFAULT_CONNECT_TIMEOUT_MS = 5_000; + +/** The daemon's (or cleanup's) authenticated connection to one terminal worker. */ +export interface TerminalWorkerConnection { + readonly connected: boolean; + readonly workerPid: number; + send(message: TerminalWorkerRequest, callback: (error: Error | null) => void): boolean; + /** Closes the socket. The worker keeps running and keeps its terminals. */ + disconnect(): void; + on(event: "message", listener: (message: TerminalWorkerToParentMessage) => void): this; + on(event: "close", listener: () => void): this; +} + +export class TerminalWorkerConnectError extends Error { + constructor(message: string, options?: { cause?: unknown }) { + super(message, options); + this.name = "TerminalWorkerConnectError"; + } +} + +class SocketTerminalWorkerConnection extends EventEmitter implements TerminalWorkerConnection { + readonly workerPid: number; + private readonly framed: FramedSocket; + private closed = false; + + constructor(framed: FramedSocket, workerPid: number) { + super(); + this.framed = framed; + this.workerPid = workerPid; + framed.socket.once("close", () => { + this.closed = true; + this.emit("close"); + }); + } + + get connected(): boolean { + return !this.closed && !this.framed.socket.destroyed; + } + + send(message: TerminalWorkerRequest, callback: (error: Error | null) => void): boolean { + return this.framed.send(message, callback); + } + + disconnect(): void { + this.framed.close(); + } + + deliver(message: TerminalWorkerToParentMessage): void { + this.emit("message", message); + } +} + +function isHelloAck(message: unknown): message is TerminalWorkerHelloAck { + return ( + typeof message === "object" && + message !== null && + (message as { type?: unknown }).type === "helloAck" && + typeof (message as { pid?: unknown }).pid === "number" + ); +} + +/** + * Connects to a worker's socket and authenticates with the record's secret. The worker closes + * the socket on a wrong secret, so a rejected hello surfaces as a connect error. + */ +export function connectTerminalWorker(input: { + socketPath: string; + secret: string; + timeoutMs?: number; +}): Promise { + const timeoutMs = input.timeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS; + return new Promise((resolve, reject) => { + const socket = createConnection(input.socketPath); + let connection: SocketTerminalWorkerConnection | null = null; + let settled = false; + const fail = (error: Error) => { + if (settled) return; + settled = true; + clearTimeout(timer); + socket.destroy(); + reject(error); + }; + const timer = setTimeout(() => { + fail( + new TerminalWorkerConnectError( + `Terminal worker at ${input.socketPath} did not answer within ${timeoutMs}ms`, + ), + ); + }, timeoutMs); + const framed = attachFramedSocket(socket, (message) => { + if (connection) { + connection.deliver(message as TerminalWorkerToParentMessage); + return; + } + if (!isHelloAck(message)) { + fail(new TerminalWorkerConnectError("Terminal worker sent an unexpected first frame")); + return; + } + settled = true; + clearTimeout(timer); + connection = new SocketTerminalWorkerConnection(framed, message.pid); + resolve(connection); + }); + // `on`, not `once`: an error after authentication must not go unhandled. `close` + // follows every socket error and ends the connection. + socket.on("error", (error) => { + fail( + new TerminalWorkerConnectError( + `Cannot connect to terminal worker at ${input.socketPath}: ${error.message}`, + { cause: error }, + ), + ); + }); + socket.once("close", () => { + fail( + new TerminalWorkerConnectError( + `Terminal worker at ${input.socketPath} closed the connection during authentication`, + ), + ); + }); + socket.once("connect", () => { + const hello: TerminalWorkerHello = { + type: "hello", + secret: input.secret, + protocolVersion: TERMINAL_WORKER_PROTOCOL_VERSION, + }; + framed.send(hello); + }); + }); +} diff --git a/packages/server/src/terminal/terminal-worker-frames.ts b/packages/server/src/terminal/terminal-worker-frames.ts new file mode 100644 index 0000000000..f0b990e239 --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-frames.ts @@ -0,0 +1,98 @@ +import type { Socket } from "node:net"; +import { deserialize, serialize } from "node:v8"; + +// Frames on the terminal worker socket: a 4-byte big-endian length, then a v8-serialized +// payload (the same structured-clone semantics the old fork IPC used with +// `serialization: "advanced"`). The frame format is part of the frozen envelope: every worker +// version must keep it. +const FRAME_HEADER_BYTES = 4; +const MAX_FRAME_BYTES = 256 * 1024 * 1024; + +export class TerminalWorkerFrameError extends Error { + constructor(message: string) { + super(message); + this.name = "TerminalWorkerFrameError"; + } +} + +export function encodeFrame(value: unknown): Buffer { + const payload = serialize(value); + if (payload.length > MAX_FRAME_BYTES) { + throw new TerminalWorkerFrameError( + `Terminal worker frame of ${payload.length} bytes is too large`, + ); + } + const header = Buffer.allocUnsafe(FRAME_HEADER_BYTES); + header.writeUInt32BE(payload.length, 0); + return Buffer.concat([header, payload]); +} + +export class FrameDecoder { + private buffered: Buffer = Buffer.alloc(0); + + push(chunk: Buffer): unknown[] { + this.buffered = this.buffered.length === 0 ? chunk : Buffer.concat([this.buffered, chunk]); + const messages: unknown[] = []; + while (this.buffered.length >= FRAME_HEADER_BYTES) { + const length = this.buffered.readUInt32BE(0); + if (length > MAX_FRAME_BYTES) { + throw new TerminalWorkerFrameError(`Terminal worker frame of ${length} bytes is too large`); + } + const end = FRAME_HEADER_BYTES + length; + if (this.buffered.length < end) break; + messages.push(deserialize(this.buffered.subarray(FRAME_HEADER_BYTES, end))); + this.buffered = this.buffered.subarray(end); + } + return messages; + } +} + +export interface FramedSocket { + readonly socket: Socket; + send(message: unknown, callback?: (error: Error | null) => void): boolean; + close(): void; +} + +/** + * Wraps a connected socket in length-prefixed frames. A malformed frame destroys the socket: + * the peer is either not a terminal worker endpoint or is corrupt, and both end the session. + */ +export function attachFramedSocket( + socket: Socket, + onMessage: (message: unknown) => void, +): FramedSocket { + const decoder = new FrameDecoder(); + socket.on("data", (chunk: Buffer) => { + let messages: unknown[]; + try { + messages = decoder.push(chunk); + } catch (error) { + socket.destroy(error instanceof Error ? error : new Error(String(error))); + return; + } + for (const message of messages) { + if (socket.destroyed) return; + onMessage(message); + } + }); + return { + socket, + send(message, callback) { + if (socket.destroyed || !socket.writable) { + callback?.(new Error("Terminal worker socket is closed")); + return false; + } + let frame: Buffer; + try { + frame = encodeFrame(message); + } catch (error) { + callback?.(error instanceof Error ? error : new Error(String(error))); + return false; + } + return socket.write(frame, (error) => callback?.(error ?? null)); + }, + close() { + socket.end(() => socket.destroy()); + }, + }; +} diff --git a/packages/server/src/terminal/terminal-worker-launch.ts b/packages/server/src/terminal/terminal-worker-launch.ts new file mode 100644 index 0000000000..573abe3bd8 --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-launch.ts @@ -0,0 +1,93 @@ +import { execFile } from "node:child_process"; +import { randomUUID } from "node:crypto"; +import { buildSelfNodeCommand } from "../server/paseo-env.js"; +import { ensurePrivateDirectory } from "../server/private-files.js"; +import { + readTerminalWorkerRecord, + terminalWorkerDirectory, + terminalWorkerRecordPath, + type TerminalWorkerRecord, +} from "./terminal-worker-record.js"; +import { resolveTerminalWorkerEntry, type TerminalWorkerEntry } from "./terminal-worker-runtime.js"; + +const LAUNCH_TIMEOUT_MS = 20_000; + +export class TerminalWorkerLaunchError extends Error { + constructor(message: string, options?: { cause?: unknown }) { + super(message, options); + this.name = "TerminalWorkerLaunchError"; + } +} + +/** + * Starts a terminal worker outside this process's tree: the launcher spawns the worker + * detached and exits once it listens, so the worker is re-parented and survives this daemon. + * Resolves with the record the worker wrote; a failed start leaves no worker behind. + */ +export async function launchTerminalWorker(input: { + paseoHome: string; + paseoVersion: string; + timeoutMs?: number; + /** Defaults to the copy of this installation's bundle (source in dev). */ + entry?: TerminalWorkerEntry; +}): Promise<{ record: TerminalWorkerRecord; recordPath: string }> { + const recordId = randomUUID(); + ensurePrivateDirectory(terminalWorkerDirectory(input.paseoHome)); + const entry = input.entry ?? resolveTerminalWorkerEntry(input); + const launch = buildSelfNodeCommand([ + ...entry.execArgv, + entry.scriptPath, + "--launch", + "--record-id", + recordId, + "--paseo-home", + input.paseoHome, + "--paseo-version", + input.paseoVersion, + ...(entry.runtime ? ["--runtime", entry.runtime] : []), + ]); + const stdout = await new Promise((resolve, reject) => { + execFile( + launch.command, + launch.args, + { + env: launch.env, + timeout: input.timeoutMs ?? LAUNCH_TIMEOUT_MS, + windowsHide: true, + encoding: "utf8", + }, + (error, out, err) => { + if (error) { + const detail = err.trim() || error.message; + reject( + new TerminalWorkerLaunchError(`Terminal worker failed to start: ${detail}`, { + cause: error, + }), + ); + return; + } + resolve(out); + }, + ); + }); + + let pid: number; + try { + const parsed = JSON.parse(stdout.trim()) as { pid?: unknown }; + if (typeof parsed.pid !== "number") throw new Error("missing pid"); + pid = parsed.pid; + } catch (error) { + throw new TerminalWorkerLaunchError( + `Terminal worker launcher printed an unexpected result: ${stdout.trim()}`, + { cause: error }, + ); + } + const recordPath = terminalWorkerRecordPath(input.paseoHome, pid); + const record = await readTerminalWorkerRecord(recordPath); + if (record.recordId !== recordId) { + throw new TerminalWorkerLaunchError( + `Terminal worker record ${recordPath} belongs to another launch`, + ); + } + return { record, recordPath }; +} diff --git a/packages/server/src/terminal/terminal-worker-ownership.test.ts b/packages/server/src/terminal/terminal-worker-ownership.test.ts new file mode 100644 index 0000000000..7abbb9aa62 --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-ownership.test.ts @@ -0,0 +1,91 @@ +import { describe, expect, it } from "vitest"; +import type { ManagedProcessInspection } from "../server/managed-processes/managed-processes.js"; +import { + classifyTerminalProgramProcess, + classifyTerminalWorkerProcess, +} from "./terminal-worker-ownership.js"; + +const BIRTH = "Wed Oct 21 18:12:49 2026"; +const OTHER_BIRTH = "Wed Oct 21 18:13:02 2026"; + +function alive(startedAt: string | null, commandLine: string | null): ManagedProcessInspection { + return { status: "alive", snapshot: { pid: 4242, startedAt, commandLine } }; +} + +const workerRecord = { + recordId: "record-1", + identity: { + startedAt: BIRTH, + commandLine: "node terminal-worker-process.js --paseo-terminal-worker record-1", + }, +}; + +describe("terminal program ownership", () => { + it("owns a program that ran exec: same pid and birth time, new command line", () => { + expect( + classifyTerminalProgramProcess({ startedAt: BIRTH }, alive(BIRTH, "sleep 100000")), + ).toEqual({ status: "owned" }); + }); + + it("treats a reused pid with the same command line but another birth time as unrelated", () => { + expect( + classifyTerminalProgramProcess({ startedAt: BIRTH }, alive(OTHER_BIRTH, "/bin/zsh -l")), + ).toMatchObject({ status: "unrelated" }); + }); + + it("never owns a process without a birth time on either side, whatever its command", () => { + expect( + classifyTerminalProgramProcess({ startedAt: BIRTH }, alive(null, "/bin/zsh -l")), + ).toMatchObject({ status: "unknown" }); + expect( + classifyTerminalProgramProcess({ startedAt: null }, alive(BIRTH, "/bin/zsh -l")), + ).toMatchObject({ status: "unknown" }); + }); + + it("reports an inspection error as unknown, not gone", () => { + expect( + classifyTerminalProgramProcess( + { startedAt: BIRTH }, + { status: "error", error: new Error("ps failed") }, + ), + ).toMatchObject({ status: "unknown", reason: expect.stringContaining("ps failed") }); + }); + + it("reports a missing process as gone", () => { + expect(classifyTerminalProgramProcess({ startedAt: BIRTH }, { status: "not-found" })).toEqual({ + status: "gone", + }); + }); +}); + +describe("terminal worker ownership", () => { + it("owns the worker whose birth time matches and whose command line carries its record id", () => { + expect( + classifyTerminalWorkerProcess(workerRecord, alive(BIRTH, workerRecord.identity.commandLine)), + ).toEqual({ status: "owned" }); + }); + + it("treats another worker reusing the pid in the same second as unrelated", () => { + expect( + classifyTerminalWorkerProcess( + workerRecord, + alive(BIRTH, "node terminal-worker-process.js --paseo-terminal-worker record-2"), + ), + ).toMatchObject({ status: "unrelated" }); + }); + + it("treats a worker pid reused with another birth time as unrelated", () => { + expect( + classifyTerminalWorkerProcess( + workerRecord, + alive(OTHER_BIRTH, workerRecord.identity.commandLine), + ), + ).toMatchObject({ status: "unrelated" }); + }); + + it("does not own a worker whose command line cannot be read", () => { + expect(classifyTerminalWorkerProcess(workerRecord, alive(BIRTH, null))).toMatchObject({ + status: "unknown", + }); + }); +}); diff --git a/packages/server/src/terminal/terminal-worker-ownership.ts b/packages/server/src/terminal/terminal-worker-ownership.ts new file mode 100644 index 0000000000..9bd02b01cd --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-ownership.ts @@ -0,0 +1,69 @@ +import type { ManagedProcessInspection } from "../server/managed-processes/managed-processes.js"; +import { TERMINAL_WORKER_MARKER_ARG, type TerminalWorkerRecord } from "./terminal-worker-record.js"; + +// Who a pid named in a terminal worker record belongs to, before anything signals it. +// +// This is deliberately not `processIdentityMatches` from managed-processes.ts: that matcher +// falls back to command text when a birth time is missing, and requires the original argv when +// it is present. A terminal program is often a shell that ran `exec`, which keeps its pid and +// birth time but changes its command line; and a reused pid can run the same command line. +// Here birth time alone identifies a terminal program, and nothing without one is ever owned. + +export type ProcessOwnership = + | { status: "gone" } + | { status: "unrelated"; reason: string } + | { status: "owned" } + | { status: "unknown"; reason: string }; + +export function classifyTerminalWorkerProcess( + record: Pick, + inspection: ManagedProcessInspection, +): ProcessOwnership { + const birth = classifyBirth(record.identity.startedAt, inspection); + if (birth.status !== "owned" || inspection.status !== "alive") return birth; + const commandLine = inspection.snapshot.commandLine; + if (!commandLine) { + return { status: "unknown", reason: "command line unavailable" }; + } + if (!hasWorkerMarker(commandLine, record.recordId)) { + return { status: "unrelated", reason: "command line lacks the worker marker" }; + } + return { status: "owned" }; +} + +export function classifyTerminalProgramProcess( + entry: { startedAt: string | null }, + inspection: ManagedProcessInspection, +): ProcessOwnership { + return classifyBirth(entry.startedAt, inspection); +} + +function classifyBirth( + recordedStartedAt: string | null, + inspection: ManagedProcessInspection, +): ProcessOwnership { + if (inspection.status === "not-found") return { status: "gone" }; + if (inspection.status === "error") { + const message = + inspection.error instanceof Error ? inspection.error.message : String(inspection.error); + return { status: "unknown", reason: `inspection failed: ${message}` }; + } + const startedAt = inspection.snapshot.startedAt; + if (!recordedStartedAt || !startedAt) { + return { status: "unknown", reason: "birth time unavailable" }; + } + if (startedAt !== recordedStartedAt) { + return { status: "unrelated", reason: "pid reused by a process with another birth time" }; + } + return { status: "owned" }; +} + +function hasWorkerMarker(commandLine: string, recordId: string): boolean { + const tokens = commandLine.split(/\s+/); + for (let index = 0; index < tokens.length - 1; index += 1) { + if (tokens[index] === TERMINAL_WORKER_MARKER_ARG && tokens[index + 1] === recordId) { + return true; + } + } + return false; +} diff --git a/packages/server/src/terminal/terminal-worker-pool.ts b/packages/server/src/terminal/terminal-worker-pool.ts new file mode 100644 index 0000000000..f15ad5b46d --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-pool.ts @@ -0,0 +1,288 @@ +import type { TerminalActivityState } from "@getpaseo/protocol/terminal-activity"; +import type { CaptureTerminalLinesResult } from "./terminal-capture.js"; +import type { + TerminalActivityListener, + TerminalsChangedListener, + TerminalWorkspaceContributionChangedListener, +} from "./terminal-manager.js"; +import type { TerminalSession, TerminalStateSnapshot } from "./terminal.js"; +import type { WorkerCreateTerminalOptions } from "./terminal-worker-protocol.js"; +import type { DaemonTerminalManager } from "./worker-terminal-manager.js"; + +// The daemon's terminal service over up to two terminal workers: the current one, which takes +// every new terminal, and one draining a previous worker protocol, which keeps serving the +// terminals it already runs and is let go once its last one exits. With no current worker (two +// were already running), the first terminal created after one exits starts one. A worker from a +// newer Paseo +// is not driven at all: the service then refuses terminal requests with +// TerminalWorkerIncompatibleError instead of serving a partial view. + +export class TerminalWorkerIncompatibleError extends Error { + readonly code = "terminal_worker_incompatible"; + readonly paseoVersion: string; + readonly protocolVersion: unknown; + + constructor(input: { paseoVersion: string; protocolVersion: unknown }) { + super( + `Terminals are held by a newer Paseo (v${input.paseoVersion}, worker protocol ${String(input.protocolVersion)}). Update Paseo to v${input.paseoVersion} or later to use them, or run \`paseo daemon stop\` to close them.`, + ); + this.name = "TerminalWorkerIncompatibleError"; + this.paseoVersion = input.paseoVersion; + this.protocolVersion = input.protocolVersion; + } +} + +export class NoTerminalWorkerAvailableError extends Error { + constructor(message: string) { + super(message); + this.name = "NoTerminalWorkerAvailableError"; + } +} + +export interface TerminalWorkerPoolMember { + manager: DaemonTerminalManager; + workerPid: number; + /** Resolves only after confirmed worker death and its scoped cleanup. */ + exited: Promise; + /** Waits for any reconnect; false once the member is retired or stopping. */ + ready(): Promise; + stopRecovery(): void; +} + +export interface TerminalWorkerPoolOptions { + current: TerminalWorkerPoolMember | null; + draining: TerminalWorkerPoolMember[]; + /** Set when a worker from a newer Paseo holds this home's terminals. */ + incompatible: TerminalWorkerIncompatibleError | null; + /** + * Starts a current worker when there is none. Throws NoTerminalWorkerAvailableError, saying + * why, while no worker may start. + */ + startCurrent?: () => Promise; + /** Closes every terminal of every worker in the home and verifies they ended. */ + closeAll: () => Promise; + /** A draining worker's last terminal exited and the pool let it go. */ + onDrained?: (member: TerminalWorkerPoolMember) => void; +} + +export function createTerminalWorkerPool( + options: TerminalWorkerPoolOptions, +): DaemonTerminalManager { + let current = options.current; + const draining = new Set(options.draining); + const terminalsChangedListeners = new Set(); + const terminalActivityListeners = new Set(); + const contributionListeners = new Set(); + let closePromise: Promise | null = null; + let detached = false; + // One start at a time, so concurrent creates never launch two workers. + let starting: Promise | null = null; + // Registrations belong to the service and are replayed whenever a current worker starts. + const cwdEnv = new Map>(); + + function members(): TerminalWorkerPoolMember[] { + return [...(current ? [current] : []), ...draining]; + } + + function assertAvailable(): void { + if (options.incompatible) throw options.incompatible; + } + + function ownerOf(terminalId: string): DaemonTerminalManager | null { + for (const member of members()) { + if (member.manager.getTerminal(terminalId)) return member.manager; + } + return null; + } + + function routed(terminalId: string): DaemonTerminalManager { + assertAvailable(); + const owner = ownerOf(terminalId) ?? current?.manager; + if (!owner) { + throw new NoTerminalWorkerAvailableError(`Terminal ${terminalId} is not running`); + } + return owner; + } + + function releaseIfDrained(member: TerminalWorkerPoolMember): void { + if (!draining.has(member) || member.manager.listDirectories().length > 0) return; + draining.delete(member); + // With no controller and no terminals the worker exits on its own. The request that closed + // the last terminal is still waiting for its answer. + void member.manager + .detach({ afterPendingRequests: true }) + .then(() => options.onDrained?.(member)); + } + + function forwardEvents(member: TerminalWorkerPoolMember): void { + void member.exited.then(() => { + if (current === member) current = null; + return draining.delete(member); + }); + member.manager.subscribeTerminalsChanged((event) => { + for (const listener of Array.from(terminalsChangedListeners)) listener(event); + releaseIfDrained(member); + }); + member.manager.subscribeTerminalActivity((event) => { + for (const listener of Array.from(terminalActivityListeners)) listener(event); + }); + member.manager.subscribeTerminalWorkspaceContributionChanged((event) => { + for (const listener of Array.from(contributionListeners)) listener(event); + }); + } + + for (const member of members()) forwardEvents(member); + for (const member of Array.from(draining)) releaseIfDrained(member); + + async function currentManager(): Promise { + if (closePromise || detached) + throw new NoTerminalWorkerAvailableError("No terminal worker can take new terminals"); + const candidate = current; + if (candidate && (await candidate.ready())) return candidate.manager; + const startCurrent = options.startCurrent; + if (!startCurrent || closePromise || detached) { + return Promise.reject( + new NoTerminalWorkerAvailableError("No terminal worker can take new terminals"), + ); + } + starting ??= startCurrent() + .then(async (member) => { + if (closePromise || detached) { + // The service closed or let go while the worker started: it takes no terminals. + member.stopRecovery(); + await member.manager.detach(); + throw new NoTerminalWorkerAvailableError("No terminal worker can take new terminals"); + } + forwardEvents(member); + for (const [cwd, env] of cwdEnv) member.manager.registerCwdEnv({ cwd, env }); + current = member; + return member; + }) + .finally(() => { + starting = null; + }); + return starting.then((member) => member.manager); + } + + function closeTerminals(): Promise { + closePromise ??= (async () => { + for (const member of members()) member.stopRecovery(); + await starting?.catch(() => {}); + await Promise.all(members().map((member) => member.manager.detach())); + draining.clear(); + await options.closeAll(); + })(); + return closePromise; + } + + return { + getUnavailableError(): Error | null { + return options.incompatible; + }, + + async getTerminals(cwd, filter) { + assertAvailable(); + const lists = await Promise.all( + members().map((member) => member.manager.getTerminals(cwd, filter)), + ); + return lists.flat(); + }, + + async createTerminal( + createOptions: WorkerCreateTerminalOptions & { workspaceId: string }, + ): Promise { + assertAvailable(); + const manager = await currentManager(); + return manager.createTerminal(createOptions); + }, + + registerCwdEnv(registration) { + cwdEnv.set(registration.cwd, registration.env); + if (current) current.manager.registerCwdEnv(registration); + }, + + validateTerminalActivityToken(terminalId, token) { + for (const member of members()) { + const result = member.manager.validateTerminalActivityToken(terminalId, token); + if (result !== "unknown") return result; + } + return "unknown"; + }, + + getTerminal(id) { + for (const member of members()) { + const session = member.manager.getTerminal(id); + if (session) return session; + } + return undefined; + }, + + async getTerminalState(id, stateOptions): Promise { + return routed(id).getTerminalState(id, stateOptions); + }, + + setTerminalTitle(id, title) { + return ownerOf(id)?.setTerminalTitle(id, title) ?? false; + }, + + async setTerminalActivity(id, state: TerminalActivityState) { + return (await ownerOf(id)?.setTerminalActivity(id, state)) ?? false; + }, + + async clearTerminalAttention(id) { + return (await ownerOf(id)?.clearTerminalAttention(id)) ?? false; + }, + + killTerminal(id) { + ownerOf(id)?.killTerminal(id); + }, + + async killTerminalAndWait(id, waitOptions) { + await routed(id).killTerminalAndWait(id, waitOptions); + }, + + async captureTerminal(id, captureOptions): Promise { + return routed(id).captureTerminal(id, captureOptions); + }, + + listDirectories() { + return [...new Set(members().flatMap((member) => member.manager.listDirectories()))]; + }, + + killAll() { + void closeTerminals().catch(() => { + // The synchronous interface cannot report it; closeTerminals() callers see the error. + }); + }, + + closeTerminals, + + async detach() { + detached = true; + for (const member of members()) member.stopRecovery(); + await starting?.catch(() => {}); + await Promise.all(members().map((member) => member.manager.detach())); + }, + + async adoptTerminals() { + const counts = await Promise.all(members().map((member) => member.manager.adoptTerminals())); + for (const member of Array.from(draining)) releaseIfDrained(member); + return counts.reduce((sum, count) => sum + count, 0); + }, + + subscribeTerminalsChanged(listener) { + terminalsChangedListeners.add(listener); + return () => terminalsChangedListeners.delete(listener); + }, + + subscribeTerminalActivity(listener) { + terminalActivityListeners.add(listener); + return () => terminalActivityListeners.delete(listener); + }, + + subscribeTerminalWorkspaceContributionChanged(listener) { + contributionListeners.add(listener); + return () => contributionListeners.delete(listener); + }, + }; +} diff --git a/packages/server/src/terminal/terminal-worker-process.ts b/packages/server/src/terminal/terminal-worker-process.ts index a70d37c5b9..6c13ba04d5 100644 --- a/packages/server/src/terminal/terminal-worker-process.ts +++ b/packages/server/src/terminal/terminal-worker-process.ts @@ -1,352 +1,777 @@ +import { spawn } from "node:child_process"; +import { randomBytes, timingSafeEqual } from "node:crypto"; +import { chmodSync, closeSync, existsSync, openSync, rmSync, writeSync } from "node:fs"; +import { createServer, type Server, type Socket } from "node:net"; +import { fileURLToPath } from "node:url"; +import { currentBootId } from "../server/pid-lock.js"; +import { PRIVATE_FILE_MODE } from "../server/private-files.js"; import { createTerminalManager } from "./terminal-manager.js"; import { captureTerminalLines } from "./terminal-capture.js"; import { TerminalOutputCoalescer } from "./terminal-output-coalescer.js"; -import type { TerminalSession, TerminalStateSnapshotOptions } from "./terminal.js"; import type { - TerminalWorkerRequest, - TerminalWorkerStateResult, - TerminalWorkerToParentMessage, - WorkerTerminalInfo, + TerminalExitInfo, + TerminalSession, + TerminalStateSnapshotOptions, +} from "./terminal.js"; +import { attachFramedSocket, type FramedSocket } from "./terminal-worker-frames.js"; +import { createTerminalWorkerProcessInspector } from "./terminal-worker-processes.js"; +import { + TERMINAL_WORKER_MARKER_ARG, + terminalWorkerLogPath, + terminalWorkerRecordPath, + writeTerminalWorkerRecord, + type TerminalWorkerRecord, +} from "./terminal-worker-record.js"; +import { resolveTerminalWorkerSocketPath } from "./terminal-worker-socket-path.js"; +import { + TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV, + TERMINAL_WORKER_PROTOCOL_VERSION, + type TerminalWorkerHello, + type TerminalWorkerHelloAck, + type TerminalWorkerListResult, + type TerminalWorkerRequest, + type TerminalWorkerStateResult, + type TerminalWorkerToParentMessage, + type WorkerTerminalInfo, } from "./terminal-worker-protocol.js"; +// The terminal worker owns every PTY. It runs detached from the daemon (re-parented by the +// launcher below) so a daemon restart, crash or forced kill of the daemon's process tree does +// not take the terminals down, and it talks to whichever daemon controls it over an +// owner-only socket authenticated by the secret in its record. +// +// `--launch` runs the launcher: it starts the real worker detached, waits for it to listen, +// prints `{ pid, socketPath }` and exits, which leaves the worker parented to init. + +const LAUNCH_ARG = "--launch"; +const READY_TIMEOUT_MS = 15_000; +const HELLO_TIMEOUT_MS = 5_000; +// A freshly launched worker waits this long for its first controller before giving up. +const FIRST_CONTROLLER_TIMEOUT_MS = 30_000; +// While nobody controls it, the worker checks that its record still exists. A deleted record +// (a removed $PASEO_HOME) means no daemon can ever find these terminals again. +const ORPHAN_CHECK_INTERVAL_MS = 10_000; +const READY_FD = 3; + +interface WorkerArgs { + recordId: string; + paseoHome: string; + paseoVersion: string; + // The copy under terminal-worker/ this worker runs from; absent when it runs from source. + runtime: string | null; +} + +function readArg(argv: string[], name: string): string { + const index = argv.indexOf(name); + const value = index === -1 ? undefined : argv[index + 1]; + if (!value) { + throw new Error(`Terminal worker requires ${name}`); + } + return value; +} + +function parseWorkerArgs(argv: string[], recordIdArg: string): WorkerArgs { + return { + recordId: readArg(argv, recordIdArg), + paseoHome: readArg(argv, "--paseo-home"), + paseoVersion: readArg(argv, "--paseo-version"), + runtime: argv.includes("--runtime") ? readArg(argv, "--runtime") : null, + }; +} + +// The protocol version this worker reports in its record and hello. Tests override it to stand +// up older and newer workers from one build. +function reportedProtocolVersion(): number { + const override = process.env[TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV]; + if (override === undefined || override === "") return TERMINAL_WORKER_PROTOCOL_VERSION; + const parsed = Number(override); + if (!Number.isSafeInteger(parsed)) { + throw new Error(`${TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV} is not an integer: ${override}`); + } + return parsed; +} + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +// --------------------------------------------------------------------------------------------- +// Launcher +// --------------------------------------------------------------------------------------------- + +function runLauncher(argv: string[]): void { + const args = parseWorkerArgs(argv, "--record-id"); + const logFd = openSync(terminalWorkerLogPath(args.paseoHome), "a", PRIVATE_FILE_MODE); + const child = spawn( + process.execPath, + [ + ...process.execArgv, + fileURLToPath(import.meta.url), + TERMINAL_WORKER_MARKER_ARG, + args.recordId, + "--paseo-home", + args.paseoHome, + "--paseo-version", + args.paseoVersion, + ...(args.runtime ? ["--runtime", args.runtime] : []), + ], + { + detached: true, + stdio: ["ignore", "ignore", logFd, "pipe"], + env: process.env, + windowsHide: true, + }, + ); + closeSync(logFd); + + let settled = false; + let buffered = ""; + const finish = (code: number, output: string) => { + if (settled) return; + settled = true; + clearTimeout(timer); + if (code !== 0 && child.exitCode === null && child.pid) { + // A worker that never reported ready must not be left behind. + try { + process.kill(child.pid, "SIGKILL"); + } catch { + // Already gone. + } + } + child.unref(); + (child.stdio[READY_FD] as NodeJS.ReadableStream & { destroy(): void }).destroy(); + // Exit from the write callback: a pipe write can still be pending when process.exit runs. + (code === 0 ? process.stdout : process.stderr).write(output, () => process.exit(code)); + }; + const timer = setTimeout(() => { + finish(1, `Terminal worker did not report ready within ${READY_TIMEOUT_MS}ms\n`); + }, READY_TIMEOUT_MS); + + const readyStream = child.stdio[READY_FD] as NodeJS.ReadableStream; + readyStream.setEncoding("utf8"); + readyStream.on("data", (chunk: string) => { + buffered += chunk; + const newline = buffered.indexOf("\n"); + if (newline === -1) return; + const line = buffered.slice(0, newline); + if (line.startsWith("ready ")) { + finish(0, `${JSON.stringify({ pid: child.pid, socketPath: line.slice("ready ".length) })}\n`); + return; + } + finish(1, `${line.startsWith("error ") ? line.slice("error ".length) : line}\n`); + }); + child.once("error", (error) => finish(1, `Cannot start terminal worker: ${error.message}\n`)); + child.once("exit", (code, signal) => { + finish(1, `Terminal worker exited before it was ready (${signal ?? `code ${code}`})\n`); + }); +} + +// --------------------------------------------------------------------------------------------- +// Worker +// --------------------------------------------------------------------------------------------- + type TerminalCreateRequest = Extract; -const manager = createTerminalManager(); -const unsubscribeByTerminalId = new Map void>>(); -const outputCoalescerByTerminalId = new Map(); -let ipcClosing = false; +function runWorker(argv: string[]): void { + const args = parseWorkerArgs(argv, TERMINAL_WORKER_MARKER_ARG); + const protocolVersion = reportedProtocolVersion(); + const manager = createTerminalManager(); + const inspector = createTerminalWorkerProcessInspector(); + const sessionsById = new Map(); + const unsubscribeByTerminalId = new Map void>>(); + const outputCoalescerByTerminalId = new Map(); + // A terminal is published (terminalCreated) only once its program is recorded. An exit that + // arrives before then is held here and sent after the creation, so the controller never + // receives an exit for a terminal it does not know yet. + const exitsHeldDuringCreation = new Map(); + const secret = randomBytes(32).toString("base64url"); + let record: TerminalWorkerRecord | null = null; + let server: Server | null = null; + let controller: FramedSocket | null = null; + let everControlled = false; + let exiting = false; -interface InFlightTerminalCreateRequest { - requestId: string; - errorReported: boolean; -} - -let inFlightTerminalCreateRequest: InFlightTerminalCreateRequest | null = null; - -// The conpty failure signal is process-scoped, not request-scoped. Serializing -// creates keeps an async spawn failure attributable to exactly one request. -let createTerminalQueue: Promise = Promise.resolve(); - -// node-pty completes its Windows conpty spawn asynchronously on a separate -// conout worker thread. When that spawn fails (bad cwd, missing command, etc.) -// it throws an exception there that cannot be caught at the call site and would -// otherwise crash this worker process and sever every existing terminal. -process.on("uncaughtException", (error) => { - console.error("Terminal worker uncaught exception (kept alive):", error); - reportInFlightTerminalCreateFailure(error); -}); - -function sendToParent(message: TerminalWorkerToParentMessage): void { - if (ipcClosing || !process.connected || !process.send) { - return; + interface InFlightTerminalCreateRequest { + requestId: string; + errorReported: boolean; } - try { - process.send(message, (error) => { - if (error) { - ipcClosing = true; - } - }); - } catch { - ipcClosing = true; - } -} -function buildTerminalStateResult( - session: TerminalSession | undefined, - options?: TerminalStateSnapshotOptions, -): TerminalWorkerStateResult { - if (!session) { - return null; - } - return { ...session.getStateSnapshot(options), replayPreamble: session.getReplayPreamble() }; -} + let inFlightTerminalCreateRequest: InFlightTerminalCreateRequest | null = null; -function toTerminalInfo(session: TerminalSession): WorkerTerminalInfo { - return { - id: session.id, - name: session.name, - cwd: session.cwd, - workspaceId: session.workspaceId, - ...(session.getTitle() ? { title: session.getTitle() } : {}), - activity: session.getActivity(), - }; -} + // The conpty failure signal is process-scoped, not request-scoped. Serializing + // creates keeps an async spawn failure attributable to exactly one request. + let createTerminalQueue: Promise = Promise.resolve(); -function terminalWorkerErrorMessage(error: unknown): string { - return error instanceof Error ? error.message : "Terminal worker request failed"; -} - -function reportInFlightTerminalCreateFailure(error: unknown): void { - if (!inFlightTerminalCreateRequest || inFlightTerminalCreateRequest.errorReported) { - return; - } - inFlightTerminalCreateRequest.errorReported = true; - sendToParent({ - type: "response", - requestId: inFlightTerminalCreateRequest.requestId, - ok: false, - error: terminalWorkerErrorMessage(error), - }); -} - -function clearTerminalSubscriptions(terminalId: string): void { - const subscriptions = unsubscribeByTerminalId.get(terminalId); - if (subscriptions) { - for (const unsubscribe of subscriptions) { - try { - unsubscribe(); - } catch { - // no-op - } - } - } - unsubscribeByTerminalId.delete(terminalId); - const coalescer = outputCoalescerByTerminalId.get(terminalId); - if (coalescer) { - coalescer.dispose(); - outputCoalescerByTerminalId.delete(terminalId); - } -} - -function watchTerminal(session: TerminalSession): void { - clearTerminalSubscriptions(session.id); - - // Coalesce pty output chunks into a single IPC message per ~5ms window so a - // burst of small chunks no longer costs one process.send each. The batch - // carries the LAST chunk's revision (the highest) so downstream snapshot - // replay dedup stays correct. - let pendingOutputRevision: number | undefined; - const outputCoalescer = new TerminalOutputCoalescer({ - timers: { setTimeout, clearTimeout }, - onFlush: ({ payload }) => { - const revision = pendingOutputRevision; - pendingOutputRevision = undefined; - sendToParent({ - type: "terminalMessage", - terminalId: session.id, - message: { type: "output", data: payload.toString("utf8"), revision }, - replayPreamble: session.getReplayPreamble(), - }); - }, - }); - outputCoalescerByTerminalId.set(session.id, outputCoalescer); - - const unsubscribeMessage = session.subscribe( - (message) => { - if (message.type === "output") { - pendingOutputRevision = message.revision; - outputCoalescer.handle(message.data); - return; - } - // Non-output messages (snapshot/snapshotReady/titleChange) must not jump - // ahead of buffered output: flush the coalescer first, then forward. - outputCoalescer.flush(); - sendToParent({ - type: "terminalMessage", - terminalId: session.id, - message, - replayPreamble: session.getReplayPreamble(), - }); - }, - // Creation already sends an authoritative state in terminalCreated. A second - // asynchronous state snapshot can arrive after the create response and - // overwrite a resize issued immediately by the caller. - { initialSnapshot: "ready" }, - ); - const unsubscribeExit = session.onExit((info) => { - outputCoalescer.flush(); - clearTerminalSubscriptions(session.id); - sendToParent({ - type: "terminalExit", - terminalId: session.id, - info, - }); - }); - const unsubscribeTitle = session.onTitleChange((title) => { - outputCoalescer.flush(); - sendToParent({ - type: "terminalTitleChange", - terminalId: session.id, - title, - }); - }); - const unsubscribeCommandFinished = session.onCommandFinished((info) => { - outputCoalescer.flush(); - sendToParent({ - type: "terminalCommandFinished", - terminalId: session.id, - info, - }); - }); - const unsubscribeActivity = session.onActivityChange((transition) => { - sendToParent({ - type: "terminalActivityChange", - terminalId: session.id, - activity: transition.activity, - previous: transition.previous, - }); - }); - - unsubscribeByTerminalId.set(session.id, [ - unsubscribeMessage, - unsubscribeExit, - unsubscribeTitle, - unsubscribeCommandFinished, - unsubscribeActivity, - ]); -} - -function enqueueCreateTerminalRequest(message: TerminalCreateRequest): Promise { - const nextRequest = createTerminalQueue.then(() => handleCreateTerminalRequest(message)); - createTerminalQueue = nextRequest.catch(() => {}); - return nextRequest; -} - -async function handleCreateTerminalRequest(message: TerminalCreateRequest): Promise { - const request: InFlightTerminalCreateRequest = { - requestId: message.requestId, - errorReported: false, - }; - inFlightTerminalCreateRequest = request; - try { - const { workspaceId } = message.options; - if (!workspaceId) { - throw new Error("workspaceId is required"); - } - const session = await manager.createTerminal({ ...message.options, workspaceId }); - if (request.errorReported) { - session.kill(); - return; - } - watchTerminal(session); - const initialSnapshot = session.getStateSnapshot(); - sendToParent({ - type: "terminalCreated", - terminal: toTerminalInfo(session), - state: initialSnapshot.state, - }); - sendToParent({ - type: "response", - requestId: message.requestId, - ok: true, - result: { - terminal: toTerminalInfo(session), - state: initialSnapshot.state, - }, - }); - } catch (error) { + // node-pty completes its Windows conpty spawn asynchronously on a separate + // conout worker thread. When that spawn fails (bad cwd, missing command, etc.) + // it throws an exception there that cannot be caught at the call site and would + // otherwise crash this worker process and sever every existing terminal. + process.on("uncaughtException", (error) => { + console.error("Terminal worker uncaught exception (kept alive):", error); reportInFlightTerminalCreateFailure(error); - } finally { - if (inFlightTerminalCreateRequest === request) { - inFlightTerminalCreateRequest = null; + }); + + function sendToController(message: TerminalWorkerToParentMessage): void { + // With no controller the event is dropped; the headless terminal keeps the screen, and the + // next daemon reads it through listTerminals. + controller?.send(message); + } + + function persistRecord(): void { + if (!record || exiting) return; + record = { + ...record, + terminals: record.terminals.filter((entry) => sessionsById.has(entry.id)), + }; + writeTerminalWorkerRecord(args.paseoHome, record); + } + + function removeOwnFiles(): void { + rmSync(terminalWorkerRecordPath(args.paseoHome, process.pid), { force: true }); + if (record && process.platform !== "win32") { + rmSync(record.socketPath, { force: true }); } } -} -async function handleRequest(message: TerminalWorkerRequest): Promise { - switch (message.type) { - case "createTerminal": { - await enqueueCreateTerminalRequest(message); - return; - } + function exitWorker(code: number): void { + if (exiting) return; + exiting = true; + removeOwnFiles(); + server?.close(); + process.exit(code); + } - case "registerCwdEnv": { - manager.registerCwdEnv({ cwd: message.cwd, env: message.env }); - sendToParent({ type: "response", requestId: message.requestId, ok: true }); - return; - } + async function killEveryTerminalAndExit(): Promise { + const sessions = Array.from(sessionsById.values()); + await Promise.all( + sessions.map((session) => + session.killAndWait().catch((error: unknown) => { + console.error(`Terminal worker could not kill terminal ${session.id}:`, error); + }), + ), + ); + exitWorker(0); + } - case "setActivity": { - await manager.setTerminalActivity(message.terminalId, message.state); - sendToParent({ type: "response", requestId: message.requestId, ok: true }); - return; - } - - case "clearAttention": { - await manager.clearTerminalAttention(message.terminalId); - sendToParent({ type: "response", requestId: message.requestId, ok: true }); - return; - } - - case "killTerminal": { - manager.killTerminal(message.terminalId); - // Removal is owned by session.onExit -> terminalExit; the parent mirror - // clears contribution and emits terminalsChanged from that single path. - clearTerminalSubscriptions(message.terminalId); - sendToParent({ type: "response", requestId: message.requestId, ok: true }); - return; - } - - case "killTerminalAndWait": { - await manager.killTerminalAndWait(message.terminalId, message.options); - clearTerminalSubscriptions(message.terminalId); - sendToParent({ type: "response", requestId: message.requestId, ok: true }); - return; - } - - case "getTerminalState": { - // Flush buffered output before snapshotting: the headless state already includes it, - // so if the coalescer emitted it afterward (in a batch carrying a revision past the - // snapshot's) the controller's revision dedup wouldn't drop it and the client would - // see the bytes twice. Flushing first sends them with a revision <= the snapshot's. - outputCoalescerByTerminalId.get(message.terminalId)?.flush(); - sendToParent({ - type: "response", - requestId: message.requestId, - ok: true, - result: buildTerminalStateResult(manager.getTerminal(message.terminalId), message.options), - }); - return; - } - - case "captureTerminal": { - const session = manager.getTerminal(message.terminalId); - const result = session - ? captureTerminalLines(session, { - start: message.start, - end: message.end, - stripAnsi: message.stripAnsi, - }) - : { lines: [], totalLines: 0 }; - sendToParent({ - type: "response", - requestId: message.requestId, - ok: true, - result, - }); - return; - } - - case "killAll": { - manager.killAll(); - for (const terminalId of Array.from(unsubscribeByTerminalId.keys())) { - clearTerminalSubscriptions(terminalId); - } - sendToParent({ type: "response", requestId: message.requestId, ok: true }); - return; - } - - case "send": { - const session = manager.getTerminal(message.terminalId); - session?.send(message.message); - sendToParent({ type: "response", requestId: message.requestId, ok: true }); - return; + function exitIfIdle(): void { + if (!controller && everControlled && sessionsById.size === 0) { + exitWorker(0); } } -} -process.on("message", (message: TerminalWorkerRequest) => { - void handleRequest(message).catch((error: unknown) => { - sendToParent({ + function buildTerminalStateResult( + session: TerminalSession | undefined, + options?: TerminalStateSnapshotOptions, + ): TerminalWorkerStateResult { + if (!session) { + return null; + } + return { ...session.getStateSnapshot(options), replayPreamble: session.getReplayPreamble() }; + } + + function toTerminalInfo(session: TerminalSession): WorkerTerminalInfo { + return { + id: session.id, + name: session.name, + cwd: session.cwd, + workspaceId: session.workspaceId, + ...(session.getTitle() ? { title: session.getTitle() } : {}), + activity: session.getActivity(), + }; + } + + function terminalWorkerErrorMessage(error: unknown): string { + return error instanceof Error ? error.message : "Terminal worker request failed"; + } + + function reportInFlightTerminalCreateFailure(error: unknown): void { + if (!inFlightTerminalCreateRequest || inFlightTerminalCreateRequest.errorReported) { + return; + } + inFlightTerminalCreateRequest.errorReported = true; + sendToController({ type: "response", - requestId: message.requestId, + requestId: inFlightTerminalCreateRequest.requestId, ok: false, error: terminalWorkerErrorMessage(error), }); - }); -}); + } -process.once("disconnect", () => { - ipcClosing = true; - manager.killAll(); -}); + function clearTerminalSubscriptions(terminalId: string): void { + const subscriptions = unsubscribeByTerminalId.get(terminalId); + if (subscriptions) { + for (const unsubscribe of subscriptions) { + try { + unsubscribe(); + } catch { + // no-op + } + } + } + unsubscribeByTerminalId.delete(terminalId); + const coalescer = outputCoalescerByTerminalId.get(terminalId); + if (coalescer) { + coalescer.dispose(); + outputCoalescerByTerminalId.delete(terminalId); + } + } + + function watchTerminal(session: TerminalSession): void { + clearTerminalSubscriptions(session.id); + + // Coalesce pty output chunks into a single frame per ~5ms window so a burst of small + // chunks no longer costs one socket write each. The batch carries the LAST chunk's + // revision (the highest) so downstream snapshot replay dedup stays correct. + let pendingOutputRevision: number | undefined; + const outputCoalescer = new TerminalOutputCoalescer({ + timers: { setTimeout, clearTimeout }, + onFlush: ({ payload }) => { + const revision = pendingOutputRevision; + pendingOutputRevision = undefined; + sendToController({ + type: "terminalMessage", + terminalId: session.id, + message: { type: "output", data: payload.toString("utf8"), revision }, + replayPreamble: session.getReplayPreamble(), + }); + }, + }); + outputCoalescerByTerminalId.set(session.id, outputCoalescer); + + const unsubscribeMessage = session.subscribe( + (message) => { + if (message.type === "output") { + pendingOutputRevision = message.revision; + outputCoalescer.handle(message.data); + return; + } + // Non-output messages (snapshot/snapshotReady/titleChange) must not jump + // ahead of buffered output: flush the coalescer first, then forward. + outputCoalescer.flush(); + sendToController({ + type: "terminalMessage", + terminalId: session.id, + message, + replayPreamble: session.getReplayPreamble(), + }); + }, + // Creation already sends an authoritative state in terminalCreated. A second + // asynchronous state snapshot can arrive after the create response and + // overwrite a resize issued immediately by the caller. + { initialSnapshot: "ready" }, + ); + const unsubscribeExit = session.onExit((info) => { + outputCoalescer.flush(); + clearTerminalSubscriptions(session.id); + sessionsById.delete(session.id); + persistRecord(); + if (exitsHeldDuringCreation.has(session.id)) { + exitsHeldDuringCreation.set(session.id, info); + return; + } + sendToController({ + type: "terminalExit", + terminalId: session.id, + info, + }); + exitIfIdle(); + }); + const unsubscribeTitle = session.onTitleChange((title) => { + outputCoalescer.flush(); + sendToController({ + type: "terminalTitleChange", + terminalId: session.id, + title, + }); + }); + const unsubscribeCommandFinished = session.onCommandFinished((info) => { + outputCoalescer.flush(); + sendToController({ + type: "terminalCommandFinished", + terminalId: session.id, + info, + }); + }); + const unsubscribeActivity = session.onActivityChange((transition) => { + sendToController({ + type: "terminalActivityChange", + terminalId: session.id, + activity: transition.activity, + previous: transition.previous, + }); + }); + + unsubscribeByTerminalId.set(session.id, [ + unsubscribeMessage, + unsubscribeExit, + unsubscribeTitle, + unsubscribeCommandFinished, + unsubscribeActivity, + ]); + } + + // A terminal enters the record only with its program's birth time, so cleanup can always + // tell the program from a later process that reuses its pid. A program that already exited + // needs no entry; one whose birth time cannot be read is killed and the create fails. + async function recordTerminalProgram(session: TerminalSession): Promise { + if (session.getExitInfo()) return; + // The manager drops a session as soon as its program exits, so only a live one has a pid. + const pid = manager.getTerminalProcessId(session.id); + if (pid === null) { + throw new Error(`Terminal ${session.id} has no program pid`); + } + const inspection = await inspector.inspect(pid); + if (inspection.status === "not-found" || session.getExitInfo()) { + return; + } + if (inspection.status === "error" || !inspection.snapshot.startedAt) { + const reason = + inspection.status === "error" ? errorMessage(inspection.error) : "no birth time reported"; + throw new Error(`Cannot identify terminal program ${pid}: ${reason}`); + } + if (!record) { + throw new Error("Terminal worker record is not written yet"); + } + record = { + ...record, + terminals: [ + ...record.terminals.filter((entry) => entry.id !== session.id), + { id: session.id, pid, startedAt: inspection.snapshot.startedAt }, + ], + }; + persistRecord(); + } + + function enqueueCreateTerminalRequest(message: TerminalCreateRequest): Promise { + const nextRequest = createTerminalQueue.then(() => handleCreateTerminalRequest(message)); + createTerminalQueue = nextRequest.catch(() => {}); + return nextRequest; + } + + async function handleCreateTerminalRequest(message: TerminalCreateRequest): Promise { + const request: InFlightTerminalCreateRequest = { + requestId: message.requestId, + errorReported: false, + }; + inFlightTerminalCreateRequest = request; + try { + const { workspaceId } = message.options; + if (!workspaceId) { + throw new Error("workspaceId is required"); + } + const session = await manager.createTerminal({ ...message.options, workspaceId }); + if (request.errorReported) { + session.kill(); + return; + } + sessionsById.set(session.id, session); + exitsHeldDuringCreation.set(session.id, null); + watchTerminal(session); + try { + await recordTerminalProgram(session); + } catch (error) { + exitsHeldDuringCreation.delete(session.id); + clearTerminalSubscriptions(session.id); + sessionsById.delete(session.id); + await session.killAndWait().catch(() => undefined); + throw error; + } + const initialSnapshot = session.getStateSnapshot(); + sendToController({ + type: "terminalCreated", + terminal: toTerminalInfo(session), + state: initialSnapshot.state, + }); + sendToController({ + type: "response", + requestId: message.requestId, + ok: true, + result: { + terminal: toTerminalInfo(session), + state: initialSnapshot.state, + }, + }); + const heldExit = exitsHeldDuringCreation.get(session.id); + exitsHeldDuringCreation.delete(session.id); + if (heldExit) { + sendToController({ type: "terminalExit", terminalId: session.id, info: heldExit }); + exitIfIdle(); + } + } catch (error) { + reportInFlightTerminalCreateFailure(error); + } finally { + if (inFlightTerminalCreateRequest === request) { + inFlightTerminalCreateRequest = null; + } + } + } + + function listTerminals(): TerminalWorkerListResult { + return Array.from(sessionsById.values()).map((session) => { + // Buffered output is already in the headless state; flushing first keeps a later + // batch from carrying bytes the snapshot already shows. + outputCoalescerByTerminalId.get(session.id)?.flush(); + return { + terminal: toTerminalInfo(session), + state: session.getStateSnapshot().state, + activityToken: manager.getTerminalActivityToken(session.id), + replayPreamble: session.getReplayPreamble(), + }; + }); + } + + async function handleRequest(message: TerminalWorkerRequest): Promise { + switch (message.type) { + case "createTerminal": { + await enqueueCreateTerminalRequest(message); + return; + } + + case "registerCwdEnv": { + manager.registerCwdEnv({ cwd: message.cwd, env: message.env }); + sendToController({ type: "response", requestId: message.requestId, ok: true }); + return; + } + + case "setActivity": { + await manager.setTerminalActivity(message.terminalId, message.state); + sendToController({ type: "response", requestId: message.requestId, ok: true }); + return; + } + + case "clearAttention": { + await manager.clearTerminalAttention(message.terminalId); + sendToController({ type: "response", requestId: message.requestId, ok: true }); + return; + } + + case "killTerminal": { + manager.killTerminal(message.terminalId); + // Removal is owned by session.onExit -> terminalExit; the parent mirror + // clears contribution and emits terminalsChanged from that single path. + sendToController({ type: "response", requestId: message.requestId, ok: true }); + return; + } + + case "killTerminalAndWait": { + await manager.killTerminalAndWait(message.terminalId, message.options); + sendToController({ type: "response", requestId: message.requestId, ok: true }); + return; + } + + case "getTerminalState": { + // Flush buffered output before snapshotting: the headless state already includes it, + // so if the coalescer emitted it afterward (in a batch carrying a revision past the + // snapshot's) the controller's revision dedup wouldn't drop it and the client would + // see the bytes twice. Flushing first sends them with a revision <= the snapshot's. + outputCoalescerByTerminalId.get(message.terminalId)?.flush(); + sendToController({ + type: "response", + requestId: message.requestId, + ok: true, + result: buildTerminalStateResult( + manager.getTerminal(message.terminalId), + message.options, + ), + }); + return; + } + + case "captureTerminal": { + const session = manager.getTerminal(message.terminalId); + const result = session + ? captureTerminalLines(session, { + start: message.start, + end: message.end, + stripAnsi: message.stripAnsi, + }) + : { lines: [], totalLines: 0 }; + sendToController({ + type: "response", + requestId: message.requestId, + ok: true, + result, + }); + return; + } + + case "listTerminals": { + sendToController({ + type: "response", + requestId: message.requestId, + ok: true, + result: listTerminals(), + }); + return; + } + + case "shutdown": { + const sessions = Array.from(sessionsById.values()); + await Promise.all(sessions.map((session) => session.killAndWait().catch(() => undefined))); + // Exit once the response frame is flushed, so the requester sees the confirmation. + const requester = controller; + if (!requester) { + exitWorker(0); + return; + } + requester.send({ type: "response", requestId: message.requestId, ok: true }, () => + exitWorker(0), + ); + return; + } + + case "send": { + const session = manager.getTerminal(message.terminalId); + session?.send(message.message); + sendToController({ type: "response", requestId: message.requestId, ok: true }); + return; + } + } + } + + function isHello(message: unknown): message is TerminalWorkerHello { + return ( + typeof message === "object" && + message !== null && + (message as { type?: unknown }).type === "hello" && + typeof (message as { secret?: unknown }).secret === "string" + ); + } + + function secretMatches(candidate: string): boolean { + const expected = Buffer.from(secret, "utf8"); + const actual = Buffer.from(candidate, "utf8"); + return expected.length === actual.length && timingSafeEqual(expected, actual); + } + + function handleConnection(socket: Socket): void { + let authenticated = false; + socket.on("error", () => { + // `close` follows; a broken controller socket only means no controller. + }); + const helloTimer = setTimeout(() => socket.destroy(), HELLO_TIMEOUT_MS); + const framed = attachFramedSocket(socket, (message) => { + if (!authenticated) { + clearTimeout(helloTimer); + if (!isHello(message) || !secretMatches(message.secret)) { + socket.destroy(); + return; + } + authenticated = true; + // One controller at a time: a new authenticated connection replaces the old one. + const previous = controller; + controller = framed; + everControlled = true; + previous?.socket.destroy(); + const ack: TerminalWorkerHelloAck = { + type: "helloAck", + pid: process.pid, + protocolVersion, + }; + framed.send(ack); + return; + } + if (framed !== controller) { + return; + } + const request = message as TerminalWorkerRequest; + void handleRequest(request).catch((error: unknown) => { + sendToController({ + type: "response", + requestId: request.requestId, + ok: false, + error: terminalWorkerErrorMessage(error), + }); + }); + }); + socket.once("close", () => { + clearTimeout(helloTimer); + if (controller === framed) { + controller = null; + exitIfIdle(); + } + }); + } + + function reportReady(line: string): void { + try { + writeSync(READY_FD, `${line}\n`); + closeSync(READY_FD); + } catch { + // Started without a launcher pipe (tests that spawn the worker directly). + } + } + + async function start(): Promise { + const socketPath = resolveTerminalWorkerSocketPath({ + paseoHome: args.paseoHome, + workerPid: process.pid, + }); + if (process.platform !== "win32") { + rmSync(socketPath, { force: true }); + } + const listening = createServer(handleConnection); + await new Promise((resolve, reject) => { + listening.once("error", reject); + listening.listen(socketPath, () => { + listening.off("error", reject); + resolve(); + }); + }); + server = listening; + if (process.platform !== "win32") { + chmodSync(socketPath, PRIVATE_FILE_MODE); + } + + const self = await inspector.inspect(process.pid); + if ( + self.status !== "alive" || + !self.snapshot.startedAt || + !self.snapshot.commandLine?.includes(args.recordId) + ) { + const reason = self.status === "error" ? errorMessage(self.error) : "no usable snapshot"; + throw new Error(`Terminal worker cannot read its own process identity: ${reason}`); + } + record = { + recordId: args.recordId, + pid: process.pid, + bootId: currentBootId(), + createdAt: new Date().toISOString(), + identity: { startedAt: self.snapshot.startedAt, commandLine: self.snapshot.commandLine }, + protocolVersion, + paseoVersion: args.paseoVersion, + socketPath, + secret, + runtime: args.runtime, + terminals: [], + }; + writeTerminalWorkerRecord(args.paseoHome, record); + reportReady(`ready ${socketPath}`); + + setTimeout(() => { + if (!everControlled && sessionsById.size === 0) exitWorker(0); + }, FIRST_CONTROLLER_TIMEOUT_MS).unref(); + setInterval(() => { + if (!controller && !existsSync(terminalWorkerRecordPath(args.paseoHome, process.pid))) { + void killEveryTerminalAndExit(); + } + }, ORPHAN_CHECK_INTERVAL_MS); + } + + process.on("SIGTERM", () => { + void killEveryTerminalAndExit(); + }); + + start().catch((error: unknown) => { + const message = errorMessage(error).replace(/\n/g, " | "); + console.error(`Terminal worker failed to start: ${errorMessage(error)}`); + reportReady(`error ${message}`); + exitWorker(1); + }); +} + +if (process.argv.includes(LAUNCH_ARG)) { + runLauncher(process.argv.slice(2)); +} else { + runWorker(process.argv.slice(2)); +} diff --git a/packages/server/src/terminal/terminal-worker-processes.ts b/packages/server/src/terminal/terminal-worker-processes.ts new file mode 100644 index 0000000000..b0c2e6d0cb --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-processes.ts @@ -0,0 +1,185 @@ +import { readFile } from "node:fs/promises"; +import { z } from "zod"; +import { execCommand } from "../utils/spawn.js"; +import { + createSystemManagedProcessTable, + type ManagedProcessCommandRunner, + type ManagedProcessInspection, + windowsPowerShellPath, +} from "../server/managed-processes/managed-processes.js"; + +// Process inspection for terminal worker ownership. Birth times are compared as the strings +// `ps -o lstart` and Win32_Process.CreationDate print, so every reader must print them the same +// way: `ps` follows LC_TIME, and the worker, the daemon, the supervisor and the CLI can run +// under different locales. Every `ps` here runs under LC_ALL=C. + +const PS_TIMEOUT_MS = 15_000; +const POSIX_LSTART_WIDTH = 24; + +export interface ProcessTableEntry { + pid: number; + ppid: number; + startedAt: string; + // POSIX session id where `ps` reports one (Linux). macOS `ps` has no session column. + sessionId: number | null; +} + +export interface TerminalWorkerProcessInspector { + /** True where the process table names each process's session (Linux). */ + readonly reportsSessions: boolean; + inspect(pid: number): Promise; + /** One snapshot of every process, for walking descendants. Throws when it cannot be read. */ + listProcesses(): Promise; + /** + * The environment a process was started with, as NAME=value entries; null when the process + * is gone. Throws when it cannot be read. Only called where `reportsSessions` is true. + */ + readEnvironment(pid: number): Promise; +} + +const WindowsProcessListSchema = z.array( + z.object({ + ProcessId: z.number().int(), + ParentProcessId: z.number().int().nullable().optional(), + CreationDate: z.string().nullable().optional(), + }), +); + +function createLocaleNeutralCommandRunner(): ManagedProcessCommandRunner { + return { + exec: (command, args) => + execCommand(command, args, { + envMode: "internal", + envOverlay: { LC_ALL: "C" }, + timeout: PS_TIMEOUT_MS, + maxBuffer: 64 * 1024 * 1024, + }).then(({ stdout, stderr }) => ({ stdout: String(stdout), stderr: String(stderr) })), + }; +} + +export function createTerminalWorkerProcessInspector( + options: { platform?: NodeJS.Platform; commandRunner?: ManagedProcessCommandRunner } = {}, +): TerminalWorkerProcessInspector { + const platform = options.platform ?? process.platform; + const commandRunner = options.commandRunner ?? createLocaleNeutralCommandRunner(); + const table = createSystemManagedProcessTable({ platform, commandRunner }); + return { + reportsSessions: platform === "linux", + inspect: (pid) => table.inspect(pid), + listProcesses: () => + platform === "win32" + ? listWindowsProcesses(commandRunner) + : listPosixProcesses(commandRunner, platform), + readEnvironment: (pid) => readLinuxEnvironment(platform, pid), + }; +} + +async function readLinuxEnvironment( + platform: NodeJS.Platform, + pid: number, +): Promise { + if (platform !== "linux") { + throw new Error(`reading a process environment is not supported on ${platform}`); + } + let raw: string; + try { + raw = await readFile(`/proc/${pid}/environ`, "utf8"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; + throw error; + } + return raw.split("\0").filter((entry) => entry.length > 0); +} + +async function listPosixProcesses( + commandRunner: ManagedProcessCommandRunner, + platform: NodeJS.Platform, +): Promise { + const withSession = platform === "linux"; + const columns = withSession + ? ["-o", "pid=", "-o", "ppid=", "-o", "sid=", "-o", "lstart="] + : ["-o", "pid=", "-o", "ppid=", "-o", "lstart="]; + const { stdout } = await commandRunner.exec("ps", ["-A", "-ww", ...columns]); + const entries: ProcessTableEntry[] = []; + const leadingInts = withSession ? 3 : 2; + for (const line of stdout.split("\n")) { + const match = line.match( + withSession ? /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(.+?)\s*$/ : /^\s*(\d+)\s+(\d+)\s+(.+?)\s*$/, + ); + if (!match) continue; + const startedAt = match[leadingInts + 1].slice(0, POSIX_LSTART_WIDTH).trim(); + entries.push({ + pid: Number(match[1]), + ppid: Number(match[2]), + sessionId: withSession ? Number(match[3]) : null, + startedAt, + }); + } + if (entries.length === 0) { + throw new Error("ps returned no processes"); + } + return entries; +} + +async function listWindowsProcesses( + commandRunner: ManagedProcessCommandRunner, +): Promise { + const command = + "@(Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,CreationDate) | ConvertTo-Json -Compress"; + const { stdout } = await commandRunner.exec(windowsPowerShellPath(), [ + "-NoProfile", + "-NonInteractive", + "-Command", + command, + ]); + const parsed: unknown = JSON.parse(stdout.trim()); + const rows = WindowsProcessListSchema.parse(Array.isArray(parsed) ? parsed : [parsed]); + return rows.flatMap((row) => + row.CreationDate + ? [ + { + pid: row.ProcessId, + ppid: row.ParentProcessId ?? 0, + startedAt: row.CreationDate, + sessionId: null, + }, + ] + : [], + ); +} + +/** + * Every process below `rootPid` in the snapshot, plus (where the platform reports sessions) + * every member of the session `rootPid` led and everything below those members. A PTY program + * is a session leader, and the kernel keeps its pid reserved as the session id while any member + * lives, so the session still names a HUP-ignoring job after the shell exits and the job is + * reparented. + */ +export function collectDescendants( + snapshot: ProcessTableEntry[], + rootPid: number, +): ProcessTableEntry[] { + const childrenByParent = new Map(); + for (const entry of snapshot) { + const siblings = childrenByParent.get(entry.ppid) ?? []; + siblings.push(entry); + childrenByParent.set(entry.ppid, siblings); + } + const found = new Map(); + const queue = [rootPid]; + for (const entry of snapshot) { + if (entry.sessionId === rootPid && entry.pid !== rootPid) { + found.set(entry.pid, entry); + queue.push(entry.pid); + } + } + while (queue.length > 0) { + const parent = queue.shift()!; + for (const child of childrenByParent.get(parent) ?? []) { + if (child.pid === rootPid || found.has(child.pid)) continue; + found.set(child.pid, child); + queue.push(child.pid); + } + } + return Array.from(found.values()); +} diff --git a/packages/server/src/terminal/terminal-worker-protocol.test.ts b/packages/server/src/terminal/terminal-worker-protocol.test.ts new file mode 100644 index 0000000000..c3810bf9cf --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-protocol.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from "vitest"; +import { classifyTerminalWorkerProtocol } from "./terminal-worker-protocol.js"; + +describe("classifyTerminalWorkerProtocol", () => { + it.each([ + [5, "current"], + [4, "previous"], + [3, "obsolete"], + [-1, "obsolete"], + [6, "newer"], + // A version this daemon cannot read comes from a Paseo it does not know. + ["6", "newer"], + [4.5, "newer"], + [Number.NaN, "newer"], + [undefined, "newer"], + ])("a worker reporting %s to a daemon at 5 is %s", (reported, fit) => { + expect(classifyTerminalWorkerProtocol(reported, 5)).toBe(fit); + }); +}); diff --git a/packages/server/src/terminal/terminal-worker-protocol.ts b/packages/server/src/terminal/terminal-worker-protocol.ts index 5e7d1a30c0..86fc4a7772 100644 --- a/packages/server/src/terminal/terminal-worker-protocol.ts +++ b/packages/server/src/terminal/terminal-worker-protocol.ts @@ -31,6 +31,55 @@ export interface WorkerCreateTerminalOptions { cols?: number; activityToken?: string; activityUrl?: string | null; + // The worker outlives the daemon that started it, so the controlling daemon + // sends its own environment and Paseo CLI path with every create instead of + // letting the worker reuse whatever it inherited at launch. + baseEnv?: Record; + paseoCliPath?: string | null; +} + +// Bumped when a request, response or event changes shape. The frozen envelope never changes +// across versions: the frame format, `hello`/`helloAck`, the `listTerminals` info fields, and +// `shutdown`. A daemon drives a worker of its own version, drains one a version older (no new +// terminals; it exits after its last terminal), shuts down anything older, and leaves a newer +// worker running untouched. See docs/terminal-worker.md. +export const TERMINAL_WORKER_PROTOCOL_VERSION = 1; + +// Test-only: the protocol version a worker reports, so tests can stand up older and newer +// workers from one build. +export const TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV = "PASEO_TERMINAL_WORKER_PROTOCOL_OVERRIDE"; + +/** How a daemon at `current` treats a worker reporting `reported`. */ +export type TerminalWorkerProtocolFit = "current" | "previous" | "obsolete" | "newer"; + +export function classifyTerminalWorkerProtocol( + reported: unknown, + current: number = TERMINAL_WORKER_PROTOCOL_VERSION, +): TerminalWorkerProtocolFit { + // A version this daemon cannot read comes from a Paseo it does not know: treat it as newer. + if (typeof reported !== "number" || !Number.isSafeInteger(reported)) return "newer"; + if (reported === current) return "current"; + if (reported === current - 1) return "previous"; + return reported < current ? "obsolete" : "newer"; +} + +export interface TerminalWorkerHello { + type: "hello"; + secret: string; + protocolVersion: number; +} + +export interface TerminalWorkerHelloAck { + type: "helloAck"; + pid: number; + protocolVersion: number; +} + +export interface WorkerListedTerminal { + terminal: WorkerTerminalInfo; + state: TerminalState; + activityToken: string | null; + replayPreamble: string; } export interface WorkerKillAndWaitOptions { @@ -87,7 +136,12 @@ export type TerminalWorkerRequest = stripAnsi?: boolean; } | { - type: "killAll"; + type: "listTerminals"; + requestId: string; + } + | { + // Kill every terminal (waiting for each program to exit) and exit. + type: "shutdown"; requestId: string; } | { @@ -149,6 +203,8 @@ export type TerminalWorkerEvent = export type TerminalWorkerToParentMessage = TerminalWorkerResponse | TerminalWorkerEvent; +export type TerminalWorkerListResult = WorkerListedTerminal[]; + export type TerminalWorkerCaptureResult = CaptureTerminalLinesResult; // The worker fills TerminalStateSnapshot.replayPreamble on getTerminalState so // the parent can cache the input-mode preamble instead of re-deriving it. diff --git a/packages/server/src/terminal/terminal-worker-reaper.test.ts b/packages/server/src/terminal/terminal-worker-reaper.test.ts new file mode 100644 index 0000000000..a872325d31 --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-reaper.test.ts @@ -0,0 +1,640 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { execFile, spawn, type ChildProcess } from "node:child_process"; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { Worker } from "node:worker_threads"; +import { isPlatform } from "../test-utils/platform.js"; +import { currentBootId } from "../server/pid-lock.js"; +import { + createTerminalWorkerProcessInspector, + type TerminalWorkerProcessInspector, +} from "./terminal-worker-processes.js"; +import { + readUnconfirmedTerminalCleanup, + reapTerminalWorkers, + retryUnconfirmedTerminalCleanup, + TerminalCleanupNotConfirmedError, +} from "./terminal-worker-reaper.js"; +import { + readTerminalWorkerRecord, + terminalCleanupRecordPath, + terminalWorkerDirectory, + writeTerminalWorkerRecord, + type TerminalWorkerRecord, +} from "./terminal-worker-record.js"; + +// Real throwaway processes stand in for workers and terminal programs, so every signal the +// reaper sends lands on a process this test started. Nothing here uses invented pids. + +const inspector = createTerminalWorkerProcessInspector(); +const children: ChildProcess[] = []; +const extraPids: number[] = []; +const temporaryDirs: string[] = []; + +function spawnIdle( + script = "setInterval(() => {}, 1e9)", + env: NodeJS.ProcessEnv = process.env, +): ChildProcess { + const child = spawn(process.execPath, ["-e", script], { + detached: true, + stdio: ["ignore", "pipe", "ignore"], + env, + }); + children.push(child); + return child; +} + +// A program with one child of its own in a separate process group, so only the descendant walk +// (not the program's group kill) can reach it. +async function spawnProgramWithChild(): Promise<{ program: ChildProcess; childPid: number }> { + const program = spawnIdle(` + const child = require("node:child_process").spawn(process.execPath, ["-e", "setInterval(() => {}, 1e9)"], { stdio: "ignore", detached: true }); + process.stdout.write(String(child.pid) + "\\n"); + setInterval(() => {}, 1e9); + `); + const childPid = await new Promise((resolve) => { + program.stdout!.once("data", (chunk: Buffer) => resolve(Number(chunk.toString().trim()))); + }); + extraPids.push(childPid); + return { program, childPid }; +} + +async function birthOf(pid: number): Promise { + const inspection = await inspector.inspect(pid); + if (inspection.status !== "alive" || !inspection.snapshot.startedAt) { + throw new Error(`cannot read birth time of ${pid}`); + } + return inspection.snapshot.startedAt; +} + +async function goneProcessPid(): Promise { + const child = spawn(process.execPath, ["-e", ""], { stdio: "ignore" }); + await new Promise((resolve) => child.once("exit", resolve)); + return child.pid!; +} + +function isAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +async function waitUntilGone(pid: number): Promise { + const deadline = Date.now() + 5_000; + while (isAlive(pid) && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 50)); + } +} + +// A member of the terminal "t1" carries its id, as every program a terminal starts does. +function terminalEnv(terminalId: string): NodeJS.ProcessEnv { + return { ...process.env, PASEO_TERMINAL_ID: terminalId }; +} + +// A process's start environment: /proc where the real inspector reads it (Linux), `ps -E` on +// macOS, whose real inspector has no session walk and so never reads one. +function readEnvironment(pid: number): Promise { + if (process.platform === "linux") return inspector.readEnvironment(pid); + return new Promise((resolve) => { + execFile("ps", ["-E", "-ww", "-o", "command=", "-p", String(pid)], (error, stdout) => { + resolve(error ? null : stdout.trim().split(/\s+/)); + }); + }); +} + +// The real process table as a Linux `ps` would print it for one session: `memberPid` belongs to +// the session `sessionId` led, and every other process to none this test knows. macOS `ps` has +// no session column, so this is the only way to run the Linux branch here; the member is a real +// process the test started. `reusedRoot` adds a process that took the session id's pid. +function withSessionMember(input: { + memberPid: number; + sessionId: number; + reusedRoot?: boolean; + environmentUnreadable?: boolean; +}): TerminalWorkerProcessInspector { + return { + reportsSessions: true, + inspect: (pid) => inspector.inspect(pid), + listProcesses: async () => { + // A fresh snapshot each call, so it is rewritten in place. + const snapshot = await inspector.listProcesses(); + for (const entry of snapshot) { + entry.sessionId = entry.pid === input.memberPid ? input.sessionId : null; + } + if (input.reusedRoot) { + snapshot.push({ + pid: input.sessionId, + ppid: 1, + startedAt: "Fri Jan 1 00:00:00 2100", + sessionId: input.sessionId, + }); + } + return snapshot; + }, + readEnvironment: (pid) => + input.environmentUnreadable + ? Promise.reject(new Error("permission denied")) + : readEnvironment(pid), + }; +} + +// A record this process cannot open until another thread restores it, the way a worker's +// rename over its record ends a Windows sharing violation. The thread waits for `release()`, then +// restores the record while this thread is still inside the (synchronous) record read. +async function unreadableUntilReleased( + recordPath: string, +): Promise<{ release: () => void; restored: Promise }> { + chmodSync(recordPath, 0); + const signal = new Int32Array(new SharedArrayBuffer(8)); + const thread = new Worker( + ` + const { parentPort, workerData } = require("node:worker_threads"); + const signal = new Int32Array(workerData.signal); + parentPort.postMessage("ready"); + Atomics.wait(signal, 0, 0); + Atomics.wait(signal, 1, 0, 30); + require("node:fs").chmodSync(workerData.recordPath, 0o600); + `, + { eval: true, workerData: { recordPath, signal: signal.buffer } }, + ); + await new Promise((resolve) => thread.once("message", resolve)); + const restored = new Promise((resolve, reject) => { + thread.once("exit", () => resolve()); + thread.once("error", reject); + }); + return { + release: () => { + Atomics.store(signal, 0, 1); + Atomics.notify(signal, 0); + }, + restored, + }; +} + +function makeHome(): string { + const home = mkdtempSync(path.join(tmpdir(), "tw-reaper-")); + temporaryDirs.push(home); + return home; +} + +function writeRecord( + home: string, + input: Partial & Pick, +): string { + const record: TerminalWorkerRecord = { + recordId: "record-under-test", + bootId: currentBootId(), + createdAt: new Date().toISOString(), + identity: { + startedAt: "Thu Jan 1 00:00:00 1970", + commandLine: "node terminal-worker --paseo-terminal-worker record-under-test", + }, + protocolVersion: 1, + paseoVersion: "0.0.0-test", + socketPath: path.join(home, "missing.sock"), + secret: "not-a-real-secret", + terminals: [], + ...input, + }; + return writeTerminalWorkerRecord(home, record); +} + +afterEach(async () => { + for (const child of children.splice(0)) { + if (child.pid && isAlive(child.pid)) { + try { + process.kill(-child.pid, "SIGKILL"); + } catch { + child.kill("SIGKILL"); + } + } + } + for (const pid of extraPids.splice(0)) { + if (isAlive(pid)) process.kill(pid, "SIGKILL"); + } + for (const dir of temporaryDirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }); + } +}); + +describe.skipIf(isPlatform("win32"))("terminal worker reaper", () => { + it("ends the programs a dead worker left, and their children, then retires the record", async () => { + const home = makeHome(); + const { program, childPid } = await spawnProgramWithChild(); + const recordPath = writeRecord(home, { + pid: await goneProcessPid(), + terminals: [{ id: "t1", pid: program.pid!, startedAt: await birthOf(program.pid!) }], + }); + + const result = await reapTerminalWorkers({ paseoHome: home, inspector }); + + await waitUntilGone(program.pid!); + await waitUntilGone(childPid); + expect(isAlive(program.pid!)).toBe(false); + expect(isAlive(childPid)).toBe(false); + expect(result.signaled).toEqual(expect.arrayContaining([program.pid!, childPid])); + expect(existsSync(recordPath)).toBe(false); + }); + + it("never signals a live process that reuses the worker pid, but still ends its programs", async () => { + const home = makeHome(); + const reusedWorkerPid = spawnIdle().pid!; + const program = spawnIdle(); + writeRecord(home, { + pid: reusedWorkerPid, + terminals: [{ id: "t1", pid: program.pid!, startedAt: await birthOf(program.pid!) }], + }); + + const result = await reapTerminalWorkers({ paseoHome: home, inspector }); + + await waitUntilGone(program.pid!); + expect(isAlive(program.pid!)).toBe(false); + expect(isAlive(reusedWorkerPid)).toBe(true); + expect(result.signaled).not.toContain(reusedWorkerPid); + }); + + it("leaves a program alive when its pid now belongs to a process with another birth time", async () => { + const home = makeHome(); + const unrelated = spawnIdle(); + const recordPath = writeRecord(home, { + pid: await goneProcessPid(), + terminals: [{ id: "t1", pid: unrelated.pid!, startedAt: "Thu Jan 1 00:00:00 1970" }], + }); + + await reapTerminalWorkers({ paseoHome: home, inspector, gracefulMs: 0 }); + + expect(isAlive(unrelated.pid!)).toBe(true); + expect(existsSync(recordPath)).toBe(false); + }); + + it("retires a record from an earlier boot without signaling anything it names", async () => { + const home = makeHome(); + const program = spawnIdle(); + const recordPath = writeRecord(home, { + pid: spawnIdle().pid!, + bootId: null, + createdAt: "2000-01-01T00:00:00.000Z", + terminals: [{ id: "t1", pid: program.pid!, startedAt: await birthOf(program.pid!) }], + }); + + await reapTerminalWorkers({ paseoHome: home, inspector }); + + expect(isAlive(program.pid!)).toBe(true); + expect(existsSync(recordPath)).toBe(false); + }); + + it("keeps a record of what it could not inspect and reports cleanup unconfirmed", async () => { + const home = makeHome(); + const uninspectable = spawnIdle(); + const killable = spawnIdle(); + const failing: TerminalWorkerProcessInspector = { + reportsSessions: inspector.reportsSessions, + inspect: (pid) => + pid === uninspectable.pid + ? Promise.resolve({ status: "error", error: new Error("ps unavailable") }) + : inspector.inspect(pid), + listProcesses: () => inspector.listProcesses(), + readEnvironment: (pid) => inspector.readEnvironment(pid), + }; + const workerPid = await goneProcessPid(); + const recordPath = writeRecord(home, { + pid: workerPid, + terminals: [ + { id: "t1", pid: uninspectable.pid!, startedAt: await birthOf(uninspectable.pid!) }, + { id: "t2", pid: killable.pid!, startedAt: await birthOf(killable.pid!) }, + ], + }); + + let caught: unknown; + try { + await reapTerminalWorkers({ paseoHome: home, inspector: failing, confirmMs: 500 }); + } catch (error) { + caught = error; + } + + expect(caught).toBeInstanceOf(TerminalCleanupNotConfirmedError); + expect((caught as TerminalCleanupNotConfirmedError).unresolved).toEqual([ + expect.objectContaining({ pid: uninspectable.pid, reason: "inspection failed" }), + ]); + await waitUntilGone(killable.pid!); + expect(isAlive(killable.pid!)).toBe(false); + expect(isAlive(uninspectable.pid!)).toBe(true); + // The closing state goes to the cleanup record; the worker's own record is left as it was. + const kept = await readTerminalWorkerRecord( + terminalCleanupRecordPath(home, "record-under-test"), + ); + expect(kept.pid).toBe(workerPid); + expect(kept.closing?.unresolved.length).toBeGreaterThan(0); + expect(kept.terminals.map((entry) => entry.pid)).toEqual([uninspectable.pid]); + expect((await readTerminalWorkerRecord(recordPath)).closing).toBeUndefined(); + }); + + it("ends a session member its gone terminal program left behind, where sessions are reported", async () => { + const home = makeHome(); + const member = spawnIdle(undefined, terminalEnv("t1")); + const goneProgramPid = await goneProcessPid(); + const recordPath = writeRecord(home, { + pid: await goneProcessPid(), + terminals: [{ id: "t1", pid: goneProgramPid, startedAt: await birthOf(process.pid) }], + }); + + const result = await reapTerminalWorkers({ + paseoHome: home, + inspector: withSessionMember({ memberPid: member.pid!, sessionId: goneProgramPid }), + }); + + await waitUntilGone(member.pid!); + expect(isAlive(member.pid!)).toBe(false); + expect(result.signaled).toContain(member.pid); + expect(existsSync(recordPath)).toBe(false); + }); + + it("leaves alive a later session that reuses a gone terminal program's session id", async () => { + const home = makeHome(); + // Born after the recorded program, as any member of a later session is; only the missing + // terminal id tells it apart. + const member = spawnIdle(undefined, terminalEnv("another-terminal")); + const goneProgramPid = await goneProcessPid(); + const recordPath = writeRecord(home, { + pid: await goneProcessPid(), + terminals: [{ id: "t1", pid: goneProgramPid, startedAt: "Thu Jan 1 00:00:00 1970" }], + }); + + const result = await reapTerminalWorkers({ + paseoHome: home, + inspector: withSessionMember({ memberPid: member.pid!, sessionId: goneProgramPid }), + }); + + expect(isAlive(member.pid!)).toBe(true); + expect(result.signaled).toEqual([]); + expect(existsSync(recordPath)).toBe(false); + }); + + it("signals no session member it cannot identify, and keeps the cleanup unconfirmed", async () => { + const home = makeHome(); + const member = spawnIdle(undefined, terminalEnv("t1")); + const goneProgramPid = await goneProcessPid(); + writeRecord(home, { + pid: await goneProcessPid(), + terminals: [{ id: "t1", pid: goneProgramPid, startedAt: "Thu Jan 1 00:00:00 1970" }], + }); + + await expect( + reapTerminalWorkers({ + paseoHome: home, + inspector: withSessionMember({ + memberPid: member.pid!, + sessionId: goneProgramPid, + environmentUnreadable: true, + }), + }), + ).rejects.toBeInstanceOf(TerminalCleanupNotConfirmedError); + + expect(isAlive(member.pid!)).toBe(true); + expect(await readUnconfirmedTerminalCleanup(home)).toEqual([ + expect.objectContaining({ pid: goneProgramPid, reason: "inspection failed" }), + ]); + }); + + it("signals no session member whose environment carries no terminal id, and keeps the cleanup unconfirmed", async () => { + const home = makeHome(); + // A job started with a scrubbed environment (`env -i`) carries no terminal id at all: it + // may still be this terminal's, so it is neither signaled nor dismissed as unrelated. + const member = spawnIdle(undefined, {}); + const goneProgramPid = await goneProcessPid(); + writeRecord(home, { + pid: await goneProcessPid(), + terminals: [{ id: "t1", pid: goneProgramPid, startedAt: "Thu Jan 1 00:00:00 1970" }], + }); + const scrubbedMember = withSessionMember({ memberPid: member.pid!, sessionId: goneProgramPid }); + + for (let attempt = 0; attempt < 2; attempt += 1) { + await expect( + reapTerminalWorkers({ paseoHome: home, inspector: scrubbedMember }), + ).rejects.toBeInstanceOf(TerminalCleanupNotConfirmedError); + expect(isAlive(member.pid!)).toBe(true); + expect(await readUnconfirmedTerminalCleanup(home)).toEqual([ + expect.objectContaining({ + pid: goneProgramPid, + reason: "inspection failed", + detail: expect.stringContaining(`session member ${member.pid}`), + }), + ]); + } + expect(existsSync(terminalCleanupRecordPath(home, "record-under-test"))).toBe(true); + }); + + it("does not walk a gone terminal program's pid that another process took before the table was read", async () => { + const home = makeHome(); + const member = spawnIdle(undefined, terminalEnv("t1")); + const goneProgramPid = await goneProcessPid(); + writeRecord(home, { + pid: await goneProcessPid(), + terminals: [{ id: "t1", pid: goneProgramPid, startedAt: "Thu Jan 1 00:00:00 1970" }], + }); + + const result = await reapTerminalWorkers({ + paseoHome: home, + inspector: withSessionMember({ + memberPid: member.pid!, + sessionId: goneProgramPid, + reusedRoot: true, + }), + }); + + expect(isAlive(member.pid!)).toBe(true); + expect(result.signaled).toEqual([]); + }); + + // A kill cleanup that meets an unreadable worker record cannot check what it names and + // leaves nothing else behind, so status and retry must keep reporting it after a respawn. + it.each([ + ["cleanup", (home: string) => terminalCleanupRecordPath(home, "record-under-test")], + ["worker", (home: string) => path.join(terminalWorkerDirectory(home), "4242.json")], + ])("never reports an unreadable %s record as finished", async (_kind, recordPathIn) => { + const home = makeHome(); + mkdirSync(terminalWorkerDirectory(home), { recursive: true }); + const unreadablePath = recordPathIn(home); + writeFileSync(unreadablePath, "{ not json"); + + for (const attempt of [ + async () => await readUnconfirmedTerminalCleanup(home), + () => retryUnconfirmedTerminalCleanup(home), + () => reapTerminalWorkers({ paseoHome: home, inspector }), + ]) { + let caught: unknown; + try { + await attempt(); + } catch (error) { + caught = error; + } + expect(caught).toBeInstanceOf(TerminalCleanupNotConfirmedError); + expect((caught as TerminalCleanupNotConfirmedError).unreadableRecords).toEqual([ + expect.objectContaining({ path: unreadablePath }), + ]); + } + expect(existsSync(unreadablePath)).toBe(true); + }); + + it("signals nothing while the process table cannot be read, so a retry still ends the children", async () => { + const home = makeHome(); + const { program, childPid } = await spawnProgramWithChild(); + const recordPath = writeRecord(home, { + pid: await goneProcessPid(), + terminals: [{ id: "t1", pid: program.pid!, startedAt: await birthOf(program.pid!) }], + }); + const tableUnavailable: TerminalWorkerProcessInspector = { + reportsSessions: inspector.reportsSessions, + inspect: (pid) => inspector.inspect(pid), + listProcesses: () => Promise.reject(new Error("ps timed out")), + readEnvironment: (pid) => inspector.readEnvironment(pid), + }; + + await expect( + reapTerminalWorkers({ paseoHome: home, inspector: tableUnavailable }), + ).rejects.toBeInstanceOf(TerminalCleanupNotConfirmedError); + + expect(isAlive(program.pid!)).toBe(true); + expect(isAlive(childPid)).toBe(true); + const kept = await readTerminalWorkerRecord( + terminalCleanupRecordPath(home, "record-under-test"), + ); + expect(kept.closing?.unresolved.length).toBeGreaterThan(0); + expect(kept.terminals.map((entry) => entry.pid)).toEqual([program.pid]); + + const retry = await reapTerminalWorkers({ paseoHome: home, inspector, gracefulMs: 0 }); + + await waitUntilGone(program.pid!); + await waitUntilGone(childPid); + expect(isAlive(program.pid!)).toBe(false); + expect(isAlive(childPid)).toBe(false); + expect(retry.signaled).toEqual(expect.arrayContaining([program.pid!, childPid])); + expect(existsSync(recordPath)).toBe(false); + expect(existsSync(terminalCleanupRecordPath(home, "record-under-test"))).toBe(false); + }); + + it("escalates to SIGKILL a program that ignores SIGHUP and SIGTERM", async () => { + const home = makeHome(); + const stubborn = spawnIdle(` + process.on("SIGHUP", () => {}); + process.on("SIGTERM", () => {}); + setInterval(() => {}, 1e9); + `); + writeRecord(home, { + pid: await goneProcessPid(), + terminals: [{ id: "t1", pid: stubborn.pid!, startedAt: await birthOf(stubborn.pid!) }], + }); + + await reapTerminalWorkers({ paseoHome: home, inspector }); + + await waitUntilGone(stubborn.pid!); + expect(isAlive(stubborn.pid!)).toBe(false); + }); + + it.skipIf(process.getuid?.() === 0)( + "keeps the daemon event loop responsive while status retries an unreadable record", + async () => { + const home = makeHome(); + const recordPath = writeRecord(home, { pid: process.pid }); + chmodSync(recordPath, 0); + let serviced = false; + setImmediate(() => { + serviced = true; + }); + try { + await expect( + Promise.resolve().then(() => readUnconfirmedTerminalCleanup(home)), + ).rejects.toBeInstanceOf(TerminalCleanupNotConfirmedError); + expect(serviced).toBe(true); + } finally { + chmodSync(recordPath, 0o600); + } + }, + ); + + // chmod cannot make a file unreadable to root. + describe.skipIf(process.getuid?.() === 0)("a record that cannot be opened for a moment", () => { + it("still ends a live worker it names, then retires the record", async () => { + const home = makeHome(); + const worker = spawn( + process.execPath, + ["-e", "setInterval(() => {}, 1e9)", "--", "--paseo-terminal-worker", "record-under-test"], + { detached: true, stdio: "ignore" }, + ); + children.push(worker); + const recordPath = writeRecord(home, { + pid: worker.pid!, + identity: { + startedAt: await birthOf(worker.pid!), + commandLine: "node -e --paseo-terminal-worker record-under-test", + }, + }); + const record = await unreadableUntilReleased(recordPath); + + record.release(); + const result = await reapTerminalWorkers({ paseoHome: home, inspector, gracefulMs: 0 }); + await record.restored; + + await waitUntilGone(worker.pid!); + expect(isAlive(worker.pid!)).toBe(false); + expect(result.signaled).toContain(worker.pid!); + expect(existsSync(recordPath)).toBe(false); + }); + + it("confirms the cleanup of a worker that already exited, then retires the record", async () => { + const home = makeHome(); + const program = spawnIdle(); + const recordPath = writeRecord(home, { + pid: await goneProcessPid(), + terminals: [{ id: "t1", pid: program.pid!, startedAt: await birthOf(program.pid!) }], + }); + const record = await unreadableUntilReleased(recordPath); + + record.release(); + const result = await reapTerminalWorkers({ paseoHome: home, inspector, gracefulMs: 0 }); + await record.restored; + + await waitUntilGone(program.pid!); + expect(isAlive(program.pid!)).toBe(false); + expect(result.retired).toBe(1); + expect(existsSync(recordPath)).toBe(false); + }); + + it("still reports a record that stays unreadable, and signals nothing it names", async () => { + const home = makeHome(); + const worker = spawn( + process.execPath, + ["-e", "setInterval(() => {}, 1e9)", "--", "--paseo-terminal-worker", "record-under-test"], + { detached: true, stdio: "ignore" }, + ); + children.push(worker); + const recordPath = writeRecord(home, { + pid: worker.pid!, + identity: { + startedAt: await birthOf(worker.pid!), + commandLine: "node -e --paseo-terminal-worker record-under-test", + }, + }); + chmodSync(recordPath, 0); + + let caught: unknown; + try { + await reapTerminalWorkers({ paseoHome: home, inspector, gracefulMs: 0 }); + } catch (error) { + caught = error; + } + + expect(caught).toBeInstanceOf(TerminalCleanupNotConfirmedError); + expect((caught as TerminalCleanupNotConfirmedError).unreadableRecords).toEqual([ + expect.objectContaining({ path: recordPath, error: expect.stringContaining("EACCES") }), + ]); + expect(isAlive(worker.pid!)).toBe(true); + chmodSync(recordPath, 0o600); + expect(existsSync(recordPath)).toBe(true); + }); + }); +}); diff --git a/packages/server/src/terminal/terminal-worker-reaper.ts b/packages/server/src/terminal/terminal-worker-reaper.ts new file mode 100644 index 0000000000..2647d4b25e --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-reaper.ts @@ -0,0 +1,642 @@ +import { randomUUID } from "node:crypto"; +import { setTimeout as delay } from "node:timers/promises"; +import treeKill from "tree-kill"; +import { writtenDuringThisBoot } from "../server/pid-lock.js"; +import { connectTerminalWorker } from "./terminal-worker-client.js"; +import { pruneTerminalWorkerRuntimes } from "./terminal-worker-runtime.js"; +import { + classifyTerminalProgramProcess, + classifyTerminalWorkerProcess, + type ProcessOwnership, +} from "./terminal-worker-ownership.js"; +import { + collectDescendants, + createTerminalWorkerProcessInspector, + type ProcessTableEntry, + type TerminalWorkerProcessInspector, +} from "./terminal-worker-processes.js"; +import { + listTerminalWorkerRecords, + retireTerminalWorkerRecord, + terminalCleanupRecordPath, + writeTerminalCleanupRecord, + type TerminalCleanupUnresolved, + type TerminalWorkerRecord, + type TerminalWorkerRecordFile, + type TerminalWorkerTerminalEntry, +} from "./terminal-worker-record.js"; + +// The one kill path for terminal workers outside a connected daemon, and the one the daemon +// uses for its own kill stop. Every kill intent (stop, quit, --force, a kill restart whose +// shutdown hung, a dead or stopped worker, a program that ignores HUP) ends here: +// +// 1. Classify the worker and every terminal program of each record on its own, by birth time. +// A record from an earlier boot names only processes the reboot ended: retire it unsignaled. +// Descendants of owned programs (and, on Linux, members of their sessions) join the +// candidates from one process-table snapshot taken before anything is signaled. Once a +// program is gone, its session id can belong to a later session, so a member of a gone +// program's session joins only when its environment carries that terminal's id. When the +// table cannot be read, nothing in the record is signaled: ending a program would reparent +// the children only the table can find, and a retry could never reach them again. +// 2. An owned worker gets an authenticated `shutdown`: it kills each terminal and waits for it. +// 3. After `gracefulMs`, SIGKILL whatever owned process is left, re-inspecting right before +// each signal. +// 4. Succeed only when every candidate is gone or proven unrelated. Otherwise keep a record of +// the unresolved entries, marked closing, in a cleanup record no worker rewrites, and throw +// TerminalCleanupNotConfirmedError. An unreadable record is never reported confirmed. + +const DEFAULT_GRACEFUL_MS = 5_000; +const DEFAULT_CONFIRM_MS = 3_000; +const POLL_INTERVAL_MS = 100; + +export interface UnresolvedTerminalProcess extends TerminalCleanupUnresolved { + recordPath: string; +} + +// What a cleanup could not confirm, as a caller reports it: read here, or from the daemon +// status of a host the caller cannot read itself. +export interface UnconfirmedTerminalProcess { + pid: number; + role: string; + reason: string; + detail: string; +} + +export interface UnreadableTerminalWorkerRecord { + path: string; + error: string; +} + +export class TerminalCleanupNotConfirmedError extends Error { + readonly code = "TERMINAL_CLEANUP_NOT_CONFIRMED"; + readonly unresolved: UnconfirmedTerminalProcess[]; + readonly unreadableRecords: UnreadableTerminalWorkerRecord[]; + + constructor( + unresolved: UnconfirmedTerminalProcess[], + unreadableRecords: UnreadableTerminalWorkerRecord[] = [], + ) { + super( + [ + "Terminal cleanup was not confirmed.", + ...(unresolved.length > 0 + ? [ + "These processes may still be running:", + ...unresolved.map( + (entry) => ` pid ${entry.pid} (${entry.role}): ${entry.reason} (${entry.detail})`, + ), + "Their record is kept; the next `paseo daemon stop` retries the cleanup.", + ] + : []), + ...(unreadableRecords.length > 0 + ? [ + "These records cannot be read, so the processes they name cannot be checked:", + ...unreadableRecords.map((entry) => ` ${entry.path}: ${entry.error}`), + "Repair or remove each once you have checked its processes are gone.", + ] + : []), + ].join("\n"), + ); + this.name = "TerminalCleanupNotConfirmedError"; + this.unresolved = unresolved; + this.unreadableRecords = unreadableRecords; + } +} + +/** + * Retries the cleanup an earlier kill could not confirm (records marked closing), leaving any + * live worker a daemon controls alone. Throws TerminalCleanupNotConfirmedError when processes + * still survive, or when a record cannot be read, so a kill restart can report them. + */ +export async function retryUnconfirmedTerminalCleanup(paseoHome: string): Promise { + const files = await listTerminalWorkerRecords(paseoHome); + const recordPaths = files.flatMap((file) => + ("record" in file && file.record.closing) || "error" in file ? [file.path] : [], + ); + if (recordPaths.length === 0) return; + await reapTerminalWorkers({ paseoHome, gracefulMs: 0, recordPaths }); +} + +/** + * What the last cleanup of this home could not confirm gone, as its closing records name it. + * Read without retrying, so a daemon can report it (daemon status) to clients that cannot read + * this home themselves. Throws TerminalCleanupNotConfirmedError when any record cannot be read, + * worker records included: a kill cleanup that met it could not check what it names, and a + * failed cleanup leaves nothing else behind, so the cleanup cannot be reported finished. + */ +export async function readUnconfirmedTerminalCleanup( + paseoHome: string, +): Promise { + const files = await listTerminalWorkerRecords(paseoHome); + const unresolved = files.flatMap((file) => + "record" in file && file.record.closing + ? file.record.closing.unresolved.map((entry) => ({ ...entry, recordPath: file.path })) + : [], + ); + const unreadable = files.flatMap((file) => + "error" in file ? [{ path: file.path, error: file.error.message }] : [], + ); + if (unreadable.length > 0) { + throw new TerminalCleanupNotConfirmedError(unresolved, unreadable); + } + return unresolved; +} + +export interface TerminalWorkerReapResult { + records: number; + retired: number; + signaled: number[]; +} + +export interface ReapTerminalWorkersOptions { + paseoHome: string; + /** Time the worker gets to close its terminals before SIGKILL. 0 skips the shutdown request. */ + gracefulMs?: number; + confirmMs?: number; + /** Limit cleanup to these record files. Defaults to every record in the home. */ + recordPaths?: string[]; + inspector?: TerminalWorkerProcessInspector; + log?: (message: string, fields?: Record) => void; +} + +interface Candidate { + pid: number; + startedAt: string; + role: UnresolvedTerminalProcess["role"]; + terminalId: string; + state: ProcessOwnership; + // Set when this program's children could not be looked up: its cleanup is never reported + // confirmed, even once the program itself is gone, and its entry stays for the retry. + descendantsUnconfirmed: string | null; +} + +interface CandidateDiscovery { + candidates: Candidate[]; + // The process table could not be read, so no process of the record may be signaled yet. + tableError: string | null; +} + +export async function reapTerminalWorkers( + options: ReapTerminalWorkersOptions, +): Promise { + const inspector = options.inspector ?? createTerminalWorkerProcessInspector(); + const gracefulMs = options.gracefulMs ?? DEFAULT_GRACEFUL_MS; + const confirmMs = options.confirmMs ?? DEFAULT_CONFIRM_MS; + const log = options.log ?? (() => {}); + const wanted = options.recordPaths ? new Set(options.recordPaths) : null; + const result: TerminalWorkerReapResult = { records: 0, retired: 0, signaled: [] }; + const unresolved: UnresolvedTerminalProcess[] = []; + const unreadable: UnreadableTerminalWorkerRecord[] = []; + + for (const file of await listTerminalWorkerRecords(options.paseoHome)) { + if (wanted && !wanted.has(file.path)) continue; + result.records += 1; + if ("error" in file) { + // Nothing in an unreadable record can identify a process, so nothing may be signaled, + // and nothing it names can be confirmed gone. + log("Skipping unreadable terminal worker record", { + recordPath: file.path, + error: file.error.message, + }); + unreadable.push({ path: file.path, error: file.error.message }); + continue; + } + const outcome = await reapRecord({ + paseoHome: options.paseoHome, + file, + inspector, + gracefulMs, + confirmMs, + log, + }); + result.signaled.push(...outcome.signaled); + if (outcome.unresolved.length === 0) { + result.retired += 1; + } else { + unresolved.push(...outcome.unresolved); + } + } + + // Copies of worker files no remaining record names belong to no worker now. + const pruned = await pruneTerminalWorkerRuntimes(options.paseoHome); + for (const failure of pruned.failed) { + log("Cannot remove a terminal worker copy; the next cleanup retries", failure); + } + + if (unresolved.length > 0 || unreadable.length > 0) { + throw new TerminalCleanupNotConfirmedError(unresolved, unreadable); + } + return result; +} + +type ReadableRecordFile = Extract; + +interface ReapRecordInput { + paseoHome: string; + file: ReadableRecordFile; + inspector: TerminalWorkerProcessInspector; + gracefulMs: number; + confirmMs: number; + log: NonNullable; +} + +async function reapRecord( + input: ReapRecordInput, +): Promise<{ signaled: number[]; unresolved: UnresolvedTerminalProcess[] }> { + const { file, inspector, log } = input; + const { record } = file; + const recordPath = file.path; + if (!writtenDuringThisBoot({ startedAt: record.createdAt, bootId: record.bootId })) { + await retireTerminalWorkerRecord(file); + log("Retired terminal worker record from an earlier boot", { recordPath }); + return { signaled: [], unresolved: [] }; + } + + const worker = classifyTerminalWorkerProcess(record, await inspector.inspect(record.pid)); + const discovery = await collectCandidates(record, inspector, log); + const tracked: TrackedProcesses = { + record, + inspector, + worker, + candidates: discovery.candidates, + }; + + if (discovery.tableError !== null) { + return await keepUnresolved(input, tracked, [], `not signaled: ${discovery.tableError}`); + } + + if (tracked.worker.status === "owned" && input.gracefulMs > 0) { + await requestWorkerShutdown(record, input.gracefulMs, log); + } + await waitUntilSettled( + tracked, + Date.now() + (tracked.worker.status === "owned" ? input.gracefulMs : 0), + ); + + let signaled: number[] = []; + if (!isSettled(tracked)) { + signaled = await forceKillOwned(tracked, recordPath, log); + await waitUntilSettled(tracked, Date.now() + input.confirmMs); + } + + return await keepUnresolved(input, tracked, signaled, null); +} + +// Retires the record when every process it names is settled; otherwise writes the cleanup +// record, marked closing, with only the unresolved entries. A live worker keeps rewriting its +// own record, so the closing state never goes there. `notSignaled` explains open processes that +// were deliberately left alone. +async function keepUnresolved( + input: Pick, + tracked: TrackedProcesses, + signaled: number[], + notSignaled: string | null, +): Promise<{ signaled: number[]; unresolved: UnresolvedTerminalProcess[] }> { + const { record } = tracked; + const { file, log } = input; + const recordPath = terminalCleanupRecordPath(input.paseoHome, record.recordId); + const { unresolved, remaining } = collectUnresolved(tracked, recordPath, notSignaled); + if (unresolved.length === 0) { + await retireTerminalWorkerRecord(file); + log("Terminal worker record cleaned up", { recordPath: file.path, signaled }); + return { signaled, unresolved }; + } + await writeTerminalCleanupRecord(input.paseoHome, { + ...record, + terminals: remaining, + closing: { + unresolved: unresolved.map(({ pid, role, reason, detail }) => ({ + pid, + role, + reason, + detail, + })), + }, + }); + log("Terminal worker cleanup not confirmed; record kept", { + recordPath, + unresolved: unresolved.map((entry) => ({ pid: entry.pid, reason: entry.reason })), + }); + return { signaled, unresolved }; +} + +interface TrackedProcesses { + record: TerminalWorkerRecord; + inspector: TerminalWorkerProcessInspector; + worker: ProcessOwnership; + candidates: Candidate[]; +} + +function isOpen(state: ProcessOwnership): boolean { + return state.status === "owned" || state.status === "unknown"; +} + +function isSettled(tracked: TrackedProcesses): boolean { + return !isOpen(tracked.worker) && tracked.candidates.every((c) => !isOpen(c.state)); +} + +async function refreshTracked(tracked: TrackedProcesses): Promise { + if (isOpen(tracked.worker)) { + tracked.worker = classifyTerminalWorkerProcess( + tracked.record, + await tracked.inspector.inspect(tracked.record.pid), + ); + } + for (const candidate of tracked.candidates) { + if (isOpen(candidate.state)) { + candidate.state = classifyTerminalProgramProcess( + candidate, + await tracked.inspector.inspect(candidate.pid), + ); + } + } +} + +async function waitUntilSettled(tracked: TrackedProcesses, deadline: number): Promise { + await refreshTracked(tracked); + while (!isSettled(tracked) && Date.now() < deadline) { + await delay(POLL_INTERVAL_MS); + await refreshTracked(tracked); + } +} + +// SIGKILL every process still owned, re-inspecting each right before its signal. +async function forceKillOwned( + tracked: TrackedProcesses, + recordPath: string, + log: NonNullable, +): Promise { + const { record, inspector } = tracked; + const signaled: number[] = []; + if (tracked.worker.status === "owned") { + tracked.worker = classifyTerminalWorkerProcess(record, await inspector.inspect(record.pid)); + if (tracked.worker.status === "owned") { + await forceKillWorker(record.pid); + signaled.push(record.pid); + log("Force-killed terminal worker", { pid: record.pid, recordPath }); + } + } + for (const candidate of tracked.candidates) { + if (candidate.state.status !== "owned") continue; + candidate.state = classifyTerminalProgramProcess( + candidate, + await inspector.inspect(candidate.pid), + ); + if (candidate.state.status !== "owned") continue; + forceKillProgram(candidate.pid); + signaled.push(candidate.pid); + log("Force-killed terminal program", { + pid: candidate.pid, + terminalId: candidate.terminalId, + recordPath, + }); + } + return signaled; +} + +function collectUnresolved( + tracked: TrackedProcesses, + recordPath: string, + notSignaled: string | null, +): { unresolved: UnresolvedTerminalProcess[]; remaining: TerminalWorkerTerminalEntry[] } { + const unresolved: UnresolvedTerminalProcess[] = []; + if (isOpen(tracked.worker)) { + unresolved.push( + describeUnresolved({ + pid: tracked.record.pid, + role: "worker", + state: tracked.worker, + recordPath, + notSignaled, + }), + ); + } + const remaining: TerminalWorkerTerminalEntry[] = []; + for (const candidate of tracked.candidates) { + const stillOpen = isOpen(candidate.state); + if (!stillOpen && candidate.descendantsUnconfirmed === null) continue; + unresolved.push( + stillOpen + ? describeUnresolved({ + pid: candidate.pid, + role: candidate.role, + state: candidate.state, + recordPath, + notSignaled, + }) + : { + pid: candidate.pid, + role: candidate.role, + reason: "inspection failed", + detail: candidate.descendantsUnconfirmed!, + recordPath, + }, + ); + remaining.push({ + id: candidate.terminalId, + pid: candidate.pid, + startedAt: candidate.startedAt, + }); + } + return { unresolved, remaining }; +} + +async function collectCandidates( + record: TerminalWorkerRecord, + inspector: TerminalWorkerProcessInspector, + log: NonNullable, +): Promise { + const candidates = new Map(); + for (const entry of record.terminals) { + candidates.set(entry.pid, { + pid: entry.pid, + startedAt: entry.startedAt, + role: "terminal program", + terminalId: entry.id, + state: classifyTerminalProgramProcess(entry, await inspector.inspect(entry.pid)), + descendantsUnconfirmed: null, + }); + } + // Owned programs are walked through the table. Where sessions are reported, so are programs + // already gone: the kernel keeps a session id reserved while a member lives, so a job the + // shell left behind is still found. A pid reused by another process (unrelated) leads someone + // else's session and is never walked. + const roots = Array.from(candidates.values()).filter( + (c) => c.state.status === "owned" || (c.state.status === "gone" && inspector.reportsSessions), + ); + if (roots.length === 0) return { candidates: Array.from(candidates.values()), tableError: null }; + + let snapshot: ProcessTableEntry[]; + try { + snapshot = await inspector.listProcesses(); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + log("Cannot list processes for terminal cleanup", { error: message }); + for (const root of roots) { + root.descendantsUnconfirmed = `its child processes could not be listed: ${message}`; + } + return { + candidates: Array.from(candidates.values()), + tableError: `process table unavailable: ${message}`, + }; + } + for (const root of roots) { + const inTable = snapshot.find((entry) => entry.pid === root.pid); + if (inTable && inTable.startedAt !== root.startedAt) { + // The program ended and its pid was reused before the snapshot: what is below that pid + // now belongs to someone else, and the old session ended with every member of it. + log("Not walking a terminal program pid reused before the process table was read", { + pid: root.pid, + terminalId: root.terminalId, + }); + continue; + } + if (!inTable && !inspector.reportsSessions) continue; + // Below a live program its parent links prove ownership. Once it is gone, its session id + // may have been reused by a later session, so each member must carry the terminal's id. + const rootGone = !inTable; + for (const descendant of collectDescendants(snapshot, root.pid)) { + if (candidates.has(descendant.pid)) continue; + if (rootGone) { + const proof = await proveTerminalMember(inspector, descendant.pid, root.terminalId); + if (proof.status === "gone") continue; + if (proof.status === "unknown") { + root.descendantsUnconfirmed = `session member ${descendant.pid} cannot be identified: ${proof.reason}`; + continue; + } + if (proof.status === "unrelated") { + log("Ignoring a session member that does not carry its terminal's id", { + pid: descendant.pid, + terminalId: root.terminalId, + }); + continue; + } + } + candidates.set(descendant.pid, { + pid: descendant.pid, + startedAt: descendant.startedAt, + role: "terminal program", + terminalId: root.terminalId, + state: { status: "owned" }, + descendantsUnconfirmed: null, + }); + } + } + return { candidates: Array.from(candidates.values()), tableError: null }; +} + +// A terminal's programs inherit PASEO_TERMINAL_ID (terminal-manager.ts) from its PTY program. +// A process in a later session that happens to reuse the session id does not carry it. +async function proveTerminalMember( + inspector: TerminalWorkerProcessInspector, + pid: number, + terminalId: string, +): Promise { + let environment: string[] | null; + try { + environment = await inspector.readEnvironment(pid); + } catch (error) { + return { + status: "unknown", + reason: `environment unreadable: ${error instanceof Error ? error.message : String(error)}`, + }; + } + if (environment === null) return { status: "gone" }; + if (environment.includes(`PASEO_TERMINAL_ID=${terminalId}`)) return { status: "owned" }; + // Another terminal's id proves the process belongs elsewhere. No id at all proves nothing: a + // job started with a scrubbed environment (`env -i`) can still be this terminal's. + return environment.some((entry) => entry.startsWith("PASEO_TERMINAL_ID=")) + ? { status: "unrelated", reason: "environment carries another terminal's id" } + : { status: "unknown", reason: "its environment carries no terminal id" }; +} + +async function requestWorkerShutdown( + record: TerminalWorkerRecord, + gracefulMs: number, + log: NonNullable, +): Promise { + const deadline = Date.now() + gracefulMs; + let connection; + try { + connection = await connectTerminalWorker({ + socketPath: record.socketPath, + secret: record.secret, + timeoutMs: Math.min(gracefulMs, 2_000), + }); + } catch (error) { + // A worker that cannot be reached is escalated by birth time below; a failed connection + // alone never authorizes a signal. + log("Terminal worker did not accept a shutdown request", { + pid: record.pid, + error: error instanceof Error ? error.message : String(error), + }); + return; + } + const responded = new Promise((resolve) => { + connection.on("message", (message) => { + if (message.type === "response") resolve(); + }); + }); + const closed = new Promise((resolve) => connection.on("close", () => resolve())); + const sendFailed = new Promise((resolve) => { + connection.send({ type: "shutdown", requestId: randomUUID() }, (error) => { + if (error) resolve(); + }); + }); + const timeout = new AbortController(); + await Promise.race([ + responded, + closed, + sendFailed, + delay(Math.max(0, deadline - Date.now()), undefined, { signal: timeout.signal }).catch( + () => undefined, + ), + ]); + timeout.abort(); + connection.disconnect(); +} + +function forceKillWorker(pid: number): Promise { + if (process.platform === "win32") { + return new Promise((resolve) => { + treeKill(pid, "SIGKILL", () => resolve()); + }); + } + signalIgnoringMissing(pid, "SIGKILL"); + return Promise.resolve(); +} + +function forceKillProgram(pid: number): void { + if (process.platform !== "win32") { + // A PTY program leads its own session and process group. The group cannot outlive its + // leader's pid while any member is alive, so it holds nothing but this program's job. + signalIgnoringMissing(-pid, "SIGKILL"); + } + signalIgnoringMissing(pid, "SIGKILL"); +} + +function signalIgnoringMissing(pid: number, signal: NodeJS.Signals): void { + try { + process.kill(pid, signal); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code !== "ESRCH" && code !== "EPERM") throw error; + } +} + +function describeUnresolved(input: { + pid: number; + role: UnresolvedTerminalProcess["role"]; + state: ProcessOwnership; + recordPath: string; + notSignaled: string | null; +}): UnresolvedTerminalProcess { + const { pid, role, state, recordPath, notSignaled } = input; + if (state.status === "unknown") { + return { pid, role, reason: "inspection failed", detail: state.reason, recordPath }; + } + if (notSignaled !== null) { + return { pid, role, reason: "inspection failed", detail: notSignaled, recordPath }; + } + return { pid, role, reason: "still alive", detail: "survived SIGKILL", recordPath }; +} diff --git a/packages/server/src/terminal/terminal-worker-record.ts b/packages/server/src/terminal/terminal-worker-record.ts new file mode 100644 index 0000000000..3176d2ee8e --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-record.ts @@ -0,0 +1,230 @@ +import { readdir, readFile, rm } from "node:fs/promises"; +import { setTimeout as delay } from "node:timers/promises"; +import path from "node:path"; +import { z } from "zod"; +import { writePrivateFileAtomicSync, writePrivateFileAtomic } from "../server/private-files.js"; + +// Owner-only metadata a detached terminal worker leaves in $PASEO_HOME so the next daemon can +// find, authenticate and adopt it, and so cleanup can identify every process it is allowed to +// signal. Process identity is the birth time `ps`/Win32_Process report, never the pid alone. + +const TerminalWorkerTerminalEntrySchema = z.object({ + id: z.string().min(1), + pid: z.number().int().positive(), + startedAt: z.string().min(1), +}); + +// One process a cleanup could not confirm gone, kept so a later caller (a retry, or a remote +// client reading daemon status) can name it. +const TerminalCleanupUnresolvedSchema = z.object({ + pid: z.number().int().positive(), + role: z.enum(["worker", "terminal program"]), + reason: z.enum(["still alive", "inspection failed"]), + detail: z.string(), +}); + +const TerminalWorkerRecordSchema = z.object({ + recordId: z.string().min(1), + pid: z.number().int().positive(), + bootId: z.string().nullable(), + createdAt: z.string().min(1), + identity: z.object({ + startedAt: z.string().min(1), + commandLine: z.string().min(1), + }), + // Read loosely: a version this daemon cannot interpret marks a worker from a newer Paseo + // (classifyTerminalWorkerProtocol), not an unreadable record. + protocolVersion: z.union([z.number(), z.string()]), + paseoVersion: z.string(), + socketPath: z.string().min(1), + secret: z.string().min(1), + // The copy of the worker's files it runs from (a directory name under terminal-worker/), or + // null when it runs from source. A copy named by any record is never deleted. + runtime: z.string().nullable().optional(), + terminals: z.array(TerminalWorkerTerminalEntrySchema), + // Set only in a cleanup record (below), with what a cleanup could not confirm gone. A record + // marked closing is never adopted: the next daemon or stop retries the cleanup instead. + closing: z.object({ unresolved: z.array(TerminalCleanupUnresolvedSchema).min(1) }).optional(), +}); + +export type TerminalWorkerTerminalEntry = z.infer; +export type TerminalCleanupUnresolved = z.infer; +export type TerminalWorkerRecord = z.infer; + +// A worker record (`.json`) belongs to the worker, which rewrites it from memory whenever +// a terminal starts or exits. A cleanup that cannot confirm every process gone therefore keeps +// its state in a cleanup record of its own (`closing-.json`) that no worker writes, so +// the kill intent and what it could not confirm survive any later worker rewrite. +type TerminalWorkerRecordKind = "worker" | "cleanup"; + +export type TerminalWorkerRecordFile = + | { + // The file holding this record's state: the cleanup record when there is one. + path: string; + record: TerminalWorkerRecord; + // The worker's own record file, when it still exists. + workerRecordPath: string | null; + } + | { path: string; error: Error }; + +// The worker's command line carries this marker followed by its record id, so a reused pid +// running some other process (even another worker) never matches the record. +export const TERMINAL_WORKER_MARKER_ARG = "--paseo-terminal-worker"; + +export function terminalWorkerDirectory(paseoHome: string): string { + return path.join(paseoHome, "terminal-worker"); +} + +export function terminalWorkerRecordPath(paseoHome: string, workerPid: number): string { + return path.join(terminalWorkerDirectory(paseoHome), `${workerPid}.json`); +} + +export function terminalCleanupRecordPath(paseoHome: string, recordId: string): string { + return path.join(terminalWorkerDirectory(paseoHome), `closing-${recordId}.json`); +} + +export function terminalWorkerLogPath(paseoHome: string): string { + return path.join(paseoHome, "terminal-worker.log"); +} + +export function writeTerminalWorkerRecord(paseoHome: string, record: TerminalWorkerRecord): string { + const recordPath = terminalWorkerRecordPath(paseoHome, record.pid); + writePrivateFileAtomicSync(recordPath, `${JSON.stringify(record, null, 2)}\n`); + return recordPath; +} + +/** Writes the state of a cleanup that could not confirm every process gone. */ +export async function writeTerminalCleanupRecord( + paseoHome: string, + record: TerminalWorkerRecord & { closing: NonNullable }, +): Promise { + if (!RECORD_ID_PATTERN.test(record.recordId)) { + throw new Error(`Terminal worker record id is not a file name: ${record.recordId}`); + } + const recordPath = terminalCleanupRecordPath(paseoHome, record.recordId); + await writePrivateFileAtomic(recordPath, `${JSON.stringify(record, null, 2)}\n`); + return recordPath; +} + +export async function readTerminalWorkerRecord(recordPath: string): Promise { + return TerminalWorkerRecordSchema.parse(JSON.parse(await readRecordFile(recordPath))); +} + +// A worker rewrites its record by renaming a new file over it. On Windows an open() that races +// that rename fails with EPERM (or EBUSY) for a moment, so such an error is retried for a short +// window before the record counts as unreadable. Reads and retries yield so daemon status and +// cleanup never block unrelated requests while another process holds the record open. +const TRANSIENT_READ_ERRORS = new Set(["EPERM", "EBUSY", "EACCES"]); +const TRANSIENT_READ_WINDOW_MS = 250; +const TRANSIENT_READ_PAUSE_MS = 10; + +async function readRecordFile(recordPath: string): Promise { + const deadline = Date.now() + TRANSIENT_READ_WINDOW_MS; + for (;;) { + try { + return await readFile(recordPath, "utf8"); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (!code || !TRANSIENT_READ_ERRORS.has(code) || Date.now() >= deadline) throw error; + await delay(TRANSIENT_READ_PAUSE_MS); + } + } +} + +const RECORD_ID_PATTERN = /^[A-Za-z0-9-]+$/; +const WORKER_RECORD_NAME = /^\d+\.json$/; +const CLEANUP_RECORD_NAME = /^closing-[A-Za-z0-9-]+\.json$/; + +function recordKindOf(fileName: string): TerminalWorkerRecordKind | null { + if (WORKER_RECORD_NAME.test(fileName)) return "worker"; + if (CLEANUP_RECORD_NAME.test(fileName)) return "cleanup"; + return null; +} + +/** + * Every record in the home. A cleanup record is merged with the worker record of the same + * record id: its closing state wins, and terminals the worker recorded since join it, so the + * retry covers everything the worker still runs. + */ +export async function listTerminalWorkerRecords( + paseoHome: string, +): Promise { + const directory = terminalWorkerDirectory(paseoHome); + let names: string[]; + try { + names = await readdir(directory); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; + throw error; + } + const errors: TerminalWorkerRecordFile[] = []; + const workers: Array<{ path: string; record: TerminalWorkerRecord }> = []; + const cleanups: Array<{ path: string; record: TerminalWorkerRecord }> = []; + for (const name of names.sort()) { + const kind = recordKindOf(name); + if (!kind) continue; + const recordPath = path.join(directory, name); + try { + const record = await readTerminalWorkerRecord(recordPath); + (kind === "worker" ? workers : cleanups).push({ path: recordPath, record }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; + errors.push({ + path: recordPath, + error: error instanceof Error ? error : new Error(String(error)), + }); + } + } + const files: TerminalWorkerRecordFile[] = []; + const merged = new Set(); + for (const cleanup of cleanups) { + const worker = workers.find( + (entry) => + entry.record.recordId === cleanup.record.recordId && + entry.record.pid === cleanup.record.pid, + ); + if (worker) merged.add(worker.path); + const known = new Set(cleanup.record.terminals.map((entry) => `${entry.id}:${entry.pid}`)); + const added = (worker?.record.terminals ?? []).filter( + (entry) => !known.has(`${entry.id}:${entry.pid}`), + ); + files.push({ + path: cleanup.path, + record: { ...cleanup.record, terminals: [...cleanup.record.terminals, ...added] }, + workerRecordPath: worker?.path ?? null, + }); + } + for (const worker of workers) { + if (merged.has(worker.path)) continue; + files.push({ path: worker.path, record: worker.record, workerRecordPath: worker.path }); + } + return [...files, ...errors]; +} + +/** + * Deletes a record, the worker's own record file and the socket it names, unless a later worker + * that reused the pid wrote that file since. The pipe namespace on Windows needs no unlink. + */ +export async function retireTerminalWorkerRecord(file: { + path: string; + record: TerminalWorkerRecord; + workerRecordPath: string | null; +}): Promise { + if (file.path !== file.workerRecordPath) await rm(file.path, { force: true }); + if (file.workerRecordPath) { + if (await workerRecordNamesAnother(file.workerRecordPath, file.record.recordId)) return; + await rm(file.workerRecordPath, { force: true }); + } + if (process.platform !== "win32") { + await rm(file.record.socketPath, { force: true }); + } +} + +// True when the file now belongs to another worker, or cannot be read to tell. +async function workerRecordNamesAnother(recordPath: string, recordId: string): Promise { + try { + return (await readTerminalWorkerRecord(recordPath)).recordId !== recordId; + } catch (error) { + return (error as NodeJS.ErrnoException).code !== "ENOENT"; + } +} diff --git a/packages/server/src/terminal/terminal-worker-runtime.test.ts b/packages/server/src/terminal/terminal-worker-runtime.test.ts new file mode 100644 index 0000000000..feb4bf3309 --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-runtime.test.ts @@ -0,0 +1,222 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + statSync, + writeFileSync, +} from "node:fs"; +import { builtinModules } from "node:module"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { isPlatform } from "../test-utils/platform.js"; +import { + prepareTerminalWorkerRuntime, + pruneTerminalWorkerRuntimes, + TerminalWorkerRuntimeError, +} from "./terminal-worker-runtime.js"; +import { + terminalWorkerDirectory, + writeTerminalWorkerRecord, + type TerminalWorkerRecord, +} from "./terminal-worker-record.js"; + +const temporaryDirs: string[] = []; + +afterEach(() => { + for (const dir of temporaryDirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +function makeDir(prefix: string): string { + const dir = mkdtempSync(path.join(tmpdir(), prefix)); + temporaryDirs.push(dir); + return dir; +} + +// A built bundle directory and a node-pty package shaped like the real ones. +function makeSources(bundleSource = "export {};\n"): { + bundleDirectory: string; + nodePtyDirectory: string; +} { + const bundleDirectory = makeDir("tw-bundle-"); + writeFileSync(path.join(bundleDirectory, "terminal-worker.mjs"), bundleSource); + mkdirSync(path.join(bundleDirectory, "shell-integration", "zsh"), { recursive: true }); + writeFileSync(path.join(bundleDirectory, "shell-integration", "zsh", ".zshenv"), "# zsh\n"); + const nodePtyDirectory = makeDir("tw-node-pty-"); + writeFileSync(path.join(nodePtyDirectory, "package.json"), '{"version":"1.2.3"}\n'); + mkdirSync(path.join(nodePtyDirectory, "lib")); + writeFileSync(path.join(nodePtyDirectory, "lib", "index.js"), "module.exports = {};\n"); + const native = path.join(nodePtyDirectory, "prebuilds", `${process.platform}-${process.arch}`); + mkdirSync(native, { recursive: true }); + writeFileSync(path.join(native, "pty.node"), "native"); + writeFileSync(path.join(native, "spawn-helper"), "#!/bin/sh\n", { mode: 0o755 }); + // Another platform's build is not copied. + mkdirSync(path.join(nodePtyDirectory, "prebuilds", "other-platform")); + return { bundleDirectory, nodePtyDirectory }; +} + +function recordNaming(runtime: string | null, pid = 4242): TerminalWorkerRecord { + return { + recordId: `record-${pid}`, + pid, + bootId: null, + createdAt: new Date().toISOString(), + identity: { startedAt: "Thu Jan 1 00:00:00 1970", commandLine: "worker" }, + protocolVersion: 1, + paseoVersion: "1.0.0", + socketPath: "/tmp/does-not-exist.sock", + secret: "secret", + runtime, + terminals: [], + }; +} + +describe("terminal worker runtime copy", () => { + it("copies the bundle, its shell integration and this platform's node-pty into the home", () => { + const home = makeDir("tw-runtime-home-"); + const entry = prepareTerminalWorkerRuntime({ + paseoHome: home, + paseoVersion: "1.0.0-beta.1", + ...makeSources(), + }); + + const directory = path.join(terminalWorkerDirectory(home), entry.runtime!); + expect(entry.runtime).toMatch(/^1\.0\.0-beta\.1-[0-9a-f]{12}$/); + expect(entry.scriptPath).toBe(path.join(directory, "terminal-worker.mjs")); + expect(entry.execArgv).toEqual([]); + expect(existsSync(path.join(directory, "shell-integration", "zsh", ".zshenv"))).toBe(true); + const nodePty = path.join(directory, "node_modules", "node-pty"); + expect(existsSync(path.join(nodePty, "lib", "index.js"))).toBe(true); + expect(readdirSync(path.join(nodePty, "prebuilds"))).toEqual([ + `${process.platform}-${process.arch}`, + ]); + if (!isPlatform("win32")) { + const helper = path.join(nodePty, "prebuilds", `${process.platform}-${process.arch}`); + expect(statSync(path.join(helper, "spawn-helper")).mode & 0o111).toBe(0o111); + } + }); + + it("reuses a finished copy of the same content and makes a new one for a different build", () => { + const home = makeDir("tw-runtime-home-"); + const sources = makeSources(); + const first = prepareTerminalWorkerRuntime({ + paseoHome: home, + paseoVersion: "1.0.0", + ...sources, + }); + const marker = path.join(terminalWorkerDirectory(home), first.runtime!, "terminal-worker.mjs"); + writeFileSync(marker, "// the running copy\n"); + + const again = prepareTerminalWorkerRuntime({ + paseoHome: home, + paseoVersion: "1.0.0", + ...sources, + }); + const rebuilt = prepareTerminalWorkerRuntime({ + paseoHome: home, + paseoVersion: "1.0.0", + ...makeSources("export const rebuilt = true;\n"), + }); + + expect(again.runtime).toBe(first.runtime); + expect(statSync(marker).size).toBe("// the running copy\n".length); + expect(rebuilt.runtime).not.toBe(first.runtime); + }); + + it("replaces a copy an earlier run left unfinished", () => { + const home = makeDir("tw-runtime-home-"); + const sources = makeSources(); + const first = prepareTerminalWorkerRuntime({ + paseoHome: home, + paseoVersion: "1.0.0", + ...sources, + }); + const directory = path.join(terminalWorkerDirectory(home), first.runtime!); + rmSync(directory, { recursive: true }); + mkdirSync(directory); + + prepareTerminalWorkerRuntime({ paseoHome: home, paseoVersion: "1.0.0", ...sources }); + + expect(existsSync(path.join(directory, "terminal-worker.mjs"))).toBe(true); + }); + + it("fails before copying anything when node-pty has no native build for this platform", () => { + const home = makeDir("tw-runtime-home-"); + const sources = makeSources(); + rmSync(path.join(sources.nodePtyDirectory, "prebuilds"), { recursive: true }); + + expect(() => + prepareTerminalWorkerRuntime({ paseoHome: home, paseoVersion: "1.0.0", ...sources }), + ).toThrow(TerminalWorkerRuntimeError); + expect(readdirSync(terminalWorkerDirectory(home))).toEqual([]); + }); + + it("removes only copies no worker record names", async () => { + const home = makeDir("tw-runtime-home-"); + const used = prepareTerminalWorkerRuntime({ + paseoHome: home, + paseoVersion: "1.0.0", + ...makeSources(), + }); + const unused = prepareTerminalWorkerRuntime({ + paseoHome: home, + paseoVersion: "0.9.0", + ...makeSources(), + }); + writeTerminalWorkerRecord(home, recordNaming(used.runtime)); + const socketDirectory = path.join(terminalWorkerDirectory(home), "sock"); + mkdirSync(socketDirectory); + + const result = await pruneTerminalWorkerRuntimes(home); + + expect(result.removed).toEqual([path.join(terminalWorkerDirectory(home), unused.runtime!)]); + expect(existsSync(path.dirname(used.scriptPath))).toBe(true); + expect(existsSync(socketDirectory)).toBe(true); + }); + + it("removes nothing while a record cannot be read", async () => { + const home = makeDir("tw-runtime-home-"); + const copy = prepareTerminalWorkerRuntime({ + paseoHome: home, + paseoVersion: "1.0.0", + ...makeSources(), + }); + writeFileSync(path.join(terminalWorkerDirectory(home), "4242.json"), "{ not json"); + + expect((await pruneTerminalWorkerRuntimes(home)).removed).toEqual([]); + expect(existsSync(copy.scriptPath)).toBe(true); + }); +}); + +describe("terminal worker bundle", () => { + // The copy holds the bundle and node-pty only. A package the bundle loads at run time + // (a require hidden from esbuild behind createRequire) would be missing from it. + it("loads nothing at run time but Node built-ins and node-pty", async () => { + const outDir = makeDir("tw-bundle-build-"); + const script = fileURLToPath( + new URL("../../scripts/build-terminal-worker.mjs", import.meta.url), + ); + const { buildTerminalWorkerBundle } = (await import(script)) as { + buildTerminalWorkerBundle(input: { outDir: string }): Promise; + }; + await buildTerminalWorkerBundle({ outDir }); + + const bundle = readFileSync(path.join(outDir, "terminal-worker.mjs"), "utf8"); + const loaded = new Set(); + for (const match of bundle.matchAll( + /(?:\brequire\w*(?:\.resolve)?\(|\bfrom\s+|\bimport\s*\()\s*"([^"]+)"/g, + )) { + loaded.add(match[1]!); + } + const builtins = new Set(builtinModules.flatMap((name) => [name, `node:${name}`])); + const packages = [...loaded].filter((specifier) => !builtins.has(specifier)); + expect(packages.map((specifier) => specifier.split("/")[0])).toEqual( + packages.map(() => "node-pty"), + ); + expect(existsSync(path.join(outDir, "shell-integration", "zsh"))).toBe(true); + }); +}); diff --git a/packages/server/src/terminal/terminal-worker-runtime.ts b/packages/server/src/terminal/terminal-worker-runtime.ts new file mode 100644 index 0000000000..7ee0696478 --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-runtime.ts @@ -0,0 +1,249 @@ +import { createHash, randomUUID } from "node:crypto"; +import { + chmodSync, + existsSync, + mkdirSync, + readdirSync, + readFileSync, + renameSync, + rmSync, + statSync, + writeFileSync, +} from "node:fs"; +import { createRequire } from "node:module"; +import { access, readdir, rm } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { ensurePrivateDirectory } from "../server/private-files.js"; +import { listTerminalWorkerRecords, terminalWorkerDirectory } from "./terminal-worker-record.js"; + +// A terminal worker outlives the installation that started it. An npm or desktop update +// replaces that installation's files, so a worker launched from them would fail its next +// terminal create (node-pty's spawn-helper, the zsh integration). A built daemon therefore +// copies the worker bundle, its shell integration and node-pty into +// $PASEO_HOME/terminal-worker/-/ and launches the worker from there. +// The hash keeps two builds of one version (a local rebuild) from sharing a copy. A copy is +// removed once no worker record names it: after a worker drains, after a kill cleanup, and at +// daemon start. Dev runs (.ts source) launch from source and copy nothing. + +export const TERMINAL_WORKER_BUNDLE_NAME = "terminal-worker.mjs"; +// Written last into a finished copy; a directory without it is an interrupted copy. +const RUNTIME_MARKER = "paseo-terminal-worker-runtime.json"; +const TEMP_PREFIX = ".tmp-"; + +export class TerminalWorkerRuntimeError extends Error { + constructor(message: string, options?: { cause?: unknown }) { + super(message, options); + this.name = "TerminalWorkerRuntimeError"; + } +} + +/** What the launcher runs: the worker script, the node flags it needs, and the copy it is in. */ +export interface TerminalWorkerEntry { + scriptPath: string; + execArgv: string[]; + /** The copy's directory name under terminal-worker/, or null when run from source. */ + runtime: string | null; +} + +function sourceExecArgv(): string[] { + const loaderUrl = new URL("./terminal-ts-loader.mjs", import.meta.url).href; + const importSource = [ + 'import { register } from "node:module";', + 'import { pathToFileURL } from "node:url";', + `register(${JSON.stringify(loaderUrl)}, pathToFileURL("./"));`, + ].join(" "); + return [ + "--experimental-strip-types", + "--import", + `data:text/javascript,${encodeURIComponent(importSource)}`, + ]; +} + +/** + * The entry a daemon launches its worker from: the source file in dev, otherwise a copy of the + * built bundle in this home, prepared on demand. + */ +export function resolveTerminalWorkerEntry(input: { + paseoHome: string; + paseoVersion: string; +}): TerminalWorkerEntry { + if (import.meta.url.endsWith(".ts")) { + return { + scriptPath: fileURLToPath(new URL("./terminal-worker-process.ts", import.meta.url)), + execArgv: sourceExecArgv(), + runtime: null, + }; + } + const bundleDirectory = fileURLToPath(new URL("../terminal-worker/", import.meta.url)); + if (!existsSync(path.join(bundleDirectory, TERMINAL_WORKER_BUNDLE_NAME))) { + throw new TerminalWorkerRuntimeError( + `The terminal worker bundle is missing from ${bundleDirectory}; rebuild @getpaseo/server (npm run build).`, + ); + } + const require = createRequire(import.meta.url); + const nodePtyDirectory = path.dirname(require.resolve("node-pty/package.json")); + return prepareTerminalWorkerRuntime({ + paseoHome: input.paseoHome, + paseoVersion: input.paseoVersion, + bundleDirectory, + nodePtyDirectory, + }); +} + +function runtimeName(input: { + paseoVersion: string; + bundleDirectory: string; + nodePtyDirectory: string; +}): string { + const hash = createHash("sha256"); + hash.update(readFileSync(path.join(input.bundleDirectory, TERMINAL_WORKER_BUNDLE_NAME))); + hash.update(readFileSync(path.join(input.nodePtyDirectory, "package.json"))); + hash.update(`${process.platform}-${process.arch}`); + const version = input.paseoVersion.replace(/[^A-Za-z0-9._-]/g, "_"); + return `${version}-${hash.digest("hex").slice(0, 12)}`; +} + +// Plain fs calls on purpose: inside the desktop app the sources live in app.asar, which +// Electron's fs reads transparently but newer helpers like cpSync do not. +function copyTree(source: string, destination: string): void { + const stat = statSync(source); + if (stat.isDirectory()) { + mkdirSync(destination, { recursive: true }); + for (const name of readdirSync(source)) { + copyTree(path.join(source, name), path.join(destination, name)); + } + return; + } + writeFileSync(destination, readFileSync(source)); + // Keeps node-pty's spawn-helper executable. + chmodSync(destination, stat.mode & 0o777); +} + +function copyNodePty(source: string, destination: string): void { + mkdirSync(destination, { recursive: true }); + copyTree(path.join(source, "package.json"), path.join(destination, "package.json")); + copyTree(path.join(source, "lib"), path.join(destination, "lib")); + const native = [ + path.join("build", "Release"), + path.join("prebuilds", `${process.platform}-${process.arch}`), + ].filter((relative) => existsSync(path.join(source, relative))); + if (native.length === 0) { + throw new TerminalWorkerRuntimeError( + `node-pty at ${source} has no native build for ${process.platform}-${process.arch}`, + ); + } + for (const relative of native) { + copyTree(path.join(source, relative), path.join(destination, relative)); + } +} + +function isCompleteRuntime(directory: string): boolean { + return existsSync(path.join(directory, RUNTIME_MARKER)); +} + +/** + * Copies the worker bundle, its shell integration and node-pty into this home, unless a finished + * copy of the same content is already there. Returns the entry to launch from the copy. + */ +export function prepareTerminalWorkerRuntime(input: { + paseoHome: string; + paseoVersion: string; + bundleDirectory: string; + nodePtyDirectory: string; +}): TerminalWorkerEntry { + const root = terminalWorkerDirectory(input.paseoHome); + ensurePrivateDirectory(root); + const name = runtimeName(input); + const directory = path.join(root, name); + const entry = { + scriptPath: path.join(directory, TERMINAL_WORKER_BUNDLE_NAME), + execArgv: [], + runtime: name, + }; + if (isCompleteRuntime(directory)) return entry; + + // An interrupted copy left behind: no worker can be running from it. + rmSync(directory, { recursive: true, force: true }); + const temporary = path.join(root, `${TEMP_PREFIX}${name}-${randomUUID()}`); + try { + mkdirSync(temporary, { recursive: true }); + copyTree( + path.join(input.bundleDirectory, TERMINAL_WORKER_BUNDLE_NAME), + path.join(temporary, TERMINAL_WORKER_BUNDLE_NAME), + ); + copyTree( + path.join(input.bundleDirectory, "shell-integration"), + path.join(temporary, "shell-integration"), + ); + copyNodePty(input.nodePtyDirectory, path.join(temporary, "node_modules", "node-pty")); + writeFileSync( + path.join(temporary, RUNTIME_MARKER), + `${JSON.stringify({ paseoVersion: input.paseoVersion, copiedAt: new Date().toISOString() })}\n`, + ); + renameSync(temporary, directory); + } catch (error) { + rmSync(temporary, { recursive: true, force: true }); + if (isCompleteRuntime(directory)) return entry; + throw new TerminalWorkerRuntimeError( + `Cannot copy the terminal worker into ${directory}: ${error instanceof Error ? error.message : String(error)}`, + { cause: error }, + ); + } + return entry; +} + +export interface PruneTerminalWorkerRuntimesResult { + removed: string[]; + /** Copies that could not be deleted (a worker that just exited can still hold files on Windows). */ + failed: Array<{ directory: string; error: string }>; +} + +/** + * Deletes every copy no worker record names. With an unreadable record it deletes nothing: that + * record could name a copy a live worker runs from. + */ +export async function pruneTerminalWorkerRuntimes( + paseoHome: string, +): Promise { + const result: PruneTerminalWorkerRuntimesResult = { removed: [], failed: [] }; + const root = terminalWorkerDirectory(paseoHome); + const files = await listTerminalWorkerRecords(paseoHome); + const inUse = new Set(); + for (const file of files) { + if ("error" in file) return result; + if (file.record.runtime) inUse.add(file.record.runtime); + } + let names: string[]; + try { + names = await readdir(root); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return result; + throw error; + } + for (const name of names) { + if (inUse.has(name)) continue; + const directory = path.join(root, name); + if ( + !name.startsWith(TEMP_PREFIX) && + !(await access(path.join(directory, RUNTIME_MARKER)).then( + () => true, + (error: NodeJS.ErrnoException) => { + if (error.code === "ENOENT" || error.code === "ENOTDIR") return false; + throw error; + }, + )) + ) + continue; + try { + await rm(directory, { recursive: true, force: true }); + result.removed.push(directory); + } catch (error) { + result.failed.push({ + directory, + error: error instanceof Error ? error.message : String(error), + }); + } + } + return result; +} diff --git a/packages/server/src/terminal/terminal-worker-socket-path.test.ts b/packages/server/src/terminal/terminal-worker-socket-path.test.ts new file mode 100644 index 0000000000..409cf60c81 --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-socket-path.test.ts @@ -0,0 +1,134 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync } from "node:fs"; +import { createServer } from "node:net"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { isPlatform } from "../test-utils/platform.js"; +import { + resolveTerminalWorkerSocketPath, + TerminalWorkerSocketPathError, +} from "./terminal-worker-socket-path.js"; + +const temporaryDirs: string[] = []; + +function makeDir(prefix: string, root = tmpdir()): string { + const dir = mkdtempSync(path.join(root, prefix)); + temporaryDirs.push(dir); + return dir; +} + +// A home path long enough that its socket cannot fit sun_path, with multi-byte segments so the +// budget is measured in bytes, not characters. +function longHome(root: string): string { + const home = path.join(root, "worktree-ñandú-".repeat(5), "paseo-home"); + mkdirSync(home, { recursive: true }); + return home; +} + +afterEach(() => { + for (const dir of temporaryDirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }); + } +}); + +describe.skipIf(isPlatform("win32"))("terminal worker socket path", () => { + it("uses the home's own socket directory when the path fits", () => { + // macOS $TMPDIR alone is ~50 bytes; a short root keeps the home's own path in budget. + const home = makeDir("tw-h-", "/tmp"); + const socketPath = resolveTerminalWorkerSocketPath({ + paseoHome: home, + workerPid: 4242, + platform: "darwin", + }); + expect(socketPath.startsWith(path.join(home, "terminal-worker", "sock"))).toBe(true); + }); + + it("falls to /tmp/paseo- when the home and TMPDIR are too long, within the byte budget", () => { + const root = makeDir("tw-sock-long-"); + const home = longHome(root); + const tmpDir = path.join(root, "tmp-ñandú-".repeat(6)); + mkdirSync(tmpDir, { recursive: true }); + const uid = process.getuid!(); + const socketPath = resolveTerminalWorkerSocketPath({ + paseoHome: home, + workerPid: 99999, + platform: "darwin", + tmpDir, + }); + expect(path.dirname(socketPath)).toBe(`/tmp/paseo-${uid}`); + expect(Buffer.byteLength(socketPath, "utf8")).toBeLessThanOrEqual(103); + }); + + it("rejects a shared-root directory that is a symlink, has another mode, or is not a directory", () => { + const root = makeDir("tw-sock-reject-"); + const home = longHome(root); + const uid = process.getuid!(); + const tmpDir = makeDir("tw-"); + const target = makeDir("tw-target-"); + chmodSync(target, 0o700); + symlinkSync(target, path.join(tmpDir, `paseo-${uid}`)); + // A budget check alone would accept the long-home fallback through the symlink; it must + // also be refused, and /tmp/paseo- takes over. + const socketPath = resolveTerminalWorkerSocketPath({ + paseoHome: home, + workerPid: 7, + platform: "darwin", + tmpDir, + }); + expect(path.dirname(socketPath)).toBe(`/tmp/paseo-${uid}`); + + const wideTmp = makeDir("tw-"); + mkdirSync(path.join(wideTmp, `paseo-${uid}`), { mode: 0o755 }); + chmodSync(path.join(wideTmp, `paseo-${uid}`), 0o755); + expect( + path.dirname( + resolveTerminalWorkerSocketPath({ + paseoHome: home, + workerPid: 7, + platform: "darwin", + tmpDir: wideTmp, + }), + ), + ).toBe(`/tmp/paseo-${uid}`); + }); + + it("names every rejected candidate with its byte length when none fits", () => { + const root = makeDir("tw-sock-none-"); + const home = longHome(root); + const tmpDir = path.join(root, "tmp-ñandú-".repeat(6)); + mkdirSync(tmpDir, { recursive: true }); + let caught: unknown; + try { + resolveTerminalWorkerSocketPath({ + paseoHome: home, + workerPid: 7, + platform: "darwin", + tmpDir, + // Another uid's /tmp/paseo- directory does not exist or is not ours; with a uid + // nobody owns, the /tmp candidate's directory is created by us but owned by our real + // uid, so it is rejected for its owner. + uid: 2_000_000_000, + }); + } catch (error) { + caught = error; + } + rmSync("/tmp/paseo-2000000000", { recursive: true, force: true }); + expect(caught).toBeInstanceOf(TerminalWorkerSocketPathError); + const rejected = (caught as TerminalWorkerSocketPathError).rejected; + expect(rejected).toHaveLength(3); + expect(rejected[0].reason).toMatch(/longer than 103 bytes/); + expect(rejected[0].byteLength).toBe(Buffer.byteLength(rejected[0].path, "utf8")); + expect(rejected[2].reason).toMatch(/owned by uid/); + }); + + it("accepts a real listen on the chosen path", async () => { + const home = makeDir("tw-l-", "/tmp"); + const socketPath = resolveTerminalWorkerSocketPath({ paseoHome: home, workerPid: 5 }); + const server = createServer(); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(socketPath, () => resolve()); + }); + await new Promise((resolve) => server.close(() => resolve())); + }); +}); diff --git a/packages/server/src/terminal/terminal-worker-socket-path.ts b/packages/server/src/terminal/terminal-worker-socket-path.ts new file mode 100644 index 0000000000..99fce0e64c --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-socket-path.ts @@ -0,0 +1,133 @@ +import { createHash } from "node:crypto"; +import { lstatSync, mkdirSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { ensurePrivateDirectory } from "../server/private-files.js"; +import { terminalWorkerDirectory } from "./terminal-worker-record.js"; + +// `sun_path` holds 104 bytes on macOS and 108 on Linux, NUL included. Dev homes under +// worktrees and long $TMPDIR values exceed that, so the socket goes to the first owner-only +// directory whose full path fits, measured in UTF-8 bytes. +const SOCKET_PATH_BYTE_BUDGET: Partial> = { + darwin: 103, + linux: 107, +}; +const DEFAULT_SOCKET_PATH_BYTE_BUDGET = 103; +const OWNER_ONLY_MODE = 0o700; + +export interface TerminalWorkerSocketPathInput { + paseoHome: string; + workerPid: number; + platform?: NodeJS.Platform; + tmpDir?: string; + uid?: number; +} + +export interface RejectedSocketCandidate { + path: string; + byteLength: number; + reason: string; +} + +export class TerminalWorkerSocketPathError extends Error { + readonly rejected: RejectedSocketCandidate[]; + + constructor(rejected: RejectedSocketCandidate[], budget: number) { + super( + [ + `No terminal worker socket path fits ${budget} bytes in an owner-only directory:`, + ...rejected.map( + (candidate) => ` ${candidate.path} (${candidate.byteLength} bytes): ${candidate.reason}`, + ), + ].join("\n"), + ); + this.name = "TerminalWorkerSocketPathError"; + this.rejected = rejected; + } +} + +/** First 16 hex chars of sha256(home) plus the worker pid: unique per home and worker. */ +export function terminalWorkerSocketId(paseoHome: string, workerPid: number): string { + const digest = createHash("sha256").update(path.resolve(paseoHome)).digest("hex"); + return `${digest.slice(0, 16)}-${workerPid}`; +} + +/** + * Picks (and creates) the socket path a worker listens on. Windows uses a named pipe; POSIX + * tries $PASEO_HOME/terminal-worker/sock, then /paseo-, then /tmp/paseo-. + * A shared root is never chmodded: an existing directory there is used only when it is a real + * directory owned by this user with mode 0700. + */ +export function resolveTerminalWorkerSocketPath(input: TerminalWorkerSocketPathInput): string { + const platform = input.platform ?? process.platform; + const id = terminalWorkerSocketId(input.paseoHome, input.workerPid); + if (platform === "win32") { + return `\\\\.\\pipe\\paseo-tw-${id}`; + } + + const uid = input.uid ?? process.getuid?.() ?? 0; + const budget = SOCKET_PATH_BYTE_BUDGET[platform] ?? DEFAULT_SOCKET_PATH_BYTE_BUDGET; + const fileName = `tw-${id}.sock`; + const homeSocketDirectory = path.join(terminalWorkerDirectory(input.paseoHome), "sock"); + const candidates: Array<{ directory: string; prepare: () => string | null }> = [ + { + directory: homeSocketDirectory, + prepare: () => { + ensurePrivateDirectory(homeSocketDirectory); + return verifyOwnerOnlyDirectory(homeSocketDirectory, uid); + }, + }, + ...[input.tmpDir ?? tmpdir(), "/tmp"].map((root) => { + const directory = path.join(root, `paseo-${uid}`); + return { + directory, + prepare: () => prepareSharedRootDirectory(directory, uid), + }; + }), + ]; + + const rejected: RejectedSocketCandidate[] = []; + const seen = new Set(); + for (const candidate of candidates) { + const socketPath = path.join(candidate.directory, fileName); + if (seen.has(socketPath)) continue; + seen.add(socketPath); + const byteLength = Buffer.byteLength(socketPath, "utf8"); + if (byteLength > budget) { + rejected.push({ path: socketPath, byteLength, reason: `longer than ${budget} bytes` }); + continue; + } + let problem: string | null; + try { + problem = candidate.prepare(); + } catch (error) { + problem = error instanceof Error ? error.message : String(error); + } + if (problem) { + rejected.push({ path: socketPath, byteLength, reason: problem }); + continue; + } + return socketPath; + } + throw new TerminalWorkerSocketPathError(rejected, budget); +} + +function prepareSharedRootDirectory(directory: string, uid: number): string | null { + try { + mkdirSync(directory, { mode: OWNER_ONLY_MODE }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + } + return verifyOwnerOnlyDirectory(directory, uid); +} + +/** Returns why the directory cannot hold the socket, or null when it is owner-only. */ +function verifyOwnerOnlyDirectory(directory: string, uid: number): string | null { + const stats = lstatSync(directory); + if (stats.isSymbolicLink()) return "is a symlink"; + if (!stats.isDirectory()) return "is not a directory"; + if (stats.uid !== uid) return `is owned by uid ${stats.uid}, not ${uid}`; + const mode = stats.mode & 0o777; + if (mode !== OWNER_ONLY_MODE) return `has mode ${mode.toString(8)}, not 700`; + return null; +} diff --git a/packages/server/src/terminal/terminal.ts b/packages/server/src/terminal/terminal.ts index 24f243b6ea..b8cb7ee8cd 100644 --- a/packages/server/src/terminal/terminal.ts +++ b/packages/server/src/terminal/terminal.ts @@ -15,6 +15,11 @@ import { basename, delimiter, dirname, extname, join, resolve as resolvePath } f import { createRequire } from "node:module"; import { fileURLToPath } from "node:url"; import { createExternalProcessEnv } from "../server/paseo-env.js"; +import { + resolveExternalProcessPath, + resolvePaseoCliBinDir, + resolvePaseoCliExecutablePath, +} from "./paseo-cli-path.js"; import { writePrivateFileAtomicSync } from "../server/private-files.js"; import { findExecutable, @@ -27,7 +32,6 @@ import type { TerminalActivity, TerminalActivityState } from "@getpaseo/protocol const { Terminal } = xterm; const require = createRequire(import.meta.url); -const PASEO_CLI_BIN_ENTRY = "@getpaseo/cli/bin/paseo"; let nodePtySpawnHelperChecked = false; const TERMINAL_TITLE_DEBOUNCE_MS = 150; const TERMINAL_EXIT_OUTPUT_LINE_LIMIT = 12; @@ -123,6 +127,11 @@ export interface TerminalSession { killAndWait(options?: { gracefulTimeoutMs?: number; forceTimeoutMs?: number }): Promise; } +/** A session that owns its PTY in this process, so it knows the program's pid. */ +export interface LocalTerminalSession extends TerminalSession { + readonly pid: number; +} + function parseCommandFinishedOsc(data: string): TerminalCommandFinishedInfo | null { // OSC 633 is terminal control traffic, but a foreground command can still // print arbitrary control bytes. Keep this boundary to the exact VS Code @@ -153,6 +162,11 @@ export interface CreateTerminalOptions { title?: string; command?: string; args?: string[]; + // Environment the terminal starts from instead of this process's own. A detached terminal + // worker outlives the daemon that launched it, so each create carries the controlling + // daemon's environment and its resolved Paseo CLI path. + baseEnv?: Record; + paseoCliPath?: string | null; } function toTerminalActivity(snapshot: { @@ -181,6 +195,7 @@ function isTerminalActivityInterruptInput(data: string): boolean { interface BuildTerminalEnvironmentInput { shell: string; env: Record; + baseEnv?: Record; zshShellIntegrationDir?: string; paseoCliBinDir?: string | null; paseoHookCliPath?: string | null; @@ -410,84 +425,12 @@ export async function resolveTerminalSpawnCommand( return { command: resolved, args }; } +export { resolvePaseoCliBinDir, resolvePaseoCliExecutablePath }; + export function resolveZshShellIntegrationDir(): string { return fileURLToPath(new URL("./shell-integration/zsh", import.meta.url)); } -function resolveExternalProcessPath(filePath: string): string { - return filePath.replace(/\.asar(?=[/\\]|$)/, ".asar.unpacked"); -} - -export function resolvePaseoCliBinDir(): string | null { - const cliExecutable = resolvePaseoCliExecutablePath(); - return cliExecutable ? dirname(cliExecutable) : null; -} - -export function resolvePaseoCliExecutablePath(): string | null { - const configuredCli = process.env.PASEO_CLI?.trim(); - if (configuredCli) { - return resolvePath(configuredCli); - } - - const cliEntrypoint = resolvePaseoCliBinEntrypoint(); - if (!cliEntrypoint) { - return null; - } - - const externalCliEntrypoint = resolveExternalProcessPath(cliEntrypoint); - const npmBinDir = findNpmBinDir(dirname(externalCliEntrypoint)); - if (npmBinDir) { - const shim = resolvePaseoCliShim(npmBinDir); - if (shim) { - return shim; - } - } - - return externalCliEntrypoint; -} - -function resolvePaseoCliBinEntrypoint(): string | null { - try { - return require.resolve(PASEO_CLI_BIN_ENTRY); - } catch { - return null; - } -} - -function findNpmBinDir(startPath: string): string | null { - let current = startPath; - while (true) { - const candidate = join(current, "node_modules", ".bin"); - if (hasPaseoCliShim(candidate)) { - return candidate; - } - - const parent = dirname(current); - if (parent === current) { - return null; - } - current = parent; - } -} - -function hasPaseoCliShim(binDir: string): boolean { - return resolvePaseoCliShim(binDir) !== null; -} - -function resolvePaseoCliShim(binDir: string): string | null { - for (const name of paseoCliShimNames()) { - const candidate = join(binDir, name); - if (existsSync(candidate)) { - return candidate; - } - } - return null; -} - -function paseoCliShimNames(): string[] { - return process.platform === "win32" ? ["paseo.cmd", "paseo.exe", "paseo"] : ["paseo"]; -} - function resolveZshShellIntegrationRuntimeDir(): string { let username = "unknown"; try { @@ -517,10 +460,14 @@ function prepareZshShellIntegrationRuntimeDir(sourceDir = resolveZshShellIntegra export function buildTerminalEnvironment( input: BuildTerminalEnvironmentInput, ): Record { - const baseEnv: Record = createExternalProcessEnv(process.env, input.env, { - TERM: "xterm-256color", - TERM_PROGRAM: "kitty", - }); + const baseEnv: Record = createExternalProcessEnv( + input.baseEnv ?? process.env, + input.env, + { + TERM: "xterm-256color", + TERM_PROGRAM: "kitty", + }, + ); const envWithAgentHooks = prependPaseoCliToPath( baseEnv, input.paseoCliBinDir === undefined ? resolvePaseoCliBinDir() : input.paseoCliBinDir, @@ -556,6 +503,23 @@ function injectPaseoHookCli( }; } +// The environment and CLI path a terminal starts from: the caller's when it sends them (the +// daemon controlling a detached worker does), this process's otherwise. +function resolveTerminalEnvironmentSource( + input: Pick, +): Pick { + const source: Pick< + BuildTerminalEnvironmentInput, + "baseEnv" | "paseoCliBinDir" | "paseoHookCliPath" + > = {}; + if (input.baseEnv) source.baseEnv = input.baseEnv; + if (input.paseoCliPath !== undefined) { + source.paseoCliBinDir = input.paseoCliPath ? dirname(input.paseoCliPath) : null; + source.paseoHookCliPath = input.paseoCliPath; + } + return source; +} + function prependPaseoCliToPath( env: Record, cliBinDir: string | null, @@ -967,7 +931,9 @@ export async function assertTerminalCommandCanStart( } } -export async function createTerminal(options: CreateTerminalOptions): Promise { +export async function createTerminal( + options: CreateTerminalOptions, +): Promise { const { cwd, workspaceId, @@ -980,8 +946,10 @@ export async function createTerminal(options: CreateTerminalOptions): Promise void>(); @@ -1033,6 +1001,7 @@ export async function createTerminal(options: CreateTerminalOptions): Promise void): boolean { @@ -100,14 +131,7 @@ class FakeTerminalWorker extends EventEmitter { disconnect(): void { this.connected = false; - this.emit("exit", 0, null); - } - - kill(): boolean { - this.killed = true; - this.connected = false; - this.emit("exit", 0, null); - return true; + this.emit("close"); } emitWorkerMessage(message: TerminalWorkerToParentMessage): void { @@ -115,8 +139,27 @@ class FakeTerminalWorker extends EventEmitter { } } -let manager: TerminalManager | null = null; +let manager: DaemonTerminalManager | null = null; const temporaryDirs: string[] = []; + +// A real detached worker in a throwaway home; afterEach closes its terminals and the worker. +async function startRealWorkerManager( + options: { getTerminalActivityUrl?: () => string | null; paseoHome?: string } = {}, +): Promise { + const { paseoHome = createTemporaryHome(), ...rest } = options; + return startWorkerTerminalManager({ + paseoHome, + paseoVersion: "0.0.0-test", + logger: pino({ level: "silent" }), + ...rest, + }); +} + +function createTemporaryHome(): string { + const paseoHome = mkdtempSync(join(tmpdir(), "worker-terminal-manager-home-")); + temporaryDirs.push(paseoHome); + return paseoHome; +} const terminalSessions: TerminalSession[] = []; function trackTerminal(session: TerminalSession): TerminalSession { @@ -150,7 +193,7 @@ afterEach(async () => { .catch(() => {}), ), ); - manager?.killAll(); + await manager?.closeTerminals(); manager = null; while (temporaryDirs.length > 0) { const dir = temporaryDirs.pop(); @@ -160,10 +203,177 @@ afterEach(async () => { } }); +it("retires a killed worker's sessions and shares one replacement across concurrent creates", async () => { + const paseoHome = createTemporaryHome(); + manager = await startRealWorkerManager({ paseoHome }); + manager.registerCwdEnv({ cwd: paseoHome, env: { QA_RECOVERY_ENV: "retained" } }); + const terminal = await manager.createTerminal({ + workspaceId: "ws-recovery", + cwd: paseoHome, + ...nodeTerminalCommand( + "process.stdin.on('data', chunk => process.stdout.write('echo:' + process.env.QA_RECOVERY_ENV + ':' + chunk)); setInterval(() => {}, 1000)", + ), + }); + const records = await listTerminalWorkerRecords(paseoHome); + const file = records.find((entry) => !("error" in entry)); + if (!file || "error" in file) throw new Error("Missing worker record"); + const changes: string[][] = []; + manager.subscribeTerminalsChanged((event) => + changes.push(event.terminals.map((item) => item.id)), + ); + const exits: unknown[] = []; + terminal.onExit((info) => exits.push(info)); + process.kill(file.record.pid, "SIGKILL"); + await waitForCondition(() => manager!.getTerminal(terminal.id) === undefined, 10000); + expect(changes).toContainEqual([]); + expect(exits).toHaveLength(1); + const sessions = await Promise.all( + Array.from({ length: 4 }, () => + manager!.createTerminal({ + workspaceId: "ws-recovery", + cwd: paseoHome, + ...nodeTerminalCommand( + "process.stdin.on('data', chunk => process.stdout.write('echo:' + process.env.QA_RECOVERY_ENV + ':' + chunk)); setInterval(() => {}, 1000)", + ), + }), + ), + ); + for (const session of sessions) { + const output: string[] = []; + session.subscribe((message) => { + if (message.type === "output") output.push(message.data); + }); + session.send({ type: "input", data: "recovered\r" }); + await waitForCondition(() => output.join("").includes("echo:retained:recovered"), 10000); + } + expect(await manager.getTerminals(paseoHome)).toHaveLength(4); + const remaining = (await listTerminalWorkerRecords(paseoHome)).filter( + (entry) => !("error" in entry), + ); + expect(remaining).toHaveLength(1); +}, 30000); + +it("reconnects a live worker without replacing terminal sessions or processes", async () => { + const paseoHome = createTemporaryHome(); + manager = await startRealWorkerManager({ paseoHome }); + const terminal = await manager.createTerminal({ + workspaceId: "ws-reconnect", + cwd: paseoHome, + ...nodeTerminalCommand( + "process.stdin.on('data', chunk => process.stdout.write('echo:' + chunk)); setInterval(() => {}, 1000)", + ), + }); + const [before] = await workerRecords(paseoHome); + const pids = await recordedTerminalPids(paseoHome); + let replayRequests = 0; + terminal.subscribe((message) => { + if (message.type === "snapshotReady") replayRequests += 1; + }); + // A second authenticated controller replaces the daemon's socket. The process stays alive. + const competitor = await connectTerminalWorker({ + socketPath: before!.socketPath, + secret: before!.secret, + }); + await waitForCondition(() => !competitor.connected, 10000); + await waitForCondition(async () => { + try { + return (await manager!.getTerminalState(terminal.id)) !== null; + } catch { + return false; + } + }, 10000); + await waitForCondition(() => replayRequests > 0, 1000); + expect(manager.getTerminal(terminal.id)).toBe(terminal); + expect(await recordedTerminalPids(paseoHome)).toEqual(pids); + expect((await workerRecords(paseoHome)).map((record) => record.pid)).toEqual([before!.pid]); + const output: string[] = []; + terminal.subscribe((message) => { + if (message.type === "output") output.push(message.data); + }); + terminal.send({ type: "input", data: "reconnected\r" }); + await waitForCondition(() => output.join("").includes("echo:reconnected"), 10000); +}, 30000); + +it.each(["detach", "closeTerminals"] as const)( + "does not replace a failed worker during %s", + async (operation) => { + const paseoHome = createTemporaryHome(); + manager = await startRealWorkerManager({ paseoHome }); + await manager.createTerminal({ + workspaceId: "ws-stop-recovery", + cwd: paseoHome, + ...nodeTerminalCommand("setInterval(() => {}, 1000)"), + }); + const [record] = await workerRecords(paseoHome); + process.kill(record!.pid, "SIGKILL"); + await manager[operation](); + await expect( + manager.createTerminal({ workspaceId: "ws-stop-recovery", cwd: paseoHome }), + ).rejects.toBeInstanceOf(NoTerminalWorkerAvailableError); + await manager.closeTerminals(); + expect(await workerRecords(paseoHome)).toEqual([]); + }, + 30000, +); + +it.each(["detach", "closeTerminals"] as const)( + "does not leak a replacement stopped during launch by %s", + async (operation) => { + const paseoHome = createTemporaryHome(); + manager = await startRealWorkerManager({ paseoHome }); + const terminal = await manager.createTerminal({ + workspaceId: "ws-launch-race", + cwd: paseoHome, + ...nodeTerminalCommand("setInterval(() => {}, 1000)"), + }); + const [record] = await workerRecords(paseoHome); + process.kill(record!.pid, "SIGKILL"); + await waitForCondition(() => !manager!.getTerminal(terminal.id), 10000); + const creating = manager.createTerminal({ workspaceId: "ws-launch-race", cwd: paseoHome }); + const rejected = expect(creating).rejects.toBeInstanceOf(NoTerminalWorkerAvailableError); + await manager[operation](); + await rejected; + await waitForCondition(async () => (await workerRecords(paseoHome)).length === 0, 10000); + expect(await manager.getTerminals(paseoHome)).toEqual([]); + }, + 30000, +); + +it.each(["current", "draining"] as const)( + "keeps the peer usable when the %s worker dies", + async (target) => { + const paseoHome = createTemporaryHome(); + const old = await leaveWorkerWithTerminal(paseoHome, 0); + manager = await startRealWorkerManager({ paseoHome }); + const added = await manager.createTerminal({ + workspaceId: "ws-peer", + cwd: old.cwd, + ...nodeTerminalCommand("setInterval(() => {}, 1000)"), + }); + const current = (await workerRecords(paseoHome)).find( + (record) => record.pid !== old.workerPid, + )!; + const deadId = target === "current" ? added.id : old.terminalId; + const healthyId = target === "current" ? old.terminalId : added.id; + const healthy = manager.getTerminal(healthyId); + process.kill(target === "current" ? current.pid : old.workerPid, "SIGKILL"); + await waitForCondition(() => !manager!.getTerminal(deadId), 10000); + expect(manager.getTerminal(healthyId)).toBe(healthy); + expect(await manager.getTerminalState(healthyId)).not.toBeNull(); + await manager.createTerminal({ + workspaceId: "ws-peer", + cwd: old.cwd, + ...nodeTerminalCommand("setInterval(() => {}, 1000)"), + }); + expect((await workerRecords(paseoHome)).length).toBeLessThanOrEqual(2); + }, + 30000, +); + it("creates a terminal through the worker and streams output", async () => { const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-output-")); temporaryDirs.push(cwd); - manager = createWorkerTerminalManager(); + manager = await startRealWorkerManager(); const session = trackTerminal( await manager.createTerminal({ workspaceId: "ws-test", @@ -208,7 +418,7 @@ it("delivers rapid small writes complete and in order through worker coalescing" const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-coalesce-")); temporaryDirs.push(cwd); const burstGatePath = join(cwd, "burst-ready"); - manager = createWorkerTerminalManager(); + manager = await startRealWorkerManager(); // The file gate starts the burst after this test subscribes without depending // on platform-specific PTY input echo/canonical-mode behavior. const session = trackTerminal( @@ -271,7 +481,7 @@ it("delivers rapid small writes complete and in order through worker coalescing" it("pulls fresh terminal state from the worker authority", async () => { const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-state-")); temporaryDirs.push(cwd); - manager = createWorkerTerminalManager(); + manager = await startRealWorkerManager(); const session = trackTerminal( await manager.createTerminal({ workspaceId: "ws-test", @@ -302,7 +512,7 @@ it.skipIf(isPlatform("win32"))( async () => { const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-preamble-")); temporaryDirs.push(cwd); - manager = createWorkerTerminalManager(); + manager = await startRealWorkerManager(); // \x1b[>1u pushes kitty keyboard flag 1, which the worker's input-mode // tracker records and reflects in its replay preamble (\x1b[=1;1u). const session = trackTerminal( @@ -328,7 +538,7 @@ it.skipIf(isPlatform("win32"))( it("refreshes cached terminal title after worker title changes", async () => { const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-title-")); temporaryDirs.push(cwd); - manager = createWorkerTerminalManager(); + manager = await startRealWorkerManager(); const session = trackTerminal( await manager.createTerminal({ workspaceId: "ws-test", @@ -348,7 +558,7 @@ it("refreshes cached terminal title after worker title changes", async () => { it("refreshes cached terminal size after worker resize", async () => { const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-resize-")); temporaryDirs.push(cwd); - manager = createWorkerTerminalManager(); + manager = await startRealWorkerManager(); const session = trackTerminal(await manager.createTerminal({ cwd, workspaceId: "ws-test" })); session.send({ type: "resize", rows: 10, cols: 40 }); @@ -363,7 +573,7 @@ it("refreshes cached terminal size after worker resize", async () => { it("captures terminal output from the worker authority", async () => { const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-capture-")); temporaryDirs.push(cwd); - manager = createWorkerTerminalManager(); + manager = await startRealWorkerManager(); const session = trackTerminal(await manager.createTerminal({ cwd, workspaceId: "ws-test" })); session.send({ type: "input", data: "echo hello world\r" }); @@ -382,7 +592,7 @@ it("does not surface fire-and-forget send timeouts as unhandled rejections", asy const worker = new FakeTerminalWorker(); manager = createWorkerTerminalManager({ requestTimeoutMs: 5, - forkWorker: () => worker, + worker, }); worker.emitWorkerMessage({ @@ -416,7 +626,7 @@ it("does not surface fire-and-forget send timeouts as unhandled rejections", asy }); it("keeps registered cwd env inheritance behind the worker manager interface", async () => { - manager = createWorkerTerminalManager(); + manager = await startRealWorkerManager(); const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-env-")); temporaryDirs.push(cwd); const markerPath = join(cwd, "env.txt"); @@ -449,7 +659,7 @@ it("injects parent-minted terminal activity env through the worker", async () => temporaryDirs.push(cwd); const envPath = join(cwd, "activity-env.json"); const activityUrl = "http://127.0.0.1:12345/api/terminal-activity"; - manager = createWorkerTerminalManager({ + manager = await startRealWorkerManager({ getTerminalActivityUrl: () => activityUrl, }); @@ -496,8 +706,177 @@ it("injects parent-minted terminal activity env through the worker", async () => expect(env.path?.split(delimiter)[0]).toBe(paseoCliBinDir); }); +it("adopts a detached worker's terminals with their activity tokens and keeps them usable", async () => { + const paseoHome = createTemporaryHome(); + const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-adopt-")); + temporaryDirs.push(cwd); + const envPath = join(cwd, "adopt-env.json"); + const first = await startRealWorkerManager({ paseoHome }); + const created = await first.createTerminal({ + workspaceId: "ws-adopt", + cwd, + ...nodeTerminalCommand(` + require("node:fs").writeFileSync( + ${JSON.stringify(envPath)}, + JSON.stringify({ token: process.env.PASEO_ACTIVITY_TOKEN }), + ); + process.stdin.on("data", (chunk) => { + process.stdout.write("adopted-output:" + chunk.toString()); + }); + setInterval(() => {}, 1000); + `), + }); + await waitForCondition(() => existsSync(envPath), 10000); + const { token } = JSON.parse(readFileSync(envPath, "utf8")) as { token: string }; + + await first.detach(); + manager = await startRealWorkerManager({ paseoHome }); + + const adopted = manager.getTerminal(created.id); + expect(adopted?.workspaceId).toBe("ws-adopt"); + expect(await manager.getTerminals(cwd)).toHaveLength(1); + expect(manager.validateTerminalActivityToken(created.id, token)).toBe("valid"); + const messages: string[] = []; + adopted?.subscribe((message) => { + if (message.type === "output") messages.push(message.data); + }); + adopted?.send({ type: "input", data: "after-adopt\r" }); + await waitForCondition(() => messages.join("").includes("adopted-output:after-adopt"), 10000); +}); + +function isProcessAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +// The terminals the worker itself recorded, read from its own record file. +async function recordedTerminalPids(paseoHome: string): Promise> { + const pids = new Map(); + const directory = terminalWorkerDirectory(paseoHome); + for (const name of readdirSync(directory).filter((entry) => /^\d+\.json$/.test(entry))) { + for (const entry of (await readTerminalWorkerRecord(join(directory, name))).terminals) { + pids.set(entry.id, entry.pid); + } + } + return pids; +} + +it("never adopts a live worker's terminals after a kill cleanup it could not finish, even once the worker rewrites its record", async () => { + const paseoHome = createTemporaryHome(); + const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-unfinished-kill-")); + temporaryDirs.push(cwd); + const first = await startRealWorkerManager({ paseoHome }); + manager = first; + const ending = await first.createTerminal({ + workspaceId: "ws-unfinished-kill", + cwd, + ...nodeTerminalCommand("setInterval(() => {}, 1000);"), + }); + const remaining = await first.createTerminal({ + workspaceId: "ws-unfinished-kill", + cwd, + ...nodeTerminalCommand("setInterval(() => {}, 1000);"), + }); + const pids = await recordedTerminalPids(paseoHome); + const endingPid = pids.get(ending.id)!; + const remainingPid = pids.get(remaining.id)!; + + // A kill cleanup whose process table read fails signals nothing and leaves the worker live. + const inspector = createTerminalWorkerProcessInspector(); + await expect( + reapTerminalWorkers({ + paseoHome, + inspector: { ...inspector, listProcesses: () => Promise.reject(new Error("ps timed out")) }, + }), + ).rejects.toBeInstanceOf(TerminalCleanupNotConfirmedError); + await first.detach(); + expect((await readUnconfirmedTerminalCleanup(paseoHome)).length).toBeGreaterThan(0); + + // One terminal ends on its own: the live worker rewrites its record from memory. + process.kill(endingPid, "SIGKILL"); + await waitForCondition( + async () => !(await recordedTerminalPids(paseoHome)).has(ending.id), + 10000, + ); + expect((await readUnconfirmedTerminalCleanup(paseoHome)).length).toBeGreaterThan(0); + + manager = await startRealWorkerManager({ paseoHome }); + + expect(manager.getTerminal(remaining.id)).toBeUndefined(); + expect(await manager.getTerminals(cwd)).toEqual([]); + await waitForCondition(() => !isProcessAlive(remainingPid), 10000); + expect(await readUnconfirmedTerminalCleanup(paseoHome)).toEqual([]); +}); + +// The worker's own `ps`, delayed: a program that exits while the worker reads its birth time +// lands its exit in the middle of creation. Only the worker launched while this PATH is set sees +// the shim; the PATH is restored as soon as it is up. +async function startWorkerWithSlowProcessTable( + delaySeconds: number, +): Promise { + const realPs = (process.env.PATH ?? "") + .split(delimiter) + .map((dir) => join(dir, "ps")) + .find((candidate) => existsSync(candidate)); + if (!realPs) throw new Error("ps not found on PATH"); + const shimDir = createTemporaryHome(); + writeFileSync(join(shimDir, "ps"), `#!/bin/sh\nsleep ${delaySeconds}\nexec ${realPs} "$@"\n`, { + mode: 0o755, + }); + const originalPath = process.env.PATH; + process.env.PATH = `${shimDir}${delimiter}${originalPath ?? ""}`; + try { + return await startRealWorkerManager(); + } finally { + process.env.PATH = originalPath; + } +} + +async function expectCompletedShortCommand( + terminalManager: DaemonTerminalManager, + script: string, +): Promise { + const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-short-")); + temporaryDirs.push(cwd); + + const session = await terminalManager.createTerminal({ + workspaceId: "ws-test", + cwd, + command: "/bin/sh", + args: ["-c", script], + }); + + await waitForCondition(() => session.getExitInfo() !== null, 10000); + expect(session.getExitInfo()?.exitCode).toBe(0); + expect(terminalManager.getTerminal(session.id)).toBeUndefined(); + expect(await terminalManager.getTerminals(cwd)).toEqual([]); + expect(await terminalManager.getTerminalState(session.id)).toBeNull(); +} + +it.skipIf(isPlatform("win32"))( + "creates a short command that finishes before creation returns, with its exit", + async () => { + manager = await startRealWorkerManager(); + for (let attempt = 0; attempt < 3; attempt += 1) { + await expectCompletedShortCommand(manager, "echo short; exit 0"); + } + }, +); + +it.skipIf(isPlatform("win32"))( + "publishes the creation before an exit that arrives while the program is being recorded", + async () => { + manager = await startWorkerWithSlowProcessTable(0.3); + await expectCompletedShortCommand(manager, "sleep 0.1; echo short; exit 0"); + }, +); + it("starts the default shell through the worker and accepts quoted commands", async () => { - manager = createWorkerTerminalManager(); + manager = await startRealWorkerManager(); const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-shell-")); temporaryDirs.push(cwd); const markerPath = join(cwd, "shell quoted marker.txt"); @@ -518,7 +897,7 @@ it("lists subdirectory terminals when querying the workspace root", async () => const subdirCwd = join(rootCwd, "apps", "mobile"); mkdirSync(subdirCwd, { recursive: true }); temporaryDirs.push(rootCwd); - manager = createWorkerTerminalManager(); + manager = await startRealWorkerManager(); const created = trackTerminal( await manager.createTerminal({ workspaceId: "ws-test", @@ -536,7 +915,7 @@ it("lists terminals locally without waiting on the worker", async () => { const worker = new FakeTerminalWorker(); manager = createWorkerTerminalManager({ requestTimeoutMs: 5, - forkWorker: () => worker, + worker, }); worker.emitWorkerMessage({ @@ -577,7 +956,7 @@ it("includes only stamped terminals in workspace-scoped local reads", async () = const worker = new FakeTerminalWorker(); manager = createWorkerTerminalManager({ requestTimeoutMs: 5, - forkWorker: () => worker, + worker, }); worker.emitWorkerMessage({ @@ -629,7 +1008,7 @@ it("rejects non-absolute cwd in getTerminals", async () => { const worker = new FakeTerminalWorker(); manager = createWorkerTerminalManager({ requestTimeoutMs: 5, - forkWorker: () => worker, + worker, }); await expect(manager.getTerminals("relative/path")).rejects.toThrow("cwd must be absolute path"); @@ -639,7 +1018,7 @@ it("surfaces worker activity changes via getActivity, onActivityChange, and term const worker = new FakeTerminalWorker(); manager = createWorkerTerminalManager({ requestTimeoutMs: 50, - forkWorker: () => worker, + worker, }); worker.emitWorkerMessage({ @@ -702,7 +1081,7 @@ it("sets terminal activity through a worker request", async () => { const worker = new FakeTerminalWorker(); manager = createWorkerTerminalManager({ requestTimeoutMs: 50, - forkWorker: () => worker, + worker, }); worker.emitWorkerMessage({ type: "terminalCreated", @@ -735,7 +1114,7 @@ it("clears terminal attention through a worker request", async () => { const worker = new FakeTerminalWorker(); manager = createWorkerTerminalManager({ requestTimeoutMs: 50, - forkWorker: () => worker, + worker, }); worker.emitWorkerMessage({ type: "terminalCreated", @@ -766,7 +1145,7 @@ it("clears terminal attention through a worker request", async () => { it("clears finished attention on a real terminal", async () => { const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-attention-")); temporaryDirs.push(cwd); - manager = createWorkerTerminalManager(); + manager = await startRealWorkerManager(); const session = trackTerminal( await manager.createTerminal({ workspaceId: "ws-test", @@ -802,7 +1181,7 @@ it("clears finished attention on a real terminal", async () => { it("removes worker terminals after killAndWait", async () => { const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-kill-")); temporaryDirs.push(cwd); - manager = createWorkerTerminalManager(); + manager = await startRealWorkerManager(); const session = trackTerminal( await manager.createTerminal({ workspaceId: "ws-test", @@ -827,7 +1206,7 @@ it("produces one terminals-changed snapshot per title change", async () => { const worker = new FakeTerminalWorker(); manager = createWorkerTerminalManager({ requestTimeoutMs: 50, - forkWorker: () => worker, + worker, }); worker.emitWorkerMessage({ @@ -864,7 +1243,7 @@ it("produces one terminals-changed snapshot and one contribution event per activ const worker = new FakeTerminalWorker(); manager = createWorkerTerminalManager({ requestTimeoutMs: 50, - forkWorker: () => worker, + worker, }); worker.emitWorkerMessage({ @@ -914,7 +1293,7 @@ it("removes a killed worker terminal from terminalExit without duplicate snapsho const worker = new FakeTerminalWorker(); manager = createWorkerTerminalManager({ requestTimeoutMs: 50, - forkWorker: () => worker, + worker, }); const workingActivity = { state: "working" as const, changedAt: 1000 }; @@ -973,7 +1352,7 @@ it("does not resurrect a terminal that exited before its create response was han const worker = new FakeTerminalWorker(); manager = createWorkerTerminalManager({ requestTimeoutMs: 50, - forkWorker: () => worker, + worker, }); const snapshots: Array<{ cwd: string; terminalIds: string[] }> = []; @@ -1026,7 +1405,7 @@ it("replays the exit to a listener attached after a create that lost the race", const worker = new FakeTerminalWorker(); manager = createWorkerTerminalManager({ requestTimeoutMs: 50, - forkWorker: () => worker, + worker, }); const created = manager.createTerminal({ @@ -1074,7 +1453,7 @@ it("rejects createTerminal and registers nothing when the worker cannot start th const worker = new FakeTerminalWorker(); manager = createWorkerTerminalManager({ requestTimeoutMs: 50, - forkWorker: () => worker, + worker, }); const snapshots: Array<{ cwd: string; terminalIds: string[] }> = []; @@ -1104,3 +1483,256 @@ it("rejects createTerminal and registers nothing when the worker cannot start th expect(await manager.getTerminals("/workspace")).toEqual([]); expect(snapshots).toEqual([]); }); + +// The live worker records in a home, by worker pid. +async function workerRecords(paseoHome: string): Promise { + return (await listTerminalWorkerRecords(paseoHome)).flatMap((file) => + "record" in file && !file.record.closing ? [file.record] : [], + ); +} + +// A worker launched while the override is set reports that protocol version; the variable is +// restored as soon as it is up, so later workers report the build's own. +async function startManagerWithWorkerProtocol( + paseoHome: string, + protocolVersion: number, +): Promise { + const previous = process.env[TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV]; + process.env[TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV] = String(protocolVersion); + try { + return await startRealWorkerManager({ paseoHome }); + } finally { + if (previous === undefined) delete process.env[TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV]; + else process.env[TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV] = previous; + } +} + +// A terminal running an idle program in a worker that reports `protocolVersion`, left running +// after its daemon lets go (stop --keep-terminals). +async function leaveWorkerWithTerminal( + paseoHome: string, + protocolVersion: number, +): Promise<{ terminalId: string; programPid: number; workerPid: number; cwd: string }> { + const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-protocol-")); + temporaryDirs.push(cwd); + const previous = await startManagerWithWorkerProtocol(paseoHome, protocolVersion); + const session = await previous.createTerminal({ + workspaceId: "ws-protocol", + cwd, + ...nodeTerminalCommand("setInterval(() => {}, 1000);"), + }); + const [record] = await workerRecords(paseoHome); + await previous.detach(); + return { + terminalId: session.id, + programPid: (await recordedTerminalPids(paseoHome)).get(session.id)!, + workerPid: record!.pid, + cwd, + }; +} + +it("drains a worker one protocol older: it keeps its terminal, new ones open in a second worker, and it exits after its last", async () => { + const paseoHome = createTemporaryHome(); + const old = await leaveWorkerWithTerminal(paseoHome, 0); + + manager = await startRealWorkerManager({ paseoHome }); + + expect(manager.getTerminal(old.terminalId)).toBeDefined(); + const workers = await workerRecords(paseoHome); + expect(workers).toHaveLength(2); + const current = workers.find((record) => record.pid !== old.workerPid)!; + expect(current.protocolVersion).toBe(1); + const added = await manager.createTerminal({ + workspaceId: "ws-protocol", + cwd: old.cwd, + ...nodeTerminalCommand("setInterval(() => {}, 1000);"), + }); + trackTerminal(added); + const currentTerminals = ( + await readTerminalWorkerRecord(join(terminalWorkerDirectory(paseoHome), `${current.pid}.json`)) + ).terminals.map((entry) => entry.id); + expect(currentTerminals).toEqual([added.id]); + expect((await manager.getTerminals(old.cwd)).map((session) => session.id).sort()).toEqual( + [old.terminalId, added.id].sort(), + ); + + await manager.killTerminalAndWait(old.terminalId); + + await waitForCondition(() => !isProcessAlive(old.workerPid), 10000); + expect((await workerRecords(paseoHome)).map((record) => record.pid)).toEqual([current.pid]); + expect(manager.getTerminal(added.id)).toBeDefined(); +}); + +it("shuts down a worker two protocol versions old, closing its terminals", async () => { + const paseoHome = createTemporaryHome(); + const old = await leaveWorkerWithTerminal(paseoHome, -1); + + manager = await startRealWorkerManager({ paseoHome }); + + await waitForCondition( + () => !isProcessAlive(old.workerPid) && !isProcessAlive(old.programPid), + 10000, + ); + expect(manager.getTerminal(old.terminalId)).toBeUndefined(); + const workers = await workerRecords(paseoHome); + expect(workers).toHaveLength(1); + expect(workers[0]!.protocolVersion).toBe(1); +}); + +it("leaves a worker from a newer Paseo running, reports it incompatible, and closes it on a kill stop", async () => { + const paseoHome = createTemporaryHome(); + const newer = await leaveWorkerWithTerminal(paseoHome, 2); + + manager = await startRealWorkerManager({ paseoHome }); + + const unavailable = manager.getUnavailableError?.(); + expect(unavailable).toBeInstanceOf(TerminalWorkerIncompatibleError); + expect(unavailable?.message).toContain("worker protocol 2"); + await expect(manager.getTerminals(newer.cwd)).rejects.toBeInstanceOf( + TerminalWorkerIncompatibleError, + ); + await expect( + manager.createTerminal({ workspaceId: "ws-protocol", cwd: newer.cwd }), + ).rejects.toBeInstanceOf(TerminalWorkerIncompatibleError); + expect(isProcessAlive(newer.programPid)).toBe(true); + expect((await workerRecords(paseoHome)).map((record) => record.pid)).toEqual([newer.workerPid]); + + await manager.closeTerminals(); + + expect(isProcessAlive(newer.workerPid)).toBe(false); + expect(isProcessAlive(newer.programPid)).toBe(false); + expect(await workerRecords(paseoHome)).toEqual([]); +}); + +// A worker launched on its own, as two daemons that each started one would leave it: running an +// idle program in a terminal, with no daemon attached. +async function launchDetachedWorkerWithTerminal( + paseoHome: string, + protocolVersion?: number, +): Promise<{ terminalId: string; workerPid: number; cwd: string }> { + const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-detached-")); + temporaryDirs.push(cwd); + const previous = process.env[TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV]; + if (protocolVersion !== undefined) { + process.env[TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV] = String(protocolVersion); + } + let launched: Awaited>; + try { + launched = await launchTerminalWorker({ paseoHome, paseoVersion: "0.0.0-test" }); + } finally { + if (previous === undefined) delete process.env[TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV]; + else process.env[TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV] = previous; + } + const worker = createWorkerTerminalManager({ + worker: await connectTerminalWorker({ + socketPath: launched.record.socketPath, + secret: launched.record.secret, + }), + }); + const session = await worker.createTerminal({ + workspaceId: "ws-detached", + cwd, + ...nodeTerminalCommand("setInterval(() => {}, 1000);"), + }); + await worker.detach(); + return { terminalId: session.id, workerPid: launched.record.pid, cwd }; +} + +// Worker pids alive in a home, from every record, closing ones included. +async function liveWorkerPids(paseoHome: string): Promise { + return (await listTerminalWorkerRecords(paseoHome)) + .flatMap((file) => ("record" in file ? [file.record.pid] : [])) + .filter(isProcessAlive) + .sort(); +} + +it.skipIf(isPlatform("win32"))( + "counts live workers whose cleanup could not be confirmed and never starts a third", + async () => { + const paseoHome = createTemporaryHome(); + const first = await launchDetachedWorkerWithTerminal(paseoHome); + const second = await launchDetachedWorkerWithTerminal(paseoHome); + // A kill cleanup that cannot read the process table signals nothing: both workers keep + // running with their records marked closing. + const inspector = createTerminalWorkerProcessInspector(); + await expect( + reapTerminalWorkers({ + paseoHome, + gracefulMs: 0, + inspector: { ...inspector, listProcesses: () => Promise.reject(new Error("ps timed out")) }, + }), + ).rejects.toBeInstanceOf(TerminalCleanupNotConfirmedError); + expect((await readUnconfirmedTerminalCleanup(paseoHome)).map((entry) => entry.role)).toContain( + "worker", + ); + + // The daemon's own retry fails the same way: only the full process table is unreadable. + const realPs = (process.env.PATH ?? "") + .split(delimiter) + .map((dir) => join(dir, "ps")) + .find((candidate) => existsSync(candidate)); + if (!realPs) throw new Error("ps not found on PATH"); + const shimDir = createTemporaryHome(); + writeFileSync( + join(shimDir, "ps"), + `#!/bin/sh\nif [ "$1" = "-A" ]; then echo "process table unavailable" >&2; exit 1; fi\nexec ${realPs} "$@"\n`, + { mode: 0o755 }, + ); + const originalPath = process.env.PATH; + process.env.PATH = `${shimDir}${delimiter}${originalPath ?? ""}`; + try { + manager = await startRealWorkerManager({ paseoHome }); + } finally { + process.env.PATH = originalPath; + } + + expect(await liveWorkerPids(paseoHome)).toEqual([first.workerPid, second.workerPid].sort()); + await expect( + manager.createTerminal({ workspaceId: "ws-detached", cwd: first.cwd }), + ).rejects.toThrow("2 terminal workers are already running"); + expect(await liveWorkerPids(paseoHome)).toEqual([first.workerPid, second.workerPid].sort()); + }, +); + +it("opens new terminals in a new worker once one of two draining workers exits", async () => { + const paseoHome = createTemporaryHome(); + const first = await launchDetachedWorkerWithTerminal(paseoHome, 0); + const second = await launchDetachedWorkerWithTerminal(paseoHome, 0); + + manager = await startRealWorkerManager({ paseoHome }); + + expect(await liveWorkerPids(paseoHome)).toEqual([first.workerPid, second.workerPid].sort()); + await expect( + manager.createTerminal({ workspaceId: "ws-detached", cwd: first.cwd }), + ).rejects.toBeInstanceOf(NoTerminalWorkerAvailableError); + + await manager.killTerminalAndWait(first.terminalId); + await waitForCondition(() => !isProcessAlive(first.workerPid), 10000); + + // Concurrent creates start one worker between them. + const created = await Promise.all( + [0, 1].map(() => + manager!.createTerminal({ + workspaceId: "ws-detached", + cwd: first.cwd, + ...nodeTerminalCommand("setInterval(() => {}, 1000);"), + }), + ), + ); + created.forEach(trackTerminal); + const workers = await workerRecords(paseoHome); + expect(workers.map((record) => record.pid).sort()).toEqual(await liveWorkerPids(paseoHome)); + expect(workers).toHaveLength(2); + const started = workers.find((record) => record.pid !== second.workerPid)!; + expect(started.protocolVersion).toBe(1); + expect( + ( + await readTerminalWorkerRecord( + join(terminalWorkerDirectory(paseoHome), `${started.pid}.json`), + ) + ).terminals + .map((entry) => entry.id) + .sort(), + ).toEqual(created.map((session) => session.id).sort()); + expect(manager.getTerminal(second.terminalId)).toBeDefined(); +}); diff --git a/packages/server/src/terminal/worker-terminal-manager.ts b/packages/server/src/terminal/worker-terminal-manager.ts index 0a1adb2c44..c9a6d7186e 100644 --- a/packages/server/src/terminal/worker-terminal-manager.ts +++ b/packages/server/src/terminal/worker-terminal-manager.ts @@ -1,7 +1,10 @@ -import { fileURLToPath } from "node:url"; -import { fork } from "node:child_process"; import { randomBytes, randomUUID } from "node:crypto"; +import { access } from "node:fs/promises"; +import { setTimeout as delay } from "node:timers/promises"; +import type { Logger } from "pino"; +import { createExternalProcessEnv } from "../server/paseo-env.js"; import { assertAbsolutePath, isSameOrDescendantPath } from "../server/path-utils.js"; +import { writtenDuringThisBoot } from "../server/pid-lock.js"; import type { TerminalState } from "@getpaseo/protocol/messages"; import type { TerminalActivity, TerminalActivityState } from "@getpaseo/protocol/terminal-activity"; import { deriveTerminalActivityStatusBucket } from "@getpaseo/protocol/terminal-activity"; @@ -14,7 +17,28 @@ import type { TerminalSession, TerminalStateSnapshot, } from "./terminal.js"; +import { resolvePaseoCliExecutablePath } from "./paseo-cli-path.js"; import type { CaptureTerminalLinesResult } from "./terminal-capture.js"; +import { connectTerminalWorker, type TerminalWorkerConnection } from "./terminal-worker-client.js"; +import { launchTerminalWorker } from "./terminal-worker-launch.js"; +import { classifyTerminalWorkerProcess } from "./terminal-worker-ownership.js"; +import { + createTerminalWorkerProcessInspector, + type TerminalWorkerProcessInspector, +} from "./terminal-worker-processes.js"; +import { reapTerminalWorkers } from "./terminal-worker-reaper.js"; +import { + listTerminalWorkerRecords, + terminalWorkerRecordPath, + type TerminalWorkerRecord, +} from "./terminal-worker-record.js"; +import { + createTerminalWorkerPool, + NoTerminalWorkerAvailableError, + TerminalWorkerIncompatibleError, + type TerminalWorkerPoolMember, +} from "./terminal-worker-pool.js"; +import { pruneTerminalWorkerRuntimes } from "./terminal-worker-runtime.js"; import type { TerminalActivityListener, TerminalActivityTransitionEvent, @@ -25,7 +49,12 @@ import type { TerminalsChangedEvent, TerminalsChangedListener, } from "./terminal-manager.js"; +import { + classifyTerminalWorkerProtocol, + type TerminalWorkerProtocolFit, +} from "./terminal-worker-protocol.js"; import type { + TerminalWorkerListResult, TerminalWorkerRequest, TerminalWorkerResponse, TerminalWorkerToParentMessage, @@ -78,49 +107,45 @@ interface WorkerTerminalRecord { session: TerminalSession; } -interface TerminalWorkerProcess { - connected: boolean; - killed: boolean; - send(message: TerminalWorkerRequest, callback: (error: Error | null) => void): boolean; - disconnect(): void; - kill(): boolean; - on(event: "message", listener: (message: TerminalWorkerToParentMessage) => void): this; - on(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; +export interface TerminalCreateEnvironment { + baseEnv: Record; + paseoCliPath: string | null; } interface WorkerTerminalManagerOptions { + worker: TerminalWorkerConnection; + /** Reconnects a surviving worker; null means it is confirmed gone or the owner stopped. */ + reconnect?: () => Promise; requestTimeoutMs?: number; - forkWorker?: () => TerminalWorkerProcess; getTerminalActivityUrl?: () => string | null; + resolveCreateEnvironment?: () => TerminalCreateEnvironment; + // The kill path. The daemon passes the reaper, which verifies every program is gone; the + // default asks the connected worker to shut down. + closeTerminals?: () => Promise; +} + +/** The daemon's terminal manager: its terminals live in a worker that can outlive it. */ +export interface DaemonTerminalManager extends TerminalManager { + /** Registers every terminal the connected worker already runs. Resolves with their count. */ + adoptTerminals(): Promise; + /** Kills every terminal and verifies their programs ended. */ + closeTerminals(): Promise; + /** + * Lets go of the worker; its terminals keep running for the next daemon. With + * `afterPendingRequests`, requests already sent get their answers first. + */ + detach(options?: { afterPendingRequests?: boolean }): Promise; } function createActivityToken(): string { return randomBytes(32).toString("base64url"); } -function resolveWorkerUrl(): URL { - const currentUrl = import.meta.url; - if (currentUrl.endsWith(".ts")) { - return new URL("./terminal-worker-process.ts", currentUrl); - } - return new URL("./terminal-worker-process.js", currentUrl); -} - -function resolveWorkerExecArgv(): string[] { - if (!import.meta.url.endsWith(".ts")) { - return []; - } - const loaderUrl = new URL("./terminal-ts-loader.mjs", import.meta.url).href; - const importSource = [ - 'import { register } from "node:module";', - 'import { pathToFileURL } from "node:url";', - `register(${JSON.stringify(loaderUrl)}, pathToFileURL("./"));`, - ].join(" "); - return [ - "--experimental-strip-types", - "--import", - `data:text/javascript,${encodeURIComponent(importSource)}`, - ]; +function resolveDaemonTerminalCreateEnvironment(): TerminalCreateEnvironment { + return { + baseEnv: createExternalProcessEnv(process.env), + paseoCliPath: resolvePaseoCliExecutablePath(), + }; } function isResponse(message: TerminalWorkerToParentMessage): message is TerminalWorkerResponse { @@ -138,20 +163,17 @@ function cloneTerminalInfo(info: RequiredWorkerTerminalInfo): RequiredWorkerTerm }; } -function forkTerminalWorker(): TerminalWorkerProcess { - return fork(fileURLToPath(resolveWorkerUrl()), [], { - execArgv: resolveWorkerExecArgv(), - serialization: "advanced", - stdio: ["ignore", "ignore", "inherit", "ipc"], - }) as TerminalWorkerProcess; -} - export function createWorkerTerminalManager( - managerOptions: WorkerTerminalManagerOptions = {}, -): TerminalManager { - const worker = managerOptions.forkWorker ? managerOptions.forkWorker() : forkTerminalWorker(); + managerOptions: WorkerTerminalManagerOptions, +): DaemonTerminalManager { + let worker = managerOptions.worker; + let detached = false; + let reconnecting: Promise | null = null; const requestTimeoutMs = managerOptions.requestTimeoutMs ?? REQUEST_TIMEOUT_MS; + const resolveCreateEnvironment = + managerOptions.resolveCreateEnvironment ?? resolveDaemonTerminalCreateEnvironment; const pendingRequests = new Map(); + const inFlight = new Set>(); const recordsById = new Map(); const terminalIdsByCwd = new Map>(); const terminalActivityTokenById = new Map(); @@ -162,8 +184,8 @@ export function createWorkerTerminalManager( const terminalActivityListeners = new Set(); const terminalWorkspaceContributionChangedListeners = new Set(); - let workerExited = false; - let workerShutdownTimer: ReturnType | null = null; + let workerDisconnected = false; + let closePromise: Promise | null = null; function emitTerminalsChanged(event: TerminalsChangedEvent): void { for (const listener of Array.from(terminalsChangedListeners)) { @@ -587,40 +609,77 @@ export function createWorkerTerminalManager( } } - worker.on("message", (message: TerminalWorkerToParentMessage) => { - if (isResponse(message)) { - const pending = pendingRequests.get(message.requestId); - if (!pending) { + function attachWorker(): void { + worker.on("message", (message: TerminalWorkerToParentMessage) => { + if (isResponse(message)) { + const pending = pendingRequests.get(message.requestId); + if (!pending) { + return; + } + clearTimeout(pending.timeout); + pendingRequests.delete(message.requestId); + if (message.ok) { + pending.resolve(message.result); + } else { + pending.reject(new Error(message.error)); + } return; } - clearTimeout(pending.timeout); - pendingRequests.delete(message.requestId); - if (message.ok) { - pending.resolve(message.result); - } else { - pending.reject(new Error(message.error)); - } - return; - } - handleWorkerEvent(message); - }); + handleWorkerEvent(message); + }); - worker.on("exit", (code, signal) => { - workerExited = true; - if (workerShutdownTimer) { - clearTimeout(workerShutdownTimer); - workerShutdownTimer = null; - } - rejectPendingRequests(new Error(`Terminal worker exited (${signal ?? code ?? "unknown"})`)); - }); + worker.on("close", () => { + workerDisconnected = true; + rejectPendingRequests(new Error("Terminal worker connection closed")); + const reconnect = managerOptions.reconnect; + if (!detached && reconnect) { + reconnecting = (async () => { + const connection = await reconnect(); + if (!connection) { + for (const terminalId of Array.from(recordsById.keys())) { + handleTerminalExitEvent({ + type: "terminalExit", + terminalId, + info: { exitCode: null, signal: null, lastOutputLines: [] }, + }); + } + return; + } + if (detached) { + connection.disconnect(); + return; + } + worker = connection; + workerDisconnected = false; + attachWorker(); + await adoptTerminals(); + // Output emitted without a controller is retained in the worker's screen. Existing + // streams must fetch that screen before applying further live output. + for (const record of recordsById.values()) { + handleTerminalMessageEvent({ + type: "terminalMessage", + terminalId: record.info.id, + message: { type: "snapshotReady" }, + replayPreamble: record.replayPreamble, + }); + } + })().finally(() => { + reconnecting = null; + }); + void reconnecting.catch(() => {}); + } + }); + } + attachWorker(); function sendRequest(input: TerminalWorkerRequestInput): Promise { - if (workerExited || !worker.connected) { + if (reconnecting && workerDisconnected) return reconnecting.then(() => sendRequest(input)); + if (workerDisconnected || !worker.connected) { return Promise.reject(new Error("Terminal worker is not running")); } const requestId = randomUUID(); const message = { ...input, requestId } as TerminalWorkerRequest; - return new Promise((resolve, reject) => { + const request = new Promise((resolve, reject) => { const timeout = setTimeout(() => { pendingRequests.delete(requestId); reject(new Error(`Terminal worker request timed out: ${input.type}`)); @@ -635,6 +694,14 @@ export function createWorkerTerminalManager( reject(error); }); }); + // Tracks settlement only; the caller handles the rejection. + const settled = request.then( + () => undefined, + () => undefined, + ); + inFlight.add(settled); + void settled.finally(() => inFlight.delete(settled)); + return request; } function sendBestEffortRequest(input: TerminalWorkerRequestInput): void { @@ -645,6 +712,71 @@ export function createWorkerTerminalManager( }); } + function clearRecords(): void { + for (const terminalId of Array.from(recordsById.keys())) { + removeRecord(terminalId); + } + } + + function disconnectWorker(): Promise { + if (workerDisconnected || !worker.connected) { + return Promise.resolve(); + } + return new Promise((resolve) => { + worker.on("close", () => resolve()); + worker.disconnect(); + }); + } + + function closeTerminals(): Promise { + detached = true; + closePromise ??= (async () => { + await reconnecting; + if (managerOptions.closeTerminals) { + await disconnectWorker(); + clearRecords(); + await managerOptions.closeTerminals(); + return; + } + // Unverified: production passes the reaper, which confirms every program ended. + sendBestEffortRequest({ type: "shutdown" }); + await disconnectWorker(); + clearRecords(); + })(); + return closePromise; + } + + async function adoptTerminals(): Promise { + const listed = (await sendRequest({ type: "listTerminals" })) as TerminalWorkerListResult; + const cwds = new Set(); + const liveIds = new Set(listed.map((item) => item.terminal.id)); + for (const terminalId of Array.from(recordsById.keys())) { + if (!liveIds.has(terminalId)) + handleTerminalExitEvent({ + type: "terminalExit", + terminalId, + info: { exitCode: null, signal: null, lastOutputLines: [] }, + }); + } + for (const item of listed) { + const info = asRequiredWorkerTerminalInfo(item.terminal); + registerRecord({ info, state: item.state }); + const record = recordsById.get(info.id); + if (record) { + record.replayPreamble = item.replayPreamble; + } + // The agent hooks inside each shell keep the token they were started with. + if (item.activityToken) { + terminalActivityTokenById.set(info.id, item.activityToken); + } + cwds.add(info.cwd); + } + for (const cwd of cwds) { + emitTerminalsChanged({ cwd, terminals: listTerminalItemsForCwd(cwd) }); + } + return listed.length; + } + return { async getTerminals( cwd: string, @@ -688,6 +820,7 @@ export function createWorkerTerminalManager( const creation = { session: null as TerminalSession | null }; pendingCreationsById.set(terminalId, creation); try { + const environment = resolveCreateEnvironment(); await sendRequest({ type: "createTerminal", options: { @@ -695,6 +828,8 @@ export function createWorkerTerminalManager( id: terminalId, activityToken, activityUrl: terminalActivityUrl, + baseEnv: environment.baseEnv, + paseoCliPath: environment.paseoCliPath, }, }); if (!creation.session) { @@ -812,25 +947,25 @@ export function createWorkerTerminalManager( }, killAll(): void { - void sendRequest({ type: "killAll" }) - .catch(() => { - // no-op - }) - .finally(() => { - if (worker.connected) { - worker.disconnect(); - } - if (!worker.killed && !workerShutdownTimer) { - workerShutdownTimer = setTimeout(() => { - worker.kill(); - }, 1000); - } - }); - for (const terminalId of Array.from(recordsById.keys())) { - removeRecord(terminalId); - } + void closeTerminals().catch(() => { + // The synchronous interface cannot report it; closeTerminals() callers see the error. + }); }, + closeTerminals, + + async detach(options?: { afterPendingRequests?: boolean }): Promise { + detached = true; + await reconnecting; + if (options?.afterPendingRequests) { + await Promise.allSettled(Array.from(inFlight)); + } + await disconnectWorker(); + clearRecords(); + }, + + adoptTerminals, + subscribeTerminalsChanged(listener: TerminalsChangedListener): () => void { terminalsChangedListeners.add(listener); return () => { @@ -856,6 +991,342 @@ export function createWorkerTerminalManager( }; } -export function terminateWorkerTerminalManager(manager: TerminalManager): void { - manager.killAll(); +export interface StartWorkerTerminalManagerOptions { + paseoHome: string; + paseoVersion: string; + logger: Logger; + getTerminalActivityUrl?: () => string | null; + requestTimeoutMs?: number; +} + +// The current worker plus one draining a previous protocol. Every live worker counts, +// incompatible, unreachable, unidentified and closing ones included: the daemon never starts a +// third. +const MAX_TERMINAL_WORKERS = 2; +const DRAINED_WORKER_EXIT_TIMEOUT_MS = 10_000; + +interface LiveWorkerRecord { + path: string; + record: TerminalWorkerRecord; + fit: TerminalWorkerProtocolFit; +} + +/** + * Connects the daemon to its terminal workers. A worker of this daemon's protocol is adopted + * (restart, crash, `stop --keep-terminals`); one a protocol older is adopted to drain; anything + * older is shut down, its terminals closed; one from a newer Paseo is left running and the + * terminal service reports it as incompatible. A worker is launched only when none is current, + * none is incompatible and fewer than two run; when two run, the first terminal created after one + * of them exits launches it. Records that cannot be adopted (a cleanup that + * never finished, a dead worker whose programs survived it) go through the reaper first, so a + * daemon never adopts terminals someone asked to close. + */ +export async function startWorkerTerminalManager( + options: StartWorkerTerminalManagerOptions, +): Promise { + const logger = options.logger.child({ module: "terminal-worker" }); + const inspector = createTerminalWorkerProcessInspector(); + const log = (message: string, fields?: Record) => logger.info(fields, message); + const live: LiveWorkerRecord[] = []; + const toReap: string[] = []; + for (const file of await listTerminalWorkerRecords(options.paseoHome)) { + if ("error" in file) { + logger.warn({ recordPath: file.path, err: file.error }, "Unreadable terminal worker record"); + continue; + } + const { record } = file; + if ( + record.closing || + !writtenDuringThisBoot({ startedAt: record.createdAt, bootId: record.bootId }) + ) { + toReap.push(file.path); + continue; + } + const worker = classifyTerminalWorkerProcess(record, await inspector.inspect(record.pid)); + if (worker.status === "owned") { + live.push({ + path: file.path, + record, + fit: classifyTerminalWorkerProtocol(record.protocolVersion), + }); + } else if (worker.status === "unknown") { + logger.warn( + { recordPath: file.path, pid: record.pid, reason: worker.reason }, + "Cannot identify terminal worker; leaving its record", + ); + } else { + // Its programs lost their PTY with the worker and cannot be adopted. + toReap.push(file.path); + } + } + + if (toReap.length > 0) { + await reapTerminalWorkers({ + paseoHome: options.paseoHome, + gracefulMs: 0, + recordPaths: toReap, + inspector, + log, + }).catch((error: unknown) => { + logger.warn({ err: error }, "Terminal cleanup of an unadoptable worker was not confirmed"); + }); + } + + const obsolete = live.filter((entry) => entry.fit === "obsolete"); + if (obsolete.length > 0) { + for (const entry of obsolete) { + logger.warn( + { + pid: entry.record.pid, + protocolVersion: entry.record.protocolVersion, + paseoVersion: entry.record.paseoVersion, + terminals: entry.record.terminals.length, + }, + "Closing a terminal worker two or more protocol versions old; its terminals close", + ); + } + await reapTerminalWorkers({ + paseoHome: options.paseoHome, + recordPaths: obsolete.map((entry) => entry.path), + inspector, + log, + }).catch((error: unknown) => { + logger.warn({ err: error }, "Closing an obsolete terminal worker was not confirmed"); + }); + } + + const closeAll = async () => { + const result = await reapTerminalWorkers({ paseoHome: options.paseoHome, inspector, log }); + logger.info(result, "Terminals closed"); + }; + const prune = async () => { + const result = await pruneTerminalWorkerRuntimes(options.paseoHome); + if (result.removed.length > 0) + log("Removed terminal worker copies", { removed: result.removed }); + for (const failure of result.failed) { + logger.warn(failure, "Cannot remove a terminal worker copy; the next start retries"); + } + }; + + const pruneAfterExit = async (workerPid: number) => { + if (await waitForWorkerRecordRemoval(options.paseoHome, workerPid)) { + await prune(); + return; + } + logger.warn({ pid: workerPid }, "Drained terminal worker has not exited yet"); + }; + + const newer = live.find((entry) => entry.fit === "newer"); + if (newer) { + const incompatible = new TerminalWorkerIncompatibleError({ + paseoVersion: newer.record.paseoVersion, + protocolVersion: newer.record.protocolVersion, + }); + logger.error({ pid: newer.record.pid }, incompatible.message); + await prune(); + return createTerminalWorkerPool({ + current: null, + draining: [], + incompatible, + closeAll, + }); + } + + const createMember = async ( + record: TerminalWorkerRecord, + connection: TerminalWorkerConnection, + ): Promise => { + let alive = true; + let resolveExit!: () => void; + const exited = new Promise((resolve) => { + resolveExit = resolve; + }); + let recovery: Promise | null = null; + const recoveryState = { stopped: false }; + const reconnect = () => { + recovery ??= (async () => { + while (!recoveryState.stopped) { + const ownership = classifyTerminalWorkerProcess( + record, + await inspector.inspect(record.pid), + ); + if (ownership.status === "gone" || ownership.status === "unrelated") { + await reapTerminalWorkers({ + paseoHome: options.paseoHome, + recordPaths: [terminalWorkerRecordPath(options.paseoHome, record.pid)], + inspector, + log, + gracefulMs: 0, + }).catch((error) => + logger.warn({ err: error }, "Dead terminal worker cleanup was not confirmed"), + ); + alive = false; + resolveExit(); + return null; + } + try { + return await connectTerminalWorker({ + socketPath: record.socketPath, + secret: record.secret, + timeoutMs: 500, + }); + } catch { + await delay(100); + } + } + return null; + })().finally(() => { + recovery = null; + }); + return recovery; + }; + const manager = createWorkerTerminalManager({ + worker: connection, + reconnect, + ...(options.requestTimeoutMs === undefined + ? {} + : { requestTimeoutMs: options.requestTimeoutMs }), + ...(options.getTerminalActivityUrl + ? { getTerminalActivityUrl: options.getTerminalActivityUrl } + : {}), + closeTerminals: closeAll, + }); + const count = await manager.adoptTerminals(); + if (count > 0) { + logger.info({ pid: record.pid, terminals: count }, "Adopted terminals from a running worker"); + } + return { + manager, + workerPid: record.pid, + exited, + ready: async () => { + await recovery; + return alive && !recoveryState.stopped; + }, + stopRecovery: () => { + recoveryState.stopped = true; + }, + }; + }; + + let current: TerminalWorkerPoolMember | null = null; + const draining: TerminalWorkerPoolMember[] = []; + const adoptable = [ + ...live.filter((entry) => entry.fit === "current"), + ...live.filter((entry) => entry.fit === "previous"), + ]; + for (const entry of adoptable) { + let connection: TerminalWorkerConnection; + try { + connection = await connectTerminalWorker({ + socketPath: entry.record.socketPath, + secret: entry.record.secret, + }); + } catch (error) { + logger.warn( + { pid: entry.record.pid, err: error }, + "Cannot reach terminal worker; leaving it running", + ); + continue; + } + const member = await createMember(entry.record, connection); + if (entry.fit === "current" && !current) { + logger.info({ pid: entry.record.pid }, "Adopting running terminal worker"); + current = member; + } else { + // A previous protocol, or a second worker of this one: it keeps its terminals and takes + // no new ones. + logger.info( + { pid: entry.record.pid, protocolVersion: entry.record.protocolVersion }, + "Draining terminal worker; it exits after its last terminal", + ); + draining.push(member); + } + } + + // Counted from the records rather than from what startup drove: a worker a cleanup could not + // confirm gone keeps running, and a draining one exits on its own. + const startCurrent = async (): Promise => { + const running = await countRunningTerminalWorkers(options.paseoHome, inspector); + if (running >= MAX_TERMINAL_WORKERS) { + throw new NoTerminalWorkerAvailableError( + `${running} terminal workers are already running in ${options.paseoHome}; new terminals can open once one of them exits`, + ); + } + const launched = await launchTerminalWorker({ + paseoHome: options.paseoHome, + paseoVersion: options.paseoVersion, + }); + const connection = await connectTerminalWorker({ + socketPath: launched.record.socketPath, + secret: launched.record.secret, + }); + logger.info( + { pid: launched.record.pid, runtime: launched.record.runtime ?? null }, + "Launched terminal worker", + ); + return createMember(launched.record, connection); + }; + + await prune(); + if (!current) { + try { + current = await startCurrent(); + } catch (error) { + if (!(error instanceof NoTerminalWorkerAvailableError)) throw error; + logger.warn(error.message); + } + } + + return createTerminalWorkerPool({ + current, + draining, + incompatible: null, + startCurrent, + closeAll, + onDrained: (member) => { + log("Released drained terminal worker", { pid: member.workerPid }); + void pruneAfterExit(member.workerPid); + }, + }); +} + +// Every worker that may still run in this home, one per record: a worker and its cleanup record +// are listed as one. Unreadable records and workers that cannot be identified count; a worker +// confirmed gone, or a pid reused by another process, does not. +async function countRunningTerminalWorkers( + paseoHome: string, + inspector: TerminalWorkerProcessInspector, +): Promise { + let running = 0; + for (const file of await listTerminalWorkerRecords(paseoHome)) { + if ("error" in file) { + running += 1; + continue; + } + const { record } = file; + if (!writtenDuringThisBoot({ startedAt: record.createdAt, bootId: record.bootId })) continue; + const worker = classifyTerminalWorkerProcess(record, await inspector.inspect(record.pid)); + if (worker.status === "owned" || worker.status === "unknown") running += 1; + } + return running; +} + +// A worker deletes its own record as it exits. +async function waitForWorkerRecordRemoval(paseoHome: string, workerPid: number): Promise { + const recordPath = terminalWorkerRecordPath(paseoHome, workerPid); + const deadline = Date.now() + DRAINED_WORKER_EXIT_TIMEOUT_MS; + while ( + await access(recordPath).then( + () => true, + (error: NodeJS.ErrnoException) => { + if (error.code === "ENOENT") return false; + throw error; + }, + ) + ) { + if (Date.now() >= deadline) return false; + await delay(100); + } + return true; } diff --git a/packages/server/tsconfig.scripts.json b/packages/server/tsconfig.scripts.json index cc8e24efd4..6a75825b00 100644 --- a/packages/server/tsconfig.scripts.json +++ b/packages/server/tsconfig.scripts.json @@ -19,6 +19,11 @@ "declaration": false, "sourceMap": true }, - "include": ["scripts/supervisor-entrypoint.ts", "scripts/dev-runner.ts", "scripts/supervisor.ts"], + "include": [ + "scripts/supervisor-entrypoint.ts", + "scripts/dev-runner.ts", + "scripts/supervisor.ts", + "src/executable-resolution/which.d.ts" + ], "exclude": ["node_modules", "dist"] } diff --git a/packages/server/tsconfig.server.json b/packages/server/tsconfig.server.json index 9c868b42df..1c7a5c3579 100644 --- a/packages/server/tsconfig.server.json +++ b/packages/server/tsconfig.server.json @@ -22,7 +22,12 @@ "declarationMap": true, "sourceMap": true }, - "include": ["src/server/**/*", "src/services/**/*", "src/terminal/**/*"], + "include": [ + "src/server/**/*", + "src/services/**/*", + "src/terminal/**/*", + "src/executable-resolution/which.d.ts" + ], "exclude": [ "node_modules", "dist", From 9fb7808191dceb411e7a58379d758a77f6e9b4f2 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Wed, 28 Oct 2026 18:55:50 +0700 Subject: [PATCH 089/173] feat(worktrees): let plugins choose creation options and placement (#8117) * feat(worktrees): let plugins choose creation options and placement Await the worktree creation request hook before Git source planning so plugins can change placement, branch and base without undoing a fetch. Manage arbitrary destinations through marker and registry ownership, and restore them at their recorded paths. Co-authored-by: Matt Cowger * fix(worktrees): compare repository paths across Windows aliases Deletion must recognize the same repository through Git native and long path spellings. Reuse ownership path equivalence instead of comparing canonical strings, and let the recovery fixture accept Git platform line endings. Co-authored-by: Matt Cowger * fix(worktrees): respect recorded ownership and creation intent Keep branch checkout distinct from branch-off, validate plugin placement once at the daemon boundary, and share default path collision resolution. A restored external worktree's marker must never override its recorded non-ownership. Co-authored-by: Matt Cowger * test(worktrees): record ownership in session archive fixture The fixture creates a Paseo-owned worktree, so its durable record must say so. Archive now treats a recorded false value as authoritative instead of replacing it with filesystem discovery. Co-authored-by: Matt Cowger * test(plugins): retry temp cleanup after worktree archive on Windows Windows releases directory handles after the daemon closes, so rmdir on the source repository can hit EBUSY. Retry like the other git temp-dir tests. * test(plugins): compare plugin-chosen worktree paths in canonical spelling Windows temp directories come back as 8.3 aliases while the daemon records the resolved spelling, so normalize the expected root the same way. --------- Co-authored-by: Matt Cowger --- CHANGELOG.md | 1 + docs/plugins.md | 6 + packages/plugin/src/boundaries.test.ts | 18 ++ packages/plugin/src/server/index.ts | 1 + packages/plugin/src/server/lifecycle.ts | 36 +++ .../src/server/paseo-worktree-service.ts | 2 +- .../src/server/plugins/lifecycle.e2e.test.ts | 253 ++++++++++++++- .../server/plugins/lifecycle/handlers.test.ts | 16 +- .../src/server/plugins/lifecycle/index.ts | 68 +++- packages/server/src/server/plugins/runtime.ts | 10 +- .../src/server/session.workspaces.test.ts | 3 + .../workspace-recovery-service.test.ts | 41 +++ .../workspace-recovery-service.ts | 3 + .../server/workspace-archive-service.test.ts | 166 +++++++++- .../src/server/workspace-archive-service.ts | 82 ++++- .../src/server/worktree-core.posix.test.ts | 52 +++ packages/server/src/server/worktree-core.ts | 86 ++++- .../server/src/server/worktree/commands.ts | 24 +- packages/server/src/utils/checkout-git.ts | 12 +- .../server/src/utils/worktree-metadata.ts | 35 ++- packages/server/src/utils/worktree-path.ts | 88 ++++++ .../server/src/utils/worktree.posix.test.ts | 197 +++++++++++- packages/server/src/utils/worktree.test.ts | 16 + packages/server/src/utils/worktree.ts | 297 +++++++++++++----- .../src/plugin-docs-navigation.test.ts | 10 +- plugin-examples/lifecycle-logger/README.md | 2 +- plugin-examples/worktree-placement/README.md | 36 +++ .../worktree-placement/index.server.ts | 12 + .../worktree-placement/paseo-plugin.json | 4 + public-docs/plugins/hooks.md | 53 +++- public-docs/plugins/hooks.zh-CN.md | 53 +++- public-docs/worktrees.md | 2 + public-docs/worktrees.zh-CN.md | 2 + 33 files changed, 1556 insertions(+), 131 deletions(-) create mode 100644 packages/server/src/utils/worktree-path.ts create mode 100644 plugin-examples/worktree-placement/README.md create mode 100644 plugin-examples/worktree-placement/index.server.ts create mode 100644 plugin-examples/worktree-placement/paseo-plugin.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d2cb59ac2..1c790c6f80 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ Voice settings now let you configure speech providers and download local models ### Added - Copy gitignored files selected by `.worktreeinclude` into new worktrees before setup and agents, using the built-in `worktree-include` plugin ([#8100](https://github.com/getpaseo/paseo/pull/8100)) +- Let plugins choose worktree paths and creation options through `worktree.create.before`, with listing, archive, deletion, and recovery at custom locations; includes a sibling-directory placement example ([#8117](https://github.com/getpaseo/paseo/pull/8117)) - Let plugins give tools to specific agents ([#7938](https://github.com/getpaseo/paseo/pull/7938)) - Added collapse and expand controls for completed conversation turns ([#7785](https://github.com/getpaseo/paseo/pull/7785), [#7990](https://github.com/getpaseo/paseo/pull/7990), [#8026](https://github.com/getpaseo/paseo/pull/8026) by [@akaready](https://github.com/akaready), [@Dey11](https://github.com/Dey11), [@Sebeb](https://github.com/Sebeb), [@Waishnav](https://github.com/Waishnav)) - Let plugins add MCP servers whenever an agent session opens ([#7983](https://github.com/getpaseo/paseo/pull/7983)) diff --git a/docs/plugins.md b/docs/plugins.md index 28eca0267e..fcc7ed7fdb 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -447,6 +447,12 @@ owns payloads, ordering, failure behavior, and examples. `agent.create.before` e configuration; `agent.open.before` contributes launch-only `env`, `tools`, and `mcpServers` on every open. Executable tool definitions stay in the plugin process; only metadata crosses the boundary. +Worktree placement is resolved before Git source planning, so a hook can change the branch and base +without undoing fetched refs. Restores use the recorded destination and bypass creation hooks. +Workspace records decide ownership, including explicit non-ownership after recovery. Without a record, +ownership checks prefer the marker-verified worktree root over the legacy +path shape: a plugin can place a worktree several directories below the default worktrees root. + Emit from the operation owner, not a client subscription. Provider history replay must not trigger live hooks. Notifications must not be awaited inside agent mutations: a handler can send a prompt or answer a permission through its own daemon session. Awaiting it there deadlocks that command. diff --git a/packages/plugin/src/boundaries.test.ts b/packages/plugin/src/boundaries.test.ts index 1699451858..b0834956d6 100644 --- a/packages/plugin/src/boundaries.test.ts +++ b/packages/plugin/src/boundaries.test.ts @@ -255,6 +255,24 @@ describe("lifecycle hook SDK types", () => { typeErrors(` import type { PluginServerContext, PluginHooks, PluginHookPayload, PluginHookResult } from "@getpaseo/plugin/server"; export default function contribute(server: PluginServerContext) { + server.addHook("worktree.create.before", async ({ request }) => { + if (request.kind === "checkout-branch") { + // @ts-expect-error Branch checkout has no branch-off base. + request.baseRef; + } else { + const base: string = request.baseRef; + } + const branch: string = request.branch; + // @ts-expect-error Repository identity is read-only. + request.repoRoot = "/other"; + // @ts-expect-error Source checkout identity is read-only. + request.sourceCheckout = "/other"; + if (request.kind === "checkout-change-request") { + const number: number = request.changeRequestNumber; + } + return { ...request, branch: "feature", baseRef: "main", slug: "feature", path: "/work/feature" }; + }); + server.addHook("worktree.create.before", async () => {}); server.addHook("worktree.create.after", async ({ worktree }) => { const path: string = worktree.path; const branch: string = worktree.branch; diff --git a/packages/plugin/src/server/index.ts b/packages/plugin/src/server/index.ts index 3c1559b775..bb6bf4ede8 100644 --- a/packages/plugin/src/server/index.ts +++ b/packages/plugin/src/server/index.ts @@ -21,6 +21,7 @@ export type { PluginHookContext, PluginHookWorkspace, PluginHookWorktree, + PluginWorktreeCreateRequest, PluginHookAgent, PluginSessionOpenRequest, PluginTurnOutcome, diff --git a/packages/plugin/src/server/lifecycle.ts b/packages/plugin/src/server/lifecycle.ts index 339529347a..20df9c2dcb 100644 --- a/packages/plugin/src/server/lifecycle.ts +++ b/packages/plugin/src/server/lifecycle.ts @@ -27,6 +27,40 @@ export interface PluginHookWorktree { sourceCheckout: string; } +/** Resolved creation options before Git fetches refs or chooses a unique branch name. */ +export type PluginWorktreeCreateRequest = { + readonly repoRoot: string; + readonly sourceCheckout: string; + branch: string; + slug: string; + path: string; +} & ( + | { kind: "branch-off"; baseRef: string } + | { kind: "checkout-branch" } + | { + kind: "checkout-change-request"; + baseRef: string; + forge: string; + changeRequestNumber: number; + headRef: string; + headRepositoryOwner?: string; + headRepository?: string; + checkoutRefs?: { remoteName?: string; remoteRef: string }[]; + pushRemoteUrl?: string; + trackOriginHead?: boolean; + } + | { + kind: "checkout-github-pr"; + baseRef: string; + githubPrNumber: number; + headRef: string; + headRepositoryOwner?: string; + checkoutRefs?: { remoteName?: string; remoteRef: string }[]; + pushRemoteUrl?: string; + trackOriginHead?: boolean; + } +); + export interface PluginHookAgent { id: string; workspaceId: string | null; @@ -81,6 +115,7 @@ export interface PluginHookEvents { } export interface PluginHookRequests { + "worktree.create.before": PluginWorktreeCreateRequest; "agent.create.before": { config: AgentSessionConfig; env?: Record }; "agent.open.before": PluginSessionOpenRequest; "workspace.create.before": Omit; @@ -140,6 +175,7 @@ export const pluginHookRegistry = { "workspace.create.before": { waits: true }, "workspace.create.after": { waits: false }, "workspace.archive.after": { waits: false }, + "worktree.create.before": { waits: true }, "worktree.create.after": { waits: true }, "agent.create.before": { waits: true }, "agent.create.after": { waits: false }, diff --git a/packages/server/src/server/paseo-worktree-service.ts b/packages/server/src/server/paseo-worktree-service.ts index 9b08e487e9..1205554d4a 100644 --- a/packages/server/src/server/paseo-worktree-service.ts +++ b/packages/server/src/server/paseo-worktree-service.ts @@ -60,7 +60,7 @@ export interface AttemptFirstAgentBranchAutoNameResult { } export interface CreatePaseoWorktreeDeps extends CreateWorktreeCoreDeps { - lifecycle?: Pick; + lifecycle?: Pick; workspaceGitService: WorkspaceGitService; workspaceProvisioning: Pick; } diff --git a/packages/server/src/server/plugins/lifecycle.e2e.test.ts b/packages/server/src/server/plugins/lifecycle.e2e.test.ts index 1299387647..bd1dfa8859 100644 --- a/packages/server/src/server/plugins/lifecycle.e2e.test.ts +++ b/packages/server/src/server/plugins/lifecycle.e2e.test.ts @@ -463,7 +463,7 @@ ${options.hooks ?? ""} test("a clean daemon shutdown leaves a completed plugin-provider agent without an error", async () => { const root = await mkdtemp(path.join(tmpdir(), "plugin-provider-shutdown-")); - onTestFinished(() => rm(root, { recursive: true, force: true })); + onTestFinished(() => rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 })); const pluginDirectory = await createProviderPlugin(root); const workspace = path.join(root, "workspace"); await mkdir(workspace, { recursive: true }); @@ -507,7 +507,7 @@ test("a clean daemon shutdown leaves a completed plugin-provider agent without a test("reloading a plugin leaves a completed plugin-provider agent without an error", async () => { const root = await mkdtemp(path.join(tmpdir(), "plugin-provider-reload-")); - onTestFinished(() => rm(root, { recursive: true, force: true })); + onTestFinished(() => rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 })); const pluginDirectory = await createProviderPlugin(root); const workspace = path.join(root, "workspace"); await mkdir(workspace, { recursive: true }); @@ -556,7 +556,7 @@ test("reloading a plugin leaves a completed plugin-provider agent without an err test("a provider that never acknowledges session.close does not hold the daemon open", async () => { const root = await mkdtemp(path.join(tmpdir(), "plugin-provider-stuck-close-")); - onTestFinished(() => rm(root, { recursive: true, force: true })); + onTestFinished(() => rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 })); const pluginDirectory = await createProviderPlugin(root, { acknowledgeClose: false }); const workspace = path.join(root, "workspace"); await mkdir(workspace, { recursive: true }); @@ -752,9 +752,36 @@ test.each([false, true])( ], { cwd: repository, stdio: "pipe" }, ); + execFileSync("git", ["checkout", "-b", "plugin-base"], { cwd: repository, stdio: "pipe" }); + await writeFile(path.join(repository, "from-plugin-base.txt"), "base"); + execFileSync("git", ["add", "."], { cwd: repository, stdio: "pipe" }); + execFileSync( + "git", + [ + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "-c", + "commit.gpgsign=false", + "commit", + "-m", + "plugin base", + ], + { cwd: repository, stdio: "pipe" }, + ); + execFileSync("git", ["checkout", "main"], { cwd: repository, stdio: "pipe" }); const orderFile = path.join(root, "order.jsonl"); const pluginDirectory = await createProviderPlugin(root, { + acknowledgeClose: true, hooks: ` + server.addHook("worktree.create.before", async ({ request }) => { + const { appendFile } = await import("node:fs/promises"); + await appendFile(${JSON.stringify(orderFile)}, JSON.stringify({ hook: "worktree.create.before", request }) + "\\n"); + return { ...request, path: ${JSON.stringify(path.join(root, "elsewhere"))} + "/" + request.slug, + branch: request.branch === "accept-hook" ? "plugin-branch" : request.branch, + baseRef: request.branch === "accept-hook" ? "plugin-base" : request.baseRef }; + }); server.addHook("worktree.create.after", async ({ worktree }) => { const { appendFile, writeFile } = await import("node:fs/promises"); await appendFile(${JSON.stringify(orderFile)}, JSON.stringify({ hook: "worktree.create.after", worktree }) + "\\n"); @@ -778,8 +805,11 @@ test.each([false, true])( return request; });`, }); - const daemon = await createTestPaseoDaemon(); - const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); + let daemon = await createTestPaseoDaemon({ + paseoHomeRoot: path.join(root, "state"), + cleanup: false, + }); + let client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); try { await client.connect(); await client.patchDaemonConfig({ pluginsEnabled: true }); @@ -805,6 +835,23 @@ test.each([false, true])( }); expect(created.error).toBeNull(); const cwd = created.workspace!.workspaceDirectory; + expect(created.workspace!.gitRuntime?.currentBranch).toBe("plugin-branch"); + const persisted = JSON.parse( + await readFile(path.join(daemon.paseoHome, "projects", "workspaces.json"), "utf8"), + ); + expect(persisted).toContainEqual( + expect.objectContaining({ + workspaceId: created.workspace!.id, + branch: "plugin-branch", + baseBranch: "refs/heads/plugin-base", + worktreeRoot: cwd, + }), + ); + expect(cwd).toBe(path.join(await realpath(root), "elsewhere", "accept-hook")); + expect(await readFile(path.join(cwd, "from-plugin-base.txt"), "utf8")).toBe("base"); + expect( + execFileSync("git", ["branch", "--show-current"], { cwd, encoding: "utf8" }).trim(), + ).toBe("plugin-branch"); expect(await readFile(path.join(cwd, "plugin-ready.txt"), "utf8")).toBe("ready"); const firstAgent = withFirstAgentContext ? created.agent! @@ -835,18 +882,40 @@ test.each([false, true])( .split("\n") .map((line) => JSON.parse(line)); expect(records.map((record) => record.hook)).toEqual([ + "worktree.create.before", "worktree.create.after", "workspace.create.after", "agent.create.before", ]); expect({ - ...records[0].worktree, - sourceCheckout: await realpath(records[0].worktree.sourceCheckout), + ...records[1].worktree, + sourceCheckout: await realpath(records[1].worktree.sourceCheckout), }).toEqual({ path: cwd, - branch: "accept-hook", + branch: "plugin-branch", sourceCheckout: await realpath(repository), }); + expect((await client.fetchWorkspaces()).entries.map((workspace) => workspace.id)).toContain( + created.workspace!.id, + ); + await client.archiveWorkspace(created.workspace!.id); + await expect(stat(cwd)).rejects.toMatchObject({ code: "ENOENT" }); + const hookRecordsBeforeRestore = await readFile(orderFile, "utf8"); + await client.close(); + await daemon.close(); + daemon = await createTestPaseoDaemon({ + paseoHomeRoot: path.join(root, "state"), + cleanup: false, + pluginsEnabled: true, + plugins: { + "shutdown-provider-plugin": { source: "directory", path: pluginDirectory, enabled: true }, + }, + }); + client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); + await client.connect(); + await client.restoreWorkspace(created.workspace!.id); + expect(await readFile(path.join(cwd, "from-plugin-base.txt"), "utf8")).toBe("base"); + expect(await readFile(orderFile, "utf8")).toBe(hookRecordsBeforeRestore); const beforeFailure = await client.fetchWorkspaces(); const worktreesBeforeFailure = execFileSync("git", ["worktree", "list", "--porcelain"], { cwd: repository, @@ -882,12 +951,176 @@ test.each([false, true])( } finally { await client.close(); await daemon.close(); - await rm(root, { recursive: true, force: true }); + await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); } }, 60_000, ); +test("worktree before hook rejects unsafe destinations with plugin attribution before creating branches", async () => { + const root = await mkdtemp(path.join(tmpdir(), "paseo-worktree-before-invalid-")); + const repository = path.join(root, "repository"); + execFileSync("git", ["init", "-b", "main", repository], { stdio: "pipe" }); + execFileSync( + "git", + [ + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "-c", + "commit.gpgsign=false", + "commit", + "--allow-empty", + "-m", + "initial", + ], + { cwd: repository, stdio: "pipe" }, + ); + const occupied = path.join(root, "occupied"); + await mkdir(occupied); + const destinations = [ + occupied, + "relative/path", + repository, + path.join(repository, ".git", "worktree"), + root, + path.parse(root).root, + (await import("node:os")).homedir(), + ]; + const pluginDirectory = await createProviderPlugin(root, { + acknowledgeClose: true, + hooks: ` + server.addHook("worktree.create.before", async ({ request }) => { + if (request.branch === "throws") throw new Error("creation denied"); + if (request.branch === "readonly") return { ...request, repoRoot: "/different-repository" }; + return { ...request, path: ${JSON.stringify(destinations)}[Number(request.branch.slice(4))] }; + });`, + }); + const daemon = await createTestPaseoDaemon(); + const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); + try { + await client.connect(); + await client.patchDaemonConfig({ pluginsEnabled: true }); + await client.installDirectoryPlugin(pluginDirectory); + for (const branchName of [ + ...destinations.map((_, index) => `bad-${index}`), + "throws", + "readonly", + ]) { + const created = await client.createWorkspace({ + source: { kind: "worktree", cwd: repository, branchName, worktreeSlug: branchName }, + }); + expect(created.workspace).toBeNull(); + expect(created.error).toContain( + "Plugin shutdown-provider-plugin worktree.create.before failed:", + ); + expect( + execFileSync("git", ["branch", "--format=%(refname:short)"], { + cwd: repository, + encoding: "utf8", + }).trim(), + ).toBe("main"); + expect( + execFileSync("git", ["worktree", "list", "--porcelain"], { + cwd: repository, + encoding: "utf8", + }).match(/^worktree /gm), + ).toHaveLength(1); + } + expect((await client.fetchWorkspaces()).entries).toEqual([]); + } finally { + await client.close(); + await daemon.close(); + await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); + } +}, 60_000); + +test("the placement example creates a sibling worktree, opens its first agent there, lists and archives it", async () => { + const root = await mkdtemp(path.join(tmpdir(), "paseo-placement-example-")); + const repository = path.join(root, "repository"); + execFileSync("git", ["init", "-b", "main", repository], { stdio: "pipe" }); + execFileSync( + "git", + [ + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "-c", + "commit.gpgsign=false", + "commit", + "--allow-empty", + "-m", + "initial", + ], + { cwd: repository, stdio: "pipe" }, + ); + const providerDirectory = await createProviderPlugin(root, { + acknowledgeClose: true, + reportOpen: true, + }); + const daemon = await createTestPaseoDaemon(); + const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); + try { + await client.connect(); + await client.patchDaemonConfig({ pluginsEnabled: true }); + await client.installDirectoryPlugin(providerDirectory); + const installed = await client.installDirectoryPlugin( + fileURLToPath(new URL("../../../../../plugin-examples/worktree-placement", import.meta.url)), + ); + expect(installed.status).toBe("running"); + const created = await client.createWorkspace({ + source: { + kind: "worktree", + cwd: repository, + branchName: "feature/x", + worktreeSlug: "feature-x", + }, + }); + expect(created.error).toBeNull(); + const cwd = path.join(await realpath(root), "repository.feature-x"); + expect(created.workspace!.workspaceDirectory).toBe(cwd); + expect((await stat(cwd)).isDirectory()).toBe(true); + expect((await client.fetchWorkspaces()).entries.map((workspace) => workspace.id)).toContain( + created.workspace!.id, + ); + const worktrees = await client.getPaseoWorktreeList({ cwd: repository }); + expect(worktrees.error).toBeNull(); + expect(worktrees.worktrees).toContainEqual( + expect.objectContaining({ worktreePath: cwd, branchName: "feature/x" }), + ); + const collision = await client.createWorkspace({ + source: { + kind: "worktree", + cwd: repository, + branchName: "feature/x", + worktreeSlug: "another-slug", + }, + }); + expect(collision.workspace).toBeNull(); + expect(collision.error).toContain("Plugin worktree-placement worktree.create.before failed:"); + expect(collision.error).toContain("already exists"); + const agent = await client.createAgent({ + provider: PROVIDER_ID, + cwd, + workspaceId: created.workspace!.id, + }); + expect(agent.cwd).toBe(cwd); + const logs = await client.getPluginLogs("shutdown-provider-plugin"); + const opened = logs + .filter((entry) => entry.message.startsWith('{"hook":"provider.open"')) + .map((entry) => JSON.parse(entry.message)); + expect(opened.map((entry) => entry.config.cwd)).toContain(cwd); + await client.archiveWorkspace(created.workspace!.id); + await expect(stat(cwd)).rejects.toMatchObject({ code: "ENOENT" }); + } finally { + await client.close(); + await daemon.close(); + await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); + } +}, 60_000); + test("worktree includes reach the first agent without copying tracked or unignored files", async () => { const root = await mkdtemp(path.join(tmpdir(), "paseo-worktree-include-")); const repository = path.join(root, "repository"); @@ -1071,6 +1304,6 @@ test("worktree includes reach the first agent without copying tracked or unignor } finally { await client.close(); await daemon.close(); - await rm(root, { recursive: true, force: true }); + await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); } }, 60_000); diff --git a/packages/server/src/server/plugins/lifecycle/handlers.test.ts b/packages/server/src/server/plugins/lifecycle/handlers.test.ts index 5de6c7b061..e17cca1ed5 100644 --- a/packages/server/src/server/plugins/lifecycle/handlers.test.ts +++ b/packages/server/src/server/plugins/lifecycle/handlers.test.ts @@ -1,7 +1,7 @@ import { expect, test } from "vitest"; import { createPaseoApi } from "@getpaseo/client"; import { DaemonClient } from "@getpaseo/client/internal/daemon-client"; -import { PluginHookHandlers } from "./index.js"; +import { validateBeforeResult, PluginHookHandlers } from "./index.js"; const paseo = createPaseoApi( new DaemonClient({ url: "ws://127.0.0.1:1/ws", clientId: "lifecycle-unit" }), @@ -239,3 +239,17 @@ test("a waiting after hook propagates failures and stops later handlers", async ).rejects.toThrow("cannot initialize worktree"); expect(received).toEqual(["/worktree"]); }); + +test("checkout-branch hooks reject a branch-off baseRef", async () => { + const request = { + kind: "checkout-branch" as const, + repoRoot: "/repo", + sourceCheckout: "/repo", + branch: "feature", + slug: "feature", + path: "/work/feature", + }; + await expect( + validateBeforeResult("worktree.create.before", request, { ...request, baseRef: "main" }), + ).rejects.toThrow(/baseRef/); +}); diff --git a/packages/server/src/server/plugins/lifecycle/index.ts b/packages/server/src/server/plugins/lifecycle/index.ts index 05f62373f6..d4f58cc78c 100644 --- a/packages/server/src/server/plugins/lifecycle/index.ts +++ b/packages/server/src/server/plugins/lifecycle/index.ts @@ -1,3 +1,4 @@ +import { validateBranchSlug } from "@getpaseo/protocol/branch-slug"; import { createLifecycleRegistration, pluginHookRegistry, @@ -37,7 +38,56 @@ export type PluginBeforeResults = PluginWireBeforeRequests & { "agent.open.before": SessionOpenWireRequest & { mcpServerOwners?: Record }; }; +const worktreeRequestFields = { + repoRoot: z.string(), + sourceCheckout: z.string(), + branch: z.string().min(1), + slug: z.string().refine((value) => validateBranchSlug(value).valid, "Invalid worktree slug"), + path: z.string().min(1), +}; +const changeRequestFields = { + headRef: z.string().min(1), + headRepositoryOwner: z.string().optional(), + checkoutRefs: z + .array(z.object({ remoteName: z.string().optional(), remoteRef: z.string() })) + .optional(), + pushRemoteUrl: z.string().optional(), + trackOriginHead: z.boolean().optional(), +}; +const worktreeRequestSchema = z.discriminatedUnion("kind", [ + z + .object({ ...worktreeRequestFields, kind: z.literal("branch-off"), baseRef: z.string().min(1) }) + .strict(), + z + .object({ + ...worktreeRequestFields, + kind: z.literal("checkout-branch"), + }) + .strict(), + z + .object({ + ...worktreeRequestFields, + ...changeRequestFields, + kind: z.literal("checkout-change-request"), + baseRef: z.string().min(1), + forge: z.string(), + changeRequestNumber: z.number().int().positive(), + headRepository: z.string().optional(), + }) + .strict(), + z + .object({ + ...worktreeRequestFields, + ...changeRequestFields, + kind: z.literal("checkout-github-pr"), + baseRef: z.string().min(1), + githubPrNumber: z.number().int().positive(), + }) + .strict(), +]); + const beforeSchemas = { + "worktree.create.before": worktreeRequestSchema, "agent.create.before": CreateAgentRequestMessageSchema.pick({ config: true, env: true, @@ -162,11 +212,11 @@ export function publishAgentStream( } } -export function validateBeforeResult( +export async function validateBeforeResult( name: Name, input: PluginWireBeforeRequests[Name], output: unknown, -): PluginWireBeforeRequests[Name] { +): Promise { const result = validateBeforeRequest(name, output); if (name === "agent.open.before") { const previous = beforeSchemas["agent.open.before"].parse(input); @@ -191,6 +241,13 @@ export function validateBeforeResult { + const { tempDir, repoDir } = createGitRepository(); + const worktreeRoot = join(realpathSync(tempDir), "external-worktree"); + execFileSync("git", ["worktree", "add", "-b", "external-feature", worktreeRoot], { + cwd: repoDir, + stdio: "pipe", + }); + const workspace = createWorkspace({ + cwd: worktreeRoot, + worktreeRoot, + mainRepoRoot: repoDir, + branch: "external-feature", + baseBranch: "main", + isPaseoOwnedWorktree: false, + }); + execFileSync("git", ["worktree", "remove", worktreeRoot], { cwd: repoDir, stdio: "pipe" }); + const unarchived: string[] = []; + const service = createWorkspaceRecoveryService({ + paseoHome: join(tempDir, "paseo-home"), + getWorkspace: async () => workspace, + getProject: async () => createProject({ rootPath: repoDir }), + isDirectory: async (target) => existsSync(target) && statSync(target).isDirectory(), + unarchiveWorkspace: async (record) => { + unarchived.push(record.workspaceId); + }, + }); + await expect(service.restore(workspace.workspaceId)).resolves.toEqual({ + workspaceId: workspace.workspaceId, + action: "restore", + }); + expect(readFileSync(join(worktreeRoot, "README.md"), "utf8").trim()).toBe("initial"); + expect( + execFileSync("git", ["branch", "--show-current"], { + cwd: worktreeRoot, + encoding: "utf8", + }).trim(), + ).toBe("external-feature"); + expect(unarchived).toEqual([workspace.workspaceId]); +}); diff --git a/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.ts b/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.ts index 1a715dd349..a683a07744 100644 --- a/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.ts +++ b/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.ts @@ -166,6 +166,7 @@ export function createWorkspaceRecoveryService(deps: { } let previousWorktreePath = workspace.worktreeRoot; + let hasRecordedWorktreePath = Boolean(previousWorktreePath); if (!previousWorktreePath) { // COMPAT(worktreeRestoreMissingWorktreeRoot): records created before v0.1.110 // lack durable backing placement; remove filesystem discovery after 2027-01-17. @@ -176,6 +177,7 @@ export function createWorkspaceRecoveryService(deps: { previousWorktreePath = ownership.allowed ? (ownership.worktreePath ?? workspace.cwd) : workspace.cwd; + hasRecordedWorktreePath = ownership.allowed; } let recreatedWorktreePath: string; @@ -187,6 +189,7 @@ export function createWorkspaceRecoveryService(deps: { paseoHome: deps.paseoHome, worktreesRoot: deps.worktreesRoot, + ...(hasRecordedWorktreePath ? { worktreePath: previousWorktreePath } : {}), }); recreatedWorktreePath = result.worktreePath; } catch (error) { diff --git a/packages/server/src/server/workspace-archive-service.test.ts b/packages/server/src/server/workspace-archive-service.test.ts index a1a901c4d6..567c80054f 100644 --- a/packages/server/src/server/workspace-archive-service.test.ts +++ b/packages/server/src/server/workspace-archive-service.test.ts @@ -7,7 +7,9 @@ import { afterEach, describe, expect, test, vi } from "vitest"; import type { ForgeService } from "../services/forge-service.js"; import { createRealpathAwarePathMatcher } from "../utils/path.js"; -import { createWorktree, type WorktreeConfig } from "../utils/worktree.js"; +import { getPaseoWorktreeMetadataPath } from "../utils/worktree-metadata.js"; +import { archiveCommand } from "./worktree/commands.js"; +import { createWorktree, listPaseoWorktrees, type WorktreeConfig } from "../utils/worktree.js"; import type { ManagedAgent } from "./agent/agent-manager.js"; import type { AgentStorage, StoredAgentRecord } from "./agent/agent-storage.js"; import type { WorkspaceGitService } from "./workspace-git-service.js"; @@ -190,6 +192,54 @@ function assertArchiveResult( } describe("archiveByScope", () => { + test.each(["workspace", "worktree"] as const)( + "%s archive preserves a restored external worktree despite its marker", + async (kind) => { + const { tempDir, repoDir } = createGitRepo(); + const paseoHome = path.join(tempDir, ".paseo"); + const recordedPath = path.join(tempDir, "external"); + execFileSync("git", ["worktree", "add", "-b", "external", recordedPath], { + cwd: repoDir, + stdio: "pipe", + }); + execFileSync("git", ["worktree", "remove", recordedPath], { cwd: repoDir, stdio: "pipe" }); + const restored = await createWorktree({ + cwd: repoDir, + paseoHome, + worktreeSlug: "external", + worktreePath: recordedPath, + source: { kind: "restore", branchName: "external", baseRef: "main" }, + }); + expect(existsSync(await getPaseoWorktreeMetadataPath(restored.worktreePath))).toBe(true); + const workspaceId = "external-workspace"; + const result = await archiveByScope( + createArchiveDeps({ + paseoHome, + activeWorkspaces: [ + { + workspaceId, + cwd: restored.worktreePath, + kind: "worktree", + worktreeRoot: restored.worktreePath, + mainRepoRoot: repoDir, + isPaseoOwnedWorktree: false, + }, + ], + }), + { + scope: + kind === "workspace" + ? { kind, workspaceId } + : { kind, targetPath: restored.worktreePath }, + requestId: "archive-external", + }, + ); + expect(result.removedDirectory).toBe(false); + expect(existsSync(restored.worktreePath)).toBe(true); + expect(result.archivedWorkspaceIds).toEqual([workspaceId]); + }, + ); + test("workspace scope archives the record and removes the directory on last reference", async () => { const { tempDir, repoDir } = createGitRepo(); const paseoHome = path.join(tempDir, ".paseo"); @@ -220,6 +270,120 @@ describe("archiveByScope", () => { expect(existsSync(worktree.worktreePath)).toBe(false); }); + test("workspace scope archives the record but leaves a plugin-placed directory whose marker is gone", async () => { + const { tempDir, repoDir } = createGitRepo(); + const paseoHome = path.join(tempDir, ".paseo"); + const worktree = await createWorktree({ + cwd: repoDir, + worktreeSlug: "unproven-workspace", + source: { kind: "branch-off", baseBranch: "main", branchName: "unproven-workspace" }, + paseoHome, + worktreePath: path.join(tempDir, "placed-worktree"), + }); + // Remove the ownership marker: no proof remains for this path. + rmSync(await getPaseoWorktreeMetadataPath(worktree.worktreePath), { force: true }); + const workspaceId = "ws-unproven"; + + const logs: Array<{ targetPath: string; msg: string }> = []; + const dependencies = createArchiveDeps({ + paseoHome, + activeWorkspaces: [{ workspaceId, cwd: worktree.worktreePath, kind: "worktree" }], + }); + dependencies.sessionLogger = pino( + { level: "warn" }, + { + write(message) { + logs.push(JSON.parse(message)); + }, + }, + ); + const result = await archiveByScope(dependencies, { + scope: { kind: "workspace", workspaceId }, + requestId: "req-unproven-workspace", + }); + + assertArchiveResult(result, { archivedWorkspaceIds: [workspaceId], removedDirectory: false }); + expect(result.directoryLeftBehind?.path).toBe(worktree.worktreePath); + expect(result.directoryLeftBehind?.reason).toContain("no ownership proof"); + expect(existsSync(worktree.worktreePath)).toBe(true); + expect(logs).toContainEqual( + expect.objectContaining({ + targetPath: worktree.worktreePath, + msg: expect.stringContaining("no ownership proof"), + }), + ); + }); + + test("archives a plugin-placed worktree by its discovered directory name", async () => { + const { tempDir, repoDir } = createGitRepo(); + const paseoHome = path.join(tempDir, ".paseo"); + const worktreePath = path.join(tempDir, "sibling-feature"); + await createWorktree({ + cwd: repoDir, + paseoHome, + worktreePath, + worktreeSlug: "original-slug", + source: { kind: "branch-off", branchName: "feature", baseBranch: "main" }, + }); + const dependencies = createArchiveDeps({ paseoHome, activeWorkspaces: [] }); + const result = await archiveCommand( + { + ...dependencies, + workspaceGitService: { + ...dependencies.workspaceGitService, + listWorktrees: (cwd) => listPaseoWorktrees({ cwd, paseoHome }), + }, + }, + { + repoRoot: repoDir, + worktreeSlug: "sibling-feature", + scope: "worktree", + requestId: "slug-archive", + }, + ); + expect(result).toEqual({ ok: true, removedAgents: [] }); + expect(existsSync(worktreePath)).toBe(false); + }); + + test("workspace scope deletes a plugin-placed directory on registry proof even with the marker gone", async () => { + const { tempDir, repoDir } = createGitRepo(); + const paseoHome = path.join(tempDir, ".paseo"); + const worktree = await createWorktree({ + cwd: repoDir, + worktreeSlug: "registry-proven-workspace", + source: { + kind: "branch-off", + baseBranch: "main", + branchName: "registry-proven-workspace", + }, + paseoHome, + worktreePath: path.join(tempDir, "placed-worktree"), + }); + rmSync(await getPaseoWorktreeMetadataPath(worktree.worktreePath), { force: true }); + const workspaceId = "ws-registry-proven"; + + const result = await archiveByScope( + createArchiveDeps({ + paseoHome, + activeWorkspaces: [ + { + workspaceId, + cwd: worktree.worktreePath, + kind: "worktree", + isPaseoOwnedWorktree: true, + worktreeRoot: worktree.worktreePath, + mainRepoRoot: repoDir, + }, + ], + }), + { scope: { kind: "workspace", workspaceId }, requestId: "req-registry-proven-workspace" }, + ); + + assertArchiveResult(result, { archivedWorkspaceIds: [workspaceId], removedDirectory: true }); + expect(result.directoryLeftBehind).toBeUndefined(); + expect(existsSync(worktree.worktreePath)).toBe(false); + }); + test("workspace scope runs teardown while keeping a directory referenced by a sibling", async () => { const { tempDir, repoDir } = createGitRepo(); writeFileSync( diff --git a/packages/server/src/server/workspace-archive-service.ts b/packages/server/src/server/workspace-archive-service.ts index e9e58681a1..78f8c0b97d 100644 --- a/packages/server/src/server/workspace-archive-service.ts +++ b/packages/server/src/server/workspace-archive-service.ts @@ -69,6 +69,10 @@ export interface ArchiveResult { archivedAgentIds: string[]; archivedWorkspaceIds: string[]; removedDirectory: boolean; + // Set when the record archived but its worktree directory was left on + // disk because no ownership proof held for it. The directory is never + // deleted in that case; the path and reason surface here and in the log. + directoryLeftBehind?: { path: string; reason: string }; } export interface ArchiveByScopeRequest { @@ -92,6 +96,15 @@ export async function requireActiveWorkspaceForArchive( interface BackingDirectory { path: string; isPaseoOwnedWorktree: boolean; + // True when the directory backs a worktree workspace (or a worktree-scope + // archive), so a failed ownership proof means a Paseo worktree directory + // is being left behind rather than a user's local checkout being ignored. + expectsPaseoOwnership: boolean; + // True only when this backing came from a workspace registry record + // matched to this path (the record is itself an ownership proof, passed + // through to deletePaseoWorktree). Disk-derived backings stay false: + // they must prove ownership on disk. + registryProven: boolean; mainRepoRoot: string | null; paseoWorktreesRoot: string | null; } @@ -141,6 +154,7 @@ async function archiveByScopeWithPriority( } let removedDirectory = false; + let directoryLeftBehind: ArchiveResult["directoryLeftBehind"]; try { if (targetWorkspaceIds.length > 0) { @@ -168,18 +182,21 @@ async function archiveByScopeWithPriority( } if (target.backing !== null) { - removedDirectory = await maybeRemoveDirectory( + const removal = await maybeRemoveDirectory( dependencies, request, target, archivedWorkspaceIds, ); + removedDirectory = removal.removedDirectory; + directoryLeftBehind = removal.directoryLeftBehind; } return { archivedAgentIds: Array.from(archivedAgents), archivedWorkspaceIds, removedDirectory, + ...(directoryLeftBehind ? { directoryLeftBehind } : {}), }; } finally { if (targetWorkspaceIds.length > 0) { @@ -226,14 +243,16 @@ async function resolveArchiveTarget( }), ) ).filter((workspace): workspace is ActiveWorkspaceRef => workspace !== null); - const persistedMainRepoRoot = targetWorkspaces.find( - (workspace) => workspace.mainRepoRoot, - )?.mainRepoRoot; + const recordedId = await dependencies.findWorkspaceIdForCwd(backing.path); + const recorded = recordedId ? await dependencies.getWorkspace?.(recordedId) : null; + const record = + targetWorkspaces.find((workspace) => workspace.kind === "worktree") ?? + (recorded && matchesBackingDirectory(recorded.worktreeRoot ?? recorded.cwd) + ? recorded + : null) ?? + targetWorkspaces[0]; return { - backing: { - ...backing, - mainRepoRoot: persistedMainRepoRoot ?? backing.mainRepoRoot, - }, + backing: record ? await resolveWorkspaceBackingDirectory(record, dependencies) : backing, teardownTargets: targetWorkspaces.length > 0 ? targetWorkspaces.map((workspace) => ({ @@ -271,10 +290,22 @@ async function resolveWorkspaceBackingDirectory( workspace: ActiveWorkspaceRef, dependencies: Pick, ): Promise { + if (workspace.isPaseoOwnedWorktree === false) { + return { + path: resolve(workspace.worktreeRoot ?? workspace.cwd), + isPaseoOwnedWorktree: false, + expectsPaseoOwnership: false, + registryProven: false, + mainRepoRoot: workspace.mainRepoRoot ?? null, + paseoWorktreesRoot: null, + }; + } if (workspace.isPaseoOwnedWorktree && workspace.worktreeRoot && workspace.mainRepoRoot) { return { path: resolve(workspace.worktreeRoot), isPaseoOwnedWorktree: true, + expectsPaseoOwnership: true, + registryProven: true, mainRepoRoot: workspace.mainRepoRoot, paseoWorktreesRoot: null, }; @@ -283,6 +314,8 @@ async function resolveWorkspaceBackingDirectory( return { path: resolve(workspace.cwd), isPaseoOwnedWorktree: false, + expectsPaseoOwnership: false, + registryProven: false, mainRepoRoot: workspace.mainRepoRoot ?? null, paseoWorktreesRoot: null, }; @@ -309,6 +342,8 @@ async function resolveBackingDirectory( return { path: resolve(ownership.allowed && ownership.worktreePath ? ownership.worktreePath : cwd), isPaseoOwnedWorktree: ownership.allowed, + expectsPaseoOwnership: true, + registryProven: false, mainRepoRoot: ownership.repoRoot ?? null, paseoWorktreesRoot: ownership.worktreeRoot ?? null, }; @@ -352,10 +387,28 @@ async function maybeRemoveDirectory( request: Pick, target: ArchiveTarget, archivedWorkspaceIds: string[], -): Promise { +): Promise<{ + removedDirectory: boolean; + directoryLeftBehind?: { path: string; reason: string }; +}> { const backing = target.backing; if (!backing?.isPaseoOwnedWorktree) { - return false; + // Missing ownership proof for a worktree-backed directory: the record + // still archives, but the directory is left in place and surfaced. + // Never delete an unproven directory. + if (backing?.expectsPaseoOwnership) { + const reason = + "no ownership proof (not under the Paseo worktrees root, no paseo/worktree.json marker, no registry record)"; + dependencies.sessionLogger?.warn( + { targetPath: backing.path, requestId: request.requestId }, + `Worktree directory left in place during archive: ${reason}`, + ); + return { + removedDirectory: false, + directoryLeftBehind: { path: backing.path, reason }, + }; + } + return { removedDirectory: false }; } const archivedWorkspaceIdSet = new Set(archivedWorkspaceIds); @@ -382,7 +435,7 @@ async function maybeRemoveDirectory( { err: error, targetPath: backing.path, requestId: request.requestId }, "Worktree teardown failed during archive; workspace already archived", ); - return false; + return { removedDirectory: false }; } throw error; } @@ -396,7 +449,7 @@ async function maybeRemoveDirectory( dependencies, )) ) { - return false; + return { removedDirectory: false }; } try { @@ -407,16 +460,17 @@ async function maybeRemoveDirectory( worktreesRoot: backing.paseoWorktreesRoot ?? undefined, paseoHome: dependencies.paseoHome, worktreesBaseRoot: dependencies.paseoWorktreesBaseRoot, + registryProven: backing.registryProven, }); dependencies.workspaceGitService.invalidateWorktrees(); dependencies.github.invalidate({ cwd: backing.path }); - return true; + return { removedDirectory: true }; } catch (error) { dependencies.sessionLogger?.warn( { err: error, targetPath: backing.path, requestId: request.requestId }, "Worktree disk removal failed during archive; workspace already archived", ); - return false; + return { removedDirectory: false }; } } diff --git a/packages/server/src/server/worktree-core.posix.test.ts b/packages/server/src/server/worktree-core.posix.test.ts index 4ec533d0c3..7a7a342732 100644 --- a/packages/server/src/server/worktree-core.posix.test.ts +++ b/packages/server/src/server/worktree-core.posix.test.ts @@ -24,6 +24,7 @@ import { getPaseoWorktreeMetadataPath, readPaseoWorktreeMetadata, } from "../utils/worktree-metadata.js"; +import { validateBeforeRequest, validateBeforeResult } from "./plugins/lifecycle/index.js"; import { UnknownBranchError } from "../utils/worktree.js"; import { createWorktreeCore as createCoreWorktree } from "./worktree-core.js"; import { isPlatform } from "../test-utils/platform.js"; @@ -419,6 +420,21 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => { expect(existsSync(result.worktree.worktreePath)).toBe(true); }); + test("keeps default placement suffixes when the default destination already exists", async () => { + const { tempDir, repoDir, paseoHome } = createGitRepo(); + cleanupPaths.push(tempDir); + const first = await createCoreWorktree( + { cwd: repoDir, paseoHome, branchName: "first", worktreeSlug: "same" }, + createCoreDeps(), + ); + const second = await createCoreWorktree( + { cwd: repoDir, paseoHome, branchName: "second", worktreeSlug: "same" }, + createCoreDeps(), + ); + expect(second.worktree.worktreePath).toBe(first.worktree.worktreePath + "-1"); + expect(existsSync(first.worktree.worktreePath)).toBe(true); + }); + test("creates branch-off worktrees from origin main without tracking origin main", async () => { const { tempDir, repoDir, paseoHome } = createGitRepoWithOriginMain(); cleanupPaths.push(tempDir); @@ -488,6 +504,42 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => { expect(result.worktree.branchName).toBe("feature/review-pr"); }); + test("round trips every resolved change-request field through an unchanged before-hook result", async () => { + const { tempDir, repoDir, paseoHome } = createGitHubPrRemoteRepo(); + cleanupPaths.push(tempDir); + const deps = createCoreDeps(); + const requests: unknown[] = []; + const result = await createCoreWorktree( + { cwd: repoDir, githubPrNumber: 123, refName: "feature/review-pr", paseoHome }, + { + ...deps, + lifecycle: { + before: async (name, request) => { + requests.push(request); + return validateBeforeResult(name, validateBeforeRequest(name, request), request); + }, + }, + }, + ); + expect(requests).toEqual([ + { + kind: "checkout-change-request", + forge: "github", + changeRequestNumber: 123, + headRef: "feature/review-pr", + baseRef: "main", + branch: "feature/review-pr", + checkoutRefs: [{ remoteName: "origin", remoteRef: "refs/pull/123/head" }], + trackOriginHead: true, + repoRoot: repoDir, + sourceCheckout: repoDir, + slug: "feature-review-pr", + path: result.worktree.worktreePath, + }, + ]); + expect(result.worktree.branchName).toBe("feature/review-pr"); + }); + test("uses the PR head ref as the default slug when no slug is supplied", async () => { const { tempDir, repoDir, paseoHome } = createGitHubPrRemoteRepo(); cleanupPaths.push(tempDir); diff --git a/packages/server/src/server/worktree-core.ts b/packages/server/src/server/worktree-core.ts index b0310d6e1f..cc6c9fdbd6 100644 --- a/packages/server/src/server/worktree-core.ts +++ b/packages/server/src/server/worktree-core.ts @@ -1,8 +1,11 @@ +import type { PluginWorktreeCreateRequest } from "@getpaseo/plugin/server"; +import type { PluginLifecycle } from "./plugins/lifecycle/index.js"; import { createNameId } from "mnemonic-id"; import type { ForgeService } from "../services/forge-service.js"; import { createWorktree, + resolveDefaultWorktreePath, slugify, validateBranchSlug, type CreatedWorktree, @@ -15,7 +18,7 @@ import { } from "./resolve-worktree-creation-intent.js"; import type { ChangeRequestCheckoutSource, FirstAgentContext } from "@getpaseo/protocol/messages"; import type { WorkspaceGitService } from "./workspace-git-service.js"; -import { runWithGitCommandPriority } from "../utils/run-git-command.js"; +import { runGitCommand, runWithGitCommandPriority } from "../utils/run-git-command.js"; export interface CreateWorktreeCoreInput { cwd: string; @@ -31,6 +34,7 @@ export interface CreateWorktreeCoreInput { } export interface CreateWorktreeCoreDeps { + lifecycle?: Pick; github: ForgeService; workspaceGitService?: Pick< WorkspaceGitService, @@ -90,7 +94,7 @@ async function createWorktreeCoreWithPriority( } const forge = await resolveForge(repoRoot, deps, intentInput); - const intent = await resolveWorktreeCreationIntent(intentInput, repoRoot, { + let intent = await resolveWorktreeCreationIntent(intentInput, repoRoot, { forge: forge.forge, forgeService: forge.service, resolveDefaultBranch: (root) => resolveDefaultBranch(root, deps), @@ -114,10 +118,33 @@ async function createWorktreeCoreWithPriority( } } + const defaultPath = await resolveDefaultWorktreePath({ + cwd: repoRoot, + paseoHome: input.paseoHome, + worktreesRoot: input.worktreesRoot, + worktreeSlug: normalizedSlug, + }); + const { stdout: sourceRoot } = await runGitCommand(["rev-parse", "--show-toplevel"], { + cwd: input.cwd, + }); + const sourceCheckout = sourceRoot.trim(); + const request = describeCreationRequest(intent, { + repoRoot, + sourceCheckout, + slug: normalizedSlug, + path: defaultPath, + }); + const transformed = deps.lifecycle + ? await deps.lifecycle.before("worktree.create.before", request) + : request; + normalizedSlug = validateWorktreeSlug(transformed.slug); + intent = creationIntentFromRequest(transformed, intent); + return { worktree: await createWorktree({ cwd: repoRoot, worktreeSlug: normalizedSlug, + worktreePath: transformed.path, source: intent, paseoHome: input.paseoHome, worktreesRoot: input.worktreesRoot, @@ -128,6 +155,61 @@ async function createWorktreeCoreWithPriority( }; } +function describeCreationRequest( + intent: WorktreeCreationIntent, + placement: Pick, +): PluginWorktreeCreateRequest { + if (intent.kind === "branch-off") + return { + ...placement, + kind: intent.kind, + branch: intent.branchName, + baseRef: intent.baseBranch, + }; + if (intent.kind === "checkout-branch") + return { ...placement, kind: intent.kind, branch: intent.branchName }; + const { localBranchName, baseRefName, ...facts } = intent; + return { + ...placement, + ...facts, + branch: localBranchName ?? intent.headRef, + baseRef: baseRefName, + }; +} + +function creationIntentFromRequest( + request: PluginWorktreeCreateRequest, + original: WorktreeCreationIntent, +): WorktreeCreationIntent { + if (request.kind === "branch-off") { + return { kind: request.kind, branchName: request.branch, baseBranch: request.baseRef }; + } + if (request.kind === "checkout-branch") { + return { + kind: request.kind, + branchName: request.branch, + }; + } + const { + repoRoot: _repoRoot, + sourceCheckout: _checkout, + slug: _slug, + path: _path, + branch, + baseRef, + ...facts + } = request; + const keepLocalBranchName = + branch !== request.headRef || + ((original.kind === "checkout-change-request" || original.kind === "checkout-github-pr") && + original.localBranchName !== undefined); + return { + ...facts, + ...(keepLocalBranchName ? { localBranchName: branch } : {}), + baseRefName: baseRef, + }; +} + async function resolveForge( repoRoot: string, deps: CreateWorktreeCoreDeps, diff --git a/packages/server/src/server/worktree/commands.ts b/packages/server/src/server/worktree/commands.ts index 0aab346984..4382e46633 100644 --- a/packages/server/src/server/worktree/commands.ts +++ b/packages/server/src/server/worktree/commands.ts @@ -1,6 +1,6 @@ -import { join } from "node:path"; +import { basename } from "node:path"; -import { getPaseoWorktreesRoot, isPaseoOwnedWorktreeCwd } from "../../utils/worktree.js"; +import { isPaseoOwnedWorktreeCwd } from "../../utils/worktree.js"; import { archiveByScope, resolveWorkspaceIdAtPath, @@ -208,10 +208,18 @@ async function resolveWorktreeSlugPath( repoRoot: string, worktreeSlug: string, ): Promise { - const worktreesRoot = await getPaseoWorktreesRoot( - repoRoot, - dependencies.paseoHome, - dependencies.paseoWorktreesBaseRoot, - ); - return join(worktreesRoot, worktreeSlug); + // Worktrees can live anywhere (legacy root or wherever + // a plugin placed them), so a slug resolves against the + // discovered worktree list for the repo, never a guessed path. + const worktrees = await dependencies.workspaceGitService.listWorktrees(repoRoot); + const match = worktrees.find((entry) => basename(entry.path) === worktreeSlug); + if (!match) { + const found = worktrees.map((entry) => basename(entry.path)); + throw new Error( + found.length > 0 + ? `Paseo worktree not found for slug ${worktreeSlug}: found ${found.join(", ")}` + : `Paseo worktree not found for slug ${worktreeSlug}`, + ); + } + return match.path; } diff --git a/packages/server/src/utils/checkout-git.ts b/packages/server/src/utils/checkout-git.ts index eed39f63e5..358bd6eb69 100644 --- a/packages/server/src/utils/checkout-git.ts +++ b/packages/server/src/utils/checkout-git.ts @@ -45,6 +45,8 @@ import { unquoteGitPath } from "./git-quoted-path.js"; import { isPaseoOwnedWorktreeCwd, resolvePaseoWorktreesBaseRoot } from "./worktree.js"; import { branchNameFromRef, + findPaseoWorktreeRootForCwd, + hasPaseoWorktreeMetadata, getPaseoWorktreeChangeRequestHintForBranch, type PaseoWorktreeMetadata, readPaseoWorktreeMetadata, @@ -1126,9 +1128,17 @@ async function getMainRepoRootFromCommonDir( }, ); const worktrees = parseWorktreeList(worktreeOut); + const paseoPaths = new Set( + ( + await Promise.all( + worktrees.map(async (wt) => ((await hasPaseoWorktreeMetadata(wt.path)) ? wt.path : null)), + ) + ).filter((p) => p !== null), + ); const nonBareNonPaseo = worktrees.filter( (wt) => !wt.isBare && + !paseoPaths.has(wt.path) && !isPaseoWorktreePath(wt.path, { paseoHome: context?.paseoHome, worktreesRoot: context?.worktreesRoot, @@ -1257,7 +1267,7 @@ async function getPaseoWorktreeForCwd( options: PaseoWorktreeLookupOptions = {}, ): Promise { // Fast-path reject: non-worktree paths do not need expensive ownership checks. - if (!/[\\/]worktrees[\\/]/.test(cwd)) { + if (!/[\\/]worktrees[\\/]/.test(cwd) && (await findPaseoWorktreeRootForCwd(cwd)) === null) { return { isPaseoOwnedWorktree: false }; } diff --git a/packages/server/src/utils/worktree-metadata.ts b/packages/server/src/utils/worktree-metadata.ts index 13c95567db..fcb0454672 100644 --- a/packages/server/src/utils/worktree-metadata.ts +++ b/packages/server/src/utils/worktree-metadata.ts @@ -2,7 +2,7 @@ import { mkdir, open, realpath, rename, stat, writeFile } from "node:fs/promises import { randomUUID } from "node:crypto"; import { constants } from "node:fs"; import pLimit from "p-limit"; -import { isAbsolute, join, resolve } from "path"; +import { dirname, isAbsolute, join, resolve } from "path"; import { z } from "zod"; const MAX_WORKTREE_METADATA_BYTES = 64 * 1024; @@ -329,6 +329,39 @@ export async function markPaseoWorktreeFirstAgentBranchAutoNameAttempted( }); } +export async function hasPaseoWorktreeMetadata(worktreeRoot: string): Promise { + try { + return (await readPaseoWorktreeMetadata(worktreeRoot)) !== null; + } catch { + return false; + } +} + +/** + * Filesystem-only search for a Paseo worktree root at or above cwd: the + * first directory containing a .git entry wins, and it only counts when + * its git admin dir holds the paseo/worktree.json marker. Lets callers + * cheaply rule out plain directories before running git ownership checks. + */ +export async function findPaseoWorktreeRootForCwd(cwd: string): Promise { + let current = resolve(cwd); + for (;;) { + if ( + await stat(join(current, ".git")).then( + () => true, + () => false, + ) + ) { + return (await hasPaseoWorktreeMetadata(current)) ? current : null; + } + const parent = dirname(current); + if (parent === current) { + return null; + } + current = parent; + } +} + export async function readPaseoWorktreeMetadata( worktreeRoot: string, ): Promise { diff --git a/packages/server/src/utils/worktree-path.ts b/packages/server/src/utils/worktree-path.ts new file mode 100644 index 0000000000..d36abea762 --- /dev/null +++ b/packages/server/src/utils/worktree-path.ts @@ -0,0 +1,88 @@ +import { realpath, lstat } from "node:fs/promises"; +import { homedir } from "node:os"; +import { basename, dirname, isAbsolute, join, parse, resolve, sep } from "node:path"; +import { getRelativePathInsideRoot } from "./path.js"; + +async function normalizeAbsolute(path: string): Promise { + try { + return await realpath(path); + } catch { + return resolve(path); + } +} + +// Resolve a path that does not exist yet (the normal case for a worktree +// destination): realpath the nearest existing ancestor, then append the +// missing tail. A plain resolve() would let a symlinked parent smuggle +// the destination past the denylist — e.g. /alias -> /.git. +async function normalizeCandidatePath(path: string): Promise { + let current = resolve(path); + const missing: string[] = []; + while (!(await pathExists(current))) { + missing.unshift(basename(current)); + const parent = dirname(current); + if (parent === current) { + break; + } + current = parent; + } + const resolvedAncestor = await normalizeAbsolute(current); + return missing.length > 0 ? join(resolvedAncestor, ...missing) : resolvedAncestor; +} + +async function pathExists(path: string): Promise { + try { + await lstat(path); + return true; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; + throw error; + } +} + +/** + * Validate a worktree destination. Throws + * with the reason on any violation; returns the normalized absolute path. + */ +export async function validateWorktreePath(options: { + candidate: string; + repoPath: string; +}): Promise { + const { candidate, repoPath } = options; + if (!isAbsolute(candidate)) { + throw new Error( + `Worktree hook returned a relative path '${candidate}'; it must be an absolute path`, + ); + } + const normalized = await normalizeCandidatePath(candidate); + const normalizedRepoPath = await normalizeAbsolute(repoPath); + + if (normalized === parse(normalized).root) { + throw new Error("Worktree hook returned the filesystem root, which is not allowed"); + } + if (normalized === (await normalizeAbsolute(homedir()))) { + throw new Error("Worktree hook returned the user's home directory, which is not allowed"); + } + if (normalized === normalizedRepoPath) { + throw new Error("Worktree hook returned the repository root itself, which is not allowed"); + } + if ( + [normalized, resolve(candidate)].some((path) => + path + .split(sep) + .some((part) => (process.platform === "win32" ? part.toLowerCase() : part) === ".git"), + ) + ) { + throw new Error(`Worktree hook returned a path inside a .git directory: ${normalized}`); + } + const relativeToCandidate = getRelativePathInsideRoot(normalized, normalizedRepoPath); + if (relativeToCandidate !== null && relativeToCandidate !== "") { + throw new Error(`Worktree hook returned an ancestor of the repository: ${normalized}`); + } + if ((await pathExists(normalized)) || (await pathExists(candidate))) { + throw new Error( + `Worktree hook returned a path that already exists: ${normalized}. Paseo creates the returned path.`, + ); + } + return normalized; +} diff --git a/packages/server/src/utils/worktree.posix.test.ts b/packages/server/src/utils/worktree.posix.test.ts index aede7cf8e3..35d59cce3f 100644 --- a/packages/server/src/utils/worktree.posix.test.ts +++ b/packages/server/src/utils/worktree.posix.test.ts @@ -1,5 +1,6 @@ // POSIX-only: git worktree and teardown shell fixtures /* eslint-disable max-nested-callbacks */ +import { validateWorktreePath } from "./worktree-path.js"; import { describe, it, expect, beforeEach, afterEach } from "vitest"; import { createWorktree as createWorktreePrimitive, @@ -159,7 +160,7 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { ).resolves.toMatchObject({ allowed: true, worktreeRoot: join(worktreesRoot, projectHash) }); await expect( isPaseoOwnedWorktreeCwd(result.worktreePath, { paseoHome }), - ).resolves.toMatchObject({ allowed: false }); + ).resolves.toMatchObject({ allowed: true, worktreePath: result.worktreePath }); const worktrees = await listPaseoWorktrees({ cwd: repoDir, paseoHome, worktreesRoot }); expect(worktrees.map((entry) => entry.path)).toContain(result.worktreePath); @@ -1380,6 +1381,200 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { }); }); + describe("worktrees at explicit paths", () => { + let tempDir: string; + let repoDir: string; + let paseoHome: string; + + beforeEach(() => { + tempDir = realpathSync(mkdtempSync(join(tmpdir(), "worktree-explicit-test-"))); + repoDir = join(tempDir, "test-repo"); + paseoHome = join(tempDir, "paseo-home"); + + mkdirSync(repoDir, { recursive: true }); + execFileSync("git", ["init", "-b", "main"], { cwd: repoDir }); + execFileSync("git", ["config", "user.email", "test@test.com"], { cwd: repoDir }); + execFileSync("git", ["config", "user.name", "Test"], { cwd: repoDir }); + writeFileSync(join(repoDir, "file.txt"), "hello\n"); + execFileSync("git", ["add", "."], { cwd: repoDir }); + execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "initial"], { + cwd: repoDir, + }); + }); + + afterEach(() => { + rmSync(tempDir, { recursive: true, force: true }); + }); + + it("places, owns, lists, and deletes a worktree outside the legacy root", async () => { + // Sibling layout: /wt- + + const result = await createWorktreePrimitive({ + cwd: repoDir, + worktreeSlug: "sibling-one", + source: { kind: "branch-off", baseBranch: "main", branchName: "feature/sibling" }, + paseoHome, + worktreePath: join(tempDir, "wt-sibling-one"), + }); + + expect(result.worktreePath).toBe(join(tempDir, "wt-sibling-one")); + expect(existsSync(join(result.worktreePath, "file.txt"))).toBe(true); + expect(existsSync(await getPaseoWorktreeMetadataPath(result.worktreePath))).toBe(true); + + const ownership = await isPaseoOwnedWorktreeCwd(result.worktreePath, { paseoHome }); + expect(ownership.allowed).toBe(true); + expect(ownership.worktreePath).toBe(result.worktreePath); + // A subdirectory of the worktree resolves to the worktree root. + mkdirSync(join(result.worktreePath, "sub"), { recursive: true }); + const nested = await isPaseoOwnedWorktreeCwd(join(result.worktreePath, "sub"), { + paseoHome, + }); + expect(nested.worktreePath).toBe(result.worktreePath); + + const listed = await listPaseoWorktrees({ cwd: repoDir, paseoHome }); + expect(listed.map((entry) => entry.path)).toContain(result.worktreePath); + + await deletePaseoWorktree({ cwd: repoDir, worktreePath: result.worktreePath, paseoHome }); + expect(existsSync(result.worktreePath)).toBe(false); + }); + + it("removes branches fetched by the source plan when git worktree add fails", async () => { + // A branch that exists only on the remote: resolving a + // checkout-branch plan fetches it into a local branch. A script + // failure must not leave that branch behind, or the next attempt + // would uniquify to a different branch name. + const remoteDir = join(tempDir, "remote.git"); + execFileSync("git", ["clone", "--bare", repoDir, remoteDir], { cwd: tempDir }); + execFileSync("git", ["remote", "add", "origin", remoteDir], { cwd: repoDir }); + execFileSync("git", ["push", "origin", "main"], { cwd: repoDir }); + execFileSync("git", ["branch", "feature/remote-check"], { cwd: repoDir }); + execFileSync("git", ["push", "origin", "feature/remote-check"], { cwd: repoDir }); + execFileSync("git", ["branch", "-D", "feature/remote-check"], { cwd: repoDir }); + execFileSync("git", ["fetch", "origin"], { cwd: repoDir }); + + mkdirSync(join(tempDir, "occupied")); + writeFileSync(join(tempDir, "occupied", "keep"), "keep"); + await expect( + createWorktreePrimitive({ + cwd: repoDir, + worktreeSlug: "remote-check", + source: { kind: "checkout-branch", branchName: "feature/remote-check" }, + paseoHome, + worktreePath: join(tempDir, "occupied"), + }), + ).rejects.toThrow(); + + const localBranches = execFileSync("git", ["branch", "--list", "feature/remote-check"], { + cwd: repoDir, + encoding: "utf8", + }); + expect(localBranches.trim()).toBe(""); + }); + + it("deletes only the registered destination nested beneath the legacy root", async () => { + const parent = join(paseoHome, "worktrees", "acme", "widgets"); + const worktreePath = join(parent, "topic"); + const siblingPath = join(parent, "sibling"); + await createWorktreePrimitive({ + cwd: repoDir, + paseoHome, + worktreeSlug: "topic", + worktreePath, + source: { kind: "branch-off", branchName: "topic", baseBranch: "main" }, + }); + await createWorktreePrimitive({ + cwd: repoDir, + paseoHome, + worktreeSlug: "sibling", + worktreePath: siblingPath, + source: { kind: "branch-off", branchName: "sibling", baseBranch: "main" }, + }); + mkdirSync(join(worktreePath, "nested")); + expect( + await isPaseoOwnedWorktreeCwd(join(worktreePath, "nested"), { paseoHome }), + ).toMatchObject({ allowed: true, worktreePath }); + await deletePaseoWorktree({ cwd: repoDir, paseoHome, worktreePath, registryProven: true }); + expect(existsSync(worktreePath)).toBe(false); + expect(readFileSync(join(siblingPath, "file.txt"), "utf8")).toBe("hello\n"); + }); + + it("rejects a destination under a symlink into .git", async () => { + const alias = join(tempDir, "git-alias"); + symlinkSync(join(repoDir, ".git"), alias, "dir"); + await expect( + validateWorktreePath({ candidate: join(alias, "new", "worktree"), repoPath: repoDir }), + ).rejects.toThrow("inside a .git directory"); + expect(existsSync(join(repoDir, ".git", "new"))).toBe(false); + }); + + it("uses an explicit worktreePath verbatim", async () => { + const explicitPath = join(tempDir, "explicit-wt"); + + const result = await createWorktreePrimitive({ + cwd: repoDir, + worktreeSlug: "explicit-one", + source: { kind: "branch-off", baseBranch: "main", branchName: "feature/explicit" }, + paseoHome, + worktreePath: explicitPath, + }); + + expect(result.worktreePath).toBe(explicitPath); + expect(existsSync(join(explicitPath, "file.txt"))).toBe(true); + }); + + it("restore recreates at the recorded path", async () => { + const created = await createWorktreePrimitive({ + cwd: repoDir, + worktreeSlug: "restorable", + source: { kind: "branch-off", baseBranch: "main", branchName: "feature/restorable" }, + paseoHome, + worktreePath: join(tempDir, "wt-sibling-one"), + }); + await deletePaseoWorktree({ cwd: repoDir, worktreePath: created.worktreePath, paseoHome }); + expect(existsSync(created.worktreePath)).toBe(false); + + const restored = await createWorktreePrimitive({ + cwd: repoDir, + worktreeSlug: "restorable", + source: { kind: "restore", branchName: "feature/restorable", baseRef: "main" }, + paseoHome, + worktreePath: created.worktreePath, + }); + + expect(restored.worktreePath).toBe(created.worktreePath); + expect(existsSync(join(restored.worktreePath, "file.txt"))).toBe(true); + }); + + it("does not treat a copied marker in a non-worktree directory as ownership", async () => { + const created = await createWorktreePrimitive({ + cwd: repoDir, + worktreeSlug: "marker-source", + source: { kind: "branch-off", baseBranch: "main", branchName: "feature/marker" }, + paseoHome, + worktreePath: join(tempDir, "wt-sibling-one"), + }); + const metadata = await readPaseoWorktreeMetadata(created.worktreePath); + expect(metadata).not.toBeNull(); + + // A plain directory with a .git file pointing at a copied admin dir + // that holds a paseo/worktree.json. Git does not list it as a + // worktree, so the copied marker must not prove ownership. + const fakeDir = join(tempDir, "fake-worktree"); + const fakeAdmin = join(tempDir, "fake-admin"); + mkdirSync(join(fakeAdmin, "paseo"), { recursive: true }); + mkdirSync(fakeDir, { recursive: true }); + writeFileSync(join(fakeAdmin, "paseo", "worktree.json"), JSON.stringify(metadata)); + writeFileSync(join(fakeDir, ".git"), `gitdir: ${fakeAdmin}\n`); + + const ownership = await isPaseoOwnedWorktreeCwd(fakeDir, { paseoHome }); + expect(ownership.allowed).toBe(false); + await expect( + deletePaseoWorktree({ cwd: repoDir, worktreePath: fakeDir, paseoHome }), + ).rejects.toThrow("Refusing to delete non-Paseo worktree"); + expect(existsSync(fakeDir)).toBe(true); + }); + }); + describe("paseo worktree manager", () => { let tempDir: string; let repoDir: string; diff --git a/packages/server/src/utils/worktree.test.ts b/packages/server/src/utils/worktree.test.ts index 605e2b8c20..f549b461f8 100644 --- a/packages/server/src/utils/worktree.test.ts +++ b/packages/server/src/utils/worktree.test.ts @@ -302,6 +302,22 @@ describe("paseo worktree manager", () => { expect(existsSync(created.worktreePath)).toBe(false); }); + it("deletes a worktree when Git reports its source through native and long path spellings", async () => { + const created = await createLegacyWorktreeForTest({ + branchName: "identity-delete", + cwd: repoDir, + baseBranch: "main", + worktreeSlug: "identity-delete", + paseoHome, + }); + await deletePaseoWorktree({ + cwd: realpathSync.native(repoDir), + worktreePath: created.worktreePath, + paseoHome, + }); + expect(existsSync(created.worktreePath)).toBe(false); + }); + it("is idempotent: deleting an already-absent worktree succeeds", async () => { const created = await createLegacyWorktreeForTest({ branchName: "idempotent-delete-branch", diff --git a/packages/server/src/utils/worktree.ts b/packages/server/src/utils/worktree.ts index 3ddc71b472..2fc8bc05db 100644 --- a/packages/server/src/utils/worktree.ts +++ b/packages/server/src/utils/worktree.ts @@ -24,6 +24,8 @@ export { import { type PaseoConfig } from "@getpaseo/protocol/paseo-config-schema"; import { createPaseoWorktreeChangeRequestHint, + hasPaseoWorktreeMetadata, + findPaseoWorktreeRootForCwd, normalizeBaseRefName, isQualifiedRef, type PaseoWorktreeChangeRequestHint, @@ -218,6 +220,7 @@ export interface CreateWorktreeOptions { source: WorktreeSource; paseoHome?: string; worktreesRoot?: string; + worktreePath?: string; } export class BranchAlreadyCheckedOutError extends Error { @@ -964,6 +967,24 @@ export async function isPaseoOwnedWorktreeCwd( } } + // Worktrees placed at plugin-chosen paths are + // proven by the marker createWorktree writes unconditionally: a + // paseo/worktree.json in the worktree's git admin dir, with the path + // still registered in the repo's `git worktree list`. The marker alone + // is not proof — it lives in a git admin dir a user can copy into a + // hand-made directory that git does not know about. + if (options?.knownGitCommonDir !== null) { + const metadataProof = await resolveMetadataOwnedWorktree(cwd, repoRoot); + if (metadataProof) { + return { + allowed: true, + ...(repoRoot !== undefined ? { repoRoot } : {}), + worktreeRoot: metadataProof.worktreeRoot, + worktreePath: metadataProof.worktreePath, + }; + } + } + const worktreesBaseRoot = resolvePaseoWorktreesBaseRoot(options); const relativePath = await getOwnershipRelativePath(worktreesBaseRoot, resolvedCwd); @@ -971,32 +992,51 @@ export async function isPaseoOwnedWorktreeCwd( // The / prefix is Paseo-private — nothing else writes there — so the // path shape alone is sufficient proof of ownership, even when git has already // forgotten about the worktree. - if (relativePath === null) { - return { - allowed: false, - ...(repoRoot !== undefined ? { repoRoot } : {}), - worktreePath: resolvedCwd, - }; + if (relativePath !== null) { + const parts = relativePath.split(sep).filter((part) => part.length > 0); + if (parts.length >= 2) { + const worktreesRoot = join(worktreesBaseRoot, parts[0]); + return { + allowed: true, + ...(repoRoot !== undefined ? { repoRoot } : {}), + worktreeRoot: worktreesRoot, + worktreePath: join(worktreesRoot, parts[1]), + }; + } } - const parts = relativePath.split(sep).filter((part) => part.length > 0); - if (parts.length < 2) { - return { - allowed: false, - ...(repoRoot !== undefined ? { repoRoot } : {}), - worktreePath: resolvedCwd, - }; - } - - const worktreesRoot = join(worktreesBaseRoot, parts[0]); return { - allowed: true, + allowed: false, ...(repoRoot !== undefined ? { repoRoot } : {}), - worktreeRoot: worktreesRoot, - worktreePath: join(worktreesRoot, parts[1]), + worktreePath: resolvedCwd, }; } +async function resolveMetadataOwnedWorktree( + cwd: string, + repoRoot: string | undefined, +): Promise<{ worktreePath: string; worktreeRoot: string } | null> { + try { + const root = await findPaseoWorktreeRootForCwd(cwd); + if (!root) return null; + const candidate = await normalizePathForOwnership(root); + if (repoRoot !== undefined && candidate === (await normalizePathForOwnership(repoRoot))) + return null; + const { stdout: listOutput } = await runGitCommand(["worktree", "list", "--porcelain"], { + cwd: candidate, + envOverlay: READ_ONLY_GIT_ENV, + }); + for (const entry of parseWorktreeList(listOutput)) { + if ((await normalizePathForOwnership(entry.path)) === candidate) { + return { worktreePath: candidate, worktreeRoot: dirname(candidate) }; + } + } + return null; + } catch { + return null; + } +} + type ParsedPaseoWorktreeInfo = Omit; function parseWorktreeList(output: string): ParsedPaseoWorktreeInfo[] { @@ -1063,12 +1103,17 @@ export async function listPaseoWorktrees({ envOverlay: READ_ONLY_GIT_ENV, }); + const mainCheckoutPath = await resolveRepoRootFromGitCommonDir(await getGitCommonDir(cwd)); const roots = await ownershipPathVariants(projectWorktreesRoot); const worktrees: PaseoWorktreeInfo[] = []; // Inspect foreign paths sequentially; a large worktree list must not consume the FS pool. for (const entry of parseWorktreeList(stdout)) { const path = await normalizePathForOwnership(entry.path); - if (!roots.some((root) => getRelativePathInsideRoot(root, path) !== null)) continue; + if ( + !roots.some((root) => getRelativePathInsideRoot(root, path) !== null) && + !(path !== mainCheckoutPath && (await hasPaseoWorktreeMetadata(path))) + ) + continue; worktrees.push({ ...entry, path, createdAt: await resolveWorktreeCreatedAtIso(path) }); } return worktrees; @@ -1082,6 +1127,30 @@ export interface DeletePaseoWorktreeOptions { worktreesRoot?: string; paseoHome?: string; worktreesBaseRoot?: string; + // The caller has a workspace registry record backing worktreePath (the + // record's cwd is this path). Registry membership is an ownership proof + // in its own right: it covers worktrees whose git admin dir is already + // gone, where the marker proof can no longer be verified. Only pass + // this when the record was matched against the path by the caller. + registryProven?: boolean; +} + +// Project scoping for delete: a proof for some other repo's worktree must +// not make this repo's delete remove it. Only refuses on a positive +// mismatch — when git has forgotten either side, the ownership proof the +// caller already established stands. +async function assertWorktreeBelongsToRepo(cwd: string, worktreePath: string): Promise { + let callerRepoRoot: string; + let targetRepoRoot: string; + try { + callerRepoRoot = await resolveRepoRootFromGitCommonDir(await getGitCommonDir(cwd)); + targetRepoRoot = await resolveRepoRootFromGitCommonDir(await getGitCommonDir(worktreePath)); + } catch { + return; + } + if ((await getOwnershipRelativePath(callerRepoRoot, targetRepoRoot)) !== "") { + throw new Error("Refusing to delete non-Paseo worktree"); + } } export async function deletePaseoWorktree({ @@ -1092,6 +1161,7 @@ export async function deletePaseoWorktree({ worktreesRoot, paseoHome, worktreesBaseRoot, + registryProven, }: DeletePaseoWorktreeOptions): Promise { if (!worktreePath && !worktreeSlug) { throw new Error("worktreePath or worktreeSlug is required"); @@ -1110,22 +1180,27 @@ export async function deletePaseoWorktree({ } const requestedPath = worktreePath ?? join(resolvedWorktreesRoot, worktreeSlug!); - const resolvedRequested = await normalizePathForOwnership(requestedPath); const ownership = await isPaseoOwnedWorktreeCwd(requestedPath, { paseoHome, worktreesRoot: worktreesBaseRoot, }); - const resolvedWorktree = - ownership.allowed && ownership.worktreePath ? ownership.worktreePath : resolvedRequested; - - const relativeWorktreePath = await getOwnershipRelativePath( - resolvedWorktreesRoot, - resolvedWorktree, - ); - if (relativeWorktreePath === null || relativeWorktreePath === "") { + // Deletion is gated on the ownership proof set (legacy shape, the + // paseo/worktree.json marker verified against `git worktree list`, or a + // caller-asserted registry record), not on living under the per-project + // hashed root: plugin-placed worktrees live anywhere. + let resolvedWorktree: string; + if (registryProven) { + resolvedWorktree = await normalizePathForOwnership(requestedPath); + } else if (ownership.allowed && ownership.worktreePath) { + resolvedWorktree = ownership.worktreePath; + } else { throw new Error("Refusing to delete non-Paseo worktree"); } + if (cwd) { + await assertWorktreeBelongsToRepo(cwd, resolvedWorktree); + } + if (await pathExists(resolvedWorktree)) { for (const teardownCwd of teardownCwds ?? [resolvedWorktree]) { await runWorktreeTeardownCommands({ @@ -1222,6 +1297,67 @@ async function removeDirectoryWithRetries(path: string): Promise { } } +async function listLocalBranchNames(cwd: string): Promise> { + const { stdout } = await runGitCommand( + ["for-each-ref", "--format=%(refname:short)", "refs/heads"], + { cwd }, + ); + return new Set( + stdout + .split("\n") + .map((name) => name.trim()) + .filter((name) => name.length > 0), + ); +} + +// The one local branch a source plan can create while resolving: a +// checkout-branch plan fetches refs/heads/, and a +// change-request/PR plan fetches refs/heads/ (which is +// the plan's branchName). branch-off creates no local branch. Only this +// ref may be rolled back when creation fails — never any other +// branch that appeared in the meantime; other creators own those. +function planCreatedLocalBranch( + source: WorktreeSource, + sourcePlan: WorktreeSourcePlan, +): string | null { + switch (source.kind) { + case "checkout-branch": + return source.branchName; + case "checkout-change-request": + case "checkout-github-pr": + return sourcePlan.branchName; + default: + return null; + } +} + +async function readLocalBranchTip(cwd: string, branchName: string): Promise { + try { + const { stdout } = await runGitCommand( + ["rev-parse", "--verify", `refs/heads/${branchName}^{commit}`], + { cwd }, + ); + const tip = stdout.trim(); + return tip.length > 0 ? tip : null; + } catch { + return null; + } +} + +/** Resolve the default placement once, before presenting it to creation hooks. */ +export async function resolveDefaultWorktreePath( + options: Pick, +): Promise { + const original = join( + await getPaseoWorktreesRoot(options.cwd, options.paseoHome, options.worktreesRoot), + options.worktreeSlug, + ); + let candidate = original; + let suffix = 1; + while (await pathExists(candidate)) candidate = `${original}-${suffix++}`; + return candidate; +} + /** * Create a git worktree with proper naming conventions */ @@ -1231,56 +1367,73 @@ export const createWorktree = async ({ worktreeSlug, paseoHome, worktreesRoot, + worktreePath: explicitWorktreePath, }: CreateWorktreeOptions): Promise => { + const branchesBefore = + source.kind === "checkout-branch" || + source.kind === "checkout-change-request" || + source.kind === "checkout-github-pr" + ? await listLocalBranchNames(cwd) + : new Set(); const sourcePlan = await resolveWorktreeSourcePlan({ cwd, source, desiredSlug: worktreeSlug }); - let worktreePath = join(await getPaseoWorktreesRoot(cwd, paseoHome, worktreesRoot), worktreeSlug); - await mkdir(dirname(worktreePath), { recursive: true }); + const fetchedBranch = planCreatedLocalBranch(source, sourcePlan); + const fetchedTip = + fetchedBranch && !branchesBefore.has(fetchedBranch) + ? await readLocalBranchTip(cwd, fetchedBranch) + : null; + try { + let worktreePath = + explicitWorktreePath ?? + (await resolveDefaultWorktreePath({ cwd, paseoHome, worktreesRoot, worktreeSlug })); + await mkdir(dirname(worktreePath), { recursive: true }); - // Also handle worktree path collision - let finalWorktreePath = worktreePath; - let pathSuffix = 1; - while (await pathExists(finalWorktreePath)) { - finalWorktreePath = `${worktreePath}-${pathSuffix}`; - pathSuffix++; - } - - // Primitive owner for `git worktree add`; callers route through createWorktreeCore. - await runGitCommand(["worktree", "add", finalWorktreePath, ...sourcePlan.addArguments], { - cwd, - timeout: 120_000, - }); - worktreePath = await normalizePathForOwnership(finalWorktreePath); - - if (sourcePlan.pushRemote) { - await configureWorktreePushRemote({ + // Primitive owner for `git worktree add`; callers route through createWorktreeCore. + await runGitCommand(["worktree", "add", worktreePath, ...sourcePlan.addArguments], { cwd, - branchName: sourcePlan.branchName, - remote: sourcePlan.pushRemote, + timeout: 120_000, }); - } - if (sourcePlan.trackingRemote) { - await configureWorktreeTrackingRemote({ - cwd, - branchName: sourcePlan.branchName, - remote: sourcePlan.trackingRemote, + worktreePath = await normalizePathForOwnership(worktreePath); + + if (sourcePlan.pushRemote) { + await configureWorktreePushRemote({ + cwd, + branchName: sourcePlan.branchName, + remote: sourcePlan.pushRemote, + }); + } + if (sourcePlan.trackingRemote) { + await configureWorktreeTrackingRemote({ + cwd, + branchName: sourcePlan.branchName, + remote: sourcePlan.trackingRemote, + }); + } + + await writePaseoWorktreeMetadata(worktreePath, { + baseRefName: sourcePlan.metadataBaseRefName, + ...(sourcePlan.metadataBaseRef ? { baseRef: sourcePlan.metadataBaseRef } : {}), + ...(sourcePlan.changeRequestLookupTarget + ? { changeRequestLookupTarget: sourcePlan.changeRequestLookupTarget } + : {}), }); + + await seedPaseoConfigFile({ sourceCwd: cwd, targetCwd: worktreePath }); + + return { + branchName: sourcePlan.branchName, + worktreePath, + comparisonBaseRef: sourcePlan.metadataBaseRef ?? sourcePlan.metadataBaseRefName, + }; + } catch (error) { + if ( + fetchedBranch && + fetchedTip && + (await readLocalBranchTip(cwd, fetchedBranch)) === fetchedTip + ) { + await runGitCommand(["branch", "-D", fetchedBranch], { cwd }).catch(() => {}); + } + throw error; } - - await writePaseoWorktreeMetadata(worktreePath, { - baseRefName: sourcePlan.metadataBaseRefName, - ...(sourcePlan.metadataBaseRef ? { baseRef: sourcePlan.metadataBaseRef } : {}), - ...(sourcePlan.changeRequestLookupTarget - ? { changeRequestLookupTarget: sourcePlan.changeRequestLookupTarget } - : {}), - }); - - await seedPaseoConfigFile({ sourceCwd: cwd, targetCwd: worktreePath }); - - return { - branchName: sourcePlan.branchName, - worktreePath, - comparisonBaseRef: sourcePlan.metadataBaseRef ?? sourcePlan.metadataBaseRefName, - }; }; interface ResolveWorktreeSourcePlanOptions { diff --git a/packages/website/src/plugin-docs-navigation.test.ts b/packages/website/src/plugin-docs-navigation.test.ts index b6f8e5128f..93f0cf7736 100644 --- a/packages/website/src/plugin-docs-navigation.test.ts +++ b/packages/website/src/plugin-docs-navigation.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { buildDocsNavTree, getDoc, getDocs, getLegacyDocsRedirect } from "./docs"; +import { buildDocsNavTree, getDoc, getDocs, getLegacyDocsRedirect, parseHeadings } from "./docs"; describe("plugin documentation", () => { it("groups current guides by task without version navigation", () => { @@ -20,6 +20,14 @@ describe("plugin documentation", () => { }); }); + it.each(["en", "zh-CN"] as const)("resolves worktree placement hook links in %s", (locale) => { + const hooks = getDoc("plugins/hooks", locale)!; + expect(parseHeadings(hooks.content).map((heading) => heading.id)).toContain( + "worktreecreatebefore", + ); + expect(hooks.content).toContain("plugin-examples/worktree-placement"); + }); + it.each(["v0.7", "v0.8"])("redirects %s links to existing current pages", (version) => { for (const page of ["", "/index", "/reference", "/providers", "/migration"]) { const target = `/docs/plugins${page === "/index" ? "" : page}`; diff --git a/plugin-examples/lifecycle-logger/README.md b/plugin-examples/lifecycle-logger/README.md index d6c00b8032..60259d34c7 100644 --- a/plugin-examples/lifecycle-logger/README.md +++ b/plugin-examples/lifecycle-logger/README.md @@ -1,6 +1,6 @@ # Lifecycle logger -Registers all eleven server lifecycle hooks and logs their data as JSON. It observes agent creation, +Registers agent, workspace, and worktree hooks and logs their data as JSON. It observes agent creation, session opening, turns, permissions, archive, and workspace creation/archive. Before hooks return the request unchanged. Environment values are redacted; prompts and timeline content are logged. diff --git a/plugin-examples/worktree-placement/README.md b/plugin-examples/worktree-placement/README.md new file mode 100644 index 0000000000..8d88d8c627 --- /dev/null +++ b/plugin-examples/worktree-placement/README.md @@ -0,0 +1,36 @@ +# Worktree placement + +Place worktrees next to their source checkout, using the repository directory name and branch. +For `/home/me/src/paseo` on branch `feature/x`, the new worktree is +`/home/me/src/paseo.feature-x`. Slashes in branch names become hyphens. + +Install on Paseo 0.14.0-beta.1 or newer with plugins enabled: + +```bash +paseo plugin install /absolute/path/to/plugin-examples/worktree-placement +``` + +The plugin is one file, `index.server.ts`: + +```ts +import { basename, dirname, join } from "node:path"; +import type { PluginServerContext } from "@getpaseo/plugin/server"; + +export default function contribute(server: PluginServerContext) { + return server.addHook("worktree.create.before", async ({ request }) => ({ + ...request, + path: join( + dirname(request.sourceCheckout), + `${basename(request.sourceCheckout)}.${request.branch.replaceAll("/", "-")}`, + ), + })); +} +``` + +Paseo validates the returned path and refuses an existing one. It creates, lists, restores, +and removes the worktree through the normal workspace workflow. Restoring uses the recorded +path without running the hook. Git can choose a unique branch name after this hook runs; +the path retains the branch name received by the hook. + +See [worktree.create.before](../../public-docs/plugins/hooks.md#worktreecreatebefore) +for the request fields and validation rules. diff --git a/plugin-examples/worktree-placement/index.server.ts b/plugin-examples/worktree-placement/index.server.ts new file mode 100644 index 0000000000..67509a000d --- /dev/null +++ b/plugin-examples/worktree-placement/index.server.ts @@ -0,0 +1,12 @@ +import { basename, dirname, join } from "node:path"; +import type { PluginServerContext } from "@getpaseo/plugin/server"; + +export default function contribute(server: PluginServerContext) { + return server.addHook("worktree.create.before", async ({ request }) => ({ + ...request, + path: join( + dirname(request.sourceCheckout), + `${basename(request.sourceCheckout)}.${request.branch.replaceAll("/", "-")}`, + ), + })); +} diff --git a/plugin-examples/worktree-placement/paseo-plugin.json b/plugin-examples/worktree-placement/paseo-plugin.json new file mode 100644 index 0000000000..ab7f7a20e6 --- /dev/null +++ b/plugin-examples/worktree-placement/paseo-plugin.json @@ -0,0 +1,4 @@ +{ + "id": "worktree-placement", + "requirements": { "paseo": ">=0.14.0-beta.1" } +} diff --git a/public-docs/plugins/hooks.md b/public-docs/plugins/hooks.md index 8d3fae125b..b535821e62 100644 --- a/public-docs/plugins/hooks.md +++ b/public-docs/plugins/hooks.md @@ -54,6 +54,7 @@ Paseo only sees the returned promise, so detached work gets no error reporting a | `workspace.create.before` | yes | `{ request }` | Entire create request | | `workspace.create.after` | no | `{ workspace }` | | | `workspace.archive.after` | no | `{ workspace }` | | +| `worktree.create.before` | yes | `{ request }` | Creation options and destination | | `worktree.create.after` | yes | `{ worktree }` | Files in the worktree; throw to abort creation | | `agent.create.before` | yes | `{ request: { config, env? } }` | Saved config except `cwd`; `env` | | `agent.create.after` | no | `{ agent }` | | @@ -145,6 +146,46 @@ server.addHook("workspace.archive.after", async ({ workspace }) => { }); ``` +## worktree.create.before {#worktreecreatebefore} + +Choose the location and creation options for a new worktree. Paseo awaits this hook before `git worktree add`, on creation from the app, CLI, MCP, and agent creation. Receives `{ request }`; return a complete replacement request or `undefined` to keep it. Throwing, invalid returned data, or a 30-second timeout aborts creation with the plugin and hook named in the error. + +```ts +import { basename, dirname, join } from "node:path"; + +server.addHook("worktree.create.before", async ({ request }) => ({ + ...request, + path: join( + dirname(request.sourceCheckout), + `${basename(request.sourceCheckout)}.${request.branch.replaceAll("/", "-")}`, + ), +})); +``` + +For source `/home/me/src/paseo` and branch `feature/x`, this creates `/home/me/src/paseo.feature-x`. See the complete [worktree-placement example](https://github.com/getpaseo/paseo/tree/main/plugin-examples/worktree-placement). + +| Request field | Meaning | +| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | +| `kind` | `branch-off`, `checkout-branch`, `checkout-change-request`, or `checkout-github-pr` | +| `branch` | Requested local branch name | +| `baseRef` | Starting ref for branch-off; comparison base for change requests; absent for `checkout-branch`. To branch off a ref, return `kind: "branch-off"`. | +| `slug` | Normalized worktree name | +| `path` | Absolute destination; initially the default location with any existing-path suffix resolved | +| `repoRoot` | Read-only main repository root | +| `sourceCheckout` | Read-only source checkout root, including when creation starts from another worktree | +| `forge`, `changeRequestNumber`, `headRef` | Change-request checkout identity; GitHub legacy checkouts use `githubPrNumber` instead of `forge` and `changeRequestNumber` | +| `headRepositoryOwner`, `headRepository` | Optional source repository facts; `headRepository` is present only on change-request checkouts | +| `checkoutRefs` | Optional fetch sources: `{ remoteName?: string, remoteRef: string }[]` | +| `pushRemoteUrl`, `trackOriginHead` | Optional push destination and tracking policy | + +Once `path` is returned, `slug` only feeds branch-off naming; the CLI looks up worktrees by the basename of their path. + +Every field except `repoRoot` and `sourceCheckout` is transformable. Return all required facts for the chosen `kind`. Paseo resolves the Git source plan after this hook, so handlers can change the branch and base before fetching refs, while Git can still choose a unique final branch name afterward. + +Paseo resolves symlinked parents and validates the returned path. It must be absolute, must not exist, and must not be the filesystem root, your home directory, the repository root, inside a `.git` directory, or an ancestor of the repository. An existing destination fails creation; Paseo never adds a suffix to a plugin-chosen path. The plugin must leave directory creation to Paseo. + +Ordering: `worktree.create.before` → `git worktree add` → `worktree.create.after` → workspace registration. Restoring a missing worktree recreates it at its recorded path without running either worktree creation hook. + ## worktree.create.after Paseo waits for this hook after a new git worktree exists and before workspace registration, setup, terminals, or agents. Receives `{ worktree: { path, branch, sourceCheckout } }`: the absolute worktree path, branch name, and source checkout directory. There is no workspace id yet. Return nothing; write files directly into the worktree. Throwing or exceeding 30 seconds aborts creation and removes the new worktree. @@ -589,12 +630,12 @@ replaces that scope's prior value. ## Complete examples -| Plugin | Includes | -| ------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------- | -| [lifecycle-logger](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-logger) | All thirteen hooks; JSON logs with environment values redacted | -| [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | Follow-ups, permissions, environment, provider switching, worktree selection | -| [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | MCP injection and Codex sandbox/approval options | -| [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | Label-targeted tools and file operations in the plugin process | +| Plugin | Includes | +| ------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------- | +| [lifecycle-logger](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-logger) | Agent, workspace, and worktree hooks; JSON logs with environment values redacted | +| [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | Follow-ups, permissions, environment, provider switching, worktree selection | +| [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | MCP injection and Codex sandbox/approval options | +| [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | Label-targeted tools and file operations in the plugin process | Read logger output with `paseo plugin logs lifecycle-logger` or the host's `daemon.log`. diff --git a/public-docs/plugins/hooks.zh-CN.md b/public-docs/plugins/hooks.zh-CN.md index c4465e3008..eecf370a29 100644 --- a/public-docs/plugins/hooks.zh-CN.md +++ b/public-docs/plugins/hooks.zh-CN.md @@ -52,6 +52,7 @@ Paseo 只观察返回的 Promise,因此独立任务没有错误报告,也没 | `workspace.create.before` | 是 | `{ request }` | 整个创建请求 | | `workspace.create.after` | 否 | `{ workspace }` | | | `workspace.archive.after` | 否 | `{ workspace }` | | +| `worktree.create.before` | 是 | `{ request }` | 创建选项和目标路径 | | `worktree.create.after` | 是 | `{ worktree }` | worktree 中的文件;抛出错误中止创建 | | `agent.create.before` | 是 | `{ request: { config, env? } }` | 除 `cwd` 外的已保存配置;`env` | | `agent.create.after` | 否 | `{ agent }` | | @@ -142,6 +143,46 @@ server.addHook("workspace.archive.after", async ({ workspace }) => { }); ``` +## worktree.create.before {#worktreecreatebefore} + +为新 worktree 选择路径和创建选项。通过应用、CLI、MCP 或创建 Agent 新建 worktree 时,Paseo 在 `git worktree add` 之前等待此钩子。钩子收到 `{ request }`,返回完整的替换请求,或返回 `undefined` 保持原值。抛出错误、返回无效数据或超过 30 秒会终止创建,错误包含插件和钩子名称。 + +```ts +import { basename, dirname, join } from "node:path"; + +server.addHook("worktree.create.before", async ({ request }) => ({ + ...request, + path: join( + dirname(request.sourceCheckout), + `${basename(request.sourceCheckout)}.${request.branch.replaceAll("/", "-")}`, + ), +})); +``` + +源检出目录为 `/home/me/src/paseo`、分支为 `feature/x` 时,目标为 `/home/me/src/paseo.feature-x`。完整插件见 [worktree-placement 示例](https://github.com/getpaseo/paseo/tree/main/plugin-examples/worktree-placement)。 + +| 请求字段 | 含义 | +| ----------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | +| `kind` | `branch-off`、`checkout-branch`、`checkout-change-request` 或 `checkout-github-pr` | +| `branch` | 请求的本地分支名称 | +| `baseRef` | branch-off 的起始引用;变更请求的比较基准;`checkout-branch` 不含此字段。要从引用创建分支,返回 `kind: "branch-off"`。 | +| `slug` | 规范化的 worktree 名称 | +| `path` | 绝对目标路径,初始值为已处理现有路径后缀的默认位置 | +| `repoRoot` | 只读,主仓库根目录 | +| `sourceCheckout` | 只读,源检出根目录,也支持从另一个 worktree 发起创建 | +| `forge`、`changeRequestNumber`、`headRef` | 变更请求检出标识;旧版 GitHub 检出用 `githubPrNumber` 代替 `forge` 和 `changeRequestNumber` | +| `headRepositoryOwner`、`headRepository` | 可选的源仓库信息;`headRepository` 仅用于变更请求检出 | +| `checkoutRefs` | 可选的获取源:`{ remoteName?: string, remoteRef: string }[]` | +| `pushRemoteUrl`、`trackOriginHead` | 可选的推送目标和跟踪策略 | + +返回 `path` 后,`slug` 仅用于 branch-off 分支命名;CLI 使用路径的最后一级目录名查找 worktree。 + +除 `repoRoot` 和 `sourceCheckout` 外,所有字段都可以修改。返回所选 `kind` 的全部必填字段。Paseo 在钩子之后解析 Git 源计划,因此钩子可以在获取引用之前修改分支和基准,而 Git 之后仍可能选择唯一的最终分支名称。 + +Paseo 解析父目录中的符号链接并验证返回的路径。路径必须为绝对路径且不存在,不能是文件系统根目录、用户主目录、仓库根目录、`.git` 目录内的路径或仓库的祖先目录。目标已存在时创建失败,Paseo 不会为插件选择的路径添加后缀。插件应让 Paseo 创建目录。 + +顺序:`worktree.create.before` → `git worktree add` → `worktree.create.after` → 注册工作区。恢复缺失的 worktree 时使用记录的原路径,不运行这两个创建钩子。 + ## worktree.create.after {#worktreecreateafter} 新的 git worktree 在磁盘上创建后,Paseo 会等待此钩子,然后才注册工作区、运行 setup、打开终端或启动 Agent。收到 `{ worktree: { path, branch, sourceCheckout } }`,分别是 worktree 绝对路径、分支名、来源 checkout 目录。此时还没有工作区 id。无需返回数据,直接写入 worktree 即可。抛出错误或超过 30 秒会中止创建并删除新 worktree。 @@ -571,12 +612,12 @@ Creation request ## 完整示例 {#complete-examples} -| 插件 | 包含 | -| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------ | -| [lifecycle-logger](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-logger) | 全部十三个钩子;隐去环境变量值的 JSON 日志 | -| [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | 后续消息、权限、环境变量、切换 Provider、选择 worktree | -| [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | MCP 注入以及 Codex 沙盒/批准选项 | -| [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | 按标签选择 Agent,并在插件进程中执行文件操作的工具 | +| 插件 | 包含 | +| ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------- | +| [lifecycle-logger](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-logger) | Agent、工作区和 worktree 钩子;隐去环境变量值的 JSON 日志 | +| [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | 后续消息、权限、环境变量、切换 Provider、选择 worktree | +| [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | MCP 注入以及 Codex 沙盒/批准选项 | +| [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | 按标签选择 Agent,并在插件进程中执行文件操作的工具 | 用 `paseo plugin logs lifecycle-logger` 或主机的 `daemon.log` 读取 logger 的输出。 diff --git a/public-docs/worktrees.md b/public-docs/worktrees.md index 7fcef41519..baaea2e177 100644 --- a/public-docs/worktrees.md +++ b/public-docs/worktrees.md @@ -35,6 +35,8 @@ With a custom root, Paseo keeps the same hashed layout under that directory: } ``` +Plugins can choose a location anywhere on disk with [`worktree.create.before`](/docs/plugins/hooks#worktreecreatebefore). The [worktree-placement example](https://github.com/getpaseo/paseo/tree/main/plugin-examples/worktree-placement) places worktrees next to the source checkout. Paseo validates the path, refuses an existing destination, and manages listing, archive, and deletion there. Recovery uses the recorded path without running creation hooks. + 1. Create a workspace with worktree isolation, Paseo creates the worktree and runs your setup hooks 2. Launch one or more agents in that workspace 3. Review the diff against the base branch diff --git a/public-docs/worktrees.zh-CN.md b/public-docs/worktrees.zh-CN.md index 7ec91da189..e84d0a8a25 100644 --- a/public-docs/worktrees.zh-CN.md +++ b/public-docs/worktrees.zh-CN.md @@ -33,6 +33,8 @@ worktree 默认存放在 `$PASEO_HOME/worktrees/` 下,按源检出路径的哈 } ``` +插件可以通过 [`worktree.create.before`](/docs/plugins/hooks#worktreecreatebefore) 将 worktree 放到磁盘上的自选位置。[worktree-placement 示例](https://github.com/getpaseo/paseo/tree/main/plugin-examples/worktree-placement) 将其放在源检出目录旁边。Paseo 验证路径并拒绝已存在的目标,同时支持在该位置列出、归档和删除 worktree。恢复时使用记录的原路径,不运行创建钩子。 + 1. 创建一个使用 worktree 隔离的工作区,Paseo 会创建 worktree 并运行你的 setup 钩子 2. 在该工作区中启动一个或多个 Agent 3. 对照基础分支审查 diff From 8537709e72daa6c0dfaae5596ef5d17645f053e5 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Wed, 28 Oct 2026 12:57:33 +0000 Subject: [PATCH 090/173] test(server): reduce npm fixture setup in the Windows timeout case (#8106) * test(server): batch npm fixture packing to reduce Windows setup time * test(server): describe the batched npm fixture setup budget --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../src/server/plugins/index.posix.test.ts | 4 ++-- scripts/test-support/npm-registry.mts | 17 ++++++++++++----- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/packages/server/src/server/plugins/index.posix.test.ts b/packages/server/src/server/plugins/index.posix.test.ts index 17f25fce3b..4fdc8c3eb4 100644 --- a/packages/server/src/server/plugins/index.posix.test.ts +++ b/packages/server/src/server/plugins/index.posix.test.ts @@ -1323,8 +1323,8 @@ export default function contribute(plugin: unknown) { describe("npm plugin installation", () => { let registry: Awaited>; - // Packing the registry starts eleven real npm processes. Give fixture construction its - // own setup budget so Windows process startup does not consume the installation journey. + // Give real npm fixture construction its own setup budget so it does not consume + // the installation journey on Windows. beforeAll(async () => { const packages = npmPluginPackages(); const fixture = packages[1]; diff --git a/scripts/test-support/npm-registry.mts b/scripts/test-support/npm-registry.mts index a0a39e27d9..5640487049 100644 --- a/scripts/test-support/npm-registry.mts +++ b/scripts/test-support/npm-registry.mts @@ -50,6 +50,7 @@ export async function startNpmRegistry(packages: FixturePackage[]) { `registry=${url}/\n//127.0.0.1:${address.port}/:_authToken=fixture-token\ncache=${root}/cache\n`, ); try { + const prepared = []; for (const [index, pkg] of packages.entries()) { const directory = path.join(root, String(index)); await mkdir(directory); @@ -65,11 +66,17 @@ export async function startNpmRegistry(packages: FixturePackage[]) { await mkdir(path.dirname(path.join(directory, file)), { recursive: true }); await writeFile(path.join(directory, file), content); } - const { stdout } = await execCommand("npm", ["pack", "--ignore-scripts", "--json"], { - cwd: directory, - }); - const packed: Array<{ filename: string }> = JSON.parse(stdout); - const artifact = await readFile(path.join(directory, packed[0].filename)); + prepared.push({ directory, manifest, pkg, index }); + } + // Pack all fixtures in one npm process instead of paying startup once per package. + const { stdout } = await execCommand( + "npm", + ["pack", "--ignore-scripts", "--json", ...prepared.map(({ directory }) => directory)], + { cwd: root }, + ); + const packed: Array<{ filename: string }> = JSON.parse(stdout); + for (const { manifest, pkg, index } of prepared) { + const artifact = await readFile(path.join(root, packed[index].filename)); const artifactPath = `/artifacts/${index}.tgz`; artifacts.set(artifactPath, artifact); const published = { From 33faacc0556e71dd0604413953385d497698cc4d Mon Sep 17 00:00:00 2001 From: suntianc <53503872+suntianc@users.noreply.github.com> Date: Wed, 28 Oct 2026 21:14:12 +0800 Subject: [PATCH 091/173] fix(server): release retained plugin streaming snapshots (#7675) Release cumulative plugin snapshots after adapter attachment and retain canonical replay items. Preserve Unicode text, root/child ordering and current tool state; release history on close. Co-authored-by: suntianc --- docs/timeline-sync.md | 5 + .../src/server/agent/plugin-provider.test.ts | 110 +++++++++++ .../src/server/agent/plugin-provider.ts | 87 ++++++--- .../server/agent/plugin-session-history.ts | 66 +++++++ .../agent/test-utils/plugin-stream-memory.ts | 176 ++++++++++++++++++ .../src/server/agent/timeline-projection.ts | 3 +- 6 files changed, 423 insertions(+), 24 deletions(-) create mode 100644 packages/server/src/server/agent/plugin-session-history.ts create mode 100644 packages/server/src/server/agent/test-utils/plugin-stream-memory.ts diff --git a/docs/timeline-sync.md b/docs/timeline-sync.md index 812718be58..f205d78924 100644 --- a/docs/timeline-sync.md +++ b/docs/timeline-sync.md @@ -10,6 +10,11 @@ then replaces the previous tool state or merges into the current text item. Inte are never retained for history or catch-up. Provider history is the durable transcript authority and rebuilds the projection when an agent resumes. +Pagination bounds each read, not total resident history. Active and idle agents retain their +projected transcript; archive releases it and later history reads rebuild it from the provider. +Streaming overhead must remain proportional to the retained transcript. Cumulative text snapshots +must be released after their deltas have been consumed. + The invariants are: > A continuously subscribed client applies every committed row in order. Opening or resuming an diff --git a/packages/server/src/server/agent/plugin-provider.test.ts b/packages/server/src/server/agent/plugin-provider.test.ts index 6a61573b6b..101a19a39f 100644 --- a/packages/server/src/server/agent/plugin-provider.test.ts +++ b/packages/server/src/server/agent/plugin-provider.test.ts @@ -4,6 +4,8 @@ import { join } from "node:path"; import { AgentStorage } from "./agent-storage.js"; import { createIdleRuntimeCleanup } from "./idle-runtime-cleanup/index.js"; import { relative } from "node:path"; +import { execFileSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; import type { ProviderConnection, ProviderLaunch, @@ -25,6 +27,21 @@ import { StaleProviderSessionError, } from "./stale-provider-session-error.js"; +test("long concurrent plugin and child streams retain text-sized history and release it on archive", () => { + const fixture = fileURLToPath(new URL("./test-utils/plugin-stream-memory.ts", import.meta.url)); + const output = execFileSync( + process.execPath, + ["--expose-gc", "--max-old-space-size=512", "--import", "tsx", fixture], + { + encoding: "utf8", + timeout: 20_000, + }, + ); + const memory = JSON.parse(output) as { retained: number; closed: number }; + expect(memory.retained).toBeLessThan(24 * 1024 * 1024); + expect(memory.closed).toBeLessThan(6 * 1024 * 1024); +}); + const CAPABILITIES = [ "prompt.message", "session.configure", @@ -292,6 +309,99 @@ function expectNestedChildren(events: AgentStreamEvent[]) { } describe("PluginAgentClientRegistry", () => { + test("history keeps the tool's first position when completion follows later text", async () => { + const harness = createProviderHarness(); + const registry = new PluginAgentClientRegistry(createTestLogger()); + registry.replace([harness.registration]); + const client = registry.clients()[harness.registration.id]!; + const session = await client.createSession({ provider: client.provider, cwd: "/tmp" }); + const opened = harness.inputs.find((input) => input.type === "session.open"); + if (opened?.type !== "session.open") throw new Error("missing session open"); + const tool = { + type: "tool_call" as const, + id: "tool-position", + callId: "call-position", + name: "read", + detail: { type: "unknown" as const, input: null, output: null }, + error: null, + }; + try { + harness.emit({ + type: "timeline.item", + sessionId: opened.sessionId, + item: { ...tool, status: "running" }, + }); + harness.emit({ + type: "timeline.item", + sessionId: opened.sessionId, + item: { type: "assistant_message", id: "later-text", text: "Working" }, + }); + harness.emit({ + type: "timeline.item", + sessionId: opened.sessionId, + item: { ...tool, status: "completed" }, + }); + const items = []; + for await (const event of session.streamHistory()) + if (event.type === "timeline") items.push(event.item); + expect(items).toEqual([ + { + type: "tool_call", + callId: "call-position", + name: "read", + detail: tool.detail, + error: null, + status: "completed", + }, + { type: "assistant_message", messageId: "later-text", text: "Working" }, + ]); + } finally { + await session.close(); + await registry.shutdown(); + } + }); + + test("detached text deltas preserve split surrogates and history replays one complete message", async () => { + const harness = createProviderHarness(); + const registry = new PluginAgentClientRegistry(createTestLogger()); + registry.replace([harness.registration]); + const client = registry.clients()[harness.registration.id]!; + const session = await client.createSession({ provider: client.provider, cwd: "/tmp" }); + const opened = harness.inputs.find((input) => input.type === "session.open"); + if (opened?.type !== "session.open") throw new Error("missing session open"); + const events: AgentStreamEvent[] = []; + session.subscribe((event) => events.push(event)); + const prefix = "long prefix ".repeat(10); + const first = prefix + "a\uD83D"; + const complete = first + "\uDE00b"; + try { + for (const text of [first, complete, complete]) { + harness.emit({ + type: "timeline.item", + sessionId: opened.sessionId, + item: { type: "assistant_message", id: "split-message", text }, + }); + } + const deltas = events.flatMap((event) => + event.type === "timeline" && event.item.type === "assistant_message" + ? [event.item.text] + : [], + ); + expect(deltas).toEqual([first, "\uDE00b"]); + expect(deltas.join("")).toBe(prefix + "a😀b"); + const history: AgentStreamEvent[] = []; + for await (const event of session.streamHistory()) history.push(event); + expect( + history.flatMap((event) => + event.type === "timeline" && event.item.type === "assistant_message" ? [event.item] : [], + ), + ).toEqual([{ type: "assistant_message", messageId: "split-message", text: complete }]); + } finally { + await session.close(); + await registry.shutdown(); + } + }); + test("stores only agent options while the plugin receives merged defaults", async () => { const logger = createTestLogger(); const harness = createProviderHarness(); diff --git a/packages/server/src/server/agent/plugin-provider.ts b/packages/server/src/server/agent/plugin-provider.ts index 3970715a55..f09f6349b0 100644 --- a/packages/server/src/server/agent/plugin-provider.ts +++ b/packages/server/src/server/agent/plugin-provider.ts @@ -1,4 +1,5 @@ import { randomUUID } from "node:crypto"; +import { PluginSessionHistory } from "./plugin-session-history.js"; import { resolve as resolvePath } from "node:path"; import type { Logger } from "pino"; import type { JsonValue } from "@getpaseo/protocol/agent-types"; @@ -592,6 +593,7 @@ class ProviderRuntime { class ProviderRuntimeSession { readonly history: ProviderEvent[] = []; + private historyClaimed = false; private readonly listeners = new Set<(event: ProviderEvent) => void>(); private capabilities: readonly string[] = []; private openRequest: { requestId: string; deferred: Deferred } | null = null; @@ -622,6 +624,10 @@ class ProviderRuntimeSession { } onEvent(listener: (event: ProviderEvent) => void): () => void { + // This buffer bridges session.open and adapter attachment. Once replayed, + // the adapter owns history; retaining live cumulative snapshots is quadratic. + this.historyClaimed = true; + this.history.length = 0; this.listeners.add(listener); return () => this.listeners.delete(listener); } @@ -713,6 +719,7 @@ class ProviderRuntimeSession { } async close(): Promise { + this.history.length = 0; if (this.restoration === "parent") { this.runtime.removeSession(this.id, this.providerSessionId); return; @@ -826,7 +833,7 @@ class ProviderRuntimeSession { if (event.type === "session.persistence" && this.restoration === "core") { this.persistence = event.persistence; } - this.history.push(event); + if (!this.historyClaimed) this.history.push(event); for (const listener of this.listeners) listener(event); } } @@ -1128,17 +1135,30 @@ class PluginAgentClient implements AgentClient { } } +interface TimelineTextSnapshot { + type: "assistant_message" | "reasoning" | "user_message"; + text: string; +} + +function isTextSnapshotItem( + item: ProviderTimelineItem, +): item is Extract { + return ( + item.type === "assistant_message" || item.type === "reasoning" || item.type === "user_message" + ); +} + class PluginAgentSession implements AgentSession { readonly initialTimeline: ImportedProviderSession["timeline"]; private readonly listeners = new Set<(event: AgentStreamEvent) => void>(); - private readonly history: AgentStreamEvent[] = []; + private readonly history = new PluginSessionHistory(); private readonly pendingPermissions = new Map(); private readonly permissionResponses = new Map(); private readonly revertTokens = new Map(); - private readonly timelineSnapshots = new Map(); + private readonly timelineSnapshots = new Map(); private readonly subagentIdsBySession = new Map(); private readonly childUnsubscribes = new Map void>(); - private readonly childSnapshots = new Map>(); + private readonly childSnapshots = new Map>(); private unsubscribe: (() => void) | null = null; private currentTurnId: string | null = null; private closed = false; @@ -1236,7 +1256,7 @@ class PluginAgentSession implements AgentSession { } async *streamHistory(): AsyncGenerator { - for (const event of this.history) yield event; + for (const event of this.history.read(this.provider)) yield event; } get canStopRuntime(): (() => Promise) | undefined { @@ -1304,6 +1324,12 @@ class PluginAgentSession implements AgentSession { for (const unsubscribe of this.childUnsubscribes.values()) unsubscribe(); this.childUnsubscribes.clear(); this.subagentIdsBySession.clear(); + this.history.clear(); + this.timelineSnapshots.clear(); + this.childSnapshots.clear(); + this.revertTokens.clear(); + this.pendingPermissions.clear(); + this.permissionResponses.clear(); this.listeners.clear(); this.onClose(); await this.bridge.close(); @@ -1344,16 +1370,20 @@ class PluginAgentSession implements AgentSession { } timelineHistory(): ImportedProviderSession["timeline"] { - return this.history.flatMap((event) => - event.type === "timeline" ? [{ item: event.item, timestamp: event.timestamp }] : [], - ); + return this.history + .read(this.provider) + .flatMap((event) => + event.type === "timeline" ? [{ item: event.item, timestamp: event.timestamp }] : [], + ); } subagentHistory(): NonNullable { - return this.history.filter( - (event): event is Extract => - event.type === "provider_subagent", - ); + return this.history + .read(this.provider) + .filter( + (event): event is Extract => + event.type === "provider_subagent", + ); } attachChild( @@ -1382,7 +1412,7 @@ class PluginAgentSession implements AgentSession { cwd: opened.cwd, }, }); - const snapshots = new Map(); + const snapshots = new Map(); this.childSnapshots.set(childId, snapshots); for (const event of child.history) this.acceptChildEvent(childId, event, snapshots); this.childUnsubscribes.set( @@ -1568,7 +1598,7 @@ class PluginAgentSession implements AgentSession { private acceptChildEvent( childId: string, event: ProviderEvent, - snapshots: Map, + snapshots: Map, ): void { if (event.type === "timeline.item") { const item = mapTimelineItem(event.item, snapshots); @@ -1721,24 +1751,24 @@ function mapPromptContent(prompt: AgentPromptInput): ProviderContent[] { function mapTimelineItem( item: ProviderTimelineItem, - snapshots: Map, + snapshots: Map, revertTokens?: Map, ): AgentTimelineItem | null { const previous = snapshots.get(item.id); - snapshots.set(item.id, item); - const { id, revertToken, ...withoutIdentity } = item; - if (revertToken !== undefined && revertTokens) { - revertTokens.set(id, revertToken); - if (item.type === "user_message" || item.type === "assistant_message") { - revertTokens.set(item.messageId ?? id, revertToken); - } + if (isTextSnapshotItem(item)) { + snapshots.set(item.id, { type: item.type, text: item.text }); } + const { id, revertToken: _revertToken, ...withoutIdentity } = item; + rememberRevertToken(item, revertTokens); if (item.type === "assistant_message" || item.type === "reasoning") { const previousText = previous?.type === item.type ? previous.text : ""; - const text = item.text.startsWith(previousText) + const suffix = item.text.startsWith(previousText) ? item.text.slice(previousText.length) : item.text; + // Match OpenCode's detachedSuffix: a sliced delta otherwise keeps its entire + // cumulative IPC snapshot alive in the projected timeline. Preserve split surrogates. + const text = Buffer.from(suffix, "utf16le").toString("utf16le"); if (text.length === 0) return null; return item.type === "assistant_message" ? { type: "assistant_message", text, messageId: item.messageId ?? id } @@ -1766,6 +1796,17 @@ function mapTimelineItem( return withoutIdentity as AgentTimelineItem; } +function rememberRevertToken( + item: ProviderTimelineItem, + tokens?: Map, +): void { + if (item.revertToken === undefined || !tokens) return; + tokens.set(item.id, item.revertToken); + if (item.type === "user_message" || item.type === "assistant_message") { + tokens.set(item.messageId ?? item.id, item.revertToken); + } +} + function persistenceHandle( provider: string, persistence: ProviderPersistence, diff --git a/packages/server/src/server/agent/plugin-session-history.ts b/packages/server/src/server/agent/plugin-session-history.ts new file mode 100644 index 0000000000..f5efd446d7 --- /dev/null +++ b/packages/server/src/server/agent/plugin-session-history.ts @@ -0,0 +1,66 @@ +import { TimelineProjection } from "./timeline-projection.js"; +import type { AgentStreamEvent } from "./agent-sdk-types.js"; + +// Replay canonical items, rather than retaining every streamed delta or tool state. +// Sequence numbers here only preserve adapter replay order, not wire cursors. +export class PluginSessionHistory { + private readonly timelines = new Map< + string, + { projection: TimelineProjection; seq: number; positions: Map } + >(); + private readonly events: Array<{ seq: number; event: AgentStreamEvent }> = []; + private seq = 0; + + push(event: AgentStreamEvent): void { + const seq = ++this.seq; + const child = + event.type === "provider_subagent" && event.event.type === "timeline" ? event.event : null; + if (event.type !== "timeline" && !child) { + this.events.push({ seq, event }); + return; + } + const key = child?.id ?? ""; + let projection = this.timelines.get(key); + if (!projection) { + projection = { projection: new TimelineProjection(), seq: 0, positions: new Map() }; + this.timelines.set(key, projection); + } + const timeline = event.type === "timeline" ? event : child!; + const row = projection.projection.append({ + seq: ++projection.seq, + item: timeline.item, + timestamp: timeline.timestamp ?? "", + ...(event.type === "timeline" && event.turnId ? { turnId: event.turnId } : {}), + }); + if (!projection.positions.has(row.seqStart)) projection.positions.set(row.seqStart, seq); + } + + read(provider: string): AgentStreamEvent[] { + const events = [...this.events]; + for (const [id, projection] of this.timelines) { + for (const row of projection.projection.getRows()) { + const timestamp = row.timestamp ? { timestamp: row.timestamp } : {}; + const event: AgentStreamEvent = id + ? { + type: "provider_subagent", + provider, + event: { type: "timeline", id, item: row.item, ...timestamp }, + } + : { + type: "timeline", + provider, + item: row.item, + ...timestamp, + ...(row.turnId ? { turnId: row.turnId } : {}), + }; + events.push({ seq: projection.positions.get(row.seqStart)!, event }); + } + } + return events.sort((a, b) => a.seq - b.seq).map(({ event }) => event); + } + + clear(): void { + this.timelines.clear(); + this.events.length = 0; + } +} diff --git a/packages/server/src/server/agent/test-utils/plugin-stream-memory.ts b/packages/server/src/server/agent/test-utils/plugin-stream-memory.ts new file mode 100644 index 0000000000..948202bae2 --- /dev/null +++ b/packages/server/src/server/agent/test-utils/plugin-stream-memory.ts @@ -0,0 +1,176 @@ +import assert from "node:assert/strict"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; +import type { ProviderEvent, ProviderRegistration } from "@getpaseo/plugin/server/provider"; +import pino from "pino"; +import { PluginAgentClientRegistry } from "../plugin-provider.js"; +import { InMemoryAgentTimelineStore } from "../agent-timeline-store.js"; +import { AgentManager } from "../agent-manager.js"; +import { AgentStorage } from "../agent-storage.js"; +import { buildProviderRegistry } from "../provider-registry.js"; + +if (!global.gc) throw new Error("Run with --expose-gc"); +const logger = pino({ level: "silent" }); +const plugins = new PluginAgentClientRegistry(logger); +const root = await mkdtemp(join(tmpdir(), "plugin-stream-memory-")); +const emitters: Array<(event: ProviderEvent) => void> = []; +const ids: string[] = []; +const registrations: ProviderRegistration[] = Array.from({ length: 3 }, (_, index) => ({ + id: `memory-${index}`, + label: "Memory fixture", + async connect() { + let listener: (event: ProviderEvent) => void = () => {}; + const capabilities = ["prompt.message", "session.persistence"] as const; + return { + version: 1, + capabilities, + onEvent(callback) { + listener = callback; + // Plugin IPC delivers independent JSON strings, rather than shared ropes. + emitters[index] = (event) => listener(JSON.parse(JSON.stringify(event))); + return () => { + listener = () => {}; + }; + }, + async send(input) { + if (input.type === "session.open") { + ids[index] = input.sessionId; + listener({ + type: "session.opened", + requestId: input.requestId, + sessionId: input.sessionId, + cwd: "/tmp", + capabilities, + restoration: "core", + persistence: { version: 1, data: { index } }, + }); + listener({ + type: "session.ready", + requestId: input.requestId, + sessionId: input.sessionId, + }); + } else if (input.type === "catalog") { + listener({ + type: "catalog", + requestId: input.requestId, + catalog: { models: [], modes: [], thinkingOptions: [] }, + }); + } else if (input.type === "session.close") { + listener({ type: "session.closed", sessionId: input.sessionId }); + listener({ type: "request.completed", requestId: input.requestId }); + } + }, + async close() {}, + }; + }, +})); +plugins.replace(registrations); +const store = new InMemoryAgentTimelineStore(); +const manager = new AgentManager({ + clients: plugins.clients(), + providerDefinitions: buildProviderRegistry(logger, { pluginProviders: plugins.definitions() }), + registry: new AgentStorage(root, logger), + timelineStore: store, + logger, +}); +const agents = await Promise.all( + Object.keys(plugins.clients()).map((provider) => + manager.createAgent({ provider, cwd: root }, undefined, {}), + ), +); +const sessions = agents.map((agent) => agent.session!); +agents.forEach((_agent, index) => { + emitters[index]!({ + type: "session.opened", + sessionId: `child-${index}`, + parentSessionId: ids[index]!, + capabilities: [], + restoration: "parent", + cwd: root, + }); +}); +global.gc(); +const before = process.memoryUsage().heapUsed; +const steps = 4; +const chunks = 200; +const expected = new Map(); +for (let step = 0; step < steps; step++) { + for (let index = 0; index < sessions.length; index++) { + const text = `${index}:${step}:` + "推理".repeat(15000) + "a\uD83D\uDE00b"; + expected.set(`${index}:${step}`, text); + for (let chunk = 1; chunk <= chunks; chunk++) { + for (const sessionId of [ids[index]!, `child-${index}`]) { + emitters[index]!({ + type: "timeline.item", + sessionId, + item: { + type: "reasoning", + id: `reason-${step}`, + text: text.slice(0, Math.ceil((chunk * text.length) / chunks)), + }, + }); + } + } + emitters[index]!({ + type: "timeline.item", + sessionId: ids[index]!, + item: { + type: "tool_call", + id: `tool-${step}`, + callId: `tool-${step}`, + name: "read", + status: "completed", + error: null, + detail: { type: "unknown", input: null, output: "输出".repeat(16000) }, + }, + }); + emitters[index]!({ + type: "timeline.item", + sessionId: `child-${index}`, + item: { + type: "assistant_message", + id: `answer-${step}`, + text: "Child step complete.", + }, + }); + } + // Drain the manager's event queue; terminal tool states flush its real coalescer. + await delay(80); +} +global.gc(); +const retained = process.memoryUsage().heapUsed - before; +assert(retained < 24 * 1024 * 1024, `Retained heap exceeded 24 MiB: ${retained} bytes`); +for (let index = 0; index < sessions.length; index++) { + const items = store.getItems(agents[index]!.id); + assert.equal(items.length, steps * 2); + for (let step = 0; step < steps; step++) { + const item = items[step * 2]!; + assert.equal(item.type === "reasoning" && item.text, expected.get(`${index}:${step}`)); + } + const children = manager.listProviderSubagents(agents[index]!.id); + assert.equal(children.length, 1); + let rootItems = 0; + let childItems = 0; + for await (const event of sessions[index]!.streamHistory()) { + if (event.type === "timeline") rootItems++; + if (event.type === "provider_subagent" && event.event.type === "timeline") childItems++; + } + assert.equal(rootItems, steps * 2); + assert.equal(childItems, steps * 2); + await manager.archiveAgent(agents[index]!.id); + assert.equal(store.has(agents[index]!.id), false); + assert.equal( + manager.listAgents().some((agent) => agent.id === agents[index]!.id), + false, + ); +} +await plugins.shutdown(); +await manager.flushForShutdown(); +await rm(root, { recursive: true, force: true }); +global.gc(); +const closed = process.memoryUsage().heapUsed - before; +// Keep closed session references alive, as callers can retain them after archive. +assert.equal(sessions.length, 3); +process.stdout.write(JSON.stringify({ retained, closed })); diff --git a/packages/server/src/server/agent/timeline-projection.ts b/packages/server/src/server/agent/timeline-projection.ts index 8b05432545..bd5357e581 100644 --- a/packages/server/src/server/agent/timeline-projection.ts +++ b/packages/server/src/server/agent/timeline-projection.ts @@ -323,7 +323,7 @@ export class TimelineProjection { this.sourceRanges.sort((a, b) => a.startSeq - b.startSeq); } - append(row: AgentTimelineRow): void { + append(row: AgentTimelineRow): ProjectedTimelineRow { const rowIndex = this.appendProjected(row); const last = this.sourceRanges.at(-1); if (last && last.rowIndex === rowIndex && last.endSeq + 1 === row.seq) { @@ -331,6 +331,7 @@ export class TimelineProjection { } else { this.sourceRanges.push({ startSeq: row.seq, endSeq: row.seq, rowIndex }); } + return { ...this.rows[rowIndex] }; } private appendProjected(row: AgentTimelineRow): number { From abc97e0545bb92e43eb96027102d845657c0a2eb Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Wed, 28 Oct 2026 14:56:13 +0000 Subject: [PATCH 092/173] Keep an interrupted background Claude subagent canceled after a daemon restart (#6259) * Keep an interrupted background Claude subagent canceled after a daemon restart Replay read a background Agent call's immediate async-launch result as the child's outcome, so every background subagent restored as completed. Skip that result, and read a child transcript that ends on the interrupt placeholder as canceled, which is what the live path reported. * Keep a background Claude subagent running when it got a new prompt after an interrupt * fix(claude): preserve background subagent outcomes on replay Use persisted task notifications as replay outcomes with the live status mapping. Diagnostic API request copies contain launch tool results without async metadata, so only transcript messages supply task declarations and tool outcomes. --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../claude/agent.sub-agent-replay.test.ts | 231 ++++++++++++++++++ .../server/agent/providers/claude/agent.ts | 66 +++-- .../providers/claude/interrupt-placeholder.ts | 6 + .../providers/claude/subagents/live-source.ts | 25 +- .../claude/subagents/replay-source.test.ts | 12 +- .../claude/subagents/replay-source.ts | 65 +++-- .../providers/claude/subagents/task-status.ts | 23 ++ .../claude/task-notification-tool-call.ts | 22 +- 8 files changed, 363 insertions(+), 87 deletions(-) create mode 100644 packages/server/src/server/agent/providers/claude/interrupt-placeholder.ts create mode 100644 packages/server/src/server/agent/providers/claude/subagents/task-status.ts diff --git a/packages/server/src/server/agent/providers/claude/agent.sub-agent-replay.test.ts b/packages/server/src/server/agent/providers/claude/agent.sub-agent-replay.test.ts index 666e701649..9fc82d6de8 100644 --- a/packages/server/src/server/agent/providers/claude/agent.sub-agent-replay.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.sub-agent-replay.test.ts @@ -422,6 +422,237 @@ describe("ClaudeAgentSession persisted subagent replay", () => { }); }); + describe("a background subagent", () => { + // Shapes recorded from Claude Code 2.1.x: the launch returns at once with an async result, + // and a child stopped by an interrupt ends on the interrupt placeholder, not an end_turn. + function backgroundLaunch(): string[] { + return [ + parentEntry([ + { + type: "tool_use", + id: TOOL_USE_ID, + name: "Agent", + input: { + subagent_type: "general-purpose", + description: "probe sleeper", + run_in_background: true, + }, + }, + ]), + JSON.stringify({ + type: "user", + sessionId: "replay-session", + timestamp: "2026-07-26T06:27:48.000Z", + message: { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: TOOL_USE_ID, + content: [ + { + type: "text", + text: `Async agent launched successfully.\nagentId: ${AGENT_ID}`, + }, + ], + }, + ], + }, + toolUseResult: { isAsync: true, status: "async_launched", agentId: AGENT_ID }, + }), + ]; + } + + function readStatus(event: { status?: string }): string | undefined { + return event.status; + } + + function interruptedChild(): string[] { + return [ + JSON.stringify({ + type: "assistant", + isSidechain: true, + agentId: AGENT_ID, + timestamp: "2026-07-26T06:27:50.000Z", + message: { + role: "assistant", + content: [{ type: "tool_use", id: "toolu_child_bash", name: "Bash", input: {} }], + stop_reason: "tool_use", + }, + }), + JSON.stringify({ + type: "user", + isSidechain: true, + agentId: AGENT_ID, + timestamp: "2026-07-26T06:28:05.000Z", + message: { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: "toolu_child_bash", + content: "The user doesn't want to proceed with this tool use.", + is_error: true, + }, + ], + }, + }), + JSON.stringify({ + type: "user", + isSidechain: true, + agentId: AGENT_ID, + timestamp: "2026-07-26T06:28:05.001Z", + message: { + role: "user", + content: [{ type: "text", text: "[Request interrupted by user for tool use]" }], + }, + }), + ]; + } + + test.each([ + ["the meta sidecar", JSON.stringify({ toolUseId: TOOL_USE_ID })], + ["the legacy scrape", null], + ])("is canceled when an interrupt stopped it, linked through %s", async (_link, meta) => { + writeSession({ parentLines: backgroundLaunch(), meta, sidechainLines: interruptedChild() }); + + expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({ + id: TOOL_USE_ID, + status: "canceled", + }); + }); + + test("stays running when the child was given a new prompt after the interrupt", async () => { + writeSession({ + parentLines: backgroundLaunch(), + meta: JSON.stringify({ toolUseId: TOOL_USE_ID }), + sidechainLines: [ + ...interruptedChild(), + JSON.stringify({ + type: "user", + isSidechain: true, + agentId: AGENT_ID, + timestamp: "2026-07-26T06:29:00.000Z", + message: { role: "user", content: [{ type: "text", text: "Carry on with the task." }] }, + }), + ], + }); + + const statuses = upserts(await replayDescriptors()).map(readStatus); + expect(statuses).not.toContain("canceled"); + expect(statuses).toContain("running"); + }); + + test.each(["interrupted", "running"])( + "ignores an API request copy of a %s child's launch result", + async (state) => { + const launch = backgroundLaunch(); + const result = JSON.parse(launch[1]!); + writeSession({ + parentLines: [ + ...launch, + JSON.stringify({ + type: "api-request-blob", + sessionId: "replay-session", + hash: "request-copy", + message: result.message, + }), + ], + meta: JSON.stringify({ toolUseId: TOOL_USE_ID }), + sidechainLines: + state === "interrupted" + ? interruptedChild() + : [sidechainEntry({ stopReason: "tool_use" })], + }); + expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({ + id: TOOL_USE_ID, + status: state === "interrupted" ? "canceled" : "running", + }); + }, + ); + + test("stays running while the child has not finished", async () => { + writeSession({ + parentLines: backgroundLaunch(), + meta: JSON.stringify({ toolUseId: TOOL_USE_ID }), + sidechainLines: [sidechainEntry({ stopReason: "tool_use" })], + }); + + const statuses = upserts(await replayDescriptors()).map(readStatus); + expect(statuses).not.toContain("completed"); + expect(statuses).toContain("running"); + }); + + function taskNotification(status: string, form = "user"): string { + const text = `\n${AGENT_ID}\n${TOOL_USE_ID}\n${status}\nBackground task ended\n`; + const records = { + user: { message: { role: "user", content: [{ type: "text", text }] } }, + system: { + subtype: "task_notification", + task_id: AGENT_ID, + tool_use_id: TOOL_USE_ID, + status, + }, + "queue-operation": { operation: "enqueue", content: text }, + }; + return JSON.stringify({ + type: form, + timestamp: "2026-07-26T06:29:00.000Z", + ...records[form as keyof typeof records], + }); + } + + for (const form of ["user", "system", "queue-operation"]) { + test.each([ + ["completed", "completed"], + ["failed", "failed"], + ["killed", "canceled"], + ["stopped", "canceled"], + ])( + `restores a %s task notification from ${form} when the child stop_reason is null`, + async (status, expected) => { + writeSession({ + parentLines: [...backgroundLaunch(), taskNotification(status, form)], + meta: JSON.stringify({ toolUseId: TOOL_USE_ID }), + sidechainLines: [sidechainEntry({ stopReason: null })], + }); + expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({ + id: TOOL_USE_ID, + status: expected, + }); + }, + ); + } + + test("prefers a stopped notification over the child's end_turn", async () => { + writeSession({ + parentLines: [...backgroundLaunch(), taskNotification("stopped")], + meta: JSON.stringify({ toolUseId: TOOL_USE_ID }), + sidechainLines: [sidechainEntry({ stopReason: "end_turn" })], + }); + expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({ status: "canceled" }); + }); + + test("does not invent an outcome for an unknown notification status", async () => { + writeSession({ + parentLines: [...backgroundLaunch(), taskNotification("unknown")], + meta: JSON.stringify({ toolUseId: TOOL_USE_ID }), + sidechainLines: [sidechainEntry({ stopReason: null })], + }); + expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({ status: "running" }); + }); + + test("completes from the child's own end_turn", async () => { + writeSession({ + parentLines: backgroundLaunch(), + meta: JSON.stringify({ toolUseId: TOOL_USE_ID }), + sidechainLines: [sidechainEntry({ stopReason: "end_turn" })], + }); + + expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({ status: "completed" }); + }); + }); + test("does not replay a skill-spawned subagent the parent never named", async () => { // The reported bug. A /code-review subagent has no Task tool_use, so its sidecar carries only // agentType and its id appears nowhere in the parent — it used to replay as running forever, diff --git a/packages/server/src/server/agent/providers/claude/agent.ts b/packages/server/src/server/agent/providers/claude/agent.ts index 6516ff81b7..e2cd9dab8f 100644 --- a/packages/server/src/server/agent/providers/claude/agent.ts +++ b/packages/server/src/server/agent/providers/claude/agent.ts @@ -33,7 +33,9 @@ import { mapTaskNotificationSystemRecordToToolCall, mapTaskNotificationUserContentToToolCall, readTaskNotificationToolUseIdFromHistoryRecord, + readTaskNotificationFromHistoryRecord, } from "./task-notification-tool-call.js"; +import { isClaudeInterruptPlaceholderText } from "./interrupt-placeholder.js"; import { getClaudeContextWindowMaxTokens, getClaudeModelsWithSettings, @@ -56,6 +58,8 @@ import { type ClaudeHookObservationInput, } from "./subagents/live-source.js"; import { observeReplaySubagents, type ClaudeReplayParentFacts } from "./subagents/replay-source.js"; +import { mapTaskStatus } from "./subagents/task-status.js"; +import type { ProviderSubagentStatus } from "../../provider-subagents/store.js"; import { foldSubagentObservations, type SubagentObservation } from "./subagents/observation.js"; import { observeReplayWorkflows } from "./subagents/workflow-replay-source.js"; import { limitAgentTimelineItemContent } from "../../agent-timeline-content.js"; @@ -425,7 +429,6 @@ const CLAUDE_ROOT_ONLY_COMMANDS = new Set([ "usage", ]); const INTERRUPT_TOOL_USE_PLACEHOLDER = "[Request interrupted by user for tool use]"; -const INTERRUPT_PLACEHOLDER_PATTERN = /^\[Request interrupted by user(?:[^\]]*)\]$/; const NO_RESPONSE_REQUESTED_PLACEHOLDER = "No response requested."; const STEER_SUPERSEDED_PERMISSION_MESSAGE = "The user answered with a message instead of approving. Their message follows."; @@ -789,11 +792,6 @@ function normalizeClaudeTranscriptText(value: unknown): string | null { return normalized.length > 0 ? normalized : null; } -function isClaudeInterruptPlaceholderText(value: unknown): boolean { - const normalized = normalizeClaudeTranscriptText(value); - return normalized !== null && INTERRUPT_PLACEHOLDER_PATTERN.test(normalized); -} - function isClaudeNoResponsePlaceholderText(value: unknown): boolean { return normalizeClaudeTranscriptText(value) === NO_RESPONSE_REQUESTED_PLACEHOLDER; } @@ -6262,33 +6260,34 @@ async function readClaudeReplayParentFacts( entries: Iterable | AsyncIterable, ): Promise { const toolCalls = new Map(); - const linksByAgentId = new Map(); - const outcomes = new Map(); + const linksByAgentId = new Map(); + const outcomes: Map = new Map(); for await (const entry of entries) { + const notification = readTaskNotificationFromHistoryRecord(entry); + const status = mapTaskStatus(notification?.status ?? undefined); + if (notification?.toolUseId && status) { + outcomes.set(notification.toolUseId, { status }); + } const content = toObjectRecord(entry.message)?.content; if (!Array.isArray(content)) continue; for (const value of content) { const block = toObjectRecord(value); + const declaration = readClaudeReplayTaskDeclaration(entry.type, block); + if (declaration) toolCalls.set(declaration.id, declaration.identity); if ( - block?.type === "tool_use" && - (block.name === "Task" || block.name === "Agent") && - typeof block.id === "string" - ) { - const input = toObjectRecord(block.input); - const title = readNonEmptyString(input?.name) ?? readNonEmptyString(input?.subagent_type); - const description = readNonEmptyString(input?.description); - toolCalls.set(block.id, { - ...(title ? { title } : {}), - ...(description ? { description } : {}), + entry.type !== "user" || + block?.type !== "tool_result" || + typeof block.tool_use_id !== "string" + ) + continue; + if (toObjectRecord(entry.toolUseResult)?.status !== "async_launched") + outcomes.set(block.tool_use_id, { + status: block.is_error === true ? "failed" : "completed", }); - } - if (block?.type !== "tool_result" || typeof block.tool_use_id !== "string") continue; - outcomes.set(block.tool_use_id, { failed: block.is_error === true }); const agentId = readLegacyClaudeSubagentId(block.content); if (agentId) linksByAgentId.set(agentId, { toolCallId: block.tool_use_id, - failed: block.is_error === true, }); } } @@ -6299,6 +6298,29 @@ async function readClaudeReplayParentFacts( }; } +function readClaudeReplayTaskDeclaration( + entryType: unknown, + block: Record | undefined, +): { + id: string; + identity: { title?: string; description?: string }; +} | null { + if ( + entryType !== "assistant" || + block?.type !== "tool_use" || + (block.name !== "Task" && block.name !== "Agent") || + typeof block.id !== "string" + ) + return null; + const input = toObjectRecord(block.input); + const title = readNonEmptyString(input?.name) ?? readNonEmptyString(input?.subagent_type); + const description = readNonEmptyString(input?.description); + return { + id: block.id, + identity: { ...(title ? { title } : {}), ...(description ? { description } : {}) }, + }; +} + function readLegacyClaudeSubagentId(content: unknown): string | undefined { return /agentId:\s*([\w-]+)/.exec(JSON.stringify(content))?.[1]; } diff --git a/packages/server/src/server/agent/providers/claude/interrupt-placeholder.ts b/packages/server/src/server/agent/providers/claude/interrupt-placeholder.ts new file mode 100644 index 0000000000..f74c899234 --- /dev/null +++ b/packages/server/src/server/agent/providers/claude/interrupt-placeholder.ts @@ -0,0 +1,6 @@ +const INTERRUPT_PLACEHOLDER_PATTERN = /^\[Request interrupted by user(?:[^\]]*)\]$/; + +/** The text Claude Code records in place of a turn that an interrupt stopped. */ +export function isClaudeInterruptPlaceholderText(value: unknown): boolean { + return typeof value === "string" && INTERRUPT_PLACEHOLDER_PATTERN.test(value.trim()); +} diff --git a/packages/server/src/server/agent/providers/claude/subagents/live-source.ts b/packages/server/src/server/agent/providers/claude/subagents/live-source.ts index 2149fae139..af941aa24b 100644 --- a/packages/server/src/server/agent/providers/claude/subagents/live-source.ts +++ b/packages/server/src/server/agent/providers/claude/subagents/live-source.ts @@ -1,7 +1,8 @@ +import type { ProviderSubagentStatus } from "../../../provider-subagents/store.js"; +import { mapTaskStatus } from "./task-status.js"; import type { SDKMessage } from "@anthropic-ai/claude-agent-sdk"; import type { AgentMetadata } from "../../../agent-sdk-types.js"; -import type { ProviderSubagentStatus } from "../../../provider-subagents/store.js"; import { resolveObservedClaudeModelId } from "../models.js"; import type { SubagentObservation } from "./observation.js"; import { @@ -120,28 +121,6 @@ function readString(value: unknown): string | undefined { return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined; } -/** - * The descriptor has no paused or pending state, and neither is terminal, so both read as - * running. `killed` is a cancellation, not a failure — the child was stopped, it did not error. - */ -function mapTaskStatus(status: string | undefined): ProviderSubagentStatus | undefined { - switch (status) { - case "pending": - case "running": - case "paused": - return "running"; - case "completed": - return "completed"; - case "failed": - return "failed"; - case "killed": - case "stopped": - return "canceled"; - default: - return undefined; - } -} - export interface ClaudeTaskProtocolSourceInput { /** * The parent's Task tool input, by tool_use id. diff --git a/packages/server/src/server/agent/providers/claude/subagents/replay-source.test.ts b/packages/server/src/server/agent/providers/claude/subagents/replay-source.test.ts index f5bbf52422..3bde4b813b 100644 --- a/packages/server/src/server/agent/providers/claude/subagents/replay-source.test.ts +++ b/packages/server/src/server/agent/providers/claude/subagents/replay-source.test.ts @@ -36,7 +36,7 @@ function parentWithTaskCall(failed = false): ClaudeReplayParentFacts { ], ]), linksByAgentId: new Map(), - outcomesByToolCallId: new Map([[TOOL_USE_ID, { failed }]]), + outcomesByToolCallId: new Map([[TOOL_USE_ID, { status: failed ? "failed" : "completed" }]]), }; } @@ -117,7 +117,7 @@ describe("observeReplaySubagents", () => { [nestedToolUseId, { title: "Explore", description: "Nested audit" }], ]), linksByAgentId: new Map(), - outcomesByToolCallId: new Map([[nestedToolUseId, { failed: false }]]), + outcomesByToolCallId: new Map([[nestedToolUseId, { status: "completed" }]]), }, }, { @@ -173,8 +173,8 @@ describe("observeReplaySubagents", () => { it("falls back to the scraped link when there is no meta file", async () => { const parent: ClaudeReplayParentFacts = { toolCalls: new Map([[TOOL_USE_ID, { title: "Explore" }]]), - linksByAgentId: new Map([[AGENT_ID, { toolCallId: TOOL_USE_ID, failed: false }]]), - outcomesByToolCallId: new Map(), + linksByAgentId: new Map([[AGENT_ID, { toolCallId: TOOL_USE_ID }]]), + outcomesByToolCallId: new Map([[TOOL_USE_ID, { status: "completed" }]]), }; const [declared, ...rest] = ( @@ -263,8 +263,8 @@ describe("observeReplaySubagents", () => { subagents: [{ agentId: AGENT_ID, meta: null, entries: [] }], parent: { toolCalls: new Map([[TOOL_USE_ID, { title: "Explore" }]]), - linksByAgentId: new Map([[AGENT_ID, { toolCallId: TOOL_USE_ID, failed: true }]]), - outcomesByToolCallId: new Map(), + linksByAgentId: new Map([[AGENT_ID, { toolCallId: TOOL_USE_ID }]]), + outcomesByToolCallId: new Map([[TOOL_USE_ID, { status: "failed" }]]), }, convertEntry: () => [], }) diff --git a/packages/server/src/server/agent/providers/claude/subagents/replay-source.ts b/packages/server/src/server/agent/providers/claude/subagents/replay-source.ts index 2a3ca74846..02cbb783f0 100644 --- a/packages/server/src/server/agent/providers/claude/subagents/replay-source.ts +++ b/packages/server/src/server/agent/providers/claude/subagents/replay-source.ts @@ -3,6 +3,7 @@ import { z } from "zod"; import type { AgentTimelineItem } from "../../../agent-sdk-types.js"; import { normalizeProviderReplayTimestamp } from "../../../provider-history-timestamps.js"; import type { ProviderSubagentStatus } from "../../../provider-subagents/store.js"; +import { isClaudeInterruptPlaceholderText } from "../interrupt-placeholder.js"; import { resolveObservedClaudeModelId } from "../models.js"; import type { SubagentObservation } from "./observation.js"; import { buildClaudeSubagentSubtitle, type ClaudeSubagentUsage } from "./presentation.js"; @@ -139,9 +140,12 @@ export interface ClaudeReplayParentFacts { /** Task `tool_use` id -> identity declared in the parent's tool input. */ toolCalls: ReadonlyMap; /** agentId -> tool call, recovered by scraping tool-result text. Legacy fallback only. */ - linksByAgentId: ReadonlyMap; - /** Task `tool_use` id -> outcome. Usable once meta.json supplies the link directly. */ - outcomesByToolCallId: ReadonlyMap; + linksByAgentId: ReadonlyMap; + /** + * Task `tool_use` id -> outcome, whichever way the child was linked. A background launch has + * none: its immediate result only says the child started. + */ + outcomesByToolCallId: ReadonlyMap; } interface ParentLink { @@ -177,27 +181,14 @@ function resolveParentLink( parent: ClaudeReplayParentFacts, ): ParentLink | null { const metaToolUseId = subagent.meta?.toolUseId?.trim(); - if (metaToolUseId && parent.toolCalls.has(metaToolUseId)) { - const outcome = parent.outcomesByToolCallId.get(metaToolUseId); - let status: ProviderSubagentStatus | null = null; - if (outcome) status = outcome.failed ? "failed" : "completed"; - return { - id: metaToolUseId, - toolCallId: metaToolUseId, - status, - }; - } + const toolCallId = + metaToolUseId && parent.toolCalls.has(metaToolUseId) + ? metaToolUseId + : parent.linksByAgentId.get(subagent.agentId)?.toolCallId; + if (!toolCallId || !parent.toolCalls.has(toolCallId)) return null; - const scraped = parent.linksByAgentId.get(subagent.agentId); - if (scraped && parent.toolCalls.has(scraped.toolCallId)) { - return { - id: scraped.toolCallId, - toolCallId: scraped.toolCallId, - status: scraped.failed ? "failed" : "completed", - }; - } - - return null; + const status = parent.outcomesByToolCallId.get(toolCallId)?.status ?? null; + return { id: toolCallId, toolCallId, status }; } /** @@ -276,9 +267,7 @@ async function observeSubagent( lastTimestamp = timestamp; Object.assign(runtime, readRuntime(entry)); usage = readUsage(entry) ?? usage; - if (entry.type === "assistant") { - childTerminalStatus = entry.message?.stop_reason === "end_turn" ? "completed" : null; - } + childTerminalStatus = readChildTerminalStatus(entry, childTerminalStatus); recordReplayToolOwners(toolOwners, entry, link.id); for (const item of await convertEntry(entry)) { timeline.push({ kind: "timeline", id: link.id, item, ...(timestamp ? { timestamp } : {}) }); @@ -308,6 +297,30 @@ async function observeSubagent( return observations; } +/** Advance the child's fallback outcome without retaining transcript entries. */ +function readChildTerminalStatus( + entry: ClaudeReplayEntry, + previous: ProviderSubagentStatus | null, +): ProviderSubagentStatus | null { + if (entry.type === "assistant") { + return entry.message?.stop_reason === "end_turn" ? "completed" : null; + } + if (entry.type !== "user") return previous; + const texts = readUserTexts(entry); + if (texts.length === 0) return previous; + return texts.some(isClaudeInterruptPlaceholderText) ? "canceled" : null; +} + +/** Tool results carry no user text and do not change the child's terminal status. */ +function readUserTexts(entry: ClaudeReplayEntry): string[] { + const content = entry.message?.content; + if (typeof content === "string") return [content]; + if (!Array.isArray(content)) return []; + return content.flatMap((block: { type?: unknown; text?: unknown } | null) => + block?.type === "text" && typeof block.text === "string" ? [block.text] : [], + ); +} + function recordReplayToolOwners( owners: Map, entry: ClaudeReplayEntry, diff --git a/packages/server/src/server/agent/providers/claude/subagents/task-status.ts b/packages/server/src/server/agent/providers/claude/subagents/task-status.ts new file mode 100644 index 0000000000..a488ce12d7 --- /dev/null +++ b/packages/server/src/server/agent/providers/claude/subagents/task-status.ts @@ -0,0 +1,23 @@ +import type { ProviderSubagentStatus } from "../../../provider-subagents/store.js"; + +/** + * The descriptor has no paused or pending state, and neither is terminal, so both read as + * running. `killed` is a cancellation, not a failure — the child was stopped, it did not error. + */ +export function mapTaskStatus(status: string | undefined): ProviderSubagentStatus | undefined { + switch (status) { + case "pending": + case "running": + case "paused": + return "running"; + case "completed": + return "completed"; + case "failed": + return "failed"; + case "killed": + case "stopped": + return "canceled"; + default: + return undefined; + } +} diff --git a/packages/server/src/server/agent/providers/claude/task-notification-tool-call.ts b/packages/server/src/server/agent/providers/claude/task-notification-tool-call.ts index c8e38bf918..76ad89d8ef 100644 --- a/packages/server/src/server/agent/providers/claude/task-notification-tool-call.ts +++ b/packages/server/src/server/agent/providers/claude/task-notification-tool-call.ts @@ -407,19 +407,21 @@ export function mapTaskNotificationSystemRecordToToolCall( } export function readTaskNotificationToolUseIdFromHistoryRecord(record: unknown): string | null { + return readTaskNotificationFromHistoryRecord(record)?.toolUseId ?? null; +} + +export function readTaskNotificationFromHistoryRecord( + record: unknown, +): TaskNotificationEnvelope | null { const parsedRecord = TaskNotificationHistoryRecordSchema.safeParse(record); - if (!parsedRecord.success) { - return null; - } + if (!parsedRecord.success) return null; if (parsedRecord.data.type === "user" && parsedRecord.data.message) { - return ( - parseTaskNotificationFromUserContent({ - content: parsedRecord.data.message.content, - messageId: parsedRecord.data.uuid ?? parsedRecord.data.message_id, - })?.toolUseId ?? null - ); + return parseTaskNotificationFromUserContent({ + content: parsedRecord.data.message.content, + messageId: parsedRecord.data.uuid ?? parsedRecord.data.message_id, + }); } - return parseTaskNotificationFromSystemRecord(record)?.toolUseId ?? null; + return parseTaskNotificationFromSystemRecord(record); } export function coerceTaskNotificationHistoryRecordToSystemMessage( From 38506ed372b6cf3c89f53f4962db3406d92a1866 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Wed, 28 Oct 2026 22:59:21 +0700 Subject: [PATCH 093/173] test(plugins): allow time for Windows legacy migration workflows (#8112) The migration case runs real Git operations and several plugin subprocess restarts. Windows CI exceeded its 30-second test deadline and entered cleanup while the operation was still active. Keep every assertion and allow 60 seconds for the complete workflow. --- packages/server/src/server/plugins/index.posix.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/server/src/server/plugins/index.posix.test.ts b/packages/server/src/server/plugins/index.posix.test.ts index 4fdc8c3eb4..364e24e40b 100644 --- a/packages/server/src/server/plugins/index.posix.test.ts +++ b/packages/server/src/server/plugins/index.posix.test.ts @@ -730,7 +730,7 @@ export default function contribute(server: PluginServerContext) { await service.stopAllPlugins(); } }, - 30_000, + 60_000, ); it("keeps the running commit when a Git update build command fails", async () => { From 5cfe8f1218fe527cc6e4a916ea0287dce703823a Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Wed, 28 Oct 2026 23:30:16 +0700 Subject: [PATCH 094/173] Remove the out-of-date daemon sidebar notice (#8133) The notice arrived with the terminal worker change (#7644) but is a separate product change. Remove it with the native/compact callout filtering it needed, restoring the sidebar callout slot to web-only. Restart and close terminals in Settings stays. --- docs/design.md | 2 +- .../browser/daemon-outdated-notice.spec.ts | 69 ------- .../e2e/browser/settings-navigation.spec.ts | 13 +- ...ve-daemon-outdated-notice-preconditions.md | 35 ---- .../native-daemon-outdated-notice.ios.yaml | 26 --- packages/app/src/app/_layout.tsx | 2 - .../daemon-outdated-callout-source.tsx | 182 ---------------- packages/app/src/components/left-sidebar.tsx | 5 +- .../resolve-daemon-outdated-callout.test.ts | 195 ------------------ .../resolve-daemon-outdated-callout.ts | 147 ------------- .../src/components/sidebar-callout-slot.d.ts | 1 + .../sidebar-callout-slot.native.tsx | 3 + .../components/sidebar-callout-slot.test.tsx | 4 +- ...-slot.tsx => sidebar-callout-slot.web.tsx} | 8 +- .../src/contexts/sidebar-callout-context.tsx | 22 +- .../contexts/sidebar-callout-state.test.ts | 24 --- .../app/src/contexts/sidebar-callout-state.ts | 13 +- packages/app/src/i18n/resources/ar.ts | 12 -- packages/app/src/i18n/resources/en.ts | 12 -- packages/app/src/i18n/resources/es.ts | 13 -- packages/app/src/i18n/resources/fr.ts | 13 -- packages/app/src/i18n/resources/ja.ts | 14 -- packages/app/src/i18n/resources/ko.ts | 14 -- packages/app/src/i18n/resources/pt-BR.ts | 13 -- packages/app/src/i18n/resources/ru.ts | 12 -- packages/app/src/i18n/resources/zh-CN.ts | 12 -- 26 files changed, 19 insertions(+), 847 deletions(-) delete mode 100644 packages/app/e2e/browser/daemon-outdated-notice.spec.ts delete mode 100644 packages/app/e2e/mobile/agent-device/native-daemon-outdated-notice-preconditions.md delete mode 100644 packages/app/e2e/mobile/agent-device/native-daemon-outdated-notice.ios.yaml delete mode 100644 packages/app/src/components/daemon-outdated-callout-source.tsx delete mode 100644 packages/app/src/components/resolve-daemon-outdated-callout.test.ts delete mode 100644 packages/app/src/components/resolve-daemon-outdated-callout.ts create mode 100644 packages/app/src/components/sidebar-callout-slot.d.ts create mode 100644 packages/app/src/components/sidebar-callout-slot.native.tsx rename packages/app/src/components/{sidebar-callout-slot.tsx => sidebar-callout-slot.web.tsx} (52%) diff --git a/docs/design.md b/docs/design.md index d115913789..a336b80a64 100644 --- a/docs/design.md +++ b/docs/design.md @@ -203,7 +203,7 @@ Inline errors are a single sentence in `palette.red[300]` `xs`, sitting under th Page-level alerts — informational notices, success confirmations, warnings, or recoverable errors that need a small visible block on the page — use `` (`packages/app/src/components/ui/alert.tsx`). Variants: `default`, `info`, `success`, `warning`, `error`. The chrome is quiet by design: a 1px tinted border, transparent background, a small variant-tinted icon, the title in the variant accent, the description in `foregroundMuted`. Actions go in the `children` slot as ` + + + + + + {isEditing ? ( + + ) : null} + + ); +} + +function ResumePromptSheet({ + initialPrompt, + isSaving, + error, + onSave, + onClose, +}: { + initialPrompt: string; + isSaving: boolean; + error: string | null; + onSave: (prompt: string) => void; + onClose: () => void; +}) { + const { t } = useTranslation(); + const [draft, setDraft] = useState(initialPrompt); + const header = useMemo( + () => ({ title: t("settings.host.agents.resumeOnStartup.prompt") }), + [t], + ); + const canSave = draft !== initialPrompt && draft.trim().length > 0 && !isSaving; + + const handleSave = useCallback(() => onSave(draft), [draft, onSave]); + + return ( + + + {error ? ( + + {error} + + ) : null} + + + + + + ); +} + +const styles = StyleSheet.create((theme) => ({ + titleRow: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[2], + }, + trailing: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[3], + }, + sheetActions: { + flexDirection: "row", + justifyContent: "flex-end", + gap: theme.spacing[2], + }, +})); diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index 26a90016a7..d20c91d773 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -237,6 +237,9 @@ export const MutableDaemonConfigSchema = z // COMPAT(idleRuntimeCleanupSetting): added in v0.13.0, keep optional while old daemons are supported. // Persisted host-wide value, applied live by the daemon. idleRuntimeCleanup: z.boolean().optional(), + // COMPAT(restartRecovery): added in v0.14.0, keep optional for older hosts. + resumeOnStartup: z.boolean().optional(), + resumePrompt: z.string().optional(), appendSystemPrompt: z.string().default(""), terminalProfiles: z.array(TerminalProfileSchema).optional(), agentProfiles: z.array(AgentProfileSchema).optional(), @@ -262,6 +265,8 @@ export const MutableDaemonConfigPatchSchema = z autoArchiveAfterMerge: z.boolean().optional(), enableTerminalAgentHooks: z.boolean().optional(), idleRuntimeCleanup: z.boolean().optional(), + resumeOnStartup: z.boolean().optional(), + resumePrompt: z.string().optional(), appendSystemPrompt: z.string().optional(), terminalProfiles: z.array(TerminalProfileSchema).optional(), agentProfiles: z.array(AgentProfileSchema).optional(), @@ -3731,6 +3736,8 @@ export const ServerInfoStatusPayloadSchema = z skillManagement: z.boolean().optional(), // COMPAT(idleRuntimeCleanupSetting): added in v0.13.0, remove gate after 2027-04-26. idleRuntimeCleanupSetting: z.boolean().optional(), + // COMPAT(restartRecovery): added in v0.14.0, remove gate after 2027-04-28. + resumeOnStartupSetting: z.boolean().optional(), // COMPAT(terminalRestoreModes): added in v0.1.81, remove gate after 2026-11-23. "terminal-restore-modes": z.boolean().optional(), // COMPAT(terminalInputModeReplay): added in v0.2.6, remove gate after 2027-02-02. diff --git a/packages/server/src/server/agent/agent-loading.ts b/packages/server/src/server/agent/agent-loading.ts index 761f1008bd..ba444a394d 100644 --- a/packages/server/src/server/agent/agent-loading.ts +++ b/packages/server/src/server/agent/agent-loading.ts @@ -135,6 +135,7 @@ export async function ensureAgentLoaded( labels: record.labels, workspaceId: record.workspaceId, owner: record.owner, + env: record.launchEnv, }); deps.logger.info({ agentId, provider: record.provider }, "Agent created from stored config"); } diff --git a/packages/server/src/server/agent/agent-manager.test.ts b/packages/server/src/server/agent/agent-manager.test.ts index eb1c05b50f..1d6f323deb 100644 --- a/packages/server/src/server/agent/agent-manager.test.ts +++ b/packages/server/src/server/agent/agent-manager.test.ts @@ -2929,6 +2929,92 @@ test("createAgent passes daemon launch env through the provider launch context", }); }); +test.each([ + { provider: "codex", hasHandle: true }, + { provider: "opencode", hasHandle: true }, + { provider: "codex", hasHandle: false }, + { provider: "opencode", hasHandle: false }, +])( + "$provider preserves explicit launch env across reloads and storage-backed resumes (handle: $hasHandle)", + async ({ provider, hasHandle }) => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-launch-env-")); + const storagePath = join(workdir, "agents"); + class LaunchEnvClient extends TestAgentClient { + lastLaunchContext: AgentLaunchContext | undefined; + + override async createSession( + config: AgentSessionConfig, + context?: AgentLaunchContext, + ): Promise { + this.lastLaunchContext = context; + const session = await super.createSession(config); + session.describePersistence = () => ({ provider, sessionId: session.id }); + return session; + } + + override async resumeSession( + handle: AgentPersistenceHandle, + config?: Partial, + context?: AgentLaunchContext, + ): Promise { + this.lastLaunchContext = context; + const session = await super.resumeSession(handle, config, context); + session.describePersistence = () => ({ provider, sessionId: handle.sessionId }); + return session; + } + } + + const client = new LaunchEnvClient(provider); + let storage = new AgentStorage(storagePath, logger); + let manager = new AgentManager({ clients: { [provider]: client }, registry: storage, logger }); + const env = { XDG_DATA_HOME: join(workdir, "agent-data"), CUSTOM_EMPTY: "" }; + const expectedEnv = { ...env }; + const agent = await manager.createAgent({ provider, cwd: workdir }, undefined, { + workspaceId: undefined, + env, + }); + onTestFinished(async () => { + await manager.closeAgent(agent.id); + await manager.flush(); + rmSync(workdir, { recursive: true, force: true }); + }); + env.XDG_DATA_HOME = "caller-mutated"; + + await manager.closeAgent(agent.id); + await manager.flush(); + + if (!hasHandle) { + const record = await storage.get(agent.id); + if (!record) throw new Error("Created agent was not persisted"); + await storage.upsert({ ...record, persistence: null }); + } + + // Fresh storage and manager instances must read the environment from disk. + for (let restart = 0; restart < 2; restart += 1) { + storage = new AgentStorage(storagePath, logger); + manager = new AgentManager({ clients: { [provider]: client }, registry: storage, logger }); + const resumed = await ensureAgentLoaded(agent.id, { + agentManager: manager, + agentStorage: storage, + logger, + }); + expect(client.lastLaunchContext).toEqual({ + agentId: agent.id, + env: { ...expectedEnv, PASEO_AGENT_ID: agent.id, PASEO_AGENT_CWD: workdir }, + }); + await manager.reloadAgentSession(agent.id); + expect(client.lastLaunchContext).toEqual({ + agentId: agent.id, + env: { ...expectedEnv, PASEO_AGENT_ID: agent.id, PASEO_AGENT_CWD: workdir }, + }); + expect(toAgentPayload(resumed)).not.toHaveProperty("launchEnv"); + expect(toAgentPayload(resumed).persistence?.metadata).not.toHaveProperty("launchEnv"); + await manager.closeAgent(agent.id); + await manager.flush(); + } + }, +); + test("createAgent passes persistSession to provider create options", async () => { const workdir = mkdtempSync(join(tmpdir(), "agent-manager-test-")); const storagePath = join(workdir, "agents"); diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index 966542ff62..46c822ea2d 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -421,6 +421,8 @@ interface ManagedAgentBase { owner?: AgentOwner; capabilities: AgentCapabilityFlags; config: AgentSessionConfig; + /** Explicit launch overrides, before per-opening hooks and daemon-owned variables. */ + launchEnv?: Record; runtimeInfo?: AgentRuntimeInfo; createdAt: Date; updatedAt: Date; @@ -1399,6 +1401,7 @@ export class AgentManager { initialTitle: options.initialTitle, workspaceId: options.workspaceId, owner: options.owner, + launchEnv: options.env ? { ...options.env } : undefined, historyPrimed: true, }); if (!agent.internal) { @@ -1487,10 +1490,11 @@ export class AgentManager { : resumeOptions; const purpose = currentResumeOptions?.purpose ?? "interactive"; + const launchEnv = record?.launchEnv; const { storedConfig, launchConfig, paseoToolPolicy } = await this.prepareSessionConfig( mergedConfig, resolvedAgentId, - { purpose }, + { purpose, env: launchEnv }, ); const client = this.requireClient(handle.provider); const available = await client.isAvailable(); @@ -1505,7 +1509,7 @@ export class AgentManager { client, storedConfig.cwd, paseoToolPolicy, - undefined, + launchEnv, { reason: "resume", purpose, @@ -1524,6 +1528,7 @@ export class AgentManager { await this.requireExternalMcpSupport(session, providerLaunchConfig, launchContext); return this.registerSession(session, storedConfig, resolvedAgentId, { ...options, + launchEnv, persistence: handle, restoring: true, }); @@ -1661,6 +1666,7 @@ export class AgentManager { const { storedConfig, launchConfig, paseoToolPolicy } = await this.prepareSessionConfig( refreshConfig, agentId, + { env: existing.launchEnv }, ); const hadPreviousPaseoToolPolicy = this.paseoToolPolicies.has(agentId); const previousPaseoToolPolicy = this.paseoToolPolicies.get(agentId); @@ -1669,7 +1675,7 @@ export class AgentManager { client, storedConfig.cwd, paseoToolPolicy, - undefined, + existing.launchEnv, { reason: "refresh", purpose: "interactive", @@ -1720,6 +1726,7 @@ export class AgentManager { labels: existing.labels, workspaceId: existing.workspaceId, owner: existing.owner, + launchEnv: existing.launchEnv, createdAt: existing.createdAt, updatedAt: existing.updatedAt, lastUserMessageAt: existing.lastUserMessageAt, @@ -3763,6 +3770,7 @@ export class AgentManager { publishWhenReady?: boolean; workspaceId?: string; owner?: AgentOwner; + launchEnv?: Record; }, ): Promise { let registered = false; @@ -3948,6 +3956,7 @@ export class AgentManager { persistence?: AgentPersistenceHandle; workspaceId?: string; owner?: AgentOwner; + launchEnv?: Record; } | undefined; }): ActiveManagedAgent { @@ -3958,6 +3967,7 @@ export class AgentManager { cwd: config.cwd, workspaceId: options?.workspaceId, owner: options?.owner, + launchEnv: options?.launchEnv, session, capabilities: session.capabilities, config, diff --git a/packages/server/src/server/agent/agent-projections.ts b/packages/server/src/server/agent/agent-projections.ts index 7d154e9c14..b388143d8e 100644 --- a/packages/server/src/server/agent/agent-projections.ts +++ b/packages/server/src/server/agent/agent-projections.ts @@ -95,6 +95,7 @@ export function toStoredAgentRecord( lastStatus: agent.lifecycle, lastModeId: agent.currentModeId ?? config?.modeId ?? null, config: config ?? null, + launchEnv: agent.launchEnv ? { ...agent.launchEnv } : undefined, runtimeInfo, features: normalizeFeatures(agent.features), persistence, diff --git a/packages/server/src/server/agent/agent-storage.ts b/packages/server/src/server/agent/agent-storage.ts index be94a31d49..a097bd7f82 100644 --- a/packages/server/src/server/agent/agent-storage.ts +++ b/packages/server/src/server/agent/agent-storage.ts @@ -54,8 +54,10 @@ const STORED_AGENT_SCHEMA = z.object({ title: z.string().nullable().optional(), labels: z.record(z.string(), z.string()).default({}), lastStatus: AgentStatusSchema.default("closed"), + resumeOnStartup: z.boolean().optional(), lastModeId: z.string().nullable().optional(), config: SERIALIZABLE_CONFIG_SCHEMA, + launchEnv: z.record(z.string(), z.string()).optional(), runtimeInfo: z .object({ provider: z.string(), @@ -259,6 +261,8 @@ export class AgentStorage { if (existing && existing.archivedAt !== undefined) { record.archivedAt = existing.archivedAt; } + record.resumeOnStartup = + existing?.resumeOnStartup && agent.lifecycle !== "idle" && agent.lifecycle !== "error"; return record; }); } diff --git a/packages/server/src/server/agent/finish-subscriptions/internal/observation.ts b/packages/server/src/server/agent/finish-subscriptions/internal/observation.ts index 887a4ba075..7abe483cf4 100644 --- a/packages/server/src/server/agent/finish-subscriptions/internal/observation.ts +++ b/packages/server/src/server/agent/finish-subscriptions/internal/observation.ts @@ -13,6 +13,8 @@ import type { FinishObservation } from "../index.js"; export function createFinishObservation(input: { agentManager: AgentManager; agentStorage: AgentStorage; + /** A child chosen for restart recovery reports its state only after its resume was sent. */ + waitForResume(agentId: string, signal: AbortSignal): Promise; messages(): AgentMessageDelivery; hosts(): ToolHosts; serverId: string; @@ -24,6 +26,7 @@ export function createFinishObservation(input: { hosts: input.hosts, local: { async wait(agentId, signal) { + await input.waitForResume(agentId, signal); await input.messages().waitForDispatch(agentId, signal); signal.throwIfAborted(); const live = agentManager.getAgent(agentId); @@ -52,6 +55,7 @@ export function createFinishObservation(input: { }; }, async observe(agentId, handler, signal, onError) { + await input.waitForResume(agentId, signal); const stored = await agentStorage.get(agentId); let updates = Promise.resolve(); const publish = (snapshot: AgentSnapshotPayload | null, event?: AgentStreamEvent) => { diff --git a/packages/server/src/server/agent/mcp-server.test.ts b/packages/server/src/server/agent/mcp-server.test.ts index 3b72c8805a..86ee383f73 100644 --- a/packages/server/src/server/agent/mcp-server.test.ts +++ b/packages/server/src/server/agent/mcp-server.test.ts @@ -881,6 +881,7 @@ async function createAgentMcpServer( logger: options.logger, ...createFinishObservation({ ...options, + waitForResume: async () => {}, messages: () => messages, serverId: options.serverId ?? "self", hosts: () => { diff --git a/packages/server/src/server/agent/providers/opencode-bridge.local.e2e.test.ts b/packages/server/src/server/agent/providers/opencode-bridge.local.e2e.test.ts index aeb87388fd..749374b29f 100644 --- a/packages/server/src/server/agent/providers/opencode-bridge.local.e2e.test.ts +++ b/packages/server/src/server/agent/providers/opencode-bridge.local.e2e.test.ts @@ -461,9 +461,19 @@ test.each([ process.platform === "win32" ? `${windowsPackage}-${process.arch}@${cliPackage.slice(cliPackage.lastIndexOf("@") + 1)}` : cliPackage; + // npm abandons a stalled registry download only after its 5 minute default, past this + // test's budget, and the killed install keeps the fixture locked. Retry stalls sooner. await execCommand( "npm", - ["install", "--prefix", root, "--no-audit", "--no-fund", installPackage], + [ + "install", + "--prefix", + root, + "--no-audit", + "--no-fund", + "--fetch-timeout=30000", + installPackage, + ], { cwd: root, timeout: 180_000, diff --git a/packages/server/src/server/agent/restart-recovery/index.test.ts b/packages/server/src/server/agent/restart-recovery/index.test.ts new file mode 100644 index 0000000000..0b1658b47d --- /dev/null +++ b/packages/server/src/server/agent/restart-recovery/index.test.ts @@ -0,0 +1,105 @@ +import { expect, test } from "vitest"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { AgentStorage, parseStoredAgentRecord } from "../agent-storage.js"; +import { createTestLogger } from "../../../test-utils/test-logger.js"; +import { createRestartRecovery } from "./index.js"; + +test("recovery saves intent before normalization, clears before dispatch, and resumes each agent independently", async () => { + const root = await mkdtemp(join(tmpdir(), "restart-recovery-")); + try { + const storage = new AgentStorage(root, createTestLogger()); + for (const [id, lastStatus] of [ + ["broken", "running"], + ["stuck", "running"], + ["working", "running"], + ["idle", "idle"], + ["initializing", "initializing"], + ] as const) { + await storage.upsert( + parseStoredAgentRecord({ + id, + lastStatus, + provider: "codex", + cwd: root, + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + }), + ); + } + const dispatched: string[] = []; + const recovery = createRestartRecovery({ + storage, + settings: () => ({ enabled: true, prompt: "Continue verbatim.\n" }), + eligible: async () => true, + dispatch: async (id, prompt) => { + expect((await storage.get(id))?.resumeOnStartup).toBe(false); + if (id === "broken") throw new Error("unavailable"); + if (id === "stuck") return new Promise(() => {}); + dispatched.push(id + prompt); + }, + report: () => {}, + }); + await recovery.prepareStartup(); + expect((await storage.get("working"))?.resumeOnStartup).toBe(true); + expect((await storage.get("working"))?.lastStatus).toBe("closed"); + recovery.resumePending(); + const running = new AbortController().signal; + await recovery.waitForResume("broken", running); + await recovery.waitForResume("working", running); + await recovery.waitForResume("idle", running); + expect(dispatched).toEqual(["workingContinue verbatim.\n"]); + const stopped = new AbortController(); + stopped.abort(); + await expect(recovery.waitForResume("stuck", stopped.signal)).rejects.toBeDefined(); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("opt-out consumes pending recovery and excludes archived, private, owned and archived-workspace agents", async () => { + const root = await mkdtemp(join(tmpdir(), "restart-recovery-")); + try { + const storage = new AgentStorage(root, createTestLogger()); + for (const extra of [ + { id: "running" }, + { id: "archived", archivedAt: "today" }, + { id: "private", internal: true }, + { id: "owned", owner: { kind: "daemon", daemonId: "hub", executionId: "run" } }, + { id: "workspace", workspaceId: "archived" }, + ]) { + await storage.upsert( + parseStoredAgentRecord({ + lastStatus: "running", + provider: "codex", + cwd: root, + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + ...extra, + }), + ); + } + let enabled = true; + const dispatched: string[] = []; + const recovery = createRestartRecovery({ + storage, + settings: () => ({ enabled, prompt: "Resume working." }), + eligible: async (record) => record.workspaceId !== "archived", + dispatch: async (id) => { + dispatched.push(id); + }, + report: () => {}, + }); + await recovery.captureRunningAgents(); + expect((await storage.get("running"))?.resumeOnStartup).toBe(true); + enabled = false; + await recovery.prepareStartup(); + enabled = true; + recovery.resumePending(); + expect(dispatched).toEqual([]); + expect((await storage.list()).every((record) => !record.resumeOnStartup)).toBe(true); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/packages/server/src/server/agent/restart-recovery/index.ts b/packages/server/src/server/agent/restart-recovery/index.ts new file mode 100644 index 0000000000..dc4e7d90c7 --- /dev/null +++ b/packages/server/src/server/agent/restart-recovery/index.ts @@ -0,0 +1,81 @@ +import type { AgentStorage, StoredAgentRecord } from "../agent-storage.js"; +interface Dependencies { + storage: AgentStorage; + settings(): { enabled: boolean; prompt: string }; + eligible(record: StoredAgentRecord): Promise; + dispatch(agentId: string, prompt: string): Promise; + report(agentId: string, error: unknown): void; +} +export function createRestartRecovery(deps: Dependencies) { + // Candidates are chosen at startup; each settles once its resume was sent or abandoned. + const resuming = new Map; resolve(): void }>(); + const eligible = async (record: StoredAgentRecord) => + !record.archivedAt && !record.internal && !record.owner && (await deps.eligible(record)); + async function resume(agentId: string) { + const record = await deps.storage.get(agentId); + if (!record?.resumeOnStartup) return; + await deps.storage.upsert({ ...record, resumeOnStartup: false }); + if (!deps.settings().enabled || !(await eligible(record))) return; + await deps.dispatch(agentId, deps.settings().prompt); + } + return { + /** Choose candidates before anything else reads or repairs persisted running status. */ + async prepareStartup() { + for (const record of await deps.storage.list()) { + const pending = + deps.settings().enabled && + (record.resumeOnStartup === true || record.lastStatus === "running") && + (await eligible(record)); + await deps.storage.upsert({ + ...record, + resumeOnStartup: pending, + lastStatus: + record.lastStatus === "running" || record.lastStatus === "initializing" + ? "closed" + : record.lastStatus, + }); + if (pending) { + let resolve!: () => void; + const promise = new Promise((settle) => { + resolve = settle; + }); + resuming.set(record.id, { promise, resolve }); + } + } + }, + async captureRunningAgents() { + await deps.storage.flush(); + for (const record of await deps.storage.list()) { + if (record.lastStatus === "running" && (await eligible(record))) + await deps.storage.upsert({ ...record, resumeOnStartup: deps.settings().enabled }); + } + }, + /** Resume every candidate in the background; a slow provider holds back only its agent. */ + resumePending() { + for (const [agentId, settled] of resuming) { + void resume(agentId) + .catch((error) => deps.report(agentId, error)) + .finally(() => { + resuming.delete(agentId); + settled.resolve(); + }); + } + }, + /** Wait until this agent's resume was sent or abandoned. Others return at once. */ + async waitForResume(agentId: string, signal: AbortSignal) { + const settled = resuming.get(agentId); + if (!settled) return; + let abort!: () => void; + const aborted = new Promise((_resolve, reject) => { + abort = () => reject(signal.reason); + if (signal.aborted) abort(); + else signal.addEventListener("abort", abort, { once: true }); + }); + try { + await Promise.race([settled.promise, aborted]); + } finally { + signal.removeEventListener("abort", abort); + } + }, + }; +} diff --git a/packages/server/src/server/bootstrap.smoke.test.ts b/packages/server/src/server/bootstrap.smoke.test.ts index f6304491ab..76fa8cc7d1 100644 --- a/packages/server/src/server/bootstrap.smoke.test.ts +++ b/packages/server/src/server/bootstrap.smoke.test.ts @@ -1069,7 +1069,7 @@ function probeWebSocketConnection( }); } -test("startup closes stale active records before serving status without resuming sessions", async () => { +test("disabled recovery closes stale active records without resuming sessions", async () => { const root = await mkdtemp(path.join(os.tmpdir(), "paseo-stale-status-")); const logger = pino({ level: "silent" }); const storagePath = path.join(root, ".paseo", "agents"); @@ -1121,6 +1121,7 @@ test("startup closes stale active records before serving status without resuming let sessionsCreated = 0; const handle = await createTestPaseoDaemon({ paseoHomeRoot: root, + resumeOnStartup: false, agentClients: createTestAgentClients({ beforeCreateSession: async () => { sessionsCreated++; @@ -1131,6 +1132,7 @@ test("startup closes stale active records before serving status without resuming try { const expected = records.map((record) => ({ ...record, + resumeOnStartup: false, lastStatus: record.lastStatus === "running" || record.lastStatus === "initializing" ? "closed" diff --git a/packages/server/src/server/bootstrap.ts b/packages/server/src/server/bootstrap.ts index 36ba9e2b06..8fe0f05b14 100644 --- a/packages/server/src/server/bootstrap.ts +++ b/packages/server/src/server/bootstrap.ts @@ -1,3 +1,5 @@ +import { createRestartRecovery } from "./agent/restart-recovery/index.js"; +import { sendPromptToAgent } from "./agent/agent-prompt.js"; import { createIdleRuntimeCleanup } from "./agent/idle-runtime-cleanup/index.js"; import { createFinishSubscriptions, @@ -464,6 +466,8 @@ export interface PaseoDaemonConfig { downloadTokenTtlMs?: number; agentProviderSettings?: AgentProviderRuntimeSettingsMap; idleRuntimeCleanup?: boolean; + resumeOnStartup?: boolean; + resumePrompt?: string; providerCatalogRefreshTimeoutMs?: number; metadataGeneration?: { providers?: Array<{ @@ -594,6 +598,8 @@ function createInitialMutableDaemonConfig(config: ResolvedDaemonSettings): Mutab autoArchiveAfterMerge: config.autoArchiveAfterMerge ?? false, enableTerminalAgentHooks: config.enableTerminalAgentHooks ?? false, idleRuntimeCleanup: config.idleRuntimeCleanup !== false, + resumeOnStartup: config.resumeOnStartup !== false, + resumePrompt: config.resumePrompt ?? "Resume working.", appendSystemPrompt: config.appendSystemPrompt ?? "", pluginsEnabled: config.pluginsEnabled ?? false, plugins: config.plugins ?? {}, @@ -1036,7 +1042,19 @@ export async function createPaseoDaemon( agentStorage, ); await agentStorage.initialize(); - await closeStaleAgentRecords(agentStorage); + const restartRecovery = createRestartRecovery({ + storage: agentStorage, + settings: () => ({ + enabled: daemonConfigStore.get().resumeOnStartup !== false, + prompt: daemonConfigStore.get().resumePrompt ?? "Resume working.", + }), + eligible: async (record) => + !record.workspaceId || !(await workspaceRegistry?.get(record.workspaceId))?.archivedAt, + dispatch: (agentId, prompt) => + sendPromptToAgent({ agentId, prompt, agentManager, agentStorage, logger, unarchive: false }), + report: (agentId, err) => logger.error({ agentId, err }, "Agent restart recovery failed"), + }); + await restartRecovery.prepareStartup(); logger.info({ elapsed: elapsed() }, "Agent storage initialized"); await bootstrapWorkspaceRegistries({ serverId, @@ -1470,6 +1488,7 @@ export async function createPaseoDaemon( ...createFinishObservation({ agentManager, agentStorage, + waitForResume: restartRecovery.waitForResume, serverId, logger, messages: () => { @@ -1869,6 +1888,7 @@ export async function createPaseoDaemon( pluginRuntime.bindPaseoSessionHost(wsServer); await pluginRuntime.start(); providerSnapshotManager.settlePluginProviders(); + restartRecovery.resumePending(); await finishSubscriptions.start(); wsServer.beginAcceptingConnections(); const relaySecurityLogger = logger.child({ module: "relay-security" }); @@ -1963,6 +1983,7 @@ export async function createPaseoDaemon( await finishSubscriptions.close(); await wsServer?.agentMessages.close(); agentManager.prepareForShutdown(); + await restartRecovery.captureRunningAgents(); await closeAllAgents(logger, agentManager); await withTimeout({ promise: pluginRuntime.drainEvents(), @@ -2029,16 +2050,6 @@ export async function createPaseoDaemon( }; } -async function closeStaleAgentRecords(agentStorage: AgentStorage): Promise { - // No provider runtimes are loaded at startup. Repair interrupted - // shutdowns before any status consumer sees the persisted active states. - for (const record of await agentStorage.list()) { - if (record.lastStatus === "running" || record.lastStatus === "initializing") { - await agentStorage.upsert({ ...record, lastStatus: "closed" }); - } - } -} - /** * Closing an agent asks its provider to close the session and waits for the * answer. A provider that never answers must not hold the daemon open, so a diff --git a/packages/server/src/server/config.ts b/packages/server/src/server/config.ts index add78aa7f5..3149fc6eb9 100644 --- a/packages/server/src/server/config.ts +++ b/packages/server/src/server/config.ts @@ -590,6 +590,8 @@ export type ResolvedDaemonSettings = Pick< | "relayRequireProtectedSecurity" | "appBaseUrl" | "idleRuntimeCleanup" + | "resumeOnStartup" + | "resumePrompt" | "providerCatalogRefreshTimeoutMs" | "metadataGeneration" | "providerOverrides" @@ -677,6 +679,7 @@ export function resolveReloadableConfig( relayEnabled: relay.enabled, relayRequireProtectedSecurity: relay.requireProtectedSecurity, idleRuntimeCleanup: persisted.agents?.idleRuntimeCleanup ?? true, + ...resolveRestartRecoveryConfig(persisted.agents), providerCatalogRefreshTimeoutMs: persisted.agents?.catalogRefreshTimeoutMs, metadataGeneration: persisted.agents?.metadataGeneration, providerOverrides: extractProviderOverrides( @@ -827,3 +830,10 @@ function resolveSpeechOverrideControlledPaths( if (env.PASEO_LOCAL_MODELS_DIR !== undefined) paths.push("providers.local.modelsDir"); return paths; } + +function resolveRestartRecoveryConfig(agents: PersistedConfig["agents"]) { + return { + resumeOnStartup: agents?.resumeOnStartup ?? true, + resumePrompt: agents?.resumePrompt ?? "Resume working.", + }; +} diff --git a/packages/server/src/server/daemon-config-store.test.ts b/packages/server/src/server/daemon-config-store.test.ts index e3b6f48895..89c3c7f977 100644 --- a/packages/server/src/server/daemon-config-store.test.ts +++ b/packages/server/src/server/daemon-config-store.test.ts @@ -940,6 +940,15 @@ describe("DaemonConfigStore", () => { await store.patch({ idleRuntimeCleanup: true }); expect(loadConfig(paseoHome, { env: {} }).idleRuntimeCleanup).toBe(true); + await store.patch({ resumeOnStartup: false, resumePrompt: "Keep going.\n" }); + expect(loadPersistedConfig(paseoHome).agents).toMatchObject({ + resumeOnStartup: false, + resumePrompt: "Keep going.\n", + }); + expect(loadConfig(paseoHome, { env: {} })).toMatchObject({ + resumeOnStartup: false, + resumePrompt: "Keep going.\n", + }); }); test("patch persists custom ACP provider overrides into config.json", async () => { diff --git a/packages/server/src/server/daemon-config-store.ts b/packages/server/src/server/daemon-config-store.ts index 57b9a6b916..1bd67822a3 100644 --- a/packages/server/src/server/daemon-config-store.ts +++ b/packages/server/src/server/daemon-config-store.ts @@ -29,6 +29,8 @@ interface SupportedMutableConfigPatch { autoArchiveAfterMerge?: boolean; enableTerminalAgentHooks?: boolean; idleRuntimeCleanup?: boolean; + resumeOnStartup?: boolean; + resumePrompt?: string; appendSystemPrompt?: string; terminalProfiles?: MutableDaemonConfig["terminalProfiles"]; agentProfiles?: MutableDaemonConfig["agentProfiles"]; @@ -193,6 +195,8 @@ const RELOADABLE_PATHS = [ "daemon.agentProfiles", "app.baseUrl", "agents.idleRuntimeCleanup", + "agents.resumeOnStartup", + "agents.resumePrompt", "agents.providers", "agents.catalogRefreshTimeoutMs", "agents.metadataGeneration", @@ -218,6 +222,8 @@ const PERSISTED_TO_MUTABLE_PATH = new Map([ ["daemon.agentProfiles", "agentProfiles"], ["app.baseUrl", "app.baseUrl"], ["agents.idleRuntimeCleanup", "idleRuntimeCleanup"], + ["agents.resumeOnStartup", "resumeOnStartup"], + ["agents.resumePrompt", "resumePrompt"], ["agents.providers", "providers"], ["agents.catalogRefreshTimeoutMs", "catalogRefreshTimeoutMs"], ["agents.metadataGeneration", "metadataGeneration"], @@ -292,6 +298,8 @@ function pickSupportedPatchFields(patch: MutableDaemonConfigPatch): SupportedMut ...(patch.enableTerminalAgentHooks !== undefined ? { enableTerminalAgentHooks: patch.enableTerminalAgentHooks } : {}), + ...(patch.resumeOnStartup !== undefined ? { resumeOnStartup: patch.resumeOnStartup } : {}), + ...(patch.resumePrompt !== undefined ? { resumePrompt: patch.resumePrompt } : {}), ...(patch.idleRuntimeCleanup !== undefined ? { idleRuntimeCleanup: patch.idleRuntimeCleanup } : {}), @@ -702,6 +710,7 @@ function mergeMutableAgentPatch( patch.providers === undefined && patch.metadataGeneration === undefined && patch.skills === undefined && + !hasRestartRecoveryPatch(patch) && patch.idleRuntimeCleanup === undefined && removeProviders.length === 0 ) { @@ -735,6 +744,7 @@ function mergeMutableAgentPatch( next["skills"] = { selection: patch.skills.selection }; } + Object.assign(next, restartRecoveryPatch(patch)); if (patch.idleRuntimeCleanup !== undefined) { next["idleRuntimeCleanup"] = patch.idleRuntimeCleanup; } @@ -771,3 +781,13 @@ function mergeMutableDaemonPatch( if (patch.agentProfiles !== undefined) next.agentProfiles = patch.agentProfiles; return Object.keys(next).length > 0 ? next : undefined; } + +function hasRestartRecoveryPatch(patch: SupportedMutableConfigPatch) { + return patch.resumeOnStartup !== undefined || patch.resumePrompt !== undefined; +} +function restartRecoveryPatch(patch: SupportedMutableConfigPatch) { + return { + ...(patch.resumeOnStartup !== undefined ? { resumeOnStartup: patch.resumeOnStartup } : {}), + ...(patch.resumePrompt !== undefined ? { resumePrompt: patch.resumePrompt } : {}), + }; +} diff --git a/packages/server/src/server/daemon-e2e/daemon-restart-resume.e2e.test.ts b/packages/server/src/server/daemon-e2e/daemon-restart-resume.e2e.test.ts index efc99c9b59..1658356eed 100644 --- a/packages/server/src/server/daemon-e2e/daemon-restart-resume.e2e.test.ts +++ b/packages/server/src/server/daemon-e2e/daemon-restart-resume.e2e.test.ts @@ -76,10 +76,14 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; import { DaemonClient } from "../test-utils/daemon-client.js"; -async function restartFixture(root: string) { +async function restartFixture( + root: string, + settings: { resumeOnStartup?: boolean; resumePrompt?: string } = {}, + fixture: { holdResume?: boolean } = {}, +) { const child = fork( fileURLToPath(new URL("../test-utils/finish-subscription-daemon.ts", import.meta.url)), - [root], + [root, JSON.stringify(settings), JSON.stringify(fixture)], { execArgv: ["--conditions=source", "--import", "tsx"], stdio: ["ignore", "pipe", "pipe", "ipc"], @@ -183,7 +187,25 @@ test.each([false, true])( await expect.poll(() => readPrompts(root), { timeout: 15000 }).toHaveLength(1); const prompts = await readPrompts(root); expect(prompts[0]).toContain(`Agent ${childId}`); - expect(prompts[0]).toContain("was closed"); + expect(prompts[0]).not.toContain("was closed"); + const recoveredPrompts = (await readFile(path.join(root, "all-prompts.jsonl"), "utf8")) + .trim() + .split("\n") + .map((line) => JSON.parse(line)); + expect(recoveredPrompts.filter((entry) => entry.prompt === "Resume working.")).toHaveLength( + 1, + ); + const restored = recoveredPrompts.find((entry) => entry.prompt === "Resume working.").config; + const original = recoveredPrompts.find((entry) => + String(entry.prompt).includes("HOLD_CHILD"), + ).config; + expect(restored).toMatchObject({ + provider: original.provider, + model: original.model, + modeId: original.modeId, + cwd: original.cwd, + }); + await expect .poll( async () => @@ -196,7 +218,7 @@ test.each([false, true])( client = new DaemonClient({ url: `ws://127.0.0.1:${second.port}/ws`, appVersion: "0.13.0" }); await client.connect(); await client.fetchAgents({ subscribe: {} }); - expect((await client.fetchAgent(childId))?.agent.status).toBe("closed"); + expect((await client.fetchAgent(childId))?.agent.status).toBe("idle"); await client.close(); client = undefined; await stopFixture(second.child, false); @@ -220,3 +242,120 @@ test.each([false, true])( }, 60000, ); + +test.each([false, true])( + "host restart recovery settings (enabled=%s)", + async (enabled) => { + const root = await mkdtemp(path.join(tmpdir(), "resume-settings-process-")); + const processes: ChildProcess[] = []; + let client: DaemonClient | undefined; + const settings = { resumeOnStartup: enabled, resumePrompt: "Continue exactly.\n" }; + try { + const first = await restartFixture(root, settings); + processes.push(first.child); + client = new DaemonClient({ url: `ws://127.0.0.1:${first.port}/ws`, appVersion: "0.13.0" }); + await client.connect(); + const working = await client.createAgent({ + provider: "claude", + cwd: first.cwd, + modeId: "full-access", + }); + const idle = await client.createAgent({ + provider: "claude", + cwd: first.cwd, + modeId: "full-access", + }); + await client.sendMessage(working.id, "HOLD_CHILD"); + await expect + .poll( + async () => + ( + await new AgentStorage(path.join(first.paseoHome, "agents"), createTestLogger()).get( + working.id, + ) + )?.lastStatus, + ) + .toBe("running"); + const original = await new AgentStorage( + path.join(first.paseoHome, "agents"), + createTestLogger(), + ).get(working.id); + await client.close(); + client = undefined; + await stopFixture(first.child, false); + const second = await restartFixture(root, settings); + processes.push(second.child); + client = new DaemonClient({ url: `ws://127.0.0.1:${second.port}/ws`, appVersion: "0.13.0" }); + await client.connect(); + const storage = new AgentStorage(path.join(second.paseoHome, "agents"), createTestLogger()); + // Resume runs in the background; it is done once the saved intent is consumed. + await expect.poll(async () => (await storage.get(working.id))?.resumeOnStartup).toBe(false); + const resumePrompts = async () => + (await readFile(path.join(root, "all-prompts.jsonl"), "utf8")) + .trim() + .split("\n") + .map((line) => JSON.parse(line)) + .filter((entry) => entry.prompt === settings.resumePrompt); + await expect.poll(resumePrompts).toHaveLength(enabled ? 1 : 0); + expect((await client.fetchAgent(idle.id))?.agent.status).toBe("closed"); + const restored = await storage.get(working.id); + expect(restored?.persistence?.sessionId).toBe(original?.persistence?.sessionId); + } finally { + await client?.close(); + for (const child of processes.toReversed()) await stopFixture(child, true); + await rm(root, { recursive: true, force: true }); + } + }, + 60000, +); + +test("a provider that is slow to reopen does not hold daemon startup", async () => { + const root = await mkdtemp(path.join(tmpdir(), "resume-background-process-")); + const processes: ChildProcess[] = []; + let client: DaemonClient | undefined; + try { + const first = await restartFixture(root); + processes.push(first.child); + client = new DaemonClient({ url: `ws://127.0.0.1:${first.port}/ws`, appVersion: "0.13.0" }); + await client.connect(); + const working = await client.createAgent({ + provider: "claude", + cwd: first.cwd, + modeId: "full-access", + }); + await client.sendMessage(working.id, "HOLD_CHILD"); + await expect + .poll( + async () => + ( + await new AgentStorage(path.join(first.paseoHome, "agents"), createTestLogger()).get( + working.id, + ) + )?.lastStatus, + ) + .toBe("running"); + await client.close(); + client = undefined; + await stopFixture(first.child, false); + + const second = await restartFixture(root, {}, { holdResume: true }); + processes.push(second.child); + client = new DaemonClient({ url: `ws://127.0.0.1:${second.port}/ws`, appVersion: "0.13.0" }); + await client.connect(); + expect((await client.fetchAgent(working.id))?.agent.id).toBe(working.id); + second.child.send("release-resume"); + await expect + .poll(async () => + (await readFile(path.join(root, "all-prompts.jsonl"), "utf8")) + .trim() + .split("\n") + .map((line) => JSON.parse(line).prompt) + .filter((prompt) => prompt === "Resume working."), + ) + .toHaveLength(1); + } finally { + await client?.close(); + for (const child of processes.toReversed()) await stopFixture(child, true); + await rm(root, { recursive: true, force: true }); + } +}, 30000); diff --git a/packages/server/src/server/persisted-config.ts b/packages/server/src/server/persisted-config.ts index 51bfb3d3a4..f7b3982513 100644 --- a/packages/server/src/server/persisted-config.ts +++ b/packages/server/src/server/persisted-config.ts @@ -348,6 +348,8 @@ export const PersistedConfigSchema = z .object({ providers: z.preprocess(normalizeAgentProviders, ProviderOverridesSchema).optional(), idleRuntimeCleanup: z.boolean().optional(), + resumeOnStartup: z.boolean().optional(), + resumePrompt: z.string().optional(), catalogRefreshTimeoutMs: z.number().int().positive().max(2_147_483_647).optional(), metadataGeneration: AgentMetadataGenerationSchema.optional(), skills: z.object({ selection: AgentSkillSelectionSchema.optional() }).strict().optional(), diff --git a/packages/server/src/server/test-utils/fake-agent-client.ts b/packages/server/src/server/test-utils/fake-agent-client.ts index 42ac0c7c79..4304a767e1 100644 --- a/packages/server/src/server/test-utils/fake-agent-client.ts +++ b/packages/server/src/server/test-utils/fake-agent-client.ts @@ -67,6 +67,7 @@ interface FakeAgentSessionOptions { export interface TestAgentClientOptions { beforeCreateSession?: (config: AgentSessionConfig) => Promise; + beforeResumeSession?: (handle: AgentPersistenceHandle) => Promise; closeSession?: () => Promise; onStartTurn?: (prompt: AgentPromptInput, config: AgentSessionConfig) => void; beforeTurnComplete?: (prompt: AgentPromptInput) => Promise; @@ -1254,6 +1255,7 @@ class FakeAgentClient implements AgentClient { overrides?: Partial, _launchContext?: AgentLaunchContext, ): Promise { + await this.options.beforeResumeSession?.(handle); const cfg: AgentSessionConfig = { provider: this.provider, cwd: overrides?.cwd ?? process.cwd(), diff --git a/packages/server/src/server/test-utils/finish-subscription-daemon.ts b/packages/server/src/server/test-utils/finish-subscription-daemon.ts index d35bc55ec8..eafe11e74a 100644 --- a/packages/server/src/server/test-utils/finish-subscription-daemon.ts +++ b/packages/server/src/server/test-utils/finish-subscription-daemon.ts @@ -9,18 +9,24 @@ const root = process.argv[2]; if (!root || !process.send) throw new Error("Expected isolated test home and IPC parent"); await mkdir(join(root, "static"), { recursive: true }); const held = Promise.withResolvers(); +const fixture = JSON.parse(process.argv[4] ?? "{}") as { holdResume?: boolean }; +const resumeReleased = Promise.withResolvers(); +if (!fixture.holdResume) resumeReleased.resolve(); const daemon = await createTestPaseoDaemon({ paseoHomeRoot: root, + ...JSON.parse(process.argv[3] ?? "{}"), staticDir: join(root, "static"), logger: pino({ level: "warn" }, pino.destination(join(root, "fixture.log"))), cleanup: false, mcpEnabled: true, agentClients: createTestAgentClients({ - onStartTurn: (prompt) => { + onStartTurn: (prompt, config) => { + void appendFile(join(root, "all-prompts.jsonl"), `${JSON.stringify({ prompt, config })}\n`); if (String(prompt).includes('kind="agent-notification"')) { void appendFile(join(root, "parent-prompts.jsonl"), `${JSON.stringify(prompt)}\n`); } }, + beforeResumeSession: () => resumeReleased.promise, beforeTurnComplete: (prompt) => String(prompt).includes("HOLD_CHILD") ? held.promise : Promise.resolve(), }), @@ -28,6 +34,7 @@ const daemon = await createTestPaseoDaemon({ process.send({ port: daemon.port, paseoHome: daemon.paseoHome, cwd: daemon.staticDir }); process.on("message", (message) => { if (message === "finish") held.resolve(); + if (message === "release-resume") resumeReleased.resolve(); if (message === "stop") { void daemon.close().then( () => process.exit(0), diff --git a/packages/server/src/server/test-utils/paseo-daemon.ts b/packages/server/src/server/test-utils/paseo-daemon.ts index a1f8369b59..766fd49919 100644 --- a/packages/server/src/server/test-utils/paseo-daemon.ts +++ b/packages/server/src/server/test-utils/paseo-daemon.ts @@ -52,6 +52,8 @@ interface TestPaseoDaemonOptions { trustedProxies?: PaseoDaemonConfig["trustedProxies"]; agentProfiles?: AgentProfile[]; autoArchiveAfterMerge?: boolean; + resumeOnStartup?: boolean; + resumePrompt?: string; pluginsEnabled?: PaseoDaemonConfig["pluginsEnabled"]; builtinPlugins?: BuiltinPluginLoader; plugins?: PaseoDaemonConfig["plugins"]; @@ -226,6 +228,8 @@ async function prepareTestDaemonConfig( downloadTokenTtlMs: options.downloadTokenTtlMs, agentProfiles: options.agentProfiles, autoArchiveAfterMerge: options.autoArchiveAfterMerge, + resumeOnStartup: options.resumeOnStartup, + resumePrompt: options.resumePrompt, pluginsEnabled: options.pluginsEnabled, plugins: options.plugins, }; diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index 6705c1cdd9..b7024a638b 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -2013,6 +2013,7 @@ export class VoiceAssistantWebSocketServer { skillManagement: true, // COMPAT(idleRuntimeCleanupSetting): added in v0.13.0, remove gate after 2027-04-26. idleRuntimeCleanupSetting: true, + resumeOnStartupSetting: true, // COMPAT(terminalRestoreModes): added in v0.1.81, remove gate after 2026-11-23. "terminal-restore-modes": true, // COMPAT(terminalInputModeReplay): added in v0.2.6, remove gate after 2027-02-02. diff --git a/packages/server/src/server/workspace-git-service.test.ts b/packages/server/src/server/workspace-git-service.test.ts index f3571f9932..4e6acff9cd 100644 --- a/packages/server/src/server/workspace-git-service.test.ts +++ b/packages/server/src/server/workspace-git-service.test.ts @@ -1171,10 +1171,14 @@ describe("WorkspaceGitServiceImpl", () => { const subscription = service.registerWorkspace({ cwd: REPO_CWD }, listener); await vi.waitFor(() => { expect(getCheckoutSnapshotFacts).toHaveBeenCalledTimes(1); + expect(service.getMetrics().fetchInFlightCount).toBe(1); }); releaseFetch.resolve(); - await flushPromises(); + // The refresh debounce starts when the fetch result is applied, not when it is released. + await vi.waitFor(() => { + expect(service.getMetrics().fetchInFlightCount).toBe(0); + }); await vi.advanceTimersByTimeAsync(1_000); await vi.waitFor(() => { expect(getCheckoutRefDerivedState).toHaveBeenCalledTimes(1); diff --git a/packages/website/public/schemas/paseo.config.v1.json b/packages/website/public/schemas/paseo.config.v1.json index c1c32ed20a..1b74066bae 100644 --- a/packages/website/public/schemas/paseo.config.v1.json +++ b/packages/website/public/schemas/paseo.config.v1.json @@ -513,6 +513,12 @@ "idleRuntimeCleanup": { "type": "boolean" }, + "resumeOnStartup": { + "type": "boolean" + }, + "resumePrompt": { + "type": "string" + }, "catalogRefreshTimeoutMs": { "type": "integer", "exclusiveMinimum": 0, From 2f0fb2a8bafbcfa96bd5489447ac0f316dd1c020 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Thu, 29 Oct 2026 00:50:24 +0700 Subject: [PATCH 096/173] Bring 0.14.0-beta.2 versions and changelog to main (#8139) * docs(changelog): fold 0.14.0-beta.2 UI fixes into the 0.14.0 entry (cherry picked from commit 28bb7e29be2e8468cd323b55c6dd07d8f047f340) * chore(release): cut 0.14.0-beta.2 (cherry picked from commit 1a05491be51d59f53f2e4a93cda2f152704690db) * docs(changelog): keep unreleased main changes out of the 0.14.0-beta.2 entry The beta.2 tag was cut from a selective hotfix branch, so #8100, #8117 and #8081 are on main but not in beta.2. Every changelog parser (app, website, release-notes sync) skips the preamble, so listing them there keeps them out of the beta.2 release body and What's new until the next release entry absorbs them. --- CHANGELOG.md | 24 +++++++--- CHANGELOG.zh-CN.md | 22 +++++++--- package-lock.json | 56 ++++++++++++------------ package.json | 2 +- packages/app/package.json | 2 +- packages/cli/package.json | 8 ++-- packages/client/package.json | 6 +-- packages/desktop/package.json | 2 +- packages/expo-two-way-audio/package.json | 2 +- packages/highlight/package.json | 2 +- packages/plugin/package.json | 10 ++--- packages/protocol/package.json | 2 +- packages/relay/package.json | 2 +- packages/server/package.json | 12 ++--- packages/website/package.json | 2 +- plugins/package.json | 2 +- 16 files changed, 89 insertions(+), 67 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c790c6f80..4a11f55d5b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,17 @@ # Changelog -## 0.14.0-beta.1 - 2026-10-27 +Not released yet. These changes are on `main` but not in 0.14.0-beta.2; the next release entry includes them. + +Added: + +- Copy gitignored files selected by `.worktreeinclude` into new worktrees before setup and agents, using the built-in `worktree-include` plugin ([#8100](https://github.com/getpaseo/paseo/pull/8100)) +- Let plugins choose worktree paths and creation options through `worktree.create.before`, with listing, archive, deletion, and recovery at custom locations; includes a sibling-directory placement example ([#8117](https://github.com/getpaseo/paseo/pull/8117)) + +Improved: + +- Added `server.addHook` with `subject.operation.position` names and the awaited `worktree.create.after` hook before setup and agents; deprecated the previous plugin hook registration methods without changing their behavior ([#8081](https://github.com/getpaseo/paseo/pull/8081)) + +## 0.14.0-beta.2 - 2026-10-28 Plugins can now add tools to individual agents and configure their MCP servers when sessions open. @@ -10,10 +21,8 @@ Voice settings now let you configure speech providers and download local models ### Added -- Copy gitignored files selected by `.worktreeinclude` into new worktrees before setup and agents, using the built-in `worktree-include` plugin ([#8100](https://github.com/getpaseo/paseo/pull/8100)) -- Let plugins choose worktree paths and creation options through `worktree.create.before`, with listing, archive, deletion, and recovery at custom locations; includes a sibling-directory placement example ([#8117](https://github.com/getpaseo/paseo/pull/8117)) - Let plugins give tools to specific agents ([#7938](https://github.com/getpaseo/paseo/pull/7938)) -- Added collapse and expand controls for completed conversation turns ([#7785](https://github.com/getpaseo/paseo/pull/7785), [#7990](https://github.com/getpaseo/paseo/pull/7990), [#8026](https://github.com/getpaseo/paseo/pull/8026) by [@akaready](https://github.com/akaready), [@Dey11](https://github.com/Dey11), [@Sebeb](https://github.com/Sebeb), [@Waishnav](https://github.com/Waishnav)) +- Added Chat display settings that group tool calls or collapse completed conversation turns ([#7785](https://github.com/getpaseo/paseo/pull/7785), [#7990](https://github.com/getpaseo/paseo/pull/7990), [#8026](https://github.com/getpaseo/paseo/pull/8026), [#8042](https://github.com/getpaseo/paseo/pull/8042), [#8109](https://github.com/getpaseo/paseo/pull/8109) by [@akaready](https://github.com/akaready), [@Dey11](https://github.com/Dey11), [@Sebeb](https://github.com/Sebeb), [@Waishnav](https://github.com/Waishnav)) - Let plugins add MCP servers whenever an agent session opens ([#7983](https://github.com/getpaseo/paseo/pull/7983)) - Added downloadable local speech models in Voice settings, including SenseVoice and Whisper for Chinese dictation ([#7295](https://github.com/getpaseo/paseo/pull/7295)) - Added a choice of Enter or ⌘/Ctrl+Enter to send messages ([#5503](https://github.com/getpaseo/paseo/pull/5503) by [@lukelabonte](https://github.com/lukelabonte)) @@ -23,10 +32,9 @@ Voice settings now let you configure speech providers and download local models ### Improved -- Added `server.addHook` with `subject.operation.position` names and the awaited `worktree.create.after` hook before setup and agents; deprecated the previous plugin hook registration methods without changing their behavior ([#8081](https://github.com/getpaseo/paseo/pull/8081)) - - Release eligible agent runtimes after one idle hour, resuming the saved session on the next prompt ([#7782](https://github.com/getpaseo/paseo/pull/7782)) - Added a link back to the parent in subagent panes ([#7784](https://github.com/getpaseo/paseo/pull/7784)) +- Opened subagents in place of the subagent list on phones, with Back returning to the list ([#8093](https://github.com/getpaseo/paseo/pull/8093)) - Added clickable links and selectable descriptions to question cards ([#7419](https://github.com/getpaseo/paseo/pull/7419) by [@NoSync](https://github.com/NoSync)) - Kept large Import session lists responsive on web ([#7872](https://github.com/getpaseo/paseo/pull/7872) by [@royenheart](https://github.com/royenheart)) - Enlarged project and workspace menu buttons on phones ([#7928](https://github.com/getpaseo/paseo/pull/7928)) @@ -52,10 +60,12 @@ Voice settings now let you configure speech providers and download local models - Fixed outside-folder links replacing Files with an access error ([#7726](https://github.com/getpaseo/paseo/pull/7726) by [@jtomaszewski](https://github.com/jtomaszewski)) - Fixed command suggestions overlapping a growing Composer on phones ([#7910](https://github.com/getpaseo/paseo/pull/7910)) - Fixed bare Markdown URLs losing ports or stopping at colons in paths ([#7859](https://github.com/getpaseo/paseo/pull/7859) by [@mariotaku](https://github.com/mariotaku)) -- Fixed inline code sizing inside emphasis, links and headings ([#7889](https://github.com/getpaseo/paseo/pull/7889)) +- Fixed inline code sizing inside emphasis, links and headings ([#7889](https://github.com/getpaseo/paseo/pull/7889), [#8088](https://github.com/getpaseo/paseo/pull/8088)) +- Fixed compact navigation sizes and a cramped Settings detail pane in docked windows 600–719 wide ([#8052](https://github.com/getpaseo/paseo/pull/8052) by [@zeyugao](https://github.com/zeyugao)) - Fixed Settings losing the selected host or sidebar scroll position between sections ([#7893](https://github.com/getpaseo/paseo/pull/7893), [#7899](https://github.com/getpaseo/paseo/pull/7899) by [@bingqilinweimaotai](https://github.com/bingqilinweimaotai), [@wangnan0916](https://github.com/wangnan0916)) - Fixed OpenCode v2 subagent rows missing model and token details ([#7799](https://github.com/getpaseo/paseo/pull/7799) by [@Davnn1](https://github.com/Davnn1)) - Fixed file-link tooltips staying over the preview after leaving a chat ([#7842](https://github.com/getpaseo/paseo/pull/7842)) +- Fixed model discovery errors touching the model picker edges ([#8039](https://github.com/getpaseo/paseo/pull/8039) by [@ilteoood](https://github.com/ilteoood)) - Fixed model selectors staying open over Settings ([#7783](https://github.com/getpaseo/paseo/pull/7783) by [@ragokan](https://github.com/ragokan)) ### Notes diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index 062e46cd13..a089401f39 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -1,6 +1,17 @@ # 更新日志 -## 0.14.0-beta.1 - 2026-10-27 +尚未发布。以下变更已合入 `main`,但不包含在 0.14.0-beta.2 中;下一个版本的条目会包含它们。 + +新增: + +- 在 setup 和 Agent 启动前,使用内置的 `worktree-include` 插件将 `.worktreeinclude` 选中的被 gitignore 忽略的文件复制到新工作树 ([#8100](https://github.com/getpaseo/paseo/pull/8100)) +- 插件可通过 `worktree.create.before` 选择工作树路径和创建选项,自定义位置的工作树支持列出、归档、删除和恢复;附带同级目录放置示例 ([#8117](https://github.com/getpaseo/paseo/pull/8117)) + +改进: + +- 新增采用 `subject.operation.position` 命名的 `server.addHook` 和在 setup 及 Agent 之前等待的 `worktree.create.after` 钩子,弃用原有的插件钩子注册方法并保留原有行为 ([#8081](https://github.com/getpaseo/paseo/pull/8081)) + +## 0.14.0-beta.2 - 2026-10-28 插件现在可以为单个 Agent 添加工具,并在会话打开时配置其 MCP 服务器。 @@ -11,7 +22,7 @@ ### 新增 - 插件现在可以为特定 Agent 提供工具 ([#7938](https://github.com/getpaseo/paseo/pull/7938)) -- 新增已完成对话轮次的折叠和展开功能 ([#7785](https://github.com/getpaseo/paseo/pull/7785), [#7990](https://github.com/getpaseo/paseo/pull/7990), [#8026](https://github.com/getpaseo/paseo/pull/8026) by [@akaready](https://github.com/akaready), [@Dey11](https://github.com/Dey11), [@Sebeb](https://github.com/Sebeb), [@Waishnav](https://github.com/Waishnav)) +- 新增“聊天显示”设置,可将工具调用分组或折叠已完成的对话轮次 ([#7785](https://github.com/getpaseo/paseo/pull/7785), [#7990](https://github.com/getpaseo/paseo/pull/7990), [#8026](https://github.com/getpaseo/paseo/pull/8026), [#8042](https://github.com/getpaseo/paseo/pull/8042), [#8109](https://github.com/getpaseo/paseo/pull/8109) by [@akaready](https://github.com/akaready), [@Dey11](https://github.com/Dey11), [@Sebeb](https://github.com/Sebeb), [@Waishnav](https://github.com/Waishnav)) - 插件现在可以在每次打开 Agent 会话时添加 MCP 服务器 ([#7983](https://github.com/getpaseo/paseo/pull/7983)) - 语音设置新增可下载的本地语音模型,支持使用 SenseVoice 和 Whisper 进行中文听写 ([#7295](https://github.com/getpaseo/paseo/pull/7295)) - 新增 Enter 或 ⌘/Ctrl+Enter 发送消息的快捷键选项 ([#5503](https://github.com/getpaseo/paseo/pull/5503) by [@lukelabonte](https://github.com/lukelabonte)) @@ -21,10 +32,9 @@ ### 改进 -- 新增采用 `subject.operation.position` 命名的 `server.addHook` 和在 setup 及 Agent 之前等待的 `worktree.create.after` 钩子,弃用原有的插件钩子注册方法并保留原有行为 ([#8081](https://github.com/getpaseo/paseo/pull/8081)) - - 符合条件的 Agent 运行时空闲一小时后释放,下次发送提示词时恢复已保存的会话 ([#7782](https://github.com/getpaseo/paseo/pull/7782)) - 在子 Agent 窗格中新增返回父 Agent 的链接 ([#7784](https://github.com/getpaseo/paseo/pull/7784)) +- 在手机上从子 Agent 列表打开子 Agent 时直接替换列表,点按“返回”可回到列表 ([#8093](https://github.com/getpaseo/paseo/pull/8093)) - 问题卡片新增可点击链接和可选中的描述文本 ([#7419](https://github.com/getpaseo/paseo/pull/7419) by [@NoSync](https://github.com/NoSync)) - 减少网页端长会话导入列表的操作卡顿 ([#7872](https://github.com/getpaseo/paseo/pull/7872) by [@royenheart](https://github.com/royenheart)) - 增大手机上项目和工作区菜单按钮的点击区域 ([#7928](https://github.com/getpaseo/paseo/pull/7928)) @@ -50,10 +60,12 @@ - 修复工作区外的文件夹链接使 Files 显示访问错误的问题 ([#7726](https://github.com/getpaseo/paseo/pull/7726) by [@jtomaszewski](https://github.com/jtomaszewski)) - 修复手机上命令建议与不断增高的 Composer 重叠的问题 ([#7910](https://github.com/getpaseo/paseo/pull/7910)) - 修复 Markdown 裸链接丢失端口或在路径冒号处截断的问题 ([#7859](https://github.com/getpaseo/paseo/pull/7859) by [@mariotaku](https://github.com/mariotaku)) -- 修复强调、链接和标题中行内代码的字号问题 ([#7889](https://github.com/getpaseo/paseo/pull/7889)) +- 修复强调、链接和标题中行内代码的字号问题 ([#7889](https://github.com/getpaseo/paseo/pull/7889), [#8088](https://github.com/getpaseo/paseo/pull/8088)) +- 修复宽度 600–719 的停靠布局使用紧凑导航尺寸、设置详情面板过窄的问题 ([#8052](https://github.com/getpaseo/paseo/pull/8052) by [@zeyugao](https://github.com/zeyugao)) - 修复切换设置页面时丢失已选主机或侧栏滚动位置的问题 ([#7893](https://github.com/getpaseo/paseo/pull/7893), [#7899](https://github.com/getpaseo/paseo/pull/7899) by [@bingqilinweimaotai](https://github.com/bingqilinweimaotai), [@wangnan0916](https://github.com/wangnan0916)) - 修复 OpenCode v2 子 Agent 行缺少模型和 token 详情的问题 ([#7799](https://github.com/getpaseo/paseo/pull/7799) by [@Davnn1](https://github.com/Davnn1)) - 修复离开聊天后文件链接提示仍遮挡预览的问题 ([#7842](https://github.com/getpaseo/paseo/pull/7842)) +- 修复模型发现错误信息紧贴模型选择器边缘的问题 ([#8039](https://github.com/getpaseo/paseo/pull/8039) by [@ilteoood](https://github.com/ilteoood)) - 修复模型选择器在打开设置后仍然显示的问题 ([#7783](https://github.com/getpaseo/paseo/pull/7783) by [@ragokan](https://github.com/ragokan)) ### 说明 diff --git a/package-lock.json b/package-lock.json index 5017de5705..0930535606 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "paseo", - "version": "0.14.0-beta.1", + "version": "0.14.0-beta.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "paseo", - "version": "0.14.0-beta.1", + "version": "0.14.0-beta.2", "hasInstallScript": true, "license": "Apache-2.0", "workspaces": [ @@ -37590,7 +37590,7 @@ }, "packages/app": { "name": "@getpaseo/app", - "version": "0.14.0-beta.1", + "version": "0.14.0-beta.2", "dependencies": { "@codemirror/commands": "6.10.4", "@codemirror/language": "6.12.4", @@ -39793,12 +39793,12 @@ }, "packages/cli": { "name": "@getpaseo/cli", - "version": "0.14.0-beta.1", + "version": "0.14.0-beta.2", "dependencies": { "@clack/prompts": "^1.0.0", - "@getpaseo/client": "0.14.0-beta.1", - "@getpaseo/protocol": "0.14.0-beta.1", - "@getpaseo/server": "0.14.0-beta.1", + "@getpaseo/client": "0.14.0-beta.2", + "@getpaseo/protocol": "0.14.0-beta.2", + "@getpaseo/server": "0.14.0-beta.2", "chalk": "^5.3.0", "commander": "^12.0.0", "mime-types": "^2.1.35", @@ -40045,10 +40045,10 @@ }, "packages/client": { "name": "@getpaseo/client", - "version": "0.14.0-beta.1", + "version": "0.14.0-beta.2", "dependencies": { - "@getpaseo/protocol": "0.14.0-beta.1", - "@getpaseo/relay": "0.14.0-beta.1", + "@getpaseo/protocol": "0.14.0-beta.2", + "@getpaseo/relay": "0.14.0-beta.2", "ws": "^8.20.0", "zod": "^4.4.3" }, @@ -40060,7 +40060,7 @@ }, "packages/desktop": { "name": "@getpaseo/desktop", - "version": "0.14.0-beta.1", + "version": "0.14.0-beta.2", "license": "Apache-2.0", "dependencies": { "@getpaseo/cli": "*", @@ -40304,7 +40304,7 @@ }, "packages/expo-two-way-audio": { "name": "@getpaseo/expo-two-way-audio", - "version": "0.14.0-beta.1", + "version": "0.14.0-beta.2", "license": "MIT", "devDependencies": { "@types/jest": "^29.5.14", @@ -40350,7 +40350,7 @@ }, "packages/highlight": { "name": "@getpaseo/highlight", - "version": "0.14.0-beta.1", + "version": "0.14.0-beta.2", "dependencies": { "@codemirror/language": "6.12.4", "@codemirror/legacy-modes": "^6.5.3", @@ -40379,15 +40379,15 @@ }, "packages/plugin": { "name": "@getpaseo/plugin", - "version": "0.14.0-beta.1", + "version": "0.14.0-beta.2", "dependencies": { "@agentclientprotocol/sdk": "^1.4.0", "i18next": "^26.3.0", "use-sync-external-store": "^1.6.0" }, "devDependencies": { - "@getpaseo/client": "0.14.0-beta.1", - "@getpaseo/protocol": "0.14.0-beta.1", + "@getpaseo/client": "0.14.0-beta.2", + "@getpaseo/protocol": "0.14.0-beta.2", "@types/node": "^20.9.0", "@types/react": "~19.2.0", "react": "19.2.3", @@ -40397,8 +40397,8 @@ "zod": "^4.4.3" }, "peerDependencies": { - "@getpaseo/client": "0.14.0-beta.1", - "@getpaseo/protocol": "0.14.0-beta.1", + "@getpaseo/client": "0.14.0-beta.2", + "@getpaseo/protocol": "0.14.0-beta.2", "react": ">=19.1.0 <20", "react-native": ">=0.81.5", "zod": "^4.4.3" @@ -40420,7 +40420,7 @@ }, "packages/protocol": { "name": "@getpaseo/protocol", - "version": "0.14.0-beta.1", + "version": "0.14.0-beta.2", "dependencies": { "semver": "^7.8.5", "zod": "^4.4.3" @@ -40447,7 +40447,7 @@ }, "packages/relay": { "name": "@getpaseo/relay", - "version": "0.14.0-beta.1", + "version": "0.14.0-beta.2", "dependencies": { "@noble/ciphers": "^2.4.0", "@noble/curves": "^2.4.0", @@ -40668,16 +40668,16 @@ }, "packages/server": { "name": "@getpaseo/server", - "version": "0.14.0-beta.1", + "version": "0.14.0-beta.2", "dependencies": { "@agentclientprotocol/sdk": "^0.17.1", "@anthropic-ai/claude-agent-sdk": "0.3.246", "@anthropic-ai/sdk": "^0.104.2", - "@getpaseo/client": "0.14.0-beta.1", - "@getpaseo/highlight": "0.14.0-beta.1", - "@getpaseo/plugin": "0.14.0-beta.1", - "@getpaseo/protocol": "0.14.0-beta.1", - "@getpaseo/relay": "0.14.0-beta.1", + "@getpaseo/client": "0.14.0-beta.2", + "@getpaseo/highlight": "0.14.0-beta.2", + "@getpaseo/plugin": "0.14.0-beta.2", + "@getpaseo/protocol": "0.14.0-beta.2", + "@getpaseo/relay": "0.14.0-beta.2", "@isaacs/ttlcache": "^2.1.4", "@modelcontextprotocol/sdk": "1.29.0", "@opencode-ai/sdk": "1.14.46", @@ -41598,7 +41598,7 @@ }, "packages/website": { "name": "@getpaseo/website", - "version": "0.14.0-beta.1", + "version": "0.14.0-beta.2", "dependencies": { "@cloudflare/vite-plugin": "^1.29.1", "@cloudflare/workers-types": "^4.20260317.1", @@ -43208,7 +43208,7 @@ }, "plugins": { "name": "@getpaseo/builtin-plugins", - "version": "0.14.0-beta.1", + "version": "0.14.0-beta.2", "dependencies": { "@getpaseo/plugin": "*", "zod": "^4.4.3" diff --git a/package.json b/package.json index 1406cab3aa..0065786340 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "paseo", - "version": "0.14.0-beta.1", + "version": "0.14.0-beta.2", "private": true, "description": "Paseo: voice-controlled development environment for local AI coding agents", "keywords": [ diff --git a/packages/app/package.json b/packages/app/package.json index f53b0ec42c..1a348e819f 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/app", - "version": "0.14.0-beta.1", + "version": "0.14.0-beta.2", "private": true, "main": "index.ts", "scripts": { diff --git a/packages/cli/package.json b/packages/cli/package.json index e5e7503c39..0d0d5cb61d 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/cli", - "version": "0.14.0-beta.1", + "version": "0.14.0-beta.2", "description": "Paseo CLI - control your AI coding agents from the command line", "bin": { "paseo": "bin/paseo" @@ -28,9 +28,9 @@ }, "dependencies": { "@clack/prompts": "^1.0.0", - "@getpaseo/client": "0.14.0-beta.1", - "@getpaseo/protocol": "0.14.0-beta.1", - "@getpaseo/server": "0.14.0-beta.1", + "@getpaseo/client": "0.14.0-beta.2", + "@getpaseo/protocol": "0.14.0-beta.2", + "@getpaseo/server": "0.14.0-beta.2", "chalk": "^5.3.0", "commander": "^12.0.0", "mime-types": "^2.1.35", diff --git a/packages/client/package.json b/packages/client/package.json index 08cd272057..e15265c8f1 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/client", - "version": "0.14.0-beta.1", + "version": "0.14.0-beta.2", "description": "Paseo client SDK package", "files": [ "dist", @@ -47,8 +47,8 @@ "test": "vitest run" }, "dependencies": { - "@getpaseo/protocol": "0.14.0-beta.1", - "@getpaseo/relay": "0.14.0-beta.1", + "@getpaseo/protocol": "0.14.0-beta.2", + "@getpaseo/relay": "0.14.0-beta.2", "ws": "^8.20.0", "zod": "^4.4.3" }, diff --git a/packages/desktop/package.json b/packages/desktop/package.json index ff5f33401a..8a77957fba 100644 --- a/packages/desktop/package.json +++ b/packages/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/desktop", - "version": "0.14.0-beta.1", + "version": "0.14.0-beta.2", "private": true, "description": "Paseo desktop app (Electron wrapper)", "homepage": "https://paseo.sh", diff --git a/packages/expo-two-way-audio/package.json b/packages/expo-two-way-audio/package.json index 98e790361e..016a28132e 100644 --- a/packages/expo-two-way-audio/package.json +++ b/packages/expo-two-way-audio/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/expo-two-way-audio", - "version": "0.14.0-beta.1", + "version": "0.14.0-beta.2", "description": "Native module for two way audio streaming", "keywords": [ "ExpoTwoWayAudio", diff --git a/packages/highlight/package.json b/packages/highlight/package.json index cf4c09305d..da80a7421c 100644 --- a/packages/highlight/package.json +++ b/packages/highlight/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/highlight", - "version": "0.14.0-beta.1", + "version": "0.14.0-beta.2", "files": [ "dist", "!dist/**/*.map", diff --git a/packages/plugin/package.json b/packages/plugin/package.json index 15c6f633e0..5fa8449b2b 100644 --- a/packages/plugin/package.json +++ b/packages/plugin/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/plugin", - "version": "0.14.0-beta.1", + "version": "0.14.0-beta.2", "description": "Paseo plugin SDK package", "files": [ "dist", @@ -77,8 +77,8 @@ "use-sync-external-store": "^1.6.0" }, "devDependencies": { - "@getpaseo/client": "0.14.0-beta.1", - "@getpaseo/protocol": "0.14.0-beta.1", + "@getpaseo/client": "0.14.0-beta.2", + "@getpaseo/protocol": "0.14.0-beta.2", "@types/node": "^20.9.0", "@types/react": "~19.2.0", "react": "19.2.3", @@ -88,8 +88,8 @@ "zod": "^4.4.3" }, "peerDependencies": { - "@getpaseo/client": "0.14.0-beta.1", - "@getpaseo/protocol": "0.14.0-beta.1", + "@getpaseo/client": "0.14.0-beta.2", + "@getpaseo/protocol": "0.14.0-beta.2", "react": ">=19.1.0 <20", "react-native": ">=0.81.5", "zod": "^4.4.3" diff --git a/packages/protocol/package.json b/packages/protocol/package.json index e1c8b14763..8829e183a3 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/protocol", - "version": "0.14.0-beta.1", + "version": "0.14.0-beta.2", "description": "Paseo shared protocol schemas and wire types", "files": [ "dist", diff --git a/packages/relay/package.json b/packages/relay/package.json index 0d96207e98..5daed2afce 100644 --- a/packages/relay/package.json +++ b/packages/relay/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/relay", - "version": "0.14.0-beta.1", + "version": "0.14.0-beta.2", "description": "Paseo relay for bridging daemon and client connections", "files": [ "dist", diff --git a/packages/server/package.json b/packages/server/package.json index 5572271cbb..7f8a6c074a 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/server", - "version": "0.14.0-beta.1", + "version": "0.14.0-beta.2", "description": "Paseo backend server", "files": [ "dist/server", @@ -107,11 +107,11 @@ "@agentclientprotocol/sdk": "^0.17.1", "@anthropic-ai/claude-agent-sdk": "0.3.246", "@anthropic-ai/sdk": "^0.104.2", - "@getpaseo/client": "0.14.0-beta.1", - "@getpaseo/highlight": "0.14.0-beta.1", - "@getpaseo/plugin": "0.14.0-beta.1", - "@getpaseo/protocol": "0.14.0-beta.1", - "@getpaseo/relay": "0.14.0-beta.1", + "@getpaseo/client": "0.14.0-beta.2", + "@getpaseo/highlight": "0.14.0-beta.2", + "@getpaseo/plugin": "0.14.0-beta.2", + "@getpaseo/protocol": "0.14.0-beta.2", + "@getpaseo/relay": "0.14.0-beta.2", "@isaacs/ttlcache": "^2.1.4", "@modelcontextprotocol/sdk": "1.29.0", "@opencode-ai/sdk": "1.14.46", diff --git a/packages/website/package.json b/packages/website/package.json index 889be528a9..9b115fbfe7 100644 --- a/packages/website/package.json +++ b/packages/website/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/website", - "version": "0.14.0-beta.1", + "version": "0.14.0-beta.2", "private": true, "type": "module", "scripts": { diff --git a/plugins/package.json b/plugins/package.json index 7ddbaab4fb..9a816eacbd 100644 --- a/plugins/package.json +++ b/plugins/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/builtin-plugins", - "version": "0.14.0-beta.1", + "version": "0.14.0-beta.2", "private": true, "type": "module", "scripts": { From 1467121b16742c2ce57320748d70d365aaf861c6 Mon Sep 17 00:00:00 2001 From: "paseo-ai[bot]" <266920839+paseo-ai[bot]@users.noreply.github.com> Date: Wed, 28 Oct 2026 18:00:41 +0000 Subject: [PATCH 097/173] fix: update lockfile signatures and Nix hash [skip ci] --- nix/npm-deps.hash | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nix/npm-deps.hash b/nix/npm-deps.hash index f57d216905..eae1803a42 100644 --- a/nix/npm-deps.hash +++ b/nix/npm-deps.hash @@ -1 +1 @@ -sha256-5/wat91m8GWxkGVk211lu9KFLhDQNEF/dlMhHMGf8Q0= +sha256-AmMp/4ugSUKXTL6H0oJaGJMztVGiYCPXeWteQaaaguw= From d3f36e92a5dae321009963a3d1dad8bf2261cf1e Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Wed, 28 Oct 2026 21:25:31 +0000 Subject: [PATCH 098/173] test(server): isolate config responsiveness from test runner work (#8131) Measure config reads in a fresh process so unrelated runner callbacks cannot consume the config CPU budget. Keep the existing budget, result, async I/O and yield assertions, and prove isolation with a busy parent callback. Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../src/utils/paseo-config-file.test.ts | 56 ++++++++++++++++--- .../test-fixtures/config-responsiveness.ts | 14 +++++ 2 files changed, 61 insertions(+), 9 deletions(-) create mode 100644 packages/server/src/utils/test-fixtures/config-responsiveness.ts diff --git a/packages/server/src/utils/paseo-config-file.test.ts b/packages/server/src/utils/paseo-config-file.test.ts index 1eed6ec054..186a5259ed 100644 --- a/packages/server/src/utils/paseo-config-file.test.ts +++ b/packages/server/src/utils/paseo-config-file.test.ts @@ -3,7 +3,6 @@ import { execFile } from "node:child_process"; import { promisify } from "node:util"; import { fileURLToPath } from "node:url"; import { writeFile, truncate, rm } from "node:fs/promises"; -import { measureMainThreadWork } from "../test-utils/main-thread-work.js"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; @@ -21,6 +20,24 @@ import { writePaseoConfigForEdit, } from "./paseo-config-file.js"; +async function measureConfigRead(directory: string) { + const fixture = fileURLToPath( + new URL("./test-fixtures/config-responsiveness.ts", import.meta.url), + ); + const { stdout, stderr } = await promisify(execFile)( + process.execPath, + ["--import", "tsx", fixture, directory], + { timeout: 15_000 }, + ); + process.stderr.write(stderr); + return JSON.parse(stdout) as { + result: Awaited>; + blockingMs: number; + filesystemRequests: number; + yields: number; + }; +} + describe("paseo config file substrate", () => { let tempDir: string; @@ -67,6 +84,33 @@ describe("paseo config file substrate", () => { ); }); + it("excludes unrelated test-runner CPU from the config read budget", async () => { + await writeFile(join(tempDir, "paseo.json"), JSON.stringify({ worktree: { setup: "npm ci" } })); + const unrelatedWork = new Promise((resolve) => { + setImmediate(() => { + const threadCpuUsage: (previous?: NodeJS.CpuUsage) => NodeJS.CpuUsage = Reflect.get( + process, + "threadCpuUsage", + ); + const start = threadCpuUsage(); + let elapsed: NodeJS.CpuUsage; + do { + elapsed = threadCpuUsage(start); + } while (elapsed.user + elapsed.system < 60_000); + resolve(); + }); + }); + const { result, blockingMs, filesystemRequests } = await measureConfigRead(tempDir); + await unrelatedWork; + expect(result).toEqual({ + ok: true, + config: { worktree: { setup: "npm ci" } }, + revision: await statPaseoConfigPath(tempDir), + }); + expect(filesystemRequests).toBeGreaterThan(0); + expect(blockingMs).toBeLessThan(20); + }); + it("keeps main-thread work below 20ms while admitting large configs", async () => { const config = { scripts: Object.fromEntries( @@ -75,10 +119,7 @@ describe("paseo config file substrate", () => { worktree: { setup: "npm ci" }, }; await writeFile(join(tempDir, "paseo.json"), JSON.stringify(config)); - const { result, blockingMs, filesystemRequests, yields } = await measureMainThreadWork( - "project config 7000 scripts main-thread work", - () => readPaseoConfigForEdit(tempDir), - ); + const { result, blockingMs, filesystemRequests, yields } = await measureConfigRead(tempDir); expect(result).toEqual({ ok: true, config, revision: await statPaseoConfigPath(tempDir) }); expect(blockingMs).toBeLessThan(20); expect(filesystemRequests).toBeGreaterThan(0); @@ -90,10 +131,7 @@ describe("paseo config file substrate", () => { join(tempDir, "paseo.json"), JSON.stringify({ extra: "x".repeat(32 * 1024 * 1024) }), ); - const { result, blockingMs, filesystemRequests } = await measureMainThreadWork( - "project config 32MiB main-thread work", - () => readPaseoConfigForEdit(tempDir), - ); + const { result, blockingMs, filesystemRequests } = await measureConfigRead(tempDir); expect(blockingMs).toBeLessThan(20); expect(filesystemRequests).toBeGreaterThan(0); expect(result).toEqual({ ok: false, error: { code: "invalid_project_config" } }); diff --git a/packages/server/src/utils/test-fixtures/config-responsiveness.ts b/packages/server/src/utils/test-fixtures/config-responsiveness.ts new file mode 100644 index 0000000000..656c5a2864 --- /dev/null +++ b/packages/server/src/utils/test-fixtures/config-responsiveness.ts @@ -0,0 +1,14 @@ +import assert from "node:assert/strict"; +import { setImmediate as nextTurn } from "node:timers/promises"; +import { measureMainThreadWork } from "../../test-utils/main-thread-work.js"; +import { readPaseoConfigForEdit } from "../paseo-config-file.js"; + +// Keep Vitest transforms, reporting, and unrelated callbacks outside the measured +// thread. Read the real file once, without warming the config snapshot or schema. +const directory = process.argv[2]; +assert.ok(directory, "Config directory is required"); +await nextTurn(); +const measured = await measureMainThreadWork("project config main-thread work", () => + readPaseoConfigForEdit(directory), +); +process.stdout.write(JSON.stringify(measured)); From 0feaf0d9871b61c736b22c17de79d49ee5b15617 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Wed, 28 Oct 2026 23:07:21 +0000 Subject: [PATCH 099/173] Keep configured Claude settings when Paseo adds flags (#8148) * fix(claude): keep extraArgs settings when Paseo sets flag settings * test(claude): verify settings survive the real SDK launch Capture the executable arguments through the public provider session interface so SDK option precedence cannot silently discard the configured settings file again. Co-authored-by: yayugu --------- Co-authored-by: yayugu Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../agent/providers/claude/agent.test.ts | 62 +++++++++++++++++++ .../server/agent/providers/claude/agent.ts | 60 +++++++++++++++--- .../providers/claude/settings-argv.test.ts | 46 ++++++++++++++ 3 files changed, 160 insertions(+), 8 deletions(-) create mode 100644 packages/server/src/server/agent/providers/claude/settings-argv.test.ts diff --git a/packages/server/src/server/agent/providers/claude/agent.test.ts b/packages/server/src/server/agent/providers/claude/agent.test.ts index 52b70c25bc..deb52f9a6b 100644 --- a/packages/server/src/server/agent/providers/claude/agent.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.test.ts @@ -887,6 +887,68 @@ describe("ClaudeAgentSession features", () => { await session.close(); }); + test("keeps an extraArgs settings file when Paseo sets Claude flag settings", async () => { + const settingsDir = await fs.mkdtemp(path.join(os.tmpdir(), "paseo-claude-settings-")); + const settingsPath = path.join(settingsDir, "settings.json"); + await fs.writeFile( + settingsPath, + JSON.stringify({ env: { ENABLE_TOOL_SEARCH: "false" }, permissions: { deny: ["Monitor"] } }), + ); + const { queryFactory } = createQueryMock(); + const client = new ClaudeAgentClient({ + logger, + queryFactory, + resolveBinary: async () => "/test/claude/bin", + }); + const session = await client.createSession({ + provider: "claude", + cwd: process.cwd(), + model: "claude-opus-5-5", + providerOptions: { + extraArgs: { chrome: null, settings: settingsPath }, + }, + }); + + await session.startTurn("hello"); + + const options = queryFactory.mock.calls[0]?.[0].options; + expect(options?.extraArgs).toEqual({ chrome: null }); + expect(options?.settings).toEqual({ + env: { ENABLE_TOOL_SEARCH: "false" }, + permissions: { deny: ["Monitor"] }, + fastMode: false, + }); + await session.close(); + await fs.rm(settingsDir, { recursive: true, force: true }); + }); + + test("keeps inline extraArgs settings JSON for internal agents", async () => { + const { queryFactory } = createQueryMock(); + const client = new ClaudeAgentClient({ + logger, + queryFactory, + resolveBinary: async () => "/test/claude/bin", + }); + const session = await client.createSession({ + provider: "claude", + cwd: process.cwd(), + internal: true, + providerOptions: { + extraArgs: { settings: '{"env":{"ENABLE_TOOL_SEARCH":"false"}}' }, + }, + }); + + await session.startTurn("hello"); + + const options = queryFactory.mock.calls[0]?.[0].options; + expect(options?.extraArgs).toEqual({}); + expect(options?.settings).toEqual({ + env: { ENABLE_TOOL_SEARCH: "false" }, + disableAllHooks: true, + }); + await session.close(); + }); + test("lists fast mode only for supported Opus models", async () => { const client = new ClaudeAgentClient({ logger, resolveBinary: async () => "/test/claude/bin" }); diff --git a/packages/server/src/server/agent/providers/claude/agent.ts b/packages/server/src/server/agent/providers/claude/agent.ts index e2cd9dab8f..824a93f3da 100644 --- a/packages/server/src/server/agent/providers/claude/agent.ts +++ b/packages/server/src/server/agent/providers/claude/agent.ts @@ -48,6 +48,7 @@ import { parseClaudeCodeVersion, resolveClaudeDisabledThinkingForModel, } from "./model-manifest.js"; +import { expandTilde } from "../../../../utils/path.js"; import { parsePartialJsonObject } from "./partial-json.js"; import { withClaudeReplayHistory, type ClaudeReplayHistory } from "./transcript-history.js"; import { ClaudeSidechainTracker } from "./sidechain-tracker.js"; @@ -648,6 +649,40 @@ function readClaudeFastModeSetting(settings: ClaudeOptions["settings"]): boolean return typeof settings.fastMode === "boolean" ? settings.fastMode : null; } +type ClaudeSettingsObject = NonNullable>; + +// Mirrors `claude --settings`: the value is inline JSON or a path to a JSON file, +// resolved against the session cwd like the Claude process would. +async function readClaudeCliSettings(value: string, cwd: string): Promise { + const trimmed = value.trim(); + const isInlineJson = trimmed.startsWith("{"); + const source = isInlineJson ? "--settings JSON" : path.resolve(cwd, expandTilde(trimmed)); + let raw = trimmed; + if (!isInlineJson) { + try { + raw = await fsPromises.readFile(source, "utf8"); + } catch (error) { + throw new Error( + `Failed to read Claude settings file ${source}: ${error instanceof Error ? error.message : String(error)}`, + { cause: error }, + ); + } + } + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch (error) { + throw new Error( + `Claude ${source} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`, + { cause: error }, + ); + } + if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) { + throw new Error(`Claude ${source} must contain a JSON object`); + } + return parsed as ClaudeSettingsObject; +} + function mergeClaudeSettings( settings: ClaudeOptions["settings"], updates: NonNullable>, @@ -3610,7 +3645,7 @@ class ClaudeAgentSession implements AgentSession { this.config.providerOptions, this.config.toolPolicy, ); - const settingsOptions = this.buildSettingsOptions(providerOptions, { ultracode }); + const settingsOptions = await this.buildSettingsOptions(providerOptions, { ultracode }); const sdkEnv = this.harnessEnvironment; assertClaudeModeCanRun(permissionMode, sdkEnv); @@ -3695,10 +3730,10 @@ class ClaudeAgentSession implements AgentSession { return base; } - private buildSettingsOptions( + private async buildSettingsOptions( providerOptions: ClaudeProviderOptions, input: { ultracode: boolean }, - ): Pick | Record { + ): Promise | Record> { const fastMode = this.resolveFastModeSetting(); // Internal agents do daemon work such as naming a branch, so the user's and // project's hooks must not run for them. @@ -3706,12 +3741,21 @@ class ClaudeAgentSession implements AgentSession { if (fastMode === null && !input.ultracode && !disableAllHooks) { return {}; } + const updates = { + ...(fastMode === null ? {} : { fastMode }), + ...(input.ultracode ? { ultracode: true } : {}), + ...(disableAllHooks ? { disableAllHooks: true } : {}), + }; + // The SDK replaces extraArgs.settings with Options.settings, so a user's + // `--settings` would be dropped whenever Paseo sets flag settings. Fold it in. + const { settings: extraArgsSettings, ...extraArgs } = providerOptions.extraArgs ?? {}; + if (typeof extraArgsSettings !== "string") { + return { settings: mergeClaudeSettings(providerOptions.settings, updates) }; + } + const cliSettings = await readClaudeCliSettings(extraArgsSettings, this.config.cwd); return { - settings: mergeClaudeSettings(providerOptions.settings, { - ...(fastMode === null ? {} : { fastMode }), - ...(input.ultracode ? { ultracode: true } : {}), - ...(disableAllHooks ? { disableAllHooks: true } : {}), - }), + extraArgs, + settings: { ...cliSettings, ...providerOptions.settings, ...updates }, }; } diff --git a/packages/server/src/server/agent/providers/claude/settings-argv.test.ts b/packages/server/src/server/agent/providers/claude/settings-argv.test.ts new file mode 100644 index 0000000000..36d1b9d794 --- /dev/null +++ b/packages/server/src/server/agent/providers/claude/settings-argv.test.ts @@ -0,0 +1,46 @@ +import * as fs from "node:fs/promises"; +import * as os from "node:os"; +import * as path from "node:path"; +import pino from "pino"; +import { expect, test } from "vitest"; +import { ClaudeAgentClient } from "./agent.js"; + +test("the real SDK passes the user's settings file contents alongside Paseo flags", async () => { + const cwd = await fs.mkdtemp(path.join(os.tmpdir(), "paseo-claude-settings-argv-")); + const capturePath = path.join(cwd, "argv.json"); + const binaryPath = path.join(cwd, "capture.mjs"); + const settingsPath = path.join(cwd, "settings.json"); + const userSettings = { + env: { ENABLE_TOOL_SEARCH: "false" }, + permissions: { deny: ["Monitor"] }, + }; + try { + // A CLI fixture records the real SDK's arguments without making a model request. + await fs.writeFile( + binaryPath, + `import fs from "node:fs"; fs.writeFileSync(${JSON.stringify(capturePath)}, JSON.stringify(process.argv.slice(2)));`, + ); + await fs.writeFile(settingsPath, JSON.stringify(userSettings)); + const client = new ClaudeAgentClient({ + logger: pino({ level: "silent" }), + resolveBinary: async () => binaryPath, + }); + const session = await client.createSession({ + provider: "claude", + cwd, + model: "claude-opus-5-5", + providerOptions: { extraArgs: { settings: settingsPath } }, + }); + try { + await session.startTurn("hello"); + } finally { + await session.close(); + } + const argv: string[] = JSON.parse(await fs.readFile(capturePath, "utf8")); + const settingsIndex = argv.indexOf("--settings"); + expect(settingsIndex).toBeGreaterThanOrEqual(0); + expect(JSON.parse(argv[settingsIndex + 1]!)).toEqual({ ...userSettings, fastMode: false }); + } finally { + await fs.rm(cwd, { recursive: true, force: true }); + } +}); From 304cbde651a73e95e0077b21ade240637a7d03ba Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Thu, 29 Oct 2026 10:17:11 +0700 Subject: [PATCH 100/173] fix(server): reopening a Codex agent no longer reads and holds its full history (#8132) * fix(server): read Codex history only when Paseo replays it Reopening a Codex agent whose timeline Paseo still held read the full thread on connect and kept it on the session until the next replay, which never came, so every reopened agent held a second copy of its transcript. thread/resume also returned every turn, and only the sandbox policy was used from it. Resume now sends excludeTurns (older Codex ignores the unknown field) and the history read moves into streamHistory, whose caller owns the result. A resumed session still needs the earlier turns for rewind targets and the sub-agent routes that keep an earlier child's interactions on its original card, so the first turn, goal or rewind indexes the thread and drops the timeline it read. * test(server): run reopened Codex agent tests without the Codex CLI installed --- .../providers/codex-app-server-agent.test.ts | 235 ++++++++++++++++-- .../agent/providers/codex-app-server-agent.ts | 100 ++++---- 2 files changed, 271 insertions(+), 64 deletions(-) diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts index 1d113fb27a..2169a059f2 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts @@ -16,6 +16,7 @@ import type { AgentSessionConfig, AgentSlashCommand, AgentStreamEvent, + AgentTimelineItem, } from "../agent-sdk-types.js"; import { buildCodexAppServerEnv, @@ -114,7 +115,6 @@ interface CodexSessionTestAccess { ensureThreadLoaded(): Promise; handleToolApprovalRequest(params: unknown): Promise; handleNotification(method: string, params: unknown): Promise; - loadPersistedHistory(client: CodexClientLike | null): Promise; refreshResolvedCollaborationMode(): void; serviceTier: "fast" | null; planModeEnabled: boolean; @@ -503,6 +503,81 @@ function archivedThreadErrorMessage(threadId: string): string { ); } +function codexUserItem(id: string, text: string) { + return { type: "userMessage", id, content: [{ type: "text", text }] }; +} + +function codexAgentItem(text: string) { + return { type: "agentMessage", id: `agent-${text}`, text }; +} + +// An AgentManager over a real Codex provider whose every spawn gets a fresh fake +// app-server serving `threads` from thread/read. +function createReopenableCodexAgent(threads: Record) { + const appServers: FakeCodexAppServer[] = []; + const provider = new CodexAppServerAgentClient(createTestLogger()); + const internals = castInternals<{ + goalsEnabledPromise: Promise | null; + autoReviewEnabledPromise: Promise | null; + spawnAppServer: () => Promise; + }>(provider); + internals.goalsEnabledPromise = Promise.resolve(false); + internals.autoReviewEnabledPromise = Promise.resolve(false); + internals.spawnAppServer = async () => { + const appServer = createFakeCodexAppServer({ + "thread/read": (params) => { + const { threadId } = params as { threadId: string }; + return { thread: { id: threadId, turns: threads[threadId] ?? [] } }; + }, + }); + appServers.push(appServer); + return appServer.child; + }; + // The fake app-server stands in for the Codex CLI, which test machines may not have. + const client: AgentClient = { + provider: "codex", + capabilities: provider.capabilities, + isAvailable: async () => true, + fetchCatalog: async () => ({ models: [], modes: [] }), + createSession: async () => { + throw new Error("Unexpected create"); + }, + resumeSession: (...args) => provider.resumeSession(...args), + }; + const manager = new AgentManager({ clients: { codex: client }, logger: createTestLogger() }); + const agentId = "00000000-0000-4000-8000-000000000001"; + const handle = { provider: "codex", sessionId: "saved-thread" }; + const config = createConfig({ cwd: process.cwd() }); + + async function open(): Promise { + await manager.resumeAgentFromPersistence(handle, config, agentId); + await manager.hydrateTimelineFromProvider(agentId); + } + + return { + manager, + agentId, + latestAppServer: () => appServers[appServers.length - 1], + threadMethods: (index: number) => + appServers[index] + .requests() + .map((request) => request.method) + .filter((method) => typeof method === "string" && method.startsWith("thread/")), + // Cold-loads the agent, closes its runtime, and reopens it while Paseo keeps its timeline. + async loadCloseAndReopen(): Promise { + await open(); + const projected = manager.getTimeline(agentId); + await manager.closeAgent(agentId); + await open(); + return projected; + }, + async close(): Promise { + await manager.closeAgent(agentId); + for (const appServer of appServers) appServer.assertNoErrors(); + }, + }; +} + function asInternals(session: CodexTestSession): CodexSessionTestAccess { return castInternals(session); } @@ -1897,12 +1972,147 @@ describe("Codex app-server provider", () => { "thread/resume", "thread/unarchive", "thread/resume", - "thread/read", ]); await session.close(); appServer.assertNoErrors(); }); + test("resumes a Codex thread without asking for its turns", async () => { + const appServer = createFakeCodexAppServer(); + const provider = createProviderWithFakeAppServer(appServer); + + const session = await provider.resumeSession({ sessionId: "saved-thread" }); + + expect( + appServer + .requests() + .filter((request) => request.method === "thread/resume") + .map((request) => request.params), + ).toEqual([expect.objectContaining({ threadId: "saved-thread", excludeTurns: true })]); + await session.close(); + appServer.assertNoErrors(); + }); + + test("reopening an agent whose timeline Paseo still holds does not read Codex history", async () => { + const codex = createReopenableCodexAgent({ + "saved-thread": [ + { id: "turn-1", items: [codexUserItem("user-1", "Hello"), codexAgentItem("Hi there.")] }, + ], + }); + try { + const projected = await codex.loadCloseAndReopen(); + + expect(projected).toEqual([ + expect.objectContaining({ type: "user_message", messageId: "user-1", text: "Hello" }), + expect.objectContaining({ type: "assistant_message", text: "Hi there." }), + ]); + expect(codex.threadMethods(0)).toEqual([ + "thread/loaded/list", + "thread/resume", + "thread/read", + ]); + expect(codex.threadMethods(1)).toEqual(["thread/loaded/list", "thread/resume"]); + expect(codex.manager.getTimeline(codex.agentId)).toEqual(projected); + } finally { + await codex.close(); + } + }); + + test("rewinds an agent reopened without reading its Codex history", async () => { + const firstTurn = { + id: "turn-1", + items: [codexUserItem("user-1", "First"), codexAgentItem("First answer.")], + }; + const codex = createReopenableCodexAgent({ + "saved-thread": [ + firstTurn, + { id: "turn-2", items: [codexUserItem("user-2", "Second"), codexAgentItem("Second.")] }, + ], + "forked-thread": [firstTurn], + }); + try { + await codex.loadCloseAndReopen(); + + await codex.manager.rewind(codex.agentId, "user-2", "conversation"); + + expect(codex.latestAppServer().recordedRollbacks).toEqual([ + { threadId: "forked-thread", numTurns: 1 }, + ]); + expect(codex.manager.getTimeline(codex.agentId)).toEqual([ + expect.objectContaining({ type: "user_message", messageId: "user-1", text: "First" }), + expect.objectContaining({ type: "assistant_message", text: "First answer." }), + ]); + } finally { + await codex.close(); + } + }); + + test("keeps a reopened agent's interaction with an earlier sub-agent on its original card", async () => { + const codex = createReopenableCodexAgent({ + "saved-thread": [ + { + id: "turn-1", + items: [ + codexUserItem("user-1", "Delegate"), + { + type: "subAgentActivity", + id: "spawn-child", + kind: "started", + agentThreadId: "child-thread", + agentPath: "/root/child", + }, + ], + }, + ], + "child-thread": [{ id: "child-turn-1", items: [codexAgentItem("Child started.")] }], + }); + try { + await codex.loadCloseAndReopen(); + const appServer = codex.latestAppServer(); + + const run = codex.manager.runAgent(codex.agentId, "Ask the child again"); + await appServer.waitForTurnStart(); + appServer.startsTurn({ threadId: "saved-thread", turnId: "turn-2" }); + appServer.beginsSubAgentActivity({ + callId: "interact-child", + threadId: "child-thread", + parentThreadId: "saved-thread", + kind: "interacted", + agentPath: "/root/child", + }); + appServer.says({ threadId: "child-thread", itemId: "child-reply", text: "Child replied." }); + appServer.completesSubAgentActivity({ + callId: "interact-child", + threadId: "child-thread", + parentThreadId: "saved-thread", + kind: "interacted", + agentPath: "/root/child", + }); + appServer.completeTurn({ threadId: "saved-thread" }); + await run; + + const toolCalls = codex.manager + .getTimeline(codex.agentId) + .filter((item) => item.type === "tool_call"); + expect(new Set(toolCalls.map((item) => item.callId))).toEqual(new Set(["spawn-child"])); + expect(toolCalls.at(-1)).toMatchObject({ callId: "spawn-child", status: "completed" }); + expect(codex.manager.getProviderSubagent(codex.agentId, "child-thread")).toMatchObject({ + toolCallId: "spawn-child", + status: "completed", + }); + expect( + codex.manager + .fetchProviderSubagentTimeline(codex.agentId, "child-thread") + .rows.map((row) => row.item), + ).toEqual([ + expect.objectContaining({ type: "assistant_message", text: "Child started." }), + expect.objectContaining({ type: "assistant_message", text: "Child replied." }), + ]); + } finally { + await codex.close(); + } + }); + test("closes Codex app-server when an interactive resume fails", async () => { const appServer = createFakeCodexAppServer({ "thread/resume": () => Promise.reject(new Error("thread resume failed")), @@ -4673,8 +4883,6 @@ describe("Codex app-server provider", () => { }), }; - await asInternals(session).loadPersistedHistory(session.client); - const history: AgentStreamEvent[] = []; for await (const event of session.streamHistory()) { history.push(event); @@ -4727,7 +4935,7 @@ describe("Codex app-server provider", () => { })), }; - await asInternals(session).loadPersistedHistory(session.client); + await Array.fromAsync(session.streamHistory()); expect(asInternals(session).codexUserMessageTurns().resolve("message-history")).toEqual({ index: 0, @@ -4796,8 +5004,6 @@ describe("Codex app-server provider", () => { }), }; - await asInternals(session).loadPersistedHistory(session.client); - const history: AgentStreamEvent[] = []; for await (const event of session.streamHistory()) { history.push(event); @@ -4958,8 +5164,6 @@ describe("Codex app-server provider", () => { }), }; - await asInternals(session).loadPersistedHistory(session.client); - const history: AgentStreamEvent[] = []; for await (const event of session.streamHistory()) { history.push(event); @@ -5023,8 +5227,6 @@ describe("Codex app-server provider", () => { }), }; - await asInternals(session).loadPersistedHistory(session.client); - const history: AgentStreamEvent[] = []; for await (const event of session.streamHistory()) { history.push(event); @@ -5200,8 +5402,6 @@ describe("Codex app-server provider", () => { }), }; - await asInternals(session).loadPersistedHistory(session.client); - const history: AgentStreamEvent[] = []; for await (const event of session.streamHistory()) { history.push(event); @@ -5261,8 +5461,6 @@ describe("Codex app-server provider", () => { }), }; - await asInternals(session).loadPersistedHistory(session.client); - const history: AgentStreamEvent[] = []; for await (const event of session.streamHistory()) { history.push(event); @@ -5564,7 +5762,10 @@ describe("Codex app-server provider", () => { expect(session.currentThreadId).toBe("archived-thread-id"); expect(requests).toEqual([ { method: "thread/loaded/list", params: {} }, - { method: "thread/resume", params: { threadId: "archived-thread-id" } }, + { + method: "thread/resume", + params: { threadId: "archived-thread-id", excludeTurns: true }, + }, ]); }); @@ -6399,8 +6600,6 @@ describe("Codex app-server provider", () => { })), }; - await asInternals(session).loadPersistedHistory(session.client); - const history: AgentStreamEvent[] = []; for await (const event of session.streamHistory()) { history.push(event); diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.ts index 291841c730..cdad017d45 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.ts @@ -496,6 +496,11 @@ interface PersistedTimelineEntry { providerTurnId?: string; } +interface CodexThreadHistory { + timeline: PersistedTimelineEntry[]; + providerSubagentEvents: AgentStreamEvent[]; +} + interface PersistedSubAgentRoute { childThreadId: string; toolCall: ToolCallTimelineItem; @@ -3464,10 +3469,12 @@ export class CodexAppServerAgentSession implements AgentSession { private serviceTier: string | null = null; private speedModels: CodexModel[] = []; private planModeEnabled = false; - private historyPending = false; - private persistedHistory: PersistedTimelineEntry[] = []; - private loadingPersistedHistory = false; - private persistedProviderSubagentEvents: AgentStreamEvent[] = []; + // History read by rewind or an archived resume, held until streamHistory consumes it. + private stagedHistory: CodexThreadHistory | null = null; + // Collects provider subagent events emitted while a thread history read rebuilds routes. + private historySubagentEvents: AgentStreamEvent[] | null = null; + // A resumed thread's earlier turns and sub-agents are known only after reading its history. + private historyIndexed = true; private pendingPermissions = new Map(); private mcpElicitationPermissionIds = new Map(); private pendingPermissionHandlers = new Map(); @@ -3574,7 +3581,7 @@ export class CodexAppServerAgentSession implements AgentSession { if (this.resumeHandle?.sessionId) { this.currentThreadId = this.resumeHandle.sessionId; - this.historyPending = true; + this.historyIndexed = false; // Resuming can start a goal before the caller receives the session. if (this.initialResumePurpose === "interactive") this.startupEvents = []; } @@ -3622,7 +3629,7 @@ export class CodexAppServerAgentSession implements AgentSession { private async establishConnection(): Promise { if (this.initialResumePurpose === "history") { - await this.readArchivedHistory(); + this.stagedHistory = await this.readArchivedHistory(); this.connectionState = "history-ready"; return; } @@ -3655,7 +3662,6 @@ export class CodexAppServerAgentSession implements AgentSession { if (this.currentThreadId) { await this.ensureThreadLoaded(); - await this.loadPersistedHistory(this.client); await this.applyDefaultModelAndThinking(); } @@ -3970,39 +3976,40 @@ export class CodexAppServerAgentSession implements AgentSession { ); } - private async readArchivedHistory(): Promise { + private async readArchivedHistory(): Promise { const child = await this.spawnAppServer(); const client = new CodexAppServerClient(child, this.logger, () => this.traceContext()); try { await client.request("initialize", buildCodexAppServerInitializeParams()); client.notify("initialized", {}); - await this.loadPersistedHistory(client); + return await this.readThreadHistory(client); } finally { await client.dispose(); } } - private async loadPersistedHistory(client: CodexAppServerClientLike | null): Promise { - if (!client || !this.currentThreadId) return; - const threadId = this.currentThreadId; - - const history = await loadCodexThreadHistoryTimeline({ - threadId, + // Reads the thread and its sub-agent threads, rebuilding the turn index and + // sub-agent routes. The caller owns the returned history; nothing retains it. + private async readThreadHistory( + client: CodexAppServerClientLike | null, + ): Promise { + if (!client || !this.currentThreadId) { + return { timeline: [], providerSubagentEvents: [] }; + } + const { timeline, subAgentRoutes } = await loadCodexThreadHistoryTimeline({ + threadId: this.currentThreadId, cwd: this.config.cwd ?? null, - requestThread: (threadIdToRead) => { - return readCodexThread(client, threadIdToRead); - }, + requestThread: (threadIdToRead) => readCodexThread(client, threadIdToRead), }); - const { timeline, subAgentRoutes } = history; this.subAgentCallsByCallId.clear(); this.subAgentCallIdByChildThreadId.clear(); this.pendingSubAgentNotificationsByThreadId.clear(); - this.persistedProviderSubagentEvents = []; - this.loadingPersistedHistory = true; + const providerSubagentEvents: AgentStreamEvent[] = []; + this.historySubagentEvents = providerSubagentEvents; try { await this.loadPersistedSubAgentHistories(client, subAgentRoutes); } finally { - this.loadingPersistedHistory = false; + this.historySubagentEvents = null; } this.resetCodexUserMessageTurns(); for (const entry of timeline) { @@ -4013,8 +4020,15 @@ export class CodexAppServerAgentSession implements AgentSession { this.rememberCodexUserMessageTurn(entry.item.messageId, entry.providerTurnId); } } - this.persistedHistory = timeline; - this.historyPending = timeline.length > 0; + this.historyIndexed = true; + return { timeline, providerSubagentEvents }; + } + + // Turns and rewind route by the thread's earlier turns and sub-agents. A resumed + // session whose projection Paseo already holds reads them here and drops the rest. + private async ensureHistoryIndexed(): Promise { + if (this.historyIndexed) return; + await this.readThreadHistory(this.client); } private async loadPersistedSubAgentHistories( @@ -4066,7 +4080,8 @@ export class CodexAppServerAgentSession implements AgentSession { private async ensureThreadLoaded(): Promise { if (!this.client || !this.currentThreadId) return; - const params: Record = { threadId: this.currentThreadId }; + // Paseo reads history only when it replays it; the resume response needs no turns. + const params: Record = { threadId: this.currentThreadId, excludeTurns: true }; const developerInstructions = composeSystemPromptParts( this.config.systemPrompt, this.config.daemonAppendSystemPrompt, @@ -4386,6 +4401,7 @@ export class CodexAppServerAgentSession implements AgentSession { if (this.currentThreadId) { await this.ensureThreadLoaded(); + await this.ensureHistoryIndexed(); } else { await this.ensureThread(); } @@ -4559,21 +4575,12 @@ export class CodexAppServerAgentSession implements AgentSession { } async *streamHistory(): AsyncGenerator { - if ( - (!this.historyPending || this.persistedHistory.length === 0) && - this.persistedProviderSubagentEvents.length === 0 - ) { - return; - } - const history = this.persistedHistory; - const providerSubagents = this.persistedProviderSubagentEvents; - this.persistedHistory = []; - this.persistedProviderSubagentEvents = []; - this.historyPending = false; - for (const event of providerSubagents) { + const history = this.stagedHistory ?? (await this.readThreadHistory(this.client)); + this.stagedHistory = null; + for (const event of history.providerSubagentEvents) { yield event; } - for (const entry of history) { + for (const entry of history.timeline) { yield { type: "timeline", provider: CODEX_PROVIDER, @@ -4956,6 +4963,7 @@ export class CodexAppServerAgentSession implements AgentSession { } else { await this.ensureThread(); } + await this.ensureHistoryIndexed(); await revertCodexConversation({ client: this.client, @@ -4970,10 +4978,8 @@ export class CodexAppServerAgentSession implements AgentSession { setThreadId: async (threadId) => { this.currentThreadId = threadId; this.cachedRuntimeInfo = null; - this.persistedHistory = []; - this.historyPending = false; - await this.loadPersistedHistory(this.client); - this.reconcileAsyncQuestionsAfterRewind(); + this.stagedHistory = await this.readThreadHistory(this.client); + this.reconcileAsyncQuestionsAfterRewind(this.stagedHistory.timeline); }, }); } @@ -5211,6 +5217,8 @@ export class CodexAppServerAgentSession implements AgentSession { await this.connect(); if (this.currentThreadId) { await this.ensureThreadLoaded(); + // A goal runs turns of its own. + await this.ensureHistoryIndexed(); } else { await this.ensureThread(); } @@ -5404,8 +5412,8 @@ export class CodexAppServerAgentSession implements AgentSession { } private emitEvent(event: AgentStreamEvent): void { - if (this.loadingPersistedHistory && event.type === "provider_subagent") { - this.persistedProviderSubagentEvents.push(event); + if (this.historySubagentEvents && event.type === "provider_subagent") { + this.historySubagentEvents.push(event); return; } this.notifySubscribers(event); @@ -6583,9 +6591,9 @@ export class CodexAppServerAgentSession implements AgentSession { } } - private reconcileAsyncQuestionsAfterRewind(): void { + private reconcileAsyncQuestionsAfterRewind(timeline: readonly PersistedTimelineEntry[]): void { const retainedIds = new Set( - this.persistedHistory.flatMap(({ item }) => + timeline.flatMap(({ item }) => item.type === "tool_call" && item.name === "request_user_input_async" ? [item.callId] : [], ), ); From e12feb633f340a88effe04a7822da678c685f75b Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Thu, 29 Oct 2026 11:24:34 +0700 Subject: [PATCH 101/173] feat(usage): show when each limit resets, and make usage rows easier to read (#8162) The reset countdown floored to one unit, so a weekly window read "resets 2d" from 2d 23h down to 2d 0h and looked stuck for a day; the session window had the same problem with hours. Countdowns now use two units ("2d 23h", "4h 59m"), and every row also shows the clock time it resets ("7:20 AM", "Sat 8:00 AM", "Oct 31, 3:00 PM"), so users can plan work around a reset without hovering. Rows now put the window name and percent on one line, the bar under it, and the reset on its own full-width line, so the exact time fits at phone width in longer languages. The pinned-row background is gone; the pin glyph, drawn in the foreground colour when pinned, is the only pinned signal. Bars are 6px. --- packages/app/e2e/browser/usage-modal.spec.ts | 8 +- packages/app/src/i18n/resources/ar.ts | 3 + packages/app/src/i18n/resources/en.ts | 7 +- packages/app/src/i18n/resources/es.ts | 3 + packages/app/src/i18n/resources/fr.ts | 3 + packages/app/src/i18n/resources/ja.ts | 3 + packages/app/src/i18n/resources/ko.ts | 3 + packages/app/src/i18n/resources/pt-BR.ts | 3 + packages/app/src/i18n/resources/ru.ts | 3 + packages/app/src/i18n/resources/zh-CN.ts | 3 + packages/app/src/usage/balance-bar.tsx | 99 +++++---------- packages/app/src/usage/format.test.ts | 69 ++++++++++- packages/app/src/usage/format.ts | 103 +++++++++------ packages/app/src/usage/meter.tsx | 4 +- packages/app/src/usage/reset-line.tsx | 48 +++++++ packages/app/src/usage/sidebar-item.tsx | 11 +- packages/app/src/usage/window-bar.tsx | 124 ++++++------------- packages/app/src/utils/time.ts | 7 +- 18 files changed, 291 insertions(+), 213 deletions(-) create mode 100644 packages/app/src/usage/reset-line.tsx diff --git a/packages/app/e2e/browser/usage-modal.spec.ts b/packages/app/e2e/browser/usage-modal.spec.ts index 1d98f6c591..6835e01bcb 100644 --- a/packages/app/e2e/browser/usage-modal.spec.ts +++ b/packages/app/e2e/browser/usage-modal.spec.ts @@ -717,15 +717,15 @@ test("open usage clocks advance without refreshing or reopening", async ({ page await openCompactUsageWithClock(page, now); const card = page.getByTestId("usage-report-login-journey:account"); await expect(card.getByTestId("usage-freshness")).toHaveText("Updated just now"); - await expect(card.getByText("resets 30m", { exact: false }).first()).toBeVisible(); + await expect(card.getByText("resets in 30m", { exact: false }).first()).toBeVisible(); // The shared minute clock is wall-aligned, and the daemon timestamps use real time. // After two browser minutes the latest displayed tick is one or two minutes old. await advanceUsageClock(page, 120_000); await expect(card.getByTestId("usage-freshness")).toHaveText(/^Updated [12]m ago$/); - await expect(card.getByText(/resets (28|29)m/).first()).toBeVisible(); - await expect(card.getByText(/runs out (28|29)m/)).toBeVisible(); + await expect(card.getByText(/resets in (28|29)m/).first()).toBeVisible(); + await expect(card.getByText(/runs out in (28|29)m/)).toBeVisible(); await expect(card.getByTestId("provider-usage-balance-credits-reset")).toHaveText( - /^resets (28|29)m$/, + /^resets in (28|29)m\s·\s/, ); } finally { await login.cleanup(); diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index 2f285ebcdb..1cb6f0da06 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -2157,6 +2157,7 @@ export const ar: TranslationResources = { minutes_few: "{{value}} دقائق", minutes_many: "{{value}} دقيقة", minutes_other: "{{value}} دقيقة", + pair: "{{first}} و{{second}}", }, timing: { lastUpdated: "آخر تحديث {{relativeTime}}", @@ -2164,6 +2165,8 @@ export const ar: TranslationResources = { resetTimePassed: "مضى وقت إعادة التعيين", resettingNow: "تتم إعادة التعيين الآن", resetsIn: "تتم إعادة التعيين خلال {{duration}}", + resetsAtWeekday: "{{weekday}} {{time}}", + resetsAtDate: "{{date}}، {{time}}", runsOutNow: "ينفد الآن", runsOutIn: "ينفد خلال {{duration}}", justNow: "الآن", diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index 896e8ebac7..0511af34e2 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -2164,15 +2164,18 @@ export const en = { days: "{{value}}d", hours: "{{value}}h", minutes: "{{value}}m", + pair: "{{first}} {{second}}", }, timing: { lastUpdated: "Last updated {{relativeTime}}", noSuccessfulUpdate: "No successful update", resetTimePassed: "Reset time passed", resettingNow: "resetting now", - resetsIn: "resets {{duration}}", + resetsIn: "resets in {{duration}}", + resetsAtWeekday: "{{weekday}} {{time}}", + resetsAtDate: "{{date}}, {{time}}", runsOutNow: "runs out now", - runsOutIn: "runs out {{duration}}", + runsOutIn: "runs out in {{duration}}", justNow: "just now", daysAgo: "{{value}}d ago", hoursAgo: "{{value}}h ago", diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index 016eb99c6e..ffe9cedc1e 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -2187,6 +2187,7 @@ export const es: TranslationResources = { days: "{{value}} d", hours: "{{value}} h", minutes: "{{value}} min", + pair: "{{first}} {{second}}", }, timing: { lastUpdated: "Última actualización {{relativeTime}}", @@ -2194,6 +2195,8 @@ export const es: TranslationResources = { resetTimePassed: "Pasó la hora de restablecimiento", resettingNow: "se restablece ahora", resetsIn: "se restablece en {{duration}}", + resetsAtWeekday: "{{weekday}} {{time}}", + resetsAtDate: "{{date}}, {{time}}", runsOutNow: "se agota ahora", runsOutIn: "se agota en {{duration}}", justNow: "ahora mismo", diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index cbbf2d9ec8..6c9df18211 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -2187,6 +2187,7 @@ export const fr: TranslationResources = { days: "{{value}} j", hours: "{{value}} h", minutes: "{{value}} min", + pair: "{{first}} {{second}}", }, timing: { lastUpdated: "Dernière mise à jour {{relativeTime}}", @@ -2194,6 +2195,8 @@ export const fr: TranslationResources = { resetTimePassed: "Heure de réinitialisation dépassée", resettingNow: "réinitialisation en cours", resetsIn: "se réinitialise dans {{duration}}", + resetsAtWeekday: "{{weekday}} {{time}}", + resetsAtDate: "{{date}}, {{time}}", runsOutNow: "s’épuise maintenant", runsOutIn: "s’épuise dans {{duration}}", justNow: "à l’instant", diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index 05a7aa457e..dd214ebac9 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -2160,6 +2160,7 @@ export const ja: TranslationResources = { days: "{{value}}日", hours: "{{value}}時間", minutes: "{{value}}分", + pair: "{{first}}{{second}}", }, timing: { lastUpdated: "最終更新: {{relativeTime}}", @@ -2167,6 +2168,8 @@ export const ja: TranslationResources = { resetTimePassed: "リセット時刻を過ぎています", resettingNow: "まもなくリセット", resetsIn: "{{duration}}後にリセット", + resetsAtWeekday: "{{weekday}} {{time}}", + resetsAtDate: "{{date}} {{time}}", runsOutNow: "まもなく上限に到達", runsOutIn: "{{duration}}後に上限に到達", justNow: "たった今", diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index d8a7491e92..d30635b2a5 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -2149,6 +2149,7 @@ export const ko: TranslationResources = { days: "{{value}}일", hours: "{{value}}시간", minutes: "{{value}}분", + pair: "{{first}} {{second}}", }, timing: { lastUpdated: "마지막 업데이트: {{relativeTime}}", @@ -2156,6 +2157,8 @@ export const ko: TranslationResources = { resetTimePassed: "초기화 시간이 지났습니다", resettingNow: "지금 재설정 중", resetsIn: "{{duration}} 후 재설정", + resetsAtWeekday: "{{weekday}} {{time}}", + resetsAtDate: "{{date}} {{time}}", runsOutNow: "지금 한도에 도달", runsOutIn: "{{duration}} 후 한도에 도달", justNow: "방금", diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index b2abd39b25..1d9ce0cb95 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -2172,6 +2172,7 @@ export const ptBR: TranslationResources = { days: "{{value}} d", hours: "{{value}} h", minutes: "{{value}} min", + pair: "{{first}} {{second}}", }, timing: { lastUpdated: "Última atualização {{relativeTime}}", @@ -2179,6 +2180,8 @@ export const ptBR: TranslationResources = { resetTimePassed: "O horário de redefinição passou", resettingNow: "redefinindo agora", resetsIn: "redefine em {{duration}}", + resetsAtWeekday: "{{weekday}} {{time}}", + resetsAtDate: "{{date}}, {{time}}", runsOutNow: "esgota agora", runsOutIn: "esgota em {{duration}}", justNow: "agora mesmo", diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index cdacf42173..766f8bdae7 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -2172,6 +2172,7 @@ export const ru: TranslationResources = { days: "{{value}} дн.", hours: "{{value}} ч", minutes: "{{value}} мин", + pair: "{{first}} {{second}}", }, timing: { lastUpdated: "Последнее обновление {{relativeTime}}", @@ -2179,6 +2180,8 @@ export const ru: TranslationResources = { resetTimePassed: "Время сброса прошло", resettingNow: "сброс сейчас", resetsIn: "сброс через {{duration}}", + resetsAtWeekday: "{{weekday}} {{time}}", + resetsAtDate: "{{date}}, {{time}}", runsOutNow: "закончится сейчас", runsOutIn: "закончится через {{duration}}", justNow: "только что", diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index f8131c7dca..64867d7d21 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -2117,6 +2117,7 @@ export const zhCN: TranslationResources = { days: "{{value}}天", hours: "{{value}}小时", minutes: "{{value}}分钟", + pair: "{{first}}{{second}}", }, timing: { lastUpdated: "上次更新于 {{relativeTime}}", @@ -2124,6 +2125,8 @@ export const zhCN: TranslationResources = { resetTimePassed: "重置时间已过", resettingNow: "正在重置", resetsIn: "将在 {{duration}}后重置", + resetsAtWeekday: "{{weekday}} {{time}}", + resetsAtDate: "{{date}} {{time}}", runsOutNow: "即将用尽", runsOutIn: "将在 {{duration}}后用尽", justNow: "刚刚", diff --git a/packages/app/src/usage/balance-bar.tsx b/packages/app/src/usage/balance-bar.tsx index def723c554..bcd33873cc 100644 --- a/packages/app/src/usage/balance-bar.tsx +++ b/packages/app/src/usage/balance-bar.tsx @@ -1,10 +1,16 @@ -import { useMemo } from "react"; import type { TFunction } from "i18next"; import { useTranslation } from "react-i18next"; -import { Text, View, type StyleProp, type ViewStyle } from "react-native"; +import { Text, View } from "react-native"; import { StyleSheet } from "react-native-unistyles"; -import { clampPct, formatAmount, formatProviderUsageLabel, formatResetLabel } from "./format"; -import type { UsageBalance, UsageTone } from "./types"; +import { + formatAmount, + formatProviderUsageLabel, + formatResetLabel, + formatResetTime, +} from "./format"; +import { UsageMeter } from "./meter"; +import { UsageResetLine } from "./reset-line"; +import type { UsageBalance } from "./types"; import { useRelativeTimeTick } from "./use-relative-time-tick"; interface ResolvedBalance { @@ -41,19 +47,6 @@ function resolveBalance({ return { amountText: "—", usedPct: null }; } -function fillToneStyle(tone: UsageTone) { - switch (tone) { - case "ok": - return styles.fillOk; - case "warning": - return styles.fillWarning; - case "danger": - return styles.fillDanger; - default: - return styles.fillDefault; - } -} - export function UsageBalanceBar({ balance, retained = false, @@ -66,11 +59,7 @@ export function UsageBalanceBar({ const { amountText, usedPct } = resolveBalance({ balance, t, locale: i18n.resolvedLanguage }); const tone = balance.tone ?? "default"; const resetLabel = formatResetLabel(balance.resetsAt, retained, now, t); - - const fillStyle = useMemo>( - () => [styles.fill, fillToneStyle(tone), { width: `${clampPct(usedPct ?? 0)}%` }], - [usedPct, tone], - ); + const resetTime = formatResetTime(balance.resetsAt, now, t); return ( @@ -78,22 +67,21 @@ export function UsageBalanceBar({ {formatProviderUsageLabel(balance.id, balance.label, t)} - - - {amountText} - - {resetLabel ? ( - - {resetLabel} - - ) : null} - + + {amountText} + - {usedPct != null ? ( - - - - ) : null} + {usedPct != null ? : null} + ); } @@ -110,44 +98,13 @@ const styles = StyleSheet.create((theme) => ({ }, label: { flexShrink: 1, - color: theme.colors.foregroundMuted, - fontSize: theme.fontSize.sm, - }, - value: { - flexShrink: 1, - alignItems: "flex-end", - }, - amount: { color: theme.colors.foreground, fontSize: theme.fontSize.sm, fontWeight: theme.fontWeight.medium, }, - reset: { - color: theme.colors.foregroundMuted, + amount: { + flexShrink: 1, + color: theme.colors.foreground, fontSize: theme.fontSize.sm, - fontWeight: theme.fontWeight.normal, - textAlign: "right", - }, - track: { - height: 4, - borderRadius: 2, - backgroundColor: theme.colors.surface3, - overflow: "hidden", - }, - fill: { - height: 4, - borderRadius: 2, - }, - fillDefault: { - backgroundColor: theme.colors.foregroundMuted, - }, - fillOk: { - backgroundColor: theme.colors.statusSuccess, - }, - fillWarning: { - backgroundColor: theme.colors.statusWarning, - }, - fillDanger: { - backgroundColor: theme.colors.statusDanger, }, })); diff --git a/packages/app/src/usage/format.test.ts b/packages/app/src/usage/format.test.ts index b7b81f0e5a..89fb9a7ed6 100644 --- a/packages/app/src/usage/format.test.ts +++ b/packages/app/src/usage/format.test.ts @@ -7,6 +7,7 @@ import { formatPct, formatProviderUsageLabel, formatResetLabel, + formatResetTime, formatRunsOutLabel, } from "./format"; @@ -36,8 +37,8 @@ describe("formatAmount", () => { const threeDaysAgo = new Date(NOW - 3 * 24 * 60 * 60 * 1000).toISOString(); expect(formatPct(7, "en")).toBe("7%"); - expect(formatResetLabel(twoHoursFromNow, false, NOW)).toBe("resets 2h"); - expect(formatRunsOutLabel(twoHoursFromNow, NOW)).toBe("runs out 2h"); + expect(formatResetLabel(twoHoursFromNow, false, NOW)).toBe("resets in 2h"); + expect(formatRunsOutLabel(twoHoursFromNow, NOW)).toBe("runs out in 2h"); await i18n.changeLanguage("ja"); expect(formatResetLabel(twoHoursFromNow, false, NOW)).toBe("2時間後にリセット"); @@ -94,6 +95,70 @@ describe("formatAmount", () => { }); }); +describe("reset countdown", () => { + const MINUTE = 60_000; + const HOUR = 60 * MINUTE; + const DAY = 24 * HOUR; + const countdown = (ms: number) => formatResetLabel(new Date(NOW + ms).toISOString(), false, NOW); + + beforeEach(async () => { + await i18n.changeLanguage("en"); + }); + + it("keeps counting down inside a day instead of sitting on the rounded-down day", () => { + expect(countdown(2 * DAY + 23 * HOUR + 10 * MINUTE)).toBe("resets in 2d 23h"); + expect(countdown(2 * DAY + 22 * HOUR + 10 * MINUTE)).toBe("resets in 2d 22h"); + }); + + it("says two units, dropping a unit that is zero", () => { + expect(countdown(DAY + 30 * MINUTE)).toBe("resets in 1d"); + expect(countdown(4 * HOUR + 59 * MINUTE)).toBe("resets in 4h 59m"); + expect(countdown(HOUR)).toBe("resets in 1h"); + expect(countdown(37 * MINUTE)).toBe("resets in 37m"); + expect(countdown(59 * 1000)).toBe("resets in 0m"); + }); + + it("joins the at-risk countdown the same way", () => { + const iso = new Date(NOW + 3 * HOUR + 5 * MINUTE).toISOString(); + expect(formatRunsOutLabel(iso, NOW)).toBe("runs out in 3h 5m"); + }); +}); + +describe("exact reset time", () => { + // Local-time dates, so the thresholds hold in any timezone the tests run in. + const now = new Date(2026, 9, 29, 12, 0).getTime(); + const at = (...args: [number, number, number, number, number]) => + formatResetTime(new Date(...args).toISOString(), now)?.replace(/\s/g, " "); + + beforeEach(async () => { + await i18n.changeLanguage("en"); + }); + + it("shows only the time within 24 hours", () => { + expect(at(2026, 9, 29, 15, 0)).toMatch(/^(3:00 PM|15:00)$/); + expect(at(2026, 9, 30, 11, 59)).toMatch(/^(11:59 AM|11:59)$/); + }); + + it("adds the weekday within 7 days", () => { + expect(at(2026, 9, 30, 12, 0)).toMatch(/^Fri (12:00 PM|12:00)$/); + expect(at(2026, 10, 5, 11, 59)).toMatch(/^Thu (11:59 AM|11:59)$/); + }); + + it("adds the date after 7 days", () => { + expect(at(2026, 10, 5, 12, 0)).toMatch(/^Nov 5, (12:00 PM|12:00)$/); + }); + + it("names the weekday in the app language", async () => { + await i18n.changeLanguage("fr"); + expect(at(2026, 9, 31, 15, 0)).toMatch(/^sam\.? /); + }); + + it("says nothing for a time that has passed", () => { + expect(formatResetTime(new Date(now - 1).toISOString(), now)).toBeNull(); + expect(formatResetTime(null, now)).toBeNull(); + }); +}); + it("retained reset times that have passed do not claim the quota is resetting", () => { const past = "2000-01-01T00:00:00.000Z"; expect(formatResetLabel(past, true)).toBe("Reset time passed"); diff --git a/packages/app/src/usage/format.ts b/packages/app/src/usage/format.ts index e7a6ba6f7b..867976a586 100644 --- a/packages/app/src/usage/format.ts +++ b/packages/app/src/usage/format.ts @@ -1,5 +1,6 @@ import type { TFunction } from "i18next"; import { i18n } from "@/i18n/i18next"; +import { formatTimeOfDay } from "@/utils/time"; import type { UsageDisplayAs } from "./preferences"; import type { UsageBalanceUnit } from "./types"; @@ -50,7 +51,17 @@ export function formatDisplayPct( : t("providerUsage.values.remaining", { amount: percentage }); } -type RelativeDuration = { unit: "now" } | { unit: "minutes" | "hours" | "days"; count: number }; +type DurationUnit = "minutes" | "hours" | "days"; +interface DurationPart { + unit: DurationUnit; + count: number; +} +/** Two units, floored, so a countdown keeps moving: "2d 23h", "4h 59m", "37m". */ +type RelativeDuration = { kind: "now" } | { kind: "remaining"; parts: DurationPart[] }; + +const MINUTE_MS = 60_000; +const HOUR_MS = 60 * MINUTE_MS; +const DAY_MS = 24 * HOUR_MS; function formatCount(value: number): string { return new Intl.NumberFormat(i18n.resolvedLanguage).format(value); @@ -59,35 +70,34 @@ function formatCount(value: number): string { function relativeDuration(iso: string, now: number): RelativeDuration | null { const diffMs = new Date(iso).getTime() - now; if (!Number.isFinite(diffMs)) return null; - if (diffMs <= 0) return { unit: "now" }; - const diffMinutes = Math.floor(diffMs / 60_000); - const diffHours = Math.floor(diffMinutes / 60); - const diffDays = Math.floor(diffHours / 24); - if (diffDays > 0) return { unit: "days", count: diffDays }; - if (diffHours > 0) return { unit: "hours", count: diffHours }; - return { unit: "minutes", count: diffMinutes }; + if (diffMs <= 0) return { kind: "now" }; + const days = Math.floor(diffMs / DAY_MS); + const hours = Math.floor((diffMs % DAY_MS) / HOUR_MS); + const minutes = Math.floor((diffMs % HOUR_MS) / MINUTE_MS); + if (days > 0) return remaining({ unit: "days", count: days }, { unit: "hours", count: hours }); + if (hours > 0) + return remaining({ unit: "hours", count: hours }, { unit: "minutes", count: minutes }); + return remaining({ unit: "minutes", count: minutes }); } -function formatRelativeDuration(duration: RelativeDuration, t: TFunction): string | null { - switch (duration.unit) { - case "now": - return null; - case "days": - return t("providerUsage.duration.days", { - count: duration.count, - value: formatCount(duration.count), - }); - case "hours": - return t("providerUsage.duration.hours", { - count: duration.count, - value: formatCount(duration.count), - }); - case "minutes": - return t("providerUsage.duration.minutes", { - count: duration.count, - value: formatCount(duration.count), - }); - } +/** The major unit, plus the minor one unless it is zero. */ +function remaining(major: DurationPart, minor?: DurationPart): RelativeDuration { + return { kind: "remaining", parts: minor && minor.count > 0 ? [major, minor] : [major] }; +} + +function formatDurationPart(part: DurationPart, t: TFunction): string { + return t(`providerUsage.duration.${part.unit}`, { + count: part.count, + value: formatCount(part.count), + }); +} + +function formatRelativeDuration( + duration: Extract, + t: TFunction, +): string { + const [first, second] = duration.parts.map((part) => formatDurationPart(part, t)); + return second ? t("providerUsage.duration.pair", { first, second }) : first; } export function formatResetLabel( @@ -99,10 +109,34 @@ export function formatResetLabel( if (!iso) return null; const rel = relativeDuration(iso, now); if (!rel) return null; - if (rel.unit === "now" && retained) return t("providerUsage.timing.resetTimePassed"); - if (rel.unit === "now") return t("providerUsage.timing.resettingNow"); - const duration = formatRelativeDuration(rel, t); - return duration ? t("providerUsage.timing.resetsIn", { duration }) : null; + if (rel.kind === "now" && retained) return t("providerUsage.timing.resetTimePassed"); + if (rel.kind === "now") return t("providerUsage.timing.resettingNow"); + return t("providerUsage.timing.resetsIn", { duration: formatRelativeDuration(rel, t) }); +} + +/** + * When a window resets on the clock: "3:00 PM" within a day, "Fri 3:00 PM" within a week, + * "Oct 31, 3:00 PM" after that. Names follow the app language; 12/24h follows the device. + * Nothing for a time that has passed, where the countdown already says so. + */ +export function formatResetTime( + iso: string | null | undefined, + now = Date.now(), + t: TFunction = i18n.t, +): string | null { + if (!iso) return null; + const at = new Date(iso); + const diffMs = at.getTime() - now; + if (!Number.isFinite(diffMs) || diffMs <= 0) return null; + const time = formatTimeOfDay(at); + const locale = i18n.resolvedLanguage; + if (diffMs < DAY_MS) return time; + if (diffMs < 7 * DAY_MS) { + const weekday = at.toLocaleDateString(locale, { weekday: "short" }); + return t("providerUsage.timing.resetsAtWeekday", { weekday, time }); + } + const date = at.toLocaleDateString(locale, { month: "short", day: "numeric" }); + return t("providerUsage.timing.resetsAtDate", { date, time }); } export function formatRunsOutLabel( @@ -113,9 +147,8 @@ export function formatRunsOutLabel( if (!iso) return null; const rel = relativeDuration(iso, now); if (!rel) return null; - if (rel.unit === "now") return t("providerUsage.timing.runsOutNow"); - const duration = formatRelativeDuration(rel, t); - return duration ? t("providerUsage.timing.runsOutIn", { duration }) : null; + if (rel.kind === "now") return t("providerUsage.timing.runsOutNow"); + return t("providerUsage.timing.runsOutIn", { duration: formatRelativeDuration(rel, t) }); } export function formatAgo( diff --git a/packages/app/src/usage/meter.tsx b/packages/app/src/usage/meter.tsx index 37842cafb5..4150477801 100644 --- a/packages/app/src/usage/meter.tsx +++ b/packages/app/src/usage/meter.tsx @@ -46,8 +46,8 @@ export function UsageMeter({ const styles = StyleSheet.create((theme) => ({ track: { - height: 4, - borderRadius: 2, + height: 6, + borderRadius: 3, backgroundColor: theme.colors.surface3, overflow: "hidden", }, diff --git a/packages/app/src/usage/reset-line.tsx b/packages/app/src/usage/reset-line.tsx new file mode 100644 index 0000000000..8016df2926 --- /dev/null +++ b/packages/app/src/usage/reset-line.tsx @@ -0,0 +1,48 @@ +import { Text, View } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; + +/** + * The reset data of a window or balance: the countdown first, then the exact time. When the line + * is too narrow the exact time gives way (truncates) and the countdown stays whole. + */ +export function UsageResetLine({ + countdown, + exactTime, + atRisk = false, + testID, +}: { + countdown: string | null; + exactTime: string | null; + /** The countdown is a runs-out warning rather than a reset. */ + atRisk?: boolean; + testID?: string; +}) { + if (!countdown) return null; + return ( + + {countdown} + {exactTime ? ( + + {`\u00a0·\u00a0${exactTime}`} + + ) : null} + + ); +} + +const styles = StyleSheet.create((theme) => ({ + line: { flexDirection: "row", alignItems: "center" }, + text: { + flexShrink: 0, + color: theme.colors.foregroundMuted, + fontSize: theme.fontSize.sm, + fontWeight: theme.fontWeight.normal, + }, + atRisk: { + flexShrink: 0, + color: theme.colors.statusDanger, + fontSize: theme.fontSize.sm, + fontWeight: theme.fontWeight.normal, + }, + exactTime: { flexShrink: 1 }, +})); diff --git a/packages/app/src/usage/sidebar-item.tsx b/packages/app/src/usage/sidebar-item.tsx index 45a8a8b293..2ca99c4e29 100644 --- a/packages/app/src/usage/sidebar-item.tsx +++ b/packages/app/src/usage/sidebar-item.tsx @@ -192,12 +192,7 @@ function PinnedUsageLine({ {layout === "meters" ? ( - + ) : null} ({ minWidth: MIN_METER_WIDTH, marginRight: METER_GAP, }, - meter: { - height: 6, - borderRadius: 3, - }, percent: { flexShrink: 0, color: theme.colors.foreground, diff --git a/packages/app/src/usage/window-bar.tsx b/packages/app/src/usage/window-bar.tsx index 99c1eb9f21..b837872e01 100644 --- a/packages/app/src/usage/window-bar.tsx +++ b/packages/app/src/usage/window-bar.tsx @@ -1,29 +1,24 @@ import { Pin } from "lucide-react-native"; import { useMemo } from "react"; import { useTranslation } from "react-i18next"; -import { Pressable, Text, View, type StyleProp, type ViewStyle } from "react-native"; +import { Pressable, Text, View } from "react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; import { formatDisplayPct, formatProviderUsageLabel, formatResetLabel, + formatResetTime, formatRunsOutLabel, } from "./format"; import { UsageMeter } from "./meter"; import { displayPercent, usageWindowRowLabel } from "./model"; +import { UsageResetLine } from "./reset-line"; import type { UsageDisplayAs } from "./preferences"; import { windowTone } from "./tone"; import type { UsageTone, UsageWindow } from "./types"; import { useRelativeTimeTick } from "./use-relative-time-tick"; -// Pinned rows carry the pinned surface; hovering an unpinned row previews it at half strength, -// so a hover never reads as the selection. Pinned rows do not react to hover. -function highlightStyle(pinned: boolean, hovered: boolean) { - if (pinned) return styles.highlightPinned; - return hovered ? styles.highlightHovered : styles.highlightNone; -} - export function UsageWindowBar({ window, displayAs, @@ -54,9 +49,12 @@ export function UsageWindowBar({ window.runsOutAt != null && window.shortfallPct != null && (!retained || Date.parse(window.runsOutAt) > now); - const trailing = isAtRisk + const countdown = isAtRisk ? formatRunsOutLabel(window.runsOutAt, now, t) : formatResetLabel(window.resetsAt, retained, now, t); + // The exact time belongs to the reset; beside a runs-out warning it would read as the moment + // the quota runs out. + const exactTime = isAtRisk ? null : formatResetTime(window.resetsAt, now, t); const value = shownPct != null ? formatDisplayPct(shownPct, displayAs, i18n.resolvedLanguage, t) : "—"; @@ -64,60 +62,57 @@ export function UsageWindowBar({ const content = { label: formatProviderUsageLabel(window.id, window.label, t), value, - trailing, + countdown, + exactTime, isAtRisk, percent: shownPct ?? 0, tone, pinned, }; - // Same padding as the pinnable row, so bars line up in both modes. if (!pinnable) { return ( - + ); } - // The whole row pins the window to the sidebar Usage item. Pinned or not, it keeps the same - // padding so toggling only changes the background. + // The whole row pins the window to the sidebar Usage item; the pin glyph is the only sign of it. return ( - {({ hovered }: { hovered?: boolean }) => ( - - )} + ); } function WindowRowContent({ - highlight, label, value, - trailing, + countdown, + exactTime, isAtRisk, percent, tone, pinnable, pinned, }: { - highlight: StyleProp; label: string; value: string; - trailing: string | null | undefined; + countdown: string | null; + exactTime: string | null; isAtRisk: boolean; percent: number; tone: UsageTone; @@ -126,24 +121,17 @@ function WindowRowContent({ }) { return ( <> - - - - - - {label} - - - {value} - {trailing ? ( - {` · ${trailing}`} - ) : null} - - - - + + + {label} + + + {value} + {pinnable ? : null} + + ); } @@ -153,9 +141,9 @@ const ThemedPin = withUnistyles(Pin); function UsagePinGlyph({ pinned }: { pinned: boolean }) { const { t } = useTranslation(); const iconMapping = useMemo( - () => (theme: { colors: { foregroundMuted: string } }) => ({ - color: theme.colors.foregroundMuted, - fill: pinned ? theme.colors.foregroundMuted : "none", + () => (theme: { colors: { foreground: string; foregroundMuted: string } }) => ({ + color: pinned ? theme.colors.foreground : theme.colors.foregroundMuted, + fill: pinned ? theme.colors.foreground : "none", }), [pinned], ); @@ -179,59 +167,23 @@ function UsagePinGlyph({ pinned }: { pinned: boolean }) { } const styles = StyleSheet.create((theme) => ({ - contentRow: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2] }, - windowContent: { flex: 1, gap: 3 }, + row: { gap: 3, paddingVertical: theme.spacing[1.5] }, pin: { width: 12, alignItems: "center" }, tooltipText: { color: theme.colors.popoverForeground, fontSize: theme.fontSize.sm }, - row: { - gap: 3, - // The highlight bleeds into the card padding so the label and bar stay on the card's rail. - marginHorizontal: -theme.spacing[2], - paddingHorizontal: theme.spacing[2], - paddingVertical: theme.spacing[1.5], - // Its own stacking context, so the highlight layer paints above the card and below the text. - zIndex: 0, - }, - highlightNone: { - display: "none", - }, - highlightPinned: { - ...StyleSheet.absoluteFill, - zIndex: -1, - borderRadius: theme.borderRadius.md, - backgroundColor: theme.colors.surface2, - }, - // The pinned surface at half strength: a separate layer, so the text keeps full opacity. - highlightHovered: { - ...StyleSheet.absoluteFill, - zIndex: -1, - borderRadius: theme.borderRadius.md, - backgroundColor: theme.colors.surface2, - opacity: theme.opacity[50], - }, labelRow: { flexDirection: "row", - justifyContent: "space-between", alignItems: "center", gap: theme.spacing[2], }, label: { flex: 1, - color: theme.colors.foregroundMuted, - fontSize: theme.fontSize.sm, - }, - value: { - flexShrink: 1, color: theme.colors.foreground, fontSize: theme.fontSize.sm, fontWeight: theme.fontWeight.medium, }, - reset: { - color: theme.colors.foregroundMuted, - fontWeight: theme.fontWeight.normal, - }, - atRisk: { - color: theme.colors.statusDanger, - fontWeight: theme.fontWeight.normal, + value: { + flexShrink: 0, + color: theme.colors.foreground, + fontSize: theme.fontSize.sm, }, })); diff --git a/packages/app/src/utils/time.ts b/packages/app/src/utils/time.ts index 948ee8eeb3..1c063d1a27 100644 --- a/packages/app/src/utils/time.ts +++ b/packages/app/src/utils/time.ts @@ -125,6 +125,11 @@ function getTimeFormatter(): Intl.DateTimeFormat { return cachedTimeFormatter; } +/** A clock time in the device's 12h/24h preference: "3:00 PM" or "15:00". */ +export function formatTimeOfDay(date: Date): string { + return getTimeFormatter().format(date); +} + /** * Format a chat-message timestamp for hover-revealed UI. * - Same day: "10:11 PM" or "22:11" depending on user preference @@ -132,7 +137,7 @@ function getTimeFormatter(): Intl.DateTimeFormat { * - Older, including today's weekday last week: "14 May 2026, 10:11 PM" */ export function formatMessageTimestamp(date: Date, now: Date = new Date()): string { - const time = getTimeFormatter().format(date); + const time = formatTimeOfDay(date); const daysAgo = localCalendarDaysBetween(date, now); if (daysAgo === 0) { From e8201ab66b79a2c6438d3a7eb1edba688ccb7307 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Thu, 29 Oct 2026 12:45:41 +0700 Subject: [PATCH 102/173] Make Claude session entrypoint relabeling optional (#8164) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(claude): make session entrypoint relabeling opt-in Keep inherited SDK and parent identities cleared. Honor the explicit session-open entrypoint contribution so users can opt into the label through a plugin instead of every session receiving it unconditionally. * test(hub): use standard budget for restart and worktree recovery The Windows CI scenario timed out at its custom 20-second limit while the other Hub cases took 4–10 seconds each. This scenario starts two daemons and creates, archives and restores a worktree. Use the existing 30-second suite budget without changing any assertions. --- .../agent/providers/claude/agent.env.test.ts | 17 +++-- .../server/agent/providers/claude/query.ts | 5 +- .../hub/execution-session.websocket.test.ts | 2 +- .../plugins/agent-configuration.e2e.test.ts | 72 ++++++++++++++++++- 4 files changed, 86 insertions(+), 10 deletions(-) diff --git a/packages/server/src/server/agent/providers/claude/agent.env.test.ts b/packages/server/src/server/agent/providers/claude/agent.env.test.ts index 0806a0dbc6..6d268e932c 100644 --- a/packages/server/src/server/agent/providers/claude/agent.env.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.env.test.ts @@ -30,16 +30,20 @@ function createQueryMock(events: unknown[]): Query { } describe("Claude SDK env", () => { - test.each(["node", "bun", process.execPath])( - "identifies the spawned %s process as Paseo after clearing parent session env", - async (command) => { + test.each( + ["node", "bun", process.execPath].flatMap((command) => + [undefined, "Paseo", "custom-client"].map((entrypoint) => ({ command, entrypoint })), + ), + )( + "preserves explicit launch identity $entrypoint in $command while clearing inherited session env", + async ({ command, entrypoint }) => { let output = ""; let exited = Promise.resolve([]); const query = claudeQuery( { prompt: "", options: {} }, { runtimeSettings: { env: { CLAUDE_CODE_ENTRYPOINT: "sdk-ts" } }, - launchEnv: { CLAUDE_CODE_ENTRYPOINT: "sdk-cli" }, + launchEnv: entrypoint === undefined ? {} : { CLAUDE_CODE_ENTRYPOINT: entrypoint }, queryFactory: ({ options }) => { if (!options.spawnClaudeCodeProcess) { throw new Error("Missing Claude process launcher"); @@ -65,7 +69,10 @@ describe("Claude SDK env", () => { try { expect(await exited).toEqual([0, null]); - expect(JSON.parse(output)).toEqual({ entrypoint: "Paseo", parentSession: null }); + expect(JSON.parse(output)).toEqual({ + ...(entrypoint === undefined ? {} : { entrypoint }), + parentSession: null, + }); } finally { query.close(); } diff --git a/packages/server/src/server/agent/providers/claude/query.ts b/packages/server/src/server/agent/providers/claude/query.ts index c8fe4ba036..0f9525d5b1 100644 --- a/packages/server/src/server/agent/providers/claude/query.ts +++ b/packages/server/src/server/agent/providers/claude/query.ts @@ -73,8 +73,9 @@ function applyRuntimeSettingsToClaudeOptions( runtimeSettings, overlays: [launchEnv], }); - // Set our identity after sanitization clears the parent session's entrypoint. - providerEnvSpec.envOverlay.CLAUDE_CODE_ENTRYPOINT = "Paseo"; + // Session-open hooks may explicitly supply a client identity. Keep inherited + // SDK/parent identities cleared while honoring this launch-only contribution. + providerEnvSpec.envOverlay.CLAUDE_CODE_ENTRYPOINT = launchEnv?.CLAUDE_CODE_ENTRYPOINT; const providerEnv = createExternalProcessEnv(spawnOptions.env, providerEnvSpec.envOverlay); const selfNodeCommand = isDefaultRuntime ? buildSelfNodeCommand(resolved.args, providerEnv) diff --git a/packages/server/src/server/hub/execution-session.websocket.test.ts b/packages/server/src/server/hub/execution-session.websocket.test.ts index 88f376b3ba..266c55e196 100644 --- a/packages/server/src/server/hub/execution-session.websocket.test.ts +++ b/packages/server/src/server/hub/execution-session.websocket.test.ts @@ -248,7 +248,7 @@ test("ordinary Hub requests survive daemon restart and restore an archived works }), ).toMatchObject({ payload: { agentId, accepted: true } }); expect(hub.providerPromptTexts().filter((text) => text === "follow up")).toHaveLength(1); -}, 20_000); +}); test("Hub completes the standard hello before rejecting a second hello", async () => { const hub = await launchRelationship(); diff --git a/packages/server/src/server/plugins/agent-configuration.e2e.test.ts b/packages/server/src/server/plugins/agent-configuration.e2e.test.ts index 9f62075125..a3e4e273a4 100644 --- a/packages/server/src/server/plugins/agent-configuration.e2e.test.ts +++ b/packages/server/src/server/plugins/agent-configuration.e2e.test.ts @@ -1,10 +1,10 @@ -import { mkdtemp, rm } from "node:fs/promises"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { expect, test } from "vitest"; import { DaemonClient } from "../test-utils/daemon-client.js"; -import type { AgentSessionConfig } from "../agent/agent-sdk-types.js"; +import type { AgentClient, AgentSessionConfig } from "../agent/agent-sdk-types.js"; import { createTestAgentClient } from "../test-utils/fake-agent-client.js"; import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js"; @@ -72,3 +72,71 @@ test("the configuration example saves Codex options and injects launch-only MCP await rm(directory, { recursive: true, force: true }); } }, 60_000); + +test("session-open entrypoint contributions are optional and rederived for existing agents", async () => { + const directory = await mkdtemp(path.join(tmpdir(), "paseo-entrypoint-hook-")); + const launches: { provider: string; env?: Record }[] = []; + function recordingProvider(provider: "claude" | "codex"): AgentClient { + const inner = createTestAgentClient(provider); + return { + provider: inner.provider, + capabilities: inner.capabilities, + isAvailable: () => inner.isAvailable(), + fetchCatalog: (options) => inner.fetchCatalog(options), + createSession: async (...args: Parameters) => { + launches.push({ provider, env: args[1]?.env }); + return inner.createSession(...args); + }, + resumeSession: async (...args: Parameters) => { + launches.push({ provider, env: args[2]?.env }); + return inner.resumeSession(...args); + }, + }; + } + const daemon = await createTestPaseoDaemon({ + daemonVersion: "0.14.0-beta.2", + agentClients: { claude: recordingProvider("claude"), codex: recordingProvider("codex") }, + mcpEnabled: false, + }); + const client = new DaemonClient({ + url: `ws://127.0.0.1:${daemon.port}/ws`, + appVersion: "0.14.0-beta.2", + }); + try { + await writeFile( + path.join(directory, "paseo-plugin.json"), + JSON.stringify({ id: "entrypoint-test", requirements: { paseo: ">=0.14.0-beta.2" } }), + ); + await writeFile( + path.join(directory, "index.server.ts"), + ` +export default function contribute(server) { + return server.before("agent.session_open", ({ request }) => { + if (request.provider !== "claude") return; + return { ...request, env: { ...request.env, CLAUDE_CODE_ENTRYPOINT: "custom-client" } }; + }); +} +`, + ); + await client.connect(); + await client.fetchAgents({ subscribe: {} }); + const existing = await client.createAgent({ provider: "claude", cwd: directory }); + expect(launches.at(-1)?.env?.CLAUDE_CODE_ENTRYPOINT).toBeUndefined(); + await client.patchDaemonConfig({ pluginsEnabled: true }); + await client.installDirectoryPlugin(directory); + await daemon.daemon.agentManager.reloadAgentSession(existing.id); + expect(launches.at(-1)?.env?.CLAUDE_CODE_ENTRYPOINT).toBe("custom-client"); + await client.createAgent({ provider: "claude", cwd: directory }); + expect(launches.at(-1)?.env?.CLAUDE_CODE_ENTRYPOINT).toBe("custom-client"); + await client.createAgent({ provider: "codex", cwd: directory }); + expect(launches.at(-1)).toMatchObject({ provider: "codex" }); + expect(launches.at(-1)?.env?.CLAUDE_CODE_ENTRYPOINT).toBeUndefined(); + await client.disablePlugin("entrypoint-test"); + await daemon.daemon.agentManager.reloadAgentSession(existing.id); + expect(launches.at(-1)?.env?.CLAUDE_CODE_ENTRYPOINT).toBeUndefined(); + } finally { + await client.close(); + await daemon.close(); + await rm(directory, { recursive: true, force: true }); + } +}, 60_000); From 870a44bc7f04b2fafd0f2cb73a911125ecd15043 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Thu, 29 Oct 2026 05:55:50 +0000 Subject: [PATCH 103/173] Deliver a steer message that arrives while the previous turn is still starting (#6192) * Deliver a steer message that arrives while the previous turn is still starting A steer send that reached an agent before its previous turn had a turn id found no turn to steer and replaced the starting turn, so the earlier message never reached the provider. Steering now waits for the starting turn to be accepted (or fail) and steers the turn it became. Fixes #6186 * Wake a waiting steer only once the starting turn has an id or its run has ended A failed start used to wake the waiting steer before its run was cleared, leaving the later send to replace a run that had already failed. * Clear a failed start's run even when reporting the failure throws A steer waiting on that start is released only when the run is cleared. * Test that a failed start keeps a waiting steer until its run is cleared * fix(server): steer Codex turns while native identification is pending Wait for the accepted foreground turn to receive its native ID before steering it. Returning unavailable in this window replaced the turn even after the manager had waited for startup. --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../src/server/agent/agent-manager.test.ts | 125 ++++++++++++++++++ .../server/src/server/agent/agent-manager.ts | 35 +++-- .../src/server/agent/agent-run-state.test.ts | 51 +++++++ .../src/server/agent/agent-run-state.ts | 40 +++++- .../providers/codex-app-server-agent.test.ts | 58 ++++++++ .../agent/providers/codex-app-server-agent.ts | 13 +- .../codex-steer-starting.real.e2e.test.ts | 80 +++++++++++ 7 files changed, 382 insertions(+), 20 deletions(-) create mode 100644 packages/server/src/server/agent/agent-run-state.test.ts create mode 100644 packages/server/src/server/daemon-e2e/codex-steer-starting.real.e2e.test.ts diff --git a/packages/server/src/server/agent/agent-manager.test.ts b/packages/server/src/server/agent/agent-manager.test.ts index 1d6f323deb..bb521abc71 100644 --- a/packages/server/src/server/agent/agent-manager.test.ts +++ b/packages/server/src/server/agent/agent-manager.test.ts @@ -956,6 +956,131 @@ test("unavailable steer interrupts once and starts one replacement turn", async } }); +test("steers a send that arrives while the previous turn is still starting", async () => { + const startHeld = deferred(); + class SlowStartSteeringSession extends SteeringTestSession { + override async startTurn(prompt: AgentPromptInput): Promise<{ turnId: string }> { + await startHeld.promise; + return await super.startTurn(prompt); + } + } + const session = new SlowStartSteeringSession({ + provider: "codex", + cwd: process.cwd(), + }); + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-steer-starting-")); + const manager = new AgentManager({ + clients: { + codex: new (class extends TestAgentClient { + override async createSession(): Promise { + return session; + } + })(), + }, + logger, + }); + let agentId: string | null = null; + try { + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + agentId = agent.id; + const steerOptions = (clientMessageId: string) => ({ + replaceRunning: true, + activeTurnBehavior: "steer" as const, + runOptions: { clientMessageId }, + }); + await startAgentRun(manager, agent.id, "FIRST", logger, steerOptions("first-client")); + const second = startAgentRun( + manager, + agent.id, + "SECOND", + logger, + steerOptions("second-client"), + ); + + startHeld.resolve(); + await expect(second).resolves.toEqual({ disposition: "steered" }); + + expect(session.startPrompts).toEqual(["FIRST"]); + expect(session.interruptCount).toBe(0); + expect( + manager + .fetchTimeline(agent.id, { limit: 0 }) + .rows.filter((row) => row.item.type === "user_message") + .map((row) => ({ + text: row.item.type === "user_message" ? row.item.text : null, + turnId: row.turnId, + })), + ).toEqual([ + { text: "FIRST", turnId: "active-turn-1" }, + { text: "SECOND", turnId: "active-turn-1" }, + ]); + } finally { + startHeld.resolve(); + if (agentId) await manager.closeAgent(agentId).catch(() => undefined); + rmSync(workdir, { recursive: true, force: true }); + } +}); + +test("starts its own turn when the previous turn fails to start under a steer send", async () => { + const startHeld = deferred(); + class FailingFirstStartSession extends SteeringTestSession { + override async startTurn(prompt: AgentPromptInput): Promise<{ turnId: string }> { + if (prompt === "FIRST") { + this.startPrompts.push(prompt); + await startHeld.promise; + throw new Error("first start failed"); + } + return await super.startTurn(prompt); + } + } + const session = new FailingFirstStartSession({ + provider: "codex", + cwd: process.cwd(), + }); + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-steer-failed-start-")); + const manager = new AgentManager({ + clients: { + codex: new (class extends TestAgentClient { + override async createSession(): Promise { + return session; + } + })(), + }, + logger, + }); + let agentId: string | null = null; + try { + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + agentId = agent.id; + const steerOptions = (clientMessageId: string) => ({ + replaceRunning: true, + activeTurnBehavior: "steer" as const, + runOptions: { clientMessageId }, + }); + await startAgentRun(manager, agent.id, "FIRST", logger, steerOptions("first-client")); + const second = startAgentRun( + manager, + agent.id, + "SECOND", + logger, + steerOptions("second-client"), + ); + + startHeld.resolve(); + await expect(second).resolves.toEqual({ disposition: "turn_started" }); + await vi.waitFor(() => expect(session.startPrompts).toEqual(["FIRST", "SECOND"])); + expect(session.interruptCount).toBe(0); + } finally { + startHeld.resolve(); + if (agentId) await manager.closeAgent(agentId).catch(() => undefined); + rmSync(workdir, { recursive: true, force: true }); + } +}); + test("orders an accepted steer before output emitted while acknowledgement is pending", async () => { const entered = deferred(); const release = deferred(); diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index 46c822ea2d..ae9e424d78 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -2734,7 +2734,7 @@ export class AgentManager { throw error; } if (isStaleProviderSessionError(error)) { - pendingRun.start = { status: "failed", error: error.message }; + this.runs.settleForegroundStart(pendingRun, { status: "failed", error: error.message }); agent.pendingReplacement = false; if (!agent.activeForegroundTurnId) agent.lifecycle = "idle"; this.runs.settleForegroundRun(agentId, pendingRun.token); @@ -2742,20 +2742,24 @@ export class AgentManager { } agent.pendingReplacement = false; const errorMsg = error instanceof Error ? error.message : "Failed to start turn"; - pendingRun.start = { status: "failed", error: errorMsg }; - // A terminal rejection belongs after the submitted prompt even though no provider turn exists. - if (options?.clientMessageId) { - this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "rejected", { - messageId: options.clientMessageId, + this.runs.settleForegroundStart(pendingRun, { status: "failed", error: errorMsg }); + try { + // A terminal rejection belongs after the submitted prompt even though no provider turn exists. + if (options?.clientMessageId) { + this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "rejected", { + messageId: options.clientMessageId, + }); + } + await this.handleStreamEvent(agent, { + type: "turn_failed", + provider: agent.provider, + error: errorMsg, }); + this.finalizeForegroundTurn(agent); + } finally { + // A steer waiting on this start is released only once the run is cleared. + this.runs.settleForegroundRun(agentId, pendingRun.token); } - await this.handleStreamEvent(agent, { - type: "turn_failed", - provider: agent.provider, - error: errorMsg, - }); - this.finalizeForegroundTurn(agent); - this.runs.settleForegroundRun(agentId, pendingRun.token); throw error; } } @@ -2832,7 +2836,7 @@ export class AgentManager { agent.pendingReplacement = false; } const turnStartedAt = new Date(); - pendingRun.start = { status: "started", turnId }; + this.runs.settleForegroundStart(pendingRun, { status: "started", turnId }); agent.activeForegroundTurnId = turnId; this.openActiveTurn(agent, turnId, turnStartedAt); agent.lifecycle = "running"; @@ -3041,6 +3045,9 @@ export class AgentManager { prompt: AgentPromptInput, options?: AgentSteerOptions, ): Promise { + // A turn that is still starting has no id to steer yet. Replacing it would drop its + // prompt, so wait until it is accepted (or fails) and steer the turn it became. + await this.runs.waitForForegroundStart(agentId); const agent = this.requireSessionAgent(agentId); const expectedTurnId = agent.activeForegroundTurnId ?? agent.activeTurnId; if (!expectedTurnId) { diff --git a/packages/server/src/server/agent/agent-run-state.test.ts b/packages/server/src/server/agent/agent-run-state.test.ts new file mode 100644 index 0000000000..29e09a5f94 --- /dev/null +++ b/packages/server/src/server/agent/agent-run-state.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, test } from "vitest"; + +import { AgentRunState } from "./agent-run-state.js"; + +function track(promise: Promise): { readonly resolved: boolean } { + const state = { resolved: false }; + void (async () => { + await promise; + state.resolved = true; + })(); + return state; +} + +async function flushMicrotasks(): Promise { + await new Promise((resolve) => setImmediate(resolve)); +} + +describe("waitForForegroundStart", () => { + test("resolves once the starting turn has an id", async () => { + const runs = new AgentRunState(); + const run = runs.createPendingRun("agent"); + const wait = track(runs.waitForForegroundStart("agent")); + + await flushMicrotasks(); + expect(wait.resolved).toBe(false); + + runs.settleForegroundStart(run, { status: "started", turnId: "turn-1" }); + await flushMicrotasks(); + expect(wait.resolved).toBe(true); + }); + + test("waits for a failed start's run to be cleared", async () => { + const runs = new AgentRunState(); + const run = runs.createPendingRun("agent"); + const wait = track(runs.waitForForegroundStart("agent")); + + runs.settleForegroundStart(run, { status: "failed", error: "start failed" }); + await flushMicrotasks(); + expect(wait.resolved).toBe(false); + expect(runs.hasPendingRun("agent")).toBe(true); + + runs.settleForegroundRun("agent", run.token); + await flushMicrotasks(); + expect(wait.resolved).toBe(true); + }); + + test("resolves at once when no turn is starting", async () => { + const runs = new AgentRunState(); + await expect(runs.waitForForegroundStart("agent")).resolves.toBeUndefined(); + }); +}); diff --git a/packages/server/src/server/agent/agent-run-state.ts b/packages/server/src/server/agent/agent-run-state.ts index ad1eb0af34..0ea85f6d81 100644 --- a/packages/server/src/server/agent/agent-run-state.ts +++ b/packages/server/src/server/agent/agent-run-state.ts @@ -10,14 +10,18 @@ export interface ForegroundTurnWaiter { resolveSettled: () => void; } +type ForegroundRunStart = + | { status: "pending" } + | { status: "started"; turnId: string } + | { status: "failed"; error: string }; + export interface PendingForegroundRun { token: string; kind: "foreground"; stagedEvents: AgentStreamEvent[]; - start: - | { status: "pending" } - | { status: "started"; turnId: string } - | { status: "failed"; error: string }; + start: ForegroundRunStart; + turnStartedPromise: Promise; + resolveTurnStarted: () => void; settled: boolean; settledPromise: Promise; resolveSettled: () => void; @@ -54,6 +58,28 @@ export class AgentRunState { return run?.kind === "foreground" ? run : null; } + settleForegroundStart( + run: PendingForegroundRun, + start: Exclude, + ): void { + run.start = start; + if (start.status === "started") { + run.resolveTurnStarted(); + } + } + + /** + * Resolves once the agent's foreground run has a turn id or has ended. A failed start + * resolves only once its run is cleared, so callers never see a failed run still tracked. + */ + async waitForForegroundStart(agentId: string): Promise { + const run = this.getPendingRun(agentId); + if (run?.start.status !== "pending") { + return; + } + await Promise.race([run.turnStartedPromise, run.settledPromise]); + } + hasPendingRun(agentId: string): boolean { return this.getPendingRun(agentId) !== null; } @@ -277,10 +303,16 @@ export class ForegroundTurnStream { } function createPendingForegroundRun(): PendingForegroundRun { + let resolveTurnStarted!: () => void; + const turnStartedPromise = new Promise((resolvePromise) => { + resolveTurnStarted = resolvePromise; + }); return { ...createTrackedRunState(), kind: "foreground", start: { status: "pending" }, + turnStartedPromise, + resolveTurnStarted, stagedEvents: [], }; } diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts index 2169a059f2..e709fd490c 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts @@ -226,6 +226,64 @@ function deferred() { } describe("Codex active-turn steering admission", () => { + test("steers an accepted turn whose native id arrives after startTurn returns", async () => { + const appServer = createFakeCodexAppServer({ + "turn/steer": () => ({ turn: { id: "native-A" } }), + }); + const session = new CodexAppServerAgentSession( + createConfig({ cwd: "/workspace/project" }), + null, + createTestLogger(), + async () => appServer.child, + ); + try { + const { turnId } = await session.startTurn("FIRST"); + const steer = session.steerActiveTurn("SECOND", { expectedTurnId: turnId }); + appServer.startsTurn({ threadId: "thread-1", turnId: "native-A" }); + + await expect(steer).resolves.toEqual({ status: "accepted" }); + expect( + appServer.requests().filter((request) => request.method === "turn/start"), + ).toHaveLength(1); + expect(appServer.requests().filter((request) => request.method === "turn/interrupt")).toEqual( + [], + ); + expect(appServer.requests().find((request) => request.method === "turn/steer")).toMatchObject( + { + params: { + threadId: "thread-1", + expectedTurnId: "native-A", + input: [{ type: "text", text: "SECOND" }], + }, + }, + ); + appServer.assertNoErrors(); + } finally { + await session.close(); + } + }); + + test("releases a waiting steer when the accepted turn ends before identification", async () => { + const appServer = createFakeCodexAppServer(); + const session = new CodexAppServerAgentSession( + createConfig({ cwd: "/workspace/project" }), + null, + createTestLogger(), + async () => appServer.child, + ); + try { + const { turnId } = await session.startTurn("FIRST"); + const steer = session.steerActiveTurn("SECOND", { expectedTurnId: turnId }); + appServer.completeTurn(); + + await expect(steer).resolves.toEqual({ status: "unavailable" }); + expect(appServer.requests().filter((request) => request.method === "turn/steer")).toEqual([]); + appServer.assertNoErrors(); + } finally { + await session.close(); + } + }); + test("a steer without the clearing contract leaves permissions open", async () => { const appServer = createFakeCodexAppServer({ "turn/steer": () => ({ turn: { id: "native-A" } }), diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.ts index cdad017d45..5e43f582c5 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.ts @@ -4456,9 +4456,18 @@ export class CodexAppServerAgentSession implements AgentSession { ): Promise { const client = this.client; const threadId = this.currentThreadId; - const nativeTurnId = this.currentTurnId; + let nativeTurnId = this.currentTurnId; const foregroundTurnId = this.activeForegroundTurnId; - if (!client || !threadId || !nativeTurnId || foregroundTurnId !== options.expectedTurnId) { + if (!client || !threadId || foregroundTurnId !== options.expectedTurnId) { + return { status: "unavailable" }; + } + const pendingIdentification = this.pendingForegroundTurnIdentification; + // The start acknowledgement precedes the notification that identifies the native + // turn. Keep this steer attached to the accepted foreground turn while it arrives. + if (!nativeTurnId && pendingIdentification?.foregroundTurnId === foregroundTurnId) { + nativeTurnId = await pendingIdentification.promise; + } + if (!nativeTurnId) { return { status: "unavailable" }; } if (await this.resolveSlashCommandInvocation(prompt)) return { status: "unavailable" }; diff --git a/packages/server/src/server/daemon-e2e/codex-steer-starting.real.e2e.test.ts b/packages/server/src/server/daemon-e2e/codex-steer-starting.real.e2e.test.ts new file mode 100644 index 0000000000..60508205f2 --- /dev/null +++ b/packages/server/src/server/daemon-e2e/codex-steer-starting.real.e2e.test.ts @@ -0,0 +1,80 @@ +import { expect, test } from "vitest"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import pino from "pino"; + +import { CodexAppServerAgentClient } from "../agent/providers/codex-app-server-agent.js"; +import { DaemonClient } from "../test-utils/daemon-client.js"; +import { createMessageCollector } from "../test-utils/message-collector.js"; +import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js"; +import { canRunRealProvider } from "./real-provider-test-config.js"; + +test("keeps two concurrent startup steer messages in one real Codex turn", async (context) => { + if (!(await canRunRealProvider("codex"))) { + context.skip(); + return; + } + const cwd = mkdtempSync(path.join(tmpdir(), "codex-steer-starting-")); + const logger = pino({ level: "silent" }); + const daemon = await createTestPaseoDaemon({ + agentClients: { codex: new CodexAppServerAgentClient(logger) }, + logger, + }); + const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); + const collector = createMessageCollector(client); + const subscriptions: ReturnType[] = []; + try { + await client.connect(); + await client.fetchAgents({ subscribe: {} }); + for (let attempt = 0; attempt < 3; attempt += 1) { + const agent = await client.createAgent({ + cwd, + provider: "codex", + modeId: "full-access", + }); + const subscription = client.subscribeAgentTimeline(agent.id, () => {}); + subscriptions.push(subscription); + await subscription.ready; + await Promise.all([ + client.sendAgentMessage(agent.id, "Reply exactly: FIRST", { + messageId: `first-${attempt}`, + activeTurnBehavior: "steer", + }), + client.sendAgentMessage(agent.id, "Reply exactly: SECOND", { + messageId: `second-${attempt}`, + activeTurnBehavior: "steer", + }), + ]); + await client.waitForFinish(agent.id, 90_000); + const timeline = await client.fetchAgentTimeline(agent.id, { limit: 100 }); + const users = timeline.entries.filter((entry) => entry.item.type === "user_message"); + const events = collector.messages.flatMap((message) => + message.type === "agent_stream" && message.payload.agentId === agent.id + ? [message.payload.event] + : [], + ); + expect(users.map((entry) => entry.item.text).sort()).toEqual([ + "Reply exactly: FIRST", + "Reply exactly: SECOND", + ]); + expect(new Set(users.map((entry) => entry.turnId)).size).toBe(1); + expect(events.filter((event) => event.type === "turn_started")).toHaveLength(1); + expect( + events.filter((event) => event.type === "turn_canceled" || event.type === "turn_failed"), + ).toHaveLength(0); + expect( + timeline.entries.some( + (entry) => + entry.item.type === "assistant_message" && entry.item.text.includes("[System Error]"), + ), + ).toBe(false); + } + } finally { + await Promise.all(subscriptions.map((subscription) => subscription.release())); + collector.unsubscribe(); + await client.close(); + await daemon.close(); + rmSync(cwd, { recursive: true, force: true }); + } +}, 300_000); From 3196260bd440d56ab5b3adda3daa8afbd8a08d0d Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Thu, 29 Oct 2026 07:06:46 +0000 Subject: [PATCH 104/173] Show completed edxeth Pi children as finished, live and after restart (#8176) * fix(pi): settle edxeth subagent lifecycle events * test(pi): preserve completed children when restoring captured histories Verify the completed child and assistant transcript through history replay and the store consumed by clients. Both captured completion protocols otherwise leave a running descriptor. Co-authored-by: Zeno_ --------- Co-authored-by: Zeno_ Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../fixtures/background-child-session.jsonl | 8 + .../fixtures/background.json | 263 ++++++++++++++ .../fixtures/foreground-child-session.jsonl | 8 + .../fixtures/foreground.json | 156 ++++++++ .../edxeth-pi-subagents/index.test.ts | 336 ++++++++++++++++++ .../extensions/edxeth-pi-subagents/index.ts | 119 +++++++ .../agent/providers/pi/extensions/registry.ts | 2 + 7 files changed, 892 insertions(+) create mode 100644 packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/fixtures/background-child-session.jsonl create mode 100644 packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/fixtures/background.json create mode 100644 packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/fixtures/foreground-child-session.jsonl create mode 100644 packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/fixtures/foreground.json create mode 100644 packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/index.test.ts create mode 100644 packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/index.ts diff --git a/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/fixtures/background-child-session.jsonl b/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/fixtures/background-child-session.jsonl new file mode 100644 index 0000000000..ed668e807f --- /dev/null +++ b/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/fixtures/background-child-session.jsonl @@ -0,0 +1,8 @@ +{"type": "session", "version": 3, "id": "e56a0006-f421-45be-9aef-e4019db1cf24", "timestamp": "2026-10-21T13:05:57.384Z", "cwd": "/tmp/paseo-edxeth-fixture/lean/workspace", "name": "[marker] Fixture marker verification", "parentSession": "/tmp/paseo-edxeth-fixture/lean/sessions/2026-10-21T13-05-53-085Z_01a15e91-73bd-7282-82c6-d3974711a941.jsonl"} +{"type": "custom", "customType": "pi-subagents_launch_metadata", "data": {"version": 1, "timestamp": "2026-10-21T13:05:57.385Z", "name": "fixture-marker", "title": "Fixture marker verification", "sessionTitle": "[marker] Fixture marker verification", "agent": "marker", "mode": "background", "sessionMode": "lineage-only", "autoExit": true, "parentClosePolicy": "terminate", "reportContextUsage": true, "async": true, "model": "openai-codex/gpt-5.6-sol", "thinking": "high", "modelRef": "openai-codex/gpt-5.6-sol:high", "definitionModel": "openai-codex/gpt-5.6-sol", "definitionThinking": "high", "allowModelOverride": true, "modelSource": "agent", "tools": "read", "denyTools": ["subagent", "subagent_resume", "subagent_kill"], "spawnableAgents": [], "spawnBudget": null, "extensions": [], "noContextFiles": false, "inheritAppendSystem": false, "noSession": false, "trustProject": false, "agentConfigDir": "/tmp/paseo-edxeth-fixture/lean/agent", "cwd": "/tmp/paseo-edxeth-fixture/lean/workspace", "boundarySystemPrompt": false}, "id": "57355eeb", "parentId": null, "timestamp": "2026-10-21T13:05:57.386Z"} +{"type": "session_info", "id": "847415e4", "parentId": "57355eeb", "timestamp": "2026-10-21T13:05:57.566Z", "name": "[marker] Fixture marker verification"} +{"type": "model_change", "id": "d4ad59be", "parentId": "847415e4", "timestamp": "2026-10-21T13:05:57.672Z", "provider": "openai-codex", "modelId": "gpt-5.6-sol"} +{"type": "thinking_level_change", "id": "7f6bf9d2", "parentId": "d4ad59be", "timestamp": "2026-10-21T13:05:57.672Z", "thinkingLevel": "high"} +{"type": "message", "id": "737b762e", "parentId": "6b436446", "timestamp": "2026-10-21T13:05:57.679Z", "message": {"role": "user", "content": [{"type": "text", "text": "\n\n\nReturn only the exact marker supplied by the user. Do not use tools.\n\nComplete your task autonomously.\n\nReturn only PASEO_EDXETH_LEAN_OK\n\nYour FINAL assistant message should summarize what you accomplished.\n\n"}], "timestamp": 1792587957678}} +{"type": "message", "id": "100b110d", "parentId": "737b762e", "timestamp": "2026-10-21T13:06:02.050Z", "message": {"role": "assistant", "content": [{"type": "text", "text": "PASEO_EDXETH_LEAN_OK"}], "api": "openai-codex-responses", "provider": "openai-codex", "model": "gpt-5.6-sol", "usage": {"input": 1713, "output": 13, "cacheRead": 0, "cacheWrite": 0, "reasoning": 0, "totalTokens": 1726, "cost": {"input": 0.006852, "output": 0.00026000000000000003, "cacheRead": 0, "cacheWrite": 0, "total": 0.007111999999999999}}, "stopReason": "stop", "timestamp": 1792587957684, "responseId": "resp_0bc8bfaee079148a016ad8b8b7edb08191924676ed8dcfd447", "rawStopReason": "completed"}} +{"type": "custom", "customType": "pi-subagent-completion", "data": {"reason": "normal"}, "id": "80bbd3bb", "parentId": "100b110d", "timestamp": "2026-10-21T13:06:02.054Z"} diff --git a/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/fixtures/background.json b/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/fixtures/background.json new file mode 100644 index 0000000000..fe4913f6b6 --- /dev/null +++ b/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/fixtures/background.json @@ -0,0 +1,263 @@ +{ + "provenance": { + "package": "Zeno2019/pi-subagents-lean", + "version": "2.9.2-lean.1", + "sourceCommit": "e10fe855808abcae193a205ea98f8ccd70d25620", + "piVersion": "0.87.1", + "captureDate": "2026-10-21" + }, + "events": [ + { + "type": "tool_execution_start", + "toolCallId": "call_f28b261de3c6440b953f0f56c3fec7d0|fc_0d35cf51b3ed48b9016ad8b8b4a63c81918a55903d0a4f12cb", + "toolName": "subagent", + "args": { + "agent": "marker", + "name": "fixture-marker", + "title": "Fixture marker verification", + "task": "Return only PASEO_EDXETH_LEAN_OK" + } + }, + { + "type": "tool_execution_end", + "toolCallId": "call_f28b261de3c6440b953f0f56c3fec7d0|fc_0d35cf51b3ed48b9016ad8b8b4a63c81918a55903d0a4f12cb", + "toolName": "subagent", + "result": { + "content": [ + { + "type": "text", + "text": "Sub-agent \"fixture-marker\" launched async with id 1bfdf3b3. Results will be delivered automatically as a steer message when it finishes. Use this exact id if you need to resume or stop this child.\n\nActivity: /home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/activity.jsonl\nRun evidence: /home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/result.json\nRead these on demand for progress or failure diagnosis; activity is evidence, not a completion verdict." + } + ], + "details": { + "evidence": { + "runId": "1bfdf3b3", + "cwd": "/tmp/paseo-edxeth-fixture/lean/workspace", + "activityFile": "/home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/activity.jsonl", + "resultFile": "/home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/result.json" + }, + "id": "1bfdf3b3", + "name": "fixture-marker", + "title": "Fixture marker verification", + "task": "Return only PASEO_EDXETH_LEAN_OK", + "agent": "marker", + "sessionFile": "/tmp/paseo-edxeth-fixture/background/child-session.jsonl", + "noSession": false, + "status": "started", + "mode": "background", + "deliveryState": "detached", + "parentClosePolicy": "terminate", + "async": true, + "autoExit": true + } + }, + "isError": false + }, + { + "type": "message_end", + "message": { + "role": "custom", + "customType": "subagent_result", + "content": "Sub-agent \"fixture-marker\" completed (7s).\n\nPASEO_EDXETH_LEAN_OK\n\nSession: /tmp/paseo-edxeth-fixture/background/child-session.jsonl\nResume: pi --session /tmp/paseo-edxeth-fixture/background/child-session.jsonl\n\nSub-agent context: 2K/372K tokens (0%) used at finish.\n\nActivity: /home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/activity.jsonl\nRun evidence: /home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/result.json\nRead these on demand for progress or failure diagnosis; activity is evidence, not a completion verdict.", + "display": true, + "details": { + "evidence": { + "runId": "1bfdf3b3", + "cwd": "/tmp/paseo-edxeth-fixture/lean/workspace", + "activityFile": "/home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/activity.jsonl", + "resultFile": "/home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/result.json", + "finalized": true + }, + "id": "1bfdf3b3", + "name": "fixture-marker", + "task": "Return only PASEO_EDXETH_LEAN_OK", + "agent": "marker", + "mode": "background", + "status": "completed", + "deliveryState": "detached", + "parentClosePolicy": "terminate", + "async": true, + "exitCode": 0, + "elapsed": 7, + "outputTokens": 13, + "contextTokens": 1775, + "contextWindow": 372000, + "sessionFile": "/tmp/paseo-edxeth-fixture/background/child-session.jsonl" + }, + "timestamp": 1792587964414 + } + } + ], + "messages": [ + { + "role": "assistant", + "content": [ + { + "type": "toolCall", + "id": "call_f28b261de3c6440b953f0f56c3fec7d0|fc_0d35cf51b3ed48b9016ad8b8b4a63c81918a55903d0a4f12cb", + "name": "subagent", + "arguments": { + "agent": "marker", + "name": "fixture-marker", + "title": "Fixture marker verification", + "task": "Return only PASEO_EDXETH_LEAN_OK" + } + } + ], + "api": "openai-codex-responses", + "provider": "openai-codex", + "model": "gpt-5.6-sol", + "usage": { + "input": 2020, + "output": 43, + "cacheRead": 0, + "cacheWrite": 0, + "reasoning": 0, + "totalTokens": 2063, + "cost": { + "input": 0.00808, + "output": 0.0008600000000000001, + "cacheRead": 0, + "cacheWrite": 0, + "total": 0.00894 + } + }, + "stopReason": "toolUse", + "timestamp": 1792587953256, + "responseId": "resp_0d35cf51b3ed48b9016ad8b8b3698481918f82962b6eaf2788", + "rawStopReason": "completed" + }, + { + "role": "toolResult", + "toolCallId": "call_f28b261de3c6440b953f0f56c3fec7d0|fc_0d35cf51b3ed48b9016ad8b8b4a63c81918a55903d0a4f12cb", + "toolName": "subagent", + "content": [ + { + "type": "text", + "text": "Sub-agent \"fixture-marker\" launched async with id 1bfdf3b3. Results will be delivered automatically as a steer message when it finishes. Use this exact id if you need to resume or stop this child.\n\nActivity: /home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/activity.jsonl\nRun evidence: /home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/result.json\nRead these on demand for progress or failure diagnosis; activity is evidence, not a completion verdict." + } + ], + "details": { + "evidence": { + "runId": "1bfdf3b3", + "cwd": "/tmp/paseo-edxeth-fixture/lean/workspace", + "activityFile": "/home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/activity.jsonl", + "resultFile": "/home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/result.json", + "finalized": true + }, + "id": "1bfdf3b3", + "name": "fixture-marker", + "title": "Fixture marker verification", + "task": "Return only PASEO_EDXETH_LEAN_OK", + "agent": "marker", + "sessionFile": "/tmp/paseo-edxeth-fixture/background/child-session.jsonl", + "noSession": false, + "status": "started", + "mode": "background", + "deliveryState": "detached", + "parentClosePolicy": "terminate", + "async": true, + "autoExit": true + }, + "isError": false, + "timestamp": 1792587957399 + }, + { + "role": "assistant", + "content": [ + { + "type": "thinking", + "thinking": "**Identifying need for await keyword**" + }, + { + "type": "text", + "text": "DONE" + } + ], + "api": "openai-codex-responses", + "provider": "openai-codex", + "model": "gpt-5.6-sol", + "usage": { + "input": 2258, + "output": 18, + "cacheRead": 0, + "cacheWrite": 0, + "reasoning": 11, + "totalTokens": 2276, + "cost": { + "input": 0.009032, + "output": 0.00036, + "cacheRead": 0, + "cacheWrite": 0, + "total": 0.009392 + } + }, + "stopReason": "stop", + "timestamp": 1792587957402, + "responseId": "resp_0d35cf51b3ed48b9016ad8b8b602108191a8e8f7fd77fbe5b5", + "rawStopReason": "completed" + }, + { + "role": "custom", + "customType": "subagent_result", + "content": "Sub-agent \"fixture-marker\" completed (7s).\n\nPASEO_EDXETH_LEAN_OK\n\nSession: /tmp/paseo-edxeth-fixture/background/child-session.jsonl\nResume: pi --session /tmp/paseo-edxeth-fixture/background/child-session.jsonl\n\nSub-agent context: 2K/372K tokens (0%) used at finish.\n\nActivity: /home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/activity.jsonl\nRun evidence: /home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/result.json\nRead these on demand for progress or failure diagnosis; activity is evidence, not a completion verdict.", + "display": true, + "details": { + "evidence": { + "runId": "1bfdf3b3", + "cwd": "/tmp/paseo-edxeth-fixture/lean/workspace", + "activityFile": "/home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/activity.jsonl", + "resultFile": "/home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/result.json", + "finalized": true + }, + "id": "1bfdf3b3", + "name": "fixture-marker", + "task": "Return only PASEO_EDXETH_LEAN_OK", + "agent": "marker", + "mode": "background", + "status": "completed", + "deliveryState": "detached", + "parentClosePolicy": "terminate", + "async": true, + "exitCode": 0, + "elapsed": 7, + "outputTokens": 13, + "contextTokens": 1775, + "contextWindow": 372000, + "sessionFile": "/tmp/paseo-edxeth-fixture/background/child-session.jsonl" + }, + "timestamp": 1792587964414 + }, + { + "role": "assistant", + "content": [ + { + "type": "text", + "text": "DONE" + } + ], + "api": "openai-codex-responses", + "provider": "openai-codex", + "model": "gpt-5.6-sol", + "usage": { + "input": 389, + "output": 5, + "cacheRead": 2176, + "cacheWrite": 0, + "reasoning": 0, + "totalTokens": 2570, + "cost": { + "input": 0.0015559999999999999, + "output": 0.0001, + "cacheRead": 0.0008704000000000001, + "cacheWrite": 0, + "total": 0.0025264 + } + }, + "stopReason": "stop", + "timestamp": 1792587964417, + "responseId": "resp_0d35cf51b3ed48b9016ad8b8bd0c548191bddd1fe3410a1c82", + "rawStopReason": "completed" + } + ] +} diff --git a/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/fixtures/foreground-child-session.jsonl b/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/fixtures/foreground-child-session.jsonl new file mode 100644 index 0000000000..a607a1032d --- /dev/null +++ b/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/fixtures/foreground-child-session.jsonl @@ -0,0 +1,8 @@ +{"type": "session", "version": 3, "id": "afbea6e0-7858-4ecf-8ef1-e26af9b7d6e0", "timestamp": "2026-10-21T13:05:17.628Z", "cwd": "/tmp/paseo-edxeth-fixture/upstream/workspace", "name": "[marker] Fixture marker verification", "parentSession": "/tmp/paseo-edxeth-fixture/upstream/sessions/2026-10-21T13-05-12-212Z_01a15e90-d414-7243-a701-4eb4b0bec880.jsonl"} +{"type": "custom", "customType": "pi-subagents_launch_metadata", "data": {"version": 1, "timestamp": "2026-10-21T13:05:17.628Z", "name": "fixture-marker", "title": "Fixture marker verification", "sessionTitle": "[marker] Fixture marker verification", "agent": "marker", "mode": "background", "sessionMode": "lineage-only", "autoExit": true, "parentClosePolicy": "terminate", "reportContextUsage": true, "async": false, "model": "openai-codex/gpt-5.6-sol", "thinking": "high", "modelRef": "openai-codex/gpt-5.6-sol:high", "definitionModel": "openai-codex/gpt-5.6-sol", "definitionThinking": "high", "allowModelOverride": true, "modelSource": "agent", "tools": "read", "denyTools": ["subagent", "subagent_resume", "subagent_kill"], "spawnableAgents": [], "spawnBudget": null, "extensions": [], "noContextFiles": false, "inheritAppendSystem": false, "noSession": false, "trustProject": false, "agentConfigDir": "/tmp/paseo-edxeth-fixture/upstream/agent", "cwd": "/tmp/paseo-edxeth-fixture/upstream/workspace", "boundarySystemPrompt": false}, "id": "3f7d3c3f", "parentId": null, "timestamp": "2026-10-21T13:05:17.629Z"} +{"type": "session_info", "id": "6e198450", "parentId": "3f7d3c3f", "timestamp": "2026-10-21T13:05:17.825Z", "name": "[marker] Fixture marker verification"} +{"type": "model_change", "id": "94bf4c0b", "parentId": "6e198450", "timestamp": "2026-10-21T13:05:17.962Z", "provider": "openai-codex", "modelId": "gpt-5.6-sol"} +{"type": "thinking_level_change", "id": "57cc6428", "parentId": "94bf4c0b", "timestamp": "2026-10-21T13:05:17.962Z", "thinkingLevel": "high"} +{"type": "message", "id": "a9e47f08", "parentId": "8c186624", "timestamp": "2026-10-21T13:05:17.970Z", "message": {"role": "user", "content": [{"type": "text", "text": "\n\n\nReturn only the exact marker supplied by the user. Do not use tools.\n\nComplete your task autonomously.\n\nReturn only PASEO_EDXETH_UPSTREAM_OK\n\nYour FINAL assistant message should summarize what you accomplished.\n\n"}], "timestamp": 1792587917968}} +{"type": "message", "id": "bc221a13", "parentId": "a9e47f08", "timestamp": "2026-10-21T13:05:23.476Z", "message": {"role": "assistant", "content": [{"type": "thinking", "thinking": "**Following user file marker exactly**"}, {"type": "text", "text": "PASEO_EDXETH_UPSTREAM_OK"}], "api": "openai-codex-responses", "provider": "openai-codex", "model": "gpt-5.6-sol", "usage": {"input": 1673, "output": 49, "cacheRead": 0, "cacheWrite": 0, "reasoning": 34, "totalTokens": 1722, "cost": {"input": 0.006692, "output": 0.0009800000000000002, "cacheRead": 0, "cacheWrite": 0, "total": 0.007672}}, "stopReason": "stop", "timestamp": 1792587917974, "responseId": "resp_09445c1733d532e7016ad8b8909c908191ba803c059497945e", "rawStopReason": "completed"}} +{"type": "custom", "customType": "pi-subagent-completion", "data": {"reason": "normal"}, "id": "832fc8c9", "parentId": "bc221a13", "timestamp": "2026-10-21T13:05:23.477Z"} diff --git a/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/fixtures/foreground.json b/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/fixtures/foreground.json new file mode 100644 index 0000000000..c8df8eb5c2 --- /dev/null +++ b/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/fixtures/foreground.json @@ -0,0 +1,156 @@ +{ + "provenance": { + "package": "edxeth/pi-subagents", + "version": "2.9.2", + "sourceCommit": "cf6dbf41c17986f3882e6804a68e8fb8282d25e6", + "piVersion": "0.87.1", + "captureDate": "2026-10-21" + }, + "events": [ + { + "type": "tool_execution_start", + "toolCallId": "call_0bc6fc2213cd49aa92950947bde5dd8a|fc_0a0ca4aa78cd296a016ad8b88d018481919eadbf09eb191a1a", + "toolName": "subagent", + "args": { + "agent": "marker", + "name": "fixture-marker", + "title": "Fixture marker verification", + "task": "Return only PASEO_EDXETH_UPSTREAM_OK" + } + }, + { + "type": "tool_execution_end", + "toolCallId": "call_0bc6fc2213cd49aa92950947bde5dd8a|fc_0a0ca4aa78cd296a016ad8b88d018481919eadbf09eb191a1a", + "toolName": "subagent", + "result": { + "content": [ + { + "type": "text", + "text": "Sub-agent \"fixture-marker\" completed (7s).\n\nPASEO_EDXETH_UPSTREAM_OK\n\nSession: /tmp/paseo-edxeth-fixture/foreground/child-session.jsonl\nResume: pi --session /tmp/paseo-edxeth-fixture/foreground/child-session.jsonl\n\nSub-agent context: 2K/372K tokens (0%) used at finish." + } + ], + "details": { + "id": "dd7f94e8", + "name": "fixture-marker", + "agent": "marker", + "status": "completed", + "mode": "background", + "parentClosePolicy": "terminate", + "deliveryState": "awaited", + "async": false, + "autoExit": true, + "exitCode": 0, + "elapsed": 7, + "outputTokens": 49, + "contextTokens": 1777, + "contextWindow": 372000, + "summary": "PASEO_EDXETH_UPSTREAM_OK", + "sessionFile": "/tmp/paseo-edxeth-fixture/foreground/child-session.jsonl" + } + }, + "isError": false + } + ], + "messages": [ + { + "role": "assistant", + "content": [ + { + "type": "toolCall", + "id": "call_0bc6fc2213cd49aa92950947bde5dd8a|fc_0a0ca4aa78cd296a016ad8b88d018481919eadbf09eb191a1a", + "name": "subagent", + "arguments": { + "agent": "marker", + "name": "fixture-marker", + "title": "Fixture marker verification", + "task": "Return only PASEO_EDXETH_UPSTREAM_OK" + } + } + ], + "api": "openai-codex-responses", + "provider": "openai-codex", + "model": "gpt-5.6-sol", + "usage": { + "input": 3256, + "output": 43, + "cacheRead": 0, + "cacheWrite": 0, + "reasoning": 0, + "totalTokens": 3299, + "cost": { + "input": 0.013023999999999999, + "output": 0.0008600000000000001, + "cacheRead": 0, + "cacheWrite": 0, + "total": 0.013883999999999999 + } + }, + "stopReason": "toolUse", + "timestamp": 1792587912428, + "responseId": "resp_0a0ca4aa78cd296a016ad8b88bd52881918cbb9b8326b3060a", + "rawStopReason": "completed" + }, + { + "role": "toolResult", + "toolCallId": "call_0bc6fc2213cd49aa92950947bde5dd8a|fc_0a0ca4aa78cd296a016ad8b88d018481919eadbf09eb191a1a", + "toolName": "subagent", + "content": [ + { + "type": "text", + "text": "Sub-agent \"fixture-marker\" completed (7s).\n\nPASEO_EDXETH_UPSTREAM_OK\n\nSession: /tmp/paseo-edxeth-fixture/foreground/child-session.jsonl\nResume: pi --session /tmp/paseo-edxeth-fixture/foreground/child-session.jsonl\n\nSub-agent context: 2K/372K tokens (0%) used at finish." + } + ], + "details": { + "id": "dd7f94e8", + "name": "fixture-marker", + "agent": "marker", + "status": "completed", + "mode": "background", + "parentClosePolicy": "terminate", + "deliveryState": "awaited", + "async": false, + "autoExit": true, + "exitCode": 0, + "elapsed": 7, + "outputTokens": 49, + "contextTokens": 1777, + "contextWindow": 372000, + "summary": "PASEO_EDXETH_UPSTREAM_OK", + "sessionFile": "/tmp/paseo-edxeth-fixture/foreground/child-session.jsonl" + }, + "isError": false, + "timestamp": 1792587924671 + }, + { + "role": "assistant", + "content": [ + { + "type": "text", + "text": "DONE" + } + ], + "api": "openai-codex-responses", + "provider": "openai-codex", + "model": "gpt-5.6-sol", + "usage": { + "input": 388, + "output": 5, + "cacheRead": 3072, + "cacheWrite": 0, + "reasoning": 0, + "totalTokens": 3465, + "cost": { + "input": 0.001552, + "output": 0.0001, + "cacheRead": 0.0012288000000000002, + "cacheWrite": 0, + "total": 0.0028808 + } + }, + "stopReason": "stop", + "timestamp": 1792587924675, + "responseId": "resp_0a0ca4aa78cd296a016ad8b896af2c81919c0ef586dd50f2f0", + "rawStopReason": "completed" + } + ] +} diff --git a/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/index.test.ts b/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/index.test.ts new file mode 100644 index 0000000000..86692ab32e --- /dev/null +++ b/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/index.test.ts @@ -0,0 +1,336 @@ +import { describe, expect, test } from "vitest"; +import { fileURLToPath } from "node:url"; +import { createPiExtensionHost } from "../index.js"; +import { readSubagentFixture, verifySubagentFixture } from "../subagent-fixture-test.js"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { edxethPiSubagents } from "./index.js"; +import { streamPiHistory } from "../../history-mapper.js"; +import { ProviderSubagentStore } from "../../../../provider-subagents/store.js"; + +const args = { + agent: "scout", + name: "status-scout", + title: "Check child status", + task: "Return the completion marker", +}; + +describe("edxeth/pi-subagents adapter", () => { + test.each(["tool", "notification"])("ends a child that requested help via %s", (delivery) => { + const host = createPiExtensionHost(); + const call = { callId: "spawn-1", toolName: "subagent", args, status: "completed" as const }; + host.mapToolCall({ + ...call, + result: { details: { id: "run-1", name: args.name, status: "started" } }, + }); + const details = { id: "run-1", name: args.name, message: "Please clarify the task" }; + const result = + delivery === "tool" + ? host.mapToolCall({ ...call, result: { details: { ...details, status: "pinged" } } }) + : host.mapCustomMessage({ + role: "custom", + customType: "subagent_ping", + content: "Child requested help and exited", + details, + }); + expect(result?.subagents).toEqual([ + expect.objectContaining({ + type: "upsert", + id: "spawn-1", + status: "canceled", + subtitle: "Needs help", + }), + ]); + }); + + test("leaves unrelated tools and other subagent protocols to their adapters", () => { + const host = createPiExtensionHost(undefined, [edxethPiSubagents]); + const call = { callId: "other", toolName: "subagent", args, status: "completed" as const }; + for (const details of [null, {}, { mode: "single", results: [] }, { id: "run-1" }]) { + expect(host.mapToolCall({ ...call, result: { details } })).toBeUndefined(); + } + expect( + host.mapToolCall({ + ...call, + toolName: "unrelated", + result: { details: { id: "run-1", name: args.name, status: "completed" } }, + }), + ).toBeUndefined(); + for (const details of [{ id: "run-1" }, { id: "run-1", status: "unknown" }]) { + expect( + host.mapCustomMessage({ + role: "custom", + customType: "subagent_result", + content: "Unrecognized result", + details, + }), + ).toBeUndefined(); + } + }); + + test("waits for cancellation after a kill acknowledgement reports stopping", () => { + const host = createPiExtensionHost(); + host.mapToolCall({ + callId: "spawn-1", + toolName: "subagent", + args, + status: "completed", + result: { details: { id: "run-1", name: args.name, status: "started" } }, + }); + const stopping = host.mapToolCall({ + callId: "kill-1", + toolName: "subagent_kill", + args: { id: "run-1" }, + status: "completed", + result: { details: { id: "run-1", name: args.name, status: "stopping" } }, + }); + expect(stopping?.subagents ?? []).toEqual([]); + expect( + host.mapCustomMessage({ + role: "custom", + customType: "subagent_result", + content: "Cancelled", + details: { id: "run-1", status: "cancelled" }, + })?.subagents, + ).toEqual([{ type: "upsert", id: "spawn-1", status: "canceled" }]); + }); + + test("preserves a completion that arrives before its launch acknowledgement", () => { + const host = createPiExtensionHost(); + const early = host.mapCustomMessage({ + role: "custom", + customType: "subagent_result", + content: "Already done", + details: { id: "fast-run", status: "completed" }, + }); + expect(early?.subagents ?? []).toEqual([]); + const started = host.mapToolCall({ + callId: "fast-call", + toolName: "subagent", + args, + status: "completed", + result: { + details: { id: "fast-run", name: args.name, agent: args.agent, status: "started" }, + }, + }); + expect(started?.subagents).toEqual([ + { + type: "upsert", + id: "fast-call", + title: "scout", + description: args.task, + toolCallId: "fast-call", + status: "completed", + }, + ]); + }); + + test.each([ + { details: { status: "completed" }, expected: "completed" }, + { details: { status: "failed" }, expected: "failed" }, + { details: { status: "cancelled" }, expected: "canceled" }, + { details: { error: "Child watcher exited unexpectedly" }, expected: "failed" }, + ])("maps completion $details to $expected", ({ details, expected }) => { + const host = createPiExtensionHost(); + host.mapToolCall({ + callId: "spawn-1", + toolName: "subagent", + args, + status: "completed", + result: { details: { id: "run-1", name: args.name, status: "started" } }, + }); + expect( + host.mapCustomMessage({ + role: "custom", + customType: "subagent_result", + content: "Child result", + details: { id: "run-1", ...details }, + })?.subagents, + ).toEqual([{ type: "upsert", id: "spawn-1", status: expected }]); + }); + + test("a resume gets its own run and reads the retained child session", async () => { + const dir = await mkdtemp(join(tmpdir(), "paseo-edxeth-resume-")); + const file = join(dir, "child.jsonl"); + const host = createPiExtensionHost(); + try { + await writeFile( + file, + JSON.stringify({ + type: "message", + message: { role: "assistant", content: [{ type: "text", text: "RESUMED" }] }, + }) + "\n", + ); + const original = host.mapToolCall({ + callId: "spawn-1", + toolName: "subagent", + args, + status: "completed", + result: { + details: { id: "run-1", name: args.name, status: "completed", sessionFile: file }, + }, + }); + await original?.hydration; + const resumed = host.mapToolCall({ + callId: "resume-1", + toolName: "subagent_resume", + args: { sessionFile: file, task: "Continue" }, + status: "completed", + result: { + details: { id: "run-2", name: args.name, status: "started", sessionFile: file }, + }, + }); + expect(resumed?.childSessions).toEqual([{ id: "resume-1", file }]); + expect(await resumed?.hydration).toEqual([ + { + type: "provider_subagent", + provider: "pi", + event: { + type: "timeline", + id: "resume-1", + item: expect.objectContaining({ type: "assistant_message", text: "RESUMED" }), + }, + }, + ]); + expect( + host.mapCustomMessage({ + role: "custom", + customType: "subagent_result", + content: "Resumed run complete", + details: { id: "run-2", status: "completed", sessionFile: file }, + })?.subagents, + ).toEqual([{ type: "upsert", id: "resume-1", status: "completed" }]); + } finally { + host.close(); + await rm(dir, { recursive: true, force: true }); + } + }); + + test("settles each batched child by run id without creating a parent-call card", () => { + const host = createPiExtensionHost(); + const result = host.mapToolCall({ + callId: "batch-1", + toolName: "subagent", + args: { children: [args, { ...args, agent: "reviewer", name: "status-reviewer" }] }, + status: "completed", + result: { + details: { + status: "batch", + children: [ + { id: "run-1", ...args, mode: "background", status: "completed" }, + { id: "run-2", name: "status-reviewer", agent: "reviewer", status: "started" }, + ], + }, + }, + }); + expect(result?.subagents).toEqual([ + { + type: "upsert", + id: "batch-1:0", + title: "scout", + description: args.task, + toolCallId: "batch-1", + status: "completed", + }, + { + type: "upsert", + id: "batch-1:1", + title: "reviewer", + description: undefined, + toolCallId: "batch-1", + status: "running", + }, + ]); + expect( + host.mapCustomMessage({ + role: "custom", + customType: "subagent_result", + content: "Done", + details: { id: "run-2", status: "completed" }, + })?.subagents, + ).toEqual([{ type: "upsert", id: "batch-1:1", status: "completed" }]); + }); + + test.each([ + { mode: "foreground", statuses: ["running", "completed"] }, + { mode: "background", statuses: ["running", "running", "completed"] }, + ])("settles the captured $mode run live and on replay", async ({ mode, statuses }) => { + const fixture = readSubagentFixture(new URL(`./fixtures/${mode}.json`, import.meta.url), { + from: `/tmp/paseo-edxeth-fixture/${mode}/child-session.jsonl`, + to: fileURLToPath(new URL(`./fixtures/${mode}-child-session.jsonl`, import.meta.url)), + }); + const events = await verifySubagentFixture(fixture); + const updates = events.flatMap(({ event }) => (event.type === "upsert" ? [event] : [])); + expect(updates.map((event) => event.status)).toEqual(statuses); + expect(new Set(updates.map((event) => event.id)).size).toBe(1); + expect(events.some(({ event }) => event.type === "timeline")).toBe(true); + }); + + test.each(["foreground", "background"])( + "restores a completed %s child and its transcript to the consumer store", + async (mode) => { + const fixture = readSubagentFixture(new URL(`./fixtures/${mode}.json`, import.meta.url), { + from: `/tmp/paseo-edxeth-fixture/${mode}/child-session.jsonl`, + to: fileURLToPath(new URL(`./fixtures/${mode}-child-session.jsonl`, import.meta.url)), + }); + const store = new ProviderSubagentStore(); + for await (const event of streamPiHistory("pi", fixture.messages)) { + if (event.type === "provider_subagent") store.apply("parent", "pi", event.event); + } + const children = store.list("parent"); + expect(children).toEqual([expect.objectContaining({ status: "completed", title: "marker" })]); + const transcript = store.fetchTimeline("parent", children[0]!.id); + expect(transcript.rows).toContainEqual( + expect.objectContaining({ + item: expect.objectContaining({ + type: "assistant_message", + text: mode === "foreground" ? "PASEO_EDXETH_UPSTREAM_OK" : "PASEO_EDXETH_LEAN_OK", + }), + }), + ); + }, + ); + + test("settles a synchronous result on the card created when the tool started", () => { + const host = createPiExtensionHost(); + const call = { callId: "spawn-1", toolName: "subagent", args }; + const start = host.mapToolCall({ ...call, status: "running", result: null }); + expect(start?.subagents).toEqual([ + { + type: "upsert", + id: "spawn-1", + title: "scout", + description: args.task, + toolCallId: "spawn-1", + status: "running", + }, + ]); + const end = host.mapToolCall({ + ...call, + status: "completed", + result: { + content: [{ type: "text", text: "DONE" }], + details: { + id: "run-1", + name: args.name, + agent: args.agent, + mode: "background", + status: "completed", + deliveryState: "awaited", + exitCode: 0, + }, + }, + }); + expect(end?.subagents).toEqual([ + { + type: "upsert", + id: "spawn-1", + title: "scout", + description: args.task, + toolCallId: "spawn-1", + status: "completed", + }, + ]); + }); +}); diff --git a/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/index.ts b/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/index.ts new file mode 100644 index 0000000000..c00e39aaad --- /dev/null +++ b/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/index.ts @@ -0,0 +1,119 @@ +import { z } from "zod"; +import { extractTextFromToolResult } from "../../tool-call-mapper.js"; +import type { PiChildSessionFile, PiExtension } from "../contract.js"; +import type { ProviderSubagentInputEvent } from "../../../../provider-subagents/store.js"; + +const Run = z + .object({ + id: z.string().trim().min(1), + name: z.string().trim().min(1), + agent: z.string().trim().min(1).optional(), + task: z.string().optional(), + status: z.enum(["started", "completed", "failed", "cancelled", "pinged"]), + sessionFile: z.string().trim().min(1).optional(), + }) + .passthrough(); +const Args = z.object({ task: z.string().optional() }).passthrough(); +const Batch = z.object({ status: z.enum(["started", "batch"]), children: z.array(Run).min(1) }); +const Completion = z + .object({ + id: z.string().trim().min(1), + status: z.enum(["completed", "failed", "cancelled", "pinged"]).optional(), + error: z.string().optional(), + sessionFile: z.string().trim().min(1).optional(), + }) + .passthrough(); +const Ping = Completion.extend({ message: z.string() }); + +function childStatus(status: z.infer["status"]) { + if (status === "started") return "running"; + // A ping ends the child process and needs a new resume run. It is not success. + if (status === "cancelled" || status === "pinged") return "canceled"; + return status; +} + +export const edxethPiSubagents: PiExtension = { + id: "edxeth/pi-subagents", + createSession: () => { + const callsByRun = new Map(); + const completions = new Map>(); + const readSessions = new Map(); + const childSession = (id: string, file: string | undefined): PiChildSessionFile[] => { + if (!file || readSessions.get(id) === file) return []; + readSessions.set(id, file); + return [{ id, file }]; + }; + const completeRun = (result: z.infer) => { + const status = result.status ?? (result.error === undefined ? undefined : "failed"); + if (!status) return undefined; + // A fast child can finish before the tool returns its run id. Keep the + // terminal outcome so a later "started" acknowledgement cannot regress it. + completions.set(result.id, { ...result, status }); + const id = callsByRun.get(result.id); + if (!id) return undefined; + const subagents: ProviderSubagentInputEvent[] = [ + { + type: "upsert", + id, + status: childStatus(status), + ...(status === "pinged" ? { subtitle: "Needs help" } : {}), + }, + ]; + return { subagents, childSessions: childSession(id, result.sessionFile) }; + }; + return { + mapToolCall(call) { + const isLaunch = call.toolName === "subagent" || call.toolName === "subagent_resume"; + if (!isLaunch || call.status === "running") return undefined; + const details = typeof call.result === "object" ? call.result?.details : null; + const single = Run.safeParse(details); + let runs: z.infer[]; + if (single.success) { + runs = [single.data]; + } else { + const batch = Batch.safeParse(details); + if (!batch.success) return undefined; + runs = batch.data.children; + } + const args = Args.safeParse(call.args); + const description = args.success ? args.data.task : undefined; + const subagents: ProviderSubagentInputEvent[] = []; + const childSessions: PiChildSessionFile[] = []; + for (const [index, run] of runs.entries()) { + const id = runs.length === 1 ? call.callId : `${call.callId}:${index}`; + const completion = completions.get(run.id); + const status = completion?.status ?? run.status; + callsByRun.set(run.id, id); + subagents.push({ + type: "upsert", + id, + title: run.agent ?? run.name, + description: run.task ?? description, + toolCallId: call.callId, + status: childStatus(status), + ...(status === "pinged" ? { subtitle: "Needs help" } : {}), + }); + childSessions.push(...childSession(id, completion?.sessionFile ?? run.sessionFile)); + } + return { + detail: { + type: "sub_agent", + description, + log: extractTextFromToolResult(call.result)?.trim() ?? "", + }, + subagents, + childSessions, + }; + }, + mapCustomMessage(message) { + if (message.customType === "subagent_ping") { + const ping = Ping.safeParse(message.details); + return ping.success ? completeRun({ ...ping.data, status: "pinged" }) : undefined; + } + if (message.customType !== "subagent_result") return undefined; + const parsed = Completion.safeParse(message.details); + return parsed.success ? completeRun(parsed.data) : undefined; + }, + }; + }, +}; diff --git a/packages/server/src/server/agent/providers/pi/extensions/registry.ts b/packages/server/src/server/agent/providers/pi/extensions/registry.ts index c66fabad80..ca273b83bb 100644 --- a/packages/server/src/server/agent/providers/pi/extensions/registry.ts +++ b/packages/server/src/server/agent/providers/pi/extensions/registry.ts @@ -1,5 +1,6 @@ import { piAskUser } from "./pi-ask-user/index.js"; import { piSubagents } from "./pi-subagents/index.js"; +import { edxethPiSubagents } from "./edxeth-pi-subagents/index.js"; import { piMcpAdapter } from "./pi-mcp-adapter/index.js"; import { rpivTodo } from "./rpiv-todo/index.js"; import { piExampleTodo } from "./pi-example-todo/index.js"; @@ -10,6 +11,7 @@ import { rpivAskUserQuestion } from "./rpiv-ask-user-question/index.js"; export const piExtensions = [ piAskUser, // Dialog correlation + edxethPiSubagents, // Structured results before the generic subagent tool matcher piSubagents, // Delegation calls tintinwebPiSubagents, gotgenesPiSubagents, From 7c88a48be47341f4dd70c155880f9351a9408330 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Thu, 29 Oct 2026 14:39:42 +0700 Subject: [PATCH 105/173] Publish store screenshots from the repo on each stable release (#8186) * feat(release): publish store screenshots from the repo Stable releases now upload the committed store renders: the App Store review lane attaches the iPhone and iPad sets to the version it submits, and a new Play lane replaces the phone and tablet screenshots after the Android submit. F-Droid reads the same Android files, which now link to the store renders instead of the website images. The Play lane needs its own copy of the submit service-account key (GOOGLE_PLAY_JSON_KEY in the EAS production environment) because the key Expo stores for eas submit is not available to custom jobs, and EAS Metadata does not handle screenshots for either store. * fix(release): rewrite the Android screenshot links on every render Google Play and F-Droid read numbered links to the Google renders. The renderer now rewrites them from the panels it exported, so adding or renaming a panel reaches all three stores. --- assets/store-screenshots/README.md | 4 ++ assets/store-screenshots/render.mjs | 21 +++++++- docs/android.md | 5 +- docs/release.md | 15 +++++- .../en-US/images/phoneScreenshots/1.png | 2 +- .../en-US/images/phoneScreenshots/2.png | 2 +- .../en-US/images/phoneScreenshots/3.png | 2 +- .../en-US/images/phoneScreenshots/4.png | 1 + .../en-US/images/phoneScreenshots/5.png | 1 + .../en-US/images/tenInchScreenshots/1.png | 1 + .../en-US/images/tenInchScreenshots/2.png | 1 + .../en-US/images/tenInchScreenshots/3.png | 1 + .../en-US/images/tenInchScreenshots/4.png | 1 + .../en-US/images/tenInchScreenshots/5.png | 1 + .../app/.eas/workflows/release-mobile.yml | 14 ++++++ packages/app/fastlane/Fastfile | 49 ++++++++++++++++++- 16 files changed, 112 insertions(+), 9 deletions(-) create mode 120000 fastlane/metadata/android/en-US/images/phoneScreenshots/4.png create mode 120000 fastlane/metadata/android/en-US/images/phoneScreenshots/5.png create mode 120000 fastlane/metadata/android/en-US/images/tenInchScreenshots/1.png create mode 120000 fastlane/metadata/android/en-US/images/tenInchScreenshots/2.png create mode 120000 fastlane/metadata/android/en-US/images/tenInchScreenshots/3.png create mode 120000 fastlane/metadata/android/en-US/images/tenInchScreenshots/4.png create mode 120000 fastlane/metadata/android/en-US/images/tenInchScreenshots/5.png diff --git a/assets/store-screenshots/README.md b/assets/store-screenshots/README.md index 6db3d236ec..fc37d98bd8 100644 --- a/assets/store-screenshots/README.md +++ b/assets/store-screenshots/README.md @@ -95,4 +95,8 @@ Callout crops are in native capture pixels. To find them, overlay a 100 px grid 6. Copy the captures into `raw/iphone/` or `raw/ipad/` under the names `render.mjs` uses, render, and check the preview. +## Publish + +The stable release uploads these exports to the App Store and Google Play, and F-Droid reads the Google ones from the repo. See [Store screenshots](../../docs/release.md#store-screenshots). The Android metadata holds links to the Google exports, and every render rewrites them, so commit the links with the exports. + Dimensions are checked against [Apple's screenshot specifications](https://developer.apple.com/help/app-store-connect/reference/app-information/screenshot-specifications/) and [Google Play's preview asset requirements](https://support.google.com/googleplay/android-developer/answer/9866151?hl=en). diff --git a/assets/store-screenshots/render.mjs b/assets/store-screenshots/render.mjs index 9e32384a60..6695eac559 100644 --- a/assets/store-screenshots/render.mjs +++ b/assets/store-screenshots/render.mjs @@ -9,7 +9,7 @@ // elsewhere point SF_FONT_DIR at a folder holding SFNS.ttf copied from a Mac. import { existsSync } from "node:fs"; -import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; @@ -23,6 +23,7 @@ const root = path.dirname(fileURLToPath(import.meta.url)); const repo = path.resolve(root, "../.."); const raw = (device, name) => path.join(root, "raw", device, `${name}.png`); const output = path.join(root, "output"); +const androidImages = path.join(repo, "fastlane/metadata/android/en-US/images"); // Native captures per device: iPhone 16 Pro Max at 3x and iPad Pro 13-inch at // 2x. The frame's screen radius and Dynamic Island are in capture pixels. @@ -116,6 +117,7 @@ const STORES = { }, google: { device: "iphone", + androidScreenshots: "phoneScreenshots", width: 1440, height: 2560, textTop: 150, @@ -134,6 +136,7 @@ const STORES = { }, "google-tablet": { device: "ipad", + androidScreenshots: "tenInchScreenshots", width: 1800, height: 3200, textTop: 200, @@ -352,6 +355,18 @@ async function expectLines(view, selector, expected, label) { if (lines !== expected) throw new Error(`${label} wraps to ${lines} lines, expected ${expected}`); } +// Google Play and F-Droid read their screenshots from the Android metadata, +// which holds links to these renders. Rewriting the links on every render keeps +// added, removed and renamed panels in step with the App Store. +async function linkAndroidScreenshots(folder, files) { + const dir = path.join(androidImages, folder); + await rm(dir, { recursive: true, force: true }); + await mkdir(dir, { recursive: true }); + for (const [index, file] of files.entries()) { + await symlink(path.relative(dir, file), path.join(dir, `${index + 1}.png`)); + } +} + async function renderPreview(rows) { const tile = 440; const gap = 40; @@ -387,7 +402,9 @@ try { const marks = await loadAgentMarks(work); const rows = []; for (const [name, store] of Object.entries(STORES)) { - rows.push(await renderStore(browser, name, store, font, marks, work)); + const files = await renderStore(browser, name, store, font, marks, work); + if (store.androidScreenshots) await linkAndroidScreenshots(store.androidScreenshots, files); + rows.push(files); } await renderPreview(rows); } finally { diff --git a/docs/android.md b/docs/android.md index 546ba92a3e..6188589eb8 100644 --- a/docs/android.md +++ b/docs/android.md @@ -215,7 +215,8 @@ fastlane/metadata/android/ │ ├── images/ │ │ ├── icon.png (512x512) │ │ ├── featureGraphic.png (1024x500) -│ │ └── phoneScreenshots/ (1.png, 2.png, ...) +│ │ ├── phoneScreenshots/ (1.png, 2.png, ... linked to the store renders) +│ │ └── tenInchScreenshots/ (1.png, 2.png, ... linked to the store renders) │ └── changelogs/ (generated — see below) ├── ja/ └── zh-CN/ @@ -223,6 +224,8 @@ fastlane/metadata/android/ Locale directories generally match `packages/app/src/i18n/locales.ts`, but note that `en` becomes `en-US`. +Google Play reads its screenshots from the same folders; see [Store screenshots](release.md#store-screenshots). + F-Droid changelogs are generated from `CHANGELOG.md`. Run `npm run fdroid:changelogs`; `npm run fdroid:changelogs:check` verifies without writing. It is wired into the npm `version` lifecycle, so a release picks it up automatically and `git add -A` stages the result. One changelog must be generated per-ABI-split, so each version will create **four** identical version-coded entries. F-Droid caps changelogs at 500 characters, so the generator strips some content and adds a link to the full notes. diff --git a/docs/release.md b/docs/release.md index 83a419b8ce..ce0857abb3 100644 --- a/docs/release.md +++ b/docs/release.md @@ -305,8 +305,8 @@ macOS 13 maps to Darwin 22. The two values use different version domains; do not iOS and Android store builds are not in `.github/workflows`. They are triggered by the EAS GitHub app the moment the `v*` tag is pushed: -- **Android (Play Store)** — EAS builds with profile `production` and auto-submits to the Play Store via `eas submit` (EAS-managed credentials, no Fastlane). -- **iOS (TestFlight + App Store)** — EAS builds with profile `production`, uploads once through a `testflight` job, distributes the build to the `Paseo Beta` external group with Beta App Review submission, and a Fastlane lane submits that same build for App Store review. +- **Android (Play Store)** — EAS builds with profile `production` and auto-submits to the Play Store via `eas submit` (EAS-managed credentials). A Fastlane lane then replaces the store screenshots. +- **iOS (TestFlight + App Store)** — EAS builds with profile `production`, uploads once through a `testflight` job, distributes the build to the `Paseo Beta` external group with Beta App Review submission, and a Fastlane lane uploads the store screenshots and submits that same build for App Store review. - **Android APK (GitHub Release asset)** — separate, via `.github/workflows/android-apk-release.yml`. This is the only Android-related workflow that lives in this repo. EAS uses the local app version source. `packages/app/app.config.js` derives the native version from the package version. Android `versionCode` is `major * 1_000_000 + minor * 1_000 + patch`. iOS reserves 1,000 build slots per app version: beta `N` uses slot `N`, and stable uses slot `999`. For example, `0.2.6-beta.2` appears in App Store Connect as version `0.2.6` build `2006002`; stable uses build `2006999`. Rebuilding the same tag produces the same native build number; if a store has already accepted a binary and you need a different binary, cut the next beta or patch instead of relying on EAS remote auto-increment. @@ -317,6 +317,16 @@ Stable iOS releases use one binary for two Apple review paths: Beta App Review f There is no mobile-release workflow under `.github/workflows`. The EAS GitHub app reads the workflows under `packages/app/.eas/workflows` and handles tag triggering directly. +### Store screenshots + +Each stable release publishes the screenshots committed under `assets/store-screenshots/output/` (see [its README](../assets/store-screenshots/README.md) for how they are made). To change the store screenshots, re-render and commit them before you tag. + +- **App Store:** `submit_review` uploads `output/apple/` and `output/apple-ipad/` to the version it submits, replacing that version's `en-US` screenshots. Apple ties screenshots to an app version, so a version that is already live keeps the ones it shipped with. `Resubmit iOS for App Store review` uploads them again. +- **Google Play:** `upload_android_screenshots` runs `fastlane android upload_screenshots` after `submit_android`. It replaces only the phone and 10-inch tablet screenshots, never the listing text or changelogs, and skips images whose checksum already matches. +- **F-Droid:** reads the same files as Google Play. `fastlane/metadata/android/en-US/images/phoneScreenshots/` and `tenInchScreenshots/` hold symlinks to the Google renders. `render.mjs` rewrites them on every render, so added or renamed panels reach Google Play and F-Droid as well. + +Fastlane cannot use the Play key Expo stores for `eas submit`. The Play lane reads its own copy of the same service-account key from the `GOOGLE_PLAY_JSON_KEY` file secret in the EAS `production` environment, and that service account needs the Play Console permission **Manage store presence**. + ### Watching mobile builds from the terminal Use the EAS CLI from `packages/app/`: @@ -359,6 +369,7 @@ For the `Release Mobile` EAS workflow, these jobs must pass: - `submit_ios_for_review` — iOS build submitted for App Store review via Fastlane - `build_android` — Android store binary built - `submit_android` — Android binary submitted to the Play Store +- `upload_android_screenshots` — Google Play screenshots replaced from the repo Do not treat `build_ios: SUCCESS` or `distribute_ios: SUCCESS` as a completed iOS release. `submit_ios_for_review: FAILURE` means the iOS release is blocked even if the build is visible in TestFlight. diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/1.png b/fastlane/metadata/android/en-US/images/phoneScreenshots/1.png index 9f633ca58f..ca3a9fa2a8 120000 --- a/fastlane/metadata/android/en-US/images/phoneScreenshots/1.png +++ b/fastlane/metadata/android/en-US/images/phoneScreenshots/1.png @@ -1 +1 @@ -../../../../../../packages/website/public/phone-1.png \ No newline at end of file +../../../../../../assets/store-screenshots/output/google/01-sidebar.png \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/2.png b/fastlane/metadata/android/en-US/images/phoneScreenshots/2.png index 6d2fbd14d7..a0748cf426 120000 --- a/fastlane/metadata/android/en-US/images/phoneScreenshots/2.png +++ b/fastlane/metadata/android/en-US/images/phoneScreenshots/2.png @@ -1 +1 @@ -../../../../../../packages/website/public/phone-2.png \ No newline at end of file +../../../../../../assets/store-screenshots/output/google/02-chat.png \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/3.png b/fastlane/metadata/android/en-US/images/phoneScreenshots/3.png index e23c27ced5..0e7dba6b41 120000 --- a/fastlane/metadata/android/en-US/images/phoneScreenshots/3.png +++ b/fastlane/metadata/android/en-US/images/phoneScreenshots/3.png @@ -1 +1 @@ -../../../../../../packages/website/public/phone-3.png \ No newline at end of file +../../../../../../assets/store-screenshots/output/google/03-plugins.png \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/4.png b/fastlane/metadata/android/en-US/images/phoneScreenshots/4.png new file mode 120000 index 0000000000..e89becb9bc --- /dev/null +++ b/fastlane/metadata/android/en-US/images/phoneScreenshots/4.png @@ -0,0 +1 @@ +../../../../../../assets/store-screenshots/output/google/04-review.png \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/5.png b/fastlane/metadata/android/en-US/images/phoneScreenshots/5.png new file mode 120000 index 0000000000..c067990032 --- /dev/null +++ b/fastlane/metadata/android/en-US/images/phoneScreenshots/5.png @@ -0,0 +1 @@ +../../../../../../assets/store-screenshots/output/google/05-terminal.png \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/images/tenInchScreenshots/1.png b/fastlane/metadata/android/en-US/images/tenInchScreenshots/1.png new file mode 120000 index 0000000000..401053965e --- /dev/null +++ b/fastlane/metadata/android/en-US/images/tenInchScreenshots/1.png @@ -0,0 +1 @@ +../../../../../../assets/store-screenshots/output/google-tablet/01-sidebar.png \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/images/tenInchScreenshots/2.png b/fastlane/metadata/android/en-US/images/tenInchScreenshots/2.png new file mode 120000 index 0000000000..2454381850 --- /dev/null +++ b/fastlane/metadata/android/en-US/images/tenInchScreenshots/2.png @@ -0,0 +1 @@ +../../../../../../assets/store-screenshots/output/google-tablet/02-chat.png \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/images/tenInchScreenshots/3.png b/fastlane/metadata/android/en-US/images/tenInchScreenshots/3.png new file mode 120000 index 0000000000..1b31012051 --- /dev/null +++ b/fastlane/metadata/android/en-US/images/tenInchScreenshots/3.png @@ -0,0 +1 @@ +../../../../../../assets/store-screenshots/output/google-tablet/03-plugins.png \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/images/tenInchScreenshots/4.png b/fastlane/metadata/android/en-US/images/tenInchScreenshots/4.png new file mode 120000 index 0000000000..13d8545d92 --- /dev/null +++ b/fastlane/metadata/android/en-US/images/tenInchScreenshots/4.png @@ -0,0 +1 @@ +../../../../../../assets/store-screenshots/output/google-tablet/04-review.png \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/images/tenInchScreenshots/5.png b/fastlane/metadata/android/en-US/images/tenInchScreenshots/5.png new file mode 120000 index 0000000000..b0905beafc --- /dev/null +++ b/fastlane/metadata/android/en-US/images/tenInchScreenshots/5.png @@ -0,0 +1 @@ +../../../../../../assets/store-screenshots/output/google-tablet/05-terminal.png \ No newline at end of file diff --git a/packages/app/.eas/workflows/release-mobile.yml b/packages/app/.eas/workflows/release-mobile.yml index 26790ef22f..e57260898c 100644 --- a/packages/app/.eas/workflows/release-mobile.yml +++ b/packages/app/.eas/workflows/release-mobile.yml @@ -42,6 +42,20 @@ jobs: build_id: ${{ needs.build_android.outputs.build_id }} profile: production + upload_android_screenshots: + name: Upload Google Play screenshots + needs: [build_android, submit_android] + environment: production + runs_on: macos-medium + steps: + - uses: eas/checkout + - name: Install fastlane + run: bundle install + - name: Upload screenshots + run: | + export ANDROID_VERSION_CODE="${{ needs.build_android.outputs.app_build_version }}" + bundle exec fastlane android upload_screenshots + submit_ios_for_review: name: Submit iOS for App Store review needs: [build_ios, distribute_ios] diff --git a/packages/app/fastlane/Fastfile b/packages/app/fastlane/Fastfile index dc7508b456..065ca48b7f 100644 --- a/packages/app/fastlane/Fastfile +++ b/packages/app/fastlane/Fastfile @@ -1,7 +1,31 @@ +require "fileutils" +require "tmpdir" + default_platform(:ios) APP_IDENTIFIER = "sh.paseo" +# Store screenshots are rendered into assets/store-screenshots/output; see the +# README there. Google Play and F-Droid both read fastlane/metadata/android at +# the repo root, whose screenshot files link to those renders. +REPO_ROOT = File.expand_path("../../..", __dir__) +STORE_SCREENSHOTS = File.join(REPO_ROOT, "assets/store-screenshots/output") +ANDROID_METADATA = File.join(REPO_ROOT, "fastlane/metadata/android") + +# deliver reads screenshots from one folder per language and picks the device +# slot from each image's size, so both Apple sets go into en-US together. +def stage_app_store_screenshots + root = Dir.mktmpdir("app-store-screenshots") + locale = File.join(root, "en-US") + FileUtils.mkdir_p(locale) + { "apple" => "iphone", "apple-ipad" => "ipad" }.each do |set, device| + Dir.glob(File.join(STORE_SCREENSHOTS, set, "*.png")).sort.each do |file| + FileUtils.cp(file, File.join(locale, "#{device}-#{File.basename(file)}")) + end + end + root +end + platform :ios do desc "Submit the latest TestFlight build to App Store Review" lane :submit_review do @@ -87,7 +111,8 @@ platform :ios do }, force: true, skip_binary_upload: true, - skip_screenshots: true, + screenshots_path: stage_app_store_screenshots, + overwrite_screenshots: true, precheck_include_in_app_purchases: false, submission_information: { add_id_info_uses_idfa: false, @@ -96,3 +121,25 @@ platform :ios do ) end end + +platform :android do + desc "Replace the Google Play store screenshots with the ones in the repo" + lane :upload_screenshots do + # supply attaches listing changes to a release on the production track. + # The release workflow passes the version code it just submitted; without + # it, supply uses the track's only release. + version_code = ENV["ANDROID_VERSION_CODE"].to_s.strip + supply( + package_name: APP_IDENTIFIER, + json_key: ENV.fetch("GOOGLE_PLAY_JSON_KEY"), + metadata_path: ANDROID_METADATA, + version_code: version_code.empty? ? nil : version_code.to_i, + skip_upload_apk: true, + skip_upload_aab: true, + skip_upload_metadata: true, + skip_upload_changelogs: true, + skip_upload_images: true, + sync_image_upload: true, + ) + end +end From 61841d1ed5ec96a9561053fad9bc682c9dc8a07e Mon Sep 17 00:00:00 2001 From: babo-jeonguk Date: Thu, 29 Oct 2026 16:58:09 +0900 Subject: [PATCH 106/173] fix(app): stop web menus snapping back to their entering-animation rect (#8180) Reanimated's web path saves a custom keyframe's element rect when the animation ends, and writes it back as inline top/left/width/height when it cleans the keyframe up 750ms after the start. A menu whose content resized in between, such as a plugin popover whose data had just arrived, was left clipped to its loading-state size or hanging over its anchor. Play the same keyframes through the Web Animations API on web, which leaves no inline style, and drop the height release that only undid part of that write. Native keeps the Reanimated Keyframe. --- docs/menus.md | 16 ++- .../ui/menu/menu-overlay.browser.test.tsx | 124 ++++++++++++++++++ .../src/components/ui/menu/menu-overlay.tsx | 105 ++++++--------- .../src/components/ui/menu/menu-surface.tsx | 1 - 4 files changed, 173 insertions(+), 73 deletions(-) create mode 100644 packages/app/src/components/ui/menu/menu-overlay.browser.test.tsx diff --git a/docs/menus.md b/docs/menus.md index 15ea6b5a5d..590def2b33 100644 --- a/docs/menus.md +++ b/docs/menus.md @@ -200,13 +200,15 @@ its own. ## Gotchas -- **Released height.** Reanimated's web entering animation leaves an inline height snapshot on - the surface. `AnchoredSurface` clears it, and a `revision` prop re-clears it when content - identity changes — a pushed page taller than the one it replaced is clipped without that. -- **Animate only once placed.** The same snapshot carries top/left, and Reanimated writes it back - 750ms after mount. `AnchoredSurface` remounts the surface when its position resolves so the - entering animation never ends at the off-screen measuring position; on a slow machine that - write moved the open menu back off-screen. +- **Web enters without Reanimated.** For a custom keyframe, Reanimated's web path snapshots the + surface's rect when the animation ends and writes it back as inline top/left/width/height 750ms + after the start. Whatever moved or resized the surface in between was undone: content that + grew once its data arrived left the menu clipped, or hanging over its anchor, until it moved + again. `AnchoredSurface` plays the same keyframes through the Web Animations API on web, which + leaves no inline style; native keeps the Reanimated `Keyframe`. +- **Animate only once placed.** `AnchoredSurface` remounts the surface when its position resolves, + so the entering animation runs at the final position rather than ending unseen at the + off-screen measuring position. - **Sheets size to content.** `enableDynamicSizing`, not fixed snap points. A pushed page is rarely the height of the page before it. A fill page is the one exception. - **The sheet's content is teleported out of the menu's subtree**, so `MenuSheetSurface` rebuilds diff --git a/packages/app/src/components/ui/menu/menu-overlay.browser.test.tsx b/packages/app/src/components/ui/menu/menu-overlay.browser.test.tsx new file mode 100644 index 0000000000..9d60353a52 --- /dev/null +++ b/packages/app/src/components/ui/menu/menu-overlay.browser.test.tsx @@ -0,0 +1,124 @@ +import React, { act, useEffect, useState, type ReactNode } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { Text, View } from "react-native"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { page } from "vitest/browser"; +import { MenuRoot, MenuSurface, MenuTrigger, type Size } from "./index"; + +// App sources compile against the classic JSX runtime, which expects React on the global. +beforeEach(() => vi.stubGlobal("React", React)); + +/** + * A real browser, because the regression lives in Reanimated's web entering path: it snapshots + * the surface's rect when a custom keyframe ends and writes that rect back as inline + * top/left/width/height when it cleans the keyframe up, 750ms after the animation starts. + * Anything that moved or resized the surface in between is undone by that write. + */ + +interface Mounted { + root: Root; + container: HTMLDivElement; +} + +const mounted: Mounted[] = []; + +function mount(node: ReactNode): void { + const container = document.createElement("div"); + document.body.appendChild(container); + const root = createRoot(container); + act(() => root.render(node)); + mounted.push({ root, container }); +} + +afterEach(() => { + for (const entry of mounted.splice(0)) { + act(() => entry.root.unmount()); + entry.container.remove(); + } +}); + +const OFFSET = 12; +const PILL_POSITION = { position: "absolute", top: 700, left: 40 } as const; +const SHORT: Size = { width: 200, height: 40 }; +const TALL: Size = { width: 200, height: 240 }; +const WIDE: Size = { width: 480, height: 40 }; +/** Inside the window between the entering animation ending and Reanimated's cleanup. */ +const GROWS_BEFORE_CLEANUP_MS = 400; +/** Past Reanimated's cleanup, where the surface used to keep a fixed height. */ +const GROWS_AFTER_CLEANUP_MS = 1_000; +/** Long enough after the content grew for anything that would write to the surface to land. */ +const SETTLE_MS = 1_200; + +/** Plain timers, not `act`: an async `act` holds every update until it resolves. */ +function wait(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +function element(testID: string): HTMLElement { + const found = document.querySelector(`[data-testid="${testID}"]`); + if (!(found instanceof HTMLElement)) throw new Error(`${testID} did not render`); + return found; +} + +/** Stands in for a popover whose data lands after it opened, like a plugin's first RPC. */ +function GrowsAfterOpen({ afterMs, from, to }: { afterMs: number; from: Size; to: Size }) { + const [grown, setGrown] = useState(false); + useEffect(() => { + const timer = setTimeout(() => setGrown(true), afterMs); + return () => clearTimeout(timer); + }, [afterMs]); + return ; +} + +function mountMenuAbovePill(body: ReactNode): void { + mount( + + + + Open panel + + + {body} + + + , + ); + act(() => element("pill").click()); +} + +describe("anchored menu surface on web", () => { + beforeEach(async () => { + await page.viewport(1280, 900); + }); + + it.each([GROWS_BEFORE_CLEANUP_MS, GROWS_AFTER_CLEANUP_MS])( + "stays on its anchor when its content grows %ims after opening", + async (afterMs) => { + mountMenuAbovePill(); + + await wait(afterMs + SETTLE_MS); + + const pill = element("pill").getBoundingClientRect(); + const panel = element("panel").getBoundingClientRect(); + expect(panel.height).toBeGreaterThan(240); + expect(panel.bottom).toBeLessThanOrEqual(pill.top); + }, + ); + + it("widens when its content widens after the entering animation", async () => { + mountMenuAbovePill(); + + await wait(GROWS_BEFORE_CLEANUP_MS + SETTLE_MS); + + const body = element("body").getBoundingClientRect(); + const panel = element("panel").getBoundingClientRect(); + expect(panel.width).toBeGreaterThanOrEqual(body.width); + }); +}); diff --git a/packages/app/src/components/ui/menu/menu-overlay.tsx b/packages/app/src/components/ui/menu/menu-overlay.tsx index 9631dbbe9a..c6935bfd91 100644 --- a/packages/app/src/components/ui/menu/menu-overlay.tsx +++ b/packages/app/src/components/ui/menu/menu-overlay.tsx @@ -2,6 +2,7 @@ import { useCallback, useEffect, useId, + useLayoutEffect, useMemo, useState, type ReactElement, @@ -47,56 +48,41 @@ const contentEntering = new Keyframe({ 100: { opacity: 1, transform: [{ scale: 1 }] }, }).duration(CONTENT_ENTERING_DURATION_MS); +/** `contentEntering` for the browser's own animation engine. Both default to linear easing. */ +const WEB_CONTENT_ENTERING_KEYFRAMES: PropertyIndexedKeyframes = { + opacity: [0, 1], + transform: ["scale(0.97)", "scale(1)"], +}; + +/** Web plays the same keyframes itself; see `useWebContentEntering`. */ +const nativeContentEntering = isWeb ? undefined : contentEntering; + const contentExiting = new Keyframe({ 0: { opacity: 1, transform: [{ scale: 1 }] }, 100: { opacity: 0, transform: [{ scale: 0.97 }] }, }).duration(100); -function releaseFixedMenuHeight(surfaceNativeID: string): void { - if (!isWeb) return; - document.getElementById(surfaceNativeID)?.style.removeProperty("height"); -} - /** - * Reanimated's web entering animation leaves an inline height snapshot on the measured surface. - * Once the menu is open, height must return to content-sized so rows can grow in place — and so - * a submenu page taller than the page it replaced is not clipped to the old height. - * - * `revision` is what makes that second case work: bump it whenever the rendered content changes - * identity (a page push, for instance) and the snapshot is released again. + * On web the surface enters through the Web Animations API rather than Reanimated. Reanimated's + * web path snapshots an element's rect when a custom keyframe ends and, when it cleans the keyframe + * up 750ms after the start, writes that rect back as inline top/left/width/height. A surface that + * moved or resized in between — content that grew once its data arrived — snapped back to the old + * rect and stayed there, clipped or hanging past its anchor. A Web Animation leaves no inline style. */ -function useReleaseFixedMenuHeight({ - contentSize, - enabled, +function useWebContentEntering({ + placed, surfaceNativeID, - revision, }: { - contentSize: Size | null; - enabled: boolean; + placed: boolean; surfaceNativeID: string; - revision?: string | number; }): void { - useEffect(() => { - if (!enabled) return undefined; - - const release = () => { - releaseFixedMenuHeight(surfaceNativeID); - if (typeof requestAnimationFrame === "function") { - requestAnimationFrame(() => releaseFixedMenuHeight(surfaceNativeID)); - } - }; - const timers: ReturnType[] = [ - setTimeout(release, CONTENT_ENTERING_DURATION_MS), - ]; - - if (contentSize) { - timers.push(setTimeout(release, 0)); - } - - return () => { - for (const timer of timers) clearTimeout(timer); - }; - }, [contentSize, enabled, surfaceNativeID, revision]); + useLayoutEffect(() => { + if (!isWeb || !placed || typeof document === "undefined") return undefined; + const animation = document + .getElementById(surfaceNativeID) + ?.animate(WEB_CONTENT_ENTERING_KEYFRAMES, CONTENT_ENTERING_DURATION_MS); + return () => animation?.cancel(); + }, [placed, surfaceNativeID]); } /** @@ -224,8 +210,6 @@ export interface AnchoredSurfaceProps { fullWidth?: boolean; horizontalPadding?: number; scrollable?: boolean; - /** Bump when the rendered content changes identity, so the height snapshot is released. */ - revision?: string | number; /** A submenu sits inside its parent's overlay and must not paint a second backdrop. */ backdrop?: boolean; /** @@ -259,7 +243,6 @@ export function AnchoredSurface({ fullWidth = false, horizontalPadding = 16, scrollable = false, - revision, backdrop = true, onPointerEnter, onPointerLeave, @@ -269,33 +252,25 @@ export function AnchoredSurface({ }: AnchoredSurfaceProps): ReactElement | null { const { t } = useTranslation(); const surfaceNativeID = useId(); - const { position, actualPlacement, contentSize, visibleContentSize, onContentLayout } = - useAnchoredPosition({ - open, - anchorRect, - anchorRef, - side, - align, - offset, - scrollable, - maxHeight, - }); - - useReleaseFixedMenuHeight({ - contentSize, - enabled: open, - surfaceNativeID, - revision, + const { position, actualPlacement, visibleContentSize, onContentLayout } = useAnchoredPosition({ + open, + anchorRect, + anchorRef, + side, + align, + offset, + scrollable, + maxHeight, }); // The surface is placed once both measurements land. Until then it sits off-screen so it can - // be measured, and it must not animate: Reanimated's web entering path snapshots the element's - // rect when the animation ends and writes that rect back as inline top/left when it cleans the - // keyframe up 750ms later. If the animation ends before placement, the snapshot is the - // off-screen rect and the menu jumps back off-screen. Remounting on placement starts the - // animation from the final position. + // be measured, and it must not animate: an entering animation that ran there would be over + // before anyone saw the menu. Remounting on placement starts the native animation from the + // final position; web starts its own animation on placement. const placed = position !== null; + useWebContentEntering({ placed, surfaceNativeID }); + useEffect(() => { if (!isWeb || !open || !placed || typeof document === "undefined") return undefined; const frame = requestAnimationFrame(() => { @@ -383,7 +358,7 @@ export function AnchoredSurface({ dataSet={surfaceDataSet} style={styles.content} frameStyle={frameStyle} - entering={placed ? contentEntering : undefined} + entering={placed ? nativeContentEntering : undefined} exiting={ !placed || isWeb || !onExited ? undefined diff --git a/packages/app/src/components/ui/menu/menu-surface.tsx b/packages/app/src/components/ui/menu/menu-surface.tsx index 56ff2c0578..581b620499 100644 --- a/packages/app/src/components/ui/menu/menu-surface.tsx +++ b/packages/app/src/components/ui/menu/menu-surface.tsx @@ -344,7 +344,6 @@ function MenuFlyout({ maxHeight={maxHeight} scrollable={scrollable} backdrop={false} - revision={page.id} onPointerEnter={cancelHoverClose} onPointerLeave={handleHoverOut} testID={testID} From 7d74ae5d6cc057e98fc95a86b28b11215e4a5f79 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Thu, 29 Oct 2026 15:08:36 +0700 Subject: [PATCH 107/173] docs(release): release from tags with selected cherry-picks while main stays open (#8188) Replace the next-branch discipline with the main-first workflow: normal PRs always merge into main, each release builds in a short-lived release workspace from origin/main or a release tag plus approved cherry-picks, promotions take an inventory that defaults to defer, and a reconcile PR brings the shipped changelog, version and F-Droid files back into main. --- .github/workflows/ci.yml | 2 +- CLAUDE.md | 7 +- docs/release.md | 205 +++++++++++++++++++++++++-------------- 3 files changed, 137 insertions(+), 77 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f61d514727..7cb267c2dd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3,7 +3,7 @@ name: CI on: push: branches: [main] - # Every base branch, so stacked PRs and PRs into `next` get the same checks. + # Every base branch, so stacked PRs and PRs into any base get the same checks. pull_request: merge_group: workflow_dispatch: diff --git a/CLAUDE.md b/CLAUDE.md index d72205a01e..9a2c70de29 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -117,10 +117,9 @@ See [docs/development.md](docs/development.md) for full setup, build sync requir ## Release branches -When the user says "this goes to next", create or -retarget the PR to `next` and preserve that destination through delivery. Follow -[release branch discipline](docs/release.md#release-branch-discipline) for creating -and updating `next`, integrating it after a release, and releasing a hotfix from a tag. +Merge normal PRs into `main`, including while a beta soaks or a release is being finalized. Each +release builds in a short-lived release workspace from `origin/main` or a release tag; see +[release base and source](docs/release.md#release-base-and-source). ## Critical rules diff --git a/docs/release.md b/docs/release.md index ce0857abb3..07c6e1b16f 100644 --- a/docs/release.md +++ b/docs/release.md @@ -6,10 +6,10 @@ All workspaces share one version and release together. A release has exactly two steps. The agent does the first, the user authorizes the second. -**Preparation** (local, reversible — agent does this): +**Preparation** (reversible — agent does this): - format, lint, typecheck all green -- resolve the release source to one commit and confirm that commit's existing CI is green +- resolve the [release base](#release-base-and-source), get the [release inventory](#release-inventory) approved when one applies, and confirm CI for the resulting release source is green - classify the diff from the previous stable to the release source as patch or minor, then show the target version and rationale to the user - draft the changelog, show it to the user, wait for review @@ -17,9 +17,10 @@ A release has exactly two steps. The agent does the first, the user authorizes t **Go-ahead** (user says "go ahead"): -- commit the approved release inputs locally -- run the release, which publishes npm and pushes the prepared branch and tag +- commit the approved release inputs locally on the release branch +- run the release, which publishes npm and pushes the release branch and tag - create the release heartbeat immediately and babysit it to completion +- [reconcile `main`](#reconcile-main) with what shipped Rules that apply to both steps: @@ -27,56 +28,128 @@ Rules that apply to both steps: - No code changes bundled into the changelog commit or the release commit. Code shims live in their own commit, reviewed on their own merits. - A sanity-check finding is information, not a directive. The agent surfaces it; the user decides. - Invoking a release skill is intent to start the flow, not blanket authorization to publish. +- An approval the user already gave covers what it names, such as an explicit PR selection or authorization to release autonomously. Do not ask for it again. - If the user asks for a release preview, show the prospective changelog/release contents and answer questions, but do not commit, tag, publish, or run release commands until they explicitly authorize the release. -## Release source and CI +## Main stays open -The default release source is `origin/main`. Fetch `origin`, then record the -resolved commit. The default release checkout is a clean local `main` whose -`HEAD` equals `origin/main`. +Merge normal PRs into `main` at any time, including while a beta soaks or a release is being +finalized. Each release builds in a short-lived release workspace, and its published tag records +the shipped source. -An explicit user instruction can select another ref, such as a hotfix commit or -tag. Resolve that ref once and apply every source, diff, and CI check to that -commit instead of `origin/main`. +## Choosing a path -Before making release-preparation commits, confirm the existing CI run for the -resolved commit is green. Pending CI is watched to completion. Release -preparation then stays local through the changelog, any explicitly requested ACP -catalog update, lockfile preparation, and the version commit. After approval, -commit the prepared inputs locally and run the release command. Its branch and -tag push is the one remote release batch and starts CI for the complete release -commit. +The user decides when the changes on `main` warrant a release and how much risk it takes: -## Release branch discipline +1. **Direct stable release** for a low-risk batch of polish and bug fixes. Stable desktop updates + already ramp over 36 hours (see [Staged rollout](#staged-rollout-stable-channel)), and store + review often takes about a day, with no guaranteed timing. +2. **Beta flow**, the default for changes that need testing. Release candidates on the `beta` + channel. Each beta folds into the series' single changelog entry, publishes npm only on the + explicit `beta` dist-tag, and stays behind the Stable/Beta switch on `/download`. -While you finalize a release on `main`, use a temporary `next` branch for work intended for the following -release. This applies to both beta and stable releases. +A beta follows these defaults, which the user can explicitly override: -- Create each new `next` from freshly fetched `origin/main`. Reuse it while active. -- "This goes to next" means create the PR against `next` or retarget an existing - PR, and keep that destination through delivery. -- Keep `next` current by merging `origin/main` into it as release fixes land. - Avoid rebasing this shared branch because agents and open PRs depend on its history. -- After the release ships, bring `next` up to date and open a `next` → `main` PR. - Pass CI and merge without squashing away the individual PR commits needed for - the changelog. Retarget remaining PRs based on `next` to `main` and delete the integrated - `next`. Create it fresh when needed again. +- Soak a beta at least 24 hours before promotion. Soak longer for risky or breaking changes, or + while feedback is open. Changes added in a later beta get their own soak; earlier soak time does + not count for them. +- A follow-up beta carries regressions, fixes, and polish for what that beta delivers. Unrelated + work on `main` and pre-existing bugs wait for a later release unless the user explicitly selects + them. +- Promotion ships the tested beta's product content unchanged and does not pull from `main`. + Adding a product change needs the user's explicit selection and a new beta, which soaks again. +- During a soak, ship urgent stable regressions and compatibility or provider model updates as a + [stable hotfix](#release-base-and-source) from the latest stable tag. The beta keeps its own + pace. -**Setup still needed:** PR checks run for every base branch, but CI, Docker, and Nix -push runs target only `main`, and GitHub permits only squash merges. Enable -required-check protection for `next`, CI on its pushes, and merge commits for the -integration PR. Handle PR -base changes (`edited` events) so retargeting runs checks against the new base; -GitHub's default PR events do not cover this. Deployment triggers stay unchanged. +npm dist-tags are independent pointers: -### Hotfix from a release tag +- A beta release publishes with `--tag beta` and moves only `beta`; `latest` remains on the + newest stable. +- A stable release publishes to `latest`. Move `beta` to it as well when the stable version is + newer than the version `beta` points to, which covers promotions and direct stable releases, so + `@getpaseo/cli@beta` users never sit behind stable. A stable hotfix on an older line leaves + `beta` on the active newer beta. -If `main` contains changes you do not want to release, branch from the affected -release tag and cherry-pick only the required fixes. Run CI on that branch, then -use the normal release flow with it as the explicit source, choosing a new patch -or beta version. Ensure the fixes and changelog also reach `main` and any active -`next`, preserving newer development and version changes there. This is a -short-lived hotfix branch, not another maintained release track. +## Release base and source + +The release base is the tag or commit a release workspace starts from. The release source is the +base plus any approved cherry-picks, and every source, diff, and CI check uses it. + +| Release | Base | Changes on top | +| -------------------------------------------------------- | ------------------------------------------------------------ | ---------------------------- | +| Starting release: first beta of a line, or direct stable | `origin/main`, captured once | None | +| Follow-up beta | The selected published beta tag, normally the series' latest | Approved commits from `main` | +| Promotion | The beta tag being promoted | None by default | +| Stable hotfix | The latest appropriate stable tag | Approved commits from `main` | + +An explicit user instruction can select another base. + +1. Fetch `origin` with tags and resolve the base to one commit. +2. Create the release workspace through Paseo MCP on a new branch from the base, named + `release/vX.Y.Z` or `release/vX.Y.Z-beta.N` for the version being cut. Run the release from + this workspace: `release:push` pushes `HEAD` to the current branch. +3. Cherry-pick the approved commits in their `main` order with `git cherry-pick -x`, so each + commit records the `main` commit it came from. Include the prerequisites the inventory listed. + Resolve conflicts within the approved changes and report how. A resolution that needs new + behavior is a scope addition: surface it for selection. +4. Confirm CI for the release source. When the source is a commit whose CI already passed (the + captured `origin/main`, or the beta tag being promoted), use that run and watch pending CI to + completion. Otherwise push the release branch and run `gh workflow run ci.yml --ref `, + because CI push runs target only `main`. +5. Keep the changelog, any explicitly requested ACP catalog update, lockfile preparation, and the + version commit local until the go-ahead. The release command pushes the release branch and tag + as one batch, and the tag push starts the release workflows. Then run + `gh workflow run ci.yml --ref ` so CI covers the complete release commit. +6. [Reconcile `main`](#reconcile-main). + +A stable hotfix can take the version a patch beta line would promote to, such as `0.13.3` +shipping while `0.13.3-beta.2` soaks. Never republish or reuse a shipped version. Continue the line +as the next unused patch beta, `0.13.4-beta.1`, from the tested beta tag. No `version:all:*` mode +computes that from a prerelease, so follow the [manual steps](#manual-step-by-step) with +`npm version 0.13.4-beta.1 --include-workspace-root --message "chore(release): cut %s"` and +`npm run release:publish:beta`. Record the tested beta tag as its source so its soak still counts +for the unchanged content. + +## Release inventory + +When the user asks for a follow-up beta or a promotion, list what `main` has that the base does +not, then get the batch approved. There is no release label or queue. + +1. Find the commits on `origin/main` whose patches are not in the base tag: + + ```bash + git log --cherry-pick --right-only --no-merges --format='%h %s' ...origin/main + ``` + + Patch equivalence recognizes commits already cherry-picked into the tag, so trust the tag + content over PR state or branch names. + +2. Present a short include/defer list. Link each PR and give one plain reason. List separately the + prerequisites an included PR depends on and anything that adds scope beyond what the beta + delivers. For each fix that shipped in a stable hotfix after the beta's base, confirm the beta + preserves its behavior, directly or through a superseding change. List the missing ones for + explicit selection; adding one to a promotion needs a new beta. +3. Wait for the user to approve the batch, unless an explicit selection or autonomous + authorization they already gave covers it. + +For a promotion, every item defaults to defer. + +## Reconcile main + +After the release push, open a PR into `main` that brings in what shipped and keeps newer +development on `main`: + +- The shipped `CHANGELOG.md` and `CHANGELOG.zh-CN.md` entries, exactly as tagged. A beta or + promotion entry replaces the series entry on `main`. A stable hotfix on an older line goes + below any newer entries. +- The shipped version in every `package.json` and `package-lock.json`, unless `main` already + carries a newer version, plus the F-Droid changelog files a stable release generates. +- No claims about unshipped work: a shipped entry describes only the tagged content, and notes + `main` holds for changes that have not shipped stay out of it. + +Delete the release branch once the PR merges. The tag is the record of shipped source; Paseo +maintains no release track besides `main`. ## ACP catalog updates @@ -91,21 +164,6 @@ ACP catalog work enters a release through an explicit user request: The release authorization covers the requested ACP commit. It ships in the same release push as the changelog and version commit. -## Two paths - -There are two supported release paths: - -1. **Direct stable release**: you are ready to ship the resolved release source to everyone immediately (default `origin/main`). -2. **Beta flow**: release candidates on the `beta` channel. Each beta folds into the series' single changelog entry, publishes npm only on the explicit `beta` dist-tag, and stays behind the Stable/Beta switch on `/download`. - -Paseo has one linear release track even though npm dist-tags are independent -pointers. The npm invariant is: - -- A beta release moves only `beta`; `latest` remains on the newest stable. -- A stable release moves both `latest` and `beta` to that stable version. This - keeps users who install `@getpaseo/cli@beta` on the newest Paseo release after - a beta is promoted or superseded by a direct stable release. - ## Release version decision Every fresh release starts by classifying the full diff from the previous @@ -133,7 +191,7 @@ as described in **Fixing a failed release build**. Before running any stable release command: -- Make sure the resolved release source passed CI, the approved release inputs are committed locally on the intended branch, and the working tree is clean. +- Make sure the release source passed CI, the approved release inputs are committed locally on the release branch, and the working tree is clean. - **Run `npm run format`, `npm run lint`, and `npm run typecheck` and commit any resulting changes BEFORE you start any `release:*` command.** `release:check` runs `npm install --workspaces --include-workspace-root` as part of `release:prepare`, which can mutate `package-lock.json` (e.g. churning `"dev": true` markers on optional deps). The next step, `version:all:*`, runs `npm version` which aborts when the working tree is dirty. If this happens mid-flight you have to commit the lockfile churn before retrying — and the pre-commit format hook will reject a lockfile-only commit because oxfmt internally skips `package-lock.json` while lefthook's glob still matches it. Avoid the whole mess by running format/lint/typecheck first, then `release:prepare` once on its own to absorb any lockfile churn into a normal commit, then start the release. - Do not use a release command as a substitute for checking whether the current commit is actually ready. @@ -145,9 +203,9 @@ npm run release:minor This bumps the version across all workspaces, runs checks, publishes to npm, and pushes the branch + tag. The tag push triggers `Desktop Release`, `Android APK Release`, `Docker`, and `Release Notes Sync` on GitHub Actions. The workflows create the GitHub Release as a draft while builds and release-note sync run. EAS picks up the same tag via the EAS GitHub app and starts the iOS + Android store builds in parallel (see "Mobile builds (EAS)" below) — there is no mobile-release workflow under `.github/workflows`. -After the stable release succeeds, move npm's `beta` pointer to the new stable -version for every published package. This changes dist-tags only; do not -republish the packages: +After the stable release succeeds, check `npm view @getpaseo/cli dist-tags`. When the new stable +is newer than `beta`, move `beta` to it for every published package. This changes dist-tags only; +do not republish the packages: ```bash PASEO_VERSION=$(node -p "require('./package.json').version") @@ -156,8 +214,8 @@ for package in highlight relay protocol client plugin server cli; do done ``` -Verify both npm tags now resolve to `PASEO_VERSION` before considering the -stable release complete. +Verify `latest` resolves to `PASEO_VERSION`, and `beta` resolves to `PASEO_VERSION` or the +active newer beta, before considering the stable release complete. The Docker workflow builds images from the checked-out source tree on pull requests and on `main` as non-publishing checks. Stable `vX.Y.Z` tag pushes publish `ghcr.io/getpaseo/paseo:X.Y.Z` and `ghcr.io/getpaseo/paseo:latest`; beta `vX.Y.Z-beta.N` tag pushes publish only `ghcr.io/getpaseo/paseo:X.Y.Z-beta.N` and never move `latest`. @@ -175,7 +233,7 @@ npm run version:all:patch npm run version:all:minor npm run release:publish # Publish to npm npm run release:push # Push HEAD + tag (triggers CI workflows) -# Then move npm's beta dist-tag to this stable version using the command above. +# Then move npm's beta dist-tag to this stable version when it is newer than beta (see above). ``` ## Beta flow @@ -488,7 +546,7 @@ git tag -f android-v0.1.28 HEAD && git push origin android-v0.1.28 --force git tag -f v0.1.29-beta.2 HEAD && git push origin v0.1.29-beta.2 --force ``` -This ensures the checkout ref matches the actual code on `main` with the fix included. +This ensures the checkout ref matches the code you want built, with the fix included. - `vX.Y.Z` or `vX.Y.Z-beta.N` rebuilds the full tagged release - `desktop-vX.Y.Z` rebuilds desktop for all desktop platforms only @@ -631,7 +689,7 @@ Rules: This returns every distinct GitHub login that authored or co-authored a commit in the PR. Use those logins for attribution. Fall back to `gh pr view N --json author` only if the commits command returns nothing (which should not happen for merged PRs). - When listing PR numbers, `git log --format='%H %s' v.. | grep -E '\(#[0-9]+\)$'` pulls the PR number out of squash commit subjects. + When listing PR numbers, `git log --cherry-pick --right-only --no-merges --format='%H %s' v... | grep -E '\(#[0-9]+\)$'` pulls the PR number out of squash commit subjects and skips commits the previous stable already shipped as cherry-picks. ## Changelog ordering @@ -663,11 +721,11 @@ Every entry covers `previous stable release → release source`: first beta, lat ### Beta release -- [ ] The resolved release source is the intended commit (default `origin/main`) and its existing CI is green +- [ ] The release base and changes match the [release base table](#release-base-and-source) and any approved [inventory](#release-inventory), and CI for the release source is green - [ ] Every PR in the release range has been opened, and its full description and every linked issue have been read before drafting the changelog - [ ] Fold this beta into the series' single `CHANGELOG.md` entry (heading `## X.Y.Z-beta.N - YYYY-MM-DD`, previous stable → release source), review it against the changelog policy, get approval, and commit it with its [`CHANGELOG.zh-CN.md` translation](#changelog-translations) before cutting the release - [ ] The diff from the previous stable to the resolved release source is classified as patch or minor, with the target version and rationale approved -- [ ] Release preparation stayed local until the approved release command pushed the complete branch and tag +- [ ] The changelog, ACP, lockfile, and version commits stayed local until the approved release command pushed the release branch and tag - [ ] `npm run release:beta:patch`, `npm run release:beta:minor`, or `npm run release:beta:next` completes successfully - [ ] Every GitHub Actions run for the complete release commit and tag is green - [ ] npm shows the version under the `beta` dist-tag, not `latest` @@ -678,22 +736,24 @@ Every entry covers `previous stable release → release source`: first beta, lat - [ ] GitHub `Docker` workflow is green and the versioned beta image is published without moving `latest` - [ ] GitHub `Release Notes Sync` mirrored the beta entry into the prerelease body - [ ] EAS `Release iOS Beta` completed its build, TestFlight distribution, external beta group, and Beta App Review path +- [ ] The [reconcile PR](#reconcile-main) brought the shipped changelog entries and version into `main` - [ ] The release heartbeat was created after the tag push and deleted only after every item above passed ### Stable release (or promotion) - [ ] Run the pre-release sanity check (see above) and address any findings - [ ] The diff from the previous stable to the resolved release source is classified as patch or minor, with the target version and rationale approved -- [ ] The resolved release source is the intended commit (default `origin/main`) and its existing CI is green +- [ ] The release base and changes match the [release base table](#release-base-and-source) and any approved [inventory](#release-inventory), and CI for the release source is green +- [ ] A promotion ships the tested beta's product content after its soak, unless the user explicitly overrode either default - [ ] Every PR in the release range has been opened, and its full description and every linked issue have been read before drafting the changelog - [ ] Ensure the approved release inputs are committed locally and the git worktree is clean before running any release command - [ ] Ensure local `npm run typecheck` passes on that exact commit before running any release command - [ ] Update `CHANGELOG.md` with user-facing release notes (features, fixes — not refactors). Promotion renames the series' `## X.Y.Z-beta.N` entry to `## X.Y.Z - YYYY-MM-DD` and re-checks it covers the full release. Commit the matching [`CHANGELOG.zh-CN.md` entry](#changelog-translations) with it - [ ] Verify the changelog heading follows strict `## X.Y.Z - YYYY-MM-DD` format -- [ ] Release preparation stayed local until the approved release command pushed the complete branch and tag +- [ ] The changelog, ACP, lockfile, and version commits stayed local until the approved release command pushed the release branch and tag - [ ] `npm run release:patch`, `npm run release:minor`, or `npm run release:promote` completes successfully - [ ] Every GitHub Actions run for the complete release commit and tag is green -- [ ] Move npm's `beta` dist-tag to the new stable version for every published package and verify both `latest` and `beta` resolve to it +- [ ] `latest` resolves to the new stable, and `beta` resolves to it too unless an active newer beta holds `beta` - [ ] The GitHub Release was published only after the three stable manifests were uploaded, and it has the changelog body and every expected macOS, Linux, Windows, and Android APK asset - [ ] GitHub `Desktop Release` workflow for the `v*` tag is green - [ ] The GitHub Release contains `latest-mac.yml`, `latest-linux.yml`, and `latest.yml` @@ -707,4 +767,5 @@ Every entry covers `previous stable release → release source`: first beta, lat - [ ] EAS iOS `submit_ios_for_review` succeeds, putting the build into App Store review - [ ] EAS Android `build_android` completes for the same tag - [ ] EAS Android `submit_android` succeeds, putting the build on its Play Store track +- [ ] The [reconcile PR](#reconcile-main) brought the shipped changelog entries and version into `main` - [ ] The release heartbeat was created after the tag push and deleted only after every item above passed From f7eef9dd0c69591b34dde2de1116e1e8651ee8bf Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Thu, 29 Oct 2026 15:40:29 +0700 Subject: [PATCH 108/173] chore(release): reconcile main with v0.14.0 (#8193) Bring in what v0.14.0 shipped: the 0.14.0 entry in CHANGELOG.md and CHANGELOG.zh-CN.md exactly as tagged (replacing the 0.14.0-beta.2 series entry), the 0.14.0 version in every package.json and package-lock.json, and the generated F-Droid changelogs. The unreleased notes on main stay above the entry and now say they are not in 0.14.0. Release commit: 8c6de842a3157530c26a7a94c78a3d647fb96ce9 (tag v0.14.0) --- CHANGELOG.md | 8 +-- CHANGELOG.zh-CN.md | 8 +-- .../android/en-US/changelogs/140001.txt | 10 ++++ .../android/en-US/changelogs/140002.txt | 10 ++++ .../android/en-US/changelogs/140003.txt | 10 ++++ .../android/en-US/changelogs/140004.txt | 10 ++++ package-lock.json | 56 +++++++++---------- package.json | 2 +- packages/app/package.json | 2 +- packages/cli/package.json | 8 +-- packages/client/package.json | 6 +- packages/desktop/package.json | 2 +- packages/expo-two-way-audio/package.json | 2 +- packages/highlight/package.json | 2 +- packages/plugin/package.json | 10 ++-- packages/protocol/package.json | 2 +- packages/relay/package.json | 2 +- packages/server/package.json | 12 ++-- packages/website/package.json | 2 +- plugins/package.json | 2 +- 20 files changed, 103 insertions(+), 63 deletions(-) create mode 100644 fastlane/metadata/android/en-US/changelogs/140001.txt create mode 100644 fastlane/metadata/android/en-US/changelogs/140002.txt create mode 100644 fastlane/metadata/android/en-US/changelogs/140003.txt create mode 100644 fastlane/metadata/android/en-US/changelogs/140004.txt diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a11f55d5b..e47984dbf7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -Not released yet. These changes are on `main` but not in 0.14.0-beta.2; the next release entry includes them. +Not released yet. These changes are on `main` but not in 0.14.0; the next release entry includes them. Added: @@ -11,7 +11,7 @@ Improved: - Added `server.addHook` with `subject.operation.position` names and the awaited `worktree.create.after` hook before setup and agents; deprecated the previous plugin hook registration methods without changing their behavior ([#8081](https://github.com/getpaseo/paseo/pull/8081)) -## 0.14.0-beta.2 - 2026-10-28 +## 0.14.0 - 2026-10-29 Plugins can now add tools to individual agents and configure their MCP servers when sessions open. @@ -43,7 +43,6 @@ Voice settings now let you configure speech providers and download local models - Reduced daemon stalls when opening and paging large Claude and OMP histories ([#7789](https://github.com/getpaseo/paseo/pull/7789), [#7940](https://github.com/getpaseo/paseo/pull/7940), [#7948](https://github.com/getpaseo/paseo/pull/7948), [#7958](https://github.com/getpaseo/paseo/pull/7958) by [@ragokan](https://github.com/ragokan)) - Reduced daemon stalls during plugin builds, image processing and config reloads ([#7967](https://github.com/getpaseo/paseo/pull/7967), [#7954](https://github.com/getpaseo/paseo/pull/7954), [#7959](https://github.com/getpaseo/paseo/pull/7959)) - Reduced blocking filesystem work during workspace and project refreshes ([#7941](https://github.com/getpaseo/paseo/pull/7941), [#7943](https://github.com/getpaseo/paseo/pull/7943), [#7944](https://github.com/getpaseo/paseo/pull/7944)) -- Added a workaround for Claude Code sessions consuming subscription limits faster in Paseo ([#7976](https://github.com/getpaseo/paseo/pull/7976) by [@david828019-oss](https://github.com/david828019-oss)) ### Fixed @@ -72,7 +71,8 @@ Voice settings now let you configure speech providers and download local models - Voice mode now defaults to off; enable it in Voice settings - If environment variables select OpenAI speech, move keys and endpoints stored only in legacy `providers.openai` into Voice settings -- Before downgrading to 0.13.2, restore a backed-up `config.json` or convert speech credentials and idle-cleanup settings saved by the beta +- Before downgrading to 0.13.2, restore a backed-up `config.json` or convert speech credentials and idle-cleanup settings saved by 0.14.0 +- Install the optional [Claude Code entrypoint plugin](https://paseo.sh/plugins/getpaseo/claude-code-entrypoint-env) to launch Claude sessions with `CLAUDE_CODE_ENTRYPOINT=Paseo`, a community workaround for subscription limits draining faster ([#7976](https://github.com/getpaseo/paseo/pull/7976), [#8164](https://github.com/getpaseo/paseo/pull/8164) by [@david828019-oss](https://github.com/david828019-oss)) ## 0.13.2 - 2026-10-26 diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index a089401f39..f87cb58805 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -1,6 +1,6 @@ # 更新日志 -尚未发布。以下变更已合入 `main`,但不包含在 0.14.0-beta.2 中;下一个版本的条目会包含它们。 +尚未发布。以下变更已合入 `main`,但不包含在 0.14.0 中;下一个版本的条目会包含它们。 新增: @@ -11,7 +11,7 @@ - 新增采用 `subject.operation.position` 命名的 `server.addHook` 和在 setup 及 Agent 之前等待的 `worktree.create.after` 钩子,弃用原有的插件钩子注册方法并保留原有行为 ([#8081](https://github.com/getpaseo/paseo/pull/8081)) -## 0.14.0-beta.2 - 2026-10-28 +## 0.14.0 - 2026-10-29 插件现在可以为单个 Agent 添加工具,并在会话打开时配置其 MCP 服务器。 @@ -43,7 +43,6 @@ - 减少打开和分页加载大型 Claude 和 OMP 历史时的 daemon 卡顿 ([#7789](https://github.com/getpaseo/paseo/pull/7789), [#7940](https://github.com/getpaseo/paseo/pull/7940), [#7948](https://github.com/getpaseo/paseo/pull/7948), [#7958](https://github.com/getpaseo/paseo/pull/7958) by [@ragokan](https://github.com/ragokan)) - 减少插件构建、图片处理和重新加载配置时的 daemon 卡顿 ([#7967](https://github.com/getpaseo/paseo/pull/7967), [#7954](https://github.com/getpaseo/paseo/pull/7954), [#7959](https://github.com/getpaseo/paseo/pull/7959)) - 减少刷新工作区和项目时由文件系统操作造成的阻塞 ([#7941](https://github.com/getpaseo/paseo/pull/7941), [#7943](https://github.com/getpaseo/paseo/pull/7943), [#7944](https://github.com/getpaseo/paseo/pull/7944)) -- 为 Claude Code 会话在 Paseo 中更快消耗订阅额度的问题添加了变通方案 ([#7976](https://github.com/getpaseo/paseo/pull/7976) by [@david828019-oss](https://github.com/david828019-oss)) ### 修复 @@ -72,7 +71,8 @@ - 语音模式默认关闭,可在语音设置中启用 - 如果通过环境变量选择 OpenAI 语音,请将仅保存在旧版 `providers.openai` 中的密钥和服务地址移至语音设置 -- 降级至 0.13.2 前,请恢复备份的 `config.json` 或转换 beta 保存的语音凭据和空闲清理设置 +- 降级至 0.13.2 前,请恢复备份的 `config.json` 或转换 0.14.0 保存的语音凭据和空闲清理设置 +- 安装可选的 [Claude Code entrypoint 插件](https://paseo.sh/plugins/getpaseo/claude-code-entrypoint-env),即可使用 `CLAUDE_CODE_ENTRYPOINT=Paseo` 启动 Claude 会话;这是针对订阅额度消耗过快问题的社区变通方案 ([#7976](https://github.com/getpaseo/paseo/pull/7976), [#8164](https://github.com/getpaseo/paseo/pull/8164) by [@david828019-oss](https://github.com/david828019-oss)) ## 0.13.2 - 2026-10-26 diff --git a/fastlane/metadata/android/en-US/changelogs/140001.txt b/fastlane/metadata/android/en-US/changelogs/140001.txt new file mode 100644 index 0000000000..32cf0aa48b --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/140001.txt @@ -0,0 +1,10 @@ +Plugins can now add tools to individual agents and configure their MCP servers when sessions open. + +Completed conversation turns can be collapsed into summaries and expanded to read the full exchange. + +Voice settings now let you configure speech providers and download local models with one tap, including SenseVoice and Whisper for Chinese dictation. Voice mode is now opt-in. + +Added +- Let plugins give tools to specific agents + +Full notes: https://paseo.sh/changelog diff --git a/fastlane/metadata/android/en-US/changelogs/140002.txt b/fastlane/metadata/android/en-US/changelogs/140002.txt new file mode 100644 index 0000000000..32cf0aa48b --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/140002.txt @@ -0,0 +1,10 @@ +Plugins can now add tools to individual agents and configure their MCP servers when sessions open. + +Completed conversation turns can be collapsed into summaries and expanded to read the full exchange. + +Voice settings now let you configure speech providers and download local models with one tap, including SenseVoice and Whisper for Chinese dictation. Voice mode is now opt-in. + +Added +- Let plugins give tools to specific agents + +Full notes: https://paseo.sh/changelog diff --git a/fastlane/metadata/android/en-US/changelogs/140003.txt b/fastlane/metadata/android/en-US/changelogs/140003.txt new file mode 100644 index 0000000000..32cf0aa48b --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/140003.txt @@ -0,0 +1,10 @@ +Plugins can now add tools to individual agents and configure their MCP servers when sessions open. + +Completed conversation turns can be collapsed into summaries and expanded to read the full exchange. + +Voice settings now let you configure speech providers and download local models with one tap, including SenseVoice and Whisper for Chinese dictation. Voice mode is now opt-in. + +Added +- Let plugins give tools to specific agents + +Full notes: https://paseo.sh/changelog diff --git a/fastlane/metadata/android/en-US/changelogs/140004.txt b/fastlane/metadata/android/en-US/changelogs/140004.txt new file mode 100644 index 0000000000..32cf0aa48b --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/140004.txt @@ -0,0 +1,10 @@ +Plugins can now add tools to individual agents and configure their MCP servers when sessions open. + +Completed conversation turns can be collapsed into summaries and expanded to read the full exchange. + +Voice settings now let you configure speech providers and download local models with one tap, including SenseVoice and Whisper for Chinese dictation. Voice mode is now opt-in. + +Added +- Let plugins give tools to specific agents + +Full notes: https://paseo.sh/changelog diff --git a/package-lock.json b/package-lock.json index 0930535606..3351d15ac9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "paseo", - "version": "0.14.0-beta.2", + "version": "0.14.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "paseo", - "version": "0.14.0-beta.2", + "version": "0.14.0", "hasInstallScript": true, "license": "Apache-2.0", "workspaces": [ @@ -37590,7 +37590,7 @@ }, "packages/app": { "name": "@getpaseo/app", - "version": "0.14.0-beta.2", + "version": "0.14.0", "dependencies": { "@codemirror/commands": "6.10.4", "@codemirror/language": "6.12.4", @@ -39793,12 +39793,12 @@ }, "packages/cli": { "name": "@getpaseo/cli", - "version": "0.14.0-beta.2", + "version": "0.14.0", "dependencies": { "@clack/prompts": "^1.0.0", - "@getpaseo/client": "0.14.0-beta.2", - "@getpaseo/protocol": "0.14.0-beta.2", - "@getpaseo/server": "0.14.0-beta.2", + "@getpaseo/client": "0.14.0", + "@getpaseo/protocol": "0.14.0", + "@getpaseo/server": "0.14.0", "chalk": "^5.3.0", "commander": "^12.0.0", "mime-types": "^2.1.35", @@ -40045,10 +40045,10 @@ }, "packages/client": { "name": "@getpaseo/client", - "version": "0.14.0-beta.2", + "version": "0.14.0", "dependencies": { - "@getpaseo/protocol": "0.14.0-beta.2", - "@getpaseo/relay": "0.14.0-beta.2", + "@getpaseo/protocol": "0.14.0", + "@getpaseo/relay": "0.14.0", "ws": "^8.20.0", "zod": "^4.4.3" }, @@ -40060,7 +40060,7 @@ }, "packages/desktop": { "name": "@getpaseo/desktop", - "version": "0.14.0-beta.2", + "version": "0.14.0", "license": "Apache-2.0", "dependencies": { "@getpaseo/cli": "*", @@ -40304,7 +40304,7 @@ }, "packages/expo-two-way-audio": { "name": "@getpaseo/expo-two-way-audio", - "version": "0.14.0-beta.2", + "version": "0.14.0", "license": "MIT", "devDependencies": { "@types/jest": "^29.5.14", @@ -40350,7 +40350,7 @@ }, "packages/highlight": { "name": "@getpaseo/highlight", - "version": "0.14.0-beta.2", + "version": "0.14.0", "dependencies": { "@codemirror/language": "6.12.4", "@codemirror/legacy-modes": "^6.5.3", @@ -40379,15 +40379,15 @@ }, "packages/plugin": { "name": "@getpaseo/plugin", - "version": "0.14.0-beta.2", + "version": "0.14.0", "dependencies": { "@agentclientprotocol/sdk": "^1.4.0", "i18next": "^26.3.0", "use-sync-external-store": "^1.6.0" }, "devDependencies": { - "@getpaseo/client": "0.14.0-beta.2", - "@getpaseo/protocol": "0.14.0-beta.2", + "@getpaseo/client": "0.14.0", + "@getpaseo/protocol": "0.14.0", "@types/node": "^20.9.0", "@types/react": "~19.2.0", "react": "19.2.3", @@ -40397,8 +40397,8 @@ "zod": "^4.4.3" }, "peerDependencies": { - "@getpaseo/client": "0.14.0-beta.2", - "@getpaseo/protocol": "0.14.0-beta.2", + "@getpaseo/client": "0.14.0", + "@getpaseo/protocol": "0.14.0", "react": ">=19.1.0 <20", "react-native": ">=0.81.5", "zod": "^4.4.3" @@ -40420,7 +40420,7 @@ }, "packages/protocol": { "name": "@getpaseo/protocol", - "version": "0.14.0-beta.2", + "version": "0.14.0", "dependencies": { "semver": "^7.8.5", "zod": "^4.4.3" @@ -40447,7 +40447,7 @@ }, "packages/relay": { "name": "@getpaseo/relay", - "version": "0.14.0-beta.2", + "version": "0.14.0", "dependencies": { "@noble/ciphers": "^2.4.0", "@noble/curves": "^2.4.0", @@ -40668,16 +40668,16 @@ }, "packages/server": { "name": "@getpaseo/server", - "version": "0.14.0-beta.2", + "version": "0.14.0", "dependencies": { "@agentclientprotocol/sdk": "^0.17.1", "@anthropic-ai/claude-agent-sdk": "0.3.246", "@anthropic-ai/sdk": "^0.104.2", - "@getpaseo/client": "0.14.0-beta.2", - "@getpaseo/highlight": "0.14.0-beta.2", - "@getpaseo/plugin": "0.14.0-beta.2", - "@getpaseo/protocol": "0.14.0-beta.2", - "@getpaseo/relay": "0.14.0-beta.2", + "@getpaseo/client": "0.14.0", + "@getpaseo/highlight": "0.14.0", + "@getpaseo/plugin": "0.14.0", + "@getpaseo/protocol": "0.14.0", + "@getpaseo/relay": "0.14.0", "@isaacs/ttlcache": "^2.1.4", "@modelcontextprotocol/sdk": "1.29.0", "@opencode-ai/sdk": "1.14.46", @@ -41598,7 +41598,7 @@ }, "packages/website": { "name": "@getpaseo/website", - "version": "0.14.0-beta.2", + "version": "0.14.0", "dependencies": { "@cloudflare/vite-plugin": "^1.29.1", "@cloudflare/workers-types": "^4.20260317.1", @@ -43208,7 +43208,7 @@ }, "plugins": { "name": "@getpaseo/builtin-plugins", - "version": "0.14.0-beta.2", + "version": "0.14.0", "dependencies": { "@getpaseo/plugin": "*", "zod": "^4.4.3" diff --git a/package.json b/package.json index 0065786340..938497a362 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "paseo", - "version": "0.14.0-beta.2", + "version": "0.14.0", "private": true, "description": "Paseo: voice-controlled development environment for local AI coding agents", "keywords": [ diff --git a/packages/app/package.json b/packages/app/package.json index 1a348e819f..42294ae6a1 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/app", - "version": "0.14.0-beta.2", + "version": "0.14.0", "private": true, "main": "index.ts", "scripts": { diff --git a/packages/cli/package.json b/packages/cli/package.json index 0d0d5cb61d..45113dd1bc 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/cli", - "version": "0.14.0-beta.2", + "version": "0.14.0", "description": "Paseo CLI - control your AI coding agents from the command line", "bin": { "paseo": "bin/paseo" @@ -28,9 +28,9 @@ }, "dependencies": { "@clack/prompts": "^1.0.0", - "@getpaseo/client": "0.14.0-beta.2", - "@getpaseo/protocol": "0.14.0-beta.2", - "@getpaseo/server": "0.14.0-beta.2", + "@getpaseo/client": "0.14.0", + "@getpaseo/protocol": "0.14.0", + "@getpaseo/server": "0.14.0", "chalk": "^5.3.0", "commander": "^12.0.0", "mime-types": "^2.1.35", diff --git a/packages/client/package.json b/packages/client/package.json index e15265c8f1..6e10c76089 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/client", - "version": "0.14.0-beta.2", + "version": "0.14.0", "description": "Paseo client SDK package", "files": [ "dist", @@ -47,8 +47,8 @@ "test": "vitest run" }, "dependencies": { - "@getpaseo/protocol": "0.14.0-beta.2", - "@getpaseo/relay": "0.14.0-beta.2", + "@getpaseo/protocol": "0.14.0", + "@getpaseo/relay": "0.14.0", "ws": "^8.20.0", "zod": "^4.4.3" }, diff --git a/packages/desktop/package.json b/packages/desktop/package.json index 8a77957fba..074e79b64d 100644 --- a/packages/desktop/package.json +++ b/packages/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/desktop", - "version": "0.14.0-beta.2", + "version": "0.14.0", "private": true, "description": "Paseo desktop app (Electron wrapper)", "homepage": "https://paseo.sh", diff --git a/packages/expo-two-way-audio/package.json b/packages/expo-two-way-audio/package.json index 016a28132e..aa86be129b 100644 --- a/packages/expo-two-way-audio/package.json +++ b/packages/expo-two-way-audio/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/expo-two-way-audio", - "version": "0.14.0-beta.2", + "version": "0.14.0", "description": "Native module for two way audio streaming", "keywords": [ "ExpoTwoWayAudio", diff --git a/packages/highlight/package.json b/packages/highlight/package.json index da80a7421c..6b1d924e05 100644 --- a/packages/highlight/package.json +++ b/packages/highlight/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/highlight", - "version": "0.14.0-beta.2", + "version": "0.14.0", "files": [ "dist", "!dist/**/*.map", diff --git a/packages/plugin/package.json b/packages/plugin/package.json index 5fa8449b2b..32cb48e026 100644 --- a/packages/plugin/package.json +++ b/packages/plugin/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/plugin", - "version": "0.14.0-beta.2", + "version": "0.14.0", "description": "Paseo plugin SDK package", "files": [ "dist", @@ -77,8 +77,8 @@ "use-sync-external-store": "^1.6.0" }, "devDependencies": { - "@getpaseo/client": "0.14.0-beta.2", - "@getpaseo/protocol": "0.14.0-beta.2", + "@getpaseo/client": "0.14.0", + "@getpaseo/protocol": "0.14.0", "@types/node": "^20.9.0", "@types/react": "~19.2.0", "react": "19.2.3", @@ -88,8 +88,8 @@ "zod": "^4.4.3" }, "peerDependencies": { - "@getpaseo/client": "0.14.0-beta.2", - "@getpaseo/protocol": "0.14.0-beta.2", + "@getpaseo/client": "0.14.0", + "@getpaseo/protocol": "0.14.0", "react": ">=19.1.0 <20", "react-native": ">=0.81.5", "zod": "^4.4.3" diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 8829e183a3..21d500fd4f 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/protocol", - "version": "0.14.0-beta.2", + "version": "0.14.0", "description": "Paseo shared protocol schemas and wire types", "files": [ "dist", diff --git a/packages/relay/package.json b/packages/relay/package.json index 5daed2afce..ec1deebff7 100644 --- a/packages/relay/package.json +++ b/packages/relay/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/relay", - "version": "0.14.0-beta.2", + "version": "0.14.0", "description": "Paseo relay for bridging daemon and client connections", "files": [ "dist", diff --git a/packages/server/package.json b/packages/server/package.json index 7f8a6c074a..90e2ccace8 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/server", - "version": "0.14.0-beta.2", + "version": "0.14.0", "description": "Paseo backend server", "files": [ "dist/server", @@ -107,11 +107,11 @@ "@agentclientprotocol/sdk": "^0.17.1", "@anthropic-ai/claude-agent-sdk": "0.3.246", "@anthropic-ai/sdk": "^0.104.2", - "@getpaseo/client": "0.14.0-beta.2", - "@getpaseo/highlight": "0.14.0-beta.2", - "@getpaseo/plugin": "0.14.0-beta.2", - "@getpaseo/protocol": "0.14.0-beta.2", - "@getpaseo/relay": "0.14.0-beta.2", + "@getpaseo/client": "0.14.0", + "@getpaseo/highlight": "0.14.0", + "@getpaseo/plugin": "0.14.0", + "@getpaseo/protocol": "0.14.0", + "@getpaseo/relay": "0.14.0", "@isaacs/ttlcache": "^2.1.4", "@modelcontextprotocol/sdk": "1.29.0", "@opencode-ai/sdk": "1.14.46", diff --git a/packages/website/package.json b/packages/website/package.json index 9b115fbfe7..7e0635c2e9 100644 --- a/packages/website/package.json +++ b/packages/website/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/website", - "version": "0.14.0-beta.2", + "version": "0.14.0", "private": true, "type": "module", "scripts": { diff --git a/plugins/package.json b/plugins/package.json index 9a816eacbd..aa09dfb568 100644 --- a/plugins/package.json +++ b/plugins/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/builtin-plugins", - "version": "0.14.0-beta.2", + "version": "0.14.0", "private": true, "type": "module", "scripts": { From fb69bf331420361edc34287167390f41c878a467 Mon Sep 17 00:00:00 2001 From: "paseo-ai[bot]" <266920839+paseo-ai[bot]@users.noreply.github.com> Date: Thu, 29 Oct 2026 08:49:01 +0000 Subject: [PATCH 109/173] fix: update lockfile signatures and Nix hash [skip ci] --- nix/npm-deps.hash | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nix/npm-deps.hash b/nix/npm-deps.hash index eae1803a42..a6061301b1 100644 --- a/nix/npm-deps.hash +++ b/nix/npm-deps.hash @@ -1 +1 @@ -sha256-AmMp/4ugSUKXTL6H0oJaGJMztVGiYCPXeWteQaaaguw= +sha256-6C4Rjh0mRVrC9akBVGK0NZaCaLJhwKObT7HrgPmcvyw= From 75f58c4fe7d3180e3ff74e10480bf0dc1111f37d Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Thu, 29 Oct 2026 15:57:08 +0700 Subject: [PATCH 110/173] fix(release): upload only en-US screenshots to Google Play (#8195) supply uploads every locale folder under fastlane/metadata/android in one edit. Play rejects the F-Droid-only ja locale, which failed the whole edit in the 0.14.0 release ("ja - Invalid request"), so no screenshots were replaced. Stage only the en-US images, add a standalone workflow to rerun the upload for the current release, and document the App Store associatedErrors gotcha. --- docs/release.md | 3 ++- .../workflows/upload-android-screenshots.yml | 27 +++++++++++++++++++ packages/app/fastlane/Fastfile | 18 ++++++++++++- 3 files changed, 46 insertions(+), 2 deletions(-) create mode 100644 packages/app/.eas/workflows/upload-android-screenshots.yml diff --git a/docs/release.md b/docs/release.md index 07c6e1b16f..328c189f7b 100644 --- a/docs/release.md +++ b/docs/release.md @@ -380,7 +380,8 @@ There is no mobile-release workflow under `.github/workflows`. The EAS GitHub ap Each stable release publishes the screenshots committed under `assets/store-screenshots/output/` (see [its README](../assets/store-screenshots/README.md) for how they are made). To change the store screenshots, re-render and commit them before you tag. - **App Store:** `submit_review` uploads `output/apple/` and `output/apple-ipad/` to the version it submits, replacing that version's `en-US` screenshots. Apple ties screenshots to an app version, so a version that is already live keeps the ones it shipped with. `Resubmit iOS for App Store review` uploads them again. -- **Google Play:** `upload_android_screenshots` runs `fastlane android upload_screenshots` after `submit_android`. It replaces only the phone and 10-inch tablet screenshots, never the listing text or changelogs, and skips images whose checksum already matches. + - When `submit_review` fails with `appStoreVersions … is not in valid state`, the reason is in the API error's `meta.associatedErrors`, which fastlane does not print. Read it with a `POST /v1/reviewSubmissionItems` against the version. A required age-rating question that Apple added, such as `socialMedia`, fails this way; answer it under App Information > Age Rating in App Store Connect, then resubmit. +- **Google Play:** `upload_android_screenshots` runs `fastlane android upload_screenshots` after `submit_android`. It replaces only the `en-US` phone and 10-inch tablet screenshots, never the listing text or changelogs, and skips images whose checksum already matches. The lane stages only `en-US`: supply uploads every locale folder in one edit, and Play rejects F-Droid locales such as `ja`, which fails the whole edit. `Upload Google Play screenshots` reruns the step for the current release without a rebuild. - **F-Droid:** reads the same files as Google Play. `fastlane/metadata/android/en-US/images/phoneScreenshots/` and `tenInchScreenshots/` hold symlinks to the Google renders. `render.mjs` rewrites them on every render, so added or renamed panels reach Google Play and F-Droid as well. Fastlane cannot use the Play key Expo stores for `eas submit`. The Play lane reads its own copy of the same service-account key from the `GOOGLE_PLAY_JSON_KEY` file secret in the EAS `production` environment, and that service account needs the Play Console permission **Manage store presence**. diff --git a/packages/app/.eas/workflows/upload-android-screenshots.yml b/packages/app/.eas/workflows/upload-android-screenshots.yml new file mode 100644 index 0000000000..dbd2fdddca --- /dev/null +++ b/packages/app/.eas/workflows/upload-android-screenshots.yml @@ -0,0 +1,27 @@ +name: Upload Google Play screenshots + +# Standalone re-trigger for the release workflow's Google Play screenshot step. +# Replaces the en-US phone and tablet screenshots with the committed renders, +# without rebuilding or resubmitting the app. + +on: + workflow_dispatch: + inputs: + android_version_code: + type: string + required: false + description: "versionCode of the production release to attach the change to, e.g. 14000. Leave empty when the production track has a single release." + +jobs: + upload_android_screenshots: + name: Upload Google Play screenshots + environment: production + runs_on: macos-medium + steps: + - uses: eas/checkout + - name: Install fastlane + run: bundle install + - name: Upload screenshots + run: | + export ANDROID_VERSION_CODE="${{ inputs.android_version_code }}" + bundle exec fastlane android upload_screenshots diff --git a/packages/app/fastlane/Fastfile b/packages/app/fastlane/Fastfile index 065ca48b7f..f9f11a0e9a 100644 --- a/packages/app/fastlane/Fastfile +++ b/packages/app/fastlane/Fastfile @@ -26,6 +26,22 @@ def stage_app_store_screenshots root end +# Google Play only has en-US screenshots, and some F-Droid locales in +# ANDROID_METADATA are not Play languages (Play rejects "ja"). supply uploads +# every locale folder in one edit, so give it only the en-US images. +def stage_google_play_screenshots + root = Dir.mktmpdir("google-play-screenshots") + images = File.join(ANDROID_METADATA, "en-US/images") + %w[phoneScreenshots tenInchScreenshots].each do |kind| + target = File.join(root, "en-US/images", kind) + FileUtils.mkdir_p(target) + Dir.glob(File.join(images, kind, "*.png")).sort.each do |file| + FileUtils.cp(File.realpath(file), File.join(target, File.basename(file))) + end + end + root +end + platform :ios do desc "Submit the latest TestFlight build to App Store Review" lane :submit_review do @@ -132,7 +148,7 @@ platform :android do supply( package_name: APP_IDENTIFIER, json_key: ENV.fetch("GOOGLE_PLAY_JSON_KEY"), - metadata_path: ANDROID_METADATA, + metadata_path: stage_google_play_screenshots, version_code: version_code.empty? ? nil : version_code.to_i, skip_upload_apk: true, skip_upload_aab: true, From c4b4516890cc8d5c78911a314cfb2c1257a26db8 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:10:25 +0000 Subject: [PATCH 111/173] Keep split dividers under the pointer across mouse and gesture input (#6011) * fix(app): keep split dividers under the mouse before Explorer is first opened The main row only left the Explorer pane out once the Explorer had been shown, because the split container read the registered pane id directly. Before that, the hidden Explorer stayed in the row with its share of the sizes, and every divider drag moved about 1.28 times the mouse distance. Resolve the pane the same way the workspace screen does, so the default Explorer pane is left out from the start. Closes #5998 * fix(app): keep split dividers under gesture input Measure the gesture from its initial press so activation does not discard the movement before its threshold. Cover coarse-pointer mouse and touch input alongside app-created workspaces, Explorer changes and reload. --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../browser/split-pane-drag-tracking.spec.ts | 134 ++++++++++++++++++ packages/app/src/components/resize-handle.tsx | 35 +++-- .../app/src/components/split-container.tsx | 5 +- 3 files changed, 158 insertions(+), 16 deletions(-) create mode 100644 packages/app/e2e/browser/split-pane-drag-tracking.spec.ts diff --git a/packages/app/e2e/browser/split-pane-drag-tracking.spec.ts b/packages/app/e2e/browser/split-pane-drag-tracking.spec.ts new file mode 100644 index 0000000000..90420c6fd9 --- /dev/null +++ b/packages/app/e2e/browser/split-pane-drag-tracking.spec.ts @@ -0,0 +1,134 @@ +import { expect, type Locator, type Page } from "@playwright/test"; +import { test } from "../support/fixtures"; +import { runWorkspaceActionFromCommandCenter } from "../support/helpers/command-center-workspace-actions"; +import { createCreationScenario } from "../support/helpers/creation"; +import { clickNewChat, gotoWorkspace } from "../support/helpers/launcher"; +import { seedWorkspace } from "../support/helpers/seed-client"; +import { waitForWorkspaceTabsVisible } from "../support/helpers/workspace-tabs"; + +const DRAG_DISTANCE = -40; +const TOLERANCE_PX = 2; + +function splitDividers(page: Page): Locator { + return page.getByTestId("workspace-split-resize-handle").filter({ visible: true }); +} + +async function dividerX(divider: Locator): Promise { + const box = await divider.boundingBox(); + if (!box) throw new Error("Divider has no bounding box"); + return box.x; +} + +async function dragDivider(divider: Locator, deltaX: number): Promise { + const page = divider.page(); + const box = await divider.boundingBox(); + if (!box) throw new Error("Divider has no bounding box"); + const x = box.x + box.width / 2; + const y = box.y + box.height / 2; + await page.mouse.move(x, y); + await page.mouse.down(); + await page.mouse.move(x + deltaX, y, { steps: 8 }); + await page.mouse.up(); +} + +async function dragDividerWithTouch(divider: Locator, deltaX: number): Promise { + const page = divider.page(); + const box = await divider.boundingBox(); + if (!box) throw new Error("Divider has no bounding box"); + const x = box.x + box.width / 2; + const y = box.y + box.height / 2; + const input = await page.context().newCDPSession(page); + try { + await input.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [{ x, y }] }); + for (let step = 1; step <= 8; step++) { + await input.send("Input.dispatchTouchEvent", { + type: "touchMove", + touchPoints: [{ x: x + (deltaX * step) / 8, y }], + }); + } + await input.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] }); + } finally { + await input.detach(); + } +} + +async function splitIntoFourPanes(page: Page): Promise { + for (const expectedDividers of [1, 2, 3]) { + await runWorkspaceActionFromCommandCenter(page, "Split pane right"); + await expect(splitDividers(page)).toHaveCount(expectedDividers); + } +} + +async function expectDividersTrackPointer( + page: Page, + distance = DRAG_DISTANCE, + drag = dragDivider, +): Promise { + for (const index of [0, 1, 2]) { + const divider = splitDividers(page).nth(index); + const before = await dividerX(divider); + await drag(divider, distance); + await expect + .poll(async () => Math.abs((await dividerX(divider)) - before - distance), { + message: `divider ${index + 1} should stay under the pointer`, + }) + .toBeLessThanOrEqual(TOLERANCE_PX); + } +} + +for (const hasTouch of [false, true]) { + test.describe(`Split pane drag tracking (${hasTouch ? "coarse" : "fine"} pointer)`, () => { + test.use({ hasTouch }); + + test("a divider moves as far as the pointer in the main row", async ({ page }) => { + await page.setViewportSize({ width: 1600, height: 900 }); + const workspace = await seedWorkspace({ repoPrefix: "split-drag-tracking-" }); + try { + await gotoWorkspace(page, workspace.workspaceId); + await waitForWorkspaceTabsVisible(page); + await clickNewChat(page); + await splitIntoFourPanes(page); + await expectDividersTrackPointer( + page, + DRAG_DISTANCE, + hasTouch ? dragDividerWithTouch : dragDivider, + ); + } finally { + await workspace.cleanup(); + } + }); + + test("dividers track the pointer after app creation, Explorer changes and reload", async ({ + page, + }) => { + await page.setViewportSize({ width: 1600, height: 900 }); + const creation = await createCreationScenario(page); + try { + await creation.openWorkspaceForm("local"); + await creation.submitPrompt("Reply briefly.", "Create"); + await creation.expectAssistantReply(); + await waitForWorkspaceTabsVisible(page); + await splitIntoFourPanes(page); + await expectDividersTrackPointer(page); + await page + .getByTestId("workspace-explorer-toggle") + .filter({ visible: true }) + .first() + .click(); + await expect(page.getByTestId("workspace-explorer-sidebar")).toBeVisible(); + await expectDividersTrackPointer(page, -DRAG_DISTANCE); + await page + .getByTestId("workspace-explorer-toggle") + .filter({ visible: true }) + .first() + .click(); + await expect(page.getByTestId("workspace-explorer-sidebar")).not.toBeVisible(); + await page.reload(); + await expect(splitDividers(page)).toHaveCount(3); + await expectDividersTrackPointer(page); + } finally { + await creation.cleanup(); + } + }); + }); +} diff --git a/packages/app/src/components/resize-handle.tsx b/packages/app/src/components/resize-handle.tsx index 6576728384..c3930688c2 100644 --- a/packages/app/src/components/resize-handle.tsx +++ b/packages/app/src/components/resize-handle.tsx @@ -49,7 +49,7 @@ export function ResizeHandle({ const { theme } = useUnistyles(); const finePointer = useHasFinePointer(); const pointerStatesRef = useRef(new Map()); - const touchDragRef = useRef(null); + const touchStateRef = useRef(null); const cursorBeforeDragRef = useRef(null); const hoverTimerRef = useRef | null>(null); const [active, setActive] = useState(false); @@ -151,23 +151,30 @@ export function ResizeHandle({ const touchGesture = useMemo(() => { const gesture = Gesture.Pan() .runOnJS(true) - .onBegin(() => setDragging(true)) - .onStart(() => { - touchDragRef.current = startResizeHandleDrag({ - sizes, - index, - preview: (nextSizes) => onPreviewResizeSplit(groupId, nextSizes), - commit: (nextSizes) => onResizeSplit(groupId, nextSizes), - }); + .onBegin((event) => { + setDragging(true); + touchStateRef.current = { + containerSize, + pointerStart: direction === "horizontal" ? event.absoluteX : event.absoluteY, + drag: startResizeHandleDrag({ + sizes, + index, + preview: (nextSizes) => onPreviewResizeSplit(groupId, nextSizes), + commit: (nextSizes) => onResizeSplit(groupId, nextSizes), + }), + }; }) .onUpdate((event) => { - if (containerSize <= 0) return; - const translation = direction === "horizontal" ? event.translationX : event.translationY; - touchDragRef.current?.move(translation / containerSize); + const state = touchStateRef.current; + if (!state || state.containerSize <= 0) return; + // Gesture Handler resets web translation when the pan activates. Measure from + // the initial press so the activation distance is included on every platform. + const pointerCurrent = direction === "horizontal" ? event.absoluteX : event.absoluteY; + state.drag.move((pointerCurrent - state.pointerStart) / state.containerSize); }) - .onEnd(() => touchDragRef.current?.finish()) + .onEnd(() => touchStateRef.current?.drag.finish()) .onFinalize(() => { - touchDragRef.current = null; + touchStateRef.current = null; setDragging(false); }); diff --git a/packages/app/src/components/split-container.tsx b/packages/app/src/components/split-container.tsx index 660b5f4e6b..278317243a 100644 --- a/packages/app/src/components/split-container.tsx +++ b/packages/app/src/components/split-container.tsx @@ -48,6 +48,7 @@ import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs- import { collectAllPanes, createDefaultLayout, + selectExplorerSidebarPaneId, useWorkspaceLayoutStore, type SplitNode, type SplitPane, @@ -183,8 +184,8 @@ export function SplitContainer({ } | null>(null); const maximizedPaneId = maximizedPane?.workspaceKey === workspaceKey ? maximizedPane.paneId : null; - const explorerSidebarPaneId = useWorkspaceLayoutStore( - (state) => state.explorerSidebarPaneIdByWorkspace[workspaceKey] ?? null, + const explorerSidebarPaneId = useWorkspaceLayoutStore((state) => + selectExplorerSidebarPaneId(state, workspaceKey), ); const mainRoot = useMemo( From ac6e4e9f96121b8954594ce3f166551a3f04649a Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Thu, 29 Oct 2026 16:56:12 +0700 Subject: [PATCH 112/173] Fix flaky 64 MiB image materialization test on Windows CI (#8198) The responsiveness test timed wall-clock gaps between 1 ms ticks, which reached 50.35 ms on the shared Windows runner for the same code. It now measures main-thread CPU time between ticks and still fails when the payload decodes in one chunk. --- .../agent/providers/provider-image-output.test.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/packages/server/src/server/agent/providers/provider-image-output.test.ts b/packages/server/src/server/agent/providers/provider-image-output.test.ts index 0606c59de3..3388edb6d5 100644 --- a/packages/server/src/server/agent/providers/provider-image-output.test.ts +++ b/packages/server/src/server/agent/providers/provider-image-output.test.ts @@ -184,17 +184,24 @@ test("repeated content is reused without rewriting the attachment", async () => test("64 MiB materialization leaves the event loop responsive and preserves bytes", async () => { const bytes = Buffer.alloc(64 * 1024 * 1024, 37); const data = bytes.toString("base64"); - let previous = performance.now(); + // Main-thread CPU time between ticks bounds the decode and hash work done on the loop; + // wall-clock gaps on shared CI runners also count preemption and timer granularity. + // File writes stay on fs/promises, so they never block the loop. + const threadCpuMs = () => { + const { user, system } = process.threadCpuUsage(); + return (user + system) / 1000; + }; + let previous = threadCpuMs(); let longest = 0; const probe = setInterval(() => { - const now = performance.now(); + const now = threadCpuMs(); longest = Math.max(longest, now - previous); previous = now; }, 1); try { const result = await materializeProviderImage({ data, mimeType: "image/png" }); await new Promise((resolve) => setTimeout(resolve, 5)); - console.log(`64 MiB attachment longest loop gap: ${longest.toFixed(2)} ms`); + console.log(`64 MiB attachment longest blocking stretch: ${longest.toFixed(2)} ms CPU`); expect(longest).toBeLessThan(50); expect(readFileSync(result.path).equals(bytes)).toBe(true); rmSync(result.path, { force: true }); From 946b6e58fd58897036f8591a84ab0061cc5dcfee Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Thu, 29 Oct 2026 11:16:48 +0000 Subject: [PATCH 113/173] Keep transcript colors in sync after a hidden theme change (#8199) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(app): preserve adaptive theme events while hidden Read the current scheme through fresh matchMedia lists so hidden runtime reads do not consume the pending events on listener-owned lists. Carry Dan Sabin's fix from #7172 into the current combined Unistyles patch, and cover both transition directions with a real Electron regression in the existing desktop browser suite. Co-authored-by: Dan Sabin * test(desktop): run adaptive theme regression on Linux Electron retains --no-sandbox in argv, so the positional lookup used the script filename as the artifact directory. Read the final argument so the same real Electron regression exercises Linux as well as macOS. Co-authored-by: Nurşat Bülbül <85260051+Nurshot@users.noreply.github.com> Co-authored-by: Dan Sabin --------- Co-authored-by: Nurshot <85260051+Nurshot@users.noreply.github.com> Co-authored-by: Dan Sabin Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- docs/unistyles.md | 8 + .../desktop/e2e/appearance-theme.electron.mjs | 158 ++++++++++++++++++ packages/desktop/e2e/browser-tabs.e2e.mjs | 9 +- patches/react-native-unistyles+3.2.4.patch | 71 ++++++++ scripts/postinstall-patches.mjs | 1 + 5 files changed, 246 insertions(+), 1 deletion(-) create mode 100644 packages/desktop/e2e/appearance-theme.electron.mjs diff --git a/docs/unistyles.md b/docs/unistyles.md index 3daae333df..6be82f70b0 100644 --- a/docs/unistyles.md +++ b/docs/unistyles.md @@ -358,6 +358,14 @@ export to `src`, but browser and Electron Metro resolve its `browser` export to `lib/module`; CommonJS consumers use `lib/commonjs`. A source-only patch leaves Electron running the old code. +The adaptive-theme patch keeps `colorScheme` reads off the media-query lists +owned by Unistyles' change listeners. Chromium defers their events while a window +is hidden; reading `matches` on those same lists can consume the pending change. +CSS variables then follow the OS theme while `withUnistyles` props retain the old +colors. Keep this patch until upstream reads the scheme through separate lists. +The desktop browser E2E checks both transition directions in an isolated Electron +process, because Playwright's focus emulation prevents real hidden-page behavior. + Register every dependency patch in `scripts/postinstall-patches.mjs`. A file in `patches/` is inert unless that script knows which installed package activates it. diff --git a/packages/desktop/e2e/appearance-theme.electron.mjs b/packages/desktop/e2e/appearance-theme.electron.mjs new file mode 100644 index 0000000000..426c50f355 --- /dev/null +++ b/packages/desktop/e2e/appearance-theme.electron.mjs @@ -0,0 +1,158 @@ +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import electronPath from "electron"; +import { build } from "esbuild"; + +export async function runAdaptiveThemeRegression(artifactDir) { + const { outputFiles } = await build({ + stdin: { + resolveDir: fileURLToPath(new URL("../../app", import.meta.url)), + contents: ` + import { createElement } from "react"; + import { createRoot } from "react-dom/client"; + import { StyleSheet, UnistylesRuntime, withUnistyles } from "react-native-unistyles"; + StyleSheet.configure({ + themes: { + dark: { foreground: "#fafafa", background: "#181b1a" }, + light: { foreground: "#1a1a1e", background: "#ffffff" }, + }, + settings: { adaptiveThemes: true }, + }); + const Message = withUnistyles(({ color }) => + createElement("p", { style: { color } }, "Theme-reactive message")); + createRoot(document.getElementById("root")).render(createElement(Message, { + style: { margin: 0 }, + uniProps: theme => ({ color: theme.foreground }), + })); + window.readThemeForTest = () => UnistylesRuntime.themeName; + `, + }, + bundle: true, + write: false, + format: "iife", + platform: "browser", + alias: { "react-native": "react-native-web" }, + define: { __DEV__: "false" }, + resolveExtensions: [".web.js", ".js", ".json"], + }); + const directory = await fs.mkdtemp(path.join(os.tmpdir(), "paseo-adaptive-theme-")); + try { + await fs.writeFile(path.join(directory, "renderer.js"), outputFiles[0].text); + await fs.writeFile(path.join(directory, "main.cjs"), `(${electronRegression.toString()})()`); + // A separate process avoids Playwright's focus emulation, which keeps hidden pages visible. + const env = { ...process.env }; + delete env.ELECTRON_RUN_AS_NODE; + const args = [ + ...(process.platform === "linux" ? ["--no-sandbox"] : []), + path.join(directory, "main.cjs"), + artifactDir, + ]; + const command = process.platform === "linux" ? "xvfb-run" : electronPath; + const commandArgs = + process.platform === "linux" + ? ["-a", "--server-args=-screen 0 1280x800x24", electronPath, ...args] + : args; + await promisify(execFile)(command, commandArgs, { + env, + timeout: 30_000, + }); + return JSON.parse(await fs.readFile(path.join(artifactDir, "adaptive-theme.json"), "utf8")); + } finally { + await fs.rm(directory, { recursive: true, force: true }); + } +} + +async function electronRegression() { + const { app, BrowserWindow, nativeTheme } = require("electron"); + const assert = require("node:assert/strict"); + const files = require("node:fs"); + const paths = require("node:path"); + const { setTimeout: delay } = require("node:timers/promises"); + app.setPath("userData", paths.join(__dirname, "profile")); + app.on("window-all-closed", () => {}); + // Electron keeps Linux's --no-sandbox in argv; the artifact directory is always last. + const artifactDir = process.argv.at(-1); + let window; + const observations = []; + const colors = { + dark: { foreground: "rgb(250, 250, 250)", background: "rgb(24, 27, 26)" }, + light: { foreground: "rgb(26, 26, 30)", background: "rgb(255, 255, 255)" }, + }; + async function read(expression) { + return window.webContents.executeJavaScript(expression); + } + async function expectValue(expression, expected) { + let actual; + for (let attempt = 0; attempt < 50; attempt++) { + actual = await read(expression); + if (actual === expected) return; + await delay(50); + } + assert.equal(actual, expected, expression); + } + try { + await app.whenReady(); + if (process.platform === "darwin") { + app.setActivationPolicy("accessory"); + app.dock.hide(); + } + for (const [from, to] of [ + ["dark", "light"], + ["light", "dark"], + ]) { + nativeTheme.themeSource = from; + window = new BrowserWindow({ width: 600, height: 200, show: false, skipTaskbar: true }); + await window.loadURL( + "data:text/html," + + encodeURIComponent(` + +
`), + ); + await read(files.readFileSync(paths.join(__dirname, "renderer.js"), "utf8")); + window.showInactive(); + const foreground = + "document.querySelector('p') && getComputedStyle(document.querySelector('p')).color"; + const background = "getComputedStyle(document.body).backgroundColor"; + await expectValue(foreground, colors[from].foreground); + await expectValue(background, colors[from].background); + window.hide(); + await expectValue("document.visibilityState", "hidden"); + nativeTheme.themeSource = to; + await expectValue(`matchMedia('(prefers-color-scheme: ${to})').matches`, true); + // Reading the public runtime while hidden must not consume the pending theme notification. + assert.equal(await read("window.readThemeForTest()"), to); + window.showInactive(); + await expectValue("document.visibilityState", "visible"); + await expectValue(background, colors[to].background); + try { + await expectValue(foreground, colors[to].foreground); + } finally { + files.writeFileSync( + paths.join(artifactDir, `theme-${from}-to-${to}.png`), + (await window.webContents.capturePage()).toPNG(), + ); + } + observations.push({ + from, + to, + foreground: await read(foreground), + background: await read(background), + }); + window.destroy(); + window = undefined; + } + files.writeFileSync( + paths.join(artifactDir, "adaptive-theme.json"), + JSON.stringify(observations, null, 2), + ); + app.exit(0); + } catch (error) { + console.error(error); + window?.destroy(); + app.exit(1); + } +} diff --git a/packages/desktop/e2e/browser-tabs.e2e.mjs b/packages/desktop/e2e/browser-tabs.e2e.mjs index 78d2fa978e..28afbab94f 100644 --- a/packages/desktop/e2e/browser-tabs.e2e.mjs +++ b/packages/desktop/e2e/browser-tabs.e2e.mjs @@ -14,6 +14,7 @@ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/ import { chromium } from "playwright"; import { hideDeveloperToasts } from "../../app/e2e/support/developer-ui.mjs"; import { runAppearanceFontSizeRegression } from "./appearance-font-size.electron.mjs"; +import { runAdaptiveThemeRegression } from "./appearance-theme.electron.mjs"; import { runSettingsScrollRegression } from "./settings-scroll.electron.mjs"; import { runSettingsMemoryRegression } from "./settings-memory.electron.mjs"; @@ -1241,6 +1242,7 @@ async function main() { return; } + const adaptiveTheme = await runAdaptiveThemeRegression(artifactDir); await runAppearanceFontSizeRegression(page); const callerAgentId = await createCallerAgent(daemonPort); @@ -1265,7 +1267,12 @@ async function main() { artifactDir, }); const pluginLinks = await checkPluginLinks(); - writeJson(path.join(artifactDir, "result.json"), { ...report, settingsMemory, pluginLinks }); + writeJson(path.join(artifactDir, "result.json"), { + ...report, + settingsMemory, + pluginLinks, + adaptiveTheme, + }); console.log( `Browser desktop browser E2E passed: WebContents ${report.originalWebContentsId} remained ${report.finalWebContentsId}; viewport, inactive capture, focus continuity, list, snapshot, click, local-page selectors passed.`, ); diff --git a/patches/react-native-unistyles+3.2.4.patch b/patches/react-native-unistyles+3.2.4.patch index 7f40053f19..1930a4db84 100644 --- a/patches/react-native-unistyles+3.2.4.patch +++ b/patches/react-native-unistyles+3.2.4.patch @@ -486,3 +486,74 @@ diff --git a/node_modules/react-native-unistyles/lib/commonjs/core/withUnistyles ...(narrowedProps.style ? { style: styleSecrets.styles } : {}), +diff --git a/node_modules/react-native-unistyles/lib/commonjs/web/runtime.js b/node_modules/react-native-unistyles/lib/commonjs/web/runtime.js +index 305fa49..5957aa5 100644 +--- a/node_modules/react-native-unistyles/lib/commonjs/web/runtime.js ++++ b/node_modules/react-native-unistyles/lib/commonjs/web/runtime.js +@@ -35,10 +35,17 @@ class UnistylesRuntime { + return this.darkMedia; + } + get colorScheme() { ++ // Read the scheme through fresh lists, never through lightMedia/darkMedia. Chromium defers ++ // MediaQueryList change events while the document is hidden and drops the pending event ++ // of any list whose `matches` was read before the document became visible again, which ++ // would silence the adaptive-theme listeners registered on those two lists. ++ if ((0, _utils.isServer)()) { ++ return _types.ColorScheme.Unspecified; ++ } + switch (true) { +- case this.getLightMedia()?.matches: ++ case window.matchMedia('(prefers-color-scheme: light)').matches: + return _types.ColorScheme.Light; +- case this.getDarkMedia()?.matches: ++ case window.matchMedia('(prefers-color-scheme: dark)').matches: + return _types.ColorScheme.Dark; + default: + return _types.ColorScheme.Unspecified; +diff --git a/node_modules/react-native-unistyles/lib/module/web/runtime.js b/node_modules/react-native-unistyles/lib/module/web/runtime.js +index 7f13a06..c487bee 100644 +--- a/node_modules/react-native-unistyles/lib/module/web/runtime.js ++++ b/node_modules/react-native-unistyles/lib/module/web/runtime.js +@@ -31,10 +31,17 @@ export class UnistylesRuntime { + return this.darkMedia; + } + get colorScheme() { ++ // Read the scheme through fresh lists, never through lightMedia/darkMedia. Chromium defers ++ // MediaQueryList change events while the document is hidden and drops the pending event ++ // of any list whose `matches` was read before the document became visible again, which ++ // would silence the adaptive-theme listeners registered on those two lists. ++ if (isServer()) { ++ return ColorScheme.Unspecified; ++ } + switch (true) { +- case this.getLightMedia()?.matches: ++ case window.matchMedia('(prefers-color-scheme: light)').matches: + return ColorScheme.Light; +- case this.getDarkMedia()?.matches: ++ case window.matchMedia('(prefers-color-scheme: dark)').matches: + return ColorScheme.Dark; + default: + return ColorScheme.Unspecified; +diff --git a/node_modules/react-native-unistyles/src/web/runtime.ts b/node_modules/react-native-unistyles/src/web/runtime.ts +index a16dac0..6519858 100644 +--- a/node_modules/react-native-unistyles/src/web/runtime.ts ++++ b/node_modules/react-native-unistyles/src/web/runtime.ts +@@ -41,8 +41,16 @@ export class UnistylesRuntime { + get colorScheme() { ++ // Read the scheme through fresh lists, never through lightMedia/darkMedia. Chromium defers ++ // MediaQueryList change events while the document is hidden and drops the pending event ++ // of any list whose `matches` was read before the document became visible again, which ++ // would silence the adaptive-theme listeners registered on those two lists. ++ if (isServer()) { ++ return ColorScheme.Unspecified ++ } ++ + switch (true) { +- case this.getLightMedia()?.matches: ++ case window.matchMedia('(prefers-color-scheme: light)').matches: + return ColorScheme.Light +- case this.getDarkMedia()?.matches: ++ case window.matchMedia('(prefers-color-scheme: dark)').matches: + return ColorScheme.Dark + default: + return ColorScheme.Unspecified diff --git a/scripts/postinstall-patches.mjs b/scripts/postinstall-patches.mjs index 435f6331e0..eca0fde25f 100644 --- a/scripts/postinstall-patches.mjs +++ b/scripts/postinstall-patches.mjs @@ -24,6 +24,7 @@ const patchedPackages = [ }, // Registry cleanup: remove after react-native-unistyles ships // https://github.com/jpudysz/react-native-unistyles/pull/1203. + // Adaptive themes: keep until colorScheme reads no longer consume listener-owned media changes. // withUnistyles: also keep the uniProps filter until upstream consumes its control prop. { nodeModulesPath: "node_modules/react-native-unistyles", From 1aef1ec6625f2c32cbd62cfbeb02cffb43a275d2 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Thu, 29 Oct 2026 12:21:29 +0000 Subject: [PATCH 114/173] test(server): isolate timeline fetch responsiveness from runner work (#8197) * test(server): isolate timeline fetch responsiveness from runner work Measure the existing cold tail workload in a separate process after fixture collection. Keep the 50ms gate and row assertions, and reproduce unrelated callback CPU contaminating the old measurement. * test(server): keep timeline probe private and exercise overlapping CPU --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../server/agent/agent-timeline-store.test.ts | 61 ++++++++++++++----- .../test-utils/timeline-responsiveness.ts | 25 ++++++++ 2 files changed, 71 insertions(+), 15 deletions(-) create mode 100644 packages/server/src/server/agent/test-utils/timeline-responsiveness.ts diff --git a/packages/server/src/server/agent/agent-timeline-store.test.ts b/packages/server/src/server/agent/agent-timeline-store.test.ts index 4baaf89edb..5d3c836e65 100644 --- a/packages/server/src/server/agent/agent-timeline-store.test.ts +++ b/packages/server/src/server/agent/agent-timeline-store.test.ts @@ -1,4 +1,6 @@ -import { measureMainThreadWork } from "../../test-utils/main-thread-work.js"; +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { fileURLToPath } from "node:url"; import { describe, expect, it } from "vitest"; import { selectReferenceProjectedTimelinePage } from "./test-utils/timeline-page-reference.js"; import type { AgentTimelineItem } from "./agent-sdk-types.js"; @@ -251,23 +253,52 @@ it("includes transitive tool updates in a contiguous projected tail", () => { expect(tail).toMatchObject({ startSeq: 1, endSeq: 6, hasOlder: false }); }); +async function measureTimelineTail(wholeTurns: boolean) { + const fixture = fileURLToPath( + new URL("./test-utils/timeline-responsiveness.ts", import.meta.url), + ); + const { stdout, stderr } = await promisify(execFile)( + process.execPath, + ["--expose-gc", "--import", "tsx", fixture, String(wholeTurns)], + { timeout: 15_000 }, + ); + process.stderr.write(stderr); + return JSON.parse(stdout) as { + result: ReturnType; + blockingMs: number; + }; +} + +it("excludes unrelated test-runner CPU from the timeline fetch budget", async () => { + let unrelatedWork: ReturnType; + const burnCpu = () => { + const threadCpuUsage: (previous?: NodeJS.CpuUsage) => NodeJS.CpuUsage = Reflect.get( + process, + "threadCpuUsage", + ); + const start = threadCpuUsage(); + let elapsed: NodeJS.CpuUsage; + do { + elapsed = threadCpuUsage(start); + } while (elapsed.user + elapsed.system < 80_000); + unrelatedWork = setImmediate(burnCpu); + }; + unrelatedWork = setImmediate(burnCpu); + try { + const { result: tail, blockingMs } = await measureTimelineTail(false); + expect(tail.rows).toHaveLength(200); + expect(tail.startSeq).toBe(99_801); + expect(tail.endSeq).toBe(100_000); + expect(blockingMs).toBeLessThan(50); + } finally { + clearImmediate(unrelatedWork); + } +}); + it.each([false, true])( "serves tail 200 from 100,000 retained rows without stalling the loop (wholeTurns=%s)", async (wholeTurns) => { - const store = new InMemoryAgentTimelineStore(); - store.initialize("large"); - for (let index = 0; index < 100_000; index++) { - store.append("large", { type: "user_message", text: String(index) }); - } - const { result: tail, blockingMs } = await measureMainThreadWork( - `timeline tail main-thread work (wholeTurns=${wholeTurns})`, - () => { - let page = store.fetch("large", { limit: 200, wholeTurns }); - for (let repeat = 1; repeat < 8; repeat++) - page = store.fetch("large", { limit: 200, wholeTurns }); - return page; - }, - ); + const { result: tail, blockingMs } = await measureTimelineTail(wholeTurns); expect(tail.rows).toHaveLength(200); expect(tail.startSeq).toBe(99_801); expect(tail.endSeq).toBe(100_000); diff --git a/packages/server/src/server/agent/test-utils/timeline-responsiveness.ts b/packages/server/src/server/agent/test-utils/timeline-responsiveness.ts new file mode 100644 index 0000000000..bfe5ee59c4 --- /dev/null +++ b/packages/server/src/server/agent/test-utils/timeline-responsiveness.ts @@ -0,0 +1,25 @@ +import { setImmediate as nextTurn } from "node:timers/promises"; +import { measureMainThreadWork } from "../../../test-utils/main-thread-work.js"; +import { InMemoryAgentTimelineStore } from "../agent-timeline-store.js"; + +// Measure a cold fetch on its own thread, without Vitest reporting or callbacks. +const wholeTurns = process.argv[2] === "true"; +const store = new InMemoryAgentTimelineStore(); +store.initialize("large"); +for (let index = 0; index < 100_000; index++) { + store.append("large", { type: "user_message", text: String(index) }); +} +// Finish fixture allocation and collect its temporary garbage before measuring. +globalThis.gc!(); +await nextTurn(); +const measured = await measureMainThreadWork( + `timeline tail main-thread work (wholeTurns=${wholeTurns})`, + () => { + let page = store.fetch("large", { limit: 200, wholeTurns }); + for (let repeat = 1; repeat < 8; repeat++) + page = store.fetch("large", { limit: 200, wholeTurns }); + return page; + }, +); + +process.stdout.write(JSON.stringify(measured)); From 9503537041002d63d9078dced49257c8d8a903d2 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Thu, 29 Oct 2026 21:02:58 +0000 Subject: [PATCH 115/173] test(server): exclude loader activity from config responsiveness (#8218) * test(server): trace recurring config responsiveness failures * test(server): keep loader messages out of config responsiveness probes --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../src/utils/paseo-config-file.test.ts | 52 ++++++++++++++----- .../test-fixtures/config-responsiveness.ts | 16 ++++-- 2 files changed, 52 insertions(+), 16 deletions(-) diff --git a/packages/server/src/utils/paseo-config-file.test.ts b/packages/server/src/utils/paseo-config-file.test.ts index 186a5259ed..6a7e43c757 100644 --- a/packages/server/src/utils/paseo-config-file.test.ts +++ b/packages/server/src/utils/paseo-config-file.test.ts @@ -5,7 +5,8 @@ import { fileURLToPath } from "node:url"; import { writeFile, truncate, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import { build } from "esbuild"; import { isPlatform } from "../test-utils/platform.js"; import { readPaseoConfig, @@ -20,21 +21,40 @@ import { writePaseoConfigForEdit, } from "./paseo-config-file.js"; +let probeDirectory: string; +let probePath: string; + +beforeAll(async () => { + probeDirectory = mkdtempSync(join(tmpdir(), "paseo-config-probe-")); + probePath = join(probeDirectory, "config-responsiveness.mjs"); + // Compile before starting the measured process. A runtime TypeScript loader + // owns MessagePorts that the responsiveness probe otherwise charges as work. + await build({ + entryPoints: [ + fileURLToPath(new URL("./test-fixtures/config-responsiveness.ts", import.meta.url)), + ], + outfile: probePath, + bundle: true, + platform: "node", + format: "esm", + }); +}); + +afterAll(() => { + rmSync(probeDirectory, { recursive: true, force: true }); +}); + async function measureConfigRead(directory: string) { - const fixture = fileURLToPath( - new URL("./test-fixtures/config-responsiveness.ts", import.meta.url), - ); - const { stdout, stderr } = await promisify(execFile)( - process.execPath, - ["--import", "tsx", fixture, directory], - { timeout: 15_000 }, - ); + const { stdout, stderr } = await promisify(execFile)(process.execPath, [probePath, directory], { + timeout: 15_000, + }); process.stderr.write(stderr); return JSON.parse(stdout) as { result: Awaited>; blockingMs: number; filesystemRequests: number; yields: number; + workerMessages: number; }; } @@ -84,7 +104,7 @@ describe("paseo config file substrate", () => { ); }); - it("excludes unrelated test-runner CPU from the config read budget", async () => { + it("excludes test-runner and loader activity from the config read budget", async () => { await writeFile(join(tempDir, "paseo.json"), JSON.stringify({ worktree: { setup: "npm ci" } })); const unrelatedWork = new Promise((resolve) => { setImmediate(() => { @@ -100,8 +120,10 @@ describe("paseo config file substrate", () => { resolve(); }); }); - const { result, blockingMs, filesystemRequests } = await measureConfigRead(tempDir); + const { result, blockingMs, filesystemRequests, workerMessages } = + await measureConfigRead(tempDir); await unrelatedWork; + expect(workerMessages).toBe(0); expect(result).toEqual({ ok: true, config: { worktree: { setup: "npm ci" } }, @@ -119,11 +141,13 @@ describe("paseo config file substrate", () => { worktree: { setup: "npm ci" }, }; await writeFile(join(tempDir, "paseo.json"), JSON.stringify(config)); - const { result, blockingMs, filesystemRequests, yields } = await measureConfigRead(tempDir); + const { result, blockingMs, filesystemRequests, yields, workerMessages } = + await measureConfigRead(tempDir); expect(result).toEqual({ ok: true, config, revision: await statPaseoConfigPath(tempDir) }); expect(blockingMs).toBeLessThan(20); expect(filesystemRequests).toBeGreaterThan(0); expect(yields).toBeGreaterThan(0); + expect(workerMessages).toBe(0); }); it("rejects a 32MiB config with main-thread work below 20ms", async () => { @@ -131,9 +155,11 @@ describe("paseo config file substrate", () => { join(tempDir, "paseo.json"), JSON.stringify({ extra: "x".repeat(32 * 1024 * 1024) }), ); - const { result, blockingMs, filesystemRequests } = await measureConfigRead(tempDir); + const { result, blockingMs, filesystemRequests, workerMessages } = + await measureConfigRead(tempDir); expect(blockingMs).toBeLessThan(20); expect(filesystemRequests).toBeGreaterThan(0); + expect(workerMessages).toBe(0); expect(result).toEqual({ ok: false, error: { code: "invalid_project_config" } }); }); diff --git a/packages/server/src/utils/test-fixtures/config-responsiveness.ts b/packages/server/src/utils/test-fixtures/config-responsiveness.ts index 656c5a2864..9e151c805a 100644 --- a/packages/server/src/utils/test-fixtures/config-responsiveness.ts +++ b/packages/server/src/utils/test-fixtures/config-responsiveness.ts @@ -1,14 +1,24 @@ +import { createHook, executionAsyncResource } from "node:async_hooks"; +import { MessagePort } from "node:worker_threads"; import assert from "node:assert/strict"; import { setImmediate as nextTurn } from "node:timers/promises"; import { measureMainThreadWork } from "../../test-utils/main-thread-work.js"; import { readPaseoConfigForEdit } from "../paseo-config-file.js"; -// Keep Vitest transforms, reporting, and unrelated callbacks outside the measured -// thread. Read the real file once, without warming the config snapshot or schema. +// The parent bundles this fixture before launching plain Node, keeping test +// runner callbacks and runtime loader messages outside the measured thread. +// Read the real file once, without warming the config snapshot or schema. const directory = process.argv[2]; assert.ok(directory, "Config directory is required"); await nextTurn(); +let workerMessages = 0; +const activity = createHook({ + before() { + if (executionAsyncResource() instanceof MessagePort) workerMessages++; + }, +}).enable(); const measured = await measureMainThreadWork("project config main-thread work", () => readPaseoConfigForEdit(directory), ); -process.stdout.write(JSON.stringify(measured)); +activity.disable(); +process.stdout.write(JSON.stringify({ ...measured, workerMessages })); From 4351445467e2af8a103c366e353eff4d0e4b3abc Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Fri, 30 Oct 2026 00:05:34 +0000 Subject: [PATCH 116/173] Keep other windows in sync when an agent is deleted (#8248) * fix(server): broadcast agent removals across logical sessions * test(server): make subscription fixtures portable on Windows The newly enabled integration suite assumed /bin/cat and a one-second reply deadline, so Windows CI failed before completing its subscription coverage. Use the running Node executable for echo terminals and let diagnostics finish their bounded external tool probes. Co-authored-by: loganmeyer <50949542+loganmeyer@users.noreply.github.com> --------- Co-authored-by: loganmeyer <50949542+loganmeyer@users.noreply.github.com> Co-authored-by: paseo-bot[bot] --- packages/server/package.json | 2 +- .../src/server/agent/agent-manager.test.ts | 54 +++++++ .../server/src/server/agent/agent-manager.ts | 13 +- .../server/owned-subscriptions.e2e.test.ts | 134 ++++++++++++++++-- packages/server/src/server/session.ts | 32 +++-- 5 files changed, 209 insertions(+), 26 deletions(-) diff --git a/packages/server/package.json b/packages/server/package.json index 90e2ccace8..13e5c9b49c 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -89,7 +89,7 @@ "speech:transcribe:local": "tsx scripts/transcribe-local-wav.ts", "test": "npm run test:unit && npm run test:integration", "test:unit": "vitest run --fileParallelism --exclude \"**/*.e2e.test.ts\"", - "test:integration": "vitest run --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts && vitest run --maxWorkers=1 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history\"", + "test:integration": "vitest run --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --maxWorkers=1 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history\"", "test:hub-cli-contract": "vitest run --maxWorkers=1 src/server/hub/hub-cli-contract.test.ts", "test:integration:all": "npm run test:e2e", "test:integration:real": "vitest run real.e2e.test.ts", diff --git a/packages/server/src/server/agent/agent-manager.test.ts b/packages/server/src/server/agent/agent-manager.test.ts index bb521abc71..902fd79ebc 100644 --- a/packages/server/src/server/agent/agent-manager.test.ts +++ b/packages/server/src/server/agent/agent-manager.test.ts @@ -8059,6 +8059,60 @@ test("global subscribers receive internal agent events only when they opt in", a unsubscribeOptedIn(); }); +test("agent removal notifications respect scoped subscriptions and internal visibility", () => { + const manager = new AgentManager({ clients: {}, logger }); + const removedId = "00000000-0000-4000-8000-000000000901"; + const internalId = "00000000-0000-4000-8000-000000000902"; + const otherId = "00000000-0000-4000-8000-000000000903"; + const publicEvents: AgentManagerEvent[] = []; + const allEvents: AgentManagerEvent[] = []; + const scopedEvents: AgentManagerEvent[] = []; + const internalEvents: AgentManagerEvent[] = []; + const unrelatedEvents: AgentManagerEvent[] = []; + const releases = [ + manager.subscribe((event) => publicEvents.push(event), { replayState: false }), + manager.subscribe((event) => allEvents.push(event), { + replayState: false, + includeInternal: true, + }), + manager.subscribe((event) => scopedEvents.push(event), { + replayState: false, + agentId: removedId, + }), + manager.subscribe((event) => internalEvents.push(event), { + replayState: false, + agentId: internalId, + }), + manager.subscribe((event) => unrelatedEvents.push(event), { + replayState: false, + agentId: otherId, + }), + ]; + try { + manager.notifyAgentRemoved({ id: removedId, workspaceId: "workspace" }); + manager.notifyAgentRemoved({ id: internalId, workspaceId: "workspace", internal: true }); + const publicRemoval = { + type: "agent_removed", + agentId: removedId, + workspaceId: "workspace", + internal: false, + }; + const internalRemoval = { + type: "agent_removed", + agentId: internalId, + workspaceId: "workspace", + internal: true, + }; + expect(publicEvents).toEqual([publicRemoval]); + expect(allEvents).toEqual([publicRemoval, internalRemoval]); + expect(scopedEvents).toEqual([publicRemoval]); + expect(internalEvents).toEqual([internalRemoval]); + expect(unrelatedEvents).toEqual([]); + } finally { + for (const release of releases) release(); + } +}); + test("getAgent returns internal agents by ID", async () => { const internalAgentId = "00000000-0000-4000-8000-000000000107"; const workdir = mkdtempSync(join(tmpdir(), "agent-manager-test-")); diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index ae9e424d78..a761e723c1 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -236,6 +236,7 @@ export type { export type AgentManagerEvent = | { type: "agent_state"; agent: ManagedAgent } + | { type: "agent_removed"; agentId: string; workspaceId?: string; internal: boolean } | { type: "provider_subagent"; event: ProviderSubagentStoreEvent } | { type: "timeline_replacement"; agentId: string; epoch: string } | { @@ -3519,6 +3520,15 @@ export class AgentManager { await this.deleteCommittedTimeline(agentId); } + notifyAgentRemoved(agent: Pick): void { + this.dispatch({ + type: "agent_removed", + agentId: agent.id, + workspaceId: agent.workspaceId, + internal: agent.internal === true, + }); + } + async deleteCommittedTimeline(agentId: string): Promise { await this.durableTimelineStore?.deleteAgent(agentId); } @@ -5376,7 +5386,7 @@ export class AgentManager { for (const subscriber of this.subscribers) { if ( subscriber.agentId && - event.type === "agent_stream" && + (event.type === "agent_stream" || event.type === "agent_removed") && subscriber.agentId !== event.agentId ) { continue; @@ -5412,6 +5422,7 @@ export class AgentManager { private eventBelongsToInternalAgent(event: AgentManagerEvent): boolean { if (event.type === "agent_state") return event.agent.internal === true; + if (event.type === "agent_removed") return event.internal; if (event.type === "agent_stream") return this.agents.get(event.agentId)?.internal === true; if (event.type !== "provider_subagent") return false; const parentAgentId = diff --git a/packages/server/src/server/owned-subscriptions.e2e.test.ts b/packages/server/src/server/owned-subscriptions.e2e.test.ts index 68437daf70..2a3128ea9f 100644 --- a/packages/server/src/server/owned-subscriptions.e2e.test.ts +++ b/packages/server/src/server/owned-subscriptions.e2e.test.ts @@ -1,7 +1,8 @@ import { MockLoadTestAgentClient } from "./agent/providers/mock-load-test-agent.js"; import { createPaseoApi } from "@getpaseo/client"; +import type { AgentManager } from "./agent/agent-manager.js"; import { execFileSync } from "node:child_process"; -import { mkdir, writeFile } from "node:fs/promises"; +import { mkdir, readFile, writeFile } from "node:fs/promises"; import path from "node:path"; import { expect, test } from "vitest"; import type { z } from "zod"; @@ -71,15 +72,18 @@ class SubscriptionPeer { async request(message: z.input): Promise { this.socket.send(JSON.stringify({ type: "session", message })); await expect - .poll(() => - this.frames.some( - (frame) => - frame.type === "session" && - "payload" in frame.message && - "requestId" in frame.message.payload && - "requestId" in message && - frame.message.payload.requestId === message.requestId, - ), + .poll( + () => + this.frames.some( + (frame) => + frame.type === "session" && + "payload" in frame.message && + "requestId" in frame.message.payload && + "requestId" in message && + frame.message.payload.requestId === message.requestId, + ), + // Diagnostics invoke external tools with their own multi-second deadlines. + { timeout: 10_000 }, ) .toBe(true); } @@ -119,6 +123,16 @@ class SubscriptionPeer { } } +function removedAgentIds(peer: SubscriptionPeer): string[] { + return peer.frames.flatMap((frame) => + frame.type === "session" && + frame.message.type === "agent_update" && + frame.message.payload.kind === "remove" + ? [frame.message.payload.agentId] + : [], + ); +} + test("a pure list reply belongs only to its source socket in a shared logical session", async () => { const daemon = await createTestPaseoDaemon({ mcpEnabled: false }); const peers: SubscriptionPeer[] = []; @@ -225,6 +239,96 @@ test("combined filtered agent lists create independent server-owned observations } }); +test.each([ + { + state: "live", + prepare: async (_manager: AgentManager, _agentId: string) => {}, + }, + { + state: "stored-only", + prepare: (manager: AgentManager, agentId: string) => manager.closeAgent(agentId), + }, +])( + "$state agent deletion reaches directory observers across logical sessions without broadcasting its reply", + async ({ prepare }) => { + const daemon = await createTestPaseoDaemon({ mcpEnabled: false }); + const admin = new DaemonClient({ + url: `ws://127.0.0.1:${daemon.port}/ws`, + appVersion: "0.8.0", + }); + const peers: SubscriptionPeer[] = []; + try { + await admin.connect(); + const workspace = ( + await admin.createWorkspace({ source: { kind: "directory", path: daemon.staticDir } }) + ).workspace; + if (!workspace) throw new Error("Workspace creation failed"); + const removed = await admin.createAgent({ + provider: "codex", + cwd: daemon.staticDir, + workspaceId: workspace.id, + }); + const survivor = await admin.createAgent({ + provider: "codex", + cwd: daemon.staticDir, + workspaceId: workspace.id, + }); + const sentinel = path.join(daemon.staticDir, "keep-project-file.txt"); + await writeFile(sentinel, "keep this project file\n"); + await prepare(daemon.daemon.agentManager, removed.id); + const requester = await SubscriptionPeer.connect(daemon.port, "deletion-origin"); + const sibling = await SubscriptionPeer.connect(daemon.port, "deletion-origin"); + const observer = await SubscriptionPeer.connect(daemon.port, "deletion-observer"); + const legacy = await SubscriptionPeer.connect(daemon.port, "deletion-legacy", { + owned_subscriptions: false, + }); + peers.push(requester, sibling, observer, legacy); + for (const [index, peer] of peers.entries()) { + await peer.request({ + type: "fetch_agents_request", + requestId: `directory-${index}`, + subscribe: {}, + }); + const entries = peer.frames.flatMap((frame) => + frame.type === "session" && frame.message.type === "fetch_agents_response" + ? frame.message.payload.entries.map((entry) => entry.agent.id) + : [], + ); + expect(entries.sort()).toEqual([removed.id, survivor.id].sort()); + peer.frames.length = 0; + } + await requester.request({ + type: "delete_agent_request", + requestId: "delete-observed-agent", + agentId: removed.id, + }); + await expect + .poll(() => peers.map(removedAgentIds)) + .toEqual([[removed.id], [removed.id], [removed.id], [removed.id]]); + const replies = peers.map((peer) => + peer.frames.flatMap((frame) => + frame.type === "session" && frame.message.type === "agent_deleted" + ? [frame.message.payload] + : [], + ), + ); + expect(replies).toEqual([ + [{ agentId: removed.id, requestId: "delete-observed-agent" }], + [], + [], + [], + ]); + expect(await daemon.daemon.agentStorage.get(removed.id)).toBeNull(); + expect((await daemon.daemon.agentStorage.get(survivor.id))?.id).toBe(survivor.id); + expect(await readFile(sentinel, "utf8")).toBe("keep this project file\n"); + } finally { + for (const peer of peers) peer.close(); + await admin.close(); + await daemon.close(); + } + }, +); + test("workspace filters and identical queries coexist until their own release", async () => { const daemon = await createTestPaseoDaemon({ mcpEnabled: false }); const admin = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws`, appVersion: "0.8.0" }); @@ -679,7 +783,8 @@ test("same-workspace terminal directory observers do not share a teardown slot", peer.frames.length = 0; const result = await admin.createTerminal(daemon.staticDir, "Observed terminal", undefined, { workspaceId: workspace.id, - command: "/bin/cat", + command: process.execPath, + args: ["-e", "process.stdin.on('data', data => process.stdout.write(data))"], }); expect(result.error).toBe(null); await expect @@ -728,7 +833,8 @@ test("terminal output has separate server IDs and binary slots, including in a s ).workspace!; const result = await admin.createTerminal(daemon.staticDir, "Output ownership", undefined, { workspaceId: workspace.id, - command: "/bin/cat", + command: process.execPath, + args: ["-e", "process.stdin.on('data', data => process.stdout.write(data))"], }); expect(result.error).toBe(null); const idle = await SubscriptionPeer.connect(daemon.port, "terminal-output-session"); @@ -1423,7 +1529,7 @@ test("request outcomes for import and attention reach only their requesting sock }); const requester = await SubscriptionPeer.connect(daemon.port, "reply-shared"); const sibling = await SubscriptionPeer.connect(daemon.port, "reply-shared"); - const admin = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); + const admin = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws`, appVersion: "0.8.0" }); try { await admin.connect(); await requester.request({ @@ -1462,7 +1568,7 @@ test("request outcomes for import and attention reach only their requesting sock }), ); const agent = await admin.createAgent({ - provider: "codex", + provider: "mock", cwd: daemon.staticDir, title: "Attention", }); diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index 3eac37cb7b..cca0b4f3fa 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -1992,6 +1992,24 @@ export class Session { return; } + if (event.type === "agent_removed") { + if (event.internal) return; + void this.agentUpdates + .removeAgent(event.agentId) + .then(() => { + if (event.workspaceId) + return this.emitWorkspaceUpdateForWorkspaceId(event.workspaceId); + return undefined; + }) + .catch((error) => { + this.sessionLogger.error( + { err: error, agentId: event.agentId }, + "Failed to emit agent removal", + ); + }); + return; + } + if (event.type === "agent_state") { this.sessionLogger.trace( { @@ -3337,10 +3355,8 @@ export class Session { private async handleDeleteAgentRequest(agentId: string, requestId: string): Promise { this.sessionLogger.info({ agentId }, `Deleting agent ${agentId} from registry`); - const knownWorkspaceId = - this.agentManager.getAgent(agentId)?.workspaceId ?? - (await this.agentStorage.get(agentId))?.workspaceId ?? - null; + const knownAgent = + this.agentManager.getAgent(agentId) ?? (await this.agentStorage.get(agentId)); // File-backed storage still needs an early delete fence before closeAgent(). beginAgentDeleteIfSupported(this.agentStorage, agentId); @@ -3361,6 +3377,8 @@ export class Session { try { await this.agentStorage.remove(agentId); await this.agentManager.deleteAgentState(agentId); + // Directory removal is daemon-wide; agent_deleted below stays a source-scoped RPC reply. + if (knownAgent) this.agentManager.notifyAgentRemoved(knownAgent); } catch (error) { this.sessionLogger.error({ err: error, agentId }, `Failed to fully delete agent ${agentId}`); } @@ -3372,12 +3390,6 @@ export class Session { requestId, }, }); - - await this.agentUpdates.removeAgent(agentId); - - if (knownWorkspaceId) { - await this.emitWorkspaceUpdateForWorkspaceId(knownWorkspaceId); - } } private async handleArchiveAgentRequest(agentId: string, requestId: string): Promise { From 9c7925de5818a01ac60ce2343b8bff81f40746f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Pe=C5=A1l?= Date: Fri, 30 Oct 2026 04:01:41 +0100 Subject: [PATCH 117/173] fix(skills): make invocation input portable across harnesses (#8252) Read invocation input and conversation context without Claude argument substitution. Recognize Pi skill references when forwarding advisor requests. --- skills/paseo-advisor/SKILL.md | 8 +++++--- skills/paseo-committee/SKILL.md | 2 +- skills/paseo-handoff/SKILL.md | 2 +- skills/paseo-help/SKILL.md | 2 +- skills/paseo-plugin/SKILL.md | 2 +- 5 files changed, 9 insertions(+), 7 deletions(-) diff --git a/skills/paseo-advisor/SKILL.md b/skills/paseo-advisor/SKILL.md index 94d4558e5a..23868d9a2d 100644 --- a/skills/paseo-advisor/SKILL.md +++ b/skills/paseo-advisor/SKILL.md @@ -9,7 +9,7 @@ argument-hint: "[--profile ] " Single agent. Reads the situation you're in. Gives a judgment. You decide what to do — the advisor doesn't drive the work. -**User's request:** $ARGUMENTS +Use the user's request and current conversation as input, including any arguments supplied with the skill invocation. Optional syntax: `[--profile ] `. ## Prerequisites @@ -40,13 +40,15 @@ This is analysis only. Do NOT edit, create, or delete any files. Do NOT write co ## Forwarded skills -If `$ARGUMENTS` contains another skill reference — `/unslop`, `/unslop-risk`, `$unslop`, etc. — the user is asking the advisor to run that skill against the current task. Examples: +If the user's request contains another skill reference, such as `/unslop`, `/skill:unslop`, or `$unslop`, the user is asking the advisor to run that skill against the current task. Examples: - `/paseo-advisor /unslop` → advisor runs `/unslop` on the current diff. - `/paseo-advisor /unslop-risk` → advisor does an unslop-risk review. - `/paseo-advisor $diagnose this build failure` → advisor invokes `/diagnose`. +- `/skill:paseo-advisor /skill:unslop` → advisor runs the `unslop` skill on the current diff in Pi. +- `$paseo-advisor $unslop` → advisor runs the `unslop` skill on the current diff in Codex. -Parse the forwarded skill name out of `$ARGUMENTS` (`/` or `$`). In the briefing, tell the advisor explicitly: +Parse the forwarded skill name from the user's request (`/`, `/skill:`, or `$`), excluding this skill's own invocation. In the briefing, tell the advisor explicitly: ``` Invoke the `` skill against this task. Load it via the Skill tool before doing anything else. diff --git a/skills/paseo-committee/SKILL.md b/skills/paseo-committee/SKILL.md index 2b16189556..e41ca8ba81 100644 --- a/skills/paseo-committee/SKILL.md +++ b/skills/paseo-committee/SKILL.md @@ -8,7 +8,7 @@ user-invocable: true Two agents from contrasting profiles, fresh context, planning a solution in parallel. -**User's additional context:** $ARGUMENTS +Use the user's request and current conversation as input, including any arguments supplied with the skill invocation. ## Prerequisites diff --git a/skills/paseo-handoff/SKILL.md b/skills/paseo-handoff/SKILL.md index b321365306..fac6793e5e 100644 --- a/skills/paseo-handoff/SKILL.md +++ b/skills/paseo-handoff/SKILL.md @@ -8,7 +8,7 @@ user-invocable: true Transfer the current task — context, decisions, failed attempts, constraints — to a fresh agent. The receiving agent starts with **zero context**, so the handoff prompt must be a self-contained briefing. -**User's arguments:** $ARGUMENTS +Use the user's request and current conversation as input, including any arguments supplied with the skill invocation. ## Prerequisites diff --git a/skills/paseo-help/SKILL.md b/skills/paseo-help/SKILL.md index 951c1207bc..52dcf57a44 100644 --- a/skills/paseo-help/SKILL.md +++ b/skills/paseo-help/SKILL.md @@ -7,7 +7,7 @@ description: Answer questions about the Paseo product and app, including setup, You are helping a user understand, configure, or troubleshoot Paseo itself. Answer their question directly, verify the answer against the current public documentation, and include the relevant documentation link. Do not send the user away to read the docs in place of helping them. -**User's question:** $ARGUMENTS +Use the user's question and current conversation as input, including any arguments supplied with the skill invocation. ## Use current documentation diff --git a/skills/paseo-plugin/SKILL.md b/skills/paseo-plugin/SKILL.md index 0a36b5b3eb..b54938ad53 100644 --- a/skills/paseo-plugin/SKILL.md +++ b/skills/paseo-plugin/SKILL.md @@ -7,7 +7,7 @@ description: Build and manage trusted local Paseo plugins. Use when the user ask Build or manage the requested plugin directly. Use the current public docs to catch contract changes, but keep working from this skill if the network is unavailable. -**User's request:** $ARGUMENTS +Use the user's request and current conversation as input, including any arguments supplied with the skill invocation. ## Check current documentation From deb1bdc2666c7fdf964933875635767fe8b66c20 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Fri, 30 Oct 2026 03:38:37 +0000 Subject: [PATCH 118/173] test(plugins): wait for global recovery without an extra restart (#8250) * test(plugins): observe global recovery without reloading again * test(plugins): leave time for recovery failure cleanup --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../src/server/plugins/index.posix.test.ts | 38 +++++++++++-------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/packages/server/src/server/plugins/index.posix.test.ts b/packages/server/src/server/plugins/index.posix.test.ts index 364e24e40b..c529bd37d3 100644 --- a/packages/server/src/server/plugins/index.posix.test.ts +++ b/packages/server/src/server/plugins/index.posix.test.ts @@ -1075,23 +1075,29 @@ export default function contribute(plugin: unknown) { const service = bindTestSessionHost( new PluginService(pino({ level: "silent" }), store, "0.4.0"), ); - await service.start(); - await service.installDirectory({ path: first }); - await service.installDirectory({ path: second }); + try { + await service.start(); + await service.installDirectory({ path: first }); + await service.installDirectory({ path: second }); + expect(catalogIds(service)).toEqual(["first", "second"]); + await store.patch({ pluginsEnabled: false }); - await store.patch({ pluginsEnabled: false }); - - expect(service.catalog()).toEqual([]); - await expect(service.invokePluginRpc("second", "anything", {})).rejects.toThrow( - "Plugin is not available", - ); - await store.patch({ pluginsEnabled: true }); - await service.reloadPlugin("first"); - expect((await service.listPlugins()).map(({ id, status }) => ({ id, status }))).toEqual([ - { id: "first", status: "running" }, - { id: "second", status: "running" }, - ]); - await service.stopAllPlugins(); + expect(service.catalog()).toEqual([]); + await expect(service.invokePluginRpc("second", "anything", {})).rejects.toThrow( + "Plugin is not available", + ); + await store.patch({ pluginsEnabled: true }); + // Observe recovery itself. Reloading here restarts a healthy plugin and + // would also conceal a failure to restart it after the global enable. + await expect + .poll(() => service.listPlugins(), { timeout: 10_000 }) + .toMatchObject([ + { id: "first", status: "running" }, + { id: "second", status: "running" }, + ]); + } finally { + await service.stopAllPlugins(); + } }, 20_000); it("does not publish an in-flight start after a later global disable", async () => { From c663630bbd78fe629c04439063d9b7f8c5f44b7e Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Fri, 30 Oct 2026 12:57:21 +0700 Subject: [PATCH 119/173] fix(server): read Codex history in pages instead of one whole-thread reply (#8171) Opening a Codex agent whose timeline the daemon doesn't hold asked Codex for the whole thread in one thread/read reply. Past the 128 MiB provider line cap that reply killed the session; before the cap it crashed the daemon. Codex 0.145 and newer reject that read on paginated threads, so importing them failed. Paginated threads now load through thread/items/list pages. A legacy thread keeps its single read. A reply over the line cap fails only its own request: for a legacy read, a warning row names the archive, `codex migrate-rollouts`, unarchive steps; for a page, a warning row ends the history there. Items are capped as they are projected, and rewind's fork no longer returns the thread's turns. Co-authored-by: hunterricks Co-authored-by: dundunHa --- .../reproduce-codex-history-string-limit.mts | 108 +++++++++ .../providers/codex-app-server-agent.test.ts | 23 +- .../agent/providers/codex-app-server-agent.ts | 162 ++++++------- ...odex-history-string-limit.real.e2e.test.ts | 53 +++++ .../codex/app-server-transport.test.ts | 31 ++- .../providers/codex/app-server-transport.ts | 32 ++- .../agent/providers/codex/rewind.test.ts | 4 +- .../server/agent/providers/codex/rewind.ts | 24 +- .../codex/test-utils/fake-app-server.ts | 104 ++++++++- .../providers/codex/thread-history.test.ts | 220 ++++++++++++++++++ .../agent/providers/codex/thread-history.ts | 168 +++++++++++++ .../agent/providers/jsonl-frame-decoder.ts | 47 +++- 12 files changed, 839 insertions(+), 137 deletions(-) create mode 100644 packages/server/scripts/reproduce-codex-history-string-limit.mts create mode 100644 packages/server/src/server/agent/providers/codex-history-string-limit.real.e2e.test.ts create mode 100644 packages/server/src/server/agent/providers/codex/thread-history.test.ts create mode 100644 packages/server/src/server/agent/providers/codex/thread-history.ts diff --git a/packages/server/scripts/reproduce-codex-history-string-limit.mts b/packages/server/scripts/reproduce-codex-history-string-limit.mts new file mode 100644 index 0000000000..b0f49e4faf --- /dev/null +++ b/packages/server/scripts/reproduce-codex-history-string-limit.mts @@ -0,0 +1,108 @@ +// Opt-in diagnostic for #3905. Run from the repository root: +// node --import tsx packages/server/scripts/reproduce-codex-history-string-limit.mts 520 [legacy|paginated] +// Requires Codex 0.148+ on PATH and approximately 2 GiB of available memory. +// `paginated` migrates the synthetic rollout with `codex migrate-rollouts` first. +import { execFileSync, spawn } from "node:child_process"; +import { randomUUID } from "node:crypto"; +import { mkdtemp, mkdir, open, rm } from "node:fs/promises"; +import path from "node:path"; +import pino from "pino"; +import { CodexAppServerAgentSession } from "../src/server/agent/providers/codex-app-server-agent.js"; + +const megabytes = Number(process.argv[2] ?? "520"); +if (!Number.isSafeInteger(megabytes) || megabytes < 1 || megabytes > 600) { + throw new Error("Expected an integer size between 1 and 600 MiB"); +} +const historyMode = process.argv[3] ?? "legacy"; +if (historyMode !== "legacy" && historyMode !== "paginated") { + throw new Error("Expected history mode legacy or paginated"); +} +const root = await mkdtemp(path.join(process.cwd(), ".codex-history-repro-")); +const home = path.join(root, "codex-home"); +const now = new Date(); +const timestamp = now.toISOString(); +const threadId = randomUUID(); +const turnId = randomUUID(); +const sessions = path.join(home, "sessions", ...timestamp.slice(0, 10).split("-")); +await mkdir(sessions, { recursive: true }); +const rollout = await open( + path.join(sessions, `rollout-${timestamp.slice(0, 19).replaceAll(":", "-")}-${threadId}.jsonl`), + "w", +); +async function write(type: string, payload: unknown) { + await rollout.write(`${JSON.stringify({ timestamp, type, payload })}\n`); +} +await write("session_meta", { + id: threadId, + timestamp, + cwd: root, + originator: "codex_cli_rs", + cli_version: "0.159.0", + source: "cli", + model_provider: "openai", + history_mode: "legacy", +}); +await write("event_msg", { type: "task_started", turn_id: turnId, model_context_window: 200000 }); +await write("event_msg", { + type: "user_message", + message: "Synthetic oversized history", + images: [], + local_images: [], + text_elements: [], +}); +for (let index = 0; index < megabytes; index++) { + await write("event_msg", { + type: "agent_message", + message: "x".repeat(1024 * 1024), + phase: "commentary", + }); +} +await write("event_msg", { type: "task_complete", turn_id: turnId, last_agent_message: "done" }); +await rollout.close(); +if (historyMode === "paginated") { + execFileSync("codex", ["migrate-rollouts", "--apply", "--thread", threadId], { + env: { ...process.env, CODEX_HOME: home }, + stdio: "ignore", + }); +} +console.log( + `Opening synthetic ${megabytes} MiB ${historyMode} history through the real Codex app-server`, +); +const session = new CodexAppServerAgentSession( + { provider: "codex", cwd: root }, + { sessionId: threadId }, + pino({ level: "silent" }), + async () => + spawn( + "codex", + ["app-server", "--disable", "plugins", "--disable", "apps", "--disable", "remote_plugin"], + { + stdio: ["pipe", "pipe", "pipe"], + env: { ...process.env, CODEX_HOME: home }, + }, + ), + { codexHome: home }, + false, + false, + false, + undefined, + "history", +); +try { + await session.connect(); + let count = 0; + for await (const event of session.streamHistory()) { + if (event.type !== "timeline") continue; + count++; + if (event.item.type === "notification") console.log(event.item.message); + } + console.log(`History loaded: ${count} timeline rows`); +} catch (error) { + // A recoverable session error is acceptable for the crash-isolation assertion. + console.log( + `History rejected without crashing: ${error instanceof Error ? error.message : String(error)}`, + ); +} finally { + await session.close(); + await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); +} diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts index e709fd490c..cb8cb2684b 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts @@ -88,6 +88,7 @@ describe("Codex executable discovery", () => { import { CodexAppServerClient } from "./codex/app-server-transport.js"; import { createFakeCodexAppServer, + fakeCodexThreadHistory, type FakeCodexAppServer, waitForNextPermission, waitForNextTimelineItem, @@ -1991,7 +1992,7 @@ describe("Codex app-server provider", () => { purpose: "history", }); - expect(threadRequests).toEqual(["thread/read"]); + expect(threadRequests).toEqual(["thread/read", "thread/read"]); await session.close(); appServer.assertNoErrors(); }); @@ -2068,6 +2069,7 @@ describe("Codex app-server provider", () => { "thread/loaded/list", "thread/resume", "thread/read", + "thread/read", ]); expect(codex.threadMethods(1)).toEqual(["thread/loaded/list", "thread/resume"]); expect(codex.manager.getTimeline(codex.agentId)).toEqual(projected); @@ -2427,7 +2429,7 @@ describe("Codex app-server provider", () => { cwd: "/workspace/project", model: "gpt-5.4", serviceTier: null, - excludeTurns: false, + excludeTurns: true, persistExtendedHistory: true, }, ]); @@ -2441,8 +2443,9 @@ describe("Codex app-server provider", () => { test("rewinds a paginated conversation through the public session capability", async () => { const appServer = createFakeCodexAppServer({ - "thread/read": () => ({ - thread: { id: "thread-1", historyMode: "paginated", turns: [] }, + ...fakeCodexThreadHistory({ + "thread-1": { historyMode: "paginated", turns: [] }, + "forked-thread": { historyMode: "paginated", turns: [] }, }), "thread/rollback": () => { throw new Error("paginated threads do not support thread/rollback"); @@ -2487,7 +2490,7 @@ describe("Codex app-server provider", () => { cwd: "/workspace/project", model: "gpt-5.4", serviceTier: null, - excludeTurns: false, + excludeTurns: true, persistExtendedHistory: true, }, ]); @@ -2504,11 +2507,10 @@ describe("Codex app-server provider", () => { async (historyMode) => { const appServer = createFakeCodexAppServer( historyMode === "paginated" - ? { - "thread/read": () => ({ - thread: { id: "thread-1", historyMode: "paginated", turns: [] }, - }), - } + ? fakeCodexThreadHistory({ + "thread-1": { historyMode: "paginated", turns: [] }, + "forked-thread": { historyMode: "paginated", turns: [] }, + }) : undefined, ); const customCodexConfig = { @@ -4947,6 +4949,7 @@ describe("Codex app-server provider", () => { } expect(requests.map((request) => [request.method, request.params])).toEqual([ + ["thread/read", { threadId: "test-thread", includeTurns: false }], ["thread/read", { threadId: "test-thread", includeTurns: true }], ]); expect(history).toEqual([ diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.ts index 5e43f582c5..f7d4f50215 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.ts @@ -92,12 +92,18 @@ import { type CodexAppServerTraceContext, } from "./codex/app-server-transport.js"; import { type CodexUserMessageTurnIndex, revertCodexConversation } from "./codex/rewind.js"; +import { + type CodexHistoryRow, + CodexThreadHistoryTooLargeError, + readCodexThreadHistory, +} from "./codex/thread-history.js"; import { materializeProviderImage, renderProviderImageOutputAsAssistantMarkdown, type ProviderImageOutput, } from "./provider-image-output.js"; import { normalizeProviderReplayTimestamp } from "../provider-history-timestamps.js"; +import { limitAgentTimelineItemContent } from "../agent-timeline-content.js"; import { formatProviderDiagnostic, formatProviderDiagnosticError, @@ -1804,22 +1810,13 @@ function readCodexHistoryTimestamp(item: unknown): string | null { ); } -function readCodexTurnHistoryTimestamp( - turn: unknown, +/** Falls back to the row's start time for a user message and its end time otherwise. */ +function readCodexHistoryRowTimestamp( + row: CodexHistoryRow, timelineItem: AgentTimelineItem, ): string | null { - const record = toObjectRecord(turn); - if (!record) { - return null; - } - - const startedAt = - normalizeProviderReplayTimestamp(record.startedAt) ?? - normalizeProviderReplayTimestamp(record.started_at); - const completedAt = - normalizeProviderReplayTimestamp(record.completedAt) ?? - normalizeProviderReplayTimestamp(record.completed_at); - + const startedAt = normalizeProviderReplayTimestamp(row.startedAt); + const completedAt = normalizeProviderReplayTimestamp(row.completedAt); if (timelineItem.type === "user_message") { return startedAt ?? completedAt; } @@ -2063,84 +2060,19 @@ async function threadItemToTimelineEntries( return [timelineItem, ...(await mcpToolResultImagesToTimeline(item))]; } -const CodexThreadReadResponseSchema = z - .object({ - thread: z - .object({ - turns: z - .array( - z - .object({ - items: z.array(z.unknown()).default([]), - }) - .passthrough(), - ) - .default([]), - }) - .passthrough() - .default({ turns: [] }), - }) - .passthrough(); - -type CodexThreadReadResponse = z.infer; -type CodexThreadReadRequest = (threadId: string) => Promise; - -async function requestCodexThreadHistory( - requestThread: CodexThreadReadRequest, - threadId: string, -): Promise { - const response = await requestThread(threadId); - return CodexThreadReadResponseSchema.parse(response); -} - async function loadCodexThreadHistoryTimeline(params: { + client: CodexAppServerClientLike; threadId: string; cwd: string | null; - requestThread: CodexThreadReadRequest; }): Promise { - const response = await requestCodexThreadHistory(params.requestThread, params.threadId); const timeline: PersistedTimelineEntry[] = []; const subAgentTimelineIndexByThreadId = new Map(); - for (const turn of response.thread.turns) { - for (const item of turn.items) { - const historicalSubAgentActivity = readCodexSubAgentActivity(item); - if (historicalSubAgentActivity) { - const existingIndex = subAgentTimelineIndexByThreadId.get( - historicalSubAgentActivity.agentThreadId, - ); - if (existingIndex !== undefined) { - const activityTimelineItem = await threadItemToTimeline(item, { cwd: params.cwd }); - updateHistoricalSubAgentActivity( - timeline, - existingIndex, - historicalSubAgentActivity.kind, - activityTimelineItem?.type === "tool_call" && - activityTimelineItem.detail.type === "sub_agent" - ? activityTimelineItem.detail.subAgentType - : undefined, - ); - continue; - } - } - for (const timelineItem of await threadItemToTimelineEntries(item, { cwd: params.cwd })) { - const timestamp = - readCodexHistoryTimestamp(item) ?? readCodexTurnHistoryTimestamp(turn, timelineItem); - const settledTimelineItem = - historicalSubAgentActivity && timelineItem.type === "tool_call" - ? settleHistoricalSubAgentActivity(timelineItem, historicalSubAgentActivity.kind) - : timelineItem; - timeline.push({ - item: settledTimelineItem, - timestamp: timestamp ?? undefined, - ...(timelineItem.type === "user_message" && typeof turn.id === "string" - ? { providerTurnId: turn.id } - : {}), - }); - for (const childThreadId of readCodexHistoricalSubAgentThreadIds(item)) { - subAgentTimelineIndexByThreadId.set(childThreadId, timeline.length - 1); - } - } - } + try { + await projectCodexThreadHistory(params, { timeline, subAgentTimelineIndexByThreadId }); + } catch (error) { + if (!(error instanceof CodexThreadHistoryTooLargeError)) throw error; + // The session stays usable; the row says why the history stops here. + timeline.push({ item: { type: "notification", level: "warning", message: error.message } }); } const subAgentRoutes = Array.from(subAgentTimelineIndexByThreadId.entries()).flatMap( ([childThreadId, timelineIndex]): PersistedSubAgentRoute[] => { @@ -2153,11 +2085,55 @@ async function loadCodexThreadHistoryTimeline(params: { return { timeline, subAgentRoutes }; } -function readCodexThread(client: CodexAppServerClientLike, threadId: string): Promise { - return client.request("thread/read", { - threadId, - includeTurns: true, - }); +async function projectCodexThreadHistory( + params: { client: CodexAppServerClientLike; threadId: string; cwd: string | null }, + projection: { + timeline: PersistedTimelineEntry[]; + subAgentTimelineIndexByThreadId: Map; + }, +): Promise { + const { timeline, subAgentTimelineIndexByThreadId } = projection; + for await (const row of readCodexThreadHistory(params.client, params.threadId)) { + const { item } = row; + const historicalSubAgentActivity = readCodexSubAgentActivity(item); + if (historicalSubAgentActivity) { + const existingIndex = subAgentTimelineIndexByThreadId.get( + historicalSubAgentActivity.agentThreadId, + ); + if (existingIndex !== undefined) { + const activityTimelineItem = await threadItemToTimeline(item, { cwd: params.cwd }); + updateHistoricalSubAgentActivity( + timeline, + existingIndex, + historicalSubAgentActivity.kind, + activityTimelineItem?.type === "tool_call" && + activityTimelineItem.detail.type === "sub_agent" + ? activityTimelineItem.detail.subAgentType + : undefined, + ); + continue; + } + } + for (const timelineItem of await threadItemToTimelineEntries(item, { cwd: params.cwd })) { + const timestamp = + readCodexHistoryTimestamp(item) ?? readCodexHistoryRowTimestamp(row, timelineItem); + const settledTimelineItem = + historicalSubAgentActivity && timelineItem.type === "tool_call" + ? settleHistoricalSubAgentActivity(timelineItem, historicalSubAgentActivity.kind) + : timelineItem; + timeline.push({ + // Cap each item as it is projected so a large history is never held uncapped. + item: limitAgentTimelineItemContent(settledTimelineItem), + timestamp: timestamp ?? undefined, + ...(timelineItem.type === "user_message" && row.turnId !== undefined + ? { providerTurnId: row.turnId } + : {}), + }); + for (const childThreadId of readCodexHistoricalSubAgentThreadIds(item)) { + subAgentTimelineIndexByThreadId.set(childThreadId, timeline.length - 1); + } + } + } } export async function forkCodexThread( @@ -3997,9 +3973,9 @@ export class CodexAppServerAgentSession implements AgentSession { return { timeline: [], providerSubagentEvents: [] }; } const { timeline, subAgentRoutes } = await loadCodexThreadHistoryTimeline({ + client, threadId: this.currentThreadId, cwd: this.config.cwd ?? null, - requestThread: (threadIdToRead) => readCodexThread(client, threadIdToRead), }); this.subAgentCallsByCallId.clear(); this.subAgentCallIdByChildThreadId.clear(); @@ -4055,9 +4031,9 @@ export class CodexAppServerAgentSession implements AgentSession { }); try { const childHistory = await loadCodexThreadHistoryTimeline({ + client, threadId: next.route.childThreadId, cwd: this.config.cwd ?? null, - requestThread: (childThreadId) => readCodexThread(client, childThreadId), }); for (const entry of childHistory.timeline) { this.emitProviderSubagentTimeline(next.route.childThreadId, entry.item, entry.timestamp); diff --git a/packages/server/src/server/agent/providers/codex-history-string-limit.real.e2e.test.ts b/packages/server/src/server/agent/providers/codex-history-string-limit.real.e2e.test.ts new file mode 100644 index 0000000000..fba51b9e1d --- /dev/null +++ b/packages/server/src/server/agent/providers/codex-history-string-limit.real.e2e.test.ts @@ -0,0 +1,53 @@ +import { execFile } from "node:child_process"; +import { mkdtemp, rm } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { expect, test } from "vitest"; + +// Regression for #3905. Real Codex, synthetic on-disk history, no model turns. +// Opt in because the oversized cases need approximately 2 GiB of memory and over +// 1 GiB of temporary storage. +const enabled = process.env.PASEO_CODEX_HISTORY_STRING_LIMIT_REPRO === "1"; +const script = fileURLToPath( + new URL("../../../../scripts/reproduce-codex-history-string-limit.mts", import.meta.url), +); + +test.runIf(enabled).each([ + { megabytes: 2, historyMode: "legacy", expected: "History loaded: 3 timeline rows" }, + { megabytes: 520, historyMode: "legacy", expected: "codex migrate-rollouts --apply --thread" }, + { megabytes: 520, historyMode: "paginated", expected: "History loaded: 521 timeline rows" }, +])( + "opening $megabytes MiB of $historyMode Codex history does not crash its hosting process", + async ({ megabytes, historyMode, expected }) => { + const root = await mkdtemp(path.join(process.cwd(), ".codex-history-test-")); + try { + const result = await new Promise<{ code: number; stdout: string; stderr: string }>( + (resolve) => { + const child = execFile( + process.execPath, + ["--import", "tsx", script, String(megabytes), historyMode], + { + cwd: root, + detached: true, + timeout: 120_000, + maxBuffer: 1024 * 1024, + }, + (error, stdout, stderr) => { + try { + if (child.pid) process.kill(-child.pid, "SIGKILL"); + } catch (killError) { + if ((killError as NodeJS.ErrnoException).code !== "ESRCH") throw killError; + } + resolve({ code: error ? Number(error.code ?? 1) : 0, stdout, stderr }); + }, + ); + }, + ); + expect(result.code, result.stderr).toBe(0); + expect(result.stdout).toContain(expected); + } finally { + await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); + } + }, + 180_000, +); diff --git a/packages/server/src/server/agent/providers/codex/app-server-transport.test.ts b/packages/server/src/server/agent/providers/codex/app-server-transport.test.ts index 3018461ba9..84b82b431b 100644 --- a/packages/server/src/server/agent/providers/codex/app-server-transport.test.ts +++ b/packages/server/src/server/agent/providers/codex/app-server-transport.test.ts @@ -185,14 +185,41 @@ describe("Codex app-server transport", () => { }); describe("Codex stdout byte admission", () => { - test("fails pending requests and the session before joining an oversized line", async () => { + test("an oversized response fails only its own request", async () => { + const child = createCodexAppServerChildProcess(); + const client = new CodexAppServerClient(child, createTestLogger()); + const terminations: Error[] = []; + client.setUnexpectedTerminationHandler((error) => terminations.push(error)); + const oversized = client.request("thread/items/list", {}).catch((error: Error) => error); + const other = client.request("model/list", {}); + const chunk = Buffer.alloc(64 * 1024, "x"); + child.stdout.write('{"id":1,"result":"'); + for (let index = 0; index < 2049; index++) child.stdout.write(chunk); + child.stdout.write('"}\n{"id":2,"result":{"data":[]}}\n'); + + expect(await oversized).toMatchObject({ + name: "CodexAppServerResponseTooLargeError", + method: "thread/items/list", + limitBytes: 128 * 1024 * 1024, + }); + await expect(other).resolves.toEqual({ data: [] }); + const next = client.request("model/list", {}); + child.stdout.write('{"id":3,"result":{"data":["next"]}}\n'); + await expect(next).resolves.toEqual({ data: ["next"] }); + expect(terminations).toEqual([]); + await client.dispose(); + child.stdout.end(); + child.stderr.end(); + }); + + test("an oversized notification fails pending requests and the session", async () => { const child = createCodexAppServerChildProcess(); const client = new CodexAppServerClient(child, createTestLogger()); const terminations: Error[] = []; client.setUnexpectedTerminationHandler((error) => terminations.push(error)); const request = client.request("thread/resume", {}, 1000).catch((error: Error) => error); const chunk = Buffer.alloc(64 * 1024, "x"); - child.stdout.write('{"id":1,"result":"'); + child.stdout.write('{"method":"item/completed","params":"'); for (let index = 0; index < 2048; index++) child.stdout.write(chunk); const error = await request; expect(error).toMatchObject({ diff --git a/packages/server/src/server/agent/providers/codex/app-server-transport.ts b/packages/server/src/server/agent/providers/codex/app-server-transport.ts index dfd4adfac4..5a218e2edb 100644 --- a/packages/server/src/server/agent/providers/codex/app-server-transport.ts +++ b/packages/server/src/server/agent/providers/codex/app-server-transport.ts @@ -33,11 +33,26 @@ interface JsonRpcNotification { } interface PendingRequest { + method: string; resolve: (value: unknown) => void; reject: (error: Error) => void; timer: NodeJS.Timeout; } +/** A response past the provider line cap. Only its request fails; the session stays up. */ +export class CodexAppServerResponseTooLargeError extends Error { + constructor( + readonly method: string, + readonly limitBytes: number, + ) { + super(`Codex app-server response to ${method} exceeds ${limitBytes} bytes`); + this.name = "CodexAppServerResponseTooLargeError"; + } +} + +// Codex serializes a response with `id` first, so its head names the request. +const OVERSIZED_RESPONSE_HEAD = /^\{"id":(\d+),"result":/; + export class CodexAppServerRpcError extends Error { constructor( message: string, @@ -258,7 +273,7 @@ export class CodexAppServerClient { this.pending.delete(id); reject(new Error(`Codex app-server request timed out for ${method}`)); }, timeoutMs); - this.pending.set(id, { resolve, reject, timer }); + this.pending.set(id, { method, resolve, reject, timer }); }); } @@ -304,8 +319,21 @@ export class CodexAppServerClient { } private handleStreamLimit(failure: ProviderStreamLimitError): void { - // A rejected response/notification cannot be replayed safely. Fail the session, + const responseId = OVERSIZED_RESPONSE_HEAD.exec(failure.lineHead)?.[1]; + const pending = responseId === undefined ? undefined : this.pending.get(Number(responseId)); + if (pending) { + clearTimeout(pending.timer); + this.pending.delete(Number(responseId)); + this.logger.warn( + { method: pending.method, limitBytes: failure.limitBytes }, + "Codex app-server response exceeded the line cap", + ); + pending.reject(new CodexAppServerResponseTooLargeError(pending.method, failure.limitBytes)); + return; + } + // A lost notification or server request cannot be replayed. Fail the session, // including live turns with no pending RPC, rather than dropping a stream unit. + this.stdoutLineReader.close(); this.handleUnexpectedTermination(failure); void this.dispose().catch((err) => { this.logger.warn({ err }, "Failed to terminate oversized Codex stdout producer"); diff --git a/packages/server/src/server/agent/providers/codex/rewind.test.ts b/packages/server/src/server/agent/providers/codex/rewind.test.ts index da7fe6a8f5..7a0b2dc0f9 100644 --- a/packages/server/src/server/agent/providers/codex/rewind.test.ts +++ b/packages/server/src/server/agent/providers/codex/rewind.test.ts @@ -108,7 +108,7 @@ describe("Codex Rewind", () => { cwd: "/workspace/project", model: "gpt-5.4-mini", serviceTier: null, - excludeTurns: false, + excludeTurns: true, persistExtendedHistory: true, }, ]); @@ -190,7 +190,7 @@ describe("Codex Rewind", () => { cwd: "/workspace/project", model: "gpt-5.4-mini", serviceTier: null, - excludeTurns: false, + excludeTurns: true, persistExtendedHistory: true, }, ]); diff --git a/packages/server/src/server/agent/providers/codex/rewind.ts b/packages/server/src/server/agent/providers/codex/rewind.ts index 021d57645c..a22931b92b 100644 --- a/packages/server/src/server/agent/providers/codex/rewind.ts +++ b/packages/server/src/server/agent/providers/codex/rewind.ts @@ -8,6 +8,7 @@ import { parseCodexThreadForkResponse, parseCodexThreadRollbackResponse, } from "./app-server-transport.js"; +import { readCodexThreadHistoryMode } from "./thread-history.js"; export interface CodexRewindClient { forkThread?(params: CodexThreadForkParams): Promise; @@ -20,26 +21,6 @@ export interface CodexUserMessageTurnIndex { count(): number; } -type CodexThreadHistoryMode = "legacy" | "paginated"; - -async function readCodexThreadHistoryMode( - client: CodexRewindClient, - threadId: string, -): Promise { - const response = await client.request("thread/read", { threadId, includeTurns: false }); - if (typeof response !== "object" || response === null || !("thread" in response)) { - throw new Error("Codex thread/read did not return thread metadata"); - } - const thread = response.thread; - if (typeof thread !== "object" || thread === null || !("historyMode" in thread)) { - return "legacy"; - } - if (thread.historyMode === "legacy" || thread.historyMode === "paginated") { - return thread.historyMode; - } - throw new Error(`Codex thread/read returned unknown history mode ${String(thread.historyMode)}`); -} - async function forkCodexThread( client: CodexRewindClient, params: CodexThreadForkParams, @@ -95,7 +76,8 @@ export async function revertCodexConversation(input: { model: input.model ?? null, serviceTier: input.serviceTier ?? null, ...(input.config ? { config: input.config } : {}), - excludeTurns: false, + // Paseo re-reads the rewound thread through paged history, not the fork reply. + excludeTurns: true, persistExtendedHistory: true, }; diff --git a/packages/server/src/server/agent/providers/codex/test-utils/fake-app-server.ts b/packages/server/src/server/agent/providers/codex/test-utils/fake-app-server.ts index 226eeb9738..99e6a73050 100644 --- a/packages/server/src/server/agent/providers/codex/test-utils/fake-app-server.ts +++ b/packages/server/src/server/agent/providers/codex/test-utils/fake-app-server.ts @@ -3,6 +3,10 @@ import { EventEmitter } from "node:events"; import { PassThrough } from "node:stream"; import type { AgentSession, AgentStreamEvent } from "../../../agent-sdk-types.js"; +import { CODEX_PROVIDER_LINE_BYTES } from "../app-server-transport.js"; + +/** A handler result that the fake writes as a response line past the provider line cap. */ +export const OVERSIZED_RESPONSE = Symbol("oversized Codex response"); type JsonObject = Record; type FakeCodexAppServerHandler = (params: unknown) => unknown; @@ -229,8 +233,18 @@ export function createFakeCodexAppServer( return; } - Promise.resolve(handler(message.params)) + let response: unknown; + try { + response = handler(message.params); + } catch (error) { + response = Promise.reject(error); + } + Promise.resolve(response) .then((result) => { + if (result === OVERSIZED_RESPONSE) { + writeOversizedResponse(message.id as number); + return undefined; + } const rpcError = toJsonObject(result).__jsonRpcError; if (rpcError) { child.stdout.write(`${JSON.stringify({ id: message.id, error: rpcError })}\n`); @@ -313,6 +327,16 @@ export function createFakeCodexAppServer( }); } + // Codex writes `id` first, then a result past the provider line cap. + function writeOversizedResponse(id: number): void { + child.stdout.write(`{"id":${id},"result":{"data":[{"item":{"text":"`); + const chunk = Buffer.alloc(1024 * 1024, "x"); + for (let written = 0; written <= CODEX_PROVIDER_LINE_BYTES; written += chunk.byteLength) { + child.stdout.write(chunk); + } + child.stdout.write('"}}]}}\n'); + } + function writeNotification(method: string, params: JsonObject): void { child.stdout.write(`${JSON.stringify({ method, params })}\n`); } @@ -696,3 +720,81 @@ export function waitForProviderSubagent( ): Promise { return waitForNextEvent(session, "provider_subagent", (event) => event.event.id === id); } + +export interface FakeCodexHistoryTurn { + id: string; + startedAt?: number; + completedAt?: number; + items: JsonObject[]; +} + +export interface FakeCodexHistoryThread { + /** Omitted on Codex builds older than 0.143, which only have legacy history. */ + historyMode?: "legacy" | "paginated"; + turns: FakeCodexHistoryTurn[]; +} + +export interface FakeCodexHistoryOptions { + /** Any response carrying one of these items is written past the line cap. */ + oversizedItemIds?: string[]; +} + +/** + * Codex's persisted thread history: `thread/read` for metadata and legacy full + * reads, `thread/items/list` for paginated threads. Paginated threads reject + * the full read as Codex 0.145 and 0.146 do. + */ +export function fakeCodexThreadHistory( + threads: Record, + options: FakeCodexHistoryOptions = {}, +): Record { + const oversizedItemIds = new Set(options.oversizedItemIds ?? []); + const isOversized = (items: JsonObject[]) => + items.some((item) => oversizedItemIds.has(String(item.id))); + + function readThread(params: unknown): { id: string; thread: FakeCodexHistoryThread } { + const id = String(toJsonObject(params).threadId); + const thread = threads[id]; + if (!thread) throw new Error(`thread not found: ${id}`); + return { id, thread }; + } + + return { + "thread/read": (params) => { + const { id, thread } = readThread(params); + if (!toJsonObject(params).includeTurns) { + return { + thread: { id, ...(thread.historyMode ? { historyMode: thread.historyMode } : {}) }, + }; + } + if (thread.historyMode === "paginated") { + throw new Error("paginated threads do not support thread/read(includeTurns=true)"); + } + if (isOversized(thread.turns.flatMap((turn) => turn.items))) return OVERSIZED_RESPONSE; + return { thread: { id, turns: thread.turns } }; + }, + "thread/items/list": (params) => { + const { thread } = readThread(params); + if (thread.historyMode !== "paginated") { + throw new Error("thread/items/list is not supported for legacy threads"); + } + const request = toJsonObject(params); + // Codex records each item's own times; the fake gives every item its turn's. + const rows = thread.turns.flatMap((turn) => + turn.items.map((item) => ({ + turnId: turn.id, + item, + startedAtMs: turn.startedAt === undefined ? null : turn.startedAt * 1000, + completedAtMs: turn.completedAt === undefined ? null : turn.completedAt * 1000, + })), + ); + const limit = Math.min(typeof request.limit === "number" ? request.limit : 25, 100); + const start = + typeof request.cursor === "string" ? Number(request.cursor.slice("cursor-".length)) : 0; + const end = Math.min(rows.length, start + limit); + const data = rows.slice(start, end); + if (isOversized(data.map((row) => row.item))) return OVERSIZED_RESPONSE; + return { data, nextCursor: end < rows.length ? `cursor-${end}` : null }; + }, + }; +} diff --git a/packages/server/src/server/agent/providers/codex/thread-history.test.ts b/packages/server/src/server/agent/providers/codex/thread-history.test.ts new file mode 100644 index 0000000000..8d3d8fce3d --- /dev/null +++ b/packages/server/src/server/agent/providers/codex/thread-history.test.ts @@ -0,0 +1,220 @@ +import type { ChildProcessWithoutNullStreams } from "node:child_process"; +import { describe, expect, test } from "vitest"; + +import { createTestLogger } from "../../../../test-utils/test-logger.js"; +import type { AgentSession, AgentStreamEvent } from "../../agent-sdk-types.js"; +import { CodexAppServerAgentClient } from "../codex-app-server-agent.js"; +import { + createFakeCodexAppServer, + type FakeCodexAppServer, + type FakeCodexHistoryOptions, + type FakeCodexHistoryThread, + fakeCodexThreadHistory, +} from "./test-utils/fake-app-server.js"; + +function userItem(id: string, text: string) { + return { type: "userMessage", id, content: [{ type: "text", text }] }; +} + +function agentItem(id: string, text: string) { + return { type: "agentMessage", id, text }; +} + +async function openCodexThread( + thread: FakeCodexHistoryThread, + options?: FakeCodexHistoryOptions, +): Promise<{ appServer: FakeCodexAppServer; session: AgentSession }> { + const appServer = createFakeCodexAppServer( + fakeCodexThreadHistory({ "saved-thread": thread }, options), + ); + const provider = new CodexAppServerAgentClient(createTestLogger()); + const internals = provider as unknown as { + goalsEnabledPromise: Promise | null; + autoReviewEnabledPromise: Promise | null; + spawnAppServer: () => Promise; + }; + internals.goalsEnabledPromise = Promise.resolve(false); + internals.autoReviewEnabledPromise = Promise.resolve(false); + internals.spawnAppServer = async () => appServer.child; + const session = await provider.resumeSession({ sessionId: "saved-thread" }); + return { appServer, session }; +} + +async function readHistory(session: AgentSession): Promise { + const events: AgentStreamEvent[] = []; + for await (const event of session.streamHistory()) events.push(event); + return events; +} + +function timelineItems(events: AgentStreamEvent[]) { + return events.flatMap((event) => (event.type === "timeline" ? [event.item] : [])); +} + +function historyRequests(appServer: FakeCodexAppServer) { + return appServer + .requests() + .filter( + (request) => + request.method === "thread/read" || + request.method === "thread/turns/list" || + request.method === "thread/items/list", + ) + .map((request) => ({ method: request.method, params: request.params })); +} + +describe("Codex thread history", () => { + test("loads a paginated thread through pages", async () => { + const answers = Array.from({ length: 150 }, (_, index) => + agentItem(`agent-${index}`, `Answer ${index}`), + ); + const { appServer, session } = await openCodexThread({ + historyMode: "paginated", + turns: [ + { + id: "turn-1", + startedAt: 1_778_832_941, + completedAt: 1_778_833_000, + items: [userItem("user-1", "First"), ...answers.slice(0, 120)], + }, + { + id: "turn-2", + startedAt: 1_778_833_094, + completedAt: 1_778_833_100, + items: [userItem("user-2", "Second"), ...answers.slice(120)], + }, + ], + }); + try { + const events = await readHistory(session); + + expect(timelineItems(events)).toEqual([ + { type: "user_message", text: "First", messageId: "user-1" }, + ...answers.slice(0, 120).map((answer) => ({ + type: "assistant_message", + text: answer.text, + messageId: answer.id, + })), + { type: "user_message", text: "Second", messageId: "user-2" }, + ...answers.slice(120).map((answer) => ({ + type: "assistant_message", + text: answer.text, + messageId: answer.id, + })), + ]); + const timestamps = events.flatMap((event) => + event.type === "timeline" ? [event.timestamp] : [], + ); + expect(timestamps[0]).toBe("2026-05-15T08:15:41.000Z"); + expect(timestamps[1]).toBe("2026-05-15T08:16:40.000Z"); + expect(timestamps[121]).toBe("2026-05-15T08:18:14.000Z"); + const requests = historyRequests(appServer); + expect(requests).not.toContainEqual( + expect.objectContaining({ params: expect.objectContaining({ includeTurns: true }) }), + ); + const itemPages = requests.filter((request) => request.method === "thread/items/list"); + expect(itemPages.length).toBeGreaterThan(1); + for (const page of itemPages) { + expect(page.params).toMatchObject({ threadId: "saved-thread", sortDirection: "asc" }); + expect((page.params as { limit: number }).limit).toBeLessThanOrEqual(100); + } + } finally { + await session.close(); + } + appServer.assertNoErrors(); + }); + + test("loads a paginated thread whose full read Codex 0.145 rejects", async () => { + const { appServer, session } = await openCodexThread({ + historyMode: "paginated", + turns: [{ id: "turn-1", items: [userItem("user-1", "Hello"), agentItem("agent-1", "Hi")] }], + }); + try { + expect(timelineItems(await readHistory(session))).toEqual([ + { type: "user_message", text: "Hello", messageId: "user-1" }, + { type: "assistant_message", text: "Hi", messageId: "agent-1" }, + ]); + } finally { + await session.close(); + } + appServer.assertNoErrors(); + }); + + test("a page too big to send shows a warning row and stops loading", async () => { + const answers = Array.from({ length: 120 }, (_, index) => + agentItem(`agent-${index}`, `Answer ${index}`), + ); + const { appServer, session } = await openCodexThread( + { + historyMode: "paginated", + turns: [ + { id: "turn-1", items: [userItem("user-1", "One"), ...answers] }, + { id: "turn-2", items: [userItem("user-2", "Two"), agentItem("huge", "never sent")] }, + ], + }, + { oversizedItemIds: ["huge"] }, + ); + const loaded = [ + { type: "user_message", text: "One", messageId: "user-1" }, + ...answers.slice(0, 99).map((answer) => ({ + type: "assistant_message", + text: answer.text, + messageId: answer.id, + })), + { + type: "notification", + level: "warning", + message: "The rest of this Codex thread's history is too large to load.", + }, + ]; + try { + expect(timelineItems(await readHistory(session))).toEqual(loaded); + // The oversized reply failed only its own request; the session still answers. + expect(timelineItems(await readHistory(session))).toEqual(loaded); + } finally { + await session.close(); + } + appServer.assertNoErrors(); + }); + + test("loads a legacy thread that fits in one read", async () => { + const { appServer, session } = await openCodexThread({ + historyMode: "legacy", + turns: [{ id: "turn-1", items: [userItem("user-1", "Hello"), agentItem("agent-1", "Hi")] }], + }); + try { + expect(timelineItems(await readHistory(session))).toEqual([ + { type: "user_message", text: "Hello", messageId: "user-1" }, + { type: "assistant_message", text: "Hi", messageId: "agent-1" }, + ]); + expect(historyRequests(appServer).map((request) => request.method)).not.toContain( + "thread/items/list", + ); + } finally { + await session.close(); + } + appServer.assertNoErrors(); + }); + + test("a legacy thread too big for one read shows the migration command", async () => { + const { appServer, session } = await openCodexThread( + { + historyMode: "legacy", + turns: [{ id: "turn-1", items: [userItem("user-1", "Hello"), agentItem("huge", "x")] }], + }, + { oversizedItemIds: ["huge"] }, + ); + const migrationRow = { + type: "notification", + level: "warning", + message: expect.stringContaining("codex migrate-rollouts --apply --thread saved-thread"), + }; + try { + expect(timelineItems(await readHistory(session))).toEqual([migrationRow]); + // The session stays up for the user to prompt until they archive it to migrate. + expect(timelineItems(await readHistory(session))).toEqual([migrationRow]); + } finally { + await session.close(); + } + appServer.assertNoErrors(); + }); +}); diff --git a/packages/server/src/server/agent/providers/codex/thread-history.ts b/packages/server/src/server/agent/providers/codex/thread-history.ts new file mode 100644 index 0000000000..bf7461deb6 --- /dev/null +++ b/packages/server/src/server/agent/providers/codex/thread-history.ts @@ -0,0 +1,168 @@ +import { z } from "zod"; + +import { CodexAppServerResponseTooLargeError } from "./app-server-transport.js"; + +// Codex clamps history pages to 100 rows. +const PAGE_SIZE = 100; + +export interface CodexThreadHistoryClient { + request(method: string, params?: unknown): Promise; +} + +export type CodexThreadHistoryMode = "legacy" | "paginated"; + +export interface CodexHistoryRow { + item: unknown; + turnId: string | undefined; + /** The item's times on a paginated thread; its turn's on a legacy thread. */ + startedAt: unknown; + completedAt: unknown; +} + +/** A history reply over the line cap; the rows before it were already read. */ +export class CodexThreadHistoryTooLargeError extends Error { + constructor(message: string) { + super(message); + this.name = "CodexThreadHistoryTooLargeError"; + } +} + +const CodexThreadMetadataSchema = z + .object({ + thread: z.object({ historyMode: z.enum(["legacy", "paginated"]).optional() }).passthrough(), + }) + .passthrough(); + +const CodexLegacyThreadReadSchema = z + .object({ + thread: z + .object({ + turns: z + .array( + z + .object({ + id: z.string().optional(), + startedAt: z.unknown().optional(), + completedAt: z.unknown().optional(), + items: z.array(z.unknown()).default([]), + }) + .passthrough(), + ) + .default([]), + }) + .passthrough() + .default({ turns: [] }), + }) + .passthrough(); + +const CodexItemsPageSchema = z + .object({ + data: z.array( + z + .object({ + turnId: z.string(), + item: z.unknown(), + startedAtMs: z.number().nullable().optional(), + completedAtMs: z.number().nullable().optional(), + }) + .passthrough(), + ), + nextCursor: z.string().nullable().optional(), + }) + .passthrough(); + +/** Codex builds before 0.143 report no history mode; their threads are legacy. */ +export async function readCodexThreadHistoryMode( + client: CodexThreadHistoryClient, + threadId: string, +): Promise { + const response = CodexThreadMetadataSchema.parse( + await client.request("thread/read", { threadId, includeTurns: false }), + ); + return response.thread.historyMode ?? "legacy"; +} + +/** + * Reads a thread's persisted items in order. Paginated threads are read in + * pages; a legacy thread arrives in one `thread/read` reply, as Codex offers + * no pages for it. + */ +export async function* readCodexThreadHistory( + client: CodexThreadHistoryClient, + threadId: string, +): AsyncGenerator { + if ((await readCodexThreadHistoryMode(client, threadId)) === "paginated") { + yield* readPaginatedHistory(client, threadId); + } else { + yield* readLegacyHistory(client, threadId); + } +} + +async function* readLegacyHistory( + client: CodexThreadHistoryClient, + threadId: string, +): AsyncGenerator { + const response = await requestHistory( + client, + "thread/read", + { threadId, includeTurns: true }, + `This Codex thread's history is too large to load in one read. ` + + `To move it to paginated history, archive this agent, ` + + `run \`codex migrate-rollouts --apply --thread ${threadId}\` (Codex 0.148 or newer), ` + + `then unarchive the agent.`, + ); + for (const turn of CodexLegacyThreadReadSchema.parse(response).thread.turns) { + for (const item of turn.items) { + yield { item, turnId: turn.id, startedAt: turn.startedAt, completedAt: turn.completedAt }; + } + } +} + +async function* readPaginatedHistory( + client: CodexThreadHistoryClient, + threadId: string, +): AsyncGenerator { + const seenCursors = new Set(); + let cursor: string | undefined; + for (;;) { + const page = CodexItemsPageSchema.parse( + await requestHistory( + client, + "thread/items/list", + { threadId, limit: PAGE_SIZE, sortDirection: "asc", cursor }, + "The rest of this Codex thread's history is too large to load.", + ), + ); + for (const row of page.data) { + yield { + item: row.item, + turnId: row.turnId, + startedAt: row.startedAtMs, + completedAt: row.completedAtMs, + }; + } + if (page.nextCursor == null) return; + // Codex's own client guards against a cursor that does not advance. + if (seenCursors.has(page.nextCursor)) { + throw new Error(`Codex repeated history cursor for thread ${threadId}`); + } + seenCursors.add(page.nextCursor); + cursor = page.nextCursor; + } +} + +async function requestHistory( + client: CodexThreadHistoryClient, + method: string, + params: unknown, + tooLargeMessage: string, +): Promise { + try { + return await client.request(method, params); + } catch (error) { + if (error instanceof CodexAppServerResponseTooLargeError) { + throw new CodexThreadHistoryTooLargeError(tooLargeMessage); + } + throw error; + } +} diff --git a/packages/server/src/server/agent/providers/jsonl-frame-decoder.ts b/packages/server/src/server/agent/providers/jsonl-frame-decoder.ts index 8b1b9767de..ff8fa83489 100644 --- a/packages/server/src/server/agent/providers/jsonl-frame-decoder.ts +++ b/packages/server/src/server/agent/providers/jsonl-frame-decoder.ts @@ -1,10 +1,17 @@ // Provider-process stdout only; these are not app/daemon wire limits. export const JSONL_PROVIDER_LINE_BYTES = 64 * 1024 * 1024; +// Enough of an oversized line to read which response it was, e.g. `{"id":12,"result":`. +const OVERSIZED_LINE_HEAD_BYTES = 64; + export class ProviderStreamLimitError extends Error { readonly code = "PROVIDER_STREAM_LINE_TOO_LARGE"; - constructor(readonly limitBytes: number) { + constructor( + readonly limitBytes: number, + /** The first bytes of the oversized line; the rest is discarded unread. */ + readonly lineHead = "", + ) { super( `Provider stdout line exceeds ${limitBytes} bytes. Start a new thread or reduce the provider response size.`, ); @@ -12,10 +19,26 @@ export class ProviderStreamLimitError extends Error { } } -/** Admits raw UTF-8 bytes before retaining, decoding or joining a complete line. */ +function readLineHead(parts: Buffer[]): string { + const head: Buffer[] = []; + let bytes = 0; + for (const part of parts) { + if (bytes >= OVERSIZED_LINE_HEAD_BYTES) break; + head.push(part.subarray(0, OVERSIZED_LINE_HEAD_BYTES - bytes)); + bytes += head[head.length - 1].byteLength; + } + return Buffer.concat(head).toString("utf8"); +} + +/** + * Admits raw UTF-8 bytes before retaining, decoding or joining a complete line. + * An oversized line is reported with its head and skipped up to its newline; + * the owner closes the reader if the stream cannot continue without it. + */ export class ProviderLineReader { private parts: Buffer[] = []; private bytes = 0; + private skippingOversizedLine = false; private stopped = false; constructor( @@ -31,11 +54,20 @@ export class ProviderLineReader { while (start < buffer.byteLength && !this.stopped) { const newline = buffer.indexOf(10, start); const end = newline === -1 ? buffer.byteLength : newline; + if (this.skippingOversizedLine) { + if (newline === -1) return; + this.skippingOversizedLine = false; + start = newline + 1; + continue; + } const length = end - start; if (length > this.limitBytes - this.bytes) { - this.close(); - this.onLimit(new ProviderStreamLimitError(this.limitBytes)); - return; + const head = readLineHead([...this.parts, buffer.subarray(start, end)]); + this.parts = []; + this.bytes = 0; + this.skippingOversizedLine = true; + this.onLimit(new ProviderStreamLimitError(this.limitBytes, head)); + continue; } if (length) this.parts.push(buffer.subarray(start, end)); this.bytes += length; @@ -150,7 +182,10 @@ export class JsonlFrameDecoder { (line) => { if (line.trim()) this.consumeLine(line); }, - (error) => this.drop("line-too-large", error), + (error) => { + this.lines.close(); + this.drop("line-too-large", error); + }, ); } From a8e0effb325d07dbe02a998b6ff6fce623b3fec1 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Fri, 30 Oct 2026 13:42:38 +0700 Subject: [PATCH 120/173] Follow system rotation on mobile devices (#8256) The app no longer locks to portrait. Phones and tablets on Android and iOS follow the device rotation and respect the system rotation lock, so Android tablets fill the display in landscape instead of letterboxing. Modals pass all orientations explicitly because React Native presents iPhone modals in portrait by default. Closes #1669 Co-authored-by: yz <43207690+yzim@users.noreply.github.com> Co-authored-by: magiclaw <930198090@qq.com> --- packages/app/app.config.js | 2 +- packages/app/app.config.test.ts | 35 +++++++++++++++++++ .../app/src/command-center/command-center.tsx | 2 +- .../app/src/components/add-project-flow.tsx | 10 ++---- packages/app/src/components/agent-list.tsx | 2 +- .../src/components/attachment-lightbox.tsx | 3 +- .../fence/mermaid/fullscreen-viewer.web.tsx | 3 +- .../markdown/fence/mermaid/host.native.tsx | 2 +- packages/app/src/components/ui/combobox.tsx | 2 +- .../src/components/ui/menu/menu-overlay.tsx | 2 +- packages/app/src/components/ui/modal.tsx | 13 +++++++ packages/app/src/components/ui/tooltip.tsx | 2 +- packages/app/src/hosts/host-chooser.tsx | 10 ++---- 13 files changed, 63 insertions(+), 25 deletions(-) create mode 100644 packages/app/src/components/ui/modal.tsx diff --git a/packages/app/app.config.js b/packages/app/app.config.js index 7ddfc95029..eb7907e5ce 100644 --- a/packages/app/app.config.js +++ b/packages/app/app.config.js @@ -102,7 +102,7 @@ export default { name: variant.name, slug: "voice-mobile", version: nativeReleaseVersion.appVersion, - orientation: "portrait", + orientation: "default", icon: "./assets/images/icon.png", scheme: "paseo", userInterfaceStyle: "automatic", diff --git a/packages/app/app.config.test.ts b/packages/app/app.config.test.ts index b98258ff9a..d0de16bd03 100644 --- a/packages/app/app.config.test.ts +++ b/packages/app/app.config.test.ts @@ -59,3 +59,38 @@ describe("Android app config", () => { 30_000, ); }); + +it("follows system rotation on Android", async () => { + const manifest = await resolveAndroidManifest(); + const activity = manifest.application[0].activity.find( + (entry: ManifestEntry) => entry.$["android:name"] === ".MainActivity", + ); + expect(activity.$["android:screenOrientation"]).toBe("unspecified"); +}, 30_000); + +it("allows all orientations on iPhone and iPad", async () => { + const { mkdtemp, rm } = await import("node:fs/promises"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const root = await mkdtemp(join(tmpdir(), "paseo-ios-config-")); + try { + const { exp } = await getPrebuildConfigAsync(__dirname, { platforms: ["ios"] }); + await compileModsAsync(exp, { + projectRoot: root, + introspect: true, + platforms: ["ios"], + assertMissingModProviders: false, + }); + const plist = exp._internal.modResults.ios.infoPlist; + const orientations = [ + "UIInterfaceOrientationPortrait", + "UIInterfaceOrientationPortraitUpsideDown", + "UIInterfaceOrientationLandscapeLeft", + "UIInterfaceOrientationLandscapeRight", + ]; + expect(plist.UISupportedInterfaceOrientations).toEqual(orientations); + expect(plist["UISupportedInterfaceOrientations~ipad"]).toEqual(orientations); + } finally { + await rm(root, { recursive: true, force: true }); + } +}, 30_000); diff --git a/packages/app/src/command-center/command-center.tsx b/packages/app/src/command-center/command-center.tsx index 7a44f8ccd9..309564bcea 100644 --- a/packages/app/src/command-center/command-center.tsx +++ b/packages/app/src/command-center/command-center.tsx @@ -1,8 +1,8 @@ +import { Modal } from "@/components/ui/modal"; import equal from "fast-deep-equal"; import { recordRenderProfileReasons } from "@/utils/render-profiler"; import { FlatList, - Modal, Pressable, Text, View, diff --git a/packages/app/src/components/add-project-flow.tsx b/packages/app/src/components/add-project-flow.tsx index a1cb5cf779..7fdf21dd83 100644 --- a/packages/app/src/components/add-project-flow.tsx +++ b/packages/app/src/components/add-project-flow.tsx @@ -1,3 +1,4 @@ +import { Modal } from "@/components/ui/modal"; import { usePanelStore } from "@/stores/panel-store"; import { getHostRuntimeStore } from "@/runtime/host-runtime"; import { router } from "expo-router"; @@ -22,14 +23,7 @@ import { type ComponentType, type RefObject, } from "react"; -import { - Modal, - Pressable, - ScrollView, - Text, - View, - type PressableStateCallbackType, -} from "react-native"; +import { Pressable, ScrollView, Text, View, type PressableStateCallbackType } from "react-native"; import { EditingTextInput as TextInput, type EditingTextInputHandle, diff --git a/packages/app/src/components/agent-list.tsx b/packages/app/src/components/agent-list.tsx index b487e53660..8921102f26 100644 --- a/packages/app/src/components/agent-list.tsx +++ b/packages/app/src/components/agent-list.tsx @@ -1,8 +1,8 @@ +import { Modal } from "@/components/ui/modal"; import { View, Text, Pressable, - Modal, RefreshControl, FlatList, type ListRenderItem, diff --git a/packages/app/src/components/attachment-lightbox.tsx b/packages/app/src/components/attachment-lightbox.tsx index 0f14f2c515..08c6042bf8 100644 --- a/packages/app/src/components/attachment-lightbox.tsx +++ b/packages/app/src/components/attachment-lightbox.tsx @@ -1,5 +1,6 @@ +import { Modal } from "@/components/ui/modal"; import { type ReactNode, useCallback, useEffect, useMemo, useState } from "react"; -import { Modal, Pressable, Text, View } from "react-native"; +import { Pressable, Text, View } from "react-native"; import { GestureHandlerRootView } from "react-native-gesture-handler"; import { StyleSheet } from "react-native-unistyles"; import { SafeAreaProvider, useSafeAreaInsets } from "react-native-safe-area-context"; diff --git a/packages/app/src/components/markdown/fence/mermaid/fullscreen-viewer.web.tsx b/packages/app/src/components/markdown/fence/mermaid/fullscreen-viewer.web.tsx index 8b68ae61cb..02ca7108d8 100644 --- a/packages/app/src/components/markdown/fence/mermaid/fullscreen-viewer.web.tsx +++ b/packages/app/src/components/markdown/fence/mermaid/fullscreen-viewer.web.tsx @@ -1,5 +1,6 @@ +import { Modal } from "@/components/ui/modal"; import { useCallback, useEffect, useMemo, useRef } from "react"; -import { Modal, View } from "react-native"; +import { View } from "react-native"; import { X } from "lucide-react-native"; import { useTranslation } from "react-i18next"; import { StyleSheet } from "react-native-unistyles"; diff --git a/packages/app/src/components/markdown/fence/mermaid/host.native.tsx b/packages/app/src/components/markdown/fence/mermaid/host.native.tsx index 001ec5cf1c..5f86efe05c 100644 --- a/packages/app/src/components/markdown/fence/mermaid/host.native.tsx +++ b/packages/app/src/components/markdown/fence/mermaid/host.native.tsx @@ -1,6 +1,6 @@ +import { Modal } from "@/components/ui/modal"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { - Modal, Pressable, StyleSheet as RNStyleSheet, ScrollView, diff --git a/packages/app/src/components/ui/combobox.tsx b/packages/app/src/components/ui/combobox.tsx index d436758d45..adcd91afcb 100644 --- a/packages/app/src/components/ui/combobox.tsx +++ b/packages/app/src/components/ui/combobox.tsx @@ -1,3 +1,4 @@ +import { Modal } from "@/components/ui/modal"; import { useCallback, useEffect, @@ -12,7 +13,6 @@ import { View, Text, Pressable, - Modal, ScrollView, Platform, StatusBar, diff --git a/packages/app/src/components/ui/menu/menu-overlay.tsx b/packages/app/src/components/ui/menu/menu-overlay.tsx index c6935bfd91..3979c5b633 100644 --- a/packages/app/src/components/ui/menu/menu-overlay.tsx +++ b/packages/app/src/components/ui/menu/menu-overlay.tsx @@ -1,3 +1,4 @@ +import { Modal } from "@/components/ui/modal"; import { useCallback, useEffect, @@ -12,7 +13,6 @@ import { createPortal } from "react-dom"; import { useTranslation } from "react-i18next"; import { Dimensions, - Modal, Platform, Pressable, View, diff --git a/packages/app/src/components/ui/modal.tsx b/packages/app/src/components/ui/modal.tsx new file mode 100644 index 0000000000..884377fd8c --- /dev/null +++ b/packages/app/src/components/ui/modal.tsx @@ -0,0 +1,13 @@ +import { Modal as NativeModal, type ModalProps } from "react-native"; + +// React Native defaults iPhone modals to portrait even when the app supports rotation. +const orientations: NonNullable = [ + "portrait", + "portrait-upside-down", + "landscape-left", + "landscape-right", +]; + +export function Modal(props: ModalProps) { + return ; +} diff --git a/packages/app/src/components/ui/tooltip.tsx b/packages/app/src/components/ui/tooltip.tsx index 697a80fdcf..99f446001f 100644 --- a/packages/app/src/components/ui/tooltip.tsx +++ b/packages/app/src/components/ui/tooltip.tsx @@ -1,3 +1,4 @@ +import { Modal } from "@/components/ui/modal"; import { Children, cloneElement, @@ -16,7 +17,6 @@ import { createPortal } from "react-dom"; import { Dimensions, Platform, - Modal, Pressable, View, type PressableProps, diff --git a/packages/app/src/hosts/host-chooser.tsx b/packages/app/src/hosts/host-chooser.tsx index 5e4d7f053c..3d807ba3a1 100644 --- a/packages/app/src/hosts/host-chooser.tsx +++ b/packages/app/src/hosts/host-chooser.tsx @@ -1,13 +1,7 @@ +import { Modal } from "@/components/ui/modal"; import { usePanelStore } from "@/stores/panel-store"; import { createElement, useCallback, useEffect, useMemo, useRef, useState } from "react"; -import { - Modal, - Pressable, - ScrollView, - Text, - View, - type PressableStateCallbackType, -} from "react-native"; +import { Pressable, ScrollView, Text, View, type PressableStateCallbackType } from "react-native"; import { EditingTextInput as TextInput, type EditingTextInputHandle, From e3682ba18c20b1f5f5b0b29d14e2e29fdb1a0dc0 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Fri, 30 Oct 2026 14:32:19 +0700 Subject: [PATCH 121/173] Usage fetches only when shown, and can be turned off (#8181) * fix(usage): fetch only when shown and add a host-wide off switch * fix(usage): restore policy defaults and isolate usage test state * refactor(usage): give the sidebar footer sole ownership of its summary --- docs/glossary.md | 1 + docs/plugins.md | 2 +- packages/app/e2e/browser/usage-off.spec.ts | 69 +++++++++++++++++++ .../e2e/browser/usage-sidebar-item.spec.ts | 28 ++++++++ .../app/e2e/support/helpers/seed-client.ts | 4 ++ .../app/e2e/support/helpers/usage-reports.ts | 10 ++- packages/app/src/components/left-sidebar.tsx | 13 ++-- packages/app/src/i18n/resources/ar.ts | 5 ++ packages/app/src/i18n/resources/en.ts | 5 ++ packages/app/src/i18n/resources/es.ts | 5 ++ packages/app/src/i18n/resources/fr.ts | 5 ++ packages/app/src/i18n/resources/ja.ts | 5 ++ packages/app/src/i18n/resources/ko.ts | 5 ++ packages/app/src/i18n/resources/pt-BR.ts | 5 ++ packages/app/src/i18n/resources/ru.ts | 5 ++ packages/app/src/i18n/resources/zh-CN.ts | 5 ++ packages/app/src/usage/controls.tsx | 13 +++- packages/app/src/usage/display.ts | 8 --- packages/app/src/usage/host-usage-section.tsx | 4 +- packages/app/src/usage/index.ts | 2 +- packages/app/src/usage/model.test.ts | 12 ++++ packages/app/src/usage/model.ts | 3 + packages/app/src/usage/options.tsx | 37 +++++++--- packages/app/src/usage/queries.ts | 12 +++- packages/app/src/usage/setting.ts | 26 +++++++ packages/app/src/usage/sidebar-item.tsx | 19 +++-- packages/app/src/usage/types.ts | 1 + packages/app/src/usage/usage-modal.tsx | 4 +- packages/app/src/usage/usage-section.tsx | 14 +++- packages/protocol/src/messages.ts | 5 ++ packages/server/src/server/bootstrap.ts | 2 + packages/server/src/server/config.ts | 6 ++ .../src/server/daemon-config-store.test.ts | 33 +++++++++ .../server/src/server/daemon-config-store.ts | 5 ++ .../server/src/server/persisted-config.ts | 1 + packages/server/src/server/session.ts | 1 + .../session/usage/usage-session.test.ts | 36 ++++++++++ .../src/server/session/usage/usage-session.ts | 14 ++++ .../server/src/server/websocket-server.ts | 1 + .../public/schemas/paseo.config.v1.json | 8 +++ 40 files changed, 386 insertions(+), 53 deletions(-) create mode 100644 packages/app/e2e/browser/usage-off.spec.ts create mode 100644 packages/app/src/usage/setting.ts diff --git a/docs/glossary.md b/docs/glossary.md index 8c9f54896c..c7fd1398c5 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -38,6 +38,7 @@ Authoritative terminology. UI label wins. Don't invent synonyms; use what's here - **Usage source** — Plugin registration that discovers accounts and fetches plan usage. Code: `UsageSourceRegistration` (`packages/plugin/src/server/usage.ts`). - **Report ID** — Stable daemon-composed identity for one source account: `:`. The source owns the account key; clients treat the whole ID as opaque. Code: `UsageReportEntry.id` (`packages/protocol/src/messages.ts`). - **Usage report** — A source's normalized usage for one account, including status and optional windows, balances, and details. Its entry carries the Report ID, account label, and fetch time. Each report renders as one card in the Usage modal, in host Settings, and in an agent's context window details (a hover card on desktop web, a tooltip on native wide screens, a sheet on compact ones), which show only the account that agent runs under, without pins. The hover card and the sheet have Refresh; the native tooltip takes no presses. Code: `UsageReport` (`packages/plugin/src/server/usage.ts`), `UsageCard` (`packages/app/src/usage/card.tsx`), `AgentUsage` (`packages/app/src/usage/agent-usage.tsx`). +- **Check usage** — Host-wide switch in Usage Settings, on by default. Turning it off stops login discovery and vendor requests on that host for every device. Usage shows an off state with **Turn on**; the sidebar summary and agent usage sections disappear. - **Usage (sidebar item)** — The sidebar footer item showing each pinned window's source icon and percent, hidden while no pinned window has data (the footer's Usage icon remains available); both entry points open the Usage modal over the current screen: a dialog on wide layouts, a bottom sheet on compact ones. Usage has no route of its own. Off until the user turns on **Summary in sidebar** (Usage Settings) or the Usage row in Settings > Sidebar; window rows pin only while it is on, and saved pins come back when it is turned on again. A pin is `{ sourceId, windowId }` and shows once per account of that source. Pins and the used/remaining choice are one per-device preference (`AppSettings.usage`) that every usage surface follows. It reads the active workspace's host, else the first connected host with usage sources. Code: `packages/app/src/usage/sidebar-item.tsx`, `usage/usage-modal.tsx`, `usage/pinned.ts`, `usage/preferences.ts`. - **Model** — A specific LLM offered by a provider. UI: "Model" / "Select model". Code: `AgentModelDefinition` (`packages/protocol/src/messages.ts:187`). - **Tab** — UI surface representing one session inside a workspace. Not a conceptual unit; use **Agent session** when talking about the model. Code: `WorkspaceTabDescriptor` (`packages/app/src/screens/workspace/workspace-tabs-types.ts`). diff --git a/docs/plugins.md b/docs/plugins.md index fcc7ed7fdb..ffae136cc6 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -550,7 +550,7 @@ string is never inline SVG or a URL. Register a usage source from `index.server.ts` with `server.registerUsageSource()`. Import `UsageSourceRegistration` and normalization helpers from `@getpaseo/plugin/server/usage`. The plugin owns account discovery, harness labels, and credential-store reads; the daemon owns account grouping and the fetch cache. Agent popovers use only the agent's own login. The host-wide Usage modal falls back across an account's logins; any success shows usage only, and all failures show every login's labeled error and remedy. Follow the [usage source discovery contract](../public-docs/plugins/reference.md#usage-sources). The resolved launch environment crosses into the trusted, unsandboxed plugin subprocess for session discovery. Usage queries never run lifecycle hooks. Inputs are validated in the plugin process and remain daemon-side. `icon` uses the same SVG file rules as provider icons. -The daemon calls discovery for `usage.list_reports`; the client gates this RPC on `server_info.features.usageSources`. The old `provider.usage.list` RPC maps discovered reports for older clients. +When the host’s **Check usage** switch is off, the daemon rejects usage requests before discovery, without reading logins or calling vendors. Otherwise, the daemon calls discovery for `usage.list_reports`; the client gates this RPC on `server_info.features.usageSources`. The old `provider.usage.list` RPC maps discovered reports for older clients. ## Contribute sidebar items diff --git a/packages/app/e2e/browser/usage-off.spec.ts b/packages/app/e2e/browser/usage-off.spec.ts new file mode 100644 index 0000000000..a0114c8e33 --- /dev/null +++ b/packages/app/e2e/browser/usage-off.spec.ts @@ -0,0 +1,69 @@ +import { expect, test } from "../support/fixtures"; +import { gotoAppShell } from "../support/helpers/app"; +import { seedSidebarFooterPreferences } from "../support/helpers/sidebar-nav-settings"; +import { installUsageReportsFixture } from "../support/helpers/usage-reports"; +import { + claudeAndCodexReports, + openUsageFromIcon, + openUsageOptions, + closeUsageOptions, + closeUsage, + expectNoUsageItem, + expectPinnedUsage, +} from "../support/helpers/usage-sidebar-item"; + +test("Check usage applies to the host and Turn on restores cards", async ({ + page, + e2eWorkerClient, +}) => { + test.setTimeout(180_000); + const previous = (await e2eWorkerClient.getDaemonConfig()).config.usage ?? { enabled: true }; + try { + const usage = await installUsageReportsFixture(page, { + lists: [() => claudeAndCodexReports()], + }); + await page.setViewportSize({ width: 1440, height: 1000 }); + await seedSidebarFooterPreferences(page, [{ key: "usage", visible: true }]); + await gotoAppShell(page); + await expectPinnedUsage(page, ["31% 5h", "54% wk", "7% 5h", "12% wk"]); + await openUsageFromIcon(page); + await usage.waitForListRequests(1); + await openUsageOptions(page); + await page.getByRole("switch", { name: "Check usage", exact: true }).click(); + await closeUsageOptions(page); + await expect(page.getByRole("button", { name: "Turn on", exact: true })).toBeVisible(); + await expect(page.getByRole("button", { name: "Refresh all", exact: true })).toHaveCount(0); + expect((await e2eWorkerClient.getDaemonConfig()).config.usage).toEqual({ enabled: false }); + await expectNoUsageItem(page); + const before = usage.listRequests().length; + await closeUsage(page); + await page.reload(); + await openUsageFromIcon(page); + await expect(page.getByRole("button", { name: "Turn on", exact: true })).toBeVisible(); + expect(usage.listRequests()).toHaveLength(before); + await page.getByRole("button", { name: "Turn on", exact: true }).click(); + await expect(page.getByText("Claude", { exact: true })).toBeVisible(); + expect((await e2eWorkerClient.getDaemonConfig()).config.usage).toEqual({ enabled: true }); + // A separate client changes the policy, as another device would. + await e2eWorkerClient.patchDaemonConfig({ usage: { enabled: false } }); + await expect(page.getByRole("button", { name: "Turn on", exact: true })).toBeVisible(); + await e2eWorkerClient.patchDaemonConfig({ usage: { enabled: true } }); + await expect(page.getByText("Claude", { exact: true })).toBeVisible(); + } finally { + await e2eWorkerClient.patchDaemonConfig({ usage: previous }); + } +}); + +test("older hosts keep usage without a Check usage switch", async ({ page }) => { + test.setTimeout(180_000); + await installUsageReportsFixture(page, { + usageSettingSupported: false, + lists: [() => claudeAndCodexReports()], + }); + await page.setViewportSize({ width: 1440, height: 1000 }); + await gotoAppShell(page); + await openUsageFromIcon(page); + await expect(page.getByText("Claude", { exact: true })).toBeVisible(); + await openUsageOptions(page); + await expect(page.getByRole("switch", { name: "Check usage", exact: true })).toHaveCount(0); +}); diff --git a/packages/app/e2e/browser/usage-sidebar-item.spec.ts b/packages/app/e2e/browser/usage-sidebar-item.spec.ts index 27fac6691c..9151403904 100644 --- a/packages/app/e2e/browser/usage-sidebar-item.spec.ts +++ b/packages/app/e2e/browser/usage-sidebar-item.spec.ts @@ -441,3 +441,31 @@ test("released hosts supply source logos through the client conversion", async ( ).toHaveAttribute("d", codexPath); await qaScreenshot(page, "released-host-usage-modal"); }); + +test("hidden usage sends no requests until opened", async ({ page }) => { + test.setTimeout(180_000); + const usage = await installUsageReportsFixture(page, { lists: [() => claudeAndCodexReports()] }); + await page.setViewportSize(WIDE); + await gotoAppShell(page); + await expectNoUsageItem(page); + await expect(page.getByRole("button", { name: "Usage", exact: true })).toBeVisible({ + timeout: 90_000, + }); + await openSidebarNavSettings(page); + await expectFooterItemSetting(page, "usage", false); + await leaveSettings(page); + expect(usage.listRequests()).toHaveLength(0); + await openUsageFromIcon(page); + await usage.waitForListRequests(1); + expect(usage.listRequests()).toHaveLength(1); +}); + +test("visible usage summary requests reports on load", async ({ page }) => { + test.setTimeout(180_000); + const usage = await installUsageReportsFixture(page, { lists: [() => claudeAndCodexReports()] }); + await seedSidebarFooterPreferences(page, [{ key: "usage", visible: true }]); + await page.setViewportSize(WIDE); + await gotoAppShell(page); + await expectPinnedUsage(page, ["31% 5h", "54% wk", "7% 5h", "12% wk"]); + expect(usage.listRequests()).toHaveLength(1); +}); diff --git a/packages/app/e2e/support/helpers/seed-client.ts b/packages/app/e2e/support/helpers/seed-client.ts index f57beb5783..fe6af133f9 100644 --- a/packages/app/e2e/support/helpers/seed-client.ts +++ b/packages/app/e2e/support/helpers/seed-client.ts @@ -28,6 +28,10 @@ interface SeedProjectDescriptor { * prefer those wrappers over reaching for this client directly. */ export interface SeedDaemonClient { + patchDaemonConfig( + config: import("@getpaseo/protocol/messages").MutableDaemonConfigPatch, + ): Promise<{ config: import("@getpaseo/protocol/messages").MutableDaemonConfig }>; + getDaemonConfig(): Promise<{ config: import("@getpaseo/protocol/messages").MutableDaemonConfig }>; connect(): Promise; close(): Promise; addProject(cwd: string): Promise<{ diff --git a/packages/app/e2e/support/helpers/usage-reports.ts b/packages/app/e2e/support/helpers/usage-reports.ts index 86b74c6ea3..bb46e52f95 100644 --- a/packages/app/e2e/support/helpers/usage-reports.ts +++ b/packages/app/e2e/support/helpers/usage-reports.ts @@ -25,6 +25,7 @@ interface UsageReportsFixtureOptions { * app connects, so a reload can switch it. */ usageSupported?: boolean | (() => boolean); + usageSettingSupported?: boolean; /** Released hosts expose provider.usage.list with no source icons. */ providerUsageListOnly?: boolean; /** The host daemon's port; defaults to the E2E daemon. */ @@ -63,6 +64,7 @@ function withUsageSupportFeature( message: WebSocketMessage, enabled: boolean, providerUsageListOnly: boolean, + usageSettingSupported: boolean, ): string | null { const envelope = parseJson(message) as { type?: unknown; @@ -86,6 +88,7 @@ function withUsageSupportFeature( ...payload, features: { ...features, + usageSetting: usageSettingSupported ? true : undefined, usageSources: enabled && !providerUsageListOnly, providerUsageList: enabled, }, @@ -229,7 +232,12 @@ export async function installUsageReportsFixture( server.onMessage((message) => { const serverInfo = typeof message === "string" - ? withUsageSupportFeature(message, isUsageSupported(), providerUsageListOnly) + ? withUsageSupportFeature( + message, + isUsageSupported(), + providerUsageListOnly, + options.usageSettingSupported ?? true, + ) : null; ws.send(serverInfo ?? message); }); diff --git a/packages/app/src/components/left-sidebar.tsx b/packages/app/src/components/left-sidebar.tsx index dbc501b5c7..983d142beb 100644 --- a/packages/app/src/components/left-sidebar.tsx +++ b/packages/app/src/components/left-sidebar.tsx @@ -64,12 +64,7 @@ import { useCloseAgentListGesture } from "@/mobile-panels/gestures"; import { MobilePanelOverlay } from "@/mobile-panels/presentation"; import { buildSettingsAddHostRoute, buildSettingsRoute } from "@/utils/host-routes"; import { openHostOverview } from "@/navigation/settings-navigation"; -import { - UsageSidebarItem, - UsageSidebarRoot, - useHasUsageSummary, - useOpenSidebarUsage, -} from "@/usage"; +import { UsageSidebarItem, UsageSidebarRoot, useUsageSummary, useOpenSidebarUsage } from "@/usage"; import { SidebarAgentListSkeleton } from "./sidebar-agent-list-skeleton"; import { SidebarCalloutSlot } from "./sidebar-callout-slot"; import { SidebarWorkspaceList } from "./sidebar-workspace-list"; @@ -480,10 +475,10 @@ function SidebarUsageIcon({ label }: { label: string }) { */ function SidebarFooterRows({ onBeforeNavigate }: { onBeforeNavigate?: () => void }) { const { items } = useSidebarNavItems("footer"); - const hasUsageSummary = useHasUsageSummary(); + const usageSummary = useUsageSummary(); const rowsRef = useRef(null); const visibleItems = items.filter( - (item) => item.visible && (item.kind === "plugin" || hasUsageSummary), + (item) => item.visible && (item.kind === "plugin" || usageSummary.length > 0), ); if (visibleItems.length === 0) return null; return ( @@ -499,7 +494,7 @@ function SidebarFooterRows({ onBeforeNavigate }: { onBeforeNavigate?: () => void onBeforeNavigate={onBeforeNavigate} /> ) : ( - + ), )} diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index 1cb6f0da06..99d5a11701 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -2092,6 +2092,11 @@ export const ar: TranslationResources = { }, }, providerUsage: { + checkUsage: "التحقق من الاستخدام", + checkUsageHint: "ينطبق على {{host}} على جميع الأجهزة", + off: "التحقق من الاستخدام متوقف على {{host}}.", + turnOn: "تشغيل", + options: "الإعدادات", refreshFailed: "تعذّر تحديث الاستخدام", noHosts: "لا توجد مضيفات متصلة", diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index 0511af34e2..636fe42d5a 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -2117,6 +2117,11 @@ export const en = { }, }, providerUsage: { + checkUsage: "Check usage", + checkUsageHint: "Applies to {{host}} on every device", + off: "Usage is off on {{host}}.", + turnOn: "Turn on", + options: "Settings", refreshFailed: "Unable to refresh usage", noHosts: "No connected hosts", diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index ffe9cedc1e..abd5320fe9 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -2140,6 +2140,11 @@ export const es: TranslationResources = { }, }, providerUsage: { + checkUsage: "Consultar uso", + checkUsageHint: "Se aplica a {{host}} en todos los dispositivos", + off: "El uso está desactivado en {{host}}.", + turnOn: "Activar", + options: "Configuración", refreshFailed: "No se pudo actualizar el uso", noHosts: "No hay hosts conectados", diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index 6c9df18211..848666b2bb 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -2140,6 +2140,11 @@ export const fr: TranslationResources = { }, }, providerUsage: { + checkUsage: "Vérifier l’utilisation", + checkUsageHint: "S’applique à {{host}} sur tous les appareils", + off: "L’utilisation est désactivée sur {{host}}.", + turnOn: "Activer", + options: "Paramètres", refreshFailed: "Impossible d’actualiser l’utilisation", noHosts: "Aucun hôte connecté", diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index dd214ebac9..eb6423913e 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -2113,6 +2113,11 @@ export const ja: TranslationResources = { }, }, providerUsage: { + checkUsage: "使用状況を確認", + checkUsageHint: "すべてのデバイスで {{host}} に適用", + off: "{{host}} の使用状況確認はオフです。", + turnOn: "オンにする", + options: "設定", refreshFailed: "使用状況を更新できません", noHosts: "接続中のホストがありません", diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index d30635b2a5..54605df4a6 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -2102,6 +2102,11 @@ export const ko: TranslationResources = { }, }, providerUsage: { + checkUsage: "사용량 확인", + checkUsageHint: "모든 기기에서 {{host}}에 적용", + off: "{{host}}의 사용량 확인이 꺼져 있습니다.", + turnOn: "켜기", + options: "설정", refreshFailed: "사용량을 새로 고칠 수 없습니다", noHosts: "연결된 호스트가 없습니다", diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index 1d9ce0cb95..ecedcb5c9e 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -2125,6 +2125,11 @@ export const ptBR: TranslationResources = { }, }, providerUsage: { + checkUsage: "Consultar uso", + checkUsageHint: "Aplica-se a {{host}} em todos os dispositivos", + off: "O uso está desativado em {{host}}.", + turnOn: "Ativar", + options: "Configurações", refreshFailed: "Não foi possível atualizar o uso", noHosts: "Nenhum host conectado", diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index 766f8bdae7..d9c7afdedd 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -2125,6 +2125,11 @@ export const ru: TranslationResources = { }, }, providerUsage: { + checkUsage: "Проверять использование", + checkUsageHint: "Применяется к {{host}} на всех устройствах", + off: "Проверка использования отключена на {{host}}.", + turnOn: "Включить", + options: "Настройки", refreshFailed: "Не удалось обновить использование", noHosts: "Нет подключённых хостов", diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index 64867d7d21..e0b5bbcdb4 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -2070,6 +2070,11 @@ export const zhCN: TranslationResources = { }, }, providerUsage: { + checkUsage: "检查用量", + checkUsageHint: "在所有设备上应用于 {{host}}", + off: "{{host}} 的用量检查已关闭。", + turnOn: "开启", + options: "设置", refreshFailed: "无法刷新用量", noHosts: "没有已连接的主机", diff --git a/packages/app/src/usage/controls.tsx b/packages/app/src/usage/controls.tsx index 20297c9df0..f0a8c73f5e 100644 --- a/packages/app/src/usage/controls.tsx +++ b/packages/app/src/usage/controls.tsx @@ -21,10 +21,12 @@ export interface UsageHostSelection { */ export function UsageControls({ view, + serverId, onRefresh, hostSelection, }: { view: UsageView; + serverId: string; onRefresh: () => void; hostSelection?: UsageHostSelection; }) { @@ -43,8 +45,8 @@ export function UsageControls({ ) : null} {view.kind === "unavailable" ? null : ( <> - - + {view.kind === "off" ? null : } + )}
@@ -84,7 +86,12 @@ export function useHostUsageWithControls(hostSelection: UsageHostSelection): { const controls = useMemo( () => hasControls ? ( - + ) : null, [hasControls, hostSelection, refresh, view], ); diff --git a/packages/app/src/usage/display.ts b/packages/app/src/usage/display.ts index 5b4e534693..c62ed78fd7 100644 --- a/packages/app/src/usage/display.ts +++ b/packages/app/src/usage/display.ts @@ -1,7 +1,5 @@ import { useCallback, useMemo } from "react"; import { useAppSettings } from "@/hooks/use-settings"; -import { useUsageHostId } from "./hosts"; -import { useUsageHostReports } from "./queries"; import { isUsagePinned, setUsageDisplayAs, @@ -25,12 +23,6 @@ interface UsagePreferencesState { display: UsageDisplay; } -/** The device's usage preferences, with pins resolved against a host's reports. */ -export function useUsagePreferences(serverId?: string): UsagePreferencesState { - const defaultServerId = useUsageHostId(); - return useUsageDisplay(useUsageHostReports(serverId ?? defaultServerId)); -} - /** The device's usage preferences, with pins resolved against the given reports. */ export function useUsageDisplay(reports: readonly UsageReportEntry[]): UsagePreferencesState { const { settings, updateSettings } = useAppSettings(); diff --git a/packages/app/src/usage/host-usage-section.tsx b/packages/app/src/usage/host-usage-section.tsx index e80e839680..4921c7f954 100644 --- a/packages/app/src/usage/host-usage-section.tsx +++ b/packages/app/src/usage/host-usage-section.tsx @@ -1,5 +1,5 @@ import { useTranslation } from "react-i18next"; -import { useUsagePreferences } from "./display"; +import { useUsageDisplay } from "./display"; import { useHostUsage } from "./queries"; import { UsageSection } from "./usage-section"; @@ -7,7 +7,7 @@ import { UsageSection } from "./usage-section"; export function HostUsageSection({ serverId }: { serverId: string }) { const { t } = useTranslation(); const { view, refresh } = useHostUsage(serverId); - const { display } = useUsagePreferences(serverId); + const { display } = useUsageDisplay(view.kind === "ready" ? view.reports : []); return ( { + expect( + resolveUsageView({ + hostLabel: "Laptop", + isConnected: true, + supportsUsage: true, + enabled: false, + query: { data: [], error: null, isFetching: false }, + }), + ).toMatchObject({ kind: "off" }); +}); diff --git a/packages/app/src/usage/model.ts b/packages/app/src/usage/model.ts index 48143ad23f..bbe183dcd0 100644 --- a/packages/app/src/usage/model.ts +++ b/packages/app/src/usage/model.ts @@ -106,6 +106,7 @@ export interface UsageQueryState { export function resolveUsageView( input: { + enabled?: boolean; hostLabel: string; isConnected: boolean; supportsUsage: boolean; @@ -125,6 +126,8 @@ export function resolveUsageView( message: t("providerUsage.hostUpgradeRequired", { host: hostLabel }), }; } + if (input.enabled === false) + return { kind: "off", message: t("providerUsage.off", { host: hostLabel }) }; if (query?.data) { return { kind: "ready", reports: query.data, isRefreshing: query.isFetching }; } diff --git a/packages/app/src/usage/options.tsx b/packages/app/src/usage/options.tsx index b735b612aa..44205fbddd 100644 --- a/packages/app/src/usage/options.tsx +++ b/packages/app/src/usage/options.tsx @@ -8,15 +8,20 @@ import { ToolbarButton, paneContentToolbarIconSize } from "@/components/ui/pane- import { useIsCompactFormFactor } from "@/constants/layout"; import { SettingsRow, SettingsSwitch } from "@/components/settings"; import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control"; +import { Alert } from "@/components/ui/alert"; +import { useHosts } from "@/runtime/host-runtime"; import { settingsStyles } from "@/styles/settings"; -import { useUsagePreferences } from "./display"; +import { useUsageSetting } from "./setting"; +import { useUsageDisplay } from "./display"; import { useUsageInSidebar } from "./in-sidebar"; import type { UsageDisplayAs } from "./preferences"; const ThemedSettings = withUnistyles(Settings); /** The shared usage preferences, opened from a cog as a popover or compact sheet. */ -export function UsageOptions() { +export function UsageOptions({ serverId }: { serverId: string | null }) { + const setting = useUsageSetting(serverId); + const hostLabel = useHosts().find((host) => host.serverId === serverId)?.label ?? serverId; const { t } = useTranslation(); const displayAsOptions: SegmentedControlOption[] = [ { value: "used", label: t("providerUsage.displayUsed"), testID: "usage-display-used" }, @@ -27,7 +32,7 @@ export function UsageOptions() { }, ]; const compact = useIsCompactFormFactor(); - const { display } = useUsagePreferences(); + const { display } = useUsageDisplay([]); const { inSidebar, setInSidebar } = useUsageInSidebar(); return ( @@ -49,13 +54,25 @@ export function UsageOptions() { testID="usage-options-surface" > - + {setting.error ? : null} + {setting.supported ? ( + + ) : null} + + + void } { + const setting = useUsageSetting(serverId); const queryClient = useQueryClient(); const isConnected = useHostRuntimeIsConnected(serverId); const isSupported = useSessionStore((state) => supportsUsage(state.sessions[serverId])); const query = useFetchQuery({ queryKey: usageReportsQueryKey(serverId), queryFn: () => listReports(queryClient, serverId), - enabled: isConnected && isSupported, + enabled: isConnected && isSupported && setting.enabled, dataShape: "list", staleTimeMs: REPORTS_STALE_TIME_MS, }); @@ -150,6 +152,7 @@ export function useHostUsage(serverId: string): { view: UsageView; refresh: () = const view = resolveUsageView( { hostLabel, + enabled: setting.ready ? setting.enabled : undefined, isConnected, supportsUsage: isSupported, query: toQueryState(query), @@ -166,14 +169,16 @@ const NO_REPORTS: UsageReportEntry[] = []; * load, or without a host. */ export function useUsageHostReports(serverId: string | null): UsageReportEntry[] { + const setting = useUsageSetting(serverId); const queryClient = useQueryClient(); const query = useFetchQuery({ + enabled: setting.enabled, queryKey: usageReportsQueryKey(serverId ?? ""), queryFn: serverId ? () => listReports(queryClient, serverId) : skipToken, dataShape: "list", staleTimeMs: REPORTS_STALE_TIME_MS, }); - return query.data ?? NO_REPORTS; + return setting.enabled ? (query.data ?? NO_REPORTS) : NO_REPORTS; } /** @@ -209,7 +214,8 @@ export function useAgentUsage(serverId: string, agentId: string): AgentUsageView export function useHostReportsUsage(serverId: string): boolean { const isConnected = useHostRuntimeIsConnected(serverId); const isSupported = useSessionStore((state) => supportsUsage(state.sessions[serverId])); - return isConnected && isSupported; + const setting = useUsageSetting(serverId); + return isConnected && isSupported && setting.enabled; } /** Every host with whether it is connected and reports usage, in host order. */ diff --git a/packages/app/src/usage/setting.ts b/packages/app/src/usage/setting.ts new file mode 100644 index 0000000000..e6916cf8c8 --- /dev/null +++ b/packages/app/src/usage/setting.ts @@ -0,0 +1,26 @@ +import { useMutation } from "@tanstack/react-query"; +import { useCallback } from "react"; +import { useDaemonConfig } from "@/hooks/use-daemon-config"; +import { useSessionStore } from "@/stores/session-store"; + +/** Host policy comes from the live daemon config replica. */ +export function useUsageSetting(serverId: string | null) { + const supported = useSessionStore((state) => + Boolean(serverId && state.sessions[serverId]?.serverInfo?.features?.usageSetting), + ); + const { config, patchConfig } = useDaemonConfig(supported ? serverId : null); + const mutation = useMutation({ + mutationFn: (enabled: boolean) => patchConfig({ usage: { enabled } }), + }); + const setEnabled = mutation.mutate; + const turnOn = useCallback(() => setEnabled(true), [setEnabled]); + return { + supported, + error: mutation.error, + // COMPAT(usageSetting): added in v0.14, remove after 2027-05-01. + enabled: !supported || (config !== null && config.usage?.enabled !== false), + ready: !supported || config !== null, + setEnabled, + turnOn, + }; +} diff --git a/packages/app/src/usage/sidebar-item.tsx b/packages/app/src/usage/sidebar-item.tsx index 2ca99c4e29..437c0a929c 100644 --- a/packages/app/src/usage/sidebar-item.tsx +++ b/packages/app/src/usage/sidebar-item.tsx @@ -17,7 +17,8 @@ import { } from "react-native"; import { StyleSheet } from "react-native-unistyles"; import { builtinSidebarNavLabelKey } from "@/sidebar-nav/model"; -import { useUsagePreferences } from "./display"; +import { useUsageDisplay } from "./display"; +import { useUsageInSidebar } from "./in-sidebar"; import { useUsageHostId } from "./hosts"; import { useUsageHostReports } from "./queries"; import { UsageSourceIcon } from "./source-icon"; @@ -33,28 +34,24 @@ import { import { UsageModal } from "./usage-modal"; /** Each summary window with data on the usage host, under its source; empty while none has. */ -function useUsageSummary(): readonly PinnedUsageSource[] { +export function useUsageSummary(): readonly PinnedUsageSource[] { const { t } = useTranslation(); - const { preferences } = useUsagePreferences(); - const reports = useUsageHostReports(useUsageHostId()); + const { inSidebar } = useUsageInSidebar(); + const serverId = useUsageHostId(); + const reports = useUsageHostReports(inSidebar ? serverId : null); + const { preferences } = useUsageDisplay(reports); return useMemo(() => resolvePinnedUsage(reports, preferences, t), [preferences, reports, t]); } -/** Whether the sidebar Usage item has anything to show. */ -export function useHasUsageSummary(): boolean { - return useUsageSummary().length > 0; -} - /** * The sidebar footer's usage entry: each summary window's source icon and percent, and nothing * while no summary window has data, since the footer's Usage icon already opens Usage. * Pressing it opens the Usage modal. */ -export function UsageSidebarItem() { +export function UsageSidebarItem({ sources }: { sources: readonly PinnedUsageSource[] }) { const { t } = useTranslation(); const label = t(builtinSidebarNavLabelKey("usage")); const openUsage = useOpenSidebarUsage(); - const sources = useUsageSummary(); if (sources.length === 0) return null; return ; } diff --git a/packages/app/src/usage/types.ts b/packages/app/src/usage/types.ts index 58b8e31c98..9e36f58c84 100644 --- a/packages/app/src/usage/types.ts +++ b/packages/app/src/usage/types.ts @@ -10,6 +10,7 @@ export type UsageBalanceUnit = UsageBalance["unit"]; /** What a host's usage surface shows. `unavailable` is a host state, not a failed request. */ export type UsageView = + | { kind: "off"; message: string } | { kind: "unavailable"; message: string } | { kind: "loading" } | { kind: "error"; message: string } diff --git a/packages/app/src/usage/usage-modal.tsx b/packages/app/src/usage/usage-modal.tsx index bf92eaa60f..4e049c0b58 100644 --- a/packages/app/src/usage/usage-modal.tsx +++ b/packages/app/src/usage/usage-modal.tsx @@ -4,7 +4,7 @@ import { View } from "react-native"; import { AdaptiveModalSheet } from "@/components/adaptive-modal-sheet"; import { builtinSidebarNavLabelKey } from "@/sidebar-nav/model"; import { useHostUsageWithControls } from "./controls"; -import { useUsagePreferences } from "./display"; +import { useUsageDisplay } from "./display"; import { useUsageHostSelection } from "./hosts"; import type { UsageHost } from "./model"; import { UsageBody, UsageMessage } from "./usage-section"; @@ -52,12 +52,12 @@ function HostUsageModal({ hosts: UsageHost[]; onSelectHost: (serverId: string) => void; }) { - const { display } = useUsagePreferences(); const hostSelection = useMemo( () => ({ hosts, serverId, onSelect: onSelectHost }), [hosts, onSelectHost, serverId], ); const { view, refresh, controls } = useHostUsageWithControls(hostSelection); + const { display } = useUsageDisplay(view.kind === "ready" ? view.reports : []); return ( diff --git a/packages/app/src/usage/usage-section.tsx b/packages/app/src/usage/usage-section.tsx index 26699fd447..9c1e9354c1 100644 --- a/packages/app/src/usage/usage-section.tsx +++ b/packages/app/src/usage/usage-section.tsx @@ -7,6 +7,7 @@ import { Button } from "@/components/ui/button"; import { settingsStyles } from "@/styles/settings"; import { SettingsSection } from "@/components/settings/headings/settings-section"; import type { UsageDisplay } from "./display"; +import { useUsageSetting } from "./setting"; import { UsageControls } from "./controls"; import { UsageList } from "./list"; import type { UsageView } from "./types"; @@ -27,8 +28,8 @@ export function UsageSection({ testID?: string; }) { const trailing = useMemo( - () => , - [onRefresh, view], + () => , + [onRefresh, view, serverId], ); return ( @@ -51,6 +52,15 @@ export function UsageBody({ onRefresh: () => void; }) { const { t } = useTranslation(); + const setting = useUsageSetting(serverId); + if (view.kind === "off") + return ( + + + {setting.error ? : null} + + + ); if (view.kind === "unavailable") { return ; } diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index d20c91d773..18c3da9b67 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -229,6 +229,8 @@ export const MutableDaemonConfigSchema = z .optional(), app: z.object({ baseUrl: z.string() }).optional(), catalogRefreshTimeoutMs: z.number().int().positive().optional(), + // COMPAT(usageSetting): added in v0.14, remove after 2027-05-01. + usage: z.object({ enabled: z.boolean() }).optional(), browserTools: MutableBrowserToolsConfigSchema.default({ enabled: false }), providers: z.record(z.string(), MutableDaemonProviderConfigSchema).default({}), metadataGeneration: MutableMetadataGenerationConfigSchema.default({ providers: [] }), @@ -256,6 +258,7 @@ export const MutableDaemonConfigPatchSchema = z .object({ relay: MutableRelayConfigSchema.partial().optional(), mcp: z.object({ injectIntoAgents: z.boolean().optional() }).passthrough().optional(), + usage: z.object({ enabled: z.boolean() }).optional(), browserTools: MutableBrowserToolsConfigSchema.partial().optional(), providers: z .record(z.string(), MutableDaemonProviderConfigSchema.partial().passthrough()) @@ -3673,6 +3676,8 @@ export const ServerInfoStatusPayloadSchema = z providersSnapshot: z.boolean().optional(), connectedHosts: z.boolean().optional(), hostMultiplexing: z.boolean().optional(), + // COMPAT(usageSetting): added in v0.14, remove after 2027-05-01. + usageSetting: z.boolean().optional(), usageSources: z.boolean().optional(), // COMPAT(providersSnapshotCwd): added in v0.3.2, remove gate after 2027-02-10. providersSnapshotCwd: z.boolean().optional(), diff --git a/packages/server/src/server/bootstrap.ts b/packages/server/src/server/bootstrap.ts index 8fe0f05b14..fa896ef898 100644 --- a/packages/server/src/server/bootstrap.ts +++ b/packages/server/src/server/bootstrap.ts @@ -420,6 +420,7 @@ export interface PaseoDaemonConfig { trustedProxies?: true | string[]; mcpEnabled?: boolean; mcpInjectIntoAgents?: boolean; + usageEnabled?: boolean; browserToolsEnabled?: boolean; git?: { maxProcessesPerSecond: number; @@ -590,6 +591,7 @@ function createInitialMutableDaemonConfig(config: ResolvedDaemonSettings): Mutab ...(config.providerCatalogRefreshTimeoutMs !== undefined ? { catalogRefreshTimeoutMs: config.providerCatalogRefreshTimeoutMs } : {}), + usage: { enabled: config.usageEnabled !== false }, browserTools: { enabled: config.browserToolsEnabled ?? false }, providers, metadataGeneration: { diff --git a/packages/server/src/server/config.ts b/packages/server/src/server/config.ts index 3149fc6eb9..07c5c287b8 100644 --- a/packages/server/src/server/config.ts +++ b/packages/server/src/server/config.ts @@ -523,6 +523,10 @@ function resolveAppendSystemPrompt(persisted: ReturnType): boolean { + return persisted.daemon?.usage?.enabled !== false; +} + function resolveBrowserToolsEnabled(persisted: ReturnType): boolean { return persisted.daemon?.browserTools?.enabled ?? false; } @@ -548,6 +552,7 @@ function resolveStaticLoadConfigSettings( mcpEnabled: cli?.mcpEnabled ?? persisted.daemon?.mcp?.enabled ?? true, mcpInjectIntoAgents: cli?.mcpInjectIntoAgents ?? persisted.daemon?.mcp?.injectIntoAgents ?? false, + usageEnabled: resolveUsageEnabled(persisted), browserToolsEnabled: resolveBrowserToolsEnabled(persisted), autoArchiveAfterMerge: persisted.daemon?.autoArchiveAfterMerge ?? false, appendSystemPrompt: resolveAppendSystemPrompt(persisted), @@ -576,6 +581,7 @@ export type ResolvedDaemonSettings = Pick< | "trustedProxies" | "mcpEnabled" | "mcpInjectIntoAgents" + | "usageEnabled" | "browserToolsEnabled" | "git" | "autoArchiveAfterMerge" diff --git a/packages/server/src/server/daemon-config-store.test.ts b/packages/server/src/server/daemon-config-store.test.ts index 89c3c7f977..d9b2e94181 100644 --- a/packages/server/src/server/daemon-config-store.test.ts +++ b/packages/server/src/server/daemon-config-store.test.ts @@ -10,6 +10,10 @@ import { readSpeechSettings } from "./speech/speech-settings.js"; import type { PersistedConfig } from "./persisted-config.js"; import type { MutableDaemonConfig } from "@getpaseo/protocol/messages"; +function usageEnabled(persisted: PersistedConfig): boolean { + return persisted.daemon?.usage?.enabled !== false; +} + function reloadableConfig( persisted: PersistedConfig, options: { relayEnabledFallback?: boolean } = {}, @@ -23,6 +27,7 @@ function reloadableConfig( enabled: relay.enabled ?? options.relayEnabledFallback ?? true, }, mcp: { enabled: true, injectIntoAgents: false }, + usage: { enabled: usageEnabled(persisted) }, browserTools: { enabled: daemon.browserTools?.enabled ?? false }, providers: (agents.providers ?? {}) as MutableDaemonConfig["providers"], metadataGeneration: { providers: agents.metadataGeneration?.providers ?? [] }, @@ -1572,3 +1577,31 @@ describe("DaemonConfigStore speech settings", () => { expect(JSON.stringify(other.get())).not.toContain("secret"); }); }); + +test("usage policy persists across restart and live reload", async () => { + const paseoHome = mkdtempSync(path.join(tmpdir(), "usage-policy-")); + try { + const initial = reloadableConfig({}); + const store = new DaemonConfigStore(paseoHome, initial, undefined, { + reloadSource: { + resolve: (persisted) => ({ + mutable: reloadableConfig(persisted), + overrideControlledPaths: [], + }), + }, + }); + await store.patch({ usage: { enabled: false } }); + expect(loadConfig(paseoHome, { env: {} }).usageEnabled).toBe(false); + const persisted = loadPersistedConfig(paseoHome); + const restarted = new DaemonConfigStore(paseoHome, reloadableConfig(persisted)); + expect(restarted.get().usage).toEqual({ enabled: false }); + writeFileSync( + path.join(paseoHome, "config.json"), + JSON.stringify({ daemon: { usage: { enabled: true } } }), + ); + await store.reload(); + expect(store.get().usage).toEqual({ enabled: true }); + } finally { + rmSync(paseoHome, { recursive: true, force: true }); + } +}); diff --git a/packages/server/src/server/daemon-config-store.ts b/packages/server/src/server/daemon-config-store.ts index 1bd67822a3..e83874235f 100644 --- a/packages/server/src/server/daemon-config-store.ts +++ b/packages/server/src/server/daemon-config-store.ts @@ -22,6 +22,7 @@ type ProviderOverride = import("./agent/provider-launch-config.js").ProviderOver interface SupportedMutableConfigPatch { relay?: { enabled?: boolean; requireProtectedSecurity?: boolean }; mcp?: { injectIntoAgents?: boolean }; + usage?: { enabled: boolean }; browserTools?: { enabled?: boolean }; providers?: MutableDaemonConfig["providers"]; removeProviders?: string[]; @@ -182,6 +183,7 @@ const RELOADABLE_PATHS = [ "daemon.relay.requireProtectedSecurity", "daemon.mcp.enabled", "daemon.mcp.injectIntoAgents", + "daemon.usage.enabled", "daemon.browserTools.enabled", "daemon.hostnames", "daemon.cors.allowedOrigins", @@ -209,6 +211,7 @@ const PERSISTED_TO_MUTABLE_PATH = new Map([ ["daemon.relay.requireProtectedSecurity", "relay.requireProtectedSecurity"], ["daemon.mcp.enabled", "mcp.enabled"], ["daemon.mcp.injectIntoAgents", "mcp.injectIntoAgents"], + ["daemon.usage.enabled", "usage.enabled"], ["daemon.browserTools.enabled", "browserTools.enabled"], ["daemon.hostnames", "hostnames"], ["daemon.cors.allowedOrigins", "cors.allowedOrigins"], @@ -281,6 +284,7 @@ function pickRelayPatch( function pickSupportedPatchFields(patch: MutableDaemonConfigPatch): SupportedMutableConfigPatch { return { ...pickRelayPatch(patch.relay), + usage: patch.usage, ...(patch.mcp?.injectIntoAgents !== undefined ? { mcp: { injectIntoAgents: patch.mcp.injectIntoAgents } } : {}), @@ -767,6 +771,7 @@ function mergeMutableDaemonPatch( if (patch.mcp?.injectIntoAgents !== undefined) { next.mcp = { ...next.mcp, injectIntoAgents: patch.mcp.injectIntoAgents }; } + if (patch.usage) next.usage = patch.usage; if (patch.browserTools?.enabled !== undefined) { next.browserTools = { ...next.browserTools, enabled: patch.browserTools.enabled }; } diff --git a/packages/server/src/server/persisted-config.ts b/packages/server/src/server/persisted-config.ts index f7b3982513..3138ec9132 100644 --- a/packages/server/src/server/persisted-config.ts +++ b/packages/server/src/server/persisted-config.ts @@ -259,6 +259,7 @@ export const PersistedConfigSchema = z }) .passthrough() .optional(), + usage: z.object({ enabled: z.boolean().optional() }).optional(), browserTools: z .object({ enabled: z.boolean().optional(), diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index cca0b4f3fa..09681de8ba 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -1042,6 +1042,7 @@ export class Session { logger: this.sessionLogger, }); this.usageSession = new UsageSession({ + isEnabled: () => daemonConfigStore.get().usage?.enabled !== false, emit: (msg) => this.emit(msg), runtime: pluginRuntime, logger: this.sessionLogger, diff --git a/packages/server/src/server/session/usage/usage-session.test.ts b/packages/server/src/server/session/usage/usage-session.test.ts index 2aa65992b8..3a397094a3 100644 --- a/packages/server/src/server/session/usage/usage-session.test.ts +++ b/packages/server/src/server/session/usage/usage-session.test.ts @@ -15,6 +15,7 @@ test("lists reports from usage sources", async () => { report: { status: "available" as const, windows: [] }, }; const usage = new UsageSession({ + isEnabled: () => true, emit: (message) => emitted.push(message), runtime: { async listUsageReports(options) { @@ -40,6 +41,7 @@ test("lists reports from usage sources", async () => { test("surfaces a legacy usage-list failure as an rpc_error envelope", async () => { const emitted: SessionOutboundMessage[] = []; const usage = new UsageSession({ + isEnabled: () => true, emit: (message) => emitted.push(message), runtime: { async listUsageReports() { @@ -61,6 +63,7 @@ test("surfaces a legacy usage-list failure as an rpc_error envelope", async () = test("request failures terminate with an error response and no updates", async () => { const emitted: SessionOutboundMessage[] = []; const usage = new UsageSession({ + isEnabled: () => true, emit: (message) => emitted.push(message), logger: pino({ level: "silent" }), }); @@ -72,3 +75,36 @@ test("request failures terminate with an error response and no updates", async ( }, ]); }); + +test("off rejects both protocols before runtime discovery and turning on restores reports", async () => { + let enabled = false; + let calls = 0; + const emitted: SessionOutboundMessage[] = []; + const usage = new UsageSession({ + isEnabled: () => enabled, + emit: (message) => emitted.push(message), + logger: pino({ level: "silent" }), + runtime: { + async listUsageReports() { + calls++; + return []; + }, + async listLegacyUsage() { + calls++; + return { fetchedAt: "now", providers: [] }; + }, + }, + }); + await usage.handleListReports({ type: "usage.list_reports.request", requestId: "off" }); + await usage.handleLegacyList({ type: "provider.usage.list.request", requestId: "old" }); + expect(calls).toBe(0); + expect(emitted[0]).toMatchObject({ payload: { error: "Usage is off on this host." } }); + expect(emitted[1]).toMatchObject({ + type: "rpc_error", + payload: { error: "Usage is off on this host." }, + }); + enabled = true; + await usage.handleListReports({ type: "usage.list_reports.request", requestId: "on" }); + expect(calls).toBe(1); + expect(emitted[2]).toMatchObject({ payload: { error: null } }); +}); diff --git a/packages/server/src/server/session/usage/usage-session.ts b/packages/server/src/server/session/usage/usage-session.ts index 500c03a088..cd1e2e8801 100644 --- a/packages/server/src/server/session/usage/usage-session.ts +++ b/packages/server/src/server/session/usage/usage-session.ts @@ -9,6 +9,7 @@ export interface UsageSessionOptions { listUsageReports(options: ListUsageReportsOptions): Promise; listLegacyUsage(): Promise<{ fetchedAt: string; providers: ProviderUsage[] }>; }; + isEnabled: () => boolean; logger: pino.Logger; } @@ -19,6 +20,7 @@ export class UsageSession { msg: Extract, ): Promise { try { + if (!this.options.isEnabled()) throw new Error("Usage is off on this host."); if (!this.options.runtime) throw new Error("Plugin runtime is unavailable"); await this.options.runtime.listUsageReports({ forceRefresh: msg.forceRefresh, @@ -49,6 +51,18 @@ export class UsageSession { async handleLegacyList( msg: Extract, ): Promise { + if (!this.options.isEnabled()) { + this.options.emit({ + type: "rpc_error", + payload: { + requestId: msg.requestId, + requestType: msg.type, + error: "Usage is off on this host.", + code: "provider_usage_list_failed", + }, + }); + return; + } try { if (!this.options.runtime) throw new Error("Plugin runtime is unavailable"); const usage = await this.options.runtime.listLegacyUsage(); diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index b7024a638b..96c81ab49a 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -1949,6 +1949,7 @@ export class VoiceAssistantWebSocketServer { hostMultiplexing: true, // COMPAT(relayProtectedSecurity): added in v0.13.0, remove gate after 2027-04-21. relayProtectedSecurity: true, + usageSetting: true, usageSources: true, ownedSubscriptions: true, agentRequestReceipts: true, diff --git a/packages/website/public/schemas/paseo.config.v1.json b/packages/website/public/schemas/paseo.config.v1.json index 1b74066bae..bae380d4c8 100644 --- a/packages/website/public/schemas/paseo.config.v1.json +++ b/packages/website/public/schemas/paseo.config.v1.json @@ -70,6 +70,14 @@ }, "additionalProperties": {} }, + "usage": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + } + } + }, "browserTools": { "type": "object", "properties": { From 1f79efcd629283ccdc56bb070287c1537a004f3a Mon Sep 17 00:00:00 2001 From: Peanut <34237301+Peanut-HZM@users.noreply.github.com> Date: Fri, 30 Oct 2026 16:08:14 +0800 Subject: [PATCH 122/173] fix(providers): name the MiniMax Code binary so npx can resolve it (#8201) The MiniMax Code catalog entry ran `npx -y @minimax-ai/code@0.6.13 acp`. npx derives the executable from the unscoped package name, which is `code`, but the package publishes `mcode` and `mcode-tools`. npm therefore exits with "could not determine executable to run" before the agent starts. Paseo reports this as a provider that timed out during `initialize`, so the entry looks like a broken agent rather than a malformed command. Name the package and the binary separately. The ACP handshake then completes and the provider reports its models and modes. Co-authored-by: Peanut-HZM --- packages/app/src/data/acp-provider-catalog.ts | 5 ++++- packages/app/src/hooks/use-acp-provider-catalog.test.ts | 4 +++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/packages/app/src/data/acp-provider-catalog.ts b/packages/app/src/data/acp-provider-catalog.ts index f0210f1402..46b7d81a2d 100644 --- a/packages/app/src/data/acp-provider-catalog.ts +++ b/packages/app/src/data/acp-provider-catalog.ts @@ -292,7 +292,10 @@ const CATALOG_DATA = [ version: "0.6.13", iconId: "minimax-code", installLink: "https://agent.minimax.io", - command: ["npx", "-y", "@minimax-ai/code@0.6.13", "acp"], + // `-p ` names the package and `mcode` names its binary. Without the + // explicit binary, npx resolves the executable from the unscoped package + // name (`code`), which this package does not publish. + command: ["npx", "-y", "-p", "@minimax-ai/code@0.6.13", "mcode", "acp"], }, { id: "minion-code", diff --git a/packages/app/src/hooks/use-acp-provider-catalog.test.ts b/packages/app/src/hooks/use-acp-provider-catalog.test.ts index a30b27ce8f..41806de307 100644 --- a/packages/app/src/hooks/use-acp-provider-catalog.test.ts +++ b/packages/app/src/hooks/use-acp-provider-catalog.test.ts @@ -62,7 +62,9 @@ describe("ACP provider catalog", () => { expect(findProvider("minimax-code")).toMatchObject({ title: "MiniMax Code", version: "0.6.13", - command: ["npx", "-y", "@minimax-ai/code@0.6.13", "acp"], + // The package publishes `mcode`, not `code`, so npx needs the package and + // the binary named separately. + command: ["npx", "-y", "-p", "@minimax-ai/code@0.6.13", "mcode", "acp"], }); expect(findProvider("minimax-code").iconSvg).toContain(" Date: Fri, 30 Oct 2026 09:17:50 +0000 Subject: [PATCH 123/173] test(server): measure Git filter work within its callback (#8270) Exclude unrelated callbacks and fixture garbage from the cold event-filter budget. Keep the 20ms limit and IO assertions, with unrelated CPU work as a regression control. Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- ...it-service.observation.integration.test.ts | 41 ++++++++++++++----- 1 file changed, 31 insertions(+), 10 deletions(-) diff --git a/packages/server/src/server/workspace-git-service.observation.integration.test.ts b/packages/server/src/server/workspace-git-service.observation.integration.test.ts index a2cb27739d..c8d97390ed 100644 --- a/packages/server/src/server/workspace-git-service.observation.integration.test.ts +++ b/packages/server/src/server/workspace-git-service.observation.integration.test.ts @@ -536,7 +536,6 @@ test("Git refresh, command tracing and 10,000 ignored alias events do no synchro const repositoryRoot = fileURLToPath(new URL("../../../../", import.meta.url)); const source = ` import assert from 'node:assert/strict'; - import { measureMainThreadWork } from './packages/server/src/test-utils/main-thread-work.ts'; import { write } from 'node:fs'; import { mkdtemp, mkdir, writeFile, symlink, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; @@ -580,17 +579,36 @@ test("Git refresh, command tracing and 10,000 ignored alias events do no synchro const events = Array.from({ length: process.env.GIT_IO_TRACE ? 2 : 10000 }, (_, i) => ({ type: 'update', path: join(i % 2 ? alias : worktree, 'ignored', 'noise') })); let fsCalls = 0; const hook = createHook({ init(_id, type) { if (type.startsWith('FSREQ')) fsCalls++; } }); + // Collect repository setup and event-fixture garbage before measuring + // the cold filter. Allocations made by the filter still count. + global.gc(); await tick(); - const { blockingMs } = await measureMainThreadWork('Git filter main-thread work', async () => { - await marker('FILTER_START'); - hook.enable(); - try { - callback(null, events); - } finally { - hook.disable(); - await marker('FILTER_END'); + // Unrelated callbacks must not consume the synchronous filter's budget. + const threadCpuUsage = Reflect.get(process, 'threadCpuUsage'); + const unrelatedWork = tick().then(() => { + const started = threadCpuUsage(); + while (true) { + const cpu = threadCpuUsage(started); + if (cpu.user + cpu.system >= 80000) break; } }); + await marker('FILTER_START'); + hook.enable(); + let blockingMs; + try { + // This callback is synchronous: measure its own span, without waiting + // for marker IO, loader messages or other event-loop callbacks. + const startedAt = performance.now(); + const startedCpu = threadCpuUsage(); + callback(null, events); + const cpu = threadCpuUsage(startedCpu); + // Cap coarse Windows CPU accounting by elapsed time; exclude descheduling. + blockingMs = Math.min(performance.now() - startedAt, (cpu.user + cpu.system) / 1000); + } finally { + hook.disable(); + await marker('FILTER_END'); + } + await unrelatedWork; assert.equal(fsCalls, 0, "filesystem calls"); assert.equal(notifications, 0, "ignored event notification"); assert.ok(blockingMs < 20, 'blocking filter work: ' + blockingMs); @@ -614,6 +632,7 @@ test("Git refresh, command tracing and 10,000 ignored alias events do no synchro const { stdout, stderr } = await promisify(execFile)( process.execPath, [ + "--expose-gc", "--import", "tsx", ...(tracing ? ["--trace-sync-io"] : []), @@ -634,7 +653,9 @@ test("Git refresh, command tracing and 10,000 ignored alias events do no synchro const output = stderr.split(`${phase}_START\n`)[1]?.split(`${phase}_END\n`)[0]; expect(output, `${phase}: synchronous filesystem IO`).toBe(""); } - expect(JSON.parse(stdout.trim().split("\n")[0])).toMatchObject({ fsCalls: 0 }); + const measurement = JSON.parse(stdout.trim().split("\n")[0]); + console.info("Git filter budget", { tracing, ...measurement }); + expect(measurement).toMatchObject({ fsCalls: 0 }); } }, 60_000); From 531370c4ce98c1e32a0c0a5c4baf4b31501999a4 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Fri, 30 Oct 2026 10:10:39 +0000 Subject: [PATCH 124/173] fix(pi): show tool-result images live and after reload (#8280) * pi: render tool-result images as inline image rows (paseo #1717 parity) * fix(pi): preserve turn ownership while rendering images * fix(pi): preserve metadata when stripping nested image payloads --------- Co-authored-by: be-my-bot Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: duyiliu --- .../server/agent/providers/pi/agent.test.ts | 111 ++++++++++++++++++ .../src/server/agent/providers/pi/agent.ts | 68 ++++++++++- .../providers/pi/extensions/child-session.ts | 11 +- .../providers/pi/extensions/index.test.ts | 6 +- .../rpiv-ask-user-question/index.test.ts | 4 +- .../pi/extensions/task-fixture-test.ts | 2 +- .../agent/providers/pi/history-mapper.test.ts | 72 ++++++++++++ .../agent/providers/pi/history-mapper.ts | 36 ++++-- .../providers/pi/tool-call-mapper.test.ts | 82 ++++++++++++- .../agent/providers/pi/tool-call-mapper.ts | 63 ++++++++++ 10 files changed, 429 insertions(+), 26 deletions(-) diff --git a/packages/server/src/server/agent/providers/pi/agent.test.ts b/packages/server/src/server/agent/providers/pi/agent.test.ts index 82887bf199..936bdbc973 100644 --- a/packages/server/src/server/agent/providers/pi/agent.test.ts +++ b/packages/server/src/server/agent/providers/pi/agent.test.ts @@ -3643,3 +3643,114 @@ test("closing Pi during image conversion rejects its pending start", async () => await session.close(); await rejected; }); + +describe("Pi tool-result images", () => { + test.each([false, true])( + "tool-result images precede the reply and completion (isError=%s)", + async (isError) => { + const { pi, session, events } = await createSession(); + onTestFinished(() => session.close()); + const fakeSession = pi.latestSession(); + await session.startTurn("run"); + fakeSession.emit({ + type: "tool_execution_start", + toolCallId: "shot-1", + toolName: "screenshot", + args: {}, + }); + fakeSession.emit({ + type: "tool_execution_end", + toolCallId: "shot-1", + toolName: "screenshot", + result: { + content: [ + { type: "text", text: "captured" }, + { type: "image", data: Buffer.from("hello").toString("base64"), mimeType: "image/png" }, + ], + structuredContent: { + type: "image", + data: Buffer.from("hello").toString("base64"), + mimeType: "image/png", + note: "captured", + }, + }, + isError, + }); + fakeSession.emit({ + type: "message_update", + assistantMessageEvent: { type: "text_delta", delta: "Image read complete." }, + }); + fakeSession.finishTurn(); + await events.nextTurnCompletion(); + + const items = events.timelineItems(); + const toolIndex = items.findIndex( + (item) => + item.type === "tool_call" && + item.callId === "shot-1" && + item.status === (isError ? "failed" : "completed"), + ); + expect(toolIndex).toBeGreaterThanOrEqual(0); + // Base64 must never reach the tool output stringifier. + expect(JSON.stringify(items[toolIndex])).not.toContain( + Buffer.from("hello").toString("base64"), + ); + expect(items.slice(toolIndex + 1)).toEqual([ + expect.objectContaining({ + type: "assistant_message", + text: expect.stringContaining("![Image]("), + }), + expect.objectContaining({ type: "assistant_message", text: "Image read complete." }), + ]); + expect(events.timelineAndCompletionEvents().at(-1)).toEqual({ type: "turn_completed" }); + }, + ); +}); + +test("Pi image rendering preserves turn ownership across an interrupt and follow-up", async () => { + const { pi, session, events } = await createSession(); + onTestFinished(() => session.close()); + const emitted: AgentStreamEvent[] = []; + session.subscribe((event) => emitted.push(event)); + const native = pi.latestSession(); + const first = await session.startTurn("read image"); + native.emit({ + type: "tool_execution_end", + toolCallId: "large-image", + toolName: "screenshot", + result: { + content: [ + { + type: "image", + data: Buffer.alloc(8 * 1024 * 1024, 73).toString("base64"), + mimeType: "image/png", + }, + ], + }, + isError: false, + }); + native.finishTurn(); + await session.interrupt(); + const followup = await session.startTurn("follow-up after image"); + await waitForImmediate(); + await waitForImmediate(); + await expect + .poll(() => + events + .timelineItems() + .some((item) => item.type === "assistant_message" && item.text.includes("![Image](")), + ) + .toBe(true); + expect(events.turnCompletedEvents().some((event) => event.turnId === followup.turnId)).toBe( + false, + ); + const imageEvent = emitted.find( + (event) => + event.type === "timeline" && + event.item.type === "assistant_message" && + event.item.text.includes("![Image]("), + ); + expect(imageEvent).toMatchObject({ turnId: first.turnId }); + native.finishTurn(); + await events.nextTurnCompletion(); +}); diff --git a/packages/server/src/server/agent/providers/pi/agent.ts b/packages/server/src/server/agent/providers/pi/agent.ts index 5fbffde84b..9474e98cc8 100644 --- a/packages/server/src/server/agent/providers/pi/agent.ts +++ b/packages/server/src/server/agent/providers/pi/agent.ts @@ -64,7 +64,11 @@ import { streamPiHistory, type PiCapturedUserMessageEntry, } from "./history-mapper.js"; -import { materializeProviderImage } from "../provider-image-output.js"; +import { + materializeProviderImage, + renderProviderImageOutputAsAssistantMarkdown, + type ProviderImageOutput, +} from "../provider-image-output.js"; import { PiCliRuntime } from "./cli-runtime.js"; import { createPiExtensionHost, @@ -89,6 +93,7 @@ import { mapToolDetail, parseToolArgs, parseToolResult, + splitPiToolResultImages, type PiToolResult, type PiTrackedToolCall, } from "./tool-call-mapper.js"; @@ -1201,6 +1206,7 @@ export class PiRpcAgentSession implements AgentSession { private closed = false; private readonly closeController = new AbortController(); private readonly pendingExtensionHydrations = new Set>(); + private pendingOutput: Promise | null = null; // Pi publishes the terminal before acknowledging abort. Autonomous runs have no // turn ID; retain their errors too until the cancellation request settles. private interruptingTurn: { turnId: string | undefined; error: string | null } | null = null; @@ -1602,6 +1608,7 @@ export class PiRpcAgentSession implements AgentSession { this.pendingExtensionUiRequests.size || this.pendingExtensionResults.size || this.pendingExtensionHydrations.size || + this.pendingOutput || this.pendingSteerSubmissions.length || this.pendingNoTurnOutputs.length || this.interruptingTurn @@ -1622,7 +1629,7 @@ export class PiRpcAgentSession implements AgentSession { try { await this.runtimeSession.close(); } finally { - await Promise.all(this.pendingExtensionHydrations); + await Promise.all([this.pendingOutput, ...this.pendingExtensionHydrations]); this.rejectAllExtensionResults(new Error("Pi session closed")); this.cleanup?.(); } @@ -1686,9 +1693,31 @@ export class PiRpcAgentSession implements AgentSession { } private emit(event: AgentStreamEvent): void { - for (const subscriber of this.subscribers) { - subscriber(event); + if (this.pendingOutput) { + this.emitAsync(() => Promise.resolve([event])); + return; } + this.publish(event); + } + + private publish(event: AgentStreamEvent): void { + for (const subscriber of this.subscribers) subscriber(event); + } + + // Keep timeline order while images are materialized, without delaying provider state changes. + private emitAsync(render: () => Promise): void { + const pending = (this.pendingOutput ?? Promise.resolve()) + .then(render) + .then((events) => { + if (!this.closed) for (const event of events) this.publish(event); + return undefined; + }) + .catch((error) => this.logger.error({ err: error }, "Pi output rendering failed")); + this.pendingOutput = pending; + void pending.then(() => { + if (this.pendingOutput === pending) this.pendingOutput = null; + return undefined; + }); } private emitExtensionOutput(output: PiExtensionEventOutput | undefined, turnId?: string): void { @@ -2315,8 +2344,11 @@ export class PiRpcAgentSession implements AgentSession { this.activeToolCalls.get(event.toolCallId) ?? parseToolArgs(event.toolName, null); this.activeToolCalls.delete(event.toolCallId); - const result = parseToolResult(event.result); - const error = event.isError ? event.result : null; + // Pull image blocks out of the result so base64 never reaches the tool output, then render + // each one as an assistant_message markdown image after the tool_call (mirroring the Claude + // provider, upstream #1717). + const { images, result } = splitPiToolResultImages(parseToolResult(event.result)); + const error = event.isError ? result : null; const status = event.isError ? "failed" : "completed"; this.extensionHost.onToolEnd({ callId: event.toolCallId, @@ -2326,6 +2358,30 @@ export class PiRpcAgentSession implements AgentSession { result, }); this.emitToolCallEvent(event.toolCallId, toolCall, status, result, error); + if (images.length === 0) return; + const turnId = this.currentTurnIdForEvent(); + this.emitAsync(() => this.renderToolResultImages(images, turnId)); + } + + private async renderToolResultImages( + images: ProviderImageOutput[], + turnId: string | undefined, + ): Promise { + const events: AgentStreamEvent[] = []; + for (const image of images) { + const imageItem = await renderProviderImageOutputAsAssistantMarkdown(image, { + materialize: materializeProviderImage, + }); + if (imageItem && !this.closed) { + events.push({ + type: "timeline", + provider: this.provider, + turnId, + item: imageItem, + }); + } + } + return events; } private emitCompactionTimeline(input: { diff --git a/packages/server/src/server/agent/providers/pi/extensions/child-session.ts b/packages/server/src/server/agent/providers/pi/extensions/child-session.ts index 2013b831be..0c7c7df9aa 100644 --- a/packages/server/src/server/agent/providers/pi/extensions/child-session.ts +++ b/packages/server/src/server/agent/providers/pi/extensions/child-session.ts @@ -21,11 +21,11 @@ export function mapPiChildSession( return new PiChildSessionFollower(id, file, maxBytes).readNew(); } -function mapChildLine( +async function mapChildLine( mapper: PiHistoryMapper, id: string, line: string, -): ProviderSubagentInputEvent[] { +): Promise { let entry: { message?: PiAgentMessage; timestamp?: string }; try { entry = JSON.parse(line); @@ -33,7 +33,7 @@ function mapChildLine( return []; } if (!entry.message || typeof entry.message !== "object" || !("role" in entry.message)) return []; - return mapper.mapMessages([entry.message]).flatMap((mapped) => + return (await mapper.mapMessages([entry.message])).flatMap((mapped) => mapped.type === "timeline" ? [ { @@ -83,7 +83,10 @@ export class PiChildSessionFollower { const events: ProviderSubagentInputEvent[] = []; for (const line of data.subarray(0, lastNewline).toString("utf8").split("\n")) { if (this.items >= MAX_ITEMS) break; - const mapped = mapChildLine(this.mapper, this.id, line).slice(0, MAX_ITEMS - this.items); + const mapped = (await mapChildLine(this.mapper, this.id, line)).slice( + 0, + MAX_ITEMS - this.items, + ); this.items += mapped.length; events.push(...mapped); } diff --git a/packages/server/src/server/agent/providers/pi/extensions/index.test.ts b/packages/server/src/server/agent/providers/pi/extensions/index.test.ts index 9afacae977..0bf32a9f2f 100644 --- a/packages/server/src/server/agent/providers/pi/extensions/index.test.ts +++ b/packages/server/src/server/agent/providers/pi/extensions/index.test.ts @@ -83,7 +83,7 @@ describe("Pi extension host", () => { test("declines a throwing adapter and preserves generic history", async () => { const host = createPiExtensionHost(undefined, [throwingAdapter]); const mapper = new PiHistoryMapper("pi", [], {}, host); - const events = mapper.mapMessages([ + const events = await mapper.mapMessages([ { role: "assistant", content: [{ type: "toolCall", id: "call-1", name: "other", arguments: {} }], @@ -193,7 +193,7 @@ describe("Pi extension host", () => { await output?.hydration; expect(reads).toHaveLength(8); }); - test("claims a tool, declines an unrelated one, and maps history like live events", () => { + test("claims a tool, declines an unrelated one, and maps history like live events", async () => { const host = createPiExtensionHost(); const args = { agent: "scout", task: "Inspect files" }; const result = parseToolResult({ content: [{ type: "text", text: "Found two files" }] }); @@ -225,7 +225,7 @@ describe("Pi extension host", () => { ).toBeUndefined(); const mapper = new PiHistoryMapper("pi"); - const events = mapper.mapMessages([ + const events = await mapper.mapMessages([ { role: "assistant", content: [{ type: "toolCall", id: "call-1", name: "subagent", arguments: args }], diff --git a/packages/server/src/server/agent/providers/pi/extensions/rpiv-ask-user-question/index.test.ts b/packages/server/src/server/agent/providers/pi/extensions/rpiv-ask-user-question/index.test.ts index 3ec9256a29..d3c9fb7a9e 100644 --- a/packages/server/src/server/agent/providers/pi/extensions/rpiv-ask-user-question/index.test.ts +++ b/packages/server/src/server/agent/providers/pi/extensions/rpiv-ask-user-question/index.test.ts @@ -79,7 +79,7 @@ test("cancellation declines each remaining real RPC dialog", () => { } }); -test("captured result renders in live and history tool rows, while foreign shapes decline", () => { +test("captured result renders in live and history tool rows, while foreign shapes decline", async () => { const call = { callId: end.toolCallId, toolName: end.toolName, @@ -93,7 +93,7 @@ test("captured result renders in live and history tool rows, while foreign shape label: "Questions", text: "Which snack?: Cookie\nWhich colors?: Red, Blue\nWhat project name?: Nebula", }); - const history = new PiHistoryMapper("pi").mapMessages([ + const history = await new PiHistoryMapper("pi").mapMessages([ { role: "assistant", content: [ diff --git a/packages/server/src/server/agent/providers/pi/extensions/task-fixture-test.ts b/packages/server/src/server/agent/providers/pi/extensions/task-fixture-test.ts index a3b2114cab..f702e0d7cf 100644 --- a/packages/server/src/server/agent/providers/pi/extensions/task-fixture-test.ts +++ b/packages/server/src/server/agent/providers/pi/extensions/task-fixture-test.ts @@ -89,7 +89,7 @@ export async function verifyTaskFixture(path: URL, expectedStatuses: string[]): for (const event of fixture.events) pi.latestSession().emit(event); pi.latestSession().finishTurn(); expect(todos(live)).toEqual(mapped); - const replay = new PiHistoryMapper("pi").mapMessages(fixture.messages); + const replay = await new PiHistoryMapper("pi").mapMessages(fixture.messages); expect(todos(replay)).toEqual(mapped); expect( replay.filter( diff --git a/packages/server/src/server/agent/providers/pi/history-mapper.test.ts b/packages/server/src/server/agent/providers/pi/history-mapper.test.ts index 24d18306b2..f4136956eb 100644 --- a/packages/server/src/server/agent/providers/pi/history-mapper.test.ts +++ b/packages/server/src/server/agent/providers/pi/history-mapper.test.ts @@ -221,3 +221,75 @@ describe("Pi history mapper", () => { ]); }); }); + +describe("Pi tool-result image replay", () => { + test("recreates an image from native tool-result history without its source file", async () => { + const events = await collectHistory([ + { + role: "assistant", + content: [ + { + type: "toolCall", + id: "image-read", + name: "read", + arguments: { path: "missing-preview.png" }, + }, + ], + }, + { + role: "toolResult", + toolCallId: "image-read", + toolName: "read", + content: [ + { type: "text", text: "Read image file [image/png]" }, + { type: "image", data: "aGVsbG8=", mimeType: "image/png" }, + ], + }, + ]); + expect(events.map((event) => event.item?.type)).toEqual([ + "tool_call", + "tool_call", + "assistant_message", + ]); + const image = events.find( + (event) => event.type === "timeline" && event.item.type === "assistant_message", + ); + expect(image).toMatchObject({ + type: "timeline", + item: { type: "assistant_message", text: expect.stringContaining("![Image](file://") }, + }); + if (image?.type !== "timeline" || image.item.type !== "assistant_message") + throw new Error("Missing image"); + const url = image.item.text.match(/\((file:[^)]+)\)/)![1]; + const { readFile, unlink } = await import("node:fs/promises"); + expect(await readFile(new URL(url))).toEqual(Buffer.from("hello")); + await unlink(new URL(url)); + const replay = await collectHistory([ + { + role: "toolResult", + toolCallId: "image-read", + toolName: "read", + content: [{ type: "image", data: "aGVsbG8=", mimeType: "image/png" }], + }, + ]); + expect(replay).toContainEqual(image); + expect(await readFile(new URL(url))).toEqual(Buffer.from("hello")); + }); +}); + +test("replayed Pi images keep their position before the following reply", async () => { + const events = await collectHistory([ + { + role: "toolResult", + toolCallId: "image-position", + toolName: "read", + content: [{ type: "image", data: "aGVsbG8=", mimeType: "image/png" }], + }, + { role: "assistant", content: [{ type: "text", text: "Image read complete." }] }, + ]); + expect( + events.map((event) => + event.item?.type === "assistant_message" ? event.item.text : event.item?.type, + ), + ).toEqual(["tool_call", expect.stringContaining("![Image]("), "Image read complete."]); +}); diff --git a/packages/server/src/server/agent/providers/pi/history-mapper.ts b/packages/server/src/server/agent/providers/pi/history-mapper.ts index 27a0250b00..89d9fcedce 100644 --- a/packages/server/src/server/agent/providers/pi/history-mapper.ts +++ b/packages/server/src/server/agent/providers/pi/history-mapper.ts @@ -1,5 +1,9 @@ import { mapCustomMessageToToolCall } from "../custom-message.js"; import type { AgentStreamEvent, AgentTimelineItem, ToolCallDetail } from "../../agent-sdk-types.js"; +import { + materializeProviderImage, + renderProviderImageOutputAsAssistantMarkdown, +} from "../provider-image-output.js"; import { createPiExtensionHost, type PiExtensionEventOutput, @@ -11,6 +15,7 @@ import { mapToolDetail, parseToolArgs, parseToolResult, + splitPiToolResultImages, type PiToolResult, type PiTrackedToolCall, } from "./tool-call-mapper.js"; @@ -71,7 +76,7 @@ export class PiHistoryMapper { private readonly extensionHost: PiExtensionHost = createPiExtensionHost(), ) {} - mapMessages(messages: readonly PiAgentMessage[]): AgentStreamEvent[] { + async mapMessages(messages: readonly PiAgentMessage[]): Promise { const events: AgentStreamEvent[] = []; for (const message of messages) { @@ -86,7 +91,7 @@ export class PiHistoryMapper { events.push(...this.mapAssistantMessage(message)); break; case "toolResult": { - events.push(...this.mapToolResultMessage(message)); + events.push(...(await this.mapToolResultMessage(message))); break; } case "bashExecution": @@ -207,24 +212,35 @@ export class PiHistoryMapper { return events; } - private mapToolResultMessage( + private async mapToolResultMessage( message: Extract, - ): AgentStreamEvent[] { + ): Promise { const tracked = this.pendingToolCalls.get(message.toolCallId) ?? parseToolArgs(message.toolName, null); this.pendingToolCalls.delete(message.toolCallId); const result = parseToolResult({ content: message.content, details: message.details }); + // Pull image blocks out of the result so base64 never reaches the tool output, then render + // each one as an assistant_message markdown image after the tool_call (mirroring the live + // path and the Claude provider, upstream #1717). + const { images, result: splitResult } = splitPiToolResultImages(result); const mapping = this.extensionHost.mapToolCall({ callId: message.toolCallId, toolName: tracked.toolName, args: tracked.args, status: message.isError ? "failed" : "completed", - result, + result: splitResult, }); - const detail = this.mapToolDetail(message.toolCallId, tracked, result, mapping?.detail); + const detail = this.mapToolDetail(message.toolCallId, tracked, splitResult, mapping?.detail); if (!detail) { return []; } + const imageEvents: AgentStreamEvent[] = []; + for (const image of images) { + const item = await renderProviderImageOutputAsAssistantMarkdown(image, { + materialize: materializeProviderImage, + }); + if (item) imageEvents.push({ type: "timeline", provider: this.provider, item }); + } return [ { type: "timeline", @@ -234,9 +250,10 @@ export class PiHistoryMapper { name: mapping?.name ?? tracked.toolName, isError: Boolean(message.isError), detail, - errorText: extractTextFromToolResult(result) ?? "Tool call failed", + errorText: extractTextFromToolResult(splitResult) ?? "Tool call failed", }), }, + ...imageEvents, ...this.extensionEvents(mapping), ]; } @@ -297,9 +314,10 @@ export async function* streamPiHistory( signal?: AbortSignal, ): AsyncGenerator { const mapper = new PiHistoryMapper(provider, userEntries, hooks, extensionHost); - for (const event of mapper.mapMessages(messages)) { + for (const message of messages) { if (signal?.aborted) return; - if (event) { + for (const event of await mapper.mapMessages([message])) { + if (signal?.aborted) return; yield event; } } diff --git a/packages/server/src/server/agent/providers/pi/tool-call-mapper.test.ts b/packages/server/src/server/agent/providers/pi/tool-call-mapper.test.ts index 63b557f994..0c065e27cd 100644 --- a/packages/server/src/server/agent/providers/pi/tool-call-mapper.test.ts +++ b/packages/server/src/server/agent/providers/pi/tool-call-mapper.test.ts @@ -1,6 +1,12 @@ import { describe, expect, test } from "vitest"; -import { mapToolDetail, parseToolArgs, parseToolResult } from "./tool-call-mapper.js"; +import { + extractTextFromToolResult, + mapToolDetail, + parseToolArgs, + parseToolResult, + splitPiToolResultImages, +} from "./tool-call-mapper.js"; describe("Pi tool call mapper", () => { test("maps bash args and result to shell detail", () => { @@ -56,3 +62,77 @@ describe("Pi tool call mapper", () => { }); }); }); + +describe("splitPiToolResultImages", () => { + test("extracts image blocks and replaces them with [image] placeholders", () => { + const parsed = parseToolResult({ + content: [ + { type: "text", text: "shot taken" }, + { type: "image", data: "aGVsbG8=", mimeType: "image/png" }, + ], + }); + const { images, result } = splitPiToolResultImages(parsed); + + expect(images).toEqual([{ data: "aGVsbG8=", mimeType: "image/png" }]); + expect(result).toEqual({ + content: [ + { type: "text", text: "shot taken" }, + { type: "text", text: "[image]" }, + ], + }); + }); + + test("replaces image-only results with a non-empty placeholder", () => { + const parsed = parseToolResult({ + content: [{ type: "image", data: "aGVsbG8=", mimeType: "image/jpeg" }], + }); + const { images, result } = splitPiToolResultImages(parsed); + + expect(images).toHaveLength(1); + expect(extractTextFromToolResult(result)).toBe("[image]"); + }); + + test("passes through string results and results without images", () => { + expect(splitPiToolResultImages("plain output")).toEqual({ + images: [], + result: "plain output", + }); + const textOnly = parseToolResult({ content: [{ type: "text", text: "no images" }] }); + expect(splitPiToolResultImages(textOnly)).toEqual({ images: [], result: textOnly }); + expect(splitPiToolResultImages(null)).toEqual({ images: [], result: null }); + }); + + test("keeps other fields on the result object", () => { + const parsed = parseToolResult({ + exitCode: 0, + content: [{ type: "image", data: "aGVsbG8=" }], + }); + const { result } = splitPiToolResultImages(parsed); + expect(result).toMatchObject({ exitCode: 0 }); + }); +}); + +test("tool-result images remove nested structured image data while preserving metadata", () => { + const data = Buffer.from("nested screenshot bytes").toString("base64"); + const result = parseToolResult({ + content: [{ type: "image", data, mimeType: "image/png" }], + structuredContent: { + content: [{ type: "image", data, mimeType: "image/png", width: 64 }], + captureId: "capture-1", + read: { type: "image", data, mimeType: "image/png", note: "Read image file" }, + extra: { data: "keep ordinary data" }, + }, + }); + const split = splitPiToolResultImages(result); + const detail = mapToolDetail(parseToolArgs("screenshot", {}), split.result); + expect(JSON.stringify(detail)).not.toContain(data); + expect(split.images).toEqual([{ data, mimeType: "image/png" }]); + expect(split.result).toMatchObject({ + structuredContent: { + content: [{ type: "image", data: "[image]", mimeType: "image/png", width: 64 }], + captureId: "capture-1", + read: { type: "image", data: "[image]", mimeType: "image/png", note: "Read image file" }, + extra: { data: "keep ordinary data" }, + }, + }); +}); diff --git a/packages/server/src/server/agent/providers/pi/tool-call-mapper.ts b/packages/server/src/server/agent/providers/pi/tool-call-mapper.ts index 8c18a8fdbf..8fbba690b8 100644 --- a/packages/server/src/server/agent/providers/pi/tool-call-mapper.ts +++ b/packages/server/src/server/agent/providers/pi/tool-call-mapper.ts @@ -1,6 +1,7 @@ import { z } from "zod"; import type { ToolCallDetail } from "../../agent-sdk-types.js"; +import type { ProviderImageOutput } from "../provider-image-output.js"; interface BashToolInput { command: string; @@ -52,6 +53,7 @@ interface PiToolResultObject { stdout?: string; text?: string; content?: PiToolResultContent[]; + structuredContent?: unknown; exitCode?: number; code?: number; details?: PiToolResultDetails; @@ -67,6 +69,12 @@ interface PiToolResultTextContent { text: string; } +const PiToolResultImageContentSchema = z.object({ + type: z.literal("image"), + data: z.string().min(1), + mimeType: z.string().optional(), +}); + interface PiToolResultUnknownContent { type: string; } @@ -236,6 +244,61 @@ export function parseToolResult(rawResult: unknown): PiToolResult { return null; } +// Pi returns images inside tool-result content as base64 blocks. Left in place they reach the +// tool-output stringifier, which dumps base64 into the tool output. We pull those blocks out to +// render them as image markdown and leave a "[image]" placeholder so image-only results still +// produce non-empty output (mirroring splitClaudeToolResultImages). +export function splitPiToolResultImages(result: PiToolResult): { + images: ProviderImageOutput[]; + result: PiToolResult; +} { + if (!result || typeof result === "string" || !result.content) { + return { images: [], result }; + } + const images: ProviderImageOutput[] = []; + let replaced = false; + const content = result.content.map((block) => { + const image = toPiImageOutput(block); + if (image) { + images.push(image); + replaced = true; + return { type: "text", text: "[image]" } satisfies PiToolResultTextContent; + } + return block; + }); + if (!replaced) { + return { images: [], result }; + } + return { + images, + result: { + ...result, + content, + ...(result.structuredContent === undefined + ? {} + : { structuredContent: withoutImageData(result.structuredContent) }), + }, + }; +} + +function withoutImageData(value: unknown): unknown { + if (Array.isArray(value)) return value.map(withoutImageData); + if (value === null || typeof value !== "object") return value; + const image = toPiImageOutput(value); + return Object.fromEntries( + Object.entries(value).map(([key, child]) => [ + key, + image && key === "data" ? "[image]" : withoutImageData(child), + ]), + ); +} + +function toPiImageOutput(block: unknown): ProviderImageOutput | null { + const parsed = PiToolResultImageContentSchema.safeParse(block); + if (!parsed.success) return null; + return { data: parsed.data.data, mimeType: parsed.data.mimeType ?? null }; +} + export function extractTextFromToolResult(result: PiToolResult): string | undefined { if (typeof result === "string") { return result; From 9477fe0c0053b40be41b0a690cdb987e815f0901 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Fri, 30 Oct 2026 17:22:53 +0700 Subject: [PATCH 125/173] fix(app): refresh Android layout after background fold changes (#8285) Backport the Unistyles 3.5.3 Activity configuration fix while keeping 3.2.4 and its existing fixes. Application resources could leave the responsive shell on the previous fold size after resume. Cover the real device-state sequence with a native UI regression. --- docs/mobile-testing.md | 14 ++ packages/app/e2e/mobile/fold/android.mjs | 104 +++++++++++++++ patches/react-native-unistyles+3.2.4.patch | 148 +++++++++++++++++++++ scripts/postinstall-patches.mjs | 2 + 4 files changed, 268 insertions(+) create mode 100644 packages/app/e2e/mobile/fold/android.mjs diff --git a/docs/mobile-testing.md b/docs/mobile-testing.md index 169803c0eb..903244e3d9 100644 --- a/docs/mobile-testing.md +++ b/docs/mobile-testing.md @@ -35,6 +35,20 @@ PASEO_MOBILE_E2E_METRO_PORT=62093 npm run test:e2e:mobile [native-terminal-basic.ios.ad](../packages/app/e2e/mobile/agent-device/native-terminal-basic.ios.ad) and [native-terminal-basic.android.ad](../packages/app/e2e/mobile/agent-device/native-terminal-basic.android.ad) are the smallest examples. Each opens a fresh terminal, types a command at zero delay, submits it, and asserts its distinct output. The app must be connected to a daemon with an active workspace. +For Android background fold recovery, install the release APK on a foldable AVD, open a +connected workspace, close the keyboard, and run: + +```bash +ANDROID_SERIAL=emulator-5574 node packages/app/e2e/mobile/fold/android.mjs +``` + +The AVD must expose `CLOSED` and `OPENED` device states. The test backgrounds the app, +changes posture, resumes immediately, and asserts compact/wide workspace controls without +restarting the process. It writes snapshots and native failure state under +`.dev/agent-device-artifacts/android-fold`. Set `PASEO_MOBILE_APP_ID=sh.paseo` for a +production package. This needs a native rebuild when the Unistyles patch changes; a Metro +reload cannot update it. + For Android keyboard continuity, run the current checkout in the app, open an idle terminal with an empty prompt, hide its keyboard, and run: diff --git a/packages/app/e2e/mobile/fold/android.mjs b/packages/app/e2e/mobile/fold/android.mjs new file mode 100644 index 0000000000..93f23dc111 --- /dev/null +++ b/packages/app/e2e/mobile/fold/android.mjs @@ -0,0 +1,104 @@ +// Run a release build with a connected workspace open and the keyboard hidden. +// ANDROID_SERIAL=emulator-5574 node packages/app/e2e/mobile/fold/android.mjs +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; + +const serial = process.env.ANDROID_SERIAL; +assert(serial, "Set ANDROID_SERIAL to a booted Android foldable emulator"); +const appId = process.env.PASEO_MOBILE_APP_ID ?? "sh.paseo.debug"; +const session = "android-fold"; +const artifacts = resolve(".dev/agent-device-artifacts/android-fold"); +const env = { + ...process.env, + AGENT_DEVICE_STATE_DIR: resolve(".dev/agent-device-android-fold"), +}; +mkdirSync(artifacts, { recursive: true }); + +function run(binary, args) { + return execFileSync(binary, args, { env, encoding: "utf8", timeout: 60_000 }); +} +function adb(...args) { + return run("adb", ["-s", serial, ...args]); +} +function ad(...args) { + return run("agent-device", [...args, "--session", session]); +} +function pid() { + return adb("shell", "pidof", appId).trim(); +} +function open() { + ad("open", appId, "--platform", "android", "--serial", serial, "--no-test-ime"); +} +function stateId(name) { + const states = adb("shell", "cmd", "device_state", "print-states"); + const match = states.match(new RegExp(`identifier=(\\d+), name='${name}'`)); + assert(match, `Emulator must expose the ${name} posture: ${states}`); + return match[1]; +} + +async function expectLayout(posture) { + const compact = posture === "CLOSED"; + const expectedId = compact ? "workspace-tab-switcher-trigger" : "workspace-tabs-scroll"; + const unexpectedId = compact ? "workspace-tabs-scroll" : "workspace-tab-switcher-trigger"; + const deadline = Date.now() + 15_000; + let nodes = []; + do { + let data; + try { + ({ data } = JSON.parse(ad("snapshot", "-i", "--json"))); + } catch (error) { + // During display handoff Android briefly has no capturable app window. + if (!error.stdout?.includes("insufficient foreground app content")) throw error; + await delay(200); + continue; + } + assert.equal(data.appBundleId, appId, "Snapshot must belong to Paseo"); + nodes = data.nodes; + if ( + nodes.some((node) => node.identifier === expectedId) && + !nodes.some((node) => node.identifier === unexpectedId) + ) { + writeFileSync(resolve(artifacts, `${posture}.json`), JSON.stringify(data, null, 2)); + console.log(`PASS: ${posture} uses ${compact ? "compact" : "wide"} workspace controls`); + return; + } + await delay(200); + } while (Date.now() < deadline); + writeFileSync(resolve(artifacts, `${posture}-failure.json`), JSON.stringify(nodes, null, 2)); + writeFileSync( + resolve(artifacts, "native-failure.txt"), + adb("shell", "dumpsys", "activity", "top"), + ); + assert.fail(`${posture}: expected ${expectedId}, without ${unexpectedId}`); +} + +const closed = stateId("CLOSED"); +const opened = stateId("OPENED"); +const initialState = adb("shell", "cmd", "device_state", "state").match( + /Committed state: DeviceState\{identifier=(\d+)/, +)?.[1]; +assert(initialState, "Could not read the initial fold state"); + +try { + adb("shell", "cmd", "device_state", "state", opened); + open(); + await expectLayout("OPENED"); + const initialPid = pid(); + for (const [posture, id] of [ + ["CLOSED", closed], + ["OPENED", opened], + ]) { + adb("shell", "input", "keyevent", "KEYCODE_HOME"); + adb("shell", "cmd", "device_state", "state", id); + // Resume immediately: waiting for configuration delivery hides the regression. + open(); + await expectLayout(posture); + assert.equal(pid(), initialPid, "Fold/resume must preserve the app process"); + } +} finally { + adb("shell", "cmd", "device_state", "state", initialState); + ad("close"); +} diff --git a/patches/react-native-unistyles+3.2.4.patch b/patches/react-native-unistyles+3.2.4.patch index 1930a4db84..af825a6afa 100644 --- a/patches/react-native-unistyles+3.2.4.patch +++ b/patches/react-native-unistyles+3.2.4.patch @@ -557,3 +557,151 @@ index a16dac0..6519858 100644 return ColorScheme.Dark default: return ColorScheme.Unspecified +diff --git a/node_modules/react-native-unistyles/android/src/main/java/com/unistyles/NativePlatform+android.kt b/node_modules/react-native-unistyles/android/src/main/java/com/unistyles/NativePlatform+android.kt +index 0f8d1f0..154a12a 100644 +--- a/node_modules/react-native-unistyles/android/src/main/java/com/unistyles/NativePlatform+android.kt ++++ b/node_modules/react-native-unistyles/android/src/main/java/com/unistyles/NativePlatform+android.kt +@@ -3,11 +3,16 @@ package com.unistyles + import android.os.Build + import android.content.Context + import android.content.res.Configuration ++import android.content.res.Resources ++import android.os.Handler ++import android.os.Looper + import android.util.DisplayMetrics + import android.view.View + import android.view.WindowManager + import androidx.annotation.Keep ++import androidx.core.content.OnConfigurationChangedProvider + import androidx.core.text.TextUtilsCompat ++import androidx.core.util.Consumer + import androidx.core.view.ViewCompat + import androidx.core.view.WindowCompat + import androidx.core.view.WindowInsetsCompat +@@ -22,6 +27,7 @@ import com.margelo.nitro.unistyles.Insets + import com.margelo.nitro.unistyles.Orientation + import com.margelo.nitro.unistyles.UnistyleDependency + import com.margelo.nitro.unistyles.UnistylesNativeMiniRuntime ++import java.lang.ref.WeakReference + import java.util.Locale + + @Keep +@@ -30,6 +36,14 @@ class NativePlatformAndroid(private val reactContext: ReactApplicationContext): + private val _insets = NativePlatformInsets(reactContext, this::getMiniRuntime) { this.onConfigChange() } + private var _miniRuntime: UnistylesNativeMiniRuntime = buildMiniRuntime() + private val _listener = NativePlatformListener(reactContext, this::getMiniRuntime) { this.diffMiniRuntime() } ++ private var _configurationProvider: WeakReference? = null ++ private val _activityConfigurationListener = Consumer { ++ Handler(Looper.getMainLooper()).post { this.onConfigChange() } ++ } ++ ++ // Application resources can lag behind configuration changes ++ private val configurationResources: Resources ++ get() = reactContext.currentActivity?.resources ?: reactContext.resources + + init { + checkEdgeToEdge() +@@ -37,12 +51,16 @@ class NativePlatformAndroid(private val reactContext: ReactApplicationContext): + } + + fun onDestroy() { ++ stopObservingActivityConfiguration() + _listener.onDestroy() + _insets.onDestroy() + reactContext.removeLifecycleEventListener(this) + } + + override fun onHostResume() { ++ observeActivityConfiguration() ++ // catch configuration changes missed while no Activity was attached ++ onConfigChange() + _insets.getInitialInsets(false) + _insets.startInsetsListener() + } +@@ -51,7 +69,26 @@ class NativePlatformAndroid(private val reactContext: ReactApplicationContext): + _insets.stopInsetsListener() + } + +- override fun onHostDestroy() {} ++ override fun onHostDestroy() { ++ stopObservingActivityConfiguration() ++ } ++ ++ private fun observeActivityConfiguration() { ++ val provider = reactContext.currentActivity as? OnConfigurationChangedProvider ++ ++ if (_configurationProvider?.get() === provider) { ++ return ++ } ++ ++ stopObservingActivityConfiguration() ++ provider?.addOnConfigurationChangedListener(_activityConfigurationListener) ++ _configurationProvider = provider?.let { WeakReference(it) } ++ } ++ ++ private fun stopObservingActivityConfiguration() { ++ _configurationProvider?.get()?.removeOnConfigurationChangedListener(_activityConfigurationListener) ++ _configurationProvider = null ++ } + + override val memorySize: Long + get() = 0 +@@ -61,7 +98,7 @@ class NativePlatformAndroid(private val reactContext: ReactApplicationContext): + } + + override fun getColorScheme(): ColorScheme { +- val uiMode = reactContext.resources.configuration.uiMode ++ val uiMode = configurationResources.configuration.uiMode + + val colorScheme = when (uiMode.and(Configuration.UI_MODE_NIGHT_MASK)) { + Configuration.UI_MODE_NIGHT_YES -> ColorScheme.DARK +@@ -73,15 +110,15 @@ class NativePlatformAndroid(private val reactContext: ReactApplicationContext): + } + + override fun getFontScale(): Double { +- return reactContext.resources.configuration.fontScale.toDouble() ++ return configurationResources.configuration.fontScale.toDouble() + } + + override fun getPixelRatio(): Double { +- return reactContext.resources.displayMetrics.density.toDouble() ++ return configurationResources.displayMetrics.density.toDouble() + } + + override fun getOrientation(): Orientation { +- val orientation = when (reactContext.resources.configuration.orientation) { ++ val orientation = when (configurationResources.configuration.orientation) { + Configuration.ORIENTATION_PORTRAIT -> Orientation.PORTRAIT + Configuration.ORIENTATION_LANDSCAPE -> Orientation.LANDSCAPE + else -> Orientation.PORTRAIT +@@ -122,7 +159,7 @@ class NativePlatformAndroid(private val reactContext: ReactApplicationContext): + return Dimensions(screenWidth, screenHeight) + } + else -> { +- val displayMetrics = reactContext.resources.displayMetrics ++ val displayMetrics = configurationResources.displayMetrics + + reactContext.currentActivity?.windowManager?.currentWindowMetrics?.bounds?.let { + val boundsWidth = (it.width() / displayMetrics.density).toDouble() +@@ -157,7 +194,7 @@ class NativePlatformAndroid(private val reactContext: ReactApplicationContext): + "com.facebook.react.modules.i18nmanager.I18nUtil", + Context.MODE_PRIVATE + ) +- val resourcesLocale = reactContext.resources.configuration.locales[0] ++ val resourcesLocale = configurationResources.configuration.locales[0] + val hasForcedRtl = sharedPrefs.getBoolean("RCTI18nUtil_forceRTL", false) + // user preferences + val isRtl = TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault()) == ViewCompat.LAYOUT_DIRECTION_RTL +diff --git a/node_modules/react-native-unistyles/android/src/main/java/com/unistyles/NativePlatform+insets.kt b/node_modules/react-native-unistyles/android/src/main/java/com/unistyles/NativePlatform+insets.kt +index a9c1804..f5a3c20 100644 +--- a/node_modules/react-native-unistyles/android/src/main/java/com/unistyles/NativePlatform+insets.kt ++++ b/node_modules/react-native-unistyles/android/src/main/java/com/unistyles/NativePlatform+insets.kt +@@ -38,7 +38,7 @@ class NativePlatformInsets( + } + + fun getInsets(): Insets { +- val density = reactContext.resources.displayMetrics.density ++ val density = (reactContext.currentActivity?.resources ?: reactContext.resources).displayMetrics.density + + return Insets( + this._insets.top / density, diff --git a/scripts/postinstall-patches.mjs b/scripts/postinstall-patches.mjs index eca0fde25f..312bb90724 100644 --- a/scripts/postinstall-patches.mjs +++ b/scripts/postinstall-patches.mjs @@ -26,6 +26,8 @@ const patchedPackages = [ // https://github.com/jpudysz/react-native-unistyles/pull/1203. // Adaptive themes: keep until colorScheme reads no longer consume listener-owned media changes. // withUnistyles: also keep the uniProps filter until upstream consumes its control prop. + // Android configuration: backport 3.5.3; remove the two NativePlatform hunks at >= 3.5.3. + // https://github.com/jpudysz/react-native-unistyles/compare/v3.5.2...v3.5.3 { nodeModulesPath: "node_modules/react-native-unistyles", patchPrefix: "react-native-unistyles+", From 385c29b655a784a236c0f580ec4893500de3af1a Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Fri, 30 Oct 2026 17:57:52 +0700 Subject: [PATCH 126/173] Keep failed chat history available for retry (#8278) * fix(app): keep failed chat history until retry Automatic retries repeatedly reopen provider sessions after persistent failures. Keep the error visible until the user retries, while retaining reconnect recovery. * fix(app): catch up chats after subscription failure A failed replacement subscription leaves chats unsubscribed, so discard its old catch-up state and fetch missed history after retry. * fix(app): recover gaps during history retry Keep gap recovery active while a user-initiated retry is running so the chat is not marked current before its follow-up fetch. * fix(app): show history errors in archived chats Cached archived chats need the same manual retry affordance when history synchronization fails. --- packages/app/src/contexts/session-context.tsx | 4 - .../use-agent-screen-state-machine.test.ts | 17 ++ .../hooks/use-agent-screen-state-machine.ts | 8 +- .../src/stores/workspace-layout-store.test.ts | 1 - packages/app/src/timeline/replica.test.ts | 2 - .../src/timeline/viewed-timeline-sync.test.ts | 226 +++++++++--------- .../app/src/timeline/viewed-timeline-sync.ts | 87 ++----- 7 files changed, 155 insertions(+), 190 deletions(-) diff --git a/packages/app/src/contexts/session-context.tsx b/packages/app/src/contexts/session-context.tsx index bccd4d3ee0..89c32c0bd5 100644 --- a/packages/app/src/contexts/session-context.tsx +++ b/packages/app/src/contexts/session-context.tsx @@ -455,10 +455,6 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider reportError: (error) => { console.warn("[Session] viewed timeline synchronization failed", { serverId, error }); }, - schedule: (task, delayMs) => { - const timeout = setTimeout(task, delayMs); - return () => clearTimeout(timeout); - }, }); viewedTimelineSyncRef.current = sync; setViewedTimelineSync(serverId, sync); diff --git a/packages/app/src/hooks/use-agent-screen-state-machine.test.ts b/packages/app/src/hooks/use-agent-screen-state-machine.test.ts index 19caef4f8b..68102ed131 100644 --- a/packages/app/src/hooks/use-agent-screen-state-machine.test.ts +++ b/packages/app/src/hooks/use-agent-screen-state-machine.test.ts @@ -422,6 +422,23 @@ describe("deriveAgentScreenViewState", () => { expect(result.memory.lastReadyAgent).toBeNull(); }); + it.each(["error", "retrying"] as const)("shows archived history sync %s", (status) => { + const result = deriveAgentScreenViewState({ + input: { + ...createBaseInput(), + agent: createAgent("agent-1"), + isArchived: true, + hasHydratedHistoryBefore: true, + visibilityCatchUpStatus: status, + }, + memory: createBaseMemory(), + }); + expect(expectReadyState(result.state).sync).toEqual({ + status: "sync_error", + isRetrying: status === "retrying", + }); + }); + it("renders an archived agent before provider history is initialized", () => { const result = deriveAgentScreenViewState({ input: { diff --git a/packages/app/src/hooks/use-agent-screen-state-machine.ts b/packages/app/src/hooks/use-agent-screen-state-machine.ts index 591fd1abb1..e0cc75ee06 100644 --- a/packages/app/src/hooks/use-agent-screen-state-machine.ts +++ b/packages/app/src/hooks/use-agent-screen-state-machine.ts @@ -175,10 +175,14 @@ function resolveAgentScreenSync(args: { hadInitialSyncFailure: boolean; }): AgentScreenReadySyncState { const { input, hadInitialSyncFailure } = args; - if (input.isArchived) { + if ( + input.isArchived && + input.visibilityCatchUpStatus !== "error" && + input.visibilityCatchUpStatus !== "retrying" + ) { return { status: "idle" }; } - if (!input.isConnected) { + if (!input.isConnected && !input.isArchived) { return { status: "reconnecting" }; } if (input.missingAgentState.kind === "error") { diff --git a/packages/app/src/stores/workspace-layout-store.test.ts b/packages/app/src/stores/workspace-layout-store.test.ts index 1946586e84..8b478b7d27 100644 --- a/packages/app/src/stores/workspace-layout-store.test.ts +++ b/packages/app/src/stores/workspace-layout-store.test.ts @@ -174,7 +174,6 @@ it("feeds restored layout to timeline sync as a release signal, not a subscripti fetchLatestTail: async () => ({ hasNewer: false, endCursor: null }), onCatchUpEnded: () => undefined, reportError: () => undefined, - schedule: () => () => undefined, }); // The edge session-context.tsx owns. Pointing it at subscription instead would resume every // agent behind a restored tab on the daemon. diff --git a/packages/app/src/timeline/replica.test.ts b/packages/app/src/timeline/replica.test.ts index 0d825673e9..859ae8e6b7 100644 --- a/packages/app/src/timeline/replica.test.ts +++ b/packages/app/src/timeline/replica.test.ts @@ -57,7 +57,6 @@ function createOwner(storage: TimelineReplicaStorage): ViewedTimelineOwner { fetchPage: async () => ({ hasNewer: false, endCursor: null }), fetchLatestTail: async () => ({ hasNewer: false, endCursor: null }), reportError: () => undefined, - schedule: () => () => undefined, }, }); } @@ -617,7 +616,6 @@ describe("create handoff lifetime", () => { }, fetchLatestTail: async () => ({ hasNewer: false, endCursor: null }), reportError: () => undefined, - schedule: () => () => undefined, }, }); diff --git a/packages/app/src/timeline/viewed-timeline-sync.test.ts b/packages/app/src/timeline/viewed-timeline-sync.test.ts index a6e7cbeb33..e556da612f 100644 --- a/packages/app/src/timeline/viewed-timeline-sync.test.ts +++ b/packages/app/src/timeline/viewed-timeline-sync.test.ts @@ -90,7 +90,7 @@ test("visible catch-up settles before hidden open chats start fetching", async ( world.sync.dispose(); }); -test("a failed visible catch-up releases hidden chats without bypassing its retry delay", async () => { +test("a failed visible catch-up releases hidden chats without bypassing its error", async () => { const world = new TimelineWorld(); world.openedEarlier(["a-hidden"]); world.sync.replaceVisibleAgentIds("pane", ["z-visible"]); @@ -103,7 +103,7 @@ test("a failed visible catch-up releases hidden chats without bypassing its retr hidden.respond({ hasNewer: false }); await world.nextError(); world.expectNoPendingFetch(); - (await world.nextRetry())(); + world.sync.retryVisibleAgentTimeline("z-visible"); (await world.nextFetch("z-visible")).respond({ hasNewer: false }); world.sync.dispose(); }); @@ -200,20 +200,6 @@ class TimelineWorld { const waiter = this.errorWaiters.shift(); if (waiter) waiter(this.errors.at(-1) ?? ""); }, - schedule: (task, delayMs) => { - const scheduled = { task, delayMs }; - this.scheduled.push(scheduled); - const waiterIndex = this.retryWaiters.findIndex((waiter) => waiter.delayMs === delayMs); - if (waiterIndex >= 0) { - const [waiter] = this.retryWaiters.splice(waiterIndex, 1); - this.scheduled.splice(this.scheduled.indexOf(scheduled), 1); - waiter.resolve(task); - } - return () => { - const index = this.scheduled.indexOf(scheduled); - if (index >= 0) this.scheduled.splice(index, 1); - }; - }, }); show(sourceId: string, agentIds: string[]): void { @@ -235,12 +221,6 @@ class TimelineWorld { }> = []; private readonly errorWaiters: Array<(message: string) => void> = []; private readonly cacheRequestWaiters: Array<(agentId: string) => void> = []; - private readonly scheduled: Array<{ task: () => void; delayMs: number }> = []; - private readonly retryWaiters: Array<{ - delayMs: number; - resolve(retry: () => void): void; - }> = []; - get pendingFetchCount(): number { return this.fetches.length; } @@ -300,22 +280,6 @@ class TimelineWorld { return new Promise((resolve) => this.errorWaiters.push(resolve)); } - nextRetry(delayMs = 1_000): Promise<() => void> { - const index = this.scheduled.findIndex((entry) => entry.delayMs === delayMs); - if (index >= 0) return Promise.resolve(this.scheduled.splice(index, 1)[0].task); - return new Promise((resolve) => this.retryWaiters.push({ delayMs, resolve })); - } - - elapse(elapsedMs: number): void { - const due = this.scheduled.filter((entry) => entry.delayMs <= elapsedMs); - this.scheduled.splice( - 0, - this.scheduled.length, - ...this.scheduled.filter((entry) => entry.delayMs > elapsedMs), - ); - for (const entry of due) entry.task(); - } - private releaseMembershipWaiter(): void { const waiter = this.membershipWaiters.shift(); if (!waiter) return; @@ -483,6 +447,28 @@ test("reports a chat current only once its parked follow-up page completes", asy world.sync.dispose(); }); +test("a gap during manual retry is recovered before reporting ready", async () => { + const world = new TimelineWorld(); + world.sync.setConnected(true); + world.show("workspace", ["agent-a"]); + (await world.nextMembership()).succeed(); + (await world.nextFetch("agent-a")).fail("unavailable"); + await world.nextError(); + world.sync.retryVisibleAgentTimeline("agent-a"); + const retry = await world.nextFetch("agent-a"); + world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 9 }); + retry.respond({ hasNewer: false }); + await vi.waitFor(() => expect(world.pendingFetchCount).toBe(1)); + const recovery = await world.nextFetch("agent-a"); + expect(recovery.request).toMatchObject({ + direction: "after", + cursor: { epoch: "epoch-agent-a", seq: 9 }, + }); + expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("retrying"); + recovery.respond({ hasNewer: false }); + await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready")); +}); + test("reports a chat current once the latest-tail fallback replaces an overflowing catch-up", async () => { const world = new TimelineWorld(); world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 42 }); @@ -780,6 +766,21 @@ test("overlapping sources deduplicate membership and retain open hidden chats", world.expectNoPendingFetch(); }); +test("failed timeline fetch does not schedule a retry", async () => { + vi.useFakeTimers(); + const world = new TimelineWorld(); + world.sync.setConnected(true); + world.show("workspace", ["agent-a"]); + (await world.nextMembership()).succeed(); + (await world.nextFetch("agent-a")).fail("unavailable"); + await world.nextError(); + expect(vi.getTimerCount()).toBe(0); + await vi.advanceTimersByTimeAsync(120_000); + world.expectNoPendingFetch(); + world.expectNoPendingMembership(); + vi.useRealTimers(); +}); + test("a failed catch-up reports once and retries through the explicit retry policy", async () => { const world = new TimelineWorld(); world.sync.setConnected(true); @@ -788,12 +789,12 @@ test("a failed catch-up reports once and retries through the explicit retry poli membership.succeed(); const failed = await world.nextFetch("agent-a"); failed.fail("timeline unavailable"); - const [error, retryCatchUp] = await Promise.all([world.nextError(), world.nextRetry()]); + const error = await world.nextError(); expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error"); - retryCatchUp(); + world.sync.retryVisibleAgentTimeline("agent-a"); const retry = await world.nextFetch("agent-a"); - expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error"); + expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("retrying"); retry.respond({ hasNewer: false }); await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready")); @@ -804,35 +805,6 @@ test("a failed catch-up reports once and retries through the explicit retry poli world.expectNoPendingMembership(); }); -test("a failed catch-up retries with exponential backoff", async () => { - const world = new TimelineWorld(); - world.sync.setConnected(true); - world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]); - const membership = await world.nextMembership(); - membership.succeed(); - - const first = await world.nextFetch("agent-a"); - first.fail("timeline unavailable"); - const [firstError, retryAfterFirstFailure] = await Promise.all([ - world.nextError(), - world.nextRetry(), - ]); - expect(firstError).toBe("timeline unavailable"); - retryAfterFirstFailure(); - - const second = await world.nextFetch("agent-a"); - second.fail("timeline unavailable"); - await world.nextError(); - - const retryAfterSecondFailure = await world.nextRetry(2_000); - expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error"); - - retryAfterSecondFailure(); - const third = await world.nextFetch("agent-a"); - third.respond({ hasNewer: false }); - await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready")); -}); - test("manual retries can immediately re-attempt a failed catch-up", async () => { const world = new TimelineWorld(); world.sync.setConnected(true); @@ -842,7 +814,7 @@ test("manual retries can immediately re-attempt a failed catch-up", async () => const failed = await world.nextFetch("agent-a"); failed.fail("timeline unavailable"); - await world.nextRetry(); + await world.nextError(); expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error"); world.sync.retryVisibleAgentTimeline("agent-a"); @@ -853,7 +825,7 @@ test("manual retries can immediately re-attempt a failed catch-up", async () => await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready")); }); -test("redeclaring unchanged visibility does not bypass catch-up backoff", async () => { +test("redeclaring unchanged visibility does not bypass catch-up error", async () => { const world = new TimelineWorld(); world.sync.setConnected(true); world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]); @@ -862,9 +834,11 @@ test("redeclaring unchanged visibility does not bypass catch-up backoff", async const failed = await world.nextFetch("agent-a"); failed.fail("timeline unavailable"); - await world.nextRetry(); + await world.nextError(); world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]); + world.sync.setActive(false); + world.sync.setActive(true); world.expectNoPendingMembership(); world.expectNoPendingFetch(); @@ -880,7 +854,7 @@ test("a manual retry that fails returns to the error state", async () => { const failed = await world.nextFetch("agent-a"); failed.fail("timeline unavailable"); - await world.nextRetry(); + await world.nextError(); world.sync.retryVisibleAgentTimeline("agent-a"); expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("retrying"); @@ -943,20 +917,34 @@ test("repeated recovery for the same running gap reuses the in-flight fetch", as gapPage.respond({ hasNewer: false }); }); -test("membership failure autonomously retries without another visibility declaration", async () => { +test("failed membership does not schedule a retry", async () => { + vi.useFakeTimers(); + const world = new TimelineWorld(); + world.sync.setConnected(true); + world.show("workspace", ["agent-a"]); + (await world.nextMembership()).fail("unavailable"); + await world.nextError(); + expect(vi.getTimerCount()).toBe(0); + await vi.advanceTimersByTimeAsync(120_000); + world.expectNoPendingFetch(); + world.expectNoPendingMembership(); + vi.useRealTimers(); +}); + +test("membership failure waits for manual retry", async () => { const world = new TimelineWorld(); world.sync.setConnected(true); world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]); const failed = await world.nextMembership(); failed.fail("subscription unavailable"); - const [error, retryMembership] = await Promise.all([world.nextError(), world.nextRetry()]); + const error = await world.nextError(); expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error"); - retryMembership(); + world.sync.retryVisibleAgentTimeline("agent-a"); const retry = await world.nextMembership(); retry.succeed(); const catchUp = await world.nextFetch("agent-a"); - expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error"); + expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("retrying"); catchUp.respond({ hasNewer: false }); await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready")); @@ -967,44 +955,68 @@ test("membership failure autonomously retries without another visibility declara }); }); -test("membership failures retry with exponential backoff", async () => { +test("retrying membership restores a previously loaded chat", async () => { const world = new TimelineWorld(); world.sync.setConnected(true); - world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]); - - const first = await world.nextMembership(); - first.fail("subscription unavailable"); - const [firstError, retryAfterFirstFailure] = await Promise.all([ - world.nextError(), - world.nextRetry(), - ]); - expect(firstError).toBe("subscription unavailable"); - - retryAfterFirstFailure(); - const second = await world.nextMembership(); - second.fail("subscription unavailable again"); - - const retryAfterSecondFailure = await world.nextRetry(2_000); - expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error"); - - retryAfterSecondFailure(); - const retry = await world.nextMembership(); - retry.succeed(); - const catchUp = await world.nextFetch("agent-a"); - catchUp.respond({ hasNewer: false }); + world.show("workspace", ["agent-a"]); + (await world.nextMembership()).succeed(); + (await world.nextFetch("agent-a")).respond({ hasNewer: false }); + await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready")); + world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 10 }); + world.show("workspace", ["agent-b"]); + (await world.nextMembership()).fail("subscription unavailable"); + await world.nextError(); + world.sync.retryVisibleAgentTimeline("agent-a"); + (await world.nextMembership()).succeed(); + (await world.nextFetch("agent-b")).respond({ hasNewer: false }); + const resumed = await world.nextFetch("agent-a"); + expect(resumed.request).toMatchObject({ + direction: "after", + cursor: { epoch: "epoch-agent-a", seq: 10 }, + }); + resumed.respond({ hasNewer: false }); await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready")); }); -test("redeclaring unchanged visibility does not bypass membership backoff", async () => { +test("a fetch that finishes after membership failure cannot clear the error", async () => { + const world = new TimelineWorld(); + world.sync.setConnected(true); + world.show("workspace", ["agent-a"]); + (await world.nextMembership()).succeed(); + const inFlight = await world.nextFetch("agent-a"); + world.show("workspace", ["agent-b"]); + (await world.nextMembership()).fail("subscription unavailable"); + await world.nextError(); + inFlight.respond({ hasNewer: false }); + await Promise.resolve(); + await Promise.resolve(); + expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error"); +}); + +test("a failed membership retry returns to error", async () => { + const world = new TimelineWorld(); + world.sync.setConnected(true); + world.show("workspace", ["agent-a"]); + (await world.nextMembership()).fail("unavailable"); + await world.nextError(); + world.sync.retryVisibleAgentTimeline("agent-a"); + expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("retrying"); + (await world.nextMembership()).fail("still unavailable"); + await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error")); +}); + +test("redeclaring unchanged visibility does not bypass membership error", async () => { const world = new TimelineWorld(); world.sync.setConnected(true); world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]); const failed = await world.nextMembership(); failed.fail("subscription unavailable"); - await world.nextRetry(); + await world.nextError(); world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]); + world.sync.setActive(false); + world.sync.setActive(true); world.expectNoPendingMembership(); world.expectNoPendingFetch(); @@ -1050,7 +1062,6 @@ test("backgrounding preserves subscriptions and returning verifies the visible c world.sync.setActive(false); world.expectNoPendingMembership(); - world.elapse(60_000); world.sync.setActive(true); world.expectNoPendingMembership(); @@ -1067,11 +1078,10 @@ test("stale membership retry cannot overwrite a newer effective set", async () = world.show("workspace", ["agent-a"]); const failed = await world.nextMembership(); failed.fail("subscription unavailable"); - const staleRetry = await world.nextRetry(); + await world.nextError(); world.show("workspace", ["agent-b"]); const current = await world.nextMembership(); - staleRetry(); current.succeed(); const agentB = await world.nextFetch("agent-b"); agentB.respond({ hasNewer: false }); @@ -1088,10 +1098,9 @@ test("membership retry cannot run while disconnected", async () => { world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]); const failed = await world.nextMembership(); failed.fail("subscription unavailable"); - const disconnectedRetry = await world.nextRetry(); + await world.nextError(); world.sync.setConnected(false); - disconnectedRetry(); world.expectNoPendingMembership(); world.sync.setConnected(true); const restored = await world.nextMembership(); @@ -1118,7 +1127,6 @@ test("returning to an open hidden agent stays live after inactivity", async () = agentBCatchUp.respond({ hasNewer: false }); await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-b")).toBe("ready")); - world.elapse(60_000); world.show("workspace", ["agent-a"]); world.expectNoPendingMembership(); diff --git a/packages/app/src/timeline/viewed-timeline-sync.ts b/packages/app/src/timeline/viewed-timeline-sync.ts index 2e14a42093..67defcec04 100644 --- a/packages/app/src/timeline/viewed-timeline-sync.ts +++ b/packages/app/src/timeline/viewed-timeline-sync.ts @@ -329,7 +329,6 @@ export interface ViewedTimelineSyncPorts { */ onCatchUpEnded(agentId: string): void; reportError(error: unknown): void; - schedule(task: () => void, delayMs: number): () => void; } export type ViewedTimelineStatus = "ready" | "pending" | "error" | "retrying"; @@ -423,26 +422,14 @@ export function createViewedTimelineOwner(input: { }; } -const RETRY_DELAY_MS = 1_000; -const MAX_RETRY_DELAY_MS = 30_000; - type CatchUpStatus = "running" | "complete" | "error"; interface CatchUpState { generation: number; status: CatchUpStatus; request?: ProjectedTimelineForwardFetchPlan; - cancelRetry?: () => void; - retryDelayMs?: number; } -const getNextRetryDelayMs = (previousDelayMs: number | undefined): number => { - if (previousDelayMs == null) { - return RETRY_DELAY_MS; - } - return Math.min(previousDelayMs * 2, MAX_RETRY_DELAY_MS); -}; - function isSameCatchUpRequest( left: ProjectedTimelineForwardFetchPlan | undefined, right: ProjectedTimelineForwardFetchPlan | undefined, @@ -472,9 +459,7 @@ function decideCatchUp(input: { } return "replace"; } - return input.current.status === "running" || input.current.status === "complete" - ? "keep" - : "replace"; + return "keep"; } function normalizeAgentIds(agentIds: string[]): string[] { @@ -494,8 +479,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed const pendingCatchUps = new Map(); const visibilityCatchUpPending = new Set(); const visibilityCatchUpErrors = new Map(); - // User-initiated retries only. Background retries stay silent; a retry the user asked for - // owes them a pending state until it settles. + // A user-initiated retry owes a pending state until it settles. const manualRetries = new Set(); const loadedCache = new Set(); const cacheLoads = new Map>(); @@ -511,8 +495,6 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed let acknowledged: string[] = []; let membershipGeneration = 0; let membershipNeedsRetry = false; - let membershipRetryDelayMs: number | undefined; - let cancelMembershipRetry: (() => void) | null = null; // Chats this session has opened. Visibility is the only way in, so an agent is never // subscribed — and never resumed on the daemon — until the user actually opens it. // Membership then survives hiding, workspace switches, backgrounding and reconnect; @@ -563,7 +545,6 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed const cancelCatchUp = (agentId: string) => { catchUpGenerations.set(agentId, (catchUpGenerations.get(agentId) ?? 0) + 1); - catchUps.get(agentId)?.cancelRetry?.(); catchUps.delete(agentId); pendingCatchUps.delete(agentId); }; @@ -607,19 +588,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed setVisibilityCatchUpReady(agentId); } catch (error) { if (catchUps.get(agentId)?.generation === generation) { - const nextRetryDelayMs = getNextRetryDelayMs(catchUps.get(agentId)?.retryDelayMs); - const cancelRetry = ports.schedule(() => { - const current = catchUps.get(agentId); - if (current?.generation !== generation || current.status !== "error") return; - startCatchUp(agentId); - }, nextRetryDelayMs); - catchUps.set(agentId, { - generation, - status: "error", - request, - cancelRetry, - retryDelayMs: nextRetryDelayMs, - }); + catchUps.set(agentId, { generation, status: "error", request }); setVisibilityCatchUpError([agentId], error); ports.reportError(error); } @@ -686,17 +655,9 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed if (decision === "keep") { return; } - current?.cancelRetry?.(); const generation = (catchUpGenerations.get(agentId) ?? 0) + 1; catchUpGenerations.set(agentId, generation); - const retryDelayMs = - supersede || current?.status !== "error" ? undefined : current.retryDelayMs; - catchUps.set(agentId, { - generation, - status: "running", - request: nextRequest, - retryDelayMs, - }); + catchUps.set(agentId, { generation, status: "running", request: nextRequest }); pendingCatchUps.delete(agentId); void fetchUntilCurrent( agentId, @@ -715,7 +676,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed for (const agentId of ordered) { const pendingCatchUp = pendingCatchUps.get(agentId); const current = catchUps.get(agentId); - // Completion of a different chat must not bypass a failed chat's backoff or + // Completion of a different chat must not bypass a failed chat's error or // supersede an in-flight tail that owns its parked gap recovery. if (current && !(current.status === "complete" && pendingCatchUp)) continue; startCatchUp(agentId, { @@ -741,42 +702,31 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed } catch (error) { if (disposed || !connected || generation !== membershipGeneration) return; membershipNeedsRetry = true; + acknowledged = []; + for (const agentId of requested) cancelCatchUp(agentId); setVisibilityCatchUpError(requested, error); - cancelMembershipRetry?.(); - const nextRetryDelayMs = getNextRetryDelayMs(membershipRetryDelayMs); - cancelMembershipRetry = ports.schedule(() => { - cancelMembershipRetry = null; - if (disposed || !connected || membershipGeneration !== generation) return; - void reconcileMembership(); - }, nextRetryDelayMs); - membershipRetryDelayMs = nextRetryDelayMs; ports.reportError(error); return; } if (disposed || !connected || generation !== membershipGeneration) return; - cancelMembershipRetry?.(); - cancelMembershipRetry = null; - membershipRetryDelayMs = undefined; acknowledged = requested; startAcknowledgedCatchUps(); }; const retryVisibleAgentTimeline = (agentId: string) => { - if (!isDesired(agentId) || manualRetries.has(agentId)) return; + if (!connected || !isDesired(agentId) || manualRetries.has(agentId)) return; const catchUp = catchUps.get(agentId); const membershipRetryable = membershipNeedsRetry && connected; if (catchUp?.status !== "error" && !membershipRetryable) return; manualRetries.add(agentId); notifyListeners(); - if (catchUp?.status === "error") { - catchUp.cancelRetry?.(); - startCatchUp(agentId, { request: catchUp.request, supersede: true }); + if (membershipRetryable) { + void reconcileMembership(); return; } - cancelMembershipRetry?.(); - cancelMembershipRetry = null; - membershipRetryDelayMs = undefined; - void reconcileMembership(); + if (catchUp?.status === "error") { + startCatchUp(agentId, { request: catchUp.request, supersede: true }); + } }; const commitDesiredMembership = ( @@ -817,8 +767,6 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed ensureCacheLoaded(agentId); } } - cancelMembershipRetry?.(); - cancelMembershipRetry = null; desired = nextDesired; ports.replaceDemandedAgentIds(desired); membershipGeneration += 1; @@ -869,6 +817,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed return; } for (const agentId of visibleAgentIds()) { + if (visibilityCatchUpErrors.has(agentId)) continue; visibilityCatchUpPending.add(agentId); visibilityCatchUpErrors.delete(agentId); startCatchUp(agentId, { supersede: true }); @@ -880,9 +829,6 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed connected = nextConnected; if (!connected) { commitDesiredMembership(desired, { resetCatchUpStatus: true }); - cancelMembershipRetry?.(); - cancelMembershipRetry = null; - membershipRetryDelayMs = undefined; void observation?.handle.release().catch(ports.reportError); observation = null; acknowledged = []; @@ -894,7 +840,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed void reconcileMembership(); }, recoverGap(agentId, cursor) { - if (!isDesired(agentId)) return; + if (!isDesired(agentId) || catchUps.get(agentId)?.status === "error") return; startCatchUp(agentId, { request: planTimelineCatchUpAfter({ epoch: cursor.epoch, seq: cursor.endSeq }), supersede: true, @@ -904,10 +850,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed disposed = true; void observation?.handle.release().catch(ports.reportError); observation = null; - cancelMembershipRetry?.(); - cancelMembershipRetry = null; membershipNeedsRetry = false; - membershipRetryDelayMs = undefined; sources.clear(); membershipGeneration += 1; for (const agentId of desired) cancelCatchUp(agentId); From 787edb1bf942d981a019bd8e661a9700dc7edb3e Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Fri, 30 Oct 2026 17:57:57 +0700 Subject: [PATCH 127/173] Respect proxy variables throughout the daemon (#8177) * fix(server): respect environment proxies across daemon traffic Install proxy routing at daemon and plugin process startup, with a separate HTTP agent for outbound WebSockets. Always exempt loopback so local provider bridges remain reachable. * test(server): run usage source regressions in CI * fix(server): validate proxy settings without blocking startup Normalize scheme-less proxies and share HTTP-only validation across fetch and WebSockets. Record ignored variables without credentials in the daemon log. Separate built-in and directory plugin regressions through a typed fixture. * refactor(server): treat ignored proxy variables as unset * fix(server): read Windows proxy environment entries once * fix(server): apply proxy policy to connected host links * test(server): isolate proxy fixture credential directories * fix(server): keep proxy routing and authentication consistent Normalize Windows environment names and wildcard bypass rules at the network boundary. Compare bypass ports numerically and keep Basic proxy credentials on the CONNECT pool, including empty credential fields. --- docs/architecture.md | 10 + package-lock.json | 24 ++ packages/client/src/node/index.ts | 20 +- packages/server/package.json | 4 +- .../src/server/connected-hosts/index.ts | 2 + packages/server/src/server/daemon-worker.ts | 6 + .../src/server/hub/relationship-remote.ts | 2 + packages/server/src/server/network/index.ts | 116 ++++++ .../server/src/server/network/network.test.ts | 341 ++++++++++++++++++ .../src/server/plugins/plugin-process.ts | 2 + .../test-fixtures/usage-proxy-daemon.ts | 31 ++ .../server/plugins/usage-sources.e2e.test.ts | 75 ++++ packages/server/src/server/relay-transport.ts | 3 +- 13 files changed, 628 insertions(+), 8 deletions(-) create mode 100644 packages/server/src/server/network/index.ts create mode 100644 packages/server/src/server/network/network.test.ts create mode 100644 packages/server/src/server/plugins/test-fixtures/usage-proxy-daemon.ts diff --git a/docs/architecture.md b/docs/architecture.md index 3c5678b0ab..a7ad69c14d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -493,6 +493,16 @@ The supervisor alone publishes its ready worker's endpoint in `paseo.pid`, clear Worker restart retains supervisor arguments/environment and rereads the configuration file. Updating a package and observing its new worker version do not refresh the running supervisor code; the launcher owns full-process replacement. See [CLI lifecycle contracts](../public-docs/cli.md#daemon-management). +## Outbound networking + +The daemon and its plugin processes honor `HTTPS_PROXY`, `HTTP_PROXY`, and `NO_PROXY` +(including lowercase forms, which take precedence). Fetch and relay, Hub, and connected-host WebSockets +share this policy. Loopback (`localhost`, `127.0.0.1`, `::1`) always goes direct. +A proxy without a scheme uses HTTP. Invalid values and unsupported proxy schemes +are treated as unset, with one warning naming the variable in `daemon.log`. +Agent and terminal environments are unchanged. System proxy settings and SOCKS-only +`ALL_PROXY` configurations are not supported. + ## Deployment models 1. **Local daemon** (default): `paseo daemon start` on `127.0.0.1:6767` diff --git a/package-lock.json b/package-lock.json index 3351d15ac9..80355dbb21 100644 --- a/package-lock.json +++ b/package-lock.json @@ -40690,6 +40690,7 @@ "esbuild": "^0.25.12", "express": "^4.18.2", "fast-deep-equal": "^3.1.3", + "https-proxy-agent": "^7.0.6", "lru-cache": "^11.5.1", "markdown-it": "^10.0.0", "mnemonic-id": "^3.2.7", @@ -40707,6 +40708,7 @@ "strip-ansi": "^7.1.2", "tree-kill": "^1.2.2", "typescript": "^5.9.3", + "undici": "^7.24.8", "uuid": "^9.0.1", "which": "^5.0.0", "ws": "^8.14.2", @@ -41280,6 +41282,15 @@ "url": "https://opencollective.com/vitest" } }, + "packages/server/node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, "packages/server/node_modules/ajv": { "version": "8.20.0", "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", @@ -41349,6 +41360,19 @@ "@esbuild/win32-x64": "0.25.12" } }, + "packages/server/node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, "packages/server/node_modules/isexe": { "version": "3.1.5", "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.5.tgz", diff --git a/packages/client/src/node/index.ts b/packages/client/src/node/index.ts index 7132d09f10..46b5cff17a 100644 --- a/packages/client/src/node/index.ts +++ b/packages/client/src/node/index.ts @@ -2,6 +2,7 @@ export { createHostChannelTransport } from "../hosts/index.js"; import { HostTransportBudget } from "./buffering.js"; export { HostTransportBudget } from "./buffering.js"; import { homedir } from "node:os"; +import type { Agent } from "node:http"; import { WebSocket } from "ws"; import { parseHostTarget, type HostTarget } from "@getpaseo/protocol/host-target"; import { createSshTunnel, type SshTunnel } from "./ssh-tunnel.js"; @@ -19,10 +20,15 @@ export { parseHostTarget }; export type { SshTunnel } from "./ssh-tunnel.js"; export { createSshTunnel, resolveSshFailureDetail } from "./ssh-tunnel.js"; +export interface HostTransportOptions { + webSocketAgent?: (url: string) => Agent | undefined; +} + /** A factory owns one attempt, including a fresh SSH process and its teardown. */ export function createHostTransportFactory( connection: string, budget = new HostTransportBudget(), + options: HostTransportOptions = {}, ): DaemonTransportFactory { const target = parseHostTarget(connection); // Rises to "protected" once the daemon negotiates it, so a later attempt @@ -68,12 +74,13 @@ export function createHostTransportFactory( return; } const socketPath = socketTarget.socketPath?.replace(/^~(?=\/)/, homedir()); - let factory = createWebSocketTransportFactory((url, options) => { + let factory = createWebSocketTransportFactory((url, socketOptions) => { const socket = new WebSocket( socketPath && url.startsWith("ws+unix:") ? `ws+unix://${socketPath}:/ws` : url, - options?.protocols, + socketOptions?.protocols, { - headers: options?.headers, + headers: socketOptions?.headers, + agent: socketPath ? undefined : options.webSocketAgent?.(url), ...(socketPath ? { socketPath } : {}), maxPayload: 100 * 1024 * 1024, }, @@ -191,14 +198,15 @@ export function createHostTransportFactory( } export function createHostClient( connection: string, - config: Omit, + config: Omit & HostTransportOptions, budget?: HostTransportBudget, ): DaemonClient { const target = parseHostTarget(connection); + const { webSocketAgent, ...clientConfig } = config; return new DaemonClient({ - ...config, + ...clientConfig, url: "ws://host-connector/ws", ...(target.password ? { password: target.password } : {}), - transportFactory: createHostTransportFactory(connection, budget), + transportFactory: createHostTransportFactory(connection, budget, { webSocketAgent }), }); } diff --git a/packages/server/package.json b/packages/server/package.json index 13e5c9b49c..a31ce8d02a 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -89,7 +89,7 @@ "speech:transcribe:local": "tsx scripts/transcribe-local-wav.ts", "test": "npm run test:unit && npm run test:integration", "test:unit": "vitest run --fileParallelism --exclude \"**/*.e2e.test.ts\"", - "test:integration": "vitest run --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --maxWorkers=1 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history\"", + "test:integration": "vitest run --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --maxWorkers=1 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history\"", "test:hub-cli-contract": "vitest run --maxWorkers=1 src/server/hub/hub-cli-contract.test.ts", "test:integration:all": "npm run test:e2e", "test:integration:real": "vitest run real.e2e.test.ts", @@ -124,6 +124,7 @@ "esbuild": "^0.25.12", "express": "^4.18.2", "fast-deep-equal": "^3.1.3", + "https-proxy-agent": "^7.0.6", "lru-cache": "^11.5.1", "markdown-it": "^10.0.0", "mnemonic-id": "^3.2.7", @@ -141,6 +142,7 @@ "strip-ansi": "^7.1.2", "tree-kill": "^1.2.2", "typescript": "^5.9.3", + "undici": "^7.24.8", "uuid": "^9.0.1", "which": "^5.0.0", "ws": "^8.14.2", diff --git a/packages/server/src/server/connected-hosts/index.ts b/packages/server/src/server/connected-hosts/index.ts index 1a8f7c2731..96d6ac35d2 100644 --- a/packages/server/src/server/connected-hosts/index.ts +++ b/packages/server/src/server/connected-hosts/index.ts @@ -21,6 +21,7 @@ import { type HostUpdate, } from "@getpaseo/protocol/hosts"; import type { DaemonPermission, WSHelloMessage } from "@getpaseo/protocol/messages"; +import { webSocketProxyAgent } from "../network/index.js"; export class HostError extends Error { constructor( @@ -242,6 +243,7 @@ export class ConnectedHosts { { clientId: `host-link-${this.self.serverId}-${row.registrationId}`, connectTimeoutMs: 10000, + webSocketAgent: webSocketProxyAgent, }, this.budget, ); diff --git a/packages/server/src/server/daemon-worker.ts b/packages/server/src/server/daemon-worker.ts index 317903a592..8af60cd7bc 100644 --- a/packages/server/src/server/daemon-worker.ts +++ b/packages/server/src/server/daemon-worker.ts @@ -1,5 +1,6 @@ import { appendFileSync, mkdirSync } from "node:fs"; import path from "node:path"; +import { initializeEnvironmentProxy } from "./network/index.js"; import { createPaseoDaemon, formatListenTarget } from "./bootstrap.js"; import { loadConfig } from "./config.js"; import { resolvePaseoHome } from "./paseo-home.js"; @@ -132,6 +133,11 @@ function applyCliFlagOverrides(config: ReturnType): void { async function main() { const { paseoHome, logger, config } = bootstrapFromEnvironment(); + for (const variable of initializeEnvironmentProxy()) { + writeWorkerLifecycleLog(paseoHome, "Ignoring invalid or unsupported HTTP proxy variable", { + variable, + }); + } let daemon: Awaited> | null = null; let shutdownPromise: Promise | null = null; let exitHookInstalled = false; diff --git a/packages/server/src/server/hub/relationship-remote.ts b/packages/server/src/server/hub/relationship-remote.ts index 9c6f88a63d..6427b71fa6 100644 --- a/packages/server/src/server/hub/relationship-remote.ts +++ b/packages/server/src/server/hub/relationship-remote.ts @@ -1,5 +1,6 @@ import { WebSocket } from "ws"; import { z } from "zod"; +import { webSocketProxyAgent } from "../network/index.js"; import type { WebSocketLike } from "../websocket-server.js"; const SOCKET_PING_INTERVAL_MS = 10_000; @@ -166,6 +167,7 @@ export class DirectHubRelationshipRemote implements HubRelationshipRemote { openSocket(input: HubSocketCredentials, events: HubSocketEvents): HubSocketConnection { let sessionProtocol: "legacy" | "session-v1" = "legacy"; const socket = new WebSocket(input.webSocketUrl, { + agent: webSocketProxyAgent(input.webSocketUrl), handshakeTimeout: this.requestTimeoutMs, headers: { authorization: `Bearer ${input.credential}`, diff --git a/packages/server/src/server/network/index.ts b/packages/server/src/server/network/index.ts new file mode 100644 index 0000000000..46565d801a --- /dev/null +++ b/packages/server/src/server/network/index.ts @@ -0,0 +1,116 @@ +import type { Agent } from "node:http"; +import { EnvHttpProxyAgent, Pool, setGlobalDispatcher } from "undici"; +import { HttpsProxyAgent } from "https-proxy-agent"; + +interface ProxyEnvironment { + httpProxy: string; + httpsProxy: string; + noProxy: string; +} + +let environment = readEnvironment(process.env, process.platform).environment; + +function readEnvironment( + env: NodeJS.ProcessEnv, + platform: NodeJS.Platform, +): { + environment: ProxyEnvironment; + ignored: string[]; +} { + // process.env lookups are case-insensitive on Windows. Read each actual entry once. + const values = new Map( + Object.entries(env).map(([name, value]) => [ + platform === "win32" ? name.toLowerCase() : name, + value, + ]), + ); + const ignored: string[] = []; + function proxy(variable: string): string | undefined { + const value = values.get(variable); + if (value === undefined) return undefined; + if (!value.trim()) return undefined; + try { + const url = new URL(value.includes("://") ? value : `http://${value}`); + if (url.protocol !== "http:" && url.protocol !== "https:") + throw new Error("Unsupported proxy protocol"); + decodeURIComponent(url.username); + decodeURIComponent(url.password); + return url.href; + } catch { + ignored.push(variable); + return undefined; + } + } + const httpProxy = proxy("http_proxy") ?? proxy("HTTP_PROXY") ?? ""; + return { + environment: { + httpProxy, + httpsProxy: proxy("https_proxy") ?? proxy("HTTPS_PROXY") ?? httpProxy, + noProxy: values.get("no_proxy") ?? values.get("NO_PROXY") ?? "", + }, + ignored, + }; +} + +function bypassList(noProxy: string): string { + return noProxy.split(/[,\s]+/).includes("*") ? "*" : `${noProxy},localhost,127.0.0.1,[::1],::1`; +} + +function proxyClient(origin: URL, options: object) { + const pool = new Pool(origin, options); + if (!origin.username && !origin.password) return pool; + const credentials = `${decodeURIComponent(origin.username)}:${decodeURIComponent(origin.password)}`; + const authorization = `Basic ${Buffer.from(credentials).toString("base64")}`; + // This pool only sends CONNECT requests to this proxy, never requests to the origin. + // undici's URL auth requires both fields; HTTP Basic also permits either field to be empty. + return pool.compose( + (dispatch) => (request, handler) => + dispatch( + { + ...request, + headers: { ...request.headers, "proxy-authorization": authorization }, + }, + handler, + ), + ); +} + +/** Install once at startup; return ignored variable names for logging without exposing credentials. */ +export function initializeEnvironmentProxy( + env: NodeJS.ProcessEnv = process.env, + platform: NodeJS.Platform = process.platform, +): string[] { + const resolved = readEnvironment(env, platform); + environment = resolved.environment; + setGlobalDispatcher( + new EnvHttpProxyAgent({ + httpProxy: environment.httpProxy, + httpsProxy: environment.httpsProxy, + noProxy: bypassList(environment.noProxy), + clientFactory: proxyClient, + }), + ); + return resolved.ignored; +} + +/** ws uses Node HTTP agents rather than the fetch dispatcher. */ +export function webSocketProxyAgent(address: string): Agent | undefined { + const url = new URL(address); + const hostname = url.hostname.toLowerCase(); + const port = url.port || (url.protocol === "wss:" ? "443" : "80"); + const entries = bypassList(environment.noProxy) + .toLowerCase() + .split(/[,\s]+/); + if ( + entries.some((entry) => { + if (entry === "*") return true; + const match = entry.match(/^(.+):(\d+)$/); + if (match && Number(match[2]) !== Number(port)) return false; + const host = (match ? match[1]! : entry).replace(/^\*?\./, ""); + return host !== "" && (hostname === host || hostname.endsWith(`.${host}`)); + }) + ) + return undefined; + const proxy = url.protocol === "wss:" ? environment.httpsProxy : environment.httpProxy; + return proxy ? new HttpsProxyAgent(proxy) : undefined; +} diff --git a/packages/server/src/server/network/network.test.ts b/packages/server/src/server/network/network.test.ts new file mode 100644 index 0000000000..88e7d61aa6 --- /dev/null +++ b/packages/server/src/server/network/network.test.ts @@ -0,0 +1,341 @@ +import { fork } from "node:child_process"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { createServer, type Server } from "node:http"; +import { once } from "node:events"; +import { connect } from "node:net"; +import { afterEach, expect, test } from "vitest"; +import { WebSocket, WebSocketServer } from "ws"; +import { getGlobalDispatcher, setGlobalDispatcher } from "undici"; +import { initializeEnvironmentProxy, webSocketProxyAgent } from "./index.js"; +import { ConnectedHosts } from "../connected-hosts/index.js"; +const original = getGlobalDispatcher(); +const servers: Server[] = []; +afterEach(async () => { + const installed = getGlobalDispatcher(); + setGlobalDispatcher(original); + if (installed !== original) await installed.close(); + await Promise.all( + servers.splice(0).map( + (server) => + new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }), + ), + ); +}); +async function listen(server: Server) { + servers.push(server); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Missing address"); + return `127.0.0.1:${address.port}`; +} +async function proxy() { + const tunnels: string[] = []; + const server = createServer(); + server.on("connect", (request, socket) => { + tunnels.push(request.url!); + socket.end("HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n"); + }); + return { url: `http://${await listen(server)}`, tunnels }; +} +test("loopback fetch and WebSockets bypass HTTP_PROXY with empty NO_PROXY", async () => { + const recorder = await proxy(); + initializeEnvironmentProxy({ HTTP_PROXY: recorder.url, NO_PROXY: "" }); + const server = createServer((_, response) => response.end("direct")); + const sockets = new WebSocketServer({ server }); + sockets.on("connection", (socket) => socket.send("direct")); + const address = await listen(server); + expect(await (await fetch(`http://${address}`)).text()).toBe("direct"); + const socket = new WebSocket(`ws://${address}`, { + agent: webSocketProxyAgent(`ws://${address}`), + }); + expect((await once(socket, "message"))[0].toString()).toBe("direct"); + socket.close(); + await once(socket, "close"); + await new Promise((resolve) => sockets.close(() => resolve())); + for (const host of ["localhost", "127.0.0.1", "[::1]"]) + expect(webSocketProxyAgent(`wss://${host}:1234`)).toBeUndefined(); + expect(recorder.tunnels).toEqual([]); +}); +test("fetch and WebSockets send non-loopback traffic through CONNECT", async () => { + const recorder = await proxy(); + initializeEnvironmentProxy({ http_proxy: recorder.url }); + await expect( + fetch("https://vendor.invalid/", { signal: AbortSignal.timeout(500) }), + ).rejects.toThrow(); + const socket = new WebSocket("wss://vendor.invalid", { + agent: webSocketProxyAgent("wss://vendor.invalid"), + }); + await once(socket, "error"); + expect( + recorder.tunnels.filter((host) => host === "vendor.invalid:443").length, + ).toBeGreaterThanOrEqual(2); +}); +test("NO_PROXY and absent variables keep matching WebSockets direct", async () => { + const recorder = await proxy(); + initializeEnvironmentProxy({ + HTTPS_PROXY: recorder.url, + NO_PROXY: "vendor.invalid,.example.invalid:443", + }); + expect(webSocketProxyAgent("wss://vendor.invalid")).toBeUndefined(); + await expect( + fetch("https://vendor.invalid/", { signal: AbortSignal.timeout(500) }), + ).rejects.toThrow(); + expect(webSocketProxyAgent("wss://sub.example.invalid")).toBeUndefined(); + expect(webSocketProxyAgent("wss://example.invalid:444")).toBeDefined(); + initializeEnvironmentProxy({ HTTP_PROXY: recorder.url, no_proxy: "*" }); + expect(webSocketProxyAgent("ws://vendor.invalid")).toBeUndefined(); + initializeEnvironmentProxy({}); + expect(webSocketProxyAgent("wss://vendor.invalid")).toBeUndefined(); + const address = await listen(createServer((_, response) => response.end("direct"))); + expect(await (await fetch(`http://${address}`)).text()).toBe("direct"); + expect(recorder.tunnels).toEqual([]); +}); + +test.each(["127.0.0.1", "localhost"])( + "scheme-less %s proxies work for fetch and WebSockets", + async (host) => { + const recorder = await proxy(); + const address = new URL(recorder.url); + initializeEnvironmentProxy({ https_proxy: `${host}:${address.port}` }); + await expect( + fetch("https://vendor.invalid", { signal: AbortSignal.timeout(500) }), + ).rejects.toThrow(); + const socket = new WebSocket("wss://vendor.invalid", { + agent: webSocketProxyAgent("wss://vendor.invalid"), + }); + await once(socket, "error"); + expect(recorder.tunnels).toContain("vendor.invalid:443"); + }, +); + +test.each([ + "http://[", + "http://user%zz:secret@proxy.corp", + "socks5://127.0.0.1:7890", + "ftp://proxy.corp:8080", +])("ignores invalid or unsupported proxy %s without stopping startup", async (value) => { + const recorder = await proxy(); + expect(initializeEnvironmentProxy({ HTTP_PROXY: recorder.url, https_proxy: value })).toEqual([ + "https_proxy", + ]); + expect(webSocketProxyAgent("wss://vendor.invalid")).toBeDefined(); + await expect( + fetch("https://vendor.invalid", { signal: AbortSignal.timeout(500) }), + ).rejects.toThrow(); + const socket = new WebSocket("wss://vendor.invalid", { + agent: webSocketProxyAgent("wss://vendor.invalid"), + }); + await once(socket, "error"); + expect(recorder.tunnels).toEqual(["vendor.invalid:443", "vendor.invalid:443"]); +}); + +test("daemon starts with an ignored proxy and writes one redacted warning to daemon.log", async () => { + const home = await mkdtemp(path.join(os.tmpdir(), "daemon-invalid-proxy-")); + const env = Object.fromEntries( + Object.entries(process.env).filter( + ([key]) => !["http_proxy", "https_proxy"].includes(key.toLowerCase()), + ), + ); + const worker = fork(fileURLToPath(new URL("../daemon-worker.ts", import.meta.url)), [], { + execArgv: ["--import", "tsx"], + silent: true, + env: { + ...env, + PASEO_HOME: home, + HOME: home, + USERPROFILE: home, + PASEO_LISTEN: "127.0.0.1:0", + PASEO_RELAY_ENABLED: "0", + https_proxy: "socks5://private:secret@127.0.0.1:7890", + }, + }); + worker.stdout?.resume(); + let stderr = ""; + worker.stderr?.on("data", (chunk) => { + stderr += String(chunk); + }); + try { + await new Promise((resolve, reject) => { + worker.on("message", (message) => { + if ( + typeof message === "object" && + message !== null && + "type" in message && + message.type === "paseo:ready" + ) + resolve(); + }); + worker.on("exit", (code) => reject(new Error(`Worker exited ${code}: ${stderr}`))); + }); + const log = await readFile(path.join(home, "daemon.log"), "utf8"); + const warnings = log + .split("\n") + .filter((line) => line.includes("Ignoring invalid or unsupported HTTP proxy variable")); + expect(warnings).toHaveLength(1); + expect(JSON.parse(warnings[0]!).variable).toBe("https_proxy"); + expect(warnings[0]).not.toContain("secret"); + } finally { + if (worker.exitCode === null && worker.signalCode === null) { + const exited = once(worker, "exit"); + worker.kill("SIGTERM"); + await exited; + } + await rm(home, { recursive: true, force: true }); + } +}, 60_000); + +test("accepts a scheme-less corporate proxy hostname", () => { + expect(initializeEnvironmentProxy({ https_proxy: "proxy.corp:8080" })).toEqual([]); + expect(webSocketProxyAgent("wss://vendor.invalid")).toBeDefined(); +}); + +test("an ignored lowercase variable falls back to the uppercase variable", async () => { + const recorder = await proxy(); + expect( + initializeEnvironmentProxy( + { + https_proxy: "socks5://proxy.invalid", + HTTPS_PROXY: recorder.url, + }, + "linux", + ), + ).toEqual(["https_proxy"]); + await expect( + fetch("https://vendor.invalid", { signal: AbortSignal.timeout(500) }), + ).rejects.toThrow(); + const socket = new WebSocket("wss://vendor.invalid", { + agent: webSocketProxyAgent("wss://vendor.invalid"), + }); + await once(socket, "error"); + expect(recorder.tunnels).toEqual(["vendor.invalid:443", "vendor.invalid:443"]); +}); + +test("case-insensitive environment access reports a variable only once", () => { + const env = new Proxy( + { https_proxy: "socks5://127.0.0.1:7890" }, + { + get(target, key) { + return Reflect.get(target, typeof key === "string" ? key.toLowerCase() : key); + }, + }, + ); + expect(initializeEnvironmentProxy(env)).toEqual(["https_proxy"]); +}); + +test("connected-host links send remote WebSockets through the environment proxy", async () => { + const recorder = await proxy(); + initializeEnvironmentProxy({ HTTPS_PROXY: recorder.url }); + const home = await mkdtemp(path.join(os.tmpdir(), "connected-host-proxy-")); + const hosts = new ConnectedHosts(home, { serverId: "self", label: "Self" }); + try { + await hosts.add( + { connection: "wss://remote.invalid/ws" }, + { sourceId: "test", manageSources: true }, + ); + await expect.poll(() => recorder.tunnels).toContain("remote.invalid:443"); + } finally { + await hosts.close(); + await rm(home, { recursive: true, force: true }); + } +}); + +test.each(["corp.internal,*", "vendor.invalid:0443"])( + "fetch and WebSockets share NO_PROXY=%s", + async (noProxy) => { + const recorder = await proxy(); + initializeEnvironmentProxy({ HTTPS_PROXY: recorder.url, NO_PROXY: noProxy }); + expect(webSocketProxyAgent("wss://vendor.invalid")).toBeUndefined(); + await expect( + fetch("https://vendor.invalid", { signal: AbortSignal.timeout(500) }), + ).rejects.toThrow(); + expect(recorder.tunnels).toEqual([]); + }, +); + +test("Windows mixed-case environment names route and bypass both transports", async () => { + const recorder = await proxy(); + // Windows preserves spelling but treats environment names without regard to case. + initializeEnvironmentProxy({ Https_Proxy: recorder.url, No_Proxy: "other.invalid" }, "win32"); + expect(webSocketProxyAgent("wss://other.invalid")).toBeUndefined(); + await expect( + fetch("https://other.invalid", { signal: AbortSignal.timeout(500) }), + ).rejects.toThrow(); + expect(webSocketProxyAgent("wss://vendor.invalid")).toBeDefined(); + await expect( + fetch("https://vendor.invalid", { signal: AbortSignal.timeout(500) }), + ).rejects.toThrow(); + const socket = new WebSocket("wss://vendor.invalid", { + agent: webSocketProxyAgent("wss://vendor.invalid"), + }); + await once(socket, "error"); + expect(recorder.tunnels).toEqual(["vendor.invalid:443", "vendor.invalid:443"]); +}); + +test("POSIX mixed-case names do not override standard proxy names", async () => { + const recorder = await proxy(); + initializeEnvironmentProxy( + { Https_Proxy: recorder.url, HTTPS_PROXY: recorder.url, No_Proxy: "*" }, + "linux", + ); + expect(webSocketProxyAgent("wss://vendor.invalid")).toBeDefined(); + await expect( + fetch("https://vendor.invalid", { signal: AbortSignal.timeout(500) }), + ).rejects.toThrow(); + expect(recorder.tunnels).toEqual(["vendor.invalid:443"]); +}); + +test("proxy credentials stay on CONNECT and do not reach the HTTP origin", async () => { + let originAuthorization: string | undefined; + const origin = createServer((request, response) => { + originAuthorization = request.headers["proxy-authorization"]; + response.end("through proxy"); + }); + const originAddress = new URL(`http://${await listen(origin)}`); + const authorizations: (string | undefined)[] = []; + const server = createServer(); + server.on("connect", (request, socket, head) => { + authorizations.push(request.headers["proxy-authorization"]); + const upstream = connect(Number(originAddress.port), "127.0.0.1", () => { + socket.write("HTTP/1.1 200 Connection Established\r\n\r\n"); + if (head.length) upstream.write(head); + socket.pipe(upstream).pipe(socket); + }); + socket.on("error", () => upstream.destroy()); + upstream.on("error", () => socket.destroy()); + socket.on("close", () => upstream.destroy()); + }); + initializeEnvironmentProxy({ HTTP_PROXY: `http://user:@${await listen(server)}` }); + const response = await fetch("http://vendor.invalid", { signal: AbortSignal.timeout(3000) }); + expect(await response.text()).toBe("through proxy"); + expect(authorizations).toEqual([`Basic ${Buffer.from("user:").toString("base64")}`]); + expect(originAuthorization).toBeUndefined(); +}); + +test.each(["user:@", ":secret@", "user:secret@"])( + "fetch and WebSockets authenticate proxy credentials %s", + async (credentials) => { + const authorizations: (string | undefined)[] = []; + const server = createServer(); + server.on("connect", (request, socket) => { + authorizations.push(request.headers["proxy-authorization"]); + socket.end("HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n"); + }); + initializeEnvironmentProxy({ HTTPS_PROXY: `http://${credentials}${await listen(server)}` }); + await expect( + fetch("https://vendor.invalid", { signal: AbortSignal.timeout(500) }), + ).rejects.toThrow(); + const socket = new WebSocket("wss://vendor.invalid", { + agent: webSocketProxyAgent("wss://vendor.invalid"), + }); + await once(socket, "error"); + const expected = `Basic ${Buffer.from(credentials.slice(0, -1)).toString("base64")}`; + expect(authorizations).toEqual([expected, expected]); + }, +); diff --git a/packages/server/src/server/plugins/plugin-process.ts b/packages/server/src/server/plugins/plugin-process.ts index a72e268e4f..62514cd0b2 100644 --- a/packages/server/src/server/plugins/plugin-process.ts +++ b/packages/server/src/server/plugins/plugin-process.ts @@ -24,6 +24,7 @@ import { createPluginClientId } from "./plugin-session-identity.js"; import { PluginSettingsStore } from "./settings/index.js"; import { readPluginProviderIcon } from "./provider-icon.js"; +import { initializeEnvironmentProxy } from "../network/index.js"; function describeError(error: unknown): string { return error instanceof Error ? error.message : String(error); } @@ -606,6 +607,7 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) { const parsed = PluginProcessRequestSchema.safeParse(raw); if (!worker && parsed.success && parsed.data.type === "initialize") { try { + initializeEnvironmentProxy(); worker = createPluginWorker({ channel, contribute: evaluateBundle(parsed.data.bundle) }); } catch (error) { channel.send({ type: "fatal", error: describeError(error) }); diff --git a/packages/server/src/server/plugins/test-fixtures/usage-proxy-daemon.ts b/packages/server/src/server/plugins/test-fixtures/usage-proxy-daemon.ts new file mode 100644 index 0000000000..23364d3fda --- /dev/null +++ b/packages/server/src/server/plugins/test-fixtures/usage-proxy-daemon.ts @@ -0,0 +1,31 @@ +import path from "node:path"; +import { initializeEnvironmentProxy } from "../../network/index.js"; +import { DaemonClient } from "../../test-utils/daemon-client.js"; +import { createTestPaseoDaemon } from "../../test-utils/paseo-daemon.js"; +import { BuiltinPluginLoader, resolveBuiltinPluginsRoot } from "../builtin/index.js"; + +const mode = process.argv[2]; +if (mode !== "builtin" && mode !== "directory") throw new Error("Expected builtin or directory"); +const sources = ["claude-usage-source", "codex-usage-source"]; +// Built-ins run inside the daemon; directory plugins initialize their own subprocess network. +if (mode === "builtin") initializeEnvironmentProxy(); +const daemon = await createTestPaseoDaemon({ + pluginsEnabled: mode === "directory", + builtinPlugins: new BuiltinPluginLoader( + resolveBuiltinPluginsRoot(), + mode === "builtin" ? sources : [], + ), +}); +const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); +try { + await client.connect(); + if (mode === "directory") { + for (const source of sources) { + await client.installDirectoryPlugin(path.join(resolveBuiltinPluginsRoot(), source), source); + } + } + await client.listUsageReports(); +} finally { + await client.close(); + await daemon.close(); +} diff --git a/packages/server/src/server/plugins/usage-sources.e2e.test.ts b/packages/server/src/server/plugins/usage-sources.e2e.test.ts index 037da5e0c6..46dc134ff6 100644 --- a/packages/server/src/server/plugins/usage-sources.e2e.test.ts +++ b/packages/server/src/server/plugins/usage-sources.e2e.test.ts @@ -1,7 +1,11 @@ +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; import { cp, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; +import { createServer } from "node:http"; +import { once } from "node:events"; import { expect, test } from "vitest"; import { DaemonClient } from "../test-utils/daemon-client.js"; import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js"; @@ -335,3 +339,74 @@ export default function contribute(server) { await rm(root, { recursive: true, force: true }); } }, 60_000); + +test.each(["builtin", "directory"])( + "%s usage plugins reach the environment proxy", + async (mode) => { + const root = await mkdtemp(path.join(os.tmpdir(), "usage-proxy-")); + const tunnels: string[] = []; + const proxy = createServer(); + proxy.on("connect", (request, socket) => { + tunnels.push(request.url!); + socket.end("HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n"); + }); + proxy.listen(0, "127.0.0.1"); + await once(proxy, "listening"); + const address = proxy.address(); + if (!address || typeof address === "string") throw new Error("Missing proxy address"); + const guard = path.join(root, "network-guard.cjs"); + // Prevent vendor DNS/network access even when proxy support is broken. + await writeFile( + guard, + `const dns = require('node:dns'); +const lookup = dns.lookup; +dns.lookup = function(host, ...args) { + if (host === 'localhost' || host === '127.0.0.1' || host === '::1') return lookup.call(this, host, ...args); + args.at(-1)(Object.assign(new Error('External DNS forbidden in proxy test'), { code: 'ENOTFOUND' })); +};`, + ); + await mkdir(path.join(root, ".claude")); + await mkdir(path.join(root, ".codex")); + await writeFile( + path.join(root, ".claude", ".credentials.json"), + JSON.stringify({ claudeAiOauth: { accessToken: "fixture-claude" } }), + ); + await writeFile( + path.join(root, ".codex", "auth.json"), + JSON.stringify({ tokens: { access_token: "fixture-codex", account_id: "fixture-account" } }), + ); + try { + await promisify(execFile)( + process.execPath, + [ + "--import", + "tsx", + fileURLToPath(new URL("./test-fixtures/usage-proxy-daemon.ts", import.meta.url)), + mode, + ], + { + timeout: 45_000, + maxBuffer: 1024 * 1024, + env: { + ...process.env, + HOME: root, + USERPROFILE: root, + CODEX_HOME: path.join(root, ".codex"), + CLAUDE_CONFIG_DIR: path.join(root, ".claude"), + NODE_OPTIONS: `--require=${JSON.stringify(guard.replaceAll("\\", "/"))}`, + https_proxy: `http://127.0.0.1:${address.port}`, + no_proxy: "", + NO_PROXY: "", + }, + }, + ); + expect(tunnels).toContain("api.anthropic.com:443"); + expect(tunnels).toContain("chatgpt.com:443"); + } finally { + proxy.closeAllConnections(); + await new Promise((resolve) => proxy.close(() => resolve())); + await rm(root, { recursive: true, force: true }); + } + }, + 60_000, +); diff --git a/packages/server/src/server/relay-transport.ts b/packages/server/src/server/relay-transport.ts index 08fcd826d5..a0898df247 100644 --- a/packages/server/src/server/relay-transport.ts +++ b/packages/server/src/server/relay-transport.ts @@ -2,6 +2,7 @@ import { WebSocket } from "ws"; import type pino from "pino"; import { buildRelayWebSocketUrl } from "@getpaseo/protocol/daemon-endpoints"; +import { webSocketProxyAgent } from "./network/index.js"; import type { ExternalSocketMetadata } from "./websocket-server.js"; export interface RelayTransportOptions { @@ -56,7 +57,7 @@ const RELAY_WEBSOCKET_OPTIONS = { } as const; function createDefaultRelayWebSocket(url: string): RelayWebSocketLike { - return new WebSocket(url, RELAY_WEBSOCKET_OPTIONS); + return new WebSocket(url, { ...RELAY_WEBSOCKET_OPTIONS, agent: webSocketProxyAgent(url) }); } function isRecord(value: unknown): value is Record { From fbe24fcdb67147d6003a27732a60bd49e71ec4e5 Mon Sep 17 00:00:00 2001 From: "paseo-ai[bot]" <266920839+paseo-ai[bot]@users.noreply.github.com> Date: Fri, 30 Oct 2026 11:06:08 +0000 Subject: [PATCH 128/173] fix: update lockfile signatures and Nix hash [skip ci] --- nix/npm-deps.hash | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nix/npm-deps.hash b/nix/npm-deps.hash index a6061301b1..35593d9f96 100644 --- a/nix/npm-deps.hash +++ b/nix/npm-deps.hash @@ -1 +1 @@ -sha256-6C4Rjh0mRVrC9akBVGK0NZaCaLJhwKObT7HrgPmcvyw= +sha256-8NOrrCAxraQ74lP3Vy59MRhloBfzStTc4rW+ltc42Fg= From 184ab66cdea7680018f06c490c3f056cc194f8a2 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Fri, 30 Oct 2026 21:26:38 +0700 Subject: [PATCH 129/173] Show sub-agents as launch markers in the parent timeline (#8276) * fix: make sub-agent cards launch markers Sub-agent tool calls no longer accumulate the child's activity into `log`. Claude, Codex, OpenCode, OMP and Pi emit the card when the child starts and when its label or status changes; the child's messages and tool calls stay in the sub-agent's own timeline. The app no longer renders a sub-agent log. The wire schema makes `log` optional. Daemons still send `log: ""` so apps that require the field keep parsing the card. * fix(server): put a tintinweb foreground answer in the child timeline A foreground @tintinweb/pi-subagents child has no session file, so its answer only exists in the Agent tool result. Emit that text as the child's assistant message when the child finishes. Tag every sub_agent producer's `log: ""` with COMPAT(subagent-log) so the shim removal finds them. * fix(server): settle child compactions and keep sub-agent cards stable - Codex: a child compaction shown as loading now completes on the child's thread/compacted or turn end, once. - Claude: a streamed child tool call's empty start input is a placeholder, so the assistant message's input reaches its card. - OMP: the task card follows only its first child, so later children no longer re-send an unchanged card. * fix(server): keep a gotgenes foreground answer on replay A foreground @gotgenes/pi-subagents child finds its session file only through the live runtime marker, which history does not keep. Without a file, emit the spawn result text as the child's assistant message. --- .../app/src/components/tool-call-details.tsx | 222 +---------- packages/app/src/i18n/resources.test.ts | 1 - packages/app/src/i18n/resources/ar.ts | 1 - packages/app/src/i18n/resources/en.ts | 1 - packages/app/src/i18n/resources/es.ts | 1 - packages/app/src/i18n/resources/fr.ts | 1 - packages/app/src/i18n/resources/ja.ts | 1 - packages/app/src/i18n/resources/ko.ts | 1 - packages/app/src/i18n/resources/pt-BR.ts | 1 - packages/app/src/i18n/resources/ru.ts | 1 - packages/app/src/i18n/resources/zh-CN.ts | 1 - .../app/src/utils/tool-call-detail-state.ts | 12 +- packages/protocol/src/agent-types.ts | 2 +- packages/protocol/src/messages.ts | 4 +- .../protocol/src/messages.wire-compat.test.ts | 24 +- .../src/server/agent/activity-curator.test.ts | 8 +- .../src/server/agent/activity-curator.ts | 3 - .../src/server/agent/agent-sdk-types.ts | 5 +- .../claude/agent.background-subagent.test.ts | 6 +- .../claude/agent.sub-agent-sidechain.test.ts | 48 ++- .../server/agent/providers/claude/agent.ts | 3 +- .../claude/sidechain-tracker.test.ts | 78 +++- .../providers/claude/sidechain-tracker.ts | 161 ++------ .../codex-app-server-agent.real.e2e.test.ts | 18 +- .../providers/codex-app-server-agent.test.ts | 174 ++++++-- .../agent/providers/codex-app-server-agent.ts | 138 +++---- .../agent/providers/codex/tool-call-mapper.ts | 2 + .../src/server/agent/providers/omp/agent.ts | 15 +- .../providers/omp/history-mapper.test.ts | 2 +- .../omp/subagent-card-tracker.test.ts | 224 +++-------- .../providers/omp/subagent-card-tracker.ts | 373 +++--------------- .../providers/omp/tool-call-mapper.test.ts | 4 +- .../agent/providers/omp/tool-call-mapper.ts | 4 +- .../server/agent/providers/opencode-agent.ts | 9 - .../opencode/tool-call-detail-parser.ts | 23 +- .../opencode/tool-call-mapper.test.ts | 10 +- .../providers/opencode/tool-call-mapper.ts | 2 +- .../extensions/edxeth-pi-subagents/index.ts | 4 +- .../gotgenes-pi-subagents/index.test.ts | 12 + .../extensions/gotgenes-pi-subagents/index.ts | 21 +- .../providers/pi/extensions/index.test.ts | 2 +- .../pi/extensions/pi-subagents/index.test.ts | 2 +- .../pi/extensions/pi-subagents/index.ts | 3 +- .../pi/extensions/subagent-fixture-test.ts | 2 - .../tintinweb-pi-subagents/index.test.ts | 21 +- .../tintinweb-pi-subagents/index.ts | 21 +- ...round-subagent-action-log.real.e2e.test.ts | 24 +- 47 files changed, 578 insertions(+), 1118 deletions(-) diff --git a/packages/app/src/components/tool-call-details.tsx b/packages/app/src/components/tool-call-details.tsx index a10bd7b0c6..5e08f944df 100644 --- a/packages/app/src/components/tool-call-details.tsx +++ b/packages/app/src/components/tool-call-details.tsx @@ -64,7 +64,7 @@ function resolveShouldFill( ): boolean { if (!fillAvailableHeight) return false; const t = detail?.type; - return t === "shell" || t === "edit" || t === "write" || t === "read" || t === "sub_agent"; + return t === "shell" || t === "edit" || t === "write" || t === "read"; } function useDetailStyles( @@ -186,184 +186,6 @@ function ShellDetailSection({ command, output, ds }: ShellDetailProps) { ); } -function resolveSubAgentFallbackHeader( - subAgentType: string | null | undefined, - description: string | null | undefined, - fallbackText: string, -): string { - if (subAgentType && description) { - return `${subAgentType}: ${description}`; - } - return subAgentType ?? description ?? fallbackText; -} - -interface SubAgentDetailProps { - log: string; - childSessionId: string | null | undefined; - subAgentType: string | null | undefined; - description: string | null | undefined; - ds: DetailStyles; -} - -interface SubAgentActivityRow { - index: number; - toolName: string; - summary?: string; -} - -interface ParsedSubAgentLog { - actions: SubAgentActivityRow[]; - remainingLog: string; -} - -function parseBracketedSubAgentLine(line: string, index: number): SubAgentActivityRow | null { - const match = line.match(/^\[([^\]]+)\](?:\s+(.*))?$/); - if (!match) { - return null; - } - const toolName = match[1]?.trim(); - if (!toolName) { - return null; - } - const summary = match[2]?.trim(); - return { - index, - toolName, - ...(summary ? { summary } : {}), - }; -} - -function parseSubAgentLog(log: string): ParsedSubAgentLog { - const actions: SubAgentActivityRow[] = []; - const remainingLines: string[] = []; - for (const line of log.replace(/^\n+/, "").split("\n")) { - const normalizedLine = line.trim(); - if (!normalizedLine) { - continue; - } - const parsedAction = parseBracketedSubAgentLine(normalizedLine, actions.length + 1); - if (parsedAction) { - actions.push(parsedAction); - } else { - remainingLines.push(line); - } - } - return { - actions, - remainingLog: remainingLines.join("\n").replace(/^\n+/, ""), - }; -} - -function SubAgentActionRow({ action }: { action: SubAgentActivityRow }) { - return ( - - - {formatSubAgentToolName(action.toolName)} - - {action.summary ? ( - - {action.summary} - - ) : null} - - ); -} - -function formatSubAgentToolName(toolName: string): string { - const trimmed = toolName.trim(); - if (!trimmed) { - return toolName; - } - return trimmed - .replace(/[._-]+/g, " ") - .split(" ") - .filter((segment) => segment.length > 0) - .map((segment) => `${segment[0]?.toUpperCase() ?? ""}${segment.slice(1)}`) - .join(" "); -} - -function SubAgentLogText({ - activityLog, - fallbackHeader, - hasActions, -}: { - activityLog: string; - fallbackHeader: string; - hasActions: boolean; -}) { - if (activityLog.length > 0) { - return ( - - {activityLog} - - ); - } - if (!hasActions) { - return ( - - {fallbackHeader} - - ); - } - return null; -} - -function SubAgentDetailSection({ - log, - childSessionId, - subAgentType, - description, - ds, -}: SubAgentDetailProps) { - const { t } = useTranslation(); - const { actions, remainingLog } = useMemo(() => parseSubAgentLog(log), [log]); - const fallbackHeader = resolveSubAgentFallbackHeader( - subAgentType, - description, - t("toolCallDetails.subAgentActivity"), - ); - const hasActions = actions.length > 0; - return ( - - - - - - {childSessionId ? ( - - session {childSessionId} - - ) : null} - {hasActions ? ( - - {actions.map((action) => ( - - ))} - - ) : null} - - - - - - - ); -} - interface EditDetailProps { diffLines: DiffLine[] | undefined; ds: DetailStyles; @@ -636,19 +458,7 @@ function buildDetailSections( , ]; } - if (detail.type === "worktree_setup") return []; - if (detail.type === "sub_agent") { - return [ - , - ]; - } + if (detail.type === "worktree_setup" || detail.type === "sub_agent") return []; if (detail.type === "edit") { return []; } @@ -900,34 +710,6 @@ const styles = StyleSheet.create((theme) => { shellPrompt: { color: theme.colors.foregroundMuted, }, - subAgentSessionText: { - fontFamily: theme.fontFamily.mono, - fontSize: theme.fontSize.code, - color: theme.colors.foregroundMuted, - lineHeight: 18, - marginBottom: theme.spacing[2], - }, - subAgentActions: { - gap: theme.spacing[1], - marginBottom: theme.spacing[2], - }, - subAgentActionRow: { - flexDirection: "row", - alignItems: "center", - gap: theme.spacing[2], - }, - subAgentActionTool: { - fontFamily: theme.fontFamily.mono, - fontSize: theme.fontSize.code, - color: theme.colors.foregroundMuted, - lineHeight: 18, - }, - subAgentActionSummary: { - fontFamily: theme.fontFamily.mono, - fontSize: theme.fontSize.code, - color: theme.colors.foreground, - lineHeight: 18, - }, jsonScroll: { borderWidth: theme.borderWidth[1], borderColor: theme.colors.border, diff --git a/packages/app/src/i18n/resources.test.ts b/packages/app/src/i18n/resources.test.ts index 18ba3f041e..b73b2c4fec 100644 --- a/packages/app/src/i18n/resources.test.ts +++ b/packages/app/src/i18n/resources.test.ts @@ -832,7 +832,6 @@ describe("translation resources", () => { expect(en.common.placeholders.search).toBe("Search..."); expect(en.common.empty.noResults).toBe("No results found"); expect(en.common.empty.noOptionsMatchSearch).toBe("No options match your search."); - expect(en.toolCallDetails.subAgentActivity).toBe("Sub-agent activity"); expect(en.panels.file.failedToLoadPreview).toBe("Failed to load file preview"); }); diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index 99d5a11701..7c9e13cce1 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -2013,7 +2013,6 @@ export const ar: TranslationResources = { toolCallDetails: { error: "خطأ", empty: "لا توجد تفاصيل إضافية متاحة", - subAgentActivity: "نشاط الوكيل الفرعي", input: "مدخل", output: "الإخراج", }, diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index 636fe42d5a..7022dc9a3d 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -2038,7 +2038,6 @@ export const en = { toolCallDetails: { error: "Error", empty: "No additional details available", - subAgentActivity: "Sub-agent activity", input: "Input", output: "Output", }, diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index abd5320fe9..1c2c07ade0 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -2061,7 +2061,6 @@ export const es: TranslationResources = { toolCallDetails: { error: "Error", empty: "No hay detalles adicionales disponibles", - subAgentActivity: "Actividad de subagente", input: "Aporte", output: "Producción", }, diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index 848666b2bb..bf1c3b6f5e 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -2060,7 +2060,6 @@ export const fr: TranslationResources = { toolCallDetails: { error: "Erreur", empty: "Aucun détail supplémentaire disponible", - subAgentActivity: "Activité du sous-agent", input: "Entrée", output: "Sortie", }, diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index eb6423913e..5147134716 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -2033,7 +2033,6 @@ export const ja: TranslationResources = { toolCallDetails: { error: "エラー", empty: "追加の詳細はありません", - subAgentActivity: "サブエージェントアクティビティ", input: "入力", output: "出力", }, diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index 54605df4a6..632bd1eeed 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -2023,7 +2023,6 @@ export const ko: TranslationResources = { toolCallDetails: { error: "오류", empty: "추가 세부 정보가 없습니다", - subAgentActivity: "서브에이전트 활동", input: "입력", output: "출력", }, diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index ecedcb5c9e..a80ded2f45 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -2046,7 +2046,6 @@ export const ptBR: TranslationResources = { toolCallDetails: { error: "Erro", empty: "Nenhum detalhe adicional disponível", - subAgentActivity: "Atividade do subagente", input: "Entrada", output: "Saída", }, diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index d9c7afdedd..d4a23a4770 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -2046,7 +2046,6 @@ export const ru: TranslationResources = { toolCallDetails: { error: "Ошибка", empty: "Дополнительные сведения отсутствуют", - subAgentActivity: "Активность субагента", input: "Входные данные", output: "Выходные данные", }, diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index e0b5bbcdb4..2ce5f7bb9e 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -1991,7 +1991,6 @@ export const zhCN: TranslationResources = { toolCallDetails: { error: "错误", empty: "没有可用的更多详情", - subAgentActivity: "Sub-agent 活动", input: "输入", output: "输出", }, diff --git a/packages/app/src/utils/tool-call-detail-state.ts b/packages/app/src/utils/tool-call-detail-state.ts index e2d983d8cb..b28848af8e 100644 --- a/packages/app/src/utils/tool-call-detail-state.ts +++ b/packages/app/src/utils/tool-call-detail-state.ts @@ -40,12 +40,6 @@ function hasMeaningfulFetchDetail(detail: Extract, -): boolean { - return Boolean(detail.subAgentType || detail.description || detail.log); -} - function hasMeaningfulPlainTextDetail( detail: Extract, ): boolean { @@ -75,9 +69,9 @@ export function hasMeaningfulToolCallDetail(detail: ToolCallDetail | undefined): case "fetch": return hasMeaningfulFetchDetail(detail); case "worktree_setup": - return false; + // A sub-agent card is a launch marker; the child's activity lives in the sub-agent panel. case "sub_agent": - return hasMeaningfulSubAgentDetail(detail); + return false; case "plain_text": return hasMeaningfulPlainTextDetail(detail); case "plan": @@ -92,7 +86,7 @@ export function isPendingToolCallDetail(params: { status: "executing" | "running" | "completed" | "failed" | "canceled"; error: unknown; }): boolean { - if (params.detail?.type === "worktree_setup") return false; + if (params.detail?.type === "worktree_setup" || params.detail?.type === "sub_agent") return false; const isRunning = params.status === "running" || params.status === "executing"; return isRunning && params.error == null && !hasMeaningfulToolCallDetail(params.detail); } diff --git a/packages/protocol/src/agent-types.ts b/packages/protocol/src/agent-types.ts index c7fffe8ce9..ca04655430 100644 --- a/packages/protocol/src/agent-types.ts +++ b/packages/protocol/src/agent-types.ts @@ -288,7 +288,7 @@ export type ToolCallDetail = subAgentType?: string; description?: string; childSessionId?: string; - log: string; + log?: string; actions?: Array<{ index: number; toolName: string; diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index 18c3da9b67..8d8f852988 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -641,7 +641,9 @@ const ToolCallDetailPayloadSchema: z.ZodType = z.discri subAgentType: z.string().optional(), description: z.string().optional(), childSessionId: z.string().optional(), - log: z.string(), + // COMPAT(subagent-log): added in v0.14.1, remove after 2027-04-30. A sub-agent card is a + // launch marker; apps before v0.14.1 required `log`, so daemons still send it empty. + log: z.string().optional(), // Compat cruft for clients <= 0.1.65-beta.3 that required this field. Producers still // emit `[]`; nothing reads it. Drop the field (and the `[]` emissions) once those // clients are no longer in the field. diff --git a/packages/protocol/src/messages.wire-compat.test.ts b/packages/protocol/src/messages.wire-compat.test.ts index d6b2bc02ff..abc89b06aa 100644 --- a/packages/protocol/src/messages.wire-compat.test.ts +++ b/packages/protocol/src/messages.wire-compat.test.ts @@ -200,8 +200,8 @@ describe("wire schema compatibility", () => { }); }); - test("sub_agent tool-call payload still parses against the v0.1.65-beta.3 schema", () => { - const parsed = LegacySubAgentToolCallSchema.parse({ + test("a sub-agent launch marker still parses against the v0.1.65-beta.3 schema", () => { + const card = { type: "tool_call", callId: "call-sub-agent-1", name: "Task", @@ -212,12 +212,26 @@ describe("wire schema compatibility", () => { subAgentType: "Explore", description: "Inspect repository structure", childSessionId: "child-session-1", - log: "[Read] README.md", + log: "", actions: [], }, - }); + } as const; - expect(parsed.detail.actions).toEqual([]); + const parsed = LegacySubAgentToolCallSchema.parse(JSON.parse(JSON.stringify(card))); + expect(parsed.detail).toMatchObject({ log: "", actions: [] }); + const { log: _log, ...withoutLog } = card.detail; + expect(LegacySubAgentToolCallSchema.safeParse({ ...card, detail: withoutLog }).success).toBe( + false, + ); + expect(AgentTimelineItemPayloadSchema.parse({ ...card, detail: withoutLog })).toMatchObject({ + detail: { type: "sub_agent", description: "Inspect repository structure" }, + }); + expect( + AgentTimelineItemPayloadSchema.parse({ + ...card, + detail: { ...card.detail, log: "[Read] README.md" }, + }), + ).toMatchObject({ detail: { log: "[Read] README.md" } }); }); test("old clients parse agent snapshots with rewind capabilities", () => { diff --git a/packages/server/src/server/agent/activity-curator.test.ts b/packages/server/src/server/agent/activity-curator.test.ts index c98bbae54d..4e9ce49528 100644 --- a/packages/server/src/server/agent/activity-curator.test.ts +++ b/packages/server/src/server/agent/activity-curator.test.ts @@ -247,7 +247,7 @@ second line'`, ]); }); - it("keeps nested sub-agent logs beside the sub-agent that produced them", () => { + it("lists each sub-agent as its launch marker", () => { const timeline: AgentTimelineItem[] = [ { type: "assistant_message", text: "Before first child." }, toolCallItem({ @@ -257,7 +257,7 @@ second line'`, type: "sub_agent", subAgentType: "Child one", description: "First investigation", - log: "[Assistant] First child result.", + log: "", }, }), { type: "assistant_message", text: "Between children." }, @@ -268,7 +268,7 @@ second line'`, type: "sub_agent", subAgentType: "Child two", description: "Second investigation", - log: "[Assistant] Second child result.", + log: "", }, }), { type: "assistant_message", text: "After second child." }, @@ -279,10 +279,8 @@ second line'`, expect(result.split("\n")).toEqual([ "[Assistant] Before first child.", "[Child one] First investigation", - "[Assistant] First child result.", "[Assistant] Between children.", "[Child two] Second investigation", - "[Assistant] Second child result.", "[Assistant] After second child.", ]); }); diff --git a/packages/server/src/server/agent/activity-curator.ts b/packages/server/src/server/agent/activity-curator.ts index 488867c657..2a7cbff5e6 100644 --- a/packages/server/src/server/agent/activity-curator.ts +++ b/packages/server/src/server/agent/activity-curator.ts @@ -164,9 +164,6 @@ function curateProjectedActivityEntries( break; } entries.push(formatToolCallEntry(item, options)); - if (item.detail.type === "sub_agent" && item.detail.log.trim()) { - entries.push(activityEntry(item.detail.log.trim())); - } break; } case "todo": diff --git a/packages/server/src/server/agent/agent-sdk-types.ts b/packages/server/src/server/agent/agent-sdk-types.ts index 507cfbceb8..6570392311 100644 --- a/packages/server/src/server/agent/agent-sdk-types.ts +++ b/packages/server/src/server/agent/agent-sdk-types.ts @@ -313,7 +313,10 @@ export type ToolCallDetail = subAgentType?: string; description?: string; childSessionId?: string; - log: string; + // COMPAT(subagent-log): added in v0.14.1, remove after 2027-04-30. Apps before v0.14.1 + // require `log`; every producer sends it empty and carries the same tag. Optional here because + // protocol timeline items, where `log` is optional, flow into this type. + log?: string; actions?: Array<{ index: number; toolName: string; diff --git a/packages/server/src/server/agent/providers/claude/agent.background-subagent.test.ts b/packages/server/src/server/agent/providers/claude/agent.background-subagent.test.ts index 8530e76844..8aa15581ae 100644 --- a/packages/server/src/server/agent/providers/claude/agent.background-subagent.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.background-subagent.test.ts @@ -466,13 +466,13 @@ describe("background Claude subagents", () => { type: "sub_agent", subAgentType: "general-purpose", description: "Count files here", - log: "[Bash] ls -1", + log: "", }, }); }); test.each(["before", "after"])( - "keeps one logged Task card when child tools start %s the parent finishes", + "keeps one Task card when child tools start %s the parent finishes", async (timing) => { // A child can stream across the main session's turn boundary. Claude opens the next // main-session turn with system/init; bare child frames do not open a turn. @@ -605,7 +605,7 @@ describe("background Claude subagents", () => { type: "sub_agent", subAgentType: "general-purpose", description: "Count files here", - log: "[Bash] ls -1", + log: "", }, }); }, diff --git a/packages/server/src/server/agent/providers/claude/agent.sub-agent-sidechain.test.ts b/packages/server/src/server/agent/providers/claude/agent.sub-agent-sidechain.test.ts index 84293afa6a..f219baa1b1 100644 --- a/packages/server/src/server/agent/providers/claude/agent.sub-agent-sidechain.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.sub-agent-sidechain.test.ts @@ -273,7 +273,7 @@ describe("ClaudeAgentSession sub-agent sidechain updates", () => { queryFactory.mockReset(); }); - test("accumulates lightweight sub_agent detail and preserves callId lifecycle collapse", async () => { + test("labels the Task card from its input and preserves callId lifecycle collapse", async () => { const session = await new ClaudeAgentClient({ logger, queryFactory, @@ -307,9 +307,7 @@ describe("ClaudeAgentSession sub-agent sidechain updates", () => { expect(latest.detail.subAgentType).toBe("Explore"); expect(latest.detail.description).toBe("Inspect repository structure"); - expect(latest.detail.log).toContain("[Read] README.md"); - expect(latest.detail.log).toContain("[Edit] src/index.ts"); - expect(latest.detail.log).not.toContain("VERY_LARGE_OLD_STRING"); + expect(latest.detail.log).toBe(""); const rows: AgentTimelineRow[] = timelineToolCalls.map((item, index) => ({ seq: index + 1, @@ -396,10 +394,7 @@ describe("ClaudeAgentSession sub-agent sidechain updates", () => { .map((event) => event.item) .at(-1); - expect(latestSubAgentUpdate?.detail).toMatchObject({ - type: "sub_agent", - log: expect.stringContaining("[Read] README.md"), - }); + expect(latestSubAgentUpdate?.detail).toMatchObject({ type: "sub_agent", log: "" }); }); test("routes a resumed SendMessage sidechain to the original child without a second Task card", async () => { @@ -553,7 +548,7 @@ describe("ClaudeAgentSession sub-agent sidechain updates", () => { ).toMatchObject({ type: "upsert", id: "task-tail-1", status: "failed" }); }); - test("tails sub-agent actions instead of dropping latest entries at cap", async () => { + test("keeps the Task card the same size while the child runs", async () => { queryFactory.mockImplementation(() => buildQueryMock(buildTailScenarioEvents(205))); const session = await new ClaudeAgentClient({ @@ -568,24 +563,27 @@ describe("ClaudeAgentSession sub-agent sidechain updates", () => { const events = await collectUntilTerminal(streamSession(session, "delegate work")); await session.close(); - const timelineToolCalls = events - .filter( - (event): event is Extract => - event.type === "timeline" && event.item.type === "tool_call", + const runningCards = events + .flatMap((event) => + event.type === "timeline" && + event.item.type === "tool_call" && + event.item.callId === "task-tail-1" && + event.item.status === "running" && + event.item.detail.type === "sub_agent" + ? [event.item] + : [], ) - .map((event) => event.item) - .filter((item) => item.callId === "task-tail-1"); - const subAgentUpdates = timelineToolCalls.filter((item) => item.detail.type === "sub_agent"); - const latest = subAgentUpdates[subAgentUpdates.length - 1]; - expect(latest).toBeDefined(); - if (!latest || latest.detail.type !== "sub_agent") { - throw new Error("expected sub_agent detail"); - } + .map((item) => JSON.stringify(item)); + expect(runningCards).toHaveLength(1); - expect(latest.detail.log).not.toContain("[Read] file-1.md"); - expect(latest.detail.log).not.toContain("[Read] file-5.md"); - expect(latest.detail.log).toContain("[Read] file-6.md"); - expect(latest.detail.log).toContain("[Read] file-205.md"); + const childToolCalls = events.filter( + (event) => + event.type === "provider_subagent" && + event.event.type === "timeline" && + event.event.id === "task-tail-1" && + event.event.item.type === "tool_call", + ); + expect(childToolCalls).toHaveLength(205); }); test("keeps a long main-thread tool call out of the subagents track", async () => { diff --git a/packages/server/src/server/agent/providers/claude/agent.ts b/packages/server/src/server/agent/providers/claude/agent.ts index 824a93f3da..c675b1ed62 100644 --- a/packages/server/src/server/agent/providers/claude/agent.ts +++ b/packages/server/src/server/agent/providers/claude/agent.ts @@ -4667,7 +4667,7 @@ class ClaudeAgentSession implements AgentSession { /** * The Task card in the parent transcript, built from the declaration. * - * The sidechain tracker also emits this card, enriched with the child's action log, and the two + * The sidechain tracker also emits this card when it first sees the child, and the two * collapse on the shared tool-call id. Emitting it at declaration matters because a * backgrounded subagent produces no sidechain frames at all — verified on the wire — so the * tracker never runs for one and its card would otherwise stay an unlabeled "Task". @@ -6276,6 +6276,7 @@ function buildClaudeSubagentCardDetail( type: "sub_agent", ...(facts.title ? { subAgentType: facts.title } : {}), ...(facts.description ? { description: facts.description } : {}), + // COMPAT(subagent-log): remove after 2027-04-30. log: "", actions: [], }; diff --git a/packages/server/src/server/agent/providers/claude/sidechain-tracker.test.ts b/packages/server/src/server/agent/providers/claude/sidechain-tracker.test.ts index a17c1cd58c..427f279bea 100644 --- a/packages/server/src/server/agent/providers/claude/sidechain-tracker.test.ts +++ b/packages/server/src/server/agent/providers/claude/sidechain-tracker.test.ts @@ -4,7 +4,7 @@ import type { SDKMessage } from "@anthropic-ai/claude-agent-sdk"; import { ClaudeSidechainTracker } from "./sidechain-tracker.js"; describe("ClaudeSidechainTracker", () => { - it("retains a background child's actions across the parent finishing", () => { + it("keeps a background child's card across the parent finishing", () => { const tracker = new ClaudeSidechainTracker({ getToolInput: () => ({ subagent_type: "general-purpose", description: "List files" }), isDescriptorOwnedElsewhere: () => true, @@ -15,27 +15,67 @@ describe("ClaudeSidechainTracker", () => { parent_tool_use_id: "task-1", message: { content: [{ type: "tool_use", id, name: "Bash", input: { command } }] }, }) as unknown as SDKMessage; - tracker.handleMessage(action("ls", "ls -1"), "task-1"); + const parentCards = (events: ReturnType) => + events.filter((event) => event.type === "timeline"); + const childCallIds = (events: ReturnType) => + events.flatMap((event) => + event.type === "provider_subagent" && + event.event.type === "timeline" && + event.event.item.type === "tool_call" + ? [event.event.item.callId] + : [], + ); + + expect(parentCards(tracker.handleMessage(action("ls", "ls -1"), "task-1"))).toHaveLength(1); expect(tracker.finishAll("completed")).toEqual([]); - const events = tracker.handleMessage(action("pwd", "pwd"), "task-1"); - expect(events).toContainEqual( - expect.objectContaining({ - type: "timeline", - item: expect.objectContaining({ - detail: expect.objectContaining({ log: "[Bash] ls -1\n[Bash] pwd" }), - }), - }), - ); + const afterFinish = tracker.handleMessage(action("pwd", "pwd"), "task-1"); + expect(parentCards(afterFinish)).toEqual([]); + expect(childCallIds(afterFinish)).toEqual(["pwd"]); + tracker.delete("task-1"); const next = tracker.handleMessage(action("next", "ls"), "task-1"); - expect(next).toContainEqual( - expect.objectContaining({ - type: "timeline", - item: expect.objectContaining({ - detail: expect.objectContaining({ log: "[Bash] ls" }), - }), - }), - ); + expect(parentCards(next)).toHaveLength(1); + expect(childCallIds(next)).toEqual(["next"]); + }); + + it("shows a streamed child tool call's input once the assistant message brings it", () => { + const tracker = new ClaudeSidechainTracker({ getToolInput: () => null }); + const frames = [ + { + type: "stream_event", + parent_tool_use_id: "task-1", + event: { + type: "content_block_start", + index: 0, + content_block: { type: "tool_use", id: "bash-1", name: "Bash", input: {} }, + }, + }, + { + type: "assistant", + parent_tool_use_id: "task-1", + message: { + content: [ + { type: "tool_use", id: "bash-1", name: "Bash", input: { command: "echo child" } }, + ], + }, + }, + ] as unknown as SDKMessage[]; + + const childCards = frames + .flatMap((frame) => tracker.handleMessage(frame, "task-1")) + .flatMap((event) => + event.type === "provider_subagent" && + event.event.type === "timeline" && + event.event.item.type === "tool_call" + ? [event.event.item] + : [], + ); + + expect(childCards.at(-1)).toMatchObject({ + callId: "bash-1", + status: "running", + detail: { type: "shell", command: "echo child" }, + }); }); it("uses Claude's native agent name for the provider subagent title", () => { diff --git a/packages/server/src/server/agent/providers/claude/sidechain-tracker.ts b/packages/server/src/server/agent/providers/claude/sidechain-tracker.ts index 083b82cea6..5ca79641f9 100644 --- a/packages/server/src/server/agent/providers/claude/sidechain-tracker.ts +++ b/packages/server/src/server/agent/providers/claude/sidechain-tracker.ts @@ -5,7 +5,6 @@ import { mapClaudeFailedToolCall, mapClaudeRunningToolCall, } from "./tool-call-mapper.js"; -import { buildToolCallDisplayModel } from "@getpaseo/protocol/tool-call-display"; import { isClaudeSubagentHandbackToolName, readClaudeSubagentHandback, @@ -20,21 +19,17 @@ interface ClaudeContentChunk { type ClaudeToolCallItem = Extract; -interface SubAgentActionEntry { - index: number; +interface SubAgentChildCall { toolName: string; input: unknown; - summary?: string; } interface SubAgentActivityState { name?: string; subAgentType?: string; description?: string; - actions: SubAgentActionEntry[]; - actionKeys: string[]; - nextActionIndex: number; - actionIndexByKey: Map; + /** The child's tool calls awaiting results, which carry no input of their own. */ + runningCalls: Map; completedActionKeys: Set; } @@ -44,7 +39,6 @@ interface SubAgentActionCandidate { input: unknown; } -const MAX_SUB_AGENT_LOG_ENTRIES = 200; const MAX_SUB_AGENT_SUMMARY_CHARS = 160; function readTrimmedString(value: unknown): string | undefined { @@ -79,8 +73,7 @@ export class ClaudeSidechainTracker { needsSyntheticParentToolCard?: (toolUseId: string) => boolean; /** * The parent's tool call once Claude has answered it. A background child streams its frames - * after that answer, so its card keeps the settled status and output and gains the child's - * action log. + * after that answer, so its card keeps the settled status and output. */ getSettledParentToolCall?: (toolUseId: string) => ClaudeToolCallItem | undefined; }) { @@ -91,28 +84,27 @@ export class ClaudeSidechainTracker { } handleMessage(message: SDKMessage, parentToolUseId: string): AgentStreamEvent[] { + const existingState = this.activeSidechains.get(parentToolUseId); const state = - this.activeSidechains.get(parentToolUseId) ?? + existingState ?? ({ - actions: [], - actionKeys: [], - nextActionIndex: 1, - actionIndexByKey: new Map(), + runningCalls: new Map(), completedActionKeys: new Set(), } satisfies SubAgentActivityState); this.activeSidechains.set(parentToolUseId, state); - const contextUpdated = this.updateSubAgentContextFromTaskInput(state, parentToolUseId); + // The parent card is a launch marker: it changes only when the child is first seen or the + // task input names it differently, never with the child's activity. + const cardUpdated = + this.updateSubAgentContextFromTaskInput(state, parentToolUseId) || !existingState; const actionCandidates = this.extractSubAgentActionCandidates(message); const childTimelineItems = [ ...this.extractSubAgentTimelineItems(message, state), ...this.extractSubAgentToolResults(message, state), ]; - let actionUpdated = false; for (const action of actionCandidates) { if (state.completedActionKeys.has(action.key)) continue; - if (this.appendSubAgentAction(state, action)) { - actionUpdated = true; + if (this.trackChildCall(state, action)) { const toolCall = mapClaudeRunningToolCall({ name: action.toolName, callId: action.key, @@ -125,7 +117,7 @@ export class ClaudeSidechainTracker { } } - if (!contextUpdated && !actionUpdated && childTimelineItems.length === 0) { + if (!cardUpdated && childTimelineItems.length === 0) { return []; } @@ -145,11 +137,8 @@ export class ClaudeSidechainTracker { type: "sub_agent", ...(state.subAgentType ? { subAgentType: state.subAgentType } : {}), ...(state.description ? { description: state.description } : {}), - log: state.actions - .map((action) => - action.summary ? `[${action.toolName}] ${action.summary}` : `[${action.toolName}]`, - ) - .join("\n"), + // COMPAT(subagent-log): remove after 2027-04-30. + log: "", actions: [], }; @@ -170,18 +159,19 @@ export class ClaudeSidechainTracker { }, ]; - const parentCard: AgentStreamEvent[] = this.needsSyntheticParentToolCard(parentToolUseId) - ? [ - { - type: "timeline", - item: { - ...toolCall, - detail, + const parentCard: AgentStreamEvent[] = + cardUpdated && this.needsSyntheticParentToolCard(parentToolUseId) + ? [ + { + type: "timeline", + item: { + ...toolCall, + detail, + }, + provider: "claude", }, - provider: "claude", - }, - ] - : []; + ] + : []; return [ ...descriptorEvents, @@ -303,8 +293,7 @@ export class ClaudeSidechainTracker { if (!isClaudeContentChunk(block) || !block.type.endsWith("tool_result")) continue; const callId = readTrimmedString(block.tool_use_id); if (!callId || state.completedActionKeys.has(callId)) continue; - const actionIndex = state.actionIndexByKey.get(callId); - const action = actionIndex === undefined ? undefined : state.actions[actionIndex]; + const action = state.runningCalls.get(callId); const toolName = action?.toolName ?? readTrimmedString(block.tool_name); if (!toolName) continue; const params = { @@ -317,6 +306,7 @@ export class ClaudeSidechainTracker { ? mapClaudeFailedToolCall({ ...params, error: block }) : mapClaudeCompletedToolCall(params); if (toolCall) { + state.runningCalls.delete(callId); state.completedActionKeys.add(callId); items.push(toolCall); } @@ -412,13 +402,12 @@ export class ClaudeSidechainTracker { const key = readTrimmedString(block.id) ?? `stream:${block.name}:${typeof event.index === "number" ? event.index : 0}`; - return [ - { - key, - toolName: block.name, - input: block.input ?? null, - }, - ]; + // A streamed call starts with `{}` until its input arrives, so an empty input is not final. + const input = + block.input && typeof block.input === "object" && Object.keys(block.input).length > 0 + ? block.input + : null; + return [{ key, toolName: block.name, input }]; } private extractSubAgentActionCandidates(message: SDKMessage): SubAgentActionCandidate[] { @@ -448,84 +437,20 @@ export class ClaudeSidechainTracker { return []; } - private appendSubAgentAction( + /** Returns whether the call is new or has gained its input, so its running card changes. */ + private trackChildCall( state: SubAgentActivityState, candidate: SubAgentActionCandidate, ): boolean { - const normalizedToolName = readTrimmedString(candidate.toolName); - if (!normalizedToolName) { + const toolName = readTrimmedString(candidate.toolName); + if (!toolName) { return false; } - - const summary = this.deriveSubAgentActionSummary(normalizedToolName, candidate.input); - const existingIndex = state.actionIndexByKey.get(candidate.key); - - if (existingIndex !== undefined) { - const existing = state.actions[existingIndex]; - if (!existing) { - return false; - } - const nextSummary = existing.summary ?? summary; - if (existing.toolName === normalizedToolName && existing.summary === nextSummary) { - return false; - } - state.actions[existingIndex] = { - ...existing, - toolName: normalizedToolName, - input: existing.input ?? candidate.input, - ...(nextSummary ? { summary: nextSummary } : {}), - }; - return true; + const existing = state.runningCalls.get(candidate.key); + if (existing && (existing.input !== null || candidate.input === null)) { + return false; } - - state.actions.push({ - index: state.nextActionIndex, - toolName: normalizedToolName, - input: candidate.input, - ...(summary ? { summary } : {}), - }); - state.nextActionIndex += 1; - state.actionKeys.push(candidate.key); - this.trimSubAgentTail(state); - this.rebuildSubAgentActionIndex(state); + state.runningCalls.set(candidate.key, { toolName, input: candidate.input }); return true; } - - private trimSubAgentTail(state: SubAgentActivityState): void { - while (state.actions.length > MAX_SUB_AGENT_LOG_ENTRIES) { - state.actions.shift(); - const removedKey = state.actionKeys.shift(); - if (removedKey) state.completedActionKeys.delete(removedKey); - } - } - - private rebuildSubAgentActionIndex(state: SubAgentActivityState): void { - state.actionIndexByKey.clear(); - for (let index = 0; index < state.actionKeys.length; index += 1) { - const key = state.actionKeys[index]; - if (key) { - state.actionIndexByKey.set(key, index); - } - } - } - - private deriveSubAgentActionSummary(toolName: string, input: unknown): string | undefined { - const runningToolCall = mapClaudeRunningToolCall({ - name: toolName, - callId: `sub-agent-summary-${toolName}`, - input, - output: null, - }); - if (!runningToolCall) { - return undefined; - } - const display = buildToolCallDisplayModel({ - name: runningToolCall.name, - status: runningToolCall.status, - error: runningToolCall.error, - detail: runningToolCall.detail, - metadata: runningToolCall.metadata, - }); - return this.normalizeSubAgentText(display.summary); - } } diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.real.e2e.test.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.real.e2e.test.ts index 5a6592862c..f564b7bf94 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.real.e2e.test.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.real.e2e.test.ts @@ -77,12 +77,19 @@ CHILD_SENTINEL in your own response. const completedChildIndex = events.findIndex( (event) => - event.type === "timeline" && - event.item.type === "tool_call" && - event.item.status === "completed" && - event.item.detail.type === "sub_agent" && - event.item.detail.log.includes("CHILD_SENTINEL"), + event.type === "provider_subagent" && + event.event.type === "upsert" && + event.event.status === "completed", ); + const childAssistantText = events + .flatMap((event) => + event.type === "provider_subagent" && + event.event.type === "timeline" && + event.event.item.type === "assistant_message" + ? [event.event.item.text] + : [], + ) + .join(""); const rootMessageIndexes = events.flatMap((event, index) => event.type === "timeline" && event.item.type === "assistant_message" ? [index] : [], ); @@ -105,6 +112,7 @@ CHILD_SENTINEL in your own response. .map((item) => item.text) .join(""); expect(topLevelAssistantText).not.toContain("CHILD_SENTINEL"); + expect(childAssistantText).toContain("CHILD_SENTINEL"); expect(completedChildIndex).toBeGreaterThanOrEqual(0); expect(rootMessageIndexes[0]).toBeGreaterThan(completedChildIndex); expect(terminalIndexes).toHaveLength(1); diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts index cb8cb2684b..61a86ccb8f 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts @@ -3524,7 +3524,7 @@ describe("Codex app-server provider", () => { ]); }); - test("folds child-thread Codex activity into the parent sub-agent tool call", async () => { + test("keeps child-thread Codex activity out of the parent sub-agent card", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); @@ -3562,7 +3562,6 @@ describe("Codex app-server provider", () => { }); const timelineEvents = events.filter((event) => event.type === "timeline"); - expect(timelineEvents).toHaveLength(4); expect(timelineEvents.every((event) => event.item.type === "tool_call")).toBe(true); const finalItem = timelineEvents.at(-1)?.item; expect(finalItem).toMatchObject({ @@ -3574,7 +3573,7 @@ describe("Codex app-server provider", () => { type: "sub_agent", subAgentType: "Sub-agent", description: "Report findings.", - log: "[Assistant] Found the path.", + log: "", actions: [], }, }); @@ -3651,13 +3650,9 @@ describe("Codex app-server provider", () => { id: "settled-child-thread", status: "completed", }); - expect(events.at(-1)).toMatchObject({ + expect(events.findLast((event) => event.type === "timeline")).toMatchObject({ type: "timeline", - item: { - callId: "call-settled-child", - status: "completed", - detail: { type: "sub_agent", log: "[Assistant] Late trailing output." }, - }, + item: { callId: "call-settled-child", status: "completed" }, }); appServer.completesSubAgentActivity({ @@ -3962,6 +3957,8 @@ describe("Codex app-server provider", () => { createTestLogger(), async () => appServer.child, ); + const events: AgentStreamEvent[] = []; + session.subscribe((event) => events.push(event)); try { const resultPromise = session.run("Delegate the investigation, then report the result."); @@ -4005,11 +4002,18 @@ describe("Codex app-server provider", () => { type: "tool_call", callId: "spawn-child-early", status: "completed", - detail: { - type: "sub_agent", - log: "[Assistant] Early child findings.", - }, + detail: { type: "sub_agent", log: "" }, }); + expect(events).toContainEqual( + expect.objectContaining({ + type: "provider_subagent", + event: expect.objectContaining({ + type: "timeline", + id: "child-thread-early", + item: expect.objectContaining({ type: "assistant_message" }), + }), + }), + ); appServer.assertNoErrors(); } finally { await session.close(); @@ -4080,10 +4084,7 @@ describe("Codex app-server provider", () => { expect(toolCalls.at(-1)).toMatchObject({ callId: "spawn-child-stable", status: "canceled", - detail: { - type: "sub_agent", - log: "[Assistant] Still on the same card.", - }, + detail: { type: "sub_agent", log: "" }, }); appServer.assertNoErrors(); } finally { @@ -4163,11 +4164,10 @@ describe("Codex app-server provider", () => { const result = await resultPromise; const toolCalls = result.timeline.filter((item) => item.type === "tool_call"); - expect(toolCalls.map((item) => item.status)).toEqual(["running", "completed", "completed"]); + expect(toolCalls.map((item) => item.status)).toEqual(["running", "completed"]); expect(toolCalls.at(-1)).toMatchObject({ callId: "spawn-child-late-compaction", status: "completed", - detail: { type: "sub_agent", log: "[Compacted]" }, }); appServer.assertNoErrors(); } finally { @@ -4175,7 +4175,7 @@ describe("Codex app-server provider", () => { } }); - test("projects legacy child tools into one stable sub-agent log", async () => { + test("routes legacy child tools to the child timeline", async () => { const appServer = createFakeCodexAppServer(); const session = new CodexAppServerAgentSession( createConfig({ cwd: "/workspace/project" }), @@ -4183,6 +4183,8 @@ describe("Codex app-server provider", () => { createTestLogger(), async () => appServer.child, ); + const events: AgentStreamEvent[] = []; + session.subscribe((event) => events.push(event)); try { const resultPromise = session.run("Delegate the implementation."); @@ -4225,19 +4227,26 @@ describe("Codex app-server provider", () => { expect(finalToolCall).toMatchObject({ callId: "spawn-legacy-tool-child", status: "completed", - detail: { type: "sub_agent" }, + detail: { type: "sub_agent", log: "" }, }); - if (finalToolCall?.detail.type === "sub_agent") { - expect(finalToolCall.detail.log.match(/\[Shell\]/g)).toHaveLength(1); - expect(finalToolCall.detail.log).toContain("[Edit]"); - } + const childToolCalls = events.flatMap((event) => + event.type === "provider_subagent" && + event.event.type === "timeline" && + event.event.id === "legacy-tool-child" && + event.event.item.type === "tool_call" + ? [event.event.item] + : [], + ); + expect(new Set(childToolCalls.map((item) => item.detail.type))).toEqual( + new Set(["shell", "edit"]), + ); appServer.assertNoErrors(); } finally { await session.close(); } }); - test("keeps nested MultiAgentV2 output inside the root sub-agent card", async () => { + test("keeps nested MultiAgentV2 output out of the root sub-agent card", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); @@ -4297,8 +4306,22 @@ describe("Codex app-server provider", () => { expect(beforeParentCompletes.at(-1)).toMatchObject({ callId: "spawn-child-root", status: "running", - detail: { type: "sub_agent", log: expect.stringContaining("Grandchild findings.") }, + detail: { type: "sub_agent", log: "" }, }); + expect(events).toContainEqual( + expect.objectContaining({ + type: "provider_subagent", + event: { + type: "timeline", + id: "grandchild-thread", + item: { + type: "assistant_message", + messageId: "grandchild-message", + text: "Grandchild findings.", + }, + }, + }), + ); await asInternals(session).handleNotification("turn/completed", { threadId: "child-thread-root", @@ -4365,13 +4388,20 @@ describe("Codex app-server provider", () => { "child-thread-root", "child-thread-root", ]); - expect(events.at(-1)).toMatchObject({ - type: "timeline", - item: { - callId: "spawn-child-root", - detail: { type: "sub_agent", log: expect.stringContaining("Still nested.") }, - }, - }); + expect(events).toContainEqual( + expect.objectContaining({ + type: "provider_subagent", + event: { + type: "timeline", + id: "grandchild-thread", + item: { + type: "assistant_message", + messageId: "grandchild-after-wait", + text: "Still nested.", + }, + }, + }), + ); }); test("never treats an unmapped foreign terminal as the root terminal", async () => { @@ -4791,7 +4821,7 @@ describe("Codex app-server provider", () => { expect(events).toHaveLength(eventCountAfterSpawn); }); - test("keeps child context compaction inside the child card", async () => { + test("keeps child context compaction on the child timeline", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); @@ -4824,10 +4854,70 @@ describe("Codex app-server provider", () => { (item) => item.type === "tool_call" && item.callId === "spawn-child-compaction", ), ).toBe(true); - expect(timelineItems.at(-1)).toMatchObject({ - type: "tool_call", - detail: { type: "sub_agent", log: "[Compacted]" }, + expect( + events.flatMap((event) => + event.type === "provider_subagent" && event.event.type === "timeline" ? [event.event] : [], + ), + ).toEqual([ + { + type: "timeline", + id: "child-thread-compaction", + item: { type: "compaction", status: "loading" }, + }, + { + type: "timeline", + id: "child-thread-compaction", + item: { type: "compaction", status: "completed" }, + }, + ]); + }); + + test("settles a child compaction once when the item completion is missing or duplicated", async () => { + const session = createSession(); + const events: AgentStreamEvent[] = []; + session.subscribe((event) => events.push(event)); + + for (const child of ["compacted-child", "turn-ended-child"]) { + await asInternals(session).handleNotification("item/completed", { + threadId: "test-thread", + item: { + type: "subAgentActivity", + id: `spawn-${child}`, + kind: "started", + agentThreadId: child, + agentPath: `/root/${child}`, + }, + }); + await asInternals(session).handleNotification("item/started", { + threadId: child, + item: { type: "contextCompaction", id: `${child}-compaction` }, + }); + } + await asInternals(session).handleNotification("thread/compacted", { + threadId: "compacted-child", }); + await asInternals(session).handleNotification("item/completed", { + threadId: "compacted-child", + item: { type: "contextCompaction", id: "compacted-child-compaction" }, + }); + await asInternals(session).handleNotification("turn/completed", { + threadId: "turn-ended-child", + turn: { status: "completed" }, + }); + + const compactions = events.flatMap((event) => + event.type === "provider_subagent" && event.event.type === "timeline" + ? [ + `${event.event.id} ${event.event.item.type === "compaction" ? event.event.item.status : ""}`, + ] + : [], + ); + expect(compactions).toEqual([ + "compacted-child loading", + "turn-ended-child loading", + "compacted-child completed", + "turn-ended-child completed", + ]); }); test("keeps the parent sub-agent running when a child command fails during the child turn", async () => { @@ -4862,7 +4952,7 @@ describe("Codex app-server provider", () => { }, }); - expect(events.at(-1)?.item).toMatchObject({ + expect(events.findLast((event) => event.type === "timeline")?.item).toMatchObject({ type: "tool_call", callId: "call-sub-agent-child-command-failure", name: "Sub-agent", @@ -5157,7 +5247,7 @@ describe("Codex app-server provider", () => { ); expect(liveToolCalls.at(-1)).toMatchObject({ status: "running", - detail: { type: "sub_agent", log: "[Assistant] More findings after resume." }, + detail: { type: "sub_agent", log: "" }, }); liveEvents.length = 0; @@ -5170,12 +5260,12 @@ describe("Codex app-server provider", () => { itemId: "legacy-child-message-after-resume", delta: "Legacy findings after resume.", }); - expect(liveEvents.at(-1)).toMatchObject({ + expect(liveEvents.findLast((event) => event.type === "timeline")).toMatchObject({ type: "timeline", item: { callId: "legacy-spawn-history", status: "running", - detail: { type: "sub_agent", log: "[Assistant] Legacy findings after resume." }, + detail: { type: "sub_agent", log: "" }, }, }); }); diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.ts index f7d4f50215..75370f0b5b 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.ts @@ -49,10 +49,10 @@ import { Dirent } from "node:fs"; import fs from "node:fs/promises"; import os from "node:os"; import path from "node:path"; +import { isDeepStrictEqual } from "node:util"; import { z } from "zod"; import { renderPromptAttachmentAsText } from "../prompt-attachments.js"; import { composeSystemPromptParts } from "../system-prompt.js"; -import { curateAgentActivity } from "../activity-curator.js"; import { CodexAsyncQuestions, codexAsyncQuestionToTimeline } from "./codex/async-questions.js"; import { mapCodexToolCallEnvelope, @@ -3384,8 +3384,6 @@ interface CodexSubAgentCallState { activityItemIds: Set; pendingCommandOutputDeltas: Map; pendingFileChangeOutputDeltas: Map; - childItemOrder: string[]; - childItems: Map; childThreadIds: Set; } @@ -3487,6 +3485,9 @@ export class CodexAppServerAgentSession implements AgentSession { private compactionTriggerByItemId = new Map(); private pendingRootCompactionItemIds = new Set(); private pendingAnonymousRootCompactions = 0; + // Child threads with a compaction shown as loading. Some Codex builds settle it only through + // `thread/compacted` or the end of the child's turn. + private pendingChildCompactionThreadIds = new Set(); // Codex can report one completed compaction through both channels: // `thread/compacted` and a completed `contextCompaction` item. private unpairedCompactionNotificationCompletions = 0; @@ -5516,6 +5517,9 @@ export class CodexAppServerAgentSession implements AgentSession { case "patch_apply_completed": this.handlePatchApplyCompletedNotification(parsed, callId); return; + case "context_compacted": + this.settleChildCompaction(parsed.threadId); + return; default: // Aggregate child telemetry is redundant and must not leak into the // root timeline. Concrete legacy tools are projected above for Codex @@ -5692,20 +5696,10 @@ export class CodexAppServerAgentSession implements AgentSession { activityItemIds: new Set(), pendingCommandOutputDeltas: new Map(), pendingFileChangeOutputDeltas: new Map(), - childItemOrder: [], - childItems: new Map(), childThreadIds: new Set(), } satisfies CodexSubAgentCallState); - state.toolCall = { - ...timelineItem, - detail: { - ...timelineItem.detail, - log: - timelineItem.detail.log || - (state.toolCall.detail.type === "sub_agent" ? state.toolCall.detail.log : ""), - }, - }; + state.toolCall = timelineItem; state.parentCallId ??= parentCallId; state.parentSubagentId ??= parentSubagentId; const activity = readCodexSubAgentActivity(rawItem); @@ -5758,25 +5752,17 @@ export class CodexAppServerAgentSession implements AgentSession { const activityToolCall = mapCodexToolCallFromThreadItem(rawItem, { cwd: this.config.cwd ?? null, }); - if ( - activityToolCall?.detail.type === "sub_agent" && - state.toolCall.detail.type === "sub_agent" - ) { - state.toolCall = { - ...state.toolCall, - detail: { - ...state.toolCall.detail, - subAgentType: activityToolCall.detail.subAgentType, - }, - }; - } + const subAgentType = + activityToolCall?.detail.type === "sub_agent" + ? activityToolCall.detail.subAgentType + : undefined; let nextStatus: ToolCallTimelineItem["status"] | undefined = "running"; if (activity.kind === "interrupted") { nextStatus = "canceled"; } else if (isTerminalSubAgentStatus(state.toolCall.status)) { nextStatus = undefined; } - this.emitSubAgentActivityUpdate(callId, nextStatus); + this.emitSubAgentActivityUpdate(callId, nextStatus, { subAgentType }); return true; } @@ -5817,7 +5803,13 @@ export class CodexAppServerAgentSession implements AgentSession { ): boolean { if ( childSubAgentCallId && - this.handleSubAgentContextCompactionItem(childSubAgentCallId, parsed.item, "completed") + parsed.threadId && + this.handleSubAgentContextCompactionItem( + childSubAgentCallId, + parsed.threadId, + parsed.item, + "completed", + ) ) { return true; } @@ -5827,17 +5819,6 @@ export class CodexAppServerAgentSession implements AgentSession { ); } - private upsertSubAgentChildItem(callId: string, itemId: string, item: AgentTimelineItem): void { - const state = this.subAgentCallsByCallId.get(callId); - if (!state) { - return; - } - if (!state.childItems.has(itemId)) { - state.childItemOrder.push(itemId); - } - state.childItems.set(itemId, item); - } - private emitCodexToolTimelineItem( timelineItem: ToolCallTimelineItem, subAgentCallId: string | null, @@ -5847,7 +5828,6 @@ export class CodexAppServerAgentSession implements AgentSession { this.emitEvent({ type: "timeline", provider: CODEX_PROVIDER, item: timelineItem }); return; } - this.upsertSubAgentChildItem(subAgentCallId, timelineItem.callId, timelineItem); const state = this.subAgentCallsByCallId.get(subAgentCallId); if (state) { const targetThreadIds = childThreadId ? [childThreadId] : state.childThreadIds; @@ -5861,26 +5841,15 @@ export class CodexAppServerAgentSession implements AgentSession { ); } - private getSubAgentChildTimeline(state: CodexSubAgentCallState): AgentTimelineItem[] { - return state.childItemOrder - .map((itemId) => state.childItems.get(itemId)) - .filter((item): item is AgentTimelineItem => Boolean(item)); - } - private emitSubAgentActivityUpdate( callId: string, status?: ToolCallTimelineItem["status"], - options?: { reopen?: boolean }, + options?: { reopen?: boolean; subAgentType?: string }, ): void { const state = this.subAgentCallsByCallId.get(callId); if (!state || state.toolCall.detail.type !== "sub_agent") { return; } - const childTimeline = this.getSubAgentChildTimeline(state); - const log = - childTimeline.length > 0 - ? curateAgentActivity(childTimeline, { labelAssistantMessages: true }) - : ""; let resolvedStatus = status ?? state.toolCall.status; if ( status === "running" && @@ -5889,16 +5858,12 @@ export class CodexAppServerAgentSession implements AgentSession { ) { resolvedStatus = state.toolCall.status; } - for (const childThreadId of state.childThreadIds) { - this.emitProviderSubagentUpsert(childThreadId, state, resolvedStatus); - } - const baseToolCall = { - ...state.toolCall, - detail: { - ...state.toolCall.detail, - log, - }, - }; + const baseToolCall = options?.subAgentType + ? { + ...state.toolCall, + detail: { ...state.toolCall.detail, subAgentType: options.subAgentType }, + } + : state.toolCall; const nextToolCall: ToolCallTimelineItem = resolvedStatus === "failed" ? { @@ -5911,10 +5876,14 @@ export class CodexAppServerAgentSession implements AgentSession { status: resolvedStatus, error: null, }; + // The card is a launch marker: the child's activity streams to its own timeline, so the card + // is re-sent only when its status or label changes. + const cardChanged = !isDeepStrictEqual(nextToolCall, state.toolCall); state.toolCall = nextToolCall; - if (state.parentCallId && state.parentCallId !== callId) { - this.upsertSubAgentChildItem(state.parentCallId, state.callId, nextToolCall); - this.emitSubAgentActivityUpdate(state.parentCallId); + for (const childThreadId of state.childThreadIds) { + this.emitProviderSubagentUpsert(childThreadId, state, resolvedStatus); + } + if (!cardChanged || (state.parentCallId && state.parentCallId !== callId)) { return; } this.emitEvent({ type: "timeline", provider: CODEX_PROVIDER, item: nextToolCall }); @@ -6022,7 +5991,6 @@ export class CodexAppServerAgentSession implements AgentSession { ): void { this.applyBufferedDeltaTextToTimelineItem(timelineItem, itemId); if (itemId) { - this.upsertSubAgentChildItem(callId, itemId, timelineItem); this.pendingAgentMessages.delete(itemId); this.pendingReasoning.delete(itemId); this.pendingCommandOutputDeltas.delete(itemId); @@ -6033,19 +6001,29 @@ export class CodexAppServerAgentSession implements AgentSession { private handleSubAgentContextCompactionItem( callId: string, + childThreadId: string, item: { id?: string; type?: string; [key: string]: unknown }, status: "loading" | "completed", ): boolean { if (!this.isContextCompactionItem(item)) { return false; } - if (item.id) { - this.upsertSubAgentChildItem(callId, item.id, { type: "compaction", status }); + if (status === "loading") { + this.pendingChildCompactionThreadIds.add(childThreadId); + this.emitProviderSubagentTimeline(childThreadId, { type: "compaction", status }); + } else { + this.settleChildCompaction(childThreadId); } this.emitSubAgentActivityUpdate(callId); return true; } + private settleChildCompaction(childThreadId: string): void { + if (this.pendingChildCompactionThreadIds.delete(childThreadId)) { + this.emitProviderSubagentTimeline(childThreadId, { type: "compaction", status: "completed" }); + } + } + private shouldSkipCompletedThreadItem( timelineItem: AgentTimelineItem, normalizedItemType: string | undefined, @@ -6076,11 +6054,6 @@ export class CodexAppServerAgentSession implements AgentSession { text: parsed.delta, }); } - this.upsertSubAgentChildItem(subAgentCallId, parsed.itemId, { - type: "assistant_message", - messageId: parsed.itemId, - text, - }); this.emitSubAgentActivityUpdate(subAgentCallId, "running"); return; } @@ -6114,10 +6087,6 @@ export class CodexAppServerAgentSession implements AgentSession { text: parsed.delta, }); } - this.upsertSubAgentChildItem(subAgentCallId, parsed.itemId, { - type: "reasoning", - text: prev.join(""), - }); this.emitSubAgentActivityUpdate(subAgentCallId, "running"); return; } @@ -6185,6 +6154,7 @@ export class CodexAppServerAgentSession implements AgentSession { ): void { const subAgentCallId = this.getSubAgentCallIdForThread(parsed.threadId); if (subAgentCallId) { + if (parsed.threadId) this.settleChildCompaction(parsed.threadId); let status: ToolCallTimelineItem["status"] = "completed"; if (parsed.status === "failed") { status = "failed"; @@ -6771,7 +6741,13 @@ export class CodexAppServerAgentSession implements AgentSession { const childSubAgentCallId = this.getSubAgentCallIdForThread(parsed.threadId); if ( childSubAgentCallId && - this.handleSubAgentContextCompactionItem(childSubAgentCallId, parsed.item, "loading") + parsed.threadId && + this.handleSubAgentContextCompactionItem( + childSubAgentCallId, + parsed.threadId, + parsed.item, + "loading", + ) ) { return; } @@ -6802,9 +6778,6 @@ export class CodexAppServerAgentSession implements AgentSession { }); if (childSubAgentCallId) { this.emitStartedProviderSubagentItem(parsed.threadId, timelineItem); - if (parsed.item.id) { - this.upsertSubAgentChildItem(childSubAgentCallId, parsed.item.id, timelineItem); - } this.emitSubAgentActivityUpdate(childSubAgentCallId, "running"); await this.replayPendingSubAgentNotifications(registeredChildThreadIds); return; @@ -6858,9 +6831,6 @@ export class CodexAppServerAgentSession implements AgentSession { if (parsed.threadId) { this.emitProviderSubagentTimeline(parsed.threadId, timelineItem); } - if (itemId) { - this.upsertSubAgentChildItem(childSubAgentCallId, itemId, timelineItem); - } this.emitSubAgentActivityUpdate(childSubAgentCallId, "running"); return; } diff --git a/packages/server/src/server/agent/providers/codex/tool-call-mapper.ts b/packages/server/src/server/agent/providers/codex/tool-call-mapper.ts index 64629bc5d9..4e77dc9367 100644 --- a/packages/server/src/server/agent/providers/codex/tool-call-mapper.ts +++ b/packages/server/src/server/agent/providers/codex/tool-call-mapper.ts @@ -950,6 +950,7 @@ function mapCollabAgentToolCallItem( type: "sub_agent", subAgentType: "Sub-agent", ...(item.prompt ? { description: item.prompt } : {}), + // COMPAT(subagent-log): remove after 2027-04-30. log: "", actions: [], }; @@ -1006,6 +1007,7 @@ function mapSubAgentActivityItem( type: "sub_agent", subAgentType: nativeName, description, + // COMPAT(subagent-log): remove after 2027-04-30. log: "", actions: [], }, diff --git a/packages/server/src/server/agent/providers/omp/agent.ts b/packages/server/src/server/agent/providers/omp/agent.ts index f2f405540b..c8b44c0bd8 100644 --- a/packages/server/src/server/agent/providers/omp/agent.ts +++ b/packages/server/src/server/agent/providers/omp/agent.ts @@ -69,7 +69,7 @@ import { type OmpRuntimeOptions, } from "./provider-config.js"; export { formatOmpVersionSupport, resolveOmpDiagnosticPaths } from "./provider-config.js"; -import { OmpSubagentCardTracker, type OmpSubagentCardScheduler } from "./subagent-card-tracker.js"; +import { OmpSubagentCardTracker } from "./subagent-card-tracker.js"; import { ompSkillPromptUserText, shouldDisplayOmpCustomMessage } from "./custom-message.js"; import { getUserMessageText } from "./message-history.js"; import { mapOmpSystemNoticeToNotification } from "./system-notice.js"; @@ -130,7 +130,6 @@ export interface OmpAgentClientOptions { logger: Logger; runtimeSettings?: ProviderRuntimeSettings; runtime?: OmpRuntime; - subagentCardScheduler?: OmpSubagentCardScheduler; providerIdleScheduler?: OmpProviderIdleScheduler; noTurnScheduler?: OmpNoTurnScheduler; usagePollScheduler?: OmpUsagePollScheduler; @@ -205,7 +204,6 @@ interface OmpAgentSessionOptions { initialState: OmpSessionState; currentModeId?: string | null; logger: Logger; - subagentCardScheduler?: OmpSubagentCardScheduler; providerIdleScheduler?: OmpProviderIdleScheduler; noTurnScheduler?: OmpNoTurnScheduler; usagePollScheduler?: OmpUsagePollScheduler; @@ -773,9 +771,7 @@ export class OmpAgentSession implements AgentSession { this.logger.debug({ err: error }, "OMP context usage poll failed"); }, }); - this.subagentCardTracker = new OmpSubagentCardTracker({ - scheduler: options.subagentCardScheduler, - }); + this.subagentCardTracker = new OmpSubagentCardTracker(); this.lastKnownThinkingOptionId = normalizeOmpThinkingOption(options.config.thinkingOptionId) ?? this.state.thinkingLevel ?? @@ -2155,8 +2151,7 @@ export class OmpAgentSession implements AgentSession { return mapOmpToolDetail(toolCall, result, { toolCallId, bridgedTool: this.hostTools?.bridge?.tool(toolCall.toolName), - mapSubagentDetail: (detail) => - this.subagentCardTracker.detailFor(toolCallId, detail) ?? detail, + mapSubagentDetail: (detail) => this.subagentCardTracker.detailFor(toolCallId, detail), }); } @@ -2246,7 +2241,6 @@ export class OmpAgentClient implements AgentClient { private readonly logger: Logger; private readonly runtimeSettings?: ProviderRuntimeSettings; - private readonly subagentCardScheduler?: OmpSubagentCardScheduler; private readonly providerIdleScheduler?: OmpProviderIdleScheduler; private readonly noTurnScheduler?: OmpNoTurnScheduler; private readonly usagePollScheduler?: OmpUsagePollScheduler; @@ -2265,7 +2259,6 @@ export class OmpAgentClient implements AgentClient { ); this.logger = options.logger; this.runtimeSettings = runtimeSettings; - this.subagentCardScheduler = options.subagentCardScheduler; this.providerIdleScheduler = options.providerIdleScheduler; this.noTurnScheduler = options.noTurnScheduler; this.usagePollScheduler = options.usagePollScheduler; @@ -2349,7 +2342,6 @@ export class OmpAgentClient implements AgentClient { initialState, currentModeId: launchMode.modeId, logger: this.logger, - subagentCardScheduler: this.subagentCardScheduler, providerIdleScheduler: this.providerIdleScheduler, noTurnScheduler: this.noTurnScheduler, usagePollScheduler: this.usagePollScheduler, @@ -2421,7 +2413,6 @@ export class OmpAgentClient implements AgentClient { initialState, currentModeId: launchMode.modeId, logger: this.logger, - subagentCardScheduler: this.subagentCardScheduler, providerIdleScheduler: this.providerIdleScheduler, noTurnScheduler: this.noTurnScheduler, usagePollScheduler: this.usagePollScheduler, diff --git a/packages/server/src/server/agent/providers/omp/history-mapper.test.ts b/packages/server/src/server/agent/providers/omp/history-mapper.test.ts index 03c0ebe5ae..6d39c21c2d 100644 --- a/packages/server/src/server/agent/providers/omp/history-mapper.test.ts +++ b/packages/server/src/server/agent/providers/omp/history-mapper.test.ts @@ -637,7 +637,7 @@ describe("OMP history mapper", () => { subAgentType: "explore", description: "Inspect files", childSessionId: "/tmp/omp-task/Explore.jsonl", - log: "done\ntranscript: /tmp/omp-task/Explore.jsonl", + log: "", }, error: null, }, diff --git a/packages/server/src/server/agent/providers/omp/subagent-card-tracker.test.ts b/packages/server/src/server/agent/providers/omp/subagent-card-tracker.test.ts index 5164097661..6819292d33 100644 --- a/packages/server/src/server/agent/providers/omp/subagent-card-tracker.test.ts +++ b/packages/server/src/server/agent/providers/omp/subagent-card-tracker.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "vitest"; -import { OmpSubagentCardTracker, type OmpSubagentCardScheduler } from "./subagent-card-tracker.js"; +import { OmpSubagentCardTracker } from "./subagent-card-tracker.js"; import type { OmpSubagentLifecyclePayload, OmpSubagentProgressPayload } from "./rpc-types.js"; const PARENT_TOOL_CALL_ID = "task-1"; @@ -59,184 +59,84 @@ const PROGRESS: OmpSubagentProgressPayload[] = [ }, ]; -class ManualScheduler implements OmpSubagentCardScheduler { - private currentMs = 0; - private nextId = 1; - private readonly timers = new Map void }>(); - - now(): number { - return this.currentMs; - } - - setTimeout(callback: () => void, delayMs: number) { - const id = this.nextId; - this.nextId += 1; - this.timers.set(id, { dueMs: this.currentMs + delayMs, callback }); - return { token: id }; - } - - clearTimeout(timer: { token: unknown }): void { - if (typeof timer.token === "number") { - this.timers.delete(timer.token); - } - } - - advance(ms: number): void { - this.currentMs += ms; - const dueTimers = [...this.timers.entries()] - .filter(([, timer]) => timer.dueMs <= this.currentMs) - .sort((left, right) => left[1].dueMs - right[1].dueMs); - for (const [id, timer] of dueTimers) { - if (this.timers.delete(id)) { - timer.callback(); - } - } - } -} - describe("OmpSubagentCardTracker", () => { - test("folds lifecycle and progress into one throttled sub-agent detail", () => { - const scheduler = new ManualScheduler(); + test("keeps the card a launch marker while the child runs", () => { const emitted: string[] = []; - const tracker = new OmpSubagentCardTracker({ - scheduler, - emitToolCall: (toolCallId) => { - emitted.push(toolCallId); - return true; - }, - }); - tracker.handleLifecycle(LIFECYCLE); + const emit = (toolCallId: string) => { + emitted.push(toolCallId); + return true; + }; + const tracker = new OmpSubagentCardTracker(); + tracker.handleLifecycle(LIFECYCLE, emit); for (const payload of PROGRESS) { - tracker.handleProgress(payload); + tracker.handleProgress(payload, emit); } expect(emitted).toEqual([PARENT_TOOL_CALL_ID]); - const detailBeforeTrailing = tracker.detailFor(PARENT_TOOL_CALL_ID, { - type: "sub_agent", - subAgentType: "task", - description: "Task arg description wins", - log: "", - }); - expect(detailBeforeTrailing).toEqual({ - type: "sub_agent", - subAgentType: "task", - description: "Task arg description wins", - childSessionId: SESSION_FILE, - log: [ - "EchoSubagent started", - "[bash] echo subagent-hi", - "[yield]", - "EchoSubagent completed", - ].join("\n"), - }); - - scheduler.advance(500); - - expect(emitted).toEqual([PARENT_TOOL_CALL_ID, PARENT_TOOL_CALL_ID]); - }); - - test("aggregates batch progress streams into one index-prefixed log", () => { - const scheduler = new ManualScheduler(); - const emitted: string[] = []; - const tracker = new OmpSubagentCardTracker({ - scheduler, - emitToolCall: (toolCallId) => { - emitted.push(toolCallId); - return true; - }, - }); - - tracker.handleLifecycle({ - id: "Explore", - agent: "task", - description: "Inspect files", - status: "started", - sessionFile: "/tmp/one.jsonl", - parentToolCallId: "task.batch-1", - index: 0, - }); - scheduler.advance(600); - tracker.handleProgress({ - index: 5, - agent: "task", - task: "Run tests", - parentToolCallId: "task.batch-1", - progress: { - id: "Test", - status: "running", - description: "Run tests", - recentTools: [{ tool: "bash", args: "npm test", endMs: 10 }], - }, - sessionFile: "/tmp/two.jsonl", - }); - - expect(emitted).toEqual(["task.batch-1", "task.batch-1"]); expect( - tracker.detailFor("task.batch-1", { + tracker.detailFor(PARENT_TOOL_CALL_ID, { type: "sub_agent", - subAgentType: "batch", - actions: [], + subAgentType: "task", + description: "Task arg description wins", log: "", }), ).toEqual({ type: "sub_agent", - subAgentType: "batch", - description: "Inspect files", - childSessionId: "/tmp/one.jsonl", - log: "[1/6] Explore started\n[6/6] [bash] npm test", - actions: [], + subAgentType: "task", + description: "Task arg description wins", + childSessionId: SESSION_FILE, + log: "", }); }); - test("keeps dirty trailing state available for final detail and cancels it on cleanup", () => { - const scheduler = new ManualScheduler(); + test("re-emits the card when a later event names the child", () => { const emitted: string[] = []; - const tracker = new OmpSubagentCardTracker({ - scheduler, - emitToolCall: (toolCallId) => { - emitted.push(toolCallId); - return true; + const emit = (toolCallId: string) => { + emitted.push(toolCallId); + return true; + }; + const tracker = new OmpSubagentCardTracker(); + tracker.handleLifecycle({ ...LIFECYCLE, description: undefined, sessionFile: undefined }, emit); + tracker.handleProgress(PROGRESS[0], emit); + + expect(emitted).toEqual([PARENT_TOOL_CALL_ID, PARENT_TOOL_CALL_ID]); + expect(tracker.detailFor(PARENT_TOOL_CALL_ID, { type: "sub_agent", log: "" })).toEqual({ + type: "sub_agent", + childSessionId: SESSION_FILE, + log: "", + }); + + tracker.delete(PARENT_TOOL_CALL_ID); + expect(tracker.detailFor(PARENT_TOOL_CALL_ID, { type: "sub_agent", log: "" })).toEqual({ + type: "sub_agent", + log: "", + }); + }); + test("leaves the card alone when a later child of the same task starts", () => { + const emitted: string[] = []; + const emit = (toolCallId: string) => { + emitted.push(toolCallId); + return true; + }; + const tracker = new OmpSubagentCardTracker(); + tracker.handleLifecycle(LIFECYCLE, emit); + tracker.handleLifecycle( + { + ...LIFECYCLE, + id: "Second", + index: 1, + description: "Second child", + sessionFile: "/s.jsonl", }, + emit, + ); + + expect(emitted).toEqual([PARENT_TOOL_CALL_ID]); + expect(tracker.detailFor(PARENT_TOOL_CALL_ID, { type: "sub_agent", log: "" })).toEqual({ + type: "sub_agent", + description: "Run echo in subagent", + childSessionId: SESSION_FILE, + log: "", }); - - tracker.handleLifecycle({ - id: "Explore", - agent: "task", - description: "Inspect files", - status: "started", - parentToolCallId: "task-1", - index: 0, - }); - scheduler.advance(100); - tracker.handleProgress({ - index: 0, - agent: "task", - task: "Inspect files", - parentToolCallId: "task-1", - progress: { - id: "Explore", - status: "running", - recentOutput: ["found target file"], - }, - }); - - expect(emitted).toEqual(["task-1"]); - expect( - tracker.detailFor("task-1", { - type: "sub_agent", - log: "", - }).log, - ).toBe("Explore started\nfound target file"); - - tracker.delete("task-1"); - scheduler.advance(500); - - expect(emitted).toEqual(["task-1"]); - expect( - tracker.detailFor("task-1", { - type: "sub_agent", - log: "static", - }).log, - ).toBe("static"); }); }); diff --git a/packages/server/src/server/agent/providers/omp/subagent-card-tracker.ts b/packages/server/src/server/agent/providers/omp/subagent-card-tracker.ts index 7034c4c506..60ad291058 100644 --- a/packages/server/src/server/agent/providers/omp/subagent-card-tracker.ts +++ b/packages/server/src/server/agent/providers/omp/subagent-card-tracker.ts @@ -1,361 +1,106 @@ import type { ToolCallDetail } from "../../agent-sdk-types.js"; import type { OmpSubagentLifecyclePayload, OmpSubagentProgressPayload } from "./rpc-types.js"; -export interface OmpSubagentCardTimer { - readonly token: unknown; -} - -export interface OmpSubagentCardScheduler { - now(): number; - setTimeout(callback: () => void, delayMs: number): OmpSubagentCardTimer; - clearTimeout(timer: OmpSubagentCardTimer): void; -} - -export interface OmpSubagentCardTrackerOptions { - scheduler?: OmpSubagentCardScheduler; - emitToolCall?: (toolCallId: string) => boolean; -} - -interface OmpSubagentLogLine { - key: string; - text: string; -} - -interface OmpSubagentCardItem { +interface OmpSubagentCardChild { index: number; description?: string; - agent?: string; - status?: "pending" | "running" | "completed" | "failed" | "aborted"; childSessionId?: string; - lines: OmpSubagentLogLine[]; - lineKeys: Set; -} - -interface OmpSubagentCardState { - items: Map; - emitToolCall: (toolCallId: string) => boolean; - lastEmitMs: number | null; - trailingTimer: OmpSubagentCardTimer | null; - dirty: boolean; -} - -const MAX_LOG_LINES_PER_ITEM = 200; -const MAX_LOG_LINE_CHARS = 240; -const THROTTLE_INTERVAL_MS = 500; - -export function createOmpSubagentCardScheduler(): OmpSubagentCardScheduler { - return { - now: () => Date.now(), - setTimeout: (callback, delayMs) => ({ token: setTimeout(callback, delayMs) }), - clearTimeout: (timer) => { - clearTimeout(timer.token as ReturnType); - }, - }; } +/** + * Fills a task card's description and child session from OMP's sub-agent events. The card is a + * launch marker that names the task's first child; the children's activity belongs to their own + * timelines. + */ export class OmpSubagentCardTracker { - private readonly scheduler: OmpSubagentCardScheduler; - private readonly emitToolCall: (toolCallId: string) => boolean; - private readonly states = new Map(); - - constructor(options: OmpSubagentCardTrackerOptions) { - this.scheduler = options.scheduler ?? createOmpSubagentCardScheduler(); - this.emitToolCall = options.emitToolCall ?? (() => false); - } + private readonly firstChildren = new Map(); handleLifecycle( payload: OmpSubagentLifecyclePayload, - emitToolCall: (toolCallId: string) => boolean = this.emitToolCall, + emitToolCall: (toolCallId: string) => boolean, ): void { - const parentToolCallId = readTrimmedString(payload.parentToolCallId); - if (!parentToolCallId) { - return; - } - this.stateFor(parentToolCallId).emitToolCall = emitToolCall; - const item = this.upsertItem(parentToolCallId, { - index: payload.index, - agent: payload.agent, - description: payload.description, - status: payload.status === "started" ? "running" : payload.status, - childSessionId: payload.sessionFile, - }); - this.appendLine( - item, - `lifecycle:${payload.status}:${payload.id}`, - `${payload.id} ${payload.status}`, + this.update( + payload.parentToolCallId, + { + index: payload.index, + description: payload.description, + childSessionId: payload.sessionFile, + }, + emitToolCall, ); - this.requestEmit(parentToolCallId); } handleProgress( payload: OmpSubagentProgressPayload, - emitToolCall: (toolCallId: string) => boolean = this.emitToolCall, + emitToolCall: (toolCallId: string) => boolean, ): void { - const parentToolCallId = readTrimmedString(payload.parentToolCallId); - if (!parentToolCallId) { - return; - } - this.stateFor(parentToolCallId).emitToolCall = emitToolCall; - const item = this.upsertItem(parentToolCallId, { - index: payload.index, - agent: payload.agent, - description: payload.progress.description, - status: payload.progress.status, - childSessionId: payload.sessionFile, - }); - - const currentToolLine = summarizeTool(readRecord(payload.progress.currentTool)); - if (currentToolLine) { - this.appendLine(item, `current:${currentToolLine.key}`, currentToolLine.text); - } - - for (const tool of readRecordArray(payload.progress.recentTools)) { - const line = summarizeTool(tool); - if (line) { - this.appendLine(item, `tool:${line.key}`, line.text); - } - } - - for (const output of readOutputLines(payload.progress.recentOutput)) { - this.appendLine(item, `output:${output}`, output); - } - - if (payload.progress.status !== "running") { - this.appendLine( - item, - `status:${payload.progress.status}:${payload.progress.id}`, - `${payload.progress.id} ${payload.progress.status}`, - ); - } - - this.requestEmit(parentToolCallId); + this.update( + payload.parentToolCallId, + { + index: payload.index, + description: payload.progress.description, + childSessionId: payload.sessionFile, + }, + emitToolCall, + ); } detailFor(toolCallId: string, baseDetail: ToolCallDetail): ToolCallDetail { if (baseDetail.type !== "sub_agent") { return baseDetail; } - const state = this.states.get(toolCallId); - if (!state) { + const first = this.firstChildren.get(toolCallId); + if (!first) { return baseDetail; } - const items = [...state.items.values()].sort((left, right) => left.index - right.index); - const firstItem = items[0]; - if (!firstItem) { - return baseDetail; - } - - const detail: ToolCallDetail = { - type: "sub_agent", - ...(baseDetail.subAgentType ? { subAgentType: baseDetail.subAgentType } : {}), - ...((baseDetail.description ?? firstItem.description) - ? { description: baseDetail.description ?? firstItem.description } - : {}), - ...((firstItem.childSessionId ?? baseDetail.childSessionId) - ? { childSessionId: firstItem.childSessionId ?? baseDetail.childSessionId } - : {}), - log: buildLog(items, baseDetail.log), + const description = baseDetail.description ?? first.description; + const childSessionId = first.childSessionId ?? baseDetail.childSessionId; + return { + ...baseDetail, + ...(description ? { description } : {}), + ...(childSessionId ? { childSessionId } : {}), }; - return baseDetail.actions ? { ...detail, actions: baseDetail.actions } : detail; - } - - flush(toolCallId: string): void { - const state = this.states.get(toolCallId); - if (!state || !state.dirty) { - return; - } - this.emitNow(toolCallId, state); } delete(toolCallId: string): void { - const state = this.states.get(toolCallId); - if (state?.trailingTimer) { - this.scheduler.clearTimeout(state.trailingTimer); - } - this.states.delete(toolCallId); + this.firstChildren.delete(toolCallId); } clear(): void { - for (const toolCallId of this.states.keys()) { - this.delete(toolCallId); - } + this.firstChildren.clear(); } - private upsertItem( - parentToolCallId: string, - input: { - index: number; - agent?: string; - status?: "pending" | "running" | "completed" | "failed" | "aborted"; - description?: string; - childSessionId?: string; - }, - ): OmpSubagentCardItem { - const state = this.stateFor(parentToolCallId); - const existing = state.items.get(input.index); - if (existing) { - existing.agent = readTrimmedString(input.agent) ?? existing.agent; - existing.status = input.status ?? existing.status; - existing.description = readTrimmedString(input.description) ?? existing.description; - existing.childSessionId = readTrimmedString(input.childSessionId) ?? existing.childSessionId; - return existing; + private update( + parentToolCallId: string | undefined, + input: { index: number; description?: string; childSessionId?: string }, + emitToolCall: (toolCallId: string) => boolean, + ): void { + const toolCallId = readTrimmedString(parentToolCallId); + if (!toolCallId) { + return; } - - const item: OmpSubagentCardItem = { + const first = this.firstChildren.get(toolCallId); + if (first && input.index > first.index) { + return; + } + const existing = first?.index === input.index ? first : undefined; + const next: OmpSubagentCardChild = { index: input.index, - lines: [], - lineKeys: new Set(), - ...(readTrimmedString(input.agent) ? { agent: readTrimmedString(input.agent) } : {}), - ...(input.status ? { status: input.status } : {}), - ...(readTrimmedString(input.description) - ? { description: readTrimmedString(input.description) } - : {}), - ...(readTrimmedString(input.childSessionId) - ? { childSessionId: readTrimmedString(input.childSessionId) } - : {}), + description: readTrimmedString(input.description) ?? existing?.description, + childSessionId: readTrimmedString(input.childSessionId) ?? existing?.childSessionId, }; - state.items.set(input.index, item); - return item; - } - - private stateFor(parentToolCallId: string): OmpSubagentCardState { - const existing = this.states.get(parentToolCallId); - if (existing) { - return existing; - } - const state: OmpSubagentCardState = { - items: new Map(), - emitToolCall: this.emitToolCall, - lastEmitMs: null, - trailingTimer: null, - dirty: false, - }; - this.states.set(parentToolCallId, state); - return state; - } - - private appendLine(item: OmpSubagentCardItem, key: string, text: string): void { - const normalizedText = normalizeLine(text); - if (!normalizedText || item.lineKeys.has(key)) { + if ( + existing && + existing.description === next.description && + existing.childSessionId === next.childSessionId + ) { return; } - item.lines.push({ key, text: normalizedText }); - item.lineKeys.add(key); - while (item.lines.length > MAX_LOG_LINES_PER_ITEM) { - const removed = item.lines.shift(); - if (removed) { - item.lineKeys.delete(removed.key); - } - } + this.firstChildren.set(toolCallId, next); + emitToolCall(toolCallId); } - - private requestEmit(toolCallId: string): void { - const state = this.stateFor(toolCallId); - const now = this.scheduler.now(); - const elapsedMs = state.lastEmitMs === null ? THROTTLE_INTERVAL_MS : now - state.lastEmitMs; - if (elapsedMs >= THROTTLE_INTERVAL_MS) { - this.emitNow(toolCallId, state); - return; - } - - state.dirty = true; - if (state.trailingTimer) { - return; - } - state.trailingTimer = this.scheduler.setTimeout(() => { - state.trailingTimer = null; - if (state.dirty) { - this.emitNow(toolCallId, state); - } - }, THROTTLE_INTERVAL_MS - elapsedMs); - } - - private emitNow(toolCallId: string, state: OmpSubagentCardState): void { - if (state.trailingTimer) { - this.scheduler.clearTimeout(state.trailingTimer); - state.trailingTimer = null; - } - state.dirty = false; - state.lastEmitMs = this.scheduler.now(); - state.emitToolCall(toolCallId); - } -} - -function buildLog(items: OmpSubagentCardItem[], fallback: string): string { - const itemCount = Math.max(...items.map((item) => item.index)) + 1; - const lines = items.flatMap((item) => { - const prefix = itemCount > 1 ? `[${item.index + 1}/${itemCount}] ` : ""; - return item.lines.map((line) => `${prefix}${line.text}`); - }); - return lines.length > 0 ? lines.join("\n") : fallback; -} - -function summarizeTool(tool: Record | null): OmpSubagentLogLine | null { - if (!tool) { - return null; - } - const toolName = readTrimmedString(tool.tool) ?? readTrimmedString(tool.name); - if (!toolName) { - return null; - } - const args = readTrimmedString(tool.args) ?? summarizeUnknown(tool.input); - const endMs = typeof tool.endMs === "number" ? `:${tool.endMs}` : ""; - return { - key: `${toolName}:${args ?? ""}${endMs}`, - text: args ? `[${toolName}] ${args}` : `[${toolName}]`, - }; -} - -function readOutputLines(value: unknown): string[] { - if (!Array.isArray(value)) { - return []; - } - return value.flatMap((item) => { - const text = - readTrimmedString(item) ?? - (isRecord(item) - ? (readTrimmedString(item.text) ?? - readTrimmedString(item.output) ?? - readTrimmedString(item.content)) - : undefined); - return text ? [text] : []; - }); -} - -function readRecord(value: unknown): Record | null { - return isRecord(value) ? value : null; -} - -function readRecordArray(value: unknown): Record[] { - return Array.isArray(value) ? value.filter(isRecord) : []; -} - -function summarizeUnknown(value: unknown): string | undefined { - if (value === undefined || value === null) { - return undefined; - } - if (typeof value === "string") { - return readTrimmedString(value); - } - const json = JSON.stringify(value); - return typeof json === "string" ? normalizeLine(json) : undefined; -} - -function normalizeLine(value: string): string | undefined { - const normalized = value.trim().replace(/\s+/g, " "); - if (!normalized) { - return undefined; - } - if (normalized.length <= MAX_LOG_LINE_CHARS) { - return normalized; - } - return `${normalized.slice(0, MAX_LOG_LINE_CHARS)}...`; } function readTrimmedString(value: unknown): string | undefined { return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined; } - -function isRecord(value: unknown): value is Record { - return typeof value === "object" && value !== null && !Array.isArray(value); -} diff --git a/packages/server/src/server/agent/providers/omp/tool-call-mapper.test.ts b/packages/server/src/server/agent/providers/omp/tool-call-mapper.test.ts index ae4c0d0d77..cc13f9001f 100644 --- a/packages/server/src/server/agent/providers/omp/tool-call-mapper.test.ts +++ b/packages/server/src/server/agent/providers/omp/tool-call-mapper.test.ts @@ -85,7 +85,7 @@ describe("OMP tool call mapper", () => { expect(mapOmpToolDetail(parseToolArgs("todo", { op: "view" }), null)).toBeNull(); }); - test("uses task result text and transcript path as the best static replay detail", () => { + test("takes the child session from the task transcript path", () => { expect( mapOmpToolDetail( parseToolArgs("task", { @@ -106,7 +106,7 @@ describe("OMP tool call mapper", () => { subAgentType: "explore", description: "Inspect the target files", childSessionId: "/tmp/omp-task-static/Explore.jsonl", - log: "done\ntranscript: /tmp/omp-task-static/Explore.jsonl", + log: "", }); }); diff --git a/packages/server/src/server/agent/providers/omp/tool-call-mapper.ts b/packages/server/src/server/agent/providers/omp/tool-call-mapper.ts index 86b1ee53ef..500123758a 100644 --- a/packages/server/src/server/agent/providers/omp/tool-call-mapper.ts +++ b/packages/server/src/server/agent/providers/omp/tool-call-mapper.ts @@ -179,7 +179,6 @@ const OPAQUE_TEXT_TOOLS = new Set([ function mapOmpTaskDetail(args: unknown, result: OmpToolResult): ToolCallDetail { const argRecord = isRecord(args) ? args : {}; const firstTask = Array.isArray(argRecord.tasks) ? argRecord.tasks.find(isRecord) : undefined; - const resultText = extractTextFromToolResult(result); const childSessionId = readChildSessionId(result); return { type: "sub_agent", @@ -200,7 +199,8 @@ function mapOmpTaskDetail(args: unknown, result: OmpToolResult): ToolCallDetail argRecord.assignment, ), ...(childSessionId ? { childSessionId } : {}), - log: resultText?.trim() ?? "", + // COMPAT(subagent-log): remove after 2027-04-30. + log: "", }; } diff --git a/packages/server/src/server/agent/providers/opencode-agent.ts b/packages/server/src/server/agent/providers/opencode-agent.ts index 81288f3e4f..6fef290d91 100644 --- a/packages/server/src/server/agent/providers/opencode-agent.ts +++ b/packages/server/src/server/agent/providers/opencode-agent.ts @@ -4846,15 +4846,6 @@ class OpenCodeAgentSession implements AgentSession { ...item, status: "failed", error, - detail: - item.detail.type === "sub_agent" - ? { - ...item.detail, - log: [item.detail.log, error.message] - .filter((entry) => entry.trim().length > 0) - .join("\n"), - } - : item.detail, }, }, turnId, diff --git a/packages/server/src/server/agent/providers/opencode/tool-call-detail-parser.ts b/packages/server/src/server/agent/providers/opencode/tool-call-detail-parser.ts index 8214ebb1d0..b3eb432f86 100644 --- a/packages/server/src/server/agent/providers/opencode/tool-call-detail-parser.ts +++ b/packages/server/src/server/agent/providers/opencode/tool-call-detail-parser.ts @@ -153,21 +153,6 @@ const OpencodeGrepOutputSchema = z ]) .nullable(); -function formatLogEntry(value: unknown): string | undefined { - const outputText = readOutputText(value); - if (outputText) { - return outputText; - } - if (value === null || value === undefined) { - return undefined; - } - try { - return JSON.stringify(value, null, 2); - } catch { - return String(value); - } -} - function extractOpenCodeTaskSessionId(value: unknown): string | undefined { const text = readOutputText(value); if (text) { @@ -195,7 +180,6 @@ function extractOpenCodeTaskSessionId(value: unknown): string | undefined { function deriveOpencodeTaskDetail( input: unknown, output: unknown, - error: unknown, metadata: Record | undefined, ): ToolCallDetail | null { if (!isRecord(input)) { @@ -208,7 +192,6 @@ function deriveOpencodeTaskDetail( return null; } - const log = [formatLogEntry(output), formatLogEntry(error)].filter((entry) => entry).join("\n"); const childSessionId = normalizeSubAgentText(metadata?.sessionId) ?? extractOpenCodeTaskSessionId(output); return { @@ -216,7 +199,8 @@ function deriveOpencodeTaskDetail( ...(subAgentType ? { subAgentType } : {}), ...(description ? { description } : {}), ...(childSessionId ? { childSessionId } : {}), - log, + // COMPAT(subagent-log): remove after 2027-04-30. + log: "", actions: [], }; } @@ -373,11 +357,10 @@ export function deriveOpencodeToolDetail( toolName: string, input: unknown, output: unknown, - error: unknown = null, metadata?: Record, ): ToolCallDetail { if (toolName.trim().toLowerCase() === "task") { - const taskDetail = deriveOpencodeTaskDetail(input, output, error, metadata); + const taskDetail = deriveOpencodeTaskDetail(input, output, metadata); if (taskDetail) { return taskDetail; } diff --git a/packages/server/src/server/agent/providers/opencode/tool-call-mapper.test.ts b/packages/server/src/server/agent/providers/opencode/tool-call-mapper.test.ts index 1c9ba212e1..eb38a04ac6 100644 --- a/packages/server/src/server/agent/providers/opencode/tool-call-mapper.test.ts +++ b/packages/server/src/server/agent/providers/opencode/tool-call-mapper.test.ts @@ -460,7 +460,7 @@ describe("opencode tool-call mapper", () => { }); }); - it("maps completed task calls with final output log to sub_agent detail", () => { + it("maps completed task calls to sub_agent detail", () => { const item = expectMapped( mapOpencodeToolCall({ toolName: "task", @@ -480,7 +480,7 @@ describe("opencode tool-call mapper", () => { type: "sub_agent", subAgentType: "explore", description: "Explore agent-tools codebase", - log: "Found the CLI entrypoint and provider registry.", + log: "", actions: [], }); }); @@ -505,12 +505,12 @@ describe("opencode tool-call mapper", () => { subAgentType: "explore", description: "Explore current directory", childSessionId: "ses_2268db431ffe299vL1bbot8R7Z", - log: 'done', + log: "", actions: [], }); }); - it("maps aborted task calls with preserved error log to sub_agent detail", () => { + it("maps aborted task calls to sub_agent detail", () => { const item = expectMapped( mapOpencodeToolCall({ toolName: "task", @@ -531,7 +531,7 @@ describe("opencode tool-call mapper", () => { type: "sub_agent", subAgentType: "explore", description: "Explore agent-tools codebase", - log: "Tool execution aborted", + log: "", actions: [], }); }); diff --git a/packages/server/src/server/agent/providers/opencode/tool-call-mapper.ts b/packages/server/src/server/agent/providers/opencode/tool-call-mapper.ts index 8fbc861a84..261a4ec827 100644 --- a/packages/server/src/server/agent/providers/opencode/tool-call-mapper.ts +++ b/packages/server/src/server/agent/providers/opencode/tool-call-mapper.ts @@ -43,7 +43,7 @@ export function mapOpencodeToolCall(params: OpencodeToolCallParams): ToolCallTim const error = raw.error ?? null; const rawStatus = typeof raw.status === "string" ? raw.status : undefined; const status = normalizeToolCallStatus(rawStatus, error, output); - const detail = deriveOpencodeToolDetail(name, input, output, error, raw.metadata); + const detail = deriveOpencodeToolDetail(name, input, output, raw.metadata); if (status === "failed") { return { diff --git a/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/index.ts b/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/index.ts index c00e39aaad..c58f0faf15 100644 --- a/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/index.ts +++ b/packages/server/src/server/agent/providers/pi/extensions/edxeth-pi-subagents/index.ts @@ -1,5 +1,4 @@ import { z } from "zod"; -import { extractTextFromToolResult } from "../../tool-call-mapper.js"; import type { PiChildSessionFile, PiExtension } from "../contract.js"; import type { ProviderSubagentInputEvent } from "../../../../provider-subagents/store.js"; @@ -99,7 +98,8 @@ export const edxethPiSubagents: PiExtension = { detail: { type: "sub_agent", description, - log: extractTextFromToolResult(call.result)?.trim() ?? "", + // COMPAT(subagent-log): remove after 2027-04-30. + log: "", }, subagents, childSessions, diff --git a/packages/server/src/server/agent/providers/pi/extensions/gotgenes-pi-subagents/index.test.ts b/packages/server/src/server/agent/providers/pi/extensions/gotgenes-pi-subagents/index.test.ts index f89a9aefd3..7bb62a9d1f 100644 --- a/packages/server/src/server/agent/providers/pi/extensions/gotgenes-pi-subagents/index.test.ts +++ b/packages/server/src/server/agent/providers/pi/extensions/gotgenes-pi-subagents/index.test.ts @@ -130,6 +130,18 @@ describe("@gotgenes/pi-subagents adapter", () => { .filter((event) => event.event.type === "upsert") .map((event) => (event.event.type === "upsert" ? event.event.status : null)), ).toEqual(["running", "completed"]); + expect( + events.flatMap((event) => (event.event.type === "timeline" ? [event.event] : [])), + ).toEqual([ + { + type: "timeline", + id: "call_502323", + item: { + type: "assistant_message", + text: "Agent completed in 4.7s (1 tool uses, 9.0k token).\nAgent ID: 848583f5-6749-4a1\n\nThe workspace is empty.", + }, + }, + ]); }); test("correlates a background notification and result collection", async () => { const source = readSubagentFixture(new URL("./fixtures/background.json", import.meta.url)); diff --git a/packages/server/src/server/agent/providers/pi/extensions/gotgenes-pi-subagents/index.ts b/packages/server/src/server/agent/providers/pi/extensions/gotgenes-pi-subagents/index.ts index e1869705f8..9383911c3d 100644 --- a/packages/server/src/server/agent/providers/pi/extensions/gotgenes-pi-subagents/index.ts +++ b/packages/server/src/server/agent/providers/pi/extensions/gotgenes-pi-subagents/index.ts @@ -64,7 +64,8 @@ export const gotgenesPiSubagents: PiExtension = { type: "sub_agent" as const, subAgentType: title, description, - log: extractTextFromToolResult(call.result)?.trim() ?? "", + // COMPAT(subagent-log): remove after 2027-04-30. + log: "", }; if (call.status === "running") return { @@ -92,6 +93,10 @@ export const gotgenesPiSubagents: PiExtension = { outputFileFromToolResult(call.result) ?? pendingFilesByAgent.get(details.data.agentId); pendingFilesByAgent.delete(details.data.agentId); const childSessions = childSession(call.callId, file); + const childStatus = status(details.data.status); + // Without a session file, as on replay, the child's answer is the tool result. + const answer = + !file && childStatus !== "running" ? extractTextFromToolResult(call.result)?.trim() : ""; return { detail, subagents: [ @@ -101,8 +106,17 @@ export const gotgenesPiSubagents: PiExtension = { title, description, toolCallId: call.callId, - status: status(details.data.status), + status: childStatus, }, + ...(answer + ? [ + { + type: "timeline" as const, + id: call.callId, + item: { type: "assistant_message" as const, text: answer }, + }, + ] + : []), ], childSessions, }; @@ -118,7 +132,8 @@ export const gotgenesPiSubagents: PiExtension = { const detail = { type: "sub_agent" as const, description: details.success ? details.data.description : undefined, - log: extractTextFromToolResult(call.result)?.trim() ?? "", + // COMPAT(subagent-log): remove after 2027-04-30. + log: "", }; if (call.status === "running" || !details.success) return { detail }; const file = details.data.transcriptPath; diff --git a/packages/server/src/server/agent/providers/pi/extensions/index.test.ts b/packages/server/src/server/agent/providers/pi/extensions/index.test.ts index 0bf32a9f2f..d374c1a02d 100644 --- a/packages/server/src/server/agent/providers/pi/extensions/index.test.ts +++ b/packages/server/src/server/agent/providers/pi/extensions/index.test.ts @@ -210,7 +210,7 @@ describe("Pi extension host", () => { type: "sub_agent", subAgentType: "scout", description: "Inspect files", - log: "Found two files", + log: "", }, }), ); diff --git a/packages/server/src/server/agent/providers/pi/extensions/pi-subagents/index.test.ts b/packages/server/src/server/agent/providers/pi/extensions/pi-subagents/index.test.ts index 8e9db54047..740d66aadc 100644 --- a/packages/server/src/server/agent/providers/pi/extensions/pi-subagents/index.test.ts +++ b/packages/server/src/server/agent/providers/pi/extensions/pi-subagents/index.test.ts @@ -137,7 +137,7 @@ describe("pi-subagents adapter", () => { type: "sub_agent", subAgentType: "reviewer", description: "Review the Pi mapper change", - log: "The mapper change preserves provider status.", + log: "", }); }); diff --git a/packages/server/src/server/agent/providers/pi/extensions/pi-subagents/index.ts b/packages/server/src/server/agent/providers/pi/extensions/pi-subagents/index.ts index 64e814af3f..058171e8df 100644 --- a/packages/server/src/server/agent/providers/pi/extensions/pi-subagents/index.ts +++ b/packages/server/src/server/agent/providers/pi/extensions/pi-subagents/index.ts @@ -131,7 +131,8 @@ export const piSubagents: PiExtension = { type: "sub_agent" as const, subAgentType: args.data.agent, description: args.data.task, - log: extractTextFromToolResult(call.result)?.trim() ?? "", + // COMPAT(subagent-log): remove after 2027-04-30. + log: "", }; const base = { type: "upsert" as const, diff --git a/packages/server/src/server/agent/providers/pi/extensions/subagent-fixture-test.ts b/packages/server/src/server/agent/providers/pi/extensions/subagent-fixture-test.ts index 8a9ca61d08..96ba771594 100644 --- a/packages/server/src/server/agent/providers/pi/extensions/subagent-fixture-test.ts +++ b/packages/server/src/server/agent/providers/pi/extensions/subagent-fixture-test.ts @@ -54,8 +54,6 @@ export async function verifySubagentFixture( try { await session.startTurn("Delegate work"); for (const event of fixture.events) pi.latestSession().emit(event); - const immediate = live.filter((event) => event.type === "provider_subagent"); - expect(immediate.some((event) => event.event.type === "timeline")).toBe(false); pi.latestSession().finishTurn(); const replay: AgentStreamEvent[] = []; for await (const event of streamPiHistory("pi", fixture.messages)) replay.push(event); diff --git a/packages/server/src/server/agent/providers/pi/extensions/tintinweb-pi-subagents/index.test.ts b/packages/server/src/server/agent/providers/pi/extensions/tintinweb-pi-subagents/index.test.ts index ad666bb4d3..60f3b12869 100644 --- a/packages/server/src/server/agent/providers/pi/extensions/tintinweb-pi-subagents/index.test.ts +++ b/packages/server/src/server/agent/providers/pi/extensions/tintinweb-pi-subagents/index.test.ts @@ -36,12 +36,17 @@ describe("@tintinweb/pi-subagents adapter", () => { }); expect(mapping?.subagents).toEqual([ expect.objectContaining({ id: "call-1", status: "completed" }), + { + type: "timeline", + id: "call-1", + item: { type: "assistant_message", text: "Wrapped up (turn limit)" }, + }, ]); expect(mapping?.detail).toEqual({ type: "sub_agent", subAgentType: "Explore", description: "Inspect", - log: "Wrapped up (turn limit)", + log: "", }); }); test("maps captured foreground lifecycle live and on replay", async () => { @@ -53,6 +58,18 @@ describe("@tintinweb/pi-subagents adapter", () => { .filter((event) => event.event.type === "upsert") .map((event) => (event.event.type === "upsert" ? event.event.status : null)), ).toEqual(["running", "completed"]); + expect( + events.flatMap((event) => (event.event.type === "timeline" ? [event.event] : [])), + ).toEqual([ + { + type: "timeline", + id: "call_458926", + item: { + type: "assistant_message", + text: "Agent completed in 6.6s (1 tool uses, 18.8k token).\n\nThe workspace directory `/tmp/paseo-pi-extension-phase3/workspace` is empty (no files or hidden dotfiles).", + }, + }, + ]); }); test("uses a structured notification to complete a background child", async () => { const source = readSubagentFixture(new URL("./fixtures/background.json", import.meta.url)); @@ -147,7 +164,7 @@ describe("@tintinweb/pi-subagents adapter", () => { expect(mapping?.detail).toEqual({ type: "sub_agent", description: undefined, - log: "Wrapped up (turn limit)", + log: "", }); }, ); diff --git a/packages/server/src/server/agent/providers/pi/extensions/tintinweb-pi-subagents/index.ts b/packages/server/src/server/agent/providers/pi/extensions/tintinweb-pi-subagents/index.ts index 56b5935172..6858dec8be 100644 --- a/packages/server/src/server/agent/providers/pi/extensions/tintinweb-pi-subagents/index.ts +++ b/packages/server/src/server/agent/providers/pi/extensions/tintinweb-pi-subagents/index.ts @@ -57,7 +57,8 @@ export const tintinwebPiSubagents: PiExtension = { type: "sub_agent" as const, subAgentType: title, description, - log: extractTextFromToolResult(call.result)?.trim() ?? "", + // COMPAT(subagent-log): remove after 2027-04-30. + log: "", }; if (call.status === "running") return { @@ -84,6 +85,10 @@ export const tintinwebPiSubagents: PiExtension = { const file = outputFileFromToolResult(call.result); const childSessions = file && !readSessions.has(file) ? [{ id: call.callId, file }] : []; if (file) readSessions.add(file); + const childStatus = status(details.data.status); + // A foreground child has no session file; its answer is the tool result. + const answer = + !file && childStatus !== "running" ? extractTextFromToolResult(call.result)?.trim() : ""; return { detail, subagents: [ @@ -93,8 +98,17 @@ export const tintinwebPiSubagents: PiExtension = { title, description, toolCallId: call.callId, - status: status(details.data.status), + status: childStatus, }, + ...(answer + ? [ + { + type: "timeline" as const, + id: call.callId, + item: { type: "assistant_message" as const, text: answer }, + }, + ] + : []), ], childSessions, }; @@ -110,7 +124,8 @@ export const tintinwebPiSubagents: PiExtension = { const detail = { type: "sub_agent" as const, description: details.success ? details.data.description : undefined, - log: extractTextFromToolResult(call.result)?.trim() ?? "", + // COMPAT(subagent-log): remove after 2027-04-30. + log: "", }; if (call.status === "running" || !details.success) return { detail }; return { diff --git a/packages/server/src/server/daemon-e2e/background-subagent-action-log.real.e2e.test.ts b/packages/server/src/server/daemon-e2e/background-subagent-action-log.real.e2e.test.ts index 7eba32f22a..557f8360de 100644 --- a/packages/server/src/server/daemon-e2e/background-subagent-action-log.real.e2e.test.ts +++ b/packages/server/src/server/daemon-e2e/background-subagent-action-log.real.e2e.test.ts @@ -1,6 +1,3 @@ -import { execFile } from "node:child_process"; -import { promisify } from "node:util"; -import { fileURLToPath } from "node:url"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; @@ -10,7 +7,7 @@ import { ClaudeAgentClient } from "../agent/providers/claude/agent.js"; import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js"; import { DaemonClient } from "../test-utils/daemon-client.js"; -test("background cards retain child actions after the parent finishes (#6253)", async () => { +test("background children keep their actions after the parent finishes (#6253)", async () => { const cwd = mkdtempSync(path.join(tmpdir(), "paseo-background-card-")); const logger = pino({ level: "silent" }); const daemon = await createTestPaseoDaemon({ @@ -62,22 +59,6 @@ test("background cards retain child actions after the parent finishes (#6253)", limit: 0, projection: "projected", }); - const { stdout } = await promisify(execFile)( - process.execPath, - [ - "--conditions=source", - "--import", - "tsx", - fileURLToPath(new URL("../../../../cli/src/index.ts", import.meta.url)), - "--host", - `127.0.0.1:${daemon.port}`, - "logs", - agent.id, - ], - { env: { ...process.env, PASEO_HOME: daemon.paseoHome }, timeout: 30_000 }, - ); - expect(stdout).toContain("[Bash] ls -1"); - expect(stdout).toContain("[Bash] pwd"); expect( atFinish.entries.filter( (row) => row.item.type === "tool_call" && row.item.detail?.type === "sub_agent", @@ -94,9 +75,6 @@ test("background cards retain child actions after the parent finishes (#6253)", ), ).toBe(true); } - for (const card of cards) { - expect(card.detail?.type === "sub_agent" ? card.detail.log : "").toContain("[Bash]"); - } } finally { await client.close(); await daemon.close(); From a4f696620b5d248598a882b1a78d82ec5038c74b Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Fri, 30 Oct 2026 21:27:27 +0700 Subject: [PATCH 130/173] Keep big agents loadable by bounding every timeline item (#8274) * fix(server): bound every timeline item so one fetch cannot close the socket A timeline page is one WebSocket message. Only three tool-call fields were capped, so MCP results, file contents, errors and merged assistant rows could make a 20-entry or even a 1-entry fetch pass the outbound high-water mark. limitAgentTimelineItemContent is now one budgeted walk over any item: 64 KiB for tool calls, 256 KiB for other items. Over budget, the largest strings are cut to a shared length with a visible marker and oversized data URLs become a marker. Fetches also apply it to merged assistant and reasoning rows. * fix(server): keep short strings whole and typed arrays valid when limiting items Strings up to 1 KiB are never cut, so a tool call keeps its callId and an item limits to the same result twice. Arrays drop trailing elements without inserting a marker element, which typed arrays such as todo items would reject. --- docs/timeline-sync.md | 14 +- .../agent-manager-stream-coalescing.test.ts | 29 +-- .../src/server/agent/agent-manager.test.ts | 12 +- .../agent/agent-timeline-content.test.ts | 133 ++++++++++--- .../server/agent/agent-timeline-content.ts | 179 ++++++++++++------ .../server/agent/agent-timeline-store.test.ts | 14 ++ .../src/server/agent/agent-timeline-store.ts | 8 +- .../agent/provider-subagents/store.test.ts | 2 +- .../claude/agent.sub-agent-replay.test.ts | 7 +- .../daemon-e2e/oversized-timeline.e2e.test.ts | 46 +++++ 10 files changed, 328 insertions(+), 116 deletions(-) create mode 100644 packages/server/src/server/daemon-e2e/oversized-timeline.e2e.test.ts diff --git a/docs/timeline-sync.md b/docs/timeline-sync.md index f205d78924..3d6af249bf 100644 --- a/docs/timeline-sync.md +++ b/docs/timeline-sync.md @@ -21,10 +21,16 @@ The invariants are: > agent establishes the daemon's current tail in one complete-turn request, with older history reachable > through backward pagination. -Tool output is bounded before it enters either delivery path. Canonical shell tool output is sliced -to 64 KiB, and the same bounded item is used for runtime timeline rows and live stream events. -Provider history hydration applies the same rule so reopening an agent cannot restore an oversized -tool payload. +Every item is bounded before it enters either delivery path, because a timeline page is one +WebSocket message and the daemon closes a socket whose outbound buffer passes 64 MiB. Tool calls get +64 KiB and other items 256 KiB. Over budget, the largest strings are cut to a shared length with a +`…[truncated 12.3 MB]` marker, and an oversized `data:` URL is replaced by the marker. Strings up +to 1 KiB stay whole, so ids and paths survive. Arrays drop their trailing elements without a marker +element, so typed arrays still match the wire schema. Limiting an item twice gives the same item. The +budget does not bound wide objects or multi-byte text. The same +bounded item is used for runtime timeline rows and live stream events. Provider history hydration +applies the same rule so reopening an agent cannot restore an oversized payload. Fetches apply it +again to assistant and reasoning rows the projection merges from many chunks. ## Presence is not delivery diff --git a/packages/server/src/server/agent/agent-manager-stream-coalescing.test.ts b/packages/server/src/server/agent/agent-manager-stream-coalescing.test.ts index 9dc194fa11..c423264869 100644 --- a/packages/server/src/server/agent/agent-manager-stream-coalescing.test.ts +++ b/packages/server/src/server/agent/agent-manager-stream-coalescing.test.ts @@ -6,6 +6,7 @@ import { afterEach, describe, expect, test, vi } from "vitest"; import { createTestLogger } from "../../test-utils/test-logger.js"; import { AgentManager, type AgentManagerEvent } from "./agent-manager.js"; import { AGENT_STREAM_COALESCE_DEFAULT_WINDOW_MS } from "./agent-stream-coalescer.js"; +import { limitAgentTimelineItemContent } from "./agent-timeline-content.js"; import type { AgentTimelineRow } from "./agent-timeline-store-types.js"; import { projectTimelineRows } from "./timeline-projection.js"; import type { @@ -31,7 +32,6 @@ import type { const COALESCE_WINDOW_MS = AGENT_STREAM_COALESCE_DEFAULT_WINDOW_MS; const BEFORE_COALESCE_WINDOW_MS = Math.max(COALESCE_WINDOW_MS - 1, 0); -const TOOL_CALL_CONTENT_MAX_LENGTH = 64 * 1024; const TEST_CAPABILITIES: AgentCapabilityFlags = { supportsStreaming: false, @@ -400,10 +400,7 @@ describe("target coalesced behavior", () => { try { const { agentId, session } = await createManagedSession(harness); const output = `${"a".repeat(512 * 1024)}${"z".repeat(512 * 1024)}`; - const expectedItem = toolCall({ - status: "completed", - output: "a".repeat(TOOL_CALL_CONTENT_MAX_LENGTH), - }); + const expectedItem = limitAgentTimelineItemContent(toolCall({ status: "completed", output })); session.pushEvent(timelineEvent(toolCall({ status: "completed", output }))); await waitForSessionEventQueue(); @@ -425,10 +422,7 @@ describe("target coalesced behavior", () => { try { const { agentId } = await createManagedSession(harness); const output = `${"a".repeat(512 * 1024)}${"z".repeat(512 * 1024)}`; - const expectedItem = toolCall({ - status: "completed", - output: "a".repeat(TOOL_CALL_CONTENT_MAX_LENGTH), - }); + const expectedItem = limitAgentTimelineItemContent(toolCall({ status: "completed", output })); await harness.manager.appendTimelineItem(agentId, toolCall({ status: "completed", output })); @@ -449,10 +443,7 @@ describe("target coalesced behavior", () => { try { const { agentId, session } = await createManagedSession(harness); const output = `${"a".repeat(512 * 1024)}${"z".repeat(512 * 1024)}`; - const expectedItem = toolCall({ - status: "completed", - output: "a".repeat(TOOL_CALL_CONTENT_MAX_LENGTH), - }); + const expectedItem = limitAgentTimelineItemContent(toolCall({ status: "completed", output })); session.setHistory([timelineEvent(toolCall({ status: "completed", output }))]); await harness.manager.hydrateTimelineFromProvider(agentId, { force: true }); @@ -470,10 +461,7 @@ describe("target coalesced behavior", () => { try { const { agentId } = await createManagedSession(harness); const output = `${"a".repeat(512 * 1024)}${"z".repeat(512 * 1024)}`; - const expectedItem = toolCall({ - status: "completed", - output: "a".repeat(TOOL_CALL_CONTENT_MAX_LENGTH), - }); + const expectedItem = limitAgentTimelineItemContent(toolCall({ status: "completed", output })); await harness.manager.emitLiveTimelineItem( agentId, @@ -495,10 +483,9 @@ describe("target coalesced behavior", () => { try { const { agentId, session } = await createManagedSession(harness); const content = `${"a".repeat(512 * 1024)}${"z".repeat(512 * 1024)}`; - const expectedItem = toolCall({ - status: "failed", - error: { content: "a".repeat(TOOL_CALL_CONTENT_MAX_LENGTH) }, - }); + const expectedItem = limitAgentTimelineItemContent( + toolCall({ status: "failed", error: { content } }), + ); session.pushEvent(timelineEvent(toolCall({ status: "failed", error: { content } }))); await waitForSessionEventQueue(); diff --git a/packages/server/src/server/agent/agent-manager.test.ts b/packages/server/src/server/agent/agent-manager.test.ts index 902fd79ebc..4b3fb5ea46 100644 --- a/packages/server/src/server/agent/agent-manager.test.ts +++ b/packages/server/src/server/agent/agent-manager.test.ts @@ -21,6 +21,7 @@ import { } from "./agent-manager.js"; import { AgentStorage } from "./agent-storage.js"; import { InMemoryAgentTimelineStore } from "./agent-timeline-store.js"; +import { limitAgentTimelineItemContent } from "./agent-timeline-content.js"; import { toAgentPayload } from "./agent-projections.js"; import { projectTimelineRows } from "./timeline-projection.js"; import { getOpenAgentTabLabel, PARENT_AGENT_ID_LABEL } from "@getpaseo/protocol/agent-labels"; @@ -4592,7 +4593,7 @@ test("importProviderSession imports the selected session without listing and pub expect(manager.getTimeline(imported.id)).toEqual([ { type: "user_message", text: "Trace provider imports" }, { type: "assistant_message", text: "Done" }, - { + limitAgentTimelineItemContent({ type: "tool_call", callId: "large-shell-result", name: "shell", @@ -4601,10 +4602,10 @@ test("importProviderSession imports the selected session without listing and pub detail: { type: "shell", command: "print output", - output: "x".repeat(64 * 1024), + output: "x".repeat(1024 * 1024), exitCode: 0, }, - }, + }), ]); expect(manager.listProviderSubagents(imported.id)).toEqual([ expect.objectContaining({ id: "thread-child", title: "Imported child", status: "completed" }), @@ -11957,10 +11958,7 @@ test("commits startup notices once on create and after restored history", async exitCode: 0, }, }; - const limitedToolOutput: AgentTimelineItem = { - ...toolOutput, - detail: { type: "shell", command: "print output", output: "x".repeat(64 * 1024), exitCode: 0 }, - }; + const limitedToolOutput = limitAgentTimelineItemContent(toolOutput); class NotifyingSession extends TestAgentSession { readonly initialTimeline = [{ item: notice, timestamp: "2026-09-22T00:00:00.000Z" }]; override async *streamHistory(): AsyncGenerator { diff --git a/packages/server/src/server/agent/agent-timeline-content.test.ts b/packages/server/src/server/agent/agent-timeline-content.test.ts index 1ccb78c67a..1461d0aeef 100644 --- a/packages/server/src/server/agent/agent-timeline-content.test.ts +++ b/packages/server/src/server/agent/agent-timeline-content.test.ts @@ -1,12 +1,30 @@ +import { AgentTimelineItemPayloadSchema } from "@getpaseo/protocol/messages"; import { describe, expect, test } from "vitest"; +import type { AgentTimelineItem } from "./agent-sdk-types.js"; import { limitAgentTimelineItemContent } from "./agent-timeline-content.js"; +function serializedBytes(item: AgentTimelineItem): number { + return Buffer.byteLength(JSON.stringify(item), "utf8"); +} + describe("agent timeline content", () => { + test("returns an item within budget unchanged", () => { + const item: AgentTimelineItem = { + type: "tool_call", + callId: "small", + name: "Bash", + status: "completed", + error: null, + detail: { type: "shell", command: "ls", output: "x".repeat(60 * 1024) }, + }; + expect(limitAgentTimelineItemContent(item)).toBe(item); + }); + test.each([false, true])( - "preserves the exact UTF-16 prefix for oversized shell output (failed=%s)", + "cuts oversized shell output and keeps short fields whole (failed=%s)", (failed) => { - const text = "x".repeat(64 * 1024 - 1) + "🙂"; + const text = "x".repeat(1024 * 1024) + "🙂"; const item = limitAgentTimelineItemContent({ type: "tool_call", callId: "large-shell", @@ -15,45 +33,116 @@ describe("agent timeline content", () => { detail: { type: "shell", command: "echo large", output: text }, error: failed ? { content: text } : null, }); - expect(item).toEqual({ - type: "tool_call", + expect(item).toMatchObject({ callId: "large-shell", name: "Bash", - status: failed ? "failed" : "completed", - detail: { type: "shell", command: "echo large", output: text.slice(0, 64 * 1024) }, - error: failed ? { content: text.slice(0, 64 * 1024) } : null, + detail: { type: "shell", command: "echo large" }, }); + if (item.type !== "tool_call" || item.detail.type !== "shell") throw new Error("shape"); + expect(item.detail.output).toMatch(/^x+…\[truncated \d{3}\.\d KB\]$/); + expect(serializedBytes(item)).toBeLessThanOrEqual(64 * 1024); }, ); - test("marks truncated plain-text tool content within the content budget", () => { - const oversizedInput = "x".repeat(64 * 1024 + 1); - + test("replaces an oversized data URL in an unknown tool result with a marker", () => { + const url = `data:image/jpeg;base64,${"A".repeat(14 * 1024 * 1024)}`; const item = limitAgentTimelineItemContent({ type: "tool_call", - callId: "terminal-session-4242", - name: "terminal", + callId: "screenshot", + name: "node_repl.js", status: "completed", error: null, detail: { - type: "plain_text", - text: oversizedInput, - icon: "square_terminal", + type: "unknown", + input: { index: 1 }, + output: { content: [{ type: "image", url }], note: "captured" }, }, }); - - expect(limitAgentTimelineItemContent(item)).toEqual(item); expect(item).toEqual({ type: "tool_call", - callId: "terminal-session-4242", - name: "terminal", + callId: "screenshot", + name: "node_repl.js", status: "completed", error: null, detail: { - type: "plain_text", - text: "x".repeat(64 * 1024 - "\n\n[Content truncated]".length) + "\n\n[Content truncated]", - icon: "square_terminal", + type: "unknown", + input: { index: 1 }, + output: { content: [{ type: "image", url: "…[truncated 14.0 MB]" }], note: "captured" }, }, }); }); + + test("gives non-tool items a 256 KiB budget", () => { + const text = "a".repeat(10 * 1024 * 1024); + const item = limitAgentTimelineItemContent({ type: "assistant_message", text }); + if (item.type !== "assistant_message") throw new Error("shape"); + expect(item.text).toMatch(/^a+…\[truncated 9\.\d MB\]$/); + expect(item.text.length).toBeGreaterThan(200 * 1024); + expect(serializedBytes(item)).toBeLessThanOrEqual(256 * 1024); + }); + + test("bounds an item whose structure alone exceeds the budget", () => { + const item = limitAgentTimelineItemContent({ + type: "tool_call", + callId: "many", + name: "query", + status: "completed", + error: null, + detail: { type: "unknown", input: null, output: Array.from({ length: 1_000_000 }, () => 1) }, + }); + if (item.type !== "tool_call" || item.detail.type !== "unknown") throw new Error("shape"); + const output = item.detail.output as unknown[]; + expect(output.length).toBeLessThan(1_000_000); + expect(output.every((value) => value === 1)).toBe(true); + expect(serializedBytes(item)).toBeLessThanOrEqual(64 * 1024); + }); + + test("keeps short strings whole and limits idempotently when an item has many strings", () => { + const callId = "3f2b8c1e-9a4d-4e6f-8b2a-1c3d5e7f9a0b"; + const item = limitAgentTimelineItemContent({ + type: "tool_call", + callId, + name: "mcp__search__files", + status: "completed", + error: null, + detail: { + type: "unknown", + input: { query: "useWorkspaceSomethingVeryDescriptive" }, + output: Array.from( + { length: 10_000 }, + (_, index) => `${String(index).padStart(5, "0")}${"p".repeat(28)}`, + ), + }, + }); + if (item.type !== "tool_call" || item.detail.type !== "unknown") throw new Error("shape"); + expect(item.callId).toBe(callId); + expect(item.detail.input).toEqual({ query: "useWorkspaceSomethingVeryDescriptive" }); + const output = item.detail.output as string[]; + expect(output.length).toBeLessThan(10_000); + expect(output.every((path) => path.length === 33)).toBe(true); + expect(serializedBytes(item)).toBeLessThanOrEqual(64 * 1024); + expect(limitAgentTimelineItemContent(item)).toBe(item); + }); + + test("keeps a long typed array valid against the wire schema", () => { + const item = limitAgentTimelineItemContent({ + type: "todo", + items: Array.from({ length: 20_000 }, (_, index) => ({ + text: `Task ${index}`, + completed: false, + })), + }); + if (item.type !== "todo") throw new Error("shape"); + expect(item.items.length).toBeLessThan(20_000); + expect(AgentTimelineItemPayloadSchema.safeParse(item).success).toBe(true); + expect(serializedBytes(item)).toBeLessThanOrEqual(256 * 1024); + }); + + test("is stable on an already-limited item", () => { + const item = limitAgentTimelineItemContent({ + type: "reasoning", + text: "r".repeat(1024 * 1024), + }); + expect(limitAgentTimelineItemContent(item)).toBe(item); + }); }); diff --git a/packages/server/src/server/agent/agent-timeline-content.ts b/packages/server/src/server/agent/agent-timeline-content.ts index 003239b283..5117073e14 100644 --- a/packages/server/src/server/agent/agent-timeline-content.ts +++ b/packages/server/src/server/agent/agent-timeline-content.ts @@ -1,9 +1,19 @@ import type { AgentTimelineItem } from "./agent-sdk-types.js"; import type { JsonValue } from "@getpaseo/protocol/agent-types"; -const TOOL_CALL_CONTENT_MAX_LENGTH = 64 * 1024; export const PLUGIN_TIMELINE_DATA_MAX_BYTES = 64 * 1024; +// One timeline fetch sends its entries in one WebSocket message, so every item must stay small. +// Budgets count UTF-16 units plus a fixed cost per node; neither is exact JSON bytes. They bound +// long strings and long arrays, not wide objects (every entry is kept) or multi-byte text. +const TOOL_CALL_BUDGET = 64 * 1024; +const ITEM_BUDGET = 256 * 1024; +const NODE_COST = 8; +const MARKER_COST = 32; +// Ids, names, paths and queries stay whole, so an item keeps its identity across passes. +const SHORT_STRING = 1024; +const MAX_DEPTH = 64; + export function assertPluginTimelineDataSize(data: JsonValue): void { const serializedBytes = Buffer.byteLength(JSON.stringify(data), "utf8"); if (serializedBytes > PLUGIN_TIMELINE_DATA_MAX_BYTES) { @@ -17,66 +27,119 @@ function retainTextPrefix(text: string, length: number): string { return Buffer.from(text.slice(0, length), "utf16le").toString("utf16le"); } -function limitFailedShellError(item: AgentTimelineItem): AgentTimelineItem { - if ( - item.type !== "tool_call" || - item.detail.type !== "shell" || - item.status !== "failed" || - typeof item.error !== "object" || - item.error === null || - !("content" in item.error) || - typeof item.error.content !== "string" || - item.error.content.length <= TOOL_CALL_CONTENT_MAX_LENGTH - ) { - return item; - } - return { - ...item, - error: { - ...item.error, - content: retainTextPrefix(item.error.content, TOOL_CALL_CONTENT_MAX_LENGTH), - }, - }; +function formatSize(units: number): string { + if (units < 1024) return `${units} B`; + if (units < 1024 * 1024) return `${(units / 1024).toFixed(1)} KB`; + return `${(units / (1024 * 1024)).toFixed(1)} MB`; } -function limitPlainText(item: AgentTimelineItem): AgentTimelineItem { - if ( - item.type !== "tool_call" || - item.detail.type !== "plain_text" || - typeof item.detail.text !== "string" || - item.detail.text.length <= TOOL_CALL_CONTENT_MAX_LENGTH - ) { - return item; - } - const notice = "\n\n[Content truncated]"; - return { - ...item, - detail: { - ...item.detail, - text: - retainTextPrefix(item.detail.text, TOOL_CALL_CONTENT_MAX_LENGTH - notice.length) + notice, - }, - }; +function truncatedMarker(units: number): string { + return `…[truncated ${formatSize(units)}]`; } +interface ItemSize { + nodeCost: number; + stringLengths: number[]; + tooDeep: boolean; +} + +function measure(value: unknown, depth: number, size: ItemSize): void { + size.nodeCost += NODE_COST; + if (depth > MAX_DEPTH) { + size.tooDeep = true; + } else if (typeof value === "string") { + size.stringLengths.push(value.length); + } else if (Array.isArray(value)) { + for (const element of value) measure(element, depth + 1, size); + } else if (typeof value === "object" && value !== null) { + for (const [key, child] of Object.entries(value)) { + size.nodeCost += key.length; + measure(child, depth + 1, size); + } + } +} + +/** The largest per-string length that keeps all strings, once cut, within `available`. */ +function findStringCap(lengths: readonly number[], available: number): number { + let low = 0; + let high = 0; + for (const length of lengths) high = Math.max(high, length); + while (low < high) { + const cap = Math.ceil((low + high) / 2); + let total = 0; + for (const length of lengths) total += Math.min(length, cap); + if (total <= available) low = cap; + else high = cap - 1; + } + return low; +} + +interface CutState { + stringCap: number; + remaining: number; +} + +function cutString(text: string, cap: number): string { + if (text.length <= cap) return text; + // A partial data URL is useless to every reader, so drop it whole. + if (text.startsWith("data:")) return truncatedMarker(text.length); + return retainTextPrefix(text, cap) + truncatedMarker(text.length - cap); +} + +function cut(value: unknown, depth: number, state: CutState): unknown { + state.remaining -= NODE_COST; + if (depth > MAX_DEPTH) return "…[truncated]"; + if (typeof value === "string") { + const text = cutString(value, state.stringCap); + state.remaining -= text.length; + return text; + } + if (Array.isArray(value)) { + let changed = false; + const output: unknown[] = []; + for (const element of value) { + const remainingBefore = state.remaining; + const next = cut(element, depth + 1, state); + if (state.remaining < 0) { + // Drop this and later elements. A marker element would break typed arrays. + state.remaining = remainingBefore; + changed = true; + break; + } + changed ||= next !== element; + output.push(next); + } + return changed ? output : value; + } + if (typeof value === "object" && value !== null) { + let changed = false; + const output: Record = {}; + for (const [key, child] of Object.entries(value)) { + state.remaining -= key.length; + const next = cut(child, depth + 1, state); + changed ||= next !== child; + output[key] = next; + } + return changed ? output : value; + } + return value; +} + +/** Returns the item itself when it fits its budget; otherwise a copy with its largest strings cut. */ export function limitAgentTimelineItemContent(item: AgentTimelineItem): AgentTimelineItem { - item = limitFailedShellError(item); - item = limitPlainText(item); - if ( - item.type !== "tool_call" || - item.detail.type !== "shell" || - typeof item.detail.output !== "string" - ) { - return item; - } - if (item.detail.output.length <= TOOL_CALL_CONTENT_MAX_LENGTH) { - return item; - } - return { - ...item, - detail: { - ...item.detail, - output: retainTextPrefix(item.detail.output, TOOL_CALL_CONTENT_MAX_LENGTH), - }, - }; + const budget = item.type === "tool_call" ? TOOL_CALL_BUDGET : ITEM_BUDGET; + const size: ItemSize = { nodeCost: 0, stringLengths: [], tooDeep: false }; + measure(item, 0, size); + let stringTotal = 0; + for (const length of size.stringLengths) stringTotal += length; + if (!size.tooDeep && size.nodeCost + stringTotal <= budget) return item; + + // Strings get what structure leaves, but at least half the budget, less a margin for JSON + // escaping. Arrays drop the elements that do not fit, which bounds items whose short strings + // or structure alone are too big. + const markerCost = + MARKER_COST * size.stringLengths.filter((length) => length > SHORT_STRING).length; + const available = (budget * 15) / 16 - Math.min(size.nodeCost, budget / 2) - markerCost; + const stringCap = Math.max(SHORT_STRING, findStringCap(size.stringLengths, available)); + return cut(item, 0, { stringCap, remaining: budget }) as AgentTimelineItem; } diff --git a/packages/server/src/server/agent/agent-timeline-store.test.ts b/packages/server/src/server/agent/agent-timeline-store.test.ts index 5d3c836e65..9ec4df4d55 100644 --- a/packages/server/src/server/agent/agent-timeline-store.test.ts +++ b/packages/server/src/server/agent/agent-timeline-store.test.ts @@ -181,6 +181,20 @@ describe("projected timeline retention", () => { }, ]); }); + + it("serves a merged assistant message within the item budget", () => { + const store = new InMemoryAgentTimelineStore(); + store.initialize("agent", { epoch: "e" }); + const chunk = "a".repeat(200 * 1024); + for (let index = 0; index < 10; index++) { + store.append("agent", { type: "assistant_message", messageId: "m", text: chunk }); + } + const [row] = store.fetch("agent", { limit: 1 }).rows; + expect(row).toMatchObject({ seqStart: 1, seqEnd: 10 }); + expect(row.item).toMatchObject({ type: "assistant_message", messageId: "m" }); + expect(Buffer.byteLength(JSON.stringify(row.item))).toBeLessThanOrEqual(256 * 1024); + expect(store.getLastAssistantMessage("agent")).toHaveLength(10 * chunk.length); + }); }); describe("projected sequence ownership", () => { diff --git a/packages/server/src/server/agent/agent-timeline-store.ts b/packages/server/src/server/agent/agent-timeline-store.ts index 49b5013fd4..4c3b9c5c3a 100644 --- a/packages/server/src/server/agent/agent-timeline-store.ts +++ b/packages/server/src/server/agent/agent-timeline-store.ts @@ -1,5 +1,6 @@ import { randomUUID } from "node:crypto"; import { TimelineProjection, type ProjectedTimelineRow } from "./timeline-projection.js"; +import { limitAgentTimelineItemContent } from "./agent-timeline-content.js"; import type { AgentTimelineItem } from "./agent-sdk-types.js"; import type { AgentTimelineFetchOptions, @@ -120,7 +121,12 @@ export class InMemoryAgentTimelineStore { hasNewer: page.hasNewer, startSeq: page.startSeq, endSeq: page.endSeq, - rows: page.entries.map((entry) => Object.assign({ seq: entry.seqEnd }, entry)), + // Stored rows are already within budget; this bounds assistant and reasoning merges. + rows: page.entries.map((entry) => + Object.assign({ seq: entry.seqEnd }, entry, { + item: limitAgentTimelineItemContent(entry.item), + }), + ), }; } diff --git a/packages/server/src/server/agent/provider-subagents/store.test.ts b/packages/server/src/server/agent/provider-subagents/store.test.ts index dc71c0f5c6..5c2ca55174 100644 --- a/packages/server/src/server/agent/provider-subagents/store.test.ts +++ b/packages/server/src/server/agent/provider-subagents/store.test.ts @@ -80,7 +80,7 @@ describe("ProviderSubagentStore", () => { const [row] = subagents.fetchTimeline("parent-a", "child-1").rows; expect(row?.item).toMatchObject({ type: "tool_call", - detail: { type: "shell", output: "x".repeat(64 * 1024) }, + detail: { type: "shell", output: expect.stringMatching(/^x+…\[truncated \d+\.\d KB\]$/) }, }); }); diff --git a/packages/server/src/server/agent/providers/claude/agent.sub-agent-replay.test.ts b/packages/server/src/server/agent/providers/claude/agent.sub-agent-replay.test.ts index 9fc82d6de8..4728767307 100644 --- a/packages/server/src/server/agent/providers/claude/agent.sub-agent-replay.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.sub-agent-replay.test.ts @@ -737,7 +737,7 @@ describe("ClaudeAgentSession persisted subagent replay", () => { ); }, 120_000); - test("limits retained child shell output to the timeline's existing content limit", async () => { + test("limits retained child shell output to the timeline item budget", async () => { const output = "x".repeat(128 * 1024); writeSession({ parentLines: [taskToolUse(), taskToolResult()], @@ -782,7 +782,10 @@ describe("ClaudeAgentSession persisted subagent replay", () => { type: "timeline", id: TOOL_USE_ID, item: expect.objectContaining({ - detail: expect.objectContaining({ type: "shell", output: output.slice(0, 64 * 1024) }), + detail: expect.objectContaining({ + type: "shell", + output: expect.stringMatching(/^x+…\[truncated \d+\.\d KB\]$/), + }), }), }), ]); diff --git a/packages/server/src/server/daemon-e2e/oversized-timeline.e2e.test.ts b/packages/server/src/server/daemon-e2e/oversized-timeline.e2e.test.ts new file mode 100644 index 0000000000..bc78db2eab --- /dev/null +++ b/packages/server/src/server/daemon-e2e/oversized-timeline.e2e.test.ts @@ -0,0 +1,46 @@ +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { expect, test } from "vitest"; +import { createDaemonTestContext } from "../test-utils/index.js"; + +// #2220: a timeline page is one WebSocket message, so a few huge entries used to close the socket. +test.each([40, 0])( + "fetching image-heavy history with limit %i keeps the direct connection usable", + async (limit) => { + const ctx = await createDaemonTestContext(); + const cwd = mkdtempSync(path.join(tmpdir(), "oversized-timeline-")); + try { + const agent = await ctx.client.createAgent({ provider: "codex", cwd }); + const imageUrl = `data:image/jpeg;base64,${"A".repeat(14 * 1024 * 1024)}`; + for (let index = 0; index < 5; index += 1) { + await ctx.daemon.daemon.agentManager.appendTimelineItem(agent.id, { + type: "tool_call", + callId: `screenshot-${index}`, + name: "node_repl.js", + status: "completed", + error: null, + detail: { + type: "unknown", + input: { index }, + output: { _meta: { "codex/toolSurface": { screenshot: { url: imageUrl } } } }, + }, + }); + } + + const page = await ctx.client.fetchAgentTimeline(agent.id, { direction: "tail", limit }); + const screenshots = page.entries.filter((entry) => entry.item.type === "tool_call"); + expect(screenshots).toHaveLength(5); + for (const entry of screenshots) { + expect(Buffer.byteLength(JSON.stringify(entry.item))).toBeLessThanOrEqual(64 * 1024); + } + + const next = await ctx.client.fetchAgentTimeline(agent.id, { direction: "tail", limit: 1 }); + expect(next.entries).toHaveLength(1); + } finally { + await ctx.cleanup(); + rmSync(cwd, { recursive: true, force: true }); + } + }, + 60_000, +); From 186c132151ff99889db0572534bd400acdf2cc5b Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sat, 31 Oct 2026 00:33:29 +0000 Subject: [PATCH 131/173] test(server): isolate the reconciliation responsiveness budget (#8317) * test(server): isolate the reconciliation responsiveness budget Measure the cold reconciliation in compiled plain Node so unrelated runner callbacks cannot consume its 20ms budget. Retain real filesystem admission and every archival assertion, with unrelated CPU work in the parent as a regression check. * test(server): initialize probe filesystem support before measurement --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../reconciliation-registries.ts | 117 ++++++++++ .../reconciliation-responsiveness.ts | 75 ++++++ .../workspace-reconciliation-service.test.ts | 214 ++++-------------- 3 files changed, 242 insertions(+), 164 deletions(-) create mode 100644 packages/server/src/server/test-fixtures/reconciliation-registries.ts create mode 100644 packages/server/src/server/test-fixtures/reconciliation-responsiveness.ts diff --git a/packages/server/src/server/test-fixtures/reconciliation-registries.ts b/packages/server/src/server/test-fixtures/reconciliation-registries.ts new file mode 100644 index 0000000000..2d020ec23f --- /dev/null +++ b/packages/server/src/server/test-fixtures/reconciliation-registries.ts @@ -0,0 +1,117 @@ +import type pino from "pino"; +import { createPersistedProjectRecord } from "../workspace-registry.js"; +import type { + PersistedProjectRecord, + PersistedWorkspaceRecord, + ProjectRegistry, + WorkspaceRegistry, +} from "../workspace-registry.js"; + +export function createTestRegistries() { + let archiveGate: { + started: ReturnType; + release: ReturnType; + } | null = null; + const holdNextArchive = () => { + archiveGate = { started: deferred(), release: deferred() }; + return archiveGate; + }; + const projects = new Map(); + const workspaces = new Map(); + + const projectRegistry: ProjectRegistry = { + initialize: async () => {}, + existsOnDisk: async () => true, + list: async () => Array.from(projects.values()), + get: async (id: string) => projects.get(id) ?? null, + getOrCreateActiveByRoot: async (input) => { + const existing = Array.from(projects.values()).find( + (project) => !project.archivedAt && project.rootPath === input.rootPath, + ); + if (existing) return existing; + const record = createPersistedProjectRecord({ + projectId: `prj_${projects.size}`, + rootPath: input.rootPath, + kind: input.kind, + displayName: input.displayName, + createdAt: input.timestamp, + updatedAt: input.timestamp, + }); + projects.set(record.projectId, record); + return record; + }, + update: async (id, updater) => { + const current = projects.get(id); + if (!current) return null; + const updated = updater(current); + projects.set(id, updated); + return updated; + }, + upsert: async (record: PersistedProjectRecord) => { + projects.set(record.projectId, record); + }, + archive: async (id: string, archivedAt: string) => { + const existing = projects.get(id); + if (existing) { + projects.set(id, { ...existing, archivedAt, updatedAt: archivedAt }); + } + }, + remove: async (id: string) => { + projects.delete(id); + }, + }; + + const workspaceRegistry: WorkspaceRegistry = { + initialize: async () => {}, + existsOnDisk: async () => true, + list: async () => Array.from(workspaces.values()), + get: async (id: string) => workspaces.get(id) ?? null, + update: async (id, updater) => { + const existing = workspaces.get(id); + if (!existing) return null; + const updated = updater(existing); + workspaces.set(id, updated); + return updated; + }, + upsert: async (record: PersistedWorkspaceRecord) => { + workspaces.set(record.workspaceId, record); + }, + archive: async (id: string, archivedAt: string) => { + const gate = archiveGate; + archiveGate = null; + if (gate) { + gate.started.resolve(); + await gate.release.promise; + } + const existing = workspaces.get(id); + if (!existing || existing.archivedAt) return false; + workspaces.set(id, { ...existing, archivedAt, updatedAt: archivedAt }); + return true; + }, + remove: async (id: string) => { + workspaces.delete(id); + }, + }; + + return { projects, workspaces, projectRegistry, workspaceRegistry, holdNextArchive }; +} + +export function createTestLogger() { + const logger = { + child: () => logger, + trace: () => undefined, + debug: () => undefined, + info: () => undefined, + warn: () => undefined, + error: () => undefined, + }; + return logger as unknown as pino.Logger; +} + +export function deferred(): { promise: Promise; resolve(): void } { + let resolve!: () => void; + const promise = new Promise((accept) => { + resolve = accept; + }); + return { promise, resolve }; +} diff --git a/packages/server/src/server/test-fixtures/reconciliation-responsiveness.ts b/packages/server/src/server/test-fixtures/reconciliation-responsiveness.ts new file mode 100644 index 0000000000..7df5414d2d --- /dev/null +++ b/packages/server/src/server/test-fixtures/reconciliation-responsiveness.ts @@ -0,0 +1,75 @@ +import path from "node:path"; +import { stat } from "node:fs/promises"; +import { setImmediate as nextTurn } from "node:timers/promises"; +import { measureMainThreadWork } from "../../test-utils/main-thread-work.js"; +import { createTestRegistries, createTestLogger } from "./reconciliation-registries.js"; +import { + createPersistedProjectRecord, + createPersistedWorkspaceRecord, +} from "../workspace-registry.js"; +import { WorkspaceReconciliationService } from "../workspace-reconciliation-service.js"; +import { deriveProjectKey } from "../project-key.js"; + +const rootPath = process.argv[2]; +if (!rootPath) throw new Error("Project root is required"); +const timestamp = "2025-01-01T00:00:00.000Z"; +const { projects, workspaces, projectRegistry, workspaceRegistry } = createTestRegistries(); +projects.set( + "p1", + createPersistedProjectRecord({ + projectId: "p1", + rootPath, + projectKey: deriveProjectKey({ + rootPath, + remoteUrl: null, + worktreeRoot: null, + mainRepoRoot: null, + }), + kind: "non_git", + displayName: "project", + createdAt: timestamp, + updatedAt: timestamp, + }), +); +for (let i = 0; i < 20000; i++) { + const workspaceId = `w${i}`; + workspaces.set( + workspaceId, + createPersistedWorkspaceRecord({ + workspaceId, + projectId: "p1", + cwd: path.join(rootPath, workspaceId), + kind: "directory", + displayName: workspaceId, + createdAt: timestamp, + updatedAt: timestamp, + }), + ); +} +const service = new WorkspaceReconciliationService({ + projectRegistry, + workspaceRegistry, + logger: createTestLogger(), +}); + +// Compile before launch and measure in plain Node, outside the test runner's +// thread and TypeScript loader. Keep the first real reconciliation cold. +// Initialize async filesystem support using the bundle, leaving every project +// and workspace path untouched until the first reconciliation. +await stat(process.argv[1]); +await nextTurn(); +try { + const measured = await measureMainThreadWork("workspace reconciliation main-thread work", () => + service.runOnce(), + ); + process.stdout.write( + JSON.stringify({ + blockingMs: measured.blockingMs, + filesystemRequests: measured.filesystemRequests, + changesApplied: measured.result.changesApplied.length, + allArchived: [...workspaces.values()].every((workspace) => workspace.archivedAt !== null), + }), + ); +} finally { + service.dispose(); +} diff --git a/packages/server/src/server/workspace-reconciliation-service.test.ts b/packages/server/src/server/workspace-reconciliation-service.test.ts index 0e9f5a2c2d..7ef187d16e 100644 --- a/packages/server/src/server/workspace-reconciliation-service.test.ts +++ b/packages/server/src/server/workspace-reconciliation-service.test.ts @@ -1,27 +1,45 @@ -import { measureMainThreadWork } from "../test-utils/main-thread-work.js"; -import { execFileSync } from "node:child_process"; +import { execFile, execFileSync } from "node:child_process"; +import { promisify } from "node:util"; +import { fileURLToPath } from "node:url"; +import { build } from "esbuild"; +import { + createTestRegistries, + createTestLogger, + deferred, +} from "./test-fixtures/reconciliation-registries.js"; import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import type { ProjectCheckoutLitePayload } from "@getpaseo/protocol/messages"; import type pino from "pino"; -import { afterEach, describe, expect, test } from "vitest"; +import { afterAll, beforeAll, afterEach, describe, expect, test } from "vitest"; import { createPersistedProjectRecord, createPersistedWorkspaceRecord, } from "./workspace-registry.js"; -import type { - PersistedProjectRecord, - PersistedWorkspaceRecord, - ProjectRegistry, - WorkspaceRegistry, -} from "./workspace-registry.js"; import { type ReconciliationChange, WorkspaceReconciliationService, } from "./workspace-reconciliation-service.js"; import { deriveProjectKey } from "./project-key.js"; +let probeDirectory: string; +let probePath: string; +beforeAll(async () => { + probeDirectory = mkdtempSync(path.join(tmpdir(), "reconciliation-probe-")); + probePath = path.join(probeDirectory, "reconciliation.mjs"); + await build({ + entryPoints: [ + fileURLToPath(new URL("./test-fixtures/reconciliation-responsiveness.ts", import.meta.url)), + ], + outfile: probePath, + bundle: true, + platform: "node", + format: "esm", + }); +}); +afterAll(() => rmSync(probeDirectory, { recursive: true, force: true })); + function canonicalLocalProjectKey(rootPath: string): string { return deriveProjectKey({ rootPath, @@ -31,107 +49,6 @@ function canonicalLocalProjectKey(rootPath: string): string { }); } -function createTestRegistries() { - let archiveGate: { - started: ReturnType; - release: ReturnType; - } | null = null; - const holdNextArchive = () => { - archiveGate = { started: deferred(), release: deferred() }; - return archiveGate; - }; - const projects = new Map(); - const workspaces = new Map(); - - const projectRegistry: ProjectRegistry = { - initialize: async () => {}, - existsOnDisk: async () => true, - list: async () => Array.from(projects.values()), - get: async (id: string) => projects.get(id) ?? null, - getOrCreateActiveByRoot: async (input) => { - const existing = Array.from(projects.values()).find( - (project) => !project.archivedAt && project.rootPath === input.rootPath, - ); - if (existing) return existing; - const record = createPersistedProjectRecord({ - projectId: `prj_${projects.size}`, - rootPath: input.rootPath, - kind: input.kind, - displayName: input.displayName, - createdAt: input.timestamp, - updatedAt: input.timestamp, - }); - projects.set(record.projectId, record); - return record; - }, - update: async (id, updater) => { - const current = projects.get(id); - if (!current) return null; - const updated = updater(current); - projects.set(id, updated); - return updated; - }, - upsert: async (record: PersistedProjectRecord) => { - projects.set(record.projectId, record); - }, - archive: async (id: string, archivedAt: string) => { - const existing = projects.get(id); - if (existing) { - projects.set(id, { ...existing, archivedAt, updatedAt: archivedAt }); - } - }, - remove: async (id: string) => { - projects.delete(id); - }, - }; - - const workspaceRegistry: WorkspaceRegistry = { - initialize: async () => {}, - existsOnDisk: async () => true, - list: async () => Array.from(workspaces.values()), - get: async (id: string) => workspaces.get(id) ?? null, - update: async (id, updater) => { - const existing = workspaces.get(id); - if (!existing) return null; - const updated = updater(existing); - workspaces.set(id, updated); - return updated; - }, - upsert: async (record: PersistedWorkspaceRecord) => { - workspaces.set(record.workspaceId, record); - }, - archive: async (id: string, archivedAt: string) => { - const gate = archiveGate; - archiveGate = null; - if (gate) { - gate.started.resolve(); - await gate.release.promise; - } - const existing = workspaces.get(id); - if (!existing || existing.archivedAt) return false; - workspaces.set(id, { ...existing, archivedAt, updatedAt: archivedAt }); - return true; - }, - remove: async (id: string) => { - workspaces.delete(id); - }, - }; - - return { projects, workspaces, projectRegistry, workspaceRegistry, holdNextArchive }; -} - -function createTestLogger() { - const logger = { - child: () => logger, - trace: () => undefined, - debug: () => undefined, - info: () => undefined, - warn: () => undefined, - error: () => undefined, - }; - return logger as unknown as pino.Logger; -} - interface CapturedLogRecord { message: string; payload: unknown; @@ -210,14 +127,6 @@ function createCheckout( }; } -function deferred(): { promise: Promise; resolve(): void } { - let resolve!: () => void; - const promise = new Promise((accept) => { - resolve = accept; - }); - return { promise, resolve }; -} - class TestCheckouts { readonly reads: string[] = []; private readonly checkouts = new Map(); @@ -626,53 +535,30 @@ describe("WorkspaceReconciliationService", () => { test("keeps the event loop responsive while inspecting 20000 real workspace paths", async () => { const rootPath = realpathSync(mkdtempSync(path.join(tmpdir(), "reconcile-many-"))); tempDirs.push(rootPath); - const { projects, workspaces, projectRegistry, workspaceRegistry } = createTestRegistries(); - projects.set( - "p1", - createPersistedProjectRecord({ - projectId: "p1", - rootPath, - projectKey: canonicalLocalProjectKey(rootPath), - kind: "non_git", - displayName: "project", - createdAt: timestamp, - updatedAt: timestamp, - }), - ); - for (let i = 0; i < 20000; i++) { - const workspaceId = `w${i}`; - workspaces.set( - workspaceId, - createPersistedWorkspaceRecord({ - workspaceId, - projectId: "p1", - cwd: path.join(rootPath, workspaceId), - kind: "directory", - displayName: workspaceId, - createdAt: timestamp, - updatedAt: timestamp, - }), - ); - } - const service = new WorkspaceReconciliationService({ - projectRegistry, - workspaceRegistry, - logger: createTestLogger(), + // Unrelated runner work must not consume the reconciliation budget. + const unrelatedWork = new Promise((resolve) => { + setImmediate(() => { + const cpu = Reflect.get(process, "threadCpuUsage") as typeof process.cpuUsage; + const start = cpu(); + while (cpu(start).user + cpu(start).system < 80_000) {} + resolve(); + }); }); - try { - const { result, blockingMs, filesystemRequests } = await measureMainThreadWork( - "workspace reconciliation main-thread work", - () => service.runOnce(), - ); - expect(blockingMs).toBeLessThan(20); - expect(filesystemRequests).toBe(20001); - expect(result.changesApplied).toHaveLength(20000); - expect([...workspaces.values()].every((workspace) => workspace.archivedAt !== null)).toBe( - true, - ); - } finally { - service.dispose(); - } + const { stdout, stderr } = await promisify(execFile)(process.execPath, [probePath, rootPath], { + timeout: 25_000, + }); + process.stderr.write(stderr); + const { changesApplied, blockingMs, filesystemRequests, allArchived } = JSON.parse(stdout) as { + changesApplied: number; + blockingMs: number; + filesystemRequests: number; + allArchived: boolean; + }; + await unrelatedWork; + expect(blockingMs).toBeLessThan(20); + expect(filesystemRequests).toBe(20001); + expect(changesApplied).toBe(20000); + expect(allArchived).toBe(true); }, 30000); test("preserves workspace archival that lands during boot reconciliation", async () => { From 0be49c06206578b57be6d04b1ea781d6a71d007b Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sat, 31 Oct 2026 09:26:24 +0700 Subject: [PATCH 132/173] feat(transport): keep large messages intact across relay connections (#8302) Negotiate shared binary chunk framing below application messages and routing, with bounded logical assembly and paced writes that respect encrypted relay limits. Preserve legacy admission, reconnect state, sibling route isolation, and native single-frame upload behavior. --- docs/protocol-compatibility.md | 27 ++ .../e2e/browser/composer-diff-stat.spec.ts | 3 +- .../new-workspace-composer-draft.spec.ts | 3 + .../src/utils/test-daemon-connection.test.ts | 19 + .../app/src/utils/test-daemon-connection.ts | 2 + packages/client/src/connection/index.ts | 1 + .../src/daemon-client-relay-e2ee-transport.ts | 17 +- .../src/daemon-client-transport-types.ts | 17 +- .../src/daemon-client-transport.test.ts | 15 + .../src/daemon-client-websocket-transport.ts | 20 + packages/client/src/daemon-client.test.ts | 451 +++++++++++++++--- packages/client/src/daemon-client.ts | 165 ++++--- packages/client/src/hosts/index.ts | 7 +- packages/client/src/node/connector.test.ts | 16 +- packages/client/src/node/index.ts | 8 +- .../protocol/src/binary-frames/host-route.ts | 5 + .../protocol/src/chunked-transport.test.ts | 392 +++++++++++++++ packages/protocol/src/chunked-transport.ts | 214 +++++++++ packages/protocol/src/client-capabilities.ts | 1 + packages/protocol/src/messages.ts | 1 + .../server/connected-hosts/hosts.e2e.test.ts | 77 +++ .../src/server/connected-hosts/index.ts | 9 +- .../server/src/server/connected-hosts/link.ts | 7 +- .../daemon-e2e/relay-transport.e2e.test.ts | 166 ++++--- .../server/daemon-e2e/terminal.e2e.test.ts | 55 +++ ...websocket-server.file-transfer.e2e.test.ts | 102 +++- .../server/src/server/websocket-server.ts | 128 +++-- .../websocket/encrypted-relay-socket.test.ts | 71 +++ .../websocket/encrypted-relay-socket.ts | 4 + .../server/websocket/physical-socket.test.ts | 93 ++++ 30 files changed, 1843 insertions(+), 253 deletions(-) create mode 100644 packages/protocol/src/chunked-transport.test.ts create mode 100644 packages/protocol/src/chunked-transport.ts diff --git a/docs/protocol-compatibility.md b/docs/protocol-compatibility.md index f7244e67ba..74650255a5 100644 --- a/docs/protocol-compatibility.md +++ b/docs/protocol-compatibility.md @@ -52,6 +52,33 @@ On capable daemons, connecting creates no timeline or event demand. Client subsc release it on unsubscribe, and restore it after reconnect. Raw message observers inspect traffic without requesting streams. Application caches and which agents are visible remain caller-owned. +## Binary chunking + +`binary_chunking_v1` in hello and optional `server_info.features.binaryChunkingV1` +negotiate connection-scoped framing. Application serializers and routed envelopes use +the same boundary. Small messages and handshakes keep their existing representation. +Older peers retain existing frame limits. + +The reserved binary opcode `0x31` is followed by version `1`, original kind +(`0` text, `1` binary), and START/END flag bits `0`/`1`. Remaining bytes are an +unchanged slice. There is no total length or chunk count; a future receiver can +consume slices incrementally. Today the receiver buffers up to the existing +100 MiB logical limit and decodes UTF-8 only after END. Transfers cannot interleave. +Disconnect clears partial state and negotiation. + +The lower transport supplies its plaintext frame budget, including encryption +overhead. The sender waits for drain between chunks while ordinary messages keep +the existing delivery path. Slow-client protections count messages queued behind +an active transfer as well as bytes already in the socket. +The framing module never selects an encryption construction. + +Native uploads retain the platform's existing queue limits. React Native's +WebSocket does not report its queued bytes, so the client cannot wait for native +drain. Android's installed OkHttp transport closes when a send would put more +than 16 MiB in its queue. The native transport disables outbound chunking, including +on routed channels, and retains its existing single-frame admission errors. +Inbound chunking remains enabled; daemon-to-native responses use the daemon's paced writes. + ## Owned observations `owned_subscriptions` and `server_info.features.ownedSubscriptions` negotiate the source-owned diff --git a/packages/app/e2e/browser/composer-diff-stat.spec.ts b/packages/app/e2e/browser/composer-diff-stat.spec.ts index 9b80222432..959567f58b 100644 --- a/packages/app/e2e/browser/composer-diff-stat.spec.ts +++ b/packages/app/e2e/browser/composer-diff-stat.spec.ts @@ -18,7 +18,7 @@ function visibleMainPane(page: Page) { } function composerChangesPill(page: Page) { - return page.getByTestId("composer-diff-stat-pill"); + return page.getByRole("button", { name: "Open Changes tab", exact: true }); } async function revealComposerChangesInExplorer(page: Page) { @@ -498,6 +498,7 @@ test.describe("send review feedback", () => { test("only open tabs in this workspace appear in compact and wide recipient menus", async ({ page, }) => { + test.setTimeout(120000); const workspace = await seedChangedAgent("review-feedback-multiple-"); const other = await seedChangedAgent("review-feedback-other-"); try { diff --git a/packages/app/e2e/browser/new-workspace-composer-draft.spec.ts b/packages/app/e2e/browser/new-workspace-composer-draft.spec.ts index 906efcfb42..01fd4638eb 100644 --- a/packages/app/e2e/browser/new-workspace-composer-draft.spec.ts +++ b/packages/app/e2e/browser/new-workspace-composer-draft.spec.ts @@ -1,3 +1,4 @@ +import { chooseModel, startWithoutRememberedModel } from "../support/helpers/model-memory"; import { composerLocator, enterComposerFullscreen, @@ -97,6 +98,7 @@ test.describe("New workspace composer draft", () => { const project = await seedWorkspace({ repoPrefix: "new-workspace-submitted-draft-" }); try { + await startWithoutRememberedModel(page); await gotoAppShell(page); await waitForSidebarHydration(page); await openNewWorkspaceComposer(page, { @@ -104,6 +106,7 @@ test.describe("New workspace composer draft", () => { projectDisplayName: project.projectDisplayName, }); + await chooseModel(page, "mock", "Ten second stream"); const composer = page.getByRole("textbox", { name: "Message agent..." }); const createButton = page.getByTestId("workspace-create-submit"); await expect(composer).toBeEditable({ timeout: 30_000 }); diff --git a/packages/app/src/utils/test-daemon-connection.test.ts b/packages/app/src/utils/test-daemon-connection.test.ts index f528065437..29382b5c89 100644 --- a/packages/app/src/utils/test-daemon-connection.test.ts +++ b/packages/app/src/utils/test-daemon-connection.test.ts @@ -76,6 +76,25 @@ describe("test-daemon-connection connectToDaemon", () => { probe = new FakeDaemonProbe(); }); + it.each([ + { id: "direct:lan:6767", type: "directTcp" as const, endpoint: "lan:6767" }, + { + id: "relay:test", + type: "relay" as const, + relayEndpoint: "relay.paseo.sh:443", + daemonPublicKeyB64: "pubkey", + }, + ])("adoptable $type probe clients use the app WebSocket factory", async (connection) => { + const { connectToDaemon } = await import("./test-daemon-connection"); + const { createAppWebSocketFactory } = await import("@/runtime/websocket-factory"); + const result = await connectToDaemon(connection, { serverId: "srv_probe_test" }, probe.deps); + try { + expect(result.client.config.webSocketFactory).toBe(createAppWebSocketFactory()); + } finally { + await result.client.close(); + } + }); + it("reuses the app clientId for direct connections", async () => { const { connectToDaemon } = await import("./test-daemon-connection"); const first = await connectToDaemon( diff --git a/packages/app/src/utils/test-daemon-connection.ts b/packages/app/src/utils/test-daemon-connection.ts index d292c67001..1d1605af62 100644 --- a/packages/app/src/utils/test-daemon-connection.ts +++ b/packages/app/src/utils/test-daemon-connection.ts @@ -6,6 +6,7 @@ import { } from "@getpaseo/client/internal/daemon-client"; import type { DaemonClientConfig } from "@getpaseo/client/internal/daemon-client"; import type { HostConnection } from "@/types/host-connection"; +import { createAppWebSocketFactory } from "@/runtime/websocket-factory"; import { getOrCreateClientId } from "./client-id"; import { resolveAppVersion } from "./app-version"; import { @@ -156,6 +157,7 @@ export async function buildClientConfig( clientType: "mobile" as const, appVersion: deps.resolveAppVersion() ?? undefined, suppressSendErrors: true, + webSocketFactory: createAppWebSocketFactory(), reconnect: { enabled: false }, ...resolveConnectionCredentials(connection, options), ...(options.capabilities ? { capabilities: options.capabilities } : {}), diff --git a/packages/client/src/connection/index.ts b/packages/client/src/connection/index.ts index eda2fec26b..1ad4b34dee 100644 --- a/packages/client/src/connection/index.ts +++ b/packages/client/src/connection/index.ts @@ -125,6 +125,7 @@ export class ConnectionSubscriptions extends OwnedSubscriptions { // Protocol support belongs to the installed client. Only browser hosting needs // a resource supplied by the caller. Keep this exhaustive as the protocol evolves. export const DEFAULT_CLIENT_CAPABILITIES = { + [CLIENT_CAPS.binaryChunkingV1]: true, [CLIENT_CAPS.helloRejection]: true, [CLIENT_CAPS.ownedSubscriptions]: true, [CLIENT_CAPS.allProviders]: true, diff --git a/packages/client/src/daemon-client-relay-e2ee-transport.ts b/packages/client/src/daemon-client-relay-e2ee-transport.ts index 258c0aa9b5..0faecdcb5e 100644 --- a/packages/client/src/daemon-client-relay-e2ee-transport.ts +++ b/packages/client/src/daemon-client-relay-e2ee-transport.ts @@ -1,3 +1,4 @@ +import { maxSecuredPlaintextByteLength } from "@getpaseo/relay"; import { MAX_RELAY_WEBSOCKET_MESSAGE_BYTES } from "@getpaseo/protocol/websocket-message-limit"; import { openClientSecureChannel, @@ -155,18 +156,15 @@ export function createEncryptedTransport( const relayTransport: RelayTransport = { send: (data) => { if (typeof data === "string") { - base.send(data); - return; + return base.send(data); } if (ArrayBuffer.isView(data)) { - base.send(normalizeTransportPayload(data)); - return; + return base.send(normalizeTransportPayload(data)); } if (data instanceof ArrayBuffer) { - base.send(data); - return; + return base.send(data); } - base.send(String(data)); + return base.send(String(data)); }, // The channel decides the close code. Report it now: a socket close event // arrives asynchronously, and the consumer must not act on an earlier @@ -226,6 +224,8 @@ export function createEncryptedTransport( }); return { + supportsDrain: base.supportsDrain, + maxFrameBytes: maxSecuredPlaintextByteLength(MAX_RELAY_WEBSOCKET_MESSAGE_BYTES), send: (data) => { if (!channel) { throw new Error("Encrypted channel not ready"); @@ -239,8 +239,9 @@ export function createEncryptedTransport( // Encryption and its transport handoff are synchronous up to send's first await. // Reject capacity failures here so a routed sender loses only its own channel. assertOutboundCapacity(wireBytes); - void channel.send(payload).catch((error) => { + return channel.send(payload).catch((error) => { emitError(error); + throw error; }); }, close: (code?: number, reason?: string) => { diff --git a/packages/client/src/daemon-client-transport-types.ts b/packages/client/src/daemon-client-transport-types.ts index ddcb57246b..64f84cf8c1 100644 --- a/packages/client/src/daemon-client-transport-types.ts +++ b/packages/client/src/daemon-client-transport-types.ts @@ -1,5 +1,8 @@ export interface DaemonTransport { - send: (data: string | Uint8Array | ArrayBuffer) => void; + /** False when the underlying socket cannot report write drain. */ + supportsDrain?: boolean; + maxFrameBytes?: number; + send: (data: string | Uint8Array | ArrayBuffer) => void | Promise; close: (code?: number, reason?: string) => void; onMessage: (handler: (data: unknown, isBinary: boolean) => void) => () => void; onOpen: (handler: () => void) => () => void; @@ -13,12 +16,16 @@ export type DaemonTransportFactory = (options: { protocols?: string[]; }) => DaemonTransport; -export type WebSocketFactory = ( - url: string, - options?: { headers?: Record; protocols?: string[] }, -) => WebSocketLike; +export interface WebSocketFactory { + ( + url: string, + options?: { headers?: Record; protocols?: string[] }, + ): WebSocketLike; + supportsDrain?: boolean; +} export interface WebSocketLike { + bufferedAmount?: number; readyState: number; send: (data: string | Uint8Array | ArrayBuffer) => void; close: (code?: number, reason?: string) => void; diff --git a/packages/client/src/daemon-client-transport.test.ts b/packages/client/src/daemon-client-transport.test.ts index 963a8b541c..c95c534129 100644 --- a/packages/client/src/daemon-client-transport.test.ts +++ b/packages/client/src/daemon-client-transport.test.ts @@ -175,3 +175,18 @@ describe("daemon-client transport helpers", () => { expect(decodeMessageData(bytes)).toBe("hello"); }); }); + +test("native drain capability survives WebSocket and encryption wrappers", async () => { + const { nativeWebSocketFactory } = await import("./daemon-client-websocket-transport.js"); + expect(nativeWebSocketFactory.supportsDrain).toBe(false); + const factory = Object.assign(() => ({ readyState: 1, send() {}, close() {} }), { + supportsDrain: false, + }); + const base = createWebSocketTransportFactory(factory)({ url: "ws://test" }); + expect(base.supportsDrain).toBe(false); + const encrypted = createEncryptedTransport(base, { + daemonPublicKeyB64: "unused-key", + logger: { warn() {} }, + }); + expect(encrypted.supportsDrain).toBe(false); +}); diff --git a/packages/client/src/daemon-client-websocket-transport.ts b/packages/client/src/daemon-client-websocket-transport.ts index f5734b4b51..c7ec87555d 100644 --- a/packages/client/src/daemon-client-websocket-transport.ts +++ b/packages/client/src/daemon-client-websocket-transport.ts @@ -39,6 +39,9 @@ export function nativeWebSocketFactory( return new (getGlobalWebSocket())(url, options?.protocols, { headers: options?.headers }); } +// React Native leaves bufferedAmount at zero, including while native output is queued. +nativeWebSocketFactory.supportsDrain = false; + export function createWebSocketTransportFactory(factory: WebSocketFactory): DaemonTransportFactory { return ({ url, headers, protocols }) => { const ws = factory(url, { headers, protocols }); @@ -50,11 +53,28 @@ export function createWebSocketTransportFactory(factory: WebSocketFactory): Daem } } return { + supportsDrain: factory.supportsDrain !== false, send: (data) => { if (typeof ws.readyState === "number" && ws.readyState !== 1) { throw new Error(`WebSocket not open (readyState=${ws.readyState})`); } ws.send(data); + if ((ws.bufferedAmount ?? 0) > 1024 * 1024) { + return new Promise((resolve, reject) => { + const drain = () => { + if (ws.readyState !== 1) { + reject(new Error("WebSocket closed while draining")); + return; + } + if ((ws.bufferedAmount ?? 0) <= 1024 * 1024) { + resolve(); + return; + } + setTimeout(drain, 10); + }; + drain(); + }); + } }, close: (code?: number, reason?: string) => { // Node's `ws` may emit an `error` when a connecting socket is closed before the diff --git a/packages/client/src/daemon-client.test.ts b/packages/client/src/daemon-client.test.ts index 112113caf6..6ef72a0e1a 100644 --- a/packages/client/src/daemon-client.test.ts +++ b/packages/client/src/daemon-client.test.ts @@ -1094,6 +1094,7 @@ test("advertises client capabilities in hello", async () => { provider_snapshot_references: true, explicit_event_subscriptions: true, owned_subscriptions: true, + binary_chunking_v1: true, compact_provider_snapshots: true, custom_mode_icons: true, project_updates: true, @@ -6817,91 +6818,102 @@ test("drops legacy agent_stream tool_call payloads and logs validation warning", expect(logger.warn).toHaveBeenCalled(); }); -test("parses canonical fetch_agent_timeline_response payloads without crashing", async () => { - const logger = createMockLogger(); - const mock = createMockTransport(); +test.each([false, true])( + "parses canonical timeline responses with chunking=%s", + async (chunked) => { + const logger = createMockLogger(); + const mock = createMockTransport(); - const client = new DaemonClient({ - url: "ws://test", - clientId: "clsk_unit_test", - logger, - reconnect: { enabled: false }, - transportFactory: () => mock.transport, - }); - clients.push(client); + const client = new DaemonClient({ + url: "ws://test", + clientId: "clsk_unit_test", + logger, + reconnect: { enabled: false }, + transportFactory: () => mock.transport, + }); + clients.push(client); - const connectPromise = client.connect(); - mock.triggerOpen(); - await connectPromise; + const connectPromise = client.connect(); + mock.triggerOpen({ features: { ownedSubscriptions: true, binaryChunkingV1: chunked } }); + await connectPromise; - const received: unknown[] = []; - const unsubscribe = client.on("fetch_agent_timeline_response", (msg) => { - received.push(msg); - }); + const received: unknown[] = []; + const unsubscribe = client.on("fetch_agent_timeline_response", (msg) => { + received.push(msg); + }); - mock.triggerMessage( - wrapSessionMessage({ - type: "fetch_agent_timeline_response", + const command = chunked ? "x".repeat(50 * 1024 * 1024) : "pwd"; + const { ChunkedTransport } = await import("@getpaseo/protocol/chunked-transport"); + const sender = new ChunkedTransport({ + frameBytes: 24 * 1024 * 1024, + send: (frame) => mock.triggerMessage(frame), + deliver: () => {}, + }); + sender.enabled = chunked; + await sender.send( + wrapSessionMessage({ + type: "fetch_agent_timeline_response", + payload: { + requestId: "req-1", + agentId: "agent_cli", + agent: null, + direction: "tail", + projection: "projected", + epoch: "epoch-1", + reset: false, + staleCursor: false, + gap: false, + window: { minSeq: 1, maxSeq: 1, nextSeq: 2 }, + startCursor: { epoch: "epoch-1", seq: 1 }, + endCursor: { epoch: "epoch-1", seq: 1 }, + hasOlder: false, + hasNewer: false, + entries: [ + { + timestamp: "2026-02-08T20:20:00.000Z", + provider: "codex", + seqStart: 1, + seqEnd: 1, + sourceSeqRanges: [{ startSeq: 1, endSeq: 1 }], + collapsed: [], + item: { + type: "tool_call", + callId: "call_cli_snapshot", + name: "shell", + status: "running", + detail: { + type: "shell", + command, + }, + error: null, + }, + }, + ], + error: null, + }, + }), + ); + + unsubscribe(); + + expect(received).toHaveLength(1); + expect(received[0]).toMatchObject({ payload: { - requestId: "req-1", - agentId: "agent_cli", - agent: null, - direction: "tail", - projection: "projected", - epoch: "epoch-1", - reset: false, - staleCursor: false, - gap: false, - window: { minSeq: 1, maxSeq: 1, nextSeq: 2 }, - startCursor: { epoch: "epoch-1", seq: 1 }, - endCursor: { epoch: "epoch-1", seq: 1 }, - hasOlder: false, - hasNewer: false, entries: [ { - timestamp: "2026-02-08T20:20:00.000Z", - provider: "codex", - seqStart: 1, - seqEnd: 1, - sourceSeqRanges: [{ startSeq: 1, endSeq: 1 }], - collapsed: [], item: { type: "tool_call", - callId: "call_cli_snapshot", - name: "shell", status: "running", - detail: { - type: "shell", - command: "pwd", - }, error: null, + detail: { type: "shell", command }, }, }, ], - error: null, }, - }), - ); - - unsubscribe(); - - expect(received).toHaveLength(1); - expect(received[0]).toMatchObject({ - payload: { - entries: [ - { - item: { - type: "tool_call", - status: "running", - error: null, - detail: { type: "shell" }, - }, - }, - ], - }, - }); - expect(logger.warn).not.toHaveBeenCalled(); -}); + }); + expect(logger.warn).not.toHaveBeenCalled(); + }, +); test("rejects and logs a correlated response that violates the protocol schema", async () => { const mock = createMockTransport(); @@ -8471,3 +8483,302 @@ test("closes before admission when a protected-capable daemon is reached in lega expect(daemonReceived).toHaveLength(1); expect(JSON.parse(daemonReceived[0] as string)).toMatchObject({ type: "hello" }); }); + +test("uses the frame budget selected by an asynchronously opened transport", async () => { + const mock = createMockTransport(); + mock.transport.maxFrameBytes = 1024; + const client = new DaemonClient({ + url: "ws://test", + clientId: "dynamic-budget", + transportFactory: () => mock.transport, + reconnect: { enabled: false }, + }); + clients.push(client); + const connecting = client.connect(); + mock.transport.maxFrameBytes = 16; + mock.triggerOpen({ features: { binaryChunkingV1: true } }); + await connecting; + client.sendHostFrame("route", new Uint8Array(100)); + await vi.waitFor(() => expect(mock.sent.length).toBeGreaterThan(1)); + expect(mock.sent.every((frame) => typeof frame !== "string" && frame.byteLength <= 16)).toBe( + true, + ); +}); + +test.each([false, true])("routed sends wait for origin drain (binary=%s)", async (binary) => { + const mock = createMockTransport(); + let drain!: () => void; + let blocked = false; + const send = mock.transport.send; + mock.transport.send = (frame) => { + send(frame); + if (blocked) + return new Promise((resolve) => { + drain = resolve; + }); + }; + const client = new DaemonClient({ + url: "ws://test", + clientId: "routed-drain", + transportFactory: () => mock.transport, + reconnect: { enabled: false }, + }); + clients.push(client); + const connecting = client.connect(); + mock.triggerOpen({ features: { binaryChunkingV1: true } }); + await connecting; + blocked = true; + let finished = false; + const write = Promise.resolve( + client.sendHostFrame("route", binary ? new Uint8Array([1]) : "hello"), + ).then(() => { + finished = true; + return undefined; + }); + await Promise.resolve(); + expect(finished).toBe(false); + drain(); + await write; + expect(finished).toBe(true); +}); + +test("a queued admission failure rejects its RPC without closing the client", async () => { + const mock = createMockTransport(); + const send = mock.transport.send; + let block = false; + let drain!: () => void; + mock.transport.send = (frame) => { + if (!block) return send(frame); + if (typeof frame !== "string") + return new Promise((resolve) => { + drain = resolve; + }); + throw new Error("capacity"); + }; + const client = new DaemonClient({ + url: "ws://test", + clientId: "queued-admission", + transportFactory: () => mock.transport, + reconnect: { enabled: false }, + }); + clients.push(client); + const connecting = client.connect(); + mock.triggerOpen(); + await connecting; + block = true; + const first = client.sendHostFrame("route", new Uint8Array([1])); + const ping = client.ping({ timeoutMs: 1000 }); + void ping.catch(() => {}); + drain(); + await first; + await expect(ping).rejects.toThrow("capacity"); + expect(client.isConnected).toBe(true); +}); + +test("RPC deadlines remain active while a preceding frame waits for drain", async () => { + const mock = createMockTransport(); + const send = mock.transport.send; + let blocked = false; + let drain!: () => void; + mock.transport.send = (frame) => { + if (!blocked) return send(frame); + if (typeof frame !== "string") + return new Promise((resolve) => { + drain = resolve; + }); + }; + const client = new DaemonClient({ + url: "ws://test", + clientId: "drain-deadline", + transportFactory: () => mock.transport, + reconnect: { enabled: false }, + }); + clients.push(client); + const connecting = client.connect(); + mock.triggerOpen(); + await connecting; + blocked = true; + const first = client.sendHostFrame("route", new Uint8Array([1])); + try { + await expect(client.ping({ timeoutMs: 20 })).rejects.toThrow("Timeout waiting for message"); + expect(client.isConnected).toBe(true); + } finally { + drain(); + await first; + } +}); + +test.each([false, true])( + "event listener errors do not close the transport (chunked=%s)", + async (chunked) => { + const mock = createMockTransport(); + const closed = vi.fn(); + mock.transport.close = closed; + const client = new DaemonClient({ + url: "ws://test", + clientId: "listener-error", + transportFactory: () => mock.transport, + reconnect: { enabled: false }, + }); + clients.push(client); + const connecting = client.connect(); + mock.triggerOpen({ features: { binaryChunkingV1: chunked } }); + await connecting; + const unsubscribe = client.subscribe(() => { + throw new Error("listener failed"); + }); + const text = wrapSessionMessage({ + type: "agent_deleted", + payload: { agentId: "agent-test", requestId: "listener-test" }, + }); + const payload = new TextEncoder().encode(text); + const frame = chunked ? new Uint8Array([0x31, 1, 0, 3, ...payload]) : text; + expect(() => mock.triggerMessage(frame)).toThrow("listener failed"); + expect(closed).not.toHaveBeenCalled(); + unsubscribe(); + const events: string[] = []; + client.subscribe((event) => { + events.push(event.type); + }); + mock.triggerMessage(frame); + expect(events).toEqual(["agent_deleted"]); + await client.sendHostFrame("route", "still connected"); + expect(client.isConnected).toBe(true); + }, +); + +test("malformed chunk metadata still closes the client transport", async () => { + const mock = createMockTransport(); + const closed = vi.fn(); + mock.transport.close = closed; + const client = new DaemonClient({ + url: "ws://test", + clientId: "malformed-chunk", + transportFactory: () => mock.transport, + reconnect: { enabled: false }, + }); + clients.push(client); + const connecting = client.connect(); + mock.triggerOpen({ features: { binaryChunkingV1: true } }); + await connecting; + mock.triggerMessage(new Uint8Array([0x31, 2, 0, 3, 65])); + expect(closed).toHaveBeenCalledWith(4003, "Invalid chunked transport"); +}); + +test.each([FileTransferOpcode.FileBegin, FileTransferOpcode.FileChunk, FileTransferOpcode.FileEnd])( + "upload stops at a queued pre-write rejection (opcode=%s)", + async (opcode) => { + const mock = createMockTransport(); + const send = mock.transport.send; + let drain!: () => void; + let blocked = false; + const attempts: number[] = []; + mock.transport.send = (frame) => { + if (typeof frame !== "string") { + const decoded = decodeFileTransferFrame(assertUint8Array(frame)); + if (decoded) { + attempts.push(decoded.opcode); + if (decoded.opcode === opcode) throw new Error("upload capacity"); + } else if (blocked) + return new Promise((resolve) => { + drain = resolve; + }); + } + return send(frame); + }; + const client = new DaemonClient({ + url: "ws://test", + clientId: "upload-admission", + transportFactory: () => mock.transport, + reconnect: { enabled: false }, + }); + clients.push(client); + const connecting = client.connect(); + mock.triggerOpen(); + await connecting; + blocked = true; + const first = client.sendHostFrame("route", new Uint8Array([1])); + const upload = client.uploadFile({ + fileName: "file.bin", + mimeType: "application/octet-stream", + bytes: new Uint8Array([1, 2]), + chunkSize: 1, + }); + let rejected: unknown; + void upload.catch((error) => { + rejected = error; + }); + await new Promise((resolve) => setTimeout(resolve, 0)); + drain(); + await first; + await vi.waitFor(() => expect(rejected).toMatchObject({ message: "upload capacity" }), { + timeout: 500, + }); + expect(attempts.at(-1)).toBe(opcode); + expect(client.isConnected).toBe(true); + }, +); + +test.each(["latency", "dictation start", "dictation finish"])( + "queued control send rejection reaches its caller (%s)", + async (operation) => { + const mock = createMockTransport(); + const send = mock.transport.send; + let blocked = false; + let drain!: () => void; + mock.transport.send = (frame) => { + if (!blocked) return send(frame); + if (typeof frame !== "string") + return new Promise((resolve) => { + drain = resolve; + }); + throw new Error("control capacity"); + }; + const client = new DaemonClient({ + url: "ws://test", + clientId: "control-admission", + transportFactory: () => mock.transport, + reconnect: { enabled: false }, + }); + clients.push(client); + const connecting = client.connect(); + mock.triggerOpen(); + await connecting; + blocked = true; + const first = client.sendHostFrame("route", new Uint8Array([1])); + let result: Promise; + if (operation === "latency") result = client.measureLatency({ timeoutMs: 1000 }); + else if (operation === "dictation start") + result = client.startDictationStream("dictation", "pcm"); + else result = client.finishDictationStream("dictation", 0); + const rejected = expect(result).rejects.toThrow("control capacity"); + drain(); + await first; + await rejected; + expect(client.isConnected).toBe(true); + }, +); + +test("routed channels inherit an origin without drain support", async () => { + const { createHostChannelTransport } = await import("./hosts/index.js"); + const mock = createMockTransport(); + mock.transport.supportsDrain = false; + const client = new DaemonClient({ + url: "ws://test", + clientId: "unpaced-route", + transportFactory: () => mock.transport, + reconnect: { enabled: false }, + }); + clients.push(client); + const connecting = client.connect(); + mock.triggerOpen(); + await connecting; + const route = createHostChannelTransport( + client, + "srv_destination", + "scope", + "route", + )({ url: "ws://route" }); + expect(route.supportsDrain).toBe(false); + route.close(); +}); diff --git a/packages/client/src/daemon-client.ts b/packages/client/src/daemon-client.ts index d4b0f28a39..9152159f1c 100644 --- a/packages/client/src/daemon-client.ts +++ b/packages/client/src/daemon-client.ts @@ -1,3 +1,7 @@ +import { + ChunkedTransport, + ChunkedTransportProtocolError, +} from "@getpaseo/protocol/chunked-transport"; import { HOST_ROUTE_OPCODE, encodeHostRouteFrame, @@ -1266,7 +1270,7 @@ function toReasonCode(reason: string | null | undefined): string | null { } interface PendingSend { - send: () => void; + send: () => void | Promise; resolve: () => void; reject: (error: Error) => void; timeoutHandle: ReturnType; @@ -1366,6 +1370,7 @@ export class DaemonClient { failed: (error) => this.logger.error({ err: error }, "Subscription failed"), }); private transport: DaemonTransport | null = null; + private chunkedTransport: ChunkedTransport | null = null; private helloAuth: HelloAuth; private transportCleanup: Array<() => void> = []; private rawMessageListeners: Set<(message: SessionOutboundMessage) => void> = new Set(); @@ -1560,6 +1565,17 @@ export class DaemonClient { }); this.traceConnectionAttempt += 1; this.transport = transport; + this.chunkedTransport = new ChunkedTransport({ + get supportsDrain() { + return transport.supportsDrain; + }, + get frameBytes() { + return transport.maxFrameBytes ?? 32 * 1024 * 1024; + }, + send: (frame) => transport.send(frame), + onFailure: () => transport.close(4003, "Transport send failed"), + deliver: (frame) => this.handleTransportMessage(frame), + }); this.lastServerInfoMessage = null; this.authFailureReasonValue = null; @@ -1666,7 +1682,16 @@ export class DaemonClient { }); }), transport.onMessage((data) => { - if (this.transport === transport) this.handleTransportMessage(data); + if (this.transport !== transport) return; + const bytes = asUint8Array(data); + try { + if (typeof data === "string" || bytes) + this.chunkedTransport!.receive(typeof data === "string" ? data : bytes!); + else this.handleTransportMessage(data); + } catch (error) { + if (!(error instanceof ChunkedTransportProtocolError)) throw error; + transport.close(4003, "Invalid chunked transport"); + } }), ]; } catch (error) { @@ -1867,9 +1892,9 @@ export class DaemonClient { }) ).routeId; } - sendHostFrame(routeId: string, data: string | Uint8Array): void { + sendHostFrame(routeId: string, data: string | Uint8Array): Promise { if (typeof data === "string") { - this.sendSessionMessageStrict({ + return this.sendSessionMessageStrict({ type: "hosts.route.frame.request", routeId, data, @@ -1877,7 +1902,7 @@ export class DaemonClient { }); } else { if (!this.isConnected || !this.transport) throw this.unavailableError(); - this.sendTransportFrame(encodeHostRouteFrame(routeId, data)); + return this.sendTransportFrame(encodeHostRouteFrame(routeId, data)); } } private readonly hostFrameListeners = new Set<(frame: HostRouteFrame) => void>(); @@ -1935,6 +1960,11 @@ export class DaemonClient { // Message Subscription // ============================================================================ + /** Drain capability inherited by transports routed through this connection. */ + get supportsDrain(): boolean { + return this.transport?.supportsDrain !== false; + } + subscribe(handler: DaemonEventHandler): () => void { this.eventListeners.add(handler); return () => { @@ -2043,7 +2073,7 @@ export class DaemonClient { messageType: string, message: unknown, submitted?: () => void, - ): void { + ): Promise { const isOpen = this.config.trace?.isEnabled() === true && this.beginTraceSection("paseo.ws.message.outbound", { @@ -2052,25 +2082,30 @@ export class DaemonClient { ...describeRequestIdentity(message), }); try { - this.sendTransportFrame(JSON.stringify(message), submitted); + return this.sendTransportFrame(JSON.stringify(message), submitted); } finally { this.endTraceSection(isOpen); } } - private sendSessionPayload(payload: SessionInboundMessage): void { - this.sendJsonMessage("session", payload.type, { type: "session", message: payload }, () => { - if (!("requestId" in payload) || typeof payload.requestId !== "string") return; - for (const waiter of this.waiters) { - if (waiter.requestId === payload.requestId) waiter.submitted = true; - } - }); + private sendSessionPayload(payload: SessionInboundMessage): Promise { + return this.sendJsonMessage( + "session", + payload.type, + { type: "session", message: payload }, + () => { + if (!("requestId" in payload) || typeof payload.requestId !== "string") return; + for (const waiter of this.waiters) { + if (waiter.requestId === payload.requestId) waiter.submitted = true; + } + }, + ); } private sendTransportFrame( frame: string | Uint8Array | ArrayBuffer, submitted?: () => void, - ): void { + ): Promise { if (!this.transport) { throw this.unavailableError(); } @@ -2083,7 +2118,8 @@ export class DaemonClient { }); try { submitted?.(); - this.transport.send(frame); + const payload = typeof frame === "string" ? frame : asUint8Array(frame)!; + return this.chunkedTransport!.send(payload); } finally { this.endTraceSection(isOpen); } @@ -2112,10 +2148,10 @@ export class DaemonClient { } } - private sendBinaryFrame(frame: Uint8Array): void { + private sendBinaryFrame(frame: Uint8Array): Promise { if (!this.transport || this.connectionState.status !== "connected") { if (this.config.suppressSendErrors) { - return; + return Promise.resolve(); } throw new Error(`Transport not connected (status: ${this.connectionState.status})`); } @@ -2124,10 +2160,10 @@ export class DaemonClient { envelopeType: "binary", messageType: "binary", }); - this.sendTransportFrame(frame); + return this.sendTransportFrame(frame); } catch (error) { if (this.config.suppressSendErrors) { - return; + return Promise.resolve(); } throw error instanceof Error ? error : new Error(String(error)); } @@ -2142,7 +2178,7 @@ export class DaemonClient { private sendSessionMessageOrThrow(message: SessionInboundMessage): Promise { return this.sendWhenConnected(() => { const payload = SessionInboundMessageSchema.parse(message); - this.sendSessionPayload(payload); + return this.sendSessionPayload(payload); }); } @@ -2151,13 +2187,12 @@ export class DaemonClient { return this.sendWhenConnected(() => undefined); } - private sendWhenConnected(send: () => void): Promise { + private sendWhenConnected(send: () => void | Promise): Promise { const status = this.connectionState.status; // If connected, send immediately if (this.transport && status === "connected") { - send(); - return Promise.resolve(); + return Promise.resolve(send()); } // If connecting, queue the message to be sent once connected @@ -2196,8 +2231,7 @@ export class DaemonClient { clearTimeout(pending.timeoutHandle); try { if (this.transport && this.connectionState.status === "connected") { - pending.send(); - pending.resolve(); + void Promise.resolve(pending.send()).then(pending.resolve, pending.reject); } else { pending.reject(new DaemonConnectionError("Connection lost before message could be sent")); } @@ -2253,19 +2287,17 @@ export class DaemonClient { { ...params.options, requestId: params.requestId }, ); + // The response deadline still applies while the transport waits for drain. + void promise.catch(() => undefined); try { - await this.sendSessionMessageOrThrow(wire.message); + const sent = this.sendSessionMessageOrThrow(wire.message); + const result = await Promise.race([promise, sent.then(() => promise)]); + if (result.kind === "error") throw result.error; + return result.value; } catch (error) { const err = error instanceof Error ? error : new Error(String(error)); cancel(err); - void promise.catch(() => undefined); throw err; - } - - try { - const result = await promise; - if (result.kind === "error") throw result.error; - return result.value; } finally { await wire.finish(); } @@ -2355,13 +2387,13 @@ export class DaemonClient { }); } - private sendSessionMessageStrict(message: SessionInboundMessage): void { + private sendSessionMessageStrict(message: SessionInboundMessage): Promise { if (!this.transport || this.connectionState.status !== "connected") { throw this.unavailableError(); } const payload = SessionInboundMessageSchema.parse(message); try { - this.sendSessionPayload(payload); + return this.sendSessionPayload(payload); } catch (error) { throw error instanceof Error ? error : new Error(String(error)); } @@ -2559,15 +2591,16 @@ export class DaemonClient { }; this.pingProbe = probe; - try { - this.sendJsonMessage("ping", "ping", { type: "ping" }); - } catch (error) { - this.clearPingProbe(); + const rejectSend = (error: unknown) => { + if (this.pingProbe !== probe) return; const sendError = error instanceof Error ? error : new Error(String(error)); - if (probe.drivesLivenessFailure) { - this.recordLivenessFailure(sendError); - } - return Promise.reject(sendError); + this.rejectPingProbe(sendError); + if (probe.drivesLivenessFailure) this.recordLivenessFailure(sendError); + }; + try { + void this.sendJsonMessage("ping", "ping", { type: "ping" }).catch(rejectSend); + } catch (error) { + rejectSend(error); } return promise; @@ -4222,7 +4255,7 @@ export class DaemonClient { } async sendVoiceAudioChunk(audio: string, format: string, isLast = false): Promise { - this.sendSessionMessage({ type: "voice_audio_chunk", audio, format, isLast }); + return this.sendSessionMessageStrict({ type: "voice_audio_chunk", audio, format, isLast }); } async startDictationStream(dictationId: string, format: string): Promise { @@ -4263,8 +4296,13 @@ export class DaemonClient { const cleanupError = new Error("Cancelled dictation start waiter"); try { - this.sendSessionMessageStrict({ type: "dictation_stream_start", dictationId, format }); - await Promise.race([ackPromise, errorPromise]); + const sent = this.sendSessionMessageStrict({ + type: "dictation_stream_start", + dictationId, + format, + }); + const response = Promise.race([ackPromise, errorPromise]); + await Promise.race([response, sent.then(() => response)]); } finally { ack.cancel(cleanupError); streamError.cancel(cleanupError); @@ -4399,12 +4437,17 @@ export class DaemonClient { const cleanupError = new Error("Cancelled dictation finish waiter"); try { - this.sendSessionMessageStrict({ type: "dictation_stream_finish", dictationId, finalSeq }); - const firstOutcome = await Promise.race([ + const sent = this.sendSessionMessageStrict({ + type: "dictation_stream_finish", + dictationId, + finalSeq, + }); + const response = Promise.race([ finalOutcomePromise, errorOutcomePromise, finishAcceptedOutcomePromise, ]); + const firstOutcome = await Promise.race([response, sent.then(() => response)]); if (firstOutcome.kind === "final") { return firstOutcome.payload; @@ -5320,8 +5363,10 @@ export class DaemonClient { return undefined; }, ); + const sendFrame = (frame: Uint8Array) => + Promise.race([this.sendBinaryFrame(frame), responsePromise]); try { - this.sendBinaryFrame( + await sendFrame( encodeFileTransferFrame({ opcode: FileTransferOpcode.FileBegin, requestId: resolvedRequestId, @@ -5335,6 +5380,7 @@ export class DaemonClient { }), ); + if (settled) return await responsePromise; const chunkSize = input.chunkSize ?? 128 * 1024; for (let offset = 0; offset < bytes.byteLength; offset += chunkSize) { // Native WebSocket.send encodes binary synchronously. Let rendering and @@ -5344,7 +5390,7 @@ export class DaemonClient { if (this.transport !== uploadTransport || this.connectionState.status !== "connected") { throw new DaemonConnectionError("Connection changed during file upload"); } - this.sendBinaryFrame( + await sendFrame( encodeFileTransferFrame({ opcode: FileTransferOpcode.FileChunk, requestId: resolvedRequestId, @@ -5353,7 +5399,7 @@ export class DaemonClient { ); } - this.sendBinaryFrame( + await sendFrame( encodeFileTransferFrame({ opcode: FileTransferOpcode.FileEnd, requestId: resolvedRequestId, @@ -6763,6 +6809,8 @@ export class DaemonClient { } private disposeTransport(code = 1001, reason = "Reconnecting"): void { + this.chunkedTransport?.close(); + this.chunkedTransport = null; this.owned.disconnected(); this.providerSnapshotUpdates.clear(); this.stopLivenessHeartbeat(); @@ -7232,15 +7280,6 @@ export class DaemonClient { probe.resolve(perfNow() - probe.startedAt); } - private clearPingProbe(): void { - const probe = this.pingProbe; - if (!probe) { - return; - } - this.pingProbe = null; - clearTimeout(probe.timeoutHandle); - } - private rejectPingProbe(error: Error): void { const probe = this.pingProbe; if (!probe) { @@ -7289,6 +7328,10 @@ export class DaemonClient { if (consumerMessage.type === "status") { const serverInfo = parseServerInfoStatusPayload(consumerMessage.payload); if (serverInfo) { + if (this.chunkedTransport) + this.chunkedTransport.enabled = + serverInfo.features?.binaryChunkingV1 === true && + this.config.capabilities?.[CLIENT_CAPS.binaryChunkingV1] !== false; this.lastServerInfoMessage = serverInfo; this.destinationServerId = serverInfo.serverId; this.connectionFailure = undefined; diff --git a/packages/client/src/hosts/index.ts b/packages/client/src/hosts/index.ts index 1baa9ebe43..aa5c910158 100644 --- a/packages/client/src/hosts/index.ts +++ b/packages/client/src/hosts/index.ts @@ -1,3 +1,4 @@ +import { MAX_HOST_CHANNEL_FRAME_BYTES } from "@getpaseo/protocol/binary-frames/index"; import { safeRandomId } from "../daemon-client-transport-utils.js"; import { DaemonClient } from "../daemon-client.js"; import type { DaemonTransportFactory } from "../daemon-client-transport-types.js"; @@ -84,13 +85,17 @@ export function createHostChannelTransport( }) .catch(close); return { + get supportsDrain() { + return origin.supportsDrain; + }, + maxFrameBytes: MAX_HOST_CHANNEL_FRAME_BYTES, send(data) { if (closed || !routeId) throw Object.assign(new Error(`Host ${serverId} is offline`), { code: "host_offline", serverId, }); - origin.sendHostFrame( + return origin.sendHostFrame( routeId, typeof data === "string" || data instanceof Uint8Array ? data : new Uint8Array(data), ); diff --git a/packages/client/src/node/connector.test.ts b/packages/client/src/node/connector.test.ts index 6e916d4bec..882a2f5706 100644 --- a/packages/client/src/node/connector.test.ts +++ b/packages/client/src/node/connector.test.ts @@ -44,12 +44,14 @@ test("a slow consumer cannot exceed the shared byte budget and close releases re socket.pause(); await ready; const frame = new Uint8Array(1024 * 1024); - for (let index = 0; index < 4; index++) transport.send(frame); + const writes = Array.from({ length: 4 }, () => transport.send(frame)); + const drained = Promise.allSettled(writes); expect(budget.bufferedBytes).toBe(4 * 1024 * 1024); expect(() => transport.send(frame)).toThrow("Connected host buffer limit reached"); expect(budget.bufferedBytes).toBeLessThanOrEqual(budget.limit); transport.close(); await expect.poll(() => budget.bufferedBytes).toBe(0); + await drained; }); test("direct connector preserves 25 MiB binary frames in both directions", async () => { const server = await endpoint(); @@ -65,12 +67,13 @@ test("direct connector preserves 25 MiB binary frames in both directions", async await ready; const bytes = new Uint8Array(25 * 1024 * 1024).fill(173); const echoed = once(socket, "message"); - transport.send(bytes); + const sending = transport.send(bytes); const [sent, binary] = await echoed; expect(binary).toBe(true); expect(Buffer.from(sent as Uint8Array).equals(bytes)).toBe(true); socket.send(bytes); expect(Buffer.from(await received).equals(bytes)).toBe(true); + await sending; }); import { @@ -124,24 +127,29 @@ test("encrypted connector rejects overload synchronously and preserves the physi }); await new Promise((resolve) => transport.onOpen(resolve)); await ready; + expect(transport.maxFrameBytes).toBeLessThan(32 * 1024 * 1024); peer.pause(); const frame = new Uint8Array(1024 * 1024).fill(173); let rejected: unknown; + const writes: (void | Promise)[] = []; for (let index = 0; index < 8; index++) { try { - transport.send(frame); + writes.push(transport.send(frame)); } catch (error) { rejected = error; break; } } + const drained = Promise.allSettled(writes); expect(rejected).toMatchObject({ code: "resource_limit" }); expect(budget.bufferedBytes).toBeLessThanOrEqual(budget.limit); await new Promise((resolve) => setImmediate(resolve)); expect(errors).toEqual([]); expect(closed).toBe(false); - transport.send("sibling control"); + const sibling = transport.send("sibling control"); peer.resume(); + await drained; + await sibling; await expect.poll(() => received.includes("sibling control")).toBe(true); expect(received.filter((data) => data instanceof ArrayBuffer).length).toBeGreaterThan(0); expect( diff --git a/packages/client/src/node/index.ts b/packages/client/src/node/index.ts index 46b5cff17a..30d2b8744f 100644 --- a/packages/client/src/node/index.ts +++ b/packages/client/src/node/index.ts @@ -172,9 +172,15 @@ export function createHostTransportFactory( close(); }); return { + get supportsDrain() { + return transport?.supportsDrain; + }, + get maxFrameBytes() { + return transport?.maxFrameBytes; + }, send(data) { if (closed || !transport) throw new Error("Host transport is unavailable"); - transport.send(data); + return transport.send(data); }, close, onOpen(handler) { diff --git a/packages/protocol/src/binary-frames/host-route.ts b/packages/protocol/src/binary-frames/host-route.ts index f45cd714f9..643dcb4e98 100644 --- a/packages/protocol/src/binary-frames/host-route.ts +++ b/packages/protocol/src/binary-frames/host-route.ts @@ -3,6 +3,11 @@ import { MAX_WEBSOCKET_MESSAGE_BYTES } from "../websocket-message-limit.js"; export const HOST_ROUTE_OPCODE = 0x30; export const MAX_HOST_ROUTE_ID_BYTES = 256; export const MAX_HOST_ROUTE_HEADER_BYTES = 3 + MAX_HOST_ROUTE_ID_BYTES; +// A logical host channel crosses the 32 MiB route admission boundary. Text can +// expand sixfold when enclosed in JSON; binary adds the bounded route header. +export const MAX_HOST_CHANNEL_FRAME_BYTES = Math.floor( + (32 * 1024 * 1024 - MAX_HOST_ROUTE_HEADER_BYTES) / 6, +); export const MAX_ROUTED_PAYLOAD_BYTES = MAX_WEBSOCKET_MESSAGE_BYTES - MAX_HOST_ROUTE_HEADER_BYTES; export interface HostRouteFrame { routeId: string; diff --git a/packages/protocol/src/chunked-transport.test.ts b/packages/protocol/src/chunked-transport.test.ts new file mode 100644 index 0000000000..3979b48885 --- /dev/null +++ b/packages/protocol/src/chunked-transport.test.ts @@ -0,0 +1,392 @@ +import { describe, expect, it } from "vitest"; +import { ChunkedTransport } from "./chunked-transport.js"; + +describe("chunked transport", () => { + it("delivers a large UTF-8 logical message once, preserving order", async () => { + const delivered: (string | Uint8Array)[] = []; + const receiver = new ChunkedTransport({ + frameBytes: 17, + send: () => {}, + deliver: (v) => delivered.push(v), + }); + receiver.enabled = true; + const frames: (string | Uint8Array)[] = []; + const sender = new ChunkedTransport({ + frameBytes: 17, + send: (v) => { + frames.push(v); + receiver.receive(v); + }, + deliver: () => {}, + }); + sender.enabled = true; + const text = "🌍".repeat(100); + await sender.send(text); + expect(delivered).toEqual([text]); + expect(frames.length).toBeGreaterThan(1); + expect(frames.every((v) => v instanceof Uint8Array && v.byteLength <= 17)).toBe(true); + }); +}); + +it("preserves binary kind and leaves legacy frames unchanged", async () => { + const delivered: (string | Uint8Array)[] = []; + const receiver = new ChunkedTransport({ + frameBytes: 8, + send: () => {}, + deliver: (v) => delivered.push(v), + }); + const frames: (string | Uint8Array)[] = []; + const sender = new ChunkedTransport({ + frameBytes: 8, + send: (v) => { + frames.push(v); + receiver.receive(v); + }, + deliver: () => {}, + }); + const data = new Uint8Array(40).fill(5); + await sender.send(data); + expect(frames).toEqual([data]); + frames.length = 0; + sender.enabled = receiver.enabled = true; + await sender.send(data); + expect(frames).toHaveLength(10); + expect(delivered).toEqual([data, data]); +}); + +it("rejects malformed sequences and drops incomplete transfers on close", () => { + const delivered: unknown[] = []; + const receiver = new ChunkedTransport({ + frameBytes: 8, + send: () => {}, + deliver: (v) => delivered.push(v), + }); + receiver.enabled = true; + receiver.receive(new Uint8Array([0x31, 1, 0, 1, 65])); + expect(() => receiver.receive("interrupted")).toThrow("Interrupted"); + receiver.receive(new Uint8Array([0x31, 1, 0, 2, 66])); + expect(delivered).toEqual([]); +}); + +it("waits for drain before the next chunk and preserves logical ordering", async () => { + const frames: (string | Uint8Array)[] = []; + let drain!: () => void; + const sender = new ChunkedTransport({ + frameBytes: 8, + send: (v) => { + frames.push(v); + if (frames.length === 1) + return new Promise((resolve) => { + drain = resolve; + }); + }, + deliver: () => {}, + }); + sender.enabled = true; + const first = sender.send("abcdefghij"); + const next = new Uint8Array([1, 2, 3, 4]); + const second = sender.send(next); + await Promise.resolve(); + expect(frames).toHaveLength(1); + expect(sender.queuedByteLength).toBe(4); + drain(); + await Promise.all([first, second]); + expect(frames).toHaveLength(4); + expect(frames[3]).toEqual(next); + expect(sender.queuedByteLength).toBe(0); +}); + +it.each([ + [0x31, 2, 0, 3, 65], + [0x31, 1, 2, 3, 65], + [0x31, 1, 0, 4, 65], + [0x31, 1, 0, 2, 65], + [0x31, 1, 0, 1], +])("rejects malformed chunk metadata %j", (...bytes) => { + const receiver = new ChunkedTransport({ + frameBytes: 8, + send: () => {}, + deliver: () => { + throw new Error("Unexpected delivery"); + }, + }); + receiver.enabled = true; + expect(() => receiver.receive(new Uint8Array(bytes))).toThrow(); +}); + +it("reconnect discards partial state and requires negotiation again", () => { + const delivered: unknown[] = []; + const create = () => + new ChunkedTransport({ frameBytes: 8, send: () => {}, deliver: (v) => delivered.push(v) }); + const old = create(); + old.enabled = true; + old.receive(new Uint8Array([0x31, 1, 0, 1, 65])); + old.close(); + old.receive(new Uint8Array([0x31, 1, 0, 2, 66])); + const fresh = create(); + expect(fresh.enabled).toBe(false); + fresh.enabled = true; + fresh.receive(new Uint8Array([0x31, 1, 0, 3, 67])); + expect(delivered).toEqual(["C"]); +}); + +it("bounds logical messages waiting behind a blocked writer", async () => { + let drain!: () => void; + const transport = new ChunkedTransport({ + frameBytes: 32 * 1024 * 1024, + send: () => + new Promise((resolve) => { + drain = resolve; + }), + deliver: () => {}, + }); + const first = transport.send(new Uint8Array(100 * 1024 * 1024)); + const overflow = transport.send("one more byte"); + try { + await expect(overflow).rejects.toThrow("queue"); + } finally { + drain(); + await first; + } +}); + +it("requests drain for chunks while ordinary frames keep the immediate write path", async () => { + const waits: boolean[] = []; + const transport = new ChunkedTransport({ + frameBytes: 8, + send: (_frame, wait) => { + waits.push(wait); + }, + deliver: () => {}, + }); + transport.enabled = true; + await transport.send("small"); + await transport.send("abcdefghij"); + expect(waits).toEqual([false, true, true, true]); +}); + +it("charges queued ASCII messages by their UTF-8 bytes", async () => { + let drain!: () => void; + let blocked = true; + const transport = new ChunkedTransport({ + frameBytes: 32 * 1024 * 1024, + send: () => { + if (blocked) { + blocked = false; + return new Promise((resolve) => { + drain = resolve; + }); + } + }, + deliver: () => {}, + }); + transport.enabled = true; + const first = transport.send(new Uint8Array([1])); + const text = "x".repeat(10 * 1024 * 1024); + const queued = Array.from({ length: 4 }, () => transport.send(text)); + const settled = Promise.allSettled(queued); + expect(transport.queuedByteLength).toBe(40 * 1024 * 1024); + drain(); + await first; + expect((await settled).map((result) => result.status)).toEqual([ + "fulfilled", + "fulfilled", + "fulfilled", + "fulfilled", + ]); +}); + +it("notifies the socket owner when an awaited send overflows the queue", async () => { + let drain!: () => void; + const failures: unknown[] = []; + const transport = new ChunkedTransport({ + frameBytes: 32 * 1024 * 1024, + send: () => + new Promise((resolve) => { + drain = resolve; + }), + deliver: () => {}, + onFailure: (error) => { + failures.push(error); + }, + }); + const first = transport.send(new Uint8Array(100 * 1024 * 1024)); + const overflow = transport.send("extra"); + await expect(overflow).rejects.toThrow("queue"); + drain(); + await first; + expect(failures).toHaveLength(1); +}); + +it("bounds retained reassembly memory for many one-byte chunks", async () => { + const { spawnSync } = await import("node:child_process"); + // Exercise the built package as a Node consumer; CI builds it before protocol tests. + const entry = new URL("../dist/chunked-transport.js", import.meta.url).href; + const result = spawnSync( + process.execPath, + [ + "--expose-gc", + "--input-type=module", + "-e", + ` + import { ChunkedTransport } from ${JSON.stringify(entry)}; + let delivered = 0; + const receiver = new ChunkedTransport({ frameBytes: 8, send() {}, deliver(frame) { delivered = frame.byteLength; } }); + receiver.enabled = true; + global.gc(); + const before = process.memoryUsage().heapUsed; + receiver.receive(new Uint8Array([0x31, 1, 1, 1, 65])); + for (let index = 0; index < 300000; index++) receiver.receive(new Uint8Array([0x31, 1, 1, 0, 65])); + global.gc(); + const growth = process.memoryUsage().heapUsed - before; + receiver.receive(new Uint8Array([0x31, 1, 1, 2, 66])); + console.log(JSON.stringify({ growth, delivered })); + `, + ], + { encoding: "utf8", timeout: 15000 }, + ); + expect(result.status, result.stderr).toBe(0); + const observed = JSON.parse(result.stdout); + expect(observed.delivered).toBe(300002); + expect(observed.growth).toBeLessThan(8 * 1024 * 1024); +}, 20000); + +it.each(["ASCII", "中", "🌍", "\ud800", "\udc00", "\ud800x"])( + "accounts for queued UTF-8 text %j exactly", + async (text) => { + let drain!: () => void; + let blocked = true; + const transport = new ChunkedTransport({ + frameBytes: 1024, + send: () => { + if (blocked) { + blocked = false; + return new Promise((resolve) => { + drain = resolve; + }); + } + }, + deliver: () => {}, + }); + const first = transport.send(new Uint8Array([1])); + const second = transport.send(text); + expect(transport.queuedByteLength).toBe(new TextEncoder().encode(text).byteLength); + drain(); + await Promise.all([first, second]); + }, +); + +it("notifies the owner once when an accepted writer fails", async () => { + const failures: unknown[] = []; + const error = new Error("write failed"); + const transport = new ChunkedTransport({ + frameBytes: 1024, + deliver: () => {}, + onFailure: (failure) => { + failures.push(failure); + }, + send: () => Promise.reject(error), + }); + await expect(transport.send("hello", { waitForDrain: true })).rejects.toThrow("write failed"); + expect(failures).toEqual([error]); + expect(() => transport.send("again")).toThrow("Transport closed"); + expect(failures).toEqual([error]); +}); + +it.each([false, true])( + "a pre-write rejection preserves the sender (chunked=%s)", + async (chunked) => { + const failures: unknown[] = []; + let reject = true; + const transport = new ChunkedTransport({ + frameBytes: 8, + deliver: () => {}, + onFailure: (error) => { + failures.push(error); + }, + send: () => { + if (reject) throw new Error("capacity"); + }, + }); + transport.enabled = chunked; + expect(() => transport.send("abcdefghij")).toThrow("capacity"); + expect(failures).toEqual([]); + reject = false; + await transport.send("sibling"); + }, +); + +it("a queued pre-write rejection does not poison the next logical send", async () => { + let drain!: () => void; + const failures: unknown[] = []; + const delivered: string[] = []; + const transport = new ChunkedTransport({ + frameBytes: 1024, + deliver: () => {}, + onFailure: (error) => { + failures.push(error); + }, + send: (frame) => { + if (frame === "blocked") + return new Promise((resolve) => { + drain = resolve; + }); + if (frame === "reject") throw new Error("capacity"); + delivered.push(frame as string); + }, + }); + const first = transport.send("blocked"); + const rejected = transport.send("reject"); + const sibling = transport.send("sibling"); + const results = Promise.allSettled([first, rejected, sibling]); + drain(); + expect((await results).map((result) => result.status)).toEqual([ + "fulfilled", + "rejected", + "fulfilled", + ]); + expect(delivered).toEqual(["sibling"]); + expect(failures).toEqual([]); +}); + +it.each([false, true])("delivery errors leave framing usable (chunked=%s)", async (chunked) => { + let fail = true; + const delivered: (string | Uint8Array)[] = []; + const transport = new ChunkedTransport({ + frameBytes: 64, + send: () => {}, + deliver: (frame) => { + if (fail) throw new Error("listener failed"); + delivered.push(frame); + }, + }); + transport.enabled = chunked; + const frame = chunked ? new Uint8Array([0x31, 1, 0, 3, 65]) : "A"; + expect(() => transport.receive(frame)).toThrow("listener failed"); + fail = false; + transport.receive(frame); + expect(delivered).toEqual(["A"]); + await transport.send("still connected"); +}); + +it("unpaced transports retain ordinary outbound admission and accept inbound chunks", async () => { + const frames: unknown[] = []; + const delivered: unknown[] = []; + const transport = new ChunkedTransport({ + frameBytes: 8, + supportsDrain: false, + send: (frame) => { + frames.push(frame); + if (typeof frame === "string" && frame.length > 8) throw new Error("single frame limit"); + }, + deliver: (frame) => { + delivered.push(frame); + }, + }); + transport.enabled = true; + expect(() => transport.send("too large for one frame")).toThrow("single frame limit"); + expect(frames).toEqual(["too large for one frame"]); + transport.receive(new Uint8Array([0x31, 1, 0, 3, 65])); + expect(delivered).toEqual(["A"]); + await transport.send("small"); +}); diff --git a/packages/protocol/src/chunked-transport.ts b/packages/protocol/src/chunked-transport.ts new file mode 100644 index 0000000000..a32d68424f --- /dev/null +++ b/packages/protocol/src/chunked-transport.ts @@ -0,0 +1,214 @@ +import { MAX_WEBSOCKET_MESSAGE_BYTES } from "./websocket-message-limit.js"; + +type Frame = string | Uint8Array; + +/** A malformed wire frame, distinct from a consumer delivery failure. */ +export class ChunkedTransportProtocolError extends Error {} +// Reserved outside the application binary opcode space. Version, kind, flags follow. +const OPCODE = 0x31; +const HEADER = 4; + +/** Connection-scoped ordered framing, below serialization and routing, above encryption. */ +export class ChunkedTransport { + enabled = false; + private assembly: Uint8Array | undefined; + private size = 0; + private kind = 0; + private closed = false; + private pending: Promise | undefined; + private queuedBytes = 0; + private activeBytes = 0; + + constructor( + private readonly io: { + frameBytes: number; + supportsDrain?: boolean; + send: (frame: Frame, waitForDrain: boolean) => void | Promise; + deliver: (frame: Frame) => void; + onFailure?: (error: unknown) => void; + }, + ) { + if (io.frameBytes <= HEADER) throw new Error("Invalid transport frame budget"); + } + + /** Bytes waiting behind the active write; physical buffering owns the active frame. */ + get queuedByteLength(): number { + return this.queuedBytes - this.activeBytes; + } + get isWriting(): boolean { + return this.pending !== undefined; + } + + send(frame: Frame, options: { waitForDrain?: boolean; byteLength?: number } = {}): Promise { + const byteLength = options.byteLength ?? frameByteLength(frame); + if (byteLength > MAX_WEBSOCKET_MESSAGE_BYTES) throw new Error("Logical message too large"); + const chunk = + this.enabled && this.io.supportsDrain !== false && byteLength > this.io.frameBytes; + if (this.closed) throw new Error("Transport closed"); + const write = () => { + if (this.closed) throw new Error("Transport closed"); + this.activeBytes = byteLength; + // A synchronous rejection did not admit a frame. Only accepted writes can + // fail the connection; queued admission failures still belong to their sender. + const result = chunk + ? this.sendChunks( + typeof frame === "string" ? new TextEncoder().encode(frame) : frame, + typeof frame === "string", + ) + : this.io.send(frame, options.waitForDrain === true); + if (!result) return; + return result.catch((error) => { + this.fail(error); + throw error; + }); + }; + if (this.queuedBytes + byteLength > MAX_WEBSOCKET_MESSAGE_BYTES) { + const error = new Error("Logical output queue exceeded its byte limit"); + this.fail(error); + const rejected = Promise.reject(error); + void rejected.catch(() => {}); + return rejected; + } + this.queuedBytes += byteLength; + let result: void | Promise; + try { + result = this.pending ? this.pending.then(write) : write(); + } catch (error) { + this.queuedBytes -= byteLength; + this.activeBytes = 0; + throw error; + } + if (!result) { + this.queuedBytes -= byteLength; + this.activeBytes = 0; + return Promise.resolve(); + } + const completion = Promise.resolve(result).finally(() => { + this.queuedBytes -= byteLength; + this.activeBytes = 0; + }); + const tail = completion.then( + () => undefined, + () => undefined, + ); + this.pending = tail; + void tail.then(() => { + if (this.pending === tail) this.pending = undefined; + return undefined; + }); + return completion; + } + + private sendChunks(bytes: Uint8Array, text: boolean): Promise { + const capacity = this.io.frameBytes - HEADER; + const writeChunk = (offset: number) => { + if (this.closed) throw new Error("Transport closed"); + const end = Math.min(bytes.byteLength, offset + capacity); + const wire = new Uint8Array(HEADER + end - offset); + wire.set([ + OPCODE, + 1, + text ? 0 : 1, + (offset === 0 ? 1 : 0) | (end === bytes.byteLength ? 2 : 0), + ]); + wire.set(bytes.subarray(offset, end), HEADER); + return this.io.send(wire, true); + }; + const first = writeChunk(0); + return (async () => { + await first; + for (let offset = capacity; offset < bytes.byteLength; offset += capacity) + await writeChunk(offset); + })(); + } + + receive(frame: Frame): void { + if (this.closed) return; + let message: Frame | undefined; + try { + message = this.assemble(frame); + } catch (error) { + this.close(); + throw new ChunkedTransportProtocolError( + error instanceof Error ? error.message : String(error), + { cause: error }, + ); + } + if (message !== undefined) this.io.deliver(message); + } + + private assemble(frame: Frame): Frame | undefined { + if (typeof frame === "string" || frame[0] !== OPCODE) { + if (this.assembly) throw new Error("Interrupted chunked message"); + return frame; + } + if ( + !this.enabled || + frame.length <= HEADER || + frame[1] !== 1 || + frame[2]! > 1 || + (frame[3]! & ~3) !== 0 + ) + throw new Error("Invalid chunk header"); + const start = (frame[3]! & 1) !== 0; + const end = (frame[3]! & 2) !== 0; + if (start === !!this.assembly) throw new Error("Invalid chunk sequence"); + if (start) { + this.assembly = new Uint8Array(0); + this.kind = frame[2]!; + this.size = 0; + } + if (frame[2] !== this.kind) throw new Error("Chunk kind changed"); + this.size += frame.length - HEADER; + if (this.size > MAX_WEBSOCKET_MESSAGE_BYTES) throw new Error("Logical message too large"); + const payload = frame.subarray(HEADER); + if (this.assembly!.byteLength < this.size) { + const capacity = Math.min( + MAX_WEBSOCKET_MESSAGE_BYTES, + Math.max(this.size, this.assembly!.byteLength * 2, 16384), + ); + const grown = new Uint8Array(capacity); + grown.set(this.assembly!.subarray(0, this.size - payload.byteLength)); + this.assembly = grown; + } + this.assembly!.set(payload, this.size - payload.byteLength); + if (!end) return; + const data = this.assembly!.subarray(0, this.size); + this.assembly = undefined; + this.size = 0; + return this.kind === 0 ? new TextDecoder("utf-8", { fatal: true }).decode(data) : data.slice(); + } + + private fail(error: unknown): void { + if (this.closed) return; + this.close(); + this.io.onFailure?.(error); + } + + close(): void { + this.closed = true; + this.enabled = false; + this.assembly = undefined; + this.size = 0; + } +} + +function frameByteLength(frame: Frame): number { + if (typeof frame !== "string") return frame.byteLength; + let bytes = 0; + for (let index = 0; index < frame.length; index++) { + const code = frame.charCodeAt(index); + if (code <= 0x7f) bytes++; + else if (code <= 0x7ff) bytes += 2; + else if ( + code >= 0xd800 && + code <= 0xdbff && + frame.charCodeAt(index + 1) >= 0xdc00 && + frame.charCodeAt(index + 1) <= 0xdfff + ) { + bytes += 4; + index++; + } else bytes += 3; + } + return bytes; +} diff --git a/packages/protocol/src/client-capabilities.ts b/packages/protocol/src/client-capabilities.ts index a35852cc06..28ec8456cb 100644 --- a/packages/protocol/src/client-capabilities.ts +++ b/packages/protocol/src/client-capabilities.ts @@ -1,4 +1,5 @@ export const CLIENT_CAPS = { + binaryChunkingV1: "binary_chunking_v1", helloRejection: "hello_rejection", // COMPAT(ownedSubscriptions): added in v0.8.0, remove legacy ownership after 2027-03-09. ownedSubscriptions: "owned_subscriptions", diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index 8d8f852988..dc63d56b75 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -3834,6 +3834,7 @@ export const ServerInfoStatusPayloadSchema = z selectiveAgentTimeline: z.boolean().optional(), explicitEventSubscriptions: z.boolean().optional(), ownedSubscriptions: z.boolean().optional(), + binaryChunkingV1: z.boolean().optional(), workspaceSetupObservation: z.boolean().optional(), workspaceSortTimes: z.boolean().optional(), // COMPAT(canonicalSubmittedPrompts): added in v0.2.6, remove gate after 2027-01-30. diff --git a/packages/server/src/server/connected-hosts/hosts.e2e.test.ts b/packages/server/src/server/connected-hosts/hosts.e2e.test.ts index b6765051f6..4c6d79aced 100644 --- a/packages/server/src/server/connected-hosts/hosts.e2e.test.ts +++ b/packages/server/src/server/connected-hosts/hosts.e2e.test.ts @@ -2091,3 +2091,80 @@ test.each(["removed", "disabled"] as const)( ).toEqual([]); }, ); + +test( + "a 50 MiB timeline crosses a routed host without dropping content or the route", + { timeout: 30000 }, + async () => { + const b = await daemon(); + const a = await daemon(); + const destination = await api(b); + const origin = await api(a); + const workspace = await destination.paseo.workspaces.create({ + source: { kind: "directory", path: b.staticDir }, + }); + const agent = await workspace.agents.create({ + config: { provider: "claude/claude-test", modeId: "full-access" }, + title: "Large history", + }); + // Keep each row below the established item budget; exercise transport size across rows. + const text = "x".repeat(240 * 1024); + const rowCount = 220; + for (let index = 0; index < rowCount; index++) { + await b.daemon.agentManager.appendTimelineItem(agent.id, { type: "user_message", text }); + } + await origin.paseo.hosts.add({ connection: `127.0.0.1:${b.port}` }); + const serverId = (await online(origin.paseo)).hosts[0]!.serverId!; + const remote = await origin.paseo.hosts.client(serverId); + const response = await remote.agents.ref(agent.id).timeline.refetch({ limit: 0 }); + const messages = response.entries.flatMap((row) => + row.item.type === "user_message" ? [row.item.text] : [], + ); + expect(messages).toHaveLength(rowCount); + expect(messages.every((message) => message === text)).toBe(true); + expect( + messages.reduce((bytes, message) => bytes + Buffer.byteLength(message), 0), + ).toBeGreaterThan(50 * 1024 * 1024); + expect((await remote.workspaces.list()).entries).toHaveLength(1); + await remote.dispose(); + }, +); + +test("a pre-write host budget rejection leaves sibling routes connected", async () => { + const { HostTransportBudget } = await import("@getpaseo/client/node"); + const b = await daemon(); + const origin = createHostClient( + `127.0.0.1:${b.port}`, + { clientId: "budget-origin", reconnect: { enabled: false } }, + new HostTransportBudget(1024 * 1024), + ); + cleanup.push(() => origin.close()); + await origin.connect(); + const serverId = origin.getLastServerInfoMessage()!.serverId; + const routeIds = [ + await origin.openHostLink("budget-first"), + await origin.openHostLink("budget-sibling"), + ]; + const peers = routeIds.map( + (id, index) => + new DaemonClient({ + url: "ws://host-link/ws", + clientId: `budget-child-${index}`, + reconnect: { enabled: false }, + transportFactory: createHostChannelTransport(origin, serverId, `budget-${index}`, id), + }), + ); + for (const peer of peers) { + cleanup.push(() => peer.close()); + await peer.connect(); + } + await expect(async () => + origin.sendHostFrame(routeIds[0]!, new Uint8Array(2 * 1024 * 1024)), + ).rejects.toMatchObject({ code: "resource_limit" }); + await peers[1]!.ping({ timeoutMs: 2000 }); + expect([origin.isConnected, ...peers.map((peer) => peer.isConnected)]).toEqual([ + true, + true, + true, + ]); +}, 30000); diff --git a/packages/server/src/server/connected-hosts/index.ts b/packages/server/src/server/connected-hosts/index.ts index 96d6ac35d2..15b1e16b97 100644 --- a/packages/server/src/server/connected-hosts/index.ts +++ b/packages/server/src/server/connected-hosts/index.ts @@ -510,10 +510,13 @@ export class ConnectedHosts { return; } if (!verified) throw new HostError("host_offline", "Host identity has not been verified"); - try { - transport.send(data); - } catch { + const rejectWrite = () => route.close("resource_limit", "Host buffer limit reached or transport unavailable"); + try { + const write = transport.send(data); + if (write) void write.catch(rejectWrite); + } catch { + rejectWrite(); } }, }; diff --git a/packages/server/src/server/connected-hosts/link.ts b/packages/server/src/server/connected-hosts/link.ts index 85fe06ed4e..a18c89aeb0 100644 --- a/packages/server/src/server/connected-hosts/link.ts +++ b/packages/server/src/server/connected-hosts/link.ts @@ -1,7 +1,11 @@ import type { SessionDelivery } from "../session/owned-subscriptions/index.js"; import { EventEmitter } from "node:events"; import { createHash } from "node:crypto"; -import { encodeHostRouteFrame, type HostRouteFrame } from "@getpaseo/protocol/binary-frames/index"; +import { + MAX_HOST_CHANNEL_FRAME_BYTES, + encodeHostRouteFrame, + type HostRouteFrame, +} from "@getpaseo/protocol/binary-frames/index"; import type { DaemonPermission, SessionInboundMessage, @@ -10,6 +14,7 @@ import type { /** A logical socket has no network resources or authority of its own. */ export class VirtualHostSocket extends EventEmitter { + readonly maxFrameBytes = MAX_HOST_CHANNEL_FRAME_BYTES; readyState = 1; constructor( private readonly output: (data: string | Uint8Array) => Promise, diff --git a/packages/server/src/server/daemon-e2e/relay-transport.e2e.test.ts b/packages/server/src/server/daemon-e2e/relay-transport.e2e.test.ts index 32d3a1f36c..f47accaa55 100644 --- a/packages/server/src/server/daemon-e2e/relay-transport.e2e.test.ts +++ b/packages/server/src/server/daemon-e2e/relay-transport.e2e.test.ts @@ -9,7 +9,7 @@ import { } from "@getpaseo/protocol/binary-frames/index"; import { getDaemonAuthFailureReason, - type DaemonClient as HostClient, + DaemonClient as HostClient, } from "@getpaseo/client/internal/daemon-client"; import type { SessionOutboundMessage } from "@getpaseo/protocol/messages"; import { describe, expect, test } from "vitest"; @@ -593,72 +593,112 @@ async function waitForCapturedLog( } }, 90000); - test("oversized attachments fail without disconnecting or resubmitting over the relay", async () => { - await startRelay({ useLocalRelay: true }); - const daemon = await createTestPaseoDaemon({ - relayEnabled: true, - relayEndpoint: `127.0.0.1:${relayPort}`, - relayUseTls: false, - relayPublicUseTls: false, - }); - let client: DaemonClient | null = null; - try { - const offerUrl = await getPairingOfferUrl({ - paseoHome: daemon.paseoHome, + test.each([true, false])( + "large messages cross the relay with unpaced upload admission preserved (supportsDrain=%s)", + async (supportsDrain) => { + await startRelay({ useLocalRelay: true }); + const daemon = await createTestPaseoDaemon({ relayEnabled: true, - relayEndpoint: daemon.config.relayEndpoint, + relayEndpoint: `127.0.0.1:${relayPort}`, + relayUseTls: false, + relayPublicUseTls: false, }); - const { serverId, daemonPublicKeyB64 } = decodeOfferFromFragmentUrl(offerUrl); - client = new DaemonClient({ - url: buildRelayWebSocketUrl({ - endpoint: `127.0.0.1:${relayPort}`, - useTls: false, - serverId, - role: "client", - }), - e2ee: { enabled: true, daemonPublicKeyB64 }, - reconnect: { baseDelayMs: 100, maxDelayMs: 100 }, - }); - await client.connect(); - const statuses: string[] = []; - client.subscribeConnectionStatus((state) => statuses.push(state.status)); - for (const imageMiB of [30, 61]) { - // Attachments are base64 in the JSON, then E2EE base64 expands the frame again. - const images = [ - { data: "A".repeat(4 * Math.ceil((imageMiB * 1024 * 1024) / 3)), mimeType: "image/png" }, - ]; + let client: HostClient | null = null; + try { + const offerUrl = await getPairingOfferUrl({ + paseoHome: daemon.paseoHome, + relayEnabled: true, + relayEndpoint: daemon.config.relayEndpoint, + }); + const { serverId, daemonPublicKeyB64 } = decodeOfferFromFragmentUrl(offerUrl); + client = new HostClient({ + clientId: "paced-relay-regression", + webSocketFactory: Object.assign((url: string) => new WebSocket(url), { supportsDrain }), + url: buildRelayWebSocketUrl({ + endpoint: `127.0.0.1:${relayPort}`, + useTls: false, + serverId, + role: "client", + }), + e2ee: { enabled: true, daemonPublicKeyB64 }, + reconnect: { baseDelayMs: 100, maxDelayMs: 100 }, + }); + await client.connect(); + const statuses: string[] = []; + client.subscribeConnectionStatus((state) => statuses.push(state.status)); + for (const imageMiB of [30, 61]) { + const images = [ + { + data: "A".repeat(4 * Math.ceil((imageMiB * 1024 * 1024) / 3)), + mimeType: "image/png", + }, + ]; + const creation = client.createWorkspace({ + source: { kind: "directory", path: daemon.staticDir }, + agent: { + provider: "claude", + cwd: daemon.staticDir, + initialPrompt: "Describe these screens.", + images, + }, + }); + if (supportsDrain) + await withTimeout(creation, 30000, "Chunked workspace creation did not settle"); + else await expect(creation).rejects.toThrow(/too large.*32\.0 MiB/); + } + expect((await client.fetchAgents()).entries).toHaveLength(supportsDrain ? 2 : 0); await expect( - withTimeout( - client.createWorkspace({ - source: { kind: "directory", path: daemon.staticDir }, - agent: { - provider: "claude", - cwd: daemon.staticDir, - initialPrompt: "Describe these screens.", - images, - }, - }), - 10000, - "Workspace creation did not settle", - ), - ).rejects.toThrow(/too large.*32\.0 MiB/); - expect((await client.fetchAgents()).entries).toEqual([]); - } - const agent = await client.createAgent({ provider: "claude", cwd: daemon.staticDir }); - await expect( - client.sendMessage(agent.id, "Describe these screens.", { + client.createWorkspace({ + source: { kind: "directory", path: daemon.staticDir }, + agent: { + provider: "claude", + cwd: daemon.staticDir, + initialPrompt: "Describe these screens.", + images: [{ data: "A".repeat(101 * 1024 * 1024), mimeType: "image/png" }], + }, + }), + ).rejects.toThrow(/too large.*100\.0 MiB/); + expect((await client.fetchAgents()).entries).toHaveLength(supportsDrain ? 2 : 0); + const agent = await client.createAgent({ provider: "claude", cwd: daemon.staticDir }); + const attachment = client.sendMessage(agent.id, "Describe these screens.", { images: [{ data: "A".repeat(40 * 1024 * 1024), mimeType: "image/png" }], - }), - ).rejects.toThrow(/too large.*32\.0 MiB/); - await client.sendMessage(agent.id, "A small follow-up still works."); - expect((await client.fetchAgents()).entries).toHaveLength(1); - expect(statuses).toEqual(["connected"]); - } finally { - await client?.close(); - await daemon.close(); - await stopRelay(); - } - }, 60000); + }); + if (supportsDrain) await attachment; + else await expect(attachment).rejects.toThrow(/too large.*32\.0 MiB/); + await expect( + client.sendMessage(agent.id, "Describe these screens.", { + images: [{ data: "A".repeat(101 * 1024 * 1024), mimeType: "image/png" }], + }), + ).rejects.toThrow(/too large.*100\.0 MiB/); + await client.sendMessage(agent.id, "A small follow-up still works."); + expect((await client.fetchAgents()).entries).toHaveLength(supportsDrain ? 3 : 1); + // Respect the per-item content budget while exceeding the relay frame limit. + const text = "x".repeat(240 * 1024); + for (let row = 0; row < 220; row++) + await daemon.daemon.agentManager.appendTimelineItem(agent.id, { + type: "user_message", + text, + }); + const timeline = await client.fetchAgentTimeline(agent.id, { + projection: "canonical", + limit: 0, + timeout: 30000, + }); + const delivered = timeline.entries.filter( + (row) => row.item.type === "user_message" && row.item.text === text, + ); + expect(delivered).toHaveLength(220); + expect(delivered.length * Buffer.byteLength(text)).toBeGreaterThan(50 * 1024 * 1024); + await client.ping(); + expect(statuses).toEqual(["connected"]); + } finally { + await client?.close(); + await daemon.close(); + await stopRelay(); + } + }, + 120000, + ); test("daemon connects to relay and client ping/pong works through relay", async () => { process.env.PASEO_PRIMARY_LAN_IP = "192.168.1.12"; diff --git a/packages/server/src/server/daemon-e2e/terminal.e2e.test.ts b/packages/server/src/server/daemon-e2e/terminal.e2e.test.ts index 633bd3bc1c..3c131ecab3 100644 --- a/packages/server/src/server/daemon-e2e/terminal.e2e.test.ts +++ b/packages/server/src/server/daemon-e2e/terminal.e2e.test.ts @@ -1836,3 +1836,58 @@ describe("list terminals across directories", () => { ]); }); }); + +test("a paused terminal consumer catches up through a snapshot instead of retaining every output frame", async () => { + const { existsSync } = await import("node:fs"); + const cwd = tmpCwd(); + tempDirs.push(cwd); + const marker = path.join(cwd, "output-complete"); + const created = await createTerminalInWorkspace(ctx.client, { + cwd, + options: { + command: process.execPath, + args: [ + "-e", + ` + const fs = require('node:fs'); + process.stdin.setRawMode?.(true); + process.stdin.resume(); + process.stdin.once('data', () => { + const chunk = Buffer.alloc(256 * 1024, 120); + let remaining = 128; + const write = () => { + if (remaining-- === 0) { fs.writeFileSync(${JSON.stringify(marker)}, 'done'); return; } + process.stdout.write(chunk, write); + }; + write(); + }); + `, + ], + }, + }); + const ws = await connectRawWebSocket(ctx.daemon.port); + try { + const slot = await subscribeRawTerminal(ws, created.terminal!.id, "slow-terminal"); + await waitForRawBinaryFrame( + ws, + (frame) => frame.slot === slot && frame.opcode === TerminalStreamOpcode.Snapshot, + ); + const capture = startTerminalOutputCapture(ws, slot); + try { + ws.pause(); + sendRawTerminalInput(ws, slot, "go\n"); + await waitForCondition(() => existsSync(marker), 20000); + ws.resume(); + await waitForCondition(() => capture.snapshotCount > 0, 10000); + expect(ws.readyState).toBe(WebSocket.OPEN); + expect(capture.frames.reduce((total, frame) => total + frame.payloadBytes, 0)).toBeLessThan( + 32 * 1024 * 1024, + ); + } finally { + ws.resume(); + capture.stop(); + } + } finally { + await closeWebSocket(ws); + } +}, 40000); diff --git a/packages/server/src/server/websocket-server.file-transfer.e2e.test.ts b/packages/server/src/server/websocket-server.file-transfer.e2e.test.ts index 5131456ee9..abce664ffd 100644 --- a/packages/server/src/server/websocket-server.file-transfer.e2e.test.ts +++ b/packages/server/src/server/websocket-server.file-transfer.e2e.test.ts @@ -90,7 +90,11 @@ test( TEST_TIMEOUT_MS, ); -async function connectSocket(port: number, clientId: string): Promise { +async function connectSocket( + port: number, + clientId: string, + capabilities?: Record, +): Promise { const socket = new WebSocket(`ws://127.0.0.1:${port}/ws`); await new Promise((resolve, reject) => { socket.once("open", resolve); @@ -98,7 +102,7 @@ async function connectSocket(port: number, clientId: string): Promise }); await sendAndWait( socket, - { type: "hello", clientId, clientType: "browser", protocolVersion: 1 }, + { type: "hello", clientId, clientType: "browser", protocolVersion: 1, capabilities }, (message) => message.type === "session" && message.message.type === "status" && @@ -166,3 +170,97 @@ function sendAndWait( socket.send(JSON.stringify(message)); return response; } + +test("an awaited timeline framing overflow closes the actual daemon socket", async () => { + const { createHostClient } = await import("@getpaseo/client/node"); + const { createPaseoApi } = await import("@getpaseo/client"); + const { default: pino } = await import("pino"); + const { Writable } = await import("node:stream"); + const messages: string[] = []; + const logger = pino( + { level: "warn" }, + new Writable({ + write(chunk, _encoding, done) { + messages.push(JSON.parse(chunk.toString()).msg); + done(); + }, + }), + ); + daemon = await createTestPaseoDaemon({ logger }); + const client = createHostClient(`127.0.0.1:${daemon.port}`, { + clientId: "framing-seed", + reconnect: { enabled: false }, + }); + await client.connect(); + const api = createPaseoApi(client); + try { + const workspace = await api.workspaces.create({ + source: { kind: "directory", path: daemon.staticDir }, + }); + const agents = []; + const text = "x".repeat(240 * 1024); + for (const [index, rows] of [350, 90].entries()) { + const agent = await workspace.agents.create({ + config: { provider: "claude/claude-test", modeId: "full-access" }, + title: `Framing overflow ${index}`, + }); + agents.push(agent.id); + for (let row = 0; row < rows; row++) + await daemon.daemon.agentManager.appendTimelineItem(agent.id, { + type: "user_message", + text, + }); + } + const source = await connectSocket(daemon.port, "framing-overflow", { + binary_chunking_v1: true, + }); + sockets.push(source); + const closed = new Promise((resolve) => source.once("close", () => resolve())); + const firstChunk = new Promise((resolve) => { + const listener = (data: RawData, binary: boolean) => { + if (!binary || (data as Buffer)[0] !== 0x31) return; + source.off("message", listener); + source.pause(); + resolve(); + }; + source.on("message", listener); + }); + const fetch = (agentId: string, requestId: string) => + source.send( + JSON.stringify({ + type: "session", + message: { + type: "fetch_agent_timeline_request", + requestId, + agentId, + direction: "tail", + projection: "canonical", + limit: 0, + }, + }), + ); + fetch(agents[0]!, "first"); + await firstChunk; + fetch(agents[1]!, "overflow"); + await expect + .poll(() => messages.includes("Closing physical WebSocket after outbound framing failure"), { + timeout: 15000, + }) + .toBe(true); + expect(messages).not.toContain("Closing physical WebSocket at outbound high-water mark"); + source.resume(); + await closed; + } finally { + await api.dispose(); + await client.close(); + } +}, 60000); + +test("malformed chunk metadata closes the daemon socket with a protocol error", async () => { + daemon = await createTestPaseoDaemon(); + const source = await connectSocket(daemon.port, "invalid-framing", { binary_chunking_v1: true }); + sockets.push(source); + const closed = new Promise((resolve) => source.once("close", (code) => resolve(code))); + source.send(new Uint8Array([0x31, 2, 0, 3, 65])); + expect(await closed).toBe(1002); +}); diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index 96c81ab49a..7bfc4d5a0f 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -1,3 +1,7 @@ +import { + ChunkedTransport, + ChunkedTransportProtocolError, +} from "@getpaseo/protocol/chunked-transport"; import { type WorkspaceRuntimeStore } from "./workspace-runtime-store/index.js"; import { createAgentMessageDelivery, @@ -124,8 +128,8 @@ import { MAX_PHYSICAL_SOCKET_BUFFERED_BYTES, outboundFrameByteLength, physicalSocketHasCapacity, - sendBoundedPhysicalFrame, sendBoundedPhysicalFrameAndWait, + sendBoundedPhysicalFrame, } from "./websocket/physical-socket.js"; const WS_CLOSE_DAEMON_AUTH_FAILED = 4401; @@ -440,6 +444,7 @@ function bufferFromWsData(data: Buffer | ArrayBuffer | Buffer[] | string): Buffe } export interface WebSocketLike { + maxFrameBytes?: number; readyState: number; bufferedAmount?: number; send: ( @@ -1273,6 +1278,67 @@ export class VoiceAssistantWebSocketServer { return { sockets: writableSockets, payload, bytes: outboundFrameByteLength(payload) }; } + private sendHelloResponse(ws: WebSocketLike, session: Session, hello: WSHelloMessage): void { + // The peer learns our support from this ordinary response before receiving chunks. + this.sendToClient(ws, this.createServerInfoMessage(session)); + this.chunkedSocket(ws).enabled = hello.capabilities?.[CLIENT_CAPS.binaryChunkingV1] === true; + } + + private readonly chunkedSockets = new WeakMap(); + + private chunkedSocket(ws: WebSocketLike): ChunkedTransport { + let transport = this.chunkedSockets.get(ws); + if (!transport) { + transport = new ChunkedTransport({ + frameBytes: ws.maxFrameBytes ?? 32 * 1024 * 1024, + onFailure: (err) => + this.closePhysicalSocket({ + ws, + logMessage: "Closing physical WebSocket after outbound framing failure", + logFields: { err }, + }), + send: (frame, waitForDrain) => { + const params = { + socket: ws, + frame, + onHighWater: () => this.closeAtOutboundHighWater(ws), + }; + if (waitForDrain) + return sendBoundedPhysicalFrameAndWait(params).then((sent) => { + if (!sent) throw new Error("Source is closed"); + return undefined; + }); + if (!sendBoundedPhysicalFrame(params)) throw new Error("Source is closed"); + }, + deliver: (frame) => + this.handleRawMessage(ws, typeof frame === "string" ? frame : Buffer.from(frame)), + }); + this.chunkedSockets.set(ws, transport); + } + return transport; + } + + private socketBufferedAmount(ws: WebSocketLike): number | null { + const queued = this.chunkedSockets.get(ws)?.queuedByteLength ?? 0; + if (typeof ws.bufferedAmount === "number") return ws.bufferedAmount + queued; + return queued > 0 ? queued : null; + } + + private sendSocketFrame( + ws: WebSocketLike, + frame: string | Uint8Array, + bytes: number, + waitForDrain = false, + ): Promise { + const transport = this.chunkedSocket(ws); + const admittedBytes = transport.isWriting + ? bytes + : Math.min(bytes, ws.maxFrameBytes ?? 32 * 1024 * 1024); + if (!this.ensureOutboundCapacity(ws, admittedBytes)) + return Promise.reject(new Error("Source is closed")); + return transport.send(frame, { waitForDrain, byteLength: bytes }); + } + private async sendMessageToClientAndWait( ws: WebSocketLike, message: WSOutboundMessage, @@ -1280,13 +1346,7 @@ export class VoiceAssistantWebSocketServer { const prepared = this.prepareJsonDelivery([ws], message, true); if (!prepared) throw new Error("Source message delivery unavailable"); try { - const sent = await sendBoundedPhysicalFrameAndWait({ - socket: ws, - frame: prepared.payload, - frameBytes: prepared.bytes, - onHighWater: () => this.closeAtOutboundHighWater(ws), - }); - if (!sent) throw new Error("Source is closed"); + await this.sendSocketFrame(ws, prepared.payload, prepared.bytes, true); this.runtimeMetrics.recordOutboundMessage(message, ws.bufferedAmount); } catch (err) { this.logger.warn({ err }, "ws_send_failed"); @@ -1313,14 +1373,7 @@ export class VoiceAssistantWebSocketServer { return; } try { - const sent = await sendBoundedPhysicalFrameAndWait({ - socket: ws, - frame, - onHighWater: () => this.closeAtOutboundHighWater(ws), - }); - if (!sent) { - throw new Error("Physical WebSocket is not open"); - } + await this.sendSocketFrame(ws, frame, frame.byteLength, true); this.runtimeMetrics.recordOutboundBinaryFrame(ws.bufferedAmount); } catch (err) { this.logger.warn({ err }, "ws_send_failed"); @@ -1335,13 +1388,9 @@ export class VoiceAssistantWebSocketServer { recordSent: () => void, ): void { try { - const sent = sendBoundedPhysicalFrame({ - socket: ws, - frame, - frameBytes, - onHighWater: () => this.closeAtOutboundHighWater(ws), + void this.sendSocketFrame(ws, frame, frameBytes).then(recordSent, (err) => { + this.logger.warn({ err }, "ws_send_failed"); }); - if (sent) recordSent(); } catch (err) { this.logger.warn({ err }, "ws_send_failed"); } @@ -1349,7 +1398,13 @@ export class VoiceAssistantWebSocketServer { private ensureOutboundCapacity(ws: WebSocketLike, frameBytes: number): boolean { if (ws.readyState !== 1) return false; - if (physicalSocketHasCapacity(ws, frameBytes)) return true; + if ( + physicalSocketHasCapacity( + { bufferedAmount: this.socketBufferedAmount(ws) ?? undefined }, + frameBytes, + ) + ) + return true; this.closeAtOutboundHighWater(ws); return false; @@ -1522,16 +1577,15 @@ export class VoiceAssistantWebSocketServer { if (!connection) { return null; } - if (source) return (source as WebSocketLike).bufferedAmount ?? null; + if (source) return this.socketBufferedAmount(source as WebSocketLike); // Relay-attached sockets are a WebSocketLike that doesn't expose // bufferedAmount. Return null when no socket gives a signal so the // terminal fallback can't mistake "no signal" for "client keeping up"; // a direct ws reports its real buffered bytes (0 when drained). let maxBuffered: number | null = null; for (const socket of connection.sockets) { - if (typeof socket.bufferedAmount === "number") { - maxBuffered = Math.max(maxBuffered ?? 0, socket.bufferedAmount); - } + const buffered = this.socketBufferedAmount(socket); + if (buffered !== null) maxBuffered = Math.max(maxBuffered ?? 0, buffered); } return maxBuffered; }, @@ -1568,8 +1622,9 @@ export class VoiceAssistantWebSocketServer { let total = 0; for (const socket of this.sessions.keys()) { if (socket instanceof VirtualHostSocket) continue; - if (typeof socket.bufferedAmount !== "number") return null; - total += socket.bufferedAmount; + const buffered = this.socketBufferedAmount(socket); + if (buffered === null) return null; + total += buffered; } return total; }, @@ -1770,7 +1825,7 @@ export class VoiceAssistantWebSocketServer { this.externalSessionsByKey.set(sessionKey, connection); } pending.identity.sessionId = connection.session.getSessionId(); - this.sendToClient(ws, this.createServerInfoMessage(connection.session)); + this.sendHelloResponse(ws, connection.session, message); connection.connectionLogger.info( { ...toConnectionLogFields(pending.identity), @@ -1906,7 +1961,7 @@ export class VoiceAssistantWebSocketServer { existing.sockets.add(ws); this.sessions.set(ws, existing); pending.identity.sessionId = existing.session.getSessionId(); - this.sendToClient(ws, this.createServerInfoMessage(existing.session)); + this.sendHelloResponse(ws, existing.session, message); pending.connectionLogger.info( { ...toConnectionLogFields(pending.identity), @@ -1952,6 +2007,7 @@ export class VoiceAssistantWebSocketServer { usageSetting: true, usageSources: true, ownedSubscriptions: true, + binaryChunkingV1: true, agentRequestReceipts: true, workspaceRequestReceipts: true, creationLifecycle: true, @@ -2165,10 +2221,16 @@ export class VoiceAssistantWebSocketServer { private bindSocketHandlers(ws: WebSocketLike): void { ws.on("message", (...args: unknown[]) => { const data = args[0] as Buffer | ArrayBuffer | Buffer[] | string; - this.handleRawMessage(ws, data); + try { + this.chunkedSocket(ws).receive(typeof data === "string" ? data : bufferFromWsData(data)); + } catch (error) { + if (!(error instanceof ChunkedTransportProtocolError)) throw error; + ws.close(1002, "Invalid chunked transport"); + } }); ws.on("close", async (...args: unknown[]) => { + this.chunkedSockets.get(ws)?.close(); const code = args[0]; const reason = args[1]; await this.detachSocket(ws, { @@ -2568,7 +2630,7 @@ export class VoiceAssistantWebSocketServer { identity: JSON.stringify([connection.principalId, connection.clientId]), permissions: () => connection.session.getPermissions(), routed: () => connection.session.isRouted(), - bufferedAmount: () => ws.bufferedAmount ?? null, + bufferedAmount: () => this.socketBufferedAmount(ws), delivery: connection.session.delivery, admit: (socket, permissions) => this.attachSocket(socket, undefined, undefined, false, { diff --git a/packages/server/src/server/websocket/encrypted-relay-socket.test.ts b/packages/server/src/server/websocket/encrypted-relay-socket.test.ts index f2a880f15f..3e17f0cbb4 100644 --- a/packages/server/src/server/websocket/encrypted-relay-socket.test.ts +++ b/packages/server/src/server/websocket/encrypted-relay-socket.test.ts @@ -140,3 +140,74 @@ test("encrypted sockets do not double-count bytes already buffered by the transp expect(socket.bufferedAmount).toBe(payload.byteLength + 40); }); + +test("50 MiB logical text and routed binary cross encrypted relay frames in both directions", async () => { + const { ChunkedTransport } = await import("@getpaseo/protocol/chunked-transport"); + const { openClientSecureChannel, openDaemonSecureChannel } = await import("@getpaseo/relay/e2ee"); + const { generateKeyPair, exportPublicKey, maxSecuredPlaintextByteLength } = + await import("@getpaseo/relay"); + const { encodeHostRouteFrame, decodeHostRouteFrame } = + await import("@getpaseo/protocol/binary-frames/index"); + type Transport = import("@getpaseo/relay/e2ee").Transport; + const limit = 32 * 1024 * 1024; + const wireSizes: number[] = []; + const endpoint = (): Transport => ({ + send: () => {}, + close: () => {}, + onmessage: null, + onclose: null, + onerror: null, + }); + const left = endpoint(); + const right = endpoint(); + const wire = (destination: Transport) => (data: string | ArrayBuffer) => { + const size = typeof data === "string" ? Buffer.byteLength(data) : data.byteLength; + expect(size).toBeLessThanOrEqual(limit); + wireSizes.push(size); + queueMicrotask(() => destination.onmessage?.({ data, isBinary: typeof data !== "string" })); + }; + left.send = wire(right); + right.send = wire(left); + const key = generateKeyPair(); + const delivered: (string | Uint8Array)[][] = [[], []]; + let receivers: InstanceType[] = []; + const incoming = (index: number) => (data: string | ArrayBuffer) => + receivers[index]!.receive(typeof data === "string" ? data : new Uint8Array(data)); + const daemonPromise = openDaemonSecureChannel(right, { + daemonKeyPair: key, + events: { onmessage: incoming(1) }, + }); + const client = await openClientSecureChannel(left, { + daemonPublicKeyB64: exportPublicKey(key.publicKey), + events: { onmessage: incoming(0) }, + }); + const daemon = await daemonPromise; + receivers = [client, daemon].map( + (channel, index) => + new ChunkedTransport({ + frameBytes: maxSecuredPlaintextByteLength(limit), + send: (frame) => channel.send(typeof frame === "string" ? frame : frame.slice().buffer), + deliver: (frame) => { + delivered[index]!.push(frame); + }, + }), + ); + for (const receiver of receivers) receiver.enabled = true; + const text = "x".repeat(50 * 1024 * 1024); + wireSizes.length = 0; + await receivers[1]!.send(text); + await new Promise((resolve) => setImmediate(resolve)); + expect(delivered[0]).toEqual([text]); + expect(wireSizes.length).toBeGreaterThan(1); + const routed = encodeHostRouteFrame("route", new Uint8Array(50 * 1024 * 1024).fill(7)); + await receivers[0]!.send(routed); + await new Promise((resolve) => setImmediate(resolve)); + expect(delivered[1]).toHaveLength(1); + const received = decodeHostRouteFrame(delivered[1]![0] as Uint8Array)!; + expect(received.routeId).toBe("route"); + expect( + Buffer.from(received.payload).equals(Buffer.from(new Uint8Array(50 * 1024 * 1024).fill(7))), + ).toBe(true); + client.close(); + daemon.close(); +}, 30_000); diff --git a/packages/server/src/server/websocket/encrypted-relay-socket.ts b/packages/server/src/server/websocket/encrypted-relay-socket.ts index f11162761c..794789718c 100644 --- a/packages/server/src/server/websocket/encrypted-relay-socket.ts +++ b/packages/server/src/server/websocket/encrypted-relay-socket.ts @@ -1,3 +1,5 @@ +import { maxSecuredPlaintextByteLength } from "@getpaseo/relay"; +import { MAX_RELAY_WEBSOCKET_MESSAGE_BYTES } from "@getpaseo/protocol/websocket-message-limit"; import { EventEmitter } from "node:events"; import { MAX_PHYSICAL_SOCKET_BUFFERED_BYTES } from "./physical-socket.js"; @@ -8,6 +10,7 @@ export interface EncryptedRelayChannel { } export interface EncryptedRelaySocket { + readonly maxFrameBytes: number; readonly readyState: number; readonly bufferedAmount: number; send: (data: string | Uint8Array | ArrayBuffer) => void | Promise; @@ -43,6 +46,7 @@ export function createEncryptedRelaySocket(params: { }); return { + maxFrameBytes: maxSecuredPlaintextByteLength(MAX_RELAY_WEBSOCKET_MESSAGE_BYTES), get readyState() { return readyState; }, diff --git a/packages/server/src/server/websocket/physical-socket.test.ts b/packages/server/src/server/websocket/physical-socket.test.ts index c81b1410d6..6dce3e151d 100644 --- a/packages/server/src/server/websocket/physical-socket.test.ts +++ b/packages/server/src/server/websocket/physical-socket.test.ts @@ -120,3 +120,96 @@ test("the awaitable physical send rejects callback errors", async () => { }), ).rejects.toThrow("send failed"); }); + +test("ordinary frames expose a paused real socket's backlog and terminate at the physical backstop", async () => { + const { once } = await import("node:events"); + const { WebSocket, WebSocketServer } = await import("ws"); + const { ChunkedTransport } = await import("@getpaseo/protocol/chunked-transport"); + const server = new WebSocketServer({ host: "127.0.0.1", port: 0 }); + await once(server, "listening"); + const connected = once(server, "connection"); + const address = server.address(); + if (typeof address === "string" || !address) throw new Error("Missing server address"); + const client = new WebSocket(`ws://127.0.0.1:${address.port}`); + await once(client, "open"); + const [socket] = (await connected) as [InstanceType]; + const tcp = (socket as unknown as { _socket: import("node:net").Socket })._socket; + let terminated = false; + const transport = new ChunkedTransport({ + frameBytes: 32 * 1024 * 1024, + deliver: () => {}, + send: (frame, wait) => { + const options = { + socket, + frame, + onHighWater: () => { + terminated = true; + socket.terminate(); + }, + }; + if (wait) return sendBoundedPhysicalFrameAndWait(options).then(() => undefined); + sendBoundedPhysicalFrame(options); + }, + }); + try { + client.pause(); + tcp.cork(); + const frame = new Uint8Array(256 * 1024); + for (let count = 0; count < 200; count++) await transport.send(frame); + expect(socket.bufferedAmount).toBeGreaterThan(4 * 1024 * 1024); + expect(transport.queuedByteLength).toBe(0); + for (let count = 0; count < 100; count++) { + if (terminated) break; + await transport.send(frame); + } + expect(terminated).toBe(true); + } finally { + transport.close(); + client.terminate(); + socket.terminate(); + await new Promise((resolve) => server.close(() => resolve())); + } +}); + +test("an awaited framing failure terminates its real socket immediately", async () => { + const { once } = await import("node:events"); + const { WebSocket, WebSocketServer } = await import("ws"); + const { ChunkedTransport } = await import("@getpaseo/protocol/chunked-transport"); + const server = new WebSocketServer({ host: "127.0.0.1", port: 0 }); + await once(server, "listening"); + const connected = once(server, "connection"); + const address = server.address(); + if (typeof address === "string" || !address) throw new Error("Missing server address"); + const client = new WebSocket(`ws://127.0.0.1:${address.port}`); + await once(client, "open"); + const [socket] = (await connected) as [InstanceType]; + const tcp = (socket as unknown as { _socket: import("node:net").Socket })._socket; + const transport = new ChunkedTransport({ + frameBytes: 32 * 1024 * 1024, + deliver: () => {}, + onFailure: () => socket.terminate(), + send: (frame) => + sendBoundedPhysicalFrameAndWait({ + socket, + frame, + onHighWater: () => socket.terminate(), + }).then(() => undefined), + }); + transport.enabled = true; + try { + client.pause(); + tcp.cork(); + const closed = once(socket, "close"); + const first = transport.send(new Uint8Array(100 * 1024 * 1024), { waitForDrain: true }); + const overflow = transport.send(new Uint8Array([1]), { waitForDrain: true }); + const settled = Promise.allSettled([first, overflow]); + await closed; + expect(socket.readyState).toBe(WebSocket.CLOSED); + expect((await settled).map((result) => result.status)).toEqual(["rejected", "rejected"]); + } finally { + transport.close(); + client.terminate(); + socket.terminate(); + await new Promise((resolve) => server.close(() => resolve())); + } +}); From 0a549945b550fe7c40c154e43e74026f44445f35 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sat, 31 Oct 2026 09:45:57 +0700 Subject: [PATCH 133/173] fix(terminal): keep native text aligned with terminal cells (#8336) Shape rows in native Canvas and CoreText, then place clusters on xterm columns so fallback font advances cannot separate text from its cursor. Wait for measured dimensions before attachment and repaint overhanging ink with affected rows. Use Android platform ICU to avoid bundling approximately 14 MB of data; retain and document the Android 10 conjunct limitation. --- CLAUDE.md | 1 + docs/terminal-rendering.md | 65 +++ .../e2e/mobile/terminal-rendering/check.mjs | 311 +++++++++++++ .../e2e/mobile/terminal-rendering/fixture.mjs | 59 +++ .../mobile/terminal-rendering/identity.mjs | 423 +++++++++++++++++ .../mobile/terminal-rendering/overhang.mjs | 236 ++++++++++ .../mobile/terminal-rendering/reattach.mjs | 149 ++++++ .../e2e/mobile/terminal-rendering/render.mjs | 197 ++++++++ .../paseo-terminal/android/build.gradle | 25 ++ .../src/androidTest/assets/grapheme-rows.json | 38 ++ .../paseo/terminal/TerminalRowLayoutTest.kt | 105 +++++ .../android/src/main/AndroidManifest.xml | 1 + .../sh/paseo/terminal/PaseoTerminalModule.kt | 24 + .../sh/paseo/terminal/PaseoTerminalView.kt | 196 ++++++++ .../sh/paseo/terminal/TerminalCustomGlyphs.kt | 76 ++++ .../java/sh/paseo/terminal/TerminalFont.kt | 61 +++ .../java/sh/paseo/terminal/TerminalFrame.kt | 100 +++++ .../sh/paseo/terminal/TerminalRowLayout.kt | 306 +++++++++++++ .../app/modules/paseo-terminal/contract.ts | 60 +++ .../paseo-terminal/custom-glyphs.test.ts} | 20 +- .../paseo-terminal/custom-glyphs.ts} | 52 ++- .../paseo-terminal/expo-module.config.json | 9 + .../paseo-terminal/frame-encoding.test.ts | 34 ++ .../modules/paseo-terminal/frame-encoding.ts | 27 ++ packages/app/modules/paseo-terminal/index.tsx | 47 ++ .../paseo-terminal/ios/PaseoTerminal.podspec | 22 + .../ios/PaseoTerminalModule.swift | 21 + .../ios/PaseoTerminalView.swift | 179 ++++++++ .../ios/TerminalCustomGlyphs.swift | 73 +++ .../paseo-terminal/ios/TerminalFont.swift | 67 +++ .../paseo-terminal/ios/TerminalFrame.swift | 122 +++++ .../ios/TerminalRowLayout.swift | 335 ++++++++++++++ .../app/modules/paseo-terminal/package.json | 5 + .../terminal-emulator-native-grid.native.tsx | 13 +- .../src/terminal/native-renderer/colors.ts | 253 +++++------ .../native-renderer/terminal-frame.test.ts | 199 ++++++++ .../native-renderer/terminal-frame.ts | 84 ++++ .../terminal-grid-metrics.test.ts | 62 +-- .../native-renderer/terminal-grid-metrics.ts | 54 --- .../terminal-grid-view.native.tsx | 425 ++---------------- .../terminal-row-model.test.ts | 120 ----- .../native-renderer/terminal-row-model.ts | 253 ----------- packages/app/vitest.config.ts | 1 + 43 files changed, 3888 insertions(+), 1022 deletions(-) create mode 100644 docs/terminal-rendering.md create mode 100644 packages/app/e2e/mobile/terminal-rendering/check.mjs create mode 100644 packages/app/e2e/mobile/terminal-rendering/fixture.mjs create mode 100644 packages/app/e2e/mobile/terminal-rendering/identity.mjs create mode 100644 packages/app/e2e/mobile/terminal-rendering/overhang.mjs create mode 100644 packages/app/e2e/mobile/terminal-rendering/reattach.mjs create mode 100644 packages/app/e2e/mobile/terminal-rendering/render.mjs create mode 100644 packages/app/modules/paseo-terminal/android/build.gradle create mode 100644 packages/app/modules/paseo-terminal/android/src/androidTest/assets/grapheme-rows.json create mode 100644 packages/app/modules/paseo-terminal/android/src/androidTest/java/sh/paseo/terminal/TerminalRowLayoutTest.kt create mode 100644 packages/app/modules/paseo-terminal/android/src/main/AndroidManifest.xml create mode 100644 packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/PaseoTerminalModule.kt create mode 100644 packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/PaseoTerminalView.kt create mode 100644 packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/TerminalCustomGlyphs.kt create mode 100644 packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/TerminalFont.kt create mode 100644 packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/TerminalFrame.kt create mode 100644 packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/TerminalRowLayout.kt create mode 100644 packages/app/modules/paseo-terminal/contract.ts rename packages/app/{src/terminal/native-renderer/terminal-custom-glyph.test.ts => modules/paseo-terminal/custom-glyphs.test.ts} (81%) rename packages/app/{src/terminal/native-renderer/terminal-custom-glyph.ts => modules/paseo-terminal/custom-glyphs.ts} (66%) create mode 100644 packages/app/modules/paseo-terminal/expo-module.config.json create mode 100644 packages/app/modules/paseo-terminal/frame-encoding.test.ts create mode 100644 packages/app/modules/paseo-terminal/frame-encoding.ts create mode 100644 packages/app/modules/paseo-terminal/index.tsx create mode 100644 packages/app/modules/paseo-terminal/ios/PaseoTerminal.podspec create mode 100644 packages/app/modules/paseo-terminal/ios/PaseoTerminalModule.swift create mode 100644 packages/app/modules/paseo-terminal/ios/PaseoTerminalView.swift create mode 100644 packages/app/modules/paseo-terminal/ios/TerminalCustomGlyphs.swift create mode 100644 packages/app/modules/paseo-terminal/ios/TerminalFont.swift create mode 100644 packages/app/modules/paseo-terminal/ios/TerminalFrame.swift create mode 100644 packages/app/modules/paseo-terminal/ios/TerminalRowLayout.swift create mode 100644 packages/app/modules/paseo-terminal/package.json create mode 100644 packages/app/src/terminal/native-renderer/terminal-frame.test.ts create mode 100644 packages/app/src/terminal/native-renderer/terminal-frame.ts delete mode 100644 packages/app/src/terminal/native-renderer/terminal-row-model.test.ts delete mode 100644 packages/app/src/terminal/native-renderer/terminal-row-model.ts diff --git a/CLAUDE.md b/CLAUDE.md index 9a2c70de29..71682af7e9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -52,6 +52,7 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the | [docs/connected-hosts.md](docs/connected-hosts.md) | Daemon-owned host registrations, routed SDK scopes, identity and authority boundaries | | [docs/permissions.md](docs/permissions.md) | Semantic daemon permissions, principals, credentials, pairing invitations, and Hub authority | | [docs/terminal-performance.md](docs/terminal-performance.md) | Terminal latency pipeline, coalescing/backpressure invariants, benchmark + perf spec usage | +| [docs/terminal-rendering.md](docs/terminal-rendering.md) | Native terminal view: xterm owns the grid, cluster placement, emoji widths, mixed-direction limits, render regression | | [docs/agent-stream-performance.md](docs/agent-stream-performance.md) | Assistant text pipeline — coalescing window, paced reveal, why arrival lumps are smoothed at render | | [docs/markdown-renderer.md](docs/markdown-renderer.md) | Shared Markdown engine, native selection, links, images and library constraints | | [docs/native-text-selection.md](docs/native-text-selection.md) | Native diagram grouping, selection boundaries and leading inline image limitations | diff --git a/docs/terminal-rendering.md b/docs/terminal-rendering.md new file mode 100644 index 0000000000..fd304aa144 --- /dev/null +++ b/docs/terminal-rendering.md @@ -0,0 +1,65 @@ +# Terminal rendering + +Web and Electron draw terminals with xterm.js. iOS and Android keep an `@xterm/headless` buffer in JS and draw it with the `PaseoTerminal` native view in `packages/app/modules/paseo-terminal`: CoreText on iOS, `Canvas.drawTextRun` on Android. `src/terminal/native-renderer/terminal-frame.ts` turns the visible buffer into frames, and both native views take the same props. + +## xterm owns the grid + +xterm decides which column every cell occupies. The native views never let text advance move a cell. Each row is shaped once, one run per font face, so Hangul jamo, ligatures, combining marks, conjuncts and fallback fonts see their neighbours. Each shaped cluster is then drawn at its first cell's column, centred in the columns it owns, and scaled down when its glyphs are wider. Cursor, selection, hit-testing and copy all use xterm's columns, so they stay correct whatever the font does. + +A cluster is the run of cells the shaper merged, and it is drawn once from the shaped row. Drawing part of a cluster on its own reshapes it: a half-form conjunct such as `स्ते` comes apart into `स्` with a visible virama. So colour and selection never split a cluster. A cluster whose cells differ in colour is drawn once per colour, clipped to that colour's columns. + +Android also groups cells with `android.icu.text.BreakIterator`, because Minikin's advances and cursor boundaries alone split some conjuncts. Grapheme rules follow the OS ICU version. Android 10 (API 29) splits `स्ते` after the virama and renders it incorrectly. The tested corpus passed on API 33, 34 and 35; API 30–32 have not been tested. We accept that version-dependent limitation to avoid bundling approximately 14 MB of ICU4J data. CoreText keeps this conjunct together on iOS. This renderer does not guarantee identical shaping across OS versions. + +`TerminalRowLayoutTest.kt` is the Android regression test. It draws the rows of `grapheme-rows.json` and compares each with its grapheme clusters drawn one at a time, and with a wrong clustering that must not match. `terminal-frame.test.ts` checks that those rows are what xterm produces and that the clusters are UAX #29 grapheme clusters. Run it with `./gradlew :paseo-terminal:connectedDebugAndroidTest` from `packages/app/android`, with `ANDROID_SERIAL` set. + +The view reports ready only after it has measured its grid size. The pane attaches with that size, so the daemon replays the terminal at the client's size. Before this, the replay arrived at the PTY's old size, the resize came after it, and the shell's redraw landed on the wrong rows. + +Emoji widths come from the headless buffer, which uses xterm's default Unicode 6 table. `👍` gets one column, and `👋🏽` and `🇰🇷` get two cells drawn as one cluster. Web loads the Unicode 11 addon, so the same output can wrap differently on web and native. + +## Ink outside the row + +Marks stacked above or below a letter, Arabic letter tails and some fallback glyphs ink into the rows next to theirs. Neither view clips a row to its own bounds, because a row clip also cuts marks and Arabic dots. Rows draw top to bottom, so a later row's cell backgrounds cover the ink that reaches into it. + +Android redraws every row on each frame, so overhanging ink cannot go stale. Its row `RenderNode`s are created with `setClipToBounds(false)`. The default would clip only unselected rows, because selected rows are drawn straight onto the view's canvas. + +iOS repaints only the rows that changed. Each `TerminalRowLayout` records how far its glyphs ink above and below the row. A changed row invalidates its old and new ink extent, and `draw(_:)` redraws every row whose ink extent meets the dirty rect. Invalidating only the row's own rect left an erased row's marks in the row next to it, erased a neighbour's marks when a row was rewritten, and showed or hid overhang depending on which rows changed together. + +## Mixed-direction text + +Rows draw left to right in logical order on both platforms. Terminal bidi escape modes are not implemented. On iOS the row needs both the `kCTWritingDirection` override and an LTR paragraph base direction. Without the base direction, bidi rule L1 moves trailing spaces ahead of a row that starts with Arabic or Hebrew, and the whole row shifts. + +Arabic still gets the contextual form its logical neighbours select, but in left-to-right order, so letters join on the wrong side. Correct visual Arabic needs implicit bidi per row: reorder RTL runs for display and map cursor, selection and hit-testing through the visual-to-logical index. That changes which column a character appears in, so it has to be decided as product behaviour first. Shaping alone cannot fix it. + +## Render regression + +The scripts live in `packages/app/e2e/mobile/terminal-rendering`. Run them from `packages/app` on the daemon's host, starting from an idle, focused terminal with an empty prompt. + +`render.mjs` prints a mixed-script fixture, screenshots it with agent-device, and checks the geometry with `check.mjs`. The check rebuilds the expected buffer with `@xterm/headless` and measures the grid from a ruler row. It checks that: + +- every grapheme cluster has ink inside its own columns, and blank cells stay blank; +- on the accent rows, every cell is drawn in its own colour, including cells inside one cluster; +- the cursor is drawn after the text; +- every row is exposed as `terminal-row-`; +- selecting one cell of a conjunct highlights only that cell. + +On iOS the screenshot is taken at 3 pixels per point (`PASEO_TERMINAL_RENDERING_PIXEL_DENSITY`), because the simulator's default is one pixel per point and a glyph is then about 12 pixels. Focus the terminal before a run: with the simulator's hardware keyboard connected the key bar shows without a focused input, and `type` fails. In a debug build, the dev client's floating gear button covers the right end of the first row, so ruler cells there fail. + +```bash +PLATFORM=android ANDROID_SERIAL=emulator-5554 node e2e/mobile/terminal-rendering/render.mjs +PLATFORM=ios IOS_DEVICE="iPhone 17" node e2e/mobile/terminal-rendering/render.mjs +``` + +Geometry passes when a cell holds the wrong glyph. `identity.mjs` judges each cluster of a `render.mjs` run against pango's rendering of the same characters in the device's fonts. The reference is cut at the edges of the cluster's columns, placed as the renderer places it, because glyphs such as Devanagari letters ink past their advance and the device cuts them there too. A shape passes when its coverage correlates with its own reference at 0.6 or more, and no other cluster of the corpus matches it better. Box and block characters are judged against their Unicode definition. Shades are judged by even density over a 4×4 grid, because the device and pango fall back to different shade fonts. Clusters that pango draws without ink are reported as unjudged instead: flags on both platforms and Apple Color Emoji. The `rect` and `swap` controls fill every cluster with white, or judge each one against another cluster. Both must fail every cluster, which shows the oracle refuses ink that is present but wrong. An Arabic letter is compared with all four of its positional forms, so the oracle shows the right letter is drawn, not that it has the right form. Ink that a neighbouring row draws into a cluster's cells counts as that cluster's ink. On iOS the tail of `م` in the Arabic row reaches one pixel into the `न` below it, so `न` fails although both rows are drawn correctly. + +```bash +FONTCONFIG_FILE=fonts.conf node e2e/mobile/terminal-rendering/identity.mjs [none|rect|swap] +``` + +`fonts.conf` points fontconfig at the device's font files and lists, for `monospace`, the terminal font followed by the device's fallbacks for Hangul, Arabic, Devanagari, CJK, emoji and symbols: + +- **Android:** pull the fonts from `/system/fonts` with `adb pull`. The terminal font is Droid Sans Mono. +- **iOS:** copy the simulator runtime's fonts from `RuntimeRoot/System/Library/Fonts`. The terminal font is Menlo. PingFang stores its outlines in Apple's `hvgl` table, which FreeType cannot draw, so the CJK references come from Apple SD Gothic Neo instead. `語` then scores below the threshold although the device draws it correctly. + +`overhang.mjs` prints rows whose marks reach the rows next to them. In one update it writes into two rows that hold a neighbour's marks and erases two rows whose marks reach a blank row. The marks must be drawn before the update, stay drawn in the written rows, and leave no ink behind the erased rows. Run it like `render.mjs`. + +`reattach.mjs` checks the restore size. It changes the PTY size by opening the keyboard (`RESIZE=keyboard`) or folding an Android foldable (`RESIZE=fold`), relaunches the app, and compares the client's rows with `paseo terminal capture`. A trial where no terminal rows appear, for example after a launch crash, counts as never attached and fails the run. diff --git a/packages/app/e2e/mobile/terminal-rendering/check.mjs b/packages/app/e2e/mobile/terminal-rendering/check.mjs new file mode 100644 index 0000000000..fbf4529bb3 --- /dev/null +++ b/packages/app/e2e/mobile/terminal-rendering/check.mjs @@ -0,0 +1,311 @@ +import assert from "node:assert/strict"; +import { writeFileSync } from "node:fs"; +import xterm from "@xterm/headless"; +import { PNG } from "pngjs"; +import { ACCENT, fixtureLines, fixtureOutput, RULER_CELLS, SELECT_LINE } from "./fixture.mjs"; + +/** A pixel is ink when one channel differs from the terminal background by more than this. */ +const INK_THRESHOLD = 70; +/** Ink pixels a printed grapheme cluster needs inside its own columns. */ +const MIN_CLUSTER_INK = 3; +/** How far a pixel may sit from the background-to-color blend line and still count as that color. */ +const BLEND_TOLERANCE = 40; +/** Pixels of another cell's color tolerated in a cell, for antialiasing at the cell edge. */ +const MAX_FOREIGN_INK = 2; + +const graphemes = new Intl.Segmenter("und", { granularity: "grapheme" }); + +/** + * Checks a screenshot of the fixture against the cells xterm assigns: every printed grapheme + * cluster has ink inside its own columns, blank cells stay blank, and the cursor sits right after + * the text. A cluster that spans cells, such as a Devanagari conjunct, is shaped as one unit, so + * it is judged across all its columns. On rows that use the fixture's accent color, every cell + * must be drawn in its own color, including cells that share a shaped cluster. + * + * These are geometry and color checks: they cannot tell a correct glyph from a wrong one. + * + * `rows` maps a terminal row index to its rect in screenshot pixels. + */ +export async function checkTerminalScreenshot({ png, size, rows }) { + const terminal = await fixtureTerminal(size); + assert.ok(rows.get(0), "The ruler row is not exposed as terminal-row-0"); + const grid = measureGrid(png, rows.get(0)); + const { failures, slots } = checkRows({ png, terminal, rows, grid }); + terminal.dispose(); + return { grid, failures, slots }; +} + +/** Where the harness selects: the first cell of the conjunct that starts the `select` line. */ +export async function selectionTarget({ size }) { + const terminal = await fixtureTerminal(size); + const row = lineNames(terminal.buffer.active, terminal.buffer.active.cursorY + 1).indexOf( + SELECT_LINE, + ); + terminal.dispose(); + return { row, col: 0, clusterColumns: 2 }; +} + +/** + * Checks a screenshot taken with only the first cell of the `select` conjunct selected: that cell + * has the selection background and the conjunct's second, unselected cell keeps its accent color. + */ +export function checkPartialSelection({ png, rows, grid, target }) { + const rect = rows.get(target.row); + if (!rect) return [{ row: target.row, kind: "missing-row" }]; + const cell = (col) => ({ + left: grid.left + col * grid.cellWidth + 1, + right: grid.left + (col + 1) * grid.cellWidth - 1, + top: rect.y, + bottom: rect.y + rect.height, + }); + const selected = cell(target.col); + const unselected = cell(target.col + 1); + const selectionBackground = pixelAt(png, selected.left + 1, selected.top + 1); + const unselectedBackground = pixelAt(png, unselected.left + 1, unselected.top + 1); + if ( + !differs(selectionBackground, grid.background) || + differs(unselectedBackground, grid.background) + ) { + return [{ row: target.row, col: target.col, kind: "selection-not-set-up" }]; + } + const failures = []; + const ownInk = countColor(png, unselected, grid.background, ACCENT); + if (ownInk < MIN_CLUSTER_INK) { + failures.push({ row: target.row, col: target.col + 1, kind: "unselected-cell-lost-color" }); + } + return failures; +} + +async function fixtureTerminal(size) { + const terminal = new xterm.Terminal({ + cols: size.columns, + rows: size.rows, + allowProposedApi: true, + }); + await new Promise((done) => + terminal.write(fixtureOutput(size.columns).replaceAll("\n", "\r\n"), done), + ); + return terminal; +} + +export function writeOverlay(png, slots, path) { + const out = new PNG({ width: png.width, height: png.height }); + png.data.copy(out.data); + for (const slot of slots) { + const color = slot.ok ? [0, 200, 0] : [255, 0, 0]; + const { left, right, top, bottom } = slot.box; + for (let x = Math.ceil(left); x < right; x += 1) { + for (const y of [Math.ceil(top), Math.floor(bottom) - 1]) { + const offset = (out.width * y + x) * 4; + out.data.set(color, offset); + } + } + if (!slot.ok) { + for (let y = Math.ceil(top); y < bottom; y += 1) { + for (const x of [Math.ceil(left), Math.floor(right) - 1]) { + out.data.set(color, (out.width * y + x) * 4); + } + } + } + } + writeFileSync(path, PNG.sync.write(out)); +} + +function inkAt(png, x, y, background) { + const offset = (png.width * Math.round(y) + Math.round(x)) * 4; + return ( + Math.abs(png.data[offset] - background[0]) > INK_THRESHOLD || + Math.abs(png.data[offset + 1] - background[1]) > INK_THRESHOLD || + Math.abs(png.data[offset + 2] - background[2]) > INK_THRESHOLD + ); +} + +/** Pixels in `box` that differ from `background` in some channel by more than the ink threshold. */ +export function countInk(png, box, background) { + let count = 0; + for (let y = Math.ceil(box.top); y < Math.floor(box.bottom); y += 1) { + for (let x = Math.ceil(box.left); x < Math.floor(box.right); x += 1) { + if (inkAt(png, x, y, background)) count += 1; + } + } + return count; +} + +function differs(a, b) { + return a.some((channel, index) => Math.abs(channel - b[index]) > INK_THRESHOLD); +} + +/** Distance from `pixel` to the nearest blend of `background` toward `color`. */ +function blendDistance(pixel, background, color) { + const direction = color.map((channel, index) => channel - background[index]); + const length = direction.reduce((sum, value) => sum + value * value, 0); + const offset = pixel.map((channel, index) => channel - background[index]); + const along = offset.reduce((sum, value, index) => sum + value * direction[index], 0); + const alpha = length === 0 ? 0 : Math.min(1, Math.max(0, along / length)); + return Math.hypot(...offset.map((value, index) => value - alpha * direction[index])); +} + +/** Ink pixels in `box` that are a blend of the background toward `color`. */ +function countColor(png, box, background, color, other) { + let count = 0; + for (let y = Math.ceil(box.top); y < Math.floor(box.bottom); y += 1) { + for (let x = Math.ceil(box.left); x < Math.floor(box.right); x += 1) { + if (!inkAt(png, x, y, background)) continue; + const pixel = pixelAt(png, x, y); + const distance = blendDistance(pixel, background, color); + if (distance > BLEND_TOLERANCE) continue; + if (other && blendDistance(pixel, background, other) <= distance) continue; + count += 1; + } + } + return count; +} + +function pixelAt(png, x, y) { + const offset = (png.width * Math.round(y) + Math.round(x)) * 4; + return [png.data[offset], png.data[offset + 1], png.data[offset + 2]]; +} + +/** Reads the grid origin and cell width from a ruler row of `RULER_CELLS` full blocks. */ +export function measureGrid(png, rulerRect) { + const y = rulerRect.y + rulerRect.height / 2; + const background = pixelAt(png, rulerRect.x + rulerRect.width - 2, y); + let left = -1; + let right = -1; + for (let x = Math.ceil(rulerRect.x); x < rulerRect.x + rulerRect.width; x += 1) { + if (!inkAt(png, x, y, background)) continue; + if (left < 0) left = x; + right = x + 1; + } + assert.ok(left >= 0, "The ruler row has no ink"); + const foreground = pixelAt(png, Math.round((left + right) / 2), y); + return { left, cellWidth: (right - left) / RULER_CELLS, background, foreground }; +} + +function lineNames(buffer, count) { + const names = fixtureLines(0).map((line) => line.name); + const result = []; + let index = -1; + for (let row = 0; row < count; row += 1) { + if (!buffer.getLine(row).isWrapped) index += 1; + result.push(names[index] ?? `line-${index}`); + } + return result; +} + +/** The row's printed cells, consecutive cells of one grapheme cluster grouped together. */ +function rowClusters(line, columns, cell) { + const cells = []; + let text = ""; + for (let col = 0; col < columns; col += 1) { + line.getCell(col, cell); + const width = cell.getWidth(); + if (width === 0) continue; + const chars = cell.getChars() || " "; + cells.push({ + col, + width, + chars, + offset: text.length, + painted: cell.isInverse() || !cell.isBgDefault(), + accent: cell.isFgRGB() && cell.getFgColor() === rgbValue(ACCENT), + }); + text += chars; + } + const clusterEnds = [...graphemes.segment(text)].map( + (segment) => segment.index + segment.segment.length, + ); + const clusters = []; + let end = 0; + for (const entry of cells) { + while (entry.offset >= clusterEnds[end]) end += 1; + const last = clusters.at(-1); + if (last && last.end === end) last.cells.push(entry); + else clusters.push({ end, cells: [entry] }); + } + return clusters.map((cluster) => cluster.cells); +} + +function rgbValue([red, green, blue]) { + return (red << 16) | (green << 8) | blue; +} + +/** Each cell of a cluster that uses the accent color holds ink of its own color only. */ +function checkClusterColors({ png, cluster, rect, grid }) { + const kinds = []; + for (const entry of cluster) { + const box = { + left: grid.left + entry.col * grid.cellWidth + 1, + right: grid.left + (entry.col + entry.width) * grid.cellWidth - 1, + top: rect.y, + bottom: rect.y + rect.height, + }; + const [color, other] = entry.accent ? [ACCENT, grid.foreground] : [grid.foreground, ACCENT]; + const own = countColor(png, box, grid.background, color, other); + const foreign = countColor(png, box, grid.background, other, color); + if (own < MIN_CLUSTER_INK || foreign > MAX_FOREIGN_INK) { + kinds.push({ col: entry.col, kind: entry.accent ? "accent-color-lost" : "color-leaked" }); + } + } + return kinds; +} + +function checkRows({ png, terminal, rows, grid }) { + const buffer = terminal.buffer.active; + const lastRow = buffer.cursorY; + const names = lineNames(buffer, lastRow + 1); + const failures = []; + const slots = []; + const cell = buffer.getNullCell(); + for (let row = 0; row <= lastRow; row += 1) { + const rect = rows.get(row); + if (!rect) { + failures.push({ row, line: names[row], kind: "missing-row" }); + continue; + } + const clusters = rowClusters(buffer.getLine(row), terminal.cols, cell); + // Color is judged on whole rows that use the accent, so a color leaking into a neighbouring + // default-colored cell fails too. + const checksColor = clusters.some((cluster) => cluster.some((entry) => entry.accent)); + for (const cluster of clusters) { + const first = cluster[0]; + const columns = cluster.reduce((sum, entry) => sum + entry.width, 0); + const left = grid.left + first.col * grid.cellWidth; + const right = left + columns * grid.cellWidth; + const box = { left: left + 1, right: right - 1, top: rect.y, bottom: rect.y + rect.height }; + const chars = cluster.map((entry) => entry.chars).join(""); + const isCursor = row === lastRow && first.col === buffer.cursorX; + let kind = null; + if (isCursor) { + const covered = countInk(png, box, grid.background); + const area = (box.right - box.left) * (box.bottom - box.top); + if (covered < area * 0.25) kind = "cursor-not-drawn"; + } else if (chars.trim() !== "") { + if (countInk(png, box, grid.background) < MIN_CLUSTER_INK) kind = "missing-ink"; + } else if (!cluster.some((entry) => entry.painted)) { + const quarter = (right - left) / 4; + const center = { ...box, left: left + quarter, right: right - quarter }; + if (countInk(png, center, grid.background) > 0) kind = "ink-in-blank"; + } + const colorFailures = + kind === null && checksColor && chars.trim() !== "" + ? checkClusterColors({ png, cluster, rect, grid }) + : []; + slots.push({ + row, + line: names[row], + col: first.col, + width: columns, + chars, + isCursor, + box, + ok: kind === null && colorFailures.length === 0, + }); + if (kind) failures.push({ row, line: names[row], col: first.col, char: chars, kind }); + for (const failure of colorFailures) { + failures.push({ row, line: names[row], char: chars, ...failure }); + } + } + } + return { failures, slots }; +} diff --git a/packages/app/e2e/mobile/terminal-rendering/fixture.mjs b/packages/app/e2e/mobile/terminal-rendering/fixture.mjs new file mode 100644 index 0000000000..e4ff5c2bb4 --- /dev/null +++ b/packages/app/e2e/mobile/terminal-rendering/fixture.mjs @@ -0,0 +1,59 @@ +// Terminal output covering the scripts and styles the native renderer must place on the grid. +// Each entry is one line of output; `ruler` is drawn with full blocks so the harness can read +// the grid origin and cell width from pixels, independent of the renderer under test. + +const ESC = "\u001b"; +const sgr = (codes, text) => `${ESC}[${codes}m${text}${ESC}[0m`; + +export const RULER_CELLS = 20; +/** A foreground no theme uses, so its pixels can be told apart from default text. */ +export const ACCENT = [255, 64, 160]; +const accent = (text) => sgr(`38;2;${ACCENT.join(";")}`, text); +/** + * The `select` line starts with a conjunct whose first cell the harness selects on its own. Its + * second cell uses the accent, which no theme's selection foreground matches. + */ +export const SELECT_LINE = "select"; + +export function fixtureLines(columns) { + const wrapSyllables = Math.ceil(columns / 2) + 6; + return [ + { name: "ruler", text: "█".repeat(RULER_CELLS) }, + { name: "ascii", text: "ASCII abcdefghij 0123456789 end" }, + { name: "hangul-mixed", text: "한글 문장 Hello end" }, + { name: "hangul-color-boundary", text: `안녕하세요${sgr(31, "NEXT")} end` }, + { name: "hangul-bold-boundary", text: `${sgr(1, "안녕하세요")}NEXT end` }, + { name: "hangul-decomposed", text: "한글 end" }, + { name: "cjk", text: "日本語テキスト 中文字符 end" }, + { name: "combining", text: "é ä ñ x̣̂ end" }, + { name: "arabic", text: "مرحبا لا 123 abc end" }, + { name: "devanagari", text: "नमस्ते क्षत्रिय end" }, + { name: "emoji", text: "👍 ❤️ 👋🏽 👩‍💻 🇰🇷 end" }, + // One shaped cluster over two cells, colored per cell: the color must follow the cell. + { name: "split-color", text: `क्${accent("ष")} ${accent("क्")}ष ल${accent("ا")} end` }, + { name: SELECT_LINE, text: `क्${accent("ष")} end` }, + { name: "box", text: "╭──┬──╮ │ab│cd│ ╰──┴──╯ ▀▄▌▐░▒▓ end" }, + { + name: "styles", + text: [ + sgr(1, "bold"), + sgr(3, "italic"), + sgr(4, "under"), + sgr(7, "inverse"), + sgr(42, "bg"), + sgr(9, "strike"), + "end", + ].join(" "), + }, + { name: "hangul-wrap", text: "가".repeat(wrapSyllables) }, + // The last line has no newline: the shell sleeps with the cursor right after it. + { name: "cursor", text: "> 안녕하세요" }, + ]; +} + +/** The bytes `cat` writes; the tty turns each newline into CR LF. */ +export function fixtureOutput(columns) { + return fixtureLines(columns) + .map((line) => line.text) + .join("\n"); +} diff --git a/packages/app/e2e/mobile/terminal-rendering/identity.mjs b/packages/app/e2e/mobile/terminal-rendering/identity.mjs new file mode 100644 index 0000000000..a0a6246a3d --- /dev/null +++ b/packages/app/e2e/mobile/terminal-rendering/identity.mjs @@ -0,0 +1,423 @@ +import { execFileSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { resolve } from "node:path"; +import { PNG } from "pngjs"; +import { checkTerminalScreenshot } from "./check.mjs"; + +// Checks that every printed cluster of a `render.mjs` run is the right glyph. `check.mjs` proves +// where ink lands and what color it has; this compares each cluster's ink with pango's (HarfBuzz) +// rendering of the same characters in the device's own fonts, so a wrong glyph, tofu, a solid +// block, a split conjunct or a cluster from elsewhere fails. +// +// FONTCONFIG_FILE= node e2e/mobile/terminal-rendering/identity.mjs [control] +// +// The fonts.conf lists the device's font files and prefers, for `monospace`, the terminal font +// followed by the device's fallbacks; `docs/terminal-rendering.md` says how to build one. Needs +// `pango-view` on the PATH. +// +// control: +// none judge the screenshot (default); exits 1 when a cluster fails. +// rect first fill every judged cluster's box with white; exits 1 unless every cluster fails. +// swap judge each cluster against a different cluster of the corpus; exits 1 unless every +// cluster fails. +// The two controls prove the oracle refuses ink that is present but wrong. + +/** Coverage grid side used to compare shapes. */ +const GRID = 16; +/** A pixel at or above this ink strength (0..1) is part of a glyph's bounding box. */ +const INK = 0.25; +/** Lowest shape correlation a cluster may have with its own reference. */ +const THRESHOLD = 0.6; +/** How much better another cluster may match before the cluster's own match stops counting. */ +const MARGIN = 0.02; +/** Lines whose cells carry decorations or a custom-drawn ruler; they stay geometry-only. */ +const SKIPPED_LINES = new Set(["ruler", "styles"]); +const ZWJ = "‍"; + +/** + * The renderer draws box and block characters to fill the cell, so they are judged against their + * Unicode definition. Shades come from the font, whose fallback differs between the device and + * pango, so a shade is judged by how evenly and densely it inks its own bounding box. Fonts dither + * differently: ░ ▒ ▓ measure 0.16, 0.31, 0.75 in Droid Sans Mono and 0.19, 0.50, 0.81 in Menlo. The + * bands split between those, and do not overlap, so one shade never passes as another. + */ +const CELL_GLYPHS = { + "─": { arms: "LR" }, + "│": { arms: "UD" }, + "┬": { arms: "LRD" }, + "┴": { arms: "LRU" }, + "╭": { arms: "DR" }, + "╮": { arms: "DL" }, + "╰": { arms: "UR" }, + "╯": { arms: "UL" }, + "▀": { fill: "top" }, + "▄": { fill: "bottom" }, + "▌": { fill: "left" }, + "▐": { fill: "right" }, + "░": { shade: [0.08, 0.25] }, + "▒": { shade: [0.25, 0.625] }, + "▓": { shade: [0.625, 0.9] }, +}; +/** A shade must ink each region of this grid over its bounding box within its band. */ +const SHADE_GRID = 4; +/** Regions of the cell, as fractions [left, top, right, bottom], that a line to each edge crosses. */ +const ARM_REGIONS = { + U: [0.3, 0, 0.7, 0.2], + D: [0.3, 0.8, 0.7, 1], + L: [0, 0.3, 0.2, 0.7], + R: [0.8, 0.3, 1, 0.7], +}; +/** [filled, empty] halves of each half block. */ +const HALVES = { + top: [ + [0, 0, 1, 0.5], + [0, 0.5, 1, 1], + ], + bottom: [ + [0, 0.5, 1, 1], + [0, 0, 1, 0.5], + ], + left: [ + [0, 0, 0.5, 1], + [0.5, 0, 1, 1], + ], + right: [ + [0.5, 0, 1, 1], + [0, 0, 0.5, 1], + ], +}; + +const [dirArg, control = "none"] = process.argv.slice(2); +if (!dirArg || !["none", "rect", "swap"].includes(control)) { + throw new Error("Usage: identity.mjs [none|rect|swap]"); +} +const dir = resolve(dirArg); +const report = JSON.parse(readFileSync(resolve(dir, "report.json"), "utf8")); +const png = PNG.sync.read(readFileSync(resolve(dir, "terminal.png"))); +const rows = new Map(report.rows.map((row) => [row.index, row.rect])); +const { grid, slots } = await checkTerminalScreenshot({ png, size: report.size, rows }); + +const printed = slots.filter( + (slot) => !SKIPPED_LINES.has(slot.line) && !slot.isCursor && slot.chars.trim() !== "", +); +/** The columns xterm gives each printed cluster. */ +const columnsOf = new Map(printed.map((slot) => [slot.chars, slot.width])); + +if (control === "rect") { + for (const { box } of printed) { + for (let y = Math.ceil(box.top); y < Math.floor(box.bottom); y += 1) { + for (let x = Math.ceil(box.left); x < Math.floor(box.right); x += 1) { + png.data.set([255, 255, 255, 255], (png.width * y + x) * 4); + } + } + } +} + +/** Ink strength 0..1 of each pixel in a box: the largest channel distance from the background. */ +function screenshotInk(box) { + const left = Math.ceil(box.left); + const top = Math.ceil(box.top); + const width = Math.floor(box.right) - left; + const height = Math.floor(box.bottom) - top; + const ink = new Float32Array(width * height); + for (let y = 0; y < height; y += 1) { + for (let x = 0; x < width; x += 1) { + const offset = (png.width * (top + y) + left + x) * 4; + let distance = 0; + for (let channel = 0; channel < 3; channel += 1) { + distance = Math.max( + distance, + Math.abs(png.data[offset + channel] - grid.background[channel]), + ); + } + ink[y * width + x] = distance / 255; + } + } + return { ink, width, height }; +} + +/** Ink of the slot's whole cells, scaled so the foreground color is 1. */ +function cellInk(slot) { + const left = Math.round(grid.left + slot.col * grid.cellWidth); + const right = Math.round(grid.left + (slot.col + slot.width) * grid.cellWidth); + const cells = screenshotInk({ left, right, top: slot.box.top, bottom: slot.box.bottom }); + const full = + Math.max(...[0, 1, 2].map((c) => Math.abs(grid.foreground[c] - grid.background[c]))) / 255; + for (let i = 0; i < cells.ink.length; i += 1) cells.ink[i] = Math.min(1, cells.ink[i] / full); + return cells; +} + +const scratch = mkdtempSync(resolve(tmpdir(), "terminal-identity-")); +/** pango-view sizes its image to the text's advance plus this margin on each side. */ +const REFERENCE_MARGIN = 48; +function pangoInk(text) { + const out = resolve(scratch, "reference.png"); + execFileSync("pango-view", [ + "--no-display", + "--dpi=72", + "--font=monospace 96px", + `--text=${text}`, + "--background=black", + "--foreground=white", + `--margin=${REFERENCE_MARGIN}`, + "-o", + out, + ]); + const image = PNG.sync.read(readFileSync(out)); + const ink = new Float32Array(image.width * image.height); + for (let i = 0; i < ink.length; i += 1) { + const o = i * 4; + ink[i] = Math.max(image.data[o], image.data[o + 1], image.data[o + 2]) / 255; + } + return { + ink, + width: image.width, + height: image.height, + advance: image.width - 2 * REFERENCE_MARGIN, + }; +} + +/** The terminal font's cell advance at the reference size. */ +const referenceCell = pangoInk("M").advance; + +/** + * The text as the renderer places it in `columns` cells: centred, scaled down when its advance is + * wider, and cut at the cells' edges. Glyphs whose ink overhangs their advance, such as Devanagari + * headlines, are cut on the device too. + */ +function referenceInk(text, columns) { + const image = pangoInk(text); + const box = Math.max(image.advance, columns * referenceCell); + const left = Math.round(REFERENCE_MARGIN + (image.advance - box) / 2); + const right = Math.round(REFERENCE_MARGIN + (image.advance + box) / 2); + for (let y = 0; y < image.height; y += 1) { + for (let x = 0; x < image.width; x += 1) { + if (x < left || x >= right) image.ink[y * image.width + x] = 0; + } + } + return image; +} + +function regionInk({ ink, width, height }, [x0, y0, x1, y1]) { + let [sum, max, count] = [0, 0, 0]; + for (let y = Math.floor(y0 * height); y < Math.ceil(y1 * height); y += 1) { + for (let x = Math.floor(x0 * width); x < Math.ceil(x1 * width); x += 1) { + const value = ink[y * width + x] ?? 0; + sum += value; + max = Math.max(max, value); + count += 1; + } + } + return { mean: sum / count, max }; +} + +function inkBox({ ink, width, height }) { + let [minX, minY, maxX, maxY] = [width, height, -1, -1]; + for (let y = 0; y < height; y += 1) { + for (let x = 0; x < width; x += 1) { + if (ink[y * width + x] < INK) continue; + minX = Math.min(minX, x); + maxX = Math.max(maxX, x); + minY = Math.min(minY, y); + maxY = Math.max(maxY, y); + } + } + return maxX < 0 ? null : { x: minX, y: minY, width: maxX - minX + 1, height: maxY - minY + 1 }; +} + +/** Whether an unbroken line crosses the region to the cell edge: a row for L/R, a column for U/D. */ +function lineCrosses({ ink, width, height }, arm) { + const [x0, y0, x1, y1] = ARM_REGIONS[arm]; + const [left, top, right, bottom] = [ + Math.floor(x0 * width), + Math.floor(y0 * height), + Math.ceil(x1 * width), + Math.ceil(y1 * height), + ]; + const horizontal = arm === "L" || arm === "R"; + const [outerFrom, outerTo, innerFrom, innerTo] = horizontal + ? [top, bottom, left, right] + : [left, right, top, bottom]; + for (let outer = outerFrom; outer < outerTo; outer += 1) { + let unbroken = true; + for (let inner = innerFrom; inner < innerTo && unbroken; inner += 1) { + const [x, y] = horizontal ? [inner, outer] : [outer, inner]; + unbroken = (ink[y * width + x] ?? 0) >= 0.5; + } + if (unbroken) return true; + } + return false; +} + +/** 1 when the cell matches the character's definition, 0 otherwise. */ +function cellGlyphScore(slot, spec) { + const ink = cellInk(slot); + if (spec.arms) { + const matches = Object.keys(ARM_REGIONS).every((arm) => + spec.arms.includes(arm) ? lineCrosses(ink, arm) : regionInk(ink, ARM_REGIONS[arm]).max < 0.3, + ); + return matches ? 1 : 0; + } + if (spec.fill) { + const [filled, empty] = HALVES[spec.fill].map((region) => regionInk(ink, region).mean); + return filled >= 0.8 && empty <= 0.2 ? 1 : 0; + } + const box = inkBox(ink); + if (!box || box.width < 0.7 * ink.width || box.height < 0.5 * ink.height) return 0; + const [x0, y0] = [box.x / ink.width, box.y / ink.height]; + const [x1, y1] = [(box.x + box.width) / ink.width, (box.y + box.height) / ink.height]; + const [w, h] = [(x1 - x0) / SHADE_GRID, (y1 - y0) / SHADE_GRID]; + const regions = Array.from({ length: SHADE_GRID * SHADE_GRID }, (_, index) => { + const [gx, gy] = [index % SHADE_GRID, Math.floor(index / SHADE_GRID)]; + return [x0 + gx * w, y0 + gy * h, x0 + (gx + 1) * w, y0 + (gy + 1) * h]; + }); + const means = regions.map((region) => regionInk(ink, region).mean); + return means.every((mean) => mean >= spec.shade[0] && mean < spec.shade[1]) ? 1 : 0; +} + +/** Coverage of the ink's bounding box, centered in a square that keeps its aspect, at GRID². */ +function coverage(image) { + const box = inkBox(image); + if (!box) return null; + const side = Math.max(box.width, box.height); + const originX = box.x - (side - box.width) / 2; + const originY = box.y - (side - box.height) / 2; + const vector = new Float32Array(GRID * GRID); + const step = side / GRID; + const samples = 4; + for (let gy = 0; gy < GRID; gy += 1) { + for (let gx = 0; gx < GRID; gx += 1) { + let sum = 0; + for (let sample = 0; sample < samples * samples; sample += 1) { + const x = Math.floor(originX + (gx + ((sample % samples) + 0.5) / samples) * step); + const y = Math.floor( + originY + (gy + (Math.floor(sample / samples) + 0.5) / samples) * step, + ); + sum += + x >= 0 && y >= 0 && x < image.width && y < image.height + ? image.ink[y * image.width + x] + : 0; + } + vector[gy * GRID + gx] = sum / (samples * samples); + } + } + return vector; +} + +/** Pearson correlation of two coverage vectors; -1 when either has no ink or no contrast. */ +function correlation(a, b) { + if (!a || !b) return -1; + const n = a.length; + let [ma, mb] = [0, 0]; + for (let i = 0; i < n; i += 1) { + ma += a[i]; + mb += b[i]; + } + ma /= n; + mb /= n; + let [num, da, db] = [0, 0, 0]; + for (let i = 0; i < n; i += 1) { + num += (a[i] - ma) * (b[i] - mb); + da += (a[i] - ma) ** 2; + db += (b[i] - mb) ** 2; + } + return da === 0 || db === 0 ? -1 : num / Math.sqrt(da * db); +} + +const references = new Map(); +/** + * The cluster alone and with a zero-width joiner before, after and on both sides, so any Arabic + * positional form of the right letter matches. + */ +function referenceVectors(chars) { + if (!references.has(chars)) { + const forms = [chars, ZWJ + chars, chars + ZWJ, ZWJ + chars + ZWJ]; + references.set( + chars, + forms.map((text) => coverage(referenceInk(text, columnsOf.get(chars)))), + ); + } + return references.get(chars); +} + +function shapeScore(vector, chars) { + return Math.max(...referenceVectors(chars).map((reference) => correlation(vector, reference))); +} + +/** + * pango draws no ink for Apple Color Emoji, and draws flags on neither device. Those clusters have + * no reference and are reported instead of judged. + */ +const hasReference = (chars) => + CELL_GLYPHS[chars] || + (!/^\p{Regional_Indicator}{2}$/u.test(chars) && referenceVectors(chars).some(Boolean)); +const judged = printed.filter((slot) => hasReference(slot.chars)); +const unjudged = printed + .filter((slot) => !hasReference(slot.chars)) + .map((slot) => ({ + line: slot.line, + col: slot.col, + chars: slot.chars, + reason: "no reference ink", + })); + +const distinct = [...new Set(judged.map((slot) => slot.chars))]; +const shapes = distinct.filter((chars) => !CELL_GLYPHS[chars]); + +/** The cluster a slot is judged against: its own, or under `swap` a different one. */ +function expectedChars(slot, index) { + if (control !== "swap") return slot.chars; + const own = distinct.indexOf(slot.chars); + const other = distinct[(own + 1 + (index % (distinct.length - 1))) % distinct.length]; + return other === slot.chars ? distinct[(own + 1) % distinct.length] : other; +} + +function judge(slot, index) { + const expected = expectedChars(slot, index); + const result = { line: slot.line, row: slot.row, col: slot.col, chars: slot.chars, expected }; + const spec = CELL_GLYPHS[expected]; + if (spec) { + result.score = cellGlyphScore(slot, spec); + return result; + } + // The shape must also resemble its own cluster at least as much as any other cluster in the + // corpus, within MARGIN, so a near-lookalike such as g judged as 8 fails. + const vector = coverage(screenshotInk(slot.box)); + const score = shapeScore(vector, expected); + let nearest = { chars: expected, score }; + for (const other of shapes) { + if (other === expected) continue; + const otherScore = shapeScore(vector, other); + if (otherScore > nearest.score) nearest = { chars: other, score: otherScore }; + } + const distinctive = nearest.chars === expected || nearest.score - score <= MARGIN; + result.score = distinctive ? score : Math.min(score, 0); + result.nearest = nearest; + return result; +} + +const results = judged.map(judge); +rmSync(scratch, { recursive: true, force: true }); + +const passed = results.filter((result) => result.score >= THRESHOLD); +const failed = results.filter((result) => result.score < THRESHOLD); +const outDir = resolve(dir, "identity"); +mkdirSync(outDir, { recursive: true }); +writeFileSync( + resolve(outDir, `${control}.json`), + `${JSON.stringify({ control, threshold: THRESHOLD, unjudged, results }, null, 2)}\n`, +); + +const format = (result) => + `${result.line}@${result.col}(${result.chars}${result.expected === result.chars ? "" : `→${result.expected}`})=${result.score.toFixed(2)}${result.nearest && result.nearest.chars !== result.expected ? ` nearest ${result.nearest.chars}` : ""}`; +console.log( + `${report.label} ${control}: ${results.length} clusters judged, ${passed.length} pass, ${failed.length} fail, ${unjudged.length} unjudged (${outDir})`, +); +if (control === "none") { + for (const result of failed) console.log(` fail ${format(result)}`); + process.exitCode = failed.length === 0 ? 0 : 1; +} else { + for (const result of passed) console.log(` accepted ${format(result)}`); + process.exitCode = passed.length === 0 ? 0 : 1; +} diff --git a/packages/app/e2e/mobile/terminal-rendering/overhang.mjs b/packages/app/e2e/mobile/terminal-rendering/overhang.mjs new file mode 100644 index 0000000000..da977d78d3 --- /dev/null +++ b/packages/app/e2e/mobile/terminal-rendering/overhang.mjs @@ -0,0 +1,236 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { homedir, tmpdir } from "node:os"; +import { resolve } from "node:path"; +import { setTimeout } from "node:timers/promises"; +import { PNG } from "pngjs"; +import { countInk, measureGrid } from "./check.mjs"; +import { RULER_CELLS } from "./fixture.mjs"; + +// Checks ink that leaves its row: stacked marks above and below a row reach into the rows next to +// it. The script prints such rows, then in one update writes into two rows that hold another row's +// overhang and erases two rows whose overhang reaches a blank row. The overhang must be drawn +// before the update, stay drawn in the written rows, and leave no ink behind the erased rows. +// +// Preconditions are the same as `render.mjs`: the app runs the build being verified against a +// daemon on the same host as this script, and shows an idle, focused terminal with an empty prompt. +// +// PLATFORM=android ANDROID_SERIAL=emulator-5554 node e2e/mobile/terminal-rendering/overhang.mjs +// PLATFORM=ios IOS_DEVICE="iPhone 17" node e2e/mobile/terminal-rendering/overhang.mjs +const platform = process.env.PLATFORM ?? "android"; +const appId = process.env.PASEO_TERMINAL_RENDERING_APP_ID ?? "sh.paseo.debug"; +const label = process.env.PASEO_TERMINAL_RENDERING_LABEL ?? "overhang"; +const session = process.env.AGENT_DEVICE_SESSION ?? `terminal-rendering-${platform}`; +const artifacts = resolve( + process.env.PASEO_TERMINAL_RENDERING_ARTIFACTS ?? + resolve(homedir(), ".paseo/artifacts/terminal-rendering", platform), + label, +); +const fixtureDir = process.env.PASEO_TERMINAL_RENDERING_FIXTURE_DIR ?? tmpdir(); +const screenshotArgs = + platform === "ios" + ? ["--pixel-density", process.env.PASEO_TERMINAL_RENDERING_PIXEL_DENSITY ?? "3"] + : []; +const env = { + ...process.env, + AGENT_DEVICE_STATE_DIR: + process.env.AGENT_DEVICE_STATE_DIR ?? + resolve(homedir(), ".paseo/artifacts/terminal-rendering/device-state"), +}; +mkdirSync(artifacts, { recursive: true }); + +/** Marks stacked below the row: Arabic dots, rings below `g`, a vowel sign below a consonant. */ +const BELOW = "پپپ ييي ججج g̥̥̥̥ कृ"; +/** Marks stacked above the row: accents over `e` and `s`, candrabindu, om. */ +const ABOVE = "é́́́ ŝ̂̂ कँ ॐ"; +/** The marks rows stay left of this column; the update writes at it, outside the checked boxes. */ +const CHECKED_COLUMNS = 26; +const WRITE_COLUMN = 30; +/** 0-based rows. Each source row's overhang reaches the row next to it. */ +const SOURCES = [ + { row: 2, text: BELOW, overhangRow: 3, update: "write" }, + { row: 6, text: ABOVE, overhangRow: 5, update: "erase" }, + { row: 9, text: BELOW, overhangRow: 10, update: "erase" }, + { row: 13, text: ABOVE, overhangRow: 12, update: "write" }, +]; +const PARK_ROW = 16; + +function ad(...args) { + return execFileSync("agent-device", [...args, "--session", session], { + env, + encoding: "utf8", + timeout: 60_000, + }); +} + +function deviceArgs() { + if (platform === "android") { + return [ + "--platform", + "android", + ...(process.env.ANDROID_SERIAL ? ["--serial", process.env.ANDROID_SERIAL] : []), + ]; + } + return [ + "--platform", + "ios", + ...(process.env.IOS_DEVICE ? ["--device", process.env.IOS_DEVICE] : []), + ]; +} + +function snapshotNodes() { + return JSON.parse(ad("snapshot", "--json")).data.nodes; +} + +function pressControl(id) { + const node = JSON.parse(ad("snapshot", "-i", "--json")).data.nodes.find( + (candidate) => candidate.identifier === id, + ); + assert.ok(node?.rect, `No ${id} control on screen`); + const { x, y, width, height } = node.rect; + ad("press", String(Math.round(x + width / 2)), String(Math.round(y + height / 2))); +} + +async function pressEnter() { + pressControl("terminal-key-enter"); + await setTimeout(2_000); +} + +async function runCommand(command) { + ad("type", command, "--delay-ms", "0"); + await pressEnter(); +} + +async function terminalSize() { + await runCommand("clear; stty size"); + for (const node of snapshotNodes()) { + const match = /^(\d+) (\d+)$/.exec((node.label ?? "").trim()); + if (match && (node.identifier ?? "").startsWith("terminal-row-")) { + return { rows: Number(match[1]), columns: Number(match[2]) }; + } + } + throw new Error("No terminal row showed the `stty size` output"); +} + +function shellQuote(text) { + return `'${text.replaceAll("'", "'\\''")}'`; +} + +/** Prints the source rows, waits for Enter, applies the update, and waits for Enter again. */ +function fixtureScript() { + const at = (row, col) => `\\033[${row + 1};${col + 1}H`; + const print = (row, text) => `printf '${at(row, 0)}%s' ${shellQuote(text)}`; + const update = SOURCES.map((source) => + source.update === "write" + ? `${at(source.overhangRow, WRITE_COLUMN)}x` + : `${at(source.row, 0)}\\033[2K`, + ).join(""); + return [ + "stty -echo", + "printf '\\033[2J\\033[3J'", + print(0, "█".repeat(RULER_CELLS)), + ...SOURCES.map((source) => print(source.row, source.text)), + `printf '${at(PARK_ROW, 0)}'`, + "read -r _", + `printf '${update}${at(PARK_ROW, 0)}'`, + "read -r _", + "stty echo", + "", + ].join("\n"); +} + +function screenshot(name) { + const path = resolve(artifacts, name); + ad("screenshot", path, ...screenshotArgs); + return PNG.sync.read(readFileSync(path)); +} + +/** Pixels in `box` where the two screenshots differ by more than the ink threshold. */ +function changedPixels(before, after, box) { + const difference = new PNG({ width: before.width, height: before.height }); + for (let index = 0; index < before.data.length; index += 1) { + difference.data[index] = Math.abs(before.data[index] - after.data[index]); + } + return countInk(difference, box, [0, 0, 0]); +} + +ad("open", appId, ...deviceArgs()); +const controls = JSON.parse(ad("snapshot", "-i", "--json")).data.nodes; +const hasControl = (id) => controls.some((node) => node.identifier === id); +assert.ok(hasControl("terminal-keyboard-toggle"), "Open a terminal first"); +if (!hasControl("terminal-key-enter")) pressControl("terminal-keyboard-toggle"); + +const size = await terminalSize(); +assert.ok( + size.rows > PARK_ROW && size.columns > WRITE_COLUMN, + `Terminal too small: ${JSON.stringify(size)}`, +); +const scriptPath = resolve(fixtureDir, "paseo-terminal-overhang.sh"); +writeFileSync(scriptPath, fixtureScript()); +await runCommand(`sh ${scriptPath}`); + +const nodes = snapshotNodes(); +const before = screenshot("before.png"); +await pressEnter(); +const after = screenshot("after.png"); +await pressEnter(); + +// Snapshot rects are in points on iOS and pixels on Android; the checks work in screenshot pixels. +const scale = before.width / Math.max(...nodes.map((node) => node.rect?.width ?? 0)); +const ruler = nodes.find((node) => node.identifier === "terminal-row-0")?.rect; +assert.ok(ruler, "The ruler row is not exposed as terminal-row-0"); +const rulerRect = { + x: ruler.x * scale, + y: ruler.y * scale, + width: ruler.width * scale, + height: ruler.height * scale, +}; +const grid = measureGrid(before, rulerRect); +const rowBox = (row) => ({ + left: grid.left, + right: grid.left + CHECKED_COLUMNS * grid.cellWidth, + top: rulerRect.y + row * rulerRect.height, + bottom: rulerRect.y + (row + 1) * rulerRect.height, +}); + +/** Measures one source row's overhang before and after the update. */ +function measure(source) { + const box = rowBox(source.overhangRow); + const overhangBefore = countInk(before, box, grid.background); + if (source.update === "write") { + const changedAfterWrite = changedPixels(before, after, box); + const failures = [ + ...(overhangBefore === 0 ? ["overhang-not-drawn"] : []), + ...(changedAfterWrite > 0 ? ["overhang-lost-after-write"] : []), + ]; + return { ...source, overhangBefore, changedAfterWrite, failures }; + } + const inkAfterErase = countInk(after, box, grid.background); + const sourceInkAfterErase = countInk(after, rowBox(source.row), grid.background); + const failures = [ + ...(overhangBefore === 0 ? ["overhang-not-drawn"] : []), + ...(inkAfterErase > 0 ? ["overhang-left-after-erase"] : []), + ...(sourceInkAfterErase > 0 ? ["source-left-after-erase"] : []), + ]; + return { ...source, overhangBefore, inkAfterErase, sourceInkAfterErase, failures }; +} + +const results = SOURCES.map(measure); + +const report = { platform, label, size, grid, rulerRect, results }; +writeFileSync(resolve(artifacts, "report.json"), `${JSON.stringify(report, null, 2)}\n`); +const failures = results.flatMap((result) => + result.failures.map((failure) => `row ${result.overhangRow}: ${failure}`), +); +console.log(`${label}: ${failures.length} failures (${artifacts})`); +for (const result of results) { + console.log( + ` row ${result.row} -> ${result.overhangRow} (${result.update}): overhang ${result.overhangBefore}` + + (result.update === "write" + ? `, changed after write ${result.changedAfterWrite}` + : `, left after erase ${result.inkAfterErase}, source left ${result.sourceInkAfterErase}`), + ); +} +for (const failure of failures) console.log(` ${failure}`); +process.exitCode = failures.length === 0 ? 0 : 1; diff --git a/packages/app/e2e/mobile/terminal-rendering/reattach.mjs b/packages/app/e2e/mobile/terminal-rendering/reattach.mjs new file mode 100644 index 0000000000..c5cb7734e9 --- /dev/null +++ b/packages/app/e2e/mobile/terminal-rendering/reattach.mjs @@ -0,0 +1,149 @@ +import { homedir } from "node:os"; +import { execFileSync } from "node:child_process"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { setTimeout } from "node:timers/promises"; + +// Reattaches to a terminal whose PTY has a different size than the app will measure, and checks +// that the client rows equal the daemon's rows. RESIZE=keyboard opens the keyboard, and the +// relaunched app starts with it closed. RESIZE=fold folds an Android foldable emulator and +// relaunches the app unfolded. Either way the shell redraws its prompt on attach. +// +// Preconditions: the app shows terminal TERMINAL_ID, idle at an empty shell prompt, against the +// daemon at PASEO_HOST. +// +// PLATFORM=android TERMINAL_ID=511fd9f0 PASEO_HOST=localhost:6870 \ +// node e2e/mobile/terminal-rendering/reattach.mjs +// +// The client used to be sized after the replay arrived, so the shell's redraw landed on the +// wrong rows in most trials. TRIALS sets how many reattaches to check. +const platform = process.env.PLATFORM ?? "android"; +const appId = process.env.PASEO_TERMINAL_RENDERING_APP_ID ?? "sh.paseo.debug"; +const appUrl = process.env.PASEO_TERMINAL_RENDERING_APP_URL; +const terminalId = process.env.TERMINAL_ID; +const host = process.env.PASEO_HOST; +const trials = Number(process.env.TRIALS ?? 5); +const resize = process.env.RESIZE ?? "keyboard"; +const label = process.env.PASEO_TERMINAL_RENDERING_LABEL ?? "reattach"; +const session = process.env.AGENT_DEVICE_SESSION ?? `terminal-rendering-${platform}`; +const artifacts = resolve( + process.env.PASEO_TERMINAL_RENDERING_ARTIFACTS ?? + resolve(homedir(), ".paseo/artifacts/terminal-rendering", platform), + label, +); +const env = { + ...process.env, + AGENT_DEVICE_STATE_DIR: + process.env.AGENT_DEVICE_STATE_DIR ?? + resolve(homedir(), ".paseo/artifacts/terminal-rendering/device-state"), +}; +if (!terminalId || !host) throw new Error("Set TERMINAL_ID and PASEO_HOST"); +mkdirSync(artifacts, { recursive: true }); + +function ad(...args) { + return execFileSync("agent-device", [...args, "--session", session], { + env, + encoding: "utf8", + timeout: 120_000, + }); +} + +function paseo(...args) { + return execFileSync("npm", ["run", "-s", "cli", "--", ...args, "--host", host], { + cwd: resolve(import.meta.dirname, "../../../../.."), + encoding: "utf8", + }); +} + +function pressControl(id) { + const node = JSON.parse(ad("snapshot", "-i", "--json")).data.nodes.find( + (candidate) => candidate.identifier === id, + ); + if (!node?.rect) throw new Error(`No ${id} control on screen`); + const { x, y, width, height } = node.rect; + ad("press", String(Math.round(x + width / 2)), String(Math.round(y + height / 2))); +} + +async function resizePty() { + if (resize === "keyboard") { + pressControl("terminal-keyboard-toggle"); + await setTimeout(2_000); + return; + } + const adb = (...args) => + execFileSync("adb", [ + ...(process.env.ANDROID_SERIAL ? ["-s", process.env.ANDROID_SERIAL] : []), + ...args, + ]); + adb("emu", "fold"); + await setTimeout(5_000); + adb("shell", "am", "force-stop", appId); + adb("emu", "unfold"); + await setTimeout(3_000); +} + +function clientRows() { + const nodes = JSON.parse(ad("snapshot", "--json")).data.nodes; + const byIndex = new Map(nodes.map((node) => [node.index, node])); + const rows = []; + for (const node of nodes) { + const match = /^terminal-row-(\d+)$/.exec(node.identifier ?? ""); + if (!match) continue; + // agent-device leaves the label on the parent when the row inherits it. + const text = node.label ?? (node.inheritsLabel ? byIndex.get(node.parentIndex)?.label : ""); + rows[Number(match[1])] = (text ?? "").trim(); + } + return rows; +} + +/** + * Waits for the relaunched app to show terminal rows, then for the shell's redraw to land. + * Returns null when no row appears, for example when the app crashed on launch. + */ +async function attachedClientRows() { + for (let attempt = 0; attempt < 30; attempt += 1) { + await setTimeout(2_000); + if (clientRows().some((text) => text !== "")) { + await setTimeout(3_000); + return clientRows(); + } + } + return null; +} + +function mismatches(client, server) { + const rows = []; + for (let row = 0; row < Math.max(client.length, server.length); row += 1) { + const expected = (server[row] ?? "").trim(); + const actual = client[row] ?? ""; + if (expected !== actual) rows.push({ row, server: expected, client: actual }); + } + return rows; +} + +const results = []; +for (let trial = 1; trial <= trials; trial += 1) { + paseo("terminal", "send-keys", terminalId, "clear", "Enter"); + await setTimeout(1_500); + await resizePty(); + ad("open", appId, ...(appUrl ? [appUrl] : []), "--relaunch"); + const client = await attachedClientRows(); + ad("screenshot", resolve(artifacts, `trial-${trial}.png`)); + if (!client) { + results.push({ trial, attached: false }); + console.log(`${label} trial ${trial}: no terminal rows appeared`); + continue; + } + const server = paseo("terminal", "capture", terminalId).split("\n"); + const rows = mismatches(client, server); + results.push({ trial, attached: true, mismatchedRows: rows }); + console.log(`${label} trial ${trial}: ${rows.length} mismatched rows`); +} + +writeFileSync(resolve(artifacts, "report.json"), `${JSON.stringify(results, null, 2)}\n`); +const attached = results.filter((result) => result.attached); +const failed = attached.filter((result) => result.mismatchedRows.length > 0).length; +console.log( + `${label}: ${failed} of ${attached.length} reattaches differ from the daemon, ${trials - attached.length} never attached (${artifacts})`, +); +process.exitCode = failed === 0 && attached.length === trials ? 0 : 1; diff --git a/packages/app/e2e/mobile/terminal-rendering/render.mjs b/packages/app/e2e/mobile/terminal-rendering/render.mjs new file mode 100644 index 0000000000..7aacfcaa8e --- /dev/null +++ b/packages/app/e2e/mobile/terminal-rendering/render.mjs @@ -0,0 +1,197 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { homedir, tmpdir } from "node:os"; +import { resolve } from "node:path"; +import { setTimeout } from "node:timers/promises"; +import { PNG } from "pngjs"; +import { + checkPartialSelection, + checkTerminalScreenshot, + selectionTarget, + writeOverlay, +} from "./check.mjs"; +import { fixtureOutput } from "./fixture.mjs"; + +// Renders the fixture in a real Paseo terminal and checks the screenshot with `check.mjs`, then +// selects one cell of a conjunct and checks a second screenshot. +// +// Preconditions: the app runs the build being verified against a daemon on the same host as +// this script, and shows an idle, focused terminal with an empty shell prompt. +// +// PLATFORM=android ANDROID_SERIAL=emulator-5554 node e2e/mobile/terminal-rendering/render.mjs +// PLATFORM=ios IOS_DEVICE="iPhone 17" node e2e/mobile/terminal-rendering/render.mjs +const platform = process.env.PLATFORM ?? "android"; +const appId = process.env.PASEO_TERMINAL_RENDERING_APP_ID ?? "sh.paseo.debug"; +const label = process.env.PASEO_TERMINAL_RENDERING_LABEL ?? "run"; +const session = process.env.AGENT_DEVICE_SESSION ?? `terminal-rendering-${platform}`; +const artifacts = resolve( + process.env.PASEO_TERMINAL_RENDERING_ARTIFACTS ?? + resolve(homedir(), ".paseo/artifacts/terminal-rendering", platform), + label, +); +const fixtureDir = process.env.PASEO_TERMINAL_RENDERING_FIXTURE_DIR ?? tmpdir(); +// iOS simulators screenshot at one pixel per point unless asked; glyph identity needs the +// device's real density. Android screenshots are always in device pixels. +const screenshotArgs = + platform === "ios" + ? ["--pixel-density", process.env.PASEO_TERMINAL_RENDERING_PIXEL_DENSITY ?? "3"] + : []; +const env = { + ...process.env, + AGENT_DEVICE_STATE_DIR: + process.env.AGENT_DEVICE_STATE_DIR ?? + resolve(homedir(), ".paseo/artifacts/terminal-rendering/device-state"), +}; +mkdirSync(artifacts, { recursive: true }); + +function ad(...args) { + return execFileSync("agent-device", [...args, "--session", session], { + env, + encoding: "utf8", + timeout: 60_000, + }); +} + +function deviceArgs() { + if (platform === "android") { + return [ + "--platform", + "android", + ...(process.env.ANDROID_SERIAL ? ["--serial", process.env.ANDROID_SERIAL] : []), + ]; + } + return [ + "--platform", + "ios", + ...(process.env.IOS_DEVICE ? ["--device", process.env.IOS_DEVICE] : []), + ]; +} + +function snapshotNodes() { + return JSON.parse(ad("snapshot", "--json")).data.nodes; +} + +function rowNodes(nodes) { + const rows = new Map(); + for (const node of nodes) { + const match = /^terminal-row-(\d+)$/.exec(node.identifier ?? ""); + if (match && node.rect) rows.set(Number(match[1]), node); + } + return rows; +} + +/** + * Taps a control at its center. On iOS the keyboard toolbar is a full-screen accessibility node + * listed after the key bar, so pressing by selector reports the keys as covered. + */ +function pressControl(id) { + const node = JSON.parse(ad("snapshot", "-i", "--json")).data.nodes.find( + (candidate) => candidate.identifier === id, + ); + assert.ok(node?.rect, `No ${id} control on screen`); + const { x, y, width, height } = node.rect; + ad("press", String(Math.round(x + width / 2)), String(Math.round(y + height / 2))); +} + +async function runCommand(command) { + ad("type", command, "--delay-ms", "0"); + pressControl("terminal-key-enter"); + await setTimeout(2_000); +} + +async function terminalSize() { + await runCommand("clear; stty size"); + for (const node of snapshotNodes()) { + const match = /^(\d+) (\d+)$/.exec((node.label ?? "").trim()); + if (match && (node.identifier ?? "").startsWith("terminal-row-")) { + return { rows: Number(match[1]), columns: Number(match[2]) }; + } + } + throw new Error("No terminal row showed the `stty size` output"); +} + +ad("open", appId, ...deviceArgs()); +const controls = JSON.parse(ad("snapshot", "-i", "--json")).data.nodes; +const hasControl = (id) => controls.some((node) => node.identifier === id); +assert.ok(hasControl("terminal-keyboard-toggle"), "Open a terminal first"); +if (!hasControl("terminal-key-enter")) pressControl("terminal-keyboard-toggle"); + +const size = await terminalSize(); +const fixturePath = resolve(fixtureDir, "paseo-terminal-rendering.txt"); +const scriptPath = resolve(fixtureDir, "paseo-terminal-rendering.sh"); +writeFileSync(fixturePath, fixtureOutput(size.columns)); +writeFileSync(scriptPath, `printf '\\033[2J\\033[3J\\033[H'; cat '${fixturePath}'; sleep 120\n`); +await runCommand(`sh ${scriptPath}`); + +const nodes = snapshotNodes(); +const screenshotPath = resolve(artifacts, "terminal.png"); +ad("screenshot", screenshotPath, ...screenshotArgs); +const png = PNG.sync.read(readFileSync(screenshotPath)); +// Snapshot rects are in points on iOS and pixels on Android; the checks work in screenshot pixels. +const scale = png.width / Math.max(...nodes.map((node) => node.rect?.width ?? 0)); +const toPixels = ({ x, y, width, height }) => ({ + x: x * scale, + y: y * scale, + width: width * scale, + height: height * scale, +}); +const rows = rowNodes(nodes); +const rects = new Map([...rows].map(([index, node]) => [index, toPixels(node.rect)])); +const { grid, failures, slots } = await checkTerminalScreenshot({ png, size, rows: rects }); + +// Long-press selects the conjunct as a word; dragging back from its second cell leaves the first. +const target = await selectionTarget({ size }); +const targetRect = rects.get(target.row); +assert.ok(targetRect, "The select line is not on screen"); +const y = Math.round((targetRect.y + targetRect.height / 2) / scale); +const cellX = (offset) => Math.round((grid.left + (target.col + offset) * grid.cellWidth) / scale); +ad("longpress", String(cellX(0.5)), String(y), "800"); +ad("gesture", "pan", String(cellX(1.75)), String(y), String(cellX(0.5) - cellX(1.75)), "0", "600"); +const selectionPath = resolve(artifacts, "selection.png"); +ad("screenshot", selectionPath, ...screenshotArgs); +const selectionFailures = checkPartialSelection({ + png: PNG.sync.read(readFileSync(selectionPath)), + rows: rects, + grid, + target, +}); +for (const failure of selectionFailures) failures.push({ line: "select", ...failure }); +// A tap clears the selection; it would otherwise survive into the next run's screenshot. +const lastRect = rects.get(size.rows - 1); +if (lastRect) { + ad("press", String(cellX(4)), String(Math.round((lastRect.y + lastRect.height / 2) / scale))); +} +try { + pressControl("terminal-key-ctrl"); + ad("type", "c", "--delay-ms", "0"); +} catch (error) { + console.warn(`Could not interrupt the fixture: ${error.message}`); +} + +writeOverlay(png, slots, resolve(artifacts, "overlay.png")); +const report = { + platform, + label, + size, + grid, + checkedClusters: slots.length, + failures, + rows: [...rows.keys()].map((index) => ({ + index, + label: rows.get(index).label, + rect: rects.get(index), + })), +}; +writeFileSync(resolve(artifacts, "report.json"), `${JSON.stringify(report, null, 2)}\n`); + +const byLine = Map.groupBy(failures, (failure) => failure.line); +console.log( + `${label}: ${slots.length} clusters checked, ${failures.length} failures (${artifacts})`, +); +for (const [line, list] of byLine) { + console.log( + ` ${line}: ${list.map((failure) => `${failure.kind}@${failure.col ?? "-"}${failure.char ? `(${failure.char})` : ""}`).join(" ")}`, + ); +} +process.exitCode = failures.length === 0 ? 0 : 1; diff --git a/packages/app/modules/paseo-terminal/android/build.gradle b/packages/app/modules/paseo-terminal/android/build.gradle new file mode 100644 index 0000000000..3be89253be --- /dev/null +++ b/packages/app/modules/paseo-terminal/android/build.gradle @@ -0,0 +1,25 @@ +apply plugin: 'com.android.library' + +group = 'sh.paseo.terminal' +version = '0.1.0' + +def expoModulesCorePlugin = new File(project(":expo-modules-core").projectDir.absolutePath, "ExpoModulesCorePlugin.gradle") +apply from: expoModulesCorePlugin +applyKotlinExpoModulesCorePlugin() +useCoreDependencies() +useExpoPublishing() +useDefaultAndroidSdkVersions() + +android { + namespace "sh.paseo.terminal" + defaultConfig { + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + } +} + +dependencies { + implementation "androidx.customview:customview:1.1.0" + testImplementation "junit:junit:4.13.2" + androidTestImplementation "androidx.test:runner:1.6.2" + androidTestImplementation "androidx.test.ext:junit:1.2.1" +} diff --git a/packages/app/modules/paseo-terminal/android/src/androidTest/assets/grapheme-rows.json b/packages/app/modules/paseo-terminal/android/src/androidTest/assets/grapheme-rows.json new file mode 100644 index 0000000000..31c2b0c8d7 --- /dev/null +++ b/packages/app/modules/paseo-terminal/android/src/androidTest/assets/grapheme-rows.json @@ -0,0 +1,38 @@ +[ + { + "output": "स्ते", + "row": "2,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1;8,4294638330,0,0;स्ते ", + "clusterStarts": [0, 2, 3, 4, 5, 6, 7], + "contrastStarts": [0, 1, 2, 3, 4, 5, 6, 7] + }, + { + "output": "क्ष", + "row": "2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1;8,4294638330,0,0;क्ष ", + "clusterStarts": [0, 2, 3, 4, 5, 6, 7], + "contrastStarts": [0, 1, 2, 3, 4, 5, 6, 7] + }, + { + "output": "নক্ষত্র", + "row": "1,1,2,1,1,1,2,1,1,1,1,1,1,1,1,1;8,4294638330,0,0;নক্ষত্র ", + "clusterStarts": [0, 1, 3, 5, 6, 7], + "contrastStarts": [0, 1, 2, 3, 4, 5, 6, 7] + }, + { + "output": "क्अ", + "row": "2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1;8,4294638330,0,0;क्अ ", + "clusterStarts": [0, 1, 2, 3, 4, 5, 6, 7], + "contrastStarts": [0, 2, 3, 4, 5, 6, 7] + }, + { + "output": "ক্অ", + "row": "2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1;8,4294638330,0,0;ক্অ ", + "clusterStarts": [0, 1, 2, 3, 4, 5, 6, 7], + "contrastStarts": [0, 2, 3, 4, 5, 6, 7] + }, + { + "output": "अ्क", + "row": "2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1;8,4294638330,0,0;अ्क ", + "clusterStarts": [0, 1, 2, 3, 4, 5, 6, 7], + "contrastStarts": [0, 2, 3, 4, 5, 6, 7] + } +] diff --git a/packages/app/modules/paseo-terminal/android/src/androidTest/java/sh/paseo/terminal/TerminalRowLayoutTest.kt b/packages/app/modules/paseo-terminal/android/src/androidTest/java/sh/paseo/terminal/TerminalRowLayoutTest.kt new file mode 100644 index 0000000000..e9b8ab1edf --- /dev/null +++ b/packages/app/modules/paseo-terminal/android/src/androidTest/java/sh/paseo/terminal/TerminalRowLayoutTest.kt @@ -0,0 +1,105 @@ +package sh.paseo.terminal + +import android.os.Build +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Paint +import android.util.Log +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.json.JSONArray +import org.json.JSONObject +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith + +private const val COLUMNS = 8 + +/** Rasters that draw the same clusters match exactly; a wrong clustering differs by 0.12 or more. */ +private const val MATCH_TOLERANCE = 0.01f + +@RunWith(AndroidJUnit4::class) +class TerminalRowLayoutTest { + private val font = TerminalFont("monospace", 40f, 1f) + private val paints = TerminalPaints() + + /** + * Draws each row of `grapheme-rows.json` and compares it with its grapheme clusters drawn one at a + * time, each centred in its own columns. `terminal-frame.test.ts` checks that the rows are what + * xterm produces and that the clusters are UAX #29 grapheme clusters. + */ + @Test + fun drawsEachGraphemeClusterInItsOwnColumns() { + val assets = InstrumentationRegistry.getInstrumentation().context.assets + val rows = JSONArray(assets.open("grapheme-rows.json").bufferedReader().readText()) + for (index in 0 until rows.length()) { + val row = rows.getJSONObject(index) + val source = TerminalRowSource.decode(row.getString("row")) + val layout = TerminalRowLayout(source, font, TerminalCustomGlyphs.EMPTY) + // Selection covers row 0 only, so drawing as row 1 draws nothing selected. + val drawn = raster { layout.drawSelected(it, 1, TerminalSelection(TerminalSelectionRecord()), paints) } + val expected = raster { drawClusters(it, source, starts(row, "clusterStarts")) } + val contrast = raster { drawClusters(it, source, starts(row, "contrastStarts")) } + val output = row.getString("output") + val (toExpected, toContrast) = difference(drawn, expected) to difference(drawn, contrast) + Log.i("TerminalRowLayoutTest", "$output expected=$toExpected contrast=$toContrast") + // Android 10's platform ICU splits this conjunct. Keep its observed raster baseline + // explicit rather than claiming this supported OS passes the modern grapheme corpus. + if (Build.VERSION.SDK_INT == 29 && output == "स्ते") { + assertTrue("Android 10 unexpectedly matches modern conjunct clustering", toExpected > MATCH_TOLERANCE) + assertTrue("Android 10 split-conjunct baseline changed", toContrast <= MATCH_TOLERANCE) + continue + } + assertTrue("$output differs from its grapheme clusters by $toExpected", toExpected <= MATCH_TOLERANCE) + assertTrue("$output also matches the wrong clusters", toContrast > MATCH_TOLERANCE) + } + } + + private fun starts(row: JSONObject, key: String): List = + row.getJSONArray(key).let { starts -> List(starts.length()) { starts.getInt(it) } } + + private fun raster(draw: (Canvas) -> Unit): Bitmap { + val bitmap = Bitmap.createBitmap(COLUMNS * font.cellWidthPx, font.cellHeightPx, Bitmap.Config.ARGB_8888) + draw(Canvas(bitmap)) + return bitmap + } + + /** Draws each cluster as its own text, centred in its columns and scaled down when wider. */ + private fun drawClusters(canvas: Canvas, source: TerminalRowSource, starts: List) { + val cellCount = source.cells.size / 2 + val paint = Paint(font.paint(0)).apply { color = source.styles[1].toLong().toInt() } + val offsets = IntArray(cellCount + 1) + val cols = IntArray(cellCount + 1) + for (cell in 0 until cellCount) { + offsets[cell + 1] = offsets[cell] + source.cells[cell * 2] + cols[cell + 1] = cols[cell] + source.cells[cell * 2 + 1] + } + for ((index, first) in starts.withIndex()) { + val end = starts.getOrElse(index + 1) { cellCount } + val text = source.text.substring(offsets[first], offsets[end]) + if (text.isBlank()) continue + val slot = (cols[end] - cols[first]) * font.cellWidthPx.toFloat() + val advance = paint.measureText(text) + val x = cols[first] * font.cellWidthPx + if (advance > slot + 1f) 0f else (slot - advance) / 2f + canvas.save() + if (advance > slot + 1f) canvas.scale(slot / advance, slot / advance, x, font.cellHeightPx / 2f) + canvas.drawText(text, x, font.baselinePx.toFloat(), paint) + canvas.restore() + } + } + + /** Share of inked pixels, in either image, whose coverage differs by more than a quarter. */ + private fun difference(a: Bitmap, b: Bitmap): Float { + var inked = 0 + var differing = 0 + for (y in 0 until a.height) { + for (x in 0 until a.width) { + val (left, right) = (a.getPixel(x, y) ushr 24) to (b.getPixel(x, y) ushr 24) + if (left < 64 && right < 64) continue + inked += 1 + if (kotlin.math.abs(left - right) > 64) differing += 1 + } + } + return if (inked == 0) 0f else differing.toFloat() / inked + } +} diff --git a/packages/app/modules/paseo-terminal/android/src/main/AndroidManifest.xml b/packages/app/modules/paseo-terminal/android/src/main/AndroidManifest.xml new file mode 100644 index 0000000000..94cbbcfc39 --- /dev/null +++ b/packages/app/modules/paseo-terminal/android/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/PaseoTerminalModule.kt b/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/PaseoTerminalModule.kt new file mode 100644 index 0000000000..e6250ec280 --- /dev/null +++ b/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/PaseoTerminalModule.kt @@ -0,0 +1,24 @@ +package sh.paseo.terminal + +import expo.modules.kotlin.modules.Module +import expo.modules.kotlin.modules.ModuleDefinition + +class PaseoTerminalModule : Module() { + override fun definition() = ModuleDefinition { + Name("PaseoTerminal") + + View(PaseoTerminalView::class) { + Events("onCellMetrics") + + Prop("frame") { view: PaseoTerminalView, frame: TerminalFrameRecord -> view.setFrame(frame) } + Prop("theme") { view: PaseoTerminalView, theme: TerminalThemeRecord -> view.setTheme(theme) } + Prop("fontFamily") { view: PaseoTerminalView, family: String -> view.setFontFamily(family) } + Prop("fontSize") { view: PaseoTerminalView, size: Double -> view.setFontSize(size) } + Prop("customGlyphs") { view: PaseoTerminalView, glyphs: List -> + view.setCustomGlyphs(glyphs) + } + + OnViewDidUpdateProps { view: PaseoTerminalView -> view.commit() } + } + } +} diff --git a/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/PaseoTerminalView.kt b/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/PaseoTerminalView.kt new file mode 100644 index 0000000000..3fcf012e03 --- /dev/null +++ b/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/PaseoTerminalView.kt @@ -0,0 +1,196 @@ +package sh.paseo.terminal + +import android.annotation.SuppressLint +import android.content.Context +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Rect +import android.os.Bundle +import android.view.MotionEvent +import android.widget.TextView +import androidx.core.view.ViewCompat +import androidx.core.view.accessibility.AccessibilityNodeInfoCompat +import androidx.customview.widget.ExploreByTouchHelper +import expo.modules.kotlin.AppContext +import expo.modules.kotlin.viewevent.EventDispatcher +import expo.modules.kotlin.views.ExpoView + +private const val MIN_CACHED_ROWS = 256 +private const val CURSOR_ALPHA = 0.45f + +/** + * Paints terminal frames on the cell grid. Row shaping is cached by row content, so cursor and + * selection changes repaint without reshaping, and unchanged rows replay their display lists. + */ +@SuppressLint("ViewConstructor") +class PaseoTerminalView(context: Context, appContext: AppContext) : ExpoView(context, appContext) { + private val onCellMetrics by EventDispatcher>() + + private var fontFamily = "monospace" + private var fontSize = 12.0 + private var font: TerminalFont? = null + private var customGlyphs = TerminalCustomGlyphs.EMPTY + private var frame: TerminalFrameRecord? = null + private var frameChanged = false + + private var rows: List = emptyList() + private var columns = 0 + private var cursor: TerminalCursorRecord? = null + private var selection: TerminalSelection? = null + private var backgroundColor = Color.BLACK + private var cursorColor = Color.WHITE + private val paints = TerminalPaints() + private val rowCache = object : LinkedHashMap(64, 0.75f, true) { + override fun removeEldestEntry(eldest: MutableMap.MutableEntry): Boolean { + if (size <= maxOf(MIN_CACHED_ROWS, rows.size * 2)) return false + eldest.value.release() + return true + } + } + private val accessibility = RowAccessibility() + + init { + setWillNotDraw(false) + ViewCompat.setAccessibilityDelegate(this, accessibility) + } + + fun setFrame(value: TerminalFrameRecord) { + frame = value + frameChanged = true + } + + fun setTheme(value: TerminalThemeRecord) { + backgroundColor = argb(value.background) + cursorColor = argb(value.cursor) + paints.selectionBackground = argb(value.selectionBackground) + paints.selectionForeground = argb(value.selectionForeground) + invalidate() + } + + fun setFontFamily(value: String) { + fontFamily = value + } + + fun setFontSize(value: Double) { + fontSize = value + } + + fun setCustomGlyphs(value: List) { + customGlyphs = TerminalCustomGlyphs(value) + clearRowCache() + frameChanged = true + } + + /** Applies a batch of prop updates: font first, then the frame laid out with it. */ + fun commit() { + val density = resources.displayMetrics.density + val sizePx = (fontSize * density).toFloat() + val current = font + if (current == null || !current.sameAs(fontFamily, sizePx, density)) { + val next = TerminalFont(fontFamily, sizePx, density) + font = next + clearRowCache() + frameChanged = true + onCellMetrics( + mapOf( + "cellWidth" to next.cellWidthPx / density, + "cellHeight" to next.cellHeightPx / density, + ), + ) + } + if (frameChanged) { + frameChanged = false + layoutFrame() + } + invalidate() + } + + private fun layoutFrame() { + val currentFont = font ?: return + val record = frame ?: return + columns = record.columns + cursor = record.cursor + selection = record.selection?.let(::TerminalSelection) + rows = record.rows.map { encoded -> + rowCache.getOrPut(encoded) { + TerminalRowLayout(TerminalRowSource.decode(encoded), currentFont, customGlyphs) + } + } + accessibility.invalidateRoot() + } + + private fun clearRowCache() { + for (layout in rowCache.values) layout.release() + rowCache.clear() + rows = emptyList() + } + + override fun onDraw(canvas: Canvas) { + super.onDraw(canvas) + canvas.drawColor(backgroundColor) + val currentFont = font ?: return + val cellWidth = currentFont.cellWidthPx + val cellHeight = currentFont.cellHeightPx + val gridWidth = columns * cellWidth + canvas.save() + canvas.clipRect(0, 0, minOf(width, gridWidth), height) + val activeSelection = selection + for ((index, row) in rows.withIndex()) { + canvas.save() + canvas.translate(0f, (index * cellHeight).toFloat()) + if (activeSelection != null && activeSelection.intersectsRow(index)) { + row.drawSelected(canvas, index, activeSelection, paints) + } else { + row.draw(canvas, gridWidth, paints) + } + canvas.restore() + } + cursor?.let { position -> + paints.fill.color = withAlpha(cursorColor, CURSOR_ALPHA) + val left = (position.col * cellWidth).toFloat() + val top = (position.row * cellHeight).toFloat() + canvas.drawRect(left, top, left + cellWidth, top + cellHeight, paints.fill) + } + canvas.restore() + } + + override fun dispatchHoverEvent(event: MotionEvent): Boolean = + accessibility.dispatchHoverEvent(event) || super.dispatchHoverEvent(event) + + override fun onDetachedFromWindow() { + super.onDetachedFromWindow() + for (layout in rowCache.values) layout.release() + } + + private fun withAlpha(color: Int, alpha: Float): Int = + Color.argb((Color.alpha(color) * alpha).toInt(), Color.red(color), Color.green(color), Color.blue(color)) + + /** Exposes each non-blank row as a virtual text node, `terminal-row-`. */ + private inner class RowAccessibility : ExploreByTouchHelper(this@PaseoTerminalView) { + override fun getVirtualViewAt(x: Float, y: Float): Int { + val cellHeight = font?.cellHeightPx ?: return INVALID_ID + val row = (y / cellHeight).toInt() + return if (row in rows.indices && rows[row].describe().isNotEmpty()) row else INVALID_ID + } + + override fun getVisibleVirtualViews(virtualViewIds: MutableList) { + for ((index, row) in rows.withIndex()) { + if (row.describe().isNotEmpty()) virtualViewIds.add(index) + } + } + + @Suppress("DEPRECATION") + override fun onPopulateNodeForVirtualView(virtualViewId: Int, node: AccessibilityNodeInfoCompat) { + val cellHeight = font?.cellHeightPx ?: 1 + val label = rows.getOrNull(virtualViewId)?.describe().orEmpty() + node.className = TextView::class.java.name + node.text = label + node.contentDescription = label + node.viewIdResourceName = "terminal-row-$virtualViewId" + val top = virtualViewId * cellHeight + node.setBoundsInParent(Rect(0, top, minOf(width, columns * (font?.cellWidthPx ?: 1)), top + cellHeight)) + } + + override fun onPerformActionForVirtualView(virtualViewId: Int, action: Int, arguments: Bundle?): Boolean = false + } +} diff --git a/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/TerminalCustomGlyphs.kt b/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/TerminalCustomGlyphs.kt new file mode 100644 index 0000000000..ce1e8d5229 --- /dev/null +++ b/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/TerminalCustomGlyphs.kt @@ -0,0 +1,76 @@ +package sh.paseo.terminal + +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.Path + +/** + * Box drawing and block elements painted as cell geometry instead of font glyphs, so frames and + * blocks join across cells regardless of the font's own metrics. + */ +internal class TerminalCustomGlyph(record: TerminalCustomGlyphRecord) { + private val rects: FloatArray = FloatArray(record.rects.size) { record.rects[it].toFloat() } + private val commands: DoubleArray = record.path + private val strokeWidth: Float = record.strokeWidth.toFloat() + private var scaledPath: Path? = null + private var scaledWidth = 0f + private var scaledHeight = 0f + + fun draw(canvas: Canvas, x: Float, width: Float, height: Float, density: Float, paint: Paint) { + paint.style = Paint.Style.FILL + var index = 0 + while (index + 3 < rects.size) { + canvas.drawRect( + x + rects[index] * width, + rects[index + 1] * height, + x + (rects[index] + rects[index + 2]) * width, + (rects[index + 1] + rects[index + 3]) * height, + paint, + ) + index += 4 + } + if (commands.isEmpty()) return + val path = pathFor(width, height) + paint.style = Paint.Style.STROKE + paint.strokeWidth = strokeWidth * density + paint.strokeCap = Paint.Cap.BUTT + paint.strokeJoin = Paint.Join.MITER + canvas.save() + canvas.translate(x, 0f) + canvas.drawPath(path, paint) + canvas.restore() + paint.style = Paint.Style.FILL + } + + private fun pathFor(width: Float, height: Float): Path { + val cached = scaledPath + if (cached != null && scaledWidth == width && scaledHeight == height) return cached + val path = Path() + var index = 0 + while (index < commands.size) { + val x = { offset: Int -> commands[index + offset].toFloat() * width } + val y = { offset: Int -> commands[index + offset].toFloat() * height } + when (commands[index].toInt()) { + 0 -> { path.moveTo(x(1), y(2)); index += 3 } + 1 -> { path.lineTo(x(1), y(2)); index += 3 } + 2 -> { path.quadTo(x(1), y(2), x(3), y(4)); index += 5 } + else -> index = commands.size + } + } + scaledPath = path + scaledWidth = width + scaledHeight = height + return path + } +} + +internal class TerminalCustomGlyphs(records: List) { + private val glyphs: Map = + records.associate { it.char to TerminalCustomGlyph(it) } + + operator fun get(text: String): TerminalCustomGlyph? = glyphs[text] + + companion object { + val EMPTY = TerminalCustomGlyphs(emptyList()) + } +} diff --git a/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/TerminalFont.kt b/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/TerminalFont.kt new file mode 100644 index 0000000000..046efd1e18 --- /dev/null +++ b/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/TerminalFont.kt @@ -0,0 +1,61 @@ +package sh.paseo.terminal + +import android.graphics.Paint +import android.graphics.Typeface +import kotlin.math.max +import kotlin.math.roundToInt + +private const val MEASURE_TEXT = "mmmmmmmmmm" + +/** + * The terminal font at one pixel size: a paint per face (regular, bold, italic, bold italic) and + * the cell those faces are laid out on. Cells are whole device pixels so every column origin is + * exact. Platform fallback fonts cover characters the family lacks. + */ +internal class TerminalFont(val family: String, val sizePx: Float, val density: Float) { + private val faces: Array = Array(4) { face -> + Paint(Paint.ANTI_ALIAS_FLAG or Paint.SUBPIXEL_TEXT_FLAG).apply { + typeface = Typeface.create(family, typefaceStyle(face)) + textSize = sizePx + } + } + + val cellWidthPx: Int + val cellHeightPx: Int + val baselinePx: Int + val underlineOffsetPx: Float + val underlineThicknessPx: Float + val strikeOffsetPx: Float + val strikeThicknessPx: Float + + init { + val regular = faces[0] + cellWidthPx = max(1, (regular.measureText(MEASURE_TEXT) / MEASURE_TEXT.length).roundToInt()) + val metrics = regular.fontMetricsInt + cellHeightPx = max(1, metrics.descent - metrics.ascent) + baselinePx = -metrics.ascent + underlineOffsetPx = regular.underlinePosition + underlineThicknessPx = max(1f, regular.underlineThickness) + strikeOffsetPx = regular.strikeThruPosition + strikeThicknessPx = max(1f, regular.strikeThruThickness) + } + + /** Paint for a style's face; callers only change its color. */ + fun paint(flags: Int): Paint = faces[face(flags)] + + fun sameAs(family: String, sizePx: Float, density: Float): Boolean = + this.family == family && this.sizePx == sizePx && this.density == density + + companion object { + fun face(flags: Int): Int = + (if (flags and TerminalStyleFlags.BOLD != 0) 1 else 0) + + (if (flags and TerminalStyleFlags.ITALIC != 0) 2 else 0) + + private fun typefaceStyle(face: Int): Int = when (face) { + 1 -> Typeface.BOLD + 2 -> Typeface.ITALIC + 3 -> Typeface.BOLD_ITALIC + else -> Typeface.NORMAL + } + } +} diff --git a/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/TerminalFrame.kt b/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/TerminalFrame.kt new file mode 100644 index 0000000000..c27be7cc7a --- /dev/null +++ b/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/TerminalFrame.kt @@ -0,0 +1,100 @@ +package sh.paseo.terminal + +import expo.modules.kotlin.records.Field +import expo.modules.kotlin.records.Record + +class TerminalCursorRecord : Record { + @Field val row: Int = 0 + @Field val col: Int = 0 +} + +class TerminalSelectionRecord : Record { + @Field val startRow: Int = 0 + @Field val startCol: Int = 0 + @Field val endRow: Int = 0 + @Field val endCol: Int = 0 +} + +class TerminalFrameRecord : Record { + @Field val columns: Int = 0 + /** Encoded rows, `cells;styles;text`; see `frame-encoding.ts`. */ + @Field val rows: List = emptyList() + @Field val cursor: TerminalCursorRecord? = null + @Field val selection: TerminalSelectionRecord? = null +} + +class TerminalThemeRecord : Record { + @Field val background: Double = 0.0 + @Field val cursor: Double = 0.0 + @Field val selectionBackground: Double = 0.0 + @Field val selectionForeground: Double = 0.0 +} + +class TerminalCustomGlyphRecord : Record { + @Field val char: String = "" + @Field val rects: DoubleArray = DoubleArray(0) + @Field val path: DoubleArray = DoubleArray(0) + @Field val strokeWidth: Double = 0.0 +} + +internal object TerminalStyleFlags { + const val BOLD = 1 + const val ITALIC = 2 + const val UNDERLINE = 4 + const val STRIKETHROUGH = 8 +} + +/** JS sends colors as unsigned ARGB numbers; Android paints signed ARGB ints. */ +internal fun argb(value: Double): Int = value.toLong().toInt() + +/** One row as the caller described it: cell text, column spans and style spans. */ +internal class TerminalRowSource private constructor( + val text: String, + val cells: IntArray, + val styles: DoubleArray, +) { + companion object { + /** Decodes `cells;styles;text`, where both number lists are comma separated. */ + fun decode(encoded: String): TerminalRowSource { + val cellsEnd = encoded.indexOf(';') + val stylesEnd = encoded.indexOf(';', cellsEnd + 1) + val cells = parseNumbers(encoded, 0, cellsEnd) + val styles = parseNumbers(encoded, cellsEnd + 1, stylesEnd) + return TerminalRowSource( + encoded.substring(stylesEnd + 1), + IntArray(cells.size) { cells[it].toInt() }, + DoubleArray(styles.size) { styles[it].toDouble() }, + ) + } + + private fun parseNumbers(encoded: String, start: Int, end: Int): LongArray { + if (end <= start) return LongArray(0) + var count = 1 + for (index in start until end) if (encoded[index] == ',') count += 1 + val numbers = LongArray(count) + var slot = 0 + for (index in start until end) { + val char = encoded[index] + if (char == ',') slot += 1 else numbers[slot] = numbers[slot] * 10 + (char - '0') + } + return numbers + } + } +} + +internal class TerminalSelection(record: TerminalSelectionRecord) { + private val startRow = record.startRow + private val startCol = record.startCol + private val endRow = record.endRow + private val endCol = record.endCol + + fun intersectsRow(row: Int): Boolean = row in startRow..endRow + + /** A cell is selected when any column it covers is inside the inclusive range. */ + fun contains(row: Int, col: Int, span: Int): Boolean { + if (!intersectsRow(row)) return false + val firstCol = if (row == startRow) startCol else 0 + val lastCol = if (row == endRow) endCol else Int.MAX_VALUE + return col + span - 1 >= firstCol && col <= lastCol + } +} diff --git a/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/TerminalRowLayout.kt b/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/TerminalRowLayout.kt new file mode 100644 index 0000000000..d2ee2355bc --- /dev/null +++ b/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/TerminalRowLayout.kt @@ -0,0 +1,306 @@ +package sh.paseo.terminal + +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.RenderNode +import android.graphics.text.MeasuredText +import android.icu.text.BreakIterator + +/** Shaped glyphs may exceed their slot by this many pixels before they are scaled down. */ +private const val OVERFLOW_TOLERANCE_PX = 1f +/** Stands in for an open edge when a group is clipped on one side only. */ +private const val CLIP_UNBOUNDED_PX = 100_000f + +/** + * One row shaped once and placed on the terminal grid. + * + * Each run of cells with the same font face is shaped as a whole, so contextual forms, ligatures, + * marks and fallback fonts see their neighbours. The shaper reports a cluster's advance on its + * first UTF-16 unit and zero on the units it absorbed. A cell whose first unit has zero advance + * therefore belongs to the cluster of the cell before it: a ligature, conjunct, emoji sequence or + * reordered mark that spans columns. A cell that does not start a grapheme cluster also stays with + * the cell before it: a half-form conjunct such as स्त keeps both consonants' advances, and drawing + * either half alone would show an explicit virama. Each resulting group is drawn from the shaped + * run (in context) at its first cell's column, centred in the columns it owns, and scaled down only when + * its glyphs are wider than those columns. Colors never split groups or reshape the row: a group + * whose cells differ in color or selection is drawn once per color, clipped to those cells' columns. + */ +internal class TerminalRowLayout( + val source: TerminalRowSource, + private val font: TerminalFont, + private val customGlyphs: TerminalCustomGlyphs, +) { + private val chars: CharArray = source.text.toCharArray() + private val cellCount = source.cells.size / 2 + private val cellCol = IntArray(cellCount) + private val cellSpan = IntArray(cellCount) + private val cellStart = IntArray(cellCount) + private val cellEnd = IntArray(cellCount) + private val cellForeground = IntArray(cellCount) + private val cellBackground = IntArray(cellCount) + private val cellFlags = IntArray(cellCount) + private val cellGlyph = arrayOfNulls(cellCount) + private val groups = ArrayList() + private val measured: MeasuredText? + val text: String get() = source.text + + private var node: RenderNode? = null + + private class Group( + val firstCell: Int, + val lastCell: Int, + val col: Int, + val start: Int, + val end: Int, + val contextStart: Int, + val contextEnd: Int, + val offsetPx: Float, + val scale: Float, + val blank: Boolean, + ) + + init { + readCells() + measured = measure() + if (measured != null) buildGroups(measured) + } + + private fun readCells() { + var offset = 0 + var col = 0 + var styleIndex = 0 + var styleEndCol = 0 + for (cell in 0 until cellCount) { + val length = source.cells[cell * 2] + val span = maxOf(1, source.cells[cell * 2 + 1]) + while (col >= styleEndCol && styleIndex + 3 < source.styles.size) { + styleEndCol += source.styles[styleIndex].toInt() + styleIndex += 4 + } + val style = styleIndex - 4 + if (style >= 0) { + cellForeground[cell] = argb(source.styles[style + 1]) + cellBackground[cell] = argb(source.styles[style + 2]) + cellFlags[cell] = source.styles[style + 3].toInt() + } + cellCol[cell] = col + cellSpan[cell] = span + cellStart[cell] = offset + cellEnd[cell] = minOf(chars.size, offset + length) + cellGlyph[cell] = customGlyphs[source.text.substring(cellStart[cell], cellEnd[cell])] + offset = cellEnd[cell] + col += span + } + } + + /** Same face, not custom glyph: cells shaped together. */ + private fun shapesWith(cell: Int, other: Int): Boolean = + cellGlyph[cell] == null && cellGlyph[other] == null && + TerminalFont.face(cellFlags[cell]) == TerminalFont.face(cellFlags[other]) + + private fun measure(): MeasuredText? { + if (chars.isEmpty()) return null + val builder = MeasuredText.Builder(chars) + var cell = 0 + while (cell < cellCount) { + var last = cell + while (last + 1 < cellCount && shapesWith(cell, last + 1)) last += 1 + val length = cellEnd[last] - cellStart[cell] + if (length > 0) { + if (cellGlyph[cell] != null) { + builder.appendReplacementRun(font.paint(cellFlags[cell]), length, 0f) + } else { + builder.appendStyleRun(font.paint(cellFlags[cell]), length, false) + } + } + cell = last + 1 + } + val trailing = chars.size - (if (cellCount > 0) cellEnd[cellCount - 1] else 0) + if (trailing > 0) builder.appendReplacementRun(font.paint(0), trailing, 0f) + return builder.build() + } + + private fun buildGroups(measured: MeasuredText) { + // Keep platform graphemes together even when Minikin reports separate advances/cursors. + // Rules follow the OS ICU version: Android 10 splits Indic conjuncts such as स्ते. + val graphemes = BreakIterator.getCharacterInstance() + graphemes.setText(source.text) + var cell = 0 + while (cell < cellCount) { + if (cellGlyph[cell] != null) { + cell += 1 + continue + } + var last = cell + while (last + 1 < cellCount && shapesWith(cell, last + 1)) last += 1 + val contextStart = cellStart[cell] + val contextEnd = cellEnd[last] + var first = cell + for (next in cell + 1..last) { + val startsCluster = + cellEnd[next] > cellStart[next] && + measured.getCharWidthAt(cellStart[next]) != 0f && + graphemes.isBoundary(cellStart[next]) + if (startsCluster) { + addGroup(measured, first, next - 1, contextStart, contextEnd) + first = next + } + } + addGroup(measured, first, last, contextStart, contextEnd) + cell = last + 1 + } + } + + private fun addGroup(measured: MeasuredText, first: Int, last: Int, contextStart: Int, contextEnd: Int) { + val start = cellStart[first] + val end = cellEnd[last] + if (end <= start) return + var columns = 0 + for (cell in first..last) columns += cellSpan[cell] + val slot = (columns * font.cellWidthPx).toFloat() + val advance = measured.getWidth(start, end) + val scale = if (advance > slot + OVERFLOW_TOLERANCE_PX) slot / advance else 1f + val offset = if (scale < 1f) 0f else (slot - advance) / 2f + var blank = true + for (index in start until end) { + if (chars[index] != ' ') { + blank = false + break + } + } + groups.add(Group(first, last, cellCol[first], start, end, contextStart, contextEnd, offset, scale, blank)) + } + + /** Draws the row with its own colors, replaying a recorded display list when possible. */ + fun draw(canvas: Canvas, width: Int, paints: TerminalPaints) { + if (!canvas.isHardwareAccelerated) { + drawContent(canvas, -1, null, paints) + return + } + // Marks stacked above or below a letter ink outside the row. The node must not clip them: the + // view redraws every row on each frame, so ink outside the row is never left stale. + val recorded = node ?: RenderNode("terminal-row").also { + it.setClipToBounds(false) + node = it + } + if (!recorded.hasDisplayList() || recorded.width != width) { + recorded.setPosition(0, 0, width, font.cellHeightPx) + val recording = recorded.beginRecording() + try { + drawContent(recording, -1, null, paints) + } finally { + recorded.endRecording() + } + } + canvas.drawRenderNode(recorded) + } + + /** Draws the row with selected cells in selection colors. Selection never reshapes the row. */ + fun drawSelected(canvas: Canvas, row: Int, selection: TerminalSelection, paints: TerminalPaints) { + drawContent(canvas, row, selection, paints) + } + + fun release() { + node?.discardDisplayList() + node = null + } + + private fun selected(row: Int, selection: TerminalSelection?, cell: Int): Boolean = + selection?.contains(row, cellCol[cell], cellSpan[cell]) == true + + private fun drawContent(canvas: Canvas, row: Int, selection: TerminalSelection?, paints: TerminalPaints) { + val cellWidth = font.cellWidthPx.toFloat() + val cellHeight = font.cellHeightPx.toFloat() + val fill = paints.fill + for (cell in 0 until cellCount) { + val background = + if (selected(row, selection, cell)) paints.selectionBackground else cellBackground[cell] + if (background ushr 24 == 0) continue + fill.color = background + canvas.drawRect( + cellCol[cell] * cellWidth, + 0f, + (cellCol[cell] + cellSpan[cell]) * cellWidth, + cellHeight, + fill, + ) + } + + val baseline = font.baselinePx.toFloat() + val text = measured + if (text != null) { + for (group in groups) { + if (group.blank) continue + val paint = font.paint(cellFlags[group.firstCell]) + var first = group.firstCell + while (first <= group.lastCell) { + val color = foreground(row, selection, first, paints) + var last = first + while (last < group.lastCell && foreground(row, selection, last + 1, paints) == color) last += 1 + // Only edges between differently colored cells clip; the group's outer edges may overhang. + val clipped = first > group.firstCell || last < group.lastCell + canvas.save() + if (clipped) { + val left = if (first > group.firstCell) cellCol[first] * cellWidth else -CLIP_UNBOUNDED_PX + val right = + if (last < group.lastCell) (cellCol[last] + cellSpan[last]) * cellWidth else CLIP_UNBOUNDED_PX + canvas.clipRect(left, -CLIP_UNBOUNDED_PX, right, CLIP_UNBOUNDED_PX) + } + paint.color = color + drawGroupText(canvas, text, group, paint, cellWidth, cellHeight, baseline) + canvas.restore() + first = last + 1 + } + } + } + + for (cell in 0 until cellCount) { + val glyph = cellGlyph[cell] + val flags = cellFlags[cell] + val foreground = foreground(row, selection, cell, paints) + if (glyph != null) { + fill.color = foreground + glyph.draw(canvas, cellCol[cell] * cellWidth, cellSpan[cell] * cellWidth, cellHeight, font.density, fill) + } + if (flags and (TerminalStyleFlags.UNDERLINE or TerminalStyleFlags.STRIKETHROUGH) == 0) continue + fill.color = foreground + val left = cellCol[cell] * cellWidth + val right = left + cellSpan[cell] * cellWidth + if (flags and TerminalStyleFlags.UNDERLINE != 0) { + val top = baseline + font.underlineOffsetPx + canvas.drawRect(left, top, right, top + font.underlineThicknessPx, fill) + } + if (flags and TerminalStyleFlags.STRIKETHROUGH != 0) { + val top = baseline + font.strikeOffsetPx + canvas.drawRect(left, top, right, top + font.strikeThicknessPx, fill) + } + } + } + + private fun drawGroupText( + canvas: Canvas, + text: MeasuredText, + group: Group, + paint: Paint, + cellWidth: Float, + cellHeight: Float, + baseline: Float, + ) { + val x = group.col * cellWidth + group.offsetPx + if (group.scale < 1f) canvas.scale(group.scale, group.scale, x, cellHeight / 2f) + canvas.drawTextRun(text, group.start, group.end, group.contextStart, group.contextEnd, x, baseline, false, paint) + } + + private fun foreground(row: Int, selection: TerminalSelection?, cell: Int, paints: TerminalPaints): Int = + if (selected(row, selection, cell)) paints.selectionForeground else cellForeground[cell] + + /** The row's text as accessibility reads it. */ + fun describe(): String = source.text.trimEnd() +} + +/** Paint state shared by every row of one view. */ +internal class TerminalPaints { + val fill = Paint(Paint.ANTI_ALIAS_FLAG) + var selectionBackground: Int = 0xFFFFFF00.toInt() + var selectionForeground: Int = 0xFF000000.toInt() +} diff --git a/packages/app/modules/paseo-terminal/contract.ts b/packages/app/modules/paseo-terminal/contract.ts new file mode 100644 index 0000000000..ee4fe45ab0 --- /dev/null +++ b/packages/app/modules/paseo-terminal/contract.ts @@ -0,0 +1,60 @@ +/** + * Native terminal renderer. The caller owns terminal state (xterm), input and gestures; this view + * shapes and paints one frame of terminal cells on the authoritative cell grid and reports the + * cell size its font produces. + * + * Colors are unsigned 32-bit ARGB numbers (`0xAARRGGBB`). Alpha 0 means "not painted". + */ +export interface PaseoTerminalFrame { + /** Columns the frame paints. Cells beyond it are clipped. */ + columns: number; + rows: PaseoTerminalRow[]; + cursor: PaseoTerminalCursor | null; + selection: PaseoTerminalSelection | null; +} + +/** + * One terminal row. Cells start at column 0 and are consecutive. `text` is every cell's text in + * order, so cell `i` owns the next `cells[2i]` UTF-16 code units of `text` and covers the next + * `cells[2i + 1]` columns. Style spans are consecutive from column 0 and cover all columns. + */ +export interface PaseoTerminalRow { + text: string; + /** Flattened `[utf16Length, columnSpan]` per cell. */ + cells: number[]; + /** Flattened `[columnCount, foreground, background, flags]` per style span. */ + styles: number[]; +} + +export interface PaseoTerminalCursor { + row: number; + col: number; +} + +/** Inclusive cell range in frame rows. A cell is selected when any of its columns is. */ +export interface PaseoTerminalSelection { + startRow: number; + startCol: number; + endRow: number; + endCol: number; +} + +export interface PaseoTerminalTheme { + background: number; + cursor: number; + selectionBackground: number; + selectionForeground: number; +} + +export interface PaseoTerminalCellMetrics { + cellWidth: number; + cellHeight: number; +} + +export const PASEO_TERMINAL_STYLE_FLAGS = { + bold: 1, + italic: 2, + underline: 4, + strikethrough: 8, + dim: 16, +} as const; diff --git a/packages/app/src/terminal/native-renderer/terminal-custom-glyph.test.ts b/packages/app/modules/paseo-terminal/custom-glyphs.test.ts similarity index 81% rename from packages/app/src/terminal/native-renderer/terminal-custom-glyph.test.ts rename to packages/app/modules/paseo-terminal/custom-glyphs.test.ts index 95de6c8c54..f3892110c0 100644 --- a/packages/app/src/terminal/native-renderer/terminal-custom-glyph.test.ts +++ b/packages/app/modules/paseo-terminal/custom-glyphs.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { resolveTerminalCustomGlyph } from "./terminal-custom-glyph"; +import { encodeTerminalCustomGlyphs, resolveTerminalCustomGlyph } from "./custom-glyphs"; describe("native terminal custom glyphs", () => { it("fills the complete cell for the full block used by the Claude mascot", () => { @@ -85,4 +85,22 @@ describe("native terminal custom glyphs", () => { expect(resolveTerminalCustomGlyph(char), `missing custom glyph ${char}`).not.toBeNull(); } }); + + it("encodes every glyph for the native renderer in cell fractions", () => { + const encoded = new Map(encodeTerminalCustomGlyphs().map((glyph) => [glyph.char, glyph])); + + expect(encoded.get("▛")).toEqual({ + char: "▛", + rects: [0, 0, 0.5, 0.5, 0.5, 0, 0.5, 0.5, 0, 0.5, 0.5, 0.5], + path: [], + strokeWidth: 0, + }); + expect(encoded.get("╭")).toEqual({ + char: "╭", + rects: [], + path: [0, 0.5, 1, 1, 0.5, 0.75, 2, 0.5, 0.5, 0.75, 0.5, 1, 1, 0.5], + strokeWidth: 1, + }); + expect(encoded.get("┣")?.strokeWidth).toBe(3); + }); }); diff --git a/packages/app/src/terminal/native-renderer/terminal-custom-glyph.ts b/packages/app/modules/paseo-terminal/custom-glyphs.ts similarity index 66% rename from packages/app/src/terminal/native-renderer/terminal-custom-glyph.ts rename to packages/app/modules/paseo-terminal/custom-glyphs.ts index f63de40e24..fd55193f74 100644 --- a/packages/app/src/terminal/native-renderer/terminal-custom-glyph.ts +++ b/packages/app/modules/paseo-terminal/custom-glyphs.ts @@ -82,12 +82,60 @@ const BLOCK_GLYPHS: Readonly> = { "▟": rects(upperRight(), lowerLeft(), lowerRight()), }; +/** + * One custom glyph as the native view consumes it. Coordinates are fractions of one cell. + * `rects` is flattened `[x, y, width, height]`. `path` is flattened commands: + * `0 x y` moves, `1 x y` draws a line, `2 cx cy x y` draws a quadratic curve. Paths are + * stroked with `strokeWidth` points regardless of cell size. + */ +export interface PaseoTerminalCustomGlyph { + char: string; + rects: number[]; + path: number[]; + strokeWidth: number; +} + +const PATH_COMMAND_CODES: Readonly> = { + M: { code: 0, coordinates: 2 }, + L: { code: 1, coordinates: 2 }, + Q: { code: 2, coordinates: 4 }, +}; + export function resolveTerminalCustomGlyph(char: string): TerminalCustomGlyph | null { return LIGHT_BOX_GLYPHS[char] ?? HEAVY_BOX_GLYPHS[char] ?? BLOCK_GLYPHS[char] ?? null; } -export function isTerminalCustomGlyph(char: string): boolean { - return resolveTerminalCustomGlyph(char) !== null; +export function encodeTerminalCustomGlyphs(): PaseoTerminalCustomGlyph[] { + const table = { ...LIGHT_BOX_GLYPHS, ...HEAVY_BOX_GLYPHS, ...BLOCK_GLYPHS }; + return Object.entries(table).map(([char, glyph]) => + glyph.kind === "rects" + ? { + char, + rects: glyph.rects.flatMap((value) => [value.x, value.y, value.width, value.height]), + path: [], + strokeWidth: 0, + } + : { char, rects: [], path: encodePath(glyph.path), strokeWidth: glyph.strokeWidth }, + ); +} + +function encodePath(pathData: string): number[] { + const tokens = pathData.match(/[MLQ]|-?\d*\.?\d+/g) ?? []; + const encoded: number[] = []; + let index = 0; + while (index < tokens.length) { + const command = PATH_COMMAND_CODES[tokens[index]]; + if (!command) { + throw new Error(`Unsupported terminal glyph path command in ${pathData}`); + } + const coordinates = tokens.slice(index + 1, index + 1 + command.coordinates).map(Number); + if (coordinates.length !== command.coordinates || coordinates.some(Number.isNaN)) { + throw new Error(`Malformed terminal glyph path ${pathData}`); + } + encoded.push(command.code, ...coordinates); + index += 1 + command.coordinates; + } + return encoded; } function path(pathData: string, strokeWidth = 1): TerminalPathGlyph { diff --git a/packages/app/modules/paseo-terminal/expo-module.config.json b/packages/app/modules/paseo-terminal/expo-module.config.json new file mode 100644 index 0000000000..6291f992c1 --- /dev/null +++ b/packages/app/modules/paseo-terminal/expo-module.config.json @@ -0,0 +1,9 @@ +{ + "platforms": ["android", "ios"], + "android": { + "modules": ["sh.paseo.terminal.PaseoTerminalModule"] + }, + "ios": { + "modules": ["PaseoTerminalModule"] + } +} diff --git a/packages/app/modules/paseo-terminal/frame-encoding.test.ts b/packages/app/modules/paseo-terminal/frame-encoding.test.ts new file mode 100644 index 0000000000..a40d4302c2 --- /dev/null +++ b/packages/app/modules/paseo-terminal/frame-encoding.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, test } from "vitest"; + +import { encodeTerminalFrame } from "./frame-encoding"; + +describe("encodeTerminalFrame", () => { + test("puts cells and styles before text, so text may contain separators", () => { + const native = encodeTerminalFrame({ + columns: 10, + rows: [ + { + text: "안a;b,", + cells: [1, 2, 1, 1, 1, 1, 1, 1, 1, 1], + styles: [3, 0xffe5e5e5, 0, 0, 3, 0xffff0000, 0, 1], + }, + { text: "", cells: [], styles: [] }, + ], + cursor: { row: 1, col: 0 }, + selection: { startRow: 0, startCol: 0, endRow: 0, endCol: 1 }, + }); + + expect(native).toEqual({ + columns: 10, + rows: ["1,2,1,1,1,1,1,1,1,1;3,4293256677,0,0,3,4294901760,0,1;안a;b,", ";;"], + cursor: { row: 1, col: 0 }, + selection: { startRow: 0, startCol: 0, endRow: 0, endCol: 1 }, + }); + }); + + test("leaves out a missing cursor and selection instead of sending null", () => { + const native = encodeTerminalFrame({ columns: 1, rows: [], cursor: null, selection: null }); + + expect(Object.keys(native)).toEqual(["columns", "rows"]); + }); +}); diff --git a/packages/app/modules/paseo-terminal/frame-encoding.ts b/packages/app/modules/paseo-terminal/frame-encoding.ts new file mode 100644 index 0000000000..fc4d113bd2 --- /dev/null +++ b/packages/app/modules/paseo-terminal/frame-encoding.ts @@ -0,0 +1,27 @@ +import type { PaseoTerminalCursor, PaseoTerminalFrame, PaseoTerminalSelection } from "./contract"; + +/** A frame as it crosses to native. */ +export interface NativePaseoTerminalFrame { + columns: number; + rows: string[]; + cursor?: PaseoTerminalCursor; + selection?: PaseoTerminalSelection; +} + +/** + * Rows cross as `cells;styles;text`, with the numbers comma separated. One string per row keeps + * prop conversion to a single copy instead of one call per number, and the string is also the + * native shaping cache key, so an unchanged row costs one lookup. + * + * A missing cursor or selection is left out rather than sent as `null`: Expo on iOS fails to + * convert `null` into an optional record field and then drops the whole frame. + */ +export function encodeTerminalFrame(frame: PaseoTerminalFrame): NativePaseoTerminalFrame { + const native: NativePaseoTerminalFrame = { + columns: frame.columns, + rows: frame.rows.map((row) => `${row.cells.join(",")};${row.styles.join(",")};${row.text}`), + }; + if (frame.cursor) native.cursor = frame.cursor; + if (frame.selection) native.selection = frame.selection; + return native; +} diff --git a/packages/app/modules/paseo-terminal/index.tsx b/packages/app/modules/paseo-terminal/index.tsx new file mode 100644 index 0000000000..321cf7c30c --- /dev/null +++ b/packages/app/modules/paseo-terminal/index.tsx @@ -0,0 +1,47 @@ +import { requireNativeView } from "expo"; +import { useCallback, useMemo } from "react"; +import type { StyleProp, ViewStyle } from "react-native"; + +import type { PaseoTerminalCellMetrics, PaseoTerminalFrame, PaseoTerminalTheme } from "./contract"; +import { encodeTerminalCustomGlyphs, type PaseoTerminalCustomGlyph } from "./custom-glyphs"; +import { encodeTerminalFrame, type NativePaseoTerminalFrame } from "./frame-encoding"; + +export * from "./contract"; + +export interface PaseoTerminalViewProps { + frame: PaseoTerminalFrame; + theme: PaseoTerminalTheme; + fontFamily: string; + /** Font size in points after the system font scale is applied. */ + fontSize: number; + onCellMetrics?: (metrics: PaseoTerminalCellMetrics) => void; + style?: StyleProp; +} + +interface NativePaseoTerminalViewProps extends Omit< + PaseoTerminalViewProps, + "frame" | "onCellMetrics" +> { + frame: NativePaseoTerminalFrame; + customGlyphs: PaseoTerminalCustomGlyph[]; + onCellMetrics?: (event: { nativeEvent: PaseoTerminalCellMetrics }) => void; +} + +const NativePaseoTerminalView = requireNativeView("PaseoTerminal"); +const CUSTOM_GLYPHS = encodeTerminalCustomGlyphs(); + +export function PaseoTerminalView({ frame, onCellMetrics, ...props }: PaseoTerminalViewProps) { + const nativeFrame = useMemo(() => encodeTerminalFrame(frame), [frame]); + const handleCellMetrics = useCallback( + (event: { nativeEvent: PaseoTerminalCellMetrics }) => onCellMetrics?.(event.nativeEvent), + [onCellMetrics], + ); + return ( + + ); +} diff --git a/packages/app/modules/paseo-terminal/ios/PaseoTerminal.podspec b/packages/app/modules/paseo-terminal/ios/PaseoTerminal.podspec new file mode 100644 index 0000000000..f15570465f --- /dev/null +++ b/packages/app/modules/paseo-terminal/ios/PaseoTerminal.podspec @@ -0,0 +1,22 @@ +Pod::Spec.new do |s| + s.name = 'PaseoTerminal' + s.version = '0.1.0' + s.summary = 'Native terminal renderer for Paseo' + s.description = 'Shapes and paints terminal frames on the terminal cell grid' + s.license = 'Apache-2.0' + s.author = 'Paseo' + s.homepage = 'https://paseo.sh' + s.platforms = { :ios => '15.1' } + s.swift_version = '5.4' + s.source = { :path => '.' } + s.static_framework = true + + s.dependency 'ExpoModulesCore' + + s.pod_target_xcconfig = { + 'DEFINES_MODULE' => 'YES', + 'SWIFT_COMPILATION_MODE' => 'wholemodule' + } + + s.source_files = "**/*.{h,m,swift}" +end diff --git a/packages/app/modules/paseo-terminal/ios/PaseoTerminalModule.swift b/packages/app/modules/paseo-terminal/ios/PaseoTerminalModule.swift new file mode 100644 index 0000000000..ec6d7edb0c --- /dev/null +++ b/packages/app/modules/paseo-terminal/ios/PaseoTerminalModule.swift @@ -0,0 +1,21 @@ +import ExpoModulesCore + +public class PaseoTerminalModule: Module { + public func definition() -> ModuleDefinition { + Name("PaseoTerminal") + + View(PaseoTerminalView.self) { + Events("onCellMetrics") + + Prop("frame") { (view: PaseoTerminalView, frame: TerminalFrameRecord) in view.setFrame(frame) } + Prop("theme") { (view: PaseoTerminalView, theme: TerminalThemeRecord) in view.setTheme(theme) } + Prop("fontFamily") { (view: PaseoTerminalView, family: String) in view.setFontFamily(family) } + Prop("fontSize") { (view: PaseoTerminalView, size: Double) in view.setFontSize(size) } + Prop("customGlyphs") { (view: PaseoTerminalView, glyphs: [TerminalCustomGlyphRecord]) in + view.setCustomGlyphs(glyphs) + } + + OnViewDidUpdateProps { (view: PaseoTerminalView) in view.commit() } + } + } +} diff --git a/packages/app/modules/paseo-terminal/ios/PaseoTerminalView.swift b/packages/app/modules/paseo-terminal/ios/PaseoTerminalView.swift new file mode 100644 index 0000000000..240cddddab --- /dev/null +++ b/packages/app/modules/paseo-terminal/ios/PaseoTerminalView.swift @@ -0,0 +1,179 @@ +import ExpoModulesCore +import UIKit + +private let minCachedRows = 256 +private let cursorAlpha: CGFloat = 0.45 + +/// Paints terminal frames on the cell grid. Row shaping is cached by row content, and a frame +/// repaints only the rows whose layout, selection or cursor changed. A row's glyphs may ink outside +/// the row, so a repaint covers the old and new row's ink and redraws every row whose ink it meets. +final class PaseoTerminalView: ExpoView { + let onCellMetrics = EventDispatcher() + + private var fontFamily = "Menlo" + private var fontSize: CGFloat = 12 + private var font: TerminalFont? + private var customGlyphs = TerminalCustomGlyphs.empty + private var frameRecord: TerminalFrameRecord? + private var frameChanged = false + + private var rows: [TerminalRowLayout] = [] + private var columns = 0 + private var cursor: (row: Int, col: Int)? + private var selection: TerminalSelection? + private var background = TerminalColor(Double(0xff00_0000)) + private var cursorColor = TerminalColor(Double(0xffff_ffff)) + private var rowPaint = TerminalRowPaint( + selectionBackground: TerminalColor(Double(0xffff_ff00)), + selectionForeground: TerminalColor(Double(0xff00_0000))) + private var rowCache: [String: TerminalRowLayout] = [:] + + required init(appContext: AppContext? = nil) { + super.init(appContext: appContext) + isOpaque = true + contentMode = .redraw + isAccessibilityElement = false + } + + func setFrame(_ record: TerminalFrameRecord) { + frameRecord = record + frameChanged = true + } + + func setTheme(_ record: TerminalThemeRecord) { + background = TerminalColor(record.background) + cursorColor = TerminalColor(record.cursor) + rowPaint = TerminalRowPaint( + selectionBackground: TerminalColor(record.selectionBackground), + selectionForeground: TerminalColor(record.selectionForeground)) + backgroundColor = UIColor(cgColor: background.cgColor()) + setNeedsDisplay() + } + + func setFontFamily(_ value: String) { fontFamily = value } + + func setFontSize(_ value: Double) { fontSize = CGFloat(value) } + + func setCustomGlyphs(_ records: [TerminalCustomGlyphRecord]) { + customGlyphs = TerminalCustomGlyphs(records) + rowCache.removeAll() + rows = [] + frameChanged = true + } + + /// Applies a batch of prop updates: font first, then the frame laid out with it. + func commit() { + let displayScale = traitCollection.displayScale > 0 ? traitCollection.displayScale : UIScreen.main.scale + if font?.sameAs(family: fontFamily, size: fontSize, displayScale: displayScale) != true { + let next = TerminalFont(family: fontFamily, size: fontSize, displayScale: displayScale) + font = next + rowCache.removeAll() + rows = [] + frameChanged = true + onCellMetrics(["cellWidth": next.cellWidth, "cellHeight": next.cellHeight]) + setNeedsDisplay() + } + if frameChanged { + frameChanged = false + layoutFrame() + } + } + + override func traitCollectionDidChange(_ previous: UITraitCollection?) { + super.traitCollectionDidChange(previous) + if previous?.displayScale != traitCollection.displayScale { commit() } + } + + override func layoutSubviews() { + super.layoutSubviews() + setNeedsDisplay() + } + + private func layoutFrame() { + guard let font, let record = frameRecord else { return } + let previousRows = rows + let previousSelection = selection + let previousCursor = cursor + let previousColumns = columns + + columns = record.columns + cursor = record.cursor.map { ($0.row, $0.col) } + selection = record.selection.map(TerminalSelection.init) + rows = record.rows.map { encoded in + if let cached = rowCache[encoded] { return cached } + let layout = TerminalRowLayout( + source: TerminalRowSource(encoded: encoded), font: font, customGlyphs: customGlyphs) + rowCache[encoded] = layout + return layout + } + trimRowCache(keeping: record.rows) + updateAccessibility() + + if previousColumns != columns || previousRows.count != rows.count { + setNeedsDisplay() + return + } + for index in rows.indices { + let layoutChanged = previousRows[index] !== rows[index] + let selectionChanged = previousSelection?.columns(onRow: index) != selection?.columns(onRow: index) + let cursorChanged = + (previousCursor?.row == index || cursor?.row == index) + && (previousCursor?.row != cursor?.row || previousCursor?.col != cursor?.col) + if layoutChanged || selectionChanged || cursorChanged { + let previous = paintedRect(previousRows[index], at: index, font: font) + setNeedsDisplay(previous.union(paintedRect(rows[index], at: index, font: font))) + } + } + } + + /// The area row `index` paints, including glyph ink outside the row. + private func paintedRect(_ row: TerminalRowLayout, at index: Int, font: TerminalFont) -> CGRect { + let top = CGFloat(index) * font.cellHeight + return CGRect(x: 0, y: top + row.inkTop, width: bounds.width, height: row.inkBottom - row.inkTop) + } + + private func trimRowCache(keeping currentRows: [String]) { + guard rowCache.count > max(minCachedRows, rows.count * 2) else { return } + let current = Set(currentRows) + rowCache = rowCache.filter { current.contains($0.key) } + } + + override func draw(_ rect: CGRect) { + guard let context = UIGraphicsGetCurrentContext() else { return } + context.setFillColor(background.cgColor()) + context.fill(rect) + guard let font else { return } + let gridWidth = CGFloat(columns) * font.cellWidth + context.saveGState() + context.clip(to: CGRect(x: 0, y: 0, width: min(bounds.width, gridWidth), height: bounds.height)) + for (index, row) in rows.enumerated() where paintedRect(row, at: index, font: font).intersects(rect) { + row.draw(in: context, row: index, top: CGFloat(index) * font.cellHeight, selection: selection, paint: rowPaint) + } + if let cursor { + context.setFillColor(cursorColor.cgColor(alphaScale: cursorAlpha)) + context.fill(CGRect( + x: CGFloat(cursor.col) * font.cellWidth, y: CGFloat(cursor.row) * font.cellHeight, + width: font.cellWidth, height: font.cellHeight)) + } + context.restoreGState() + } + + /// Exposes each non-blank row as a static text element, `terminal-row-`. + private func updateAccessibility() { + guard let font else { return } + var elements: [UIAccessibilityElement] = [] + for (index, row) in rows.enumerated() { + let label = row.accessibilityText + guard !label.isEmpty else { continue } + let element = UIAccessibilityElement(accessibilityContainer: self) + element.accessibilityIdentifier = "terminal-row-\(index)" + element.accessibilityLabel = label + element.accessibilityTraits = .staticText + element.accessibilityFrameInContainerSpace = CGRect( + x: 0, y: CGFloat(index) * font.cellHeight, + width: min(bounds.width, CGFloat(columns) * font.cellWidth), height: font.cellHeight) + elements.append(element) + } + accessibilityElements = elements + } +} diff --git a/packages/app/modules/paseo-terminal/ios/TerminalCustomGlyphs.swift b/packages/app/modules/paseo-terminal/ios/TerminalCustomGlyphs.swift new file mode 100644 index 0000000000..2442131916 --- /dev/null +++ b/packages/app/modules/paseo-terminal/ios/TerminalCustomGlyphs.swift @@ -0,0 +1,73 @@ +import CoreGraphics + +/// Box drawing and block elements painted as cell geometry instead of font glyphs, so frames and +/// blocks join across cells regardless of the font's own metrics. +final class TerminalCustomGlyph { + private let rects: [Double] + private let commands: [Double] + private let strokeWidth: CGFloat + + init(_ record: TerminalCustomGlyphRecord) { + rects = record.rects + commands = record.path + strokeWidth = CGFloat(record.strokeWidth) + } + + func draw(in context: CGContext, rect cell: CGRect, color: CGColor) { + context.saveGState() + context.setFillColor(color) + var index = 0 + while index + 3 < rects.count { + context.fill(CGRect( + x: cell.minX + CGFloat(rects[index]) * cell.width, + y: cell.minY + CGFloat(rects[index + 1]) * cell.height, + width: CGFloat(rects[index + 2]) * cell.width, + height: CGFloat(rects[index + 3]) * cell.height)) + index += 4 + } + if !commands.isEmpty { + let point = { (offset: Int) in + CGPoint( + x: cell.minX + CGFloat(self.commands[offset]) * cell.width, + y: cell.minY + CGFloat(self.commands[offset + 1]) * cell.height) + } + let path = CGMutablePath() + index = 0 + while index < commands.count { + switch Int(commands[index]) { + case 0: + path.move(to: point(index + 1)) + index += 3 + case 1: + path.addLine(to: point(index + 1)) + index += 3 + case 2: + path.addQuadCurve(to: point(index + 3), control: point(index + 1)) + index += 5 + default: + index = commands.count + } + } + context.setStrokeColor(color) + context.setLineWidth(strokeWidth) + context.setLineCap(.butt) + context.setLineJoin(.miter) + context.addPath(path) + context.strokePath() + } + context.restoreGState() + } +} + +final class TerminalCustomGlyphs { + static let empty = TerminalCustomGlyphs([]) + private let glyphs: [String: TerminalCustomGlyph] + + init(_ records: [TerminalCustomGlyphRecord]) { + var glyphs: [String: TerminalCustomGlyph] = [:] + for record in records { glyphs[record.char] = TerminalCustomGlyph(record) } + self.glyphs = glyphs + } + + subscript(text: String) -> TerminalCustomGlyph? { glyphs[text] } +} diff --git a/packages/app/modules/paseo-terminal/ios/TerminalFont.swift b/packages/app/modules/paseo-terminal/ios/TerminalFont.swift new file mode 100644 index 0000000000..d2f52a78da --- /dev/null +++ b/packages/app/modules/paseo-terminal/ios/TerminalFont.swift @@ -0,0 +1,67 @@ +import CoreText +import UIKit + +private let measureText = "mmmmmmmmmm" + +/// The terminal font at one size: a CTFont per face (regular, bold, italic, bold italic) and the +/// cell those faces are laid out on. Cells are whole device pixels so every column origin is +/// exact. CoreText's cascade list covers characters the family lacks. +final class TerminalFont { + let family: String + let size: CGFloat + let displayScale: CGFloat + private let faces: [CTFont] + + /// Cell size and baseline in points, each a whole number of device pixels. + let cellWidth: CGFloat + let cellHeight: CGFloat + let baseline: CGFloat + let underlineOffset: CGFloat + let underlineThickness: CGFloat + let strikeOffset: CGFloat + let strikeThickness: CGFloat + + init(family: String, size: CGFloat, displayScale: CGFloat) { + self.family = family + self.size = size + self.displayScale = displayScale + let regular = TerminalFont.makeFont(family: family, size: size, traits: []) + faces = [ + regular, + TerminalFont.makeFont(family: family, size: size, traits: .traitBold), + TerminalFont.makeFont(family: family, size: size, traits: .traitItalic), + TerminalFont.makeFont(family: family, size: size, traits: [.traitBold, .traitItalic]), + ] + + let pixel = { (value: CGFloat) in max(1, (value * displayScale).rounded()) / displayScale } + let line = CTLineCreateWithAttributedString( + NSAttributedString(string: measureText, attributes: [.font: regular])) + let width = CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil)) + cellWidth = pixel(width / CGFloat(measureText.count)) + let ascent = CTFontGetAscent(regular) + let descent = CTFontGetDescent(regular) + let leading = CTFontGetLeading(regular) + cellHeight = pixel(ascent + descent + leading) + baseline = pixel(ascent) + underlineOffset = -CTFontGetUnderlinePosition(regular) + underlineThickness = max(1 / displayScale, CTFontGetUnderlineThickness(regular)) + strikeOffset = -CTFontGetXHeight(regular) / 2 + strikeThickness = underlineThickness + } + + func font(flags: Int) -> CTFont { faces[TerminalFont.face(flags: flags)] } + + func sameAs(family: String, size: CGFloat, displayScale: CGFloat) -> Bool { + self.family == family && self.size == size && self.displayScale == displayScale + } + + static func face(flags: Int) -> Int { + (flags & TerminalStyleFlags.bold != 0 ? 1 : 0) + (flags & TerminalStyleFlags.italic != 0 ? 2 : 0) + } + + private static func makeFont(family: String, size: CGFloat, traits: UIFontDescriptor.SymbolicTraits) -> CTFont { + let base = UIFontDescriptor(fontAttributes: [.family: family]) + let descriptor = traits.isEmpty ? base : (base.withSymbolicTraits(traits) ?? base) + return UIFont(descriptor: descriptor, size: size) as CTFont + } +} diff --git a/packages/app/modules/paseo-terminal/ios/TerminalFrame.swift b/packages/app/modules/paseo-terminal/ios/TerminalFrame.swift new file mode 100644 index 0000000000..84ba6e8b0c --- /dev/null +++ b/packages/app/modules/paseo-terminal/ios/TerminalFrame.swift @@ -0,0 +1,122 @@ +import CoreGraphics +import ExpoModulesCore + +struct TerminalCursorRecord: Record { + @Field var row: Int = 0 + @Field var col: Int = 0 +} + +struct TerminalSelectionRecord: Record { + @Field var startRow: Int = 0 + @Field var startCol: Int = 0 + @Field var endRow: Int = 0 + @Field var endCol: Int = 0 +} + +struct TerminalFrameRecord: Record { + @Field var columns: Int = 0 + /// Encoded rows, `cells;styles;text`; see `frame-encoding.ts`. + @Field var rows: [String] = [] + @Field var cursor: TerminalCursorRecord? = nil + @Field var selection: TerminalSelectionRecord? = nil +} + +struct TerminalThemeRecord: Record { + @Field var background: Double = 0 + @Field var cursor: Double = 0 + @Field var selectionBackground: Double = 0 + @Field var selectionForeground: Double = 0 +} + +struct TerminalCustomGlyphRecord: Record { + @Field var char: String = "" + @Field var rects: [Double] = [] + @Field var path: [Double] = [] + @Field var strokeWidth: Double = 0 +} + +enum TerminalStyleFlags { + static let bold = 1 + static let italic = 2 + static let underline = 4 + static let strikethrough = 8 +} + +/// JS sends colors as unsigned ARGB numbers. +struct TerminalColor: Equatable { + let argb: UInt32 + + init(_ value: Double) { + argb = UInt32(truncatingIfNeeded: Int64(value)) + } + + var isPainted: Bool { argb >> 24 != 0 } + + func cgColor(alphaScale: CGFloat = 1) -> CGColor { + let channel = { (shift: UInt32) in CGFloat((argb >> shift) & 0xff) / 255 } + return CGColor(srgbRed: channel(16), green: channel(8), blue: channel(0), alpha: channel(24) * alphaScale) + } +} + +/// One row as the caller described it: cell text, column spans and style spans. +struct TerminalRowSource { + let text: String + let cells: [Int] + let styles: [Double] + + /// Decodes `cells;styles;text`, where both number lists are comma separated. + init(encoded: String) { + let utf8 = encoded.utf8 + let separator = UInt8(ascii: ";") + let cellsEnd = utf8.firstIndex(of: separator) ?? utf8.endIndex + let stylesStart = cellsEnd == utf8.endIndex ? cellsEnd : utf8.index(after: cellsEnd) + let stylesEnd = utf8[stylesStart...].firstIndex(of: separator) ?? utf8.endIndex + let textStart = stylesEnd == utf8.endIndex ? stylesEnd : utf8.index(after: stylesEnd) + cells = TerminalRowSource.parseNumbers(utf8[utf8.startIndex.. [Int64] { + guard !bytes.isEmpty else { return [] } + var numbers: [Int64] = [0] + for byte in bytes { + if byte == UInt8(ascii: ",") { + numbers.append(0) + } else { + numbers[numbers.count - 1] = numbers[numbers.count - 1] * 10 + Int64(byte - UInt8(ascii: "0")) + } + } + return numbers + } +} + +struct TerminalSelection: Equatable { + let startRow: Int + let startCol: Int + let endRow: Int + let endCol: Int + + init(_ record: TerminalSelectionRecord) { + startRow = record.startRow + startCol = record.startCol + endRow = record.endRow + endCol = record.endCol + } + + func intersects(row: Int) -> Bool { row >= startRow && row <= endRow } + + /// A cell is selected when any column it covers is inside the inclusive range. + func contains(row: Int, col: Int, span: Int) -> Bool { + guard intersects(row: row) else { return false } + let firstCol = row == startRow ? startCol : 0 + let lastCol = row == endRow ? endCol : Int.max + return col + span - 1 >= firstCol && col <= lastCol + } + + /// The part of the selection on one row, so a row only repaints when its own part changes. + func columns(onRow row: Int) -> ClosedRange? { + guard intersects(row: row) else { return nil } + return (row == startRow ? startCol : 0)...(row == endRow ? endCol : Int.max) + } +} diff --git a/packages/app/modules/paseo-terminal/ios/TerminalRowLayout.swift b/packages/app/modules/paseo-terminal/ios/TerminalRowLayout.swift new file mode 100644 index 0000000000..80050c9040 --- /dev/null +++ b/packages/app/modules/paseo-terminal/ios/TerminalRowLayout.swift @@ -0,0 +1,335 @@ +import CoreText +import UIKit + +/// Shaped glyphs may exceed their slot by this many points before they are scaled down. +private let overflowTolerance: CGFloat = 0.5 +/// Stands in for an open edge when a group is clipped on one side only. +private let clipUnbounded: CGFloat = 100_000 + +/// Lays text out left to right in logical order. The override fixes every character's direction; +/// the base direction also covers trailing spaces, which bidi rule L1 otherwise moves to the +/// direction detected from the first strong character, ahead of an Arabic or Hebrew row. +private let leftToRightAttributes: [NSAttributedString.Key: Any] = { + var base = CTWritingDirection.leftToRight + let paragraph = withUnsafeBytes(of: &base) { bytes in + CTParagraphStyleCreate( + [CTParagraphStyleSetting( + spec: .baseWritingDirection, valueSize: MemoryLayout.size, value: bytes.baseAddress!)], + 1) + } + let overrideLeftToRight = CTWritingDirection.leftToRight.rawValue | 2 // kCTWritingDirectionOverride + return [ + NSAttributedString.Key(kCTWritingDirectionAttributeName as String): [NSNumber(value: overrideLeftToRight)], + NSAttributedString.Key(kCTParagraphStyleAttributeName as String): paragraph, + ] +}() + +/// Colors a row is painted with besides its own styles. +struct TerminalRowPaint { + let selectionBackground: TerminalColor + let selectionForeground: TerminalColor +} + +/// One row shaped once and placed on the terminal grid. +/// +/// Each run of cells with the same font face is shaped as a whole line, in logical order and left +/// to right like the terminal grid, so contextual forms, ligatures, marks and fallback fonts see +/// their neighbours. CoreText reports which UTF-16 offset produced each glyph. Cells whose units +/// produced no advancing glyph, and cells a reordered glyph crosses, join the cluster of the cell +/// before them: a ligature, conjunct, emoji sequence or reordered mark that spans columns. Each +/// group is drawn at its first cell's column with the glyph offsets CoreText produced, centred in +/// the columns it owns and scaled down only when wider than them. Colors never split groups. +final class TerminalRowLayout { + let source: TerminalRowSource + private let font: TerminalFont + private let units: [UInt16] + private let cellCount: Int + private var cellCol: [Int] + private var cellSpan: [Int] + private var cellStart: [Int] + private var cellEnd: [Int] + private var cellForeground: [TerminalColor] + private var cellBackground: [TerminalColor] + private var cellFlags: [Int] + private var cellGlyph: [TerminalCustomGlyph?] + private var groups: [Group] = [] + /// The row's painted extent, relative to its top edge. Marks stacked above or below a + /// letter and some fallback glyphs ink outside the row; the view repaints that area with it. + private(set) var inkTop: CGFloat = 0 + private(set) var inkBottom: CGFloat + + private struct GlyphRun { + let font: CTFont + var glyphs: [CGGlyph] + /// Relative to the group's pen origin, y up from the baseline. + var positions: [CGPoint] + } + + private struct Group { + let firstCell: Int + let lastCell: Int + let col: Int + let offset: CGFloat + let scale: CGFloat + let runs: [GlyphRun] + } + + private struct ShapedGlyph { + let font: CTFont + let glyph: CGGlyph + let position: CGPoint + let advance: CGFloat + let cell: Int + } + + init(source: TerminalRowSource, font: TerminalFont, customGlyphs: TerminalCustomGlyphs) { + self.source = source + self.font = font + units = Array(source.text.utf16) + cellCount = source.cells.count / 2 + cellCol = Array(repeating: 0, count: cellCount) + cellSpan = Array(repeating: 1, count: cellCount) + cellStart = Array(repeating: 0, count: cellCount) + cellEnd = Array(repeating: 0, count: cellCount) + cellForeground = Array(repeating: TerminalColor(0), count: cellCount) + cellBackground = Array(repeating: TerminalColor(0), count: cellCount) + cellFlags = Array(repeating: 0, count: cellCount) + cellGlyph = Array(repeating: nil, count: cellCount) + inkBottom = font.cellHeight + readCells(customGlyphs: customGlyphs) + shapeRuns() + } + + var accessibilityText: String { + var text = source.text + while text.last == " " { text.removeLast() } + return text + } + + private func readCells(customGlyphs: TerminalCustomGlyphs) { + var offset = 0 + var col = 0 + var styleIndex = 0 + var styleEndCol = 0 + for cell in 0..= styleEndCol && styleIndex + 3 < source.styles.count { + styleEndCol += Int(source.styles[styleIndex]) + styleIndex += 4 + } + let style = styleIndex - 4 + if style >= 0 { + cellForeground[cell] = TerminalColor(source.styles[style + 1]) + cellBackground[cell] = TerminalColor(source.styles[style + 2]) + cellFlags[cell] = Int(source.styles[style + 3]) + } + cellCol[cell] = col + cellSpan[cell] = span + cellStart[cell] = offset + cellEnd[cell] = min(units.count, offset + length) + cellGlyph[cell] = customGlyphs[text(from: cellStart[cell], to: cellEnd[cell])] + offset = cellEnd[cell] + col += span + } + } + + private func text(from start: Int, to end: Int) -> String { + String(utf16CodeUnits: Array(units[start.. Bool { + cellGlyph[cell] == nil && cellGlyph[other] == nil + && TerminalFont.face(flags: cellFlags[cell]) == TerminalFont.face(flags: cellFlags[other]) + } + + private func shapeRuns() { + var cell = 0 + while cell < cellCount { + if cellGlyph[cell] != nil { + cell += 1 + continue + } + var last = cell + while last + 1 < cellCount && shapesWith(cell, last + 1) { last += 1 } + shapeRun(first: cell, last: last) + cell = last + 1 + } + } + + private func shapeRun(first: Int, last: Int) { + let start = cellStart[first] + let end = cellEnd[last] + guard end > start else { return } + var cellOfUnit = Array(repeating: first, count: end - start) + for cell in first...last where cellEnd[cell] > cellStart[cell] { + for unit in cellStart[cell].. 0 else { continue } + let runAttributes = CTRunGetAttributes(run) as NSDictionary + let runFont = runAttributes[kCTFontAttributeName as String].map { $0 as! CTFont } + ?? font.font(flags: cellFlags[first]) + var glyphs = Array(repeating: CGGlyph(0), count: count) + var positions = Array(repeating: CGPoint.zero, count: count) + var advances = Array(repeating: CGSize.zero, count: count) + var indices = Array(repeating: CFIndex(0), count: count) + let all = CFRange(location: 0, length: 0) + CTRunGetGlyphs(run, all, &glyphs) + CTRunGetPositions(run, all, &positions) + CTRunGetAdvances(run, all, &advances) + CTRunGetStringIndices(run, all, &indices) + for index in 0.. first { + for cell in (first + 1)...last where advance[cell - first] == 0 { + startsCluster[cell - first] = false + } + } + + var groupFirst = first + for cell in first...last { + let closesGroup = cell == last || startsCluster[cell + 1 - first] + guard closesGroup else { continue } + addGroup(first: groupFirst, last: cell, glyphs: shaped.filter { $0.cell >= groupFirst && $0.cell <= cell }) + groupFirst = cell + 1 + } + } + + private func addGroup(first: Int, last: Int, glyphs: [ShapedGlyph]) { + let isBlank = (cellStart[first].. slot + overflowTolerance ? slot / advance : 1 + let offset = scale < 1 ? 0 : (slot - advance) / 2 + var runs: [GlyphRun] = [] + for glyph in glyphs { + let position = CGPoint(x: glyph.position.x - origin, y: glyph.position.y) + if let lastRun = runs.last, CFEqual(lastRun.font, glyph.font) { + runs[runs.count - 1].glyphs.append(glyph.glyph) + runs[runs.count - 1].positions.append(position) + } else { + runs.append(GlyphRun(font: glyph.font, glyphs: [glyph.glyph], positions: [position])) + } + } + groups.append(Group( + firstCell: first, lastCell: last, col: cellCol[first], offset: offset, scale: scale, runs: runs)) + extendInk(runs: runs, scale: scale) + } + + /// Grows the row's ink extent to cover the glyphs as `draw` places them, padded by a device pixel + /// for antialiasing. + private func extendInk(runs: [GlyphRun], scale: CGFloat) { + let centerY = font.cellHeight / 2 + let baselineInTextSpace = font.cellHeight / 2 - font.baseline + let pixel = 1 / font.displayScale + for run in runs { + var bounds = Array(repeating: CGRect.zero, count: run.glyphs.count) + CTFontGetBoundingRectsForGlyphs(run.font, .horizontal, run.glyphs, &bounds, run.glyphs.count) + for (glyph, position) in zip(bounds, run.positions) where !glyph.isEmpty { + let top = centerY - (position.y + baselineInTextSpace + glyph.maxY) * scale - pixel + let bottom = centerY - (position.y + baselineInTextSpace + glyph.minY) * scale + pixel + inkTop = min(inkTop, (top * font.displayScale).rounded(.down) / font.displayScale) + inkBottom = max(inkBottom, (bottom * font.displayScale).rounded(.up) / font.displayScale) + } + } + } + + private func isSelected(_ cell: Int, row: Int, selection: TerminalSelection?) -> Bool { + selection?.contains(row: row, col: cellCol[cell], span: cellSpan[cell]) ?? false + } + + private func foreground(_ cell: Int, row: Int, selection: TerminalSelection?, paint: TerminalRowPaint) -> TerminalColor { + isSelected(cell, row: row, selection: selection) ? paint.selectionForeground : cellForeground[cell] + } + + /// Draws the row with its top edge at `top`, selected cells in selection colors. + func draw(in context: CGContext, row: Int, top: CGFloat, selection: TerminalSelection?, paint: TerminalRowPaint) { + let cellWidth = font.cellWidth + let cellHeight = font.cellHeight + for cell in 0.. group.firstCell || last < group.lastCell { + let left = first > group.firstCell ? CGFloat(cellCol[first]) * cellWidth : -clipUnbounded + let right = last < group.lastCell ? CGFloat(cellCol[last] + cellSpan[last]) * cellWidth : clipUnbounded + context.clip(to: CGRect(x: left, y: -clipUnbounded, width: right - left, height: 2 * clipUnbounded)) + } + context.setFillColor(color.cgColor()) + context.translateBy(x: CGFloat(group.col) * cellWidth + group.offset, y: centerY) + context.scaleBy(x: group.scale, y: -group.scale) + context.textMatrix = .identity + for run in group.runs { + let positions = run.positions.map { CGPoint(x: $0.x, y: $0.y + baselineInTextSpace) } + CTFontDrawGlyphs(run.font, run.glyphs, positions, run.glyphs.count, context) + } + context.restoreGState() + first = last + 1 + } + } + + let baseline = top + font.baseline + for cell in 0.. { hasNotifiedMeasuredSizeRef.current = false; resetTerminal(mountInputRef.current.initialSnapshot); - callbacksRef.current.onRendererReadyChange?.({ streamKey, isReady: true }); + emitMeasuredSize({ source: "measure" }); return () => { callbacksRef.current.onRendererReadyChange?.({ streamKey, isReady: false }); clearSelectionLongPressTimeout(); @@ -604,7 +613,7 @@ function NativeTerminalEmulator({ terminalRef.current?.dispose(); terminalRef.current = null; }; - }, [clearSelectionLongPressTimeout, resetTerminal, streamKey]); + }, [clearSelectionLongPressTimeout, emitMeasuredSize, resetTerminal, streamKey]); useEffect(() => { if (focusRequestToken <= 0) return; diff --git a/packages/app/src/terminal/native-renderer/colors.ts b/packages/app/src/terminal/native-renderer/colors.ts index dfebe4eb4d..03452cd30b 100644 --- a/packages/app/src/terminal/native-renderer/colors.ts +++ b/packages/app/src/terminal/native-renderer/colors.ts @@ -1,6 +1,6 @@ import type { ITheme } from "@xterm/xterm"; -import type { TextStyle } from "react-native"; import type { TerminalCell } from "@getpaseo/protocol/messages"; +import { PASEO_TERMINAL_STYLE_FLAGS } from "../../../modules/paseo-terminal/contract"; import { darkTheme } from "@/styles/theme"; import { toXtermTheme } from "@/utils/to-xterm-theme"; @@ -29,77 +29,115 @@ const DEFAULT_COLOR_MODE = 0; const ANSI_COLOR_MODE = 1; const INDEXED_COLOR_MODE = 2; const RGB_COLOR_MODE = 3; -const FLAG_BOLD = 1 << 0; -const FLAG_ITALIC = 1 << 1; -const FLAG_UNDERLINE = 1 << 2; -const FLAG_DIM = 1 << 3; -const FLAG_INVERSE = 1 << 4; -const FLAG_STRIKETHROUGH = 1 << 5; +const OPAQUE_BLACK = 0xff000000; +const DIM_ALPHA = 0.65; -interface ResolvedCellStyle { - key: string; - style: TextStyle; - foregroundColor: string; -} - -interface ResolvedCellColors { - foreground: string; - background: string; - paintsBackground: boolean; +/** Colors are unsigned ARGB. A background of 0 is the terminal background. */ +export interface ResolvedCellStyle { + foreground: number; + background: number; + flags: number; } export interface TerminalCellStyleResolver { - readonly themeKey: string; - readonly backgroundColor: string; - readonly cursorColor: string; + readonly backgroundColor: number; + readonly cursorColor: number; resolve(cell: TerminalCell): ResolvedCellStyle; } export const DEFAULT_TERMINAL_THEME = toXtermTheme(darkTheme.colors.terminal); export const NATIVE_TERMINAL_SELECTION_COLORS = { - background: "#ffff00", - foreground: "#000000", + background: 0xffffff00, + foreground: 0xff000000, } as const; -function build256Palette(theme: ITheme): string[] { - const palette = Array.from({ length: 256 }, () => ""); +function build256Palette(theme: ITheme): number[] { + const palette = Array.from({ length: 256 }, () => OPAQUE_BLACK); for (let index = 0; index < ANSI_THEME_KEYS.length; index += 1) { const key = ANSI_THEME_KEYS[index]; - palette[index] = theme[key] ?? DEFAULT_TERMINAL_THEME[key] ?? "#000000"; + palette[index] = parseTerminalColor(theme[key] ?? DEFAULT_TERMINAL_THEME[key], OPAQUE_BLACK); } for (let red = 0; red < CUBE_LEVELS.length; red += 1) { for (let green = 0; green < CUBE_LEVELS.length; green += 1) { for (let blue = 0; blue < CUBE_LEVELS.length; blue += 1) { const index = 16 + red * 36 + green * 6 + blue; - palette[index] = `rgb(${CUBE_LEVELS[red]}, ${CUBE_LEVELS[green]}, ${CUBE_LEVELS[blue]})`; + palette[index] = rgbColor( + (CUBE_LEVELS[red] << 16) | (CUBE_LEVELS[green] << 8) | CUBE_LEVELS[blue], + ); } } } for (let index = 0; index < 24; index += 1) { const value = 8 + index * 10; - palette[232 + index] = `rgb(${value}, ${value}, ${value})`; + palette[232 + index] = rgbColor((value << 16) | (value << 8) | value); } return palette; } -function rgbColor(value: number): string { - const red = (value >> 16) & 0xff; - const green = (value >> 8) & 0xff; - const blue = value & 0xff; - return `rgb(${red}, ${green}, ${blue})`; +function rgbColor(value: number): number { + return (OPAQUE_BLACK | (value & 0xffffff)) >>> 0; +} + +function argb(input: { alpha: number; red: number; green: number; blue: number }): number { + const channel = (value: number) => Math.max(0, Math.min(255, Math.round(value))); + return ( + ((channel(input.alpha) << 24) | + (channel(input.red) << 16) | + (channel(input.green) << 8) | + channel(input.blue)) >>> + 0 + ); +} + +/** Parses the CSS color forms terminal themes use: `#rgb`, `#rrggbb`, `#rrggbbaa`, `rgb()`, `rgba()`. */ +export function parseTerminalColor(value: string | undefined, fallback: number): number { + if (!value) return fallback; + const color = value.trim().toLowerCase(); + const hex = /^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/.exec(color)?.[1]; + if (hex) { + const digits = hex.length === 3 ? [...hex].map((digit) => digit + digit).join("") : hex; + const channel = (offset: number) => Number.parseInt(digits.slice(offset, offset + 2), 16); + return argb({ + alpha: digits.length === 8 ? channel(6) : 255, + red: channel(0), + green: channel(2), + blue: channel(4), + }); + } + const functional = /^rgba?\(([^)]*)\)$/.exec(color)?.[1]; + if (functional) { + const parts = functional + .split(/[\s,/]+/) + .filter(Boolean) + .map(Number); + if (parts.length >= 3 && parts.every((part) => Number.isFinite(part))) { + return argb({ + alpha: parts.length >= 4 ? parts[3] * 255 : 255, + red: parts[0], + green: parts[1], + blue: parts[2], + }); + } + } + return fallback; +} + +function withDimAlpha(color: number): number { + const alpha = (color >>> 24) & 0xff; + return (((Math.round(alpha * DIM_ALPHA) & 0xff) << 24) | (color & 0xffffff)) >>> 0; } function resolveColor(input: { value: number | undefined; mode: number | undefined; - fallback: string; - palette: string[]; -}): string { + fallback: number; + palette: number[]; +}): number { const mode = input.mode ?? DEFAULT_COLOR_MODE; const value = input.value ?? 0; @@ -114,131 +152,50 @@ function resolveColor(input: { function cellFlags(cell: TerminalCell): number { let flags = 0; - if (cell.bold) flags |= FLAG_BOLD; - if (cell.italic) flags |= FLAG_ITALIC; - if (cell.underline) flags |= FLAG_UNDERLINE; - if (cell.dim) flags |= FLAG_DIM; - if (cell.inverse) flags |= FLAG_INVERSE; - if (cell.strikethrough) flags |= FLAG_STRIKETHROUGH; + if (cell.bold) flags |= PASEO_TERMINAL_STYLE_FLAGS.bold; + if (cell.italic) flags |= PASEO_TERMINAL_STYLE_FLAGS.italic; + if (cell.underline) flags |= PASEO_TERMINAL_STYLE_FLAGS.underline; + if (cell.strikethrough) flags |= PASEO_TERMINAL_STYLE_FLAGS.strikethrough; + if (cell.dim) flags |= PASEO_TERMINAL_STYLE_FLAGS.dim; return flags; } -function resolveCellColors(input: { - cell: TerminalCell; - palette: string[]; - foregroundColor: string; - backgroundColor: string; -}): ResolvedCellColors { - const foreground = resolveColor({ - value: input.cell.fg, - mode: input.cell.fgMode, - fallback: input.foregroundColor, - palette: input.palette, - }); - const background = resolveColor({ - value: input.cell.bg, - mode: input.cell.bgMode, - fallback: input.backgroundColor, - palette: input.palette, - }); - - const resolvedForeground = input.cell.inverse ? background : foreground; - const resolvedBackground = input.cell.inverse ? foreground : background; - return { - foreground: resolvedForeground, - background: resolvedBackground, - paintsBackground: resolvedBackground !== input.backgroundColor, - }; -} - -function textDecorationLine(flags: number): TextStyle["textDecorationLine"] | undefined { - const underline = (flags & FLAG_UNDERLINE) !== 0; - const strikethrough = (flags & FLAG_STRIKETHROUGH) !== 0; - if (underline && strikethrough) return "underline line-through"; - if (underline) return "underline"; - if (strikethrough) return "line-through"; - return undefined; -} - -function createTextStyle(input: { - foreground: string; - background: string; - paintsBackground: boolean; - flags: number; -}): TextStyle { - const style: TextStyle = { - color: input.foreground, - }; - - if (input.paintsBackground) { - style.backgroundColor = input.background; - } - if ((input.flags & FLAG_BOLD) !== 0) { - style.fontWeight = "700"; - } - if ((input.flags & FLAG_ITALIC) !== 0) { - style.fontStyle = "italic"; - } - if ((input.flags & FLAG_DIM) !== 0) { - style.opacity = 0.65; - } - - const decorationLine = textDecorationLine(input.flags); - if (decorationLine) { - style.textDecorationLine = decorationLine; - style.textDecorationColor = input.foreground; - } - - return style; -} - -function buildStyleKey(input: { - foreground: string; - background: string; - paintsBackground: boolean; - flags: number; -}): string { - const background = input.paintsBackground ? input.background : "default"; - return `${input.foreground}|${background}|${input.flags}`; -} - -function buildThemeKey(theme: ITheme): string { - return JSON.stringify(theme); -} - export function createTerminalCellStyleResolver(theme: ITheme): TerminalCellStyleResolver { const palette = build256Palette(theme); - const foregroundColor = theme.foreground ?? DEFAULT_TERMINAL_THEME.foreground ?? "#fafafa"; - const backgroundColor = theme.background ?? DEFAULT_TERMINAL_THEME.background ?? "#181B1A"; - const cursorColor = theme.cursor ?? foregroundColor; - const styleCache = new Map(); + const foregroundColor = parseTerminalColor( + theme.foreground ?? DEFAULT_TERMINAL_THEME.foreground, + 0xfffafafa, + ); + const backgroundColor = parseTerminalColor( + theme.background ?? DEFAULT_TERMINAL_THEME.background, + 0xff181b1a, + ); + const cursorColor = parseTerminalColor(theme.cursor, foregroundColor); return { - themeKey: buildThemeKey(theme), backgroundColor, cursorColor, resolve(cell: TerminalCell): ResolvedCellStyle { + const foreground = resolveColor({ + value: cell.fg, + mode: cell.fgMode, + fallback: foregroundColor, + palette, + }); + const background = resolveColor({ + value: cell.bg, + mode: cell.bgMode, + fallback: backgroundColor, + palette, + }); + const resolvedForeground = cell.inverse ? background : foreground; + const resolvedBackground = cell.inverse ? foreground : background; const flags = cellFlags(cell); - const colors = resolveCellColors({ cell, palette, foregroundColor, backgroundColor }); - const key = buildStyleKey({ - foreground: colors.foreground, - background: colors.background, - paintsBackground: colors.paintsBackground, + return { + foreground: cell.dim ? withDimAlpha(resolvedForeground) : resolvedForeground, + background: resolvedBackground === backgroundColor ? 0 : resolvedBackground, flags, - }); - const cachedStyle = styleCache.get(key); - if (cachedStyle) { - return { key, style: cachedStyle, foregroundColor: colors.foreground }; - } - - const style = createTextStyle({ - foreground: colors.foreground, - background: colors.background, - paintsBackground: colors.paintsBackground, - flags, - }); - styleCache.set(key, style); - return { key, style, foregroundColor: colors.foreground }; + }; }, }; } diff --git a/packages/app/src/terminal/native-renderer/terminal-frame.test.ts b/packages/app/src/terminal/native-renderer/terminal-frame.test.ts new file mode 100644 index 0000000000..129a7d9082 --- /dev/null +++ b/packages/app/src/terminal/native-renderer/terminal-frame.test.ts @@ -0,0 +1,199 @@ +import { describe, expect, test } from "vitest"; + +import graphemeRows from "../../../modules/paseo-terminal/android/src/androidTest/assets/grapheme-rows.json"; +import { PASEO_TERMINAL_STYLE_FLAGS } from "../../../modules/paseo-terminal/contract"; +import { encodeTerminalFrame } from "../../../modules/paseo-terminal/frame-encoding"; +import { + createTerminalCellStyleResolver, + DEFAULT_TERMINAL_THEME, + parseTerminalColor, +} from "./colors"; +import { createNativeHeadlessTerminal } from "./headless-terminal-state"; +import { buildTerminalFrame } from "./terminal-frame"; + +const resolver = createTerminalCellStyleResolver(DEFAULT_TERMINAL_THEME); +const RED = parseTerminalColor(DEFAULT_TERMINAL_THEME.red, 0); +const FOREGROUND = parseTerminalColor(DEFAULT_TERMINAL_THEME.foreground, 0); + +async function frameFor(output: string, options: { cols?: number; rows?: number } = {}) { + const terminal = createNativeHeadlessTerminal({ + cols: options.cols ?? 20, + rows: options.rows ?? 4, + }); + await terminal.write(output); + const state = terminal.getViewportState({ firstRow: 0, rowCount: options.rows ?? 4 }); + terminal.dispose(); + return { + state, + frame: buildTerminalFrame({ state, columns: state.cols, resolver, selection: null }), + }; +} + +function cellLayout(row: { text: string; cells: number[] }) { + const layout: Array<{ text: string; col: number; span: number }> = []; + let offset = 0; + let col = 0; + for (let index = 0; index < row.cells.length; index += 2) { + const [length, span] = [row.cells[index], row.cells[index + 1]]; + layout.push({ text: row.text.slice(offset, offset + length), col, span }); + offset += length; + col += span; + } + return layout; +} + +/** Indexes of the cells that start a grapheme cluster. */ +function clusterStartCells(row: { text: string; cells: number[] }, segmenter: Intl.Segmenter) { + const boundaries = new Set(Array.from(segmenter.segment(row.text), (segment) => segment.index)); + const starts: number[] = []; + let offset = 0; + for (let cell = 0; cell < row.cells.length / 2; cell += 1) { + if (boundaries.has(offset)) starts.push(cell); + offset += row.cells[cell * 2]; + } + return starts; +} + +describe("native terminal frame", () => { + test("keeps each Hangul syllable on xterm's two-column allocation", async () => { + const { frame } = await frameFor("> 안녕하세요"); + + expect(cellLayout(frame.rows[0]).slice(0, 7)).toEqual([ + { text: ">", col: 0, span: 1 }, + { text: " ", col: 1, span: 1 }, + { text: "안", col: 2, span: 2 }, + { text: "녕", col: 4, span: 2 }, + { text: "하", col: 6, span: 2 }, + { text: "세", col: 8, span: 2 }, + { text: "요", col: 10, span: 2 }, + ]); + expect(frame.cursor).toEqual({ row: 0, col: 12 }); + }); + + test("covers every column once, including trailing blanks", async () => { + const corpus = ["안녕하세요NEXT", "日本語 中文", "áé é x̸", "क्ष कि ❤️ 👩‍💻 🇰🇷"]; + const { frame } = await frameFor(corpus.join("\r\n"), { rows: 4, cols: 24 }); + + for (const row of frame.rows) { + const spans = row.cells.filter((_, index) => index % 2 === 1); + const styleColumns = row.styles.filter((_, index) => index % 4 === 0); + expect(spans.reduce((total, span) => total + span, 0)).toBe(24); + expect(styleColumns.reduce((total, span) => total + span, 0)).toBe(24); + expect(row.cells.filter((_, index) => index % 2 === 0).reduce((a, b) => a + b, 0)).toBe( + row.text.length, + ); + } + }); + + test("keeps combining marks and joiners inside the cell xterm assigned them", async () => { + const { frame } = await frameFor("éx̸ 각 क्ष 👩‍💻"); + + expect(cellLayout(frame.rows[0]).slice(0, 11)).toEqual([ + { text: "é", col: 0, span: 1 }, + { text: "x̸", col: 1, span: 1 }, + { text: " ", col: 2, span: 1 }, + { text: "각", col: 3, span: 2 }, + { text: " ", col: 5, span: 1 }, + { text: "क्", col: 6, span: 1 }, + { text: "ष", col: 7, span: 1 }, + { text: " ", col: 8, span: 1 }, + { text: "👩‍", col: 9, span: 1 }, + { text: "💻", col: 10, span: 1 }, + { text: " ", col: 11, span: 1 }, + ]); + }); + + test("splits style spans at SGR changes without moving cells", async () => { + const { frame } = await frameFor("안녕\x1b[31mNEXT\x1b[0m\x1b[1;4m!\x1b[0m"); + const row = frame.rows[0]; + + expect( + cellLayout(row) + .slice(0, 7) + .map((cell) => cell.col), + ).toEqual([0, 2, 4, 5, 6, 7, 8]); + expect(row.styles.slice(0, 12)).toEqual([ + 4, + FOREGROUND, + 0, + 0, + 4, + RED, + 0, + 0, + 1, + FOREGROUND, + 0, + PASEO_TERMINAL_STYLE_FLAGS.bold | PASEO_TERMINAL_STYLE_FLAGS.underline, + ]); + }); + + test("resolves inverse and dim into paint colors", async () => { + const { frame } = await frameFor("\x1b[7mI\x1b[0m\x1b[2mD\x1b[0m"); + const background = parseTerminalColor(DEFAULT_TERMINAL_THEME.background, 0); + + expect(frame.rows[0].styles.slice(0, 8)).toEqual([ + 1, + background, + FOREGROUND, + 0, + 1, + (((Math.round(255 * 0.65) & 0xff) << 24) | (FOREGROUND & 0xffffff)) >>> 0, + 0, + PASEO_TERMINAL_STYLE_FLAGS.dim, + ]); + }); + + test("rows follow content and style but not cursor or selection", async () => { + const plain = await frameFor("same\r\nrow"); + const moved = await frameFor("same\r\nrow\x1b[1;1H"); + const recolored = await frameFor("\x1b[31msame\x1b[0m\r\nrow"); + + expect(moved.frame.rows[0]).toEqual(plain.frame.rows[0]); + expect(moved.frame.cursor).not.toEqual(plain.frame.cursor); + expect(recolored.frame.rows[0]).not.toEqual(plain.frame.rows[0]); + + const selected = buildTerminalFrame({ + state: plain.state, + columns: plain.state.cols, + resolver, + selection: { + start: { row: 0, col: 1 }, + end: { row: 1, col: 0 }, + coordinateEpoch: 0, + }, + }); + expect(selected.rows).toEqual(plain.frame.rows); + expect(selected.selection).toEqual({ startRow: 0, startCol: 1, endRow: 1, endCol: 0 }); + }); + + test("clips the frame to the visible columns", async () => { + const { state } = await frameFor("0123456789abcdefghij"); + const frame = buildTerminalFrame({ state, columns: 8, resolver, selection: null }); + + expect(frame.columns).toBe(8); + expect(frame.rows[0].text).toBe("01234567"); + }); + + // The Android instrumented test draws these rows and compares them with each cluster drawn on its + // own. This keeps its input equal to what xterm produces, and its clusters equal to UAX #29 + // grapheme clusters. `contrastStarts` is a wrong clustering the comparison must reject. + test("Android cluster fixture matches xterm cells and grapheme clusters", async () => { + const segmenter = new Intl.Segmenter("und", { granularity: "grapheme" }); + const actual = await Promise.all( + graphemeRows.map(async ({ output, contrastStarts }) => { + const { frame } = await frameFor(output, { cols: 8, rows: 1 }); + const row = frame.rows[0]; + const [encoded] = encodeTerminalFrame({ ...frame, rows: [row] }).rows; + return { + output, + row: encoded, + clusterStarts: clusterStartCells(row, segmenter), + contrastStarts, + }; + }), + ); + + expect(actual).toEqual(graphemeRows); + }); +}); diff --git a/packages/app/src/terminal/native-renderer/terminal-frame.ts b/packages/app/src/terminal/native-renderer/terminal-frame.ts new file mode 100644 index 0000000000..584e09a274 --- /dev/null +++ b/packages/app/src/terminal/native-renderer/terminal-frame.ts @@ -0,0 +1,84 @@ +import type { + PaseoTerminalFrame, + PaseoTerminalRow, + PaseoTerminalSelection, +} from "../../../modules/paseo-terminal/contract"; +import type { TerminalCellStyleResolver } from "./colors"; +import type { NativeTerminalCell, TerminalViewportState } from "./headless-terminal-state"; +import type { TerminalSelectionRange } from "./terminal-selection"; + +/** + * Converts the xterm viewport into the native renderer's frame. Every cell keeps its own text and + * xterm's column span; continuation cells of wide characters (width 0) belong to the cell before + * them. Nothing here measures or joins text: the renderer shapes rows and places the result on + * these columns. + */ +export function buildTerminalFrame(input: { + state: TerminalViewportState; + columns: number; + resolver: TerminalCellStyleResolver; + selection: TerminalSelectionRange | null; +}): PaseoTerminalFrame { + const grid = input.state.grid as NativeTerminalCell[][]; + return { + columns: input.columns, + rows: grid.map((cells) => + buildRow({ cells, columns: input.columns, resolver: input.resolver }), + ), + cursor: input.state.cursor.hidden + ? null + : { row: input.state.cursor.row, col: input.state.cursor.col }, + selection: input.selection + ? toFrameSelection({ range: input.selection, firstRow: input.state.firstRow }) + : null, + }; +} + +function buildRow(input: { + cells: NativeTerminalCell[]; + columns: number; + resolver: TerminalCellStyleResolver; +}): PaseoTerminalRow { + let text = ""; + const cells: number[] = []; + const styles: number[] = []; + const lastColumn = Math.min(input.columns, input.cells.length); + + for (let col = 0; col < lastColumn; col += 1) { + const cell = input.cells[col]; + const span = cell.width ?? 1; + if (span <= 0) { + continue; + } + const cellText = cell.char || " "; + text += cellText; + cells.push(cellText.length, span); + + const style = input.resolver.resolve(cell); + const previous = styles.length - 4; + if ( + previous >= 0 && + styles[previous + 1] === style.foreground && + styles[previous + 2] === style.background && + styles[previous + 3] === style.flags + ) { + styles[previous] += span; + } else { + styles.push(span, style.foreground, style.background, style.flags); + } + } + + return { text, cells, styles }; +} + +function toFrameSelection(input: { + range: TerminalSelectionRange; + firstRow: number; +}): PaseoTerminalSelection { + return { + startRow: input.range.start.row - input.firstRow, + startCol: input.range.start.col, + endRow: input.range.end.row - input.firstRow, + endCol: input.range.end.col, + }; +} diff --git a/packages/app/src/terminal/native-renderer/terminal-grid-metrics.test.ts b/packages/app/src/terminal/native-renderer/terminal-grid-metrics.test.ts index 0c4d7bc25f..c0fef99104 100644 --- a/packages/app/src/terminal/native-renderer/terminal-grid-metrics.test.ts +++ b/packages/app/src/terminal/native-renderer/terminal-grid-metrics.test.ts @@ -1,68 +1,8 @@ import { describe, expect, it } from "vitest"; -import { - resolveTerminalCustomGlyphCellTransform, - resolveTerminalGridMetricsMeasurement, - resolveMeasuredTerminalCellMetrics, - resolveTerminalCursorOffset, -} from "./terminal-grid-metrics"; +import { resolveTerminalGridMetricsMeasurement } from "./terminal-grid-metrics"; describe("native terminal grid metrics", () => { - it("places each normalized custom glyph in run viewport coordinates", () => { - expect( - resolveTerminalCustomGlyphCellTransform({ - cellOffset: 57, - cellWidth: 7.4, - cellHeight: 16.2, - }), - ).toBe("matrix(7.4 0 0 16.2 421.8 0)"); - }); - - it("preserves fractional measured cell width for horizontal layout", () => { - expect( - resolveMeasuredTerminalCellMetrics({ - measuredTextWidth: 72.246, - measuredTextHeight: 16.2, - measureTextLength: 10, - roundToNearestPixel: (value) => value, - }), - ).toEqual({ - cellWidth: 7.2246, - cellHeight: 16.2, - }); - }); - - it.each([1, 2, 2.75, 3, 3.5])( - "aligns cells to the physical pixel grid at density %s", - (density) => { - const metrics = resolveMeasuredTerminalCellMetrics({ - measuredTextWidth: 72.246, - measuredTextHeight: 16.2, - measureTextLength: 10, - roundToNearestPixel: (value) => Math.round(value * density) / density, - }); - - expect(metrics.cellWidth * density).toBeCloseTo(Math.round(metrics.cellWidth * density), 10); - expect(metrics.cellHeight * density).toBeCloseTo( - Math.round(metrics.cellHeight * density), - 10, - ); - }, - ); - - it("positions the cursor with the measured fractional cell width", () => { - expect( - resolveTerminalCursorOffset({ - cursorCol: 80, - cursorRow: 3, - metrics: { cellWidth: 7.2246, cellHeight: 16 }, - }), - ).toEqual({ - x: 577.968, - y: 48, - }); - }); - it("emits measured metrics once until the measurement changes", () => { const measured = { cellWidth: 7.2, cellHeight: 16 }; diff --git a/packages/app/src/terminal/native-renderer/terminal-grid-metrics.ts b/packages/app/src/terminal/native-renderer/terminal-grid-metrics.ts index cb14111bf2..806c149c60 100644 --- a/packages/app/src/terminal/native-renderer/terminal-grid-metrics.ts +++ b/packages/app/src/terminal/native-renderer/terminal-grid-metrics.ts @@ -3,47 +3,6 @@ export interface TerminalGridCellMetrics { cellHeight: number; } -export interface TerminalGridCellMetricsInput { - measuredTextWidth: number; - measuredTextHeight: number; - measureTextLength: number; - roundToNearestPixel: (value: number) => number; -} - -export interface TerminalCursorOffsetInput { - cursorCol: number; - cursorRow: number; - metrics: TerminalGridCellMetrics; -} - -export interface TerminalCursorOffset { - x: number; - y: number; -} - -export interface TerminalCustomGlyphCellTransformInput { - cellOffset: number; - cellWidth: number; - cellHeight: number; -} - -export function resolveTerminalCustomGlyphCellTransform( - input: TerminalCustomGlyphCellTransformInput, -): string { - const translateX = input.cellOffset * input.cellWidth; - return `matrix(${input.cellWidth} 0 0 ${input.cellHeight} ${translateX} 0)`; -} - -export function resolveMeasuredTerminalCellMetrics( - input: TerminalGridCellMetricsInput, -): TerminalGridCellMetrics { - const textLength = Math.max(1, input.measureTextLength); - return { - cellWidth: snapCellMetric(input.measuredTextWidth / textLength, input.roundToNearestPixel), - cellHeight: snapCellMetric(input.measuredTextHeight, input.roundToNearestPixel), - }; -} - export function resolveTerminalGridMetricsMeasurement( previous: TerminalGridCellMetrics | null, next: TerminalGridCellMetrics, @@ -53,16 +12,3 @@ export function resolveTerminalGridMetricsMeasurement( } return next; } - -export function resolveTerminalCursorOffset( - input: TerminalCursorOffsetInput, -): TerminalCursorOffset { - return { - x: input.cursorCol * input.metrics.cellWidth, - y: input.cursorRow * input.metrics.cellHeight, - }; -} - -function snapCellMetric(value: number, roundToNearestPixel: (value: number) => number): number { - return Math.max(1, roundToNearestPixel(value)); -} diff --git a/packages/app/src/terminal/native-renderer/terminal-grid-view.native.tsx b/packages/app/src/terminal/native-renderer/terminal-grid-view.native.tsx index 04f82c1011..d88daf0679 100644 --- a/packages/app/src/terminal/native-renderer/terminal-grid-view.native.tsx +++ b/packages/app/src/terminal/native-renderer/terminal-grid-view.native.tsx @@ -1,71 +1,34 @@ -import { memo, useCallback, useMemo, useRef, useState } from "react"; +import { useCallback, useMemo, useRef, useState } from "react"; import { - PixelRatio, - Text, + useWindowDimensions, View, type LayoutChangeEvent, type StyleProp, - type TextStyle, type ViewStyle, } from "react-native"; import { StyleSheet } from "react-native-unistyles"; -import Svg, { G, Path } from "react-native-svg"; import type { ITheme } from "@xterm/xterm"; +import { + PaseoTerminalView, + type PaseoTerminalCellMetrics, + type PaseoTerminalTheme, +} from "../../../modules/paseo-terminal"; import { createTerminalCellStyleResolver, DEFAULT_TERMINAL_THEME, NATIVE_TERMINAL_SELECTION_COLORS, } from "./colors"; -import type { TerminalGlyphRect } from "./terminal-custom-glyph"; import { resolveNativeTerminalFontFamily } from "./font.native"; import type { TerminalViewportState } from "./headless-terminal-state"; import { - resolveMeasuredTerminalCellMetrics, - resolveTerminalCustomGlyphCellTransform, resolveTerminalGridMetricsMeasurement, - resolveTerminalCursorOffset, type TerminalGridCellMetrics, } from "./terminal-grid-metrics"; -import { - buildRows, - type TerminalCustomGlyphCell, - type TerminalCustomGlyphRun, - type TerminalRowModel, - type TerminalRun, -} from "./terminal-row-model"; +import { buildTerminalFrame } from "./terminal-frame"; import type { TerminalSelectionRange } from "./terminal-selection"; -const MEASURE_TEXT = "mmmmmmmmmm"; const DEFAULT_FONT_SIZE = 12; -const INITIAL_CELL_WIDTH_RATIO = 0.62; -const INITIAL_CELL_HEIGHT_RATIO = 1.35; - -interface CellMetrics { - cellWidth: number; - cellHeight: number; -} - -interface TerminalGridViewport { - width: number; - height: number; -} - -interface TerminalGridRowProps { - row: TerminalRowModel; - cellWidth: number; - cellHeight: number; - fontFamily?: string; - fontSize: number; - styleEpoch: string; -} - -interface TerminalGridRunProps { - run: TerminalRun; - cellWidth: number; - cellHeight: number; - textStyle: StyleProp; -} export interface TerminalGridViewProps { state: TerminalViewportState; @@ -77,221 +40,20 @@ export interface TerminalGridViewProps { onCellMetricsChange?: (metrics: TerminalGridCellMetrics) => void; } -function estimateCellMetrics(fontSize: number): CellMetrics { - return { - cellWidth: snapPixel(fontSize * INITIAL_CELL_WIDTH_RATIO), - cellHeight: snapPixel(fontSize * INITIAL_CELL_HEIGHT_RATIO), - }; -} - -function snapPixel(value: number): number { - return Math.max(1, PixelRatio.roundToNearestPixel(value)); -} - function resolveVisibleCols(input: { - viewportWidth: number; - cellWidth: number; + viewportWidth: number | null; + cellWidth: number | null; gridCols: number; }): number { + if (input.viewportWidth === null || input.cellWidth === null) { + return input.gridCols; + } if (input.viewportWidth <= 0 || input.cellWidth <= 0 || input.gridCols <= 0) { return 0; } return Math.min(input.gridCols, Math.max(1, Math.floor(input.viewportWidth / input.cellWidth))); } -function TerminalGridRun({ run, cellWidth, cellHeight, textStyle }: TerminalGridRunProps) { - const runStyle = useMemo>( - () => [ - styles.run, - { - backgroundColor: run.style.backgroundColor, - height: cellHeight, - width: run.cellCount * cellWidth, - }, - ], - [cellHeight, cellWidth, run.cellCount, run.style.backgroundColor], - ); - const runTextStyle = useMemo>( - () => [textStyle, run.style], - [run.style, textStyle], - ); - - return ( - - {run.renderKind === "custom-glyph" ? ( - - ) : ( - - {run.text} - - )} - - ); -} - -interface TerminalGridCustomGlyphRunProps { - run: TerminalCustomGlyphRun; - cellWidth: number; - cellHeight: number; -} - -interface TerminalGridCustomGlyphRectProps { - cell: TerminalCustomGlyphCell; - rect: TerminalGlyphRect; - cellWidth: number; - cellHeight: number; - foregroundColor: string; -} - -function TerminalGridCustomGlyphRect({ - cell, - rect, - cellWidth, - cellHeight, - foregroundColor, -}: TerminalGridCustomGlyphRectProps) { - const style = useMemo( - () => ({ - position: "absolute", - backgroundColor: foregroundColor, - left: (cell.offset + rect.x) * cellWidth, - top: rect.y * cellHeight, - width: rect.width * cellWidth, - height: rect.height * cellHeight, - }), - [cell.offset, cellHeight, cellWidth, foregroundColor, rect], - ); - - return ; -} - -function TerminalGridCustomGlyphRun({ - run, - cellWidth, - cellHeight, -}: TerminalGridCustomGlyphRunProps) { - const opacity = typeof run.style.opacity === "number" ? run.style.opacity : 1; - - return ( - - {run.glyphs.map((cell) => - cell.glyph.kind === "rects" - ? cell.glyph.rects.map((rect) => ( - - )) - : null, - )} - - - {run.glyphs.map((cell) => - cell.glyph.kind === "path" ? ( - - ) : null, - )} - - - - ); -} - -const MemoTerminalGridRun = memo(TerminalGridRun, (previous, next) => { - return ( - previous.run === next.run && - previous.cellWidth === next.cellWidth && - previous.cellHeight === next.cellHeight && - previous.textStyle === next.textStyle - ); -}); - -function TerminalGridRow({ - row, - cellWidth, - cellHeight, - fontFamily, - fontSize, -}: TerminalGridRowProps) { - const rowStyle = useMemo>( - () => [styles.row, { height: cellHeight }], - [cellHeight], - ); - const textStyle = useMemo>( - () => [ - styles.rowText, - { - height: cellHeight, - lineHeight: cellHeight, - fontFamily, - fontSize, - }, - ], - [cellHeight, fontFamily, fontSize], - ); - const accessibilityLabel = useMemo( - () => - row.runs - .map((run) => run.text) - .join("") - .trimEnd(), - [row.runs], - ); - - return ( - 0} - style={rowStyle} - testID={`terminal-row-${row.index}`} - > - {row.runs.map((run) => ( - - ))} - - ); -} - -const MemoTerminalGridRow = memo(TerminalGridRow, (previous, next) => { - return ( - previous.row.hash === next.row.hash && - previous.cellWidth === next.cellWidth && - previous.cellHeight === next.cellHeight && - previous.fontFamily === next.fontFamily && - previous.fontSize === next.fontSize && - previous.styleEpoch === next.styleEpoch - ); -}); - export function TerminalGridView({ state, xtermTheme = DEFAULT_TERMINAL_THEME, @@ -301,129 +63,61 @@ export function TerminalGridView({ selection = null, onCellMetricsChange, }: TerminalGridViewProps) { - const [metrics, setMetrics] = useState(() => estimateCellMetrics(fontSize)); + const { fontScale } = useWindowDimensions(); + const [cellWidth, setCellWidth] = useState(null); + const [viewportWidth, setViewportWidth] = useState(null); const measuredMetricsRef = useRef(null); - const [viewport, setViewport] = useState(null); const resolvedFontFamily = useMemo( () => resolveNativeTerminalFontFamily(fontFamily), [fontFamily], ); const resolver = useMemo(() => createTerminalCellStyleResolver(xtermTheme), [xtermTheme]); - const visibleCols = useMemo(() => { - const viewportWidth = viewport?.width ?? state.cols * metrics.cellWidth; - return resolveVisibleCols({ - viewportWidth, - cellWidth: metrics.cellWidth, - gridCols: state.cols, - }); - }, [metrics.cellWidth, state.cols, viewport?.width]); - const projectedGrid = useMemo( - () => state.grid.map((row) => row.slice(0, visibleCols)), - [state.grid, visibleCols], + const theme = useMemo( + () => ({ + background: resolver.backgroundColor, + cursor: resolver.cursorColor, + selectionBackground: NATIVE_TERMINAL_SELECTION_COLORS.background, + selectionForeground: NATIVE_TERMINAL_SELECTION_COLORS.foreground, + }), + [resolver], ); - const rows = useMemo( - () => - buildRows({ - grid: projectedGrid, - resolver, - selection: selection - ? { - range: selection, - firstRow: state.firstRow, - backgroundColor: NATIVE_TERMINAL_SELECTION_COLORS.background, - foregroundColor: NATIVE_TERMINAL_SELECTION_COLORS.foreground, - } - : undefined, - }), - [projectedGrid, resolver, selection, state.firstRow], + const columns = resolveVisibleCols({ viewportWidth, cellWidth, gridCols: state.cols }); + const frame = useMemo( + () => buildTerminalFrame({ state, columns, resolver, selection }), + [columns, resolver, selection, state], ); - const containerStyle = useMemo>( - () => [styles.root, { backgroundColor: resolver.backgroundColor }, style], - [resolver.backgroundColor, style], - ); - const gridStyle = useMemo>( - () => [ - styles.grid, - { - width: visibleCols * metrics.cellWidth, - height: state.grid.length * metrics.cellHeight, - }, - ], - [metrics.cellHeight, metrics.cellWidth, state.grid.length, visibleCols], - ); - const measureStyle = useMemo>( - () => [styles.measureText, { fontFamily: resolvedFontFamily, fontSize }], - [resolvedFontFamily, fontSize], - ); - const cursorStyle = useMemo>(() => { - const cursorOffset = resolveTerminalCursorOffset({ - cursorCol: state.cursor.col, - cursorRow: state.cursor.row, - metrics, - }); - return [ - styles.cursor, - { - backgroundColor: resolver.cursorColor, - width: metrics.cellWidth, - height: metrics.cellHeight, - transform: [{ translateX: cursorOffset.x }, { translateY: cursorOffset.y }], - }, - ]; - }, [metrics, state.cursor.col, state.cursor.row, resolver.cursorColor]); - - const handleMeasure = useCallback( - (event: LayoutChangeEvent) => { - const nextMetrics = resolveMeasuredTerminalCellMetrics({ - measuredTextWidth: event.nativeEvent.layout.width, - measuredTextHeight: event.nativeEvent.layout.height, - measureTextLength: MEASURE_TEXT.length, - roundToNearestPixel: (value) => PixelRatio.roundToNearestPixel(value), - }); + const handleCellMetrics = useCallback( + (metrics: PaseoTerminalCellMetrics) => { const changedMetrics = resolveTerminalGridMetricsMeasurement( measuredMetricsRef.current, - nextMetrics, + metrics, ); if (!changedMetrics) { return; } measuredMetricsRef.current = changedMetrics; - setMetrics(changedMetrics); + setCellWidth(changedMetrics.cellWidth); onCellMetricsChange?.(changedMetrics); }, [onCellMetricsChange], ); const handleContainerLayout = useCallback((event: LayoutChangeEvent) => { - const { width, height } = event.nativeEvent.layout; - setViewport((current) => { - if (current?.width === width && current.height === height) { - return current; - } - return { width, height }; - }); + const { width } = event.nativeEvent.layout; + setViewportWidth((current) => (current === width ? current : width)); }, []); return ( - - - - {MEASURE_TEXT} - - {rows.map((row) => ( - - ))} - {!state.cursor.hidden && } - + + ); } @@ -432,38 +126,7 @@ const styles = StyleSheet.create({ root: { overflow: "hidden", }, - grid: { - position: "relative", - }, - row: { - flexDirection: "row", - }, - run: { - overflow: "hidden", - }, - customGlyphRun: { + surface: { flex: 1, - position: "relative", - }, - customGlyphSvg: { - left: 0, - position: "absolute", - top: 0, - }, - rowText: { - includeFontPadding: false, - margin: 0, - padding: 0, - }, - measureText: { - includeFontPadding: false, - opacity: 0, - position: "absolute", - }, - cursor: { - left: 0, - opacity: 0.45, - position: "absolute", - top: 0, }, }); diff --git a/packages/app/src/terminal/native-renderer/terminal-row-model.test.ts b/packages/app/src/terminal/native-renderer/terminal-row-model.test.ts deleted file mode 100644 index b19922b7a9..0000000000 --- a/packages/app/src/terminal/native-renderer/terminal-row-model.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -import type { TerminalCell } from "@getpaseo/protocol/messages"; -import { describe, expect, test } from "vitest"; - -import { createTerminalCellStyleResolver, DEFAULT_TERMINAL_THEME } from "./colors"; -import { buildRows } from "./terminal-row-model"; - -function cell( - char: string, - overrides: Partial & { width?: number } = {}, -): TerminalCell & { width?: number } { - return { char, ...overrides }; -} - -describe("terminal row model", () => { - test("preserves terminal cell width for styled runs and trailing spaces", () => { - const resolver = createTerminalCellStyleResolver(DEFAULT_TERMINAL_THEME); - - const rows = buildRows({ - grid: [ - [cell("n", { bg: 2, bgMode: 1 }), cell("v", { bg: 2, bgMode: 1 }), cell(" "), cell(" ")], - ], - resolver, - }); - - expect(rows[0].runs.map((run) => ({ text: run.text, cellCount: run.cellCount }))).toEqual([ - { text: "nv", cellCount: 2 }, - { text: " ", cellCount: 2 }, - ]); - }); - - test("uses xterm's authoritative width instead of guessing from the code point", () => { - const resolver = createTerminalCellStyleResolver(DEFAULT_TERMINAL_THEME); - - const rows = buildRows({ - grid: [[cell("A", { width: 2 }), cell(" ", { width: 0 }), cell("界", { width: 1 })]], - resolver, - }); - - expect(rows[0].runs.map((run) => ({ text: run.text, cellCount: run.cellCount }))).toEqual([ - { text: "A界", cellCount: 3 }, - ]); - }); - - test("redraws selected cells with the terminal selection colors", () => { - const resolver = createTerminalCellStyleResolver(DEFAULT_TERMINAL_THEME); - const grid = [[cell("a", { fg: 1, fgMode: 1 }), cell("b", { dim: true }), cell("c")]]; - - const rows = buildRows({ - grid, - resolver, - selection: { - range: { - start: { row: 7, col: 1 }, - end: { row: 7, col: 2 }, - coordinateEpoch: 1, - }, - firstRow: 7, - backgroundColor: "#ffff00", - foregroundColor: "#000000", - }, - }); - - expect( - rows[0].runs.map((run) => ({ - text: run.text, - color: run.style.color, - backgroundColor: run.style.backgroundColor, - opacity: run.style.opacity, - })), - ).toEqual([ - { - text: "a", - color: DEFAULT_TERMINAL_THEME.red, - backgroundColor: undefined, - opacity: undefined, - }, - { text: "b", color: "#000000", backgroundColor: "#ffff00", opacity: 1 }, - { text: "c", color: "#000000", backgroundColor: "#ffff00", opacity: 1 }, - ]); - expect(rows[0].hash).not.toBe(buildRows({ grid, resolver })[0].hash); - }); - - test("splits Claude box drawing from font text at exact terminal columns", () => { - const resolver = createTerminalCellStyleResolver(DEFAULT_TERMINAL_THEME); - const frame = "╭─ Claude Code ───╮"; - - const [row] = buildRows({ - grid: [frame.split("").map((char) => cell(char, { fg: 1, fgMode: 1 }))], - resolver, - }); - - expect( - row.runs.map((run) => ({ - text: run.text, - cellCount: run.cellCount, - renderKind: run.renderKind, - })), - ).toEqual([ - { text: "╭─", cellCount: 2, renderKind: "custom-glyph" }, - { text: " Claude Code ", cellCount: 13, renderKind: "text" }, - { text: "───╮", cellCount: 4, renderKind: "custom-glyph" }, - ]); - }); - - test("keeps Claude mascot glyphs custom while preserving copied row text", () => { - const resolver = createTerminalCellStyleResolver(DEFAULT_TERMINAL_THEME); - const mascot = "▐▛███▜▌ Claude Code"; - - const [row] = buildRows({ - grid: [mascot.split("").map((char) => cell(char, { fg: 1, fgMode: 1 }))], - resolver, - }); - - expect(row.runs.map((run) => [run.text, run.renderKind])).toEqual([ - ["▐▛███▜▌", "custom-glyph"], - [" Claude Code", "text"], - ]); - expect(row.runs.map((run) => run.text).join("")).toBe(mascot); - }); -}); diff --git a/packages/app/src/terminal/native-renderer/terminal-row-model.ts b/packages/app/src/terminal/native-renderer/terminal-row-model.ts deleted file mode 100644 index a65f39fd44..0000000000 --- a/packages/app/src/terminal/native-renderer/terminal-row-model.ts +++ /dev/null @@ -1,253 +0,0 @@ -import type { TextStyle } from "react-native"; -import type { TerminalCell } from "@getpaseo/protocol/messages"; - -import type { TerminalCellStyleResolver } from "./colors"; -import { resolveTerminalCustomGlyph, type TerminalCustomGlyph } from "./terminal-custom-glyph"; -import type { TerminalSelectionRange } from "./terminal-selection"; - -const WIDE_CHAR_RANGES: ReadonlyArray = [ - [0x1100, 0x115f], - [0x2329, 0x232a], - [0x2e80, 0xa4cf], - [0xac00, 0xd7a3], - [0xf900, 0xfaff], - [0xfe10, 0xfe19], - [0xfe30, 0xfe6f], - [0xff00, 0xff60], - [0xffe0, 0xffe6], - [0x1f300, 0x1faff], -]; - -interface TerminalRunBase { - key: string; - text: string; - cellCount: number; - styleKey: string; - style: TextStyle; - foregroundColor: string; -} - -export interface TerminalTextRun extends TerminalRunBase { - renderKind: "text"; -} - -export interface TerminalCustomGlyphRun extends TerminalRunBase { - renderKind: "custom-glyph"; - glyphs: TerminalCustomGlyphCell[]; -} - -export type TerminalRun = TerminalCustomGlyphRun | TerminalTextRun; - -export interface TerminalCustomGlyphCell { - key: string; - offset: number; - glyph: TerminalCustomGlyph; -} - -export interface TerminalRowModel { - index: number; - hash: string; - runs: TerminalRun[]; -} - -type TerminalRenderableCell = TerminalCell & { width?: number }; - -interface TerminalRowSelectionStyle { - range: TerminalSelectionRange; - firstRow: number; - backgroundColor: string; - foregroundColor: string; -} - -function hashStringPart(hash: number, value: string): number { - let nextHash = hash; - for (let index = 0; index < value.length; index += 1) { - nextHash = Math.imul(nextHash ^ value.charCodeAt(index), 16777619); - } - return nextHash; -} - -function finishHash(hash: number): string { - return (hash >>> 0).toString(36); -} - -function terminalCharWidth(char: string): number { - const codePoint = char.codePointAt(0); - if (codePoint === undefined) return 1; - const isWide = WIDE_CHAR_RANGES.some(([start, end]) => codePoint >= start && codePoint <= end); - return isWide ? 2 : 1; -} - -function shouldSkipSpacerCell(cells: TerminalRenderableCell[], col: number, char: string): boolean { - if (terminalCharWidth(char) < 2) { - return false; - } - return cells[col + 1]?.char === " "; -} - -function terminalCellCount(cells: TerminalRenderableCell[], col: number, char: string): number { - const authoritativeWidth = cells[col]?.width; - if (authoritativeWidth !== undefined) { - return Math.max(1, authoritativeWidth); - } - if (shouldSkipSpacerCell(cells, col, char)) { - return 2; - } - return 1; -} - -function appendRun(input: { - runs: TerminalRun[]; - text: string; - cellCount: number; - styleKey: string; - style: TextStyle; - foregroundColor: string; - customGlyph: TerminalCustomGlyph | null; - col: number; -}): void { - const renderKind = input.customGlyph ? "custom-glyph" : "text"; - const previousRun = input.runs[input.runs.length - 1]; - if ( - previousRun && - previousRun.styleKey === input.styleKey && - previousRun.renderKind === renderKind - ) { - const offset = previousRun.cellCount; - previousRun.text += input.text; - previousRun.cellCount += input.cellCount; - if (previousRun.renderKind === "custom-glyph" && input.customGlyph) { - previousRun.glyphs.push({ - key: `${input.col}:${input.text}`, - offset, - glyph: input.customGlyph, - }); - } - return; - } - - const baseRun: TerminalRunBase = { - key: `${input.col}:${input.styleKey}`, - text: input.text, - cellCount: input.cellCount, - styleKey: input.styleKey, - style: input.style, - foregroundColor: input.foregroundColor, - }; - if (input.customGlyph) { - input.runs.push({ - ...baseRun, - renderKind: "custom-glyph", - glyphs: [{ key: `${input.col}:${input.text}`, offset: 0, glyph: input.customGlyph }], - }); - return; - } - input.runs.push({ ...baseRun, renderKind: "text" }); -} - -function cellIntersectsSelection(input: { - selection: TerminalRowSelectionStyle; - row: number; - col: number; - cellCount: number; -}): boolean { - const absoluteRow = input.selection.firstRow + input.row; - const { start, end } = input.selection.range; - if (absoluteRow < start.row || absoluteRow > end.row) { - return false; - } - - const selectedStartCol = absoluteRow === start.row ? start.col : 0; - const selectedEndCol = absoluteRow === end.row ? end.col : Number.POSITIVE_INFINITY; - const cellEndCol = input.col + input.cellCount - 1; - return cellEndCol >= selectedStartCol && input.col <= selectedEndCol; -} - -function selectedCellStyle(input: { - style: TextStyle; - foregroundColor: string; - backgroundColor: string; -}): TextStyle { - return { - ...input.style, - backgroundColor: input.backgroundColor, - color: input.foregroundColor, - opacity: 1, - ...(input.style.textDecorationLine - ? { textDecorationColor: input.foregroundColor } - : undefined), - }; -} - -function buildRowModel(input: { - cells: TerminalRenderableCell[]; - index: number; - resolver: TerminalCellStyleResolver; - selection?: TerminalRowSelectionStyle; -}): TerminalRowModel { - const runs: TerminalRun[] = []; - let hash = 2166136261; - - for (let col = 0; col < input.cells.length; col += 1) { - const cell = input.cells[col]; - const text = cell.char || " "; - const resolvedStyle = input.resolver.resolve(cell); - const cellCount = terminalCellCount(input.cells, col, text); - const customGlyph = resolveTerminalCustomGlyph(text); - const selection = input.selection; - let styleKey = resolvedStyle.key; - let style = resolvedStyle.style; - let foregroundColor = resolvedStyle.foregroundColor; - if ( - selection && - cellIntersectsSelection({ - selection, - row: input.index, - col, - cellCount, - }) - ) { - styleKey = `${resolvedStyle.key}|selection:${selection.foregroundColor}:${selection.backgroundColor}`; - style = selectedCellStyle({ - style: resolvedStyle.style, - foregroundColor: selection.foregroundColor, - backgroundColor: selection.backgroundColor, - }); - foregroundColor = selection.foregroundColor; - } - appendRun({ - runs, - text, - cellCount, - styleKey, - style, - foregroundColor, - customGlyph, - col, - }); - hash = hashStringPart(hash, text); - hash = hashStringPart(hash, String(cellCount)); - hash = hashStringPart(hash, styleKey); - hash = hashStringPart(hash, customGlyph ? "custom-glyph" : "text"); - - if (cellCount > 1) { - col += 1; - } - } - - return { - index: input.index, - hash: finishHash(hash), - runs, - }; -} - -export function buildRows(input: { - grid: TerminalRenderableCell[][]; - resolver: TerminalCellStyleResolver; - selection?: TerminalRowSelectionStyle; -}): TerminalRowModel[] { - return input.grid.map((cells, index) => - buildRowModel({ cells, index, resolver: input.resolver, selection: input.selection }), - ); -} diff --git a/packages/app/vitest.config.ts b/packages/app/vitest.config.ts index b139e266c5..ba4c0fc979 100644 --- a/packages/app/vitest.config.ts +++ b/packages/app/vitest.config.ts @@ -82,6 +82,7 @@ export default defineConfig({ environment: "node", include: [ "src/**/*.{test,spec}.{ts,tsx}", + "modules/**/*.{test,spec}.{ts,tsx}", "native-release-version.test.ts", "app.config.test.ts", "vitest-environment.test.ts", From 7b03f0ad21d9d8d701ecd5867cb8f1ac52d406f7 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sat, 31 Oct 2026 10:05:16 +0700 Subject: [PATCH 134/173] fix(ci): migrate to the latest macOS runners (#8335) * fix(ci): replace retiring macOS 14 runners Use the supported macOS 15 ARM64 image before the November 2 retirement. Keep the Intel release runner and existing test/build/release commands unchanged. * fix(ci): use the latest macOS runner images --- .github/workflows/ci.yml | 4 ++-- .github/workflows/desktop-release.yml | 4 ++-- .github/workflows/nix.yml | 2 +- scripts/ci-workflow.test.mjs | 32 ++++++++++++++++++++++++++- 4 files changed, 36 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7cb267c2dd..285ff8e072 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -281,10 +281,10 @@ jobs: # otherwise has no server-test coverage. Scoped to the observer/watcher suites to # bound runtime. server-tests-macos: - name: server-tests (macos-14, file observation) + name: server-tests (macos-latest, file observation) needs: changes if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.server != 'false') }} - runs-on: macos-14 + runs-on: macos-latest steps: - uses: actions/checkout@v4 diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.yml index d81c036e62..26be12291b 100644 --- a/.github/workflows/desktop-release.yml +++ b/.github/workflows/desktop-release.yml @@ -100,10 +100,10 @@ jobs: fail-fast: false matrix: include: - - runner: macos-14 + - runner: macos-latest electron_arch: arm64 node_heap_mb: 4096 - - runner: macos-15-intel + - runner: macos-26-intel electron_arch: x64 node_heap_mb: 8192 permissions: diff --git a/.github/workflows/nix.yml b/.github/workflows/nix.yml index f37a8b0cdf..b653564793 100644 --- a/.github/workflows/nix.yml +++ b/.github/workflows/nix.yml @@ -101,7 +101,7 @@ jobs: run: nix build .#desktop -o result-desktop build-desktop-darwin: - runs-on: macos-14 + runs-on: macos-latest steps: - uses: actions/checkout@v4 diff --git a/scripts/ci-workflow.test.mjs b/scripts/ci-workflow.test.mjs index 37508cad7d..73a9003312 100644 --- a/scripts/ci-workflow.test.mjs +++ b/scripts/ci-workflow.test.mjs @@ -24,7 +24,10 @@ const gatedCiJobs = new Map([ "server-integration-windows", { name: "server-integration (windows-latest)", contract: "server" }, ], - ["server-tests-macos", { name: "server-tests (macos-14, file observation)", contract: "server" }], + [ + "server-tests-macos", + { name: "server-tests (macos-latest, file observation)", contract: "server" }, + ], ["desktop-tests-ubuntu", { name: "desktop-tests (ubuntu-latest)", contract: "desktop" }], ["desktop-tests-windows", { name: "desktop-tests (windows-latest)", contract: "desktop" }], ["app-tests", { name: "app-tests", contract: "app" }], @@ -649,3 +652,30 @@ process.exit(code); }); } }); + +// GitHub retires macOS 14 on 2026-11-02; brownouts already reject these jobs. +test("workflows avoid retired macOS 14 runners", () => { + for (const path of filesUnder(".github/workflows", (candidate) => /\.ya?ml$/.test(candidate))) { + assert.doesNotMatch( + readFileSync(new URL(path, repoRoot), "utf8"), + /macos-14(?:-large|-xlarge)?\b/, + path, + ); + } +}); + +test("macOS jobs use latest runners while preserving release architectures", () => { + for (const [workflow, jobId] of [ + [ciWorkflowPath, "server-tests-macos"], + [nixWorkflowPath, "build-desktop-darwin"], + ]) { + assert.match( + jobBlocks(readFileSync(workflow, "utf8")).get(jobId).join("\n"), + /^ runs-on: macos-latest$/m, + ); + } + const release = readFileSync(new URL(".github/workflows/desktop-release.yml", repoRoot), "utf8"); + assert.match(release, /runner: macos-latest\n\s+electron_arch: arm64/); + // GitHub has no standard macos-latest-intel alias; use the newest Intel image. + assert.match(release, /runner: macos-26-intel\n\s+electron_arch: x64/); +}); From 9c926ed126358247421e62cf6c7399df042fb97d Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sat, 31 Oct 2026 10:51:45 +0700 Subject: [PATCH 135/173] fix(terminal): preserve 10,000 rows with direct ANSI replay (#8282) Restore configured terminal history on reconnect, retaining 10,000 rows plus the screen. Serialize the worker-owned xterm buffer directly to ANSI and forward negotiated bounded replay chunks while preserving ANSI-era clients and per-viewer live ordering. Preserve captured geometry through replay, bound pressure recovery to 500 rows, and keep the omitted visible-history default at 200. Remove the full cell-grid copy and obsolete JSON rendering. All 21 CI checks pass. Real browser, native Debug emulator/simulator and Linux Electron coverage and platform limits are documented in the PR. The Android Debug invalid native delegate dispatch also reproduces on upstream main; its cause and any change in frequency remain unproven. Credit Manav Dhindsa (DrakenKor), #6139 and #6148, and Lennart Schoch, #6743, for prior ANSI replay and retention work informing this change. Closes #6137. Closes #6147. --- docs/protocol-compatibility.md | 14 + docs/terminal-performance.md | 16 +- docs/terminal-worker.md | 16 +- package-lock.json | 8 + .../app/e2e/browser/daemon-lifecycle.spec.ts | 57 +- .../terminal-retained-tab-stream.spec.ts | 66 + .../e2e/support/helpers/daemon-lifecycle.ts | 41 +- .../support/helpers/isolated-host-daemon.ts | 53 +- .../app/e2e/support/helpers/terminal-perf.ts | 98 ++ packages/app/package.json | 1 + .../components/terminal-emulator-contract.ts | 5 +- .../terminal-emulator-native-grid.native.tsx | 191 +-- .../app/src/components/terminal-emulator.tsx | 48 +- packages/app/src/components/terminal-pane.tsx | 48 +- packages/app/src/i18n/resources/ar.ts | 1 + packages/app/src/i18n/resources/en.ts | 1 + packages/app/src/i18n/resources/es.ts | 1 + packages/app/src/i18n/resources/fr.ts | 1 + packages/app/src/i18n/resources/ja.ts | 1 + packages/app/src/i18n/resources/ko.ts | 1 + packages/app/src/i18n/resources/pt-BR.ts | 1 + packages/app/src/i18n/resources/ru.ts | 1 + packages/app/src/i18n/resources/zh-CN.ts | 1 + .../screens/workspace/workspace-screen.tsx | 16 - ...se-workspace-terminal-session-retention.ts | 18 - .../headless-terminal-output-drain.test.ts | 326 ++++- .../headless-terminal-output-drain.ts | 121 +- .../headless-terminal-state.ts | 46 - .../native-renderer/terminal-frame.test.ts | 47 + .../terminal-scrollback.test.ts | 19 +- .../terminal-emulator-runtime.browser.test.ts | 120 +- .../runtime/terminal-emulator-runtime.test.ts | 139 +- .../runtime/terminal-emulator-runtime.ts | 69 +- .../runtime/terminal-find.browser.test.ts | 1 - .../terminal-glyph-rendering.browser.test.ts | 1 - .../terminal-resize-repro.browser.test.ts | 65 +- .../runtime/terminal-restore-options.test.ts | 27 +- .../runtime/terminal-restore-options.ts | 10 +- .../runtime/terminal-snapshot.test.ts | 8 +- .../src/terminal/runtime/terminal-snapshot.ts | 1 - .../terminal-stream-controller.test.ts | 116 +- .../runtime/terminal-stream-controller.ts | 22 +- .../workspace-terminal-session.test.ts | 75 -- .../runtime/workspace-terminal-session.ts | 79 -- .../utils/terminal-renderer-readiness.test.ts | 22 - .../src/utils/terminal-renderer-readiness.ts | 7 - .../46-daemon-terminal-worker-upgrade.test.ts | 144 ++- packages/client/src/connection/index.ts | 1 + packages/client/src/daemon-client.test.ts | 252 +++- packages/client/src/daemon-client.ts | 5 +- packages/client/src/index.ts | 1 + .../client/src/terminal-stream-router.test.ts | 56 +- packages/client/src/terminal-stream-router.ts | 55 +- .../protocol/src/binary-frames/demux.test.ts | 15 + packages/protocol/src/binary-frames/demux.ts | 3 + .../protocol/src/binary-frames/terminal.ts | 12 + packages/protocol/src/client-capabilities.ts | 1 + .../protocol/src/terminal-snapshot.test.ts | 79 -- packages/protocol/src/terminal-snapshot.ts | 224 ---- packages/server/package.json | 1 + .../src/server/agent/mcp-server.test.ts | 1 - .../terminal-byte-headless-parity.e2e.test.ts | 74 +- .../server/daemon-e2e/terminal.e2e.test.ts | 364 ++++-- .../server/owned-subscriptions.e2e.test.ts | 166 +-- .../src/server/script-health-monitor.test.ts | 8 +- packages/server/src/server/session.ts | 4 +- .../reconciliation-responsiveness.ts | 17 + .../workspace-reconciliation-service.test.ts | 78 +- .../src/server/worktree-bootstrap.test.ts | 18 +- .../server/src/server/worktree-bootstrap.ts | 17 +- .../src/server/worktree-session.test.ts | 8 +- .../server/src/terminal/terminal-capture.ts | 29 +- .../src/terminal/terminal-manager.test.ts | 1 - .../server/src/terminal/terminal-manager.ts | 37 +- .../server/src/terminal/terminal-replay.ts | 135 ++ .../src/terminal/terminal-restore.test.ts | 91 +- .../server/src/terminal/terminal-restore.ts | 112 +- .../src/terminal/terminal-serializer.ts | 42 + .../terminal-session-controller.test.ts | 420 +++--- .../terminal/terminal-session-controller.ts | 174 ++- .../terminal/terminal-worker-client.test.ts | 43 + .../src/terminal/terminal-worker-frames.ts | 12 + .../src/terminal/terminal-worker-pool.ts | 6 +- .../src/terminal/terminal-worker-process.ts | 112 +- .../terminal/terminal-worker-protocol.test.ts | 18 +- .../src/terminal/terminal-worker-protocol.ts | 33 +- .../src/terminal/terminal.posix.test.ts | 141 +- packages/server/src/terminal/terminal.test.ts | 390 +++++- packages/server/src/terminal/terminal.ts | 284 +--- .../src/terminal/test-utils/terminal-state.ts | 51 + .../terminal/worker-terminal-manager.test.ts | 1145 +++++++++++++++-- .../src/terminal/worker-terminal-manager.ts | 112 +- 92 files changed, 4380 insertions(+), 2638 deletions(-) delete mode 100644 packages/app/src/terminal/hooks/use-workspace-terminal-session-retention.ts delete mode 100644 packages/app/src/terminal/runtime/terminal-snapshot.ts delete mode 100644 packages/app/src/terminal/runtime/workspace-terminal-session.test.ts delete mode 100644 packages/app/src/terminal/runtime/workspace-terminal-session.ts delete mode 100644 packages/protocol/src/terminal-snapshot.test.ts delete mode 100644 packages/protocol/src/terminal-snapshot.ts create mode 100644 packages/server/src/terminal/terminal-replay.ts create mode 100644 packages/server/src/terminal/terminal-serializer.ts create mode 100644 packages/server/src/terminal/test-utils/terminal-state.ts diff --git a/docs/protocol-compatibility.md b/docs/protocol-compatibility.md index 74650255a5..0fa4fed63d 100644 --- a/docs/protocol-compatibility.md +++ b/docs/protocol-compatibility.md @@ -52,6 +52,20 @@ On capable daemons, connecting creates no timeline or event demand. Client subsc release it on unsubscribe, and restore it after reconnect. Raw message observers inspect traffic without requesting streams. Application caches and which agents are visible remain caller-owned. +## Terminal ANSI replay + +Terminal replay intentionally drops JSON-era apps, an exception to the general cross-version policy: +use app v0.1.81 or newer. Earlier apps omit `restore` and reject ANSI Restore (`0x05`), so they show +only subsequent live output, without the existing screen or history. + +`terminal_chunked_replay` is SDK-owned delivery behavior. The daemon sends new binary opcodes only to a source +advertising the capability. The SDK keeps the established subscribe request against older +ANSI hosts and normalizes their single Restore frame into begin/data/end. `observeTerminal` defaults +to an explicit full snapshot: omitting restore on an ANSI-era host selects its discarded JSON path. +Explicit caller restore modes and history counts pass through unchanged. JSON snapshot +wire declarations remain accepted, but JSON snapshot frames have no rendering runtime. +Terminals require `terminal-restore-modes`; older hosts show an update message without attaching. + ## Binary chunking `binary_chunking_v1` in hello and optional `server_info.features.binaryChunkingV1` diff --git a/docs/terminal-performance.md b/docs/terminal-performance.md index 3bb7c4d71c..c757d004ec 100644 --- a/docs/terminal-performance.md +++ b/docs/terminal-performance.md @@ -6,9 +6,9 @@ How terminal output stays low-latency, what the invariants are, and how to measu ``` pty (node-pty, forked worker process) - → headless xterm parse (worker, snapshot fidelity) - → TerminalOutputCoalescer (worker, ≤1 IPC message per 5ms per terminal) - → process.send IPC → daemon main process + → headless xterm parse (worker, ANSI replay fidelity) + → TerminalOutputCoalescer (worker, ≤1 socket frame per 5ms per terminal) + → framed local socket → daemon main process → TerminalOutputCoalescer (per client stream, terminal-session-controller.ts) → binary ws frame (2-byte header + raw bytes) → client decode (daemon-client.ts) → stream router → emulator runtime @@ -19,11 +19,15 @@ Terminal frames share the daemon main event loop with all agent traffic. The `ev ## Invariants (the easy-to-break ones) +- **Replay is incremental across the daemon and SDK.** Capable clients request their configured history, bounded by [worker retention](terminal-worker.md#process-model). Older apps retain their own 200-row request. Explicit SDK history demand is unchanged against older ANSI hosts, which apply their existing 500-row ceiling. Begin resets once, chunks keep a streaming UTF-8 decoder/parser, and each renderer suppresses generated replies while parsing replay. Never concatenate capable replay chunks to feed the renderer. +- **Replay serialization reads xterm directly.** The [worker](terminal-worker.md#process-model) uses its existing buffer; text capture translates only the requested rows, and readiness scans row strings. Do not rebuild a full cell-object grid. Serialization still allocates a whole ANSI string and UTF-8 bytes before bounded delivery; chunking does not bound those allocations. - **Coalescers are leading+trailing throttles.** The first chunk after an idle window flushes immediately (synchronously); only sustained bursts wait for the trailing timer. Reverting to trailing-only adds a full window (~5ms) to every keystroke echo. -- **Output coalescing happens in the worker, before IPC.** One `process.send` per pty chunk was a main-loop flood under build output. Non-output messages (snapshot/snapshotReady/titleChange/exit) must flush the coalescer first so ordering is preserved. +- **Output coalescing happens in the worker, before IPC.** One socket frame per pty chunk was a main-loop flood under build output. Non-output messages (snapshotReady/titleChange/exit) must flush the coalescer first so ordering is preserved. +- **Replay delivery is isolated per viewer.** Live worker output never waits for app delivery. Each daemon stream owns its bounded live tail and revision deduplication; a slow or failed replay cannot pause another viewer of the same terminal. +- **Replay geometry belongs to the parser queue.** Native measurements and web fits must leave the captured dimensions intact through every chunk's commit. Apply the latest measured size after replay, before live bytes; clear, replacement and disposal must release that geometry ownership. A layout effect must not resize the renderer directly during replay. - **Coalesced output carries the LAST chunk's revision.** Snapshot replay dedup (`replayTerminalOutputAfterSnapshot`) skips buffered output with `revision <= replayRevision`; a merged batch with a lower revision would be wrongly skipped (lost output). -- **The input-mode tracker runs once per process boundary, not per hop.** The worker owns the authoritative tracker; the daemon caches the replay preamble from `getTerminalState` responses and `snapshotReady` messages. Do not reintroduce a per-chunk `feed()` on the daemon main loop. -- **Snapshot catch-up is backpressure-gated.** A stream falls back to a full snapshot only when `outputBytesSinceSnapshot > MAX_TERMINAL_OUTPUT_FRAME_BYTES` (256KB) **and** the client transport reports `bufferedAmount > MAX_CLIENT_BUFFERED_BYTES` (4MB). A client that keeps draining streams continuously, no matter how much output is produced. Before this gate existed, every 256KB of build output dropped a frame and forced a full JSON cell-grid snapshot (~200k objects across IPC) — the historical source of spiky lag and GC hitches. +- **The input-mode tracker runs once per process boundary, not per hop.** The worker commits its authoritative tracker with xterm parsing before publishing the corresponding revision; the daemon caches current modes from ordered worker events and adoption. A replay response carries capture-time modes for its viewer; it must not overwrite the shared cache after newer live output. Apply that viewer's preamble before its buffered live bytes. Do not reintroduce a per-chunk `feed()` on the daemon main loop. +- **Snapshot catch-up is backpressure-gated.** After more than 256 KiB of output, a stream catches up only when its transport reports more than 4 MiB queued, or exposes no backpressure reading. A draining client streams continuously. Pressure recovery sends at most 500 recent history rows plus the screen, preserving smaller explicit demands including zero; even a live-only subscription needs this resynchronization. It does not change the subscription's configured demand: later attach/reconnect restores still request the full configured history. The recent window avoids repeatedly serializing all retained history for a slow viewer. - **Plugin daemon sessions report IPC queue bytes.** Their virtual socket increments `bufferedAmount` before `process.send` and decrements it only in the send callback. Text and binary frames share that ordered queue, so the normal snapshot catch-up and physical high-water gates remain valid for server-side plugin SDK traffic. - **Client output writes are not serialized per frame.** The emulator runtime drains contiguous plain writes straight into xterm (which buffers internally). Only barrier ops (`clear`, `snapshot`, `suppressInput` writes) wait — behind a zero-length sentinel write — so resets can't interleave with in-flight output. - **Find preserves the inspected xterm viewport, including at the live bottom.** Keep its output anchor inside the existing batched write path. Serializing output to preserve a search result would add terminal latency. diff --git a/docs/terminal-worker.md b/docs/terminal-worker.md index 991fc5d644..be9321fb4f 100644 --- a/docs/terminal-worker.md +++ b/docs/terminal-worker.md @@ -15,6 +15,8 @@ supervisor (paseo.pid) ──► daemon worker ──► launcher ──► term - The worker exits on its own when it has no controller and no terminals, on `shutdown`, on SIGTERM (killing its terminals), and when its record disappears (a deleted `$PASEO_HOME`: nobody can ever reach it again). - Its stderr goes to `$PASEO_HOME/terminal-worker.log`. No pipe to the daemon survives the daemon. +The worker retains a fixed 10,000 history rows plus the screen in its existing xterm. Replay uses `@xterm/addon-serialize` 0.14 against headless xterm 6; no second cell grid or lifetime byte log is retained. The serializer boundary owns cursor position, visibility and explicit program-selected presentation; the addon alone does not preserve all three. An unset program style leaves each client’s configured cursor defaults intact. Standard modes come from the serializer; the existing input-mode tracker retains protocol modes such as Kitty and Win32 input. Commit that tracker with parsed output so replay bytes and metadata describe the same cut. + Which triggers keep terminals and which close them is owned by the stop reason (`keepTerminals`) that flows from the request through the supervisor to `stop()`. The kill side always ends in the reaper (`terminal-worker-reaper.ts`), the only path that signals terminal processes outside a connected daemon. ## Record, socket and secret @@ -40,10 +42,22 @@ The worker writes `$PASEO_HOME/terminal-worker/.json` (owner-only) with its Never more than two workers run. A new worker launches only when none is current, none is incompatible and fewer than two run. The count comes from the records, so an unreachable or unidentified worker counts, and so does one a cleanup could not confirm gone. When two run, the daemon starts with no current worker, and the first terminal created after one of them exits launches it. -**The frozen envelope never changes across versions:** the frame format (4-byte length + `v8.serialize`), `hello`/`helloAck`, the `listTerminals` info fields and `shutdown`. That is what lets any daemon close any worker: a kill stop sends `shutdown` to a newer worker it cannot otherwise drive. When you bump the version, keep a previous-version adapter so the draining worker can still be driven, and drop the adapter for the version before that. +**The frozen envelope never changes across versions:** the frame format (4-byte length + `v8.serialize`), `hello`/`helloAck`, the `listTerminals` info fields and `shutdown`. That is what lets any daemon close any worker: a kill stop sends `shutdown` to a newer worker it cannot otherwise drive. Protocol 5 hard cuts unreleased protocols 1 through 4, including the acknowledgement-based replay contract: those workers are obsolete and close. For future versions, keep a previous-version adapter so the draining worker can still be driven, and drop the adapter for the version before that. Tests stand up other versions with `PASEO_TERMINAL_WORKER_PROTOCOL_OVERRIDE`, read by the worker. It is test-only. +## Display replay + +The worker keeps the headless xterm model and generates ANSI. A replay request emits begin metadata (dimensions, retained history, revision and input modes), at most 64 KiB per data chunk, and end. Live output keeps flowing independently during replay. Capture is synchronous with PTY callbacks; flush the output coalescer before the cut so a later batch never includes bytes already in replay. Retained-history metadata counts the worker history before the request limit. + +ConPTY renders a console rather than forwarding every program escape sequence unchanged. A program write callback does not establish that its hidden cursor move or input modes reached the worker. Test exact ANSI fidelity at the serializer boundary; PTY integration compares the initial replay plus committed observed output at the capture cut, including startup modes. + +The worker paces replay writes on its local socket; the daemon synchronously queues each event into the application's bounded transport. App network delivery does not extend the worker's request deadline. There is no per-chunk acknowledgement or second replay delivery queue in the daemon. The physical application transport owns its 64 MiB high-water close, so a backed-up app cannot hold worker capture open. Each daemon viewer still holds at most 4 MiB of live output during capture, then drops revisions already present in the worker replay. Capture failure and tail overflow affect only that viewer; PTYs and healthy viewers keep running. + +Live traffic that fills the shared worker socket beyond 4 MiB disconnects the stalled controller. Reconnection adopts the surviving sessions and requests fresh replay for existing streams. Readiness does not require a revision: adoption announces readiness without one, while the replay capture supplies the revision used for deduplication. + +The SDK advertises `terminal_chunked_replay` only because it decodes begin/data/end. Capable clients receive these events directly; the daemon collects one Restore frame only for older ANSI clients. The SDK normalizes an older host's single Restore into the same lifecycle. Capture stays a worker request; bootstrap readiness uses `hasOutput`, not a transported grid. + ## Running from its own copy A worker outlives the installation that started it. An npm or desktop update replaces that installation's files, and the next terminal the old worker creates would load node-pty's `spawn-helper` and the zsh integration from paths that no longer exist. So a built daemon does not launch the worker from its install: diff --git a/package-lock.json b/package-lock.json index 80355dbb21..30ceb1cb4c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14740,6 +14740,12 @@ "node": ">=10.0.0" } }, + "node_modules/@xterm/addon-serialize": { + "version": "0.14.0", + "resolved": "https://registry.npmjs.org/@xterm/addon-serialize/-/addon-serialize-0.14.0.tgz", + "integrity": "sha512-uteyTU1EkrQa2Ux6P/uFl2fzmXI46jy5uoQMKEOM0fKTyiW7cSn0WrFenHm5vO5uEXX/GpwW/FgILvv3r0WbkA==", + "license": "MIT" + }, "node_modules/@xterm/headless": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/@xterm/headless/-/headless-6.0.0.tgz", @@ -37703,6 +37709,7 @@ "@types/ws": "^8.18.1", "@vitest/browser": "^4.1.7", "@vitest/browser-playwright": "^4.1.7", + "@xterm/addon-serialize": "0.14.0", "@xterm/headless": "^6.1.0-beta.213", "babel-preset-expo": "~57.0.16", "dotenv": "^17.2.3", @@ -40682,6 +40689,7 @@ "@modelcontextprotocol/sdk": "1.29.0", "@opencode-ai/sdk": "1.14.46", "@opencode/client": "2.0.10", + "@xterm/addon-serialize": "0.14.0", "@xterm/headless": "^6.0.0", "ai": "5.0.78", "ajv": "^8.20.0", diff --git a/packages/app/e2e/browser/daemon-lifecycle.spec.ts b/packages/app/e2e/browser/daemon-lifecycle.spec.ts index 2e65778868..23f6f5b2ff 100644 --- a/packages/app/e2e/browser/daemon-lifecycle.spec.ts +++ b/packages/app/e2e/browser/daemon-lifecycle.spec.ts @@ -1,8 +1,9 @@ import { randomUUID } from "node:crypto"; -import { mkdtemp, writeFile } from "node:fs/promises"; +import { mkdtemp, writeFile, rm } from "node:fs/promises"; +import { existsSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; -import { expect, test } from "../support/fixtures"; +import { expect, test, daemonTest as cleanupTest } from "../support/fixtures"; import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon"; import { openDaemonOverview, @@ -13,6 +14,10 @@ import { readWorkerPid, openLongLivedTerminal, listTerminalIds, + suspendDaemonProcess, + resumeDaemonProcess, + daemonProcessCanWrite, + readTerminalProcessIds, } from "../support/helpers/daemon-lifecycle"; test("settings restart waits for a replacement worker while retaining the supervisor", async ({ @@ -119,3 +124,51 @@ async function createHomeWithSlowProvider(versionDelayMs: number): Promise { + cleanupTest.skip(process.platform === "win32", "POSIX stopped-process failure injection"); + const daemon = await startIsolatedHostDaemon(randomUUID()); + const workerPid = await readWorkerPid(daemon); + try { + suspendDaemonProcess(workerPid); + await daemon.close(); + resumeDaemonProcess(workerPid); + await expect.poll(() => daemonProcessCanWrite(workerPid)).toBe(false); + expect(existsSync(daemon.paseoHome)).toBe(false); + } finally { + resumeDaemonProcess(workerPid); + await daemon.close(); + await rm(daemon.paseoHome, { recursive: true, force: true }); + } + }, +); + +cleanupTest( + "isolated cleanup force-stops a frozen supervisor and its detached terminal writers", + async () => { + cleanupTest.skip(process.platform === "win32", "POSIX stopped-process failure injection"); + const daemon = await startIsolatedHostDaemon(randomUUID()); + const supervisorPid = daemon.getPid()!; + const workerPid = await readWorkerPid(daemon); + try { + await openLongLivedTerminal(daemon); + const terminalProcesses = await readTerminalProcessIds(daemon); + expect(terminalProcesses.length).toBeGreaterThanOrEqual(2); + suspendDaemonProcess(supervisorPid); + await daemon.close(); + const writerStates = await Promise.all( + [supervisorPid, workerPid, ...terminalProcesses].map(daemonProcessCanWrite), + ); + expect(writerStates).toEqual(Array(terminalProcesses.length + 2).fill(false)); + expect(existsSync(daemon.paseoHome)).toBe(false); + } finally { + resumeDaemonProcess(supervisorPid); + await daemon.close(); + } + }, +); diff --git a/packages/app/e2e/browser/terminal-retained-tab-stream.spec.ts b/packages/app/e2e/browser/terminal-retained-tab-stream.spec.ts index c3481110f7..d0dbe9be23 100644 --- a/packages/app/e2e/browser/terminal-retained-tab-stream.spec.ts +++ b/packages/app/e2e/browser/terminal-retained-tab-stream.spec.ts @@ -1,5 +1,10 @@ import type { Page } from "@playwright/test"; import { expect, test } from "../support/fixtures"; +import { + expectTerminalCursor, + getTerminalBufferText, + waitForTerminalContent, +} from "../support/helpers/terminal-perf"; import { TerminalE2EHarness } from "../support/helpers/terminal-dsl"; interface AttachOverlayProbeWindow extends Window { @@ -59,4 +64,65 @@ test.describe("retained terminal tab streams", () => { expect(await terminalAttachOverlayWasSeen(page)).toBe(false); }); + + for (const { count, retainedMarker } of [ + { count: 3000, retainedMarker: "history-0001界🙂" }, + { count: 12050, retainedMarker: "history-3000界🙂" }, + ]) { + test(`reattach restores retained styled Unicode history from ${count} lines`, async ({ + page, + }) => { + await page.addInitScript(() => { + const key = "@paseo:app-settings"; + const settings = JSON.parse(localStorage.getItem(key) ?? "{}"); + localStorage.setItem(key, JSON.stringify({ ...settings, terminalScrollbackLines: 10000 })); + }); + const terminal = await harness.createTerminal({ + name: `history-${count}`, + command: "/bin/sh", + args: [ + "-lc", + `i=1; while [ $i -le ${count} ]; do printf '\\033[31mhistory-%04d界🙂 payload-abcdefghijklmnopqrstuvwxyz0123456789\\033[0m\\n' $i; i=$((i+1)); done; sleep 120`, + ], + }); + const last = `history-${String(count).padStart(4, "0")}界🙂`; + await harness.openTerminal(page, { terminalId: terminal.id }); + await waitForTerminalContent(page, (text) => text.includes(last), 10000); + expect(await getTerminalBufferText(page)).toContain(retainedMarker); + await page.reload(); + await waitForTerminalContent(page, (text) => text.includes(last), 10000); + const restored = await getTerminalBufferText(page); + expect(restored).toContain(retainedMarker); + expect(restored.match(/history-\d{4,5}/g)?.length).toBeGreaterThanOrEqual( + Math.min(count, 10000), + ); + if (count > 10000) expect(restored).not.toContain("history-0001界🙂"); + }); + } + for (const input of [ + { name: "client blinking bar", presentation: "", shape: "bar" as const, blinking: true }, + { + name: "program blinking underline", + presentation: "\x1b[3 q", + shape: "underline" as const, + blinking: true, + }, + ]) { + test(`reattach preserves the ${input.name} cursor`, async ({ page }) => { + const terminal = await harness.createTerminal({ + name: "cursor-presentation", + command: process.execPath, + args: [ + "-e", + `process.stdout.write(${JSON.stringify(input.presentation + "CURSOR-READY\r\n")});setInterval(()=>{},1000)`, + ], + }); + await harness.openTerminal(page, { terminalId: terminal.id }); + await waitForTerminalContent(page, (text) => text.includes("CURSOR-READY"), 10000); + await expectTerminalCursor(page, input); + await page.reload(); + await waitForTerminalContent(page, (text) => text.includes("CURSOR-READY"), 10000); + await expectTerminalCursor(page, input); + }); + } }); diff --git a/packages/app/e2e/support/helpers/daemon-lifecycle.ts b/packages/app/e2e/support/helpers/daemon-lifecycle.ts index d72cf063b1..c38c0f5f78 100644 --- a/packages/app/e2e/support/helpers/daemon-lifecycle.ts +++ b/packages/app/e2e/support/helpers/daemon-lifecycle.ts @@ -1,5 +1,5 @@ import { execFile, spawn } from "node:child_process"; -import { writeFile } from "node:fs/promises"; +import { writeFile, readFile, readdir } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; import { expect, type Page } from "@playwright/test"; @@ -154,3 +154,42 @@ export async function plantUnclosableTerminalProgram( throw error; } } + +/** Fault injection and liveness checks for the isolated daemon cleanup journey. */ +export function suspendDaemonProcess(pid: number): void { + process.kill(pid, "SIGSTOP"); +} + +export function resumeDaemonProcess(pid: number): void { + try { + process.kill(pid, "SIGCONT"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; + } +} + +export async function daemonProcessCanWrite(pid: number): Promise { + try { + const state = await psField(pid, "stat"); + return state.length > 0 && !state.startsWith("Z"); + } catch (error) { + if ((error as { code?: unknown }).code === 1) return false; + throw error; + } +} + +export async function readTerminalProcessIds(daemon: IsolatedHostDaemon): Promise { + const directory = path.join(daemon.paseoHome, "terminal-worker"); + const records = await Promise.all( + (await readdir(directory)) + .filter((name) => name.endsWith(".json")) + .map(async (name) => { + const record = JSON.parse(await readFile(path.join(directory, name), "utf8")) as { + pid: number; + terminals: Array<{ pid: number }>; + }; + return [record.pid].concat(record.terminals.map((terminal) => terminal.pid)); + }), + ); + return records.flat(); +} diff --git a/packages/app/e2e/support/helpers/isolated-host-daemon.ts b/packages/app/e2e/support/helpers/isolated-host-daemon.ts index 01fe3a70c1..c8dd3eaa44 100644 --- a/packages/app/e2e/support/helpers/isolated-host-daemon.ts +++ b/packages/app/e2e/support/helpers/isolated-host-daemon.ts @@ -1,4 +1,11 @@ -import { spawn, execFileSync, type ChildProcess, type SpawnOptions } from "node:child_process"; +import { promisify } from "node:util"; +import { + spawn, + execFile, + execFileSync, + type ChildProcess, + type SpawnOptions, +} from "node:child_process"; import { mkdtemp, rm, writeFile } from "node:fs/promises"; import net from "node:net"; import { tmpdir } from "node:os"; @@ -6,6 +13,8 @@ import path from "node:path"; import { withDisabledE2ESpeechEnv } from "./speech-env"; import { killProcessTree, spawnTsx } from "./spawn-node"; +const execFileAsync = promisify(execFile); + export interface IsolatedHostDaemon { serverId: string; port: number; @@ -152,6 +161,24 @@ export async function startIsolatedHostDaemon( const serverDir = publishedPackageRoot ? path.join(publishedPackageRoot, "node_modules", "@getpaseo", "server") : path.resolve(__dirname, "../../../../server"); + let child: ChildProcess | null = null; + const stopDaemon = async (): Promise => { + // The CLI owns graceful shutdown, forced cleanup and detached terminal + // reaping. Keep its ESM graph out of Playwright's transforming loader. + await execFileAsync( + process.execPath, + [ + path.resolve(__dirname, "../../../../cli/dist/index.js"), + "daemon", + "stop", + "--home", + paseoHome, + "--force", + ], + { timeout: 30_000 }, + ); + await killProcessTree(child); + }; const spawnDaemon = async (): Promise => { const spawnOptions: SpawnOptions = { cwd: serverDir, @@ -169,21 +196,21 @@ export async function startIsolatedHostDaemon( stdio: ["ignore", "ignore", "pipe"], detached: false, }; - const child = publishedPackageRoot + const spawned = publishedPackageRoot ? spawn(process.execPath, ["dist/scripts/supervisor-entrypoint.js"], spawnOptions) : spawnTsx("scripts/supervisor-entrypoint.ts", ["--dev"], spawnOptions); + child = spawned; let stderr = ""; - child.stderr?.on("data", (chunk: Buffer) => { + spawned.stderr?.on("data", (chunk: Buffer) => { stderr += chunk.toString("utf8"); stderr = stderr.split("\n").slice(-40).join("\n"); }); try { - await waitForServer(port, child); - return child; + await waitForServer(port, spawned); + return spawned; } catch (error) { - await killProcessTree(child); throw new Error( `${error instanceof Error ? error.message : String(error)}\nDaemon stderr:\n${stderr}`, { cause: error }, @@ -191,10 +218,10 @@ export async function startIsolatedHostDaemon( } }; - let child: ChildProcess; try { - child = await spawnDaemon(); + await spawnDaemon(); } catch (error) { + await stopDaemon(); if (!options.preserveHome) { await rm(paseoHome, { recursive: true, force: true }); } @@ -209,22 +236,22 @@ export async function startIsolatedHostDaemon( serverId, port, paseoHome, - getPid: () => child.pid, + getPid: () => child?.pid, restart: async () => { if (closed) throw new Error(`Cannot restart closed isolated daemon ${serverId}`); - await killProcessTree(child); - child = await spawnDaemon(); + await stopDaemon(); + await spawnDaemon(); }, close: async () => { if (closed) return; - closed = true; - await killProcessTree(child); + await stopDaemon(); if (!options.preserveHome) { await rm(paseoHome, { recursive: true, force: true }); } if (publishedPackageRoot) { await rm(publishedPackageRoot, { recursive: true, force: true }); } + closed = true; }, }; } diff --git a/packages/app/e2e/support/helpers/terminal-perf.ts b/packages/app/e2e/support/helpers/terminal-perf.ts index 5c00bed485..67a114b30f 100644 --- a/packages/app/e2e/support/helpers/terminal-perf.ts +++ b/packages/app/e2e/support/helpers/terminal-perf.ts @@ -1,4 +1,5 @@ import { expect, type Page } from "@playwright/test"; +import type { Terminal } from "@xterm/xterm"; import { buildHostWorkspaceRoute } from "../../../src/utils/host-routes"; import { getServerId } from "./server-id"; @@ -206,3 +207,100 @@ export function computePercentile(samples: number[], p: number): number { export function round2(value: number): number { return Math.round(value * 100) / 100; } + +/** Observe actual cursor pixels and blink phases through xterm's public render event. */ +export async function expectTerminalCursor( + page: Page, + expected: { shape: "bar" | "underline"; blinking: boolean }, +): Promise { + const observed = await page.evaluate(async () => { + const terminal = (window as Window & { __paseoTerminal?: Terminal }).__paseoTerminal; + if (!terminal) throw new Error("Terminal did not mount"); + const source = Array.from(document.querySelectorAll(".xterm-screen canvas")).find( + (canvas): canvas is HTMLCanvasElement => + canvas instanceof HTMLCanvasElement && canvas.getContext("webgl2") !== null, + ); + if (!source) throw new Error("Cursor verification requires the actual WebGL renderer"); + const copy = document.createElement("canvas"); + const context = copy.getContext("2d"); + if (!context) throw new Error("Cursor pixel capture is unavailable"); + terminal.focus(); + await new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())), + ); + if (!terminal.element?.contains(document.activeElement)) + throw new Error("Terminal did not focus"); + const started = performance.now(); + const frames: Array<{ time: number; width: number; height: number }> = []; + const rendered = terminal.onRender(() => { + copy.width = source.width; + copy.height = source.height; + // WebGL's default drawing buffer must be copied before this render returns. + context.drawImage(source, 0, 0); + const cellWidth = source.width / terminal.cols; + const cellHeight = source.height / terminal.rows; + const x = Math.round(terminal.buffer.active.cursorX * cellWidth); + const y = Math.round(terminal.buffer.active.cursorY * cellHeight); + const width = Math.ceil(cellWidth); + const height = Math.ceil(cellHeight); + const background = context.getImageData(x + width + 2, y, 1, 1).data; + const pixels = context.getImageData(x, y, width, height).data; + let minX = width; + let maxX = -1; + let minY = height; + let maxY = -1; + for (let row = 0; row < height; row++) { + for (let col = 0; col < width; col++) { + const offset = (row * width + col) * 4; + if ( + ![0, 1, 2, 3].some( + (channel) => Math.abs(pixels[offset + channel]! - background[channel]!) > 20, + ) + ) + continue; + minX = Math.min(minX, col); + maxX = Math.max(maxX, col); + minY = Math.min(minY, row); + maxY = Math.max(maxY, row); + } + } + frames.push({ + time: performance.now() - started, + width: maxX < 0 ? 0 : (maxX - minX + 1) / cellWidth, + height: maxY < 0 ? 0 : (maxY - minY + 1) / cellHeight, + }); + }); + try { + const refresh = setInterval(() => terminal.refresh(0, terminal.rows - 1), 40); + try { + await new Promise((resolve) => setTimeout(resolve, 1800)); + } finally { + clearInterval(refresh); + } + } finally { + rendered.dispose(); + } + return { + frames, + focused: terminal.element?.contains(document.activeElement), + samples: frames.length, + width: Math.max(...frames.map((frame) => frame.width)), + height: Math.max(...frames.map((frame) => frame.height)), + blinking: + frames.filter( + (frame, index) => index > 0 && (frame.width === 0) !== (frames[index - 1]!.width === 0), + ).length >= 2, + }; + }); + expect(observed.samples).toBeGreaterThan(5); + expect(observed.blinking, JSON.stringify(observed)).toBe(expected.blinking); + if (expected.shape === "bar") { + expect(observed.width).toBeGreaterThan(0); + expect(observed.width).toBeLessThan(0.4); + expect(observed.height).toBeGreaterThan(0.6); + } else { + expect(observed.width).toBeGreaterThan(0.6); + expect(observed.height).toBeGreaterThan(0); + expect(observed.height).toBeLessThan(0.4); + } +} diff --git a/packages/app/package.json b/packages/app/package.json index 42294ae6a1..4fcd5d4737 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -154,6 +154,7 @@ "@types/ws": "^8.18.1", "@vitest/browser": "^4.1.7", "@vitest/browser-playwright": "^4.1.7", + "@xterm/addon-serialize": "0.14.0", "@xterm/headless": "^6.1.0-beta.213", "babel-preset-expo": "~57.0.16", "dotenv": "^17.2.3", diff --git a/packages/app/src/components/terminal-emulator-contract.ts b/packages/app/src/components/terminal-emulator-contract.ts index c4c7080b83..12638161a1 100644 --- a/packages/app/src/components/terminal-emulator-contract.ts +++ b/packages/app/src/components/terminal-emulator-contract.ts @@ -4,7 +4,6 @@ import type { } from "../terminal/runtime/terminal-emulator-runtime"; import type { Ref } from "react"; import type { ITheme } from "@xterm/xterm"; -import type { TerminalState } from "@getpaseo/protocol/messages"; import type { TerminalInputModeState } from "@getpaseo/protocol/terminal-input-mode"; import type { TerminalOutputData } from "../terminal/runtime/terminal-emulator-runtime"; import type { @@ -19,8 +18,7 @@ import type { TerminalRendererReadyChange } from "../utils/terminal-renderer-rea export interface TerminalEmulatorHandle { find?: TerminalFindHandle; writeOutput: (data: TerminalOutputData) => void; - restoreOutput: (data: TerminalOutputData) => void; - renderSnapshot: (state: TerminalState | null) => void; + replay: (event: import("@getpaseo/client").TerminalReplayEvent) => void; paste: (text: string) => void; copySelection: (clipboard: TerminalClipboardWriter) => Promise; clear: () => void; @@ -44,7 +42,6 @@ export interface TerminalEmulatorProps { swipeGesturesEnabled?: boolean; onSwipeLeft?: () => void; onSwipeRight?: () => void; - initialSnapshot?: TerminalState | null; onFindRequest?: () => void; onFindResult?: (result: TerminalFindResult) => void; onInput?: (data: string) => Promise | void; diff --git a/packages/app/src/components/terminal-emulator-native-grid.native.tsx b/packages/app/src/components/terminal-emulator-native-grid.native.tsx index b85380b715..57286f2a95 100644 --- a/packages/app/src/components/terminal-emulator-native-grid.native.tsx +++ b/packages/app/src/components/terminal-emulator-native-grid.native.tsx @@ -13,7 +13,6 @@ import { type ViewStyle, } from "react-native"; import type { ITheme } from "@xterm/xterm"; -import type { TerminalState } from "@getpaseo/protocol/messages"; import { TerminalInputModeTracker, terminalInputModeStatesEqual, @@ -120,43 +119,8 @@ function resolvePanResponderPoint( }; } -function initialNativeTerminalSize(snapshot: TerminalState | null): TerminalMeasuredSize { - return { - rows: snapshot?.rows ?? MIN_NATIVE_TERMINAL_ROWS, - cols: snapshot?.cols ?? MIN_NATIVE_TERMINAL_COLS, - }; -} - -function screenStateFromViewport(viewport: TerminalViewportState): TerminalScreenState { - const visibleRows = viewport.grid.length; - const currentViewport = { - firstRow: viewport.firstRow, - lastRow: Math.min(viewport.newestRow, viewport.firstRow + Math.max(1, visibleRows) - 1), - }; - return { - viewport, - scroll: { - mode: "following", - firstRow: viewport.firstRow, - visibleRows, - oldestRow: viewport.oldestRow, - newestRow: viewport.newestRow, - currentViewport, - bottomViewport: currentViewport, - }, - }; -} - -function viewportStateFromSnapshot(state: TerminalState): TerminalViewportState { - return { - rows: state.grid.length, - cols: state.cols, - firstRow: 0, - oldestRow: 0, - newestRow: Math.max(0, state.grid.length - 1), - grid: state.grid, - cursor: state.cursor, - }; +function initialNativeTerminalSize(): TerminalMeasuredSize { + return { rows: MIN_NATIVE_TERMINAL_ROWS, cols: MIN_NATIVE_TERMINAL_COLS }; } function NativeTerminalEmulator({ @@ -169,7 +133,6 @@ function NativeTerminalEmulator({ fontSize, keyboardInset = 0, isKeyboardVisible = false, - initialSnapshot = null, onInput, onTerminalKey, onResize, @@ -181,20 +144,18 @@ function NativeTerminalEmulator({ resizeRequestToken = 0, }: TerminalEmulatorProps) { const terminalRef = useRef(null); - const mountInputRef = useRef({ streamKey, initialSnapshot }); + const mountInputRef = useRef({ streamKey }); if ( resolveNativeTerminalMountAction({ mountedStreamKey: mountInputRef.current.streamKey, nextStreamKey: streamKey, }) === "mount" ) { - mountInputRef.current = { streamKey, initialSnapshot }; + mountInputRef.current = { streamKey }; } const inputRef = useRef(null); - const terminalSizeRef = useRef(initialNativeTerminalSize(initialSnapshot)); - const resizePolicyRef = useRef( - createTerminalResizePolicy(initialNativeTerminalSize(initialSnapshot)), - ); + const terminalSizeRef = useRef(initialNativeTerminalSize()); + const resizePolicyRef = useRef(createTerminalResizePolicy(initialNativeTerminalSize())); const activeResizeClaimTokenRef = useRef(0); const layoutRef = useRef(null); const metricsRef = useRef(null); @@ -220,11 +181,7 @@ function NativeTerminalEmulator({ ...inputModeTrackerRef.current.getState(), applicationCursorKeys: false, }); - const [terminalScreen, setTerminalScreen] = useState(() => { - return initialSnapshot - ? screenStateFromViewport(viewportStateFromSnapshot(initialSnapshot)) - : null; - }); + const [terminalScreen, setTerminalScreen] = useState(null); const [selectionRange, setSelectionRange] = useState(null); const selectionRangeRef = useRef(null); const hasNotifiedSelectionRef = useRef(false); @@ -361,10 +318,14 @@ function NativeTerminalEmulator({ (terminal: NativeHeadlessTerminal): NativeTerminalOutputDrain => createNativeTerminalOutputDrain({ write: async (chunk) => { + inputModeTrackerRef.current.feed(chunk); await terminal.write(chunk); emitInputModeChange(); }, - reset: () => { + restoreSize: () => terminal.resize(terminalSizeRef.current), + reset: (size) => { + inputModeTrackerRef.current.reset(); + if (size) terminal.resize(size); terminal.reset(); emitInputModeChange(); }, @@ -419,8 +380,7 @@ function NativeTerminalEmulator({ hasNotifiedMeasuredSizeRef.current = true; terminalSizeRef.current = policyResult.measuredSize; if (policyResult.measuredSizeChanged) { - terminalRef.current?.resize(policyResult.measuredSize); - schedulePaint(); + outputDrainRef.current?.resize(); } callbacksRef.current.onResize?.({ rows: policyResult.measuredSize.rows, @@ -437,68 +397,51 @@ function NativeTerminalEmulator({ }); } }, - [schedulePaint], + [], ); - const resetTerminal = useCallback( - (snapshot: TerminalState | null) => { - outputDrainRef.current?.dispose(); - outputDrainRef.current = null; - terminalRef.current?.dispose(); - screenModelRef.current = null; - latestResolvedScreenRef.current = null; - clearSelection(); - const measuredSize = resolveMeasuredNativeTerminalSize({ - layout: layoutRef.current, - metrics: metricsRef.current, - }); - const size = - measuredSize ?? - (snapshot ? { rows: snapshot.rows, cols: snapshot.cols } : terminalSizeRef.current); - terminalSizeRef.current = size; - resizePolicyRef.current = createTerminalResizePolicy(size); - outputDecoderRef.current.decode(); - const terminal = createNativeHeadlessTerminal({ - rows: size.rows, - cols: size.cols, - scrollbackLines, - }); - terminalRef.current = terminal; - screenModelRef.current = createNativeTerminalScreenModel({ terminal }); - const outputDrain = createOutputDrain(terminal); - outputDrainRef.current = outputDrain; - const screen = snapshot - ? screenStateFromViewport(viewportStateFromSnapshot(snapshot)) - : resolveTerminalScreen(terminal); - commitTerminalScreen(screen); - resetInputModeTracker(); - if (snapshot) { - outputDrain.restoreSnapshot(snapshot); - } - }, - [ - commitTerminalScreen, - createOutputDrain, - resetInputModeTracker, - resolveTerminalScreen, + const resetTerminal = useCallback(() => { + outputDrainRef.current?.dispose(); + outputDrainRef.current = null; + terminalRef.current?.dispose(); + screenModelRef.current = null; + latestResolvedScreenRef.current = null; + clearSelection(); + const measuredSize = resolveMeasuredNativeTerminalSize({ + layout: layoutRef.current, + metrics: metricsRef.current, + }); + const size = measuredSize ?? terminalSizeRef.current; + terminalSizeRef.current = size; + resizePolicyRef.current = createTerminalResizePolicy(size); + outputDecoderRef.current.decode(); + const terminal = createNativeHeadlessTerminal({ + rows: size.rows, + cols: size.cols, scrollbackLines, - clearSelection, - ], - ); + }); + terminalRef.current = terminal; + screenModelRef.current = createNativeTerminalScreenModel({ terminal }); + const outputDrain = createOutputDrain(terminal); + outputDrainRef.current = outputDrain; + const screen = resolveTerminalScreen(terminal); + commitTerminalScreen(screen); + resetInputModeTracker(); + }, [ + commitTerminalScreen, + createOutputDrain, + resetInputModeTracker, + resolveTerminalScreen, + scrollbackLines, + clearSelection, + ]); - const enqueueOutputText = useCallback( - (text: string) => { - if (text.length === 0) { - return; - } - const inputModeUpdate = inputModeTrackerRef.current.feed(text); - if (inputModeUpdate.changed) { - emitInputModeChange(); - } - outputDrainRef.current?.enqueueText(text); - }, - [emitInputModeChange], - ); + const enqueueOutputText = useCallback((text: string) => { + if (text.length === 0) { + return; + } + outputDrainRef.current?.enqueueText(text); + }, []); const claimActiveTerminalSize = useCallback(() => { activeResizeClaimTokenRef.current += 1; @@ -521,27 +464,7 @@ function NativeTerminalEmulator({ const text = outputDecoderRef.current.decode(data, { stream: true }); enqueueOutputText(text); }, - restoreOutput: (data: TerminalOutputData) => { - outputDecoderRef.current.decode(); - resetInputModeTracker(); - const text = outputDecoderRef.current.decode(data, { stream: false }); - outputDrainRef.current?.restoreText(text); - }, - renderSnapshot: (state: TerminalState | null) => { - outputDecoderRef.current.decode(); - resetInputModeTracker(); - if (!state) { - resetTerminal(null); - return; - } - clearSelection(); - const outputDrain = outputDrainRef.current; - if (!outputDrain) { - resetTerminal(state); - return; - } - outputDrain.restoreSnapshot(state); - }, + replay: (event) => outputDrainRef.current?.replay(event), paste: (text: string) => { if (text.length === 0) { return; @@ -572,7 +495,6 @@ function NativeTerminalEmulator({ screenModelRef.current?.reset(); clearSelection(); resetInputModeTracker(); - terminalRef.current?.reset(); schedulePaint(); }, claimSize: claimActiveTerminalSize, @@ -591,14 +513,13 @@ function NativeTerminalEmulator({ claimActiveTerminalSizeForAction, clearSelection, resetInputModeTracker, - resetTerminal, schedulePaint, ], ); useEffect(() => { hasNotifiedMeasuredSizeRef.current = false; - resetTerminal(mountInputRef.current.initialSnapshot); + resetTerminal(); emitMeasuredSize({ source: "measure" }); return () => { callbacksRef.current.onRendererReadyChange?.({ streamKey, isReady: false }); diff --git a/packages/app/src/components/terminal-emulator.tsx b/packages/app/src/components/terminal-emulator.tsx index 3d272fb75e..fa6ac9faba 100644 --- a/packages/app/src/components/terminal-emulator.tsx +++ b/packages/app/src/components/terminal-emulator.tsx @@ -19,7 +19,6 @@ import type { DOMProps } from "expo/dom"; import { useDOMImperativeHandle, type DOMImperativeFactory } from "expo/dom"; import "@xterm/xterm/css/xterm.css"; import type { ITheme } from "@xterm/xterm"; -import type { TerminalState } from "@getpaseo/protocol/messages"; import type { TerminalInputModeState } from "@getpaseo/protocol/terminal-input-mode"; import type { PendingTerminalModifiers } from "../utils/terminal-keys"; import { @@ -40,8 +39,7 @@ import { focusWithRetries } from "../utils/web-focus"; export interface TerminalEmulatorHandle { find?: TerminalFindHandle; writeOutput: (data: TerminalOutputData) => void; - restoreOutput: (data: TerminalOutputData) => void; - renderSnapshot: (state: TerminalState | null) => void; + replay: (event: import("@getpaseo/client").TerminalReplayEvent) => void; paste: (text: string) => void; copySelection: (clipboard: TerminalClipboardWriter) => Promise; clear: () => void; @@ -108,7 +106,6 @@ interface TerminalEmulatorProps { swipeGesturesEnabled?: boolean; onSwipeLeft?: () => void; onSwipeRight?: () => void; - initialSnapshot?: TerminalState | null; onFindRequest?: () => void; onFindResult?: (result: TerminalFindResult) => void; onInput?: (data: string) => Promise | void; @@ -147,16 +144,6 @@ declare global { interface Window {} } -function isTerminalState(value: unknown): value is TerminalState { - return ( - typeof value === "object" && - value !== null && - "rows" in value && - "cols" in value && - "grid" in value - ); -} - export default function TerminalEmulator({ ref, streamKey, @@ -172,7 +159,6 @@ export default function TerminalEmulator({ swipeGesturesEnabled = false, onSwipeLeft, onSwipeRight, - initialSnapshot = null, onFindRequest, onFindResult, onInput, @@ -228,8 +214,6 @@ export default function TerminalEmulator({ onOpenLocalFileLink, onFilePaste, }; - const initialSnapshotRef = useRef(initialSnapshot); - initialSnapshotRef.current = initialSnapshot; const pendingModifiersRef = useRef(pendingModifiers); pendingModifiersRef.current = pendingModifiers; @@ -253,17 +237,17 @@ export default function TerminalEmulator({ const data = args[0]; if (data instanceof Uint8Array) runtimeRef.current?.write({ data }); }, - restoreOutput: (...args) => { - const data = args[0]; - if (data instanceof Uint8Array) runtimeRef.current?.restoreOutput({ data }); - }, - renderSnapshot: (...args) => { - const state = args[0]; - if (state === null) { - runtimeRef.current?.renderSnapshot({ state: null }); - } else if (isTerminalState(state)) { - runtimeRef.current?.renderSnapshot({ state }); - } + replay: (event) => { + if (!event || typeof event !== "object" || Array.isArray(event)) return; + if (event.type === "end") runtimeRef.current?.replay({ type: "end" }); + if (event.type === "data" && event.data instanceof Uint8Array) + runtimeRef.current?.replay({ type: "data", data: event.data }); + if (event.type === "begin") + runtimeRef.current?.replay({ + type: "begin", + rows: typeof event.rows === "number" ? event.rows : undefined, + cols: typeof event.cols === "number" ? event.cols : undefined, + }); }, paste: (...args) => { const text = args[0]; @@ -299,12 +283,7 @@ export default function TerminalEmulator({ writeOutput: (data: TerminalOutputData) => { runtimeRef.current?.write({ data }); }, - restoreOutput: (data: TerminalOutputData) => { - runtimeRef.current?.restoreOutput({ data }); - }, - renderSnapshot: (state: TerminalState | null) => { - runtimeRef.current?.renderSnapshot({ state }); - }, + replay: (event) => runtimeRef.current?.replay(event), paste: (text: string) => { pasteText(text); }, @@ -471,7 +450,6 @@ export default function TerminalEmulator({ runtime.mount({ root, host, - initialSnapshot: initialSnapshotRef.current, scrollback: scrollbackLinesRef.current, theme: mountedThemeRef.current, fontFamily: fontFamilyRef.current, diff --git a/packages/app/src/components/terminal-pane.tsx b/packages/app/src/components/terminal-pane.tsx index 6c1561bc5b..d60556e0fa 100644 --- a/packages/app/src/components/terminal-pane.tsx +++ b/packages/app/src/components/terminal-pane.tsx @@ -15,7 +15,6 @@ import Animated, { runOnJS, useAnimatedReaction } from "react-native-reanimated" import { StyleSheet, useUnistyles } from "react-native-unistyles"; import { Keyboard as KeyboardIcon, KeyboardOff as KeyboardOffIcon } from "lucide-react-native"; import type { TerminalKeyInput } from "@getpaseo/protocol/terminal-key-input"; -import type { TerminalState } from "@getpaseo/protocol/messages"; import { DEFAULT_TERMINAL_INPUT_MODE_STATE, type TerminalInputModeState, @@ -60,7 +59,6 @@ import { getDesktopHost } from "@/desktop/host"; import { routeTerminalDrop } from "@/terminal/drop/terminal-file-drop"; import { prepareDroppedPathsForTerminal } from "@/terminal/drop/terminal-path"; import { toErrorMessage } from "@/utils/error-messages"; -import { getWorkspaceTerminalSession } from "@/terminal/runtime/workspace-terminal-session"; import { EMPTY_FOCUS_CLAIM_STATE, canRequestFocusClaim, @@ -88,7 +86,6 @@ import { isNative } from "@/constants/platform"; import { applyTerminalRendererReadyChange, resolveTerminalStreamTarget, - shouldReplayTerminalSnapshotForRenderer, shouldShowTerminalLoadingOverlay, type TerminalRendererReadyChange, } from "@/utils/terminal-renderer-readiness"; @@ -316,10 +313,6 @@ export function TerminalPane({ const measuredTerminalSizeRef = useRef<{ rows: number; cols: number } | null>(null); const lastSentTerminalSizeRef = useRef<{ rows: number; cols: number } | null>(null); const streamControllerRef = useRef(null); - const workspaceTerminalSession = useMemo( - () => getWorkspaceTerminalSession({ scopeKey }), - [scopeKey], - ); const [isAttaching, setIsAttaching] = useState(false); const [streamError, setStreamError] = useState(null); const [rendererReadyStreamKey, setRendererReadyStreamKey] = useState(null); @@ -383,7 +376,6 @@ export function TerminalPane({ const keyboardRefitTimeoutsRef = useRef>>([]); const lastAutoFocusKeyRef = useRef(null); const paneFocusResizeClaimRef = useRef(EMPTY_FOCUS_CLAIM_STATE); - const initialSnapshot = workspaceTerminalSession.snapshots.get({ terminalId }); useEffect(() => { terminalIdRef.current = terminalId; @@ -441,16 +433,8 @@ export function TerminalPane({ (change: TerminalRendererReadyChange) => { if (!change.isReady && change.streamKey === terminalStreamKey) findRef.current?.reset(); setRendererReadyStreamKey((current) => applyTerminalRendererReadyChange(current, change)); - if (!shouldReplayTerminalSnapshotForRenderer({ change, terminalStreamKey })) { - return; - } - - const snapshot = workspaceTerminalSession.snapshots.get({ terminalId }); - if (snapshot) { - emulatorRef.current?.renderSnapshot(snapshot); - } }, - [terminalId, terminalStreamKey, workspaceTerminalSession.snapshots], + [terminalStreamKey], ); useEffect(() => { @@ -564,7 +548,6 @@ export function TerminalPane({ ); const handleStreamExit = useStableEvent((exitedTerminalId: string) => { - workspaceTerminalSession.snapshots.clear({ terminalId: exitedTerminalId }); if (terminalIdRef.current === exitedTerminalId) emulatorRef.current?.clear(); setModifiers({ ...EMPTY_MODIFIERS }); }); @@ -604,29 +587,10 @@ export function TerminalPane({ }, ); - const handleStreamRestore = useStableEvent( - ({ terminalId: restoreTerminalId, data }: { terminalId: string; data: Uint8Array }) => { - workspaceTerminalSession.snapshots.clear({ terminalId: restoreTerminalId }); - if (terminalIdRef.current !== restoreTerminalId) { - return; - } - emulatorRef.current?.restoreOutput(data); - }, - ); - - const handleStreamSnapshot = useStableEvent( - ({ terminalId: snapshotTerminalId, state }: { terminalId: string; state: TerminalState }) => { - workspaceTerminalSession.snapshots.set({ terminalId: snapshotTerminalId, state }); - if (terminalIdRef.current !== snapshotTerminalId) { - return; - } - emulatorRef.current?.renderSnapshot(state); - }, - ); - const getStreamRestoreOptions = useStableEvent(() => resolveTerminalRestoreOptions({ supportsTerminalRestoreModes, + scrollbackLines: settings.terminalScrollbackLines, canClaimSize: canRequestFocusClaim({ isWorkspaceFocused: terminalPresentedRef.current, isPaneFocused, @@ -653,8 +617,9 @@ export function TerminalPane({ client, getPreferredSize: getPreferredStreamSize, onOutput: handleStreamOutput, - onRestore: handleStreamRestore, - onSnapshot: handleStreamSnapshot, + onReplay: ({ terminalId: id, replay }) => { + if (terminalIdRef.current === id) emulatorRef.current?.replay(replay); + }, onExit: handleStreamExit, getRestoreOptions: getStreamRestoreOptions, onStatusChange: handleStreamControllerStatus, @@ -674,8 +639,6 @@ export function TerminalPane({ getStreamRestoreOptions, handleStreamControllerStatus, handleStreamOutput, - handleStreamRestore, - handleStreamSnapshot, handleStreamExit, isConnected, ]); @@ -1216,7 +1179,6 @@ export function TerminalPane({ keyboardInset={keyboardInset} isKeyboardVisible={isKeyboardVisible} swipeGesturesEnabled={swipeGesturesEnabled} - initialSnapshot={initialSnapshot} onRendererReadyChange={handleRendererReadyChange} onSwipeRight={handleSwipeRight} onSwipeLeft={handleSwipeLeft} diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index 7c9e13cce1..8d7c2a2950 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -617,6 +617,7 @@ export const ar: TranslationResources = { terminal: { hostDisconnected: "Host غير متصل", updateHost: "حدّث المضيف لاستخدام عارض الطرفية الأصلي.", + restoreRequiresUpdate: "حدّث المضيف لعرض الطرفيات.", unableToSubscribe: "غير قادر على الاشتراك في المحطة", fileUploaded: "تم رفع الملف", pasteFileFailed: "تعذر لصق الملف: {{reason}}", diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index 7022dc9a3d..1f61a83f12 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -614,6 +614,7 @@ export const en = { terminal: { hostDisconnected: "Host is not connected", updateHost: "Update the host to use the native terminal renderer.", + restoreRequiresUpdate: "Update the host to view terminals.", unableToSubscribe: "Unable to subscribe to terminal", fileUploaded: "File uploaded", pasteFileFailed: "Failed to paste file: {{reason}}", diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index 1c2c07ade0..7e5a1d41e6 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -623,6 +623,7 @@ export const es: TranslationResources = { terminal: { hostDisconnected: "Hostno está conectado", updateHost: "Actualiza el host para usar el renderizador de terminal nativo.", + restoreRequiresUpdate: "Actualiza el host para ver las terminales.", unableToSubscribe: "No se puede suscribir al terminal", fileUploaded: "Archivo subido", pasteFileFailed: "No se pudo pegar el archivo: {{reason}}", diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index bf1c3b6f5e..551f4a4158 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -623,6 +623,7 @@ export const fr: TranslationResources = { terminal: { hostDisconnected: "L’hôte n’est pas connecté", updateHost: "Mettez à jour l’hôte pour utiliser le rendu natif du terminal.", + restoreRequiresUpdate: "Mettez à jour l’hôte pour afficher les terminaux.", unableToSubscribe: "Impossible de s’abonner au terminal", fileUploaded: "Fichier envoyé", pasteFileFailed: "Impossible de coller le fichier : {{reason}}", diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index 5147134716..4b1b8b6f64 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -623,6 +623,7 @@ export const ja: TranslationResources = { terminal: { hostDisconnected: "ホストが接続されていません", updateHost: "ネイティブターミナルを使用するにはホストを更新してください。", + restoreRequiresUpdate: "ターミナルを表示するにはホストを更新してください。", unableToSubscribe: "ターミナルに接続できません", fileUploaded: "ファイルをアップロードしました", pasteFileFailed: "ファイルを貼り付けられませんでした: {{reason}}", diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index 632bd1eeed..b9e33b4eba 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -618,6 +618,7 @@ export const ko: TranslationResources = { terminal: { hostDisconnected: "호스트가 연결되어 있지 않습니다", updateHost: "기본 터미널 렌더러를 사용하도록 호스트를 업데이트합니다.", + restoreRequiresUpdate: "터미널을 보려면 호스트를 업데이트하세요.", unableToSubscribe: "터미널을 구독할 수 없습니다", fileUploaded: "파일을 업로드했습니다", pasteFileFailed: "파일을 붙여넣지 못했습니다: {{reason}}", diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index a80ded2f45..2fa6c30c8e 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -622,6 +622,7 @@ export const ptBR: TranslationResources = { terminal: { hostDisconnected: "Host não está conectado", updateHost: "Atualize o host para usar o renderizador de terminal nativo.", + restoreRequiresUpdate: "Atualize o host para visualizar os terminais.", unableToSubscribe: "Não foi possível assinar o terminal", fileUploaded: "Arquivo enviado", pasteFileFailed: "Falha ao colar o arquivo: {{reason}}", diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index d4a23a4770..9a6eb5b0e2 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -624,6 +624,7 @@ export const ru: TranslationResources = { terminal: { hostDisconnected: "Хост не подключён", updateHost: "Обновите хост, чтобы использовать нативный рендерер терминала.", + restoreRequiresUpdate: "Обновите хост, чтобы просматривать терминалы.", unableToSubscribe: "Не удалось подключиться к терминалу", fileUploaded: "Файл загружен", pasteFileFailed: "Не удалось вставить файл: {{reason}}", diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index 2ce5f7bb9e..553d8212b4 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -617,6 +617,7 @@ export const zhCN: TranslationResources = { terminal: { hostDisconnected: "Host 未连接", updateHost: "请更新主机以使用原生终端渲染器。", + restoreRequiresUpdate: "更新主机以查看终端。", unableToSubscribe: "无法订阅 Terminal", fileUploaded: "文件已上传", pasteFileFailed: "无法粘贴文件:{{reason}}", diff --git a/packages/app/src/screens/workspace/workspace-screen.tsx b/packages/app/src/screens/workspace/workspace-screen.tsx index 0b1cfe07ab..dd806e1fa1 100644 --- a/packages/app/src/screens/workspace/workspace-screen.tsx +++ b/packages/app/src/screens/workspace/workspace-screen.tsx @@ -127,7 +127,6 @@ import { useWorkspaceSetupStore, } from "@/stores/workspace-setup-store"; import { useWorkspace } from "@/stores/session-store-hooks"; -import { useWorkspaceTerminalSessionRetention } from "@/terminal/hooks/use-workspace-terminal-session-retention"; import type { CheckoutStatusPayload } from "@/git/use-status-query"; import { confirmDialog } from "@/utils/confirm-dialog"; import { useArchiveAgent } from "@/hooks/use-archive-agent"; @@ -881,13 +880,6 @@ function shouldShowWorkspaceScreenHeader(input: { return !input.isFocusModeEnabled || input.isMobile; } -function buildWorkspaceTerminalScopeKey(serverId: string, workspaceId: string): string | null { - if (!serverId || !workspaceId) { - return null; - } - return `${serverId}:${workspaceId}`; -} - /** * A pane the user acted inside owns the tab: it opens there, and an existing tab * moves there. No pane means the open has no opinion beyond the focused pane. @@ -1066,14 +1058,6 @@ function WorkspaceScreenContent({ const { handleRetryHost, handleManageHost, handleDismissMissingWorkspace } = useWorkspaceRouteActions(normalizedServerId); - const workspaceTerminalScopeKey = useMemo( - () => buildWorkspaceTerminalScopeKey(normalizedServerId, normalizedWorkspaceId), - [normalizedServerId, normalizedWorkspaceId], - ); - useWorkspaceTerminalSessionRetention({ - scopeKey: workspaceTerminalScopeKey, - }); - const client = useHostRuntimeClient(normalizedServerId); const isConnected = useHostRuntimeIsConnected(normalizedServerId); const supportsProvidersSnapshot = useSessionStore( diff --git a/packages/app/src/terminal/hooks/use-workspace-terminal-session-retention.ts b/packages/app/src/terminal/hooks/use-workspace-terminal-session-retention.ts deleted file mode 100644 index 506a5baab3..0000000000 --- a/packages/app/src/terminal/hooks/use-workspace-terminal-session-retention.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { useEffect } from "react"; -import { - releaseWorkspaceTerminalSession, - retainWorkspaceTerminalSession, -} from "@/terminal/runtime/workspace-terminal-session"; - -export function useWorkspaceTerminalSessionRetention(input: { scopeKey: string | null }): void { - useEffect(() => { - if (!input.scopeKey) { - return; - } - - retainWorkspaceTerminalSession({ scopeKey: input.scopeKey }); - return () => { - releaseWorkspaceTerminalSession({ scopeKey: input.scopeKey! }); - }; - }, [input.scopeKey]); -} diff --git a/packages/app/src/terminal/native-renderer/headless-terminal-output-drain.test.ts b/packages/app/src/terminal/native-renderer/headless-terminal-output-drain.test.ts index fb94588a01..4d238b98c6 100644 --- a/packages/app/src/terminal/native-renderer/headless-terminal-output-drain.test.ts +++ b/packages/app/src/terminal/native-renderer/headless-terminal-output-drain.test.ts @@ -1,8 +1,8 @@ +import { createTerminalResizePolicy, updateTerminalResizePolicy } from "./terminal-resize-policy"; import { describe, expect, test } from "vitest"; import { createNativeHeadlessTerminal, - type TerminalCellRow, type TerminalViewportState, } from "./headless-terminal-state"; import { createNativeTerminalBenchmarkPayload } from "./native-terminal-benchmark-payload"; @@ -11,7 +11,8 @@ import { NATIVE_TERMINAL_PARSE_CHUNK_CHARS, } from "./headless-terminal-output-drain"; import { createNativeTerminalScreenModel, type TerminalScreenState } from "./terminal-screen-model"; -import { renderTerminalSnapshotToAnsi } from "../runtime/terminal-snapshot"; +import { Terminal as ReplaySource } from "@xterm/headless"; +import { SerializeAddon } from "@xterm/addon-serialize"; const ROWS = 12; const COLS = 80; @@ -41,33 +42,6 @@ function createFrameRecorder() { }; } -function lineCells(line: string, cols: number): TerminalCellRow { - const cells: TerminalCellRow = []; - for (let index = 0; index < cols; index += 1) { - cells.push({ char: line[index] ?? " ", width: 1 }); - } - return cells; -} - -function terminalStateFromLines(input: { - lines: string[]; - rows: number; - cols: number; - cursor: TerminalViewportState["cursor"]; -}) { - const grid: TerminalCellRow[] = []; - for (let row = 0; row < input.rows; row += 1) { - grid.push(lineCells(input.lines[row] ?? "", input.cols)); - } - return { - rows: input.rows, - cols: input.cols, - grid, - scrollback: [], - cursor: input.cursor, - }; -} - async function runScheduledWork(input: { callbacks: Array<() => void>; flush: Promise; @@ -80,11 +54,13 @@ async function runScheduledWork(input: { } async function benchmarkSnapshot(lineCount: number) { - const terminal = createNativeHeadlessTerminal({ rows: ROWS, cols: COLS, scrollbackLines: 100 }); - await terminal.write( - createNativeTerminalBenchmarkPayload({ startLine: 0, lineCount, cols: COLS }), - ); - return terminal.getState(); + return { + rows: ROWS, + cols: COLS, + data: new TextEncoder().encode( + createNativeTerminalBenchmarkPayload({ startLine: 0, lineCount, cols: COLS }), + ), + }; } function createScreenRestorer( @@ -94,6 +70,7 @@ function createScreenRestorer( const frameRecorder = createFrameRecorder(); let screen: TerminalScreenState | null = null; const drain = createNativeTerminalOutputDrain({ + restoreSize: () => {}, write: (chunk) => terminal.write(chunk), reset: () => terminal.reset(), getViewportState: () => { @@ -107,7 +84,12 @@ function createScreenRestorer( return { async restore(snapshot: Awaited>) { - drain.restoreSnapshot(snapshot); + drain.replay({ type: "begin", rows: snapshot.rows, cols: snapshot.cols }); + drain.replay({ + type: "data", + data: snapshot.data, + }); + drain.replay({ type: "end" }); await drain.flush(); frameRecorder.frames[0]?.(); return screen; @@ -122,6 +104,7 @@ describe("native terminal output drain", () => { const frameRecorder = createFrameRecorder(); const payload = "x".repeat(NATIVE_TERMINAL_PARSE_CHUNK_CHARS * 2); const drain = createNativeTerminalOutputDrain({ + restoreSize: () => {}, write: async (chunk) => { writes.push(chunk); }, @@ -170,6 +153,7 @@ describe("native terminal output drain", () => { const paintedStates: TerminalViewportState[] = []; const frameRecorder = createFrameRecorder(); const drain = createNativeTerminalOutputDrain({ + restoreSize: () => {}, write: (chunk) => terminal.write(chunk), reset: () => terminal.reset(), getViewportState: () => terminal.getViewportState(), @@ -202,6 +186,7 @@ describe("native terminal output drain", () => { const scheduledWork: Array<() => void> = []; const frameRecorder = createFrameRecorder(); const drain = createNativeTerminalOutputDrain({ + restoreSize: () => {}, write: (chunk) => terminal.write(chunk), reset: () => terminal.reset(), getViewportState: () => terminal.getViewportState(), @@ -210,21 +195,22 @@ describe("native terminal output drain", () => { scheduleFrame: frameRecorder.scheduleFrame, cancelFrame: frameRecorder.cancelFrame, }); - const restoredSnapshot = terminalStateFromLines({ - rows: 4, - cols: 32, - lines: ["restored-one", "restored-two"], - cursor: { row: 1, col: "restored-two".length }, - }); + const restoredCursor = { row: 1, col: "restored-two".length }; + const replay = new TextEncoder().encode("restored-one\r\nrestored-two"); await terminal.write("old-one\r\nold-two\r\nold-three\r\n"); drain.enqueueText("stale-queued\r\n"); - drain.restoreText(renderTerminalSnapshotToAnsi(restoredSnapshot)); + drain.replay({ type: "begin" }); + drain.replay({ + type: "data", + data: replay, + }); + drain.replay({ type: "end" }); await runScheduledWork({ callbacks: scheduledWork, flush: drain.flush() }); const state = terminal.getViewportState(); expect(state.grid.map(rowText)).toEqual(["restored-one", "restored-two", "", ""]); - expect(state.cursor).toEqual(restoredSnapshot.cursor); + expect(state.cursor).toEqual(restoredCursor); }); test("snapshot restore preserves a scrolled viewport anchor while replacing terminal state", async () => { @@ -242,7 +228,7 @@ describe("native terminal output drain", () => { paintedMode: screen?.scroll.mode, paintedTopRow: rowText(screen?.viewport.grid[0] ?? []), beforeTopRow, - restoredBottomRows: terminal.getState().grid.slice(-2).map(rowText), + restoredBottomRows: terminal.getViewportState().grid.slice(-2).map(rowText), }).toEqual({ paintedMode: "scrolled", paintedTopRow: beforeTopRow, @@ -268,3 +254,255 @@ describe("native terminal output drain", () => { }); }); }); + +test("replays split Unicode and ANSI with one reset then live output", async () => { + const terminal = createNativeHeadlessTerminal({ rows: 4, cols: 40, scrollbackLines: 1000 }); + let resets = 0; + const drain = createNativeTerminalOutputDrain({ + restoreSize: () => {}, + write: (text) => terminal.write(text), + reset: (size) => { + resets++; + if (size) terminal.resize(size); + terminal.reset(); + }, + getViewportState: () => terminal.getViewportState(), + onPaint: () => {}, + }); + try { + drain.replay({ type: "begin", rows: 4, cols: 40, retainedHistoryLines: 400 }); + const bytes = new TextEncoder().encode("\x1b[31m界🙂 replay\x1b[0m\r\n"); + for (let i = 0; i < bytes.length; i++) + drain.replay({ type: "data", data: bytes.subarray(i, i + 1) }); + drain.replay({ type: "end" }); + drain.enqueueText("live"); + await drain.flush(); + expect(resets).toBe(1); + expect( + terminal + .getBufferWindow({ startRow: 0, rowCount: 4 }) + .rows.map((row) => + row + .filter((cell) => cell.width !== 0) + .map((cell) => cell.char) + .join(""), + ) + .join("\n"), + ).toContain("界🙂 replay"); + expect( + terminal + .getBufferWindow({ startRow: 0, rowCount: 4 }) + .rows.map((row) => + row + .filter((cell) => cell.width !== 0) + .map((cell) => cell.char) + .join(""), + ) + .join("\n"), + ).toContain("live"); + } finally { + drain.dispose(); + terminal.dispose(); + } +}); + +test("an empty replacement replay resets after an in-flight write finishes", async () => { + let finish!: () => void; + let started!: () => void; + const writing = new Promise((resolve) => { + started = resolve; + }); + const blocked = new Promise((resolve) => { + finish = resolve; + }); + let resets = 0; + const drain = createNativeTerminalOutputDrain({ + restoreSize: () => {}, + write: async () => { + started(); + await blocked; + }, + reset: () => { + resets++; + }, + getViewportState: () => null, + onPaint: () => {}, + }); + try { + drain.enqueueText("old terminal"); + await writing; + drain.replay({ type: "begin" }); + drain.replay({ type: "end" }); + finish(); + await drain.flush(); + expect(resets).toBe(1); + expect(drain.getQueuedChars()).toBe(0); + } finally { + finish(); + drain.dispose(); + } +}); + +test("replay geometry returns to measured layout before live writes and unchanged-layout focus", async () => { + const measured = { rows: 24, cols: 40 }; + const terminal = createNativeHeadlessTerminal({ ...measured, scrollbackLines: 1000 }); + const policy = createTerminalResizePolicy(measured); + const sizes: number[] = []; + const drain = createNativeTerminalOutputDrain({ + write: async (text) => { + sizes.push(terminal.getViewportState().cols); + await terminal.write(text); + }, + reset: (size) => { + if (size) terminal.resize(size); + terminal.reset(); + }, + restoreSize: () => terminal.resize(measured), + getViewportState: () => terminal.getViewportState(), + onPaint: () => {}, + }); + try { + drain.replay({ type: "begin", rows: 30, cols: 120 }); + drain.replay({ type: "data", data: new TextEncoder().encode("x".repeat(100) + "\r\n") }); + drain.replay({ type: "end" }); + drain.enqueueText("LIVE-" + "y".repeat(60)); + await drain.flush(); + expect(sizes).toEqual([120, 40]); + const focus = updateTerminalResizePolicy(policy, { + source: "claim", + size: measured, + claimToken: 1, + }); + expect(focus.measuredSizeChanged).toBe(false); + expect(focus.resizeClaim).toMatchObject(measured); + expect(terminal.getViewportState()).toMatchObject(measured); + expect(terminal.getBufferBounds().cols).toBe(40); + const lines = terminal + .getViewportState() + .grid.map((row) => + row + .map((cell) => cell.char) + .join("") + .trimEnd(), + ) + .join("\n"); + expect(lines).toContain("LIVE-" + "y".repeat(35) + "\n" + "y".repeat(25)); + } finally { + drain.dispose(); + terminal.dispose(); + } +}); + +test.each(["clear", "replacement", "dispose"] as const)( + "cancels queued replay geometry on %s", + async (action) => { + const local = { rows: 24, cols: 40 }; + const terminal = createNativeHeadlessTerminal({ ...local, scrollbackLines: 1000 }); + let finish!: () => void; + const block = new Promise((resolve) => { + finish = resolve; + }); + let started!: () => void; + const writing = new Promise((resolve) => { + started = resolve; + }); + let first = true; + let restores = 0; + const drain = createNativeTerminalOutputDrain({ + restoreSize: () => { + restores++; + terminal.resize(local); + }, + reset: (size) => { + if (size) terminal.resize(size); + terminal.reset(); + }, + write: async (text) => { + await terminal.write(text); + if (first) { + first = false; + started(); + await block; + } + }, + getViewportState: () => terminal.getViewportState(), + onPaint: () => {}, + }); + try { + drain.replay({ type: "begin", rows: 30, cols: 120 }); + drain.replay({ type: "data", data: new TextEncoder().encode("old") }); + await writing; + local.cols = 60; + drain.resize(); + expect(terminal.getViewportState().cols).toBe(120); + drain.replay({ type: "end" }); + if (action === "clear") drain.clear(); + else if (action === "dispose") { + drain.dispose(); + drain.clear(); + } else { + drain.replay({ type: "begin", rows: 20, cols: 80 }); + drain.replay({ type: "data", data: new TextEncoder().encode("new") }); + drain.replay({ type: "end" }); + } + finish(); + await drain.flush(); + expect(restores).toBe(action === "dispose" ? 0 : 1); + if (action !== "dispose") expect(terminal.getViewportState()).toMatchObject(local); + } finally { + finish(); + drain.dispose(); + terminal.dispose(); + } + }, +); + +test("holds captured geometry across mid-replay measurement changes", async () => { + const source = new ReplaySource({ rows: 4, cols: 8, scrollback: 100, allowProposedApi: true }); + const serializer = new SerializeAddon(); + source.loadAddon(serializer); + await new Promise((resolve) => + source.write("ABCDEFGH\r\n12345678\r\nabcdefgh\r\nxyz\x1b[2;8H", resolve), + ); + const ansi = new TextEncoder().encode(serializer.serialize()); + const terminal = createNativeHeadlessTerminal({ rows: 4, cols: 8, scrollbackLines: 100 }); + const expected = createNativeHeadlessTerminal({ rows: 4, cols: 8, scrollbackLines: 100 }); + await expected.write(new TextDecoder().decode(ansi)); + expected.resize({ rows: 4, cols: 4 }); + let measured = { rows: 4, cols: 8 }; + const drain = createNativeTerminalOutputDrain({ + write: (chunk) => terminal.write(chunk), + reset: (size) => { + if (size) terminal.resize(size); + terminal.reset(); + }, + restoreSize: () => terminal.resize(measured), + getViewportState: () => terminal.getViewportState(), + onPaint: () => {}, + }); + try { + drain.replay({ type: "begin", rows: 4, cols: 8 }); + await drain.flush(); + measured = { rows: 4, cols: 4 }; + drain.resize(); + drain.replay({ type: "data", data: ansi }); + drain.replay({ type: "end" }); + await drain.flush(); + expect(terminal.getViewportState()).toEqual(expected.getViewportState()); + const actualBounds = terminal.getBufferBounds(); + const expectedBounds = expected.getBufferBounds(); + expect( + terminal.getBufferWindow({ + startRow: actualBounds.oldestRow, + rowCount: actualBounds.newestRow - actualBounds.oldestRow + 1, + }), + ).toEqual( + expected.getBufferWindow({ + startRow: expectedBounds.oldestRow, + rowCount: expectedBounds.newestRow - expectedBounds.oldestRow + 1, + }), + ); + } finally { + drain.dispose(); + } +}); diff --git a/packages/app/src/terminal/native-renderer/headless-terminal-output-drain.ts b/packages/app/src/terminal/native-renderer/headless-terminal-output-drain.ts index d853165371..00b9865be9 100644 --- a/packages/app/src/terminal/native-renderer/headless-terminal-output-drain.ts +++ b/packages/app/src/terminal/native-renderer/headless-terminal-output-drain.ts @@ -1,5 +1,3 @@ -import type { TerminalState } from "@getpaseo/protocol/messages"; -import { renderTerminalSnapshotToAnsi } from "../runtime/terminal-snapshot"; import type { TerminalViewportState } from "./headless-terminal-state"; import { nativeTerminalPerformanceNow } from "./terminal-performance"; @@ -14,9 +12,9 @@ export interface NativeTerminalParseSample { } export interface NativeTerminalOutputDrain { + replay(event: import("@getpaseo/client").TerminalReplayEvent): void; enqueueText(text: string): void; - restoreText(text: string): void; - restoreSnapshot(snapshot: TerminalState): void; + resize(): void; clear(): void; flush(): Promise; dispose(): void; @@ -25,7 +23,8 @@ export interface NativeTerminalOutputDrain { export interface NativeTerminalOutputDrainOptions { write: (chunk: string) => Promise; - reset: () => void; + restoreSize: () => void; + reset: (size?: { rows: number; cols: number }) => void; getViewportState: () => TerminalViewportState | null; onPaint: (state: TerminalViewportState) => void; onParse?: (sample: NativeTerminalParseSample) => void; @@ -68,16 +67,22 @@ export function createNativeTerminalOutputDrain( const chunkChars = options.chunkChars ?? NATIVE_TERMINAL_PARSE_CHUNK_CHARS; const chunksPerTurn = options.chunksPerTurn ?? NATIVE_TERMINAL_PARSE_CHUNKS_PER_TURN; const idleWaiters: Array<() => void> = []; - let pendingText = ""; + type Operation = + | { type: "write"; text: string } + | { type: "reset"; size?: { rows: number; cols: number } } + | { type: "restore-size" }; + let operations: Operation[] = []; + let queuedChars = 0; let drainScheduled = false; let draining = false; let disposed = false; + let replaying = false; let paintFrame: number | null = null; let generation = 0; - let resetBeforeNextWrite = false; + const replayDecoder = new TextDecoder(); function resolveIdleIfReady(): void { - if (drainScheduled || draining || pendingText.length > 0) { + if (drainScheduled || draining || operations.length > 0) { return; } while (idleWaiters.length > 0) { @@ -119,15 +124,6 @@ export function createNativeTerminalOutputDrain( }); } - function replacePendingText(text: string): void { - generation += 1; - pendingText = text; - resetBeforeNextWrite = true; - cancelPendingPaint(); - scheduleDrain(); - resolveIdleIfReady(); - } - async function drainPending(): Promise { if (disposed || draining) { return; @@ -138,16 +134,23 @@ export function createNativeTerminalOutputDrain( let parsedChunks = 0; try { - while (pendingText.length > 0 && parsedChunks < chunksPerTurn) { - if (disposed || activeGeneration !== generation) { - return; + while (operations.length > 0 && parsedChunks < chunksPerTurn) { + if (disposed || activeGeneration !== generation) return; + const operation = operations[0]!; + if (operation.type !== "write") { + operations.shift(); + if (operation.type === "reset") options.reset(operation.size); + else { + options.restoreSize(); + replaying = false; + } + requestPaint(); + continue; } - if (resetBeforeNextWrite) { - options.reset(); - resetBeforeNextWrite = false; - } - const chunk = pendingText.slice(0, chunkChars); - pendingText = pendingText.slice(chunk.length); + const chunk = operation.text.slice(0, chunkChars); + operation.text = operation.text.slice(chunk.length); + queuedChars -= chunk.length; + if (!operation.text) operations.shift(); const parseStart = nativeTerminalPerformanceNow(); await options.write(chunk); if (disposed || activeGeneration !== generation) { @@ -156,14 +159,14 @@ export function createNativeTerminalOutputDrain( options.onParse?.({ durationMs: nativeTerminalPerformanceNow() - parseStart, parsedChars: chunk.length, - queuedChars: pendingText.length, + queuedChars, }); requestPaint(); parsedChunks += 1; } } finally { draining = false; - if (!disposed && pendingText.length > 0) { + if (!disposed && operations.length > 0) { scheduleDrain(); } resolveIdleIfReady(); @@ -171,38 +174,56 @@ export function createNativeTerminalOutputDrain( } return { - enqueueText(text: string): void { - if (disposed || text.length === 0) { - return; + replay(event): void { + if (disposed) return; + if (event.type === "begin") { + replaying = true; + generation++; + replayDecoder.decode(); + operations = [ + { + type: "reset", + size: event.rows && event.cols ? { rows: event.rows, cols: event.cols } : undefined, + }, + ]; + queuedChars = 0; + cancelPendingPaint(); + } else if (event.type === "data") { + this.enqueueText(replayDecoder.decode(event.data, { stream: true })); + } else { + this.enqueueText(replayDecoder.decode()); + operations.push({ type: "restore-size" }); } - pendingText += text; + scheduleDrain(); + }, + enqueueText(text: string): void { + if (disposed || !text) return; + const last = operations.at(-1); + if (last?.type === "write") last.text += text; + else operations.push({ type: "write", text }); + queuedChars += text.length; scheduleDrain(); }, - restoreText(text: string): void { - if (disposed) { - return; - } - replacePendingText(text); - }, - - restoreSnapshot(snapshot: TerminalState): void { - if (disposed) { - return; - } - replacePendingText(renderTerminalSnapshotToAnsi(snapshot)); + resize(): void { + if (disposed || replaying) return; + operations.push({ type: "restore-size" }); + scheduleDrain(); }, clear(): void { + if (disposed) return; generation += 1; - pendingText = ""; - resetBeforeNextWrite = false; + operations = [{ type: "restore-size" }, { type: "reset" }]; + queuedChars = 0; + replayDecoder.decode(); cancelPendingPaint(); + scheduleDrain(); resolveIdleIfReady(); }, flush(): Promise { - if (!drainScheduled && !draining && pendingText.length === 0) { + if (!drainScheduled && !draining && operations.length === 0) { return Promise.resolve(); } scheduleDrain(); @@ -214,8 +235,8 @@ export function createNativeTerminalOutputDrain( dispose(): void { disposed = true; generation += 1; - pendingText = ""; - resetBeforeNextWrite = false; + operations = []; + queuedChars = 0; cancelPendingPaint(); while (idleWaiters.length > 0) { idleWaiters.shift()?.(); @@ -223,7 +244,7 @@ export function createNativeTerminalOutputDrain( }, getQueuedChars(): number { - return pendingText.length; + return queuedChars; }, }; } diff --git a/packages/app/src/terminal/native-renderer/headless-terminal-state.ts b/packages/app/src/terminal/native-renderer/headless-terminal-state.ts index c25399c9b2..5fd87f7315 100644 --- a/packages/app/src/terminal/native-renderer/headless-terminal-state.ts +++ b/packages/app/src/terminal/native-renderer/headless-terminal-state.ts @@ -21,7 +21,6 @@ export interface NativeHeadlessTerminalOptions { export interface NativeHeadlessTerminal { write(data: NativeTerminalWriteData): Promise; - getState(): TerminalState; getViewportState(input?: TerminalViewportStateInput): TerminalViewportState; getInputModeState(): NativeHeadlessTerminalInputModeState; getBufferBounds(): TerminalBufferBounds; @@ -165,35 +164,6 @@ function extractRow( return rowCells; } -function extractGrid(terminal: HeadlessTerminalInstance): TerminalCellRow[] { - const grid: TerminalCellRow[] = []; - const baseY = terminal.buffer.active.baseY; - const reusableCell = terminal.buffer.active.getNullCell(); - for (let row = 0; row < terminal.rows; row += 1) { - grid.push(extractRow(terminal, baseY + row, reusableCell)); - } - return grid; -} - -function extractScrollback( - terminal: HeadlessTerminalInstance, - options: { scrollbackLines?: number }, -): TerminalCellRow[] { - const scrollback: TerminalCellRow[] = []; - const scrollbackLines = terminal.buffer.active.baseY; - const startRow = - typeof options.scrollbackLines === "number" - ? Math.max(0, scrollbackLines - options.scrollbackLines) - : 0; - const reusableCell = terminal.buffer.active.getNullCell(); - - for (let row = startRow; row < scrollbackLines; row += 1) { - scrollback.push(extractRow(terminal, row, reusableCell)); - } - - return scrollback; -} - function extractBufferWindow( terminal: HeadlessTerminalInstance, oldestRow: number, @@ -290,19 +260,6 @@ function extractInputModeState( }; } -function extractState( - terminal: HeadlessTerminalInstance, - options: { scrollbackLines?: number }, -): TerminalState { - return { - rows: terminal.rows, - cols: terminal.cols, - grid: extractGrid(terminal), - scrollback: extractScrollback(terminal, options), - cursor: extractCursorState(terminal), - }; -} - function extractViewportState( terminal: HeadlessTerminalInstance, coordinateEpoch: number, @@ -380,9 +337,6 @@ export function createNativeHeadlessTerminal( }); }); }, - getState(): TerminalState { - return extractState(terminal, { scrollbackLines: options.scrollbackLines }); - }, getViewportState(input?: TerminalViewportStateInput): TerminalViewportState { return extractViewportState( terminal, diff --git a/packages/app/src/terminal/native-renderer/terminal-frame.test.ts b/packages/app/src/terminal/native-renderer/terminal-frame.test.ts index 129a7d9082..ea8b7a0cf3 100644 --- a/packages/app/src/terminal/native-renderer/terminal-frame.test.ts +++ b/packages/app/src/terminal/native-renderer/terminal-frame.test.ts @@ -10,6 +10,8 @@ import { } from "./colors"; import { createNativeHeadlessTerminal } from "./headless-terminal-state"; import { buildTerminalFrame } from "./terminal-frame"; +import { createNativeTerminalOutputDrain } from "./headless-terminal-output-drain"; +import { resolveMeasuredNativeTerminalSize } from "./terminal-size-measurement"; const resolver = createTerminalCellStyleResolver(DEFAULT_TERMINAL_THEME); const RED = parseTerminalColor(DEFAULT_TERMINAL_THEME.red, 0); @@ -197,3 +199,48 @@ describe("native terminal frame", () => { expect(actual).toEqual(graphemeRows); }); }); + +test("builds native frames after replay commits at captured geometry and the latest measurement precedes live text", async () => { + let measured = resolveMeasuredNativeTerminalSize({ + layout: { width: 400, height: 240 }, + metrics: { cellWidth: 10, cellHeight: 10 }, + })!; + const terminal = createNativeHeadlessTerminal({ ...measured, scrollbackLines: 10000 }); + const parsedColumns: number[] = []; + const drain = createNativeTerminalOutputDrain({ + write: async (text) => { + parsedColumns.push(terminal.getViewportState().cols); + await terminal.write(text); + }, + reset: (size) => { + if (size) terminal.resize(size); + terminal.reset(); + }, + restoreSize: () => terminal.resize(measured), + getViewportState: () => terminal.getViewportState(), + onPaint: () => {}, + }); + try { + drain.replay({ type: "begin", rows: 30, cols: 120 }); + drain.replay({ type: "data", data: new TextEncoder().encode("x".repeat(100) + "\r\n") }); + measured = resolveMeasuredNativeTerminalSize({ + layout: { width: 500, height: 100 }, + metrics: { cellWidth: 10, cellHeight: 10 }, + })!; + drain.resize(); + drain.replay({ type: "end" }); + drain.enqueueText("\x1b[H\x1b[2K\x1b[31mLIVE-界🙂\x1b[0m"); + await drain.flush(); + expect(parsedColumns).toEqual([120, 50]); + const state = terminal.getViewportState(); + const frame = buildTerminalFrame({ state, columns: state.cols, resolver, selection: null }); + expect(frame.columns).toBe(50); + expect(frame.rows).toHaveLength(10); + expect(frame.rows[0].text.trimEnd()).toBe("LIVE-界🙂"); + expect(frame.rows[0].styles.slice(0, 4)).toEqual([8, RED, 0, 0]); + expect(encodeTerminalFrame(frame).rows[0]).toContain("LIVE-界🙂"); + } finally { + drain.dispose(); + terminal.dispose(); + } +}); diff --git a/packages/app/src/terminal/native-renderer/terminal-scrollback.test.ts b/packages/app/src/terminal/native-renderer/terminal-scrollback.test.ts index 3464bcd973..6bacdc0472 100644 --- a/packages/app/src/terminal/native-renderer/terminal-scrollback.test.ts +++ b/packages/app/src/terminal/native-renderer/terminal-scrollback.test.ts @@ -54,16 +54,19 @@ describe("native terminal scrollback retention", () => { scrollbackLines: SCROLLBACK, lineCount: SCROLLBACK + ROWS + 10, }); - const state = terminal.getState(); const bounds = terminal.getBufferBounds(); - expect(state.scrollback.length).toBeGreaterThan(0); - expect(state.scrollback.length).toBeLessThanOrEqual(SCROLLBACK); + const historyRows = bounds.bottomViewport.firstRow - bounds.oldestRow; + expect(historyRows).toBeGreaterThan(0); + expect(historyRows).toBeLessThanOrEqual(SCROLLBACK); expect(bounds.newestRow).toBeGreaterThan(ROWS); expect(bounds.oldestRow).toBeGreaterThan(0); - expect(bounds.newestRow - bounds.oldestRow + 1).toBe( - state.scrollback.length + state.grid.length, - ); + const retained = terminal.getBufferWindow({ + startRow: bounds.oldestRow, + rowCount: SCROLLBACK + ROWS + 1, + }); + expect(retained.rows).toHaveLength(SCROLLBACK + ROWS); + expect(rowText(retained.rows[0]!)).toBe(expectedBenchmarkLine(bounds.oldestRow)); }); test("observable scrollback count is bounded by configured lines", async () => { @@ -73,9 +76,9 @@ describe("native terminal scrollback retention", () => { scrollbackLines: SCROLLBACK, lineCount: SCROLLBACK * 3, }); - const state = terminal.getState(); - expect(state.scrollback.length).toBe(SCROLLBACK); + const bounds = terminal.getBufferBounds(); + expect(bounds.bottomViewport.firstRow - bounds.oldestRow).toBe(SCROLLBACK); }); test("scroll up moves viewport into retained history", async () => { diff --git a/packages/app/src/terminal/runtime/terminal-emulator-runtime.browser.test.ts b/packages/app/src/terminal/runtime/terminal-emulator-runtime.browser.test.ts index 5dcefb8ebf..7f54361265 100644 --- a/packages/app/src/terminal/runtime/terminal-emulator-runtime.browser.test.ts +++ b/packages/app/src/terminal/runtime/terminal-emulator-runtime.browser.test.ts @@ -166,7 +166,6 @@ function createTerminalHost(input: CreateTerminalHostInput): MountedTerminal { runtime.mount({ root, host, - initialSnapshot: null, scrollback: input.scrollback ?? 10_000, theme: { background: "#0b0b0b", @@ -750,30 +749,11 @@ describe("terminal emulator runtime in a real browser", () => { const reset = vi.fn(originalReset); terminal.reset = reset; - mounted.runtime.renderSnapshot({ - state: { - rows: terminal.rows, - cols: terminal.cols, - scrollback: [], - grid: [ - [ - { char: "p" }, - { char: "r" }, - { char: "o" }, - { char: "m" }, - { char: "p" }, - { char: "t" }, - ], - ], - cursor: { - row: 0, - col: 6, - }, - }, - }); - await nextFrame(); - + mounted.runtime.replay({ type: "begin", rows: terminal.rows, cols: terminal.cols }); + mounted.runtime.replay({ type: "data", data: terminalOutput("prompt") }); + mounted.runtime.replay({ type: "end" }); expect(reset).not.toHaveBeenCalled(); + await nextFrame(); }); it("opens OSC 8 hyperlinks the same way as plain-text URLs", async () => { @@ -795,3 +775,95 @@ describe("terminal emulator runtime in a real browser", () => { expect(confirm).not.toHaveBeenCalled(); }); }); + +describe("incremental replay lifecycle", () => { + it.each(["clear", "remount"] as const)( + "recovers live input after interrupted replay and %s", + async (cleanup) => { + const mounted = createTerminalHost({ width: 720, height: 360 }); + mounted.runtime.replay({ type: "begin", rows: 30, cols: 120 }); + mounted.root.style.width = "360px"; + mounted.runtime.resize({ shouldClaim: false }); + mounted.runtime.replay({ type: "data", data: terminalOutput("interrupted") }); + if (cleanup === "clear") + await new Promise((resolve) => mounted.runtime.clear({ onCommitted: resolve })); + else { + mounted.runtime.unmount(); + mounted.runtime.mount({ + root: mounted.root, + host: mounted.host, + scrollback: 1000, + theme: {}, + }); + } + await new Promise((resolve) => + mounted.runtime.write({ data: terminalOutput("live"), onCommitted: resolve }), + ); + getBrowserTerminal().input("user-input", true); + expect(mounted.inputs).toContain("user-input"); + expect(getBrowserTerminal().cols).toBeLessThan(60); + }, + ); + + it("suppresses generated replies until queued replay chunks commit after end", async () => { + const mounted = createTerminalHost({ width: 720, height: 360 }); + mounted.runtime.replay({ type: "begin" }); + mounted.runtime.replay({ type: "data", data: terminalOutput("\x1b]4;1;?\x07") }); + mounted.runtime.replay({ type: "data", data: terminalOutput("\x1b]4;1;?\x07") }); + mounted.runtime.replay({ type: "end" }); + await new Promise((resolve) => + mounted.runtime.write({ data: terminalOutput("committed"), onCommitted: resolve }), + ); + expect(mounted.inputs).toEqual([]); + await new Promise((resolve) => + mounted.runtime.write({ data: terminalOutput("\x1b]4;1;?\x07"), onCommitted: resolve }), + ); + expect(mounted.inputs).toHaveLength(1); + expect(mounted.inputs[0]?.startsWith("\x1b]4;1;rgb:")).toBe(true); + }); +}); + +it("restores fitted web geometry after replay before live output", async () => { + const mounted = createTerminalHost({ width: 720, height: 360 }); + await settleMountRefits(); + const local = latestSize(mounted.sizes); + mounted.runtime.replay({ type: "begin", rows: 30, cols: 120 }); + mounted.runtime.replay({ type: "data", data: terminalOutput("x".repeat(100)) }); + mounted.runtime.replay({ type: "end" }); + await new Promise((resolve) => + mounted.runtime.write({ data: terminalOutput("LIVE"), onCommitted: resolve }), + ); + expect(getBrowserTerminal().cols).toBe(latestSize(mounted.sizes).cols); + expect(getBrowserTerminal().cols).toBeLessThan(120); + expect(getBrowserTerminal().rows).toBe(local.rows); + mounted.runtime.resize({ forceClaim: true, shouldClaim: true }); + expect(getBrowserTerminal().cols).toBe(latestSize(mounted.sizes).cols); +}); + +it("defers layout fit until all replay chunks commit", async () => { + const mounted = createTerminalHost({ width: 720, height: 360 }); + await settleMountRefits(); + mounted.runtime.replay({ type: "begin", rows: 30, cols: 120 }); + await new Promise((resolve) => + mounted.runtime.write({ + data: terminalOutput("first"), + suppressInput: true, + onCommitted: resolve, + }), + ); + expect(getBrowserTerminal().cols).toBe(120); + mounted.root.style.width = "360px"; + mounted.runtime.resize({ shouldClaim: true, forceClaim: true, forceRefresh: true }); + await nextFrame(); + expect(getBrowserTerminal().cols).toBe(120); + mounted.runtime.replay({ type: "data", data: terminalOutput("\x1b[2;110Hsecond") }); + mounted.runtime.replay({ type: "end" }); + await new Promise((resolve) => + mounted.runtime.write({ data: terminalOutput("LIVE"), onCommitted: resolve }), + ); + expect(getBrowserTerminal().cols).toBe(latestSize(mounted.sizes).cols); + expect(getBrowserTerminal().cols).toBeLessThan(60); + expect(latestSize(mounted.sizes)).toMatchObject({ shouldClaim: true, forceClaim: true }); + mounted.runtime.resize({ shouldClaim: true, forceClaim: true }); + expect(getBrowserTerminal().cols).toBe(latestSize(mounted.sizes).cols); +}); diff --git a/packages/app/src/terminal/runtime/terminal-emulator-runtime.test.ts b/packages/app/src/terminal/runtime/terminal-emulator-runtime.test.ts index a11cedbfe2..a6939aaecb 100644 --- a/packages/app/src/terminal/runtime/terminal-emulator-runtime.test.ts +++ b/packages/app/src/terminal/runtime/terminal-emulator-runtime.test.ts @@ -302,25 +302,14 @@ describe("terminal-emulator-runtime", () => { expect(committed).toEqual(["first", "second", "clear", "third"]); }); - it("falls back to timeout commit for a barrier op when the gate sentinel never fires", () => { + it("unblocks queued replay writes if a begin barrier never commits", () => { vi.useFakeTimers(); - const { runtime, terminal } = createRuntimeWithTerminal(); - const onCommitted = vi.fn(); - - // restoreOutput is a barrier; if xterm never commits the gate sentinel, the barrier still - // applies (and commits) after the 5s safety timeout instead of stalling forever. - runtime.restoreOutput({ - data: terminalOutput("stuck"), - onCommitted, - }); - - expect(onCommitted).not.toHaveBeenCalled(); - expect(terminal.resetCalls).toBe(0); - vi.advanceTimersByTime(5_000); - // The barrier now runs (write submitted) but its own commit still waits on xterm; advance - // again to fire the barrier's own write timeout. - vi.advanceTimersByTime(5_000); - expect(onCommitted).toHaveBeenCalledTimes(1); + const { runtime, writeTexts } = createRuntimeWithTerminal(); + runtime.replay({ type: "begin" }); + runtime.replay({ type: "data", data: terminalOutput("stuck") }); + expect(writeTexts).toEqual(["\x1bc"]); + vi.advanceTimersByTime(5000); + expect(writeTexts).toEqual(["\x1bc", "stuck"]); }); it("reports input mode changes from terminal output and resets them on snapshots", () => { @@ -343,18 +332,7 @@ describe("terminal-emulator-runtime", () => { }); runtime.write({ data: terminalOutput("\x1b[>7u") }); - runtime.renderSnapshot({ - state: { - rows: 2, - cols: 8, - scrollback: [], - grid: [[{ char: "$" }, { char: " " }]], - cursor: { - row: 0, - col: 2, - }, - }, - }); + runtime.replay({ type: "begin", rows: 2, cols: 8 }); // The plain write reports kitty flags synchronously during drain; the snapshot resets // them only after its barrier gate (the sentinel write callback) resolves. expect(inputModeChanges).toEqual([ @@ -410,40 +388,18 @@ describe("terminal-emulator-runtime", () => { expect(committed).toEqual(["second", "first"]); }); - it("applies a snapshot after the writes ahead of it, never interleaving the reset", () => { + it("keeps replay reset and data after preceding writes, without interleaving", () => { const { runtime, terminal, writeTexts, writeCallbacks } = createRuntimeWithTerminal(); - const committed: string[] = []; - - runtime.write({ - data: terminalOutput("before-a"), - onCommitted: () => { - committed.push("before-a"); - }, - }); - runtime.write({ - data: terminalOutput("before-b"), - onCommitted: () => { - committed.push("before-b"); - }, - }); - runtime.restoreOutput({ - data: terminalOutput("snap"), - onCommitted: () => { - committed.push("snap"); - }, - }); - - // Plain writes are submitted up front; the snapshot's reset+write has not run yet. + runtime.write({ data: terminalOutput("before-a") }); + runtime.write({ data: terminalOutput("before-b") }); + runtime.replay({ type: "begin" }); + runtime.replay({ type: "data", data: terminalOutput("snap") }); + runtime.replay({ type: "end" }); expect(writeTexts).toEqual(["before-a", "before-b"]); - - // writeCallbacks: [0]=before-a, [1]=before-b, [2]=barrier gate sentinel. - // The snapshot is gated behind the prior writes; resolving the gate runs it after them. writeCallbacks[2]?.(); - expect(writeTexts).toEqual(["before-a", "before-b", "csnap"]); - - // Snapshot commit fires only after its own write callback, strictly after the writes. + expect(writeTexts).toEqual(["before-a", "before-b", "\x1bc"]); writeCallbacks[3]?.(); - expect(committed).toEqual(["snap"]); + expect(writeTexts).toEqual(["before-a", "before-b", "\x1bc", "snap"]); expect(terminal.resetCalls).toBe(0); }); @@ -456,7 +412,7 @@ describe("terminal-emulator-runtime", () => { // No plain writes precede this barrier (mount), so there is nothing to gate: it starts // at once with no sentinel, flipping suppressInput synchronously. - runtime.restoreOutput({ data: terminalOutput("snapshot") }); + runtime.replay({ type: "begin" }); expect(readSuppressInput()).toBe(true); // writeCallbacks[0] is the barrier's own snapshot write; committing it restores input. @@ -471,7 +427,7 @@ describe("terminal-emulator-runtime", () => { // A plain write is now ungated, so the following barrier must wait on the sentinel. runtime.write({ data: terminalOutput("output") }); - runtime.restoreOutput({ data: terminalOutput("snapshot") }); + runtime.replay({ type: "begin" }); // The plain write commits first. Only the following sentinel opens the barrier. expect(readSuppressInput()).toBe(false); @@ -505,57 +461,40 @@ describe("terminal-emulator-runtime", () => { expect(onCommittedB).toHaveBeenCalledTimes(1); }); - it("clears ungated writes on unmount so remount barriers apply immediately", () => { + it("clears ungated writes on unmount so remount replay begins immediately", () => { const { runtime } = createRuntimeWithTerminal(); - runtime.write({ data: terminalOutput("before unmount") }); runtime.unmount(); - const remounted = attachStubTerminal(runtime); - runtime.restoreOutput({ data: terminalOutput("restored screen") }); - - expect(remounted.writeTexts).toEqual(["\u001bcrestored screen"]); - expect(remounted.writeCallbacks).toHaveLength(1); + runtime.replay({ type: "begin" }); + runtime.replay({ type: "data", data: terminalOutput("restored screen") }); + expect(remounted.writeTexts).toEqual(["\x1bc"]); + remounted.writeCallbacks[0]?.(); + expect(remounted.writeTexts).toEqual(["\x1bc", "restored screen"]); }); - it("replays snapshots through a single write without first painting a reset terminal", () => { + it("parses replay chunks serially without synchronously resetting the terminal", () => { const { runtime, terminal, writeTexts, writeCallbacks } = createRuntimeWithTerminal(); - - runtime.renderSnapshot({ - state: { - rows: 2, - cols: 8, - scrollback: [], - grid: [ - [{ char: "h" }, { char: "i" }], - [{ char: "$" }, { char: " " }], - ], - cursor: { - row: 1, - col: 2, - }, - }, - }); - - // The snapshot is a barrier; its write applies after the gate sentinel (writeCallbacks[0]). - writeCallbacks[0]?.(); - + runtime.replay({ type: "begin", rows: 2, cols: 8 }); + runtime.replay({ type: "data", data: terminalOutput("hi") }); + runtime.replay({ type: "data", data: terminalOutput("\r\n$") }); + runtime.replay({ type: "end" }); expect(terminal.resetCalls).toBe(0); - expect(writeTexts).toHaveLength(1); - expect(writeTexts[0]?.startsWith("\u001bc")).toBe(true); - expect(writeTexts[0]).toContain("hi"); + expect(writeTexts).toEqual(["\x1bc"]); + writeCallbacks[0]?.(); + expect(writeTexts).toEqual(["\x1bc", "hi"]); + writeCallbacks[1]?.(); + expect(writeTexts).toEqual(["\x1bc", "hi", "\r\n$"]); }); - it("restores server-rendered ANSI snapshots through the snapshot write path", () => { + it("restores worker-rendered ANSI through the replay lifecycle", () => { const { runtime, terminal, writeTexts, writeCallbacks } = createRuntimeWithTerminal(); - - runtime.restoreOutput({ data: terminalOutput("restored screen") }); - - // restoreOutput is a barrier (suppressInput); it applies after the gate sentinel. + runtime.replay({ type: "begin" }); + runtime.replay({ type: "data", data: terminalOutput("restored screen") }); + runtime.replay({ type: "end" }); writeCallbacks[0]?.(); - expect(terminal.resetCalls).toBe(0); - expect(writeTexts).toEqual(["\u001bcrestored screen"]); + expect(writeTexts).toEqual(["\x1bc", "restored screen"]); }); it("forces a refit when resize is requested", () => { diff --git a/packages/app/src/terminal/runtime/terminal-emulator-runtime.ts b/packages/app/src/terminal/runtime/terminal-emulator-runtime.ts index 0a55cd7126..a7460f7f80 100644 --- a/packages/app/src/terminal/runtime/terminal-emulator-runtime.ts +++ b/packages/app/src/terminal/runtime/terminal-emulator-runtime.ts @@ -7,7 +7,6 @@ import { WebLinksAddon } from "@xterm/addon-web-links"; import { WebglAddon } from "@xterm/addon-webgl"; import { LigaturesAddon } from "@xterm/addon-ligatures/lib/addon-ligatures.mjs"; import { Terminal, type ITheme, type IMarker } from "@xterm/xterm"; -import type { TerminalState } from "@getpaseo/protocol/messages"; import { type TerminalInputModeState, TerminalInputModeTracker, @@ -24,7 +23,6 @@ import { resolveMacTerminalEditingShortcut, shouldInterceptDomTerminalKey, } from "@/utils/terminal-keys"; -import { renderTerminalSnapshotToAnsi } from "./terminal-snapshot"; import { createTerminalLocalFileLinkProvider, type TerminalLocalFileLinkSource, @@ -55,7 +53,6 @@ const FIND_HIGHLIGHT_LIMIT = 20_000; export interface TerminalEmulatorRuntimeMountInput { root: HTMLDivElement; host: HTMLDivElement; - initialSnapshot: TerminalState | null; scrollback: number; theme: ITheme; fontFamily?: string; @@ -134,7 +131,7 @@ interface TerminalEmulatorRuntimeDisposables { } interface TerminalOutputOperation { - type: "write" | "clear" | "snapshot"; + type: "write" | "clear" | "snapshot" | "fit"; data: TerminalOutputData; rows?: number; cols?: number; @@ -280,6 +277,7 @@ export class TerminalEmulatorRuntime { }, }; + private replayResize: TerminalResizeRequest | null = null; private fitAndEmitResize: ((input?: TerminalResizeRequest) => void) | null = null; private lastSize: { rows: number; cols: number } | null = null; private cleanup: (() => void) | null = null; @@ -652,6 +650,7 @@ export class TerminalEmulatorRuntime { window.__paseoTerminal = terminal; const fitAndEmitResize = (resizeInput?: TerminalResizeRequest): void => { + if (this.deferReplayResize(resizeInput)) return; const forceRefresh = resizeInput?.forceRefresh ?? false; const shouldClaim = resizeInput?.shouldClaim ?? true; const forceClaim = resizeInput?.forceClaim ?? false; @@ -777,10 +776,6 @@ export class TerminalEmulatorRuntime { fitAndEmitResize({ forceRefresh: true, shouldClaim: false }); }, 0); - if (input.initialSnapshot) { - this.renderSnapshot({ state: input.initialSnapshot }); - } - this.processOutputQueue(); const disposables: TerminalEmulatorRuntimeDisposables = { @@ -898,20 +893,19 @@ export class TerminalEmulatorRuntime { onFilePaste?.(file); } - renderSnapshot(input: { state: TerminalState | null; onCommitted?: () => void }): void { - if (!input.state) { - this.clear(input); - return; + replay(event: import("@getpaseo/client").TerminalReplayEvent): void { + if (event.type === "begin") { + this.replayResize ??= { shouldClaim: false }; + this.restoreOutput({ data: EMPTY_TERMINAL_OUTPUT, rows: event.rows, cols: event.cols }); + } else if (event.type === "data") { + this.write({ data: event.data, suppressInput: true }); + } else { + this.outputOperations.push({ type: "fit", data: EMPTY_TERMINAL_OUTPUT }); + this.processOutputQueue(); } - this.restoreOutput({ - data: encodeTerminalOutput(renderTerminalSnapshotToAnsi(input.state)), - rows: input.state.rows, - cols: input.state.cols, - ...(input.onCommitted ? { onCommitted: input.onCommitted } : {}), - }); } - restoreOutput(input: { + private restoreOutput(input: { data: TerminalOutputData; rows?: number; cols?: number; @@ -928,6 +922,16 @@ export class TerminalEmulatorRuntime { this.processOutputQueue(); } + private deferReplayResize(input?: TerminalResizeRequest): boolean { + if (!this.replayResize) return false; + this.replayResize = { + forceRefresh: this.replayResize.forceRefresh || input?.forceRefresh, + shouldClaim: this.replayResize.shouldClaim || (input?.shouldClaim ?? true), + forceClaim: this.replayResize.forceClaim || input?.forceClaim, + }; + return true; + } + resize(input?: TerminalResizeRequest): void { this.fitAndEmitResize?.(input); } @@ -1047,6 +1051,7 @@ export class TerminalEmulatorRuntime { commit(); } this.hasUngatedWrites = false; + this.replayResize = null; this.cleanup?.(); this.cleanup = null; @@ -1176,16 +1181,40 @@ export class TerminalEmulatorRuntime { this.processOutputQueue(); }; + if (operation.type === "fit") { + // xterm resize flushes its write buffer synchronously. Leave the parser's + // commit callback before fitting, or that flush consumes the next write. + queueMicrotask(() => { + if (this.inFlightOutputOperation !== operation || this.terminal !== terminal) return; + const resize = this.replayResize ?? { shouldClaim: false }; + this.replayResize = null; + this.fitAndEmitResize?.(resize); + finalizeOperation(operation); + }); + return; + } + if (operation.type === "clear") { this.inputModeDecoder.decode(); this.inputModeTracker.reset(); this.emitInputModeChange(); terminal.reset(); - finalizeOperation(operation); + if (!this.replayResize) { + finalizeOperation(operation); + return; + } + queueMicrotask(() => { + if (this.inFlightOutputOperation !== operation || this.terminal !== terminal) return; + const resize = this.replayResize ?? { shouldClaim: false }; + this.replayResize = null; + this.fitAndEmitResize?.(resize); + finalizeOperation(operation); + }); return; } if (operation.type === "snapshot") { + this.replayResize ??= { shouldClaim: false }; this.inputModeDecoder.decode(); this.inputModeTracker.reset(); this.emitInputModeChange(); diff --git a/packages/app/src/terminal/runtime/terminal-find.browser.test.ts b/packages/app/src/terminal/runtime/terminal-find.browser.test.ts index 8336925338..84b941a340 100644 --- a/packages/app/src/terminal/runtime/terminal-find.browser.test.ts +++ b/packages/app/src/terminal/runtime/terminal-find.browser.test.ts @@ -31,7 +31,6 @@ function mount(options?: { isMac: boolean }) { runtime.mount({ root, host, - initialSnapshot: null, scrollback: 1000, theme: { background: "#ffffff", foreground: "#111111" }, }); diff --git a/packages/app/src/terminal/runtime/terminal-glyph-rendering.browser.test.ts b/packages/app/src/terminal/runtime/terminal-glyph-rendering.browser.test.ts index 35629f01f8..62a65c6878 100644 --- a/packages/app/src/terminal/runtime/terminal-glyph-rendering.browser.test.ts +++ b/packages/app/src/terminal/runtime/terminal-glyph-rendering.browser.test.ts @@ -38,7 +38,6 @@ function mountTerminal(left: number): TerminalView { runtime.mount({ root, host, - initialSnapshot: null, scrollback: 1000, fontFamily: "monospace", fontSize: 16, diff --git a/packages/app/src/terminal/runtime/terminal-resize-repro.browser.test.ts b/packages/app/src/terminal/runtime/terminal-resize-repro.browser.test.ts index 35b3492b71..d72a935f49 100644 --- a/packages/app/src/terminal/runtime/terminal-resize-repro.browser.test.ts +++ b/packages/app/src/terminal/runtime/terminal-resize-repro.browser.test.ts @@ -1,15 +1,14 @@ +import { Terminal as ReplaySource } from "@xterm/xterm"; +import { SerializeAddon } from "@xterm/addon-serialize"; import { page } from "@vitest/browser/context"; import { afterEach, describe, expect, it } from "vitest"; -import type { TerminalState } from "@getpaseo/protocol/messages"; import { encodeTerminalOutput, TerminalEmulatorRuntime } from "./terminal-emulator-runtime"; // Regression: "streaming pino log, resized the Paseo terminal, old logs stayed // narrow and new logs drew on top of the old ones." // -// A heavy stream overflows MAX_TERMINAL_OUTPUT_FRAME_BYTES, so the server sends a -// SNAPSHOT mid-stream. The client restores it via renderTerminalSnapshotToAnsi. -// When the snapshot carries per-row soft-wrap flags, restored long lines must -// reflow on resize just like live output — not freeze at the snapshot width. +// Backpressure triggers an ANSI replay serialized directly from xterm. Replayed +// soft-wrapped lines must reflow on resize like live output. interface Mounted { host: HTMLDivElement; @@ -57,7 +56,6 @@ function mount(width: number, height: number): Mounted { runtime.mount({ root, host, - initialSnapshot: null, scrollback: 10_000, theme: { background: "#0b0b0b", foreground: "#e6e6e6", cursor: "#e6e6e6" }, }); @@ -90,9 +88,18 @@ function someRowContains(term: InspectableTerminal, text: string): boolean { return dumpRows(term).some((r) => r.text.includes(text)); } -function renderSnapshotCommitted(runtime: TerminalEmulatorRuntime, state: TerminalState) { +function replayCommitted( + runtime: TerminalEmulatorRuntime, + state: { rows: number; cols: number; data: Uint8Array }, +) { return new Promise((resolve) => { - runtime.renderSnapshot({ state, onCommitted: resolve }); + runtime.replay({ type: "begin", rows: state.rows, cols: state.cols }); + runtime.replay({ + type: "data", + data: state.data, + }); + runtime.replay({ type: "end" }); + runtime.write({ data: new Uint8Array([0]), onCommitted: resolve }); }); } @@ -102,31 +109,18 @@ function writeCommitted(runtime: TerminalEmulatorRuntime, data: Uint8Array) { }); } -// Build a server-style snapshot of one long pino line that the SERVER soft-wrapped -// at `cols`, represented as multiple grid rows (exactly what the daemon stores in -// its headless xterm and ships in a snapshot). -function buildWrappedSnapshot(cols: number): TerminalState { - const longLine = `[server] [15:30:00.123] TRACE: provider.claude.raw_event {"module":"agent","seq":1,"sessionId":"ed8972f4-d3be-45d0-992c-631f8f1ed04e","turnId":"foreground-turn-1","payload":"${"A".repeat(40)}"}`; - const grid: TerminalState["grid"] = []; - for (let i = 0; i < longLine.length; i += cols) { - const chunk = longLine.slice(i, i + cols); - grid.push([...chunk].map((char) => ({ char }))); +// Serialize one long pino line from a real server-width xterm buffer. +// The replay must retain its soft-wrap boundaries for later client reflow. +async function buildWrappedSnapshot(cols: number) { + const source = new ReplaySource({ rows: 24, cols, allowProposedApi: true }); + const serializer = new SerializeAddon(); + source.loadAddon(serializer); + try { + await new Promise((resolve) => source.write(pinoLine(0), resolve)); + return { rows: 24, cols, data: new TextEncoder().encode(serializer.serialize()) }; + } finally { + source.dispose(); } - // The fixed daemon ships per-row soft-wrap flags: every row of the logical line - // continues onto the next except the last. - const gridWrapped = grid.map((_, index) => index < grid.length - 1); - // Cursor sits just below the restored content, exactly where the daemon's - // headless terminal leaves it after a line break, so streamed output appends - // cleanly below instead of overwriting the restored rows. - return { - rows: 24, - cols, - scrollback: [], - scrollbackWrapped: [], - grid, - gridWrapped, - cursor: { row: grid.length, col: 0 }, - }; } function pinoLine(seq: number): string { @@ -141,15 +135,14 @@ afterEach(() => { }); describe("terminal resize reflow repro (Paseo terminal)", () => { - it("snapshot-restored rows stay frozen at the snapshot width after the terminal grows", async () => { + it("replayed soft-wrapped rows reflow after the terminal grows", async () => { await page.viewport(1600, 700); const m = mount(560, 360); // ~70 cols await waitFor(() => m.terminal.cols > 40); const narrowCols = m.terminal.cols; - // 1) Mid-stream snapshot arrives (server overflowed 256KB). It carries the - // long line wrapped at the server width as separate grid rows. - await renderSnapshotCommitted(m.runtime, buildWrappedSnapshot(narrowCols)); + // 1) A mid-stream ANSI replay arrives, preserving wraps at the captured width. + await replayCommitted(m.runtime, await buildWrappedSnapshot(narrowCols)); await waitFor(() => someRowContains(m.terminal, "[15:30:00.123]")); // 2) Normal post-snapshot streaming resumes (autowrap on -> soft-wrapped). diff --git a/packages/app/src/terminal/runtime/terminal-restore-options.test.ts b/packages/app/src/terminal/runtime/terminal-restore-options.test.ts index 14f2ce4d8f..7e5294b347 100644 --- a/packages/app/src/terminal/runtime/terminal-restore-options.test.ts +++ b/packages/app/src/terminal/runtime/terminal-restore-options.test.ts @@ -4,25 +4,27 @@ import { resolveTerminalRestoreOptions } from "./terminal-restore-options"; describe("terminal restore options", () => { it("omits restore options for daemons without terminal restore modes", () => { - expect( + expect(() => resolveTerminalRestoreOptions({ + scrollbackLines: 10000, supportsTerminalRestoreModes: false, canClaimSize: true, size: { rows: 24, cols: 80 }, }), - ).toBeUndefined(); + ).toThrow("Update the host to view terminals."); }); - it("requests visible snapshot restore with bounded scrollback for capable daemons", () => { + it("requests visible snapshot restore with configured scrollback for capable daemons", () => { expect( resolveTerminalRestoreOptions({ + scrollbackLines: 10000, supportsTerminalRestoreModes: true, canClaimSize: true, size: { rows: 24, cols: 80 }, }), ).toEqual({ mode: "visible-snapshot", - scrollbackLines: 200, + scrollbackLines: 10000, size: { rows: 24, cols: 80 }, }); }); @@ -30,26 +32,39 @@ describe("terminal restore options", () => { it("omits size until the terminal has been measured", () => { expect( resolveTerminalRestoreOptions({ + scrollbackLines: 10000, supportsTerminalRestoreModes: true, canClaimSize: true, size: null, }), ).toEqual({ mode: "visible-snapshot", - scrollbackLines: 200, + scrollbackLines: 10000, }); }); it("does not let a background attach resize the PTY", () => { expect( resolveTerminalRestoreOptions({ + scrollbackLines: 10000, supportsTerminalRestoreModes: true, canClaimSize: false, size: { rows: 24, cols: 80 }, }), ).toEqual({ mode: "visible-snapshot", - scrollbackLines: 200, + scrollbackLines: 10000, }); }); }); + +it.each([0, 5, 400, 10000])("requests exactly %s configured history rows", (scrollbackLines) => { + expect( + resolveTerminalRestoreOptions({ + supportsTerminalRestoreModes: true, + scrollbackLines, + canClaimSize: false, + size: null, + }), + ).toEqual({ mode: "visible-snapshot", scrollbackLines }); +}); diff --git a/packages/app/src/terminal/runtime/terminal-restore-options.ts b/packages/app/src/terminal/runtime/terminal-restore-options.ts index d1e304cec7..3fcd894eac 100644 --- a/packages/app/src/terminal/runtime/terminal-restore-options.ts +++ b/packages/app/src/terminal/runtime/terminal-restore-options.ts @@ -1,23 +1,23 @@ +import { i18n } from "@/i18n/i18next"; import type { SubscribeTerminalRequest } from "@getpaseo/protocol/messages"; -export const TERMINAL_VISIBLE_RESTORE_SCROLLBACK_LINES = 200; - export interface ResolveTerminalRestoreOptionsInput { supportsTerminalRestoreModes: boolean; + scrollbackLines: number; canClaimSize: boolean; size: { rows: number; cols: number } | null; } export function resolveTerminalRestoreOptions( input: ResolveTerminalRestoreOptionsInput, -): SubscribeTerminalRequest["restore"] | undefined { +): NonNullable { if (!input.supportsTerminalRestoreModes) { - return undefined; + throw new Error(i18n.t("workspace.terminal.restoreRequiresUpdate")); } return { mode: "visible-snapshot", - scrollbackLines: TERMINAL_VISIBLE_RESTORE_SCROLLBACK_LINES, + scrollbackLines: input.scrollbackLines, ...(input.canClaimSize && input.size ? { size: input.size } : {}), }; } diff --git a/packages/app/src/terminal/runtime/terminal-snapshot.test.ts b/packages/app/src/terminal/runtime/terminal-snapshot.test.ts index c5fdbbd9fd..6232d9a8c0 100644 --- a/packages/app/src/terminal/runtime/terminal-snapshot.test.ts +++ b/packages/app/src/terminal/runtime/terminal-snapshot.test.ts @@ -2,7 +2,7 @@ import { Terminal as HeadlessTerminal } from "@xterm/headless"; import { Terminal as ClientTerminal } from "@xterm/xterm"; import { describe, expect, it } from "vitest"; -import { renderTerminalSnapshotToAnsi } from "./terminal-snapshot"; +import { SerializeAddon } from "@xterm/addon-serialize"; interface SnapshotCell { char: string; @@ -122,7 +122,7 @@ function extractRow(terminal: ClientTerminal | HeadlessTerminal, row: number): S } describe("terminal-snapshot", () => { - it("replays extracted terminal state into a client xterm with matching grid, scrollback, and cursor presentation", async () => { + it("replays upstream serialized ANSI into a client xterm with matching grid, scrollback, and cursor presentation", async () => { const source = new HeadlessTerminal({ rows: 4, cols: 12, @@ -138,6 +138,8 @@ describe("terminal-snapshot", () => { await writeToTerminal(source, "\u001b[2 q"); await writeToTerminal(source, "\u001b[?25l"); + const serializer = new SerializeAddon(); + source.loadAddon(serializer); const snapshot = extractState(source); const client = new ClientTerminal({ @@ -147,7 +149,7 @@ describe("terminal-snapshot", () => { scrollback: 100, }); - await writeToTerminal(client, renderTerminalSnapshotToAnsi(snapshot)); + await writeToTerminal(client, serializer.serialize() + "\x1b[2 q\x1b[?25l"); expect(extractState(client)).toEqual(snapshot); }); diff --git a/packages/app/src/terminal/runtime/terminal-snapshot.ts b/packages/app/src/terminal/runtime/terminal-snapshot.ts deleted file mode 100644 index 4b7a8e0b9b..0000000000 --- a/packages/app/src/terminal/runtime/terminal-snapshot.ts +++ /dev/null @@ -1 +0,0 @@ -export { renderTerminalSnapshotToAnsi } from "@getpaseo/protocol/terminal-snapshot"; diff --git a/packages/app/src/terminal/runtime/terminal-stream-controller.test.ts b/packages/app/src/terminal/runtime/terminal-stream-controller.test.ts index 388484d79d..ecd49c6fd5 100644 --- a/packages/app/src/terminal/runtime/terminal-stream-controller.test.ts +++ b/packages/app/src/terminal/runtime/terminal-stream-controller.test.ts @@ -1,3 +1,4 @@ +import { resolveTerminalRestoreOptions } from "./terminal-restore-options"; import type { SessionOutboundMessage } from "@getpaseo/protocol/messages"; import { describe, expect, it } from "vitest"; @@ -7,34 +8,16 @@ import { type TerminalStreamControllerStatus, } from "./terminal-stream-controller"; -interface TerminalSnapshot { - rows: number; - cols: number; - grid: Array>; - scrollback: Array>; - cursor: { row: number; col: number }; -} - -function terminalCellText(cell: { char: string }): string { - return cell.char; -} - -function terminalRowText(row: Array<{ char: string }>): string { - return row.map(terminalCellText).join(""); -} - -function terminalSnapshotText(state: TerminalSnapshot): string { - return state.grid.map(terminalRowText).join("\n"); -} - function terminalOutput(text: string): Uint8Array { return new TextEncoder().encode(text); } -type TerminalStreamEvent = - | { terminalId: string; type: "output"; data: Uint8Array } - | { terminalId: string; type: "snapshot"; state: TerminalSnapshot } - | { terminalId: string; type: "restore"; data: Uint8Array }; +type StreamEvent = import("@getpaseo/client").TerminalStreamEvent; +type TerminalStreamEvent = StreamEvent extends infer Event + ? Event extends StreamEvent + ? Omit + : never + : never; class FakeTerminalStreamClient implements TerminalStreamControllerClient { private readonly updates = new Set<(message: SessionOutboundMessage) => void>(); @@ -115,32 +98,23 @@ class FakeTerminalStreamClient implements TerminalStreamControllerClient { function createHarness(input?: { client?: FakeTerminalStreamClient }) { const client = input?.client ?? new FakeTerminalStreamClient(); const outputs: Array<{ terminalId: string; data: Uint8Array }> = []; - const restores: Array<{ terminalId: string; data: Uint8Array }> = []; - const snapshots: Array<{ terminalId: string; text: string }> = []; + const replays: import("@getpaseo/client").TerminalReplayEvent[] = []; const statuses: TerminalStreamControllerStatus[] = []; const exits: string[] = []; const controller = new TerminalStreamController({ client, + onReplay: ({ replay }) => replays.push(replay), onExit: (terminalId) => exits.push(terminalId), getPreferredSize: () => ({ rows: 24, cols: 80 }), onOutput: (output) => { outputs.push(output); }, - onRestore: (restore) => { - restores.push(restore); - }, - onSnapshot: ({ terminalId, state }) => { - snapshots.push({ - terminalId, - text: terminalSnapshotText(state), - }); - }, onStatusChange: (status) => { statuses.push(status); }, }); - return { client, controller, outputs, restores, snapshots, statuses, exits }; + return { client, controller, outputs, replays, statuses, exits }; } async function flushAsyncWork(): Promise { @@ -149,24 +123,20 @@ async function flushAsyncWork(): Promise { } describe("terminal-stream-controller", () => { - it("subscribes, resizes, and forwards snapshot/output events", async () => { + it("subscribes, resizes, and forwards replay/output events", async () => { const harness = createHarness(); harness.client.nextSubscribeResults.push({ terminalId: "term-1", error: null }); harness.controller.setTerminal({ terminalId: "term-1" }); await flushAsyncWork(); - harness.client.emit({ - terminalId: "term-1", - type: "snapshot", - state: { - rows: 1, - cols: 5, - grid: [[{ char: "h" }, { char: "e" }, { char: "l" }, { char: "l" }, { char: "o" }]], - scrollback: [], - cursor: { row: 0, col: 5 }, - }, - }); + const replay: import("@getpaseo/client").TerminalReplayEvent[] = [ + { type: "begin", rows: 24, cols: 80, retainedHistoryLines: 400 }, + { type: "data", data: terminalOutput("hello") }, + { type: "end" }, + ]; + for (const event of replay) + harness.client.emit({ terminalId: "term-1", type: "replay", replay: event }); const outputData = terminalOutput(" world"); harness.client.emit({ terminalId: "term-1", @@ -178,7 +148,7 @@ describe("terminal-stream-controller", () => { expect(harness.client.resizeCalls).toEqual([ { terminalId: "term-1", rows: 24, cols: 80, intent: "claim" }, ]); - expect(harness.snapshots).toEqual([{ terminalId: "term-1", text: "hello" }]); + expect(harness.replays).toEqual(replay); expect(harness.outputs[0]?.data).toBe(outputData); expect(harness.outputs).toEqual([{ terminalId: "term-1", data: terminalOutput(" world") }]); expect(harness.statuses.at(-1)).toEqual({ @@ -236,23 +206,19 @@ describe("terminal-stream-controller", () => { size: { rows: 24, cols: 80 }, }), onOutput: (output) => harness.outputs.push(output), - onRestore: (restore) => harness.restores.push(restore), - onSnapshot: ({ terminalId, state }) => { - harness.snapshots.push({ - terminalId, - text: terminalSnapshotText(state), - }); - }, + onReplay: ({ replay }) => harness.replays.push(replay), }); controller.setTerminal({ terminalId: "term-1" }); await flushAsyncWork(); const restoreData = terminalOutput("restored"); - client.emit({ - terminalId: "term-1", - type: "restore", - data: restoreData, - }); + const replay: import("@getpaseo/client").TerminalReplayEvent[] = [ + { type: "begin" }, + { type: "data", data: restoreData }, + { type: "end" }, + ]; + for (const event of replay) + client.emit({ terminalId: "term-1", type: "replay", replay: event }); controller.dispose(); expect(client.subscribeCalls).toEqual([ @@ -270,8 +236,7 @@ describe("terminal-stream-controller", () => { expect(client.resizeCalls).toEqual([ { terminalId: "term-1", rows: 24, cols: 80, intent: "claim" }, ]); - expect(harness.restores[0]?.data).toBe(restoreData); - expect(harness.restores).toEqual([{ terminalId: "term-1", data: terminalOutput("restored") }]); + expect(harness.replays).toEqual(replay); expect(harness.outputs).toEqual([]); }); @@ -319,3 +284,28 @@ it("reports observation failure without declaring the PTY exited, then allows re expect(h.statuses.at(-1)?.error).toBe(null); h.controller.dispose(); }); + +it("does not resize or attach on a JSON-era host and reports the required update", () => { + const client = new FakeTerminalStreamClient(); + const statuses: TerminalStreamControllerStatus[] = []; + const controller = new TerminalStreamController({ + client, + getPreferredSize: () => ({ rows: 24, cols: 40 }), + onOutput: () => {}, + getRestoreOptions: () => + resolveTerminalRestoreOptions({ + supportsTerminalRestoreModes: false, + scrollbackLines: 10000, + canClaimSize: true, + size: { rows: 24, cols: 40 }, + }), + onStatusChange: (status) => statuses.push(status), + }); + controller.setTerminal({ terminalId: "old-host-terminal" }); + expect(client.subscribeCalls).toEqual([]); + expect(client.resizeCalls).toEqual([]); + expect(statuses.at(-1)).toMatchObject({ + isAttaching: false, + error: "Update the host to view terminals.", + }); +}); diff --git a/packages/app/src/terminal/runtime/terminal-stream-controller.ts b/packages/app/src/terminal/runtime/terminal-stream-controller.ts index 90d54be4d4..b4b166cadf 100644 --- a/packages/app/src/terminal/runtime/terminal-stream-controller.ts +++ b/packages/app/src/terminal/runtime/terminal-stream-controller.ts @@ -1,5 +1,5 @@ import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; -import type { SubscribeTerminalRequest, TerminalState } from "@getpaseo/protocol/messages"; +import type { SubscribeTerminalRequest } from "@getpaseo/protocol/messages"; import type { TerminalOutputData } from "./terminal-emulator-runtime"; import { i18n } from "@/i18n/i18next"; @@ -23,9 +23,11 @@ export interface TerminalStreamControllerOptions { client: TerminalStreamControllerClient; getPreferredSize: () => TerminalStreamControllerSize | null; onOutput: (input: { terminalId: string; data: TerminalOutputData }) => void; - onSnapshot: (input: { terminalId: string; state: TerminalState }) => void; onExit?: (terminalId: string) => void; - onRestore?: (input: { terminalId: string; data: TerminalOutputData }) => void; + onReplay?: (input: { + terminalId: string; + replay: import("@getpaseo/client").TerminalReplayEvent; + }) => void; getRestoreOptions?: () => SubscribeTerminalRequest["restore"] | undefined; onStatusChange?: (status: TerminalStreamControllerStatus) => void; } @@ -43,17 +45,11 @@ export class TerminalStreamController { if (this.disposed || event.terminalId !== this.terminalId) { return; } - if (event.type === "snapshot") { - this.options.onSnapshot({ terminalId: event.terminalId, state: event.state }); + if (event.type === "replay") { + this.options.onReplay?.({ terminalId: event.terminalId, replay: event.replay }); return; } - if (event.type === "restore") { - if (event.data.length > 0) { - this.options.onRestore?.({ terminalId: event.terminalId, data: event.data }); - } - return; - } - if (event.data.length > 0) { + if (event.type === "output" && event.data.length > 0) { this.options.onOutput({ terminalId: event.terminalId, data: event.data }); } }; @@ -70,10 +66,10 @@ export class TerminalStreamController { this.options.onStatusChange?.({ terminalId: null, isAttaching: false, error: null }); return; } - const restore = this.options.getRestoreOptions?.(); this.options.onStatusChange?.({ terminalId: nextTerminalId, isAttaching: true, error: null }); let subscription: ReturnType; try { + const restore = this.options.getRestoreOptions?.(); const preferredSize = restore?.size ?? this.options.getPreferredSize(); if (preferredSize) this.options.client.sendTerminalInput(nextTerminalId, { diff --git a/packages/app/src/terminal/runtime/workspace-terminal-session.test.ts b/packages/app/src/terminal/runtime/workspace-terminal-session.test.ts deleted file mode 100644 index 97063539d6..0000000000 --- a/packages/app/src/terminal/runtime/workspace-terminal-session.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { - getWorkspaceTerminalSession, - releaseWorkspaceTerminalSession, - retainWorkspaceTerminalSession, -} from "./workspace-terminal-session"; - -describe("workspace-terminal-session", () => { - it("returns the same workspace session instance for the same scope", () => { - const first = getWorkspaceTerminalSession({ - scopeKey: "workspace-a", - }); - const second = getWorkspaceTerminalSession({ - scopeKey: "workspace-a", - }); - - expect(second).toBe(first); - }); - - it("preserves snapshots across repeated lookups", () => { - const first = getWorkspaceTerminalSession({ - scopeKey: "workspace-snapshots", - }); - first.snapshots.set({ - terminalId: "term-1", - state: { - rows: 1, - cols: 1, - grid: [[{ char: "A" }]], - scrollback: [], - cursor: { row: 0, col: 0 }, - }, - }); - - const second = getWorkspaceTerminalSession({ - scopeKey: "workspace-snapshots", - }); - - expect(second.snapshots.get({ terminalId: "term-1" })).toEqual({ - rows: 1, - cols: 1, - grid: [[{ char: "A" }]], - scrollback: [], - cursor: { row: 0, col: 0 }, - }); - }); - - it("evicts workspace terminal session state when the retain count returns to zero", () => { - const scopeKey = "workspace-release"; - const first = getWorkspaceTerminalSession({ - scopeKey, - }); - first.snapshots.set({ - terminalId: "term-1", - state: { - rows: 1, - cols: 1, - grid: [[{ char: "A" }]], - scrollback: [], - cursor: { row: 0, col: 0 }, - }, - }); - - retainWorkspaceTerminalSession({ scopeKey }); - releaseWorkspaceTerminalSession({ scopeKey }); - - const second = getWorkspaceTerminalSession({ - scopeKey, - }); - - expect(second).not.toBe(first); - expect(second.snapshots.get({ terminalId: "term-1" })).toBeNull(); - }); -}); diff --git a/packages/app/src/terminal/runtime/workspace-terminal-session.ts b/packages/app/src/terminal/runtime/workspace-terminal-session.ts deleted file mode 100644 index 277f956b97..0000000000 --- a/packages/app/src/terminal/runtime/workspace-terminal-session.ts +++ /dev/null @@ -1,79 +0,0 @@ -import type { TerminalState } from "@getpaseo/protocol/messages"; - -export interface WorkspaceTerminalSnapshots { - get: (input: { terminalId: string }) => TerminalState | null; - set: (input: { terminalId: string; state: TerminalState }) => void; - clear: (input: { terminalId: string }) => void; - prune: (input: { terminalIds: string[] }) => void; -} - -export interface WorkspaceTerminalSession { - scopeKey: string; - snapshots: WorkspaceTerminalSnapshots; -} - -interface WorkspaceTerminalSessionRecord { - snapshotByTerminalId: Map; - session: WorkspaceTerminalSession; -} - -const sessionsByScopeKey = new Map(); -const refCountByScopeKey = new Map(); - -function createSnapshots(input: { - snapshotByTerminalId: Map; -}): WorkspaceTerminalSnapshots { - return { - get: ({ terminalId }) => input.snapshotByTerminalId.get(terminalId) ?? null, - set: ({ terminalId, state }) => { - input.snapshotByTerminalId.set(terminalId, state); - }, - clear: ({ terminalId }) => { - input.snapshotByTerminalId.delete(terminalId); - }, - prune: ({ terminalIds }) => { - const terminalIdSet = new Set(terminalIds); - for (const terminalId of Array.from(input.snapshotByTerminalId.keys())) { - if (!terminalIdSet.has(terminalId)) { - input.snapshotByTerminalId.delete(terminalId); - } - } - }, - }; -} - -export function getWorkspaceTerminalSession(input: { scopeKey: string }): WorkspaceTerminalSession { - const existing = sessionsByScopeKey.get(input.scopeKey); - if (existing) { - return existing.session; - } - - const snapshotByTerminalId = new Map(); - const session: WorkspaceTerminalSession = { - scopeKey: input.scopeKey, - snapshots: createSnapshots({ - snapshotByTerminalId, - }), - }; - - sessionsByScopeKey.set(input.scopeKey, { - snapshotByTerminalId, - session, - }); - return session; -} - -export function retainWorkspaceTerminalSession(input: { scopeKey: string }): void { - const current = refCountByScopeKey.get(input.scopeKey) ?? 0; - refCountByScopeKey.set(input.scopeKey, current + 1); -} - -export function releaseWorkspaceTerminalSession(input: { scopeKey: string }): void { - const current = refCountByScopeKey.get(input.scopeKey) ?? 0; - if (current > 1) { - refCountByScopeKey.set(input.scopeKey, current - 1); - return; - } - refCountByScopeKey.delete(input.scopeKey); - sessionsByScopeKey.delete(input.scopeKey); -} diff --git a/packages/app/src/utils/terminal-renderer-readiness.test.ts b/packages/app/src/utils/terminal-renderer-readiness.test.ts index 45866f8df6..d7e5f71833 100644 --- a/packages/app/src/utils/terminal-renderer-readiness.test.ts +++ b/packages/app/src/utils/terminal-renderer-readiness.test.ts @@ -3,7 +3,6 @@ import { describe, expect, it } from "vitest"; import { applyTerminalRendererReadyChange, resolveTerminalStreamTarget, - shouldReplayTerminalSnapshotForRenderer, shouldShowTerminalLoadingOverlay, } from "./terminal-renderer-readiness"; @@ -74,27 +73,6 @@ describe("terminal-renderer-readiness", () => { expect(current).toBeNull(); }); - it("replays snapshots only for ready events from the current renderer", () => { - expect( - shouldReplayTerminalSnapshotForRenderer({ - change: { streamKey: "scope:terminal-1", isReady: true }, - terminalStreamKey: "scope:terminal-1", - }), - ).toBe(true); - expect( - shouldReplayTerminalSnapshotForRenderer({ - change: { streamKey: "scope:terminal-1", isReady: false }, - terminalStreamKey: "scope:terminal-1", - }), - ).toBe(false); - expect( - shouldReplayTerminalSnapshotForRenderer({ - change: { streamKey: "scope:terminal-1", isReady: true }, - terminalStreamKey: "scope:terminal-2", - }), - ).toBe(false); - }); - it("does not attach the stream before the matching renderer is ready", () => { expect( resolveTerminalStreamTarget({ diff --git a/packages/app/src/utils/terminal-renderer-readiness.ts b/packages/app/src/utils/terminal-renderer-readiness.ts index 7d4f855aba..197a8811f9 100644 --- a/packages/app/src/utils/terminal-renderer-readiness.ts +++ b/packages/app/src/utils/terminal-renderer-readiness.ts @@ -14,13 +14,6 @@ export function applyTerminalRendererReadyChange( return currentReadyStreamKey === change.streamKey ? null : currentReadyStreamKey; } -export function shouldReplayTerminalSnapshotForRenderer(input: { - change: TerminalRendererReadyChange; - terminalStreamKey: string; -}): boolean { - return input.change.isReady && input.change.streamKey === input.terminalStreamKey; -} - export function resolveTerminalStreamTarget(input: { terminalId: string; terminalStreamKey: string; diff --git a/packages/cli/tests/46-daemon-terminal-worker-upgrade.test.ts b/packages/cli/tests/46-daemon-terminal-worker-upgrade.test.ts index ff8ef6bc6f..9090456406 100644 --- a/packages/cli/tests/46-daemon-terminal-worker-upgrade.test.ts +++ b/packages/cli/tests/46-daemon-terminal-worker-upgrade.test.ts @@ -10,11 +10,10 @@ * `stop --keep-terminals` and moving A's node-pty, worker bundle and shell integration away, * a daemon from B adopts the same worker and opens a new, working terminal in it with B's * environment and CLI, while the first terminal keeps A's. - * 2. Worker protocol versions (PASEO_TERMINAL_WORKER_PROTOCOL_OVERRIDE): a worker one version - * old drains (keeps its terminal, new ones open in a second worker, it exits after its last - * terminal and its copy is deleted); one two versions old is shut down; one from a newer - * Paseo is left running, reported as terminal_worker_incompatible, and closed by - * `daemon stop`. + * 2. Worker protocol versions (PASEO_TERMINAL_WORKER_PROTOCOL_OVERRIDE): protocols 0–4 + * are obsolete unreleased wires, so their programs/workers/copies are closed and a current + * worker serves new terminals. A truly newer protocol is left running, reported as + * terminal_worker_incompatible, and closed by `daemon stop`. * * Every process it starts is stopped in `finally`. */ @@ -35,7 +34,7 @@ import { import { mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { getAvailablePort } from "./helpers/network.ts"; +import { createServer } from "node:net"; if (process.platform === "win32") { console.log("Skipping terminal worker upgrade CLI test on Windows (POSIX shell terminals)."); @@ -50,7 +49,7 @@ const paseoHome = join(root, "home"); const cliHome = join(root, "os-home"); const workDir = join(root, "work"); for (const dir of [paseoHome, cliHome, workDir]) mkdirSync(dir, { recursive: true }); -const port = await getAvailablePort(); +const currentProtocolVersion = 5; const zsh = ["/bin/zsh", "/usr/bin/zsh"].find((candidate) => existsSync(candidate)) ?? null; interface Installation { @@ -336,7 +335,18 @@ async function terminalIds(installation: Installation): Promise { } async function startDaemon(installation: Installation, extraEnv: Record = {}) { - await paseo(installation, ["daemon", "start"], extraEnv); + const result = await paseo(installation, ["daemon", "start", "--json"], extraEnv); + lastListen = (JSON.parse(result.stdout) as { listen: string }).listen; + assert.match(lastListen, /^127\.0\.0\.1:[1-9]\d*$/, "start publishes the actual bound port"); + if (competingListener.listening) { + const competitor = competingListener.address(); + assert(competitor && typeof competitor !== "string"); + assert.notEqual( + Number(lastListen.split(":").at(-1)), + competitor.port, + "each daemon binds its own endpoint while the released port belongs to a peer", + ); + } } async function stopDaemon(installation: Installation, keepTerminals = false) { @@ -371,10 +381,14 @@ const a = createInstallation("A", "0.98.0"); const b = createInstallation("B", "0.99.0"); let restoreA: (() => void) | null = null; let passed = false; +let lastListen = ""; +const competingListener = createServer(); try { for (const [field, value] of [ - ["daemon.listen", `127.0.0.1:${port}`], + // Let the listening daemon reserve its port atomically. Clients discover the + // actual endpoint from this home's PID record after every start. + ["daemon.listen", "127.0.0.1:0"], ["daemon.relay.enabled", "false"], ["features.dictation.enabled", "false"], ["features.voiceMode.enabled", "false"], @@ -387,6 +401,7 @@ try { const t1 = await openTerminal(a, "t1"); const [firstWorker] = workerRecords(); assert(firstWorker, "one worker runs"); + assert.equal(firstWorker.protocolVersion, currentProtocolVersion, "the current wire is adopted"); assert.match(firstWorker.runtime ?? "", /^0\.98\.0-[0-9a-f]{12}$/); const copyA = join(paseoHome, "terminal-worker", firstWorker.runtime!); assert( @@ -432,54 +447,62 @@ try { restoreA = null; console.log("✓ closed and cleaned up\n"); - console.log("Test 4: a worker one protocol version old drains"); - const old = await leaveWorkerWithProtocol(a, 0, "t3"); - await startDaemon(b); - const workers = workerRecords(); - assert.equal(workers.length, 2, "the old worker drains beside a new one"); - const current = workers.find((record) => record.pid !== old.workerPid)!; - assert.equal(current.protocolVersion, 1); - assert.match(current.runtime ?? "", /^0\.99\.0-/); - assert((await terminalIds(b)).includes(old.terminal.id), "the old worker's terminal is listed"); - await type(b, old.terminal.id, "echo still-served"); - await waitForScreen(b, old.terminal.id, "\nstill-served"); - const t4 = await openTerminal(b, "t4"); - assert.deepEqual( - workerRecords() - .find((record) => record.pid === current.pid)! - .terminals.map((terminal) => terminal.id), - [t4.id], - "new terminals open in the current worker", - ); - await paseo(b, ["terminal", "kill", old.terminal.id]); - await waitFor( - () => !isAlive(old.workerPid), - () => `the drained worker ${old.workerPid} did not exit`, - ); - await waitFor( - () => !runtimeCopies().includes(old.runtime), - () => `the drained worker's copy ${old.runtime} was not deleted: ${runtimeCopies().join(", ")}`, - ); - assert.deepEqual(runtimeCopies(), [current.runtime], "the current worker's copy stays"); - await type(b, t4.id, "echo after-drain"); - await waitForScreen(b, t4.id, "\nafter-drain"); - await stopDaemon(b); - console.log("✓ drained, exited, copy deleted\n"); + // A released endpoint belongs to nobody. Reproduce another process taking it + // between starts; worker adoption is keyed by the home, not by a stable TCP port. + const releasedPort = Number(lastListen.split(":").at(-1)); + await new Promise((resolve, reject) => { + competingListener.once("error", reject); + competingListener.listen(releasedPort, "127.0.0.1", resolve); + }); + console.log(`Competing listener owns released port ${releasedPort}`); - console.log("Test 5: a worker two protocol versions old is shut down"); - const obsolete = await leaveWorkerWithProtocol(a, -1, "t5"); - await startDaemon(b); - await waitFor( - () => !isAlive(obsolete.workerPid) && !isAlive(obsolete.terminal.pid), - () => "the obsolete worker or its terminal survived", - ); - assert(!(await terminalIds(b)).includes(obsolete.terminal.id), "its terminal is gone"); - assert.equal(workerRecords().length, 1, "one current worker runs"); - await stopDaemon(b); - console.log("✓ shut down\n"); + // There is no supported previous wire at protocol 5. Future previous-version classification + // is covered by terminal-worker-protocol.test.ts; do not simulate an unreleased drain adapter. + for (const protocolVersion of [0, 1, 2, 3, 4]) { + console.log(`Test 4: obsolete protocol ${protocolVersion} is closed before serving terminals`); + const obsolete = await leaveWorkerWithProtocol( + a, + protocolVersion, + `obsolete-${protocolVersion}`, + ); + await startDaemon(b); + await waitFor( + () => !isAlive(obsolete.workerPid) && !isAlive(obsolete.terminal.pid), + () => "the obsolete worker or its terminal survived", + ); + assert(!(await terminalIds(b)).includes(obsolete.terminal.id), "its terminal is gone"); + const [current] = workerRecords(); + assert.equal(workerRecords().length, 1, "one current worker runs"); + assert(current); + assert.equal(current.protocolVersion, currentProtocolVersion); + assert.match(current.runtime ?? "", /^0\.99\.0-/); + await waitFor( + () => !runtimeCopies().includes(obsolete.runtime), + () => `the obsolete worker's copy ${obsolete.runtime} was not deleted`, + ); + assert.deepEqual(runtimeCopies(), [current.runtime], "the current copy stays"); + const replacement = await openTerminal(b, `replacement-${protocolVersion}`); + assert.deepEqual( + workerRecords() + .find((record) => record.pid === current.pid)! + .terminals.map((terminal) => terminal.id), + [replacement.id], + "new terminals open in the current worker", + ); + await type(b, replacement.id, `echo after-protocol-cut-${protocolVersion}`); + await waitForScreen(b, replacement.id, `\nafter-protocol-cut-${protocolVersion}`); + await stopDaemon(b); + await waitFor( + () => !isAlive(replacement.pid) && !isAlive(current.pid), + () => "the replacement worker or program outlived daemon stop", + ); + assert.deepEqual(workerRecords(), [], "no worker record is left"); + assert.deepEqual(runtimeCopies(), [], "no copy is left"); + console.log("✓ obsolete closed, current usable, copies cleaned up\n"); + } - console.log("Test 6: a worker from a newer Paseo is left running and reported"); - const newer = await leaveWorkerWithProtocol(a, 2, "t6"); + console.log("Test 5: a worker from a newer Paseo is left running and reported"); + const newer = await leaveWorkerWithProtocol(a, currentProtocolVersion + 1, "newer"); await startDaemon(b); const listed = await run(b, ["terminal", "ls", "--all", "--json"]); assert.notEqual(listed.exitCode, 0, "terminal ls fails"); @@ -514,6 +537,17 @@ try { } } } + if (competingListener.listening) { + await new Promise((resolve, reject) => + competingListener.close((error) => { + if (error) { + reject(error); + return; + } + resolve(); + }), + ); + } restoreA?.(); for (const installation of [b, a]) { await run(installation, ["daemon", "stop", "--home", paseoHome, "--force"]); diff --git a/packages/client/src/connection/index.ts b/packages/client/src/connection/index.ts index 1ad4b34dee..62753bca5c 100644 --- a/packages/client/src/connection/index.ts +++ b/packages/client/src/connection/index.ts @@ -125,6 +125,7 @@ export class ConnectionSubscriptions extends OwnedSubscriptions { // Protocol support belongs to the installed client. Only browser hosting needs // a resource supplied by the caller. Keep this exhaustive as the protocol evolves. export const DEFAULT_CLIENT_CAPABILITIES = { + [CLIENT_CAPS.terminalChunkedReplay]: true, [CLIENT_CAPS.binaryChunkingV1]: true, [CLIENT_CAPS.helloRejection]: true, [CLIENT_CAPS.ownedSubscriptions]: true, diff --git a/packages/client/src/daemon-client.test.ts b/packages/client/src/daemon-client.test.ts index 6ef72a0e1a..4fa7d5723c 100644 --- a/packages/client/src/daemon-client.test.ts +++ b/packages/client/src/daemon-client.test.ts @@ -13,6 +13,7 @@ import { type PluginClientBundleStore, } from "./daemon-client"; import { CLIENT_CAPS } from "@getpaseo/protocol/client-capabilities"; +import { ChunkedTransport } from "@getpaseo/protocol/chunked-transport"; import { BROWSER_AUTOMATION_COMMAND_NAMES } from "@getpaseo/protocol/browser-automation/rpc-schemas"; import { decodeFileTransferFrame, @@ -1102,6 +1103,7 @@ test("advertises client capabilities in hello", async () => { projected_subagent_timeline: true, reasoning_merge_enum: true, terminal_reflowable_snapshot: true, + terminal_chunked_replay: true, timeline_notifications: true, plugin_timeline_items: true, workspace_setup_blocked: true, @@ -6388,66 +6390,80 @@ test("emits output events for the active terminal stream", async () => { unsubscribe(); }); -test("emits snapshot events for the subscribed terminal stream", async () => { - const logger = createMockLogger(); - const mock = createMockTransport(); +test.each([5, 500, 10000])( + "preserves explicit %s history demand on an old ANSI host and normalizes restore", + async (history) => { + const logger = createMockLogger(); + const mock = createMockTransport(); - const client = new DaemonClient({ - url: "ws://test", - clientId: "clsk_unit_test", - logger, - reconnect: { enabled: false }, - transportFactory: () => mock.transport, - }); - clients.push(client); + const client = new DaemonClient({ + url: "ws://test", + clientId: "clsk_unit_test", + logger, + reconnect: { enabled: false }, + transportFactory: () => mock.transport, + }); + clients.push(client); - const connectPromise = client.connect(); - mock.triggerOpen(); - await connectPromise; + const connectPromise = client.connect(); + mock.triggerOpen(); + await connectPromise; - const snapshots: unknown[] = []; - client.onTerminalStreamEvent((event) => { - if (event.type !== "snapshot") { - return; - } - snapshots.push(event.state); - }); + const events: unknown[] = []; + const replayEvents: unknown[] = []; + client.onTerminalStreamEvent((event) => { + if (event.type === "replay") replayEvents.push(event.replay); + events.push(event); + }); - const subscribePromise = client.subscribeTerminal("term-1", { requestId: "sub-2" }); - await vi.waitFor(() => - expect(parseSentFrame(mock.sent.at(-1)).type).toBe("subscribe_terminal_request"), - ); - mock.triggerMessage( - wrapSessionMessage({ - type: "subscribe_terminal_response", - payload: { - subscriptionId: "server-" + String(parseSentFrame(mock.sent.at(-1)).requestId), - terminalId: "term-1", + const subscribePromise = client.subscribeTerminal("term-1", { + requestId: "sub-2", + restore: { mode: "visible-snapshot", scrollbackLines: history }, + }); + await vi.waitFor(() => + expect(parseSentFrame(mock.sent.at(-1)).type).toBe("subscribe_terminal_request"), + ); + expect(parseSentFrame(mock.sent.at(-1)).restore).toEqual({ + mode: "visible-snapshot", + scrollbackLines: history, + }); + mock.triggerMessage( + wrapSessionMessage({ + type: "subscribe_terminal_response", + payload: { + subscriptionId: "server-" + String(parseSentFrame(mock.sent.at(-1)).requestId), + terminalId: "term-1", + slot: 12, + error: null, + requestId: "sub-2", + }, + }), + ); + await subscribePromise; + + const state = { + rows: 1, + cols: 5, + grid: [[{ char: "h" }, { char: "e" }, { char: "l" }, { char: "l" }, { char: "o" }]], + scrollback: [], + cursor: { row: 0, col: 5 }, + }; + mock.triggerMessage( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Snapshot, slot: 12, - error: null, - requestId: "sub-2", - }, - }), - ); - await subscribePromise; + payload: encodeTerminalSnapshotPayload(state), + }), + ); - const state = { - rows: 1, - cols: 5, - grid: [[{ char: "h" }, { char: "e" }, { char: "l" }, { char: "l" }, { char: "o" }]], - scrollback: [], - cursor: { row: 0, col: 5 }, - }; - mock.triggerMessage( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Snapshot, - slot: 12, - payload: encodeTerminalSnapshotPayload(state), - }), - ); - - expect(snapshots).toEqual([state]); -}); + expect(events).toEqual([]); + const data = new TextEncoder().encode("\x1b[31mold ANSI host界🙂"); + mock.triggerMessage( + encodeTerminalStreamFrame({ opcode: TerminalStreamOpcode.Restore, slot: 12, payload: data }), + ); + expect(replayEvents).toEqual([{ type: "begin" }, { type: "data", data }, { type: "end" }]); + }, +); test("sends explicit terminal input and resize commands", async () => { const logger = createMockLogger(); @@ -6843,7 +6859,6 @@ test.each([false, true])( }); const command = chunked ? "x".repeat(50 * 1024 * 1024) : "pwd"; - const { ChunkedTransport } = await import("@getpaseo/protocol/chunked-transport"); const sender = new ChunkedTransport({ frameBytes: 24 * 1024 * 1024, send: (frame) => mock.triggerMessage(frame), @@ -8484,6 +8499,133 @@ test("closes before admission when a protected-capable daemon is reached in lega expect(JSON.parse(daemonReceived[0] as string)).toMatchObject({ type: "hello" }); }); +test.each([ + { chunked: false, transportChunked: false }, + { chunked: true, transportChunked: false }, + { chunked: false, transportChunked: true }, + { chunked: true, transportChunked: true }, +])( + "default terminal observation requests ANSI replay (replay=$chunked, transport=$transportChunked)", + async ({ chunked, transportChunked }) => { + const transport = createMockTransport(); + const client = new DaemonClient({ + url: "ws://test", + clientId: "clsk_unit_test", + logger: createMockLogger(), + reconnect: { enabled: false }, + transportFactory: () => transport.transport, + }); + clients.push(client); + const connecting = client.connect(); + transport.triggerOpen({ + preserveSent: true, + features: { + ownedSubscriptions: true, + "terminal-restore-modes": true, + binaryChunkingV1: transportChunked, + }, + }); + await connecting; + const hello = JSON.parse(transport.sent[0] as string); + expect(hello.capabilities[CLIENT_CAPS.terminalChunkedReplay]).toBe(true); + expect(hello.capabilities[CLIENT_CAPS.binaryChunkingV1]).toBe(true); + const wire: Uint8Array[] = []; + const sender = new ChunkedTransport({ + frameBytes: 17, + send: (frame) => { + if (typeof frame === "string") throw new Error("Expected binary terminal frame"); + wire.push(frame); + transport.triggerMessage(frame); + }, + deliver: () => {}, + }); + sender.enabled = transportChunked; + const events: import("./terminal-stream-router").TerminalStreamEvent[] = []; + const observation = client.observeTerminal("default-terminal", (event) => events.push(event)); + await vi.waitFor(() => + expect(parseSentFrame(transport.sent.at(-1)).type).toBe("subscribe_terminal_request"), + ); + const request = parseSentFrame(transport.sent.at(-1)); + expect(request.restore).toEqual({ mode: "full-snapshot" }); + transport.triggerMessage( + wrapSessionMessage({ + type: "subscribe_terminal_response", + payload: { + terminalId: "default-terminal", + requestId: request.requestId, + subscriptionId: "default-subscription", + slot: 2, + error: null, + }, + }), + ); + await observation.ready; + const data = new TextEncoder().encode("\x1b[31mretained 界🙂\x1b[0m"); + const metadata = { rows: 24, cols: 80, retainedHistoryLines: 1000 }; + if (chunked) { + await sender.send( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.ReplayBegin, + slot: 2, + payload: JSON.stringify(metadata), + }), + ); + await sender.send( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.ReplayData, + slot: 2, + payload: data, + }), + ); + await sender.send( + encodeTerminalStreamFrame({ opcode: TerminalStreamOpcode.ReplayEnd, slot: 2 }), + ); + } else { + // An ANSI-era host selects its existing Restore path for this explicit request. + await sender.send( + encodeTerminalStreamFrame({ opcode: TerminalStreamOpcode.Restore, slot: 2, payload: data }), + ); + } + if (transportChunked) { + expect(wire.length).toBeGreaterThan(chunked ? 3 : 1); + expect(wire.some((frame) => frame[0] === 0x31)).toBe(true); + expect(wire.every((frame) => frame.length <= 17)).toBe(true); + } else { + expect(wire.map((frame) => frame[0])).toEqual(chunked ? [6, 7, 8] : [5]); + } + expect(events).toEqual([ + { + terminalId: "default-terminal", + subscriptionId: "default-subscription", + type: "replay", + replay: chunked ? { type: "begin", ...metadata } : { type: "begin" }, + }, + { + terminalId: "default-terminal", + subscriptionId: "default-subscription", + type: "replay", + replay: { type: "data", data }, + }, + { + terminalId: "default-terminal", + subscriptionId: "default-subscription", + type: "replay", + replay: { type: "end" }, + }, + ]); + const live = new TextEncoder().encode("live after replay 界🙂"); + await sender.send( + encodeTerminalStreamFrame({ opcode: TerminalStreamOpcode.Output, slot: 2, payload: live }), + ); + expect(events.at(-1)).toEqual({ + terminalId: "default-terminal", + subscriptionId: "default-subscription", + type: "output", + data: live, + }); + }, +); + test("uses the frame budget selected by an asynchronously opened transport", async () => { const mock = createMockTransport(); mock.transport.maxFrameBytes = 1024; diff --git a/packages/client/src/daemon-client.ts b/packages/client/src/daemon-client.ts index 9152159f1c..3aa91f84c7 100644 --- a/packages/client/src/daemon-client.ts +++ b/packages/client/src/daemon-client.ts @@ -6460,7 +6460,8 @@ export class DaemonClient { } /** - * Snapshot/restore and output arrive in receive. Subscribe to the returned handle + * Defaults to a full ANSI replay. Replay begin/data/end and live output arrive in receive. + * Subscribe to the returned handle * for terminal_stream_exit: payload.error means observation failure, not PTY exit. * Either outcome detaches this slot and releases the handle automatically. */ @@ -6479,7 +6480,7 @@ export class DaemonClient { { type: "subscribe_terminal_request", terminalId, - ...(options?.restore ? { restore: options.restore } : {}), + restore: options?.restore ?? { mode: "full-snapshot" }, }, options, ); diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index 1437068f95..3655b0023a 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -1,3 +1,4 @@ +export type { TerminalReplayEvent, TerminalStreamEvent } from "./terminal-stream-router.js"; import type { AgentAddress } from "@getpaseo/protocol/addresses"; import { parentAddressLabels } from "@getpaseo/protocol/agent-labels"; export type { AgentAddress } from "@getpaseo/protocol/addresses"; diff --git a/packages/client/src/terminal-stream-router.test.ts b/packages/client/src/terminal-stream-router.test.ts index 7b9e598410..b8ed727117 100644 --- a/packages/client/src/terminal-stream-router.test.ts +++ b/packages/client/src/terminal-stream-router.test.ts @@ -4,7 +4,7 @@ import { describe, expect, test } from "vitest"; import { TerminalStreamRouter, type TerminalStreamEvent } from "./terminal-stream-router.js"; describe("terminal-stream-router", () => { - test("routes restore frames as restore events", () => { + test("normalizes old ANSI restore into the replay lifecycle", () => { const router = new TerminalStreamRouter(); const events: TerminalStreamEvent[] = []; const payload = new TextEncoder().encode("restored screen"); @@ -16,14 +16,14 @@ describe("terminal-stream-router", () => { payload, }); - expect(events).toEqual([ - { + expect(events).toEqual( + ["begin", "data", "end"].map((type) => ({ terminalId: "term-1", subscriptionId: "subscription-1", - type: "restore", - data: payload, - }, - ]); + type: "replay", + replay: type === "data" ? { type, data: payload } : { type }, + })), + ); }); }); @@ -61,3 +61,45 @@ test("legacy listeners share a terminal slot without releasing each other", () = router.handleFrame(frame); expect(received).toEqual(["first", "second", "second"]); }); + +test("streams chunks without joining and ignores released slots during replay", () => { + const router = new TerminalStreamRouter(); + const events: TerminalStreamEvent[] = []; + const release = router.attach("old", "terminal", 4, (event) => events.push(event)); + const payload = new TextEncoder().encode( + JSON.stringify({ rows: 24, cols: 80, retainedHistoryLines: 1000 }), + ); + router.handleFrame({ opcode: TerminalStreamOpcode.ReplayBegin, slot: 4, payload }); + const data = new TextEncoder().encode("\x1b[31m界🙂"); + router.handleFrame({ + opcode: TerminalStreamOpcode.ReplayData, + slot: 4, + payload: data.subarray(0, 7), + }); + release(); + router.attach("new", "terminal", 5, (event) => events.push(event)); + router.handleFrame({ + opcode: TerminalStreamOpcode.ReplayData, + slot: 4, + payload: data.subarray(7), + }); + router.handleFrame({ + opcode: TerminalStreamOpcode.ReplayEnd, + slot: 4, + payload: new Uint8Array(), + }); + expect(events).toHaveLength(2); + expect(events[1]).toMatchObject({ + subscriptionId: "old", + type: "replay", + replay: { type: "data", data: data.subarray(0, 7) }, + }); + router.handleFrame({ opcode: TerminalStreamOpcode.ReplayBegin, slot: 5, payload }); + router.handleFrame({ opcode: TerminalStreamOpcode.ReplayData, slot: 5, payload: data }); + router.handleFrame({ + opcode: TerminalStreamOpcode.ReplayEnd, + slot: 5, + payload: new Uint8Array(), + }); + expect(events.slice(2).map((event) => event.subscriptionId)).toEqual(["new", "new", "new"]); +}); diff --git a/packages/client/src/terminal-stream-router.ts b/packages/client/src/terminal-stream-router.ts index a2c9575450..bca9fb3ea1 100644 --- a/packages/client/src/terminal-stream-router.ts +++ b/packages/client/src/terminal-stream-router.ts @@ -1,14 +1,17 @@ import { - decodeTerminalSnapshotPayload, TerminalStreamOpcode, + TerminalReplayMetadataSchema, type TerminalStreamFrame, } from "@getpaseo/protocol/binary-frames/index"; -import type { TerminalState } from "@getpaseo/protocol/messages"; + +export type TerminalReplayEvent = + | { type: "begin"; rows?: number; cols?: number; retainedHistoryLines?: number } + | { type: "data"; data: Uint8Array } + | { type: "end" }; export type TerminalStreamEvent = { terminalId: string; subscriptionId: string } & ( | { type: "output"; data: Uint8Array } - | { type: "snapshot"; state: TerminalState } - | { type: "restore"; data: Uint8Array } + | { type: "replay"; replay: TerminalReplayEvent } ); export class TerminalStreamRouter { @@ -61,20 +64,42 @@ export class TerminalStreamRouter { let event: TerminalStreamEvent; if (frame.opcode === TerminalStreamOpcode.Output) event = { ...identity, type: "output", data: frame.payload }; - else if (frame.opcode === TerminalStreamOpcode.Restore) - event = { ...identity, type: "restore", data: frame.payload }; - else if (frame.opcode === TerminalStreamOpcode.Snapshot) { - const state = decodeTerminalSnapshotPayload(frame.payload); - if (!state) return; - event = { ...identity, type: "snapshot", state }; - } else return; - registration.receive(event); - for (const listener of this.listeners) { + else if (frame.opcode === TerminalStreamOpcode.Restore) { + // COMPAT(terminalSingleRestore): added after v0.14.0; remove when ANSI host floor supports chunked replay after 2027-04-30. + for (const replay of [ + { type: "begin" }, + { type: "data", data: frame.payload }, + { type: "end" }, + ] as TerminalReplayEvent[]) + this.deliver(registration.receive, { ...identity, type: "replay", replay }); + continue; + } else if (frame.opcode === TerminalStreamOpcode.ReplayBegin) { + let raw: unknown; try { - listener(event); + raw = JSON.parse(new TextDecoder().decode(frame.payload)); } catch { - /* Passive diagnostics cannot interrupt delivery. */ + return; } + const parsed = TerminalReplayMetadataSchema.safeParse(raw); + if (!parsed.success) return; + const metadata = parsed.data; + event = { ...identity, type: "replay", replay: { type: "begin", ...metadata } }; + } else if (frame.opcode === TerminalStreamOpcode.ReplayData) + event = { ...identity, type: "replay", replay: { type: "data", data: frame.payload } }; + else if (frame.opcode === TerminalStreamOpcode.ReplayEnd) + event = { ...identity, type: "replay", replay: { type: "end" } }; + else return; + this.deliver(registration.receive, event); + } + } + + private deliver(receive: (event: TerminalStreamEvent) => void, event: TerminalStreamEvent): void { + receive(event); + for (const listener of this.listeners) { + try { + listener(event); + } catch { + /* Passive diagnostics cannot interrupt delivery. */ } } } diff --git a/packages/protocol/src/binary-frames/demux.test.ts b/packages/protocol/src/binary-frames/demux.test.ts index c56e417528..a350cfaf03 100644 --- a/packages/protocol/src/binary-frames/demux.test.ts +++ b/packages/protocol/src/binary-frames/demux.test.ts @@ -89,3 +89,18 @@ describe("host route binary framing", () => { ).toThrow("Invalid host route ID"); }); }); + +it.each([ + TerminalStreamOpcode.ReplayBegin, + TerminalStreamOpcode.ReplayData, + TerminalStreamOpcode.ReplayEnd, +])("decodes replay opcode %s directly and inside a host route", (opcode) => { + const payload = new TextEncoder().encode("界 replay"); + const bytes = encodeTerminalStreamFrame({ opcode, slot: 12, payload }); + const expected = { kind: "terminal", frame: { opcode, slot: 12, payload } }; + expect(decodeBinaryFrame(bytes)).toEqual(expected); + const routed = decodeBinaryFrame(encodeHostRouteFrame("host", bytes)); + expect(routed?.kind).toBe("host_route"); + if (routed?.kind !== "host_route") throw new Error("Missing host route"); + expect(decodeBinaryFrame(routed.frame.payload)).toEqual(expected); +}); diff --git a/packages/protocol/src/binary-frames/demux.ts b/packages/protocol/src/binary-frames/demux.ts index a8503b898f..c207026362 100644 --- a/packages/protocol/src/binary-frames/demux.ts +++ b/packages/protocol/src/binary-frames/demux.ts @@ -25,6 +25,9 @@ export function decodeBinaryFrame(bytes: Uint8Array): BinaryFrame | null { case TerminalStreamOpcode.Input: case TerminalStreamOpcode.Resize: case TerminalStreamOpcode.Snapshot: + case TerminalStreamOpcode.ReplayBegin: + case TerminalStreamOpcode.ReplayData: + case TerminalStreamOpcode.ReplayEnd: case TerminalStreamOpcode.Restore: { const frame = decodeTerminalStreamFrame(bytes); return frame ? { kind: "terminal", frame } : null; diff --git a/packages/protocol/src/binary-frames/terminal.ts b/packages/protocol/src/binary-frames/terminal.ts index 3936502c89..b74ea7a8de 100644 --- a/packages/protocol/src/binary-frames/terminal.ts +++ b/packages/protocol/src/binary-frames/terminal.ts @@ -1,6 +1,12 @@ import { z } from "zod"; import { TerminalStateSchema } from "../messages.js"; +export const TerminalReplayMetadataSchema = z.object({ + rows: z.number().int().positive(), + cols: z.number().int().positive(), + retainedHistoryLines: z.number().int().nonnegative(), +}); + export const TerminalStreamResizeSchema = z.object({ rows: z.number().int().positive(), cols: z.number().int().positive(), @@ -13,6 +19,9 @@ export const TerminalStreamOpcode = { Resize: 0x03, Snapshot: 0x04, Restore: 0x05, + ReplayBegin: 0x06, + ReplayData: 0x07, + ReplayEnd: 0x08, } as const; export type TerminalStreamOpcode = (typeof TerminalStreamOpcode)[keyof typeof TerminalStreamOpcode]; @@ -58,6 +67,9 @@ function isTerminalStreamOpcode(value: number): value is TerminalStreamOpcode { value === TerminalStreamOpcode.Input || value === TerminalStreamOpcode.Resize || value === TerminalStreamOpcode.Snapshot || + value === TerminalStreamOpcode.ReplayBegin || + value === TerminalStreamOpcode.ReplayData || + value === TerminalStreamOpcode.ReplayEnd || value === TerminalStreamOpcode.Restore ); } diff --git a/packages/protocol/src/client-capabilities.ts b/packages/protocol/src/client-capabilities.ts index 28ec8456cb..3ae02671e7 100644 --- a/packages/protocol/src/client-capabilities.ts +++ b/packages/protocol/src/client-capabilities.ts @@ -1,4 +1,5 @@ export const CLIENT_CAPS = { + terminalChunkedReplay: "terminal_chunked_replay", binaryChunkingV1: "binary_chunking_v1", helloRejection: "hello_rejection", // COMPAT(ownedSubscriptions): added in v0.8.0, remove legacy ownership after 2027-03-09. diff --git a/packages/protocol/src/terminal-snapshot.test.ts b/packages/protocol/src/terminal-snapshot.test.ts deleted file mode 100644 index 96d82a9205..0000000000 --- a/packages/protocol/src/terminal-snapshot.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { describe, it, expect } from "vitest"; -import { renderTerminalSnapshotToAnsi } from "./terminal-snapshot"; -import type { TerminalState } from "./messages"; - -function cells(text: string): TerminalState["grid"][number] { - return [...text].map((char) => ({ char })); -} - -describe("renderTerminalSnapshotToAnsi", () => { - it("renders soft-wrapped rows as one contiguous logical line when wrap flags are present", () => { - // The server soft-wrapped one logical line "ABCDEFGHIJKLMNOP" at 10 cols into - // two grid rows. gridWrapped[0] = true marks row 0 as continuing into row 1. - const state: TerminalState = { - rows: 2, - cols: 10, - scrollback: [], - scrollbackWrapped: [], - grid: [cells("ABCDEFGHIJ"), cells("KLMNOP")], - gridWrapped: [true, false], - cursor: { row: 1, col: 6 }, - }; - - const ansi = renderTerminalSnapshotToAnsi(state); - - // The rows must arrive unbroken so xterm re-wraps them itself (and can later - // reflow them) — no hard newline injected between "...IJ" and "KL...". - expect(ansi).toContain("ABCDEFGHIJKLMNOP"); - // Auto-wrap must stay enabled; disabling it (ESC[?7l) is what makes xterm mark - // the rows non-wrapped and refuse to reflow them on resize. - expect(ansi).not.toContain("[?7l"); - }); - - it("falls back to verbatim per-row replay when wrap flags are absent (old daemon)", () => { - // No gridWrapped/scrollbackWrapped: the client cannot tell soft-wraps from hard - // newlines, so it must keep today's exact behaviour rather than guess. - const state: TerminalState = { - rows: 2, - cols: 10, - scrollback: [], - grid: [cells("ABCDEFGHIJ"), cells("KLMNOP")], - cursor: { row: 1, col: 6 }, - }; - - const ansi = renderTerminalSnapshotToAnsi(state); - - expect(ansi).toContain("[?7l"); - expect(ansi).toContain("ABCDEFGHIJ\r\nKLMNOP"); - }); -}); - -describe("renderTerminalSnapshotToAnsi wide chars", () => { - it("skips wide-char continuation cells so the glyph keeps its two columns", () => { - // The daemon captures "통" as the glyph followed by an empty continuation - // cell. Emitting anything for that cell pushes the rest of the row right. - const state: TerminalState = { - rows: 1, - cols: 10, - scrollback: [], - grid: [[{ char: "통" }, { char: "" }, { char: "합" }, { char: "" }, { char: "!" }]], - cursor: { row: 0, col: 5 }, - }; - - expect(renderTerminalSnapshotToAnsi(state)).toContain("통합!"); - }); - - it("replays snapshots from an old daemon verbatim, including its continuation spaces", () => { - // Old daemons already collapsed the continuation to " ". The serializer - // cannot tell that apart from a real space, so it must not guess. - const state: TerminalState = { - rows: 1, - cols: 10, - scrollback: [], - grid: [cells("통 합 !")], - cursor: { row: 0, col: 6 }, - }; - - expect(renderTerminalSnapshotToAnsi(state)).toContain("통 합 !"); - }); -}); diff --git a/packages/protocol/src/terminal-snapshot.ts b/packages/protocol/src/terminal-snapshot.ts deleted file mode 100644 index 1860067573..0000000000 --- a/packages/protocol/src/terminal-snapshot.ts +++ /dev/null @@ -1,224 +0,0 @@ -import type { TerminalCell, TerminalState } from "./messages.js"; - -interface TerminalStyle { - fg: number | undefined; - bg: number | undefined; - fgMode: number | undefined; - bgMode: number | undefined; - bold: boolean; - italic: boolean; - underline: boolean; - dim: boolean; - inverse: boolean; - strikethrough: boolean; -} - -const DEFAULT_STYLE: TerminalStyle = { - fg: undefined, - bg: undefined, - fgMode: undefined, - bgMode: undefined, - bold: false, - italic: false, - underline: false, - dim: false, - inverse: false, - strikethrough: false, -}; - -export function renderTerminalSnapshotToAnsi(state: TerminalState): string { - const rows = [...state.scrollback, ...state.grid]; - const wrapFlags = [...(state.scrollbackWrapped ?? []), ...(state.gridWrapped ?? [])]; - // Soft-wrapped lines can only be re-wrapped on resize when we know which rows - // were continuations. With that per-row flag we replay each logical line as one - // unbroken run (autowrap on) so xterm marks the continuations wrapped and reflows - // them. Without it (old daemon) we keep the verbatim per-row replay: autowrap off - // plus a hard newline per row. - const hasWrapInfo = wrapFlags.length === rows.length; - const lines: string[] = hasWrapInfo ? [] : ["\u001b[?7l"]; - - for (let rowIndex = 0; rowIndex < rows.length; rowIndex += 1) { - const row = rows[rowIndex] ?? []; - const continuesToNextRow = hasWrapInfo && wrapFlags[rowIndex] === true; - // A continuation row must fill the full width so the next row first cell - // triggers xterm auto-wrap, which is what marks the row wrapped/reflowable. - lines.push(renderTerminalRow(row, continuesToNextRow ? state.cols : undefined)); - if (rowIndex < rows.length - 1 && !continuesToNextRow) { - lines.push("\r\n"); - } - } - - lines.push("\u001b[0m"); - const cursorPresentationAnsi = renderCursorPresentationToAnsi(state.cursor); - if (cursorPresentationAnsi) { - lines.push(cursorPresentationAnsi); - } - lines.push(`\u001b[${state.cursor.row + 1};${state.cursor.col + 1}H`); - lines.push(state.cursor.hidden ? "\u001b[?25l" : "\u001b[?25h"); - if (!hasWrapInfo) { - lines.push("\u001b[?7h"); - } - return lines.join(""); -} - -function renderCursorPresentationToAnsi(cursor: TerminalState["cursor"]): string | null { - if (!cursor.style) { - return null; - } - - const cursorStyleCode = (() => { - if (cursor.style === "block") { - return cursor.blink === false ? 2 : 1; - } - if (cursor.style === "underline") { - return cursor.blink === false ? 4 : 3; - } - return cursor.blink === false ? 6 : 5; - })(); - - return `\u001b[${cursorStyleCode} q`; -} - -function renderTerminalRow(row: TerminalCell[], padToCols?: number): string { - const output: string[] = []; - const contentLength = getTerminalRowLength(row); - const length = padToCols !== undefined ? Math.max(contentLength, padToCols) : contentLength; - let previousStyle = DEFAULT_STYLE; - - for (let index = 0; index < length; index += 1) { - const cell = row[index] ?? { char: " " }; - // An empty char marks a wide-char continuation cell. The glyph in the - // previous cell already advances the cursor two columns, so emitting - // anything here would shift the rest of the row one column right. - if (cell.char === "") { - continue; - } - const nextStyle = getTerminalStyle(cell); - if (!terminalStylesEqual(previousStyle, nextStyle)) { - output.push(styleToAnsi(nextStyle)); - previousStyle = nextStyle; - } - output.push(cell.char || " "); - } - - if (!terminalStylesEqual(previousStyle, DEFAULT_STYLE)) { - output.push("\u001b[0m"); - } - - return output.join(""); -} - -function getTerminalRowLength(row: TerminalCell[]): number { - for (let index = row.length - 1; index >= 0; index -= 1) { - const cell = row[index]; - if (!cell) { - continue; - } - if (cell.char !== " ") { - return index + 1; - } - if ( - cell.fg !== undefined || - cell.bg !== undefined || - cell.fgMode !== undefined || - cell.bgMode !== undefined || - cell.bold || - cell.italic || - cell.underline || - cell.dim || - cell.inverse || - cell.strikethrough - ) { - return index + 1; - } - } - return 0; -} - -function getTerminalStyle(cell: TerminalCell): TerminalStyle { - return { - fg: cell.fg, - bg: cell.bg, - fgMode: cell.fgMode, - bgMode: cell.bgMode, - bold: Boolean(cell.bold), - italic: Boolean(cell.italic), - underline: Boolean(cell.underline), - dim: Boolean(cell.dim), - inverse: Boolean(cell.inverse), - strikethrough: Boolean(cell.strikethrough), - }; -} - -function terminalStylesEqual(left: TerminalStyle, right: TerminalStyle): boolean { - return ( - left.fg === right.fg && - left.bg === right.bg && - left.fgMode === right.fgMode && - left.bgMode === right.bgMode && - left.bold === right.bold && - left.italic === right.italic && - left.underline === right.underline && - left.dim === right.dim && - left.inverse === right.inverse && - left.strikethrough === right.strikethrough - ); -} - -function styleToAnsi(style: TerminalStyle): string { - const codes = ["0"]; - - if (style.bold) { - codes.push("1"); - } - if (style.dim) { - codes.push("2"); - } - if (style.italic) { - codes.push("3"); - } - if (style.underline) { - codes.push("4"); - } - if (style.inverse) { - codes.push("7"); - } - if (style.strikethrough) { - codes.push("9"); - } - - if (style.fg !== undefined && style.fgMode !== undefined) { - codes.push(...colorToSgr(style.fgMode, style.fg, false)); - } - - if (style.bg !== undefined && style.bgMode !== undefined) { - codes.push(...colorToSgr(style.bgMode, style.bg, true)); - } - - return `\u001b[${codes.join(";")}m`; -} - -function colorToSgr(mode: number, value: number, background: boolean): string[] { - if (mode === 1) { - if (value >= 8) { - return [String((background ? 100 : 90) + (value - 8))]; - } - return [String((background ? 40 : 30) + value)]; - } - - if (mode === 2) { - return [background ? "48" : "38", "5", String(value)]; - } - - if (mode === 3) { - return [ - background ? "48" : "38", - "2", - String((value >> 16) & 0xff), - String((value >> 8) & 0xff), - String(value & 0xff), - ]; - } - - return []; -} diff --git a/packages/server/package.json b/packages/server/package.json index a31ce8d02a..0fcbacaf24 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -116,6 +116,7 @@ "@modelcontextprotocol/sdk": "1.29.0", "@opencode-ai/sdk": "1.14.46", "@opencode/client": "2.0.10", + "@xterm/addon-serialize": "0.14.0", "@xterm/headless": "^6.0.0", "ai": "5.0.78", "ajv": "^8.20.0", diff --git a/packages/server/src/server/agent/mcp-server.test.ts b/packages/server/src/server/agent/mcp-server.test.ts index 86ee383f73..ecf2d912a5 100644 --- a/packages/server/src/server/agent/mcp-server.test.ts +++ b/packages/server/src/server/agent/mcp-server.test.ts @@ -1493,7 +1493,6 @@ describe("terminal MCP tools", () => { id: "term-1", name: "daemon", cwd: process.cwd(), - getState: vi.fn().mockReturnValue({ scrollback: [], grid: [[]] }), }), captureTerminal, }); diff --git a/packages/server/src/server/daemon-e2e/terminal-byte-headless-parity.e2e.test.ts b/packages/server/src/server/daemon-e2e/terminal-byte-headless-parity.e2e.test.ts index 2b789788ad..ed00f6cd9a 100644 --- a/packages/server/src/server/daemon-e2e/terminal-byte-headless-parity.e2e.test.ts +++ b/packages/server/src/server/daemon-e2e/terminal-byte-headless-parity.e2e.test.ts @@ -7,7 +7,6 @@ import { Terminal as HeadlessTerminal, type IBufferCell, type IBufferLine } from import { expect, test } from "vitest"; import type { TerminalCell, TerminalState } from "@getpaseo/protocol/messages"; -import { renderTerminalSnapshotToAnsi } from "@getpaseo/protocol/terminal-snapshot"; import type { TerminalStreamEvent } from "@getpaseo/client/internal/daemon-client"; import { DaemonClient } from "../test-utils/daemon-client.js"; import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js"; @@ -46,7 +45,7 @@ test("byte-stream headless terminal matches daemon state after high-output attac terminalId: terminal.id, headless: liveHeadless, }); - const initialSnapshot = waitForTerminalStreamEvent(client, terminal.id, "snapshot"); + const initialSnapshot = waitForReplayEnd(client, terminal.id); const liveSubscription = await subscribeTerminal(client, terminal.id); await initialSnapshot; @@ -60,13 +59,13 @@ test("byte-stream headless terminal matches daemon state after high-output attac text: BYTE_DONE_MARKER, rows: BYTE_TEST_SIZE.rows, }); - const daemonSnapshot = await readTerminalSnapshot({ + const daemonSnapshot = await readReplayViewport({ port: daemon.port, terminalId: terminal.id, }); await liveHeadless.flush(); - expect(liveHeadless.visibleLines()).toEqual(visibleTerminalLines(daemonSnapshot)); + expect(liveHeadless.visibleLines()).toEqual(daemonSnapshot.lines); expect(liveHeadless.cursor()).toEqual(daemonSnapshot.cursor); expect(liveHeadless.visibleLines()).toEqual(capturedViewport.lines); @@ -79,7 +78,7 @@ test("byte-stream headless terminal matches daemon state after high-output attac terminalId: terminal.id, headless: restoreHeadless, }); - const restoreFrame = waitForTerminalStreamEvent(client, terminal.id, "restore"); + const restoreFrame = waitForReplayEnd(client, terminal.id); await subscribeTerminal(client, terminal.id, { restore: { mode: "visible-snapshot", scrollbackLines: 200, size: BYTE_TEST_SIZE }, @@ -116,12 +115,10 @@ class ClientHeadlessTerminal { } applyEvent(event: TerminalStreamEvent): void { - if (event.type === "snapshot") { - this.enqueueText(renderTerminalSnapshotToAnsi(event.state), { resetDecoder: true }); - return; - } - if (event.type === "restore") { - this.enqueueText(this.decoder.decode(event.data, { stream: false }), { resetDecoder: true }); + if (event.type === "replay") { + if (event.replay.type === "begin") this.enqueueText("\x1bc", { resetDecoder: true }); + if (event.replay.type === "data") + this.enqueueText(this.decoder.decode(event.replay.data, { stream: true })); return; } this.enqueueText(this.decoder.decode(event.data, { stream: true })); @@ -187,35 +184,32 @@ async function subscribeTerminal( return response.subscription; } -async function readTerminalSnapshot(input: { - port: number; - terminalId: string; -}): Promise { - const client = new DaemonClient({ - url: `ws://127.0.0.1:${input.port}/ws`, - appVersion: "0.1.96", - clientType: "mobile", - }); +async function readReplayViewport(input: { port: number; terminalId: string }): Promise<{ + lines: string[]; + cursor: TerminalState["cursor"]; +}> { + const client = new DaemonClient({ url: `ws://127.0.0.1:${input.port}/ws`, clientType: "mobile" }); + const headless = new ClientHeadlessTerminal(BYTE_TEST_SIZE); + const stop = pipeTerminalStreamToHeadless({ client, terminalId: input.terminalId, headless }); try { await client.connect(); - const snapshot = waitForTerminalStreamEvent(client, input.terminalId, "snapshot"); + const completed = waitForReplayEnd(client, input.terminalId); await subscribeTerminal(client, input.terminalId); - const event = await snapshot; - return event.state; + await completed; + await headless.flush(); + return { lines: headless.visibleLines(), cursor: headless.cursor() }; } finally { + stop(); await client.close(); } } -function waitForTerminalStreamEvent( - client: DaemonClient, - terminalId: string, - type: TType, -): Promise> { - return client.waitForTerminalStreamEvent( - (event) => event.terminalId === terminalId && event.type === type, - 10_000, - ) as Promise>; +async function waitForReplayEnd(client: DaemonClient, terminalId: string): Promise { + await client.waitForTerminalStreamEvent( + (event) => + event.terminalId === terminalId && event.type === "replay" && event.replay.type === "end", + 10000, + ); } async function createPackageLockTerminalCwd(): Promise { @@ -287,24 +281,16 @@ async function waitForCondition( throw new Error(`Timed out after ${timeoutMs}ms waiting for terminal byte parity`); } -function visibleTerminalLines(state: TerminalState): string[] { - return state.grid.map(terminalRowText); -} - -function terminalRowText(row: TerminalState["grid"][number]): string { - return row - .map((cell) => cell.char) - .join("") - .trimEnd(); -} - function bufferLineText(line: IBufferLine | undefined, reusableCell: IBufferCell): string { const cells: TerminalCell[] = []; for (let col = 0; col < BYTE_TEST_SIZE.cols; col += 1) { const cell = line?.getCell(col, reusableCell); cells.push({ char: cell?.getChars() || " " }); } - return terminalRowText(cells); + return cells + .map((cell) => cell.char) + .join("") + .trimEnd(); } function packageLockStreamScript(): string { diff --git a/packages/server/src/server/daemon-e2e/terminal.e2e.test.ts b/packages/server/src/server/daemon-e2e/terminal.e2e.test.ts index 3c131ecab3..36425ffeec 100644 --- a/packages/server/src/server/daemon-e2e/terminal.e2e.test.ts +++ b/packages/server/src/server/daemon-e2e/terminal.e2e.test.ts @@ -1,3 +1,4 @@ +import { Terminal as HeadlessTerminal } from "@xterm/headless"; import { afterEach, beforeEach, describe, expect, test } from "vitest"; import { mkdtempSync, rmSync } from "fs"; import { tmpdir } from "os"; @@ -10,7 +11,6 @@ import { type WSOutboundMessage, } from "@getpaseo/protocol/messages"; import { - decodeTerminalSnapshotPayload, decodeTerminalStreamFrame, encodeTerminalStreamFrame, TerminalStreamOpcode, @@ -80,6 +80,24 @@ async function waitForCondition( throw new Error(`Timed out after ${timeoutMs}ms waiting for condition`); } +function readHeadlessState(terminal: HeadlessTerminal): TerminalState { + const buffer = terminal.buffer.active; + const lines: TerminalState["grid"] = []; + for (let row = 0; row < buffer.length; row++) { + const cells: TerminalState["grid"][number] = []; + for (let col = 0; col < terminal.cols; col++) + cells.push({ char: buffer.getLine(row)?.getCell(col)?.getChars() ?? "" }); + lines.push(cells); + } + return { + rows: terminal.rows, + cols: terminal.cols, + grid: lines.slice(buffer.baseY), + scrollback: lines.slice(0, buffer.baseY), + cursor: { row: buffer.cursorY, col: buffer.cursorX }, + }; +} + async function waitForTerminalSnapshot( client: DaemonClient, terminalId: string, @@ -92,16 +110,34 @@ async function waitForTerminalSnapshot( reject(new Error(`Timeout waiting for terminal snapshot (${timeout}ms)`)); }, timeout); + let terminal: HeadlessTerminal | null = null; + let writes = Promise.resolve(); const unsubscribe = client.onTerminalStreamEvent((event) => { - if (event.terminalId !== terminalId || event.type !== "snapshot") { - return; + if (event.terminalId !== terminalId || event.type !== "replay") return; + const replay = event.replay; + if (replay.type === "begin") { + terminal?.dispose(); + terminal = new HeadlessTerminal({ + rows: replay.rows ?? 24, + cols: replay.cols ?? 80, + scrollback: 1000, + allowProposedApi: true, + }); + } else if (replay.type === "data") { + const active = terminal!; + writes = writes.then(() => new Promise((done) => active.write(replay.data, done))); + } else { + void writes.then(() => { + const active = terminal!; + const state = readHeadlessState(active); + if (!predicate(state)) return null; + clearTimeout(timeoutHandle); + unsubscribe(); + active.dispose(); + resolve(state); + return null; + }); } - if (!predicate(event.state)) { - return; - } - clearTimeout(timeoutHandle); - unsubscribe(); - resolve(event.state); }); }); } @@ -160,7 +196,7 @@ function toWsBuffer(raw: WebSocket.RawData): Buffer | null { return null; } -async function connectRawWebSocket(port: number): Promise { +async function connectRawWebSocket(port: number, chunkedReplay = false): Promise { const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`); await new Promise((resolve, reject) => { ws.once("open", () => resolve()); @@ -180,6 +216,7 @@ async function connectRawWebSocket(port: number): Promise { clientId: `terminal-raw-${Date.now()}-${Math.random().toString(36).slice(2)}`, clientType: "cli", protocolVersion: 1, + capabilities: { terminal_chunked_replay: chunkedReplay }, }), ); @@ -386,17 +423,24 @@ async function collectRawBinaryFrames( }); } +async function decodeRestoreState( + frame: TerminalStreamFrame, + terminalId: string, +): Promise { + const size = ctx.daemon.daemon.terminalManager!.getTerminal(terminalId)!.getSize(); + const terminal = new HeadlessTerminal({ ...size, scrollback: 1000, allowProposedApi: true }); + try { + await new Promise((resolve) => terminal.write(frame.payload, resolve)); + return readHeadlessState(terminal); + } finally { + terminal.dispose(); + } +} + function getFrameText(frame: TerminalStreamFrame): string { if (frame.opcode === TerminalStreamOpcode.Output) { return new TextDecoder().decode(frame.payload); } - if (frame.opcode === TerminalStreamOpcode.Snapshot) { - const state = decodeTerminalSnapshotPayload(frame.payload); - if (!state) { - return ""; - } - return extractStateText(state); - } if (frame.opcode === TerminalStreamOpcode.Restore) { return new TextDecoder().decode(frame.payload); } @@ -446,7 +490,10 @@ function startTerminalOutputCapture(ws: WebSocket, slot: number): TerminalOutput if (!frame || frame.slot !== slot) { return; } - if (frame.opcode === TerminalStreamOpcode.Snapshot) { + if ( + frame.opcode === TerminalStreamOpcode.Restore || + frame.opcode === TerminalStreamOpcode.ReplayEnd + ) { snapshotCount += 1; return; } @@ -634,7 +681,7 @@ async function measureRepeatCadenceForTerminal(input: { const slot = await subscribeRawTerminal(ws, terminalId, `sub-repeat-cadence-${input.name}`); await waitForRawBinaryFrame( ws, - (frame) => frame.slot === slot && frame.opcode === TerminalStreamOpcode.Snapshot, + (frame) => frame.slot === slot && frame.opcode === TerminalStreamOpcode.Restore, 10000, ); await new Promise((resolve) => setTimeout(resolve, 1000)); @@ -817,13 +864,7 @@ test("live terminal restore skips the initial snapshot", async () => { expect(outputText).toContain("after-live"); expect(outputText).not.toContain("before-live"); - expect( - outputFrames.some( - (frame) => - frame.opcode === TerminalStreamOpcode.Snapshot || - frame.opcode === TerminalStreamOpcode.Restore, - ), - ).toBe(false); + expect(outputFrames.some((frame) => frame.opcode === TerminalStreamOpcode.Restore)).toBe(false); } finally { await closeWebSocket(ws); } @@ -901,15 +942,12 @@ test("propagates debounced terminal titles through list responses and snapshots" } expect(listedTitle).toBe("Build Output"); - const snapshotPromise = waitForTerminalSnapshot( - ctx.client, - terminalId, - (state) => state.title === "Build Output", + const attached = await ctx.client.subscribeTerminal(terminalId); + expect(attached.error).toBeNull(); + const afterAttach = await ctx.client.listTerminals(cwd); + expect(afterAttach.terminals.find((terminal) => terminal.id === terminalId)?.title).toBe( + "Build Output", ); - await ctx.client.subscribeTerminal(terminalId); - const snapshot = await snapshotPromise; - - expect(snapshot.title).toBe("Build Output"); rmSync(cwd, { recursive: true, force: true }); }, 30000); @@ -973,13 +1011,10 @@ test("subscribe response is sent before the initial snapshot frame", async () => return; } const frame = decodeTerminalStreamFrame(new Uint8Array(buffer)); - if (frame?.opcode !== TerminalStreamOpcode.Snapshot) { - return; - } - const state = decodeTerminalSnapshotPayload(frame.payload); - if (!state || !extractStateText(state).includes("hello-ordering")) { + if (frame?.opcode !== TerminalStreamOpcode.Restore) { return; } + if (!getFrameText(frame).includes("hello-ordering")) return; events.push("snapshot"); maybeResolve(); }; @@ -1113,7 +1148,7 @@ test("reconnected terminal streams replay active input modes after the snapshot" const firstSlot = await subscribeRawTerminal(firstWs, terminalId, "sub-input-mode-first"); await waitForRawBinaryFrame( firstWs, - (frame) => frame.slot === firstSlot && frame.opcode === TerminalStreamOpcode.Snapshot, + (frame) => frame.slot === firstSlot && frame.opcode === TerminalStreamOpcode.Restore, ); sendRawTerminalInput(firstWs, firstSlot, "e"); await waitForRawBinaryFrame( @@ -1140,7 +1175,7 @@ test("reconnected terminal streams replay active input modes after the snapshot" const secondSlot = await subscribeRawTerminal(secondWs, terminalId, "sub-input-mode-second"); await waitForRawBinaryFrame( secondWs, - (frame) => frame.slot === secondSlot && frame.opcode === TerminalStreamOpcode.Snapshot, + (frame) => frame.slot === secondSlot && frame.opcode === TerminalStreamOpcode.Restore, ); const replay = await waitForRawBinaryFrame( secondWs, @@ -1172,7 +1207,7 @@ test("reconnected terminal streams do not replay input modes before they are ena const slot = await subscribeRawTerminal(ws, terminalId, "sub-input-mode-inactive"); await waitForRawBinaryFrame( ws, - (frame) => frame.slot === slot && frame.opcode === TerminalStreamOpcode.Snapshot, + (frame) => frame.slot === slot && frame.opcode === TerminalStreamOpcode.Restore, ); await waitForNoRawBinaryFrame(ws, 300); } finally { @@ -1188,7 +1223,7 @@ test("fast output to a slow websocket client falls back to a snapshot", async () const ws = await connectRawWebSocket(ctx.daemon.port); await subscribeRawTerminal(ws, terminalId, "sub-raw"); - await waitForRawBinaryFrame(ws, (frame) => frame.opcode === TerminalStreamOpcode.Snapshot, 10000); + await waitForRawBinaryFrame(ws, (frame) => frame.opcode === TerminalStreamOpcode.Restore, 10000); const rawSocket = (ws as WebSocket & { _socket?: { pause: () => void; resume: () => void } }) ._socket; @@ -1203,12 +1238,12 @@ test("fast output to a slow websocket client falls back to a snapshot", async () await new Promise((resolve) => setTimeout(resolve, 750)); const catchUpFramePromise = waitForRawBinaryFrame( ws, - (frame) => frame.opcode === TerminalStreamOpcode.Snapshot, + (frame) => frame.opcode === TerminalStreamOpcode.Restore, 15000, ); rawSocket!.resume(); const catchUpFrame = await catchUpFramePromise; - expect(catchUpFrame.opcode).toBe(TerminalStreamOpcode.Snapshot); + expect(catchUpFrame.opcode).toBe(TerminalStreamOpcode.Restore); await closeWebSocket(ws); rmSync(cwd, { recursive: true, force: true }); @@ -1260,7 +1295,7 @@ test("resize updates server dimensions without sending a live snapshot", async ( await new Promise((resolve) => setTimeout(resolve, 300)); - const state = ctx.daemon.daemon.terminalManager?.getTerminal(terminalId)?.getState(); + const state = ctx.daemon.daemon.terminalManager?.getTerminal(terminalId)?.getSize(); expect(state?.rows).toBe(10); expect(state?.cols).toBe(40); @@ -1277,7 +1312,7 @@ test("the latest resize from any attached client owns the PTY size", async () => ); const readSize = () => { - const state = ctx.daemon.daemon.terminalManager?.getTerminal(terminalId)?.getState(); + const state = ctx.daemon.daemon.terminalManager?.getTerminal(terminalId)?.getSize(); return state ? { rows: state.rows, cols: state.cols } : null; }; const expectSize = async (size: { rows: number; cols: number }) => { @@ -1403,10 +1438,10 @@ test("websocket terminate then new connection gets snapshot with all prior outpu await subscribeRawTerminal(firstSocket, terminalId, "sub-drop-a"); const initialSnapshot = await waitForRawBinaryFrame( firstSocket, - (frame) => frame.opcode === TerminalStreamOpcode.Snapshot, + (frame) => frame.opcode === TerminalStreamOpcode.Restore, 10000, ); - expect(initialSnapshot.opcode).toBe(TerminalStreamOpcode.Snapshot); + expect(initialSnapshot.opcode).toBe(TerminalStreamOpcode.Restore); ctx.client.sendTerminalInput(terminalId, { type: "input", @@ -1442,9 +1477,9 @@ test("websocket terminate then new connection gets snapshot with all prior outpu try { await subscribeRawTerminal(secondSocket, terminalId, "sub-drop-b"); const reconnectFrame = await waitForRawBinaryFrame(secondSocket, () => true, 10000); - expect(reconnectFrame.opcode).toBe(TerminalStreamOpcode.Snapshot); + expect(reconnectFrame.opcode).toBe(TerminalStreamOpcode.Restore); - const state = decodeTerminalSnapshotPayload(reconnectFrame.payload); + const state = await decodeRestoreState(reconnectFrame, terminalId); expect(state).not.toBeNull(); expect(extractStateText(state!)).toContain("before-drop"); expect(extractStateText(state!)).toContain("while-dead"); @@ -1513,11 +1548,11 @@ test("snapshot fidelity through websocket decode preserves dimensions and visibl await subscribeRawTerminal(ws, terminalId, "sub-fidelity"); const snapshotFrame = await waitForRawBinaryFrame( ws, - (frame) => frame.opcode === TerminalStreamOpcode.Snapshot, + (frame) => frame.opcode === TerminalStreamOpcode.Restore, 10000, ); - const state = decodeTerminalSnapshotPayload(snapshotFrame.payload); + const state = await decodeRestoreState(snapshotFrame, terminalId); expect(state).not.toBeNull(); expect(state).toMatchObject({ rows: 24, @@ -1545,7 +1580,7 @@ test("terminal exit prevents resubscribe and sends no frames after exit", async await subscribeRawTerminal(ws, terminalId, "sub-exit"); await waitForRawBinaryFrame( ws, - (frame) => frame.opcode === TerminalStreamOpcode.Snapshot, + (frame) => frame.opcode === TerminalStreamOpcode.Restore, 10000, ); @@ -1561,8 +1596,7 @@ test("terminal exit prevents resubscribe and sends no frames after exit", async const exitMessage = await exitMessagePromise; expect(exitMessage.message.type).toBe("terminal_stream_exit"); - const subscribeResult = await ctx.client.subscribeTerminal(terminalId); - expect(subscribeResult.error).toBe("Terminal not found"); + await expect(ctx.client.subscribeTerminal(terminalId)).rejects.toThrow("Terminal not found"); await waitForNoRawBinaryFrame(ws, 750); } finally { await closeWebSocket(ws); @@ -1580,7 +1614,7 @@ test("empty input frame does not crash the server", async () => { const slot = await subscribeRawTerminal(ws, terminalId, "sub-empty-input"); await waitForRawBinaryFrame( ws, - (frame) => frame.opcode === TerminalStreamOpcode.Snapshot, + (frame) => frame.opcode === TerminalStreamOpcode.Restore, 10000, ); @@ -1619,7 +1653,7 @@ test("1MB output burst keeps frames decodable and terminal usable afterward", as await subscribeRawTerminal(ws, terminalId, "sub-large-output"); await waitForRawBinaryFrame( ws, - (frame) => frame.opcode === TerminalStreamOpcode.Snapshot, + (frame) => frame.opcode === TerminalStreamOpcode.Restore, 10000, ); @@ -1636,7 +1670,7 @@ test("1MB output burst keeps frames decodable and terminal usable afterward", as .reduce((sum, frame) => sum + frame.payload.byteLength, 0); return ( outputBytes >= 1024 * 1024 || - collectedFrames.some((frame) => frame.opcode === TerminalStreamOpcode.Snapshot) + collectedFrames.some((frame) => frame.opcode === TerminalStreamOpcode.Restore) ); }, 20000, @@ -1646,7 +1680,7 @@ test("1MB output burst keeps frames decodable and terminal usable afterward", as for (const frame of frames) { expect( frame.opcode === TerminalStreamOpcode.Output || - frame.opcode === TerminalStreamOpcode.Snapshot, + frame.opcode === TerminalStreamOpcode.Restore, ).toBe(true); } @@ -1837,18 +1871,149 @@ describe("list terminals across directories", () => { }); }); -test("a paused terminal consumer catches up through a snapshot instead of retaining every output frame", async () => { - const { existsSync } = await import("node:fs"); - const cwd = tmpCwd(); - tempDirs.push(cwd); - const marker = path.join(cwd, "output-complete"); - const created = await createTerminalInWorkspace(ctx.client, { - cwd, - options: { - command: process.execPath, - args: [ - "-e", - ` +test.each([3000, 12050])( + "chunked SDK replay retains requested history for %s printed lines", + async (count) => { + const cwd = tmpCwd(); + tempDirs.push(cwd); + const created = await createTerminalInWorkspace(ctx.client, { + cwd, + options: { + command: "/bin/sh", + args: [ + "-lc", + `i=1; while [ $i -le ${count} ]; do printf '\\033[31mreplay-%04d界🙂 payload-abcdefghijklmnopqrstuvwxyz0123456789\\033[0m\\n' $i; i=$((i+1)); done; sleep 30`, + ], + }, + }); + const id = created.terminal!.id; + await waitForCondition( + async () => + (await ctx.client.captureTerminal(id)).lines + .join("\n") + .includes(`replay-${String(count).padStart(4, "0")}`), + 10000, + ); + const events: import("@getpaseo/client").TerminalStreamEvent[] = []; + let end!: () => void; + const completed = new Promise((resolve) => { + end = resolve; + }); + const subscription = ctx.client.observeTerminal( + id, + (event) => { + events.push(event); + if (event.type === "replay" && event.replay.type === "end") end(); + }, + { restore: { mode: "visible-snapshot", scrollbackLines: 10000 } }, + ); + try { + await subscription.ready; + await completed; + const replay = events.flatMap((event) => (event.type === "replay" ? [event.replay] : [])); + expect(replay[0]).toMatchObject({ + type: "begin", + retainedHistoryLines: count === 12050 ? 10000 : expect.any(Number), + }); + expect(replay.at(-1)).toEqual({ type: "end" }); + const chunks = replay.flatMap((event) => (event.type === "data" ? [event.data] : [])); + expect(chunks.every((chunk) => chunk.length <= 65536)).toBe(true); + const text = Buffer.concat(chunks).toString("utf8"); + const begin = replay[0]; + if (begin?.type !== "begin" || begin.rows === undefined) + throw new Error("Missing replay dimensions"); + expect(text.match(/replay-\d{4,5}/g)).toHaveLength(Math.min(count, 10000 + begin.rows - 1)); + expect(text).toContain(`replay-${String(count).padStart(4, "0")}界🙂`); + if (count === 3000) expect(text).toContain("replay-0001界🙂"); + else { + expect(text).not.toContain("replay-0001"); + expect(chunks.length).toBeGreaterThan(1); + } + } finally { + await subscription.release(); + } + }, + 30000, +); + +test.each([false, true])( + "default SDK observation replays a terminal without waiting for output (quietScreen=%s)", + async (quietScreen) => { + const cwd = tmpCwd(); + tempDirs.push(cwd); + const created = await createTerminalInWorkspace(ctx.client, { + cwd, + options: { + command: process.execPath, + args: [ + "-e", + `${quietScreen ? 'process.stdout.write("QUIET-SCREEN\\r\\n");' : ""} process.stdin.on("data", data => process.stdout.write("LIVE:" + data)); setInterval(() => {}, 1000);`, + ], + }, + }); + const id = created.terminal!.id; + if (quietScreen) + await waitForCondition( + async () => (await ctx.client.captureTerminal(id)).lines.join("").includes("QUIET-SCREEN"), + 10000, + ); + const events: import("@getpaseo/client").TerminalStreamEvent[] = []; + const observation = ctx.client.observeTerminal(id, (event) => events.push(event)); + try { + await observation.ready; + await waitForCondition( + () => events.some((event) => event.type === "replay" && event.replay.type === "end"), + 10000, + ); + const replay = events.flatMap((event) => (event.type === "replay" ? [event.replay] : [])); + const begin = replay[0]; + if (begin?.type !== "begin" || !begin.rows || !begin.cols) + throw new Error("Missing replay begin geometry"); + expect(replay.at(-1)).toEqual({ type: "end" }); + const terminal = new HeadlessTerminal({ + rows: begin.rows, + cols: begin.cols, + allowProposedApi: true, + }); + try { + for (const event of replay) + if (event.type === "data") + await new Promise((resolve) => terminal.write(event.data, resolve)); + const text = extractStateText(readHeadlessState(terminal)); + expect(text).toBe(quietScreen ? "QUIET-SCREEN" : ""); + } finally { + terminal.dispose(); + } + ctx.client.sendTerminalInput(id, { type: "input", data: "next\r" }); + await waitForCondition( + () => + events.some( + (event) => + event.type === "output" && new TextDecoder().decode(event.data).includes("LIVE:next"), + ), + 10000, + ); + } finally { + await observation.release(); + } + }, + 30000, +); + +test.each([false, true])( + "a paused terminal consumer catches up through ANSI replay instead of retaining every output frame (chunked=%s)", + async (chunked) => { + const { existsSync } = await import("node:fs"); + const cwd = tmpCwd(); + tempDirs.push(cwd); + const marker = path.join(cwd, "output-complete"); + const created = await createTerminalInWorkspace(ctx.client, { + cwd, + options: { + command: process.execPath, + args: [ + "-e", + ` const fs = require('node:fs'); process.stdin.setRawMode?.(true); process.stdin.resume(); @@ -1862,32 +2027,37 @@ test("a paused terminal consumer catches up through a snapshot instead of retain write(); }); `, - ], - }, - }); - const ws = await connectRawWebSocket(ctx.daemon.port); - try { - const slot = await subscribeRawTerminal(ws, created.terminal!.id, "slow-terminal"); - await waitForRawBinaryFrame( - ws, - (frame) => frame.slot === slot && frame.opcode === TerminalStreamOpcode.Snapshot, - ); - const capture = startTerminalOutputCapture(ws, slot); + ], + }, + }); + const ws = await connectRawWebSocket(ctx.daemon.port, chunked); try { - ws.pause(); - sendRawTerminalInput(ws, slot, "go\n"); - await waitForCondition(() => existsSync(marker), 20000); - ws.resume(); - await waitForCondition(() => capture.snapshotCount > 0, 10000); - expect(ws.readyState).toBe(WebSocket.OPEN); - expect(capture.frames.reduce((total, frame) => total + frame.payloadBytes, 0)).toBeLessThan( - 32 * 1024 * 1024, + const slot = await subscribeRawTerminal(ws, created.terminal!.id, "slow-terminal"); + await waitForRawBinaryFrame( + ws, + (frame) => + frame.slot === slot && + frame.opcode === + (chunked ? TerminalStreamOpcode.ReplayEnd : TerminalStreamOpcode.Restore), ); + const capture = startTerminalOutputCapture(ws, slot); + try { + ws.pause(); + sendRawTerminalInput(ws, slot, "go\n"); + await waitForCondition(() => existsSync(marker), 20000); + ws.resume(); + await waitForCondition(() => capture.snapshotCount > 0, 10000); + expect(ws.readyState).toBe(WebSocket.OPEN); + expect(capture.frames.reduce((total, frame) => total + frame.payloadBytes, 0)).toBeLessThan( + 32 * 1024 * 1024, + ); + } finally { + ws.resume(); + capture.stop(); + } } finally { - ws.resume(); - capture.stop(); + await closeWebSocket(ws); } - } finally { - await closeWebSocket(ws); - } -}, 40000); + }, + 40000, +); diff --git a/packages/server/src/server/owned-subscriptions.e2e.test.ts b/packages/server/src/server/owned-subscriptions.e2e.test.ts index 2a3128ea9f..fc73e44db4 100644 --- a/packages/server/src/server/owned-subscriptions.e2e.test.ts +++ b/packages/server/src/server/owned-subscriptions.e2e.test.ts @@ -822,86 +822,100 @@ test("same-workspace terminal directory observers do not share a teardown slot", } }); -test("terminal output has separate server IDs and binary slots, including in a shared session", async () => { - const daemon = await createTestPaseoDaemon({ mcpEnabled: false }); - const admin = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws`, appVersion: "0.8.0" }); - const peers: SubscriptionPeer[] = []; - try { - await admin.connect(); - const workspace = ( - await admin.createWorkspace({ source: { kind: "directory", path: daemon.staticDir } }) - ).workspace!; - const result = await admin.createTerminal(daemon.staticDir, "Output ownership", undefined, { - workspaceId: workspace.id, - command: process.execPath, - args: ["-e", "process.stdin.on('data', data => process.stdout.write(data))"], +test.each([false, true])( + "terminal output has separate server IDs and binary slots, including in a shared session (chunked=%s)", + async (chunked) => { + const daemon = await createTestPaseoDaemon({ mcpEnabled: false }); + const admin = new DaemonClient({ + url: `ws://127.0.0.1:${daemon.port}/ws`, + appVersion: "0.8.0", }); - expect(result.error).toBe(null); - const idle = await SubscriptionPeer.connect(daemon.port, "terminal-output-session"); - peers.push(idle); - const peer = await SubscriptionPeer.connect(daemon.port, "terminal-output-session"); - peers.push(peer); - for (const requestId of ["output-a", "output-b"]) { - await peer.request({ - type: "subscribe_terminal_request", - requestId, - terminalId: result.terminal!.id, + const peers: SubscriptionPeer[] = []; + try { + await admin.connect(); + const workspace = ( + await admin.createWorkspace({ source: { kind: "directory", path: daemon.staticDir } }) + ).workspace!; + const result = await admin.createTerminal(daemon.staticDir, "Output ownership", undefined, { + workspaceId: workspace.id, + command: process.execPath, + args: ["-e", "process.stdin.on('data', data => process.stdout.write(data))"], }); - } - const replies = peer.frames.flatMap((frame) => - frame.type === "session" && - frame.message.type === "subscribe_terminal_response" && - frame.message.payload.error === null - ? [frame.message.payload] - : [], - ); - expect(replies).toHaveLength(2); - const ids = replies.map( - (reply) => (reply as typeof reply & { subscriptionId: string }).subscriptionId, - ); - expect(ids.every((id) => typeof id === "string")).toBe(true); - expect(ids[0]).not.toBe(ids[1]); - expect(replies[0].slot).not.toBe(replies[1].slot); - await expect - .poll(() => - peer.binaryFrames - .map(decodeTerminalStreamFrame) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.Snapshot) - .map((frame) => frame!.slot), - ) - .toEqual(expect.arrayContaining(replies.map((reply) => reply.slot))); - expect(idle.binaryFrames).toEqual([]); - await peer.request({ - type: "subscription.release.request", - requestId: "release-output-a", - subscriptionId: ids[0], - }); - peer.binaryFrames.length = 0; - admin.sendTerminalInput(result.terminal!.id, { type: "input", data: "remaining-observer\n" }); - await expect - .poll( - () => + expect(result.error).toBe(null); + const idle = await SubscriptionPeer.connect(daemon.port, "terminal-output-session", { + terminal_chunked_replay: chunked, + }); + peers.push(idle); + const peer = await SubscriptionPeer.connect(daemon.port, "terminal-output-session", { + terminal_chunked_replay: chunked, + }); + peers.push(peer); + for (const requestId of ["output-a", "output-b"]) { + await peer.request({ + type: "subscribe_terminal_request", + requestId, + terminalId: result.terminal!.id, + }); + } + const replies = peer.frames.flatMap((frame) => + frame.type === "session" && + frame.message.type === "subscribe_terminal_response" && + frame.message.payload.error === null + ? [frame.message.payload] + : [], + ); + expect(replies).toHaveLength(2); + const ids = replies.map( + (reply) => (reply as typeof reply & { subscriptionId: string }).subscriptionId, + ); + expect(ids.every((id) => typeof id === "string")).toBe(true); + expect(ids[0]).not.toBe(ids[1]); + expect(replies[0].slot).not.toBe(replies[1].slot); + await expect + .poll(() => peer.binaryFrames .map(decodeTerminalStreamFrame) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) - .map((frame) => Buffer.from(frame!.payload).toString()) - .join(""), - { timeout: 5000 }, - ) - .toContain("remaining-observer"); - expect( - peer.binaryFrames - .map(decodeTerminalStreamFrame) - .every((frame) => frame?.slot === replies[1].slot), - ).toBe(true); - expect(idle.binaryFrames).toEqual([]); - await admin.killTerminal(result.terminal!.id); - } finally { - for (const peer of peers) peer.close(); - await admin.close(); - await daemon.close(); - } -}); + .filter( + (frame) => + frame?.opcode === + (chunked ? TerminalStreamOpcode.ReplayEnd : TerminalStreamOpcode.Restore), + ) + .map((frame) => frame!.slot), + ) + .toEqual(expect.arrayContaining(replies.map((reply) => reply.slot))); + expect(idle.binaryFrames).toEqual([]); + await peer.request({ + type: "subscription.release.request", + requestId: "release-output-a", + subscriptionId: ids[0], + }); + peer.binaryFrames.length = 0; + admin.sendTerminalInput(result.terminal!.id, { type: "input", data: "remaining-observer\n" }); + await expect + .poll( + () => + peer.binaryFrames + .map(decodeTerminalStreamFrame) + .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) + .map((frame) => Buffer.from(frame!.payload).toString()) + .join(""), + { timeout: 5000 }, + ) + .toContain("remaining-observer"); + expect( + peer.binaryFrames + .map(decodeTerminalStreamFrame) + .every((frame) => frame?.slot === replies[1].slot), + ).toBe(true); + expect(idle.binaryFrames).toEqual([]); + await admin.killTerminal(result.terminal!.id); + } finally { + for (const peer of peers) peer.close(); + await admin.close(); + await daemon.close(); + } + }, +); test("a modern connection and pure reads retain no client observation producers", async () => { const daemon = await createTestPaseoDaemon({ mcpEnabled: false }); diff --git a/packages/server/src/server/script-health-monitor.test.ts b/packages/server/src/server/script-health-monitor.test.ts index 96af0133ca..c5e4904a9d 100644 --- a/packages/server/src/server/script-health-monitor.test.ts +++ b/packages/server/src/server/script-health-monitor.test.ts @@ -68,13 +68,7 @@ function createStubTerminalManager( subscribe: () => () => {}, onExit: () => () => {}, onCommandFinished: () => () => {}, - getState: () => ({ - rows: 1, - cols: 1, - grid: [[{ char: "$" }]], - scrollback: [], - cursor: { row: 0, col: 0 }, - }), + hasOutput: () => true, kill: () => {}, onTitleChange: () => () => {}, getSize: () => ({ rows: 1, cols: 1 }), diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index 09681de8ba..42c676b50b 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -1130,11 +1130,11 @@ export class Session { terminalManager, emit: (msg) => this.emit(msg), hasBinaryChannel: () => this.onBinaryMessage !== null, + supportsChunkedReplay: (source) => + this.supportsForSource(CLIENT_CAPS.terminalChunkedReplay, source), isPathWithinRoot: (rootPath, candidatePath) => this.isPathWithinRoot(rootPath, candidatePath), sessionLogger: this.sessionLogger, listTerminalWorkspaceRefs: () => this.listActiveWorkspaceRefs(), - clientSupportsWrapReflow: (source) => - this.supportsForSource(CLIENT_CAPS.terminalReflowableSnapshot, source), getClientBufferedAmount: (source) => this.getTransportBufferedAmount(source), }); this.agentDirectory = new AgentDirectory({ diff --git a/packages/server/src/server/test-fixtures/reconciliation-responsiveness.ts b/packages/server/src/server/test-fixtures/reconciliation-responsiveness.ts index 7df5414d2d..dd73ce38a8 100644 --- a/packages/server/src/server/test-fixtures/reconciliation-responsiveness.ts +++ b/packages/server/src/server/test-fixtures/reconciliation-responsiveness.ts @@ -1,3 +1,6 @@ +import assert from "node:assert/strict"; +import { createHook, executionAsyncResource } from "node:async_hooks"; +import { MessagePort } from "node:worker_threads"; import path from "node:path"; import { stat } from "node:fs/promises"; import { setImmediate as nextTurn } from "node:timers/promises"; @@ -57,19 +60,33 @@ const service = new WorkspaceReconciliationService({ // Initialize async filesystem support using the bundle, leaving every project // and workspace path untouched until the first reconciliation. await stat(process.argv[1]); +// Collect fixture allocations before the measured run; allocations made by +// reconciliation itself remain part of its budget. +assert.ok(global.gc, "Launch the probe with --expose-gc"); +global.gc(); await nextTurn(); +let workerMessages = 0; +const activity = createHook({ + before() { + if (executionAsyncResource() instanceof MessagePort) workerMessages++; + }, +}).enable(); try { const measured = await measureMainThreadWork("workspace reconciliation main-thread work", () => service.runOnce(), ); + activity.disable(); process.stdout.write( JSON.stringify({ blockingMs: measured.blockingMs, filesystemRequests: measured.filesystemRequests, + yields: measured.yields, + workerMessages, changesApplied: measured.result.changesApplied.length, allArchived: [...workspaces.values()].every((workspace) => workspace.archivedAt !== null), }), ); } finally { + activity.disable(); service.dispose(); } diff --git a/packages/server/src/server/workspace-reconciliation-service.test.ts b/packages/server/src/server/workspace-reconciliation-service.test.ts index 7ef187d16e..b818804912 100644 --- a/packages/server/src/server/workspace-reconciliation-service.test.ts +++ b/packages/server/src/server/workspace-reconciliation-service.test.ts @@ -1,15 +1,15 @@ import { execFile, execFileSync } from "node:child_process"; -import { promisify } from "node:util"; +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; import { build } from "esbuild"; import { createTestRegistries, createTestLogger, deferred, } from "./test-fixtures/reconciliation-registries.js"; -import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import path from "node:path"; import type { ProjectCheckoutLitePayload } from "@getpaseo/protocol/messages"; import type pino from "pino"; import { afterAll, beforeAll, afterEach, describe, expect, test } from "vitest"; @@ -535,30 +535,54 @@ describe("WorkspaceReconciliationService", () => { test("keeps the event loop responsive while inspecting 20000 real workspace paths", async () => { const rootPath = realpathSync(mkdtempSync(path.join(tmpdir(), "reconcile-many-"))); tempDirs.push(rootPath); - // Unrelated runner work must not consume the reconciliation budget. - const unrelatedWork = new Promise((resolve) => { - setImmediate(() => { - const cpu = Reflect.get(process, "threadCpuUsage") as typeof process.cpuUsage; - const start = cpu(); - while (cpu(start).user + cpu(start).system < 80_000) {} - resolve(); - }); - }); - const { stdout, stderr } = await promisify(execFile)(process.execPath, [probePath, rootPath], { - timeout: 25_000, - }); - process.stderr.write(stderr); - const { changesApplied, blockingMs, filesystemRequests, allArchived } = JSON.parse(stdout) as { - changesApplied: number; - blockingMs: number; - filesystemRequests: number; - allArchived: boolean; + // This CPU belongs to the runner, not to reconciliation. Keep it present + // throughout the read so a later loop turn cannot contaminate the budget. + let running = true; + const unrelatedWork = () => { + const threadCpuUsage: (previous?: NodeJS.CpuUsage) => NodeJS.CpuUsage = Reflect.get( + process, + "threadCpuUsage", + ); + const start = threadCpuUsage(); + let elapsed: NodeJS.CpuUsage; + do { + elapsed = threadCpuUsage(start); + } while (elapsed.user + elapsed.system < 60_000); + if (running) unrelated = setImmediate(unrelatedWork); }; - await unrelatedWork; - expect(blockingMs).toBeLessThan(20); - expect(filesystemRequests).toBe(20001); - expect(changesApplied).toBe(20000); - expect(allArchived).toBe(true); + let unrelated = setImmediate(unrelatedWork); + try { + const { stdout, stderr } = await promisify(execFile)( + process.execPath, + ["--expose-gc", probePath, rootPath], + { timeout: 25_000 }, + ); + process.stderr.write(stderr); + const { + changesApplied, + blockingMs, + filesystemRequests, + yields, + allArchived, + workerMessages, + } = JSON.parse(stdout) as { + changesApplied: number; + blockingMs: number; + filesystemRequests: number; + yields: number; + allArchived: boolean; + workerMessages: number; + }; + expect(blockingMs).toBeLessThan(20); + expect(filesystemRequests).toBe(20001); + expect(changesApplied).toBe(20000); + expect(allArchived).toBe(true); + expect(yields).toBeGreaterThan(0); + expect(workerMessages).toBe(0); + } finally { + running = false; + clearImmediate(unrelated); + } }, 30000); test("preserves workspace archival that lands during boot reconciliation", async () => { diff --git a/packages/server/src/server/worktree-bootstrap.test.ts b/packages/server/src/server/worktree-bootstrap.test.ts index 96da6e648b..ed43e02388 100644 --- a/packages/server/src/server/worktree-bootstrap.test.ts +++ b/packages/server/src/server/worktree-bootstrap.test.ts @@ -209,13 +209,8 @@ describe("runWorktreeAutoTerminals", () => { getSize: () => ({ rows: 0, cols: 0 }), getTitle: () => undefined, getExitInfo: () => null, - getState: () => ({ - rows: 0, - cols: 0, - grid: [], - scrollback: [], - cursor: { row: 0, col: 0 }, - }), + hasOutput: () => false, + kill: () => {}, killAndWait: async () => {}, }; @@ -312,13 +307,8 @@ describe("runWorktreeAutoTerminals", () => { } }; }, - getState: () => ({ - rows: 1, - cols: 1, - grid: [[{ char: "$" }]], - scrollback: [], - cursor: { row: 0, col: 0 }, - }), + hasOutput: () => true, + kill: () => {}, onTitleChange: () => () => {}, onActivityChange: () => () => {}, diff --git a/packages/server/src/server/worktree-bootstrap.ts b/packages/server/src/server/worktree-bootstrap.ts index d656738bd4..1e1ba58f8e 100644 --- a/packages/server/src/server/worktree-bootstrap.ts +++ b/packages/server/src/server/worktree-bootstrap.ts @@ -269,9 +269,9 @@ export function buildWorktreeSetupDetail(input: { } async function waitForTerminalBootstrapReadiness( - terminal: Pick, + terminal: Pick, ): Promise { - if (terminalHasOutput(terminal.getState())) { + if (terminal.hasOutput()) { return; } @@ -304,7 +304,7 @@ async function waitForTerminalBootstrapReadiness( finish(); }); - if (terminalHasOutput(terminal.getState())) { + if (terminal.hasOutput()) { finish(); return; } @@ -313,17 +313,6 @@ async function waitForTerminalBootstrapReadiness( }); } -function terminalHasOutput(state: ReturnType): boolean { - for (const row of [...state.scrollback, ...state.grid]) { - for (const cell of row) { - if (cell.char.trim().length > 0) { - return true; - } - } - } - return false; -} - export async function runWorktreeAutoTerminals(options: { workspaceId: string; worktree: WorktreeConfig; diff --git a/packages/server/src/server/worktree-session.test.ts b/packages/server/src/server/worktree-session.test.ts index d462a2605a..7117aa2501 100644 --- a/packages/server/src/server/worktree-session.test.ts +++ b/packages/server/src/server/worktree-session.test.ts @@ -212,13 +212,7 @@ function createTerminalManagerStub(options?: { id: `terminal-${terminals.length + 1}`, name: input.name ?? "Terminal", cwd: input.cwd, - getState: () => ({ - rows: 1, - cols: 1, - scrollback: [[{ char: "$" }]], - grid: [], - cursor: { row: 0, col: 0 }, - }), + hasOutput: () => true, subscribe: () => () => {}, onExit: () => () => {}, onCommandFinished: () => () => {}, diff --git a/packages/server/src/terminal/terminal-capture.ts b/packages/server/src/terminal/terminal-capture.ts index e22d3b6f69..4f8a0f4625 100644 --- a/packages/server/src/terminal/terminal-capture.ts +++ b/packages/server/src/terminal/terminal-capture.ts @@ -1,6 +1,5 @@ import stripAnsi from "strip-ansi"; -import type { TerminalCell } from "@getpaseo/protocol/messages"; -import type { TerminalSession } from "./terminal.js"; +import type { IBuffer } from "@xterm/headless"; export interface CaptureTerminalLinesOptions { start?: number; @@ -13,14 +12,6 @@ export interface CaptureTerminalLinesResult { totalLines: number; } -function cellsToPlainText(cells: TerminalCell[], options: { stripAnsi: boolean }): string { - const text = cells - .map((cell) => cell.char) - .join("") - .trimEnd(); - return options.stripAnsi ? stripAnsi(text) : text; -} - function resolveCaptureLineIndex( lineNumber: number | undefined, totalLines: number, @@ -46,14 +37,10 @@ function resolveCaptureLineIndex( } export function captureTerminalLines( - terminal: TerminalSession, + buffer: IBuffer, options: CaptureTerminalLinesOptions = {}, ): CaptureTerminalLinesResult { - const state = terminal.getState(); - const allLines = [...state.scrollback, ...state.grid].map((cells) => - cellsToPlainText(cells, { stripAnsi: options.stripAnsi ?? true }), - ); - const totalLines = allLines.length; + const totalLines = buffer.length; const startIndex = resolveCaptureLineIndex(options.start, totalLines, "start"); const endIndex = resolveCaptureLineIndex(options.end, totalLines, "end"); @@ -64,8 +51,10 @@ export function captureTerminalLines( }; } - return { - lines: allLines.slice(startIndex, endIndex + 1), - totalLines, - }; + const lines: string[] = []; + for (let row = startIndex; row <= endIndex; row++) { + const text = buffer.getLine(row)!.translateToString(true).trimEnd(); + lines.push(options.stripAnsi === false ? text : stripAnsi(text)); + } + return { lines, totalLines }; } diff --git a/packages/server/src/terminal/terminal-manager.test.ts b/packages/server/src/terminal/terminal-manager.test.ts index 47905d1424..83ba035c37 100644 --- a/packages/server/src/terminal/terminal-manager.test.ts +++ b/packages/server/src/terminal/terminal-manager.test.ts @@ -457,7 +457,6 @@ it("setTerminalTitle returns false for unknown terminal ids without changing exi expect(manager.setTerminalTitle("unknown-id", "x")).toBe(false); expect(session.getTitle()).toBe("Existing title"); - expect(session.getState().title).toBe("Existing title"); expect(snapshots).toEqual([]); unsubscribe(); diff --git a/packages/server/src/terminal/terminal-manager.ts b/packages/server/src/terminal/terminal-manager.ts index 86b4cdb662..f8ba1851fa 100644 --- a/packages/server/src/terminal/terminal-manager.ts +++ b/packages/server/src/terminal/terminal-manager.ts @@ -1,12 +1,16 @@ +import { + replayTerminal, + type TerminalReplaySink, + type TerminalReplayMetadata, + type TerminalReplayOptions, +} from "./terminal-replay.js"; import { createTerminal, type LocalTerminalSession, type TerminalActivityTransition, type TerminalSession, - type TerminalStateSnapshot, - type TerminalStateSnapshotOptions, } from "./terminal.js"; -import { captureTerminalLines, type CaptureTerminalLinesResult } from "./terminal-capture.js"; +import { type CaptureTerminalLinesResult } from "./terminal-capture.js"; import { randomBytes, randomUUID } from "node:crypto"; import { resolve, sep } from "node:path"; import { assertAbsolutePath, isSameOrDescendantPath } from "../server/path-utils.js"; @@ -76,10 +80,11 @@ export interface TerminalManager { registerCwdEnv(options: { cwd: string; env: Record }): void; validateTerminalActivityToken(terminalId: string, token: string): "valid" | "unknown" | "invalid"; getTerminal(id: string): TerminalSession | undefined; - getTerminalState( + replayTerminal( id: string, - options?: TerminalStateSnapshotOptions, - ): Promise; + options: TerminalReplayOptions | undefined, + sink: TerminalReplaySink, + ): Promise; setTerminalTitle(id: string, title: string): boolean; setTerminalActivity(id: string, state: TerminalActivityState): Promise; clearTerminalAttention(id: string): Promise; @@ -107,6 +112,10 @@ export interface TerminalManagerOptions { /** The in-process manager the terminal worker runs: it owns each PTY, so it knows its pid. */ export interface LocalTerminalManager extends TerminalManager { + createTerminal( + options: Parameters[0], + ): Promise; + getTerminal(id: string): LocalTerminalSession | undefined; getTerminalProcessId(id: string): number | null; getTerminalActivityToken(id: string): string | null; } @@ -337,7 +346,7 @@ export function createTerminalManager( activityUrl?: string | null; baseEnv?: Record; paseoCliPath?: string | null; - }): Promise { + }): Promise { assertAbsolutePath(options.cwd); const terminals = terminalsByCwd.get(options.cwd) ?? []; @@ -357,7 +366,7 @@ export function createTerminalManager( ...(terminalActivityUrl ? { PASEO_TERMINAL_ACTIVITY_URL: terminalActivityUrl } : {}), }; terminalActivityTokenById.set(terminalId, activityToken); - let session: TerminalSession; + let session: LocalTerminalSession; try { session = registerSession( await createTerminal({ @@ -404,7 +413,7 @@ export function createTerminalManager( return expected === token ? "valid" : "invalid"; }, - getTerminal(id: string): TerminalSession | undefined { + getTerminal(id: string): LocalTerminalSession | undefined { return terminalsById.get(id); }, @@ -416,11 +425,9 @@ export function createTerminalManager( return terminalActivityTokenById.get(id) ?? null; }, - async getTerminalState( - id: string, - options?: TerminalStateSnapshotOptions, - ): Promise { - return terminalsById.get(id)?.getStateSnapshot(options) ?? null; + async replayTerminal(id, options, sink) { + const session = terminalsById.get(id); + return session ? replayTerminal(session, options, sink) : null; }, setTerminalTitle(id: string, title: string): boolean { @@ -482,7 +489,7 @@ export function createTerminalManager( totalLines: 0, }; } - return captureTerminalLines(session, options); + return session.captureLines(options); }, listDirectories(): string[] { diff --git a/packages/server/src/terminal/terminal-replay.ts b/packages/server/src/terminal/terminal-replay.ts new file mode 100644 index 0000000000..73336a88f1 --- /dev/null +++ b/packages/server/src/terminal/terminal-replay.ts @@ -0,0 +1,135 @@ +import type { FramedSocket } from "./terminal-worker-frames.js"; +import type { + TerminalWorkerRequest, + TerminalWorkerToParentMessage, +} from "./terminal-worker-protocol.js"; +import type { LocalTerminalSession } from "./terminal.js"; + +export interface TerminalReplayOptions { + scrollbackLines?: number; +} + +export interface TerminalReplayMetadata { + rows: number; + cols: number; + retainedHistoryLines: number; + revision: number; + replayPreamble: string; +} +export type TerminalReplayEvent = + | { type: "begin"; metadata: TerminalReplayMetadata } + | { type: "data"; data: Uint8Array } + | { type: "end" }; +export type TerminalReplaySink = (event: TerminalReplayEvent) => void; +export const TERMINAL_REPLAY_CHUNK_BYTES = 64 * 1024; + +export function* createTerminalReplay( + session: LocalTerminalSession, + options: TerminalReplayOptions | undefined, +): Generator { + const { metadata, data } = session.serializeReplay(options); + yield { type: "begin", metadata }; + for (let offset = 0; offset < data.length; offset += TERMINAL_REPLAY_CHUNK_BYTES) { + yield { type: "data", data: data.subarray(offset, offset + TERMINAL_REPLAY_CHUNK_BYTES) }; + } + yield { type: "end" }; + return metadata; +} + +export async function replayTerminal( + session: LocalTerminalSession, + options: TerminalReplayOptions | undefined, + sink: TerminalReplaySink, +): Promise { + const replay = createTerminalReplay(session, options); + let next = replay.next(); + while (!next.done) { + sink(next.value); + next = replay.next(); + } + return next.value; +} + +interface TerminalReplayPorts { + getSession(id: string): LocalTerminalSession | undefined; + flushOutput(id: string): void; +} + +/** Worker-owned ANSI capture and paced delivery; live observations never wait for a replay. */ +export function createTerminalReplayController(ports: TerminalReplayPorts) { + let controller: FramedSocket | null = null; + + function sendToController(message: TerminalWorkerToParentMessage): void { + // A stalled physical controller is different from a stalled viewer: all its + // observations must reconnect to the surviving worker after this socket closes. + if (controller && controller.socket.writableLength > 4 * 1024 * 1024) { + controller.socket.destroy(); + return; + } + controller?.send(message); + } + + async function deliverReplay( + connection: FramedSocket, + message: Extract, + ): Promise { + ports.flushOutput(message.terminalId); + const session = ports.getSession(message.terminalId); + if (!session) { + await connection.sendAndWait({ + type: "response", + requestId: message.requestId, + ok: true, + result: null, + }); + return; + } + // Flush and capture share one synchronous turn. Each daemon viewer buffers + // its own live tail and discards revisions already included in this cut. + const replay = createTerminalReplay(session, message.options); + let next = replay.next(); + while (!next.done) { + if (controller !== connection) throw new Error("Terminal replay controller disconnected"); + await connection.sendAndWait({ + type: "terminalReplay", + requestId: message.requestId, + event: next.value, + }); + next = replay.next(); + } + await connection.sendAndWait({ + type: "response", + requestId: message.requestId, + ok: true, + result: next.value, + }); + } + + return { + setConnection(connection: FramedSocket | null): void { + if (controller === connection) return; + const previous = controller; + controller = connection; + previous?.socket.destroy(); + }, + send: sendToController, + async replay( + request: Extract, + ): Promise { + const connection = controller; + if (!connection) return; + try { + await deliverReplay(connection, request); + } catch (error) { + await connection + .sendAndWait({ + type: "response", + requestId: request.requestId, + ok: false, + error: error instanceof Error ? error.message : String(error), + }) + .catch(() => {}); + } + }, + }; +} diff --git a/packages/server/src/terminal/terminal-restore.test.ts b/packages/server/src/terminal/terminal-restore.test.ts index 7255cba1a5..ad008e1bd7 100644 --- a/packages/server/src/terminal/terminal-restore.test.ts +++ b/packages/server/src/terminal/terminal-restore.test.ts @@ -4,56 +4,45 @@ import { TerminalStreamOpcode, decodeTerminalStreamFrame, } from "@getpaseo/protocol/binary-frames/index"; -import type { TerminalCell, TerminalState } from "@getpaseo/protocol/messages"; import { + createTerminalRestoreDelivery, encodeTerminalRestoreFrame, resolveRestoreAfterOutputOverflow, resolveTerminalRestoreSnapshotOptions, - resolveTerminalSubscriptionSnapshotMode, } from "./terminal-restore.js"; -function terminalRow(text: string, cols = 80): TerminalCell[] { - return Array.from({ length: cols }, (_, index) => ({ - char: text[index] ?? " ", - })); -} - -function terminalState(text: string): TerminalState { - return { - rows: 1, - cols: 80, - grid: [terminalRow(text)], - scrollback: [], - cursor: { row: 0, col: text.length }, - }; -} - describe("terminal restore policy", () => { - test("uses ready snapshots only for restore-aware subscriptions", () => { - expect(resolveTerminalSubscriptionSnapshotMode(undefined)).toBe("state"); - expect(resolveTerminalSubscriptionSnapshotMode({ mode: "live" })).toBe("ready"); - }); - test("resolves bounded restore snapshot options", () => { - expect(resolveTerminalRestoreSnapshotOptions({ mode: "live" })).toBeNull(); - expect(resolveTerminalRestoreSnapshotOptions({ mode: "full-snapshot" })).toBeUndefined(); - expect(resolveTerminalRestoreSnapshotOptions({ mode: "visible-snapshot" })).toEqual({ + expect( + resolveTerminalRestoreSnapshotOptions({ restore: { mode: "live" }, chunked: false }), + ).toBeNull(); + expect( + resolveTerminalRestoreSnapshotOptions({ restore: { mode: "full-snapshot" }, chunked: false }), + ).toBeUndefined(); + expect( + resolveTerminalRestoreSnapshotOptions({ + restore: { mode: "visible-snapshot" }, + chunked: false, + }), + ).toEqual({ scrollbackLines: 200, }); expect( resolveTerminalRestoreSnapshotOptions({ - mode: "visible-snapshot", - scrollbackLines: 999, + restore: { mode: "visible-snapshot", scrollbackLines: 999 }, + chunked: false, }), ).toEqual({ scrollbackLines: 500 }); }); - test("promotes live restore to visible restore after output overflow", () => { + test("bounds pressure recovery for every restore mode", () => { expect(resolveRestoreAfterOutputOverflow({ mode: "live" })).toEqual({ mode: "visible-snapshot", + scrollbackLines: 500, }); expect(resolveRestoreAfterOutputOverflow({ mode: "full-snapshot" })).toEqual({ - mode: "full-snapshot", + mode: "visible-snapshot", + scrollbackLines: 500, }); }); @@ -61,10 +50,7 @@ describe("terminal restore policy", () => { const frame = decodeTerminalStreamFrame( encodeTerminalRestoreFrame({ slot: 4, - snapshot: { - state: terminalState("restored"), - revision: 1, - }, + data: new TextEncoder().encode("restored"), }), ); @@ -73,3 +59,40 @@ describe("terminal restore policy", () => { expect(new TextDecoder().decode(frame?.payload ?? new Uint8Array())).toContain("restored"); }); }); + +test("projects chunked replay begin onto the declared wire metadata", () => { + const frames: Uint8Array[] = []; + const deliver = createTerminalRestoreDelivery({ + slot: 7, + chunked: true, + send: (frame) => { + frames.push(frame); + }, + }); + deliver({ + type: "begin", + metadata: { + rows: 30, + cols: 120, + retainedHistoryLines: 842, + revision: 5123, + replayPreamble: "\x1b[?2004h", + }, + }); + const data = new TextEncoder().encode("\x1b[31m界 replay\x1b[0m"); + deliver({ type: "data", data }); + deliver({ type: "end" }); + const decoded = frames.map((frame) => decodeTerminalStreamFrame(frame)!); + expect(decoded.map((frame) => ({ slot: frame.slot, opcode: frame.opcode }))).toEqual([ + { slot: 7, opcode: TerminalStreamOpcode.ReplayBegin }, + { slot: 7, opcode: TerminalStreamOpcode.ReplayData }, + { slot: 7, opcode: TerminalStreamOpcode.ReplayEnd }, + ]); + expect(JSON.parse(new TextDecoder().decode(decoded[0]!.payload))).toEqual({ + rows: 30, + cols: 120, + retainedHistoryLines: 842, + }); + expect(decoded[1]!.payload).toEqual(data); + expect(decoded[2]!.payload.byteLength).toBe(0); +}); diff --git a/packages/server/src/terminal/terminal-restore.ts b/packages/server/src/terminal/terminal-restore.ts index ffc1bd9faa..c0ee7b1105 100644 --- a/packages/server/src/terminal/terminal-restore.ts +++ b/packages/server/src/terminal/terminal-restore.ts @@ -1,11 +1,11 @@ +import type { z } from "zod"; import type { SubscribeTerminalRequest } from "@getpaseo/protocol/messages"; import { TerminalStreamOpcode, - encodeTerminalSnapshotPayload, + type TerminalReplayMetadataSchema, encodeTerminalStreamFrame, } from "@getpaseo/protocol/binary-frames/index"; -import { renderTerminalSnapshotToAnsi } from "@getpaseo/protocol/terminal-snapshot"; -import type { TerminalStateSnapshot, TerminalStateSnapshotOptions } from "./terminal.js"; +import type { TerminalReplaySink, TerminalReplayOptions } from "./terminal-replay.js"; export const MAX_TERMINAL_OUTPUT_FRAME_BYTES = 256 * 1024; @@ -21,62 +21,84 @@ const MAX_VISIBLE_RESTORE_SCROLLBACK_LINES = 500; export type TerminalRestoreOptions = NonNullable; -export type TerminalSubscriptionSnapshotMode = "state" | "ready"; - -export function resolveTerminalSubscriptionSnapshotMode( - restore: TerminalRestoreOptions | undefined, -): TerminalSubscriptionSnapshotMode { - return restore ? "ready" : "state"; -} - export function resolveRestoreAfterOutputOverflow( restore: TerminalRestoreOptions | undefined, -): TerminalRestoreOptions | undefined { - if (restore?.mode === "live") { - return { mode: "visible-snapshot" }; - } - return restore; +): TerminalRestoreOptions { + return { + mode: "visible-snapshot", + scrollbackLines: Math.min( + restore?.scrollbackLines ?? MAX_VISIBLE_RESTORE_SCROLLBACK_LINES, + MAX_VISIBLE_RESTORE_SCROLLBACK_LINES, + ), + }; } -export function resolveTerminalRestoreSnapshotOptions( - restore: TerminalRestoreOptions, -): TerminalStateSnapshotOptions | null | undefined { +export function resolveTerminalRestoreSnapshotOptions({ + restore, + chunked, +}: { + restore: TerminalRestoreOptions; + chunked: boolean; +}): TerminalReplayOptions | null | undefined { if (restore.mode === "live") { return null; } - if (restore.mode === "visible-snapshot") { - return { - scrollbackLines: resolveVisibleRestoreScrollbackLines(restore.scrollbackLines), - }; + if (restore.mode === "full-snapshot") { + return chunked ? { scrollbackLines: restore.scrollbackLines } : undefined; } - return undefined; + const scrollbackLines = restore.scrollbackLines ?? DEFAULT_VISIBLE_RESTORE_SCROLLBACK_LINES; + return { + scrollbackLines: chunked + ? scrollbackLines + : Math.min(scrollbackLines, MAX_VISIBLE_RESTORE_SCROLLBACK_LINES), + }; } -export function encodeLegacyTerminalSnapshotFrame(input: { - slot: number; - snapshot: TerminalStateSnapshot; -}): Uint8Array { - return encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Snapshot, - slot: input.slot, - payload: encodeTerminalSnapshotPayload(input.snapshot.state), - }); -} - -export function encodeTerminalRestoreFrame(input: { - slot: number; - snapshot: TerminalStateSnapshot; -}): Uint8Array { +export function encodeTerminalRestoreFrame(input: { slot: number; data: Uint8Array }): Uint8Array { return encodeTerminalStreamFrame({ opcode: TerminalStreamOpcode.Restore, slot: input.slot, - payload: renderTerminalSnapshotToAnsi(input.snapshot.state), + payload: input.data, }); } -function resolveVisibleRestoreScrollbackLines(value: number | undefined): number { - if (typeof value !== "number") { - return DEFAULT_VISIBLE_RESTORE_SCROLLBACK_LINES; - } - return Math.min(Math.max(0, value), MAX_VISIBLE_RESTORE_SCROLLBACK_LINES); +/** The daemon's only old-app adapter. Capable delivery never assembles the replay. */ +export function createTerminalRestoreDelivery(input: { + slot: number; + chunked: boolean; + send(frame: Uint8Array): void; +}): TerminalReplaySink { + // COMPAT(terminalSingleRestore): added after v0.14.0; remove after 2027-04-30 when client floor supports chunked replay. + const legacyChunks: Uint8Array[] = []; + return (event) => { + if (!input.chunked) { + if (event.type === "data") legacyChunks.push(event.data); + if (event.type === "end") + input.send( + encodeTerminalRestoreFrame({ + slot: input.slot, + data: Buffer.concat(legacyChunks), + }), + ); + return; + } + const opcodes = { + begin: TerminalStreamOpcode.ReplayBegin, + data: TerminalStreamOpcode.ReplayData, + end: TerminalStreamOpcode.ReplayEnd, + }; + let payload: string | Uint8Array | undefined; + if (event.type === "begin") { + const begin = { + rows: event.metadata.rows, + cols: event.metadata.cols, + retainedHistoryLines: event.metadata.retainedHistoryLines, + } satisfies z.infer; + payload = JSON.stringify(begin); + } + if (event.type === "data") payload = event.data; + input.send( + encodeTerminalStreamFrame({ slot: input.slot, opcode: opcodes[event.type], payload }), + ); + }; } diff --git a/packages/server/src/terminal/terminal-serializer.ts b/packages/server/src/terminal/terminal-serializer.ts new file mode 100644 index 0000000000..5f79064948 --- /dev/null +++ b/packages/server/src/terminal/terminal-serializer.ts @@ -0,0 +1,42 @@ +import type { Terminal as TerminalType } from "@xterm/headless"; +import { SerializeAddon } from "@xterm/addon-serialize"; +import type { TerminalReplayOptions } from "./terminal-replay.js"; + +/** Serialize the owned model; the PTY is a transport, not an ANSI parser oracle. */ +export function createTerminalSerializer( + terminal: TerminalType, +): (options?: TerminalReplayOptions) => Uint8Array { + const addon = new SerializeAddon(); + terminal.loadAddon(addon); + return (options) => { + const data = addon.serialize({ scrollback: options?.scrollbackLines }); + const buffer = terminal.buffer.active; + // Addon 0.14 applies a horizontal offset after vertical movement has already + // clamped a pending-wrap column, losing a column. Restore a valid position + // absolutely; an x==cols cursor must keep its pending wrap for the next byte. + const position = + buffer.cursorX < terminal.cols ? `\x1b[${buffer.cursorY + 1};${buffer.cursorX + 1}H` : ""; + return Buffer.from(data + position + serializeCursorPresentation(terminal), "utf8"); + }; +} + +// Stable addon 0.14 serializes buffer/modes but omits DECSCUSR and cursor visibility. +// xterm 6 keeps the program-selected presentation in coreService, not public options. +function serializeCursorPresentation(terminal: TerminalType): string { + const core = ( + terminal as unknown as { + _core: { + coreService: { + isCursorHidden: boolean; + decPrivateModes: { cursorStyle?: "block" | "underline" | "bar"; cursorBlink?: boolean }; + }; + }; + } + )._core.coreService; + const visibility = `\x1b[?25${core.isCursorHidden ? "l" : "h"}`; + const cursorStyle = core.decPrivateModes.cursorStyle; + // Unset presentation belongs to each renderer's configured defaults. + if (cursorStyle === undefined) return visibility; + const style = { block: 2, underline: 4, bar: 6 }[cursorStyle]; + return `${visibility}\x1b[${style - (core.decPrivateModes.cursorBlink ? 1 : 0)} q`; +} diff --git a/packages/server/src/terminal/terminal-session-controller.test.ts b/packages/server/src/terminal/terminal-session-controller.test.ts index 27f69cb44d..ccb152aa23 100644 --- a/packages/server/src/terminal/terminal-session-controller.test.ts +++ b/packages/server/src/terminal/terminal-session-controller.test.ts @@ -1,3 +1,6 @@ +import type { TerminalReplayOptions } from "./terminal-replay.js"; +import type { TerminalRestoreOptions } from "./terminal-restore.js"; +import type { TerminalReplayMetadata } from "./terminal-replay.js"; import { describe, expect, test, vi } from "vitest"; import pino from "pino"; @@ -7,8 +10,7 @@ import { decodeTerminalStreamFrame, type TerminalStreamFrame, } from "@getpaseo/protocol/binary-frames/index"; -import type { TerminalCell, TerminalState } from "@getpaseo/protocol/messages"; -import type { ServerMessage, TerminalSession, TerminalStateSnapshot } from "./terminal.js"; +import type { ServerMessage, TerminalSession } from "./terminal.js"; import { TerminalSessionController, type TerminalSessionControllerOptions, @@ -19,8 +21,33 @@ import { isSameOrDescendantPath } from "../server/path-utils.js"; import { PluginSessionSocket } from "../server/plugins/session-socket.js"; import { TerminalWorkerIncompatibleError } from "./terminal-worker-pool.js"; +interface ReplayFixture { + data: Uint8Array; + metadata: TerminalReplayMetadata; +} +function terminalReplay(text: string, revision: number, replayPreamble = ""): ReplayFixture { + return { + data: Buffer.from(text), + metadata: { rows: 1, cols: 80, retainedHistoryLines: 0, revision, replayPreamble }, + }; +} +function replayFixture( + read: () => Promise, +): TerminalManager["replayTerminal"] { + return async (_id, _options, sink) => { + const replay = await read(); + if (!replay) return null; + await sink({ type: "begin", metadata: replay.metadata }); + await sink({ type: "data", data: replay.data }); + await sink({ type: "end" }); + return replay.metadata; + }; +} + function createController( - options: TerminalSessionControllerOptions & { emitBinary(frame: Uint8Array): void }, + options: TerminalSessionControllerOptions & { + emitBinary(frame: Uint8Array): void | Promise; + }, ) { const source = {}; const ownership = new SessionDelivery( @@ -59,22 +86,6 @@ function deferred(): { return { promise, resolve, reject }; } -function terminalRow(text: string, cols = 80): TerminalCell[] { - return Array.from({ length: cols }, (_, index) => ({ - char: text[index] ?? " ", - })); -} - -function terminalState(text: string): TerminalState { - return { - rows: 1, - cols: 80, - grid: [terminalRow(text)], - scrollback: [], - cursor: { row: 0, col: text.length }, - }; -} - function createLogger(): pino.Logger { return { warn: vi.fn(), @@ -85,7 +96,7 @@ function createLogger(): pino.Logger { describe("terminal-session-controller restore", () => { test("delivers output produced while restore is in flight after the restore frame", async () => { let terminalListener: ((message: ServerMessage) => void) | null = null; - const snapshot = deferred(); + const snapshot = deferred(); const binaryFrames: TerminalStreamFrame[] = []; const outboundMessages: SessionOutboundMessage[] = []; const terminal: TerminalSession = { @@ -104,8 +115,7 @@ describe("terminal-session-controller restore", () => { onTitleChange: () => vi.fn(), onActivityChange: () => vi.fn(), getSize: () => ({ rows: 1, cols: 80 }), - getState: () => terminalState("restore-before"), - getStateSnapshot: () => ({ state: terminalState("restore-before"), revision: 1 }), + hasOutput: () => true, getReplayPreamble: () => "\x1b[?1h\x1b[?2004h", getTitle: () => undefined, getActivity: () => null, @@ -121,7 +131,7 @@ describe("terminal-session-controller restore", () => { registerCwdEnv: vi.fn(), validateTerminalActivityToken: vi.fn(() => "unknown"), getTerminal: vi.fn(() => terminal), - getTerminalState: vi.fn(() => snapshot.promise), + replayTerminal: replayFixture(() => snapshot.promise), setTerminalTitle: vi.fn(), setTerminalActivity: vi.fn(), killTerminal: vi.fn(), @@ -157,10 +167,10 @@ describe("terminal-session-controller restore", () => { }, }); await Promise.resolve(); - expect(terminalManager.getTerminalState).toHaveBeenCalledTimes(1); + expect(binaryFrames).toEqual([]); terminalListener?.({ type: "output", data: "restore-after\n", revision: 2 }); - snapshot.resolve({ state: terminalState("restore-before"), revision: 1 }); + snapshot.resolve(terminalReplay("restore-before", 1, "\x1b[?1h\x1b[?2004h")); await snapshot.promise; await new Promise((resolve) => setTimeout(resolve, 20)); @@ -202,8 +212,7 @@ function listSession(input: { onTitleChange: () => vi.fn(), onActivityChange: () => vi.fn(), getSize: () => ({ rows: 1, cols: 80 }), - getState: () => terminalState(""), - getStateSnapshot: () => ({ state: terminalState(""), revision: 0 }), + hasOutput: () => true, getReplayPreamble: () => "", getTitle: () => undefined, getActivity: () => null, @@ -236,7 +245,7 @@ describe("terminal-session-controller legacy terminal creation", () => { registerCwdEnv: vi.fn(), validateTerminalActivityToken: vi.fn(() => "unknown"), getTerminal: vi.fn(), - getTerminalState: vi.fn(), + replayTerminal: async () => null, setTerminalTitle: vi.fn(), setTerminalActivity: vi.fn(), clearTerminalAttention: vi.fn(), @@ -311,7 +320,7 @@ describe("terminal-session-controller legacy terminal creation", () => { registerCwdEnv: vi.fn(), validateTerminalActivityToken: vi.fn(() => "unknown"), getTerminal: vi.fn(), - getTerminalState: vi.fn(), + replayTerminal: async () => null, setTerminalTitle: vi.fn(), setTerminalActivity: vi.fn(), clearTerminalAttention: vi.fn(), @@ -362,7 +371,7 @@ describe("terminal-session-controller with terminals held by a newer Paseo", () registerCwdEnv: vi.fn(), validateTerminalActivityToken: vi.fn(() => "unknown"), getTerminal: vi.fn(), - getTerminalState: vi.fn(), + replayTerminal: async () => null, setTerminalTitle: vi.fn(), setTerminalActivity: vi.fn(), clearTerminalAttention: vi.fn(), @@ -428,99 +437,6 @@ async function waitForCoalescerFlush(): Promise { await new Promise((resolve) => setTimeout(resolve, 30)); } -describe("terminal-session-controller wrap-flag gating", () => { - function setup(clientSupportsWrapReflow?: () => boolean): { - controller: ReturnType; - getTerminalState: ReturnType; - } { - const terminal: TerminalSession = { - id: "term-1", - name: "Terminal", - cwd: "/tmp", - workspaceId: "ws-test", - send: vi.fn(), - subscribe: (listener) => { - queueMicrotask(() => listener({ type: "snapshotReady", revision: 1 })); - return vi.fn(); - }, - onExit: () => vi.fn(), - onCommandFinished: () => vi.fn(), - onTitleChange: () => vi.fn(), - onActivityChange: () => vi.fn(), - getSize: () => ({ rows: 1, cols: 80 }), - getState: () => terminalState("hello"), - getStateSnapshot: () => ({ state: terminalState("hello"), revision: 1 }), - getReplayPreamble: () => "", - getTitle: () => undefined, - getActivity: () => null, - setActivity: vi.fn(), - setTitle: vi.fn(), - getExitInfo: () => null, - kill: vi.fn(), - killAndWait: vi.fn(), - }; - const getTerminalState = vi.fn(() => - Promise.resolve({ state: terminalState("hello"), revision: 1 }), - ); - const terminalManager = { - getTerminals: vi.fn(), - createTerminal: vi.fn(), - registerCwdEnv: vi.fn(), - validateTerminalActivityToken: vi.fn(() => "unknown"), - getTerminal: vi.fn(() => terminal), - getTerminalState, - setTerminalTitle: vi.fn(), - setTerminalActivity: vi.fn(), - killTerminal: vi.fn(), - killTerminalAndWait: vi.fn(), - captureTerminal: vi.fn(), - listDirectories: vi.fn(() => []), - killAll: vi.fn(), - subscribeTerminalsChanged: vi.fn(() => vi.fn()), - subscribeTerminalActivity: vi.fn(() => vi.fn()), - subscribeTerminalWorkspaceContributionChanged: vi.fn(() => vi.fn()), - } as unknown as TerminalManager; - const controller = createController({ - terminalManager, - emit: vi.fn(), - emitBinary: vi.fn(), - hasBinaryChannel: () => true, - isPathWithinRoot: () => false, - sessionLogger: createLogger(), - ...(clientSupportsWrapReflow ? { clientSupportsWrapReflow } : {}), - }); - return { controller, getTerminalState }; - } - - async function subscribe(controller: ReturnType): Promise { - await controller.dispatch({ - type: "subscribe_terminal_request", - terminalId: "term-1", - requestId: "req-1", - restore: { mode: "visible-snapshot", scrollbackLines: 200 }, - }); - await flushMicrotasks(); - } - - test("requests wrap flags when the client supports reflowable snapshots", async () => { - const { controller, getTerminalState } = setup(() => true); - await subscribe(controller); - expect(getTerminalState).toHaveBeenCalledWith( - "term-1", - expect.objectContaining({ includeWrapFlags: true }), - ); - }); - - test("omits wrap flags when the client does not advertise support", async () => { - const { controller, getTerminalState } = setup(); - await subscribe(controller); - expect(getTerminalState).toHaveBeenCalledWith( - "term-1", - expect.objectContaining({ includeWrapFlags: false }), - ); - }); -}); - describe("terminal-session-controller subdirectory aggregation", () => { test("delivers a subdirectory change to a root subscriber as an aggregated, root-keyed snapshot", async () => { const rootCwd = "/work/repo"; @@ -541,7 +457,7 @@ describe("terminal-session-controller subdirectory aggregation", () => { registerCwdEnv: vi.fn(), validateTerminalActivityToken: vi.fn(() => "unknown"), getTerminal: vi.fn(), - getTerminalState: vi.fn(), + replayTerminal: async () => null, setTerminalTitle: vi.fn(), setTerminalActivity: vi.fn(), killTerminal: vi.fn(), @@ -609,7 +525,7 @@ describe("terminal-session-controller subdirectory aggregation", () => { registerCwdEnv: vi.fn(), validateTerminalActivityToken: vi.fn(() => "unknown"), getTerminal: vi.fn(), - getTerminalState: vi.fn(), + replayTerminal: async () => null, setTerminalTitle: vi.fn(), setTerminalActivity: vi.fn(), killTerminal: vi.fn(), @@ -701,7 +617,7 @@ describe("terminal-session-controller workspace-scoped subscriptions", () => { registerCwdEnv: vi.fn(), validateTerminalActivityToken: vi.fn(() => "unknown"), getTerminal: vi.fn(), - getTerminalState: vi.fn(), + replayTerminal: async () => null, setTerminalTitle: vi.fn(), setTerminalActivity: vi.fn(), killTerminal: vi.fn(), @@ -764,9 +680,17 @@ describe("terminal-session-controller workspace-scoped subscriptions", () => { }); describe("terminal-session-controller backpressure snapshot fallback", () => { - async function setup(getClientBufferedAmount: () => number | null): Promise<{ + async function setup( + getClientBufferedAmount: () => number | null, + chunked = false, + pace?: () => Promise, + restore?: TerminalRestoreOptions, + ): Promise<{ + messages: SessionOutboundMessage[]; pushOutput: (data: string) => void; frames: TerminalStreamFrame[]; + replayOptions: Array; + ready: () => void; }> { let terminalListener: ((message: ServerMessage) => void) | null = null; const terminal: TerminalSession = { @@ -777,19 +701,15 @@ describe("terminal-session-controller backpressure snapshot fallback", () => { send: vi.fn(), subscribe: (listener) => { terminalListener = listener; - // Legacy stream: a snapshot arrives on subscribe (one Snapshot frame), - // after which output streams through the coalescer as Output frames. - queueMicrotask(() => - listener({ type: "snapshot", state: terminalState("live"), revision: 1 }), - ); + // Readiness starts ANSI replay; later bytes use Output frames. + queueMicrotask(() => listener({ type: "snapshotReady", revision: 1 })); return vi.fn(); }, onExit: () => vi.fn(), onCommandFinished: () => vi.fn(), onTitleChange: () => vi.fn(), getSize: () => ({ rows: 1, cols: 80 }), - getState: () => terminalState("live"), - getStateSnapshot: () => ({ state: terminalState("live"), revision: 1 }), + hasOutput: () => true, getReplayPreamble: () => "", getTitle: () => undefined, setTitle: vi.fn(), @@ -797,14 +717,16 @@ describe("terminal-session-controller backpressure snapshot fallback", () => { kill: vi.fn(), killAndWait: vi.fn(), }; - const terminalManager = { + const replayOptions: Array = []; + const terminalManager: TerminalManager = { getTerminals: vi.fn(), createTerminal: vi.fn(), registerCwdEnv: vi.fn(), getTerminal: vi.fn(() => terminal), - getTerminalState: vi.fn(() => - Promise.resolve({ state: terminalState("live"), revision: 1 }), - ), + replayTerminal: (id, options, sink) => { + replayOptions.push(options); + return replayFixture(async () => terminalReplay("live", 1))(id, options, sink); + }, setTerminalTitle: vi.fn(), killTerminal: vi.fn(), killTerminalAndWait: vi.fn(), @@ -812,16 +734,26 @@ describe("terminal-session-controller backpressure snapshot fallback", () => { listDirectories: vi.fn(() => []), killAll: vi.fn(), subscribeTerminalsChanged: vi.fn(() => vi.fn()), - } as unknown as TerminalManager; + validateTerminalActivityToken: () => "unknown", + setTerminalActivity: async () => true, + clearTerminalAttention: async () => false, + subscribeTerminalActivity: () => () => {}, + subscribeTerminalWorkspaceContributionChanged: () => () => {}, + }; const frames: TerminalStreamFrame[] = []; + const messages: SessionOutboundMessage[] = []; const controller = createController({ terminalManager, - emit: vi.fn(), + emit: (message) => { + messages.push(message); + }, + supportsChunkedReplay: () => chunked, emitBinary: (bytes) => { const frame = decodeTerminalStreamFrame(bytes); if (frame) { frames.push(frame); + if (frame.opcode === TerminalStreamOpcode.ReplayBegin) return pace?.(); } }, hasBinaryChannel: () => true, @@ -834,6 +766,7 @@ describe("terminal-session-controller backpressure snapshot fallback", () => { type: "subscribe_terminal_request", terminalId: "term-1", requestId: "req-1", + restore, }); await waitForCoalescerFlush(); // Drop the initial subscribe snapshot frame so each test only sees frames @@ -841,11 +774,83 @@ describe("terminal-session-controller backpressure snapshot fallback", () => { frames.length = 0; return { + replayOptions, + ready: () => terminalListener?.({ type: "snapshotReady" }), pushOutput: (data) => terminalListener?.({ type: "output", data, revision: 2 }), frames, + messages, }; } + test.each([false, true])( + "preserves visible history defaults and explicit requests across delivery (chunked=%s)", + async (chunked) => { + const replayOpcodes = chunked + ? [ + TerminalStreamOpcode.ReplayBegin, + TerminalStreamOpcode.ReplayData, + TerminalStreamOpcode.ReplayEnd, + ] + : [TerminalStreamOpcode.Restore]; + for (const [restore, expected] of [ + [{ mode: "visible-snapshot" }, [{ scrollbackLines: 200 }]], + [{ mode: "visible-snapshot", scrollbackLines: 0 }, [{ scrollbackLines: 0 }]], + [{ mode: "visible-snapshot", scrollbackLines: 5 }, [{ scrollbackLines: 5 }]], + [{ mode: "visible-snapshot", scrollbackLines: 500 }, [{ scrollbackLines: 500 }]], + [ + { mode: "visible-snapshot", scrollbackLines: 10000 }, + [{ scrollbackLines: chunked ? 10000 : 500 }], + ], + [{ mode: "full-snapshot" }, [chunked ? { scrollbackLines: undefined } : undefined]], + [{ mode: "live" }, []], + ] as const) { + const fixture = await setup(() => 0, chunked, undefined, restore); + expect(fixture.replayOptions).toEqual(expected); + fixture.ready(); + await waitForCoalescerFlush(); + expect(fixture.replayOptions).toEqual([...expected, ...expected]); + expect(fixture.frames.map((frame) => frame.opcode)).toEqual( + restore.mode === "live" ? [] : replayOpcodes, + ); + fixture.pushOutput("after-restore"); + await waitForCoalescerFlush(); + expect(fixture.frames.at(-1)?.opcode).toBe(TerminalStreamOpcode.Output); + expect(new TextDecoder().decode(fixture.frames.at(-1)!.payload)).toBe("after-restore"); + } + }, + ); + + test.each([false, true])( + "bounds recovery without changing attach demand (chunked=%s)", + async (chunked) => { + for (const [restore, history] of [ + [{ mode: "visible-snapshot" }, 500], + [{ mode: "visible-snapshot", scrollbackLines: 10000 }, 500], + [{ mode: "full-snapshot" }, 500], + [{ mode: "visible-snapshot", scrollbackLines: 5 }, 5], + [{ mode: "visible-snapshot", scrollbackLines: 0 }, 0], + [{ mode: "full-snapshot", scrollbackLines: 0 }, 0], + [{ mode: "live", scrollbackLines: 0 }, 0], + [{ mode: "live" }, 500], + [undefined, 500], + ] as const) { + const fixture = await setup(() => 8 * 1024 * 1024, chunked, undefined, restore); + const initial = fixture.replayOptions.slice(); + fixture.pushOutput("pressure".repeat(40000)); + await waitForCoalescerFlush(); + expect(fixture.replayOptions.at(-1)).toEqual({ scrollbackLines: history }); + expect(fixture.replayOptions).toHaveLength(initial.length + 1); + fixture.ready(); // Worker adoption must use the original demand, even on the same stream. + await waitForCoalescerFlush(); + expect(fixture.replayOptions.slice(initial.length + 1)).toEqual(initial); + fixture.frames.length = 0; + fixture.pushOutput("after-catch-up"); + await waitForCoalescerFlush(); + expect(fixture.frames.map((frame) => frame.opcode)).toEqual([TerminalStreamOpcode.Output]); + } + }, + ); + test("streams all output without a snapshot when the client keeps up", async () => { const { pushOutput, frames } = await setup(() => 0); @@ -853,7 +858,7 @@ describe("terminal-session-controller backpressure snapshot fallback", () => { pushOutput(chunk); await waitForCoalescerFlush(); - expect(frames.some((frame) => frame.opcode === TerminalStreamOpcode.Snapshot)).toBe(false); + expect(frames.some((frame) => frame.opcode === TerminalStreamOpcode.Restore)).toBe(false); const outputFrames = frames.filter((frame) => frame.opcode === TerminalStreamOpcode.Output); expect(outputFrames.length).toBeGreaterThan(0); const receivedBytes = outputFrames.reduce( @@ -869,7 +874,7 @@ describe("terminal-session-controller backpressure snapshot fallback", () => { pushOutput("y".repeat(300 * 1024)); await waitForCoalescerFlush(); - expect(frames.some((frame) => frame.opcode === TerminalStreamOpcode.Snapshot)).toBe(true); + expect(frames.some((frame) => frame.opcode === TerminalStreamOpcode.Restore)).toBe(true); // After the snapshot the byte counter is reset, so a small follow-up chunk // streams as Output rather than tripping the fallback again. @@ -877,7 +882,7 @@ describe("terminal-session-controller backpressure snapshot fallback", () => { pushOutput("z".repeat(1024)); await waitForCoalescerFlush(); - expect(frames.some((frame) => frame.opcode === TerminalStreamOpcode.Snapshot)).toBe(false); + expect(frames.some((frame) => frame.opcode === TerminalStreamOpcode.Restore)).toBe(false); expect(frames.some((frame) => frame.opcode === TerminalStreamOpcode.Output)).toBe(true); }); @@ -893,7 +898,7 @@ describe("terminal-session-controller backpressure snapshot fallback", () => { pushOutput("p".repeat(300 * 1024)); await waitForCoalescerFlush(); - expect(frames.some((frame) => frame.opcode === TerminalStreamOpcode.Snapshot)).toBe(true); + expect(frames.some((frame) => frame.opcode === TerminalStreamOpcode.Restore)).toBe(true); }); test("falls back to a snapshot at the byte threshold when no backpressure signal exists", async () => { @@ -905,11 +910,41 @@ describe("terminal-session-controller backpressure snapshot fallback", () => { pushOutput("r".repeat(300 * 1024)); await waitForCoalescerFlush(); - expect(frames.some((frame) => frame.opcode === TerminalStreamOpcode.Snapshot)).toBe(true); + expect(frames.some((frame) => frame.opcode === TerminalStreamOpcode.Restore)).toBe(true); + }); + test("queues capable catch-up without waiting for the direct socket to drain", async () => { + let buffered = 0; + let release!: () => void; + const gate = new Promise((resolve) => { + release = resolve; + }); + const { pushOutput, frames, messages } = await setup( + () => buffered, + true, + () => (buffered ? gate : Promise.resolve()), + ); + buffered = 8 * 1024 * 1024; + pushOutput("y".repeat(300 * 1024)); + await waitForCoalescerFlush(); + expect(messages.filter((message) => message.type === "terminal_stream_exit")).toEqual([]); + expect(frames.map((frame) => frame.opcode)).toEqual([ + TerminalStreamOpcode.ReplayBegin, + TerminalStreamOpcode.ReplayData, + TerminalStreamOpcode.ReplayEnd, + ]); + buffered = 0; + release(); + await waitForCoalescerFlush(); + expect(frames.map((frame) => frame.opcode)).toContain(TerminalStreamOpcode.ReplayEnd); + frames.length = 0; + buffered = 8 * 1024 * 1024; // Small output must stay live after the replay resets its byte counter. + pushOutput("live-after-recovery"); + await waitForCoalescerFlush(); + expect(frames.map((frame) => frame.opcode)).toEqual([TerminalStreamOpcode.Output]); }); }); -function exitFixture(readSnapshot: () => Promise, backedUp = false) { +function exitFixture(readReplay: () => Promise, backedUp = false) { const outputs = new Set<(message: ServerMessage) => void>(); const exits = new Set[0]>(); const terminal: TerminalSession = { @@ -934,8 +969,7 @@ function exitFixture(readSnapshot: () => Promise, onTitleChange: () => () => {}, onActivityChange: () => () => {}, getSize: () => ({ rows: 1, cols: 80 }), - getState: () => terminalState("snapshot"), - getStateSnapshot: () => ({ state: terminalState("snapshot"), revision: 0 }), + hasOutput: () => true, getReplayPreamble: () => "", getTitle: () => undefined, getActivity: () => null, @@ -948,7 +982,7 @@ function exitFixture(readSnapshot: () => Promise, }; const manager: TerminalManager = { getTerminal: () => terminal, - getTerminalState: readSnapshot, + replayTerminal: replayFixture(readReplay), getTerminals: async () => [terminal], createTerminal: async () => terminal, registerCwdEnv() {}, @@ -1026,7 +1060,7 @@ describe("terminal output before natural exit", () => { "flushes each observer's final bytes before exit (modern=%s)", async (modern) => { vi.useFakeTimers(); - const f = exitFixture(async () => ({ state: terminalState("snapshot"), revision: 0 })); + const f = exitFixture(async () => terminalReplay("snapshot", 0)); try { const source = {}; const owners = [ @@ -1048,7 +1082,7 @@ describe("terminal output before natural exit", () => { row.message.payload.subscriptionId === owner.id)), ); expect(ordered.map((row) => row.binary?.opcode ?? row.message?.type)).toEqual([ - TerminalStreamOpcode.Snapshot, + TerminalStreamOpcode.Restore, TerminalStreamOpcode.Output, TerminalStreamOpcode.Output, "terminal_stream_exit", @@ -1068,7 +1102,7 @@ describe("terminal output before natural exit", () => { test("waits for bootstrap snapshot and flushes buffered bytes without starting backpressure work", async () => { vi.useFakeTimers(); - const snapshot = deferred(); + const snapshot = deferred(); let reads = 0; const f = exitFixture(() => { reads++; @@ -1081,10 +1115,10 @@ describe("terminal output before natural exit", () => { f.exit(); await vi.advanceTimersByTimeAsync(0); expect(f.frames.map((row) => row.message?.type)).toEqual(["subscribe_terminal_response"]); - snapshot.resolve({ state: terminalState("snapshot"), revision: 0 }); + snapshot.resolve(terminalReplay("snapshot", 0)); await vi.advanceTimersByTimeAsync(0); expect(f.frames.slice(1).map((row) => row.binary?.opcode ?? row.message?.type)).toEqual([ - TerminalStreamOpcode.Snapshot, + TerminalStreamOpcode.Restore, TerminalStreamOpcode.Output, "terminal_stream_exit", ]); @@ -1104,11 +1138,10 @@ describe("terminal output before natural exit", () => { "finishes an in-flight backpressure snapshot (available=%s)", async (available) => { vi.useFakeTimers(); - const snapshot = deferred(); + const snapshot = deferred(); let reads = 0; const f = exitFixture( - async () => - ++reads === 1 ? { state: terminalState("initial"), revision: 0 } : snapshot.promise, + async () => (++reads === 1 ? terminalReplay("initial", 0) : snapshot.promise), true, ); try { @@ -1122,10 +1155,7 @@ describe("terminal output before natural exit", () => { await vi.advanceTimersByTimeAsync(0); expect(f.frames.some((row) => row.message?.type === "terminal_stream_exit")).toBe(false); if (available === "rejected") snapshot.reject(new Error("Snapshot failed during exit")); - else - snapshot.resolve( - available ? { state: terminalState("pressure-snapshot"), revision: 1 } : null, - ); + else snapshot.resolve(available ? terminalReplay("pressure-snapshot", 1) : null); await vi.advanceTimersByTimeAsync(0); const output = f.frames .filter((row) => row.binary?.opcode === TerminalStreamOpcode.Output) @@ -1145,7 +1175,7 @@ describe("terminal output before natural exit", () => { test("release during exit's pending snapshot suppresses late delivery", async () => { vi.useFakeTimers(); - const snapshot = deferred(); + const snapshot = deferred(); const f = exitFixture(() => snapshot.promise); const source = {}; try { @@ -1158,7 +1188,7 @@ describe("terminal output before natural exit", () => { subscriptionId: owner.id!, }; const release = f.delivery.request(source, request, () => f.delivery.release(owner.id!)); - snapshot.resolve({ state: terminalState("snapshot"), revision: 0 }); + snapshot.resolve(terminalReplay("snapshot", 0)); await release; await vi.advanceTimersByTimeAsync(0); expect(f.frames.map((row) => row.message?.type)).toEqual(["subscribe_terminal_response"]); @@ -1173,7 +1203,7 @@ describe("terminal output before natural exit", () => { test("explicit release discards only that observer's trailing output", async () => { vi.useFakeTimers(); - const f = exitFixture(async () => ({ state: terminalState("snapshot"), revision: 0 })); + const f = exitFixture(async () => terminalReplay("snapshot", 0)); const source = {}; try { const a = await f.subscribe(source, true, "a"); @@ -1221,8 +1251,8 @@ describe("terminal snapshot failure", () => { let reads = 0; const f = exitFixture(async () => { if (++reads === (phase === "backpressure" ? 2 : 1)) - throw new Error("Terminal worker request timed out: getTerminalState"); - return { state: terminalState("healthy"), revision: 0 }; + throw new Error("Terminal worker request timed out: replayTerminal"); + return terminalReplay("healthy", 0); }, phase === "backpressure"); try { const source = {}; @@ -1250,7 +1280,7 @@ describe("terminal snapshot failure", () => { payload: { terminalId: "exit-terminal", subscriptionId: failed.id, - error: "Terminal worker request timed out: getTerminalState", + error: "Terminal worker request timed out: replayTerminal", }, }, ]); @@ -1281,7 +1311,7 @@ describe("terminal snapshot failure", () => { ); test("release during pending rejection suppresses the failure and completes cleanup", async () => { - const snapshot = deferred(); + const snapshot = deferred(); const f = exitFixture(() => snapshot.promise); const source = {}; try { @@ -1293,7 +1323,7 @@ describe("terminal snapshot failure", () => { subscriptionId: owner.id!, }; const release = f.delivery.request(source, request, () => f.delivery.release(owner.id!)); - snapshot.reject(new Error("Terminal worker request timed out: getTerminalState")); + snapshot.reject(new Error("Terminal worker request timed out: replayTerminal")); await release; expect(f.frames.map((row) => row.message?.type)).toEqual(["subscribe_terminal_response"]); expect(f.delivery.registrationCount).toBe(0); @@ -1313,7 +1343,7 @@ test.each([false, true])( let reads = 0; const f = exitFixture(async () => { if (++reads === (backpressure ? 2 : 1)) throw new Error("Snapshot unavailable"); - return { state: terminalState("recovered"), revision: 0 }; + return terminalReplay("recovered", 0); }, backpressure); try { await f.subscribe({}, false, "legacy-recovery"); @@ -1327,7 +1357,7 @@ test.each([false, true])( for (const listener of f.outputs) listener({ type: "snapshotReady", revision: 2 }); await vi.advanceTimersByTimeAsync(5); expect(reads).toBe(backpressure ? 3 : 2); - expect(f.frames.some((row) => row.binary?.opcode === TerminalStreamOpcode.Snapshot)).toBe( + expect(f.frames.some((row) => row.binary?.opcode === TerminalStreamOpcode.Restore)).toBe( true, ); f.exit(); @@ -1347,3 +1377,51 @@ test.each([false, true])( } }, ); + +test("bounds a capturing viewer tail without ending a healthy viewer", async () => { + const pending = deferred(); + let reads = 0; + const f = exitFixture(() => + ++reads === 2 ? pending.promise : Promise.resolve(terminalReplay("retained", 0)), + ); + const desktop = {}, + phone = {}; + try { + await f.subscribe(desktop, true, "desktop"); + await waitForCoalescerFlush(); + await f.subscribe(phone, true, "phone"); + f.output("x".repeat(4 * 1024 * 1024 + 1), 1); + await waitForCoalescerFlush(); + expect( + f.frames.filter( + (row) => row.source === phone && row.message?.type === "terminal_stream_exit", + ), + ).toHaveLength(1); + expect( + f.frames.filter( + (row) => row.source === desktop && row.message?.type === "terminal_stream_exit", + ), + ).toHaveLength(0); + expect( + f.frames.some( + (row) => row.source === desktop && row.binary?.opcode === TerminalStreamOpcode.Output, + ), + ).toBe(true); + pending.resolve(terminalReplay("phone", 1)); + await waitForCoalescerFlush(); + f.output("AFTER-OVERFLOW", 2); + await waitForCoalescerFlush(); + expect( + f.frames.some( + (row) => + row.source === desktop && + row.binary?.opcode === TerminalStreamOpcode.Output && + Buffer.from(row.binary.payload).toString().includes("AFTER-OVERFLOW"), + ), + ).toBe(true); + expect(f.delivery.registrationCount).toBe(1); + } finally { + pending.resolve(null); + await f.delivery.close(); + } +}); diff --git a/packages/server/src/terminal/terminal-session-controller.ts b/packages/server/src/terminal/terminal-session-controller.ts index e41186fdb1..653524e54a 100644 --- a/packages/server/src/terminal/terminal-session-controller.ts +++ b/packages/server/src/terminal/terminal-session-controller.ts @@ -28,13 +28,12 @@ import { TerminalOutputCoalescer } from "./terminal-output-coalescer.js"; import { MAX_CLIENT_BUFFERED_BYTES, MAX_TERMINAL_OUTPUT_FRAME_BYTES, - encodeLegacyTerminalSnapshotFrame, - encodeTerminalRestoreFrame, + createTerminalRestoreDelivery, resolveRestoreAfterOutputOverflow, resolveTerminalRestoreSnapshotOptions, - resolveTerminalSubscriptionSnapshotMode, type TerminalRestoreOptions, } from "./terminal-restore.js"; +import type { TerminalReplayMetadata } from "./terminal-replay.js"; import type { TerminalSession } from "./terminal.js"; import type { TerminalManager, TerminalsChangedEvent } from "./terminal-manager.js"; import { applyTerminalSize } from "./terminal-size-ownership.js"; @@ -68,31 +67,28 @@ interface ActiveTerminalStream { needsSnapshot: boolean; snapshotInFlight: boolean; retrySnapshotErrors: boolean; - readyRevision?: number; + // Readiness is independent of revision: reconnect adoption has no revision. + snapshotReady: boolean; restore?: TerminalRestoreOptions; bufferedOutputs: BufferedTerminalOutput[]; + bufferedOutputBytes: number; outputBytesSinceSnapshot: number; outputCoalescer: TerminalOutputCoalescer; } -interface SnapshotSendResult { - shouldContinue: boolean; - replayRevision?: number; -} +type SnapshotSendResult = + | { shouldContinue: false } + | { shouldContinue: true; replay: TerminalReplayMetadata | null }; export interface TerminalSessionControllerOptions { terminalManager: TerminalManager | null; emit: (msg: SessionOutboundMessage) => void; hasBinaryChannel: () => boolean; + supportsChunkedReplay?: (source: object) => boolean; isPathWithinRoot: (rootPath: string, candidatePath: string) => boolean; sessionLogger: pino.Logger; listTerminalWorkspaceRefs?: () => Promise; listTerminalWorkspaceRoots?: () => Promise; - // Whether the connected client can reflow restored snapshots. When true the - // daemon attaches per-row soft-wrap flags to snapshots; otherwise it omits them - // so old (strict-schema) clients still parse the snapshot. - clientSupportsWrapReflow?: (source: object) => boolean; - // Current max bytes queued on the client's transport(s) but not yet sent. // Drives the snapshot catch-up fallback: a keeping-up client reports ~0 and // keeps streaming; a backed-up client trips the snapshot path. Defaults to a // constant 0 (no backpressure signal) so callers without a transport always @@ -145,7 +141,6 @@ export class TerminalSessionController { private readonly sessionLogger: pino.Logger; private readonly listTerminalWorkspaceRefs: () => Promise; private readonly listTerminalWorkspaceRoots: () => Promise; - private readonly clientSupportsWrapReflow: (source: object) => boolean; private readonly getClientBufferedAmount: (source: object) => number | null; private readonly subscribedDirectories = new Map(); @@ -153,7 +148,7 @@ export class TerminalSessionController { private readonly activeStreams = new Map(); private nextSlot = 0; - constructor(options: TerminalSessionControllerOptions) { + constructor(private readonly options: TerminalSessionControllerOptions) { this.terminalManager = options.terminalManager; this.emit = options.emit; this.hasBinaryChannel = options.hasBinaryChannel; @@ -163,7 +158,6 @@ export class TerminalSessionController { this.listTerminalWorkspaceRoots = options.listTerminalWorkspaceRoots ?? (async () => (await this.listTerminalWorkspaceRefs()).map((workspace) => workspace.cwd)); - this.clientSupportsWrapReflow = options.clientSupportsWrapReflow ?? (() => false); this.getClientBufferedAmount = options.getClientBufferedAmount ?? (() => 0); } @@ -904,9 +898,10 @@ export class TerminalSessionController { snapshotInFlight: false, retrySnapshotErrors: options.retrySnapshotErrors, exiting: false, - readyRevision: undefined, + snapshotReady: false, restore: options?.restore, bufferedOutputs: [], + bufferedOutputBytes: 0, outputBytesSinceSnapshot: 0, outputCoalescer: new TerminalOutputCoalescer({ timers: { setTimeout, clearTimeout }, @@ -934,7 +929,6 @@ export class TerminalSessionController { // The snapshot replaces this batch only after it succeeds. If the // terminal disappears during the read, completion still owns these bytes. activeStream.snapshotOutput = payload; - activeStream.restore = resolveRestoreAfterOutputOverflow(activeStream.restore); activeStream.needsSnapshot = true; void this.trySendSnapshot(activeStream); return; @@ -952,35 +946,45 @@ export class TerminalSessionController { this.activeStreams.set(slot, activeStream); - const unsubscribeOutput = terminal.subscribe( - (message) => { - if (this.activeStreams.get(slot) !== activeStream) { - return; - } - if (message.type === "snapshot" || message.type === "snapshotReady") { - activeStream.readyRevision = message.revision; - activeStream.outputCoalescer.flush(); - activeStream.needsSnapshot = true; - void this.trySendSnapshot(activeStream); - return; - } - if (message.type === "titleChange") { - return; - } - if (message.data.length === 0) { - return; - } - if (activeStream.needsSnapshot || activeStream.snapshotInFlight) { - activeStream.bufferedOutputs.push({ - data: message.data, - revision: message.revision, + const unsubscribeOutput = terminal.subscribe((message) => { + if (this.activeStreams.get(slot) !== activeStream) { + return; + } + if (message.type === "snapshotReady") { + activeStream.snapshotReady = true; + activeStream.outputCoalescer.flush(); + activeStream.needsSnapshot = true; + void this.trySendSnapshot(activeStream); + return; + } + if (message.type === "titleChange") { + return; + } + if (message.data.length === 0) { + return; + } + if (activeStream.needsSnapshot || activeStream.snapshotInFlight) { + activeStream.bufferedOutputBytes += Buffer.byteLength(message.data); + if (activeStream.bufferedOutputBytes > MAX_CLIENT_BUFFERED_BYTES) { + activeStream.owner.emit({ + type: "terminal_stream_exit", + payload: { + terminalId: activeStream.terminalId, + error: "Terminal replay live tail exceeded the buffer; attach again", + }, }); + this.detachRegistration(activeStream); + void activeStream.owner.release(); return; } - activeStream.outputCoalescer.handle(message.data); - }, - { initialSnapshot: resolveTerminalSubscriptionSnapshotMode(options?.restore) }, - ); + activeStream.bufferedOutputs.push({ + data: message.data, + revision: message.revision, + }); + return; + } + activeStream.outputCoalescer.handle(message.data); + }); const unsubscribeExit = terminal.onExit(() => this.detachStream(terminal.id, { emitExit: true }), ); @@ -1017,22 +1021,27 @@ export class TerminalSessionController { this.detachStream(activeStream.terminalId, { emitExit: true }); return; } - if (activeStream.restore && activeStream.readyRevision === undefined) { + if (activeStream.restore && !activeStream.snapshotReady) { return; } activeStream.outputCoalescer.flush(); activeStream.snapshotInFlight = true; try { - const restore = activeStream.restore; + // A pressure catch-up replaces the skipped batch with a recent window. + // Keep the subscription demand intact for later adoption/full restores. + const restore = + activeStream.snapshotOutput !== undefined + ? resolveRestoreAfterOutputOverflow(activeStream.restore) + : activeStream.restore; const snapshotResult = restore ? await this.emitRestoreSnapshot(activeStream, terminalManager, restore) - : await this.emitLegacySnapshot(activeStream, terminalManager); + : await this.emitRestoreSnapshot(activeStream, terminalManager, { mode: "full-snapshot" }); if (!snapshotResult.shouldContinue) { return; } activeStream.snapshotOutput = undefined; - this.replayTerminalOutputAfterSnapshot(activeStream, terminal, snapshotResult.replayRevision); + this.replayTerminalOutputAfterSnapshot(activeStream, terminal, snapshotResult.replay); activeStream.needsSnapshot = false; activeStream.outputBytesSinceSnapshot = 0; } catch (error) { @@ -1070,47 +1079,31 @@ export class TerminalSessionController { } } - private async emitLegacySnapshot( - activeStream: ActiveTerminalStream, - terminalManager: TerminalManager, - ): Promise { - const snapshot = await terminalManager.getTerminalState(activeStream.terminalId, { - includeWrapFlags: this.clientSupportsWrapReflow(activeStream.owner.source), - }); - if (this.activeStreams.get(activeStream.slot) !== activeStream) { - return { shouldContinue: false }; - } - if (!snapshot) { - this.detachStream(activeStream.terminalId, { emitExit: true }); - return { shouldContinue: false }; - } - - activeStream.owner.emitBinary( - encodeLegacyTerminalSnapshotFrame({ - slot: activeStream.slot, - snapshot, - }), - ); - // The snapshot frame went out-of-band; keep the replay that follows on the - // coalescer's trailing path so it doesn't flush back-to-back with it. - activeStream.outputCoalescer.markFlushed(); - return { shouldContinue: true, replayRevision: snapshot.revision }; - } - private async emitRestoreSnapshot( activeStream: ActiveTerminalStream, terminalManager: TerminalManager, restore: TerminalRestoreOptions, ): Promise { - const snapshotOptions = resolveTerminalRestoreSnapshotOptions(restore); + const chunked = this.options.supportsChunkedReplay?.(activeStream.owner.source) === true; + const snapshotOptions = resolveTerminalRestoreSnapshotOptions({ restore, chunked }); if (snapshotOptions === null) { - return { shouldContinue: true }; + return { shouldContinue: true, replay: null }; } - const snapshot = await terminalManager.getTerminalState(activeStream.terminalId, { - ...snapshotOptions, - includeWrapFlags: this.clientSupportsWrapReflow(activeStream.owner.source), + const deliver = createTerminalRestoreDelivery({ + slot: activeStream.slot, + chunked, + // Network delivery belongs to the bounded application transport, not the worker request. + send: (frame) => activeStream.owner.emitBinary(frame), }); + const snapshot = await terminalManager.replayTerminal( + activeStream.terminalId, + snapshotOptions, + (event) => { + if (this.activeStreams.get(activeStream.slot) !== activeStream) return; + deliver(event); + }, + ); if (this.activeStreams.get(activeStream.slot) !== activeStream) { return { shouldContinue: false }; } @@ -1119,38 +1112,31 @@ export class TerminalSessionController { return { shouldContinue: false }; } - activeStream.owner.emitBinary( - encodeTerminalRestoreFrame({ - slot: activeStream.slot, - snapshot, - }), - ); // The restore frame went out-of-band; keep the replay that follows on the // coalescer's trailing path so it doesn't flush back-to-back with it. activeStream.outputCoalescer.markFlushed(); - return { shouldContinue: true, replayRevision: snapshot.revision }; + return { shouldContinue: true, replay: snapshot }; } private replayTerminalOutputAfterSnapshot( activeStream: ActiveTerminalStream, terminal: TerminalSession, - replayRevision: number | undefined, + replay: TerminalReplayMetadata | null, ): void { - const replayPreamble = terminal.getReplayPreamble(); + // A captured viewer must start from its cut, then apply the buffered mode changes. + // Live-only subscriptions have no capture and start from the current shared modes. + const replayPreamble = replay === null ? terminal.getReplayPreamble() : replay.replayPreamble; if (replayPreamble.length > 0) { activeStream.outputCoalescer.handle(replayPreamble); } + activeStream.bufferedOutputBytes = 0; const bufferedOutputs = activeStream.bufferedOutputs.splice( 0, activeStream.bufferedOutputs.length, ); for (const output of bufferedOutputs) { - if ( - replayRevision !== undefined && - output.revision !== undefined && - output.revision <= replayRevision - ) { + if (replay !== null && output.revision !== undefined && output.revision <= replay.revision) { continue; } activeStream.outputCoalescer.handle(output.data); diff --git a/packages/server/src/terminal/terminal-worker-client.test.ts b/packages/server/src/terminal/terminal-worker-client.test.ts index a363ab500d..01a4dd91d3 100644 --- a/packages/server/src/terminal/terminal-worker-client.test.ts +++ b/packages/server/src/terminal/terminal-worker-client.test.ts @@ -72,3 +72,46 @@ describe("terminal worker authentication", () => { await waitUntil(() => !existsSync(recordPath), 10_000); }); }); + +it("bounds a stalled framed writer to one chunk and resumes in order", async () => { + const { createServer, createConnection } = await import("node:net"); + const { attachFramedSocket } = await import("./terminal-worker-frames.js"); + const server = createServer(); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Missing test address"); + const accepted = new Promise((resolve) => + server.once("connection", resolve), + ); + const reader = createConnection(address.port, "127.0.0.1"); + reader.pause(); + const writer = await accepted; + const framed = attachFramedSocket(writer, () => {}); + let completed = 0; + let peakQueuedBytes = 0; + const received: number[] = []; + attachFramedSocket(reader, (value) => received.push((value as { index: number }).index)); + const sending = (async () => { + for (let index = 0; index < 512; index++) { + const pending = framed.sendAndWait({ index, data: Buffer.alloc(64 * 1024) }); + peakQueuedBytes = Math.max(peakQueuedBytes, writer.writableLength); + await pending; + completed++; + } + })(); + try { + await waitUntil(() => writer.writableLength > 0, 10000); + await new Promise((resolve) => setTimeout(resolve, 100)); + expect(completed).toBeLessThan(512); + expect(peakQueuedBytes).toBeLessThan(65 * 1024); + reader.resume(); + await sending; + await waitUntil(() => received.length === 512, 10000); + expect(received).toEqual(Array.from({ length: 512 }, (_, index) => index)); + expect(writer.destroyed).toBe(false); + } finally { + reader.destroy(); + writer.destroy(); + await new Promise((resolve) => server.close(() => resolve())); + } +}); diff --git a/packages/server/src/terminal/terminal-worker-frames.ts b/packages/server/src/terminal/terminal-worker-frames.ts index f0b990e239..897e91826f 100644 --- a/packages/server/src/terminal/terminal-worker-frames.ts +++ b/packages/server/src/terminal/terminal-worker-frames.ts @@ -50,6 +50,7 @@ export class FrameDecoder { export interface FramedSocket { readonly socket: Socket; send(message: unknown, callback?: (error: Error | null) => void): boolean; + sendAndWait(message: unknown): Promise; close(): void; } @@ -91,6 +92,17 @@ export function attachFramedSocket( } return socket.write(frame, (error) => callback?.(error ?? null)); }, + sendAndWait(message) { + return new Promise((resolve, reject) => { + this.send(message, (error) => { + if (error) { + reject(error); + return; + } + resolve(); + }); + }); + }, close() { socket.end(() => socket.destroy()); }, diff --git a/packages/server/src/terminal/terminal-worker-pool.ts b/packages/server/src/terminal/terminal-worker-pool.ts index f15ad5b46d..517d34aa33 100644 --- a/packages/server/src/terminal/terminal-worker-pool.ts +++ b/packages/server/src/terminal/terminal-worker-pool.ts @@ -5,7 +5,7 @@ import type { TerminalsChangedListener, TerminalWorkspaceContributionChangedListener, } from "./terminal-manager.js"; -import type { TerminalSession, TerminalStateSnapshot } from "./terminal.js"; +import type { TerminalSession } from "./terminal.js"; import type { WorkerCreateTerminalOptions } from "./terminal-worker-protocol.js"; import type { DaemonTerminalManager } from "./worker-terminal-manager.js"; @@ -217,8 +217,8 @@ export function createTerminalWorkerPool( return undefined; }, - async getTerminalState(id, stateOptions): Promise { - return routed(id).getTerminalState(id, stateOptions); + async replayTerminal(id, replayOptions, sink) { + return routed(id).replayTerminal(id, replayOptions, sink); }, setTerminalTitle(id, title) { diff --git a/packages/server/src/terminal/terminal-worker-process.ts b/packages/server/src/terminal/terminal-worker-process.ts index 6c13ba04d5..b3e8864f9d 100644 --- a/packages/server/src/terminal/terminal-worker-process.ts +++ b/packages/server/src/terminal/terminal-worker-process.ts @@ -1,3 +1,4 @@ +import { createTerminalReplayController } from "./terminal-replay.js"; import { spawn } from "node:child_process"; import { randomBytes, timingSafeEqual } from "node:crypto"; import { chmodSync, closeSync, existsSync, openSync, rmSync, writeSync } from "node:fs"; @@ -6,13 +7,8 @@ import { fileURLToPath } from "node:url"; import { currentBootId } from "../server/pid-lock.js"; import { PRIVATE_FILE_MODE } from "../server/private-files.js"; import { createTerminalManager } from "./terminal-manager.js"; -import { captureTerminalLines } from "./terminal-capture.js"; import { TerminalOutputCoalescer } from "./terminal-output-coalescer.js"; -import type { - TerminalExitInfo, - TerminalSession, - TerminalStateSnapshotOptions, -} from "./terminal.js"; +import type { TerminalExitInfo, LocalTerminalSession } from "./terminal.js"; import { attachFramedSocket, type FramedSocket } from "./terminal-worker-frames.js"; import { createTerminalWorkerProcessInspector } from "./terminal-worker-processes.js"; import { @@ -30,7 +26,6 @@ import { type TerminalWorkerHelloAck, type TerminalWorkerListResult, type TerminalWorkerRequest, - type TerminalWorkerStateResult, type TerminalWorkerToParentMessage, type WorkerTerminalInfo, } from "./terminal-worker-protocol.js"; @@ -177,7 +172,7 @@ function runWorker(argv: string[]): void { const protocolVersion = reportedProtocolVersion(); const manager = createTerminalManager(); const inspector = createTerminalWorkerProcessInspector(); - const sessionsById = new Map(); + const sessionsById = new Map(); const unsubscribeByTerminalId = new Map void>>(); const outputCoalescerByTerminalId = new Map(); // A terminal is published (terminalCreated) only once its program is recorded. An exit that @@ -211,10 +206,12 @@ function runWorker(argv: string[]): void { reportInFlightTerminalCreateFailure(error); }); + const replayController = createTerminalReplayController({ + getSession: (id) => sessionsById.get(id), + flushOutput: (id) => outputCoalescerByTerminalId.get(id)?.flush(), + }); function sendToController(message: TerminalWorkerToParentMessage): void { - // With no controller the event is dropped; the headless terminal keeps the screen, and the - // next daemon reads it through listTerminals. - controller?.send(message); + replayController.send(message); } function persistRecord(): void { @@ -259,17 +256,11 @@ function runWorker(argv: string[]): void { } } - function buildTerminalStateResult( - session: TerminalSession | undefined, - options?: TerminalStateSnapshotOptions, - ): TerminalWorkerStateResult { - if (!session) { - return null; - } - return { ...session.getStateSnapshot(options), replayPreamble: session.getReplayPreamble() }; + function terminalMetadata(session: LocalTerminalSession) { + return { ...session.getSize(), hasOutput: session.hasOutput(), title: session.getTitle() }; } - function toTerminalInfo(session: TerminalSession): WorkerTerminalInfo { + function toTerminalInfo(session: LocalTerminalSession): WorkerTerminalInfo { return { id: session.id, name: session.name, @@ -316,7 +307,7 @@ function runWorker(argv: string[]): void { } } - function watchTerminal(session: TerminalSession): void { + function watchTerminal(session: LocalTerminalSession): void { clearTerminalSubscriptions(session.id); // Coalesce pty output chunks into a single frame per ~5ms window so a burst of small @@ -338,28 +329,22 @@ function runWorker(argv: string[]): void { }); outputCoalescerByTerminalId.set(session.id, outputCoalescer); - const unsubscribeMessage = session.subscribe( - (message) => { - if (message.type === "output") { - pendingOutputRevision = message.revision; - outputCoalescer.handle(message.data); - return; - } - // Non-output messages (snapshot/snapshotReady/titleChange) must not jump - // ahead of buffered output: flush the coalescer first, then forward. - outputCoalescer.flush(); - sendToController({ - type: "terminalMessage", - terminalId: session.id, - message, - replayPreamble: session.getReplayPreamble(), - }); - }, - // Creation already sends an authoritative state in terminalCreated. A second - // asynchronous state snapshot can arrive after the create response and - // overwrite a resize issued immediately by the caller. - { initialSnapshot: "ready" }, - ); + const unsubscribeMessage = session.subscribe((message) => { + if (message.type === "output") { + pendingOutputRevision = message.revision; + outputCoalescer.handle(message.data); + return; + } + // Non-output messages (snapshotReady/titleChange) must not jump + // ahead of buffered output: flush the coalescer first, then forward. + outputCoalescer.flush(); + sendToController({ + type: "terminalMessage", + terminalId: session.id, + message, + replayPreamble: session.getReplayPreamble(), + }); + }); const unsubscribeExit = session.onExit((info) => { outputCoalescer.flush(); clearTerminalSubscriptions(session.id); @@ -413,7 +398,7 @@ function runWorker(argv: string[]): void { // A terminal enters the record only with its program's birth time, so cleanup can always // tell the program from a later process that reuses its pid. A program that already exited // needs no entry; one whose birth time cannot be read is killed and the create fails. - async function recordTerminalProgram(session: TerminalSession): Promise { + async function recordTerminalProgram(session: LocalTerminalSession): Promise { if (session.getExitInfo()) return; // The manager drops a session as soon as its program exits, so only a live one has a pid. const pid = manager.getTerminalProcessId(session.id); @@ -476,11 +461,19 @@ function runWorker(argv: string[]): void { await session.killAndWait().catch(() => undefined); throw error; } - const initialSnapshot = session.getStateSnapshot(); + const state = terminalMetadata(session); sendToController({ type: "terminalCreated", terminal: toTerminalInfo(session), - state: initialSnapshot.state, + state, + }); + // Startup output/readiness may have arrived while recording the program, + // before the daemon knew this terminal. Publish its current modes after creation. + sendToController({ + type: "terminalMessage", + terminalId: session.id, + message: { type: "snapshotReady" }, + replayPreamble: session.getReplayPreamble(), }); sendToController({ type: "response", @@ -488,7 +481,7 @@ function runWorker(argv: string[]): void { ok: true, result: { terminal: toTerminalInfo(session), - state: initialSnapshot.state, + state, }, }); const heldExit = exitsHeldDuringCreation.get(session.id); @@ -513,7 +506,7 @@ function runWorker(argv: string[]): void { outputCoalescerByTerminalId.get(session.id)?.flush(); return { terminal: toTerminalInfo(session), - state: session.getStateSnapshot().state, + state: terminalMetadata(session), activityToken: manager.getTerminalActivityToken(session.id), replayPreamble: session.getReplayPreamble(), }; @@ -559,28 +552,15 @@ function runWorker(argv: string[]): void { return; } - case "getTerminalState": { - // Flush buffered output before snapshotting: the headless state already includes it, - // so if the coalescer emitted it afterward (in a batch carrying a revision past the - // snapshot's) the controller's revision dedup wouldn't drop it and the client would - // see the bytes twice. Flushing first sends them with a revision <= the snapshot's. - outputCoalescerByTerminalId.get(message.terminalId)?.flush(); - sendToController({ - type: "response", - requestId: message.requestId, - ok: true, - result: buildTerminalStateResult( - manager.getTerminal(message.terminalId), - message.options, - ), - }); + case "replayTerminal": { + await replayController.replay(message); return; } case "captureTerminal": { const session = manager.getTerminal(message.terminalId); const result = session - ? captureTerminalLines(session, { + ? session.captureLines({ start: message.start, end: message.end, stripAnsi: message.stripAnsi, @@ -659,10 +639,9 @@ function runWorker(argv: string[]): void { } authenticated = true; // One controller at a time: a new authenticated connection replaces the old one. - const previous = controller; controller = framed; + replayController.setConnection(framed); everControlled = true; - previous?.socket.destroy(); const ack: TerminalWorkerHelloAck = { type: "helloAck", pid: process.pid, @@ -688,6 +667,7 @@ function runWorker(argv: string[]): void { clearTimeout(helloTimer); if (controller === framed) { controller = null; + replayController.setConnection(null); exitIfIdle(); } }); diff --git a/packages/server/src/terminal/terminal-worker-protocol.test.ts b/packages/server/src/terminal/terminal-worker-protocol.test.ts index c3810bf9cf..6ea9a823db 100644 --- a/packages/server/src/terminal/terminal-worker-protocol.test.ts +++ b/packages/server/src/terminal/terminal-worker-protocol.test.ts @@ -2,18 +2,24 @@ import { describe, expect, it } from "vitest"; import { classifyTerminalWorkerProtocol } from "./terminal-worker-protocol.js"; describe("classifyTerminalWorkerProtocol", () => { + it("rejects the unreleased cell protocol without a draining adapter", () => { + expect(classifyTerminalWorkerProtocol(1, 2)).toBe("obsolete"); + expect(classifyTerminalWorkerProtocol(2, 3)).toBe("obsolete"); + expect(classifyTerminalWorkerProtocol(3, 4)).toBe("obsolete"); + expect(classifyTerminalWorkerProtocol(4, 5)).toBe("obsolete"); + }); it.each([ - [5, "current"], - [4, "previous"], - [3, "obsolete"], + [6, "current"], + [5, "previous"], + [4, "obsolete"], [-1, "obsolete"], - [6, "newer"], + [7, "newer"], // A version this daemon cannot read comes from a Paseo it does not know. ["6", "newer"], [4.5, "newer"], [Number.NaN, "newer"], [undefined, "newer"], - ])("a worker reporting %s to a daemon at 5 is %s", (reported, fit) => { - expect(classifyTerminalWorkerProtocol(reported, 5)).toBe(fit); + ])("a worker reporting %s to a daemon at 6 is %s", (reported, fit) => { + expect(classifyTerminalWorkerProtocol(reported, 6)).toBe(fit); }); }); diff --git a/packages/server/src/terminal/terminal-worker-protocol.ts b/packages/server/src/terminal/terminal-worker-protocol.ts index 86fc4a7772..e781543697 100644 --- a/packages/server/src/terminal/terminal-worker-protocol.ts +++ b/packages/server/src/terminal/terminal-worker-protocol.ts @@ -1,11 +1,11 @@ -import type { - TerminalExitInfo, - ServerMessage, - ClientMessage, - TerminalStateSnapshot, - TerminalStateSnapshotOptions, -} from "./terminal.js"; -import type { TerminalState } from "@getpaseo/protocol/messages"; +import type { TerminalExitInfo, ServerMessage, ClientMessage } from "./terminal.js"; +import type { TerminalReplayEvent, TerminalReplayOptions } from "./terminal-replay.js"; +export interface WorkerTerminalState { + rows: number; + cols: number; + hasOutput: boolean; + title?: string; +} import type { TerminalActivity, TerminalActivityState } from "@getpaseo/protocol/terminal-activity"; import type { CaptureTerminalLinesResult } from "./terminal-capture.js"; @@ -43,7 +43,7 @@ export interface WorkerCreateTerminalOptions { // `shutdown`. A daemon drives a worker of its own version, drains one a version older (no new // terminals; it exits after its last terminal), shuts down anything older, and leaves a newer // worker running untouched. See docs/terminal-worker.md. -export const TERMINAL_WORKER_PROTOCOL_VERSION = 1; +export const TERMINAL_WORKER_PROTOCOL_VERSION = 5; // Test-only: the protocol version a worker reports, so tests can stand up older and newer // workers from one build. @@ -59,7 +59,8 @@ export function classifyTerminalWorkerProtocol( // A version this daemon cannot read comes from a Paseo it does not know: treat it as newer. if (typeof reported !== "number" || !Number.isSafeInteger(reported)) return "newer"; if (reported === current) return "current"; - if (reported === current - 1) return "previous"; + // Protocols 1 through 4 were unreleased; they have no draining adapter. + if (reported === current - 1 && reported >= 5) return "previous"; return reported < current ? "obsolete" : "newer"; } @@ -77,7 +78,7 @@ export interface TerminalWorkerHelloAck { export interface WorkerListedTerminal { terminal: WorkerTerminalInfo; - state: TerminalState; + state: WorkerTerminalState; activityToken: string | null; replayPreamble: string; } @@ -122,10 +123,10 @@ export type TerminalWorkerRequest = options?: WorkerKillAndWaitOptions; } | { - type: "getTerminalState"; + type: "replayTerminal"; requestId: string; terminalId: string; - options?: TerminalStateSnapshotOptions; + options?: TerminalReplayOptions; } | { type: "captureTerminal"; @@ -166,10 +167,11 @@ export type TerminalWorkerResponse = }; export type TerminalWorkerEvent = + | { type: "terminalReplay"; requestId: string; event: TerminalReplayEvent } | { type: "terminalCreated"; terminal: WorkerTerminalInfo; - state: TerminalState; + state: WorkerTerminalState; } | { type: "terminalMessage"; @@ -206,6 +208,3 @@ export type TerminalWorkerToParentMessage = TerminalWorkerResponse | TerminalWor export type TerminalWorkerListResult = WorkerListedTerminal[]; export type TerminalWorkerCaptureResult = CaptureTerminalLinesResult; -// The worker fills TerminalStateSnapshot.replayPreamble on getTerminalState so -// the parent can cache the input-mode preamble instead of re-deriving it. -export type TerminalWorkerStateResult = TerminalStateSnapshot | null; diff --git a/packages/server/src/terminal/terminal.posix.test.ts b/packages/server/src/terminal/terminal.posix.test.ts index 4452fb6c1f..474507f771 100644 --- a/packages/server/src/terminal/terminal.posix.test.ts +++ b/packages/server/src/terminal/terminal.posix.test.ts @@ -1,3 +1,5 @@ +import { readTerminalState } from "./test-utils/terminal-state.js"; +import type { TerminalState } from "@getpaseo/protocol/messages"; // POSIX-only: node-pty + POSIX shell assertions /* eslint-disable max-nested-callbacks */ import { describe, it, expect, afterEach } from "vitest"; @@ -6,7 +8,7 @@ import { buildTerminalEnvironment, createTerminal, resolveZshShellIntegrationDir, - type TerminalSession, + type LocalTerminalSession as TerminalSession, } from "./terminal.js"; import { chmodSync, @@ -28,7 +30,7 @@ if (isPlatform("win32") && !process.env.ComSpec && !process.env.COMSPEC) { process.env.ComSpec = "C:\\Windows\\System32\\cmd.exe"; } -type TerminalRow = ReturnType["grid"][number]; +type TerminalRow = TerminalState["grid"][number]; function rowToText(row: TerminalRow): string { return row @@ -38,12 +40,12 @@ function rowToText(row: TerminalRow): string { } // Extract text from a single row -function getRowText(state: ReturnType, rowIndex: number): string { +function getRowText(state: TerminalState, rowIndex: number): string { return rowToText(state.grid[rowIndex]); } // Extract all visible lines as array (trimmed, empty lines included) -function getLines(state: ReturnType): string[] { +function getLines(state: TerminalState): string[] { return state.grid.map(rowToText); } @@ -55,7 +57,7 @@ async function waitForLines( ): Promise { const start = Date.now(); while (Date.now() - start < timeoutMs) { - const lines = getLines(session.getState()); + const lines = getLines(await readTerminalState(session)); let matches = true; for (let i = 0; i < expectedLines.length; i++) { if (lines[i] !== expectedLines[i]) { @@ -68,7 +70,7 @@ async function waitForLines( } await new Promise((resolve) => setTimeout(resolve, 50)); } - const actual = getLines(session.getState()).slice(0, expectedLines.length); + const actual = getLines(await readTerminalState(session)).slice(0, expectedLines.length); throw new Error( `Timeout waiting for expected lines.\nExpected:\n${JSON.stringify(expectedLines, null, 2)}\nActual:\n${JSON.stringify(actual, null, 2)}`, ); @@ -76,12 +78,12 @@ async function waitForLines( async function waitForState( session: TerminalSession, - predicate: (state: ReturnType) => boolean, + predicate: (state: TerminalState) => boolean, timeoutMs = 5000, -): Promise> { +): Promise { const start = Date.now(); while (Date.now() - start < timeoutMs) { - const state = session.getState(); + const state = await readTerminalState(session); if (predicate(state)) { return state; } @@ -232,19 +234,19 @@ function isOsc11OkLine(line: string): boolean { return line.startsWith("OSC11_OK:"); } -function hasDaOkLine(state: ReturnType): boolean { +function hasDaOkLine(state: TerminalState): boolean { return getLines(state).some(isDaOkLine); } -function hasDsrOkLine(state: ReturnType): boolean { +function hasDsrOkLine(state: TerminalState): boolean { return getLines(state).some(isDsrOkLine); } -function hasOsc11OkLine(state: ReturnType): boolean { +function hasOsc11OkLine(state: TerminalState): boolean { return getLines(state).some(isOsc11OkLine); } -function lastNonEmptyLineIsPrompt(state: ReturnType): boolean { +function lastNonEmptyLineIsPrompt(state: TerminalState): boolean { const last = getLines(state) .toReversed() @@ -322,7 +324,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { // Line 2: "$" await waitForLines(session, ["$ echo hello", "hello", "$"]); - const state = session.getState(); + const state = await readTerminalState(session); expect(getRowText(state, 0)).toBe("$ echo hello"); expect(getRowText(state, 1)).toBe("hello"); expect(getRowText(state, 2)).toBe("$"); @@ -346,7 +348,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { session.send({ type: "input", data: "echo second\r" }); await waitForLines(session, ["$ echo first", "first", "$ echo second", "second", "$"]); - const state = session.getState(); + const state = await readTerminalState(session); expect(getRowText(state, 0)).toBe("$ echo first"); expect(getRowText(state, 1)).toBe("first"); expect(getRowText(state, 2)).toBe("$ echo second"); @@ -370,7 +372,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { await waitForLines(session, ["$ pwd", "/tmp", "$"]); - const state = session.getState(); + const state = await readTerminalState(session); expect(getRowText(state, 0)).toBe("$ pwd"); expect(getRowText(state, 1)).toBe("/tmp"); expect(getRowText(state, 2)).toBe("$"); @@ -431,7 +433,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { expect(seenTitles).toContain("npm run dev"); expect(session.getTitle()).toBe("npm run dev"); - expect(session.getState().title).toBe("npm run dev"); + expect(session.getTitle()).toBe("npm run dev"); unsubscribeTitle(); }); @@ -457,7 +459,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { expect(seenTitles).toContain("Build Log"); expect(session.getTitle()).toBe("Build Log"); - expect(session.getState().title).toBe("Build Log"); + expect(session.getTitle()).toBe("Build Log"); unsubscribeTitle(); }); @@ -478,7 +480,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { await new Promise((resolve) => setTimeout(resolve, 150)); expect(session.getTitle()).toBe("typecheck"); - expect(session.getState().title).toBe("typecheck"); + expect(session.getTitle()).toBe("typecheck"); }); it("emits command completion from VS Code OSC 633 without visible output", async () => { @@ -507,7 +509,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { await waitForState(session, () => commandCompletions.length === 1); expect(commandCompletions).toEqual([7]); - expect(getLines(session.getState()).join("\n")).not.toContain("633;D;7"); + expect(getLines(await readTerminalState(session)).join("\n")).not.toContain("633;D;7"); unsubscribeCommandFinished(); }); @@ -541,7 +543,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { await waitForState(session, () => commandCompletions.length === 1); expect(commandCompletions).toEqual([3]); - expect(getLines(session.getState()).join("\n")).not.toContain("633;D;garbage"); + expect(getLines(await readTerminalState(session)).join("\n")).not.toContain("633;D;garbage"); unsubscribeCommandFinished(); }); @@ -696,7 +698,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { await waitForState(session, () => commandCompletions.includes(1)); expect(commandCompletions).toEqual([1]); - expect(getLines(session.getState()).join("\n")).not.toContain("633;D;1"); + expect(getLines(await readTerminalState(session)).join("\n")).not.toContain("633;D;1"); unsubscribeCommandFinished(); }); @@ -720,7 +722,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { await waitForLines(session, ["$ printf '\\033[31mRED\\033[0m'", "RED$"]); - const state = session.getState(); + const state = await readTerminalState(session); const outputRow = state.grid[1]; expect(outputRow[0].char).toBe("R"); @@ -750,7 +752,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { await waitForLines(session, ["$ printf '\\033[38;5;208mORG\\033[0m'", "ORG$"]); - const state = session.getState(); + const state = await readTerminalState(session); const outputRow = state.grid[1]; // Check O cell @@ -776,7 +778,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { await waitForLines(session, ["$ printf '\\033[38;2;255;128;64mRGB\\033[0m'", "RGB$"]); - const state = session.getState(); + const state = await readTerminalState(session); const outputRow = state.grid[1]; // Check R cell @@ -805,7 +807,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { await waitForLines(session, ["$ printf '\\033[41mBG\\033[0m'", "BG$"]); - const state = session.getState(); + const state = await readTerminalState(session); const outputRow = state.grid[1]; expect(outputRow[0].char).toBe("B"); @@ -815,7 +817,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { }); describe("subscribe", () => { - it("receives a snapshot on initial subscription", async () => { + it("receives readiness on initial subscription", async () => { const session = trackSession( await createTerminal({ workspaceId: "ws-test", @@ -831,7 +833,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { await new Promise((resolve) => setTimeout(resolve, 100)); expect(messages.length).toBeGreaterThan(0); - expect(messages[0].type).toBe("snapshot"); + expect(messages[0].type).toBe("snapshotReady"); unsubscribe(); }); @@ -861,12 +863,14 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { await waitForLines(session, ["$ echo test", "test", "$"]); expect(messages.some((message) => message.type === "output")).toBe(true); - expect(messages.some((message) => message.type === "snapshot")).toBe(false); + expect( + messages.every((message) => message.type === "output" || message.type === "titleChange"), + ).toBe(true); unsubscribe(); }); - it("does not emit snapshot messages for resize-only updates", async () => { + it("keeps resize updates in the live observation lifecycle", async () => { const session = trackSession( await createTerminal({ workspaceId: "ws-test", @@ -889,13 +893,15 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { session.send({ type: "resize", rows: 30, cols: 100 }); await new Promise((resolve) => setTimeout(resolve, 200)); - expect(messages.some((message) => message.type === "snapshot")).toBe(false); + expect( + messages.every((message) => message.type === "output" || message.type === "titleChange"), + ).toBe(true); expect(session.getSize()).toEqual({ rows: 30, cols: 100 }); unsubscribe(); }); - it("emits output only after getState reflects the new data", async () => { + it("emits output only after text capture reflects the new data", async () => { const session = trackSession( await createTerminal({ workspaceId: "ws-test", @@ -912,7 +918,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { return; } unsubscribe(); - const stateText = getLines(session.getState()).join("\n"); + const stateText = session.captureLines().lines.join("\n"); resolve(stateText.includes("state-after-output")); }); }); @@ -965,7 +971,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { session.send({ type: "input", data: `${process.execPath} ${helperPath}\r` }); await waitForState(session, hasDaOkLine); - const ack = getLines(session.getState()).find(isDaOkLine) ?? ""; + const ack = getLines(await readTerminalState(session)).find(isDaOkLine) ?? ""; expect(ack).toMatch(/^DA_OK:\[\?[\d;]+c$/); }); @@ -1003,7 +1009,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { session.send({ type: "input", data: `${process.execPath} ${helperPath} cursor\r` }); await waitForState(session, hasDsrOkLine); - const ack = getLines(session.getState()).find(isDsrOkLine) ?? ""; + const ack = getLines(await readTerminalState(session)).find(isDsrOkLine) ?? ""; expect(ack).toMatch(/^DSR_OK:\d+:\d+$/); }); @@ -1023,7 +1029,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { session.send({ type: "input", data: `${process.execPath} ${helperPath} private-cursor\r` }); await waitForState(session, hasDsrOkLine); - const ack = getLines(session.getState()).find(isDsrOkLine) ?? ""; + const ack = getLines(await readTerminalState(session)).find(isDsrOkLine) ?? ""; expect(ack).toMatch(/^DSR_OK:\d+:\d+$/); }); @@ -1043,7 +1049,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { session.send({ type: "input", data: `${process.execPath} ${helperPath} status\r` }); await waitForState(session, hasDsrOkLine); - const ack = getLines(session.getState()).find(isDsrOkLine) ?? ""; + const ack = getLines(await readTerminalState(session)).find(isDsrOkLine) ?? ""; expect(ack).toBe("DSR_OK:status"); }); @@ -1063,7 +1069,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { session.send({ type: "input", data: `${process.execPath} ${helperPath}\r` }); await waitForState(session, hasOsc11OkLine); - const ack = getLines(session.getState()).find(isOsc11OkLine) ?? ""; + const ack = getLines(await readTerminalState(session)).find(isOsc11OkLine) ?? ""; expect(ack).toBe("OSC11_OK:ESC]11;rgb:0b0b/0b0b/0b0bESC\\"); }); }); @@ -1097,7 +1103,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { unsubscribe(); }); - it("sends the current snapshot to a new subscriber instead of replaying raw output", async () => { + it("announces readiness for a fresh replay instead of replaying raw live output", async () => { const session = trackSession( await createTerminal({ workspaceId: "ws-test", @@ -1121,26 +1127,24 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { "$", ]); - let snapshotText = ""; - const unsubscribe = session.subscribe((message) => { - if (message.type !== "snapshot") { - return; - } - snapshotText = [...message.state.scrollback, ...message.state.grid] - .map(rowToText) - .join("\n"); + let ready!: () => void; + const readiness = new Promise((resolve) => { + ready = resolve; }); - - await new Promise((resolve) => setTimeout(resolve, 100)); - - expect(snapshotText).toContain("before-detach"); - expect(snapshotText).toContain("after-detach"); + const unsubscribe = session.subscribe((message) => { + if (message.type === "snapshotReady") ready(); + }); + await readiness; + const state = await readTerminalState(session); + const text = [...state.scrollback, ...state.grid].map(rowToText).join("\n"); + expect(text).toContain("before-detach"); + expect(text).toContain("after-detach"); unsubscribe(); }); }); - describe("getState", () => { - it("returns current terminal state with grid", async () => { + describe("ANSI replay observation", () => { + it("reconstructs current terminal state from ANSI", async () => { const session = trackSession( await createTerminal({ workspaceId: "ws-test", @@ -1152,7 +1156,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { }), ); - const state = session.getState(); + const state = await readTerminalState(session); expect(state.rows).toBe(24); expect(state.cols).toBe(80); @@ -1179,19 +1183,16 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { await waitForLines(session, ["$"]); session.send({ type: "input", data: "printf '\\033[2 q\\033[?25l'\r" }); - const state = await waitForState( - session, - (current) => - current.cursor.style === "block" && - current.cursor.blink === false && - current.cursor.hidden === true, + const deadline = Date.now() + 5000; + while ( + !new TextDecoder().decode(session.serializeReplay().data).includes("\x1b[?25l\x1b[2 q") + ) { + if (Date.now() > deadline) throw new Error("cursor presentation did not reach replay"); + await new Promise((resolve) => setTimeout(resolve, 20)); + } + expect(new TextDecoder().decode(session.serializeReplay().data)).toContain( + "\x1b[?25l\x1b[2 q", ); - - expect(state.cursor).toMatchObject({ - style: "block", - blink: false, - hidden: true, - }); }); it("grid cells have char and color attributes", async () => { @@ -1206,7 +1207,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { await waitForLines(session, ["$"]); - const state = session.getState(); + const state = await readTerminalState(session); // First cell should be "$" expect(state.grid[0][0].char).toBe("$"); expect(state.grid[0][0]).toHaveProperty("fg"); @@ -1238,7 +1239,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { // The visible area will show something like: 17, 18, 19, 20, $ await waitForLines(session, ["17", "18", "19", "20", "$"]); - const state = session.getState(); + const state = await readTerminalState(session); // Scrollback should contain the earlier output expect(state.scrollback.length).toBeGreaterThan(0); @@ -1269,7 +1270,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { session.kill(); // Should not throw when trying to get state after kill - const state = session.getState(); + const state = await readTerminalState(session); expect(state).toBeDefined(); }); diff --git a/packages/server/src/terminal/terminal.test.ts b/packages/server/src/terminal/terminal.test.ts index 751fb1b33a..69e6468673 100644 --- a/packages/server/src/terminal/terminal.test.ts +++ b/packages/server/src/terminal/terminal.test.ts @@ -1,3 +1,7 @@ +import { TerminalInputModeTracker } from "@getpaseo/protocol/terminal-input-mode"; +import { createTerminalSerializer } from "./terminal-serializer.js"; +import { readTerminalState } from "./test-utils/terminal-state.js"; +import type { TerminalState } from "@getpaseo/protocol/messages"; import { describe, it, expect, afterEach, vi } from "vitest"; import { isPlatform } from "../test-utils/platform.js"; import { @@ -10,7 +14,7 @@ import { humanizeProcessTitle, normalizeProcessTitle, resolveZshShellIntegrationDir, - type TerminalSession, + type LocalTerminalSession as TerminalSession, } from "./terminal.js"; import { chmodSync, @@ -26,7 +30,6 @@ import { import { spawnSync } from "node:child_process"; import * as pty from "node-pty"; import xterm from "@xterm/headless"; -import { renderTerminalSnapshotToAnsi } from "@getpaseo/protocol/terminal-snapshot"; import { delimiter, join } from "node:path"; import { tmpdir } from "node:os"; import { setImmediate as waitForImmediate, setTimeout as delay } from "node:timers/promises"; @@ -34,7 +37,7 @@ import { stripVTControlCharacters } from "node:util"; const hasZsh = existsSync("/bin/zsh"); -type TerminalRow = ReturnType["grid"][number]; +type TerminalRow = TerminalState["grid"][number]; function rowToText(row: TerminalRow): string { return row @@ -44,12 +47,12 @@ function rowToText(row: TerminalRow): string { } // Extract text from a single row -function getRowText(state: ReturnType, rowIndex: number): string { +function getRowText(state: TerminalState, rowIndex: number): string { return rowToText(state.grid[rowIndex]); } // Extract all visible lines as array (trimmed, empty lines included) -function getLines(state: ReturnType): string[] { +function getLines(state: TerminalState): string[] { return state.grid.map(rowToText); } @@ -65,7 +68,7 @@ async function waitForLines( ): Promise { const start = Date.now(); while (Date.now() - start < timeoutMs) { - const lines = getLines(session.getState()); + const lines = getLines(await readTerminalState(session)); let matches = true; for (let i = 0; i < expectedLines.length; i++) { if (lines[i] !== expectedLines[i]) { @@ -78,7 +81,7 @@ async function waitForLines( } await new Promise((resolve) => setTimeout(resolve, 50)); } - const actual = getLines(session.getState()).slice(0, expectedLines.length); + const actual = getLines(await readTerminalState(session)).slice(0, expectedLines.length); throw new Error( `Timeout waiting for expected lines.\nExpected:\n${JSON.stringify(expectedLines, null, 2)}\nActual:\n${JSON.stringify(actual, null, 2)}`, ); @@ -86,12 +89,12 @@ async function waitForLines( async function waitForState( session: TerminalSession, - predicate: (state: ReturnType) => boolean, + predicate: (state: TerminalState) => boolean, timeoutMs = 5000, -): Promise> { +): Promise { const start = Date.now(); while (Date.now() - start < timeoutMs) { - const state = session.getState(); + const state = await readTerminalState(session); if (predicate(state)) { return state; } @@ -473,7 +476,7 @@ describe("createTerminal", () => { }), ); - const state = session.getState(); + const state = await readTerminalState(session); expect(state.rows).toBe(24); expect(state.cols).toBe(80); }); @@ -493,12 +496,12 @@ describe("createTerminal", () => { }), ); - const state = session.getState(); + const state = await readTerminalState(session); expect(state.rows).toBe(40); expect(state.cols).toBe(120); }); - it("reports per-row soft-wrap flags only when wrap flags are requested", async () => { + it("preserves soft-wrap boundaries through public replay", async () => { const session = trackSession( await createTerminal({ workspaceId: "ws-test", @@ -513,21 +516,15 @@ describe("createTerminal", () => { const start = Date.now(); while (Date.now() - start < 5000) { - if (rowToText(session.getState().grid[2]).startsWith("A")) { + if (rowToText((await readTerminalState(session)).grid[2]).startsWith("A")) { break; } await new Promise((resolve) => setTimeout(resolve, 50)); } // Rows 0 and 1 continue onto the next row; row 2 is the end of the logical line. - const withFlags = session.getState({ includeWrapFlags: true }); + const withFlags = await readTerminalState(session); expect(withFlags.gridWrapped?.slice(0, 3)).toEqual([true, true, false]); - - // Back-compat gate: without the capability the daemon must not attach the new - // fields, so an old strict-schema client still parses the snapshot. - const withoutFlags = session.getState(); - expect(withoutFlags.gridWrapped).toBeUndefined(); - expect(withoutFlags.scrollbackWrapped).toBeUndefined(); }); it("restores CJK text without injected spaces when a snapshot round-trips through the client", async () => { @@ -555,9 +552,7 @@ describe("createTerminal", () => { // row back the way a selection copy would. const restored = new xterm.Terminal({ cols: 80, rows: 10, allowProposedApi: true }); try { - await new Promise((resolve) => - restored.write(renderTerminalSnapshotToAnsi(state), resolve), - ); + await new Promise((resolve) => restored.write(session.serializeReplay().data, resolve)); expect(restored.buffer.active.getLine(0)?.translateToString(true)).toBe(text); } finally { restored.dispose(); @@ -615,11 +610,8 @@ describe("createTerminal", () => { // Poll the parsed buffer until the final line lands, so the exit summary // (which reads the headless buffer) can't race the async xterm parse. - const finalLineParsed = (): boolean => { - const state = session.getState(); - const rowText = (row: { char: string }[]): string => row.map((cell) => cell.char).join(""); - return [...state.scrollback, ...state.grid].some((row) => rowText(row).includes("line-2999")); - }; + const finalLineParsed = (): boolean => + session.captureLines({ start: -12 }).lines.some((line) => line.includes("line-2999")); const deadline = Date.now() + 10000; while (!finalLineParsed()) { if (Date.now() > deadline) { @@ -678,7 +670,7 @@ describe("createTerminal", () => { ); await waitForLines(session, ["paseo-launch-ok"]); - expect(getLines(session.getState())[0]).toBe("paseo-launch-ok"); + expect(getLines(await readTerminalState(session))[0]).toBe("paseo-launch-ok"); }, ); @@ -721,7 +713,7 @@ describe("createTerminal", () => { ); await waitForLines(session, ["paseo-launch-ok"]); - expect(getLines(session.getState())[0]).toBe("paseo-launch-ok"); + expect(getLines(await readTerminalState(session))[0]).toBe("paseo-launch-ok"); }, ); @@ -743,7 +735,7 @@ describe("createTerminal", () => { ); await waitForLines(session, ["paseo-launch-ok"]); - expect(getLines(session.getState())[0]).toBe("paseo-launch-ok"); + expect(getLines(await readTerminalState(session))[0]).toBe("paseo-launch-ok"); }); it("leaves the command check to the terminal itself on Windows", async () => { @@ -807,7 +799,7 @@ describe.skipIf(isPlatform("win32"))("send input", () => { // Line 2: "$" await waitForLines(session, ["$ echo hello", "hello", "$"]); - const state = session.getState(); + const state = await readTerminalState(session); expect(getRowText(state, 0)).toBe("$ echo hello"); expect(getRowText(state, 1)).toBe("hello"); expect(getRowText(state, 2)).toBe("$"); @@ -829,7 +821,7 @@ describe.skipIf(isPlatform("win32"))("send input", () => { await waitForLines(session, ["$ pwd", "/tmp", "$"]); - const state = session.getState(); + const state = await readTerminalState(session); expect(getRowText(state, 0)).toBe("$ pwd"); expect(getRowText(state, 1)).toBe("/tmp"); expect(getRowText(state, 2)).toBe("$"); @@ -890,7 +882,6 @@ describe.skipIf(isPlatform("win32"))("terminal title", () => { expect(seenTitles).toContain("npm run dev"); expect(session.getTitle()).toBe("npm run dev"); - expect(session.getState().title).toBe("npm run dev"); unsubscribeTitle(); }); @@ -916,7 +907,6 @@ describe.skipIf(isPlatform("win32"))("terminal title", () => { expect(seenTitles).toContain("Build Log"); expect(session.getTitle()).toBe("Build Log"); - expect(session.getState().title).toBe("Build Log"); unsubscribeTitle(); }); @@ -937,7 +927,6 @@ describe.skipIf(isPlatform("win32"))("terminal title", () => { await new Promise((resolve) => setTimeout(resolve, 150)); expect(session.getTitle()).toBe("typecheck"); - expect(session.getState().title).toBe("typecheck"); }); it("emits command completion from VS Code OSC 633 without visible output", async () => { @@ -966,7 +955,7 @@ describe.skipIf(isPlatform("win32"))("terminal title", () => { await waitForState(session, () => commandCompletions.length === 1); expect(commandCompletions).toEqual([7]); - expect(getLines(session.getState()).join("\n")).not.toContain("633;D;7"); + expect(getLines(await readTerminalState(session)).join("\n")).not.toContain("633;D;7"); unsubscribeCommandFinished(); }); @@ -1000,7 +989,7 @@ describe.skipIf(isPlatform("win32"))("terminal title", () => { await waitForState(session, () => commandCompletions.length === 1); expect(commandCompletions).toEqual([3]); - expect(getLines(session.getState()).join("\n")).not.toContain("633;D;garbage"); + expect(getLines(await readTerminalState(session)).join("\n")).not.toContain("633;D;garbage"); unsubscribeCommandFinished(); }); @@ -1155,7 +1144,7 @@ describe.skipIf(isPlatform("win32"))("terminal title", () => { await waitForState(session, () => commandCompletions.includes(1)); expect(commandCompletions).toEqual([1]); - expect(getLines(session.getState()).join("\n")).not.toContain("633;D;1"); + expect(getLines(await readTerminalState(session)).join("\n")).not.toContain("633;D;1"); unsubscribeCommandFinished(); }); @@ -1189,7 +1178,6 @@ describe.skipIf(isPlatform("win32"))("terminal title", () => { expect(seenTitles).toEqual(["Build Log", "User terminal"]); expect(session.getTitle()).toBe("User terminal"); - expect(session.getState().title).toBe("User terminal"); unsubscribeTitle(); }); @@ -1219,7 +1207,6 @@ describe.skipIf(isPlatform("win32"))("terminal title", () => { expect(seenTitles).toEqual(["Build Log", "User terminal"]); expect(session.getTitle()).toBe("User terminal"); - expect(session.getState().title).toBe("User terminal"); unsubscribeTitle(); }); @@ -1248,7 +1235,6 @@ describe.skipIf(isPlatform("win32"))("terminal title", () => { expect(seenTitles).toEqual(["Build Log", "User terminal"]); expect(session.getTitle()).toBe("User terminal"); - expect(session.getState().title).toBe("User terminal"); unsubscribeTitle(); }); @@ -1272,7 +1258,7 @@ describe.skipIf(isPlatform("win32"))("colors", () => { await waitForLines(session, ["$ printf '\\033[31mRED\\033[0m'", "RED$"]); - const state = session.getState(); + const state = await readTerminalState(session); const outputRow = state.grid[1]; expect(outputRow[0].char).toBe("R"); @@ -1302,7 +1288,7 @@ describe.skipIf(isPlatform("win32"))("colors", () => { await waitForLines(session, ["$ printf '\\033[38;2;255;128;64mRGB\\033[0m'", "RGB$"]); - const state = session.getState(); + const state = await readTerminalState(session); const outputRow = state.grid[1]; // Check R cell @@ -1331,7 +1317,7 @@ describe.skipIf(isPlatform("win32"))("colors", () => { await waitForLines(session, ["$ printf '\\033[41mBG\\033[0m'", "BG$"]); - const state = session.getState(); + const state = await readTerminalState(session); const outputRow = state.grid[1]; expect(outputRow[0].char).toBe("B"); @@ -1355,7 +1341,7 @@ describe("resize", () => { await new Promise((resolve) => setTimeout(resolve, 100)); - const state = session.getState(); + const state = await readTerminalState(session); expect(state.rows).toBe(40); expect(state.cols).toBe(120); }); @@ -1373,7 +1359,7 @@ describe("resize", () => { session.send({ type: "resize", rows: 10, cols: 40 }); await new Promise((resolve) => setTimeout(resolve, 100)); - const state = session.getState(); + const state = await readTerminalState(session); expect(state.grid.length).toBe(10); expect(state.grid[0].length).toBe(40); }); @@ -1552,7 +1538,7 @@ it.runIf(isPlatform("linux", "darwin"))( env: { PATH: "bin" }, }); await waitForLines(session, ["paseo-launch-ok"]); - expect(getLines(session.getState())[0]).toBe("paseo-launch-ok"); + expect(getLines(await readTerminalState(session))[0]).toBe("paseo-launch-ok"); expect(session.cwd).toBe(realpathSync(projectDir)); expect(session.getExitInfo()).toBeNull(); } finally { @@ -1574,3 +1560,309 @@ it.runIf(isPlatform("linux", "darwin"))( ).rejects.toThrow(" node : command not found"); }, ); + +it.each([false, true])( + "serializes styled Unicode, cursor presentation and modes directly (alternate=%s)", + async (alternate) => { + // Exercise the serializer's input model directly. ConPTY renders program + // output: it consumes input modes and need not publish a hidden cursor move. + const terminal = new xterm.Terminal({ + rows: 4, + cols: 16, + scrollback: 10000, + allowProposedApi: true, + }); + const serialize = createTerminalSerializer(terminal); + const inputModes = new TerminalInputModeTracker(); + const content = + Array.from({ length: 8 }, (_, i) => "normal-" + i + "\r\n").join("") + + (alternate ? "\x1b[?1049h\x1b[H" : "") + + "\x1b[38;2;255;128;64;4m界é🙂\x1b[0m\r\nVIEW-READY\x1b[?1h\x1b[?2004h\x1b[>1u\x1b[?9001h\x1b[?7l\x1b[?1000h\x1b[5 q\x1b[?25l"; + const output = content + "\x1b[2;7H"; + await new Promise((resolve) => terminal.write(output, resolve)); + inputModes.feed(output); + const data = serialize(); + const ansi = new TextDecoder().decode(data); + expect(ansi).toContain("\x1b[?25l\x1b[5 q"); + expect(ansi).not.toContain("NaN"); + expect(terminal.buffer.normal.baseY).toBeGreaterThan(0); + const receiver = new xterm.Terminal({ + rows: 4, + cols: 16, + scrollback: 10000, + allowProposedApi: true, + }); + try { + await new Promise((resolve) => receiver.write(data, resolve)); + await new Promise((resolve) => receiver.write(inputModes.getPreamble(), resolve)); + expect(receiver.buffer.active.type).toBe(alternate ? "alternate" : "normal"); + const lines = Array.from({ length: receiver.buffer.active.length }, (_, i) => + receiver.buffer.active.getLine(i)!.translateToString(true), + ); + expect(lines.join("\n")).toContain("界é🙂"); + expect(lines.join("\n")).toContain("VIEW-READY"); + const coloredIndex = lines.findIndex((line) => line.includes("界")); + const colored = receiver.buffer.active.getLine(coloredIndex)!.getCell(0)!; + expect(colored.getChars()).toBe("界"); + expect(colored.getFgColor()).toBe(0xff8040); + expect(colored.isUnderline()).not.toBe(0); + expect(receiver.buffer.normal.getLine(0)!.translateToString(true)).toBe("normal-0"); + expect({ row: receiver.buffer.active.cursorY, col: receiver.buffer.active.cursorX }).toEqual({ + row: 1, + col: 6, + }); + expect(receiver.modes).toMatchObject({ + applicationCursorKeysMode: true, + bracketedPasteMode: true, + wraparoundMode: false, + mouseTrackingMode: "vt200", + }); + const modes = new TerminalInputModeTracker(); + modes.feed(ansi + inputModes.getPreamble()); + expect(modes.getState()).toMatchObject({ + kittyKeyboardFlags: 1, + win32InputMode: true, + applicationCursorKeys: true, + bracketedPaste: true, + }); + } finally { + receiver.dispose(); + terminal.dispose(); + } + }, +); + +it.each([ + { name: "unset", presentation: "", style: undefined, visible: true }, + { + name: "reset to client default", + presentation: "\x1b[5 q\x1b[0 q", + style: undefined, + visible: true, + }, + { name: "unset hidden", presentation: "\x1b[?25l", style: undefined, visible: false }, + ...[1, 2, 3, 4, 5, 6].map((style) => ({ + name: `explicit style ${style}`, + presentation: `\x1b[${style} q\x1b[?25l`, + style, + visible: false, + })), +])("replays cursor presentation without replacing client defaults ($name)", async (input) => { + const session = trackSession( + await createTerminal({ + cwd: realpathSync(tmpdir()), + workspaceId: "cursor-presentation", + command: process.execPath, + args: [ + "-e", + `process.stdout.write(${JSON.stringify(input.presentation + "CURSOR-READY\r\n")});setInterval(()=>{},1000)`, + ], + }), + ); + await waitForLines(session, ["CURSOR-READY"]); + const { data } = session.serializeReplay(); + const ansi = new TextDecoder().decode(data); + const receiver = new xterm.Terminal({ + cursorStyle: "bar", + cursorBlink: true, + allowProposedApi: true, + }); + const styles: number[] = []; + receiver.parser.registerCsiHandler({ intermediates: " ", final: "q" }, (params) => { + styles.push(Number(params[0])); + return false; + }); + try { + await new Promise((resolve) => receiver.write(data, resolve)); + expect(styles).toEqual(input.style === undefined ? [] : [input.style]); + expect(ansi).toContain(`\x1b[?25${input.visible ? "h" : "l"}`); + } finally { + receiver.dispose(); + } +}); + +it("captures input modes at the same committed cut as serialized bytes", async () => { + const session = trackSession( + await createTerminal({ + cwd: realpathSync(tmpdir()), + workspaceId: "mode-cut", + rows: 4, + cols: 80, + command: process.execPath, + args: [ + "-e", + 'process.stdin.on("data",()=>process.stdout.write("x".repeat(1024*1024)+"\x1b[?1hMODE-CUT"));setInterval(()=>{},1000)', + ], + }), + ); + const mismatches: string[] = []; + let completed!: () => void; + const output = new Promise((resolve) => { + completed = resolve; + }); + const unsubscribe = session.subscribe((message) => { + if (message.type !== "output") return; + if (session.getReplayPreamble().includes("\x1b[?1h")) { + const cut = session.serializeReplay({ scrollbackLines: 0 }); + if (!new TextDecoder().decode(cut.data).includes("\x1b[?1h")) + mismatches.push(cut.metadata.replayPreamble); + } + if (message.data.includes("MODE-CUT")) completed(); + }); + try { + session.send({ type: "input", data: "go\r" }); + await Promise.race([ + output, + delay(5000).then(() => { + throw new Error("mode cut did not complete"); + }), + ]); + expect(mismatches).toEqual([]); + } finally { + unsubscribe(); + } +}); + +it.each( + [false, true].flatMap((alternate) => [ + { + alternate, + pendingWrap: false, + position: "\x1b[3;16H", + cursor: { row: 2, col: 15 }, + after: { row: 2, col: 16 }, + }, + { + alternate, + pendingWrap: true, + position: "", + cursor: { row: 0, col: 16 }, + after: { row: 1, col: 1 }, + }, + ]), +)( + "replays a full-width row without losing cursor state ($alternate, pendingWrap=$pendingWrap)", + async (input) => { + const source = new xterm.Terminal({ + rows: 4, + cols: 16, + scrollback: 10000, + allowProposedApi: true, + }); + const serialize = createTerminalSerializer(source); + const receiver = new xterm.Terminal({ + rows: 4, + cols: 16, + scrollback: 10000, + allowProposedApi: true, + }); + try { + await new Promise((resolve) => + source.write( + (input.alternate ? "\x1b[?1049h" : "") + "x".repeat(16) + input.position, + resolve, + ), + ); + expect({ row: source.buffer.active.cursorY, col: source.buffer.active.cursorX }).toEqual( + input.cursor, + ); + await new Promise((resolve) => receiver.write(serialize(), resolve)); + expect({ row: receiver.buffer.active.cursorY, col: receiver.buffer.active.cursorX }).toEqual( + input.cursor, + ); + await new Promise((resolve) => receiver.write("Z", resolve)); + expect({ row: receiver.buffer.active.cursorY, col: receiver.buffer.active.cursorX }).toEqual( + input.after, + ); + } finally { + receiver.dispose(); + source.dispose(); + } + }, +); + +it.each([false, true])( + "replays the observed PTY projection including startup modes (alternate=%s)", + async (alternate) => { + const gate = mkdtempSync(join(tmpdir(), "terminal-projection-")); + temporaryDirs.push(gate); + const release = join(gate, "output"); + const content = + Array.from({ length: 8 }, (_, i) => `normal-${i}\r\n`).join("") + + (alternate ? "\x1b[?1049h\x1b[H" : "") + + "\x1b[38;2;255;128;64;4m界é🙂\x1b[0m\r\nVIEW-READY\x1b[?1h\x1b[?2004h\x1b[>1u\x1b[?9001h\x1b[?7l\x1b[?1000h\x1b[5 q\x1b[?25l\x1b[2;7H"; + const session = trackSession( + await createTerminal({ + cwd: realpathSync(tmpdir()), + workspaceId: "projection", + rows: 4, + cols: 16, + command: process.execPath, + args: [ + "-e", + `const fs=require("node:fs");let sent=false; + function emit(){if(!sent&&fs.existsSync(${JSON.stringify(release)})){sent=true;watcher.close();process.stdout.write(${JSON.stringify(content)});}} + const watcher=fs.watch(${JSON.stringify(gate)},emit);emit();setInterval(()=>{},1000);`, + ], + }), + ); + const bootstrap = session.serializeReplay(); + const output: string[] = []; + const unsubscribe = session.subscribe((message) => { + if (message.type === "output") output.push(message.data); + }); + const reference = new xterm.Terminal({ + rows: 4, + cols: 16, + scrollback: 10000, + allowProposedApi: true, + }); + const receiver = new xterm.Terminal({ + rows: 4, + cols: 16, + scrollback: 10000, + allowProposedApi: true, + }); + try { + await new Promise((resolve) => reference.write(bootstrap.data, resolve)); + await new Promise((resolve) => + reference.write(bootstrap.metadata.replayPreamble, resolve), + ); + writeFileSync(release, "release"); + const deadline = Date.now() + 5000; + while (!session.captureLines().lines.some((line) => line.includes("VIEW-READY"))) { + if (Date.now() > deadline) throw new Error("PTY did not render fixture output"); + await delay(20); + } + // Bootstrap and these committed output events cover precisely this source cut. + // Program bytes are not the oracle: ConPTY consumes modes and renders cells. + const replay = session.serializeReplay(); + const committed = output.join(""); + await new Promise((resolve) => reference.write(committed, resolve)); + await new Promise((resolve) => receiver.write(replay.data, resolve)); + await new Promise((resolve) => receiver.write(replay.metadata.replayPreamble, resolve)); + const text = (terminal: typeof receiver) => + Array.from({ length: terminal.buffer.active.length }, (_, i) => + terminal.buffer.active.getLine(i)!.translateToString(true).trimEnd(), + ); + expect(text(receiver)).toEqual(text(reference)); + expect(text(receiver).join("\n")).toContain("界é🙂"); + expect(text(receiver).join("\n")).toContain("VIEW-READY"); + expect(receiver.buffer.active.type).toBe(alternate ? "alternate" : "normal"); + expect({ row: receiver.buffer.active.cursorY, col: receiver.buffer.active.cursorX }).toEqual({ + row: reference.buffer.active.cursorY, + col: reference.buffer.active.cursorX, + }); + expect(receiver.modes).toEqual(reference.modes); + const expectedModes = new TerminalInputModeTracker(); + expectedModes.feed(bootstrap.metadata.replayPreamble + committed); + const actualModes = new TerminalInputModeTracker(); + actualModes.feed(new TextDecoder().decode(replay.data) + replay.metadata.replayPreamble); + expect(actualModes.getState()).toEqual(expectedModes.getState()); + } finally { + unsubscribe(); + receiver.dispose(); + reference.dispose(); + } + }, +); diff --git a/packages/server/src/terminal/terminal.ts b/packages/server/src/terminal/terminal.ts index b8cb7ee8cd..3294c11b93 100644 --- a/packages/server/src/terminal/terminal.ts +++ b/packages/server/src/terminal/terminal.ts @@ -25,7 +25,13 @@ import { findExecutable, findExecutableWithoutProbing, } from "../executable-resolution/executable-resolution.js"; -import type { TerminalCell, TerminalState } from "@getpaseo/protocol/messages"; +import { createTerminalSerializer } from "./terminal-serializer.js"; +import { + captureTerminalLines, + type CaptureTerminalLinesOptions, + type CaptureTerminalLinesResult, +} from "./terminal-capture.js"; +import type { TerminalReplayOptions, TerminalReplayMetadata } from "./terminal-replay.js"; import { TerminalInputModeTracker } from "@getpaseo/protocol/terminal-input-mode"; import { TerminalActivityTracker } from "./activity/terminal-activity-tracker.js"; import type { TerminalActivity, TerminalActivityState } from "@getpaseo/protocol/terminal-activity"; @@ -66,26 +72,6 @@ export interface TerminalCommandFinishedInfo { exitCode: number | null; } -export interface TerminalStateSnapshot { - state: TerminalState; - revision: number; - // Input-mode replay preamble at snapshot time. Populated by the terminal - // worker so the daemon main loop doesn't have to re-derive it from output. - replayPreamble?: string; -} - -export interface TerminalStateSnapshotOptions { - scrollbackLines?: number; - // Include per-row soft-wrap flags (gridWrapped/scrollbackWrapped) so the client - // can reflow restored content on resize. Gated on a client capability, so old - // clients never receive the extra fields. - includeWrapFlags?: boolean; -} - -export interface TerminalSubscribeOptions { - initialSnapshot?: "state" | "ready"; -} - export type ClientMessage = | { type: "input"; data: string } | { type: "resize"; rows: number; cols: number } @@ -93,7 +79,6 @@ export type ClientMessage = export type ServerMessage = | { type: "output"; data: string; revision?: number } - | { type: "snapshot"; state: TerminalState; revision?: number } | { type: "snapshotReady"; revision?: number; replayPreamble?: string } | { type: "titleChange"; title?: string }; @@ -108,14 +93,13 @@ export interface TerminalSession { cwd: string; workspaceId: string; send(msg: ClientMessage): void; - subscribe(listener: (msg: ServerMessage) => void, options?: TerminalSubscribeOptions): () => void; + subscribe(listener: (msg: ServerMessage) => void): () => void; onExit(listener: (info: TerminalExitInfo) => void): () => void; onCommandFinished(listener: (info: TerminalCommandFinishedInfo) => void): () => void; onTitleChange(listener: (title?: string) => void): () => void; onActivityChange(listener: (transition: TerminalActivityTransition) => void): () => void; getSize(): { rows: number; cols: number }; - getState(): TerminalState; - getStateSnapshot(options?: TerminalStateSnapshotOptions): TerminalStateSnapshot; + hasOutput(): boolean; getReplayPreamble(): string; getTitle(): string | undefined; getActivity(): TerminalActivity | null; @@ -130,6 +114,11 @@ export interface TerminalSession { /** A session that owns its PTY in this process, so it knows the program's pid. */ export interface LocalTerminalSession extends TerminalSession { readonly pid: number; + serializeReplay(options?: TerminalReplayOptions): { + metadata: TerminalReplayMetadata; + data: Uint8Array; + }; + captureLines(options?: CaptureTerminalLinesOptions): CaptureTerminalLinesResult; } function parseCommandFinishedOsc(data: string): TerminalCommandFinishedInfo | null { @@ -545,179 +534,6 @@ function prependPathEntry(currentPath: string, entry: string): string { return [entry, ...entries].join(delimiter); } -function extractCell(terminal: TerminalType, row: number, col: number): TerminalCell { - const buffer = terminal.buffer.active; - const line = buffer.getLine(row); - if (!line) { - return { char: " ", fg: undefined, bg: undefined }; - } - - const cell = line.getCell(col); - if (!cell) { - return { char: " ", fg: undefined, bg: undefined }; - } - - // Color modes from xterm.js: 0=DEFAULT, 1=16 colors (ANSI), 2=256 colors, 3=RGB - // getFgColorMode() returns packed value with mode in upper byte (e.g. 0x01000000 for mode 1) - const fgModeRaw = cell.getFgColorMode(); - const bgModeRaw = cell.getBgColorMode(); - const fgMode = fgModeRaw >> 24; - const bgMode = bgModeRaw >> 24; - - // Only return color if not default (mode 0) - const fg = fgMode !== 0 ? cell.getFgColor() : undefined; - const bg = bgMode !== 0 ? cell.getBgColor() : undefined; - - return { - // Wide chars (CJK) span two cells; xterm returns "" for the zero-width - // continuation. Collapsing it to " " injects a real space on restore. - char: cell.getWidth() === 0 ? "" : cell.getChars() || " ", - fg, - bg, - fgMode: fgMode !== 0 ? fgMode : undefined, - bgMode: bgMode !== 0 ? bgMode : undefined, - bold: cell.isBold() !== 0, - italic: cell.isItalic() !== 0, - underline: cell.isUnderline() !== 0, - dim: cell.isDim() !== 0, - inverse: cell.isInverse() !== 0, - strikethrough: cell.isStrikethrough() !== 0, - }; -} - -function extractGrid(terminal: TerminalType): TerminalCell[][] { - const grid: TerminalCell[][] = []; - const buffer = terminal.buffer.active; - // Visible viewport starts at baseY - const baseY = buffer.baseY; - - for (let row = 0; row < terminal.rows; row++) { - const rowCells: TerminalCell[] = []; - for (let col = 0; col < terminal.cols; col++) { - rowCells.push(extractCell(terminal, baseY + row, col)); - } - grid.push(rowCells); - } - - return grid; -} - -function extractScrollback( - terminal: TerminalType, - options?: { scrollbackLines?: number }, -): TerminalCell[][] { - const scrollback: TerminalCell[][] = []; - const buffer = terminal.buffer.active; - // baseY is the first row of the visible viewport (0-indexed) - // Lines 0 to baseY-1 are in scrollback, lines baseY onwards are visible - const scrollbackLines = buffer.baseY; - const startRow = - typeof options?.scrollbackLines === "number" - ? Math.max(0, scrollbackLines - options.scrollbackLines) - : 0; - - for (let row = startRow; row < scrollbackLines; row++) { - const rowCells: TerminalCell[] = []; - const line = buffer.getLine(row); - for (let col = 0; col < terminal.cols; col++) { - if (line) { - const cell = line.getCell(col); - if (cell) { - const fgModeRaw = cell.getFgColorMode(); - const bgModeRaw = cell.getBgColorMode(); - const fgMode = fgModeRaw >> 24; - const bgMode = bgModeRaw >> 24; - const fg = fgMode !== 0 ? cell.getFgColor() : undefined; - const bg = bgMode !== 0 ? cell.getBgColor() : undefined; - rowCells.push({ - // Wide chars (CJK) span two cells; xterm returns "" for the zero-width - // continuation. Collapsing it to " " injects a real space on restore. - char: cell.getWidth() === 0 ? "" : cell.getChars() || " ", - fg, - bg, - fgMode: fgMode !== 0 ? fgMode : undefined, - bgMode: bgMode !== 0 ? bgMode : undefined, - bold: cell.isBold() !== 0, - italic: cell.isItalic() !== 0, - underline: cell.isUnderline() !== 0, - dim: cell.isDim() !== 0, - inverse: cell.isInverse() !== 0, - strikethrough: cell.isStrikethrough() !== 0, - }); - } else { - rowCells.push({ char: " ", fg: undefined, bg: undefined }); - } - } else { - rowCells.push({ char: " ", fg: undefined, bg: undefined }); - } - } - scrollback.push(rowCells); - } - - return scrollback; -} - -// xterm marks a line `isWrapped` when it is a continuation of the PREVIOUS line. -// The snapshot carries the inverse, tmux-style flag — "this row continues onto the -// next row" — so the client can rejoin and reflow logical lines. So row y's flag is -// whether line y+1 is a wrapped continuation. -function lineContinuesToNext(terminal: TerminalType, absoluteRow: number): boolean { - return terminal.buffer.active.getLine(absoluteRow + 1)?.isWrapped === true; -} - -function extractGridWrapped(terminal: TerminalType): boolean[] { - const baseY = terminal.buffer.active.baseY; - const wrapped: boolean[] = []; - for (let row = 0; row < terminal.rows; row++) { - wrapped.push(lineContinuesToNext(terminal, baseY + row)); - } - return wrapped; -} - -function extractScrollbackWrapped( - terminal: TerminalType, - options?: { scrollbackLines?: number }, -): boolean[] { - const scrollbackLines = terminal.buffer.active.baseY; - const startRow = - typeof options?.scrollbackLines === "number" - ? Math.max(0, scrollbackLines - options.scrollbackLines) - : 0; - const wrapped: boolean[] = []; - for (let row = startRow; row < scrollbackLines; row++) { - wrapped.push(lineContinuesToNext(terminal, row)); - } - return wrapped; -} - -function extractCursorState(terminal: TerminalType): TerminalState["cursor"] { - const coreService = (terminal as unknown as { _core?: { coreService?: Record } }) - ._core?.coreService as - | { - decPrivateModes?: { cursorStyle?: unknown; cursorBlink?: unknown }; - isCursorHidden?: unknown; - } - | undefined; - const cursorStyle = coreService?.decPrivateModes?.cursorStyle; - const normalizedCursorStyle = - cursorStyle === "block" || cursorStyle === "underline" || cursorStyle === "bar" - ? cursorStyle - : undefined; - const cursorBlink = - typeof coreService?.decPrivateModes?.cursorBlink === "boolean" - ? coreService.decPrivateModes.cursorBlink - : undefined; - const hidden = Boolean(coreService?.isCursorHidden); - - return { - row: terminal.buffer.active.cursorY, - col: terminal.buffer.active.cursorX, - ...(hidden ? { hidden: true } : {}), - ...(normalizedCursorStyle ? { style: normalizedCursorStyle } : {}), - ...(typeof cursorBlink === "boolean" ? { blink: cursorBlink } : {}), - }; -} - function normalizeProcessToken(token: string): string { if (token.length === 0) { return token; @@ -984,10 +800,12 @@ export async function createTerminal( const terminal = new Terminal({ rows, cols, - scrollback: 1000, + scrollback: 10000, allowProposedApi: true, }); + const serialize = createTerminalSerializer(terminal); + ensureNodePtySpawnHelperExecutableForCurrentPlatform(); // Create PTY @@ -1224,6 +1042,10 @@ export async function createTerminal( if (disposed || killed) { return; } + // Commit protocol modes with the parsed bytes, so a replay cut cannot + // combine an older xterm buffer with modes from queued future output. + const inputModeUpdate = inputModeTracker.feed(data); + for (const response of inputModeUpdate.responses) ptyProcess.write(response); stateRevision += 1; for (const listener of listeners) { listener({ type: "output", data, revision: stateRevision }); @@ -1234,10 +1056,6 @@ export async function createTerminal( // Pipe PTY output to terminal emulator ptyProcess.onData((data) => { if (killed) return; - const inputModeUpdate = inputModeTracker.feed(data); - for (const response of inputModeUpdate.responses) { - ptyProcess.write(response); - } recentOutputChunks.push(data); recentOutputLength += data.length; // Drop whole leading chunks while the rest still covers the char limit, so @@ -1295,32 +1113,15 @@ export async function createTerminal( } } - function getState(snapshotOptions?: TerminalStateSnapshotOptions): TerminalState { - return { + function serializeReplay(replayOptions?: TerminalReplayOptions) { + const metadata = { rows: terminal.rows, cols: terminal.cols, - grid: extractGrid(terminal), - scrollback: extractScrollback(terminal, { - scrollbackLines: snapshotOptions?.scrollbackLines, - }), - cursor: extractCursorState(terminal), - ...(title ? { title } : {}), - ...(snapshotOptions?.includeWrapFlags - ? { - gridWrapped: extractGridWrapped(terminal), - scrollbackWrapped: extractScrollbackWrapped(terminal, { - scrollbackLines: snapshotOptions?.scrollbackLines, - }), - } - : {}), - }; - } - - function getStateSnapshot(snapshotOptions?: TerminalStateSnapshotOptions): TerminalStateSnapshot { - return { - state: getState(snapshotOptions), + retainedHistoryLines: terminal.buffer.normal.baseY, revision: stateRevision, + replayPreamble: getReplayPreamble(), }; + return { metadata, data: serialize(replayOptions) }; } function getSize(): { rows: number; cols: number } { @@ -1386,14 +1187,10 @@ export async function createTerminal( } } - function subscribe( - listener: (msg: ServerMessage) => void, - subscribeOptions?: TerminalSubscribeOptions, - ): () => void { + function subscribe(listener: (msg: ServerMessage) => void): () => void { let active = true; let snapshotDelivered = false; const queuedMessages: ServerMessage[] = []; - const initialSnapshot = subscribeOptions?.initialSnapshot ?? "state"; const subscriptionListener = (msg: ServerMessage): void => { if (!active) { return; @@ -1410,17 +1207,11 @@ export async function createTerminal( terminal.write("", () => { if (!disposed && active && listeners.has(subscriptionListener)) { snapshotDelivered = true; - if (initialSnapshot === "ready") { - // Carry the input-mode preamble so the snapshot-less "ready" path - // (live restore) can replay it without a separate state fetch. - listener({ - type: "snapshotReady", - revision: stateRevision, - replayPreamble: getReplayPreamble(), - }); - } else { - listener({ type: "snapshot", ...getStateSnapshot() }); - } + listener({ + type: "snapshotReady", + revision: stateRevision, + replayPreamble: getReplayPreamble(), + }); for (const message of queuedMessages.splice(0)) { listener(message); } @@ -1604,8 +1395,15 @@ export async function createTerminal( onTitleChange, onActivityChange, getSize, - getState, - getStateSnapshot, + serializeReplay, + captureLines: (captureOptions) => captureTerminalLines(terminal.buffer.active, captureOptions), + hasOutput: () => { + const buffer = terminal.buffer.active; + for (let row = 0; row < buffer.length; row++) { + if (buffer.getLine(row)?.translateToString(true).trim()) return true; + } + return false; + }, getReplayPreamble, getTitle, getActivity, diff --git a/packages/server/src/terminal/test-utils/terminal-state.ts b/packages/server/src/terminal/test-utils/terminal-state.ts new file mode 100644 index 0000000000..0fd4777b4c --- /dev/null +++ b/packages/server/src/terminal/test-utils/terminal-state.ts @@ -0,0 +1,51 @@ +import xterm from "@xterm/headless"; +import type { TerminalState } from "@getpaseo/protocol/messages"; +import type { LocalTerminalSession } from "../terminal.js"; + +/** Observe the public ANSI replay using a real receiver; no production cell extraction API. */ +export async function readTerminalState(session: LocalTerminalSession): Promise { + const { metadata, data } = session.serializeReplay(); + const terminal = new xterm.Terminal({ + rows: metadata.rows, + cols: metadata.cols, + scrollback: 10000, + allowProposedApi: true, + }); + try { + await new Promise((resolve) => terminal.write(data, resolve)); + const buffer = terminal.buffer.active; + const rows = Array.from({ length: buffer.length }, (_, row) => + Array.from({ length: terminal.cols }, (_cell, col) => { + const cell = buffer.getLine(row)!.getCell(col)!; + const fgMode = cell.getFgColorMode() >> 24; + const bgMode = cell.getBgColorMode() >> 24; + return { + char: cell.getWidth() === 0 ? "" : cell.getChars() || " ", + fg: fgMode ? cell.getFgColor() : undefined, + bg: bgMode ? cell.getBgColor() : undefined, + fgMode: fgMode || undefined, + bgMode: bgMode || undefined, + bold: !!cell.isBold(), + italic: !!cell.isItalic(), + underline: !!cell.isUnderline(), + dim: !!cell.isDim(), + inverse: !!cell.isInverse(), + strikethrough: !!cell.isStrikethrough(), + }; + }), + ); + const wrapped = rows.map((_, i) => buffer.getLine(i + 1)?.isWrapped === true); + return { + rows: terminal.rows, + cols: terminal.cols, + grid: rows.slice(buffer.baseY), + scrollback: rows.slice(0, buffer.baseY), + gridWrapped: wrapped.slice(buffer.baseY), + scrollbackWrapped: wrapped.slice(0, buffer.baseY), + cursor: { row: buffer.cursorY, col: buffer.cursorX }, + ...(session.getTitle() ? { title: session.getTitle() } : {}), + }; + } finally { + terminal.dispose(); + } +} diff --git a/packages/server/src/terminal/worker-terminal-manager.test.ts b/packages/server/src/terminal/worker-terminal-manager.test.ts index d953d6cb69..ad066327a2 100644 --- a/packages/server/src/terminal/worker-terminal-manager.test.ts +++ b/packages/server/src/terminal/worker-terminal-manager.test.ts @@ -1,3 +1,17 @@ +import { TerminalInputModeTracker } from "@getpaseo/protocol/terminal-input-mode"; +import { encodeTerminalKeyInput } from "@getpaseo/protocol/terminal-key-input"; +import type { SubscribeTerminalRequest } from "@getpaseo/protocol/messages"; +import { TerminalSessionController } from "./terminal-session-controller.js"; +import { SessionDelivery } from "../server/session/owned-subscriptions/index.js"; +import { + decodeTerminalStreamFrame, + TerminalStreamOpcode, + type TerminalStreamFrame, +} from "@getpaseo/protocol/binary-frames/index"; +import type { SessionOutboundMessage } from "../server/messages.js"; +import { createConnection } from "node:net"; +import { attachFramedSocket } from "./terminal-worker-frames.js"; +import xterm from "@xterm/headless"; import { afterEach, expect, it } from "vitest"; import { isPlatform } from "../test-utils/platform.js"; import { EventEmitter } from "node:events"; @@ -31,6 +45,7 @@ import type { TerminalState } from "@getpaseo/protocol/messages"; import type { TerminalActivity } from "@getpaseo/protocol/terminal-activity"; import type { TerminalWorkerRequest, + WorkerTerminalState, TerminalWorkerToParentMessage, } from "./terminal-worker-protocol.js"; import { createTerminalWorkerProcessInspector } from "./terminal-worker-processes.js"; @@ -77,8 +92,35 @@ async function waitForCondition( throw new Error(`Timed out after ${timeoutMs}ms waiting for condition`); } -function getVisibleText(session: TerminalSession): string { - return getVisibleTextFromState(session.getState()); +async function readReplay(manager: DaemonTerminalManager, id: string) { + const chunks: Uint8Array[] = []; + const metadata = await manager.replayTerminal(id, undefined, (event) => { + if (event.type === "data") chunks.push(event.data); + }); + if (!metadata) return null; + const terminal = new xterm.Terminal({ + rows: metadata.rows, + cols: metadata.cols, + scrollback: 1000, + allowProposedApi: true, + }); + await new Promise((resolve) => terminal.write(Buffer.concat(chunks), resolve)); + const buffer = terminal.buffer.active; + const rows = Array.from({ length: buffer.length }, (_, i) => { + const line = buffer.getLine(i)!; + return Array.from({ length: metadata.cols }, (_cell, col) => ({ + char: line.getCell(col)?.getChars() || " ", + })); + }); + const state: TerminalState = { + rows: metadata.rows, + cols: metadata.cols, + scrollback: rows.slice(0, buffer.baseY), + grid: rows.slice(buffer.baseY), + cursor: { row: buffer.cursorY, col: buffer.cursorX }, + }; + terminal.dispose(); + return { state, revision: metadata.revision }; } function rowToText(row: TerminalRow): string { @@ -107,15 +149,8 @@ function readRenderedTokenIndexesFromState(state: TerminalState): number[] { return indexes; } -function createTerminalState(): TerminalState { - const blankCell = { char: " " }; - return { - rows: 1, - cols: 1, - grid: [[blankCell]], - scrollback: [], - cursor: { row: 0, col: 0 }, - }; +function createTerminalState(): WorkerTerminalState { + return { rows: 1, cols: 1, hasOutput: false }; } class FakeTerminalWorker extends EventEmitter { @@ -144,7 +179,11 @@ const temporaryDirs: string[] = []; // A real detached worker in a throwaway home; afterEach closes its terminals and the worker. async function startRealWorkerManager( - options: { getTerminalActivityUrl?: () => string | null; paseoHome?: string } = {}, + options: { + getTerminalActivityUrl?: () => string | null; + requestTimeoutMs?: number; + paseoHome?: string; + } = {}, ): Promise { const { paseoHome = createTemporaryHome(), ...rest } = options; return startWorkerTerminalManager({ @@ -277,7 +316,7 @@ it("reconnects a live worker without replacing terminal sessions or processes", await waitForCondition(() => !competitor.connected, 10000); await waitForCondition(async () => { try { - return (await manager!.getTerminalState(terminal.id)) !== null; + return (await readReplay(manager!, terminal.id)) !== null; } catch { return false; } @@ -343,26 +382,36 @@ it.each(["current", "draining"] as const)( "keeps the peer usable when the %s worker dies", async (target) => { const paseoHome = createTemporaryHome(); - const old = await leaveWorkerWithTerminal(paseoHome, 0); + const seeds = [ + await launchDetachedWorkerWithTerminal(paseoHome), + await launchDetachedWorkerWithTerminal(paseoHome), + ]; + // Exercise an existing seed adopted as current; launch age does not imply draining ownership. + const [firstAdopted] = await workerRecords(paseoHome); + const seed = seeds.find((candidate) => candidate.workerPid === firstAdopted!.pid)!; manager = await startRealWorkerManager({ paseoHome }); const added = await manager.createTerminal({ workspaceId: "ws-peer", - cwd: old.cwd, + cwd: seed.cwd, ...nodeTerminalCommand("setInterval(() => {}, 1000)"), }); - const current = (await workerRecords(paseoHome)).find( - (record) => record.pid !== old.workerPid, + const records = await workerRecords(paseoHome); + const current = records.find((record) => + record.terminals.some((terminal) => terminal.id === added.id), )!; - const deadId = target === "current" ? added.id : old.terminalId; - const healthyId = target === "current" ? old.terminalId : added.id; + const draining = records.find((record) => record.pid !== current.pid)!; + const drainingId = draining.terminals[0]!.id; + const deadId = target === "current" ? added.id : drainingId; + const healthyId = target === "current" ? drainingId : added.id; const healthy = manager.getTerminal(healthyId); - process.kill(target === "current" ? current.pid : old.workerPid, "SIGKILL"); + expect(healthy).toBeDefined(); + process.kill(target === "current" ? current.pid : draining.pid, "SIGKILL"); await waitForCondition(() => !manager!.getTerminal(deadId), 10000); expect(manager.getTerminal(healthyId)).toBe(healthy); - expect(await manager.getTerminalState(healthyId)).not.toBeNull(); + expect(await readReplay(manager, healthyId)).not.toBeNull(); await manager.createTerminal({ workspaceId: "ws-peer", - cwd: old.cwd, + cwd: seed.cwd, ...nodeTerminalCommand("setInterval(() => {}, 1000)"), }); expect((await workerRecords(paseoHome)).length).toBeLessThanOrEqual(2); @@ -387,31 +436,26 @@ it("creates a terminal through the worker and streams output", async () => { }), ); const messages: string[] = []; - let snapshots = 0; + let readinessEvents = 0; const unsubscribe = session.subscribe((message) => { if (message.type === "output") { messages.push(message.data); } - if (message.type === "snapshot") { - snapshots += 1; + if (message.type === "snapshotReady") { + readinessEvents += 1; } }); await new Promise((resolve) => setTimeout(resolve, 100)); - const snapshotsBeforeOutput = snapshots; + expect(readinessEvents).toBe(1); session.send({ type: "input", data: "hello\r" }); - await waitForCondition( - () => - messages.join("").includes("worker-output:hello") || - getVisibleText(session).includes("worker-output:hello"), - 10000, - ); + await waitForCondition(() => messages.join("").includes("worker-output:hello"), 10000); await new Promise((resolve) => setTimeout(resolve, 100)); unsubscribe(); - expect(messages.join("") + getVisibleText(session)).toContain("worker-output:hello"); - expect(snapshots).toBe(snapshotsBeforeOutput); + expect(messages.join("")).toContain("worker-output:hello"); + expect(readinessEvents).toBe(1); }); it("delivers rapid small writes complete and in order through worker coalescing", async () => { @@ -447,19 +491,19 @@ it("delivers rapid small writes complete and in order through worker coalescing" session.subscribe((message) => { if (message.type === "output") { events.push({ type: "output", data: message.data }); - } else if (message.type === "snapshot" || message.type === "snapshotReady") { + } else if (message.type === "snapshotReady") { events.push({ type: message.type }); } }); - // Let the snapshot subscription settle, then trigger the burst. + // Let readiness settle, then trigger the burst. await new Promise((resolve) => setTimeout(resolve, 100)); writeFileSync(burstGatePath, "go"); const expected = Array.from({ length: 500 }, (_, index) => index); let received: number[] = []; await waitForCondition(async () => { - const snapshot = await manager!.getTerminalState(session.id); + const snapshot = await readReplay(manager!, session.id); received = snapshot ? readRenderedTokenIndexesFromState(snapshot.state) : []; return expected.every((value, index) => received[index] === value); }, 10000); @@ -468,14 +512,13 @@ it("delivers rapid small writes complete and in order through worker coalescing" await waitForCondition(() => events.some((event) => event.type === "output"), 10000); - // No snapshot may land after output it should have preceded: every snapshot - // event must come before the first output event. + // Readiness precedes the ordered live stream. const firstOutputIndex = events.findIndex((event) => event.type === "output"); expect(firstOutputIndex).toBeGreaterThanOrEqual(0); - const snapshotAfterOutput = events + const readinessAfterOutput = events .slice(firstOutputIndex + 1) - .find((event) => event.type === "snapshot" || event.type === "snapshotReady"); - expect(snapshotAfterOutput).toBeUndefined(); + .find((event) => event.type === "snapshotReady"); + expect(readinessAfterOutput).toBeUndefined(); }); it("pulls fresh terminal state from the worker authority", async () => { @@ -495,7 +538,7 @@ it("pulls fresh terminal state from the worker authority", async () => { let visibleText = ""; await waitForCondition(async () => { - const snapshot = await manager!.getTerminalState(session.id); + const snapshot = await readReplay(manager!, session.id); visibleText = snapshot ? getVisibleTextFromState(snapshot.state) : ""; return visibleText.includes("worker-state-ready"); }, 10000); @@ -508,7 +551,7 @@ it("pulls fresh terminal state from the worker authority", async () => { // preamble-caching contract is verified on Linux/macOS; the daemon's input-mode // handling runs identically on every platform once the escape is observed. it.skipIf(isPlatform("win32"))( - "caches the input-mode replay preamble from the worker after getTerminalState", + "caches input modes from worker output independently of replay capture", async () => { const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-preamble-")); temporaryDirs.push(cwd); @@ -526,11 +569,10 @@ it.skipIf(isPlatform("win32"))( }), ); - await waitForCondition(async () => { - const snapshot = await manager!.getTerminalState(session.id); - return snapshot !== null && session.getReplayPreamble() === "\x1b[=1;1u"; - }, 10000); - + await waitForCondition(() => session.getReplayPreamble() === "\x1b[=1;1u", 10000); + // Initial shared modes must be ready without a replay response repairing the cache. + expect(session.getReplayPreamble()).toBe("\x1b[=1;1u"); + expect(await readReplay(manager!, session.id)).not.toBeNull(); expect(session.getReplayPreamble()).toBe("\x1b[=1;1u"); }, ); @@ -552,7 +594,7 @@ it("refreshes cached terminal title after worker title changes", async () => { await waitForCondition(() => session.getTitle() === "Build Output", 10000); - expect(session.getState().title).toBe("Build Output"); + expect(session.getTitle()).toBe("Build Output"); }); it("refreshes cached terminal size after worker resize", async () => { @@ -562,12 +604,12 @@ it("refreshes cached terminal size after worker resize", async () => { const session = trackTerminal(await manager.createTerminal({ cwd, workspaceId: "ws-test" })); session.send({ type: "resize", rows: 10, cols: 40 }); - const snapshot = await manager.getTerminalState(session.id); + const snapshot = await readReplay(manager, session.id); expect(snapshot?.state.rows).toBe(10); expect(snapshot?.state.cols).toBe(40); - expect(session.getState().rows).toBe(10); - expect(session.getState().cols).toBe(40); + expect(session.getSize().rows).toBe(10); + expect(session.getSize().cols).toBe(40); }); it("captures terminal output from the worker authority", async () => { @@ -817,6 +859,7 @@ it("never adopts a live worker's terminals after a kill cleanup it could not fin // the shim; the PATH is restored as soon as it is up. async function startWorkerWithSlowProcessTable( delaySeconds: number, + options: { paseoHome?: string; requestTimeoutMs?: number } = {}, ): Promise { const realPs = (process.env.PATH ?? "") .split(delimiter) @@ -830,7 +873,7 @@ async function startWorkerWithSlowProcessTable( const originalPath = process.env.PATH; process.env.PATH = `${shimDir}${delimiter}${originalPath ?? ""}`; try { - return await startRealWorkerManager(); + return await startRealWorkerManager(options); } finally { process.env.PATH = originalPath; } @@ -854,7 +897,7 @@ async function expectCompletedShortCommand( expect(session.getExitInfo()?.exitCode).toBe(0); expect(terminalManager.getTerminal(session.id)).toBeUndefined(); expect(await terminalManager.getTerminals(cwd)).toEqual([]); - expect(await terminalManager.getTerminalState(session.id)).toBeNull(); + expect(await readReplay(terminalManager, session.id)).toBeNull(); } it.skipIf(isPlatform("win32"))( @@ -1531,63 +1574,34 @@ async function leaveWorkerWithTerminal( }; } -it("drains a worker one protocol older: it keeps its terminal, new ones open in a second worker, and it exits after its last", async () => { - const paseoHome = createTemporaryHome(); - const old = await leaveWorkerWithTerminal(paseoHome, 0); +it.each([1, 4])( + "hard cuts unreleased worker protocol %s, closing its terminals", + async (version) => { + const paseoHome = createTemporaryHome(); + const old = await leaveWorkerWithTerminal(paseoHome, version); - manager = await startRealWorkerManager({ paseoHome }); + manager = await startRealWorkerManager({ paseoHome }); - expect(manager.getTerminal(old.terminalId)).toBeDefined(); - const workers = await workerRecords(paseoHome); - expect(workers).toHaveLength(2); - const current = workers.find((record) => record.pid !== old.workerPid)!; - expect(current.protocolVersion).toBe(1); - const added = await manager.createTerminal({ - workspaceId: "ws-protocol", - cwd: old.cwd, - ...nodeTerminalCommand("setInterval(() => {}, 1000);"), - }); - trackTerminal(added); - const currentTerminals = ( - await readTerminalWorkerRecord(join(terminalWorkerDirectory(paseoHome), `${current.pid}.json`)) - ).terminals.map((entry) => entry.id); - expect(currentTerminals).toEqual([added.id]); - expect((await manager.getTerminals(old.cwd)).map((session) => session.id).sort()).toEqual( - [old.terminalId, added.id].sort(), - ); - - await manager.killTerminalAndWait(old.terminalId); - - await waitForCondition(() => !isProcessAlive(old.workerPid), 10000); - expect((await workerRecords(paseoHome)).map((record) => record.pid)).toEqual([current.pid]); - expect(manager.getTerminal(added.id)).toBeDefined(); -}); - -it("shuts down a worker two protocol versions old, closing its terminals", async () => { - const paseoHome = createTemporaryHome(); - const old = await leaveWorkerWithTerminal(paseoHome, -1); - - manager = await startRealWorkerManager({ paseoHome }); - - await waitForCondition( - () => !isProcessAlive(old.workerPid) && !isProcessAlive(old.programPid), - 10000, - ); - expect(manager.getTerminal(old.terminalId)).toBeUndefined(); - const workers = await workerRecords(paseoHome); - expect(workers).toHaveLength(1); - expect(workers[0]!.protocolVersion).toBe(1); -}); + await waitForCondition( + () => !isProcessAlive(old.workerPid) && !isProcessAlive(old.programPid), + 10000, + ); + expect(manager.getTerminal(old.terminalId)).toBeUndefined(); + const workers = await workerRecords(paseoHome); + expect(workers).toHaveLength(1); + expect(workers[0]!.protocolVersion).toBe(5); + }, +); it("leaves a worker from a newer Paseo running, reports it incompatible, and closes it on a kill stop", async () => { const paseoHome = createTemporaryHome(); - const newer = await leaveWorkerWithTerminal(paseoHome, 2); + const newer = await leaveWorkerWithTerminal(paseoHome, 6); manager = await startRealWorkerManager({ paseoHome }); const unavailable = manager.getUnavailableError?.(); expect(unavailable).toBeInstanceOf(TerminalWorkerIncompatibleError); - expect(unavailable?.message).toContain("worker protocol 2"); + expect(unavailable?.message).toContain("worker protocol 6"); await expect(manager.getTerminals(newer.cwd)).rejects.toBeInstanceOf( TerminalWorkerIncompatibleError, ); @@ -1694,45 +1708,892 @@ it.skipIf(isPlatform("win32"))( }, ); -it("opens new terminals in a new worker once one of two draining workers exits", async () => { - const paseoHome = createTemporaryHome(); - const first = await launchDetachedWorkerWithTerminal(paseoHome, 0); - const second = await launchDetachedWorkerWithTerminal(paseoHome, 0); - - manager = await startRealWorkerManager({ paseoHome }); - - expect(await liveWorkerPids(paseoHome)).toEqual([first.workerPid, second.workerPid].sort()); - await expect( - manager.createTerminal({ workspaceId: "ws-detached", cwd: first.cwd }), - ).rejects.toBeInstanceOf(NoTerminalWorkerAvailableError); - - await manager.killTerminalAndWait(first.terminalId); - await waitForCondition(() => !isProcessAlive(first.workerPid), 10000); - - // Concurrent creates start one worker between them. - const created = await Promise.all( - [0, 1].map(() => - manager!.createTerminal({ - workspaceId: "ws-detached", - cwd: first.cwd, - ...nodeTerminalCommand("setInterval(() => {}, 1000);"), - }), - ), +it("replays bounded ANSI chunks independently of live output and reconstructs the revision cut", async () => { + const cwd = createTemporaryHome(); + manager = await startRealWorkerManager(); + const session = trackTerminal( + await manager.createTerminal({ + cwd, + workspaceId: "ws-replay", + rows: 8, + cols: 120, + ...nodeTerminalCommand(` + for (let i = 0; i < 800; i++) process.stdout.write("\\x1b[31m" + String(i).padStart(4, "0") + ":" + "x".repeat(100) + "\\x1b[0m\\r\\n"); + require("node:readline").createInterface({ input: process.stdin }).on("line", line => process.stdout.write(line === "before" ? "PRE-CUT\\r\\n" : "LIVE-AFTER-REPLAY\\r\\n")); + setInterval(() => {}, 1000); + `), + }), ); - created.forEach(trackTerminal); - const workers = await workerRecords(paseoHome); - expect(workers.map((record) => record.pid).sort()).toEqual(await liveWorkerPids(paseoHome)); - expect(workers).toHaveLength(2); - const started = workers.find((record) => record.pid !== second.workerPid)!; - expect(started.protocolVersion).toBe(1); - expect( - ( - await readTerminalWorkerRecord( - join(terminalWorkerDirectory(paseoHome), `${started.pid}.json`), - ) - ).terminals - .map((entry) => entry.id) - .sort(), - ).toEqual(created.map((session) => session.id).sort()); - expect(manager.getTerminal(second.terminalId)).toBeDefined(); + await waitForCondition( + async () => + (await manager!.captureTerminal(session.id)).lines.some((line) => line.startsWith("0799:")), + 10000, + ); + const events: string[] = []; + const replayEvents: string[] = []; + const liveOutputs: Array<{ data: string; revision?: number }> = []; + const chunks: Uint8Array[] = []; + let live = ""; + const unsubscribe = session.subscribe((event) => { + if (event.type === "output") { + events.push("live"); + liveOutputs.push(event); + live += event.data; + } + }); + session.send({ type: "input", data: "before\r" }); + await waitForCondition(() => live.includes("PRE-CUT"), 10000); + const expected = await manager.captureTerminal(session.id); + const metadata = await manager.replayTerminal(session.id, undefined, (event) => { + events.push(event.type); + replayEvents.push(event.type); + if (event.type === "begin") session.send({ type: "input", data: "go\r" }); + if (event.type === "data") chunks.push(event.data); + }); + await waitForCondition(() => live.includes("LIVE-AFTER-REPLAY"), 10000); + unsubscribe(); + // Existing live observers are independent of replay. Pre-cut output may also be + // flushed by capture before begin; only the replay events have begin/data/end order. + expect(events[0]).toBe("live"); + expect(replayEvents[0]).toBe("begin"); + expect(replayEvents.at(-1)).toBe("end"); + expect(replayEvents.slice(1, -1)).toEqual(chunks.map(() => "data")); + const beforeCut = liveOutputs.filter((output) => output.data.includes("PRE-CUT")); + const afterCut = liveOutputs.filter((output) => output.data.includes("LIVE-AFTER-REPLAY")); + expect(beforeCut).toHaveLength(1); + expect(afterCut).toHaveLength(1); + expect(beforeCut[0]!.revision).toBeDefined(); + expect(beforeCut[0]!.revision).toBeLessThanOrEqual(metadata!.revision); + expect(afterCut[0]!.revision).toBeGreaterThan(metadata!.revision); + expect(live.match(/LIVE-AFTER-REPLAY/g)).toHaveLength(1); + expect(chunks.length).toBeGreaterThan(1); + expect(chunks.every((chunk) => chunk.byteLength <= 64 * 1024)).toBe(true); + expect(metadata?.rows).toBe(8); + expect(metadata?.cols).toBe(120); + const terminal = new xterm.Terminal({ + rows: 8, + cols: 120, + scrollback: 1000, + allowProposedApi: true, + }); + try { + await new Promise((resolve) => terminal.write(Buffer.concat(chunks), resolve)); + const buffer = terminal.buffer.active; + expect( + Array.from({ length: buffer.length }, (_, i) => buffer.getLine(i)!.translateToString(true)), + ).toEqual(expected.lines); + expect(expected.lines.filter((line) => line.includes("PRE-CUT"))).toHaveLength(1); + expect(expected.lines.some((line) => line.includes("LIVE-AFTER-REPLAY"))).toBe(false); + expect(buffer.getLine(0)!.getCell(0)!.getFgColor()).toBe(1); + } finally { + terminal.dispose(); + } }); + +it("completes a replay larger than the socket budget while a sibling stays usable", async () => { + const paseoHome = createTemporaryHome(); + const overflowProgress = join(paseoHome, "overflow-progress"); + manager = await startRealWorkerManager({ paseoHome }); + const terminal = trackTerminal( + await manager.createTerminal({ + cwd: paseoHome, + workspaceId: "ws-wide", + rows: 4, + cols: 1024, + ...nodeTerminalCommand(` + const row = Array.from({length: 1000}, (_, i) => "\\x1b[" + (31 + i % 2) + "mX").join(""); + for (let i = 0; i < 900; i++) process.stdout.write(row + "\\r\\n"); + process.stdout.write("READY-WIDE\\r\\n"); + process.stdin.on("data", data => { if (data.toString().includes("small")) { process.stdout.write("SAME-TERMINAL-LIVE\\r\\n"); return; } process.stdout.write("q".repeat(8 * 1024 * 1024) + "\\r\\nRECOVERED-LIVE\\r\\n", () => require("node:fs").writeFileSync(${JSON.stringify(overflowProgress)}, "done")); }); + setInterval(() => {}, 1000); + `), + }), + ); + const siblingProgress = join(paseoHome, "sibling-progress"); + const sibling = trackTerminal( + await manager.createTerminal({ + cwd: paseoHome, + workspaceId: "ws-wide", + ...nodeTerminalCommand(` + let count = 0; + process.stdin.on("data", () => { + count++; + process.stdout.write((count > 1 ? "z".repeat(1024 * 1024) : "") + "SIBLING-ALIVE\\r\\n", () => require("node:fs").writeFileSync(${JSON.stringify(siblingProgress)}, String(count))); + }); + setInterval(() => {}, 1000); + `), + }), + ); + await waitForCondition( + async () => + (await manager!.captureTerminal(terminal.id)).lines.some((line) => + line.includes("READY-WIDE"), + ), + 20000, + ); + const seen: string[] = []; + const unsubscribe = sibling.subscribe((event) => { + if (event.type === "output") seen.push(event.data); + }); + let bytes = 0; + const metadata = await manager.replayTerminal(terminal.id, undefined, (event) => { + if (event.type === "data") bytes += event.data.byteLength; + if (event.type === "begin") { + sibling.send({ type: "input", data: "go\r" }); + } + }); + expect(bytes).toBeGreaterThan(4 * 1024 * 1024); + expect(metadata?.cols).toBe(1024); + await waitForCondition(() => seen.join("").includes("SIBLING-ALIVE"), 10000); + unsubscribe(); + expect(manager.getTerminal(sibling.id)).toBe(sibling); + const truncated = await manager.replayTerminal(terminal.id, { scrollbackLines: 200 }, () => {}); + expect(metadata!.retainedHistoryLines).toBeGreaterThan(200); + expect(truncated!.retainedHistoryLines).toBe(metadata!.retainedHistoryLines); + const concurrent = await Promise.all( + [0, 1].map(() => manager!.replayTerminal(terminal.id, { scrollbackLines: 200 }, () => {})), + ); + expect(concurrent.map((replay) => replay!.retainedHistoryLines)).toEqual([ + metadata!.retainedHistoryLines, + metadata!.retainedHistoryLines, + ]); + await manager.detach(); + const [record] = await workerRecords(paseoHome); + const socket = createConnection(record!.socketPath); + let began = false; + let ended = false; + let completed = false; + let resumedBytes = 0; + let cancelledReplayBegan = false; + let existingLiveOutput = ""; + const replayOrder: string[] = []; + const framed = attachFramedSocket(socket, (value) => { + const message = value as TerminalWorkerToParentMessage | { type: "helloAck" }; + if ( + message.type === "terminalMessage" && + message.terminalId === terminal.id && + message.message.type === "output" + ) { + existingLiveOutput += message.message.data; + replayOrder.push("live"); + } + if (message.type === "helloAck") { + framed.send({ type: "replayTerminal", terminalId: terminal.id, requestId: "stalled-replay" }); + } else if (message.type === "terminalReplay") { + if (message.requestId === "cancelled-replay") { + if (message.event.type === "begin") { + cancelledReplayBegan = true; + socket.pause(); + } + return; + } + if (message.event.type === "begin") { + began = true; + socket.pause(); + } + if (message.event.type === "data") resumedBytes += message.event.data.byteLength; + if (message.event.type === "end") { + ended = true; + replayOrder.push("end"); + } + } else if (message.type === "response" && message.requestId === "stalled-replay") + completed = message.ok; + }); + try { + framed.send({ type: "hello", secret: record!.secret, protocolVersion: 5 }); + await waitForCondition(() => began, 10000); + framed.send({ + type: "send", + terminalId: terminal.id, + requestId: "same-terminal-input", + message: { type: "input", data: "small\r" }, + }); + framed.send({ + type: "send", + terminalId: sibling.id, + requestId: "sibling-input", + message: { type: "input", data: "again\r" }, + }); + await waitForCondition( + () => existsSync(siblingProgress) && readFileSync(siblingProgress, "utf8") === "2", + 10000, + ); + await new Promise((resolve) => setTimeout(resolve, 150)); + expect(completed).toBe(false); + expect(socket.destroyed).toBe(false); + socket.resume(); + await waitForCondition(() => completed, 10000); + expect(ended).toBe(true); + expect(resumedBytes).toBe(bytes); + await waitForCondition(() => existingLiveOutput.includes("SAME-TERMINAL-LIVE"), 10000); + expect(existingLiveOutput.match(/SAME-TERMINAL-LIVE/g)).toHaveLength(1); + expect(replayOrder.indexOf("live")).toBeLessThan(replayOrder.indexOf("end")); + framed.send({ type: "replayTerminal", terminalId: terminal.id, requestId: "cancelled-replay" }); + await waitForCondition(() => cancelledReplayBegan, 10000); + // Replace a controller while its large replay is socket-paced. The original + // request must never leak frames or completion onto the replacement connection. + manager = await startRealWorkerManager({ paseoHome }); + socket.resume(); + await waitForCondition(() => socket.destroyed, 10000); + expect((await readReplay(manager, terminal.id))?.state.cols).toBe(1024); + } finally { + socket.destroy(); + } + expect( + (await manager!.captureTerminal(terminal.id)).lines.some((line) => line.includes("READY-WIDE")), + ).toBe(true); + const exitingReplay = await manager.replayTerminal( + terminal.id, + { scrollbackLines: 200 }, + (event) => { + if (event.type === "begin") manager!.killTerminal(terminal.id); + }, + ); + expect(exitingReplay!.cols).toBe(1024); + await waitForCondition(() => manager!.getTerminal(terminal.id) === undefined, 10000); + expect(manager.getTerminal(sibling.id)?.id).toBe(sibling.id); +}, 60000); + +function terminalViewers( + terminalManager: DaemonTerminalManager, + terminalId: string, + chunked = true, + getClientBufferedAmount?: (source: object) => number | null, +) { + const frames: Array<{ source: object; frame: TerminalStreamFrame }> = []; + const messages: Array<{ source: object; message: SessionOutboundMessage }> = []; + let blockedSource: object | null = null; + let started = false; + let finish!: (error?: Error) => void; + const block = new Promise((resolve, reject) => { + finish = (error) => (error ? reject(error) : resolve()); + }); + const delivery = new SessionDelivery( + (source, message) => { + messages.push({ source, message }); + }, + async (source, bytes) => { + const frame = decodeTerminalStreamFrame(bytes)!; + frames.push({ source, frame }); + if ( + source === blockedSource && + frame.opcode === (chunked ? TerminalStreamOpcode.ReplayBegin : TerminalStreamOpcode.Restore) + ) { + started = true; + await block; + } + }, + ); + const controller = new TerminalSessionController({ + terminalManager, + emit: (message) => { + delivery.reply(message); + }, + hasBinaryChannel: () => true, + supportsChunkedReplay: () => chunked, + getClientBufferedAmount, + isPathWithinRoot: () => true, + sessionLogger: pino({ level: "silent" }), + }); + return { + frames, + messages, + delivery, + controller, + block(source: object) { + blockedSource = source; + }, + started: () => started, + finish, + async attach( + source: object, + requestId: string, + restore: NonNullable = { + mode: "visible-snapshot", + scrollbackLines: 1000, + }, + ) { + delivery.attach(source, true); + const request = { + type: "subscribe_terminal_request" as const, + terminalId, + requestId, + restore, + }; + await delivery.request(source, request, () => controller.dispatch(request, delivery)); + }, + text(source: object) { + return frames + .filter((row) => row.source === source && row.frame.opcode === TerminalStreamOpcode.Output) + .map((row) => Buffer.from(row.frame.payload).toString("utf8")) + .join(""); + }, + ended(source: object) { + return messages.filter( + (row) => row.source === source && row.message.type === "terminal_stream_exit", + ); + }, + replayed(source: object) { + return frames.some( + (row) => row.source === source && row.frame.opcode === TerminalStreamOpcode.ReplayEnd, + ); + }, + }; +} + +it("isolates a failed app transport while another viewer of the same terminal stays live", async () => { + manager = await startRealWorkerManager(); + const session = trackTerminal( + await manager.createTerminal({ + cwd: createTemporaryHome(), + workspaceId: "two-viewers", + ...nodeTerminalCommand( + 'process.stdout.write("READY\\r\\n"); process.stdin.on("data", data => process.stdout.write("ECHO:" + data)); setInterval(() => {}, 1000);', + ), + }), + ); + await waitForCondition( + async () => + (await manager!.captureTerminal(session.id)).lines.some((line) => line.includes("READY")), + 10000, + ); + const viewers = terminalViewers(manager, session.id); + const desktop = {}, + phone = {}, + fresh = {}; + try { + await viewers.attach(desktop, "desktop"); + await waitForCondition(() => viewers.replayed(desktop), 10000); + await expect( + manager.replayTerminal(session.id, undefined, () => { + throw new Error("Consumer cancelled replay"); + }), + ).rejects.toThrow("Consumer cancelled replay"); + viewers.block(phone); + await viewers.attach(phone, "phone"); + await waitForCondition(viewers.started, 10000); + session.send({ type: "input", data: "BEFORE-FAILURE\r" }); + await waitForCondition(() => viewers.text(desktop).includes("ECHO:BEFORE-FAILURE"), 1500); + expect(viewers.ended(desktop)).toHaveLength(0); + expect(viewers.ended(phone)).toHaveLength(0); + viewers.finish(new Error("Phone socket closed")); + await viewers.delivery.detach(phone); + expect(viewers.ended(desktop)).toHaveLength(0); + session.send({ type: "input", data: "AFTER-FAILURE\r" }); + await waitForCondition(() => viewers.text(desktop).includes("ECHO:AFTER-FAILURE"), 10000); + expect(viewers.ended(desktop)).toHaveLength(0); + await viewers.attach(fresh, "fresh"); + await waitForCondition(() => viewers.replayed(fresh), 10000); + expect(manager.getTerminal(session.id)).toBe(session); + } finally { + viewers.finish(); + await viewers.delivery.close(); + } +}, 20000); + +it("keeps concurrent viewer replays and live output ordered behind slow app delivery", async () => { + manager = await startRealWorkerManager(); + const session = trackTerminal( + await manager.createTerminal({ + cwd: createTemporaryHome(), + workspaceId: "concurrent-delivery", + ...nodeTerminalCommand( + 'process.stdout.write("READY\\r\\n"); process.stdin.on("data", data => process.stdout.write("ECHO:" + data)); setInterval(() => {}, 1000);', + ), + }), + ); + await waitForCondition( + async () => (await manager!.captureTerminal(session.id)).lines.join("").includes("READY"), + 10000, + ); + const viewers = terminalViewers(manager, session.id); + const desktop = {}, + phone = {}, + concurrent = {}; + try { + await viewers.attach(desktop, "desktop"); + await waitForCondition(() => viewers.replayed(desktop), 10000); + viewers.block(phone); + await viewers.attach(phone, "phone"); + await waitForCondition(viewers.started, 10000); + await viewers.attach(concurrent, "concurrent"); + await waitForCondition(() => viewers.replayed(concurrent) && viewers.replayed(phone), 10000); + session.send({ type: "input", data: "DURING-DELIVERY\r" }); + await waitForCondition( + () => + viewers.text(phone).includes("ECHO:DURING-DELIVERY") && + viewers.text(desktop).includes("ECHO:DURING-DELIVERY"), + 3000, + ); + expect(viewers.text(phone).match(/ECHO:DURING-DELIVERY/g)).toHaveLength(1); + const order = viewers.frames + .filter((row) => row.source === phone) + .map((row) => row.frame.opcode); + expect(order.indexOf(TerminalStreamOpcode.Output)).toBeGreaterThan( + order.indexOf(TerminalStreamOpcode.ReplayEnd), + ); + expect(viewers.ended(phone)).toHaveLength(0); + expect(viewers.ended(desktop)).toHaveLength(0); + } finally { + viewers.finish(); + await viewers.delivery.close(); + } +}, 20000); + +it.each([true, false])( + "queues replay independently of app delivery past the worker deadline (chunked=%s)", + async (chunked) => { + const paseoHome = createTemporaryHome(); + // Slow program identification belongs to setup, not the replay request deadline. + // The POSIX shim deterministically exceeds 800 ms; Windows keeps its real OS path. + manager = isPlatform("win32") + ? await startRealWorkerManager({ paseoHome }) + : await startWorkerWithSlowProcessTable(1, { paseoHome }); + const created = await manager.createTerminal({ + cwd: paseoHome, + workspaceId: "slow-delivery", + ...nodeTerminalCommand( + 'process.stdout.write("READY\\r\\n"); process.stdin.on("data", data => process.stdout.write("ECHO:" + data)); setInterval(() => {}, 1000);', + ), + }); + await waitForCondition( + async () => (await manager!.captureTerminal(created.id)).lines.join("").includes("READY"), + 10000, + ); + await manager.detach(); + manager = await startRealWorkerManager({ paseoHome, requestTimeoutMs: 800 }); + const session = manager.getTerminal(created.id); + if (!session) throw new Error("Replay fixture did not adopt its prepared terminal"); + trackTerminal(session); + const viewers = terminalViewers(manager, session.id, chunked); + const phone = {}; + viewers.block(phone); + try { + await viewers.attach(phone, "slow-phone"); + await waitForCondition(viewers.started, 10000); + await new Promise((resolve) => setTimeout(resolve, 1100)); + expect(viewers.ended(phone)).toHaveLength(0); + expect((await manager.captureTerminal(session.id)).lines.join("")).toContain("READY"); + session.send({ type: "input", data: "AFTER-DEADLINE\r" }); + await waitForCondition(() => viewers.text(phone).includes("ECHO:AFTER-DEADLINE"), 3000); + } finally { + viewers.finish(); + await viewers.delivery.close(); + } + }, + 20000, +); + +it.each(["replacement", "socket-overflow"] as const)( + "recovers an attached restore viewer after worker %s", + async (loss) => { + const paseoHome = createTemporaryHome(); + const drained = join(paseoHome, "burst-drained"); + manager = await startRealWorkerManager({ paseoHome }); + const session = trackTerminal( + await manager.createTerminal({ + cwd: paseoHome, + workspaceId: "attached-reconnect", + ...nodeTerminalCommand( + `process.stdout.write("RETAINED\\r\\n"); process.stdin.on("data", data => { + if (data.toString().includes("BURST")) process.stdout.write("x".repeat(12 * 1024 * 1024) + "\\r\\nRETAINED-AFTER-LOSS\\r\\n", () => require("node:fs").writeFileSync(${JSON.stringify(drained)}, "done")); + else process.stdout.write("ECHO:" + data); + }); setInterval(() => {}, 1000);`, + ), + }), + ); + await waitForCondition( + async () => (await manager!.captureTerminal(session.id)).lines.join("").includes("RETAINED"), + 10000, + ); + const viewers = terminalViewers(manager, session.id); + const desktop = {}; + try { + await viewers.attach(desktop, "desktop"); + await waitForCondition(() => viewers.replayed(desktop), 10000); + viewers.frames.length = 0; + const [record] = await workerRecords(paseoHome); + if (loss === "replacement") { + const competitor = await connectTerminalWorker({ + socketPath: record!.socketPath, + secret: record!.secret, + }); + await waitForCondition(() => !competitor.connected, 10000); + } else { + session.send({ type: "input", data: "BURST\r" }); + // Stall only the daemon event loop. The detached worker and PTY keep running, + // filling the bounded worker socket and forcing its disconnect/re-adoption path. + const stall = new Int32Array(new SharedArrayBuffer(4)); + const deadline = Date.now() + 10000; + while (!existsSync(drained) && Date.now() < deadline) Atomics.wait(stall, 0, 0, 25); + expect(existsSync(drained)).toBe(true); + } + await waitForCondition(() => viewers.replayed(desktop), 10000); + const replay = viewers.frames + .filter((row) => row.frame.opcode === TerminalStreamOpcode.ReplayData) + .map((row) => Buffer.from(row.frame.payload).toString("utf8")) + .join(""); + expect(replay).toContain("RETAINED"); + if (loss === "socket-overflow") expect(replay).toContain("RETAINED-AFTER-LOSS"); + expect((await workerRecords(paseoHome)).map((worker) => worker.pid)).toEqual([record!.pid]); + session.send({ type: "input", data: "RECOVERED\r" }); + await waitForCondition(() => viewers.text(desktop).includes("ECHO:RECOVERED"), 3000); + expect(viewers.ended(desktop)).toHaveLength(0); + expect(manager.getTerminal(session.id)).toBe(session); + } finally { + await viewers.delivery.close(); + } + }, + 30000, +); + +it.each([true, false])( + "keeps live modes after a replay captured enabled=%s while restoring its own modes first", + async (enabled) => { + const on = "\x1b[?1h\x1b[?2004h"; + const off = "\x1b[?1l\x1b[?2004l"; + const captured = enabled ? on : ""; + const latest = enabled ? "" : on; + const live = (enabled ? off : on) + "MODE-LIVE"; + const worker = new FakeTerminalWorker(); + manager = createWorkerTerminalManager({ worker, requestTimeoutMs: 1000 }); + worker.emitWorkerMessage({ + type: "terminalCreated", + terminal: { + id: "mode-terminal", + name: "Terminal", + cwd: "/tmp", + workspaceId: "modes", + activity: null, + }, + state: createTerminalState(), + }); + worker.emitWorkerMessage({ + type: "terminalMessage", + terminalId: "mode-terminal", + replayPreamble: captured, + message: { type: "snapshotReady", revision: 1 }, + }); + const session = manager.getTerminal("mode-terminal")!; + const viewers = terminalViewers(manager, session.id); + const restoring = {}, + following = {}; + try { + await viewers.attach(restoring, "restoring"); + await waitForCondition( + () => worker.sentMessages.some((message) => message.type === "replayTerminal"), + 1000, + ); + const request = worker.sentMessages.find((message) => message.type === "replayTerminal")!; + const metadata = { + rows: 30, + cols: 120, + retainedHistoryLines: 10, + revision: 1, + replayPreamble: captured, + }; + worker.emitWorkerMessage({ + type: "terminalReplay", + requestId: request.requestId, + event: { type: "begin", metadata }, + }); + worker.emitWorkerMessage({ + type: "terminalReplay", + requestId: request.requestId, + event: { type: "data", data: Buffer.from("CAPTURE-A") }, + }); + worker.emitWorkerMessage({ + type: "terminalMessage", + terminalId: session.id, + replayPreamble: latest, + message: { type: "output", data: live, revision: 2 }, + }); + expect(session.getReplayPreamble()).toBe(latest); + worker.emitWorkerMessage({ + type: "terminalReplay", + requestId: request.requestId, + event: { type: "data", data: Buffer.from("CAPTURE-B") }, + }); + worker.emitWorkerMessage({ + type: "terminalReplay", + requestId: request.requestId, + event: { type: "end" }, + }); + worker.emitWorkerMessage({ + type: "response", + requestId: request.requestId, + ok: true, + result: metadata, + }); + await waitForCondition(() => viewers.text(restoring).includes("MODE-LIVE"), 1000); + expect(session.getReplayPreamble()).toBe(latest); + expect(viewers.text(restoring)).toBe(captured + live); + const sequence = viewers.frames + .filter((row) => row.source === restoring) + .map((row) => row.frame.opcode); + expect(sequence.indexOf(TerminalStreamOpcode.Output)).toBeGreaterThan( + sequence.indexOf(TerminalStreamOpcode.ReplayEnd), + ); + const modes = new TerminalInputModeTracker(); + modes.feed(session.getReplayPreamble()); + expect(encodeTerminalKeyInput({ key: "ArrowUp" }, { inputMode: modes.getState() })).toBe( + enabled ? "\x1b[A" : "\x1bOA", + ); + expect(modes.getState().bracketedPaste).toBe(!enabled); + await viewers.attach(following, "live-following", { mode: "live" }); + await waitForCondition(() => latest === "" || viewers.text(following).length > 0, 1000); + expect(viewers.text(following)).toBe(latest); + expect( + worker.sentMessages.filter((message) => message.type === "replayTerminal"), + ).toHaveLength(1); + } finally { + await viewers.delivery.close(); + } + }, +); + +it.each([3000, 12050])( + "retains ten thousand history rows and restores exact demands after %s printed rows", + async (count) => { + manager = await startRealWorkerManager(); + const gate = createTemporaryHome(); + const releaseNewline = join(gate, "newline"); + const session = trackTerminal( + await manager.createTerminal({ + cwd: createTemporaryHome(), + workspaceId: "ten-thousand", + rows: 4, + cols: 80, + ...nodeTerminalCommand( + `const fs=require("node:fs"); + const watcher=fs.watch(${JSON.stringify(gate)},()=>{ + if(fs.existsSync(${JSON.stringify(releaseNewline)})){ + watcher.close();process.stdout.write("\\r\\nROWS-COMPLETE"); + } + }); + for(let i=0;i<${count};i++) process.stdout.write("\\x1b[31mrow-"+String(i).padStart(5,"0")+" 界é🙂\\x1b[0m"+(i===${count}-1?"":"\\r\\n")); + setInterval(()=>{},1000)`, + ), + }), + ); + await waitForCondition( + async () => + (await manager!.captureTerminal(session.id, { start: -5 })).lines + .join("") + .includes("row-" + String(count - 1).padStart(5, "0")), + 15000, + ); + // A visible final label can precede its trailing CRLF. Hold that transition + // deliberately, then observe content on the following row before capture. + writeFileSync(releaseNewline, "release"); + await waitForCondition( + async () => + (await manager!.captureTerminal(session.id, { start: -1 })).lines[0] === "ROWS-COMPLETE", + 15000, + ); + for (const history of [0, 200, 1000, 10000]) { + const chunks: Uint8Array[] = []; + const metadata = await manager.replayTerminal( + session.id, + { scrollbackLines: history }, + (event) => { + if (event.type === "data") chunks.push(event.data); + }, + ); + expect(metadata).toMatchObject({ + rows: 4, + cols: 80, + retainedHistoryLines: Math.min(10000, count - 3), + }); + expect(chunks.every((chunk) => chunk.byteLength <= 64 * 1024)).toBe(true); + const restored = new xterm.Terminal({ + rows: 4, + cols: 80, + scrollback: 10000, + allowProposedApi: true, + }); + try { + await new Promise((resolve) => restored.write(Buffer.concat(chunks), resolve)); + const buffer = restored.buffer.active; + const labels = Array.from({ length: buffer.length }, (_, i) => + buffer.getLine(i)!.translateToString(true), + ).filter((line) => line.includes("row-")); + expect({ row: buffer.cursorY, col: buffer.cursorX }).toEqual({ row: 3, col: 13 }); + expect(buffer.getLine(buffer.length - 1)!.translateToString(true)).toBe("ROWS-COMPLETE"); + expect(labels).toHaveLength(Math.min(count, history + 3)); + expect(labels[0]).toContain("row-" + String(count - labels.length).padStart(5, "0")); + expect(labels.at(-1)).toContain("row-" + String(count - 1).padStart(5, "0") + " 界é🙂"); + } finally { + restored.dispose(); + } + } + }, + 30000, +); + +it.each([false, true])( + "shrinks real ten-thousand-row pressure recovery and preserves reattach (chunked=%s)", + async (chunked) => { + manager = await startRealWorkerManager(); + const session = trackTerminal( + await manager.createTerminal({ + cwd: createTemporaryHome(), + workspaceId: "pressure-history", + rows: 4, + cols: 120, + ...nodeTerminalCommand(` + process.stdin.setRawMode(true); + let row = 0; + function print(count) { + for(let i=0;i { + if(data.toString().includes("BURST")) { print(4000); process.stdout.write("BURST-DONE\\r\\n"); } + else process.stdout.write("ECHO:" + data.toString() + "\\r\\n"); + }); + setInterval(()=>{},1000); + `), + }), + ); + await waitForCondition( + async () => + (await manager!.captureTerminal(session.id, { start: -5 })).lines + .join("") + .includes("READY"), + 15000, + ); + const desktop = {}, + phone = {}, + fresh = {}; + let pressure = false; + const viewers = terminalViewers(manager, session.id, chunked, (source) => + source === phone && pressure ? 8 * 1024 * 1024 : 0, + ); + const restore = { mode: "full-snapshot" as const, scrollbackLines: 10000 }; + function payloads(source: object): Buffer[] { + const result: Buffer[] = []; + let chunks: Uint8Array[] = []; + for (const { source: owner, frame } of viewers.frames) { + if (owner !== source) continue; + if (frame.opcode === TerminalStreamOpcode.Restore) result.push(Buffer.from(frame.payload)); + if (frame.opcode === TerminalStreamOpcode.ReplayBegin) chunks = []; + if (frame.opcode === TerminalStreamOpcode.ReplayData) chunks.push(frame.payload); + if (frame.opcode === TerminalStreamOpcode.ReplayEnd) result.push(Buffer.concat(chunks)); + } + return result; + } + async function parse(payload: Uint8Array) { + const receiver = new xterm.Terminal({ + rows: 4, + cols: 120, + scrollback: 10000, + allowProposedApi: true, + }); + try { + await new Promise((resolve) => receiver.write(payload, resolve)); + const buffer = receiver.buffer.active; + return { + history: buffer.baseY, + text: Array.from({ length: buffer.length }, (_, i) => + buffer.getLine(i)!.translateToString(true), + ).join("\n"), + }; + } finally { + receiver.dispose(); + } + } + try { + await viewers.attach(desktop, "healthy", restore); + await viewers.attach(phone, "pressured", restore); + await waitForCondition( + () => payloads(phone).length === 1 && payloads(desktop).length === 1, + 15000, + ); + const initial = payloads(phone)[0]!; + expect((await parse(initial)).history).toBe(10000); + pressure = true; + session.send({ type: "input", data: "BURST" }); + await waitForCondition(() => payloads(phone).length >= 2, 15000); + pressure = false; + // The final burst marker may belong to the replay cut or to its live tail. + // Read the same replay/output exchange a renderer sees rather than assuming + // worker parsing and daemon request scheduling cut the burst at one point. + async function currentView(source: object) { + const frames = viewers.frames + .filter((row) => row.source === source) + .map((row) => row.frame); + const start = frames.findLastIndex( + (frame) => + frame.opcode === TerminalStreamOpcode.Restore || + frame.opcode === TerminalStreamOpcode.ReplayBegin, + ); + return parse( + Buffer.concat( + frames + .slice(start) + .filter( + (frame) => + frame.opcode === TerminalStreamOpcode.Restore || + frame.opcode === TerminalStreamOpcode.ReplayData || + frame.opcode === TerminalStreamOpcode.Output, + ) + .map((frame) => frame.payload), + ), + ); + } + await waitForCondition( + async () => + (await currentView(phone)).text.includes("BURST-DONE") && + (await currentView(desktop)).text.includes("BURST-DONE"), + 15000, + ); + const recovery = payloads(phone)[1]!; + const recovered = await parse(recovery); + expect(recovered.history).toBe(500); + expect(recovered.text).toContain("界é🙂"); + for (const source of [phone, desktop]) { + const indexes = [...(await currentView(source)).text.matchAll(/row-(\d+)/g)].map((match) => + Number(match[1]), + ); + expect(indexes.at(-1)).toBe(16049); + expect(indexes).toEqual(Array.from({ length: indexes.length }, (_, i) => indexes[0]! + i)); + } + expect(recovery.byteLength).toBeLessThan(initial.byteLength / 10); + expect(recovery.byteLength).toBeLessThan(256 * 1024); + expect(payloads(desktop)).toHaveLength(1); // The healthy peer keeps its full replay and live stream. + session.send({ type: "input", data: "AFTER-CATCH-UP" }); + await waitForCondition( + () => + viewers.text(phone).includes("ECHO:AFTER-CATCH-UP") && + viewers.text(desktop).includes("ECHO:AFTER-CATCH-UP"), + 10000, + ); + expect(viewers.text(phone).match(/ECHO:AFTER-CATCH-UP/g)).toHaveLength(1); + expect(viewers.text(desktop).match(/ECHO:AFTER-CATCH-UP/g)).toHaveLength(1); + await viewers.delivery.detach(phone); + await viewers.attach(fresh, "reattach", restore); + await waitForCondition(() => payloads(fresh).length === 1, 15000); + const reattached = await parse(payloads(fresh)[0]!); + expect(reattached.history).toBe(10000); + expect(reattached.text).toContain("row-16049"); + expect(reattached.text).toContain("ECHO:AFTER-CATCH-UP"); + expect(viewers.ended(desktop)).toHaveLength(0); + expect(viewers.ended(phone)).toHaveLength(0); + process.stdout.write( + JSON.stringify({ + chunked, + initialBytes: initial.byteLength, + recoveryBytes: recovery.byteLength, + reattachBytes: payloads(fresh)[0]!.byteLength, + retainedHistory: reattached.history, + recoveryHistory: recovered.history, + }) + "\n", + ); + } finally { + await viewers.delivery.close(); + } + }, + 45000, +); diff --git a/packages/server/src/terminal/worker-terminal-manager.ts b/packages/server/src/terminal/worker-terminal-manager.ts index c9a6d7186e..9a82826cec 100644 --- a/packages/server/src/terminal/worker-terminal-manager.ts +++ b/packages/server/src/terminal/worker-terminal-manager.ts @@ -1,3 +1,4 @@ +import type { TerminalReplaySink, TerminalReplayMetadata } from "./terminal-replay.js"; import { randomBytes, randomUUID } from "node:crypto"; import { access } from "node:fs/promises"; import { setTimeout as delay } from "node:timers/promises"; @@ -5,7 +6,7 @@ import type { Logger } from "pino"; import { createExternalProcessEnv } from "../server/paseo-env.js"; import { assertAbsolutePath, isSameOrDescendantPath } from "../server/path-utils.js"; import { writtenDuringThisBoot } from "../server/pid-lock.js"; -import type { TerminalState } from "@getpaseo/protocol/messages"; +import type { WorkerTerminalState } from "./terminal-worker-protocol.js"; import type { TerminalActivity, TerminalActivityState } from "@getpaseo/protocol/terminal-activity"; import { deriveTerminalActivityStatusBucket } from "@getpaseo/protocol/terminal-activity"; import type { @@ -15,7 +16,6 @@ import type { TerminalCommandFinishedInfo, TerminalExitInfo, TerminalSession, - TerminalStateSnapshot, } from "./terminal.js"; import { resolvePaseoCliExecutablePath } from "./paseo-cli-path.js"; import type { CaptureTerminalLinesResult } from "./terminal-capture.js"; @@ -59,7 +59,6 @@ import type { TerminalWorkerResponse, TerminalWorkerToParentMessage, WorkerCreateTerminalOptions, - TerminalWorkerStateResult, WorkerTerminalInfo, } from "./terminal-worker-protocol.js"; @@ -93,7 +92,7 @@ interface PendingRequest { interface WorkerTerminalRecord { info: RequiredWorkerTerminalInfo; - state: TerminalState; + state: WorkerTerminalState; activity: TerminalActivity | null; // Cached input-mode preamble from the worker (the authoritative tracker lives // in the worker process). Updated with streamed output and snapshot responses. @@ -172,6 +171,7 @@ export function createWorkerTerminalManager( const requestTimeoutMs = managerOptions.requestTimeoutMs ?? REQUEST_TIMEOUT_MS; const resolveCreateEnvironment = managerOptions.resolveCreateEnvironment ?? resolveDaemonTerminalCreateEnvironment; + const replaySinks = new Map(); const pendingRequests = new Map(); const inFlight = new Set>(); const recordsById = new Map(); @@ -244,7 +244,7 @@ export function createWorkerTerminalManager( function registerRecord(input: { info: RequiredWorkerTerminalInfo; - state: TerminalState; + state: WorkerTerminalState; }): TerminalSession { const existing = recordsById.get(input.info.id); if (existing) { @@ -290,18 +290,11 @@ export function createWorkerTerminalManager( } sendBestEffortRequest({ type: "send", terminalId: record.info.id, message }); }, - subscribe( - listener: (msg: ServerMessage) => void, - options?: { initialSnapshot?: "state" | "ready" }, - ): () => void { + subscribe(listener: (msg: ServerMessage) => void): () => void { record.messageListeners.add(listener); - if (options?.initialSnapshot === "ready") { - queueMicrotask(() => { - if (record.messageListeners.has(listener)) { - listener({ type: "snapshotReady", revision: 0 }); - } - }); - } + queueMicrotask(() => { + if (record.messageListeners.has(listener)) listener({ type: "snapshotReady" }); + }); return () => { record.messageListeners.delete(listener); }; @@ -362,19 +355,8 @@ export function createWorkerTerminalManager( cols: record.state.cols, }; }, - getState(): TerminalState { - return record.state; - }, - getStateSnapshot(options?: { scrollbackLines?: number }): TerminalStateSnapshot { - const scrollbackLines = options?.scrollbackLines; - const scrollback = - typeof scrollbackLines === "number" - ? record.state.scrollback.slice(-scrollbackLines) - : record.state.scrollback; - return { - state: { ...record.state, scrollback }, - revision: 0, - }; + hasOutput(): boolean { + return record.state.hasOutput; }, getReplayPreamble(): string { return record.replayPreamble; @@ -442,9 +424,7 @@ export function createWorkerTerminalManager( if (!record) { return; } - if (message.message.type === "snapshot") { - record.state = message.message.state; - } + if (message.message.type === "output") record.state.hasOutput = true; record.replayPreamble = message.replayPreamble; for (const listener of Array.from(record.messageListeners)) { listener(message.message); @@ -610,7 +590,23 @@ export function createWorkerTerminalManager( } function attachWorker(): void { - worker.on("message", (message: TerminalWorkerToParentMessage) => { + const connection = worker; + connection.on("message", (message: TerminalWorkerToParentMessage) => { + if (message.type === "terminalReplay") { + // Consumption queues into the application's bounded transport synchronously. + // Never wait for app network delivery or accumulate a second replay queue here. + if (worker !== connection || !pendingRequests.has(message.requestId)) return; + try { + replaySinks.get(message.requestId)?.(message.event); + } catch (error) { + const pending = pendingRequests.get(message.requestId)!; + clearTimeout(pending.timeout); + pendingRequests.delete(message.requestId); + replaySinks.delete(message.requestId); + pending.reject(error instanceof Error ? error : new Error(String(error))); + } + return; + } if (isResponse(message)) { const pending = pendingRequests.get(message.requestId); if (!pending) { @@ -628,14 +624,15 @@ export function createWorkerTerminalManager( handleWorkerEvent(message); }); - worker.on("close", () => { + connection.on("close", () => { + if (worker !== connection) return; workerDisconnected = true; rejectPendingRequests(new Error("Terminal worker connection closed")); const reconnect = managerOptions.reconnect; if (!detached && reconnect) { reconnecting = (async () => { - const connection = await reconnect(); - if (!connection) { + const recovered = await reconnect(); + if (!recovered) { for (const terminalId of Array.from(recordsById.keys())) { handleTerminalExitEvent({ type: "terminalExit", @@ -646,10 +643,10 @@ export function createWorkerTerminalManager( return; } if (detached) { - connection.disconnect(); + recovered.disconnect(); return; } - worker = connection; + worker = recovered; workerDisconnected = false; attachWorker(); await adoptTerminals(); @@ -672,12 +669,18 @@ export function createWorkerTerminalManager( } attachWorker(); - function sendRequest(input: TerminalWorkerRequestInput): Promise { - if (reconnecting && workerDisconnected) return reconnecting.then(() => sendRequest(input)); + function sendRequest( + input: TerminalWorkerRequestInput, + sink?: TerminalReplaySink, + ): Promise { + if (reconnecting && workerDisconnected) + return reconnecting.then(() => sendRequest(input, sink)); if (workerDisconnected || !worker.connected) { return Promise.reject(new Error("Terminal worker is not running")); } + const connection = worker; const requestId = randomUUID(); + if (sink) replaySinks.set(requestId, sink); const message = { ...input, requestId } as TerminalWorkerRequest; const request = new Promise((resolve, reject) => { const timeout = setTimeout(() => { @@ -685,7 +688,7 @@ export function createWorkerTerminalManager( reject(new Error(`Terminal worker request timed out: ${input.type}`)); }, requestTimeoutMs); pendingRequests.set(requestId, { resolve, reject, timeout }); - worker.send(message, (error) => { + connection.send(message, (error) => { if (!error) { return; } @@ -700,7 +703,10 @@ export function createWorkerTerminalManager( () => undefined, ); inFlight.add(settled); - void settled.finally(() => inFlight.delete(settled)); + void settled.finally(() => { + inFlight.delete(settled); + replaySinks.delete(requestId); + }); return request; } @@ -867,22 +873,12 @@ export function createWorkerTerminalManager( return recordsById.get(id)?.session; }, - async getTerminalState( - id: string, - options?: { scrollbackLines?: number }, - ): Promise { - const snapshot = (await sendRequest({ - type: "getTerminalState", - terminalId: id, - ...(options ? { options } : {}), - })) as TerminalWorkerStateResult; - if (snapshot && snapshot.replayPreamble !== undefined) { - const record = recordsById.get(id); - if (record) { - record.replayPreamble = snapshot.replayPreamble; - } - } - return snapshot; + async replayTerminal(id, options, sink): Promise { + const metadata = (await sendRequest( + { type: "replayTerminal", terminalId: id, options }, + sink, + )) as TerminalReplayMetadata | null; + return metadata; }, setTerminalTitle(id: string, title: string): boolean { From 5ea639d9b25147560d1f384fbf6c7f4538b961c2 Mon Sep 17 00:00:00 2001 From: "paseo-ai[bot]" <266920839+paseo-ai[bot]@users.noreply.github.com> Date: Sat, 31 Oct 2026 04:01:29 +0000 Subject: [PATCH 136/173] fix: update lockfile signatures and Nix hash [skip ci] --- nix/npm-deps.hash | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nix/npm-deps.hash b/nix/npm-deps.hash index 35593d9f96..c7a63567f9 100644 --- a/nix/npm-deps.hash +++ b/nix/npm-deps.hash @@ -1 +1 @@ -sha256-8NOrrCAxraQ74lP3Vy59MRhloBfzStTc4rW+ltc42Fg= +sha256-zFjdXeRpqrjEZk44ZCvEOTnVVGX0ASfDPktYNiWZpsw= From 9b3f1bfffdce88fb00f24e0b12a5a476fdac2944 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sat, 31 Oct 2026 05:02:14 +0000 Subject: [PATCH 137/173] Start custom Codex providers with reserved names (#6954) * fix(codex): start custom providers with reserved names Codex rejects custom provider keys such as ollama before a turn starts. Namespace the generated keys without changing user-facing provider ids. Keep older sessions discoverable and select the new key explicitly when resuming them, so the startup fix does not strand existing conversations. Closes #6874 Co-authored-by: Egg3901 * fix(codex): keep native sessions out of custom provider imports * fix(providers): align custom provider example with generated config Correct the documented internal provider key and simplify import filtering while preserving native and legacy session selection. * fix(codex): exclude native GCP sessions from custom imports * test(codex): seed sessions through the portable launcher --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Egg3901 --- docs/custom-providers.md | 6 +- .../providers/codex-app-server-agent.test.ts | 69 ++++++++- .../agent/providers/codex-app-server-agent.ts | 34 ++++- ...x-custom-provider-import.local.e2e.test.ts | 143 ++++++++++++------ 4 files changed, 195 insertions(+), 57 deletions(-) diff --git a/docs/custom-providers.md b/docs/custom-providers.md index a6c6cefbdc..615389fe60 100644 --- a/docs/custom-providers.md +++ b/docs/custom-providers.md @@ -232,7 +232,7 @@ For pay-as-you-go, use `ANTHROPIC_API_KEY` with a standard Model Studio key (`sk Codex talks to OpenAI's Responses API by default. Custom providers that extend `"codex"` can point Codex at any OpenAI-compatible endpoint (OpenRouter, LiteLLM, vLLM, llama.cpp server, an internal gateway, etc.) by setting `OPENAI_BASE_URL` and `OPENAI_API_KEY` in the provider `env`. -Paseo passes those variables through to the Codex app-server process **and** maps them into Codex's thread config under `model_provider` / `model_providers`, because Codex reads provider routing from config rather than from `OPENAI_BASE_URL` alone. +Paseo passes those variables through to the Codex app-server process **and** maps them into Codex's thread config under `model_provider` / `model_providers`, because Codex reads provider routing from config rather than from `OPENAI_BASE_URL` alone. The generated Codex provider key is `paseo:`, so a Paseo provider such as `ollama` does not override a Codex built-in. Existing custom sessions created with a non-built-in provider key remain available in Import session. Native Codex conversations using a built-in key stay separate from a custom provider of the same name. ### Setup @@ -260,9 +260,9 @@ Paseo passes those variables through to the Codex app-server process **and** map Under the hood, for each custom Codex provider Paseo injects this into Codex's config: ```toml -model_provider = "my-codex" +model_provider = "paseo:my-codex" -[model_providers.my-codex] +[model_providers."paseo:my-codex"] name = "My Codex" base_url = "https://custom-relay.example.com/v1" wire_api = "responses" diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts index 61a86ccb8f..62e6bb0404 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts @@ -2623,9 +2623,9 @@ describe("Codex app-server provider", () => { OPENAI_BASE_URL: "https://custom-relay.example.com", }); expect(capturedThreadStartConfig(capturedRequests)).toEqual({ - model_provider: "codex-iisb", + model_provider: "paseo:codex-iisb", model_providers: { - "codex-iisb": { + "paseo:codex-iisb": { name: "Custom Codex", base_url: "https://custom-relay.example.com/v1", env_key: "OPENAI_API_KEY", @@ -2643,15 +2643,30 @@ describe("Codex app-server provider", () => { ); expect(capturedThreadStartConfig(capturedRequests)).toEqual({ - model_provider: "codex-custom", + model_provider: "paseo:codex-custom", model_providers: { - "codex-custom": expect.objectContaining({ + "paseo:codex-custom": expect.objectContaining({ base_url: "https://custom-relay.example.com/v1", }), }, }); }); + test("namespaces provider ids that collide with Codex built-ins", async () => { + // `ollama` is a reserved Codex provider id: without namespacing, Codex rejects + // the generated config outright and the agent never starts. + const capturedRequests = await runCustomCodexProviderTurn("ollama", "https://ollama.com"); + + expect(capturedThreadStartConfig(capturedRequests)).toEqual({ + model_provider: "paseo:ollama", + model_providers: { + "paseo:ollama": expect.objectContaining({ + base_url: "https://ollama.com/v1", + }), + }, + }); + }); + test("resumeSession does not replace a persisted Codex thread when app-server resume fails", async () => { const threadRequests: string[] = []; const appServer = createFakeCodexAppServer({ @@ -7348,9 +7363,21 @@ describe("Codex importable sessions", () => { const threadsByModelProvider = [ { id: "stock-thread", cwd: "/workspace/project-a", modelProvider: "openai", updatedAt: 2 }, { id: "custom-thread", cwd: "/workspace/project-a", modelProvider: "my-codex", updatedAt: 1 }, + { + id: "new-custom-thread", + cwd: "/workspace/project-a", + modelProvider: "paseo:my-codex", + updatedAt: 3, + }, + { + id: "other-custom-thread", + cwd: "/workspace/project-a", + modelProvider: "paseo-my-codex", + updatedAt: 4, + }, ]; - test("a custom Codex provider lists the threads it created", async () => { + test("a custom Codex provider lists its old and namespaced threads without other providers", async () => { const appServer = createFakeCodexAppServer({ "thread/list": providerFilteringThreadListHandler(threadsByModelProvider), }); @@ -7363,10 +7390,40 @@ describe("Codex importable sessions", () => { const sessions = await provider.listImportableSessions({ cwd: "/workspace/project-a" }); - expect(sessions.map((session) => session.providerHandleId)).toEqual(["custom-thread"]); + expect(sessions.map((session) => session.providerHandleId)).toEqual([ + "custom-thread", + "new-custom-thread", + ]); appServer.assertNoErrors(); }); + test.each(["openai", "ollama", "lmstudio", "amazon-bedrock", "amazon-bedrock-runtime", "gcp"])( + "a custom provider named %s excludes native built-in sessions", + async (providerId) => { + const appServer = createFakeCodexAppServer({ + "thread/list": providerFilteringThreadListHandler([ + { id: "native-thread", cwd: "/workspace/project-a", modelProvider: providerId }, + { + id: "custom-thread", + cwd: "/workspace/project-a", + modelProvider: `paseo:${providerId}`, + }, + ]), + }); + const provider = createProviderWithFakeAppServer(appServer, { + runtimeSettings: { + env: { OPENAI_BASE_URL: "https://llm.example.test/v1", OPENAI_API_KEY: "test-key" }, + }, + customProvider: { id: providerId, label: "Custom Codex", extends: "codex" }, + }); + + const sessions = await provider.listImportableSessions({ cwd: "/workspace/project-a" }); + + expect(sessions.map((session) => session.providerHandleId)).toEqual(["custom-thread"]); + appServer.assertNoErrors(); + }, + ); + test("stock Codex keeps listing only its own threads", async () => { const appServer = createFakeCodexAppServer({ "thread/list": providerFilteringThreadListHandler(threadsByModelProvider), diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.ts index 75370f0b5b..ea4e6378d9 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.ts @@ -151,6 +151,16 @@ function isCodexAlreadyUnarchivedError(error: unknown, threadId: string): boolea const TURN_START_TIMEOUT_MS = 90 * 1000; const INTERRUPT_TIMEOUT_MS = 2_000; const CODEX_PROVIDER = "codex" as const; +// These native provider identities belong to Codex, not to an older custom +// Paseo provider. Never include them in a custom provider's legacy import scan. +const CODEX_BUILTIN_MODEL_PROVIDER_IDS = new Set([ + "openai", + "ollama", + "lmstudio", + "amazon-bedrock", + "amazon-bedrock-runtime", + "gcp", +]); // Codex treats most app-server client names as the model-request originator. // This reserved Codex name is non-originating, so requests keep Codex's default // CLI identity instead of showing up as Paseo in provider usage logs. @@ -3368,10 +3378,14 @@ function buildCodexCustomProviderConfig( providerConfig.env_key = "OPENAI_API_KEY"; providerConfig.requires_openai_auth = false; } + // Namespace Paseo ids so they cannot override Codex's built-ins. A colon is + // forbidden in Paseo ids, keeping these keys distinct from every legacy id + // when both generations are listed together. + const providerKey = `paseo:${customProvider.id}`; return { - model_provider: customProvider.id, + model_provider: providerKey, model_providers: { - [customProvider.id]: providerConfig, + [providerKey]: providerConfig, }, }; } @@ -4059,6 +4073,11 @@ export class CodexAppServerAgentSession implements AgentSession { if (!this.client || !this.currentThreadId) return; // Paseo reads history only when it replays it; the resume response needs no turns. const params: Record = { threadId: this.currentThreadId, excludeTurns: true }; + if (this.deps.customCodexConfig) { + // Resume otherwise prefers the provider stored on the thread, including + // the unnamespaced key emitted by earlier Paseo versions. + params.modelProvider = this.deps.customCodexConfig.model_provider; + } const developerInstructions = composeSystemPromptParts( this.config.systemPrompt, this.config.daemonAppendSystemPrompt, @@ -7373,12 +7392,19 @@ export class CodexAppServerAgentClient implements AgentClient { const listLimit = options?.cwd ? Math.max(scanLimit, 50) : scanLimit; // Codex records each thread under the model provider that ran it and, // unless told otherwise, lists only the provider its own config selects. - // A custom provider runs under its own id, so ask for exactly that one. + // Include legacy custom ids, but keep Codex built-in sessions separate. const customProviderConfig = this.customProviderConfig(); + let modelProviders: string[] | undefined; + if (customProviderConfig && this.deps.customProvider) { + modelProviders = [customProviderConfig.model_provider]; + if (!CODEX_BUILTIN_MODEL_PROVIDER_IDS.has(this.deps.customProvider.id)) { + modelProviders.push(this.deps.customProvider.id); + } + } const allThreads = await readCodexThreadWindow(client, this.logger, { limit: listLimit, cwd: options?.cwd, - ...(customProviderConfig ? { modelProviders: [customProviderConfig.model_provider] } : {}), + ...(modelProviders ? { modelProviders } : {}), }); const threads = filterCodexThreadsByCwd(allThreads, options?.cwd); return threads.slice(0, limit).map((thread) => { diff --git a/packages/server/src/server/agent/providers/codex-custom-provider-import.local.e2e.test.ts b/packages/server/src/server/agent/providers/codex-custom-provider-import.local.e2e.test.ts index ebd8de5ab5..f546dc69e7 100644 --- a/packages/server/src/server/agent/providers/codex-custom-provider-import.local.e2e.test.ts +++ b/packages/server/src/server/agent/providers/codex-custom-provider-import.local.e2e.test.ts @@ -7,7 +7,8 @@ import path from "node:path"; import { afterEach, describe, expect, test } from "vitest"; import { createTestLogger } from "../../../test-utils/test-logger.js"; -import { CodexAppServerAgentClient } from "./codex-app-server-agent.js"; +import { spawnProcess } from "../../../utils/spawn.js"; +import { CodexAppServerAgentClient, CodexAppServerAgentSession } from "./codex-app-server-agent.js"; // Runs the real `codex` binary against a local Responses endpoint standing in // for a custom provider's OPENAI_BASE_URL, so no login is needed. @@ -88,52 +89,106 @@ describe("Codex custom provider import list", () => { for (const cleanup of cleanups.splice(0).toReversed()) await cleanup(); }); - test("lists a custom provider's session under that provider and imports it there", async () => { - const codexHome = mkdtempSync(path.join(os.tmpdir(), "codex-custom-import-home-")); - const cwd = mkdtempSync(path.join(os.tmpdir(), "codex-custom-import-cwd-")); - cleanups.push(() => rmSync(codexHome, { recursive: true, force: true })); - cleanups.push(() => rmSync(cwd, { recursive: true, force: true })); - const { baseUrl, server, requestCount } = await startResponsesEndpoint(); - cleanups.push(() => closeServer(server)); + test.each([ + { providerId: "my-codex", seedLegacy: false, seedBuiltin: false }, + { providerId: "ollama", seedLegacy: false, seedBuiltin: false }, + { providerId: "my-codex", seedLegacy: true, seedBuiltin: false }, + { providerId: "ollama", seedLegacy: false, seedBuiltin: true }, + ])( + "lists and imports sessions for $providerId (legacy: $seedLegacy, native: $seedBuiltin)", + async ({ providerId, seedLegacy, seedBuiltin }) => { + const codexHome = mkdtempSync(path.join(os.tmpdir(), "codex-custom-import-home-")); + const cwd = mkdtempSync(path.join(os.tmpdir(), "codex-custom-import-cwd-")); + cleanups.push(() => rmSync(codexHome, { recursive: true, force: true })); + cleanups.push(() => rmSync(cwd, { recursive: true, force: true })); + const { baseUrl, server, requestCount } = await startResponsesEndpoint(); + cleanups.push(() => closeServer(server)); - const logger = createTestLogger(); - const customCodex = new CodexAppServerAgentClient( - logger, - { env: { CODEX_HOME: codexHome, OPENAI_BASE_URL: baseUrl, OPENAI_API_KEY: "test-key" } }, - { customProvider: { id: "my-codex", label: "My Codex", extends: "codex" } }, - ); - const stockCodex = new CodexAppServerAgentClient(logger, { env: { CODEX_HOME: codexHome } }); + const logger = createTestLogger(); + if (seedLegacy || seedBuiltin) { + // Seed an old custom session or a native built-in session with real Codex. + const environment = { + ...process.env, + CODEX_HOME: codexHome, + CODEX_OSS_BASE_URL: baseUrl, + OPENAI_API_KEY: "test-key", + }; + const legacy = new CodexAppServerAgentSession( + { provider: "codex", cwd, model: "mock-model" }, + null, + logger, + async () => + spawnProcess("codex", ["app-server"], { cwd, env: environment, stdio: "pipe" }), + { + environment, + customCodexConfig: { + model_provider: providerId, + model_providers: seedBuiltin + ? {} + : { + [providerId]: { + name: "My Codex", + base_url: baseUrl, + wire_api: "responses", + env_key: "OPENAI_API_KEY", + requires_openai_auth: false, + }, + }, + }, + }, + ); + try { + await legacy.run("hello from the legacy provider"); + } finally { + await legacy.close(); + } + } + const customCodex = new CodexAppServerAgentClient( + logger, + { env: { CODEX_HOME: codexHome, OPENAI_BASE_URL: baseUrl, OPENAI_API_KEY: "test-key" } }, + { customProvider: { id: providerId, label: "My Codex", extends: "codex" } }, + ); + const stockCodex = new CodexAppServerAgentClient(logger, { env: { CODEX_HOME: codexHome } }); - const session = await customCodex.createSession({ - provider: "codex", - cwd, - model: "mock-model", - }); - try { - await session.run("hello from the custom provider"); - } finally { - await session.close(); - } + const session = await customCodex.createSession({ + provider: "codex", + cwd, + model: "mock-model", + }); + try { + await session.run("hello from the custom provider"); + } finally { + await session.close(); + } - const customSessions = await customCodex.listImportableSessions({ cwd }); - const stockSessions = await stockCodex.listImportableSessions({ cwd }); + const customSessions = await customCodex.listImportableSessions({ cwd }); + const stockSessions = await stockCodex.listImportableSessions({ cwd }); - expect(customSessions.map((entry) => entry.firstPromptPreview)).toEqual([ - "hello from the custom provider", - ]); - expect(stockSessions).toEqual([]); + expect(customSessions.map((entry) => entry.firstPromptPreview).sort()).toEqual( + seedLegacy + ? ["hello from the custom provider", "hello from the legacy provider"] + : ["hello from the custom provider"], + ); + expect(stockSessions).toEqual([]); - const config = { provider: "codex", cwd, model: "mock-model" }; - const imported = await customCodex.importSession( - { providerHandleId: customSessions[0].providerHandleId, cwd }, - { config, storedConfig: config }, - ); - const requestsBeforeImportedTurn = requestCount(); - try { - await imported.session.run("hello again after import"); - } finally { - await imported.session.close(); - } - expect(requestCount()).toBeGreaterThan(requestsBeforeImportedTurn); - }, 120_000); + const config = { provider: "codex", cwd, model: "mock-model" }; + const sessionToImport = seedLegacy + ? customSessions.find( + (entry) => entry.firstPromptPreview === "hello from the legacy provider", + )! + : customSessions[0]; + const imported = await customCodex.importSession( + { providerHandleId: sessionToImport.providerHandleId, cwd }, + { config, storedConfig: config }, + ); + const requestsBeforeImportedTurn = requestCount(); + try { + await imported.session.run("hello again after import"); + } finally { + await imported.session.close(); + } + expect(requestCount()).toBeGreaterThan(requestsBeforeImportedTurn); + }, + 120_000, + ); }); From 3b51b8ab2e2a394a7ae8c22645870cfe0ea44467 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sat, 31 Oct 2026 06:31:08 +0000 Subject: [PATCH 138/173] Recover terminal worker records after Windows reader contention (#8155) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * test(terminal): let cleanup fixture exit on request * test(terminal): capture the Windows record rewrite failure * test(terminal): repeat Windows cleanup exit diagnostics * fix(server): reopening a Codex agent no longer reads and holds its full history (#8132) * fix(server): read Codex history only when Paseo replays it Reopening a Codex agent whose timeline Paseo still held read the full thread on connect and kept it on the session until the next replay, which never came, so every reopened agent held a second copy of its transcript. thread/resume also returned every turn, and only the sandbox policy was used from it. Resume now sends excludeTurns (older Codex ignores the unknown field) and the history read moves into streamHistory, whose caller owns the result. A resumed session still needs the earlier turns for rewind targets and the sub-agent routes that keep an earlier child's interactions on its original card, so the first turn, goal or rewind indexes the thread and drops the timeline it read. * test(server): run reopened Codex agent tests without the Codex CLI installed * test(terminal): isolate record reader contention on exit * feat(usage): show when each limit resets, and make usage rows easier to read (#8162) The reset countdown floored to one unit, so a weekly window read "resets 2d" from 2d 23h down to 2d 0h and looked stuck for a day; the session window had the same problem with hours. Countdowns now use two units ("2d 23h", "4h 59m"), and every row also shows the clock time it resets ("7:20 AM", "Sat 8:00 AM", "Oct 31, 3:00 PM"), so users can plan work around a reset without hovering. Rows now put the window name and percent on one line, the bar under it, and the reset on its own full-width line, so the exact time fits at phone width in longer languages. The pinned-row background is gone; the pin glyph, drawn in the foreground colour when pinned, is the only pinned signal. Bars are 6px. * Make Claude session entrypoint relabeling optional (#8164) * fix(claude): make session entrypoint relabeling opt-in Keep inherited SDK and parent identities cleared. Honor the explicit session-open entrypoint contribution so users can opt into the label through a plugin instead of every session receiving it unconditionally. * test(hub): use standard budget for restart and worktree recovery The Windows CI scenario timed out at its custom 20-second limit while the other Hub cases took 4–10 seconds each. This scenario starts two daemons and creates, archives and restores a worktree. Use the existing 30-second suite budget without changing any assertions. * Deliver a steer message that arrives while the previous turn is still starting (#6192) * Deliver a steer message that arrives while the previous turn is still starting A steer send that reached an agent before its previous turn had a turn id found no turn to steer and replaced the starting turn, so the earlier message never reached the provider. Steering now waits for the starting turn to be accepted (or fail) and steers the turn it became. Fixes #6186 * Wake a waiting steer only once the starting turn has an id or its run has ended A failed start used to wake the waiting steer before its run was cleared, leaving the later send to replace a run that had already failed. * Clear a failed start's run even when reporting the failure throws A steer waiting on that start is released only when the run is cleared. * Test that a failed start keeps a waiting steer until its run is cleared * fix(server): steer Codex turns while native identification is pending Wait for the accepted foreground turn to receive its native ID before steering it. Returning unavailable in this window replaced the turn even after the manager had waited for startup. --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> * fix(terminal): recover worker records after reader contention Retain the latest record until a transient sharing failure clears. Deliver exits while publication is pending, await publication before confirming creation, and cancel retries before retirement. --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Mohamed Boudra --- .../src/terminal/terminal-worker-process.ts | 16 ++- .../terminal-worker-record-publisher.test.ts | 70 +++++++++++ .../terminal-worker-record-publisher.ts | 62 ++++++++++ .../terminal/worker-terminal-manager.test.ts | 116 +++++++++++------- 4 files changed, 218 insertions(+), 46 deletions(-) create mode 100644 packages/server/src/terminal/terminal-worker-record-publisher.test.ts create mode 100644 packages/server/src/terminal/terminal-worker-record-publisher.ts diff --git a/packages/server/src/terminal/terminal-worker-process.ts b/packages/server/src/terminal/terminal-worker-process.ts index b3e8864f9d..855c39da59 100644 --- a/packages/server/src/terminal/terminal-worker-process.ts +++ b/packages/server/src/terminal/terminal-worker-process.ts @@ -18,6 +18,7 @@ import { writeTerminalWorkerRecord, type TerminalWorkerRecord, } from "./terminal-worker-record.js"; +import { createTerminalWorkerRecordPublisher } from "./terminal-worker-record-publisher.js"; import { resolveTerminalWorkerSocketPath } from "./terminal-worker-socket-path.js"; import { TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV, @@ -214,13 +215,17 @@ function runWorker(argv: string[]): void { replayController.send(message); } - function persistRecord(): void { + const recordPublisher = createTerminalWorkerRecordPublisher((state) => { + writeTerminalWorkerRecord(args.paseoHome, state); + }); + + async function persistRecord(): Promise { if (!record || exiting) return; record = { ...record, terminals: record.terminals.filter((entry) => sessionsById.has(entry.id)), }; - writeTerminalWorkerRecord(args.paseoHome, record); + await recordPublisher.publish(record); } function removeOwnFiles(): void { @@ -233,6 +238,7 @@ function runWorker(argv: string[]): void { function exitWorker(code: number): void { if (exiting) return; exiting = true; + recordPublisher.stop(); removeOwnFiles(); server?.close(); process.exit(code); @@ -349,7 +355,9 @@ function runWorker(argv: string[]): void { outputCoalescer.flush(); clearTerminalSubscriptions(session.id); sessionsById.delete(session.id); - persistRecord(); + void persistRecord().catch((error) => { + if (!exiting) console.error("Cannot publish terminal exit:", error); + }); if (exitsHeldDuringCreation.has(session.id)) { exitsHeldDuringCreation.set(session.id, info); return; @@ -424,7 +432,7 @@ function runWorker(argv: string[]): void { { id: session.id, pid, startedAt: inspection.snapshot.startedAt }, ], }; - persistRecord(); + await persistRecord(); } function enqueueCreateTerminalRequest(message: TerminalCreateRequest): Promise { diff --git a/packages/server/src/terminal/terminal-worker-record-publisher.test.ts b/packages/server/src/terminal/terminal-worker-record-publisher.test.ts new file mode 100644 index 0000000000..dba50b9efe --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-record-publisher.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, it } from "vitest"; +import { setTimeout as delay } from "node:timers/promises"; +import { createTerminalWorkerRecordPublisher } from "./terminal-worker-record-publisher.js"; +import type { TerminalWorkerRecord } from "./terminal-worker-record.js"; + +const record: TerminalWorkerRecord = { + recordId: "worker", + pid: 123, + bootId: null, + createdAt: "now", + identity: { startedAt: "now", commandLine: "worker" }, + protocolVersion: 1, + paseoVersion: "test", + socketPath: "socket", + secret: "secret", + terminals: [{ id: "terminal", pid: 124, startedAt: "now" }], +}; + +describe("live worker record publication", () => { + it.each(["EPERM", "EBUSY", "EACCES"])( + "publishes the latest state after %s contention clears", + async (code) => { + let locked = true; + const written: TerminalWorkerRecord[] = []; + const publisher = createTerminalWorkerRecordPublisher((state) => { + if (locked) throw Object.assign(new Error("reader holds record"), { code }); + written.push(state); + }); + try { + const creation = publisher.publish(record); + const exited = { ...record, terminals: [] }; + const exit = publisher.publish(exited); + expect(written).toEqual([]); + locked = false; + await Promise.all([creation, exit]); + expect(written).toEqual([exited]); + } finally { + publisher.stop(); + } + }, + ); + + it("does not recreate a retired record when a reader releases it", async () => { + let locked = true; + const written: TerminalWorkerRecord[] = []; + const publisher = createTerminalWorkerRecordPublisher((state) => { + if (locked) + throw Object.assign(new Error("reader holds record"), { + code: "EPERM", + }); + written.push(state); + }); + const pending = publisher.publish(record); + const rejected = expect(pending).rejects.toThrow("stopped"); + publisher.stop(); + locked = false; + await rejected; + await delay(50); + expect(written).toEqual([]); + await expect(publisher.publish(record)).rejects.toThrow("stopped"); + }); + + it("reports permanent storage failures without retrying", async () => { + const publisher = createTerminalWorkerRecordPublisher(() => { + throw Object.assign(new Error("disk full"), { code: "ENOSPC" }); + }); + await expect(publisher.publish(record)).rejects.toThrow("disk full"); + publisher.stop(); + }); +}); diff --git a/packages/server/src/terminal/terminal-worker-record-publisher.ts b/packages/server/src/terminal/terminal-worker-record-publisher.ts new file mode 100644 index 0000000000..415c785102 --- /dev/null +++ b/packages/server/src/terminal/terminal-worker-record-publisher.ts @@ -0,0 +1,62 @@ +import type { TerminalWorkerRecord } from "./terminal-worker-record.js"; + +const TRANSIENT_ERRORS = new Set(["EPERM", "EBUSY", "EACCES"]); + +/** Serializes live worker publication, retaining the latest state across reader contention. + * Creation awaits publication; exit notifications need not wait for a reader to close. + * Stop before retiring the record so a pending retry cannot recreate it. + */ +export function createTerminalWorkerRecordPublisher(write: (record: TerminalWorkerRecord) => void) { + let stopped = false; + let latest: TerminalWorkerRecord; + let timer: ReturnType | undefined; + let pending: + | { + promise: Promise; + resolve: () => void; + reject: (error: unknown) => void; + } + | undefined; + + function attempt(): void { + timer = undefined; + const publication = pending; + if (!publication) return; + try { + write(latest); + publication.resolve(); + pending = undefined; + } catch (error) { + if (TRANSIENT_ERRORS.has((error as NodeJS.ErrnoException).code ?? "")) { + timer = setTimeout(attempt, 25); + } else { + publication.reject(error); + pending = undefined; + } + } + } + + return { + publish(record: TerminalWorkerRecord): Promise { + if (stopped) return Promise.reject(new Error("Worker record publisher stopped")); + latest = record; + if (pending) return pending.promise; + let resolve!: () => void; + let reject!: (error: unknown) => void; + const promise = new Promise((yes, no) => { + resolve = yes; + reject = no; + }); + pending = { promise, resolve, reject }; + attempt(); + return promise; + }, + stop(): void { + stopped = true; + clearTimeout(timer); + timer = undefined; + pending?.reject(new Error("Worker record publisher stopped")); + pending = undefined; + }, + }; +} diff --git a/packages/server/src/terminal/worker-terminal-manager.test.ts b/packages/server/src/terminal/worker-terminal-manager.test.ts index ad066327a2..ffc9b18a45 100644 --- a/packages/server/src/terminal/worker-terminal-manager.test.ts +++ b/packages/server/src/terminal/worker-terminal-manager.test.ts @@ -16,7 +16,9 @@ import { afterEach, expect, it } from "vitest"; import { isPlatform } from "../test-utils/platform.js"; import { EventEmitter } from "node:events"; import { + closeSync, existsSync, + openSync, mkdirSync, mkdtempSync, readdirSync, @@ -58,6 +60,7 @@ import { listTerminalWorkerRecords, readTerminalWorkerRecord, terminalWorkerDirectory, + terminalWorkerRecordPath, type TerminalWorkerRecord, } from "./terminal-worker-record.js"; import { TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV } from "./terminal-worker-protocol.js"; @@ -807,52 +810,81 @@ async function recordedTerminalPids(paseoHome: string): Promise { - const paseoHome = createTemporaryHome(); - const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-unfinished-kill-")); - temporaryDirs.push(cwd); - const first = await startRealWorkerManager({ paseoHome }); - manager = first; - const ending = await first.createTerminal({ - workspaceId: "ws-unfinished-kill", - cwd, - ...nodeTerminalCommand("setInterval(() => {}, 1000);"), - }); - const remaining = await first.createTerminal({ - workspaceId: "ws-unfinished-kill", - cwd, - ...nodeTerminalCommand("setInterval(() => {}, 1000);"), - }); - const pids = await recordedTerminalPids(paseoHome); - const endingPid = pids.get(ending.id)!; - const remainingPid = pids.get(remaining.id)!; +it.each([false, true])( + "never adopts a live worker's terminals after a kill cleanup it could not finish, even once the worker rewrites its record (held reader: %s)", + async (holdReader) => { + const paseoHome = createTemporaryHome(); + const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-unfinished-kill-")); + temporaryDirs.push(cwd); + const first = await startRealWorkerManager({ paseoHome }); + manager = first; + const exitRequestPath = join(cwd, "exit-requested"); + const exitObservedPath = join(cwd, "exit-observed"); + const ending = await first.createTerminal({ + workspaceId: "ws-unfinished-kill", + cwd, + ...nodeTerminalCommand(` + const { existsSync, writeFileSync } = require("node:fs"); + setInterval(() => { + if (existsSync(${JSON.stringify(exitRequestPath)})) { + writeFileSync(${JSON.stringify(exitObservedPath)}, ""); + process.exit(0); + } + }, 25); + `), + }); + const remaining = await first.createTerminal({ + workspaceId: "ws-unfinished-kill", + cwd, + ...nodeTerminalCommand("setInterval(() => {}, 1000);"), + }); + const pids = await recordedTerminalPids(paseoHome); + const endingPid = pids.get(ending.id)!; + const remainingPid = pids.get(remaining.id)!; + const [record] = await workerRecords(paseoHome); - // A kill cleanup whose process table read fails signals nothing and leaves the worker live. - const inspector = createTerminalWorkerProcessInspector(); - await expect( - reapTerminalWorkers({ - paseoHome, - inspector: { ...inspector, listProcesses: () => Promise.reject(new Error("ps timed out")) }, - }), - ).rejects.toBeInstanceOf(TerminalCleanupNotConfirmedError); - await first.detach(); - expect((await readUnconfirmedTerminalCleanup(paseoHome)).length).toBeGreaterThan(0); + // A kill cleanup whose process table read fails signals nothing and leaves the worker live. + const inspector = createTerminalWorkerProcessInspector(); + await expect( + reapTerminalWorkers({ + paseoHome, + inspector: { + ...inspector, + listProcesses: () => Promise.reject(new Error("ps timed out")), + }, + }), + ).rejects.toBeInstanceOf(TerminalCleanupNotConfirmedError); + expect((await readUnconfirmedTerminalCleanup(paseoHome)).length).toBeGreaterThan(0); - // One terminal ends on its own: the live worker rewrites its record from memory. - process.kill(endingPid, "SIGKILL"); - await waitForCondition( - async () => !(await recordedTerminalPids(paseoHome)).has(ending.id), - 10000, - ); - expect((await readUnconfirmedTerminalCleanup(paseoHome)).length).toBeGreaterThan(0); + // Keep an ordinary reader open until the worker delivers the terminal exit. + // Windows cannot replace the record while this handle is open. The exit must + // still reach the controller, and publication must recover after release. + const recordFd = holdReader + ? openSync(terminalWorkerRecordPath(paseoHome, record!.pid), "r") + : null; + try { + writeFileSync(exitRequestPath, ""); + await waitForCondition(() => first.getTerminal(ending.id) === undefined, 10000); + expect(existsSync(exitObservedPath)).toBe(true); + expect(isProcessAlive(endingPid)).toBe(false); + } finally { + if (recordFd !== null) closeSync(recordFd); + } + await waitForCondition( + async () => !(await recordedTerminalPids(paseoHome)).has(ending.id), + 10000, + ); + expect((await readUnconfirmedTerminalCleanup(paseoHome)).length).toBeGreaterThan(0); - manager = await startRealWorkerManager({ paseoHome }); + await first.detach(); + manager = await startRealWorkerManager({ paseoHome }); - expect(manager.getTerminal(remaining.id)).toBeUndefined(); - expect(await manager.getTerminals(cwd)).toEqual([]); - await waitForCondition(() => !isProcessAlive(remainingPid), 10000); - expect(await readUnconfirmedTerminalCleanup(paseoHome)).toEqual([]); -}); + expect(manager.getTerminal(remaining.id)).toBeUndefined(); + expect(await manager.getTerminals(cwd)).toEqual([]); + await waitForCondition(() => !isProcessAlive(remainingPid), 10000); + expect(await readUnconfirmedTerminalCleanup(paseoHome)).toEqual([]); + }, +); // The worker's own `ps`, delayed: a program that exits while the worker reads its birth time // lands its exit in the middle of creation. Only the worker launched while this PATH is set sees From 9c5b47421a8c1a1b307612b59becf76f85ce800d Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sat, 31 Oct 2026 06:49:47 +0000 Subject: [PATCH 139/173] test(server): exclude filesystem startup from config responsiveness (#8296) * test(server): diagnose recurring config responsiveness failure * test(server): compare profiled and plain config reads on Windows * test(server): correlate config profiles with long callbacks * test(server): probe config timing under CPU contention * test(server): exclude filesystem pool startup from config budget * test(terminal): finish output before comparing replay captures A marker can arrive before its trailing newline. Comparing captures taken on either side of that output compares different terminal states. Split that output deliberately and wait for its parsed completion before capturing the expected replay. --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../terminal/worker-terminal-manager.test.ts | 18 +++++++++++++++++- .../test-fixtures/config-responsiveness.ts | 6 ++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/packages/server/src/terminal/worker-terminal-manager.test.ts b/packages/server/src/terminal/worker-terminal-manager.test.ts index ffc9b18a45..7d91ec180e 100644 --- a/packages/server/src/terminal/worker-terminal-manager.test.ts +++ b/packages/server/src/terminal/worker-terminal-manager.test.ts @@ -1742,6 +1742,7 @@ it.skipIf(isPlatform("win32"))( it("replays bounded ANSI chunks independently of live output and reconstructs the revision cut", async () => { const cwd = createTemporaryHome(); + const finishBefore = join(cwd, "finish-before"); manager = await startRealWorkerManager(); const session = trackTerminal( await manager.createTerminal({ @@ -1751,7 +1752,15 @@ it("replays bounded ANSI chunks independently of live output and reconstructs th cols: 120, ...nodeTerminalCommand(` for (let i = 0; i < 800; i++) process.stdout.write("\\x1b[31m" + String(i).padStart(4, "0") + ":" + "x".repeat(100) + "\\x1b[0m\\r\\n"); - require("node:readline").createInterface({ input: process.stdin }).on("line", line => process.stdout.write(line === "before" ? "PRE-CUT\\r\\n" : "LIVE-AFTER-REPLAY\\r\\n")); + require("node:readline").createInterface({ input: process.stdin }).on("line", line => { + if (line !== "before") { process.stdout.write("LIVE-AFTER-REPLAY\\r\\n"); return; } + process.stdout.write("PRE-CUT"); + const finish = setInterval(() => { + if (!require("node:fs").existsSync(${JSON.stringify(finishBefore)})) return; + clearInterval(finish); + process.stdout.write("\\r\\n"); + }, 5); + }); setInterval(() => {}, 1000); `), }), @@ -1775,6 +1784,13 @@ it("replays bounded ANSI chunks independently of live output and reconstructs th }); session.send({ type: "input", data: "before\r" }); await waitForCondition(() => live.includes("PRE-CUT"), 10000); + // A PTY may deliver the marker and its trailing newline separately. Finish + // that output before replay, so the two captures must describe the same cut. + writeFileSync(finishBefore, ""); + await waitForCondition(async () => { + const { lines } = await manager!.captureTerminal(session.id); + return lines.at(-2) === "PRE-CUT" && lines.at(-1) === ""; + }, 10000); const expected = await manager.captureTerminal(session.id); const metadata = await manager.replayTerminal(session.id, undefined, (event) => { events.push(event.type); diff --git a/packages/server/src/utils/test-fixtures/config-responsiveness.ts b/packages/server/src/utils/test-fixtures/config-responsiveness.ts index 9e151c805a..787ad88674 100644 --- a/packages/server/src/utils/test-fixtures/config-responsiveness.ts +++ b/packages/server/src/utils/test-fixtures/config-responsiveness.ts @@ -1,4 +1,5 @@ import { createHook, executionAsyncResource } from "node:async_hooks"; +import { stat } from "node:fs/promises"; import { MessagePort } from "node:worker_threads"; import assert from "node:assert/strict"; import { setImmediate as nextTurn } from "node:timers/promises"; @@ -10,6 +11,11 @@ import { readPaseoConfigForEdit } from "../paseo-config-file.js"; // Read the real file once, without warming the config snapshot or schema. const directory = process.argv[2]; assert.ok(directory, "Config directory is required"); +// The daemon has already used asynchronous filesystem APIs before reading a +// project config. Start libuv's filesystem worker pool outside the measurement: +// its first submission synchronously creates workers in a fresh Node process. +// Stat the probe itself so the config, snapshot and schemas remain cold. +await stat(process.argv[1]); await nextTurn(); let workerMessages = 0; const activity = createHook({ From 254166e7c13b87f1bcf48105716a9021c48f643a Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sat, 31 Oct 2026 14:23:10 +0700 Subject: [PATCH 140/173] feat(terminal): add native selection handles (#8348) * feat(terminal): add native selection handles * fix(terminal): preserve selection at row boundaries * fix(terminal): preserve selection boundary when handles cross --- .../paseo/terminal/TerminalRowLayoutTest.kt | 35 ++ .../sh/paseo/terminal/PaseoTerminalView.kt | 1 - .../java/sh/paseo/terminal/TerminalFrame.kt | 1 - .../sh/paseo/terminal/TerminalRowLayout.kt | 38 +- .../app/modules/paseo-terminal/contract.ts | 1 - .../ios/PaseoTerminalView.swift | 6 +- .../paseo-terminal/ios/TerminalFrame.swift | 1 - .../ios/TerminalRowLayout.swift | 29 +- .../terminal-emulator-native-grid.native.tsx | 379 +++++----------- .../src/terminal/native-renderer/colors.ts | 3 +- .../terminal-grid-view.native.tsx | 1 - .../terminal-selection-controller.test.ts | 411 ++++++++++++++++++ .../terminal-selection-controller.ts | 208 +++++++++ .../terminal-selection-gesture.test.ts | 354 --------------- .../terminal-selection-gesture.ts | 108 ----- .../terminal-selection.test.ts | 48 ++ .../native-renderer/terminal-selection.ts | 27 +- 17 files changed, 865 insertions(+), 786 deletions(-) create mode 100644 packages/app/src/terminal/native-renderer/terminal-selection-controller.test.ts create mode 100644 packages/app/src/terminal/native-renderer/terminal-selection-controller.ts delete mode 100644 packages/app/src/terminal/native-renderer/terminal-selection-gesture.test.ts delete mode 100644 packages/app/src/terminal/native-renderer/terminal-selection-gesture.ts diff --git a/packages/app/modules/paseo-terminal/android/src/androidTest/java/sh/paseo/terminal/TerminalRowLayoutTest.kt b/packages/app/modules/paseo-terminal/android/src/androidTest/java/sh/paseo/terminal/TerminalRowLayoutTest.kt index e9b8ab1edf..8e889bccf2 100644 --- a/packages/app/modules/paseo-terminal/android/src/androidTest/java/sh/paseo/terminal/TerminalRowLayoutTest.kt +++ b/packages/app/modules/paseo-terminal/android/src/androidTest/java/sh/paseo/terminal/TerminalRowLayoutTest.kt @@ -10,6 +10,7 @@ import androidx.test.platform.app.InstrumentationRegistry import org.json.JSONArray import org.json.JSONObject import org.junit.Assert.assertTrue +import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith @@ -55,6 +56,40 @@ class TerminalRowLayoutTest { } } + @Test + fun selectionCompositesOverCellAndTerminalBackgroundsWithoutChangingForeground() { + val red = 0xffff0000.toInt() + val green = 0xff00aa00.toInt() + val overlay = 0x472684ff + val source = TerminalRowSource.decode("1,1;1,4294901760,4278233600,0;M") + val layout = TerminalRowLayout(source, font, TerminalCustomGlyphs.EMPTY) + paints.selectionBackground = overlay + for (terminalBackground in listOf(0xffffffff.toInt(), 0xff000000.toInt())) { + val actual = raster { canvas -> + canvas.drawColor(terminalBackground) + layout.drawSelected(canvas, 0, TerminalSelection(TerminalSelectionRecord()), paints) + } + val expected = raster { canvas -> + canvas.drawColor(terminalBackground) + canvas.drawColor(green) + canvas.drawColor(overlay) + } + assertEquals(expected.getPixel(0, 0), actual.getPixel(0, 0)) + assertTrue("selected glyph retains its red foreground", (0 until font.cellHeightPx).any { y -> + (0 until font.cellWidthPx).any { x -> actual.getPixel(x, y) == red } + }) + } + val defaultBackground = TerminalRowLayout(TerminalRowSource.decode("1,1;1,4294901760,0,0;M"), font, TerminalCustomGlyphs.EMPTY) + for (terminalBackground in listOf(0xffffffff.toInt(), 0xff000000.toInt())) { + val actual = raster { canvas -> + canvas.drawColor(terminalBackground) + defaultBackground.drawSelected(canvas, 0, TerminalSelection(TerminalSelectionRecord()), paints) + } + val expected = raster { canvas -> canvas.drawColor(terminalBackground); canvas.drawColor(overlay) } + assertEquals(expected.getPixel(0, 0), actual.getPixel(0, 0)) + } + } + private fun starts(row: JSONObject, key: String): List = row.getJSONArray(key).let { starts -> List(starts.length()) { starts.getInt(it) } } diff --git a/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/PaseoTerminalView.kt b/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/PaseoTerminalView.kt index 3fcf012e03..03f76cf91b 100644 --- a/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/PaseoTerminalView.kt +++ b/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/PaseoTerminalView.kt @@ -63,7 +63,6 @@ class PaseoTerminalView(context: Context, appContext: AppContext) : ExpoView(con backgroundColor = argb(value.background) cursorColor = argb(value.cursor) paints.selectionBackground = argb(value.selectionBackground) - paints.selectionForeground = argb(value.selectionForeground) invalidate() } diff --git a/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/TerminalFrame.kt b/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/TerminalFrame.kt index c27be7cc7a..a33eca76e6 100644 --- a/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/TerminalFrame.kt +++ b/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/TerminalFrame.kt @@ -27,7 +27,6 @@ class TerminalThemeRecord : Record { @Field val background: Double = 0.0 @Field val cursor: Double = 0.0 @Field val selectionBackground: Double = 0.0 - @Field val selectionForeground: Double = 0.0 } class TerminalCustomGlyphRecord : Record { diff --git a/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/TerminalRowLayout.kt b/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/TerminalRowLayout.kt index d2ee2355bc..6680f15ed9 100644 --- a/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/TerminalRowLayout.kt +++ b/packages/app/modules/paseo-terminal/android/src/main/java/sh/paseo/terminal/TerminalRowLayout.kt @@ -23,7 +23,7 @@ private const val CLIP_UNBOUNDED_PX = 100_000f * either half alone would show an explicit virama. Each resulting group is drawn from the shaped * run (in context) at its first cell's column, centred in the columns it owns, and scaled down only when * its glyphs are wider than those columns. Colors never split groups or reshape the row: a group - * whose cells differ in color or selection is drawn once per color, clipped to those cells' columns. + * whose cells differ in color is drawn once per color, clipped to those cells' columns. */ internal class TerminalRowLayout( val source: TerminalRowSource, @@ -195,7 +195,7 @@ internal class TerminalRowLayout( canvas.drawRenderNode(recorded) } - /** Draws the row with selected cells in selection colors. Selection never reshapes the row. */ + /** Draws backgrounds, the selection overlay, then text with its original colors. */ fun drawSelected(canvas: Canvas, row: Int, selection: TerminalSelection, paints: TerminalPaints) { drawContent(canvas, row, selection, paints) } @@ -213,17 +213,17 @@ internal class TerminalRowLayout( val cellHeight = font.cellHeightPx.toFloat() val fill = paints.fill for (cell in 0 until cellCount) { - val background = - if (selected(row, selection, cell)) paints.selectionBackground else cellBackground[cell] - if (background ushr 24 == 0) continue - fill.color = background - canvas.drawRect( - cellCol[cell] * cellWidth, - 0f, - (cellCol[cell] + cellSpan[cell]) * cellWidth, - cellHeight, - fill, - ) + val left = cellCol[cell] * cellWidth + val right = (cellCol[cell] + cellSpan[cell]) * cellWidth + val background = cellBackground[cell] + if (background ushr 24 != 0) { + fill.color = background + canvas.drawRect(left, 0f, right, cellHeight, fill) + } + if (selected(row, selection, cell)) { + fill.color = paints.selectionBackground + canvas.drawRect(left, 0f, right, cellHeight, fill) + } } val baseline = font.baselinePx.toFloat() @@ -234,9 +234,9 @@ internal class TerminalRowLayout( val paint = font.paint(cellFlags[group.firstCell]) var first = group.firstCell while (first <= group.lastCell) { - val color = foreground(row, selection, first, paints) + val color = cellForeground[first] var last = first - while (last < group.lastCell && foreground(row, selection, last + 1, paints) == color) last += 1 + while (last < group.lastCell && cellForeground[last + 1] == color) last += 1 // Only edges between differently colored cells clip; the group's outer edges may overhang. val clipped = first > group.firstCell || last < group.lastCell canvas.save() @@ -257,7 +257,7 @@ internal class TerminalRowLayout( for (cell in 0 until cellCount) { val glyph = cellGlyph[cell] val flags = cellFlags[cell] - val foreground = foreground(row, selection, cell, paints) + val foreground = cellForeground[cell] if (glyph != null) { fill.color = foreground glyph.draw(canvas, cellCol[cell] * cellWidth, cellSpan[cell] * cellWidth, cellHeight, font.density, fill) @@ -291,9 +291,6 @@ internal class TerminalRowLayout( canvas.drawTextRun(text, group.start, group.end, group.contextStart, group.contextEnd, x, baseline, false, paint) } - private fun foreground(row: Int, selection: TerminalSelection?, cell: Int, paints: TerminalPaints): Int = - if (selected(row, selection, cell)) paints.selectionForeground else cellForeground[cell] - /** The row's text as accessibility reads it. */ fun describe(): String = source.text.trimEnd() } @@ -301,6 +298,5 @@ internal class TerminalRowLayout( /** Paint state shared by every row of one view. */ internal class TerminalPaints { val fill = Paint(Paint.ANTI_ALIAS_FLAG) - var selectionBackground: Int = 0xFFFFFF00.toInt() - var selectionForeground: Int = 0xFF000000.toInt() + var selectionBackground: Int = 0x472684FF } diff --git a/packages/app/modules/paseo-terminal/contract.ts b/packages/app/modules/paseo-terminal/contract.ts index ee4fe45ab0..6fd6c0906b 100644 --- a/packages/app/modules/paseo-terminal/contract.ts +++ b/packages/app/modules/paseo-terminal/contract.ts @@ -43,7 +43,6 @@ export interface PaseoTerminalTheme { background: number; cursor: number; selectionBackground: number; - selectionForeground: number; } export interface PaseoTerminalCellMetrics { diff --git a/packages/app/modules/paseo-terminal/ios/PaseoTerminalView.swift b/packages/app/modules/paseo-terminal/ios/PaseoTerminalView.swift index 240cddddab..9739202cad 100644 --- a/packages/app/modules/paseo-terminal/ios/PaseoTerminalView.swift +++ b/packages/app/modules/paseo-terminal/ios/PaseoTerminalView.swift @@ -24,8 +24,7 @@ final class PaseoTerminalView: ExpoView { private var background = TerminalColor(Double(0xff00_0000)) private var cursorColor = TerminalColor(Double(0xffff_ffff)) private var rowPaint = TerminalRowPaint( - selectionBackground: TerminalColor(Double(0xffff_ff00)), - selectionForeground: TerminalColor(Double(0xff00_0000))) + selectionBackground: TerminalColor(Double(0x4726_84ff))) private var rowCache: [String: TerminalRowLayout] = [:] required init(appContext: AppContext? = nil) { @@ -44,8 +43,7 @@ final class PaseoTerminalView: ExpoView { background = TerminalColor(record.background) cursorColor = TerminalColor(record.cursor) rowPaint = TerminalRowPaint( - selectionBackground: TerminalColor(record.selectionBackground), - selectionForeground: TerminalColor(record.selectionForeground)) + selectionBackground: TerminalColor(record.selectionBackground)) backgroundColor = UIColor(cgColor: background.cgColor()) setNeedsDisplay() } diff --git a/packages/app/modules/paseo-terminal/ios/TerminalFrame.swift b/packages/app/modules/paseo-terminal/ios/TerminalFrame.swift index 84ba6e8b0c..2cba97fd61 100644 --- a/packages/app/modules/paseo-terminal/ios/TerminalFrame.swift +++ b/packages/app/modules/paseo-terminal/ios/TerminalFrame.swift @@ -25,7 +25,6 @@ struct TerminalThemeRecord: Record { @Field var background: Double = 0 @Field var cursor: Double = 0 @Field var selectionBackground: Double = 0 - @Field var selectionForeground: Double = 0 } struct TerminalCustomGlyphRecord: Record { diff --git a/packages/app/modules/paseo-terminal/ios/TerminalRowLayout.swift b/packages/app/modules/paseo-terminal/ios/TerminalRowLayout.swift index 80050c9040..83d731f1e3 100644 --- a/packages/app/modules/paseo-terminal/ios/TerminalRowLayout.swift +++ b/packages/app/modules/paseo-terminal/ios/TerminalRowLayout.swift @@ -27,7 +27,6 @@ private let leftToRightAttributes: [NSAttributedString.Key: Any] = { /// Colors a row is painted with besides its own styles. struct TerminalRowPaint { let selectionBackground: TerminalColor - let selectionForeground: TerminalColor } /// One row shaped once and placed on the terminal grid. @@ -267,31 +266,33 @@ final class TerminalRowLayout { selection?.contains(row: row, col: cellCol[cell], span: cellSpan[cell]) ?? false } - private func foreground(_ cell: Int, row: Int, selection: TerminalSelection?, paint: TerminalRowPaint) -> TerminalColor { - isSelected(cell, row: row, selection: selection) ? paint.selectionForeground : cellForeground[cell] - } - - /// Draws the row with its top edge at `top`, selected cells in selection colors. + /// Draws cell backgrounds, the selection overlay, then text with its original colors. func draw(in context: CGContext, row: Int, top: CGFloat, selection: TerminalSelection?, paint: TerminalRowPaint) { let cellWidth = font.cellWidth let cellHeight = font.cellHeight for cell in 0.. Math.abs(gesture.dx) ? eventDx : gesture.dx; - const dy = Math.abs(eventDy) > Math.abs(gesture.dy) ? eventDy : gesture.dy; - return { - x: press.startX + dx, - y: press.startY + dy, - }; -} - function initialNativeTerminalSize(): TerminalMeasuredSize { return { rows: MIN_NATIVE_TERMINAL_ROWS, cols: MIN_NATIVE_TERMINAL_COLS }; } @@ -163,19 +127,14 @@ function NativeTerminalEmulator({ const outputDrainRef = useRef(null); const screenModelRef = useRef(null); const selectionModelRef = useRef(createTerminalSelectionModel()); - const selectionLongPressTimeoutRef = useRef | null>(null); - const selectionPressRef = useRef(null); + const selectionControllerRef = useRef | null>(null); + const gestureStartRef = useRef({ x: 0, y: 0 }); + const [cellMetrics, setCellMetrics] = useState(null); const latestResolvedScreenRef = useRef(null); const paintFrameRef = useRef(null); const outputDecoderRef = useRef(new TextDecoder()); - const panStateRef = useRef({ - lastDy: 0, - rowRemainder: 0, - didScroll: false, - didNavigate: false, - movedBeyondTapTolerance: false, - intent: null, - }); const inputModeTrackerRef = useRef(new TerminalInputModeTracker()); const lastInputModeStateRef = useRef({ ...inputModeTrackerRef.current.getState(), @@ -245,6 +204,7 @@ function NativeTerminalEmulator({ }, []); const clearSelection = useCallback(() => { + selectionControllerRef.current?.cancel(); const snapshot = selectionModelRef.current.clear(); commitSelectionRange(snapshot.range); }, [commitSelectionRange]); @@ -255,20 +215,14 @@ function NativeTerminalEmulator({ const syncSelectionWithTerminal = useCallback( (terminal: NativeHeadlessTerminal) => { + const previous = selectionModelRef.current.getSnapshot().range; const snapshot = selectionModelRef.current.sync({ bounds: terminal.getBufferBounds() }); + if (previous && !snapshot.range) selectionControllerRef.current?.cancel(); commitSelectionRange(snapshot.range); }, [commitSelectionRange], ); - const clearSelectionLongPressTimeout = useCallback(() => { - if (selectionLongPressTimeoutRef.current === null) { - return; - } - clearTimeout(selectionLongPressTimeoutRef.current); - selectionLongPressTimeoutRef.current = null; - }, []); - const resolveVisibleRows = useCallback((terminal: NativeHeadlessTerminal): number => { return ( resolveMeasuredNativeTerminalSize({ @@ -523,8 +477,7 @@ function NativeTerminalEmulator({ emitMeasuredSize({ source: "measure" }); return () => { callbacksRef.current.onRendererReadyChange?.({ streamKey, isReady: false }); - clearSelectionLongPressTimeout(); - selectionPressRef.current = null; + selectionControllerRef.current?.cancel(); if (paintFrameRef.current !== null) { cancelAnimationFrame(paintFrameRef.current); paintFrameRef.current = null; @@ -534,7 +487,7 @@ function NativeTerminalEmulator({ terminalRef.current?.dispose(); terminalRef.current = null; }; - }, [clearSelectionLongPressTimeout, emitMeasuredSize, resetTerminal, streamKey]); + }, [emitMeasuredSize, resetTerminal, streamKey]); useEffect(() => { if (focusRequestToken <= 0) return; @@ -591,6 +544,7 @@ function NativeTerminalEmulator({ const handleCellMetricsChange = useCallback( (metrics: TerminalGridCellMetrics) => { metricsRef.current = metrics; + setCellMetrics(metrics); emitMeasuredSize({ source: "measure" }); }, [emitMeasuredSize], @@ -663,14 +617,6 @@ function NativeTerminalEmulator({ if (!coordinate) { return; } - const existingPress = selectionPressRef.current; - selectionPressRef.current = { - startX: point.x, - startY: point.y, - startedAt: existingPress?.startedAt ?? Date.now(), - startedWithSelection: existingPress?.startedWithSelection ?? false, - status: "selecting", - }; const bounds = terminal.getBufferBounds(); const wordSelection = resolveTerminalWordSelection({ terminal, coordinate }); let snapshot = selectionModelRef.current.begin({ @@ -685,222 +631,61 @@ function NativeTerminalEmulator({ [commitSelectionRange, resolveSelectionCoordinate], ); - const updateSelectionAtPoint = useCallback( - (point: { x: number; y: number }) => { - const terminal = terminalRef.current; - if (!terminal || selectionPressRef.current?.status !== "selecting") { - return; - } - const coordinate = resolveSelectionCoordinate(point); - if (!coordinate) { - return; - } - const snapshot = selectionModelRef.current.update({ - coordinate, - bounds: terminal.getBufferBounds(), - }); - commitSelectionRange(snapshot.range); - }, - [commitSelectionRange, resolveSelectionCoordinate], - ); - - const handlePanResponderScroll = useCallback( - (currentDy: number) => { - const cellHeight = metricsRef.current?.cellHeight; - if (!cellHeight || cellHeight <= 0) { - return; - } - const panState = panStateRef.current; - const update = advanceTerminalScrollGesture({ - state: panState, - currentDy, - cellHeight, - }); - panState.lastDy = update.state.lastDy; - panState.rowRemainder = update.state.rowRemainder; - panState.didScroll = update.state.didScroll; - const { rowDelta } = update; - if (rowDelta === 0) { - return; - } - if (rowDelta > 0) { - applyScroll("up", rowDelta); - return; - } - applyScroll("down", Math.abs(rowDelta)); - }, - [applyScroll], + const selectionController = useMemo( + () => + createTerminalSelectionController({ + getGeometry: () => { + const viewport = resolveSelectionViewport(); + const metrics = metricsRef.current; + return viewport && metrics + ? { range: selectionRangeRef.current, viewport, metrics } + : null; + }, + onBeginHandle: (endpoint, cols) => + selectionModelRef.current.beginEndpointDrag(endpoint, cols), + onMoveHandle: (coordinate) => { + const terminal = terminalRef.current; + if (!terminal) return; + commitSelectionRange( + selectionModelRef.current.update({ coordinate, bounds: terminal.getBufferBounds() }) + .range, + ); + }, + onLongPress: beginSelectionAtPoint, + onTap: focusTerminalFromTap, + onScroll: applyScroll, + schedule: (callback, delay) => setTimeout(callback, delay) as unknown as number, + cancel: (timer) => clearTimeout(timer), + }), + [ + applyScroll, + beginSelectionAtPoint, + commitSelectionRange, + focusTerminalFromTap, + resolveSelectionViewport, + ], ); + selectionControllerRef.current = selectionController; const panResponder = useMemo( () => PanResponder.create({ onStartShouldSetPanResponder: () => true, onStartShouldSetPanResponderCapture: () => true, - onMoveShouldSetPanResponder: (_event, gesture) => { - const intent = classifyTerminalGestureIntent({ - status: selectionRangeRef.current ? "selecting" : "pressing", - dx: gesture.dx, - dy: gesture.dy, - vx: gesture.vx, - vy: gesture.vy, - }); - return intent === "scroll" || intent === "select"; - }, - onMoveShouldSetPanResponderCapture: (_event, gesture) => { - const intent = classifyTerminalGestureIntent({ - status: selectionRangeRef.current ? "selecting" : "pressing", - dx: gesture.dx, - dy: gesture.dy, - vx: gesture.vx, - vy: gesture.vy, - }); - return intent === "scroll" || intent === "select"; - }, onPanResponderGrant: (event) => { - panStateRef.current = { - lastDy: 0, - rowRemainder: 0, - didScroll: false, - didNavigate: false, - movedBeyondTapTolerance: false, - intent: null, - }; - const point = { - x: event.nativeEvent.locationX, - y: event.nativeEvent.locationY, - }; - const pressStatus = selectionRangeRef.current ? "selecting" : "pressing"; - selectionPressRef.current = { - startX: point.x, - startY: point.y, - startedAt: Date.now(), - startedWithSelection: pressStatus === "selecting", - status: pressStatus, - }; - clearSelectionLongPressTimeout(); - if (pressStatus === "selecting") { - return; - } - selectionLongPressTimeoutRef.current = setTimeout(() => { - selectionLongPressTimeoutRef.current = null; - const press = selectionPressRef.current; - if (press?.status !== "pressing") { - return; - } - beginSelectionAtPoint({ x: press.startX, y: press.startY }); - }, TERMINAL_GESTURE_LONG_PRESS_MS); - }, - onPanResponderMove: (event, gesture) => { - const selectionPress = selectionPressRef.current; - const panState = panStateRef.current; - if (Math.hypot(gesture.dx, gesture.dy) > TERMINAL_GESTURE_TAP_TOLERANCE_PX) { - panState.movedBeyondTapTolerance = true; - } - if (selectionPress?.status === "selecting") { - if (panState.movedBeyondTapTolerance) { - updateSelectionAtPoint(resolvePanResponderPoint(selectionPress, event, gesture)); - } - return; - } - - if (panState.intent === "scroll") { - handlePanResponderScroll(gesture.dy); - return; - } - if (panState.didNavigate) { - return; - } - - if (selectionPress?.status === "pressing") { - const point = resolvePanResponderPoint(selectionPress, event, gesture); - const dx = point.x - selectionPress.startX; - const dy = point.y - selectionPress.startY; - const intent = classifyTerminalGestureIntent({ - status: "pressing", - dx, - dy, - vx: gesture.vx, - vy: gesture.vy, - elapsedMs: Date.now() - selectionPress.startedAt, - }); - if (intent === "tap" || intent === "pending") { - return; - } - - clearSelectionLongPressTimeout(); - panState.intent = intent; - - if (intent === "scroll") { - selectionPressRef.current = null; - handlePanResponderScroll(gesture.dy); - return; - } - - if (intent === "select") { - beginSelectionAtPoint({ x: selectionPress.startX, y: selectionPress.startY }); - updateSelectionAtPoint(point); - return; - } - } - }, - onPanResponderRelease: (event, gesture) => { - clearSelectionLongPressTimeout(); - const selectionPress = selectionPressRef.current; - if ( - selectionPress?.status === "selecting" && - panStateRef.current.movedBeyondTapTolerance - ) { - updateSelectionAtPoint(resolvePanResponderPoint(selectionPress, event, gesture)); - } - selectionPressRef.current = null; - const { didScroll, didNavigate, movedBeyondTapTolerance } = panStateRef.current; - panStateRef.current = { - lastDy: 0, - rowRemainder: 0, - didScroll: false, - didNavigate: false, - movedBeyondTapTolerance: false, - intent: null, - }; - const releaseAction = resolveTerminalGestureReleaseAction({ - status: selectionPress?.status ?? "idle", - startedWithSelection: selectionPress?.startedWithSelection, - didScroll, - didNavigate, - movedBeyondTapTolerance, - pressDurationMs: selectionPress ? Date.now() - selectionPress.startedAt : 0, - longPressMs: TERMINAL_GESTURE_LONG_PRESS_MS, - scrollMode: terminalScreenRef.current?.scroll.mode ?? "following", - }); - if (releaseAction === "select" && selectionPress) { - beginSelectionAtPoint({ x: selectionPress.startX, y: selectionPress.startY }); - return; - } - if (releaseAction === "focus" || releaseAction === "clear") { - focusTerminalFromTap(); - } - }, - onPanResponderTerminate: () => { - clearSelectionLongPressTimeout(); - selectionPressRef.current = null; - panStateRef.current = { - lastDy: 0, - rowRemainder: 0, - didScroll: false, - didNavigate: false, - movedBeyondTapTolerance: false, - intent: null, - }; + const point = { x: event.nativeEvent.locationX, y: event.nativeEvent.locationY }; + gestureStartRef.current = point; + selectionController.press(point); }, + onPanResponderMove: (_event, gesture) => + selectionController.move({ + x: gestureStartRef.current.x + gesture.dx, + y: gestureStartRef.current.y + gesture.dy, + }), + onPanResponderRelease: () => selectionController.release(), + onPanResponderTerminate: () => selectionController.cancel(), }), - [ - beginSelectionAtPoint, - clearSelectionLongPressTimeout, - focusTerminalFromTap, - handlePanResponderScroll, - updateSelectionAtPoint, - ], + [selectionController], ); const backgroundColor = xtermTheme.background ?? "#0b0b0b"; @@ -911,6 +696,11 @@ function NativeTerminalEmulator({ const terminalState = terminalScreen?.viewport ?? null; const isScrolled = terminalScreen?.scroll.mode === "scrolled"; + const viewport = resolveSelectionViewport(); + const handles = + viewport && cellMetrics + ? terminalSelectionHandles({ range: selectionRange, viewport, metrics: cellMetrics }) + : []; const terminalGrid = terminalState ? ( {terminalGrid} + + {handles.map((handle) => ( + + + + + + + ))} + { + it("preserves the grab offset while moving a handle", () => { + const range = { start: { row: 1, col: 2 }, end: { row: 1, col: 5 }, coordinateEpoch: 0 }; + const moves: Array<{ row: number; col: number }> = []; + const controller = createTerminalSelectionController({ + getGeometry: () => ({ + range, + viewport: { firstRow: 0, rows: 10, cols: 10 }, + metrics: { cellWidth: 10, cellHeight: 10 }, + }), + onBeginHandle: () => {}, + onMoveHandle: (coordinate) => moves.push(coordinate), + onLongPress: () => {}, + onTap: () => {}, + onScroll: () => {}, + schedule: () => 1, + cancel: () => {}, + }); + controller.press({ x: 23, y: 15 }); + controller.move({ x: 63, y: 15 }); + controller.release(); + expect(moves).toEqual([{ row: 1, col: 5 }]); + }); +}); + +it("selects on hold, preserves a handle tap, and cancels an active drag", () => { + const actions: string[] = []; + let timer: (() => void) | null = null; + const controller = createTerminalSelectionController({ + getGeometry: () => ({ + range: { start: { row: 2, col: 2 }, end: { row: 2, col: 5 }, coordinateEpoch: 0 }, + viewport: { firstRow: 0, rows: 10, cols: 10 }, + metrics: { cellWidth: 10, cellHeight: 10 }, + }), + onBeginHandle: (endpoint) => actions.push(endpoint), + onMoveHandle: () => actions.push("move"), + onLongPress: () => actions.push("long"), + onTap: () => actions.push("tap"), + onScroll: () => actions.push("scroll"), + schedule: (callback) => { + timer = callback; + return 1; + }, + cancel: () => { + timer = null; + }, + }); + controller.press({ x: 90, y: 80 }); + (timer as (() => void) | null)?.(); + controller.release(); + controller.press({ x: 20, y: 25 }); + controller.release(); + controller.press({ x: 20, y: 25 }); + controller.cancel(); + controller.move({ x: 50, y: 25 }); + expect(actions).toEqual(["long", "start", "start"]); +}); + +it("scrolls selection into history while holding a handle at the edge", () => { + let firstRow = 10; + let timer: (() => void) | null = null; + const coordinates: Array<{ row: number; col: number }> = []; + const controller = createTerminalSelectionController({ + getGeometry: () => ({ + range: { start: { row: 12, col: 2 }, end: { row: 13, col: 5 }, coordinateEpoch: 0 }, + viewport: { firstRow, rows: 10, cols: 10 }, + metrics: { cellWidth: 10, cellHeight: 10 }, + }), + onBeginHandle: () => {}, + onMoveHandle: (point) => coordinates.push(point), + onLongPress: () => {}, + onTap: () => {}, + onScroll: (direction) => { + if (direction === "up") firstRow--; + }, + schedule: (callback) => { + timer = callback; + return 1; + }, + cancel: () => { + timer = null; + }, + }); + controller.press({ x: 20, y: 25 }); + controller.move({ x: 20, y: 1 }); + (timer as (() => void) | null)?.(); + (timer as (() => void) | null)?.(); + controller.release(); + expect(coordinates).toEqual([ + { row: 10, col: 2 }, + { row: 9, col: 2 }, + { row: 8, col: 2 }, + ]); + expect(timer).toBeNull(); +}); + +it("scrolls outside handles without clearing selection and clears on an outside tap", () => { + const actions: string[] = []; + const controller = createTerminalSelectionController({ + getGeometry: () => ({ + range: { start: { row: 2, col: 2 }, end: { row: 2, col: 5 }, coordinateEpoch: 0 }, + viewport: { firstRow: 0, rows: 10, cols: 10 }, + metrics: { cellWidth: 10, cellHeight: 10 }, + }), + onBeginHandle: () => actions.push("handle"), + onMoveHandle: () => actions.push("move"), + onLongPress: () => actions.push("long"), + onTap: () => actions.push("tap"), + onScroll: (direction, rows) => actions.push(`${direction}:${rows}`), + schedule: () => 1, + cancel: () => {}, + }); + controller.press({ x: 95, y: 70 }); + controller.move({ x: 95, y: 90 }); + controller.release(); + controller.press({ x: 95, y: 70 }); + controller.release(); + expect(actions).toEqual(["up:2", "tap"]); +}); + +it("extends the selection after a long press and drag", () => { + let timer: (() => void) | null = null; + const moves: Array<{ row: number; col: number }> = []; + const controller = createTerminalSelectionController({ + getGeometry: () => ({ + range: null, + viewport: { firstRow: 0, rows: 10, cols: 10 }, + metrics: { cellWidth: 10, cellHeight: 10 }, + }), + onBeginHandle: () => {}, + onMoveHandle: (coordinate) => moves.push(coordinate), + onLongPress: () => {}, + onTap: () => {}, + onScroll: () => {}, + schedule: (callback) => { + timer = callback; + return 1; + }, + cancel: () => { + timer = null; + }, + }); + controller.press({ x: 25, y: 25 }); + (timer as (() => void) | null)?.(); + controller.move({ x: 65, y: 35 }); + controller.release(); + expect(moves).toEqual([{ row: 3, col: 6 }]); +}); + +it.each([ + { + endpoint: "start" as const, + startX: 20, + crossedX: 80, + crossedText: "gh", + crossedStart: 6, + crossedEnd: 7, + backX: 10, + backText: "bcdef", + backStart: 1, + backEnd: 5, + }, + { + endpoint: "end" as const, + startX: 60, + crossedX: 10, + crossedText: "b", + crossedStart: 1, + crossedEnd: 1, + backX: 80, + backText: "cdefgh", + backStart: 2, + backEnd: 7, + }, +])("tracks the $endpoint handle through crossing and back", async (scenario) => { + const terminal = createNativeHeadlessTerminal({ rows: 4, cols: 10 }); + try { + await terminal.write("abcdefghij"); + const bounds = terminal.getBufferBounds(); + const model = createTerminalSelectionModel(); + model.begin({ coordinate: { row: 0, col: 2 }, bounds }); + model.update({ coordinate: { row: 0, col: 5 }, bounds }); + const viewport = { firstRow: 0, rows: 4, cols: 10 }; + const metrics = { cellWidth: 10, cellHeight: 10 }; + const geometry = () => ({ range: model.getSnapshot().range, viewport, metrics }); + const controller = createTerminalSelectionController({ + getGeometry: geometry, + onBeginHandle: (endpoint, cols) => model.beginEndpointDrag(endpoint, cols), + onMoveHandle: (coordinate) => { + model.update({ coordinate, bounds }); + }, + onLongPress: () => {}, + onTap: () => {}, + onScroll: () => {}, + schedule: () => 1, + cancel: () => {}, + }); + const check = (start: number, end: number, text: string) => { + const range = model.getSnapshot().range; + expect(range).toEqual({ + start: { row: 0, col: start }, + end: { row: 0, col: end }, + coordinateEpoch: bounds.coordinateEpoch, + }); + expect(terminalSelectionHandles(geometry())).toMatchObject([ + { endpoint: "start", x: start * 10, y: 5 }, + { endpoint: "end", x: (end + 1) * 10, y: 5 }, + ]); + expect(resolveTerminalSelectionRects({ selection: range, viewport, metrics })).toEqual([ + { + key: `0:${start}:${end}`, + x: start * 10, + y: 0, + width: (end - start + 1) * 10, + height: 10, + }, + ]); + expect(extractTerminalSelectedText({ terminal, selection: range })).toBe(text); + }; + controller.press({ x: scenario.startX, y: 5 }); + controller.move({ x: scenario.crossedX, y: 5 }); + check(scenario.crossedStart, scenario.crossedEnd, scenario.crossedText); + controller.move({ x: scenario.backX, y: 5 }); + check(scenario.backStart, scenario.backEnd, scenario.backText); + controller.release(); + } finally { + terminal.dispose(); + } +}); + +it.each([ + { + endpoint: "end" as const, + initialRow: 0, + targetRow: 1, + targetX: 0, + expectedRow: 0, + expectedCol: 9, + text: "cdefghij", + }, + { + endpoint: "start" as const, + initialRow: 1, + targetRow: 0, + targetX: 100, + expectedRow: 1, + expectedCol: 0, + text: "KLMNOP", + }, +])("preserves a $endpoint boundary at a row edge", async (scenario) => { + const terminal = createNativeHeadlessTerminal({ rows: 4, cols: 10 }); + try { + await terminal.write("abcdefghij\r\nKLMNOPQRST"); + const bounds = terminal.getBufferBounds(); + const model = createTerminalSelectionModel(); + model.begin({ coordinate: { row: scenario.initialRow, col: 2 }, bounds }); + model.update({ coordinate: { row: scenario.initialRow, col: 5 }, bounds }); + const viewport = { firstRow: 0, rows: 4, cols: 10 }; + const metrics = { cellWidth: 10, cellHeight: 10 }; + const geometry = () => ({ range: model.getSnapshot().range, viewport, metrics }); + const controller = createTerminalSelectionController({ + getGeometry: geometry, + onBeginHandle: (endpoint, cols) => model.beginEndpointDrag(endpoint, cols), + onMoveHandle: (coordinate) => { + model.update({ coordinate, bounds }); + }, + onLongPress: () => {}, + onTap: () => {}, + onScroll: () => {}, + schedule: () => 1, + cancel: () => {}, + }); + controller.press({ x: scenario.endpoint === "end" ? 60 : 20, y: scenario.initialRow * 10 + 5 }); + controller.move({ x: scenario.targetX, y: scenario.targetRow * 10 + 5 }); + const range = model.getSnapshot().range; + expect(range?.[scenario.endpoint]).toEqual({ + row: scenario.expectedRow, + col: scenario.expectedCol, + }); + expect(extractTerminalSelectedText({ terminal, selection: range })).toBe(scenario.text); + expect( + terminalSelectionHandles(geometry()).find((handle) => handle.endpoint === scenario.endpoint), + ).toMatchObject({ + x: scenario.endpoint === "end" ? 100 : 0, + y: scenario.expectedRow * 10 + 5, + }); + controller.release(); + } finally { + terminal.dispose(); + } +}); + +it("cancels a drag when buffer coordinates are invalidated", () => { + const model = createTerminalSelectionModel(); + const bounds = { oldestRow: 0, newestRow: 9, coordinateEpoch: 0 }; + model.begin({ coordinate: { row: 2, col: 2 }, bounds }); + model.update({ coordinate: { row: 2, col: 5 }, bounds }); + const viewport = { firstRow: 0, rows: 10, cols: 10 }; + const metrics = { cellWidth: 10, cellHeight: 10 }; + const controller = createTerminalSelectionController({ + getGeometry: () => ({ range: model.getSnapshot().range, viewport, metrics }), + onBeginHandle: (endpoint, cols) => model.beginEndpointDrag(endpoint, cols), + onMoveHandle: (coordinate) => { + model.update({ coordinate, bounds }); + }, + onLongPress: () => {}, + onTap: () => {}, + onScroll: () => {}, + schedule: () => 1, + cancel: () => {}, + }); + controller.press({ x: 20, y: 25 }); + const previous = model.getSnapshot().range; + const snapshot = model.sync({ bounds: { ...bounds, coordinateEpoch: 1 } }); + if (previous && !snapshot.range) controller.cancel(); + controller.move({ x: 80, y: 25 }); + controller.release(); + expect(model.getSnapshot().range).toBeNull(); +}); + +it("preserves a newly selected word through small movement at the viewport edge", () => { + const model = createTerminalSelectionModel(); + const bounds = { oldestRow: 0, newestRow: 9, coordinateEpoch: 0 }; + let timer: (() => void) | null = null; + const controller = createTerminalSelectionController({ + getGeometry: () => ({ + range: model.getSnapshot().range, + viewport: { firstRow: 0, rows: 10, cols: 20 }, + metrics: { cellWidth: 10, cellHeight: 10 }, + }), + onBeginHandle: (endpoint, cols) => model.beginEndpointDrag(endpoint, cols), + onMoveHandle: (coordinate) => { + model.update({ coordinate, bounds }); + }, + onLongPress: () => { + model.begin({ coordinate: { row: 0, col: 2 }, bounds }); + model.update({ coordinate: { row: 0, col: 6 }, bounds }); + }, + onTap: () => {}, + onScroll: () => {}, + schedule: (callback) => { + timer = callback; + return 1; + }, + cancel: () => { + timer = null; + }, + }); + controller.press({ x: 45, y: 5 }); + const fire = timer as (() => void) | null; + timer = null; + fire?.(); + controller.move({ x: 44, y: 4 }); + controller.release(); + expect(model.getSnapshot().range).toEqual({ + start: { row: 0, col: 2 }, + end: { row: 0, col: 6 }, + coordinateEpoch: 0, + }); + expect(timer).toBeNull(); +}); + +it("places mirrored teardrop grips below the selected row", () => { + const handles = terminalSelectionHandles({ + range: { start: { row: 2, col: 2 }, end: { row: 2, col: 5 }, coordinateEpoch: 0 }, + viewport: { firstRow: 0, rows: 10, cols: 10 }, + metrics: { cellWidth: 10, cellHeight: 10 }, + }); + expect(handles).toMatchObject([ + { endpoint: "start", x: 20, y: 25, gripX: 11, gripY: 39, gripDirection: "left" }, + { endpoint: "end", x: 60, y: 25, gripX: 69, gripY: 39, gripDirection: "right" }, + ]); +}); + +it("keeps edge grips reachable and preserves the offset from the cell when dragging a grip", () => { + const range = { start: { row: 0, col: 0 }, end: { row: 9, col: 9 }, coordinateEpoch: 0 }; + const viewport = { firstRow: 0, rows: 10, cols: 10 }; + const metrics = { cellWidth: 10, cellHeight: 10 }; + const handles = terminalSelectionHandles({ range, viewport, metrics }); + expect(handles.map(({ gripX, gripY }) => ({ gripX, gripY }))).toEqual([ + { gripX: 9, gripY: 19 }, + { gripX: 91, gripY: 81 }, + ]); + const moves: Array<{ row: number; col: number }> = []; + const controller = createTerminalSelectionController({ + getGeometry: () => ({ range, viewport, metrics }), + onBeginHandle: () => {}, + onMoveHandle: (coordinate) => moves.push(coordinate), + onLongPress: () => {}, + onTap: () => {}, + onScroll: () => {}, + schedule: () => 1, + cancel: () => {}, + }); + controller.press({ x: 9, y: 19 }); + controller.move({ x: 19, y: 29 }); + controller.release(); + expect(moves).toEqual([{ row: 1, col: 1 }]); +}); diff --git a/packages/app/src/terminal/native-renderer/terminal-selection-controller.ts b/packages/app/src/terminal/native-renderer/terminal-selection-controller.ts new file mode 100644 index 0000000000..721fd501d7 --- /dev/null +++ b/packages/app/src/terminal/native-renderer/terminal-selection-controller.ts @@ -0,0 +1,208 @@ +import type { TerminalGridCellMetrics } from "./terminal-grid-metrics"; +import type { + TerminalBufferCoordinate, + TerminalSelectionPoint, + TerminalSelectionRange, + TerminalSelectionViewport, +} from "./terminal-selection"; +export const TERMINAL_SELECTION_GRIP_SIZE = 18; +const TERMINAL_GESTURE_LONG_PRESS_MS = 450; +const TERMINAL_GESTURE_TAP_TOLERANCE_PX = 8; + +type Endpoint = "start" | "end"; +interface Geometry { + range: TerminalSelectionRange | null; + viewport: TerminalSelectionViewport; + metrics: TerminalGridCellMetrics; +} +interface Ports { + getGeometry(): Geometry | null; + onBeginHandle(endpoint: Endpoint, cols: number): void; + onMoveHandle(coordinate: TerminalBufferCoordinate): void; + onLongPress(point: TerminalSelectionPoint): void; + onTap(): void; + onScroll(direction: "up" | "down", rows: number): void; + schedule(callback: () => void, delay: number): number; + cancel(timer: number): void; +} + +export function terminalSelectionHandles(geometry: Geometry): Array<{ + endpoint: Endpoint; + x: number; + y: number; + gripX: number; + gripY: number; + gripDirection: "left" | "right"; + gripAbove: boolean; + stemTop: number; + stemHeight: number; +}> { + const { range, viewport, metrics } = geometry; + if (!range) return []; + return (["start", "end"] as const).flatMap((endpoint) => { + const cell = range[endpoint]; + if (cell.row < viewport.firstRow || cell.row >= viewport.firstRow + viewport.rows) return []; + const x = (cell.col + (endpoint === "end" ? 1 : 0)) * metrics.cellWidth; + const stemTop = (cell.row - viewport.firstRow) * metrics.cellHeight; + const size = TERMINAL_SELECTION_GRIP_SIZE; + const width = viewport.cols * metrics.cellWidth; + const height = viewport.rows * metrics.cellHeight; + const wantsLeft = endpoint === "start"; + const gripDirection = + (wantsLeft && x >= size) || (!wantsLeft && x > width - size) ? "left" : "right"; + const gripAbove = stemTop + metrics.cellHeight + size > height; + const gripTop = gripAbove ? Math.max(0, stemTop - size) : stemTop + metrics.cellHeight; + return [ + { + endpoint, + x, + y: stemTop + metrics.cellHeight / 2, + gripX: x + (gripDirection === "left" ? -size / 2 : size / 2), + gripY: gripTop + size / 2, + gripDirection, + gripAbove, + stemTop, + stemHeight: metrics.cellHeight, + }, + ]; + }); +} + +export function createTerminalSelectionController(ports: Ports) { + let press: { + start: TerminalSelectionPoint; + point: TerminalSelectionPoint; + endpoint: Endpoint | null; + offset: TerminalSelectionPoint; + fixed: TerminalBufferCoordinate | null; + moved: boolean; + long: boolean; + scrolling: boolean; + remainder: number; + } | null = null; + let timer: number | null = null; + function stopTimer() { + if (timer !== null) ports.cancel(timer); + timer = null; + } + function updateHandle() { + const geometry = ports.getGeometry(); + if (!press || (!press.endpoint && !press.long) || !geometry) return; + const { viewport, metrics } = geometry; + const x = press.point.x - press.offset.x; + const y = press.point.y - press.offset.y; + let row = + viewport.firstRow + + Math.max(0, Math.min(viewport.rows - 1, Math.floor(y / metrics.cellHeight))); + let col = Math.floor(x / metrics.cellWidth); + if (press.endpoint && press.fixed) { + const boundary = Math.round(x / metrics.cellWidth); + const isEnd = + row > press.fixed.row || (row === press.fixed.row && boundary > press.fixed.col); + col = boundary - (isEnd ? 1 : 0); + if (col < 0 && isEnd) { + row -= 1; + col = viewport.cols - 1; + } else if (col >= viewport.cols && !isEnd) { + row += 1; + col = 0; + } + } + col = Math.max(0, Math.min(viewport.cols - 1, col)); + ports.onMoveHandle({ row, col }); + } + function edgeTick() { + timer = null; + const geometry = ports.getGeometry(); + if (!press || (!press.endpoint && !press.long) || !geometry) return; + const y = press.point.y - press.offset.y; + const height = geometry.viewport.rows * geometry.metrics.cellHeight; + let direction: "up" | "down" | null = null; + if (y < geometry.metrics.cellHeight) direction = "up"; + else if (y > height - geometry.metrics.cellHeight) direction = "down"; + if (!direction) return; + ports.onScroll(direction, 1); + if (!press) return; + updateHandle(); + if (press) timer = ports.schedule(edgeTick, 100); + } + return { + press(point: TerminalSelectionPoint) { + stopTimer(); + const geometry = ports.getGeometry(); + const handles = geometry ? terminalSelectionHandles(geometry) : []; + const handle = handles + .map((item) => ({ + endpoint: item.endpoint, + x: item.x, + y: item.y, + distance: Math.hypot(point.x - item.gripX, point.y - item.gripY), + })) + .filter((item) => item.distance <= 28) + .sort((a, b) => a.distance - b.distance)[0]; + press = { + start: point, + point, + endpoint: handle?.endpoint ?? null, + offset: handle ? { x: point.x - handle.x, y: point.y - handle.y } : { x: 0, y: 0 }, + fixed: + handle && geometry?.range + ? geometry.range[handle.endpoint === "start" ? "end" : "start"] + : null, + moved: false, + long: false, + scrolling: false, + remainder: 0, + }; + if (handle && geometry) { + ports.onBeginHandle(handle.endpoint, geometry.viewport.cols); + return; + } + timer = ports.schedule(() => { + timer = null; + if (press && !press.moved) { + press.long = true; + ports.onLongPress(press.start); + } + }, TERMINAL_GESTURE_LONG_PRESS_MS); + }, + move(point: TerminalSelectionPoint) { + if (!press) return; + const previous = press.point; + press.point = point; + const dx = point.x - press.start.x, + dy = point.y - press.start.y; + if (Math.hypot(dx, dy) > TERMINAL_GESTURE_TAP_TOLERANCE_PX) { + press.moved = true; + if (!press.endpoint) stopTimer(); + } + if (press.endpoint || press.long) { + if (press.endpoint || press.moved) { + updateHandle(); + stopTimer(); + if (press) timer = ports.schedule(edgeTick, 100); + } + } else if (!press.long) { + if (!press.scrolling && Math.abs(dy) > 12 && Math.abs(dy) > Math.abs(dx)) { + press.scrolling = true; + press.remainder = dy; + } else if (press.scrolling) press.remainder += point.y - previous.y; + const height = ports.getGeometry()?.metrics.cellHeight ?? 0; + if (press.scrolling && height > 0) { + const rows = Math.trunc(press.remainder / height); + press.remainder -= rows * height; + if (rows) ports.onScroll(rows > 0 ? "up" : "down", Math.abs(rows)); + } + } + }, + release() { + stopTimer(); + if (press && !press.endpoint && !press.long && !press.moved) ports.onTap(); + press = null; + }, + cancel() { + stopTimer(); + press = null; + }, + }; +} diff --git a/packages/app/src/terminal/native-renderer/terminal-selection-gesture.test.ts b/packages/app/src/terminal/native-renderer/terminal-selection-gesture.test.ts deleted file mode 100644 index aed6857d5c..0000000000 --- a/packages/app/src/terminal/native-renderer/terminal-selection-gesture.test.ts +++ /dev/null @@ -1,354 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { - TERMINAL_GESTURE_LONG_PRESS_MS, - TERMINAL_GESTURE_TAP_TOLERANCE_PX, - TERMINAL_GESTURE_VERTICAL_SCROLL_THRESHOLD_PX, - advanceTerminalScrollGesture, - classifyTerminalGestureIntent, - resolveTerminalGestureReleaseAction, -} from "./terminal-selection-gesture"; - -describe("native terminal gesture policy", () => { - describe("advanceTerminalScrollGesture", () => { - it("keeps consuming a slow drag after scroll intent arms below one row", () => { - let state = { lastDy: 0, rowRemainder: 0, didScroll: false }; - const rowDeltas: number[] = []; - - for (const currentDy of [13, 15, 18, 22, 28]) { - const update = advanceTerminalScrollGesture({ - state, - currentDy, - cellHeight: 14, - }); - state = update.state; - rowDeltas.push(update.rowDelta); - } - - expect({ rowDeltas, state }).toEqual({ - rowDeltas: [0, 1, 0, 0, 1], - state: { lastDy: 28, rowRemainder: 0, didScroll: true }, - }); - }); - }); - - describe("classifyTerminalGestureIntent", () => { - it("treats a motionless press as a tap", () => { - expect( - classifyTerminalGestureIntent({ - status: "pressing", - dx: 0, - dy: 0, - vx: 0, - vy: 0, - }), - ).toEqual("tap"); - }); - - it("treats a tiny jitter within tap tolerance as a tap", () => { - expect( - classifyTerminalGestureIntent({ - status: "pressing", - dx: TERMINAL_GESTURE_TAP_TOLERANCE_PX - 4, - dy: TERMINAL_GESTURE_TAP_TOLERANCE_PX - 4, - vx: 0, - vy: 0, - }), - ).toEqual("tap"); - }); - - it("leaves horizontal movement available to terminal selection", () => { - expect( - classifyTerminalGestureIntent({ - status: "pressing", - dx: TERMINAL_GESTURE_TAP_TOLERANCE_PX + 20, - dy: 4, - vx: 0, - vy: 0, - }), - ).toEqual("pending"); - }); - - it("does not infer selection from slow horizontal drag dwell", () => { - expect( - classifyTerminalGestureIntent({ - status: "pressing", - dx: TERMINAL_GESTURE_TAP_TOLERANCE_PX + 40, - dy: 3, - vx: 0, - vy: 0, - elapsedMs: TERMINAL_GESTURE_LONG_PRESS_MS + 50, - }), - ).toEqual("pending"); - }); - - it("keeps tiny horizontal jitter inside tap tolerance as a tap", () => { - expect( - classifyTerminalGestureIntent({ - status: "pressing", - dx: TERMINAL_GESTURE_TAP_TOLERANCE_PX - 1, - dy: 1, - vx: 2, - vy: 0, - elapsedMs: 20, - }), - ).toEqual("tap"); - }); - - it("keeps horizontal movement below navigation distance pending", () => { - expect( - classifyTerminalGestureIntent({ - status: "pressing", - dx: TERMINAL_GESTURE_TAP_TOLERANCE_PX + 10, - dy: 2, - vx: 0, - vy: 0, - }), - ).toEqual("pending"); - }); - - it("treats a clearly vertical drag as scroll", () => { - expect( - classifyTerminalGestureIntent({ - status: "pressing", - dx: 4, - dy: TERMINAL_GESTURE_VERTICAL_SCROLL_THRESHOLD_PX + 5, - vx: 0, - vy: 0.2, - }), - ).toEqual("scroll"); - }); - - it("does not navigate on a fast rightward swipe", () => { - expect( - classifyTerminalGestureIntent({ - status: "pressing", - dx: TERMINAL_GESTURE_TAP_TOLERANCE_PX + 40, - dy: 4, - vx: 2, - vy: 0, - }), - ).toEqual("pending"); - }); - - it("does not navigate on a slow rightward swipe", () => { - expect( - classifyTerminalGestureIntent({ - status: "pressing", - dx: TERMINAL_GESTURE_TAP_TOLERANCE_PX + 40, - dy: 4, - vx: 0, - vy: 0, - }), - ).toEqual("pending"); - }); - - it("does not navigate on a fast leftward swipe", () => { - expect( - classifyTerminalGestureIntent({ - status: "pressing", - dx: -(TERMINAL_GESTURE_TAP_TOLERANCE_PX + 40), - dy: -4, - vx: -2, - vy: 0, - }), - ).toEqual("pending"); - }); - - it("does not navigate while movement stays inside tap tolerance", () => { - expect( - classifyTerminalGestureIntent({ - status: "pressing", - dx: TERMINAL_GESTURE_TAP_TOLERANCE_PX - 1, - dy: 2, - vx: 2, - vy: 0, - }), - ).toEqual("tap"); - }); - - it("keeps selection intent once selection is active", () => { - expect( - classifyTerminalGestureIntent({ - status: "selecting", - dx: 100, - dy: 50, - vx: 2, - vy: 1, - }), - ).toEqual("select"); - }); - }); - - describe("resolveTerminalGestureReleaseAction", () => { - it("focuses the terminal after a normal tap", () => { - expect( - resolveTerminalGestureReleaseAction({ - status: "pressing", - didScroll: false, - didNavigate: false, - movedBeyondTapTolerance: false, - pressDurationMs: 80, - longPressMs: TERMINAL_GESTURE_LONG_PRESS_MS, - scrollMode: "following", - }), - ).toEqual("focus"); - }); - - it("focuses the terminal after a normal tap while scrolled", () => { - expect( - resolveTerminalGestureReleaseAction({ - status: "pressing", - didScroll: false, - didNavigate: false, - movedBeyondTapTolerance: false, - pressDurationMs: 80, - longPressMs: TERMINAL_GESTURE_LONG_PRESS_MS, - scrollMode: "scrolled", - }), - ).toEqual("focus"); - }); - - it("starts selection after a long press", () => { - expect( - resolveTerminalGestureReleaseAction({ - status: "pressing", - didScroll: false, - didNavigate: false, - movedBeyondTapTolerance: false, - pressDurationMs: TERMINAL_GESTURE_LONG_PRESS_MS + 50, - longPressMs: TERMINAL_GESTURE_LONG_PRESS_MS, - scrollMode: "following", - }), - ).toEqual("select"); - }); - - it("starts selection after a 500ms hold", () => { - expect( - resolveTerminalGestureReleaseAction({ - status: "pressing", - didScroll: false, - didNavigate: false, - movedBeyondTapTolerance: false, - pressDurationMs: 500, - longPressMs: TERMINAL_GESTURE_LONG_PRESS_MS, - scrollMode: "following", - }), - ).toEqual("select"); - }); - - it("keeps a 400ms press as a tap", () => { - expect( - resolveTerminalGestureReleaseAction({ - status: "pressing", - didScroll: false, - didNavigate: false, - movedBeyondTapTolerance: false, - pressDurationMs: 400, - longPressMs: TERMINAL_GESTURE_LONG_PRESS_MS, - scrollMode: "following", - }), - ).toEqual("focus"); - }); - - it("does nothing after a scroll gesture", () => { - expect( - resolveTerminalGestureReleaseAction({ - status: "pressing", - didScroll: true, - didNavigate: false, - movedBeyondTapTolerance: true, - pressDurationMs: 80, - longPressMs: TERMINAL_GESTURE_LONG_PRESS_MS, - scrollMode: "scrolled", - }), - ).toEqual("none"); - }); - - it("does nothing after a navigation swipe", () => { - expect( - resolveTerminalGestureReleaseAction({ - status: "pressing", - didScroll: false, - didNavigate: true, - movedBeyondTapTolerance: true, - pressDurationMs: 80, - longPressMs: TERMINAL_GESTURE_LONG_PRESS_MS, - scrollMode: "following", - }), - ).toEqual("none"); - }); - - it("does nothing while actively selecting", () => { - expect( - resolveTerminalGestureReleaseAction({ - status: "selecting", - didScroll: false, - didNavigate: false, - movedBeyondTapTolerance: true, - pressDurationMs: 80, - longPressMs: TERMINAL_GESTURE_LONG_PRESS_MS, - scrollMode: "following", - }), - ).toEqual("none"); - }); - - it("clears an existing selection after a short tap", () => { - expect( - resolveTerminalGestureReleaseAction({ - status: "selecting", - startedWithSelection: true, - didScroll: false, - didNavigate: false, - movedBeyondTapTolerance: false, - pressDurationMs: 80, - longPressMs: TERMINAL_GESTURE_LONG_PRESS_MS, - scrollMode: "following", - }), - ).toEqual("clear"); - }); - - it("preserves a word selection created by the current long press", () => { - expect( - resolveTerminalGestureReleaseAction({ - status: "selecting", - startedWithSelection: false, - didScroll: false, - didNavigate: false, - movedBeyondTapTolerance: false, - pressDurationMs: TERMINAL_GESTURE_LONG_PRESS_MS + 50, - longPressMs: TERMINAL_GESTURE_LONG_PRESS_MS, - scrollMode: "following", - }), - ).toEqual("none"); - }); - - it("does not focus after an undecided fast drag", () => { - expect( - resolveTerminalGestureReleaseAction({ - status: "pressing", - didScroll: false, - didNavigate: false, - movedBeyondTapTolerance: true, - pressDurationMs: 80, - longPressMs: TERMINAL_GESTURE_LONG_PRESS_MS, - scrollMode: "following", - }), - ).toEqual("none"); - }); - - it("does nothing from idle", () => { - expect( - resolveTerminalGestureReleaseAction({ - status: "idle", - didScroll: false, - didNavigate: false, - movedBeyondTapTolerance: false, - pressDurationMs: 80, - longPressMs: TERMINAL_GESTURE_LONG_PRESS_MS, - scrollMode: "following", - }), - ).toEqual("none"); - }); - }); -}); diff --git a/packages/app/src/terminal/native-renderer/terminal-selection-gesture.ts b/packages/app/src/terminal/native-renderer/terminal-selection-gesture.ts deleted file mode 100644 index 07b5267e87..0000000000 --- a/packages/app/src/terminal/native-renderer/terminal-selection-gesture.ts +++ /dev/null @@ -1,108 +0,0 @@ -export type TerminalGestureStatus = "idle" | "pressing" | "selecting"; -export type TerminalGestureIntent = "tap" | "pending" | "select" | "scroll"; -export type TerminalGestureScrollMode = "following" | "scrolled"; - -export interface TerminalGestureMoveInput { - status: TerminalGestureStatus; - dx: number; - dy: number; - vx: number; - vy: number; - elapsedMs?: number; -} - -export interface TerminalGestureReleaseInput { - status: TerminalGestureStatus; - startedWithSelection?: boolean; - didScroll: boolean; - didNavigate: boolean; - movedBeyondTapTolerance: boolean; - pressDurationMs: number; - longPressMs: number; - scrollMode: TerminalGestureScrollMode; -} - -export interface TerminalScrollGestureState { - lastDy: number; - rowRemainder: number; - didScroll: boolean; -} - -export interface TerminalScrollGestureUpdate { - state: TerminalScrollGestureState; - rowDelta: number; -} - -export type TerminalGestureAction = "none" | "focus" | "select" | "clear"; - -export const TERMINAL_GESTURE_TAP_TOLERANCE_PX = 8; -export const TERMINAL_GESTURE_LONG_PRESS_MS = 450; -export const TERMINAL_GESTURE_VERTICAL_SCROLL_THRESHOLD_PX = 12; - -export function classifyTerminalGestureIntent( - input: TerminalGestureMoveInput, -): TerminalGestureIntent { - if (input.status === "selecting") { - return "select"; - } - - const absDx = Math.abs(input.dx); - const absDy = Math.abs(input.dy); - - if (absDy > TERMINAL_GESTURE_VERTICAL_SCROLL_THRESHOLD_PX && absDy > absDx) { - return "scroll"; - } - - if (Math.hypot(input.dx, input.dy) > TERMINAL_GESTURE_TAP_TOLERANCE_PX) { - return "pending"; - } - - return "tap"; -} - -export function advanceTerminalScrollGesture(input: { - state: TerminalScrollGestureState; - currentDy: number; - cellHeight: number; -}): TerminalScrollGestureUpdate { - const deltaY = input.currentDy - input.state.lastDy; - const accumulatedRows = input.state.rowRemainder + deltaY; - const rowDelta = Math.trunc(accumulatedRows / input.cellHeight); - return { - state: { - lastDy: input.currentDy, - rowRemainder: accumulatedRows - rowDelta * input.cellHeight, - didScroll: input.state.didScroll || rowDelta !== 0, - }, - rowDelta, - }; -} - -export function resolveTerminalGestureReleaseAction( - input: TerminalGestureReleaseInput, -): TerminalGestureAction { - if (input.didScroll || input.didNavigate) { - return "none"; - } - - if (input.status === "selecting") { - if (!input.startedWithSelection) { - return "none"; - } - return input.movedBeyondTapTolerance ? "none" : "clear"; - } - - if (input.status !== "pressing") { - return "none"; - } - - if (input.pressDurationMs >= input.longPressMs) { - return "select"; - } - - if (input.movedBeyondTapTolerance) { - return "none"; - } - - return "focus"; -} diff --git a/packages/app/src/terminal/native-renderer/terminal-selection.test.ts b/packages/app/src/terminal/native-renderer/terminal-selection.test.ts index c188671ffe..6141bf1efd 100644 --- a/packages/app/src/terminal/native-renderer/terminal-selection.test.ts +++ b/packages/app/src/terminal/native-renderer/terminal-selection.test.ts @@ -483,3 +483,51 @@ describe("native terminal selection", () => { expect(copied).toEqual([]); }); }); + +describe("endpoint dragging", () => { + it.each([ + { + endpoint: "start" as const, + fixed: { row: 2, col: 9 }, + target: { row: 3, col: 2 }, + expected: { row: 3, col: 0 }, + }, + { + endpoint: "end" as const, + fixed: { row: 2, col: 0 }, + target: { row: 1, col: 7 }, + expected: { row: 1, col: 9 }, + }, + ])( + "preserves the fixed boundary across a row edge for $endpoint", + ({ endpoint, fixed, target, expected }) => { + const selection = createTerminalSelectionModel(); + const bounds = { oldestRow: 0, newestRow: 10, coordinateEpoch: 1 }; + selection.begin({ coordinate: fixed, bounds }); + selection.update({ coordinate: fixed, bounds }); + selection.beginEndpointDrag(endpoint, 10); + selection.update({ coordinate: target, bounds }); + expect(selection.getSnapshot().range?.[endpoint === "start" ? "start" : "end"]).toEqual( + expected, + ); + }, + ); + + it.each(["start", "end"] as const)( + "keeps the opposite endpoint fixed as %s crosses it", + (endpoint) => { + const selection = createTerminalSelectionModel(); + const bounds = { oldestRow: 0, newestRow: 10, coordinateEpoch: 1 }; + selection.begin({ coordinate: { row: 2, col: 2 }, bounds }); + selection.update({ coordinate: { row: 3, col: 4 }, bounds }); + selection.beginEndpointDrag(endpoint, 10); + const coordinate = endpoint === "start" ? { row: 4, col: 5 } : { row: 1, col: 1 }; + selection.update({ coordinate, bounds }); + expect(selection.getSnapshot().range).toEqual( + endpoint === "start" + ? { start: { row: 3, col: 5 }, end: coordinate, coordinateEpoch: 1 } + : { start: coordinate, end: { row: 2, col: 1 }, coordinateEpoch: 1 }, + ); + }, + ); +}); diff --git a/packages/app/src/terminal/native-renderer/terminal-selection.ts b/packages/app/src/terminal/native-renderer/terminal-selection.ts index 450a3813ac..0f7391e669 100644 --- a/packages/app/src/terminal/native-renderer/terminal-selection.ts +++ b/packages/app/src/terminal/native-renderer/terminal-selection.ts @@ -25,6 +25,7 @@ export interface TerminalSelectionBounds { export interface TerminalSelectionModel { begin(input: TerminalSelectionUpdateInput): TerminalSelectionSnapshot; update(input: TerminalSelectionUpdateInput): TerminalSelectionSnapshot; + beginEndpointDrag(endpoint: "start" | "end", cols: number): void; clear(): TerminalSelectionSnapshot; sync(input: TerminalSelectionSyncInput): TerminalSelectionSnapshot; getSnapshot(): TerminalSelectionSnapshot; @@ -252,6 +253,7 @@ export function resolveTerminalSelectionRects( export function createTerminalSelectionModel(): TerminalSelectionModel { let state: TerminalSelectionState = { anchor: null, range: null }; + let drag: { endpoint: "start" | "end"; cols: number } | null = null; function snapshot(): TerminalSelectionSnapshot { return { range: state.range }; @@ -259,18 +261,31 @@ export function createTerminalSelectionModel(): TerminalSelectionModel { function setSelection(input: TerminalSelectionUpdateInput): TerminalSelectionSnapshot { const coordinate = clampCoordinate(input.coordinate, input.bounds); - const anchor = state.anchor ?? coordinate; + const fixed = state.anchor ?? coordinate; + let anchor = fixed; + if (drag?.endpoint === "start" && compareCoordinates(coordinate, fixed) > 0) { + anchor = + fixed.col + 1 < drag.cols + ? { row: fixed.row, col: fixed.col + 1 } + : { row: fixed.row + 1, col: 0 }; + } else if (drag?.endpoint === "end" && compareCoordinates(coordinate, fixed) < 0) { + anchor = + fixed.col > 0 + ? { row: fixed.row, col: fixed.col - 1 } + : { row: fixed.row - 1, col: drag.cols - 1 }; + } const range = normalizeTerminalSelection({ anchor, focus: coordinate, coordinateEpoch: input.bounds.coordinateEpoch, }); - state = { anchor, range }; + state = { anchor: fixed, range }; return snapshot(); } return { begin(input: TerminalSelectionUpdateInput): TerminalSelectionSnapshot { + drag = null; const coordinate = clampCoordinate(input.coordinate, input.bounds); state = { anchor: coordinate, @@ -285,7 +300,14 @@ export function createTerminalSelectionModel(): TerminalSelectionModel { update(input: TerminalSelectionUpdateInput): TerminalSelectionSnapshot { return setSelection(input); }, + beginEndpointDrag(endpoint, cols) { + if (state.range) { + drag = { endpoint, cols }; + state = { ...state, anchor: state.range[endpoint === "start" ? "end" : "start"] }; + } + }, clear(): TerminalSelectionSnapshot { + drag = null; state = { anchor: null, range: null }; return snapshot(); }, @@ -293,6 +315,7 @@ export function createTerminalSelectionModel(): TerminalSelectionModel { if (!state.range || rangeIsSafe(state.range, input.bounds)) { return snapshot(); } + drag = null; state = { anchor: null, range: null }; return snapshot(); }, From fd65985e9d588109898fcf84298b6ecd1815462a Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sat, 31 Oct 2026 14:45:13 +0700 Subject: [PATCH 141/173] fix(android): resize header fades after rotation (#8349) Clear Android SVG descendant geometry caches when the canvas resizes. Cover growth and shrinkage with a native pixel-rendering regression. --- docs/android.md | 12 +++ patches/react-native-svg+15.15.4.patch | 127 +++++++++++++++++++++++++ scripts/postinstall-patches.mjs | 2 + 3 files changed, 141 insertions(+) diff --git a/docs/android.md b/docs/android.md index 6188589eb8..17bafd6b24 100644 --- a/docs/android.md +++ b/docs/android.md @@ -61,6 +61,18 @@ Gradle auto-fetches the platform/build-tools it needs once licenses are accepted ## Local build + install +The `react-native-svg@15.15.4` patch prevents header fades retaining their old painted size after +rotation. Rebuild native Android after changing it; Metro reloads cannot update this code. Keep the +resize hunks until upstream invalidates descendant geometry on canvas resize. Its instrumentation +regression renders real gradient pixels across growing and shrinking layouts, including a nested +group. From `packages/app/android`, run it on your selected emulator: + +```bash +ANDROID_SERIAL=emulator-5562 ./gradlew :react-native-svg:connectedDebugAndroidTest \ + -Pandroid.testInstrumentationRunnerArguments.class=com.horcrux.svg.SvgResizeTest \ + --no-daemon --max-workers=2 -Dorg.gradle.parallel=false +``` + The locked `expo-modules-core@57.0.23` needs the patch installed by `npm install`. It backports [Expo's Activity-result launcher fix](https://github.com/expo/expo/pull/49634): changing diff --git a/patches/react-native-svg+15.15.4.patch b/patches/react-native-svg+15.15.4.patch index b6b4a85a90..90a30090d7 100644 --- a/patches/react-native-svg+15.15.4.patch +++ b/patches/react-native-svg+15.15.4.patch @@ -59,3 +59,130 @@ index 0c854d6..7dc2828 100644 } return props.transform as TransformsStyle['transform']; } +diff --git a/node_modules/react-native-svg/android/build.gradle b/node_modules/react-native-svg/android/build.gradle +--- a/node_modules/react-native-svg/android/build.gradle ++++ b/node_modules/react-native-svg/android/build.gradle +@@ -103,6 +103,7 @@ + } + + defaultConfig { ++ testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner' + minSdkVersion safeExtGet('minSdkVersion', 16) + //noinspection OldTargetApi + targetSdkVersion safeExtGet('targetSdkVersion', 28) +@@ -136,6 +137,8 @@ + } + + dependencies { ++ androidTestImplementation 'androidx.test:runner:1.6.2' ++ androidTestImplementation 'androidx.test.ext:junit:1.2.1' + implementation 'com.facebook.react:react-native:+' + implementation("com.facebook.fresco:fresco:${FRESCO_VERSION}") { + exclude group: 'com.facebook.soloader' +diff --git a/node_modules/react-native-svg/android/src/main/java/com/horcrux/svg/SvgView.java b/node_modules/react-native-svg/android/src/main/java/com/horcrux/svg/SvgView.java +--- a/node_modules/react-native-svg/android/src/main/java/com/horcrux/svg/SvgView.java ++++ b/node_modules/react-native-svg/android/src/main/java/com/horcrux/svg/SvgView.java +@@ -159,6 +159,8 @@ + @Override + protected void onSizeChanged(int w, int h, int oldw, int oldh) { + super.onSizeChanged(w, h, oldw, oldh); ++ // Percentage lengths and paths depend on the canvas size, not just SVG props. ++ clearChildCache(); + this.invalidate(); + } + +diff --git a/node_modules/react-native-svg/android/src/androidTest/java/com/horcrux/svg/SvgResizeTest.java b/node_modules/react-native-svg/android/src/androidTest/java/com/horcrux/svg/SvgResizeTest.java +new file mode 100644 +--- /dev/null ++++ b/node_modules/react-native-svg/android/src/androidTest/java/com/horcrux/svg/SvgResizeTest.java +@@ -0,0 +1,90 @@ ++package com.horcrux.svg; ++ ++import static org.junit.Assert.assertEquals; ++import static org.junit.Assert.assertTrue; ++ ++import android.graphics.Bitmap; ++import android.graphics.Canvas; ++import android.graphics.Color; ++import android.view.View; ++import androidx.test.ext.junit.runners.AndroidJUnit4; ++import androidx.test.platform.app.InstrumentationRegistry; ++import com.facebook.react.bridge.BridgeReactContext; ++import com.facebook.react.bridge.DynamicFromObject; ++import com.facebook.react.bridge.JavaOnlyArray; ++import com.facebook.react.bridge.JavaOnlyMap; ++import com.facebook.react.soloader.OpenSourceMergedSoMapping; ++import com.facebook.react.uimanager.DisplayMetricsHolder; ++import com.facebook.soloader.SoLoader; ++import org.junit.Test; ++import org.junit.runner.RunWith; ++ ++@RunWith(AndroidJUnit4.class) ++public class SvgResizeTest { ++ @Test ++ public void percentageFadeFollowsCanvasGrowthAndShrinkage() { ++ InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { ++ android.content.Context app = InstrumentationRegistry.getInstrumentation().getTargetContext(); ++ DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(app); ++ try { ++ SoLoader.init(app, OpenSourceMergedSoMapping.INSTANCE); ++ } catch (java.io.IOException exception) { ++ throw new RuntimeException(exception); ++ } ++ BridgeReactContext context = new DrawingContext(app); ++ SvgView svg = new SvgView(context); ++ LinearGradientView gradient = new LinearGradientView(context); ++ gradient.setName("fade"); ++ gradient.setX1(new DynamicFromObject("0%")); ++ gradient.setY1(new DynamicFromObject("0%")); ++ gradient.setX2(new DynamicFromObject("0%")); ++ gradient.setY2(new DynamicFromObject("100%")); ++ gradient.setGradientUnits(0); ++ gradient.setGradient(JavaOnlyArray.of(0.0, Color.RED, 1.0, Color.TRANSPARENT)); ++ svg.addView(gradient); ++ // Exercise recursive invalidation as well as the direct child case. ++ GroupView group = new GroupView(context); ++ RectView rectangle = new RectView(context); ++ rectangle.setX(new DynamicFromObject(0.0)); ++ rectangle.setY(new DynamicFromObject(0.0)); ++ rectangle.setWidth(new DynamicFromObject("100%")); ++ rectangle.setHeight(new DynamicFromObject("100%")); ++ rectangle.setFill(JavaOnlyMap.of("type", 1, "brushRef", "fade")); ++ group.addView(rectangle); ++ svg.addView(group); ++ ++ assertFade(svg, 80, 60); ++ assertFade(svg, 160, 120); ++ assertFade(svg, 60, 40); ++ assertFade(svg, 160, 120); ++ }); ++ } ++ ++ // Pixel rendering needs a React context but does not send layout events to JavaScript. ++ private static final class DrawingContext extends BridgeReactContext ++ implements com.facebook.react.uimanager.events.EventDispatcherProvider { ++ DrawingContext(android.content.Context context) { super(context); } ++ ++ @Override ++ public com.facebook.react.uimanager.events.EventDispatcher getEventDispatcher() { return null; } ++ } ++ ++ private static void assertFade(SvgView svg, int width, int height) { ++ svg.measure(View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY), ++ View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY)); ++ svg.layout(0, 0, width, height); ++ Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); ++ svg.draw(new Canvas(image)); ++ try { ++ int middle = Color.alpha(image.getPixel(width / 2, height / 2)); ++ int right = Color.alpha(image.getPixel(width - 2, height / 2)); ++ assertTrue("Gradient midpoint must follow canvas height at " + width + "x" + height ++ + "; alpha=" + middle, middle >= 120 && middle <= 135); ++ assertEquals("Fade must reach the right edge at " + width + "x" + height, middle, right); ++ assertTrue("Fade must end at the new bottom edge", ++ Color.alpha(image.getPixel(width / 2, height - 2)) < 20); ++ } finally { ++ image.recycle(); ++ } ++ } ++} diff --git a/scripts/postinstall-patches.mjs b/scripts/postinstall-patches.mjs index 312bb90724..fbf87241c7 100644 --- a/scripts/postinstall-patches.mjs +++ b/scripts/postinstall-patches.mjs @@ -59,6 +59,8 @@ const patchedPackages = [ nodeModulesPath: "node_modules/@gorhom/bottom-sheet", patchPrefix: "@gorhom+bottom-sheet+", }, + // Android resize: retain until upstream clears descendant geometry when the SVG canvas resizes. + // The native pixel regression is included in the patch; preserve the separate transform hunks. { nodeModulesPath: "packages/app/node_modules/react-native-svg", patchPrefix: "react-native-svg+", From a7d9bb34fce2633ecb847786d5bc03ce212f741c Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sat, 31 Oct 2026 17:48:42 +0700 Subject: [PATCH 142/173] fix(plugins): keep rewound conversations on their retained branch (#8368) Refresh direct plugin history from authoritative native persistence after conversation/combined rewind, matching the built-in providers' history refresh strategy. Reopen/replay rebuilds translation baselines, rewind tokens and child bindings while preserving outward subscriptions; file-only rewind stays unchanged. Keep replay internal and replace the manager timeline after it completes. Preserve the committed native handle and close routing across refresh failures so retry and reload recover the retained branch. The full native session reload is intentionally inefficient, pending a smarter timeline cut that restores translation state, reused IDs, children and permissions without reopening. Closes #4667 Supersedes #4668 and the rewind-history proposal in #4754. Verified with 72 targeted tests, green CI, and real OMP browser UI A/B/C -> rewind B -> replacement D with native history/timeline equality and a clean browser reload. Co-authored-by: Matt Cowger Co-authored-by: Omer Cohen <639682+omercnet@users.noreply.github.com> --- .../server/src/server/agent/agent-manager.ts | 4 + .../src/server/agent/plugin-provider.test.ts | 568 ++++++++++++++++++ .../src/server/agent/plugin-provider.ts | 193 +++++- public-docs/plugins/providers.md | 5 + 4 files changed, 745 insertions(+), 25 deletions(-) diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index a761e723c1..c69a574849 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -3505,6 +3505,10 @@ export class AgentManager { "agent.rewind.complete", ); } catch (error) { + // Native rewind can commit a fork before history refresh fails. Recovery + // must resume that latest handle rather than the abandoned conversation. + this.refreshSessionPersistence(agent); + await this.persistSnapshot(agent); this.logger.warn( { err: error, agentId, provider: agent.provider, messageId, mode }, "agent.rewind.failed", diff --git a/packages/server/src/server/agent/plugin-provider.test.ts b/packages/server/src/server/agent/plugin-provider.test.ts index 101a19a39f..a9cf3b0ed5 100644 --- a/packages/server/src/server/agent/plugin-provider.test.ts +++ b/packages/server/src/server/agent/plugin-provider.test.ts @@ -53,6 +53,7 @@ const CAPABILITIES = [ interface ProviderHarnessOptions { capabilities?: ProviderConnection["capabilities"]; completeTurn?: boolean; + closeAcknowledgementOnly?: boolean; openChildren?: (rootSessionId: string, emit: (event: ProviderEvent) => void) => void; handleInput?: (input: ProviderInput, emit: (event: ProviderEvent) => void) => Promise; } @@ -208,6 +209,7 @@ function createProviderHarness(options: ProviderHarnessOptions = {}) { } if (input.type === "session.close") { emit({ type: "session.closed", sessionId: input.sessionId }); + if (options.closeAcknowledgementOnly) return; } if ("requestId" in input) { emit({ type: "request.completed", requestId: input.requestId }); @@ -246,6 +248,572 @@ function eventsOfType(events: AgentStreamEvent[], type: AgentStreamEvent["type"] return events.filter((event) => event.type === type); } +function createRewindProviderHarness( + options: { + reuseAnswerId?: boolean; + forkOnRevert?: boolean; + handleInput?: ProviderHarnessOptions["handleInput"]; + } = {}, +) { + const nativeMessages: string[] = []; + let originalMessages: string[] | null = null; + const harness = createProviderHarness({ + closeAcknowledgementOnly: true, + capabilities: [ + ...CAPABILITIES, + "session.revert.conversation", + "session.revert.files", + "session.revert.both", + ], + async handleInput(input, emit) { + if (await options.handleInput?.(input, emit)) return true; + if (input.type === "session.open" && input.history === "replay") { + emit({ + type: "session.opened", + requestId: input.requestId, + sessionId: input.sessionId, + capabilities: [ + ...CAPABILITIES, + "session.revert.conversation", + "session.revert.files", + "session.revert.both", + ], + restoration: "core", + persistence: input.persistence ?? { version: 1, data: { token: "root" } }, + cwd: input.config.cwd, + }); + const messages = + options.forkOnRevert && + (input.persistence?.data as { token?: string })?.token === "root" && + originalMessages + ? originalMessages + : nativeMessages; + for (const [index, text] of messages.entries()) { + emit({ + type: "timeline.item", + sessionId: input.sessionId, + item: { type: "user_message", id: `user-${text}`, text, revertToken: text }, + }); + emit({ + type: "timeline.item", + sessionId: input.sessionId, + item: { + type: "assistant_message", + id: options.reuseAnswerId ? `answer-${index + 1}` : `answer-${text}`, + text: `Reply ${text}`, + }, + }); + } + emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId }); + return true; + } + if (input.type === "session.prompt") { + if (input.prompt.input.type !== "message") throw new Error("Expected a message"); + const text = input.prompt.input.content + .flatMap((part) => (part.type === "text" ? [part.text] : [])) + .join(""); + nativeMessages.push(text); + const turnId = `turn-${text}`; + emit({ + type: "session.prompt_result", + sessionId: input.sessionId, + clientMessageId: input.prompt.clientMessageId, + result: { type: "turn", turnId }, + }); + emit({ type: "session.turn", sessionId: input.sessionId, turnId, state: "started" }); + emit({ + type: "timeline.item", + sessionId: input.sessionId, + item: { + type: "user_message", + id: `user-${text}`, + text, + clientMessageId: input.prompt.clientMessageId, + revertToken: text, + }, + }); + emit({ + type: "timeline.item", + sessionId: input.sessionId, + item: { + type: "assistant_message", + id: options.reuseAnswerId ? `answer-${nativeMessages.length}` : `answer-${text}`, + text: `Reply ${text}`, + }, + }); + emit({ type: "session.turn", sessionId: input.sessionId, turnId, state: "completed" }); + return true; + } + if (input.type === "session.revert") { + if (options.forkOnRevert && input.scope !== "files") { + originalMessages = [...nativeMessages]; + emit({ + type: "session.persistence", + sessionId: input.sessionId, + persistence: { version: 1, data: { token: "fork" } }, + }); + } + if (input.scope !== "files") + nativeMessages.splice(nativeMessages.indexOf(String(input.token))); + emit({ type: "request.completed", requestId: input.requestId }); + return true; + } + return false; + }, + }); + return { ...harness, nativeMessages }; +} + +async function withRewindAgent( + run: (context: { + manager: AgentManager; + agentId: string; + nativeMessages: string[]; + messages: () => string[]; + }) => Promise, + options: Parameters[0] = {}, +) { + const harness = createRewindProviderHarness(options); + const logger = createTestLogger(); + const registry = new PluginAgentClientRegistry(logger); + registry.replace([harness.registration]); + const manager = new AgentManager({ + logger, + clients: registry.clients(), + providerDefinitions: registry.definitions(), + }); + const agent = await manager.createAgent( + { provider: harness.registration.id, cwd: tmpdir() }, + undefined, + { workspaceId: undefined }, + ); + const messages = () => + manager + .getTimeline(agent.id) + .flatMap((item) => + item.type === "user_message" || item.type === "assistant_message" ? [item.text] : [], + ); + try { + await manager.runAgent(agent.id, "A", { clientMessageId: "client-A" }); + await manager.runAgent(agent.id, "B", { clientMessageId: "client-B" }); + await manager.runAgent(agent.id, "C", { clientMessageId: "client-C" }); + expect(messages()).toEqual(["A", "Reply A", "B", "Reply B", "C", "Reply C"]); + await run({ manager, agentId: agent.id, nativeMessages: harness.nativeMessages, messages }); + } finally { + await manager.closeAgent(agent.id); + await registry.shutdown(); + } +} + +test("conversation rewind discards withdrawn plugin turns before and after a replacement prompt", async () => { + await withRewindAgent(async ({ manager, agentId, nativeMessages, messages }) => { + await manager.rewind(agentId, "user-B", "conversation"); + const afterRewind = messages(); + expect(nativeMessages).toEqual(["A"]); + await manager.runAgent(agentId, "D", { clientMessageId: "client-D" }); + const afterReplacement = messages(); + expect(nativeMessages).toEqual(["A", "D"]); + expect({ afterRewind, afterReplacement }).toEqual({ + afterRewind: ["A", "Reply A"], + afterReplacement: ["A", "Reply A", "D", "Reply D"], + }); + }); +}); + +test("file-only plugin rewind preserves the conversation before and after a replacement prompt", async () => { + await withRewindAgent(async ({ manager, agentId, nativeMessages, messages }) => { + await manager.rewind(agentId, "user-B", "files"); + expect(nativeMessages).toEqual(["A", "B", "C"]); + expect(messages()).toEqual(["A", "Reply A", "B", "Reply B", "C", "Reply C"]); + await manager.runAgent(agentId, "D", { clientMessageId: "client-D" }); + expect(messages()).toEqual(["A", "Reply A", "B", "Reply B", "C", "Reply C", "D", "Reply D"]); + }); +}); + +test("plugin rewind restores translation state when a replacement reuses a discarded item id", async () => { + const harness = createRewindProviderHarness({ reuseAnswerId: true }); + const registry = new PluginAgentClientRegistry(createTestLogger()); + registry.replace([harness.registration]); + const client = registry.clients()[harness.registration.id]!; + const session = await client.createSession({ provider: harness.registration.id, cwd: tmpdir() }); + const live: AgentStreamEvent[] = []; + try { + await session.run("A"); + await session.run("B"); + session.subscribe((event) => live.push(event)); + await session.revertConversation!({ messageId: "user-B" }); + live.length = 0; + await session.run("B revised"); + const assistant = live.flatMap((event) => + event.type === "timeline" && event.item.type === "assistant_message" ? [event.item.text] : [], + ); + expect(harness.nativeMessages).toEqual(["A", "B revised"]); + expect(assistant).toEqual(["Reply B revised"]); + } finally { + await session.close(); + await registry.shutdown(); + } +}); + +async function withPluginRewindSession( + options: Parameters[0], + run: ( + session: Awaited>, + harness: ReturnType, + ) => Promise, +) { + const harness = createRewindProviderHarness(options); + const registry = new PluginAgentClientRegistry(createTestLogger()); + registry.replace([harness.registration]); + const client = registry.clients()[harness.registration.id]!; + const session = await client.createSession({ provider: harness.registration.id, cwd: tmpdir() }); + try { + await session.run("A"); + await session.run("B"); + await session.run("C"); + await run(session, harness); + } finally { + await session.close(); + await registry.shutdown(); + } +} + +async function pluginMessages(session: Awaited>) { + const events = await Array.fromAsync(session.streamHistory()); + return events.flatMap((event) => + event.type === "timeline" && + (event.item.type === "user_message" || event.item.type === "assistant_message") + ? [event.item.text] + : [], + ); +} + +test("combined plugin rewind replays the retained native branch", async () => { + await withPluginRewindSession({}, async (session) => { + await session.revertBoth!({ messageId: "user-B" }); + expect(await pluginMessages(session)).toEqual(["A", "Reply A"]); + await session.revertConversation!({ messageId: "user-A" }); + expect(await pluginMessages(session)).toEqual([]); + }); +}); + +test("plugin rewind resumes the latest persistence rather than the original handle", async () => { + await withPluginRewindSession( + { + handleInput: async (input, emit) => { + if (input.type === "session.revert") + emit({ + type: "session.persistence", + sessionId: input.sessionId, + persistence: { version: 1, data: { token: "fork" } }, + }); + return false; + }, + }, + async (session, harness) => { + await session.revertConversation!({ messageId: "user-B" }); + expect(harness.inputs.findLast((input) => input.type === "session.open")).toMatchObject({ + persistence: { version: 1, data: { token: "fork" } }, + history: "replay", + }); + expect(await pluginMessages(session)).toEqual(["A", "Reply A"]); + }, + ); +}); + +test("failed native plugin rewind preserves history and does not reopen", async () => { + await withPluginRewindSession( + { + handleInput: async (input, emit) => { + if (input.type !== "session.revert") return false; + emit({ + type: "request.failed", + requestId: input.requestId, + error: { message: "native rewind failed" }, + }); + return true; + }, + }, + async (session, harness) => { + await expect(session.revertConversation!({ messageId: "user-B" })).rejects.toThrow( + "native rewind failed", + ); + expect(await pluginMessages(session)).toEqual([ + "A", + "Reply A", + "B", + "Reply B", + "C", + "Reply C", + ]); + expect(harness.inputs.filter((input) => input.type === "session.open")).toHaveLength(1); + }, + ); +}); + +test("failed plugin rewind replay blocks prompts until retry without repeating native rewind", async () => { + let failReplay = true; + await withPluginRewindSession( + { + handleInput: async (input, emit) => { + if (input.type !== "session.open" || input.history !== "replay" || !failReplay) + return false; + failReplay = false; + emit({ + type: "request.failed", + requestId: input.requestId, + error: { message: "replay failed" }, + }); + return true; + }, + }, + async (session, harness) => { + await expect(session.revertConversation!({ messageId: "user-B" })).rejects.toThrow( + "replay failed", + ); + await expect(session.run("D")).rejects.toThrow("Retry the rewind or reload"); + await session.revertConversation!({ messageId: "user-B" }); + await session.run("D"); + expect(await pluginMessages(session)).toEqual(["A", "Reply A", "D", "Reply D"]); + expect(harness.inputs.filter((input) => input.type === "session.revert")).toHaveLength(1); + }, + ); +}); + +test("retrying a failed plugin rewind replay replaces the manager timeline before prompting", async () => { + let failReplay = true; + await withRewindAgent( + async ({ manager, agentId, messages }) => { + await expect(manager.rewind(agentId, "user-B", "conversation")).rejects.toThrow( + "replay failed", + ); + await expect(manager.runAgent(agentId, "D")).rejects.toThrow("Retry the rewind or reload"); + await manager.rewind(agentId, "user-B", "conversation"); + expect(messages()).toEqual(["A", "Reply A"]); + await manager.runAgent(agentId, "D"); + expect(messages()).toEqual(["A", "Reply A", "D", "Reply D"]); + }, + { + handleInput: async (input, emit) => { + if (input.type !== "session.open" || input.history !== "replay" || !failReplay) + return false; + failReplay = false; + emit({ + type: "request.failed", + requestId: input.requestId, + error: { message: "replay failed" }, + }); + return true; + }, + }, + ); +}); + +test("reload after failed plugin rewind replay resumes the committed fork", async () => { + let failReplay = true; + await withRewindAgent( + async ({ manager, agentId, messages }) => { + await expect(manager.rewind(agentId, "user-B", "conversation")).rejects.toThrow( + "replay failed", + ); + await manager.reloadAgentSession(agentId, undefined, { rehydrateFromDisk: true }); + await manager.hydrateTimelineFromProvider(agentId, { force: true }); + expect(messages()).toEqual(["A", "Reply A"]); + }, + { + forkOnRevert: true, + handleInput: async (input, emit) => { + if (input.type === "session.close") { + emit({ type: "request.completed", requestId: input.requestId }); + return true; + } + if (input.type !== "session.open" || input.history !== "replay" || !failReplay) + return false; + failReplay = false; + emit({ + type: "request.failed", + requestId: input.requestId, + error: { message: "replay failed" }, + }); + return true; + }, + }, + ); +}); + +test("closing during plugin rewind replay closes each native binding once", async () => { + let opened!: () => void; + let release!: () => void; + const replayStarted = new Promise((resolve) => { + opened = resolve; + }); + const replayAllowed = new Promise((resolve) => { + release = resolve; + }); + await withPluginRewindSession( + { + handleInput: async (input) => { + if (input.type === "session.open" && input.history === "replay") { + opened(); + await replayAllowed; + } + return false; + }, + }, + async (session, harness) => { + const rewind = session.revertConversation!({ messageId: "user-B" }); + await replayStarted; + const closing = session.close(); + release(); + await Promise.all([rewind, closing]); + const closes = harness.inputs.flatMap((input) => + input.type === "session.close" ? [input.sessionId] : [], + ); + expect(closes).toHaveLength(2); + expect(new Set(closes).size).toBe(2); + }, + ); +}); + +test("plugin rewind retries a failed close before reopening the native writer", async () => { + let failClose = true; + await withPluginRewindSession( + { + handleInput: async (input, emit) => { + if (input.type !== "session.close" || !failClose) return false; + failClose = false; + emit({ + type: "request.failed", + requestId: input.requestId, + error: { message: "close failed" }, + }); + return true; + }, + }, + async (session, harness) => { + await expect(session.revertConversation!({ messageId: "user-B" })).rejects.toThrow( + "close failed", + ); + expect(harness.inputs.filter((input) => input.type === "session.open")).toHaveLength(1); + expect(await pluginMessages(session)).toEqual(["A", "Reply A"]); + expect(harness.inputs.filter((input) => input.type === "session.revert")).toHaveLength(1); + }, + ); +}); + +test("plugin rewind retries permission settlement before retiring its session", async () => { + let failPermission = true; + await withPluginRewindSession( + { + handleInput: async (input) => { + if (input.type !== "session.permission" || !failPermission) return false; + failPermission = false; + throw new Error("permission delivery failed"); + }, + }, + async (session, harness) => { + const opened = harness.inputs.find((input) => input.type === "session.open")!; + if (opened.type !== "session.open") throw new Error("Missing root"); + harness.emit({ + type: "session.permission", + sessionId: opened.sessionId, + request: { id: "pending", name: "tool", kind: "tool" }, + }); + await expect(session.revertConversation!({ messageId: "user-B" })).rejects.toThrow( + "permission delivery failed", + ); + expect(session.getPendingPermissions()).toHaveLength(1); + expect(harness.inputs.filter((input) => input.type === "session.close")).toHaveLength(0); + expect(await pluginMessages(session)).toEqual(["A", "Reply A"]); + expect(session.getPendingPermissions()).toEqual([]); + expect(harness.inputs.filter((input) => input.type === "session.permission")).toHaveLength(2); + }, + ); +}); + +test("plugin rewind replaces child listeners and settles old pending permissions", async () => { + await withPluginRewindSession({}, async (session, harness) => { + const root = harness.inputs.find((input) => input.type === "session.open")!; + if (root.type !== "session.open") throw new Error("Missing root"); + harness.emit({ + type: "session.permission", + sessionId: root.sessionId, + request: { id: "old-permission", name: "tool", kind: "tool", title: "Run tool" }, + }); + expect(session.getPendingPermissions()).toHaveLength(1); + await session.revertConversation!({ messageId: "user-B" }); + expect(session.getPendingPermissions()).toEqual([]); + expect(harness.inputs).toContainEqual( + expect.objectContaining({ + type: "session.permission", + permissionId: "old-permission", + response: { behavior: "deny", message: "Session replaced after rewind" }, + }), + ); + harness.emit({ + type: "timeline.item", + sessionId: "child-1", + item: { type: "assistant_message", id: "child-message", text: "Discarded child update" }, + }); + const history = await Array.fromAsync(session.streamHistory()); + expect(history.filter((event) => event.type === "provider_subagent")).toEqual([]); + const reopened = harness.inputs.findLast((input) => input.type === "session.open")!; + if (reopened.type !== "session.open") throw new Error("Missing reopened root"); + harness.emit({ + type: "session.opened", + sessionId: "child-1", + parentSessionId: reopened.sessionId, + capabilities: [], + restoration: "parent", + cwd: tmpdir(), + }); + harness.emit({ + type: "timeline.item", + sessionId: "child-1", + item: { type: "assistant_message", id: "child-message", text: "New child reply" }, + }); + const next = await Array.fromAsync(session.streamHistory()); + expect(next).toContainEqual( + expect.objectContaining({ + type: "provider_subagent", + event: expect.objectContaining({ + type: "timeline", + item: expect.objectContaining({ text: "New child reply" }), + }), + }), + ); + }); +}); + +test("nonpersisted plugin sessions reject conversation rewind before native mutation", async () => { + await withPluginRewindSession( + { + handleInput: async (input, emit) => { + if (input.type !== "session.open") return false; + emit({ + type: "session.opened", + requestId: input.requestId, + sessionId: input.sessionId, + capabilities: [...CAPABILITIES, "session.revert.conversation", "session.revert.files"], + restoration: "core", + cwd: input.config.cwd, + }); + emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId }); + return true; + }, + }, + async (session, harness) => { + expect(session.capabilities.supportsRewindConversation).toBe(false); + await expect(session.revertConversation!({ messageId: "user-B" })).rejects.toThrow( + "requires session persistence", + ); + expect(harness.inputs.filter((input) => input.type === "session.revert")).toEqual([]); + await session.revertFiles!({ messageId: "user-B" }); + expect(harness.nativeMessages).toEqual(["A", "B", "C"]); + }, + ); +}); + function openNestedChildren(rootSessionId: string, emit: (event: ProviderEvent) => void) { for (const [sessionId, parentSessionId] of [ ["a", rootSessionId], diff --git a/packages/server/src/server/agent/plugin-provider.ts b/packages/server/src/server/agent/plugin-provider.ts index f09f6349b0..2d20056930 100644 --- a/packages/server/src/server/agent/plugin-provider.ts +++ b/packages/server/src/server/agent/plugin-provider.ts @@ -603,6 +603,7 @@ class ProviderRuntimeSession { >(); private readonly activeTurnIds = new Set(); private terminal = false; + private closePromise: Promise | null = null; config: ProviderConfigState = { models: [], modes: [], thinkingOptions: [], settings: [] }; commands: Array<{ name: string; description: string; argumentHint?: string }> = []; persistence: ProviderPersistence | null = null; @@ -724,6 +725,14 @@ class ProviderRuntimeSession { this.runtime.removeSession(this.id, this.providerSessionId); return; } + this.closePromise ??= this.closeNativeSession().catch((error) => { + this.closePromise = null; + throw error; + }); + await this.closePromise; + } + + private async closeNativeSession(): Promise { try { await this.runtime.complete({ type: "session.close", @@ -732,9 +741,9 @@ class ProviderRuntimeSession { }); } catch (error) { if (!this.runtime.isClosed) throw error; - } finally { - this.runtime.removeSession(this.id, this.providerSessionId); } + // A failed close still needs its routing for a subsequent session.closed ack. + this.runtime.removeSession(this.id, this.providerSessionId); } beginOpen(requestId: string): Promise { @@ -1092,11 +1101,40 @@ class PluginAgentClient implements AgentClient { persistence: input.persistence, history: input.history, }); - const session = new PluginAgentSession(this.provider, bridge, () => { - this.rootsBySession.delete(bridge.id); - }); - this.rootsBySession.set(bridge.id, session); - this.attachPendingChildren(); + const forget = () => { + for (const [id, owner] of this.rootsBySession) { + if (owner === session) this.rootsBySession.delete(id); + } + }; + const bind = (next: ProviderRuntimeSession) => { + this.rootsBySession.set(next.id, session); + this.attachPendingChildren(); + }; + const config = mapSessionConfig(input.config, input.launchContext, input.persist); + const session = new PluginAgentSession( + this.provider, + bridge, + forget, + async (persistence, state) => { + forget(); + return await this.runtime.openSession({ + sessionId: randomUUID(), + config: { + ...config, + model: state.model, + mode: state.mode, + thinkingOption: state.thinkingOption, + settings: Object.fromEntries( + state.settings.map((setting) => [setting.id, setting.value]), + ), + }, + persistence, + history: "replay", + }); + }, + bind, + ); + bind(bridge); return session; } @@ -1157,16 +1195,32 @@ class PluginAgentSession implements AgentSession { private readonly revertTokens = new Map(); private readonly timelineSnapshots = new Map(); private readonly subagentIdsBySession = new Map(); - private readonly childUnsubscribes = new Map void>(); + private readonly children = new Map< + string, + { session: ProviderRuntimeSession; unsubscribe: () => void } + >(); private readonly childSnapshots = new Map>(); private unsubscribe: (() => void) | null = null; private currentTurnId: string | null = null; private closed = false; + private replay: { + persistence: ProviderPersistence; + config: ProviderConfigState; + messageId: string; + scope: "conversation" | "both"; + closed: boolean; + } | null = null; + private replaying: Promise | null = null; constructor( readonly provider: string, - private readonly bridge: ProviderRuntimeSession, + private bridge: ProviderRuntimeSession, private readonly onClose: () => void, + private readonly reopen: ( + persistence: ProviderPersistence, + state: ProviderConfigState, + ) => Promise, + private readonly onBind: (bridge: ProviderRuntimeSession) => void, ) { this.subagentIdsBySession.set(bridge.id, null); for (const event of bridge.history) this.accept(event, false); @@ -1183,7 +1237,13 @@ class PluginAgentSession implements AgentSession { } get capabilities(): AgentCapabilityFlags { - return agentCapabilities(this.bridge.negotiatedCapabilities); + const capabilities = agentCapabilities(this.bridge.negotiatedCapabilities); + const resumable = this.canReplayHistory; + return { + ...capabilities, + supportsRewindConversation: capabilities.supportsRewindConversation && resumable, + supportsRewindBoth: capabilities.supportsRewindBoth && resumable, + }; } get features(): AgentFeature[] { @@ -1211,6 +1271,7 @@ class PluginAgentSession implements AgentSession { prompt: AgentPromptInput, options: AgentRunOptions = {}, ): Promise<{ turnId: string }> { + this.assertReplayComplete(); const clientMessageId = options.clientMessageId ?? randomUUID(); const result = await this.bridge.prompt({ clientMessageId, @@ -1233,6 +1294,7 @@ class PluginAgentSession implements AgentSession { prompt: AgentPromptInput, options: SteerActiveTurnOptions, ): Promise { + this.assertReplayComplete(); if (!this.bridge.negotiatedCapabilities.includes("prompt.steer")) { return { status: "unavailable" }; } @@ -1256,6 +1318,7 @@ class PluginAgentSession implements AgentSession { } async *streamHistory(): AsyncGenerator { + await this.ensureReplay(); for (const event of this.history.read(this.provider)) yield event; } @@ -1283,6 +1346,7 @@ class PluginAgentSession implements AgentSession { } async setMode(modeId: string): Promise { + this.assertReplayComplete(); await this.bridge.configure({ mode: modeId }); } @@ -1319,17 +1383,10 @@ class PluginAgentSession implements AgentSession { async close(): Promise { if (this.closed) return; this.closed = true; - this.unsubscribe?.(); - this.unsubscribe = null; - for (const unsubscribe of this.childUnsubscribes.values()) unsubscribe(); - this.childUnsubscribes.clear(); - this.subagentIdsBySession.clear(); - this.history.clear(); - this.timelineSnapshots.clear(); - this.childSnapshots.clear(); - this.revertTokens.clear(); - this.pendingPermissions.clear(); - this.permissionResponses.clear(); + this.listeners.clear(); + await this.replaying?.catch(() => undefined); + await this.clearBinding(); + this.replay = null; this.listeners.clear(); this.onClose(); await this.bridge.close(); @@ -1344,14 +1401,17 @@ class PluginAgentSession implements AgentSession { } async setModel(modelId: string | null): Promise { + this.assertReplayComplete(); await this.bridge.configure({ model: modelId }); } async setThinkingOption(thinkingOptionId: string | null): Promise { + this.assertReplayComplete(); await this.bridge.configure({ thinkingOption: thinkingOptionId }); } async setFeature(featureId: string, value: unknown): Promise { + this.assertReplayComplete(); await this.bridge.configure({ settings: { [featureId]: toJsonValue(value, `setting '${featureId}'`) }, }); @@ -1415,10 +1475,10 @@ class PluginAgentSession implements AgentSession { const snapshots = new Map(); this.childSnapshots.set(childId, snapshots); for (const event of child.history) this.acceptChildEvent(childId, event, snapshots); - this.childUnsubscribes.set( - child.id, - child.onEvent((event) => this.acceptChildEvent(childId, event, snapshots)), - ); + this.children.set(child.id, { + session: child, + unsubscribe: child.onEvent((event) => this.acceptChildEvent(childId, event, snapshots)), + }); } private accept(event: ProviderEvent, live: boolean): void { @@ -1636,7 +1696,84 @@ class PluginAgentSession implements AgentSession { } } + private async clearBinding(): Promise { + this.unsubscribe?.(); + this.unsubscribe = null; + for (const child of this.children.values()) { + child.unsubscribe(); + await child.session.close(); + } + this.children.clear(); + this.subagentIdsBySession.clear(); + this.history.clear(); + this.timelineSnapshots.clear(); + this.childSnapshots.clear(); + this.revertTokens.clear(); + this.pendingPermissions.clear(); + this.permissionResponses.clear(); + this.currentTurnId = null; + } + + private assertReplayComplete(): void { + if (this.replay) { + throw new Error( + "Plugin rewind history refresh is incomplete. Retry the rewind or reload the agent before continuing.", + ); + } + } + + // A native rewind has already committed. Until replay succeeds, neither history + // nor a new prompt may use the retired binding. Keep its latest handle for retry. + private async ensureReplay(): Promise { + if (!this.replay) return; + if (this.closed) throw new StaleProviderSessionError(this.id); + if (!this.replaying) { + this.replaying = this.replayBinding().finally(() => { + this.replaying = null; + }); + } + await this.replaying; + } + + private async replayBinding(): Promise { + const replay = this.replay!; + if (!replay.closed) { + for (const request of this.pendingPermissions.values()) { + await this.respondToPermission(request.id, { + behavior: "deny", + message: "Session replaced after rewind", + }); + this.pendingPermissions.delete(request.id); + this.permissionResponses.delete(request.id); + } + await this.clearBinding(); + await this.bridge.close(); + replay.closed = true; + } + const bridge = await this.reopen(replay.persistence, replay.config); + this.bridge = bridge; + this.subagentIdsBySession.set(bridge.id, null); + for (const event of bridge.history) this.accept(event, false); + this.unsubscribe = bridge.onEvent((event) => this.accept(event, true)); + this.onBind(bridge); + this.replay = null; + } + + private get canReplayHistory(): boolean { + return ( + this.bridge.restoration === "core" && + this.bridge.persistence !== null && + this.bridge.negotiatedCapabilities.includes("session.persistence") + ); + } + private async revert(messageId: string, scope: "conversation" | "files" | "both") { + const pending = this.replay; + await this.ensureReplay(); + if (pending?.messageId === messageId && pending.scope === scope) return; + if (scope !== "files" && !this.canReplayHistory) { + throw new Error("Plugin conversation rewind requires session persistence for history replay"); + } const token = this.revertTokens.get(messageId); if (token === undefined) throw new Error(`No provider revert token for message ${messageId}`); await this.bridge.revert({ @@ -1646,6 +1783,12 @@ class PluginAgentSession implements AgentSession { token, scope, }); + if (scope !== "files") { + const persistence = this.bridge.persistence; + if (!persistence) throw new Error("Plugin rewind removed session persistence"); + this.replay = { persistence, config: this.bridge.config, messageId, scope, closed: false }; + await this.ensureReplay(); + } } private publish(event: AgentStreamEvent): void { diff --git a/public-docs/plugins/providers.md b/public-docs/plugins/providers.md index 6fbe766c61..9a87dfb155 100644 --- a/public-docs/plugins/providers.md +++ b/public-docs/plugins/providers.md @@ -287,6 +287,11 @@ Paseo refreshes an agent by closing its current provider session and opening it configuration and persistence. Re-read credentials, environment, global configuration, and MCP servers during `session.open`. There is no separate reload operation. +Conversation and combined rewind require a core-restored session with persistence. After a +successful rewind, Paseo closes the session and reopens its latest persistence value with +`history: "replay"`. Publish the retained native branch before `session.ready`, including its +children. File-only rewind keeps the current session and conversation history. + Use `restoration: "core"` when Paseo can reopen a session from persistence. A provider-owned child uses `restoration: "parent"`; emit it as another `session.opened` event with `parentSessionId` and recreate it while restoring the parent. From 0e5bcbd9f50dfca46a8b5835c4b09f158762003d Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sat, 31 Oct 2026 11:05:06 +0000 Subject: [PATCH 143/173] fix(app): open relative chat links inside nested repositories (#8361) * fix(app): open a nested-repo file when the workspace-root path is missing A workspace that contains another git repo often gets paths written relative to that nested repo. `schema/x.md` is really `repo-a/schema/x.md`. A markdown link was joined onto the workspace root and opened a missing file. Inline code already asked the daemon for a suffix match. Resolved workspace-relative paths that contain a slash now use that same lookup before opening. An exact hit stays on the original path. A suffix hit replaces it and keeps the line range. A failed lookup still opens the original path. Bare names, absolute paths, and `~/` paths are unchanged. Example: - Input: workspace `/repo`, link `schema/x.md`, file at `repo-a/schema/x.md` - Before: open `/repo/schema/x.md` (missing) - After: open `/repo/repo-a/schema/x.md` * fix(app): preserve explicit destinations when finding nested files Relative chat links can name a file inside a nested repository. Retain the suffix lookup while using the original href and document base to preserve absolute paths, preview links, and folder destinations. Co-authored-by: Ouyang Xingyuan * fix(app): keep network share links on their absolute destination Use the shared absolute-path classifier so network share hrefs retain their destination alongside drive and POSIX paths. * fix(app): keep nested-file lookup inside ordered path opening Resolve the original directory before considering suffix matches, and allocate click ordering before asynchronous lookup. The existing opener now owns the complete operation so a slow earlier click cannot replace a later selection. * test(app): load UI modules before test lifecycle hooks Cold module transformation exceeded the lifecycle hook deadline before these suites could run. Complete module initialization before registering the tests, retaining their assertions and timeout settings. --------- Co-authored-by: Ouyang Xingyuan Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../assistant-file-link-tooltip.spec.ts | 54 +++++- packages/app/e2e/browser/folder-links.spec.ts | 5 + packages/app/src/agent-stream/view.tsx | 1 + .../assistant-file-links/path-open.test.ts | 52 +++++- .../app/src/assistant-file-links/path-open.ts | 24 ++- .../src/assistant-file-links/resolver.test.ts | 169 ++++++++++++++++++ .../app/src/assistant-file-links/resolver.ts | 63 ++++++- .../composer/draft/input-draft.live.test.tsx | 14 +- .../app/src/hooks/use-agent-history.test.ts | 16 +- 9 files changed, 364 insertions(+), 34 deletions(-) diff --git a/packages/app/e2e/browser/assistant-file-link-tooltip.spec.ts b/packages/app/e2e/browser/assistant-file-link-tooltip.spec.ts index 69cccc52dd..09a9434995 100644 --- a/packages/app/e2e/browser/assistant-file-link-tooltip.spec.ts +++ b/packages/app/e2e/browser/assistant-file-link-tooltip.spec.ts @@ -1,4 +1,5 @@ -import { writeFile } from "node:fs/promises"; +import { execFileSync } from "node:child_process"; +import { mkdir, writeFile } from "node:fs/promises"; import path from "node:path"; import { test, expect, type Page } from "../support/fixtures"; import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent"; @@ -67,3 +68,54 @@ test("opening an assistant file link dismisses its tooltip over the file tab", a await agent.cleanup(); } }); + +async function readLinkedGuide(page: Page, linkName: string, content: string): Promise { + await page.getByRole("link", { name: linkName, exact: true }).click(); + await expect(page.getByTestId("markdown-preview-frame").filter({ visible: true })).toContainText( + content, + ); +} + +async function returnToNestedLinks(page: Page): Promise { + await page.getByRole("button", { name: "Nested file links", exact: true }).click(); + await expect(page.getByRole("link", { name: "nested guide", exact: true })).toBeVisible(); +} + +test("assistant directory paths find nested files and preserve exact workspace paths", async ({ + page, +}, testInfo) => { + testInfo.setTimeout(120_000); + const agent = await seedMockAgentWorkspace({ + repoPrefix: "nested-file-link-", + title: "Nested file links", + featureValues: { + mockStreamingAssistantResponse: + "Read [nested guide](schema/x.md), [exact guide](schema/exact.md), and [missing guide](schema/missing.md).", + mockStreamingAssistantIntervalMs: 5, + }, + }); + try { + await mkdir(path.join(agent.cwd, "repo-a/schema"), { recursive: true }); + execFileSync("git", ["init", "-b", "main"], { cwd: path.join(agent.cwd, "repo-a") }); + await writeFile( + path.join(agent.cwd, "repo-a/schema/x.md"), + "# Nested file content\n\nDetails\n", + ); + await mkdir(path.join(agent.cwd, "schema"), { recursive: true }); + await writeFile(path.join(agent.cwd, "schema/exact.md"), "# Exact file content\n"); + await writeFile(path.join(agent.cwd, "repo-a/schema/exact.md"), "# Wrong nested content\n"); + await openAgentRoute(page, agent); + await agent.client.sendAgentMessage(agent.agentId, "Show the file links."); + await agent.client.waitForFinish(agent.agentId, 30_000); + + await expect(page.getByRole("textbox", { name: "Message agent..." }).first()).toBeEnabled(); + await readLinkedGuide(page, "nested guide", "Nested file content"); + await returnToNestedLinks(page); + await readLinkedGuide(page, "exact guide", "Exact file content"); + await returnToNestedLinks(page); + await page.getByRole("link", { name: "missing guide", exact: true }).click(); + await expect(page.getByText("File not found", { exact: true })).toBeVisible(); + } finally { + await agent.cleanup(); + } +}); diff --git a/packages/app/e2e/browser/folder-links.spec.ts b/packages/app/e2e/browser/folder-links.spec.ts index a893fbcb68..358c579357 100644 --- a/packages/app/e2e/browser/folder-links.spec.ts +++ b/packages/app/e2e/browser/folder-links.spec.ts @@ -81,6 +81,8 @@ for (const folder of [ "docs/guides", "docs/guides/", "docs/指南", + "examples/next.js/", + "examples/next.js", ]) { test(`chat folder link opens folder contents: ${folder}`, async ({ page }) => { const session = await seedMockAgentWorkspace({ @@ -92,6 +94,9 @@ for (const folder of [ try { await mkdir(path.join(session.cwd, folder), { recursive: true }); await writeFile(path.join(session.cwd, folder, "guide.md"), "# Folder link destination\n"); + const competingFile = path.join(session.cwd, "repo-a", folder.replace(/\/$/, "")); + await mkdir(path.dirname(competingFile), { recursive: true }); + await writeFile(competingFile, "This is a file, not the requested folder.\n"); await session.client.waitForFinish(session.agentId, 30_000); await page.addInitScript(() => { localStorage.setItem( diff --git a/packages/app/src/agent-stream/view.tsx b/packages/app/src/agent-stream/view.tsx index cb9999745b..72923b4212 100644 --- a/packages/app/src/agent-stream/view.tsx +++ b/packages/app/src/agent-stream/view.tsx @@ -468,6 +468,7 @@ const AgentStreamViewComponent = forwardRef createInlinePathOpener({ workspaceRoot, + resolveRelativeFiles: true, client, openFile: openInlineFile, openDirectory: openInlineDirectory, diff --git a/packages/app/src/assistant-file-links/path-open.test.ts b/packages/app/src/assistant-file-links/path-open.test.ts index a85d4c8ec0..f54ee88765 100644 --- a/packages/app/src/assistant-file-links/path-open.test.ts +++ b/packages/app/src/assistant-file-links/path-open.test.ts @@ -64,7 +64,10 @@ it("ignores an older probe after a newer file link opens", async () => { const opened: string[] = []; const opener = createInlinePathOpener({ workspaceRoot: "/repo", - client: { listDirectory: () => pendingProbe }, + client: { + listDirectory: () => pendingProbe, + getDirectorySuggestions: async () => ({ entries: [], error: null }), + }, openFile: (location) => { opened.push(location.path); }, @@ -91,7 +94,10 @@ it("ignores a pending probe when its view is left", async () => { const opened: string[] = []; const opener = createInlinePathOpener({ workspaceRoot: "/repo", - client: { listDirectory: () => pendingProbe }, + client: { + listDirectory: () => pendingProbe, + getDirectorySuggestions: async () => ({ entries: [], error: null }), + }, openFile: (location) => { opened.push(location.path); }, @@ -130,3 +136,45 @@ it("sends folders outside the workspace away from the workspace Files panel", as expect(outsideFolders).toEqual(["~/Downloads/contracts", "/tmp/reports"]); expect(workspaceFolders).toEqual(["docs"]); }); + +it("keeps a later selection when an earlier nested-file lookup finishes last", async () => { + const { createInlinePathOpener } = await import("./path-open"); + const lookup = Promise.withResolvers<{ + entries: Array<{ path: string; kind: "file" }>; + error: null; + }>(); + const queries: string[] = []; + const opened: string[] = []; + const opener = createInlinePathOpener({ + workspaceRoot: "/repo", + resolveRelativeFiles: true, + client: { + listDirectory: async () => { + throw new Error("Not a directory"); + }, + getDirectorySuggestions: async ({ query }: { query: string }) => { + queries.push(query); + return lookup.promise; + }, + }, + openFile: (location) => { + opened.push(location.path); + }, + openDirectory: (directory) => { + opened.push(directory); + }, + openOutsideDirectory: (directory) => { + opened.push(directory); + }, + }); + const earlier = opener.open( + { raw: "schema/x.md:2", path: "/repo/schema/x.md", lineStart: 2 }, + "side", + ); + await Promise.resolve(); + expect(queries).toEqual(["schema/x.md"]); + await opener.open({ raw: "./guide.md:2", path: "/repo/guide.md", lineStart: 2 }, "side"); + lookup.resolve({ entries: [{ path: "repo-a/schema/x.md", kind: "file" }], error: null }); + await earlier; + expect(opened).toEqual(["guide.md"]); +}); diff --git a/packages/app/src/assistant-file-links/path-open.ts b/packages/app/src/assistant-file-links/path-open.ts index 7c9cf228f4..7ff50c9a1a 100644 --- a/packages/app/src/assistant-file-links/path-open.ts +++ b/packages/app/src/assistant-file-links/path-open.ts @@ -5,6 +5,7 @@ import { type OpenFileDisposition, } from "@/workspace/file-open"; import { isAbsolutePath } from "@/utils/path"; +import { resolveMissingNestedRelativeFile, type GetDirectorySuggestions } from "./resolver"; interface PathOpenInput { file?: string; @@ -50,7 +51,11 @@ export async function resolveInlinePathOpen(input: PathOpenInput): Promise; + getDirectorySuggestions: GetDirectorySuggestions; + } | null; + resolveRelativeFiles?: boolean; openFile: (location: WorkspaceFileLocation, disposition: OpenFileDisposition) => void; openDirectory: (path: string) => void; openOutsideDirectory: (path: string) => void; @@ -73,10 +78,21 @@ export function createInlinePathOpener(input: { } else if (destination.kind === "outsideDirectory") { input.openOutsideDirectory(destination.directoryPath); } else if (normalized.file) { + const resolvedTarget = + input.resolveRelativeFiles && input.client + ? await resolveMissingNestedRelativeFile({ + target, + workspaceRoot: input.workspaceRoot, + getDirectorySuggestions: input.client.getDirectorySuggestions.bind(input.client), + }) + : target; + if (ownGeneration !== generation) return; + const resolved = normalizeInlinePathTarget(resolvedTarget.path, input.workspaceRoot); + if (!resolved?.file) return; const location = normalizeWorkspaceFileLocation({ - path: normalized.file, - lineStart: target.lineStart, - lineEnd: target.lineEnd, + path: resolved.file, + lineStart: resolvedTarget.lineStart, + lineEnd: resolvedTarget.lineEnd, }); if (location) input.openFile(location, disposition); } diff --git a/packages/app/src/assistant-file-links/resolver.test.ts b/packages/app/src/assistant-file-links/resolver.test.ts index 121c60f5a0..dc38c24c68 100644 --- a/packages/app/src/assistant-file-links/resolver.test.ts +++ b/packages/app/src/assistant-file-links/resolver.test.ts @@ -7,6 +7,7 @@ import { classifyForResolution, fetchDaemonResolution, getAssistantFileLinkToken, + resolveMissingNestedRelativeFile, UnresolvedFileLinkError, type AssistantFileLinkContext, type DirectorySuggestionEntry, @@ -424,6 +425,174 @@ describe("fetchDaemonResolution", () => { }); }); +describe("resolveMissingNestedRelativeFile", () => { + const target = { + raw: "schema/x.md:12-14", + path: "/Users/test/project/schema/x.md", + lineStart: 12, + lineEnd: 14, + }; + + it("opens a nested-repo suffix when the workspace-root path is missing", async () => { + const { getDirectorySuggestions, searches } = suggestionsFromMap({ + "schema/x.md": [{ path: "repo-a/schema/x.md", kind: "file" }], + }); + + const result = await resolveMissingNestedRelativeFile({ + target, + workspaceRoot: "/Users/test/project", + getDirectorySuggestions, + }); + + expect(searches).toEqual([ + { + query: "schema/x.md", + cwd: "/Users/test/project", + matchMode: "suffix", + limit: 1, + }, + ]); + expect(result).toEqual({ + ...target, + path: "/Users/test/project/repo-a/schema/x.md", + }); + }); + + it("keeps the exact workspace path when suggestions return that relative path", async () => { + const { getDirectorySuggestions } = suggestionsFromMap({ + "schema/x.md": [{ path: "schema/x.md", kind: "file" }], + }); + + const result = await resolveMissingNestedRelativeFile({ + target, + workspaceRoot: "/Users/test/project", + getDirectorySuggestions, + }); + + expect(result).toEqual(target); + }); + + it("keeps the original target when suggestions are empty", async () => { + const { getDirectorySuggestions } = suggestionsFromMap({}); + + await expect( + resolveMissingNestedRelativeFile({ + target, + workspaceRoot: "/Users/test/project", + getDirectorySuggestions, + }), + ).resolves.toEqual(target); + }); + + it("keeps the original target when the daemon throws", async () => { + await expect( + resolveMissingNestedRelativeFile({ + target, + workspaceRoot: "/Users/test/project", + getDirectorySuggestions: unavailableSuggestions, + }), + ).resolves.toEqual(target); + }); + + it.each([ + ["a bare filename", { ...target, path: "/Users/test/project/file.ts" }], + ["a path outside the workspace", { ...target, path: "/tmp/schema/x.md" }], + ["a home-relative path", { ...target, path: "~/schema/x.md" }], + ])("does not search %s", async (_label, candidate) => { + const { getDirectorySuggestions, searches } = suggestionsFromMap({ + "schema/x.md": [{ path: "repo-a/schema/x.md", kind: "file" }], + }); + + const result = await resolveMissingNestedRelativeFile({ + target: candidate, + workspaceRoot: "/Users/test/project", + getDirectorySuggestions, + }); + + expect(searches).toEqual([]); + expect(result).toEqual(candidate); + }); + + it("does not search when the workspace root is blank", async () => { + const { getDirectorySuggestions, searches } = suggestionsFromMap({}); + + const result = await resolveMissingNestedRelativeFile({ + target, + workspaceRoot: " ", + getDirectorySuggestions, + }); + + expect(searches).toEqual([]); + expect(result).toEqual(target); + }); + + it.each([ + ["/Users/test/project/schema/x.md", "/Users/test/project"], + ["file:///Users/test/project/schema/x.md", "/Users/test/project"], + ["C:/repo/schema/x.md", "C:/repo"], + ["\\\\server\\share\\schema\\x.md", "//server/share"], + ])("keeps absolute destination %s", async (raw, workspaceRoot) => { + const { getDirectorySuggestions, searches } = suggestionsFromMap({ + "schema/x.md": [{ path: "repo-a/schema/x.md", kind: "file" }], + }); + const absoluteTarget = { raw, path: `${workspaceRoot}/schema/x.md` }; + await expect( + resolveMissingNestedRelativeFile({ + target: absoluteTarget, + workspaceRoot, + getDirectorySuggestions, + }), + ).resolves.toEqual(absoluteTarget); + expect(searches).toEqual([]); + }); + + it.each(["docs/guides", "./docs/guides", "docs/guides/"])( + "keeps folder href %s direct", + async (raw) => { + const { getDirectorySuggestions, searches } = suggestionsFromMap({ + "docs/guides": [{ path: "repo-a/docs/guides", kind: "file" }], + }); + const folderTarget = { raw, path: "/Users/test/project/docs/guides" }; + await expect( + resolveMissingNestedRelativeFile({ + target: folderTarget, + workspaceRoot: "/Users/test/project", + getDirectorySuggestions, + }), + ).resolves.toEqual(folderTarget); + expect(searches).toEqual([]); + }, + ); + + it("normalizes a Windows workspace root before the suffix lookup", async () => { + const windowsTarget = { + raw: "schema/x.md", + path: "C:\\repo\\schema\\x.md", + lineStart: undefined, + lineEnd: undefined, + }; + const { getDirectorySuggestions, searches } = suggestionsFromMap({ + "schema/x.md": [{ path: "repo-a/schema/x.md", kind: "file" }], + }); + + const result = await resolveMissingNestedRelativeFile({ + target: windowsTarget, + workspaceRoot: "C:\\repo\\", + getDirectorySuggestions, + }); + + expect(searches).toEqual([ + { + query: "schema/x.md", + cwd: "C:\\repo\\", + matchMode: "suffix", + limit: 1, + }, + ]); + expect(result.path).toBe("C:/repo/repo-a/schema/x.md"); + }); +}); + describe("getAssistantFileLinkToken", () => { it("uses rendered text for markdown-it linkified tokens and href for explicit links", () => { expect( diff --git a/packages/app/src/assistant-file-links/resolver.ts b/packages/app/src/assistant-file-links/resolver.ts index 66c4137e2d..f77800b75b 100644 --- a/packages/app/src/assistant-file-links/resolver.ts +++ b/packages/app/src/assistant-file-links/resolver.ts @@ -5,6 +5,7 @@ import { type InlinePathTarget, } from "./parse"; import { i18n } from "@/i18n/i18next"; +import { isAbsolutePath } from "@/utils/path"; export interface AssistantFileLinkSource { href: string; @@ -105,6 +106,62 @@ export async function fetchDaemonResolution({ }; } +/** Only file-looking paths nested inside the workspace need suffix search. */ +function nestedRelativeLookupQuery( + targetPath: string, + workspaceRoot: string | undefined, +): string | null { + const root = workspaceRoot?.trim(); + if (!root) { + return null; + } + const normalizedRoot = root.replace(/\\/g, "/").replace(/\/+$/, ""); + const normalizedPath = targetPath.replace(/\\/g, "/"); + const prefix = `${normalizedRoot}/`; + if (!normalizedPath.startsWith(prefix)) { + return null; + } + const relative = normalizedPath.slice(prefix.length); + if (!relative.includes("/") || !isFileLookingAssistantToken(encodeURI(relative))) { + return null; + } + return relative; +} + +/** When a markdown link points at workspaceRoot/schema/x.md and that file is + * missing, ask the same suffix lookup bare names already use. An exact hit + * stays on that path. A suffix hit such as repo-a/schema/x.md replaces it. + * Lookup failure keeps the original target. + */ +export async function resolveMissingNestedRelativeFile(input: { + target: InlinePathTarget; + workspaceRoot?: string; + getDirectorySuggestions: GetDirectorySuggestions; +}): Promise { + if ( + isAbsoluteInlineCodeToken(input.target.raw) || + input.target.raw.startsWith("~/") || + input.target.raw.endsWith("/") + ) { + return input.target; + } + const query = nestedRelativeLookupQuery(input.target.path, input.workspaceRoot); + if (!query) { + return input.target; + } + try { + return await fetchDaemonResolution({ + ambiguousQuery: query, + token: input.target.raw, + target: input.target, + workspaceRoot: input.workspaceRoot, + getDirectorySuggestions: input.getDirectorySuggestions, + }); + } catch { + return input.target; + } +} + export function classifyForResolution( source: AssistantFileLinkSource, context: AssistantFileLinkContext, @@ -215,11 +272,7 @@ export function shouldResolveDirectFileThroughSuggestions(input: { } function isAbsoluteInlineCodeToken(token: string): boolean { - return ( - token.startsWith("/") || - token.toLowerCase().startsWith("file://") || - /^[A-Za-z]:[\\/]/.test(token) - ); + return isAbsolutePath(token) || token.toLowerCase().startsWith("file://"); } function isLinkifiedSource(source: AssistantFileLinkSource): boolean { diff --git a/packages/app/src/composer/draft/input-draft.live.test.tsx b/packages/app/src/composer/draft/input-draft.live.test.tsx index 8bc31bb176..82de9d3d73 100644 --- a/packages/app/src/composer/draft/input-draft.live.test.tsx +++ b/packages/app/src/composer/draft/input-draft.live.test.tsx @@ -2,7 +2,7 @@ import React, { act } from "react"; import { createRoot, type Root } from "react-dom/client"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { useDraftStore } from "@/stores/draft-store"; import type { AttachmentMetadata, ComposerAttachment } from "@/attachments/types"; import { createWorkspaceFileAttachment } from "@/attachments/workspace-file"; @@ -126,17 +126,13 @@ afterEach(async () => { }); }); -let useAgentInputDraft: typeof import("./input-draft").useAgentInputDraft; type DraftRecordForTest = ReturnType["drafts"][string]; -beforeAll(async () => { - Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", { - value: true, - configurable: true, - }); - - ({ useAgentInputDraft } = await import("./input-draft")); +Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", { + value: true, + configurable: true, }); +const { useAgentInputDraft } = await import("./input-draft"); describe("useAgentInputDraft live contract", () => { beforeEach(() => { diff --git a/packages/app/src/hooks/use-agent-history.test.ts b/packages/app/src/hooks/use-agent-history.test.ts index d4da1f01bb..9a5d80e07e 100644 --- a/packages/app/src/hooks/use-agent-history.test.ts +++ b/packages/app/src/hooks/use-agent-history.test.ts @@ -1,4 +1,4 @@ -import { beforeAll, describe, expect, it } from "vitest"; +import { describe, expect, it } from "vitest"; import type { DaemonClient, FetchAgentHistoryEntry, @@ -13,18 +13,8 @@ import { allAgentHistoryQueryKey } from "./agent-history-query-key"; } ).__DEV__ = false; -type UseAgentHistoryModule = typeof import("./use-agent-history"); - -let fetchAgentHistoryBatch: UseAgentHistoryModule["fetchAgentHistoryBatch"]; -let fetchAgentHistoryPage: UseAgentHistoryModule["fetchAgentHistoryPage"]; -let collectAgentHistoryHostErrors: UseAgentHistoryModule["collectAgentHistoryHostErrors"]; - -beforeAll(async () => { - const module = await import("./use-agent-history"); - fetchAgentHistoryBatch = module.fetchAgentHistoryBatch; - fetchAgentHistoryPage = module.fetchAgentHistoryPage; - collectAgentHistoryHostErrors = module.collectAgentHistoryHostErrors; -}); +const { fetchAgentHistoryBatch, fetchAgentHistoryPage, collectAgentHistoryHostErrors } = + await import("./use-agent-history"); type FetchAgentHistory = DaemonClient["fetchAgentHistory"]; type FetchAgentHistoryResult = Awaited>; From 74613e4bc34313c03c5559a578337ef2a519d004 Mon Sep 17 00:00:00 2001 From: Matt Cowger Date: Sat, 31 Oct 2026 04:55:24 -0700 Subject: [PATCH 144/173] feat(opencode): reuse running OpenCode v2 services (#7435) * feat(opencode): connect v2 client to an existing server * feat(providers): reuse running agent servers Keep shared server sessions isolated and retain native tools while refreshes reuse the running service. * fix(providers): recognize formatted bridge manifests Managed plugin ownership must survive harmless JSON formatting changes. * test(providers): distinguish isolated session bindings Use separate session identities to verify that dedicated helpers keep their environments isolated. --------- Co-authored-by: Mohamed Boudra --- docs/custom-providers.md | 30 +++ docs/providers.md | 2 +- .../scripts/build-opencode-bridge-plugin.mjs | 8 +- .../src/server/agent/provider-runtime.ts | 7 +- .../providers/opencode-bridge-adapter.test.ts | 14 +- .../agent/providers/opencode/bridge.test.ts | 235 +++++++++--------- .../server/agent/providers/opencode/bridge.ts | 20 +- .../providers/opencode/runtime-client.test.ts | 38 +++ .../providers/opencode/runtime-client.ts | 25 ++ .../opencode/test-utils/v2-harness.ts | 3 + .../agent/providers/opencode/v2/agent.test.ts | 20 ++ .../agent/providers/opencode/v2/agent.ts | 21 +- .../providers/opencode/v2/bridge-plugin.mjs | 95 +------ .../opencode/v2/bridge-provisioning.test.ts | 37 +++ .../opencode/v2/bridge-provisioning.ts | 89 +++++++ .../opencode/v2/external-runtime.test.ts | 180 ++++++++++++++ .../opencode/v2/external-server.test.ts | 60 +++++ .../providers/opencode/v2/external-server.ts | 38 +++ .../opencode/v2/owned-runtime.test.ts | 77 ++++++ .../agent/providers/opencode/v2/runtime.ts | 119 ++++++++- .../opencode/v2/service-selection.test.ts | 55 ++++ .../opencode/v2/service-selection.ts | 43 ++++ .../agent/providers/opencode/v2/session.ts | 13 + .../opencode/v2/shared-bridge-plugin.mjs | 207 +++++++++++++++ .../opencode/v2/shared-bridge.test.ts | 168 +++++++++++++ .../providers/opencode/v2/shared-service.ts | 192 ++++++++++++++ .../agent/providers/opencode/v2/state.mjs | 11 + ...ncode-initial-prompt-wait.real.e2e.test.ts | 2 +- .../daemon-e2e/real-provider-test-config.ts | 2 +- 29 files changed, 1578 insertions(+), 233 deletions(-) create mode 100644 packages/server/src/server/agent/providers/opencode/v2/bridge-provisioning.test.ts create mode 100644 packages/server/src/server/agent/providers/opencode/v2/bridge-provisioning.ts create mode 100644 packages/server/src/server/agent/providers/opencode/v2/external-runtime.test.ts create mode 100644 packages/server/src/server/agent/providers/opencode/v2/external-server.test.ts create mode 100644 packages/server/src/server/agent/providers/opencode/v2/external-server.ts create mode 100644 packages/server/src/server/agent/providers/opencode/v2/owned-runtime.test.ts create mode 100644 packages/server/src/server/agent/providers/opencode/v2/service-selection.test.ts create mode 100644 packages/server/src/server/agent/providers/opencode/v2/service-selection.ts create mode 100644 packages/server/src/server/agent/providers/opencode/v2/shared-bridge-plugin.mjs create mode 100644 packages/server/src/server/agent/providers/opencode/v2/shared-bridge.test.ts create mode 100644 packages/server/src/server/agent/providers/opencode/v2/shared-service.ts create mode 100644 packages/server/src/server/agent/providers/opencode/v2/state.mjs diff --git a/docs/custom-providers.md b/docs/custom-providers.md index 615389fe60..1d6d67d453 100644 --- a/docs/custom-providers.md +++ b/docs/custom-providers.md @@ -65,6 +65,7 @@ per-agent examples and provider-specific keys. ## Table of Contents - [Extending a built-in provider](#extending-a-built-in-provider) +- [OpenCode with an existing v2 server](#opencode-with-an-existing-v2-server) - [Z.AI (Zhipu) coding plan](#zai-zhipu-coding-plan) - [Alibaba Cloud (Qwen) coding plan](#alibaba-cloud-qwen-coding-plan) - [Codex with a custom OpenAI-compatible endpoint](#codex-with-a-custom-openai-compatible-endpoint) @@ -107,6 +108,35 @@ See [Codex with a custom OpenAI-compatible endpoint](#codex-with-a-custom-openai --- +## OpenCode with an existing v2 server + +Paseo first uses an explicitly configured server, then a healthy locally registered OpenCode v2 service, then starts its own helper. It never stops a reused service. To select a server explicitly, set its URL in the provider environment: + +```json +{ + "agents": { + "providers": { + "opencode": { + "env": { + "PASEO_OPENCODE_SERVER_URL": "http://127.0.0.1:4096", + "PASEO_OPENCODE_SERVER_PASSWORD": "" + } + } + } + } +} +``` + +`PASEO_OPENCODE_SERVER_URL` must be an absolute `http` or `https` URL. Omit `PASEO_OPENCODE_SERVER_PASSWORD` when the server has no authentication; when set, Paseo authenticates with HTTP Basic auth as `opencode`. + +A configured URL takes precedence even when unreachable; Paseo reports the connection error. The local service registration supplies its own authentication. For a discovered local service, Paseo installs its bridge package in OpenCode's watched global plugin directory without changing the existing configuration. Refresh reads the existing service's catalogs without starting another server. + +An explicitly configured server needs the bridge installed separately. Connect once and start a session: the setup error gives the local package directory. Copy that directory to the server's OpenCode global `plugins` directory, then retry. For a server on another machine, set `PASEO_OPENCODE_BRIDGE_PORT` in the Paseo OpenCode provider environment before starting Paseo, and set `PASEO_OPENCODE_BRIDGE_URL` to the URL the OpenCode server can use to reach that port. For example, an SSH reverse tunnel can expose the Paseo loopback port on the OpenCode host. The bridge token is exchanged through the OpenCode connection and is not written into the plugin package. + +OpenCode's custom MCP registrations are shared by all sessions in a location. Paseo rejects custom MCP servers and per-agent process environment overrides on a reused server rather than applying them to other sessions or ignoring them. Session identity is applied to each session's shell environment. A Paseo-owned helper supports custom process and MCP settings; it is selected when there is no explicit URL or healthy registered service. + +--- + ## Z.AI (Zhipu) coding plan [Z.AI](https://z.ai) is a Chinese AI company (Zhipu AI) that offers an Anthropic-compatible API endpoint. Their GLM Coding Plan provides flat-rate access to GLM models through Claude Code's Anthropic API protocol. These are **not** Anthropic Claude models — they are Zhipu's own GLM models exposed through an Anthropic-compatible API. diff --git a/docs/providers.md b/docs/providers.md index 1a43558ae3..b92e171c12 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -89,7 +89,7 @@ OMP supports native Paseo host tools. The adapter registers the full caller-scop Pi RPC extension UI dialog requests (`select`, `input`, `editor`, `confirm`) are bridged into Paseo question permissions and answered with `extension_ui_response`. Pi extensions such as `ask_user` may chain dialogs: for example, a `select` can be followed by an optional-comment `input`. When an `ask_user` tool call declares `allowComment: true`, Paseo presents the selection and optional comment as one question permission, answers Pi's initial `select` immediately, then auto-answers the follow-up optional `input` with the comment the user already supplied (or an empty string). Preserve placeholders and optional/skip semantics for standalone optional inputs so the app can still distinguish "skip this optional input" from "cancel the whole dialog." Fire-and-forget extension UI requests such as notifications are intentionally ignored by the provider adapter unless Paseo grows first-class UI for them. -OpenCode adapters target v1.14.46 and v2.0.10. V2 rejects binaries older than the tested 2.0.10 SDK at runtime selection. Runtime selection uses the configured command and environment. A recognized version is cached until provider configuration reload; a failed, timed-out, or unrecognized probe retains the v1 path and retries detection on the next operation. Load v2 code and materialize its plugin only after positive v2 selection; v1 sessions remain undecorated. Keep upstream SDK types inside the version-specific adapter. OpenCode owns storage migration; a missing native session must fail resume rather than create a replacement. V2 has no native archive/unarchive operation: archiving affects Paseo only. V1 retains native archiving. +OpenCode adapters target v1.14.46 and v2.0.10. V2 rejects versions older than 2.0.10. Paseo selects an explicit server, then a healthy local registered service, then its own helper. It never stops a reused service. A local service loads the Paseo bridge from its watched plugin directory; sessions bind their own bridge credentials through OpenCode RPC. See [OpenCode with an existing v2 server](custom-providers.md#opencode-with-an-existing-v2-server) for setup and isolation limits. Load v2 code and materialize its plugin only after positive v2 selection; v1 sessions remain undecorated. Keep upstream SDK types inside the version-specific adapter. OpenCode owns storage migration; a missing native session must fail resume rather than create a replacement. V2 has no native archive/unarchive operation: archiving affects Paseo only. V1 retains native archiving. Use OpenCode v2 execution events to trigger turn completion, with active-state and durable-log reconciliation after admission, reconnect, and while a turn remains active. Do not use `session.wait`: a healthy turn exceeding Node's HTTP headers deadline produces a transport error while OpenCode keeps working. The live event feed has no replay, and shutdown interruption preserves the previous idle outcome, so the session snapshot alone cannot recover missed execution events. Quiet streams are healthy: v2 heartbeats are SSE comments, not application events. diff --git a/packages/server/scripts/build-opencode-bridge-plugin.mjs b/packages/server/scripts/build-opencode-bridge-plugin.mjs index 69f1e774f0..33cd3402ce 100644 --- a/packages/server/scripts/build-opencode-bridge-plugin.mjs +++ b/packages/server/scripts/build-opencode-bridge-plugin.mjs @@ -1,4 +1,4 @@ -import { mkdir } from "node:fs/promises"; +import { copyFile, mkdir } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; @@ -27,4 +27,10 @@ for (const directory of ["", "v2/"]) { target: "es2022", outfile: outputPath, }); + if (directory === "v2/") { + await copyFile( + new URL("../src/server/agent/providers/opencode/v2/state.mjs", import.meta.url), + path.join(path.dirname(outputPath), "state.mjs"), + ); + } } diff --git a/packages/server/src/server/agent/provider-runtime.ts b/packages/server/src/server/agent/provider-runtime.ts index 398d35746d..c266614273 100644 --- a/packages/server/src/server/agent/provider-runtime.ts +++ b/packages/server/src/server/agent/provider-runtime.ts @@ -22,7 +22,12 @@ interface CreateAgentProviderRuntimeOptions { export async function createAgentProviderRuntime( options: CreateAgentProviderRuntimeOptions, ): Promise { - const bridge = new OpenCodeBridge({ paseoHome: options.paseoHome, logger: options.logger }); + const configuredPort = + options.snapshotManager.runtimeSettings?.opencode?.env?.PASEO_OPENCODE_BRIDGE_PORT; + const port = configuredPort === undefined ? undefined : Number(configuredPort); + if (port !== undefined && (!Number.isInteger(port) || port < 1 || port > 65535)) + throw new Error("PASEO_OPENCODE_BRIDGE_PORT must be an integer between 1 and 65535"); + const bridge = new OpenCodeBridge({ paseoHome: options.paseoHome, logger: options.logger, port }); try { await bridge.start(); const snapshotManager = new ProviderSnapshotManager({ diff --git a/packages/server/src/server/agent/providers/opencode-bridge-adapter.test.ts b/packages/server/src/server/agent/providers/opencode-bridge-adapter.test.ts index 133ac3c992..6cb15ccb6d 100644 --- a/packages/server/src/server/agent/providers/opencode-bridge-adapter.test.ts +++ b/packages/server/src/server/agent/providers/opencode-bridge-adapter.test.ts @@ -80,8 +80,12 @@ describe("OpenCode bridge adapter", () => { await rm(paseoHome, { recursive: true, force: true }); }); const runtime = new TestOpenCodeHarness(); - runtime.enqueueClient(new TestOpenCodeClient()); - runtime.enqueueClient(new TestOpenCodeClient()); + const envClient = new TestOpenCodeClient(); + const mcpClient = new TestOpenCodeClient(); + envClient.sessionCreateResponse = { data: { id: "ses_env" } }; + mcpClient.sessionCreateResponse = { data: { id: "ses_mcp" } }; + runtime.enqueueClient(envClient); + runtime.enqueueClient(mcpClient); const client = new OpenCodeAgentClient(createTestLogger(), undefined, { serverManager: runtime, createClient: runtime.createClient, @@ -102,6 +106,12 @@ describe("OpenCode bridge adapter", () => { ); expect(runtime.acquisitions.map(({ kind }) => kind)).toEqual(["dedicated", "dedicated"]); + await expect(readBridgeContext(bridge, "ses_env")).resolves.toEqual({ + env: { PASEO_AGENT_ID: "one", CUSTOM_TOKEN: "secret" }, + }); + await expect(readBridgeContext(bridge, "ses_mcp")).resolves.toEqual({ + env: { PASEO_AGENT_ID: "two" }, + }); await customEnv.close(); await customMcp.close(); }); diff --git a/packages/server/src/server/agent/providers/opencode/bridge.test.ts b/packages/server/src/server/agent/providers/opencode/bridge.test.ts index 33f43c4f79..468baabe14 100644 --- a/packages/server/src/server/agent/providers/opencode/bridge.test.ts +++ b/packages/server/src/server/agent/providers/opencode/bridge.test.ts @@ -20,6 +20,7 @@ import { createPaseoAgentToolManifest, createPaseoToolCatalog } from "../../tool import { serializePaseoToolInputParameters } from "../../tools/paseo-tool-serialization.js"; import { OpenCodeBridge, + decorateOpenCodeV2Env, loadOpenCodeBridgePluginArtifact, materializeOpenCodeV2Plugin, } from "./bridge.js"; @@ -137,33 +138,28 @@ describe("OpenCodeBridge", () => { }; expect(ajv.compile(createDefinition.inputSchema)(createInput)).toBe(true); - const v2Config = z - .object({ plugins: z.array(z.object({ package: z.string() })) }) - .parse(JSON.parse((await bridge.decorateV2ServerEnv({})).OPENCODE_CONFIG_CONTENT)); - const v2Module: { - default: { setup(context: V2TestPluginContext): Promise<() => Promise> }; - } = await import( - pathToFileURL(path.join(fileURLToPath(v2Config.plugins[0]!.package), "server.js")).href - ); const tools = new Map(); - const dispose = await v2Module.default.setup({ - options: plugin, - tool: { - transform: async (transform) => { - transform({ - add: (tool) => { - tools.set(tool.name, tool); - }, - }); - return { dispose: async () => undefined }; + const dispose = await setupBoundV2Plugin( + bridge, + { + tool: { + transform: async (transform) => { + transform({ + add: (tool) => { + tools.set(tool.name, tool); + }, + }); + return { dispose: async () => undefined }; + }, + }, + session: { + context: async () => [], + get: async () => ({ parentID: "bound" }), + hook: async () => ({ dispose: async () => undefined }), }, }, - session: { - context: async () => [], - get: async () => ({ parentID: "bound" }), - hook: async () => ({ dispose: async () => undefined }), - }, - }); + ["bound"], + ); try { const created = await tools .get("paseo_create_agent")! @@ -402,45 +398,35 @@ describe("OpenCodeBridge", () => { const release = bridge.bindSession({ sessionId: "parent", env: {}, tools: catalog }); const releaseDisabled = bridge.bindSession({ sessionId: "disabled", env: {} }); try { - const env = await bridge.decorateV2ServerEnv({}); - const config = z - .object({ - plugins: z.array( - z.object({ - package: z.string(), - options: z.object({ baseUrl: z.string(), token: z.string() }), - }), - ), - }) - .parse(JSON.parse(env.OPENCODE_CONFIG_CONTENT)); - expect(await bridge.decorateV2ServerEnv(env)).toEqual(env); - const plugin = config.plugins[0]!; + const pluginUrl = await bridge.materializeV2Plugin(); + const env = decorateOpenCodeV2Env({}, pluginUrl); + expect(decorateOpenCodeV2Env(env, pluginUrl)).toEqual(env); const tools = new Map(); let filter!: (input: V2TestContext) => Promise; - const module: { - default: { setup(context: V2TestPluginContext): Promise<() => Promise> }; - } = await import(pathToFileURL(path.join(fileURLToPath(plugin.package), "server.js")).href); - const dispose = await module.default.setup({ - options: plugin.options, - tool: { - transform: async (transform) => { - transform({ - add: (tool) => { - tools.set(tool.name, tool); - }, - }); - return { dispose: async () => undefined }; + const dispose = await setupBoundV2Plugin( + bridge, + { + tool: { + transform: async (transform) => { + transform({ + add: (tool) => { + tools.set(tool.name, tool); + }, + }); + return { dispose: async () => undefined }; + }, + }, + session: { + context: async () => [], + get: async ({ sessionID }) => ({ parentID: sessionID === "child" ? "parent" : "" }), + hook: async (_name, callback) => { + filter = callback; + return { dispose: async () => undefined }; + }, }, }, - session: { - context: async () => [], - get: async () => ({ parentID: "parent" }), - hook: async (_name, callback) => { - filter = callback; - return { dispose: async () => undefined }; - }, - }, - }); + ["parent", "disabled"], + ); const allowed: V2TestContext = { sessionID: "child", tools: { paseo_echo_context: {}, native: {} }, @@ -453,6 +439,12 @@ describe("OpenCodeBridge", () => { }; await filter(disabled); expect(Object.keys(disabled.tools)).toEqual(["native"]); + const unrelated: V2TestContext = { + sessionID: "unrelated", + tools: { paseo_echo_context: {}, native: {} }, + }; + await filter(unrelated); + expect(Object.keys(unrelated.tools)).toEqual(["native"]); await expect( tools.get("paseo_echo_context")!.execute({ value: "child result" }, { sessionID: "child" }), ).resolves.toMatchObject({ content: [{ type: "text", text: "child result" }] }); @@ -486,35 +478,33 @@ describe("OpenCodeBridge", () => { await bridge.start(); const release = bridge.bindSession({ sessionId: "caller", env: {}, tools: catalog }); try { - const env = await bridge.decorateV2ServerEnv({}); - const { plugins } = JSON.parse(env.OPENCODE_CONFIG_CONTENT); - const plugin = plugins[0]; - const module = await import( - pathToFileURL(path.join(fileURLToPath(plugin.package), "server.js")).href - ); + const options = bridge.sharedV2Connection(); const tools = new Map(); - const dispose = await module.default.setup({ - options: plugin.options, - tool: { - transform: async (transform: (editor: { add(tool: V2TestTool): void }) => void) => { - transform({ add: (tool) => tools.set(tool.name, tool) }); - return { dispose: async () => undefined }; + const dispose = await setupBoundV2Plugin( + bridge, + { + tool: { + transform: async (transform: (editor: { add(tool: V2TestTool): void }) => void) => { + transform({ add: (tool) => tools.set(tool.name, tool) }); + return { dispose: async () => undefined }; + }, + }, + session: { + context: async () => [], + get: async () => ({ parentID: "" }), + hook: async () => ({ dispose: async () => undefined }), }, }, - session: { - context: async () => [], - get: async () => ({ parentID: "" }), - hook: async () => ({ dispose: async () => undefined }), - }, - } satisfies V2TestPluginContext); + ["caller"], + ); try { const input = { provider: "codex", title: "Invalid provider", initialPrompt: "Hello" }; const response = await fetch( - `${plugin.options.baseUrl}/_internal/opencode/sessions/caller/tools/create_agent`, + `${options.baseUrl}/_internal/opencode/sessions/caller/tools/create_agent`, { method: "POST", headers: { - Authorization: `Bearer ${plugin.options.token}`, + Authorization: `Bearer ${options.token}`, "Content-Type": "application/json", }, body: JSON.stringify(input), @@ -572,35 +562,24 @@ describe("OpenCodeBridge", () => { await bridge.start(); const release = bridge.bindSession({ sessionId: "session", env: {}, tools: catalog }); try { - const env = await bridge.decorateV2ServerEnv({}); - const plugin = z - .object({ - plugins: z.array( - z.object({ - package: z.string(), - options: z.object({ baseUrl: z.string(), token: z.string() }), - }), - ), - }) - .parse(JSON.parse(env.OPENCODE_CONFIG_CONTENT)).plugins[0]!; const pluginTools = new Map(); - const module: { - default: { setup(context: V2TestPluginContext): Promise<() => Promise> }; - } = await import(pathToFileURL(path.join(fileURLToPath(plugin.package), "server.js")).href); - const dispose = await module.default.setup({ - options: plugin.options, - tool: { - transform: async (transform) => { - transform({ add: (tool) => pluginTools.set(tool.name, tool) }); - return { dispose: async () => undefined }; + const dispose = await setupBoundV2Plugin( + bridge, + { + tool: { + transform: async (transform) => { + transform({ add: (tool) => pluginTools.set(tool.name, tool) }); + return { dispose: async () => undefined }; + }, + }, + session: { + context: async () => [], + get: async () => ({ parentID: undefined }), + hook: async () => ({ dispose: async () => undefined }), }, }, - session: { - context: async () => [], - get: async () => ({ parentID: undefined }), - hook: async () => ({ dispose: async () => undefined }), - }, - }); + ["session"], + ); const result = await pluginTools .get("paseo_browser_screenshot")! .execute({}, { sessionID: "session" }); @@ -642,7 +621,8 @@ describe("OpenCodeBridge", () => { const tools = new Map(); let hook!: (input: V2TestContext) => Promise; const dispose = await module.default.setup({ - options: { baseUrl: "", token: "" }, + options: { mode: "structured-only" }, + location: { directory: root }, tool: { transform: async (transform) => { transform({ @@ -657,7 +637,7 @@ describe("OpenCodeBridge", () => { context: async () => history, get: async () => ({ parentID: "parent" }), hook: async (_name, callback) => { - hook = callback; + hook ??= callback; return { dispose: async () => undefined }; }, }, @@ -701,9 +681,13 @@ describe("OpenCodeBridge", () => { name.startsWith("paseo-v2-"), ), ).toEqual([]); - const env = await bridge.decorateV2ServerEnv({ - OPENCODE_CONFIG_CONTENT: JSON.stringify({ plugins: ["user-plugin"] }), - }); + const pluginUrl = await bridge.materializeV2Plugin(); + const env = decorateOpenCodeV2Env( + { + OPENCODE_CONFIG_CONTENT: JSON.stringify({ plugins: ["user-plugin"] }), + }, + pluginUrl, + ); const config = z .object({ plugins: z.tuple([z.literal("user-plugin"), z.object({ package: z.string() })]) }) .parse(JSON.parse(env.OPENCODE_CONFIG_CONTENT)); @@ -711,6 +695,9 @@ describe("OpenCodeBridge", () => { expect((await stat(directory)).isDirectory()).toBe(true); const entry = await readFile(path.join(directory, "server.js"), "utf8"); expect(entry).toContain('id: "paseo"'); + expect(await readFile(path.join(directory, "state.mjs"), "utf8")).toBe( + await readFile(new URL("./v2/state.mjs", import.meta.url), "utf8"), + ); const manifest = JSON.parse(await readFile(path.join(directory, "package.json"), "utf8")); expect(manifest).toMatchObject({ type: "module", exports: { "./server": "./server.js" } }); } finally { @@ -856,7 +843,8 @@ interface V2TestContext { system?: Array<{ type: "text"; text: string }>; } interface V2TestPluginContext { - options: { baseUrl: string; token: string }; + options: Record; + location?: { directory: string }; tool: { transform( callback: (editor: { add(tool: V2TestTool): void }) => void, @@ -864,10 +852,33 @@ interface V2TestPluginContext { }; session: { context(input: { sessionID: string }): Promise; - get(input: { sessionID: string }): Promise<{ parentID: string }>; + get(input: { sessionID: string }): Promise<{ parentID: string | undefined }>; hook( name: string, callback: (input: V2TestContext) => Promise, ): Promise<{ dispose(): Promise }>; }; } + +async function setupBoundV2Plugin( + bridge: OpenCodeBridge, + context: Pick, + sessionIds: string[], +): Promise<() => Promise> { + const directory = fileURLToPath(await bridge.materializeV2Plugin()); + const module = await import(pathToFileURL(path.join(directory, "server.js")).href); + let bind!: (input: { sessionID: string; baseUrl: string; token: string }) => Promise; + const dispose: () => Promise = await module.default.setup({ + ...context, + options: {}, + location: { directory }, + rpc: { + register: async (_definition: unknown, handlers: { bind: typeof bind }) => { + bind = handlers.bind; + return { dispose: async () => undefined }; + }, + }, + }); + for (const sessionID of sessionIds) await bind({ sessionID, ...bridge.sharedV2Connection() }); + return dispose; +} diff --git a/packages/server/src/server/agent/providers/opencode/bridge.ts b/packages/server/src/server/agent/providers/opencode/bridge.ts index 7abe34475d..87ee07798b 100644 --- a/packages/server/src/server/agent/providers/opencode/bridge.ts +++ b/packages/server/src/server/agent/providers/opencode/bridge.ts @@ -30,6 +30,7 @@ class OpenCodeBridgeClientError extends Error { interface OpenCodeBridgeOptions { paseoHome: string; logger: Logger; + port?: number; } interface OpenCodeSessionBinding { @@ -54,6 +55,7 @@ interface OpenCodeConfig { export class OpenCodeBridge { private readonly paseoHome: string; private readonly logger: Logger; + private readonly port: number; private readonly token = randomBytes(32).toString("hex"); private readonly sessions = new Map(); private server: Server | null = null; @@ -65,6 +67,7 @@ export class OpenCodeBridge { constructor(options: OpenCodeBridgeOptions) { this.paseoHome = options.paseoHome; this.logger = options.logger.child({ module: "agent", component: "opencode-bridge" }); + this.port = options.port ?? 0; } async start(): Promise { @@ -75,7 +78,7 @@ export class OpenCodeBridge { }); await new Promise((resolve, reject) => { server.once("error", reject); - server.listen(0, "127.0.0.1", () => { + server.listen(this.port, "127.0.0.1", () => { server.off("error", reject); resolve(); }); @@ -94,6 +97,8 @@ export class OpenCodeBridge { } bindSession(input: BindOpenCodeSessionInput): () => void { + if (this.sessions.has(input.sessionId)) + throw new Error(`OpenCode session ${input.sessionId} is already bound to a Paseo agent`); const binding: OpenCodeSessionBinding = { env: { ...input.env }, ...(input.tools ? { tools: input.tools } : {}), @@ -127,12 +132,13 @@ export class OpenCodeBridge { }; } - async decorateV2ServerEnv(env: Record): Promise> { + async materializeV2Plugin(): Promise { this.v2PluginUrl ??= await this.materializePlugin(2); - return decorateOpenCodeV2Env(env, this.v2PluginUrl, { - baseUrl: this.requireBaseUrl(), - token: this.token, - }); + return this.v2PluginUrl; + } + + sharedV2Connection(baseUrl = this.requireBaseUrl()): OpenCodePluginOptions { + return { baseUrl, token: this.token }; } async close(): Promise { @@ -282,6 +288,8 @@ export async function materializeOpenCodeV2Plugin(paseoHome: string): Promise { + const { OpenCodeRuntimeClient } = await import("./runtime-client.js"); + const { createTestLogger } = await import("../../../../test-utils/test-logger.js"); + const client = new OpenCodeRuntimeClient(createTestLogger(), { + command: { mode: "replace", argv: [process.execPath, "-e", "process.exit(1)"] }, + env: { PASEO_OPENCODE_SERVER_URL: "http://127.0.0.1:4096" }, + }); + try { + const features = await client.listFeatures({ provider: "opencode", cwd: "/tmp/project" }); + expect(features.map((feature) => feature.label)).toEqual(["Auto-accept"]); + } finally { + await client.shutdown(); + } +}); + +test("keeps native Paseo tools available when an external server is configured", async () => { + const { OpenCodeRuntimeClient } = await import("./runtime-client.js"); + const { createTestLogger } = await import("../../../../test-utils/test-logger.js"); + const { OpenCodeBridge } = await import("./bridge.js"); + const bridge = new OpenCodeBridge({ paseoHome: "/tmp", logger: createTestLogger() }); + const external = new OpenCodeRuntimeClient( + createTestLogger(), + { env: { PASEO_OPENCODE_SERVER_URL: "http://127.0.0.1:4096" } }, + { bridge }, + ); + const local = new OpenCodeRuntimeClient(createTestLogger(), undefined, { bridge }); + try { + expect(external.capabilities.supportsNativePaseoTools).toBe(true); + expect(local.capabilities.supportsNativePaseoTools).toBe(true); + } finally { + await external.shutdown(); + await local.shutdown(); + } +}); diff --git a/packages/server/src/server/agent/providers/opencode/runtime-client.ts b/packages/server/src/server/agent/providers/opencode/runtime-client.ts index 2a34abe35d..e5fa17021a 100644 --- a/packages/server/src/server/agent/providers/opencode/runtime-client.ts +++ b/packages/server/src/server/agent/providers/opencode/runtime-client.ts @@ -19,7 +19,9 @@ import { import { execCommand } from "../../../../utils/spawn.js"; import { OpenCodeAgentClient } from "../opencode-agent.js"; import type { OpenCodeV2AgentClient } from "./v2/agent.js"; +import { resolveExternalOpenCodeServer } from "./v2/external-server.js"; import { withOpenCodeRuntimeNotice } from "./runtime-notice.js"; +import { selectOpenCodeService } from "./v2/service-selection.js"; // Keep the minimum aligned with the SDK and binary exercised by CI. const MINIMUM_V2: readonly [number, number] = [0, 10]; @@ -67,8 +69,25 @@ export class OpenCodeRuntimeClient implements AgentClient { this.resolveCreateConfig = this.legacy.resolveCreateConfig; this.isCreateConfigUnattended = this.legacy.isCreateConfigUnattended; } + private selectService() { + return selectOpenCodeService({ + explicit: resolveExternalOpenCodeServer({ ...globalThis.process.env, ...this.settings?.env }), + env: this.settings?.env, + }); + } private client(): Promise { this.selected ??= (async () => { + const selection = await this.selectService(); + if (selection.kind !== "owned") { + const { OpenCodeV2AgentClient } = await import("./v2/agent.js"); + return new OpenCodeV2AgentClient({ + logger: this.logger, + settings: this.settings, + managedProcesses: this.options.managedProcesses, + bridge: this.options.bridge, + selection, + }); + } let output: string; try { const launch = await resolveProviderLaunch({ @@ -97,6 +116,7 @@ export class OpenCodeRuntimeClient implements AgentClient { settings: this.settings, managedProcesses: this.options.managedProcesses, bridge: this.options.bridge, + selection, }); })().catch((error: unknown) => { // A failed probe must not poison refresh after the user updates the binary. @@ -106,9 +126,14 @@ export class OpenCodeRuntimeClient implements AgentClient { return this.selected; } async isAvailable() { + const selection = await this.selectService(); + if (selection.kind !== "owned") return true; return this.legacy.isAvailable(); } async getDiagnostic() { + const selection = await this.selectService(); + if (selection.kind !== "owned") + return { diagnostic: `OpenCode server: ${selection.server.url}` }; return this.legacy.getDiagnostic(); } async createSession( diff --git a/packages/server/src/server/agent/providers/opencode/test-utils/v2-harness.ts b/packages/server/src/server/agent/providers/opencode/test-utils/v2-harness.ts index 505955f64c..eb06928e63 100644 --- a/packages/server/src/server/agent/providers/opencode/test-utils/v2-harness.ts +++ b/packages/server/src/server/agent/providers/opencode/test-utils/v2-harness.ts @@ -172,6 +172,9 @@ export class V2Harness { event: { subscribe: (options) => this.events(options?.signal) }, }; readonly connection: V2Connection = { + bindSession: async () => {}, + unbindSession: async () => {}, + refreshLocation: async () => {}, client: this.api, release: async () => { this.releases += 1; diff --git a/packages/server/src/server/agent/providers/opencode/v2/agent.test.ts b/packages/server/src/server/agent/providers/opencode/v2/agent.test.ts index 564e1f46c5..e8188730f5 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/agent.test.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/agent.test.ts @@ -17,6 +17,26 @@ function terminalEvents(events: AgentStreamEvent[]) { } describe("OpenCode v2 session lifecycle", () => { + test("refreshes the existing location before reading a forced catalog", async () => { + const harness = new V2Harness(); + const refreshed: string[] = []; + harness.connection.refreshLocation = async (directory) => { + refreshed.push(directory); + }; + harness.api.model.list = async () => ({ location: harness.info.location, data: [] }); + harness.api.provider.list = async () => ({ + location: harness.info.location, + data: [{ id: "test", name: "Test", activation: "enabled", package: "test" }], + }); + const client = new OpenCodeV2AgentClient({ + logger: createTestLogger(), + runtime: harness.runtime, + }); + await client.fetchCatalog({ scope: "workspace", cwd: "/tmp/project", force: true }); + await client.fetchCatalog({ scope: "workspace", cwd: "/tmp/project", force: false }); + expect(refreshed).toEqual(["/tmp/project"]); + await client.shutdown(); + }); test("completes from execution events without a long-lived HTTP wait", async () => { const harness = new V2Harness(); harness.prompt = async (input) => { diff --git a/packages/server/src/server/agent/providers/opencode/v2/agent.ts b/packages/server/src/server/agent/providers/opencode/v2/agent.ts index 2e50e759bd..119fa0ade7 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/agent.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/agent.ts @@ -8,7 +8,7 @@ import { } from "./configuration.js"; import { commands } from "./commands.js"; -import { waitForLocationReady, awaitPaseoPlugin } from "./readiness.js"; +import { waitForLocationReady } from "./readiness.js"; import type { SessionInfo } from "@opencode/client"; @@ -40,6 +40,7 @@ import { importSessionFromPersistence } from "../../../provider-session-import.j import type { OpenCodeBridge } from "../bridge.js"; import { resolveOpenCodeHomeDir } from "../paths.js"; import { V2Runtime, type V2Connection } from "./runtime.js"; +import type { OpenCodeServiceSelection } from "./service-selection.js"; import { modelRef, modesFromV2, modelsFromV2 } from "./mapping.js"; interface V2AgentOptions { @@ -48,6 +49,7 @@ interface V2AgentOptions { managedProcesses?: ManagedProcessRegistry; bridge?: OpenCodeBridge; runtime?: Pick; + selection?: OpenCodeServiceSelection; } export class OpenCodeV2AgentClient implements AgentClient { @@ -56,12 +58,12 @@ export class OpenCodeV2AgentClient implements AgentClient { private readonly runtime: Pick; private readonly connections = new Map(); constructor(private readonly options: V2AgentOptions) { - this.capabilities = { ...V2_CAPABILITIES, supportsNativePaseoTools: Boolean(options.bridge) }; + const bridge = options.bridge; + this.capabilities = { ...V2_CAPABILITIES, supportsNativePaseoTools: Boolean(bridge) }; this.runtime = options.runtime ?? new V2Runtime({ ...options, - decorateEnv: options.bridge ? (env) => options.bridge!.decorateV2ServerEnv(env) : undefined, }); } async isAvailable() { @@ -85,6 +87,10 @@ export class OpenCodeV2AgentClient implements AgentClient { await activity("plugin.list", () => waitForLocationReady({ client: connection.client, location, signal: request.signal }), ); + if (options.force) + await activity("paseo.bridge.refresh", () => + connection.refreshLocation(location.directory, request.signal), + ); const [models, agents, providers] = await Promise.all([ activity("model.list", () => connection.client.model.list({ location }, request)), activity("agent.list", () => connection.client.agent.list({ location }, request)), @@ -163,7 +169,8 @@ export class OpenCodeV2AgentClient implements AgentClient { requiresDedicatedV2Server(config, launch) ? { env: launch?.env, dedicated: true } : {}, ); let ownedConnection = connection; - const unbind = this.options.bridge?.bindSession({ + const bridge = this.options.bridge; + const unbind = bridge?.bindSession({ sessionId: info.id, env: launch?.env ?? {}, tools: launch?.paseoTools, @@ -172,7 +179,7 @@ export class OpenCodeV2AgentClient implements AgentClient { const bindChild = (childId: string) => { this.connections.set(childId, ownedConnection); if (bound.has(childId)) return; - const childUnbind = this.options.bridge?.bindSession({ + const childUnbind = bridge?.bindSession({ sessionId: childId, env: launch?.env ?? {}, tools: launch?.paseoTools, @@ -204,10 +211,6 @@ export class OpenCodeV2AgentClient implements AgentClient { moved, ); try { - if (this.options.bridge) { - const location = { directory: config.cwd }; - await awaitPaseoPlugin({ client: connection.client, location }); - } await session.initialize( launch?.env ? createProviderEnv({ runtimeSettings: this.options.settings, overlays: [launch.env] }) diff --git a/packages/server/src/server/agent/providers/opencode/v2/bridge-plugin.mjs b/packages/server/src/server/agent/providers/opencode/v2/bridge-plugin.mjs index 1664c0b59f..6971a5b323 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/bridge-plugin.mjs +++ b/packages/server/src/server/agent/providers/opencode/v2/bridge-plugin.mjs @@ -1,100 +1,15 @@ -import { registerStructuredOutput, STRUCTURED_OUTPUT_TOOL } from "./structured-output-plugin.mjs"; +import { registerStructuredOutput } from "./structured-output-plugin.mjs"; +import { registerSharedBridge } from "./shared-bridge-plugin.mjs"; export default { id: "paseo", async setup(context) { const disposeStructuredOutput = await registerStructuredOutput(context); - const { baseUrl, token } = context.options; - if (!baseUrl || !token) return disposeStructuredOutput; - async function request(pathname, body, allowMissing = false) { - const response = await fetch(new URL(`/_internal/opencode${pathname}`, baseUrl), { - method: body === undefined ? "GET" : "POST", - headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, - ...(body === undefined ? {} : { body: JSON.stringify(body) }), - }); - if (allowMissing && response.status === 404) return null; - if (!response.ok) { - const payload = await response.json().catch(() => null); - const detail = formatErrorDetail(payload?.issues ?? payload?.details); - const message = - typeof payload?.error === "string" && payload.error - ? payload.error - : `Paseo tool bridge returned HTTP ${response.status}`; - const error = new Error(detail ? `${message}: ${detail}` : message); - error.status = response.status; - if (detail) error.details = detail; - throw error; - } - return response.json(); - } - async function scope(sessionID) { - const visited = new Set(); - while (sessionID && !visited.has(sessionID)) { - visited.add(sessionID); - const binding = await request( - `/sessions/${encodeURIComponent(sessionID)}/context?tools`, - undefined, - true, - ); - if (binding) return { ...binding, sessionID }; - const session = await context.session.get({ sessionID }); - sessionID = session.parentID; - } - throw new Error("OpenCode session is not bound to a Paseo agent"); - } - const manifest = await request("/tools"); - const registration = await context.tool.transform((editor) => { - for (const definition of manifest.tools) { - editor.add({ - name: `paseo_${definition.name}`, - description: definition.description, - input: definition.inputSchema, - options: { codemode: false }, - async execute(input, call) { - const binding = await scope(call.sessionID); - const result = await request( - `/sessions/${encodeURIComponent(binding.sessionID)}/tools/${encodeURIComponent(definition.name)}`, - input, - ); - return { - content: result.content.map(toOpenCodeContent), - metadata: { paseoTool: definition.name }, - }; - }, - }); - } - }); - const filtering = await context.session.hook("context", async (input) => { - const binding = await scope(input.sessionID); - const allowed = new Set(binding.tools.map((name) => `paseo_${name}`)); - for (const name of Object.keys(input.tools)) { - if (name !== STRUCTURED_OUTPUT_TOOL && name.startsWith("paseo_") && !allowed.has(name)) - delete input.tools[name]; - } - }); + if (context.options.mode === "structured-only") return disposeStructuredOutput; + const disposeBridge = await registerSharedBridge(context); return async () => { + await disposeBridge(); await disposeStructuredOutput(); - await filtering.dispose(); - await registration.dispose(); }; }, }; - -function formatErrorDetail(details) { - if (!Array.isArray(details)) return typeof details === "string" ? details : ""; - return details - .map((issue) => { - const path = - Array.isArray(issue?.path) && issue.path.length > 0 ? issue.path.join(".") : "input"; - return `${path}: ${issue?.message ?? "Invalid value"}`; - }) - .join("; "); -} - -// OpenCode tool content is text or a file; MCP images arrive as base64 data. -function toOpenCodeContent(part) { - if (part.type === "image") { - return { type: "file", uri: `data:${part.mimeType};base64,${part.data}`, mime: part.mimeType }; - } - return part; -} diff --git a/packages/server/src/server/agent/providers/opencode/v2/bridge-provisioning.test.ts b/packages/server/src/server/agent/providers/opencode/v2/bridge-provisioning.test.ts new file mode 100644 index 0000000000..52b483cca3 --- /dev/null +++ b/packages/server/src/server/agent/providers/opencode/v2/bridge-provisioning.test.ts @@ -0,0 +1,37 @@ +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { expect, test } from "vitest"; +import { hasManagedBridge, provisionLocalBridge } from "./bridge-provisioning.js"; + +test("installs a watched plugin without changing existing OpenCode configuration", async () => { + const root = await mkdtemp(path.join(tmpdir(), "paseo-opencode-provision-")); + const source = path.join(root, "source.js"); + const config = path.join(root, "opencode.json"); + await writeFile(source, "export default { id: 'paseo' };"); + await writeFile(path.join(root, "state.mjs"), "export const state = new Map();"); + await writeFile(config, '{"plugins":["existing"]}\n'); + try { + expect(await hasManagedBridge(root)).toBe(false); + await Promise.all([ + provisionLocalBridge({ configDirectory: root, artifact: source }), + provisionLocalBridge({ configDirectory: root, artifact: source }), + ]); + expect(await hasManagedBridge(root)).toBe(true); + const manifest = path.join(root, "plugins/paseo-managed-bridge/package.json"); + const formatted = `${JSON.stringify(JSON.parse(await readFile(manifest, "utf8")), null, 2)}\n`; + await writeFile(manifest, formatted); + expect(await hasManagedBridge(root)).toBe(true); + await provisionLocalBridge({ configDirectory: root, artifact: source }); + expect(await readFile(manifest, "utf8")).toBe(formatted); + expect(await readFile(config, "utf8")).toBe('{"plugins":["existing"]}\n'); + expect(await readFile(path.join(root, "plugins/paseo-managed-bridge/state.mjs"), "utf8")).toBe( + "export const state = new Map();", + ); + expect( + await readFile(path.join(root, "plugins/paseo-managed-bridge/server.js"), "utf8"), + ).toContain("id: 'paseo'"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/packages/server/src/server/agent/providers/opencode/v2/bridge-provisioning.ts b/packages/server/src/server/agent/providers/opencode/v2/bridge-provisioning.ts new file mode 100644 index 0000000000..ce2626c38b --- /dev/null +++ b/packages/server/src/server/agent/providers/opencode/v2/bridge-provisioning.ts @@ -0,0 +1,89 @@ +import { mkdir, readFile } from "node:fs/promises"; +import { homedir } from "node:os"; +import path from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; +import { writeFileAtomic } from "../../../../atomic-file.js"; + +const PACKAGE = JSON.stringify({ + name: "paseo-managed-bridge", + private: true, + type: "module", + exports: { "./server": "./server.js" }, +}); + +export function openCodeConfigDirectory(env: NodeJS.ProcessEnv): string { + return ( + env.OPENCODE_CONFIG_DIR ?? + path.join(env.XDG_CONFIG_HOME ?? path.join(homedir(), ".config"), "opencode") + ); +} + +export async function hasManagedBridge(configDirectory: string): Promise { + const directory = path.join(configDirectory, "plugins", "paseo-managed-bridge"); + const [manifest, artifact] = await Promise.all([ + readFile(path.join(directory, "package.json"), "utf8").catch(() => ""), + readFile(path.join(directory, "server.js")).catch(() => undefined), + ]); + return isManagedPackage(manifest) && Boolean(artifact?.length); +} + +export async function provisionLocalBridge(input: { + configDirectory: string; + artifact: string; +}): Promise { + const directory = path.join(input.configDirectory, "plugins", "paseo-managed-bridge"); + await mkdir(path.dirname(directory), { recursive: true }); + let created = false; + try { + await mkdir(directory); + created = true; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + } + const manifest = path.join(directory, "package.json"); + if (created) await writeFileAtomic(manifest, PACKAGE); + else if (!isManagedPackage(await readManagedManifest(manifest))) + throw new Error(`Cannot install OpenCode bridge: ${directory} is not managed by Paseo`); + const artifact = await readFile(input.artifact); + const state = await readFile(path.join(path.dirname(input.artifact), "state.mjs")); + const stateTarget = path.join(directory, "state.mjs"); + const existingState = await readFile(stateTarget).catch(() => undefined); + if (!existingState) await writeFileAtomic(stateTarget, state); + else if (!existingState.equals(state)) + throw new Error(`Cannot update OpenCode bridge state module at ${stateTarget}`); + const target = path.join(directory, "server.js"); + const existing = await readFile(target).catch(() => undefined); + if (!existing?.equals(artifact)) await writeFileAtomic(target, artifact); +} + +function isManagedPackage(content: string): boolean { + let value: unknown; + try { + value = JSON.parse(content); + } catch { + return false; + } + if (!value || typeof value !== "object" || Array.isArray(value)) return false; + const manifest = value as Record; + if (!manifest.exports || typeof manifest.exports !== "object" || Array.isArray(manifest.exports)) + return false; + const exports = manifest.exports as Record; + return ( + manifest.name === "paseo-managed-bridge" && + manifest.private === true && + manifest.type === "module" && + exports["./server"] === "./server.js" + ); +} + +async function readManagedManifest(file: string): Promise { + for (let attempt = 0; attempt < 20; attempt++) { + try { + return await readFile(file, "utf8"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + await delay(25); + } + } + return ""; +} diff --git a/packages/server/src/server/agent/providers/opencode/v2/external-runtime.test.ts b/packages/server/src/server/agent/providers/opencode/v2/external-runtime.test.ts new file mode 100644 index 0000000000..f4f39f4aeb --- /dev/null +++ b/packages/server/src/server/agent/providers/opencode/v2/external-runtime.test.ts @@ -0,0 +1,180 @@ +import { createServer, type Server } from "node:http"; +import { createServer as createNetServer } from "node:net"; + +import { afterEach, describe, expect, test } from "vitest"; + +import { createTestLogger } from "../../../../../test-utils/test-logger.js"; +import { V2Runtime } from "./runtime.js"; +import { EXTERNAL_SERVER_PASSWORD_ENV, EXTERNAL_SERVER_URL_ENV } from "./external-server.js"; + +function listen(server: Server): Promise { + return new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + if (!address || typeof address === "string") { + reject(new Error("Test server did not expose a TCP address")); + return; + } + resolve(address.port); + }); + }); +} + +function close(server: Server): Promise { + return new Promise((resolve, reject) => { + server.close((error) => { + if (error) { + reject(error); + return; + } + resolve(); + }); + server.closeAllConnections(); + }); +} + +function reserveClosedPort(): Promise { + return new Promise((resolve, reject) => { + const server = createNetServer(); + server.once("error", reject); + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + if (!address || typeof address === "string") { + server.close(); + reject(new Error("Could not reserve a test port")); + return; + } + server.close((error) => { + if (error) { + reject(error); + return; + } + resolve(address.port); + }); + }); + }); +} + +describe("V2Runtime against an external server", () => { + let server: Server | undefined; + + afterEach(async () => { + if (server) await close(server); + server = undefined; + }); + + test("reuses the configured server and never spawns a local one", async () => { + const requests: Array<{ url: string | undefined; authorization: string | undefined }> = []; + server = createServer((request, response) => { + requests.push({ url: request.url, authorization: request.headers.authorization }); + if (request.url !== "/api/info") { + response.writeHead(404); + response.end(); + return; + } + response.writeHead(200, { "content-type": "application/json" }); + response.end(JSON.stringify({ version: "2.0.10", pid: 1, urls: [], paths: { tmp: "/tmp" } })); + }); + const port = await listen(server); + const runtime = new V2Runtime({ + logger: createTestLogger(), + externalServer: { url: `http://127.0.0.1:${port}`, password: "secret" }, + }); + + const first = await runtime.acquire(); + const second = await runtime.acquire(); + expect(first.client).toBe(second.client); + expect(requests).toEqual([ + { + url: "/api/info", + authorization: `Basic ${Buffer.from("opencode:secret").toString("base64")}`, + }, + ]); + + await first.release(); + await second.release(); + const refreshed = await runtime.acquire({ fresh: true }); + expect(refreshed.client).toBe(first.client); + await refreshed.release(); + await runtime.shutdown(); + expect(requests).toHaveLength(1); + }); + + test("selects the external server from provider environment", async () => { + const paths: Array = []; + server = createServer((request, response) => { + paths.push(request.url); + if (request.url !== "/api/info") { + response.writeHead(404); + response.end(); + return; + } + response.writeHead(200, { "content-type": "application/json" }); + response.end(JSON.stringify({ version: "2.0.10", pid: 1, urls: [], paths: { tmp: "/tmp" } })); + }); + const port = await listen(server); + const runtime = new V2Runtime({ + logger: createTestLogger(), + settings: { + env: { + [EXTERNAL_SERVER_URL_ENV]: `http://127.0.0.1:${port}`, + [EXTERNAL_SERVER_PASSWORD_ENV]: "", + }, + }, + }); + + const connection = await runtime.acquire(); + expect(paths).toEqual(["/api/info"]); + await connection.release(); + await runtime.shutdown(); + }); + + test("reports an unreachable configured server", async () => { + const port = await reserveClosedPort(); + const runtime = new V2Runtime({ + logger: createTestLogger(), + externalServer: { url: `http://127.0.0.1:${port}` }, + }); + + await expect(runtime.acquire()).rejects.toThrow( + `Cannot reach OpenCode v2 server at http://127.0.0.1:${port}`, + ); + await runtime.shutdown(); + }); + + test("rejects session configuration that requires process isolation", async () => { + const runtime = new V2Runtime({ + logger: createTestLogger(), + externalServer: { url: "http://127.0.0.1:1" }, + }); + await expect(runtime.acquire({ dedicated: true })).rejects.toThrow( + "require an isolated server", + ); + await runtime.shutdown(); + }); + + test("rejects provider process environment on an explicit server", async () => { + const runtime = new V2Runtime({ + logger: createTestLogger(), + externalServer: { url: "http://127.0.0.1:1" }, + settings: { env: { XDG_CONFIG_HOME: "/custom", PROVIDER_KEY: "secret" } }, + }); + await expect(runtime.acquire()).rejects.toThrow("XDG_CONFIG_HOME, PROVIDER_KEY"); + await runtime.shutdown(); + }); + + test("rejects an unsupported explicit server version", async () => { + server = createServer((_request, response) => { + response.writeHead(200, { "content-type": "application/json" }); + response.end(JSON.stringify({ version: "2.0.9", pid: 1, urls: [], paths: { tmp: "/tmp" } })); + }); + const port = await listen(server); + const runtime = new V2Runtime({ + logger: createTestLogger(), + externalServer: { url: `http://127.0.0.1:${port}` }, + }); + await expect(runtime.acquire()).rejects.toThrow("Unsupported OpenCode version 2.0.9"); + await runtime.shutdown(); + }); +}); diff --git a/packages/server/src/server/agent/providers/opencode/v2/external-server.test.ts b/packages/server/src/server/agent/providers/opencode/v2/external-server.test.ts new file mode 100644 index 0000000000..f9986215ad --- /dev/null +++ b/packages/server/src/server/agent/providers/opencode/v2/external-server.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, test } from "vitest"; + +import { + EXTERNAL_SERVER_PASSWORD_ENV, + EXTERNAL_SERVER_URL_ENV, + resolveExternalOpenCodeServer, +} from "./external-server.js"; + +describe("resolveExternalOpenCodeServer", () => { + test("returns undefined when no URL is configured", () => { + expect(resolveExternalOpenCodeServer(undefined)).toBeUndefined(); + expect(resolveExternalOpenCodeServer({ [EXTERNAL_SERVER_URL_ENV]: " " })).toBeUndefined(); + }); + + test("reads the URL and password and removes a trailing slash", () => { + expect( + resolveExternalOpenCodeServer({ + [EXTERNAL_SERVER_URL_ENV]: " http://127.0.0.1:4096/ ", + [EXTERNAL_SERVER_PASSWORD_ENV]: "secret", + }), + ).toEqual({ url: "http://127.0.0.1:4096", password: "secret" }); + }); + + test("omits an empty password", () => { + expect( + resolveExternalOpenCodeServer({ + [EXTERNAL_SERVER_URL_ENV]: "https://opencode.example.com", + [EXTERNAL_SERVER_PASSWORD_ENV]: "", + }), + ).toEqual({ url: "https://opencode.example.com" }); + }); + + test("preserves spaces in the password", () => { + expect( + resolveExternalOpenCodeServer({ + [EXTERNAL_SERVER_URL_ENV]: "https://opencode.example.com", + [EXTERNAL_SERVER_PASSWORD_ENV]: " secret ", + }), + ).toEqual({ url: "https://opencode.example.com", password: " secret " }); + }); + + test("rejects relative and non-HTTP URLs", () => { + expect(() => + resolveExternalOpenCodeServer({ [EXTERNAL_SERVER_URL_ENV]: "127.0.0.1:4096" }), + ).toThrow(`${EXTERNAL_SERVER_URL_ENV} must be an absolute URL, received "127.0.0.1:4096"`); + expect(() => + resolveExternalOpenCodeServer({ [EXTERNAL_SERVER_URL_ENV]: "unix:/tmp/opencode.sock" }), + ).toThrow( + `${EXTERNAL_SERVER_URL_ENV} must use http or https, received "unix:/tmp/opencode.sock"`, + ); + }); + + test("rejects credentials embedded in URLs", () => { + expect(() => + resolveExternalOpenCodeServer({ + [EXTERNAL_SERVER_URL_ENV]: "https://user:password@opencode.example.com", + }), + ).toThrow("must not contain credentials"); + }); +}); diff --git a/packages/server/src/server/agent/providers/opencode/v2/external-server.ts b/packages/server/src/server/agent/providers/opencode/v2/external-server.ts new file mode 100644 index 0000000000..c00b158ce3 --- /dev/null +++ b/packages/server/src/server/agent/providers/opencode/v2/external-server.ts @@ -0,0 +1,38 @@ +export const EXTERNAL_SERVER_URL_ENV = "PASEO_OPENCODE_SERVER_URL"; +export const EXTERNAL_SERVER_PASSWORD_ENV = "PASEO_OPENCODE_SERVER_PASSWORD"; + +export interface ExternalOpenCodeServer { + url: string; + password?: string; +} + +/** + * Reads the optional connection to a user-managed OpenCode v2 server from + * provider environment. When absent, Paseo keeps spawning its own server. + */ +export function resolveExternalOpenCodeServer( + env: Record | undefined, +): ExternalOpenCodeServer | undefined { + const rawUrl = env?.[EXTERNAL_SERVER_URL_ENV]?.trim(); + if (!rawUrl) return undefined; + + let url: URL; + try { + url = new URL(rawUrl); + } catch { + throw new Error(`${EXTERNAL_SERVER_URL_ENV} must be an absolute URL, received "${rawUrl}"`); + } + if (url.protocol !== "http:" && url.protocol !== "https:") { + throw new Error(`${EXTERNAL_SERVER_URL_ENV} must use http or https, received "${rawUrl}"`); + } + if (url.username || url.password) + throw new Error( + `${EXTERNAL_SERVER_URL_ENV} must not contain credentials; use ${EXTERNAL_SERVER_PASSWORD_ENV}`, + ); + + const password = env?.[EXTERNAL_SERVER_PASSWORD_ENV]; + return { + url: url.toString().replace(/\/$/, ""), + ...(password ? { password } : {}), + }; +} diff --git a/packages/server/src/server/agent/providers/opencode/v2/owned-runtime.test.ts b/packages/server/src/server/agent/providers/opencode/v2/owned-runtime.test.ts new file mode 100644 index 0000000000..d60535889b --- /dev/null +++ b/packages/server/src/server/agent/providers/opencode/v2/owned-runtime.test.ts @@ -0,0 +1,77 @@ +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { expect, test } from "vitest"; +import { createTestLogger } from "../../../../../test-utils/test-logger.js"; +import { OpenCodeBridge } from "../bridge.js"; +import { provisionLocalBridge } from "./bridge-provisioning.js"; +import { V2Runtime } from "./runtime.js"; + +test("an owned helper uses an installed bridge once and survives catalog refresh", async () => { + const root = await mkdtemp(path.join(tmpdir(), "paseo-owned-opencode-")); + const config = path.join(root, "config", "opencode"); + const script = path.join(root, "server.cjs"); + const record = path.join(root, "env.json"); + const bridge = new OpenCodeBridge({ paseoHome: root, logger: createTestLogger() }); + await bridge.start(); + const artifact = fileURLToPath(await bridge.materializeV2Plugin()); + await provisionLocalBridge({ + configDirectory: config, + artifact: path.join(artifact, "server.js"), + }); + await writeFile( + script, + ` + const http = require('node:http'); + require('node:fs').writeFileSync(${JSON.stringify(record)}, process.env.OPENCODE_CONFIG_CONTENT); + const server = http.createServer((_request, response) => { + response.writeHead(200, { 'content-type': 'application/json' }); + response.end(JSON.stringify({ version: '2.0.10', pid: process.pid, urls: [], paths: { tmp: '/tmp' } })); + }); + server.listen(0, '127.0.0.1', () => console.log('server listening on http://127.0.0.1:' + server.address().port)); + `, + ); + const runtime = new V2Runtime({ + logger: createTestLogger(), + bridge, + selection: { kind: "owned" }, + settings: { + command: { mode: "replace", argv: [process.execPath, script] }, + env: { XDG_CONFIG_HOME: path.join(root, "config"), OPENCODE_CONFIG_CONTENT: "{}" }, + }, + }); + try { + const first = await runtime.acquire(); + const pid = (await first.client.server.info()).pid; + expect(JSON.parse(await readFile(record, "utf8"))).toEqual({}); + await first.release(); + const refreshed = await runtime.acquire({ fresh: true }); + expect((await refreshed.client.server.info()).pid).toBe(pid); + await refreshed.release(); + } finally { + await runtime.shutdown(); + await bridge.close(); + await rm(root, { recursive: true, force: true }); + } +}, 15_000); + +test("reports a bridge port change that has not been applied", async () => { + const root = await mkdtemp(path.join(tmpdir(), "paseo-opencode-port-")); + const bridge = new OpenCodeBridge({ paseoHome: root, logger: createTestLogger() }); + await bridge.start(); + const actual = Number(new URL(bridge.sharedV2Connection().baseUrl).port); + const runtime = new V2Runtime({ + logger: createTestLogger(), + bridge, + selection: { kind: "explicit", server: { url: "http://127.0.0.1:1" } }, + settings: { env: { PASEO_OPENCODE_BRIDGE_PORT: actual === 1 ? "2" : "1" } }, + }); + try { + await expect(runtime.acquire()).rejects.toThrow("restart Paseo to apply the bridge port"); + } finally { + await runtime.shutdown(); + await bridge.close(); + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/packages/server/src/server/agent/providers/opencode/v2/runtime.ts b/packages/server/src/server/agent/providers/opencode/v2/runtime.ts index cab5544582..0fe830fe45 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/runtime.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/runtime.ts @@ -16,11 +16,25 @@ import type { ManagedProcessRegistry } from "../../../../managed-processes/manag import { resolveOpenCodeHomeDir } from "../paths.js"; import { OpenCodeHttpError } from "../http-error.js"; import { raceProviderRefreshAbort } from "../../../provider-refresh-deadline.js"; +import { resolveExternalOpenCodeServer, type ExternalOpenCodeServer } from "./external-server.js"; +import { selectOpenCodeService, type OpenCodeServiceSelection } from "./service-selection.js"; +import { bridgeBindings, connectSharedService } from "./shared-service.js"; +import { + hasManagedBridge, + openCodeConfigDirectory, + provisionLocalBridge, +} from "./bridge-provisioning.js"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import type { OpenCodeBridge } from "../bridge.js"; export interface V2Connection { client: V2Api; release(): Promise; retain(): V2Connection; + bindSession(sessionId: string, cwd: string): Promise; + unbindSession(sessionId: string, cwd: string): Promise; + refreshLocation(cwd: string, signal?: AbortSignal): Promise; readonly exited: Promise; } interface Generation { @@ -28,12 +42,17 @@ interface Generation { users: number; stop(): Promise; exited: Promise; + bindSession(sessionId: string, cwd: string): Promise; + unbindSession(sessionId: string, cwd: string): Promise; + refreshLocation(cwd: string, signal?: AbortSignal): Promise; } export interface V2RuntimeOptions { logger: Logger; settings?: ProviderRuntimeSettings; managedProcesses?: ManagedProcessRegistry; - decorateEnv?: (env: Record) => Promise>; + externalServer?: ExternalOpenCodeServer; + selection?: OpenCodeServiceSelection; + bridge?: OpenCodeBridge; } export interface V2RuntimeAcquireOptions { @@ -49,17 +68,36 @@ export class V2Runtime { private generations = new Set(); private starts = new Set>(); private closed = false; + private readonly selection: Promise; - constructor(private readonly options: V2RuntimeOptions) {} + constructor(private readonly options: V2RuntimeOptions) { + this.selection = options.selection + ? Promise.resolve(options.selection) + : selectOpenCodeService({ + explicit: + options.externalServer ?? + resolveExternalOpenCodeServer({ + ...globalThis.process.env, + ...options.settings?.env, + }), + env: options.settings?.env, + }); + } async acquire(input: V2RuntimeAcquireOptions = {}): Promise { if (this.closed) throw new Error("OpenCode runtime is closed"); input.signal?.throwIfAborted(); + this.assertBridgePort(); + const selection = await raceProviderRefreshAbort(input.signal, this.selection); let pending: Promise; - if (input.env || input.dedicated) { + if (selection.kind !== "owned") { + this.assertSharedConfiguration(input, selection); + this.current ??= this.startTracked(); + pending = this.current; + } else if (input.env || input.dedicated) { pending = this.startTracked(input.env); } else { - if (input.fresh || !this.current) this.current = this.startTracked(); + if (!this.current) this.current = this.startTracked(); pending = this.current; } let generation: Generation; @@ -97,6 +135,39 @@ export class V2Runtime { return connection; } + private assertBridgePort(): void { + const port = this.options.settings?.env?.PASEO_OPENCODE_BRIDGE_PORT; + if (!port || !this.options.bridge) return; + const actual = new URL(this.options.bridge.sharedV2Connection().baseUrl).port; + if (Number(port) !== Number(actual)) + throw new Error("PASEO_OPENCODE_BRIDGE_PORT changed; restart Paseo to apply the bridge port"); + } + + private assertSharedConfiguration( + input: V2RuntimeAcquireOptions, + selection: OpenCodeServiceSelection, + ): void { + const connectionEnv = new Set([ + "PASEO_OPENCODE_SERVER_URL", + "PASEO_OPENCODE_SERVER_PASSWORD", + "PASEO_OPENCODE_BRIDGE_URL", + "PASEO_OPENCODE_BRIDGE_PORT", + ]); + if (selection.kind === "discovered") { + connectionEnv.add("XDG_CONFIG_HOME"); + connectionEnv.add("XDG_STATE_HOME"); + connectionEnv.add("OPENCODE_CONFIG_DIR"); + } + const processOverrides = Object.keys(this.options.settings?.env ?? {}).filter( + (key) => !connectionEnv.has(key), + ); + if (input.env || input.dedicated || processOverrides.length) { + throw new Error( + `Custom OpenCode MCP servers or process environment require an isolated server and cannot be used with a shared OpenCode service${processOverrides.length ? `: ${processOverrides.join(", ")}` : ""}.`, + ); + } + } + private lease(generation: Generation, pending: Promise): V2Connection { if (this.closed || !this.generations.has(generation)) throw new Error("OpenCode helper server is no longer running"); @@ -107,7 +178,7 @@ export class V2Runtime { released = true; generation.users -= 1; if (generation.users !== 0) return; - if (this.current === pending) this.current = null; + if (this.current === pending) return; this.generations.delete(generation); await generation.stop(); }; @@ -115,6 +186,9 @@ export class V2Runtime { client: generation.client, release, retain: () => this.lease(generation, pending), + bindSession: generation.bindSession, + unbindSession: generation.unbindSession, + refreshLocation: generation.refreshLocation, exited: generation.exited, }; } @@ -146,6 +220,16 @@ export class V2Runtime { } private async start(env: Record = {}): Promise { + const selection = await this.selection; + if (selection.kind !== "owned") { + const generation: Generation = { + ...(await connectSharedService(selection, this.options)), + users: 0, + }; + this.generations.add(generation); + return generation; + } + const { settings, managedProcesses, logger } = this.options; const launch = await resolveProviderLaunch({ commandConfig: settings?.command, @@ -160,9 +244,20 @@ export class V2Runtime { ...settings?.env, ...env, }; - const decorated = this.options.decorateEnv - ? await this.options.decorateEnv(configured) - : decorateOpenCodeV2Env(configured, await materializeOpenCodeV2Plugin(resolvePaseoHome())); + const bridge = this.options.bridge; + const plugin = bridge + ? await bridge.materializeV2Plugin() + : await materializeOpenCodeV2Plugin(resolvePaseoHome()); + const globalConfig = openCodeConfigDirectory({ ...globalThis.process.env, ...configured }); + const managed = await hasManagedBridge(globalConfig); + if (managed && bridge) + await provisionLocalBridge({ + configDirectory: globalConfig, + artifact: path.join(fileURLToPath(plugin), "server.js"), + }); + const decorated = managed + ? configured + : decorateOpenCodeV2Env(configured, plugin, bridge ? {} : { mode: "structured-only" }); const args = [...launch.args, "serve", "--hostname", "127.0.0.1", "--port", "0"]; const process = spawnProcess(launch.command, args, { cwd, @@ -253,7 +348,13 @@ export class V2Runtime { }, }); await client.server.info({ signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())) }); - const generation: Generation = { client, users: 0, stop, exited }; + const generation: Generation = { + client, + users: 0, + stop, + exited, + ...bridgeBindings(client, bridge), + }; this.generations.add(generation); process.once("exit", () => { this.generations.delete(generation); diff --git a/packages/server/src/server/agent/providers/opencode/v2/service-selection.test.ts b/packages/server/src/server/agent/providers/opencode/v2/service-selection.test.ts new file mode 100644 index 0000000000..876582fb9c --- /dev/null +++ b/packages/server/src/server/agent/providers/opencode/v2/service-selection.test.ts @@ -0,0 +1,55 @@ +import { createServer } from "node:http"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { tmpdir } from "node:os"; +import { expect, test } from "vitest"; +import { selectOpenCodeService } from "./service-selection.js"; + +test("selects the registered service with its credential and ignores stale registration", async () => { + const directory = await mkdtemp(path.join(tmpdir(), "paseo-service-")); + const file = path.join(directory, "service.json"); + let requests = 0; + const server = createServer((request, response) => { + requests++; + if ( + request.headers.authorization !== `Basic ${Buffer.from("opencode:secret").toString("base64")}` + ) { + response.writeHead(401).end(); + return; + } + response.writeHead(200, { "Content-Type": "application/json" }); + response.end(JSON.stringify({ version: "2.0.10", pid: process.pid })); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("No test address"); + const url = `http://127.0.0.1:${address.port}`; + try { + await writeFile( + file, + JSON.stringify({ url, password: "secret", pid: process.pid, version: "2.0.10" }), + ); + expect(await selectOpenCodeService({ file })).toEqual({ + kind: "discovered", + server: { url, password: "secret" }, + }); + expect(requests).toBe(1); + expect( + await selectOpenCodeService({ file, explicit: { url: "http://explicit.test" } }), + ).toEqual({ kind: "explicit", server: { url: "http://explicit.test" } }); + expect(requests).toBe(1); + await writeFile(file, JSON.stringify({ url, password: "secret", pid: process.pid + 1 })); + expect(await selectOpenCodeService({ file })).toEqual({ kind: "owned" }); + } finally { + await new Promise((resolve, reject) => { + server.close((error) => { + if (error) { + reject(error); + return; + } + resolve(); + }); + }); + await rm(directory, { recursive: true, force: true }); + } +}); diff --git a/packages/server/src/server/agent/providers/opencode/v2/service-selection.ts b/packages/server/src/server/agent/providers/opencode/v2/service-selection.ts new file mode 100644 index 0000000000..eeb2cb0994 --- /dev/null +++ b/packages/server/src/server/agent/providers/opencode/v2/service-selection.ts @@ -0,0 +1,43 @@ +import { Service } from "@opencode/client/service"; +import { homedir, networkInterfaces } from "node:os"; +import path from "node:path"; +import type { ExternalOpenCodeServer } from "./external-server.js"; + +export type OpenCodeServiceSelection = + | { kind: "owned" } + | { kind: "explicit" | "discovered"; server: ExternalOpenCodeServer }; + +export async function selectOpenCodeService(input: { + explicit?: ExternalOpenCodeServer; + file?: string; + env?: Record; +}): Promise { + if (input.explicit) return { kind: "explicit", server: input.explicit }; + const state = + input.env?.XDG_STATE_HOME ?? + process.env.XDG_STATE_HOME ?? + path.join(homedir(), ".local", "state"); + const endpoint = await Service.discover({ + file: input.file ?? path.join(state, "opencode", "service.json"), + version: compatibleVersion, + }).catch(() => undefined); + if (!endpoint) return { kind: "owned" }; + if (!isLocalOpenCodeHost(new URL(endpoint.url).hostname)) return { kind: "owned" }; + return { + kind: "discovered", + server: { url: endpoint.url, ...(endpoint.auth ? { password: endpoint.auth.password } : {}) }, + }; +} + +export function isLocalOpenCodeHost(input: string): boolean { + const hostname = input.replace(/^\[|\]$/g, ""); + const localAddresses = Object.values(networkInterfaces()).flatMap((items) => + (items ?? []).map((item) => item.address), + ); + return ["localhost", "127.0.0.1", "::1", "0.0.0.0", "::", ...localAddresses].includes(hostname); +} + +export function compatibleVersion(version: string): boolean { + const match = /^2\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(version); + return Boolean(match && (Number(match[1]) > 0 || Number(match[2]) >= 10)); +} diff --git a/packages/server/src/server/agent/providers/opencode/v2/session.ts b/packages/server/src/server/agent/providers/opencode/v2/session.ts index f173ccb301..a167ec0713 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/session.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/session.ts @@ -146,6 +146,7 @@ export class OpenCodeV2Session implements AgentSession { } private async configureConnection() { const location = { directory: this.config.cwd }; + await this.connection.bindSession(this.id, this.config.cwd); await waitForLocationReady({ client: this.client, location, signal: this.abort.signal }); if (this.requiresPaseoPlugin) await awaitPaseoPlugin({ client: this.client, location, signal: this.abort.signal }); @@ -207,6 +208,11 @@ export class OpenCodeV2Session implements AgentSession { if (!this.acquire) throw new Error("OpenCode helper server exited"); await this.stream; await this.sync.catch(() => undefined); + await this.connection + .unbindSession(this.id, this.config.cwd) + .catch((error: unknown) => + this.logger.warn({ error }, "Could not unbind the OpenCode Paseo bridge"), + ); const next = await this.acquire(); if (this.closed) { await next.release(); @@ -386,6 +392,7 @@ export class OpenCodeV2Session implements AgentSession { } async startTurn(prompt: AgentPromptInput, options?: AgentRunOptions) { await this.reconnectIfExited(); + await this.connection.bindSession(this.id, this.config.cwd); return this.turns.startTurn(prompt, options); } steerActiveTurn(prompt: AgentPromptInput, options: SteerActiveTurnOptions): Promise { @@ -436,6 +443,7 @@ export class OpenCodeV2Session implements AgentSession { } } private async reconcileConnection() { + await this.connection.bindSession(this.id, this.config.cwd); // Session environments are process-local. Reapply this agent's snapshot before // reconciling a new connection, including event-stream reconnections. if (this.launchEnv) @@ -560,6 +568,11 @@ export class OpenCodeV2Session implements AgentSession { await this.stream; await this.reconnecting?.catch(() => undefined); await this.sync.catch(() => undefined); + await this.connection + .unbindSession(this.id, this.config.cwd) + .catch((error: unknown) => + this.logger.warn({ error }, "Could not unbind the OpenCode Paseo bridge"), + ); this.unbind?.(); try { if (!this.persist) await this.client.session.remove({ sessionID: this.id }); diff --git a/packages/server/src/server/agent/providers/opencode/v2/shared-bridge-plugin.mjs b/packages/server/src/server/agent/providers/opencode/v2/shared-bridge-plugin.mjs new file mode 100644 index 0000000000..4be98bfba9 --- /dev/null +++ b/packages/server/src/server/agent/providers/opencode/v2/shared-bridge-plugin.mjs @@ -0,0 +1,207 @@ +import { STRUCTURED_OUTPUT_TOOL } from "./structured-output-plugin.mjs"; + +// OpenCode owns this plugin for the lifetime of a location. Paseo supplies only +// live, per-session bindings over the authenticated OpenCode RPC channel. +export async function registerSharedBridge(context) { + const state = await import(new URL("./state.mjs", import.meta.url).href); + const { bindings, definitions } = state.stateFor(context.location); + const registrations = new Map(); + let updating = Promise.resolve(); + async function request(binding, pathname, body, allowMissing = false, signal) { + const requestSignal = body === undefined ? AbortSignal.timeout(5_000) : signal; + const response = await fetch(new URL(`/_internal/opencode${pathname}`, binding.baseUrl), { + method: body === undefined ? "GET" : "POST", + headers: { Authorization: `Bearer ${binding.token}`, "Content-Type": "application/json" }, + signal: requestSignal, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }); + if (allowMissing && response.status === 404) return null; + const payload = await response.json().catch(() => null); + if (!response.ok) { + const detail = formatErrorDetail(payload?.issues ?? payload?.details); + const message = payload?.error ?? `Paseo tool bridge returned HTTP ${response.status}`; + const error = new Error(detail ? `${message}: ${detail}` : message); + error.status = response.status; + if (detail) error.details = detail; + throw error; + } + return payload; + } + async function find(sessionID) { + const seen = new Set(); + while (sessionID && !seen.has(sessionID)) { + seen.add(sessionID); + const binding = bindings.get(sessionID); + if (binding) return { ...binding, sessionID }; + sessionID = (await context.session.get({ sessionID })).parentID; + } + return null; + } + async function install(binding) { + const manifest = await request(binding, "/tools"); + for (const definition of manifest.tools) await installDefinition(definition); + } + async function installDefinition(definition) { + const signature = JSON.stringify(definition); + const known = definitions.get(definition.name); + if (known && JSON.stringify(known) !== signature) + throw new Error(`Conflicting Paseo tool definition: ${definition.name}`); + const old = registrations.get(definition.name); + if (old) { + if (old.signature !== signature) + throw new Error(`Conflicting Paseo tool definition: ${definition.name}`); + return; + } + const registration = await context.tool.transform((editor) => { + editor.add({ + name: `paseo_${definition.name}`, + description: definition.description, + input: definition.inputSchema, + options: { codemode: false }, + async execute(input, call) { + const scope = await find(call.sessionID); + if (!scope) throw new Error("OpenCode session is not bound to a Paseo agent"); + const result = await request( + scope, + `/sessions/${encodeURIComponent(scope.sessionID)}/tools/${encodeURIComponent(definition.name)}`, + input, + false, + call.signal, + ); + return { + content: result.content.map(toOpenCodeContent), + metadata: { paseoTool: definition.name }, + }; + }, + }); + }); + registrations.set(definition.name, { signature, registration }); + definitions.set(definition.name, definition); + } + async function clearUnusedDefinitions() { + if (bindings.size) return; + await Promise.all( + [...registrations.values()].map(({ registration }) => registration.dispose()), + ); + registrations.clear(); + definitions.clear(); + } + // Reinstall live tools before this plugin generation is made visible. + // Definitions are kept in memory, so unavailable owners cannot delay reload. + for (const definition of definitions.values()) await installDefinition(definition); + const object = { type: "object", additionalProperties: true }; + const rpc = await context.rpc.register( + { + id: "paseo.bridge", + methods: { + bind: { input: object, output: object }, + unbind: { input: object, output: object }, + refresh: { input: object, output: object }, + }, + events: {}, + }, + { + bind: async (input) => { + if ( + typeof input.sessionID !== "string" || + typeof input.baseUrl !== "string" || + typeof input.token !== "string" + ) + throw new Error("Invalid Paseo bridge binding"); + const next = updating + .catch(() => undefined) + .then(async () => { + const previous = bindings.get(input.sessionID); + if ( + previous && + (previous.baseUrl !== input.baseUrl || previous.token !== input.token) + ) { + let active; + try { + active = await request( + previous, + `/sessions/${encodeURIComponent(input.sessionID)}/context`, + undefined, + true, + ); + } catch (error) { + // Refusal or rejected credentials mean this endpoint no longer + // serves the previous binding. Other failures are inconclusive. + if ( + error?.status !== 401 && + error?.cause?.code !== "ECONNREFUSED" && + error?.code !== "ConnectionRefused" + ) + throw error; + } + if (active) + return { error: "OpenCode session is already bound to another Paseo bridge" }; + bindings.delete(input.sessionID); + await clearUnusedDefinitions(); + } + await install(input); + bindings.set(input.sessionID, { baseUrl: input.baseUrl, token: input.token }); + return {}; + }); + updating = next; + return await next; + }, + unbind: async (input) => { + const next = updating + .catch(() => undefined) + .then(async () => { + const binding = bindings.get(input.sessionID); + if (binding && binding.token === input.token && binding.baseUrl === input.baseUrl) + bindings.delete(input.sessionID); + await clearUnusedDefinitions(); + return {}; + }); + updating = next; + await next; + return {}; + }, + refresh: async () => { + await context.provider.reload(); + await context.model.reload(); + await context.agent.reload(); + await context.command.reload(); + await context.skill.reload(); + return {}; + }, + }, + ); + const filter = await context.session.hook("context", async (input) => { + const binding = await find(input.sessionID); + const scope = + binding && + (await request(binding, `/sessions/${encodeURIComponent(binding.sessionID)}/context?tools`)); + const allowed = new Set((scope?.tools ?? []).map((name) => `paseo_${name}`)); + for (const name of Object.keys(input.tools)) { + if (name.startsWith("paseo_") && name !== STRUCTURED_OUTPUT_TOOL && !allowed.has(name)) + delete input.tools[name]; + } + }); + return async () => { + await filter.dispose(); + await rpc.dispose(); + await Promise.all( + [...registrations.values()].map(({ registration }) => registration.dispose()), + ); + }; +} + +function toOpenCodeContent(part) { + if (part.type === "image") + return { type: "file", uri: `data:${part.mimeType};base64,${part.data}`, mime: part.mimeType }; + return part; +} + +function formatErrorDetail(details) { + if (!Array.isArray(details)) return typeof details === "string" ? details : ""; + return details + .map((issue) => { + const path = Array.isArray(issue?.path) && issue.path.length ? issue.path.join(".") : "input"; + return `${path}: ${issue?.message ?? "Invalid value"}`; + }) + .join("; "); +} diff --git a/packages/server/src/server/agent/providers/opencode/v2/shared-bridge.test.ts b/packages/server/src/server/agent/providers/opencode/v2/shared-bridge.test.ts new file mode 100644 index 0000000000..c560fa6558 --- /dev/null +++ b/packages/server/src/server/agent/providers/opencode/v2/shared-bridge.test.ts @@ -0,0 +1,168 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { expect, test } from "vitest"; +import { z } from "zod"; +import { createTestLogger } from "../../../../../test-utils/test-logger.js"; +import { OpenCodeBridge } from "../bridge.js"; + +interface Binding { + sessionID: string; + baseUrl: string; + token: string; +} +interface TestTool { + name: string; + execute(input: { value: string }, call: { sessionID: string }): Promise; +} +interface TestContext { + sessionID: string; + tools: Record; + system: unknown[]; +} + +test("a shared plugin binds Paseo sessions without involving unrelated sessions", async () => { + const home = await mkdtemp(path.join(tmpdir(), "paseo-shared-bridge-")); + const bridge = new OpenCodeBridge({ paseoHome: home, logger: createTestLogger() }); + const tool = { name: "echo", description: "echo", inputSchema: { value: z.string() } }; + const tools = new Map([[tool.name, tool]]); + bridge.setManifestCatalog({ tools }); + await bridge.start(); + const unbind = bridge.bindSession({ + sessionId: "paseo", + env: {}, + tools: { + tools, + getTool: (name) => tools.get(name), + executeTool: async (_name, input) => ({ + content: [{ type: "text", text: String((input as { value: string }).value) }], + }), + }, + }); + expect(() => bridge.bindSession({ sessionId: "paseo", env: {} })).toThrow("already bound"); + try { + const plugin = { + package: await bridge.materializeV2Plugin(), + options: bridge.sharedV2Connection(), + }; + const module = await import( + pathToFileURL(path.join(fileURLToPath(plugin.package), "server.js")).href + ); + const installed = new Map(); + const hooks: Array<(input: TestContext) => Promise> = []; + const refreshed: string[] = []; + let structured = false; + let rpc: Record Promise> = {}; + const context = { + options: {}, + location: { directory: home }, + provider: { + reload: async () => { + refreshed.push("provider"); + }, + }, + model: { + reload: async () => { + refreshed.push("model"); + }, + }, + agent: { + reload: async () => { + refreshed.push("agent"); + }, + }, + command: { + reload: async () => { + refreshed.push("command"); + }, + }, + skill: { + reload: async () => { + refreshed.push("skill"); + }, + }, + rpc: { + register: async (_definition: unknown, handlers: typeof rpc) => { + rpc = handlers; + return { dispose: async () => {} }; + }, + }, + tool: { + transform: async (fn: (editor: { add(item: TestTool): void }) => void) => { + fn({ add: (item) => installed.set(item.name, item) }); + return { dispose: async () => {} }; + }, + }, + session: { + context: async () => + structured ? [{ type: "user", metadata: { paseoOutputSchema: { type: "string" } } }] : [], + get: async () => ({ parentID: "" }), + hook: async (_name: string, fn: (input: TestContext) => Promise) => { + hooks.push(fn); + return { dispose: async () => {} }; + }, + }, + }; + let dispose = await module.default.setup(context); + await rpc.bind({ sessionID: "paseo", ...plugin.options }); + await rpc.refresh({ sessionID: "paseo", ...plugin.options }); + expect(refreshed).toEqual(["provider", "model", "agent", "command", "skill"]); + await expect( + rpc.bind({ sessionID: "paseo", ...plugin.options, token: "another-daemon" }), + ).resolves.toEqual({ error: "OpenCode session is already bound to another Paseo bridge" }); + const own = { sessionID: "paseo", tools: { paseo_echo: {}, native: {} }, system: [] }; + for (const hook of hooks) await hook(own); + expect(Object.keys(own.tools)).toEqual(["paseo_echo", "native"]); + expect( + await installed.get("paseo_echo")!.execute({ value: "ok" }, { sessionID: "paseo" }), + ).toMatchObject({ content: [{ type: "text", text: "ok" }] }); + await dispose(); + hooks.length = 0; + installed.clear(); + dispose = await module.default.setup(context); + const afterReload = { sessionID: "paseo", tools: { paseo_echo: {}, native: {} }, system: [] }; + for (const hook of hooks) await hook(afterReload); + expect(Object.keys(afterReload.tools)).toEqual(["paseo_echo", "native"]); + expect( + await installed.get("paseo_echo")!.execute({ value: "reloaded" }, { sessionID: "paseo" }), + ).toMatchObject({ content: [{ type: "text", text: "reloaded" }] }); + await bridge.close(); + await dispose(); + hooks.length = 0; + installed.clear(); + dispose = await module.default.setup(context); + const unrelated = { sessionID: "other", tools: { paseo_echo: {}, native: {} }, system: [] }; + for (const hook of hooks) await hook(unrelated); + expect(Object.keys(unrelated.tools)).toEqual(["native"]); + structured = true; + const structuredOnly = { + sessionID: "other", + tools: { paseo_structured_output: {} }, + system: [], + }; + for (const hook of hooks) await hook(structuredOnly); + expect(Object.keys(structuredOnly.tools)).toEqual(["paseo_structured_output"]); + const restarted = new OpenCodeBridge({ + paseoHome: home, + logger: createTestLogger(), + port: Number(new URL(plugin.options.baseUrl).port), + }); + restarted.setManifestCatalog({ tools }); + await restarted.start(); + const releaseRestarted = restarted.bindSession({ sessionId: "paseo", env: {} }); + try { + await expect( + rpc.bind({ sessionID: "paseo", ...restarted.sharedV2Connection() }), + ).resolves.toEqual({}); + } finally { + releaseRestarted(); + await restarted.close(); + } + await dispose(); + } finally { + unbind(); + await bridge.close(); + await rm(home, { recursive: true, force: true }); + } +}); diff --git a/packages/server/src/server/agent/providers/opencode/v2/shared-service.ts b/packages/server/src/server/agent/providers/opencode/v2/shared-service.ts new file mode 100644 index 0000000000..26fcbb7d26 --- /dev/null +++ b/packages/server/src/server/agent/providers/opencode/v2/shared-service.ts @@ -0,0 +1,192 @@ +import { OpenCode } from "@opencode/client"; +import { mkdir } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import type { Logger } from "pino"; +import type { ProviderRuntimeSettings } from "../../../provider-launch-config.js"; +import type { OpenCodeBridge } from "../bridge.js"; +import { OpenCodeHttpError } from "../http-error.js"; +import { resolveOpenCodeHomeDir } from "../paths.js"; +import { openCodeConfigDirectory, provisionLocalBridge } from "./bridge-provisioning.js"; +import { awaitPaseoPlugin } from "./readiness.js"; +import { + compatibleVersion, + isLocalOpenCodeHost, + type OpenCodeServiceSelection, +} from "./service-selection.js"; +import type { V2Api } from "./api.js"; + +interface SharedServiceOptions { + logger: Logger; + settings?: ProviderRuntimeSettings; + bridge?: OpenCodeBridge; +} + +export interface SharedService { + client: V2Api; + exited: Promise; + stop(): Promise; + bindSession(sessionId: string, cwd: string): Promise; + unbindSession(sessionId: string, cwd: string): Promise; + refreshLocation(cwd: string, signal?: AbortSignal): Promise; +} + +export async function connectSharedService( + selection: Extract, + options: SharedServiceOptions, +): Promise { + const server = selection.server; + const { logger } = options; + const lifetime = new AbortController(); + const closed = new Error(`OpenCode external server connection closed (${server.url})`); + let resolveExited!: (error: Error) => void; + const exited = new Promise((resolve) => { + resolveExited = resolve; + }); + const authorization = server.password + ? `Basic ${Buffer.from(`opencode:${server.password}`).toString("base64")}` + : undefined; + const client = OpenCode.make({ + baseUrl: server.url, + ...(authorization ? { headers: { Authorization: authorization } } : {}), + fetch: async (request, init) => { + const signal = init?.signal + ? AbortSignal.any([init.signal, lifetime.signal]) + : lifetime.signal; + const response = await fetch(request, { ...init, signal }); + const html = response.headers.get("content-type")?.includes("text/html") ?? false; + if (!response.ok || html) { + const requestUrl = request instanceof Request ? request.url : String(request); + throw new OpenCodeHttpError(new URL(requestUrl).pathname, response.status, html); + } + return response; + }, + }); + let info: Awaited>; + try { + info = await client.server.info({ + signal: AbortSignal.any([lifetime.signal, AbortSignal.timeout(30_000)]), + }); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + throw new Error(`Cannot reach OpenCode v2 server at ${server.url}: ${message}`, { + cause: error, + }); + } + if (!compatibleVersion(info.version)) + throw new Error( + `Unsupported OpenCode version ${info.version}; version 2.0.10 or newer is required`, + ); + const bridge = options.bridge; + const pluginDirectory = bridge ? fileURLToPath(await bridge.materializeV2Plugin()) : undefined; + if (selection.kind === "discovered" && pluginDirectory) { + const env = { ...globalThis.process.env, ...options.settings?.env }; + const configDirectory = openCodeConfigDirectory(env); + const home = resolveOpenCodeHomeDir(); + await mkdir(home, { recursive: true }); + const entries = await client.config.get({ location: { directory: home } }); + if ( + !entries.some( + (entry) => + entry.type === "directory" && path.resolve(entry.path) === path.resolve(configDirectory), + ) + ) + throw new Error( + `OpenCode service does not use the expected configuration directory ${configDirectory}; configure the bridge on that service explicitly`, + ); + await provisionLocalBridge({ + configDirectory, + artifact: path.join(pluginDirectory, "server.js"), + }); + } + const advertised = + options.settings?.env?.PASEO_OPENCODE_BRIDGE_URL ?? + globalThis.process.env.PASEO_OPENCODE_BRIDGE_URL; + validateBridgeAddress(selection, bridge, advertised); + const generation: SharedService = { + client, + stop: async () => { + if (lifetime.signal.aborted) return; + lifetime.abort(closed); + resolveExited(closed); + }, + exited, + ...bridgeBindings(client, bridge, advertised, pluginDirectory), + }; + logger.info({ url: server.url }, "Using existing OpenCode v2 server"); + return generation; +} + +function validateBridgeAddress( + selection: Extract, + bridge: OpenCodeBridge | undefined, + advertised: string | undefined, +): void { + if (advertised) { + let bridgeUrl: URL; + try { + bridgeUrl = new URL(advertised); + } catch { + throw new Error("PASEO_OPENCODE_BRIDGE_URL must be an absolute HTTP or HTTPS URL"); + } + if (bridgeUrl.protocol !== "http:" && bridgeUrl.protocol !== "https:") + throw new Error("PASEO_OPENCODE_BRIDGE_URL must be an absolute HTTP or HTTPS URL"); + } + const hostname = new URL(selection.server.url).hostname; + if (bridge && selection.kind === "explicit" && !advertised && !isLocalOpenCodeHost(hostname)) + throw new Error( + "Remote OpenCode requires PASEO_OPENCODE_BRIDGE_URL pointing to a reachable Paseo bridge tunnel and the Paseo plugin installed on the server", + ); +} + +export function bridgeBindings( + client: ReturnType, + bridge: OpenCodeBridge | undefined, + advertised?: string, + pluginDirectory?: string, +): Pick { + return { + bindSession: async (sessionId, cwd) => { + if (!bridge) return; + const location = { directory: cwd }; + let result: Awaited>; + try { + await awaitPaseoPlugin({ client, location }); + result = await client.rpc.call({ + location, + rpcID: "paseo.bridge", + method: "bind", + input: { sessionID: sessionId, ...bridge.sharedV2Connection(advertised) }, + }); + } catch (error) { + throw new Error( + `Cannot connect the Paseo tool bridge to OpenCode. Install the plugin from ${pluginDirectory ?? "Paseo's runtime directory"} and configure a reachable bridge URL: ${error instanceof Error ? error.message : String(error)}`, + { cause: error }, + ); + } + if (result.output && typeof result.output === "object" && "error" in result.output) + throw new Error(String(result.output.error)); + }, + unbindSession: async (sessionId, cwd) => { + if (bridge) + await client.rpc.call( + { + location: { directory: cwd }, + rpcID: "paseo.bridge", + method: "unbind", + input: { sessionID: sessionId, ...bridge.sharedV2Connection(advertised) }, + }, + { signal: AbortSignal.timeout(2_000) }, + ); + }, + refreshLocation: async (cwd, signal) => { + if (!bridge) return; + const location = { directory: cwd }; + await awaitPaseoPlugin({ client, location, signal }); + await client.rpc.call( + { location, rpcID: "paseo.bridge", method: "refresh", input: {} }, + { signal }, + ); + }, + }; +} diff --git a/packages/server/src/server/agent/providers/opencode/v2/state.mjs b/packages/server/src/server/agent/providers/opencode/v2/state.mjs new file mode 100644 index 0000000000..858be8f14a --- /dev/null +++ b/packages/server/src/server/agent/providers/opencode/v2/state.mjs @@ -0,0 +1,11 @@ +// OpenCode reloads the plugin entry point independently from this module. +// Keep live bindings and tool definitions in memory across those reloads. +const locations = new Map(); + +export function stateFor(location) { + const key = JSON.stringify([location.directory, location.workspaceID ?? null]); + if (!locations.has(key)) { + locations.set(key, { bindings: new Map(), definitions: new Map() }); + } + return locations.get(key); +} diff --git a/packages/server/src/server/daemon-e2e/opencode-initial-prompt-wait.real.e2e.test.ts b/packages/server/src/server/daemon-e2e/opencode-initial-prompt-wait.real.e2e.test.ts index e03c66bca0..db278d0249 100644 --- a/packages/server/src/server/daemon-e2e/opencode-initial-prompt-wait.real.e2e.test.ts +++ b/packages/server/src/server/daemon-e2e/opencode-initial-prompt-wait.real.e2e.test.ts @@ -46,7 +46,7 @@ describe("daemon E2E (real opencode) - initial prompt wait", () => { } }); - test("waitForFinish does not resolve before an initial prompt using opencode/big-pickle actually completes", async () => { + test("waitForFinish does not resolve before an OpenCode initial prompt completes", async () => { const cwd = tmpCwd(); const { client, daemon } = await createHarness(); diff --git a/packages/server/src/server/daemon-e2e/real-provider-test-config.ts b/packages/server/src/server/daemon-e2e/real-provider-test-config.ts index e54b781e65..e15c618fbf 100644 --- a/packages/server/src/server/daemon-e2e/real-provider-test-config.ts +++ b/packages/server/src/server/daemon-e2e/real-provider-test-config.ts @@ -26,7 +26,7 @@ const PI_AUTH_CONFIG_PATH = join(homedir(), ".pi", "agent", "auth.json"); const CODEX_AUTH_CONFIG_PATH = join(homedir(), ".codex", "auth.json"); const CLAUDE_REAL_TEST_MODEL = "haiku"; const CODEX_REAL_TEST_MODEL = "~openai/gpt-latest"; -const OPENCODE_REAL_TEST_MODEL = "openrouter/google/gemini-2.5-flash-lite"; +const OPENCODE_REAL_TEST_MODEL = "openrouter/google/gemini-3.5-flash-lite"; const PI_OPENROUTER_REAL_TEST_MODEL = "openrouter/google/gemini-2.5-flash-lite"; const PI_CODEX_REAL_TEST_MODEL = "openai-codex/gpt-5.4"; const OMP_OPENROUTER_REAL_TEST_MODEL = "openrouter/google/gemini-2.5-flash-lite"; From 1008e9fffc20fc809d5d1023d43642b39df19c39 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sat, 31 Oct 2026 19:25:16 +0700 Subject: [PATCH 145/173] Insert suggested commands into the composer (#8371) * feat(composer): insert suggested commands into drafts * fix(composer): close suggestions after command insertion * fix(composer): place caret after inserted commands --- .../e2e/browser/composer-autocomplete.spec.ts | 56 ++++++- .../cache/index.ts} | 48 ++++++ packages/app/src/agent-commands/index.tsx | 99 +++++++++++ .../query.test.ts} | 52 +++++- .../use-query.test.ts} | 12 +- .../use-query.ts} | 36 +++- .../app/src/components/markdown/images.ts | 10 +- .../src/components/markdown/renderer.test.ts | 24 +++ .../app/src/components/markdown/renderer.tsx | 39 +++-- .../app/src/components/markdown/source.ts | 18 +- packages/app/src/components/message.tsx | 1 + .../app/src/composer/draft/input-draft.ts | 2 +- .../composer/editing-session/index.test.ts | 25 +++ .../src/composer/editing-session/index.tsx | 19 +++ packages/app/src/composer/index.tsx | 2 +- packages/app/src/composer/input/input.tsx | 10 ++ packages/app/src/data/providers-snapshot.ts | 2 +- packages/app/src/data/push-router.ts | 20 ++- packages/app/src/data/query.ts | 4 +- .../app/src/git/checkout-status-cache.test.ts | 2 +- packages/app/src/git/checkout-status-cache.ts | 2 +- .../app/src/hooks/use-agent-autocomplete.ts | 6 +- .../src/hooks/use-providers-snapshot.test.ts | 155 +++++++++++++++++- packages/app/src/panels/agent-panel.tsx | 35 +++- .../provider-selection/provider-selection.ts | 2 +- 25 files changed, 626 insertions(+), 55 deletions(-) rename packages/app/src/{hooks/agent-commands-query.ts => agent-commands/cache/index.ts} (54%) create mode 100644 packages/app/src/agent-commands/index.tsx rename packages/app/src/{hooks/agent-commands-query.test.ts => agent-commands/query.test.ts} (51%) rename packages/app/src/{hooks/use-agent-commands-query.test.ts => agent-commands/use-query.test.ts} (82%) rename packages/app/src/{hooks/use-agent-commands-query.ts => agent-commands/use-query.ts} (70%) diff --git a/packages/app/e2e/browser/composer-autocomplete.spec.ts b/packages/app/e2e/browser/composer-autocomplete.spec.ts index d83046d8b2..f40b51304b 100644 --- a/packages/app/e2e/browser/composer-autocomplete.spec.ts +++ b/packages/app/e2e/browser/composer-autocomplete.spec.ts @@ -1,5 +1,9 @@ import { expect, test, type Page } from "../support/fixtures"; -import { composerLocator, expectComposerVisible } from "../support/helpers/composer"; +import { + attachFileFromMenu, + composerLocator, + expectComposerVisible, +} from "../support/helpers/composer"; import { openAgentRoute, seedMockAgentWorkspace, @@ -365,6 +369,56 @@ function expectPopoverDoesNotDisappearAfterFirstVisible(frames: PopoverFrame[]): } test.describe("Composer autocomplete", () => { + test("inserts suggested commands from assistant messages without sending", async ({ page }) => { + const requests = recordCommandRequestsByAgentId(page); + const session = await seedMockAgentWorkspace({ + repoPrefix: "suggested-command-", + title: "Suggested commands", + initialPrompt: "Suggest `/mock` without running it", + featureValues: { mockAssistantResponse: "Try `/mock` or [Run mock](/mock)." }, + }); + try { + await openAgentRoute(page, session); + const message = page.getByTestId("assistant-message").filter({ hasText: "Run mock" }); + await expect(message).toBeVisible(); + await expect(page.getByTestId("user-message").getByRole("link")).toHaveCount(0); + await expect.poll(() => requests.length).toBe(1); + await attachFileFromMenu(page, { + name: "note.txt", + mimeType: "text/plain", + buffer: Buffer.from("attachment"), + }); + await expect(page.getByTestId("composer-file-attachment-pill")).toContainText("note.txt"); + await message.getByRole("link", { name: "/mock", exact: true }).click(); + await expect(composerLocator(page)).toHaveValue("/mock "); + await expect( + page.getByTestId("composer-autocomplete-popover").filter({ visible: true }), + ).toHaveCount(0); + await expect(composerLocator(page)).toBeFocused(); + await message.getByRole("link", { name: "Run mock" }).click(); + await expect(composerLocator(page)).toHaveValue("/mock /mock "); + await expect( + page.getByTestId("composer-autocomplete-popover").filter({ visible: true }), + ).toHaveCount(0); + await expect(composerLocator(page)).toBeFocused(); + await expect(page.getByTestId("composer-file-attachment-pill")).toContainText("note.txt"); + await composerLocator(page).fill("draft"); + await composerLocator(page).evaluate((element: HTMLTextAreaElement) => + element.setSelectionRange(0, 0), + ); + await message.getByRole("link", { name: "/mock", exact: true }).click(); + await composerLocator(page).pressSequentially("argument"); + await expect(composerLocator(page)).toHaveValue("draft /mock argument"); + await composerLocator(page).fill("/"); + await expect( + page.getByTestId("composer-autocomplete-popover").filter({ visible: true }), + ).toContainText("/mock"); + expect(requests).toHaveLength(1); + } finally { + await session.cleanup(); + } + }); + test("keeps New workspace off the running-agent command list before a project is chosen", async ({ page, }) => { diff --git a/packages/app/src/hooks/agent-commands-query.ts b/packages/app/src/agent-commands/cache/index.ts similarity index 54% rename from packages/app/src/hooks/agent-commands-query.ts rename to packages/app/src/agent-commands/cache/index.ts index 276c0fd9ba..474491f297 100644 --- a/packages/app/src/hooks/agent-commands-query.ts +++ b/packages/app/src/agent-commands/cache/index.ts @@ -1,8 +1,16 @@ import type { QueryClient } from "@tanstack/react-query"; import type { AgentProvider } from "@getpaseo/protocol/agent-types"; +import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types"; +import equal from "fast-deep-equal"; import { normalizeWorkspacePath } from "@/utils/workspace-identity"; export const AGENT_COMMANDS_QUERY_ROOT = "agentCommands"; +export const sessionCommandQueryPolicy = { + staleTime: 600_000, + gcTime: 1_800_000, + refetchOnMount: true, + refetchOnWindowFocus: false, +} as const; export interface AgentCommandsDraftConfig { provider: AgentProvider; @@ -21,6 +29,46 @@ export function agentCommandsQueryRoot(serverId: string) { return [AGENT_COMMANDS_QUERY_ROOT, serverId] as const; } +/** Snapshot announcements contain provider metadata, not command catalogs. Ignore initial + * discovery and unrelated providers; explicit refresh still invalidates every catalog. */ +export function invalidateCommandsForProviderChange(input: { + queryClient: QueryClient; + serverId: string; + cwd: string | null; + previous: readonly ProviderSnapshotEntry[] | undefined; + current: readonly ProviderSnapshotEntry[]; +}): Promise { + const previous = new Map((input.previous ?? []).map((entry) => [entry.provider, entry])); + const current = new Map(input.current.map((entry) => [entry.provider, entry])); + const relevant = (entry: ProviderSnapshotEntry | undefined) => + entry && { + status: entry.status, + enabled: entry.enabled, + source: entry.source, + models: entry.models, + modes: entry.modes, + defaultModeId: entry.defaultModeId, + }; + return input.queryClient.invalidateQueries({ + queryKey: agentCommandsQueryRoot(input.serverId), + predicate: (query) => { + const isDraft = query.queryKey[2] === "draft"; + const provider = + query.meta?.agentCommandProvider ?? (isDraft ? query.queryKey[6] : undefined); + const cwd = query.meta?.agentCommandCwd ?? (isDraft ? query.queryKey[4] : undefined); + if (input.cwd && typeof cwd === "string" && normalizeAgentCommandsCwd(cwd) !== input.cwd) + return false; + if (typeof provider !== "string") return false; + const before = previous.get(provider); + const after = current.get(provider); + if (!before) return after?.status === "ready" && query.state.status === "error"; + if (before.status !== "ready") + return after?.status === "ready" && query.state.status === "error"; + return !equal(relevant(before), relevant(after)); + }, + }); +} + export function sessionAgentCommandsQueryKey(input: { serverId: string; agentId: string }) { return [...agentCommandsQueryRoot(input.serverId), "session", input.agentId] as const; } diff --git a/packages/app/src/agent-commands/index.tsx b/packages/app/src/agent-commands/index.tsx new file mode 100644 index 0000000000..23d5a61e5f --- /dev/null +++ b/packages/app/src/agent-commands/index.tsx @@ -0,0 +1,99 @@ +import { createContext, useCallback, useContext, useMemo, type ReactNode } from "react"; +import { useQueryClient } from "@tanstack/react-query"; +import type { ComposerEditingSession } from "@/composer/editing-session"; +import { agentCommandsQueryKey } from "./cache"; +import { + useAgentCommandsQuery, + type AgentSlashCommand, + type DraftCommandConfig, +} from "./use-query"; + +export type { + AgentSlashCommand, + DraftCommandConfig, + DraftCommandTarget, + AgentCommandsClient, +} from "./use-query"; +export { fetchAgentCommands } from "./use-query"; + +type CommandQuery = ReturnType; +const QueryContext = createContext(null); +export interface CommandHints { + names: ReadonlySet; + insert(command: string): void; +} +const HintsContext = createContext(null); + +function useLiveAgentCommands() { + return useContext(QueryContext); +} +export function useAutocompleteCommands(input: { + serverId: string; + agentId: string; + enabled: boolean; + draftConfig?: DraftCommandConfig; +}) { + const live = useLiveAgentCommands(); + const fallback = useAgentCommandsQuery({ + serverId: input.serverId, + agentId: input.agentId, + enabled: !live && input.enabled, + draftConfig: input.draftConfig, + }); + return live ?? fallback; +} +export function useAgentCommandHints() { + return useContext(HintsContext); +} +export function matchCommandLink( + url: string, + sourceType: "markdown" | "text" | "inline-code" | undefined, + names: ReadonlySet, +): string | null { + return (sourceType === "markdown" || sourceType === "inline-code") && + url.startsWith("/") && + names.has(url.slice(1)) + ? url + : null; +} + +export function AgentCommandsProvider({ + serverId, + agentId, + editingSession, + enabled, + children, +}: { + serverId: string; + agentId: string; + editingSession: ComposerEditingSession; + enabled: boolean; + children: ReactNode; +}) { + const query = useAgentCommandsQuery({ serverId, agentId, enabled }); + const queryClient = useQueryClient(); + const namesKey = JSON.stringify( + [...new Set(query.commands.map((command) => command.name))].sort(), + ); + const names = useMemo>( + () => new Set(JSON.parse(namesKey) as string[]), + [namesKey], + ); + const insert = useCallback( + (token: string) => { + const commands = queryClient.getQueryData( + agentCommandsQueryKey({ serverId, agentId }), + ); + if (token.startsWith("/") && commands?.some((command) => `/${command.name}` === token)) { + editingSession.insertCommand(token); + } + }, + [agentId, editingSession, queryClient, serverId], + ); + const hints = useMemo(() => ({ names, insert }), [names, insert]); + return ( + + {children} + + ); +} diff --git a/packages/app/src/hooks/agent-commands-query.test.ts b/packages/app/src/agent-commands/query.test.ts similarity index 51% rename from packages/app/src/hooks/agent-commands-query.test.ts rename to packages/app/src/agent-commands/query.test.ts index e8d8ee0b94..33b55b4464 100644 --- a/packages/app/src/hooks/agent-commands-query.test.ts +++ b/packages/app/src/agent-commands/query.test.ts @@ -1,11 +1,61 @@ import { describe, expect, it } from "vitest"; +import { QueryClient, QueryObserver } from "@tanstack/react-query"; +import { fetchQueryOptions } from "@/data/query"; import { agentCommandsQueryKey, agentCommandsQueryRoot, draftAgentCommandsQueryKey, normalizeAgentCommandsCwd, sessionAgentCommandsQueryKey, -} from "./agent-commands-query"; + sessionCommandQueryPolicy, +} from "./cache"; + +it("reuses fresh commands and keeps stale commands during a shared refresh and failure", async () => { + const client = new QueryClient({ defaultOptions: { queries: { gcTime: 300_000 } } }); + const key = sessionAgentCommandsQueryKey({ serverId: "s", agentId: "a" }); + let calls = 0; + let fail = false; + let resolveRefresh: (value: string[]) => void = () => {}; + const refresh = new Promise((resolve) => { + resolveRefresh = resolve; + }); + const options = fetchQueryOptions({ + ...sessionCommandQueryPolicy, + staleTimeMs: sessionCommandQueryPolicy.staleTime, + dataShape: "value", + queryKey: key, + retry: false, + queryFn: async () => { + calls++; + if (fail) throw new Error("offline"); + return refresh; + }, + }); + client.setQueryData(key, ["old"]); + const fresh = new QueryObserver(client, options); + const unsubscribeFresh = fresh.subscribe(() => {}); + expect(calls).toBe(0); + unsubscribeFresh(); + client.setQueryData(key, ["old"], { updatedAt: 1 }); + const first = new QueryObserver(client, options); + const second = new QueryObserver(client, options); + const unsubscribeFirst = first.subscribe(() => {}); + const unsubscribeSecond = second.subscribe(() => {}); + expect(calls).toBe(1); + expect(first.getCurrentResult().data).toEqual(["old"]); + expect(client.getQueryCache().find({ queryKey: key })?.gcTime).toBe(1_800_000); + resolveRefresh(["new"]); + await refresh; + await first.refetch({ cancelRefetch: false }); + expect(second.getCurrentResult().data).toEqual(["new"]); + fail = true; + await client.invalidateQueries({ queryKey: key }); + expect(first.getCurrentResult().data).toEqual(["new"]); + expect(first.getCurrentResult().isError).toBe(true); + unsubscribeFirst(); + unsubscribeSecond(); + client.clear(); +}); describe("agent command query keys", () => { it("shares draft commands across draft tabs with the same provider setup", () => { diff --git a/packages/app/src/hooks/use-agent-commands-query.test.ts b/packages/app/src/agent-commands/use-query.test.ts similarity index 82% rename from packages/app/src/hooks/use-agent-commands-query.test.ts rename to packages/app/src/agent-commands/use-query.test.ts index 87f5919da8..db14491923 100644 --- a/packages/app/src/hooks/use-agent-commands-query.test.ts +++ b/packages/app/src/agent-commands/use-query.test.ts @@ -1,9 +1,5 @@ import { describe, expect, it } from "vitest"; -import { - type AgentCommandsClient, - type DraftCommandConfig, - fetchAgentCommands, -} from "./use-agent-commands-query"; +import { type AgentCommandsClient, type DraftCommandConfig, fetchAgentCommands } from "./use-query"; type ListCommands = AgentCommandsClient["listCommands"]; type ListCommandsResult = Awaited>; @@ -38,6 +34,12 @@ function commandsPayload(commands: ListCommandsResult["commands"]): ListCommands } describe("fetchAgentCommands", () => { + it("rejects a discovery error so a previous catalog is retained", async () => { + const client = createClient({ ...commandsPayload([]), error: "provider unavailable" }); + await expect(fetchAgentCommands({ client, agentId: "agent-1" })).rejects.toThrow( + "provider unavailable", + ); + }); it("loads commands for a draft composer without an agent id", async () => { const client = createClient( commandsPayload([{ name: "compact", description: "Compact context", argumentHint: "" }]), diff --git a/packages/app/src/hooks/use-agent-commands-query.ts b/packages/app/src/agent-commands/use-query.ts similarity index 70% rename from packages/app/src/hooks/use-agent-commands-query.ts rename to packages/app/src/agent-commands/use-query.ts index eddc0ab02b..000e6e8057 100644 --- a/packages/app/src/hooks/use-agent-commands-query.ts +++ b/packages/app/src/agent-commands/use-query.ts @@ -1,12 +1,15 @@ -import { useQuery } from "@tanstack/react-query"; +import { useFetchQuery } from "@/data/query"; import { useTranslation } from "react-i18next"; import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; import { useRetainedPanelActive } from "@/components/retained-panel"; +import { useSessionStore } from "@/stores/session-store"; +import { useShallow } from "zustand/shallow"; import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime"; -import { agentCommandsQueryKey, type AgentCommandsDraftConfig } from "@/hooks/agent-commands-query"; - -const DRAFT_COMMANDS_STALE_TIME = Number.POSITIVE_INFINITY; -const SESSION_COMMANDS_STALE_TIME = 60_000; +import { + agentCommandsQueryKey, + sessionCommandQueryPolicy, + type AgentCommandsDraftConfig, +} from "./cache"; export interface AgentSlashCommand { name: string; @@ -41,6 +44,7 @@ export async function fetchAgentCommands(input: { agentId: input.agentId, draftConfig: input.draftConfig, }); + if (response.error) throw new Error(response.error); return response.commands as AgentSlashCommand[]; } @@ -62,8 +66,16 @@ export function useAgentCommandsQuery({ const queryEnabled = enabled && retainedPanelActive; const client = useHostRuntimeClient(serverId); const isConnected = useHostRuntimeIsConnected(serverId); + const { provider, cwd } = useSessionStore( + useShallow((state) => { + const agent = + state.sessions[serverId]?.agents?.get(agentId) ?? + state.sessions[serverId]?.agentDetails?.get(agentId); + return { provider: agent?.provider, cwd: agent?.cwd }; + }), + ); - const query = useQuery({ + const query = useFetchQuery({ queryKey: agentCommandsQueryKey({ serverId, agentId, draftConfig }), queryFn: async () => { if (!client) { @@ -72,7 +84,15 @@ export function useAgentCommandsQuery({ return fetchAgentCommands({ client, agentId, draftConfig }); }, enabled: queryEnabled && !!client && isConnected && (!!agentId || !!draftConfig), - staleTime: draftConfig ? DRAFT_COMMANDS_STALE_TIME : SESSION_COMMANDS_STALE_TIME, + dataShape: "value", + meta: { + agentCommandProvider: draftConfig?.provider ?? provider, + agentCommandCwd: draftConfig?.cwd ?? cwd, + }, + ...(draftConfig + ? { immutableWhen: () => true as const } + : { ...sessionCommandQueryPolicy, staleTimeMs: sessionCommandQueryPolicy.staleTime }), + subscribed: queryEnabled, retry: 3, retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 5000), }); @@ -84,7 +104,7 @@ export function useAgentCommandsQuery({ return { commands: query.data ?? [], isLoading, - isError: query.isError, + isError: query.isError && query.data === undefined, error: query.error, }; } diff --git a/packages/app/src/components/markdown/images.ts b/packages/app/src/components/markdown/images.ts index 83b24b481b..e2f8d07992 100644 --- a/packages/app/src/components/markdown/images.ts +++ b/packages/app/src/components/markdown/images.ts @@ -35,11 +35,15 @@ export interface MarkdownImageContext { filePath?: string; } -export function useMarkdownSource(text: string, context: MarkdownImageContext) { +export function useMarkdownSource( + text: string, + context: MarkdownImageContext, + commandNames?: ReadonlySet, +) { const occurrenceKey = useId(); const prepared = useMemo( - () => prepareMarkdownSource(text, context.workspaceRoot, { supportsSvg: isWeb }), - [text, context.workspaceRoot], + () => prepareMarkdownSource(text, context.workspaceRoot, { supportsSvg: isWeb, commandNames }), + [text, context.workspaceRoot, commandNames], ); const sources = [...new Set(prepared.images.map((image) => image.source))]; const acquisitions = sources.map((source) => { diff --git a/packages/app/src/components/markdown/renderer.test.ts b/packages/app/src/components/markdown/renderer.test.ts index bb5679f6f8..4256685f9c 100644 --- a/packages/app/src/components/markdown/renderer.test.ts +++ b/packages/app/src/components/markdown/renderer.test.ts @@ -2,6 +2,8 @@ import { fromMarkdown } from "mdast-util-from-markdown"; import { toNativeLinkRecognition } from "react-native-enriched-markdown/src/utils/regexParser"; import { parseMarkdown } from "react-native-enriched-markdown/src/web/parseMarkdown"; import { recognizeTextLinks } from "react-native-enriched-markdown/src/web/recognizeTextLinks"; +import { matchCommandLink } from "@/agent-commands"; + import { classifyAssistantFileLink } from "@/assistant-file-links"; import { markInlineImages } from "react-native-enriched-markdown/src/web/utils"; import type { ASTNode } from "react-native-enriched-markdown/src/web/types"; @@ -13,6 +15,28 @@ import { createMarkdownStyles } from "./styles"; import { prepareMarkdownSource, PENDING_MARKDOWN_IMAGE } from "./source"; import { normalizeMarkdownHtml } from "./html"; +it("recognizes complete known commands in inline code", () => { + const names = new Set(["code-review", "review:fast"]); + const prepared = prepareMarkdownSource("`/code-review` `/unknown`", undefined, { + commandNames: names, + }); + expect(prepared.linkRecognition.inlineCode.test("/code-review")).toBe(true); + expect(prepared.linkRecognition.inlineCode.test("/unknown")).toBe( + prepareMarkdownSource("`/unknown`").linkRecognition.inlineCode.test("/unknown"), + ); + const nonPath = prepareMarkdownSource("`/review:fast`", undefined, { commandNames: names }); + expect(nonPath.linkRecognition.inlineCode.test("/review:fast")).toBe(true); + expect(matchCommandLink("/code-review", "inline-code", names)).toBe("/code-review"); +}); + +it("resolves authored root-relative links only when the target is a known command", () => { + const names = new Set(["code-review"]); + expect(matchCommandLink("/code-review", "markdown", names)).toBe("/code-review"); + expect(matchCommandLink("/code-review/file", "markdown", names)).toBeNull(); + expect(matchCommandLink("/code-review", "text", names)).toBeNull(); + expect(matchCommandLink("https://example.com/code-review", "markdown", names)).toBeNull(); +}); + describe("shared Markdown source adaptation", () => { it("keeps paragraphs, fences and quotes together for the library", () => { const source = "First paragraph.\n\nSecond paragraph.\n\n```ts\nconst n = 1;\n```\n\n> Quote"; diff --git a/packages/app/src/components/markdown/renderer.tsx b/packages/app/src/components/markdown/renderer.tsx index 8e51495369..c14ecb5198 100644 --- a/packages/app/src/components/markdown/renderer.tsx +++ b/packages/app/src/components/markdown/renderer.tsx @@ -6,6 +6,7 @@ import { useAssistantFileLinkEnvironment, } from "@/assistant-file-links"; import { useStableEvent } from "@/hooks/use-stable-event"; +import { matchCommandLink, useAgentCommandHints, type CommandHints } from "@/agent-commands"; import { AttachmentLightbox, type ImageLightboxSource } from "@/components/attachment-lightbox"; import type { Theme } from "@/styles/theme"; import { isWeb } from "@/constants/platform"; @@ -48,6 +49,7 @@ export interface MarkdownRendererProps extends MarkdownImageContext { selectable?: boolean; streaming?: boolean; onLinkPress?: (url: string) => unknown; + agentCommands?: boolean; } /** All Markdown surfaces share the same engine and source adaptation. */ @@ -59,15 +61,21 @@ export const MarkdownRenderer = memo(function MarkdownRenderer(props: MarkdownRe () => splitStreamingMarkdown(completeLines, true).head.length, [completeLines], ); - if (!streaming || boundary === 0) return ; + const Part = props.agentCommands ? CommandMarkdownPart : MarkdownPart; + if (!streaming || boundary === 0) return ; return ( - - + + ); }); +const CommandMarkdownPart = memo(function CommandMarkdownPart(props: MarkdownRendererProps) { + const commandHints = useAgentCommandHints(); + return ; +}); + const MarkdownPart = memo(function MarkdownPart({ text, compact = false, @@ -75,8 +83,10 @@ const MarkdownPart = memo(function MarkdownPart({ selectable = true, streaming = false, onLinkPress, + agentCommands: _agentCommands, + commandHints = null, ...imageContext -}: MarkdownRendererProps) { +}: MarkdownRendererProps & { commandHints?: CommandHints | null }) { const environment = useAssistantFileLinkEnvironment(); const actions = useAssistantFileLinkActions(); const client = @@ -84,14 +94,23 @@ const MarkdownPart = memo(function MarkdownPart({ (environment.client?.readFile ? { readFile: environment.client.readFile.bind(environment.client) } : undefined); - const { markdown, imageSources, linkRecognition, linkSource } = useMarkdownSource(text, { - workspaceRoot: environment.workspaceRoot, - serverId: environment.serverId, - ...imageContext, - client, - }); + const { markdown, imageSources, linkRecognition, linkSource } = useMarkdownSource( + text, + { + workspaceRoot: environment.workspaceRoot, + serverId: environment.serverId, + ...imageContext, + client, + }, + commandHints?.names, + ); const [image, setImage] = useState(null); const pressLink = useStableEvent(({ url, sourceType }: LinkPressEvent) => { + const command = commandHints && matchCommandLink(url, sourceType, commandHints.names); + if (command) { + commandHints.insert(command); + return; + } const source = linkSource(url, sourceType); if (onLinkPress && !actions.canResolveFile(source)) onLinkPress(url); else actions.open(source, "preferred"); diff --git a/packages/app/src/components/markdown/source.ts b/packages/app/src/components/markdown/source.ts index 5c82088898..3462320d7d 100644 --- a/packages/app/src/components/markdown/source.ts +++ b/packages/app/src/components/markdown/source.ts @@ -56,7 +56,11 @@ function linkMetadata(inlineCodePaths: ReadonlySet) { }; } -function collectInlineCodePaths(source: string, workspaceRoot?: string): ReadonlySet { +function collectInlineCodePaths( + source: string, + workspaceRoot?: string, + commandNames?: ReadonlySet, +): ReadonlySet { const paths = new Set(); const previousEnds = new Map(); // Collect candidates between consecutive runs of equal length. The engine owns @@ -74,7 +78,11 @@ function collectInlineCodePaths(source: string, workspaceRoot?: string): Readonl value = value.slice(1, -1); } const classification = classifyAssistantFileLink(value, { workspaceRoot }); - if (classification && classification.kind !== "external") paths.add(value); + if ( + (classification && classification.kind !== "external") || + (value.startsWith("/") && commandNames?.has(value.slice(1))) + ) + paths.add(value); } return paths; } @@ -112,7 +120,7 @@ function workspaceHoverTitle(link: Link, markup: string, workspaceRoot?: string) export function prepareMarkdownSource( source: string, workspaceRoot?: string, - options: { supportsSvg?: boolean } = {}, + options: { supportsSvg?: boolean; commandNames?: ReadonlySet } = {}, ) { source = normalizeMarkdownHtml(source); const images: MarkdownImage[] = []; @@ -122,7 +130,9 @@ export function prepareMarkdownSource( extensions: [gfmTable()], mdastExtensions: [gfmTableFromMarkdown()], })); - const metadata = linkMetadata(collectInlineCodePaths(source, workspaceRoot)); + const metadata = linkMetadata( + collectInlineCodePaths(source, workspaceRoot, options.commandNames), + ); const edits: { start: number; end: number; text: string }[] = []; if ( !source.includes("![") && diff --git a/packages/app/src/components/message.tsx b/packages/app/src/components/message.tsx index 2c6165d305..0ec5cbfb44 100644 --- a/packages/app/src/components/message.tsx +++ b/packages/app/src/components/message.tsx @@ -1199,6 +1199,7 @@ export const AssistantMessage = memo(function AssistantMessage({ > { + it("appends commands to the current editor buffer and focuses it", () => { + const session = new ComposerEditingSession(); + let text = "draft typed since publication"; + let focuses = 0; + let selection = { start: 0, end: 0 }; + const detach = session.attachEditor({ + getText: () => text, + replaceText: (next, nextSelection) => { + text = next; + selection = nextSelection; + }, + focus: () => { + focuses += 1; + }, + }); + session.insertCommand("/review"); + expect(selection).toEqual({ start: text.length, end: text.length }); + session.insertCommand("/test"); + expect(text).toBe("draft typed since publication /review /test "); + expect(focuses).toBe(2); + expect(selection).toEqual({ start: text.length, end: text.length }); + detach(); + session.insertCommand("/ignored"); + expect(text).toBe("draft typed since publication /review /test "); + }); it("publishes fullscreen changes once per transition", () => { const session = new ComposerEditingSession(); const changes: boolean[] = []; diff --git a/packages/app/src/composer/editing-session/index.tsx b/packages/app/src/composer/editing-session/index.tsx index 4776b5af3d..237b15251a 100644 --- a/packages/app/src/composer/editing-session/index.tsx +++ b/packages/app/src/composer/editing-session/index.tsx @@ -30,10 +30,29 @@ export interface ComposerRetainedEditor { */ export class ComposerEditingSession { private fullscreen = false; + private editor: { + getText(): string; + replaceText(text: string, selection: ComposerSelection): void; + focus(): void; + } | null = null; private retained: ComposerRetainedEditor | null = null; private listeners = new Set<() => void>(); constructor(private readonly onChange?: () => void) {} getFullscreen = () => this.fullscreen; + attachEditor(editor: NonNullable) { + this.editor = editor; + return () => { + if (this.editor === editor) this.editor = null; + }; + } + insertCommand(command: string) { + const editor = this.editor; + if (!editor) return; + const text = editor.getText(); + const nextText = `${text}${text && !/\s$/.test(text) ? " " : ""}${command} `; + editor.replaceText(nextText, { start: nextText.length, end: nextText.length }); + editor.focus(); + } /** Called by the unmounting editor; the next mount of this session takes it. */ retainEditor(retained: ComposerRetainedEditor) { this.retained = retained; diff --git a/packages/app/src/composer/index.tsx b/packages/app/src/composer/index.tsx index b7088ddeef..d6b4bae63f 100644 --- a/packages/app/src/composer/index.tsx +++ b/packages/app/src/composer/index.tsx @@ -71,7 +71,7 @@ import { } from "./input/input"; import type { ImageAttachment, MessagePayload, TextReplacement } from "./types"; import { ICON_SIZE, type Theme } from "@/styles/theme"; -import type { DraftCommandTarget } from "@/hooks/use-agent-commands-query"; +import type { DraftCommandTarget } from "@/agent-commands"; import { encodeImages } from "@/utils/encode-images"; import { focusWithRetries } from "@/utils/web-focus"; import { diff --git a/packages/app/src/composer/input/input.tsx b/packages/app/src/composer/input/input.tsx index 16acede7e5..8cb8cd4c32 100644 --- a/packages/app/src/composer/input/input.tsx +++ b/packages/app/src/composer/input/input.tsx @@ -1407,6 +1407,16 @@ export const MessageInput = forwardRef( [onChangeText, updateComposerHeightForText, updateLiveTextPresence], ); + useLayoutEffect( + () => + editingSession.attachEditor({ + getText: () => textInputRef.current?.getText() ?? valueRef.current, + replaceText, + focus: () => textInputRef.current?.focus(), + }), + [editingSession, replaceText], + ); + useImperativeHandle(ref, () => ({ focus: () => { textInputRef.current?.focus(); diff --git a/packages/app/src/data/providers-snapshot.ts b/packages/app/src/data/providers-snapshot.ts index 68b389fe15..87c62f81ca 100644 --- a/packages/app/src/data/providers-snapshot.ts +++ b/packages/app/src/data/providers-snapshot.ts @@ -8,7 +8,7 @@ import { } from "./provider-snapshot-cache"; import { queryClient as singletonQueryClient } from "./query-client"; import { replaceProviderSnapshotIcons } from "@/data/provider-icons"; -import { agentCommandsQueryRoot } from "@/hooks/agent-commands-query"; +import { agentCommandsQueryRoot } from "@/agent-commands/cache"; import type { AgentProvider } from "@getpaseo/protocol/agent-types"; import { normalizeWorkspacePath } from "@/utils/workspace-identity"; diff --git a/packages/app/src/data/push-router.ts b/packages/app/src/data/push-router.ts index 75ac313169..cc32f8f8e3 100644 --- a/packages/app/src/data/push-router.ts +++ b/packages/app/src/data/push-router.ts @@ -1,11 +1,12 @@ import type { OwnedSubscription } from "@getpaseo/client"; +import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types"; import type { Query, QueryCacheNotifyEvent, QueryClient, QueryKey } from "@tanstack/react-query"; import type { ListTerminalsResponse, MutableDaemonConfig, SessionOutboundMessage, } from "@getpaseo/protocol/messages"; -import { agentCommandsQueryRoot } from "@/hooks/agent-commands-query"; +import { invalidateCommandsForProviderChange } from "@/agent-commands/cache"; import { shareCheckoutDiff } from "@/git/diff-sharing"; import { orderCheckoutDiffFiles } from "@/git/diff-order"; import { daemonConfigQueryKey } from "@/data/daemon-config"; @@ -186,10 +187,10 @@ export async function applyProvidersSnapshotUpdate(input: { const snapshot = { ...input.message.payload, requestId: "providers_snapshot_update" }; const cwd = normalizeProvidersSnapshotCwd(snapshot.cwd); const queryKey = providersSnapshotQueryKey(input.serverId, cwd); - const previous = input.queryClient.getQueryData<{ snapshotHash?: string }>(queryKey); + const previous = input.queryClient.getQueryData<{ entries: ProviderSnapshotEntry[] }>(queryKey); let announcement: typeof snapshot | undefined = snapshot; void input.queryClient.cancelQueries({ queryKey, exact: true }); - await input.queryClient.fetchQuery({ + const current = await input.queryClient.fetchQuery({ queryKey, staleTime: 0, structuralSharing: false, @@ -205,12 +206,13 @@ export async function applyProvidersSnapshotUpdate(input: { }); }, }); - if (!snapshot.snapshotHash || previous?.snapshotHash !== snapshot.snapshotHash) { - void input.queryClient.invalidateQueries({ - queryKey: agentCommandsQueryRoot(input.serverId), - exact: false, - }); - } + void invalidateCommandsForProviderChange({ + queryClient: input.queryClient, + serverId: input.serverId, + cwd, + previous: previous?.entries, + current: current.entries, + }); } export function mountServerDataPushRouter(input: PushRouterInput): () => void { diff --git a/packages/app/src/data/query.ts b/packages/app/src/data/query.ts index 2a645f8666..e2b25d7b29 100644 --- a/packages/app/src/data/query.ts +++ b/packages/app/src/data/query.ts @@ -27,7 +27,7 @@ type ReplicaQueryInput type FetchQueryInput = Omit< UseQueryOptions, - "initialData" | "placeholderData" | "queryFn" | "refetchOnMount" | "staleTime" + "initialData" | "placeholderData" | "queryFn" | "staleTime" > & { dataShape: "list" | "value"; queryFn: QueryFnOption; @@ -113,7 +113,7 @@ export function fetchQueryOptions< dataShape, }, }, - refetchOnMount: immutableWhen ? true : "always", + refetchOnMount: options.refetchOnMount ?? (immutableWhen ? true : "always"), staleTime: immutableWhen ? (query) => query.state.data !== undefined && immutableWhen(query.state.data) ? Infinity : 0 diff --git a/packages/app/src/git/checkout-status-cache.test.ts b/packages/app/src/git/checkout-status-cache.test.ts index 026ec9d43a..bbfeb6d758 100644 --- a/packages/app/src/git/checkout-status-cache.test.ts +++ b/packages/app/src/git/checkout-status-cache.test.ts @@ -16,7 +16,7 @@ import { resolveWorkingDiffComparison, selectWorkingDiffComparison, } from "@/git/working-diff-comparison"; -import { draftAgentCommandsQueryKey } from "@/hooks/agent-commands-query"; +import { draftAgentCommandsQueryKey } from "@/agent-commands/cache"; import { applyCheckoutStatusUpdateFromEvent, ensureCheckoutStatus, diff --git a/packages/app/src/git/checkout-status-cache.ts b/packages/app/src/git/checkout-status-cache.ts index ca5cbb3a7a..4aaa650c70 100644 --- a/packages/app/src/git/checkout-status-cache.ts +++ b/packages/app/src/git/checkout-status-cache.ts @@ -8,7 +8,7 @@ import { invalidatePrPaneTimelineForCheckout, } from "@/git/query-keys"; import { type CheckoutPrStatusPayload, normalizeCheckoutPrStatusPayload } from "@/git/pr-status"; -import { resetDraftAgentCommandsForCheckout } from "@/hooks/agent-commands-query"; +import { resetDraftAgentCommandsForCheckout } from "@/agent-commands/cache"; export type CheckoutStatusPayload = CheckoutStatusResponse["payload"]; export type { CheckoutPrStatusPayload } from "@/git/pr-status"; diff --git a/packages/app/src/hooks/use-agent-autocomplete.ts b/packages/app/src/hooks/use-agent-autocomplete.ts index fe6f98c3f1..ef144477dc 100644 --- a/packages/app/src/hooks/use-agent-autocomplete.ts +++ b/packages/app/src/hooks/use-agent-autocomplete.ts @@ -4,11 +4,11 @@ import type { TFunction } from "i18next"; import { useTranslation } from "react-i18next"; import type { AutocompleteOption } from "@/components/ui/autocomplete"; import { - useAgentCommandsQuery, + useAutocompleteCommands, type AgentSlashCommand, type DraftCommandConfig, type DraftCommandTarget, -} from "./use-agent-commands-query"; +} from "@/agent-commands"; import { orderAutocompleteOptions } from "@/components/ui/autocomplete-utils"; import { useAutocomplete } from "./use-autocomplete"; import { useSessionStore } from "@/stores/session-store"; @@ -432,7 +432,7 @@ export function useAgentAutocomplete(input: UseAgentAutocompleteInput): AgentAut autocompleteCwd, }); - const commandsQuery = useAgentCommandsQuery({ + const commandsQuery = useAutocompleteCommands({ serverId, agentId, enabled: mode === "command" && canLoadCommands && canListCommands, diff --git a/packages/app/src/hooks/use-providers-snapshot.test.ts b/packages/app/src/hooks/use-providers-snapshot.test.ts index 2f3c90b340..0c730cddbd 100644 --- a/packages/app/src/hooks/use-providers-snapshot.test.ts +++ b/packages/app/src/hooks/use-providers-snapshot.test.ts @@ -1,4 +1,4 @@ -import { QueryClient } from "@tanstack/react-query"; +import { QueryClient, QueryObserver } from "@tanstack/react-query"; import { beforeEach, describe, expect, it } from "vitest"; import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; @@ -8,7 +8,7 @@ import { expandProviderSnapshot, } from "@getpaseo/protocol/provider-snapshot-codec"; import type { CachedProviderSnapshot, ProviderSnapshotCache } from "@/data/provider-snapshot-cache"; -import { draftAgentCommandsQueryKey } from "@/hooks/agent-commands-query"; +import { draftAgentCommandsQueryKey, sessionAgentCommandsQueryKey } from "@/agent-commands/cache"; import { providerSnapshotIcons } from "@/data/provider-icons"; import { applyProvidersSnapshotUpdate, type ProvidersSnapshotUpdate } from "@/data/push-router"; import { @@ -363,6 +363,153 @@ describe("applyProvidersSnapshotUpdate", () => { }; } + it("refreshes active commands only when their provider changes after discovery", async () => { + const key = sessionAgentCommandsQueryKey({ serverId, agentId: "agent-1" }); + let requests = 0; + const observer = new QueryObserver(queryClient, { + queryKey: key, + queryFn: async () => { + requests++; + return [{ name: "review" }]; + }, + staleTime: Infinity, + meta: { agentCommandProvider: "codex", agentCommandCwd: "/repo-a" }, + }); + const unsubscribe = observer.subscribe(() => {}); + await observer.refetch({ cancelRefetch: false }); + expect(requests).toBe(1); + const codex = codexEntry("ready", [readyCodexModel]); + const other = { provider: "claude", status: "loading", enabled: true } as ProviderSnapshotEntry; + await applyProvidersSnapshotUpdate({ + client: createClient(), + serverId, + queryClient, + message: updateMessage([codexEntry("loading"), other], "/repo-a"), + }); + expect(requests).toBe(1); + await applyProvidersSnapshotUpdate({ + client: createClient(), + serverId, + queryClient, + message: updateMessage([codex, other], "/repo-a"), + }); + expect(requests).toBe(1); + await applyProvidersSnapshotUpdate({ + client: createClient(), + serverId, + queryClient, + message: updateMessage([codex, { ...other, status: "ready" }], "/repo-a"), + }); + expect(requests).toBe(1); + await applyProvidersSnapshotUpdate({ + client: createClient(), + serverId, + queryClient, + message: updateMessage( + [ + { ...codex, fetchedAt: "2026-01-01T00:00:02.000Z" }, + { ...other, status: "ready" }, + ], + "/repo-a", + ), + }); + expect(requests).toBe(1); + queryClient.setQueryData( + providersSnapshotQueryKey(serverId, "/repo-b"), + providersSnapshot([codex]), + ); + await applyProvidersSnapshotUpdate({ + client: createClient(), + serverId, + queryClient, + message: updateMessage( + [codexEntry("ready", [{ ...readyCodexModel, label: "Other checkout" }])], + "/repo-b", + ), + }); + expect(requests).toBe(1); + await applyProvidersSnapshotUpdate({ + client: createClient(), + serverId, + queryClient, + message: updateMessage( + [ + codexEntry("ready", [{ ...readyCodexModel, label: "Updated" }]), + { ...other, status: "ready" }, + ], + "/repo-a", + ), + }); + await observer.refetch({ cancelRefetch: false }); + expect(requests).toBe(2); + unsubscribe(); + queryClient.clear(); + }); + + it("retries a failed command discovery when its provider first becomes ready", async () => { + const key = sessionAgentCommandsQueryKey({ serverId, agentId: "agent-1" }); + let ready = false; + let requests = 0; + const observer = new QueryObserver(queryClient, { + queryKey: key, + queryFn: async () => { + requests++; + if (!ready) throw new Error("provider unavailable"); + return [{ name: "review" }]; + }, + retry: false, + meta: { agentCommandProvider: "codex", agentCommandCwd: "/repo-a" }, + }); + const unsubscribe = observer.subscribe(() => {}); + await observer.refetch({ cancelRefetch: false }); + expect(observer.getCurrentResult().isError).toBe(true); + ready = true; + await applyProvidersSnapshotUpdate({ + client: createClient(), + serverId, + queryClient, + message: updateMessage([codexEntry("ready", [readyCodexModel])], "/repo-a"), + }); + await observer.refetch({ cancelRefetch: false }); + expect(requests).toBe(2); + expect(observer.getCurrentResult().data).toEqual([{ name: "review" }]); + unsubscribe(); + queryClient.clear(); + }); + + it("refreshes again when its provider changes during an active refresh", async () => { + const key = sessionAgentCommandsQueryKey({ serverId, agentId: "agent-1" }); + queryClient.setQueryData(key, [{ name: "old" }]); + let requests = 0; + const waiting = new Promise<{ name: string }[]>(() => {}); + const observer = new QueryObserver(queryClient, { + queryKey: key, + queryFn: async () => (++requests === 1 ? waiting : [{ name: "new" }]), + staleTime: Infinity, + meta: { agentCommandProvider: "codex", agentCommandCwd: "/repo-a" }, + }); + const unsubscribe = observer.subscribe(() => {}); + queryClient.setQueryData( + providersSnapshotQueryKey(serverId, "/repo-a"), + providersSnapshot([codexEntry("ready", [readyCodexModel])]), + ); + const send = (label: string) => + applyProvidersSnapshotUpdate({ + client: createClient(), + serverId, + queryClient, + message: updateMessage([codexEntry("ready", [{ ...readyCodexModel, label }])], "/repo-a"), + }); + await send("First change"); + expect(requests).toBe(1); + await send("Second change"); + expect(requests).toBe(2); + await observer.refetch({ cancelRefetch: false }); + expect(observer.getCurrentResult().data).toEqual([{ name: "new" }]); + unsubscribe(); + queryClient.clear(); + }); + it("routes updates to the home query cache when the message carries no cwd", async () => { await applyProvidersSnapshotUpdate({ client: createClient(), @@ -455,6 +602,10 @@ describe("applyProvidersSnapshotUpdate", () => { draftConfig: { provider: "codex", cwd: "/repo-a" }, }); queryClient.setQueryData(commandsKey, [{ name: "compact", description: "", argumentHint: "" }]); + queryClient.setQueryData( + providersSnapshotQueryKey(serverId, "/repo-a"), + providersSnapshot([codexEntry("ready")]), + ); await applyProvidersSnapshotUpdate({ client: createClient(), diff --git a/packages/app/src/panels/agent-panel.tsx b/packages/app/src/panels/agent-panel.tsx index 712d9d65a1..147ab7b260 100644 --- a/packages/app/src/panels/agent-panel.tsx +++ b/packages/app/src/panels/agent-panel.tsx @@ -28,6 +28,7 @@ import { FileDropZone } from "@/components/file-drop/file-drop-zone"; import { useRetainedPanelActive } from "@/components/retained-panel"; import { RetainedChatContent } from "./retained-chat-content"; import { Composer } from "@/composer"; +import { AgentCommandsProvider } from "@/agent-commands"; import { useComposerEditingSession, useComposerFullscreen, @@ -1255,7 +1256,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({ ); - return ( + const content = ( ); + return wrapAgentCommandProvider({ + enabled: showsComposer && hasActiveComposer, + serverId, + agentId, + editingSession: composerEditingSession, + children: content, + }); }); +function wrapAgentCommandProvider({ + enabled, + serverId, + agentId, + editingSession, + children, +}: { + enabled: boolean; + serverId: string; + agentId: string; + editingSession: ComposerEditingSession; + children: ReactNode; +}) { + return ( + + {children} + + ); +} + function ChatSurface({ children, disabled, diff --git a/packages/app/src/provider-selection/provider-selection.ts b/packages/app/src/provider-selection/provider-selection.ts index e0313c6623..54d75f1da2 100644 --- a/packages/app/src/provider-selection/provider-selection.ts +++ b/packages/app/src/provider-selection/provider-selection.ts @@ -5,7 +5,7 @@ import type { ProviderSnapshotEntry, } from "@getpaseo/protocol/agent-types"; import type { AgentProviderDefinition } from "@getpaseo/protocol/provider-manifest"; -import type { DraftCommandTarget } from "@/hooks/use-agent-commands-query"; +import type { DraftCommandTarget } from "@/agent-commands"; import { i18n } from "@/i18n/i18next"; import { compareMatchScores, scoreTextFields } from "@getpaseo/protocol/search/text-match"; import { filterSelectableModels } from "./model-catalog"; From 2ac288f4d053eb8bc5ca37113c353c8ceed75593 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sat, 31 Oct 2026 12:26:32 +0000 Subject: [PATCH 146/173] test(plugins): make global switch recovery deterministic (#8342) * test(plugins): trace recurring global recovery failure * test(plugins): control cleanup in global switch recovery --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../src/server/plugins/index.posix.test.ts | 34 ++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/packages/server/src/server/plugins/index.posix.test.ts b/packages/server/src/server/plugins/index.posix.test.ts index c529bd37d3..1f8b3f124b 100644 --- a/packages/server/src/server/plugins/index.posix.test.ts +++ b/packages/server/src/server/plugins/index.posix.test.ts @@ -1071,9 +1071,38 @@ export default function contribute(plugin: unknown) { "second", `export default function contribute(plugin: unknown) { void plugin; return () => undefined; }`, ); + // Hold cleanup open so synchronous detach and queued recovery are tested + // independently of compiler/process startup speed on the runner. + let finishCleanup = () => undefined; + const cleanup = new Promise((resolve) => { + finishCleanup = resolve; + }); + const running = new Set(); + const runtime: TestPluginRuntime = { + ...emptyUsageRuntime, + catalog: () => [...running].map((id) => ({ id, clientBundle: "bundle" })), + invoke: async (pluginId) => { + if (!running.has(pluginId)) throw new Error(`Plugin is not available: ${pluginId}`); + return pluginId; + }, + getLogs: () => [], + clearLogs: () => undefined, + startPlugin: async (pluginId, _path, canPublish) => { + if (!canPublish()) throw new Error(`Plugin start cancelled: ${pluginId}`); + running.add(pluginId); + }, + stopPluginById: async (pluginId) => { + const existed = running.delete(pluginId); + await cleanup; + return existed; + }, + stopAll: async () => running.clear(), + subscribe: () => () => undefined, + bindPaseoSessionHost: () => undefined, + }; const store = createStore(home); const service = bindTestSessionHost( - new PluginService(pino({ level: "silent" }), store, "0.4.0"), + new PluginService(pino({ level: "silent" }), store, "0.4.0", { runtime }), ); try { await service.start(); @@ -1087,6 +1116,8 @@ export default function contribute(plugin: unknown) { "Plugin is not available", ); await store.patch({ pluginsEnabled: true }); + expect(service.catalog()).toEqual([]); + finishCleanup(); // Observe recovery itself. Reloading here restarts a healthy plugin and // would also conceal a failure to restart it after the global enable. await expect @@ -1096,6 +1127,7 @@ export default function contribute(plugin: unknown) { { id: "second", status: "running" }, ]); } finally { + finishCleanup(); await service.stopAllPlugins(); } }, 20_000); From b117e3fb0f814730546346ec619720b100f03590 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sat, 31 Oct 2026 13:03:27 +0000 Subject: [PATCH 147/173] fix(claude): allow conversation rewind to messages sent during a turn (#8372) * fix(server): let a message steered into a running Claude turn be rewound to A steered message never got a provider message id, because Claude takes it into the running turn without echoing it back, so rewinding to it refused with "Cannot rewind before the provider acknowledges the submitted prompt". The steer admission now reports the uuid Claude minted for the message, and a Claude conversation rewind to it forks at the entry Claude read it after. Co-Authored-By: Claude Opus 5.5 * fix(server): keep messages steered into a running Claude turn in the replayed timeline Claude records a steered message as a queued_command attachment rather than a user entry, and the history replay skipped it, so every such message, replies from other agents included, vanished from the timeline after a daemon restart. Co-Authored-By: Claude Opus 5.5 * test(claude): verify steer identities across lifecycle tests Match the accepted-steer contract used by conversation rewind and verify that its identity names the message delivered to the provider. Co-authored-by: tieo <65707274+tieo@users.noreply.github.com> * fix(claude): release transcript streams after rewind lookup Closing readline leaves a partially read transcript open after an early match. Destroy the owned stream on exit and cover repeated lookups with unread data. --------- Co-authored-by: tieo <65707274+tieo@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../src/server/agent/agent-manager.test.ts | 68 ++++++++++++ .../server/src/server/agent/agent-manager.ts | 18 ++- .../src/server/agent/agent-sdk-types.ts | 6 +- .../claude/agent.history-load.test.ts | 37 +++++++ ...agent.interrupt-restart-regression.test.ts | 10 +- .../claude/agent.rewind-anchors.test.ts | 50 +++++++++ .../agent/providers/claude/agent.test.ts | 17 +-- .../server/agent/providers/claude/agent.ts | 38 ++++++- .../agent/providers/claude/rewind.test.ts | 103 +++++++++++++++++- .../server/agent/providers/claude/rewind.ts | 50 +++++++++ 10 files changed, 380 insertions(+), 17 deletions(-) diff --git a/packages/server/src/server/agent/agent-manager.test.ts b/packages/server/src/server/agent/agent-manager.test.ts index 4b3fb5ea46..ccf29b17b0 100644 --- a/packages/server/src/server/agent/agent-manager.test.ts +++ b/packages/server/src/server/agent/agent-manager.test.ts @@ -1220,6 +1220,74 @@ test("orders buffered pre-steer output before an immediately accepted steer", as } }); +test("a steer the provider names without echoing it can be rewound to", async () => { + // Claude takes a steered message into the running turn without echoing it back as a user + // message, so the id it minted for the message reaches the manager only through the admission. + class SilentSteeringSession extends SteeringTestSession { + override readonly capabilities = { + ...TEST_CAPABILITIES, + supportsRewindFiles: true, + }; + rewindMessageIds: string[] = []; + + override async steerActiveTurn( + _prompt: AgentPromptInput, + options: import("./agent-sdk-types.js").SteerActiveTurnOptions, + ): Promise { + if (options.expectedTurnId !== `active-turn-${this.startCount}`) { + return { status: "unavailable" }; + } + return { status: "accepted", providerMessageId: `provider-${options.clientMessageId}` }; + } + + override async revertFiles({ messageId }: { messageId: string }): Promise { + this.rewindMessageIds.push(messageId); + } + } + const session = new SilentSteeringSession({ provider: "codex", cwd: process.cwd() }); + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-steer-rewind-")); + const manager = new AgentManager({ + clients: { + codex: new (class extends TestAgentClient { + override async createSession(): Promise { + return session; + } + })(), + }, + logger, + }); + let agentId: string | null = null; + try { + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + agentId = agent.id; + const run = manager.streamAgent(agent.id, "initial"); + void (async () => { + for await (const _event of run) { + } + })(); + await manager.waitForAgentRunStart(agent.id); + + await expect( + manager.steerAgentRun(agent.id, "steered", { clientMessageId: "steer-client" }), + ).resolves.toMatchObject({ status: "accepted" }); + const row = manager + .fetchTimeline(agent.id, { limit: 0 }) + .rows.find((candidate) => candidate.item.type === "user_message"); + expect(row).toMatchObject({ + providerMessageId: "provider-steer-client", + item: { text: "steered", clientMessageId: "steer-client" }, + }); + + await manager.rewind(agent.id, "steer-client", "files"); + expect(session.rewindMessageIds).toEqual(["provider-steer-client"]); + } finally { + if (agentId) await manager.closeAgent(agentId).catch(() => undefined); + rmSync(workdir, { recursive: true, force: true }); + } +}); + test("orders a concurrent replacement after a pending accepted steer", async () => { const entered = deferred(); const release = deferred(); diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index c69a574849..94250e5cdd 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -3029,7 +3029,13 @@ export class AgentManager { expectedTurnId, }); if (admission.status === "accepted") { - await this.recordAcceptedSteer(agent, prompt, options?.clientMessageId, expectedTurnId); + await this.recordAcceptedSteer( + agent, + prompt, + options?.clientMessageId, + expectedTurnId, + admission.providerMessageId, + ); } return admission; }); @@ -3062,7 +3068,13 @@ export class AgentManager { expectedTurnId, }); if (admission.status === "accepted") { - await this.recordAcceptedSteer(agent, prompt, options?.clientMessageId, expectedTurnId); + await this.recordAcceptedSteer( + agent, + prompt, + options?.clientMessageId, + expectedTurnId, + admission.providerMessageId, + ); } return admission; }) @@ -3167,6 +3179,7 @@ export class AgentManager { prompt: AgentPromptInput, clientMessageId: string | undefined, expectedTurnId: string, + providerMessageId: string | undefined, ): Promise { if (!clientMessageId) { return; @@ -3174,6 +3187,7 @@ export class AgentManager { this.recordSubmittedPrompt(agent, prompt, clientMessageId, "accepted", { messageId: clientMessageId, turnId: expectedTurnId, + ...(providerMessageId ? { providerMessageId } : {}), }); this.emitState(agent); } diff --git a/packages/server/src/server/agent/agent-sdk-types.ts b/packages/server/src/server/agent/agent-sdk-types.ts index 6570392311..c31d1afb86 100644 --- a/packages/server/src/server/agent/agent-sdk-types.ts +++ b/packages/server/src/server/agent/agent-sdk-types.ts @@ -208,7 +208,11 @@ export interface AgentSteerOptions extends AgentRunOptions { clearPendingPermissions?: boolean; } -export type SteerResult = { status: "accepted" } | { status: "unavailable" }; +// providerMessageId names the steered message in the provider's own history, when the provider +// mints one. Rewinding to the message needs it. +export type SteerResult = + | { status: "accepted"; providerMessageId?: string } + | { status: "unavailable" }; export interface SteerActiveTurnOptions extends AgentSteerOptions { expectedTurnId: string; diff --git a/packages/server/src/server/agent/providers/claude/agent.history-load.test.ts b/packages/server/src/server/agent/providers/claude/agent.history-load.test.ts index 393fda60de..e2ea6850bb 100644 --- a/packages/server/src/server/agent/providers/claude/agent.history-load.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.history-load.test.ts @@ -614,6 +614,43 @@ describe("ClaudeAgentSession persisted history load", () => { ); }); + test("replays a message steered into a running turn as the user's message", async () => { + const queued = (commandMode: string, prompt: unknown, sourceUuid?: string) => ({ + type: "attachment", + uuid: `attachment-${commandMode}`, + parentUuid: "a1", + attachment: { + type: "queued_command", + commandMode, + prompt, + ...(sourceUuid ? { source_uuid: sourceUuid } : {}), + }, + }); + const entries = [ + { type: "user", uuid: "u1", parentUuid: null, message: { content: "first" } }, + { type: "assistant", uuid: "a1", parentUuid: "u1", message: { content: "working" } }, + queued("prompt", [{ type: "text", text: "steered while working" }], "steered-1"), + queued("task-notification", "t1"), + { type: "assistant", uuid: "a2", parentUuid: "a1", message: { content: "answer" } }, + ]; + mkdirSync(path.dirname(transcriptPath()), { recursive: true }); + writeFileSync(transcriptPath(), entries.map((entry) => JSON.stringify(entry)).join("\n")); + + const session = await resume(); + try { + const users = []; + for await (const event of session.streamHistory()) { + if (event.type === "timeline" && event.item.type === "user_message") users.push(event.item); + } + expect(users).toEqual([ + { type: "user_message", text: "first", messageId: "u1" }, + { type: "user_message", text: "steered while working", messageId: "steered-1" }, + ]); + } finally { + await session.close(); + } + }); + test("loads readable history when the temporary directory is unavailable", async () => { const file = transcriptPath(); const entry = { type: "assistant", message: { content: [{ type: "text", text: "saved" }] } }; diff --git a/packages/server/src/server/agent/providers/claude/agent.interrupt-restart-regression.test.ts b/packages/server/src/server/agent/providers/claude/agent.interrupt-restart-regression.test.ts index 02a09ba44b..fa0266c355 100644 --- a/packages/server/src/server/agent/providers/claude/agent.interrupt-restart-regression.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.interrupt-restart-regression.test.ts @@ -349,8 +349,11 @@ async function startSteeredTurn(sessionId: string): Promise<{ expectedTurnId: start.value.turnId, clientMessageId: "steer-client", }); - expect(steered).toEqual({ status: "accepted" }); await waitFor(() => query?.prompts.length === 2); + expect(steered).toEqual({ + status: "accepted", + providerMessageId: query?.prompts[1]?.uuid, + }); return { session, query: () => query, turn }; } @@ -972,7 +975,10 @@ test("steers an autonomous turn through its existing query without restarting it const steeredTimeline = await autonomousEvents.next(); const completion = await autonomousEvents.next(); - expect(steer).toEqual({ status: "accepted" }); + expect(steer).toEqual({ + status: "accepted", + providerMessageId: queryRef?.prompts[1]?.uuid, + }); expect(queryFactory).toHaveBeenCalledTimes(1); expect(queryRef?.interrupt).not.toHaveBeenCalled(); expect(queryRef?.prompts.map((prompt) => prompt.text)).toEqual(["seed prompt", "steer prompt"]); diff --git a/packages/server/src/server/agent/providers/claude/agent.rewind-anchors.test.ts b/packages/server/src/server/agent/providers/claude/agent.rewind-anchors.test.ts index 1b1932e9cd..ed9b324ff4 100644 --- a/packages/server/src/server/agent/providers/claude/agent.rewind-anchors.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.rewind-anchors.test.ts @@ -1,7 +1,11 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; import { describe, expect, test, vi } from "vitest"; import { createTestLogger } from "../../../../test-utils/test-logger.js"; import { ClaudeAgentClient } from "./agent.js"; +import { claudeProjectDir } from "./project-dir.js"; import { FakeClaudeSdk } from "./test-rewind-claude-sdk.js"; import { streamSession } from "../test-utils/session-stream-adapter.js"; import type { AgentSession } from "../../agent-sdk-types.js"; @@ -267,3 +271,49 @@ describe("Claude rewind after a turn whose last assistant message came from a su expect(rewindSdk.recordedForks).toEqual([{ upToMessageId: "assistant-1" }]); }); }); + +describe("Claude rewind to a message steered into a running turn", () => { + test("forks at the entry Claude read the message after", async () => { + const configDir = mkdtempSync(path.join(tmpdir(), "claude-rewind-steer-")); + const previousConfigDir = process.env.CLAUDE_CONFIG_DIR; + process.env.CLAUDE_CONFIG_DIR = configDir; + const conversation = createConversation([{ assistantMessageId: "assistant-1" }]); + const rewindSdk = new FakeClaudeSdk(); + const session = await createSession(conversation, rewindSdk); + + try { + await runTurns(session, 1); + // A steered message opens no turn: Claude Code records it as a queued_command attachment + // under the uuid Paseo minted for it, hung off the entry it was read after. + const projectDir = await claudeProjectDir(process.cwd(), { configDir }); + mkdirSync(projectDir, { recursive: true }); + const entries = [ + { type: "user", uuid: conversation.userMessageIds[0], parentUuid: null }, + { type: "assistant", uuid: "assistant-1", parentUuid: conversation.userMessageIds[0] }, + { type: "user", uuid: "tool-result-1", parentUuid: "assistant-1" }, + { + type: "attachment", + uuid: "queued-command-1", + parentUuid: "tool-result-1", + attachment: { type: "queued_command", source_uuid: "steered-message-1" }, + }, + ]; + writeFileSync( + path.join(projectDir, `${SESSION_ID}.jsonl`), + entries.map((entry) => `${JSON.stringify(entry)}\n`).join(""), + ); + + await session.revertConversation?.({ messageId: "steered-message-1" }); + } finally { + await session.close(); + if (previousConfigDir === undefined) { + delete process.env.CLAUDE_CONFIG_DIR; + } else { + process.env.CLAUDE_CONFIG_DIR = previousConfigDir; + } + rmSync(configDir, { recursive: true, force: true }); + } + + expect(rewindSdk.recordedForks).toEqual([{ upToMessageId: "tool-result-1" }]); + }); +}); diff --git a/packages/server/src/server/agent/providers/claude/agent.test.ts b/packages/server/src/server/agent/providers/claude/agent.test.ts index deb52f9a6b..758fad2e8f 100644 --- a/packages/server/src/server/agent/providers/claude/agent.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.test.ts @@ -1224,16 +1224,17 @@ describe("ClaudeAgentSession features", () => { const iterator = input[Symbol.asyncIterator](); await expect(iterator.next()).resolves.toMatchObject({ value: { type: "user" } }); - await expect( - session.steerActiveTurn?.("same turn follow-up", { - expectedTurnId: turnId, - clientMessageId: "steer-client-id", - }), - ).resolves.toEqual({ status: "accepted" }); + const admission = await session.steerActiveTurn?.("same turn follow-up", { + expectedTurnId: turnId, + clientMessageId: "steer-client-id", + }); + expect(admission).toEqual({ status: "accepted", providerMessageId: expect.any(String) }); + if (admission?.status !== "accepted") throw new Error("Expected steer admission"); await expect(iterator.next()).resolves.toMatchObject({ value: { type: "user", priority: "next", + uuid: admission.providerMessageId, message: { content: [{ type: "text", text: "same turn follow-up" }] }, }, }); @@ -1291,7 +1292,7 @@ describe("ClaudeAgentSession features", () => { expectedTurnId: turnId, clearPendingPermissions: true, }), - ).resolves.toEqual({ status: "accepted" }); + ).resolves.toEqual({ status: "accepted", providerMessageId: expect.any(String) }); await expect(firstPermission).resolves.toMatchObject({ behavior: "deny", interrupt: undefined, @@ -1350,7 +1351,7 @@ describe("ClaudeAgentSession features", () => { const permission = internal.handlePermissionRequest("Write", {}, { toolUseID: "tool-1" }); await expect( session.steerActiveTurn?.("system notification", { expectedTurnId: turnId }), - ).resolves.toEqual({ status: "accepted" }); + ).resolves.toEqual({ status: "accepted", providerMessageId: expect.any(String) }); expect(session.getPendingPermissions()).toHaveLength(1); const requestId = session.getPendingPermissions()[0]!.id; await session.respondToPermission(requestId, { behavior: "deny", message: "test cleanup" }); diff --git a/packages/server/src/server/agent/providers/claude/agent.ts b/packages/server/src/server/agent/providers/claude/agent.ts index c675b1ed62..ae48883654 100644 --- a/packages/server/src/server/agent/providers/claude/agent.ts +++ b/packages/server/src/server/agent/providers/claude/agent.ts @@ -82,6 +82,7 @@ import { renderPromptAttachmentAsText } from "../../prompt-attachments.js"; import { discoverClaudeModels } from "./model-discovery.js"; import { claudeQuery, type ClaudeOptions, type ClaudeQueryFactory } from "./query.js"; import { + findSteeredMessageParent, realClaudeRewindSdk, revertClaudeConversation, revertClaudeFiles, @@ -2627,7 +2628,7 @@ class ClaudeAgentSession implements AgentSession { return { status: "unavailable" }; } this.enqueueSteer(input, message, options.clearPendingPermissions === true); - return { status: "accepted" }; + return { status: "accepted", ...(message.uuid ? { providerMessageId: message.uuid } : {}) }; } private enqueueSteer( @@ -3094,7 +3095,7 @@ class ClaudeAgentSession implements AgentSession { async revertConversation(input: { messageId: string }): Promise { await this.ensureHistoryReady(); - const target = this.resolveConversationRewindTarget(input.messageId); + const target = await this.resolveConversationRewindTarget(input.messageId); if (target.kind === "fresh-session") { this.startFreshConversationSession(); return; @@ -3429,12 +3430,24 @@ class ClaudeAgentSession implements AgentSession { return messageId; } - private resolveConversationRewindTarget(messageId: string): ClaudeConversationRewindTarget { + private async resolveConversationRewindTarget( + messageId: string, + ): Promise { const targetUserMessageId = this.resolveClaudeMessageId(messageId); const index = this.rewindTurnAnchors.findIndex( (anchor) => anchor.userMessageId === targetUserMessageId, ); if (index < 0) { + // A message steered into a running turn opens no turn of its own. + const transcriptPath = this.claudeSessionId + ? await this.resolveHistoryPath(this.claudeSessionId) + : null; + const steerParent = transcriptPath + ? await findSteeredMessageParent(transcriptPath, targetUserMessageId) + : null; + if (steerParent) { + return { kind: "fork", messageId: steerParent }; + } throw new Error(`Claude rewind target ${messageId} is not in the tracked conversation`); } @@ -6431,6 +6444,10 @@ function convertClaudeHistoryEntryPreamble( if (entry.type === "user" && isSyntheticHistoryUserEntry(entry)) { return { shortCircuit: [] }; } + const steeredPrompt = readSteeredPromptHistoryItem(entry); + if (steeredPrompt) { + return { shortCircuit: [steeredPrompt] }; + } // Only user and assistant records are conversation turns. Claude Code 2.1.x also journals each // API request as `api-request-blob` records whose message replays the system context. if (entry.type !== "user" && entry.type !== "assistant") { @@ -6457,6 +6474,21 @@ function isProviderImageMessage(item: AgentTimelineItem): boolean { return item.type === "assistant_message" && isProviderImageMarkdown(item.text); } +/** + * A message steered into a running turn. Claude Code gives it no user entry: it records a + * queued_command attachment in prompt mode, under the uuid Paseo minted for the message, which is + * also what a rewind to it resolves. The other modes carry task notifications, not user messages. + */ +function readSteeredPromptHistoryItem(entry: ClaudeHistoryEntry): AgentTimelineItem | null { + if (entry.type !== "attachment") return null; + const attachment = toObjectRecord(entry.attachment); + if (attachment?.type !== "queued_command" || attachment.commandMode !== "prompt") return null; + const text = extractUserMessageText(attachment.prompt); + if (!text) return null; + const messageId = readTrimmedString(attachment.source_uuid); + return { type: "user_message", text, ...(messageId ? { messageId } : {}) }; +} + export async function convertClaudeHistoryEntry( entry: ClaudeHistoryEntry, mapBlocks: ( diff --git a/packages/server/src/server/agent/providers/claude/rewind.test.ts b/packages/server/src/server/agent/providers/claude/rewind.test.ts index 2d6d3853c2..226f41d39c 100644 --- a/packages/server/src/server/agent/providers/claude/rewind.test.ts +++ b/packages/server/src/server/agent/providers/claude/rewind.test.ts @@ -1,11 +1,20 @@ import { randomUUID } from "node:crypto"; -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + readlinkSync, + rmSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { afterEach, describe, expect, test } from "vitest"; import type { Query } from "@anthropic-ai/claude-agent-sdk"; import { + findSteeredMessageParent, revertClaudeConversation, revertClaudeConversationAndFiles, revertClaudeFiles, @@ -217,4 +226,96 @@ describe("Claude rewind against the Claude SDK", () => { "first reply", ]); }); + + test("forks just before a message steered into a running turn", async () => { + tempRoot = mkdtempSync(path.join(tmpdir(), "claude-rewind-steer-")); + delete process.env.CLAUDE_CONFIG_DIR; + const projectDir = path.join(tempRoot, "projects", "-repo"); + mkdirSync(projectDir, { recursive: true }); + const sessionId = randomUUID(); + const firstUser = randomUUID(); + const toolUse = randomUUID(); + const toolResult = randomUUID(); + const steeredMessage = randomUUID(); + const queuedCommand = randomUUID(); + const transcriptPath = path.join(projectDir, `${sessionId}.jsonl`); + writeTranscript(transcriptPath, sessionId, [ + { type: "user", uuid: firstUser, parentUuid: null, text: "first" }, + { type: "assistant", uuid: toolUse, parentUuid: firstUser, text: "running a tool" }, + { type: "user", uuid: toolResult, parentUuid: toolUse, text: "tool output" }, + // What Claude Code writes when it reads a steered message between two tool calls. + JSON.stringify({ + type: "attachment", + uuid: queuedCommand, + parentUuid: toolResult, + sessionId, + attachment: { + type: "queued_command", + prompt: [{ type: "text", text: "steered" }], + source_uuid: steeredMessage, + }, + }), + { type: "assistant", uuid: randomUUID(), parentUuid: queuedCommand, text: "reply to steer" }, + ]); + + const parent = await findSteeredMessageParent(transcriptPath, steeredMessage); + expect(parent).toBe(toolResult); + expect(await findSteeredMessageParent(transcriptPath, randomUUID())).toBeNull(); + + let currentSessionId = sessionId; + await revertClaudeConversation({ + sdk: realClaudeRewindSdk, + sessionId, + transcriptPath, + messageId: parent!, + setSessionId: (nextSessionId) => { + currentSessionId = nextSessionId; + }, + }); + expect(readMessageTexts(path.join(projectDir, `${currentSessionId}.jsonl`))).toEqual([ + "first", + "running a tool", + "tool output", + ]); + }); }); + +test.runIf(process.platform === "linux")( + "releases the transcript descriptor after an early steer match", + async () => { + const artifacts = path.resolve(".artifacts"); + mkdirSync(artifacts, { recursive: true }); + const root = mkdtempSync(path.join(artifacts, "claude-rewind-descriptor-")); + const transcriptPath = path.join(root, "session.jsonl"); + const matchingEntry = { + type: "attachment", + parentUuid: "before-steer", + attachment: { type: "queued_command", source_uuid: "steered-message" }, + }; + const unreadEntry = JSON.stringify({ type: "assistant", message: "x".repeat(1024) }); + writeFileSync( + transcriptPath, + JSON.stringify(matchingEntry) + "\n" + (unreadEntry + "\n").repeat(1200), + ); + const openDescriptors = () => + readdirSync("/proc/self/fd").filter((descriptor) => { + try { + return readlinkSync(path.join("/proc/self/fd", descriptor)) === transcriptPath; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; + throw error; + } + }).length; + try { + expect(openDescriptors()).toBe(0); + for (let attempt = 0; attempt < 5; attempt++) { + await expect(findSteeredMessageParent(transcriptPath, "steered-message")).resolves.toBe( + "before-steer", + ); + } + await expect.poll(openDescriptors, { timeout: 1000 }).toBe(0); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }, +); diff --git a/packages/server/src/server/agent/providers/claude/rewind.ts b/packages/server/src/server/agent/providers/claude/rewind.ts index 91183687e0..75607c184b 100644 --- a/packages/server/src/server/agent/providers/claude/rewind.ts +++ b/packages/server/src/server/agent/providers/claude/rewind.ts @@ -1,5 +1,7 @@ +import { createReadStream } from "node:fs"; import { appendFile, readFile } from "node:fs/promises"; import path from "node:path"; +import { createInterface } from "node:readline"; import { forkSession as claudeForkSession, type Query, @@ -70,6 +72,54 @@ function isSessionStoreEntry(value: unknown): value is SessionStoreEntry { ); } +/** + * The entry a message steered into a running turn follows. Claude Code gives such a message no + * entry of its own: it records a queued_command attachment, under the uuid Paseo minted for the + * message, hung off the entry it was read after. Forking at that entry drops the message and + * everything after it. Null when the transcript holds no such attachment. + */ +export async function findSteeredMessageParent( + transcriptPath: string, + messageId: string, +): Promise { + const input = createReadStream(transcriptPath, { encoding: "utf8" }); + const lines = createInterface({ + input, + crlfDelay: Infinity, + }); + try { + for await (const line of lines) { + if (!line.includes(messageId) || !line.includes('"queued_command"')) continue; + let entry: unknown; + try { + entry = JSON.parse(line); + } catch { + continue; + } + const record = entry as { + type?: unknown; + parentUuid?: unknown; + attachment?: { type?: unknown; source_uuid?: unknown }; + }; + if ( + record.type === "attachment" && + record.attachment?.type === "queued_command" && + record.attachment.source_uuid === messageId && + typeof record.parentUuid === "string" + ) { + return record.parentUuid; + } + } + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; + throw error; + } finally { + lines.close(); + input.destroy(); + } + return null; +} + export async function revertClaudeConversation(input: { sdk: ClaudeRewindSdk; sessionId: string | null; From e02fa9a5f893ff809f8850d0b9afd9c21c9c7577 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sat, 31 Oct 2026 14:55:17 +0000 Subject: [PATCH 148/173] fix(acp): report provider startup exits without waiting for timeout (#8384) * fix(server): resolve ACP providers installed after the daemon started Windows hands a new process the PATH its parent had when it started. The daemon's supervisor therefore keeps the PATH it inherited at launch, and any CLI installed afterwards stays invisible to it. A provider installed after the daemon started reported "not installed" forever, even though the binary was on PATH in a fresh shell. Refresh the process PATH from the Windows user/machine registry environment when the daemon worker starts. Existing entries keep their order and take precedence; registry entries are appended. This runs once at startup so PATH-isolated availability checks and explicit env overrides stay authoritative. Spawn the absolute path the launcher resolver verified rather than the bare command. The resolver already finds installs outside the daemon's inherited PATH (Winget packages, directories added after startup); the resolved path was previously discarded. An ACP agent that exits during the handshake never rejects the SDK's initialize request, so the provider refresh waited out its full 120s deadline and reported "Timed out refreshing after 120000ms; pending: initialize" instead of the child's stderr. Race a child-exit rejection against initialize so the real failure surfaces. Also repair persisted MiniMax Code commands. The first catalog entry ran `npx -y @minimax-ai/code@ acp`; npx derives the executable name from the package name (`code`), but the package publishes `mcode`, so npm exited before the ACP handshake. The catalog was fixed separately, but commands already persisted by an older client were never migrated. * fix(acp): report startup exits across probes and sessions Extend the shared process failure handler so initialize rejects with stderr after the child exits, including session creation. Keep this fix scoped to startup error reporting; remove the separate PATH and persisted-command changes. Co-authored-by: peanut_hzm * fix(acp): validate provider options before starting probes Reject malformed options before creating a child or its process-failure promise, so cleanup cannot cause an unhandled rejection in the daemon. --------- Co-authored-by: peanut_hzm Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../src/server/agent/providers/acp-agent.ts | 40 ++++--- .../agent/providers/acp-startup-exit.test.ts | 112 ++++++++++++++++++ 2 files changed, 138 insertions(+), 14 deletions(-) create mode 100644 packages/server/src/server/agent/providers/acp-startup-exit.test.ts diff --git a/packages/server/src/server/agent/providers/acp-agent.ts b/packages/server/src/server/agent/providers/acp-agent.ts index e26b6e4ade..d2973d42c7 100644 --- a/packages/server/src/server/agent/providers/acp-agent.ts +++ b/packages/server/src/server/agent/providers/acp-agent.ts @@ -142,14 +142,26 @@ function assertChildWithPipes( } } -// Node reports a failed spawn (missing binary or missing cwd) as a child -// `error` event; without a listener it becomes an uncaught exception. -function rejectOnSpawnError(child: ChildProcess, stderrChunks: string[]): Promise { +// Watch process failures as well as spawn errors: the SDK leaves initialize +// pending when the child exits without replying. `close` waits for stderr to +// drain, so the failure includes the launcher's diagnostic. +function rejectOnProcessFailure(child: ChildProcess, stderrChunks: string[]): Promise { return new Promise((_, reject) => { child.once("error", (error) => { const stderr = stderrChunks.join("").trim(); reject(new Error(stderr ? `${String(error)}\n${stderr}` : String(error))); }); + child.once("close", (code, signal) => { + const stderr = stderrChunks.join("").trim(); + const status = signal ? `signal ${signal}` : `exit code ${code ?? "unknown"}`; + reject( + new Error( + `ACP agent process exited before initialization completed (${status})${ + stderr ? `\n${stderr}` : "" + }`, + ), + ); + }); }); } @@ -542,7 +554,7 @@ interface ACPProcessTransport { connection: ClientSideConnection; stderrChunks: string[]; spawnReady: Promise; - spawnError: Promise; + processError: Promise; } interface ACPImportPromptPreviews { @@ -1380,6 +1392,7 @@ export class ACPAgentClient implements AgentClient { client?: ACPClient; }, ): Promise { + const configuredOptions = ACPProviderOptionsSchema.parse(options?.providerOptions ?? {}); const transport = await this.spawnTransport(launchEnv, options?.client); const probe: UninitializedACPProcess = { child: transport.child, @@ -1391,7 +1404,7 @@ export class ACPAgentClient implements AgentClient { const initialize = await this.initializeTransport( transport, options?.initializeTimeoutMs, - options?.providerOptions, + configuredOptions.clientCapabilities, ); const initializedProbe: SpawnedACPProcess = { ...probe, @@ -1425,7 +1438,7 @@ export class ACPAgentClient implements AgentClient { stderrChunks.push(chunk.toString()); }); - const spawnErrorPromise = rejectOnSpawnError(child, stderrChunks); + const processErrorPromise = rejectOnProcessFailure(child, stderrChunks); const spawnReadyPromise = new Promise((resolve) => { child.once("spawn", () => { resolve(); @@ -1444,16 +1457,15 @@ export class ACPAgentClient implements AgentClient { connection, stderrChunks, spawnReady: spawnReadyPromise, - spawnError: spawnErrorPromise, + processError: processErrorPromise, }; } protected async initializeTransport( transport: ACPProcessTransport, initializeTimeoutMs?: number, - providerOptions?: Record, + clientCapabilities?: ACPClientCapabilities, ): Promise { - const configuredOptions = ACPProviderOptionsSchema.parse(providerOptions ?? {}); let timeout: ReturnType | null = null; const initializeTimeoutPromise = initializeTimeoutMs ? new Promise((_, reject) => { @@ -1470,11 +1482,11 @@ export class ACPAgentClient implements AgentClient { protocolVersion: PROTOCOL_VERSION, clientCapabilities: buildACPClientCapabilities( this.clientCapabilityMeta, - configuredOptions.clientCapabilities ?? this.clientCapabilities, + clientCapabilities ?? this.clientCapabilities, ), clientInfo: { name: "Paseo", version: "dev" }, }), - transport.spawnError, + transport.processError, ...(initializeTimeoutPromise ? [initializeTimeoutPromise] : []), ]), ); @@ -1555,7 +1567,7 @@ export class ACPAgentClient implements AgentClient { try { transport = await this.spawnTransport(PROBE_ENV); await withTimeout( - Promise.race([transport.spawnReady, transport.spawnError]), + Promise.race([transport.spawnReady, transport.processError]), phaseTimeoutMs, `ACP spawn timed out after ${phaseTimeoutMs}ms`, ); @@ -2910,7 +2922,7 @@ export class ACPAgentSession implements AgentSession, ACPClient { child.stderr.on("data", (chunk: Buffer | string) => { stderrChunks.push(chunk.toString()); }); - const spawnError = rejectOnSpawnError(child, stderrChunks); + const processError = rejectOnProcessFailure(child, stderrChunks); child.once("exit", (code, signal) => { if (this.closed || this.historyRuntimeReleased) { return; @@ -2947,7 +2959,7 @@ export class ACPAgentSession implements AgentSession, ACPClient { ), clientInfo: { name: "Paseo", version: "dev" }, }), - spawnError, + processError, ]), ); diff --git a/packages/server/src/server/agent/providers/acp-startup-exit.test.ts b/packages/server/src/server/agent/providers/acp-startup-exit.test.ts new file mode 100644 index 0000000000..39ae6f743e --- /dev/null +++ b/packages/server/src/server/agent/providers/acp-startup-exit.test.ts @@ -0,0 +1,112 @@ +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { describe, expect, test } from "vitest"; + +import { GenericACPAgentClient } from "./generic-acp-agent.js"; +import { createTestLogger } from "../../../test-utils/test-logger.js"; + +// Exercise the public catalog API with a real child, including stdout EOF and +// stderr draining. No provider installation or external service is involved. +const failingCommand: [string, ...string[]] = [ + process.execPath, + "-e", + "process.stdin.once('data', () => { process.stderr.write('launcher failed: fixture startup error\\n'); process.exitCode = 1; process.stdin.destroy(); });", +]; + +describe("ACP catalog startup failures", () => { + test("reports a process that exits during initialize with its stderr", async () => { + const client = new GenericACPAgentClient({ + logger: createTestLogger(), + command: failingCommand, + }); + await expect( + client.fetchCatalog({ scope: "workspace", cwd: process.cwd(), force: true }), + ).rejects.toThrow(/launcher failed: fixture startup error/); + }, 5_000); + + test("session startup reports the same process exit with its stderr", async () => { + const client = new GenericACPAgentClient({ + logger: createTestLogger(), + command: failingCommand, + }); + await expect(client.createSession({ provider: "acp", cwd: process.cwd() })).rejects.toThrow( + /launcher failed: fixture startup error/, + ); + }, 5_000); + + test("provider diagnostics report the startup exit instead of an initialize timeout", async () => { + const client = new GenericACPAgentClient({ + logger: createTestLogger(), + command: failingCommand, + diagnosticPhaseTimeoutMs: 2_000, + }); + const { diagnostic } = await client.getDiagnostic(); + expect(diagnostic).toContain( + "ACP agent process exited before initialization completed (exit code 1)", + ); + expect(diagnostic).toContain("launcher failed: fixture startup error"); + expect(diagnostic).not.toContain("initialize timed out"); + }); + + test("invalid provider options reject without crashing the host process", async () => { + const clientModule = new URL("./generic-acp-agent.ts", import.meta.url).href; + const loggerModule = new URL("../../../test-utils/test-logger.ts", import.meta.url).href; + const script = ` + import { GenericACPAgentClient } from ${JSON.stringify(clientModule)}; + import { createTestLogger } from ${JSON.stringify(loggerModule)}; + const client = new GenericACPAgentClient({ + logger: createTestLogger(), + command: [process.execPath, '-e', 'setInterval(() => {}, 1000)'], + }); + try { + await client.fetchCatalog({ + scope: 'workspace', cwd: process.cwd(), force: true, + providerOptions: { clientCapabilities: { fs: 'invalid' } }, + }); + throw new Error('Expected invalid options to reject'); + } catch (error) { + if (error.name !== 'ZodError') throw error; + } + // Let child cleanup and Node's unhandled-rejection check complete. + await new Promise(resolve => setTimeout(resolve, 100)); + console.log('host stayed alive'); + `; + const result = await promisify(execFile)( + process.execPath, + ["--import", "tsx", "--input-type=module", "-e", script], + { timeout: 10_000 }, + ); + expect(result.stdout).toContain("host stayed alive"); + expect(result.stderr).toBe(""); + }); + + test("a successful catalog probe still returns its models and closes cleanly", async () => { + const client = new GenericACPAgentClient({ + logger: createTestLogger(), + command: [ + process.execPath, + "-e", + ` + require('node:readline').createInterface({ input: process.stdin }).on('line', (line) => { + const request = JSON.parse(line); + const result = request.method === 'initialize' + ? { protocolVersion: 1, agentCapabilities: {} } + : { sessionId: 'fixture', models: { + currentModelId: 'fixture-model', + availableModels: [{ modelId: 'fixture-model', name: 'Fixture model' }] + } }; + process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: request.id, result }) + '\\n'); + }); + `, + ], + }); + const catalog = await client.fetchCatalog({ + scope: "workspace", + cwd: process.cwd(), + force: true, + }); + expect(catalog.models).toEqual([ + expect.objectContaining({ id: "fixture-model", label: "Fixture model" }), + ]); + }); +}); From eab9ac3b03c04fdf8d3bfb67449ec4d88e7860c0 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:07:08 +0000 Subject: [PATCH 149/173] fix(acp): include late-discovered skills in initial command lists (#8387) * fix(providers): wait for the ACP command inventory to settle An ACP agent publishes its slash-command inventory in batches. MiniMax Code sends its built-in commands first, then merges in every discovered skill roughly 350ms later. `listCommands()` settled on the first batch, so a session that had to discover its commands at creation time offered the 10 built-in commands instead of the 396 the agent eventually publishes. Every skill was missing from `/` until the session was reopened and the cached inventory was read again. Wait for the inventory to go quiet (600ms without another batch) instead of for the first batch. An empty batch still settles immediately, and `initialCommandsWaitTimeoutMs` (1500ms default) still bounds the whole wait for providers that publish once or never publish at all. * test(acp): verify late commands through the provider boundary Exercise initial command discovery over real stdio, including a first batch cached before session creation returns. Keep the later skill and subsequent cached read in the same public session contract. Co-authored-by: huazhongmin --------- Co-authored-by: huazhongmin Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../server/agent/providers/acp-agent.test.ts | 68 +++++++++++- .../src/server/agent/providers/acp-agent.ts | 102 +++++++++--------- 2 files changed, 118 insertions(+), 52 deletions(-) diff --git a/packages/server/src/server/agent/providers/acp-agent.test.ts b/packages/server/src/server/agent/providers/acp-agent.test.ts index e902493dcb..7e50b32cf5 100644 --- a/packages/server/src/server/agent/providers/acp-agent.test.ts +++ b/packages/server/src/server/agent/providers/acp-agent.test.ts @@ -1,6 +1,6 @@ import { type ChildProcess, type ChildProcessWithoutNullStreams } from "node:child_process"; import { EventEmitter } from "node:events"; -import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { createRequire } from "node:module"; import { tmpdir } from "node:os"; import path from "node:path"; @@ -2634,6 +2634,72 @@ describe("ACPAgentSession slash commands", () => { }, ]); }); + + test("lists late command batches through the public ACP client", async () => { + const artifacts = path.resolve(".artifacts"); + await mkdir(artifacts, { recursive: true }); + const directory = await mkdtemp(path.join(artifacts, "acp-command-inventory-")); + const script = path.join(directory, "agent.mjs"); + await writeFile( + script, + ` +import { createInterface } from "node:readline"; +const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n"); +const help = { name: "help", description: "Show available commands" }; +const skill = { name: "xlsx", description: "Work with spreadsheets", input: { hint: "[instructions]" } }; +const publish = (commands) => send({ + jsonrpc: "2.0", method: "session/update", params: { + sessionId: "inventory-session", update: { + sessionUpdate: "available_commands_update", availableCommands: commands, + }, + }, +}); +createInterface({ input: process.stdin }).on("line", (line) => { + const request = JSON.parse(line); + if (request.method === "initialize") { + send({ jsonrpc: "2.0", id: request.id, result: { protocolVersion: 1, agentCapabilities: {} } }); + } else if (request.method === "session/new") { + // The first batch is already cached when createSession returns. + publish([help]); + send({ jsonrpc: "2.0", id: request.id, result: { sessionId: "inventory-session" } }); + setTimeout(() => publish([help]), 100); + setTimeout(() => publish([help, skill]), 350); + } else if (request.id !== undefined) { + send({ jsonrpc: "2.0", id: request.id, error: { code: -32601, message: "Method not found" } }); + } +}); +`, + ); + const client = new GenericACPAgentClient({ + logger: createTestLogger(), + command: [process.execPath, script], + }); + try { + const session = await client.createSession({ provider: "acp", cwd: directory }); + try { + const commands = await session.listCommands!(); + expect(commands).toEqual([ + { + name: "help", + description: "Show available commands", + argumentHint: "", + kind: "command", + }, + { + name: "xlsx", + description: "Work with spreadsheets", + argumentHint: "[instructions]", + kind: "command", + }, + ]); + expect(await session.listCommands!()).toEqual(commands); + } finally { + await session.close(); + } + } finally { + await rm(directory, { recursive: true, force: true }); + } + }); }); describe("ACPAgentSession", () => { diff --git a/packages/server/src/server/agent/providers/acp-agent.ts b/packages/server/src/server/agent/providers/acp-agent.ts index d2973d42c7..6831274d2d 100644 --- a/packages/server/src/server/agent/providers/acp-agent.ts +++ b/packages/server/src/server/agent/providers/acp-agent.ts @@ -337,6 +337,14 @@ const ACP_CLOSE_REQUEST_TIMEOUT_MS = 2_000; const ACP_IMPORT_HISTORY_LOAD_TIMEOUT_MS = 30_000; const ACP_IMPORT_HISTORY_BUDGET_MS = 60_000; +/** + * An ACP agent publishes its slash-command inventory incrementally. Wait this + * long without another batch before treating the inventory as complete. MiniMax + * publishes its skills about 350ms after its built-in commands. + */ +const COMMAND_INVENTORY_QUIET_MS = 600; +const COMMAND_INVENTORY_POLL_MS = 25; + function summarizeMalformedACPStdoutError(error: unknown): { type: string; message: string } { return { type: error instanceof Error ? error.name : typeof error, @@ -1765,7 +1773,8 @@ export class ACPAgentSession implements AgentSession, ACPClient { private lastActivityAt: string | null = null; private configOptions: SessionConfigOption[] = []; private cachedCommands: AgentSlashCommand[] = []; - private commandsReadyDeferred: { promise: Promise; resolve: () => void } | null = null; + /** When the last command batch arrived; null while nothing has been published. */ + private commandsUpdatedAt: number | null = null; private commandsReadySettled = false; private waitForInitialCommands: boolean; private initialCommandsWaitTimeoutMs: number; @@ -2063,58 +2072,39 @@ export class ACPAgentSession implements AgentSession, ACPClient { ]; } - private ensureCommandsReadyDeferred(): void { - if (this.commandsReadyDeferred || this.commandsReadySettled || this.cachedCommands.length > 0) { - return; - } - - let resolve!: () => void; - const promise = new Promise((r) => { - resolve = r; - }); - this.commandsReadyDeferred = { promise, resolve }; - } - private settleCommandsReady(): void { - if (this.commandsReadySettled) { - return; - } this.commandsReadySettled = true; - this.commandsReadyDeferred?.resolve(); - this.commandsReadyDeferred = null; } - private async waitForCommandsReady(): Promise { - const deferred = this.commandsReadyDeferred; - if (!deferred) { - return; - } - - let timer: ReturnType | null = null; - try { - await Promise.race([ - deferred.promise, - new Promise((resolve) => { - timer = setTimeout(resolve, this.initialCommandsWaitTimeoutMs); - }), - ]); - } finally { - if (timer) { - clearTimeout(timer); - } + /** + * Providers publish their command inventory incrementally. MiniMax sends its + * built-in commands twice, then a third batch about 350ms later that merges in + * every discovered skill. Returning after the first batch loses the skills. + * + * Wait for the inventory to go quiet rather than for the first batch. The + * quiet window must exceed the gap between a provider's own batches; 600ms + * covers MiniMax with margin. `initialCommandsWaitTimeoutMs` still bounds the + * whole wait for providers that publish once or never publish at all. + */ + private async waitForCommandsToSettle(): Promise { + const deadline = Date.now() + this.initialCommandsWaitTimeoutMs; + while (!this.commandsReadySettled && !this.closed) { + const remaining = deadline - Date.now(); + if (remaining <= 0) return; + const quietFor = this.commandsUpdatedAt === null ? 0 : Date.now() - this.commandsUpdatedAt; + if (quietFor >= COMMAND_INVENTORY_QUIET_MS) return; + await new Promise((resolve) => + setTimeout(resolve, Math.min(remaining, COMMAND_INVENTORY_POLL_MS)), + ); } } async listCommands(): Promise { - if (this.cachedCommands.length > 0) { - return this.cachedCommands; - } - if (!this.waitForInitialCommands || this.closed) { + if (this.commandsReadySettled || this.closed || !this.waitForInitialCommands) { return this.cachedCommands; } - this.ensureCommandsReadyDeferred(); - await this.waitForCommandsReady(); + await this.waitForCommandsToSettle(); this.settleCommandsReady(); return this.cachedCommands; } @@ -2745,14 +2735,12 @@ export class ACPAgentSession implements AgentSession, ACPClient { } } - // Cache an asynchronously-delivered slash-command batch and unblock any - // listCommands() call that is waiting on the initial batch. Used when a - // provider supplies an extensionCommandsParser whose result arrives after - // session/new (e.g. via a vendor extension notification). The ready gate is - // always settled — even for an empty batch — so a provider that legitimately - // reports no commands does not leave listCommands() blocked for the full - // initial-commands timeout. An optional sessionId scopes the batch to this - // session; notifications addressed to a different session are ignored. + // Cache an asynchronously-delivered slash-command batch from a provider that + // supplies an extensionCommandsParser (e.g. a vendor extension notification). + // An empty batch is the provider saying it has no commands, so it settles the + // waiter immediately instead of letting it wait out the quiet window. An + // optional sessionId scopes the batch to this session; notifications + // addressed to a different session are ignored. private applyResolvedCommands( commands: AgentSlashCommand[], options?: { sessionId?: string }, @@ -2766,7 +2754,13 @@ export class ACPAgentSession implements AgentSession, ACPClient { } if (commands.length > 0) { + this.commandsUpdatedAt = Date.now(); this.cachedCommands = commands; + // A non-empty batch may be followed by more. Let the quiet window decide + // when the inventory is complete rather than settling here; an empty + // batch is the provider saying it has nothing, which must still unblock + // the waiter immediately. + return; } this.settleCommandsReady(); } @@ -3150,13 +3144,19 @@ export class ACPAgentSession implements AgentSession, ACPClient { this.handleUsageUpdate(update); return pendingUserEvents; case "available_commands_update": + this.commandsUpdatedAt = Date.now(); this.cachedCommands = update.availableCommands.map((command) => ({ name: command.name, description: command.description, argumentHint: command.input?.hint ?? "", kind: "command", })); - this.settleCommandsReady(); + // An empty batch means the agent has no commands and would otherwise + // wait out the whole quiet window. A non-empty batch may be one of + // several, so completion belongs to the quiet window. + if (update.availableCommands.length === 0) { + this.settleCommandsReady(); + } return pendingUserEvents; default: return pendingUserEvents; From 58eafd81e587d758d391c18b6b9b34de86f05962 Mon Sep 17 00:00:00 2001 From: QTom <22166516+DaydreamCoding@users.noreply.github.com> Date: Sun, 1 Nov 2026 01:01:27 +0800 Subject: [PATCH 150/173] fix(app): fall back to native terminal copy/paste without the Clipboard API (#8230) Browsers omit navigator.clipboard outside secure contexts, such as the daemon web UI served over plain http on a Tailscale or LAN address. The non-Mac Ctrl+C/Ctrl+V terminal shortcuts then threw synchronously, and Ctrl+V had already prevented the native paste, so terminal copy/paste broke. When the Clipboard API is unavailable, the shortcuts now leave the default action alone so xterm's native copy/paste event handlers do the work, and the browser clipboard rejects instead of throwing. Co-authored-by: Claude Opus 5.5 --- .../runtime/terminal-emulator-runtime.test.ts | 95 +++++++++++++++++++ .../runtime/terminal-emulator-runtime.ts | 64 +++++++++---- 2 files changed, 140 insertions(+), 19 deletions(-) diff --git a/packages/app/src/terminal/runtime/terminal-emulator-runtime.test.ts b/packages/app/src/terminal/runtime/terminal-emulator-runtime.test.ts index a6939aaecb..8b90839154 100644 --- a/packages/app/src/terminal/runtime/terminal-emulator-runtime.test.ts +++ b/packages/app/src/terminal/runtime/terminal-emulator-runtime.test.ts @@ -82,6 +82,7 @@ import { createTerminalResizeEvent, encodeTerminalOutput, TerminalEmulatorRuntime, + type TerminalClipboard, } from "./terminal-emulator-runtime"; interface StubTerminal { @@ -638,3 +639,97 @@ describe("terminal-emulator-runtime", () => { expect(fitAndEmitResize).not.toHaveBeenCalled(); }); }); + +describe("terminal-emulator-runtime clipboard shortcuts", () => { + type KeyHandler = (event: KeyboardEvent) => boolean; + + function createClipboard(available: boolean) { + return { + isAvailable: () => available, + readText: vi.fn(async () => "clipboard text"), + read: vi.fn(async () => []), + writeText: vi.fn(async (_text: string) => undefined), + } satisfies TerminalClipboard; + } + + function attachKeyHandler(input: { clipboard: TerminalClipboard; selection: string }) { + const runtime = new TerminalEmulatorRuntime({ isMac: false }, input.clipboard); + let handler: KeyHandler | null = null; + const paste = vi.fn(); + runtime.attachKeyEventHandler({ + attachCustomKeyEventHandler: (next: KeyHandler) => { + handler = next; + }, + hasSelection: () => input.selection.length > 0, + getSelection: () => input.selection, + paste, + input: vi.fn(), + scrollToBottom: vi.fn(), + }); + if (!handler) throw new Error("key handler was not attached"); + return { handler: handler as KeyHandler, paste }; + } + + function ctrlKey(key: string) { + const preventDefault = vi.fn(); + const event = { + type: "keydown", + key, + isComposing: false, + ctrlKey: true, + shiftKey: false, + altKey: false, + metaKey: false, + preventDefault, + stopPropagation: vi.fn(), + } as unknown as KeyboardEvent; + return { event, preventDefault }; + } + + it("leaves Ctrl+C with a selection to the native copy event without the Clipboard API", () => { + const clipboard = createClipboard(false); + const { handler } = attachKeyHandler({ clipboard, selection: "selected text" }); + const { event, preventDefault } = ctrlKey("c"); + + expect(handler(event)).toBe(false); + expect(clipboard.writeText).not.toHaveBeenCalled(); + expect(preventDefault).not.toHaveBeenCalled(); + }); + + it("leaves Ctrl+V to the native paste event without the Clipboard API", () => { + const clipboard = createClipboard(false); + const { handler, paste } = attachKeyHandler({ clipboard, selection: "" }); + const { event, preventDefault } = ctrlKey("v"); + + expect(handler(event)).toBe(false); + expect(clipboard.readText).not.toHaveBeenCalled(); + expect(preventDefault).not.toHaveBeenCalled(); + expect(paste).not.toHaveBeenCalled(); + }); + + it("lets xterm send ^C for Ctrl+C without a selection when the Clipboard API is missing", () => { + const clipboard = createClipboard(false); + const { handler } = attachKeyHandler({ clipboard, selection: "" }); + const { event, preventDefault } = ctrlKey("c"); + + expect(handler(event)).toBe(true); + expect(clipboard.writeText).not.toHaveBeenCalled(); + expect(preventDefault).not.toHaveBeenCalled(); + }); + + it("copies and pastes through the Clipboard API when it is available", async () => { + const clipboard = createClipboard(true); + const { handler, paste } = attachKeyHandler({ clipboard, selection: "selected text" }); + + const copy = ctrlKey("c"); + expect(handler(copy.event)).toBe(false); + expect(clipboard.writeText).toHaveBeenCalledWith("selected text"); + expect(copy.preventDefault).not.toHaveBeenCalled(); + + const pasteKey = ctrlKey("v"); + expect(handler(pasteKey.event)).toBe(false); + expect(pasteKey.preventDefault).toHaveBeenCalledTimes(1); + expect(clipboard.readText).toHaveBeenCalledTimes(1); + await vi.waitFor(() => expect(paste).toHaveBeenCalledWith("clipboard text")); + }); +}); diff --git a/packages/app/src/terminal/runtime/terminal-emulator-runtime.ts b/packages/app/src/terminal/runtime/terminal-emulator-runtime.ts index a7460f7f80..0e1f88dafb 100644 --- a/packages/app/src/terminal/runtime/terminal-emulator-runtime.ts +++ b/packages/app/src/terminal/runtime/terminal-emulator-runtime.ts @@ -182,15 +182,26 @@ function withOverviewRulerBorderHidden(theme: ITheme): ITheme { } export interface TerminalClipboard { + /** Whether the async Clipboard API is usable. Browsers omit it outside secure contexts. */ + isAvailable?(): boolean; readText(): Promise; read(): Promise[]>; writeText(text: string): Promise; } +function getBrowserClipboard(): Clipboard | undefined { + return typeof navigator !== "undefined" ? navigator.clipboard : undefined; +} + +function rejectUnavailableClipboard(): Promise { + return Promise.reject(new Error("Clipboard API is unavailable")); +} + const browserClipboard: TerminalClipboard = { - readText: () => navigator.clipboard.readText(), - read: () => navigator.clipboard.read(), - writeText: (text) => navigator.clipboard.writeText(text), + isAvailable: () => !!getBrowserClipboard(), + readText: () => getBrowserClipboard()?.readText() ?? rejectUnavailableClipboard(), + read: () => getBrowserClipboard()?.read() ?? rejectUnavailableClipboard(), + writeText: (text) => getBrowserClipboard()?.writeText(text) ?? rejectUnavailableClipboard(), }; async function readClipboardImage(clipboard: TerminalClipboard): Promise { @@ -368,22 +379,7 @@ export class TerminalEmulatorRuntime { !event.altKey && !event.metaKey ) { - const key = event.key.toLowerCase(); - - // Ctrl+C: copy selection to clipboard if text is selected, otherwise let xterm send SIGINT - if (key === "c" && terminal.hasSelection()) { - void this.clipboard.writeText(terminal.getSelection()); - return false; - } - - // Ctrl+V: paste clipboard text, or the clipboard image when there is no text - if (key === "v") { - event.preventDefault(); - this.pasteClipboard(terminal); - return false; - } - - return true; + return !this.handleCtrlClipboardShortcut(terminal, event); } if (this.maybeSendMacEditingShortcut(terminal, event)) { @@ -432,6 +428,36 @@ export class TerminalEmulatorRuntime { }); } + /** Returns true when a non-Mac Ctrl+C / Ctrl+V clipboard shortcut was handled. */ + private handleCtrlClipboardShortcut( + terminal: Pick, + event: KeyboardEvent, + ): boolean { + const key = event.key.toLowerCase(); + // Without the Clipboard API (e.g. plain http on a LAN address), the browser's native + // copy/paste events still fire and xterm handles them, so leave the default action. + const clipboardAvailable = this.clipboard.isAvailable?.() ?? true; + + // Ctrl+C: copy selection to clipboard if text is selected, otherwise let xterm send SIGINT + if (key === "c" && terminal.hasSelection()) { + if (clipboardAvailable) { + void this.clipboard.writeText(terminal.getSelection()); + } + return true; + } + + // Ctrl+V: paste clipboard text, or the clipboard image when there is no text + if (key === "v") { + if (clipboardAvailable) { + event.preventDefault(); + this.pasteClipboard(terminal); + } + return true; + } + + return false; + } + private handleFindShortcut(event: KeyboardEvent): boolean { if (!isFindShortcut(event, this.options) || !this.callbacks.onFindRequest) return false; event.preventDefault(); From 2dd931c8bdd3714b1c958688b3a3d9f9659fb8fd Mon Sep 17 00:00:00 2001 From: QTom <22166516+DaydreamCoding@users.noreply.github.com> Date: Sun, 1 Nov 2026 02:06:12 +0800 Subject: [PATCH 151/173] fix(app): accept host:port and URLs in the direct connection host field (#8223) The direct connection form treated any host containing a colon as a bare IPv6 address, so entering "100.66.69.36:6767" or "tcp://host:6767" built "tcp://[100.66.69.36:6767]:6767" and surfaced the browser's raw "Invalid URL" error. Normalize the host input first: strip a leading scheme and any path/query/fragment, split "host:port" (the inline port wins), and only treat unbracketed hosts with two or more colons as IPv6. Co-authored-by: Claude Opus 5.5 --- .../app/src/components/add-host-modal.tsx | 37 ++-------- .../components/direct-connection-host.test.ts | 68 ++++++++++++++++++ .../src/components/direct-connection-host.ts | 70 +++++++++++++++++++ 3 files changed, 142 insertions(+), 33 deletions(-) create mode 100644 packages/app/src/components/direct-connection-host.test.ts create mode 100644 packages/app/src/components/direct-connection-host.ts diff --git a/packages/app/src/components/add-host-modal.tsx b/packages/app/src/components/add-host-modal.tsx index 653d69c4f1..aa0c65b638 100644 --- a/packages/app/src/components/add-host-modal.tsx +++ b/packages/app/src/components/add-host-modal.tsx @@ -6,15 +6,12 @@ import { useIsCompactFormFactor } from "@/constants/layout"; import { Check, ChevronDown, ChevronRight, Eye, EyeOff, Link2 } from "lucide-react-native"; import type { HostProfile } from "@/types/host-connection"; import { useHosts, useHostMutations } from "@/runtime/host-runtime"; -import { - parseConnectionUri, - serializeConnectionUri, - serializeConnectionUriForStorage, -} from "@/utils/daemon-endpoints"; +import { parseConnectionUri, serializeConnectionUri } from "@/utils/daemon-endpoints"; import { buildConnectionFailureCopy } from "./connection-failure-copy"; import { AdaptiveModalSheet, AdaptiveTextInput, type SheetHeader } from "./adaptive-modal-sheet"; import { Button } from "@/components/ui/button"; import { PairingTargetTracker } from "./pair-link-credentials"; +import { buildDirectConnectionUri } from "./direct-connection-host"; const FLEX_ONE_STYLE = { flex: 1 } as const; @@ -139,37 +136,11 @@ const styles = StyleSheet.create((theme) => ({ }, })); -function isIpv6Host(host: string): boolean { - return host.includes(":") && !host.startsWith("[") && !host.endsWith("]"); -} - -function buildConnectionUriFromDraft( - draft: DirectConnectionDraft, - labels: DirectConnectionLabels, -): string { - const host = draft.host.trim(); - const port = Number(draft.port.trim()); - if (!host) { - throw new Error(labels.hostRequired); - } - if (!Number.isInteger(port) || port < 1 || port > 65535) { - throw new Error(labels.invalidPort); - } - - return serializeConnectionUriForStorage({ - host, - port, - isIpv6: isIpv6Host(host), - useTls: draft.useTls, - ...(draft.password ? { password: draft.password } : {}), - }); -} - function prepareDirectConnection( draft: DirectConnectionDraft, labels: DirectConnectionLabels, ): PreparedDirectConnection { - const parsed = parseConnectionUri(buildConnectionUriFromDraft(draft, labels)); + const parsed = parseConnectionUri(buildDirectConnectionUri(draft, labels)); const endpoint = parsed.isIpv6 ? `[${parsed.host}]:${parsed.port}` : `${parsed.host}:${parsed.port}`; @@ -420,7 +391,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod advancedTarget.current = new PairingTargetTracker("", true); try { setAdvancedUri( - buildConnectionUriFromDraft({ host, port, useTls, password }, directConnectionLabels), + buildDirectConnectionUri({ host, port, useTls, password }, directConnectionLabels), ); } catch { setAdvancedUri(""); diff --git a/packages/app/src/components/direct-connection-host.test.ts b/packages/app/src/components/direct-connection-host.test.ts new file mode 100644 index 0000000000..0a2411215a --- /dev/null +++ b/packages/app/src/components/direct-connection-host.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it } from "vitest"; +import { buildDirectConnectionUri, normalizeDirectConnectionHost } from "./direct-connection-host"; + +const labels = { + hostRequired: "host required", + invalidPort: "invalid port", +}; + +function buildUri(host: string, port = "6767"): string { + return buildDirectConnectionUri({ host, port, useTls: false, password: "" }, labels); +} + +describe("normalizeDirectConnectionHost", () => { + it.each([ + ["100.66.69.36", { host: "100.66.69.36", port: null, isIpv6: false }], + [" 100.66.69.36 ", { host: "100.66.69.36", port: null, isIpv6: false }], + ["100.66.69.36:6767", { host: "100.66.69.36", port: "6767", isIpv6: false }], + ["tcp://100.66.69.36:6767", { host: "100.66.69.36", port: "6767", isIpv6: false }], + ["http://100.66.69.36:6767/path?x=1#y", { host: "100.66.69.36", port: "6767", isIpv6: false }], + ["HTTPS://example.test", { host: "example.test", port: null, isIpv6: false }], + ["my-host.local:7000", { host: "my-host.local", port: "7000", isIpv6: false }], + ["[::1]", { host: "::1", port: null, isIpv6: true }], + ["[::1]:7000", { host: "::1", port: "7000", isIpv6: true }], + ["::1", { host: "::1", port: null, isIpv6: true }], + ["fe80::1", { host: "fe80::1", port: null, isIpv6: true }], + ["", { host: "", port: null, isIpv6: false }], + ])("normalizes %j", (input, expected) => { + expect(normalizeDirectConnectionHost(input)).toEqual(expected); + }); +}); + +describe("buildDirectConnectionUri", () => { + it.each([ + ["100.66.69.36", "tcp://100.66.69.36:6767"], + ["100.66.69.36:6767", "tcp://100.66.69.36:6767"], + ["tcp://100.66.69.36:6767", "tcp://100.66.69.36:6767"], + ["http://100.66.69.36:6767/path?x", "tcp://100.66.69.36:6767"], + ["my-host.local:6767", "tcp://my-host.local:6767"], + ["[::1]", "tcp://[::1]:6767"], + ["[::1]:7000", "tcp://[::1]:7000"], + ["::1", "tcp://[::1]:6767"], + ["fe80::1", "tcp://[fe80::1]:6767"], + ])("builds a tcp URI from host %j", (host, expected) => { + expect(buildUri(host)).toBe(expected); + }); + + it("lets a port typed in the host field override the port field", () => { + expect(buildUri("100.66.69.36:7000", "6767")).toBe("tcp://100.66.69.36:7000"); + }); + + it("keeps TLS and password settings", () => { + expect( + buildDirectConnectionUri( + { host: "tcp://example.test:443", port: "6767", useTls: true, password: "secret" }, + labels, + ), + ).toBe("tcp://example.test:443?ssl=true&password=secret"); + }); + + it.each(["", " ", "tcp://", "http:///path"])("requires a host for %j", (host) => { + expect(() => buildUri(host)).toThrow("host required"); + }); + + it("rejects an invalid port", () => { + expect(() => buildUri("100.66.69.36", "70000")).toThrow("invalid port"); + expect(() => buildUri("100.66.69.36:0")).toThrow("invalid port"); + }); +}); diff --git a/packages/app/src/components/direct-connection-host.ts b/packages/app/src/components/direct-connection-host.ts new file mode 100644 index 0000000000..db694dd7c2 --- /dev/null +++ b/packages/app/src/components/direct-connection-host.ts @@ -0,0 +1,70 @@ +import { serializeConnectionUriForStorage } from "@/utils/daemon-endpoints"; + +export interface DirectConnectionHostInput { + host: string; + port: string; + useTls: boolean; + password: string; +} + +export interface DirectConnectionHostLabels { + hostRequired: string; + invalidPort: string; +} + +export interface NormalizedDirectConnectionHost { + host: string; + /** Port typed into the host field, if any. Overrides the separate port field. */ + port: string | null; + isIpv6: boolean; +} + +const SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:\/\//i; +const BRACKETED_IPV6_PATTERN = /^\[([^\]]*)\](?::(\d*))?$/; +const HOST_WITH_PORT_PATTERN = /^([^:]+):(\d+)$/; + +/** + * Users often paste `host:port` or a full URL into the host field. + * Reduce it to a bare host (plus an optional port) before building the URI. + */ +export function normalizeDirectConnectionHost(input: string): NormalizedDirectConnectionHost { + let host = input.trim().replace(SCHEME_PATTERN, ""); + const suffixIndex = host.search(/[/?#]/); + if (suffixIndex !== -1) { + host = host.slice(0, suffixIndex); + } + + const bracketed = BRACKETED_IPV6_PATTERN.exec(host); + if (bracketed) { + return { host: bracketed[1] ?? "", port: bracketed[2] || null, isIpv6: true }; + } + + const hostWithPort = HOST_WITH_PORT_PATTERN.exec(host); + if (hostWithPort) { + return { host: hostWithPort[1] ?? "", port: hostWithPort[2] ?? null, isIpv6: false }; + } + + return { host, port: null, isIpv6: host.split(":").length > 2 }; +} + +export function buildDirectConnectionUri( + draft: DirectConnectionHostInput, + labels: DirectConnectionHostLabels, +): string { + const normalized = normalizeDirectConnectionHost(draft.host); + const port = Number((normalized.port ?? draft.port).trim()); + if (!normalized.host) { + throw new Error(labels.hostRequired); + } + if (!Number.isInteger(port) || port < 1 || port > 65535) { + throw new Error(labels.invalidPort); + } + + return serializeConnectionUriForStorage({ + host: normalized.host, + port, + isIpv6: normalized.isIpv6, + useTls: draft.useTls, + ...(draft.password ? { password: draft.password } : {}), + }); +} From 85354fcb6aae7320f638685d55b8cf4bb7cb0dd2 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sat, 31 Oct 2026 18:38:48 +0000 Subject: [PATCH 152/173] test(terminal): verify cleanup by process identity (#8389) * test(terminal): capture recurring worker publication failures * test(terminal): diagnose the remaining process cleanup wait * test(terminal): verify cleanup by process identity * test(terminal): retain native liveness proof during cleanup checks --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../src/terminal/terminal-worker-reaper.test.ts | 7 ++++++- .../src/terminal/worker-terminal-manager.test.ts | 14 +++++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/packages/server/src/terminal/terminal-worker-reaper.test.ts b/packages/server/src/terminal/terminal-worker-reaper.test.ts index a872325d31..a20d571b7f 100644 --- a/packages/server/src/terminal/terminal-worker-reaper.test.ts +++ b/packages/server/src/terminal/terminal-worker-reaper.test.ts @@ -5,6 +5,7 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { Worker } from "node:worker_threads"; import { isPlatform } from "../test-utils/platform.js"; +import { classifyTerminalProgramProcess } from "./terminal-worker-ownership.js"; import { currentBootId } from "../server/pid-lock.js"; import { createTerminalWorkerProcessInspector, @@ -260,15 +261,19 @@ describe.skipIf(isPlatform("win32"))("terminal worker reaper", () => { it("leaves a program alive when its pid now belongs to a process with another birth time", async () => { const home = makeHome(); const unrelated = spawnIdle(); + const original = { id: "t1", pid: unrelated.pid!, startedAt: "Thu Jan 1 00:00:00 1970" }; const recordPath = writeRecord(home, { pid: await goneProcessPid(), - terminals: [{ id: "t1", pid: unrelated.pid!, startedAt: "Thu Jan 1 00:00:00 1970" }], + terminals: [original], }); await reapTerminalWorkers({ paseoHome: home, inspector, gracefulMs: 0 }); expect(isAlive(unrelated.pid!)).toBe(true); expect(existsSync(recordPath)).toBe(false); + expect( + classifyTerminalProgramProcess(original, await inspector.inspect(original.pid)), + ).toMatchObject({ status: "unrelated" }); }); it("retires a record from an earlier boot without signaling anything it names", async () => { diff --git a/packages/server/src/terminal/worker-terminal-manager.test.ts b/packages/server/src/terminal/worker-terminal-manager.test.ts index 7d91ec180e..2605e62965 100644 --- a/packages/server/src/terminal/worker-terminal-manager.test.ts +++ b/packages/server/src/terminal/worker-terminal-manager.test.ts @@ -50,6 +50,7 @@ import type { WorkerTerminalState, TerminalWorkerToParentMessage, } from "./terminal-worker-protocol.js"; +import { classifyTerminalProgramProcess } from "./terminal-worker-ownership.js"; import { createTerminalWorkerProcessInspector } from "./terminal-worker-processes.js"; import { readUnconfirmedTerminalCleanup, @@ -881,8 +882,19 @@ it.each([false, true])( expect(manager.getTerminal(remaining.id)).toBeUndefined(); expect(await manager.getTerminals(cwd)).toEqual([]); - await waitForCondition(() => !isProcessAlive(remainingPid), 10000); expect(await readUnconfirmedTerminalCleanup(paseoHome)).toEqual([]); + const original = record!.terminals.find((entry) => entry.id === remaining.id)!; + // Startup can launch a new worker after cleanup and Windows can reuse the old PID. + // Require the original process to be gone, not the numeric PID to remain unused. + await expect + .poll( + async () => + !isProcessAlive(remainingPid) || + classifyTerminalProgramProcess(original, await inspector.inspect(remainingPid)).status === + "unrelated", + { timeout: 10000 }, + ) + .toBe(true); }, ); From 56c051503b68ae8ad7a5b8baf331f8700b469f24 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sat, 31 Oct 2026 18:56:22 +0000 Subject: [PATCH 153/173] fix(server): keep promptless Codex agents usable after reopening (#8393) * fix(server): report a Codex thread only once Codex can resume it Codex writes a new thread's rollout at its first turn, but the adapter starts a thread when the agent is created and reported its ID at once. AgentManager stored that ID as the persistence handle, so a Codex agent that was reopened before its first prompt (idle runtime release, daemon restart, plugin tool reload) failed every prompt with "no rollout found". The adapter now reports a thread's ID, as runtime info and as a handle, only once it is resumable: after Codex announces the thread's first turn, or when the thread was resumed or forked. Until then a reopened agent starts a new session, as an unprompted Claude agent does. Document that a persistence handle must be resumable. * test(server): reopen promptless Codex agents without model requests Exercise the real app-server before any first turn, so publishing an unsaved persistence handle fails at the actual resume operation. Co-authored-by: Jeong-Uk,Kim --------- Co-authored-by: Jeong-Uk,Kim Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- docs/providers.md | 2 + .../src/server/agent/agent-sdk-types.ts | 1 + .../codex-app-server-agent.local.e2e.test.ts | 92 +++++++++++++++++++ .../providers/codex-app-server-agent.test.ts | 63 ++++++++++++- .../agent/providers/codex-app-server-agent.ts | 35 ++++++- 5 files changed, 187 insertions(+), 6 deletions(-) diff --git a/docs/providers.md b/docs/providers.md index b92e171c12..60fb75a785 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -507,6 +507,8 @@ interface AgentSession { } ``` +`describePersistence()` returns a handle only once a new provider process could resume it. Reload, idle runtime collection and daemon restart resume whatever handle the agent stored; a stored agent without one starts a new session instead. When there is no handle, `AgentManager` stores `getRuntimeInfo().sessionId` as one, so that ID follows the same rule. Codex, for example, starts a thread when the agent is created but writes its rollout only at its first turn, and `thread/resume` fails for it until then, so its adapter reports neither ID before Codex announces that turn. + `setMode` and `setThinkingOption` may return an `AgentProviderNotice` when the provider knows the change needs user-facing context. For example, providers that stage changes until the next turn should return an `info` notice while a turn is already running. The app renders the notice generically as a toast; provider-specific lifecycle behavior stays in the provider implementation. ### Steps diff --git a/packages/server/src/server/agent/agent-sdk-types.ts b/packages/server/src/server/agent/agent-sdk-types.ts index c31d1afb86..903bbe5c99 100644 --- a/packages/server/src/server/agent/agent-sdk-types.ts +++ b/packages/server/src/server/agent/agent-sdk-types.ts @@ -697,6 +697,7 @@ export interface AgentSession { requestId: string, response: AgentPermissionResponse, ): Promise; + /** Null until a new provider process could resume this session; see docs/providers.md. */ describePersistence(): AgentPersistenceHandle | null; /** * Resolve once every foreground turn that predates this call can no longer run or become active. diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.local.e2e.test.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.local.e2e.test.ts index 0469d9fbe1..dc7f920993 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.local.e2e.test.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.local.e2e.test.ts @@ -264,6 +264,98 @@ describe("Codex app-server provider (local e2e)", () => { 30_000, ); + test.runIf(isCodexInstalled())( + "reopens a promptless agent repeatedly before its first model request", + async () => { + const cwd = mkdtempSync(path.join(os.tmpdir(), "codex-promptless-cwd-")); + const logger = createTestLogger(); + const storage = new AgentStorage(path.join(cwd, "agents"), logger); + const manager = new AgentManager({ + clients: { codex: new CodexAppServerAgentClient(logger) }, + registry: storage, + logger, + }); + let agentId: string | undefined; + try { + const created = await manager.createAgent( + { provider: "codex", cwd, modeId: "auto", model: "mock-model" }, + undefined, + { workspaceId: undefined }, + ); + agentId = created.id; + // A real app-server rejects an unsaved thread on resume. No model request is + // needed to prove that reopening the agent remains safe before its first turn. + for (let i = 0; i < 2; i++) { + const reopened = await manager.reloadAgentSession(agentId); + expect(reopened.lifecycle).toBe("idle"); + expect(reopened.persistence).toBeNull(); + } + await storage.flush(); + expect((await storage.get(agentId))?.persistence).toBeNull(); + } finally { + if (agentId && manager.getAgent(agentId)) await manager.closeAgent(agentId); + await storage.flush(); + rmSync(cwd, { recursive: true, force: true }); + } + }, + 30_000, + ); + + test.runIf(isCodexInstalled())( + "reopens an agent that was never prompted without resuming its unsaved thread", + async () => { + const cwd = mkdtempSync(path.join(os.tmpdir(), "codex-unprompted-cwd-")); + const codexHome = mkdtempSync(path.join(os.tmpdir(), "codex-unprompted-home-")); + const mockServer = await startMockResponsesServer([ + assistantMessageSse("first"), + assistantMessageSse("second"), + ]); + const logger = createTestLogger(); + const storage = new AgentStorage(path.join(cwd, "agents"), logger); + const manager = new AgentManager({ + clients: { codex: new CodexAppServerAgentClient(logger) }, + registry: storage, + logger, + }); + let agentId: string | undefined; + try { + writeMockCodexConfig(codexHome, mockServer.url); + vi.stubEnv("CODEX_HOME", codexHome); + const created = await manager.createAgent( + { provider: "codex", cwd, modeId: "auto", model: "mock-model" }, + undefined, + { workspaceId: undefined }, + ); + agentId = created.id; + // Codex writes a thread's rollout at its first turn, so there is nothing to resume yet. + expect(manager.getAgent(agentId)?.persistence).toBeNull(); + await storage.flush(); + expect((await storage.get(agentId))?.persistence).toBeNull(); + + await manager.reloadAgentSession(agentId); + await manager.runAgent(agentId, "first prompt after reopening"); + const threadId = manager.getAgent(agentId)?.persistence?.sessionId; + expect(threadId).toEqual(expect.any(String)); + await storage.flush(); + expect((await storage.get(agentId))?.persistence?.sessionId).toBe(threadId); + + const reloaded = await manager.reloadAgentSession(agentId); + expect(reloaded.persistence?.sessionId).toBe(threadId); + await manager.runAgent(agentId, "continue the saved thread"); + expect(manager.getAgent(agentId)?.lifecycle).toBe("idle"); + expect(mockServer.requestBodies.at(-1)).toContain("first prompt after reopening"); + } finally { + if (agentId && manager.getAgent(agentId)) await manager.closeAgent(agentId); + await storage.flush(); + vi.unstubAllEnvs(); + await mockServer.close(); + rmSync(cwd, { recursive: true, force: true }); + rmSync(codexHome, { recursive: true, force: true }); + } + }, + 30_000, + ); + test.runIf(isCodexInstalled())( "surfaces request_user_input from the app-server as question permissions and timeline tool calls", async () => { diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts index 62e6bb0404..9986357cf4 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts @@ -90,6 +90,7 @@ import { createFakeCodexAppServer, fakeCodexThreadHistory, type FakeCodexAppServer, + waitForNextEvent, waitForNextPermission, waitForNextTimelineItem, waitForProviderSubagent, @@ -1287,6 +1288,9 @@ describe("Codex app-server provider", () => { ); await firstSession.startTurn("first turn"); await expect(beforeRestart.waitForTurnStart()).resolves.toMatchObject({ effort: "medium" }); + const saved = waitForNextEvent(firstSession, "thread_started"); + beforeRestart.startsTurn({ threadId: "thread-1" }); + await saved; const handle = firstSession.describePersistence()!; await firstSession.close(); @@ -1319,6 +1323,9 @@ describe("Codex app-server provider", () => { try { await session.startTurn("persist the configured session"); await appServer.waitForTurnStart(); + const saved = waitForNextEvent(session, "thread_started"); + appServer.startsTurn({ threadId: "thread-1" }); + await saved; const handle = session.describePersistence()!; expect(handle.metadata).not.toHaveProperty("providerOptions"); appServer.assertNoErrors(); @@ -1327,6 +1334,55 @@ describe("Codex app-server provider", () => { } }); + test("reports a new thread only after Codex announces its first turn", async () => { + const appServer = createFakeCodexAppServer(); + const session = await createProviderWithFakeAppServer(appServer).createSession(createConfig()); + try { + // Codex has started the thread but writes its rollout at the first turn, so another + // app-server could not resume it yet. + await expect(session.getRuntimeInfo()).resolves.toMatchObject({ sessionId: null }); + expect(session.describePersistence()).toBeNull(); + expect( + appServer.requests().filter((request) => request.method === "thread/start"), + ).toHaveLength(1); + + await session.startTurn("first prompt"); + await appServer.waitForTurnStart(); + expect(session.describePersistence()).toBeNull(); + + const saved = waitForNextEvent(session, "thread_started"); + appServer.startsTurn({ threadId: "thread-1" }); + await expect(saved).resolves.toMatchObject({ + type: "thread_started", + provider: "codex", + sessionId: "thread-1", + }); + expect(session.describePersistence()).toMatchObject({ + sessionId: "thread-1", + nativeHandle: "thread-1", + }); + await expect(session.getRuntimeInfo()).resolves.toMatchObject({ sessionId: "thread-1" }); + appServer.assertNoErrors(); + } finally { + await session.close(); + } + }); + + test("reports a resumed thread before its next turn", async () => { + const appServer = createFakeCodexAppServer(); + const session = await createProviderWithFakeAppServer(appServer).resumeSession( + { provider: "codex", sessionId: "saved-thread" }, + createConfig(), + ); + try { + expect(session.describePersistence()).toMatchObject({ sessionId: "saved-thread" }); + await expect(session.getRuntimeInfo()).resolves.toMatchObject({ sessionId: "saved-thread" }); + appServer.assertNoErrors(); + } finally { + await session.close(); + } + }); + test("preapproves only granted tools on the injected Codex MCP server", async () => { const session = createSession({ modeId: undefined, @@ -2604,7 +2660,12 @@ describe("Codex app-server provider", () => { clientMessageId: "client-message", }, }); - expect(events.slice(0, 2).map((event) => event.type)).toEqual(["turn_started", "timeline"]); + // The first turn of a new thread also reports the thread, now that Codex has saved it. + expect(events.slice(0, 3).map((event) => event.type)).toEqual([ + "thread_started", + "turn_started", + "timeline", + ]); appServer.completeTurn(); await new Promise((resolve) => setImmediate(resolve)); await new Promise((resolve) => setImmediate(resolve)); diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.ts index ea4e6378d9..2aecd18e21 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.ts @@ -3435,6 +3435,9 @@ export class CodexAppServerAgentSession implements AgentSession { > | null = null; private resolvedSandboxPolicy: Record | null = null; private currentThreadId: string | null = null; + // Codex writes a new thread's rollout at its first turn. Until then the thread exists only + // in this app-server, so no other app-server can resume it and it is not reported. + private savedThreadId: string | null = null; private currentTurnId: string | null = null; private pendingForegroundTurnIdentification: { foregroundTurnId: string; @@ -3572,6 +3575,7 @@ export class CodexAppServerAgentSession implements AgentSession { if (this.resumeHandle?.sessionId) { this.currentThreadId = this.resumeHandle.sessionId; + this.savedThreadId = this.resumeHandle.sessionId; this.historyIndexed = false; // Resuming can start a goal before the caller receives the session. if (this.initialResumePurpose === "interactive") this.startupEvents = []; @@ -4605,7 +4609,7 @@ export class CodexAppServerAgentSession implements AgentSession { } const info: AgentRuntimeInfo = { provider: CODEX_PROVIDER, - sessionId: this.currentThreadId, + sessionId: this.savedCurrentThreadId(), model: this.config.model ?? null, thinkingOptionId: normalizeCodexThinkingOptionId(this.config.thinkingOptionId) ?? null, modeId: this.currentMode ?? null, @@ -4936,17 +4940,18 @@ export class CodexAppServerAgentSession implements AgentSession { nativeHandle: string; metadata: Record; } | null { - if (!this.currentThreadId) return null; + const threadId = this.savedCurrentThreadId(); + if (!threadId) return null; const thinkingOptionId = normalizeCodexThinkingOptionId(this.config.thinkingOptionId) ?? null; return { provider: CODEX_PROVIDER, - sessionId: this.currentThreadId, - nativeHandle: this.currentThreadId, + sessionId: threadId, + nativeHandle: threadId, metadata: { provider: CODEX_PROVIDER, cwd: this.config.cwd, title: this.config.title ?? null, - threadId: this.currentThreadId, + threadId, modeId: this.config.modeId, model: this.config.model ?? null, thinkingOptionId, @@ -4958,6 +4963,12 @@ export class CodexAppServerAgentSession implements AgentSession { }; } + private savedCurrentThreadId(): string | null { + return this.currentThreadId !== null && this.currentThreadId === this.savedThreadId + ? this.currentThreadId + : null; + } + async revertConversation(input: { messageId: string }): Promise { await this.connect(); if (!this.client) { @@ -4982,6 +4993,8 @@ export class CodexAppServerAgentSession implements AgentSession { threadRollbackAvailable: this.threadRollbackAvailable, setThreadId: async (threadId) => { this.currentThreadId = threadId; + // Codex writes a forked thread's rollout when it forks it, even before any turn. + this.savedThreadId = threadId; this.cachedRuntimeInfo = null; this.stagedHistory = await this.readThreadHistory(this.client); this.reconcileAsyncQuestionsAfterRewind(this.stagedHistory.timeline); @@ -6155,6 +6168,7 @@ export class CodexAppServerAgentSession implements AgentSession { this.emitSubAgentActivityUpdate(subAgentCallId, "running", { reopen: true }); return; } + this.markCurrentThreadSaved(parsed.threadId); this.currentTurnId = parsed.turnId; const pendingIdentification = this.pendingForegroundTurnIdentification; if ( @@ -6168,6 +6182,17 @@ export class CodexAppServerAgentSession implements AgentSession { this.emitEvent({ type: "turn_started", provider: CODEX_PROVIDER }); } + // Codex has written the rollout by the time it announces a thread's turn, including a + // goal's or a compaction's. From here on the thread can be reported and resumed. + private markCurrentThreadSaved(threadId: string | null): void { + const current = this.currentThreadId; + if (!current || (threadId !== null && threadId !== current)) return; + if (this.savedThreadId === current) return; + this.savedThreadId = current; + this.cachedRuntimeInfo = null; + this.emitEvent({ type: "thread_started", provider: CODEX_PROVIDER, sessionId: current }); + } + private handleTurnCompletedNotification( parsed: Extract, ): void { From f0dfb9134ce08cf99166fa36275a68b69672a75a Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sat, 31 Oct 2026 20:03:31 +0000 Subject: [PATCH 154/173] fix(app): keep the open workspace visible in collapsed groups (#8395) * fix(app): keep the open workspace visible in collapsed sidebar groups A collapsed group showed its first seven rows plus working and needs-attention rows, so an idle open workspace past the limit was hidden behind Show more and no sidebar row was highlighted. selectSidebarGroupVisibility now takes the route selection. When the collapsed limit would hide the open workspace, it is returned as leadingItem and rendered first in project groups, status groups and both Pinned sections. Rows the group already shows stay in place, expanded groups keep group order, and drag lists render the leading row outside their sortable data, so a reorder never saves its borrowed position. Refs #8078 Co-Authored-By: Claude Opus 5.5 * test(app): keep shortcut targets visible in collapsed groups The navigation journey still required the selected overflow workspace to stay hidden. Assert its visible selection while preserving collapsed-group navigation and the seven ordinary rows. Co-authored-by: 0xRoy <1997roylee@gmail.com> --------- Co-authored-by: 0xRoy <1997roylee@gmail.com> Co-authored-by: Claude Opus 5.5 Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../app/e2e/browser/sidebar-reorder.spec.ts | 78 ++++++++++ .../workspace-relative-navigation.spec.ts | 20 ++- .../sidebar-workspace-list.test.tsx | 27 +++- .../src/components/sidebar-workspace-list.tsx | 126 ++++++++++------ .../sidebar/sidebar-group-visibility.test.ts | 137 ++++++++++++++++++ .../sidebar/sidebar-group-visibility.ts | 73 ++++++++-- .../sidebar/sidebar-status-list.tsx | 87 +++++++---- .../sidebar/use-limited-sidebar-group.ts | 25 +++- 8 files changed, 466 insertions(+), 107 deletions(-) create mode 100644 packages/app/src/components/sidebar/sidebar-group-visibility.test.ts diff --git a/packages/app/e2e/browser/sidebar-reorder.spec.ts b/packages/app/e2e/browser/sidebar-reorder.spec.ts index 56cdd3dc5a..cf885a1d14 100644 --- a/packages/app/e2e/browser/sidebar-reorder.spec.ts +++ b/packages/app/e2e/browser/sidebar-reorder.spec.ts @@ -426,3 +426,81 @@ test("Manual restores pre-beta order and keeps drag order across sorting and rel await seed.cleanup(); } }); + +function workspaceRows(page: Page, ids: string[]) { + return page.locator( + ids.map((id) => `[data-testid="sidebar-workspace-row-${getServerId()}:${id}"]`).join(", "), + ); +} + +async function openWorkspaceRow(page: Page, workspaceId: string) { + await page.getByTestId(`sidebar-workspace-row-${getServerId()}:${workspaceId}`).click(); + await expect(page).toHaveURL(new RegExp(`/workspace/${workspaceId}`)); +} + +test("collapsed groups lead with the open workspace instead of hiding it behind Show more", async ({ + page, +}) => { + test.setTimeout(120_000); + const { seed, ids } = await seedCompactProject(); + try { + await gotoAppShell(page); + await waitForSidebarHydration(page); + await selectWorkspaceSort(page, "Created"); + const { rows, group } = compactProjectRows(page, seed); + await expectWorkspaceOrder(rows, ids.slice(0, 7)); + await revealWorkspaces(group, "Show more"); + await openWorkspaceRow(page, ids[9]!); + await expectWorkspaceOrder(rows, ids); + await revealWorkspaces(group, "Show less"); + await expectWorkspaceOrder(rows, [ids[9]!, ...ids.slice(0, 7)]); + await expect( + page.getByTestId(`sidebar-workspace-row-${getServerId()}:${ids[9]!}`), + ).toHaveAttribute("aria-selected", "true"); + await reconnectSidebar(page); + await expectWorkspaceOrder(rows, [ids[9]!, ...ids.slice(0, 7)]); + await expect( + page.getByTestId(`sidebar-workspace-row-${getServerId()}:${ids[9]!}`), + ).toHaveAttribute("aria-selected", "true"); + await openWorkspaceRow(page, ids[2]!); + await expectWorkspaceOrder(rows, ids.slice(0, 7)); + await expect( + page.getByTestId(`sidebar-workspace-row-${getServerId()}:${ids[2]!}`), + ).toHaveAttribute("aria-selected", "true"); + } finally { + await seed.cleanup(); + } +}); + +test("a Manual drag in a collapsed group keeps the open workspace's saved place", async ({ + page, +}) => { + test.setTimeout(120_000); + const { seed, ids } = await seedCompactProject(); + try { + await gotoAppShell(page); + await waitForSidebarHydration(page); + const projectKey = projectEquivalenceViewKey(seed.projectKey); + await restorePreBetaOrder( + page, + projectKey, + ids.map((id) => `${getServerId()}:${id}`), + ); + await selectWorkspaceSort(page, "Manual"); + const rows = workspaceRows(page, ids); + const toggle = page.getByTestId(`sidebar-project-show-more-${projectKey}`); + await expectWorkspaceOrder(rows, ids.slice(0, 7)); + await toggle.click(); + await openWorkspaceRow(page, ids[9]!); + await toggle.click(); + await expectWorkspaceOrder(rows, [ids[9]!, ...ids.slice(0, 7)]); + await quickDragFirstRowAfterSecond(workspaceRows(page, [ids[0]!, ids[1]!]), pressWorkspaceRow); + await expectWorkspaceOrder(rows, [ids[9]!, ids[1]!, ids[0]!, ...ids.slice(2, 7)]); + await reconnectSidebar(page); + await expectWorkspaceOrder(rows, [ids[9]!, ids[1]!, ids[0]!, ...ids.slice(2, 7)]); + await toggle.click(); + await expectWorkspaceOrder(rows, [ids[1]!, ids[0]!, ...ids.slice(2)]); + } finally { + await seed.cleanup(); + } +}); diff --git a/packages/app/e2e/browser/workspace-relative-navigation.spec.ts b/packages/app/e2e/browser/workspace-relative-navigation.spec.ts index 909672c489..5066411c78 100644 --- a/packages/app/e2e/browser/workspace-relative-navigation.spec.ts +++ b/packages/app/e2e/browser/workspace-relative-navigation.spec.ts @@ -70,25 +70,31 @@ test("previous and next traverse every visible workspace while digit shortcuts s workspaceId: order[8], }); }); - await test.step("hidden Done rows remain shortcut targets without expanding the project", async () => { - await expectHiddenWorkspaceShortcuts(page, order); + await test.step("collapsed groups keep shortcut targets selected without expanding", async () => { + await expectCollapsedWorkspaceShortcuts(page, order); }); } finally { await project.cleanup(); } }); -async function expectHiddenWorkspaceShortcuts(page: Page, order: string[]) { +async function expectCollapsedWorkspaceShortcuts(page: Page, order: string[]) { await page.getByLabel("Show less", { exact: true }).click(); const rows = page.getByRole("button", { name: /^Workspace \d{2}$/ }); - await expect(rows).toHaveCount(7); + await expect(rows).toHaveCount(8); + await expectSidebarWorkspaceSelected({ page, serverId: getServerId(), workspaceId: order[8] }); await switchWorkspaceViaSidebar({ page, serverId: getServerId(), workspaceId: order[0] }); + await expect(rows).toHaveCount(7); await page.keyboard.press("Alt+9"); await expect(page).toHaveURL(new RegExp(`/workspace/${order[8]}$`)); + await expectSidebarWorkspaceSelected({ page, serverId: getServerId(), workspaceId: order[8] }); + await expect(rows).toHaveCount(8); + await page.keyboard.press("Alt+]"); + await expect(page).toHaveURL(new RegExp(`/workspace/${order[9]}$`)); + await expectSidebarWorkspaceSelected({ page, serverId: getServerId(), workspaceId: order[9] }); + await expect(rows).toHaveCount(8); await expect(page.getByTestId(`sidebar-workspace-row-${getServerId()}:${order[8]}`)).toHaveCount( 0, ); - await page.keyboard.press("Alt+]"); - await expect(page).toHaveURL(new RegExp(`/workspace/${order[9]}$`)); - await expect(rows).toHaveCount(7); + await expect(page.getByLabel("Show more", { exact: true })).toBeVisible(); } diff --git a/packages/app/src/components/sidebar-workspace-list.test.tsx b/packages/app/src/components/sidebar-workspace-list.test.tsx index fc57dc2dce..9532c422dd 100644 --- a/packages/app/src/components/sidebar-workspace-list.test.tsx +++ b/packages/app/src/components/sidebar-workspace-list.test.tsx @@ -462,7 +462,7 @@ describe("sidebar group visibility", () => { it.each([0, 7, 8])("limits %i Done rows to seven", (count) => { const items = entries(Array(count).fill("done")); - const { result } = renderHook(() => useLimitedSidebarGroup(items, policy)); + const { result } = renderHook(() => useLimitedSidebarGroup({ items, selection: null, policy })); expect(result.current.visibleItems).toEqual(items.slice(0, 7)); expect(result.current.canToggle).toBe(count > 7); }); @@ -471,7 +471,9 @@ describe("sidebar group visibility", () => { "keeps row twelve visible for %s without filling gaps", (status) => { const items = entries([...Array(11).fill("done"), status]); - const { result } = renderHook(() => useLimitedSidebarGroup(items, policy)); + const { result } = renderHook(() => + useLimitedSidebarGroup({ items, selection: null, policy }), + ); expect(names(result.current.visibleItems)).toEqual([ "row-1", "row-2", @@ -492,7 +494,11 @@ describe("sidebar group visibility", () => { const hydrated = new Map(items.slice(0, 9).map((item) => [item.workspaceKey, item])); for (const entriesByKey of [new Map(), hydrated]) { const { result } = renderHook(() => - useLimitedSidebarGroup(items, createWorkspaceVisibilityPolicy(entriesByKey)), + useLimitedSidebarGroup({ + items, + selection: null, + policy: createWorkspaceVisibilityPolicy(entriesByKey), + }), ); expect(result.current.canToggle).toBe(true); expect(names(result.current.visibleItems)).toEqual( @@ -512,7 +518,7 @@ describe("sidebar group visibility", () => { "needs_input", "failed", ]); - const { result } = renderHook(() => useLimitedSidebarGroup(items, policy)); + const { result } = renderHook(() => useLimitedSidebarGroup({ items, selection: null, policy })); expect(result.current.visibleItems).toEqual(items); expect(result.current.canToggle).toBe(false); }); @@ -527,7 +533,7 @@ describe("sidebar group visibility", () => { "attention", ]); const { result, rerender, unmount } = renderHook( - ({ rows }) => useLimitedSidebarGroup(rows, policy), + ({ rows }) => useLimitedSidebarGroup({ items: rows, selection: null, policy }), { initialProps: { rows: items } }, ); expect(names(result.current.visibleItems)).toEqual([ @@ -568,7 +574,7 @@ describe("sidebar group visibility", () => { expect(result.current.expanded).toBe(false); act(() => result.current.toggleExpanded()); unmount(); - const remounted = renderHook(() => useLimitedSidebarGroup(items, policy)); + const remounted = renderHook(() => useLimitedSidebarGroup({ items, selection: null, policy })); expect(remounted.result.current.expanded).toBe(false); expect(remounted.result.current.visibleItems).toHaveLength(10); }); @@ -592,7 +598,12 @@ describe("sidebar group visibility", () => { lifecycle: "active" as const, }; const { result, rerender } = renderHook( - ({ last }) => useLimitedSidebarGroup([...items.slice(0, 11), last], policy), + ({ last }) => + useLimitedSidebarGroup({ + items: [...items.slice(0, 11), last], + selection: null, + policy, + }), { initialProps: { last: items[11] } }, ); expect(result.current.visibleItems).toHaveLength(7); @@ -630,7 +641,7 @@ describe("sidebar group visibility", () => { it("preserves the twenty-row pinned policy regardless of status", () => { const items = entries(Array(21).fill("running")); - const { result } = renderHook(() => useLimitedSidebarGroup(items)); + const { result } = renderHook(() => useLimitedSidebarGroup({ items, selection: null })); expect(result.current.visibleItems).toEqual(items.slice(0, 20)); expect(result.current.canToggle).toBe(true); act(() => result.current.toggleExpanded()); diff --git a/packages/app/src/components/sidebar-workspace-list.tsx b/packages/app/src/components/sidebar-workspace-list.tsx index 333eb68221..8697a4b27b 100644 --- a/packages/app/src/components/sidebar-workspace-list.tsx +++ b/packages/app/src/components/sidebar-workspace-list.tsx @@ -1598,11 +1598,16 @@ function ProjectBlock({ [workspaceEntriesByKey], ); const { + leadingItem: leadingWorkspace, visibleItems: visibleWorkspaces, expanded: workspacesExpanded, canToggle: canToggleWorkspaces, toggleExpanded: toggleWorkspacesExpanded, - } = useLimitedSidebarGroup(project.workspaces, visibilityPolicy); + } = useLimitedSidebarGroup({ + items: project.workspaces, + selection: selectionEnabled ? activeWorkspaceSelection : null, + policy: visibilityPolicy, + }); const activeServerId = activeWorkspaceSelection?.serverId ?? null; const activeHostStatus = useHostRuntimeConnectionStatus(activeServerId ?? ""); const preferredServerId = activeHostStatus === "online" ? activeServerId : null; @@ -1761,28 +1766,33 @@ function ProjectBlock({ let projectChildren = null; if (!collapsed) { if (project.workspaces.length > 0) { + const leadingWorkspaceRow = leadingWorkspace ? renderWorkspaceRow(leadingWorkspace) : null; projectChildren = ( <> {manualSort ? ( - + <> + {leadingWorkspaceRow} + + ) : ( + {leadingWorkspaceRow} {visibleWorkspaces.map((item) => renderWorkspaceRow(item))} )} @@ -2188,11 +2198,15 @@ function ProjectModeList({ const activeWorkspaceSelection = useActiveWorkspaceSelection(); const { pinnedChats, unpinnedProjects } = pinnedGroups; const { + leadingItem: leadingPinnedChat, visibleItems: visiblePinnedChats, expanded: pinnedChatsExpanded, canToggle: canTogglePinnedChats, toggleExpanded: togglePinnedChatsExpanded, - } = useLimitedSidebarGroup(pinnedChats); + } = useLimitedSidebarGroup({ + items: pinnedChats, + selection: selectionEnabled ? activeWorkspaceSelection : null, + }); const nativeScrollGestureProps = useMemo( () => parentGestureRef @@ -2395,37 +2409,38 @@ function ProjectModeList({ [renderProjectBlock], ); - const renderPinnedChat = useCallback( - ({ - item: workspace, - drag, - isActive, - dragHandleProps, - }: DraggableRenderItemInfo) => { - return ( - - ); - }, + const renderPinnedChatRow = useCallback( + ( + workspace: SidebarWorkspacePlacement, + input?: { + drag?: () => void; + isDragging?: boolean; + dragHandleProps?: DraggableListDragHandleProps; + }, + ) => ( + + ), [ activeWorkspaceSelection, creatingWorkspaceIds, @@ -2441,6 +2456,22 @@ function ProjectModeList({ ], ); + const renderPinnedChat = useCallback( + ({ + item: workspace, + drag, + isActive, + dragHandleProps, + }: DraggableRenderItemInfo) => { + return renderPinnedChatRow(workspace, { + drag, + isDragging: isActive, + dragHandleProps, + }); + }, + [renderPinnedChatRow], + ); + const projectBody = projects.length === 0 ? ( @@ -2473,6 +2504,7 @@ function ProjectModeList({ /> {pinnedCollapsed ? null : ( <> + {leadingPinnedChat ? renderPinnedChatRow(leadingPinnedChat) : null} ({ + id: index + 1, + serverId: rowServerId, + workspaceId: `workspace-${index + 1}`, + statusBucket, + })); +} + +const workspacePolicy: SidebarGroupVisibilityPolicy = { + kind: "workspaces", + getStatusBucket: (item) => item.statusBucket, +}; + +function selectionFor(item: SidebarGroupItem): ActiveWorkspaceSelection { + return { serverId: item.serverId, workspaceId: item.workspaceId }; +} + +describe("selectSidebarGroupVisibility", () => { + it("leads with a hidden open row while keeping the baseline order", () => { + const items = rows(Array(9).fill("done")); + const result = selectSidebarGroupVisibility({ + items, + expanded: false, + policy: workspacePolicy, + selection: selectionFor(items[8]!), + }); + + expect(result.leadingItem).toBe(items[8]); + expect(result.visibleItems).toEqual(items.slice(0, 7)); + expect(result.canToggle).toBe(true); + }); + + it("leaves selected rows in place when they are already in the baseline", () => { + const items = rows([...Array(8).fill("done"), "running", "done"]); + const expected = [...items.slice(0, 7), items[8]]; + + for (const selectedIndex of [2, 8]) { + const result = selectSidebarGroupVisibility({ + items, + expanded: false, + policy: workspacePolicy, + selection: selectionFor(items[selectedIndex]!), + }); + + expect(result.leadingItem).toBeNull(); + expect(result.visibleItems).toEqual(expected); + expect(result.canToggle).toBe(true); + } + }); + + it("shows the whole group without a toggle when the open row is the only hidden row", () => { + const items = rows(Array(8).fill("done")); + const result = selectSidebarGroupVisibility({ + items, + expanded: false, + policy: workspacePolicy, + selection: selectionFor(items[7]!), + }); + + expect(result.leadingItem).toBeNull(); + expect(result.visibleItems).toEqual(items); + expect(result.canToggle).toBe(false); + }); + + it("keeps expanded groups in their original order", () => { + const items = rows(Array(9).fill("done")); + const result = selectSidebarGroupVisibility({ + items, + expanded: true, + policy: workspacePolicy, + selection: selectionFor(items[8]!), + }); + + expect(result.leadingItem).toBeNull(); + expect(result.visibleItems).toEqual(items); + expect(result.canToggle).toBe(true); + }); + + it("applies the twenty-row limit to pinned groups", () => { + const items = rows(Array(22).fill("done")); + const result = selectSidebarGroupVisibility({ + items, + expanded: false, + policy: { kind: "pinned" }, + selection: selectionFor(items[21]!), + }); + + expect(result.leadingItem).toBe(items[21]); + expect(result.visibleItems).toEqual(items.slice(0, 20)); + expect(result.canToggle).toBe(true); + }); + + it("preserves the current limit when selection is null", () => { + const items = rows(Array(8).fill("done")); + const result = selectSidebarGroupVisibility({ + items, + expanded: false, + policy: workspacePolicy, + selection: null, + }); + + expect(result.leadingItem).toBeNull(); + expect(result.visibleItems).toEqual(items.slice(0, 7)); + expect(result.canToggle).toBe(true); + }); + + it("matches the open row by server and workspace identity", () => { + const items = rows(Array(9).fill("done"), "host-b"); + const result = selectSidebarGroupVisibility({ + items, + expanded: false, + policy: workspacePolicy, + selection: { serverId: serverId, workspaceId: items[8]!.workspaceId }, + }); + + expect(result.leadingItem).toBeNull(); + expect(result.visibleItems).toEqual(items.slice(0, 7)); + expect(result.canToggle).toBe(true); + }); +}); diff --git a/packages/app/src/components/sidebar/sidebar-group-visibility.ts b/packages/app/src/components/sidebar/sidebar-group-visibility.ts index 1bc3018e9a..f109f0114a 100644 --- a/packages/app/src/components/sidebar/sidebar-group-visibility.ts +++ b/packages/app/src/components/sidebar/sidebar-group-visibility.ts @@ -1,4 +1,28 @@ import type { SidebarStateBucket } from "@/hooks/sidebar-workspaces-view-model"; +import type { ActiveWorkspaceSelection } from "@/stores/last-workspace-selection"; + +export interface SidebarGroupItem { + serverId: string; + workspaceId: string; +} + +export interface SidebarGroupVisibilityInput { + items: readonly T[]; + expanded: boolean; + policy: SidebarGroupVisibilityPolicy; + /** The workspace the group's rows highlight as selected. Null when no row can be selected. */ + selection: ActiveWorkspaceSelection | null; +} + +export interface SidebarGroupVisibility { + /** + * The open workspace when the collapsed limit would hide it. Rendered before `visibleItems`, + * out of group order, outside any drag list. Never also present in `visibleItems`. + */ + leadingItem: T | null; + visibleItems: T[]; + canToggle: boolean; +} export type SidebarGroupVisibilityPolicy = | { kind: "pinned" } @@ -16,18 +40,45 @@ export function createWorkspaceVisibilityPolicy( - items: readonly T[], - expanded: boolean, - policy: SidebarGroupVisibilityPolicy, -) { - const limit = policy.kind === "pinned" ? 20 : 7; - const baseline = items.filter( - (item, index) => - index < limit || (policy.kind === "workspaces" && policy.getStatusBucket(item) !== "done"), +function isOpenWorkspace( + item: SidebarGroupItem, + selection: ActiveWorkspaceSelection | null, +): boolean { + return ( + selection !== null && + item.serverId === selection.serverId && + item.workspaceId === selection.workspaceId ); +} + +export function selectSidebarGroupVisibility( + input: SidebarGroupVisibilityInput, +): SidebarGroupVisibility { + const { items, expanded, policy, selection } = input; + const limit = policy.kind === "pinned" ? 20 : 7; + const baseline: T[] = []; + let leadingItem: T | null = null; + let canToggle = false; + + items.forEach((item, index) => { + const inBaseline = + index < limit || (policy.kind === "workspaces" && policy.getStatusBucket(item) !== "done"); + if (inBaseline) { + baseline.push(item); + } else if (leadingItem === null && isOpenWorkspace(item, selection)) { + leadingItem = item; + } else { + canToggle = true; + } + }); + + if (expanded || !canToggle) { + return { leadingItem: null, visibleItems: items.slice(), canToggle }; + } + return { - visibleItems: expanded ? items.slice() : baseline, - canToggle: baseline.length < items.length, + leadingItem, + visibleItems: baseline, + canToggle, }; } diff --git a/packages/app/src/components/sidebar/sidebar-status-list.tsx b/packages/app/src/components/sidebar/sidebar-status-list.tsx index 44622385a4..ce8ad535c4 100644 --- a/packages/app/src/components/sidebar/sidebar-status-list.tsx +++ b/packages/app/src/components/sidebar/sidebar-status-list.tsx @@ -147,6 +147,7 @@ export function SidebarStatusWorkspaceList({ dragGestureHostActive, }: StatusWorkspaceListProps) { const { t } = useTranslation(); + const activeWorkspaceSelection = useActiveWorkspaceSelection(); const collapsedWorkspaceGroupKeys = useSidebarCollapsedSectionsStore( (state) => state.collapsedWorkspaceGroupKeys, ); @@ -155,23 +156,27 @@ export function SidebarStatusWorkspaceList({ (state) => state.togglePinnedCollapsed, ); const { + leadingItem: leadingPinnedWorkspace, visibleItems: visiblePinnedWorkspaces, expanded: pinnedWorkspacesExpanded, canToggle: canTogglePinnedWorkspaces, toggleExpanded: togglePinnedWorkspacesExpanded, - } = useLimitedSidebarGroup(pinnedWorkspaces); + } = useLimitedSidebarGroup({ items: pinnedWorkspaces, selection: activeWorkspaceSelection }); const statusShortcutIndex = showShortcutBadges ? shortcutIndexByWorkspaceKey : EMPTY_SHORTCUT_INDEX; - const renderPinnedWorkspace = useCallback( - ({ - item: workspace, - drag, - isActive, - dragHandleProps, - }: DraggableRenderItemInfo) => ( + const renderPinnedWorkspaceRow = useCallback( + ( + workspace: SidebarWorkspaceEntry, + input?: { + drag?: () => void; + isDragging?: boolean; + dragHandleProps?: DraggableListDragHandleProps; + }, + ) => ( ), [ @@ -199,6 +204,20 @@ export function SidebarStatusWorkspaceList({ supportsPinningByServerId, ], ); + const renderPinnedWorkspace = useCallback( + ({ + item: workspace, + drag, + isActive, + dragHandleProps, + }: DraggableRenderItemInfo) => + renderPinnedWorkspaceRow(workspace, { + drag, + isDragging: isActive, + dragHandleProps, + }), + [renderPinnedWorkspaceRow], + ); const content = ( <> {pinnedWorkspaces.length > 0 ? ( @@ -211,6 +230,7 @@ export function SidebarStatusWorkspaceList({ /> {pinnedCollapsed ? null : ( <> + {leadingPinnedWorkspace ? renderPinnedWorkspaceRow(leadingPinnedWorkspace) : null} ; onToggleWorkspacePin: ToggleSidebarWorkspacePin; }) { + const activeWorkspaceSelection = useActiveWorkspaceSelection(); const { + leadingItem: leadingWorkspace, visibleItems: visibleWorkspaces, expanded: workspacesExpanded, canToggle: canToggleWorkspaces, toggleExpanded: toggleWorkspacesExpanded, - } = useLimitedSidebarGroup(group.rows, STATUS_GROUP_VISIBILITY); + } = useLimitedSidebarGroup({ + items: group.rows, + selection: activeWorkspaceSelection, + policy: STATUS_GROUP_VISIBILITY, + }); + + function renderWorkspaceRow(workspace: SidebarWorkspaceEntry) { + return ( + + ); + } return ( @@ -360,22 +405,8 @@ function StatusGroupRows({ style={styles.statusWorkspaceListContainer} testID={`sidebar-status-group-rows-${group.key}`} > - {visibleWorkspaces.map((workspace) => ( - - ))} + {leadingWorkspace ? renderWorkspaceRow(leadingWorkspace) : null} + {visibleWorkspaces.map(renderWorkspaceRow)} {canToggleWorkspaces ? ( ( - items: readonly T[], - policy: SidebarGroupVisibilityPolicy = PINNED_POLICY, -) { +interface LimitedSidebarGroupInput { + items: readonly T[]; + selection: ActiveWorkspaceSelection | null; + policy?: SidebarGroupVisibilityPolicy; +} + +export function useLimitedSidebarGroup({ + items, + selection, + policy = PINNED_POLICY, +}: LimitedSidebarGroupInput): SidebarGroupVisibility & { + expanded: boolean; + toggleExpanded: () => void; +} { const [expanded, setExpanded] = useState(false); const visibility = useMemo( - () => selectSidebarGroupVisibility(items, expanded, policy), - [expanded, items, policy], + () => selectSidebarGroupVisibility({ items, expanded, policy, selection }), + [expanded, items, policy, selection], ); const toggleExpanded = useCallback(() => setExpanded((current) => !current), []); From caf9300358ea40a7adf5c888d1b2f5a3cc8bc4c9 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sat, 31 Oct 2026 20:52:07 +0000 Subject: [PATCH 155/173] fix(server): preserve running status after agent creation (#8396) * fix(server): forward a created agent's current state, not its pre-prompt copy create_agent_request forwarded the snapshot createAgent returned when registration finished, after the initial prompt had already published the agent as running. Subscribers received that idle copy last, with an older updatedAt, and providers that report nothing until the turn ends left the agent listed as idle for the whole turn. Forward the agent manager's current state instead. Closes #8022 * test(server): drain agent persistence before fixture cleanup --------- Co-authored-by: luke Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- packages/server/package.json | 2 +- .../daemon-e2e/creation-status.e2e.test.ts | 64 +++++++++ packages/server/src/server/session.ts | 5 +- .../src/server/session.workspaces.test.ts | 130 ++++++++++++++++++ 4 files changed, 199 insertions(+), 2 deletions(-) create mode 100644 packages/server/src/server/daemon-e2e/creation-status.e2e.test.ts diff --git a/packages/server/package.json b/packages/server/package.json index 0fcbacaf24..0feadfe9cd 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -89,7 +89,7 @@ "speech:transcribe:local": "tsx scripts/transcribe-local-wav.ts", "test": "npm run test:unit && npm run test:integration", "test:unit": "vitest run --fileParallelism --exclude \"**/*.e2e.test.ts\"", - "test:integration": "vitest run --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --maxWorkers=1 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history\"", + "test:integration": "vitest run --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/creation-status.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --maxWorkers=1 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history\"", "test:hub-cli-contract": "vitest run --maxWorkers=1 src/server/hub/hub-cli-contract.test.ts", "test:integration:all": "npm run test:e2e", "test:integration:real": "vitest run real.e2e.test.ts", diff --git a/packages/server/src/server/daemon-e2e/creation-status.e2e.test.ts b/packages/server/src/server/daemon-e2e/creation-status.e2e.test.ts new file mode 100644 index 0000000000..c2293a2bc7 --- /dev/null +++ b/packages/server/src/server/daemon-e2e/creation-status.e2e.test.ts @@ -0,0 +1,64 @@ +import { expect, test } from "vitest"; +import { createDaemonTestContext } from "../test-utils/index.js"; +import { MockLoadTestAgentClient } from "../agent/providers/mock-load-test-agent.js"; +import type { AgentSnapshotPayload } from "../messages.js"; + +test("creation never regresses a running subscription to the pre-prompt idle snapshot", async () => { + const ctx = await createDaemonTestContext({ + agentClients: { mock: new MockLoadTestAgentClient() }, + mcpEnabled: false, + isDev: true, + }); + try { + const workspace = await ctx.client.createWorkspace({ + source: { kind: "directory", path: ctx.daemon.staticDir }, + }); + if (!workspace.workspace) throw new Error(workspace.error ?? "Missing workspace"); + const observations: { + list: string; + kind: string; + agent?: AgentSnapshotPayload; + agentId?: string; + }[] = []; + for (const [list, statuses] of [ + ["running", ["running", "initializing", "error"]], + ["done", ["idle", "closed"]], + ] as const) { + const result = await ctx.client.fetchAgents({ + filter: { statuses: [...statuses] }, + subscribe: {}, + }); + result.subscription.subscribe({ + snapshot() {}, + update(message) { + observations.push({ list, ...message.payload }); + }, + }); + } + const agent = await ctx.client.createAgent({ + workspaceId: workspace.workspace.id, + provider: "mock", + cwd: ctx.daemon.staticDir, + initialPrompt: "Work on this task", + }); + await expect + .poll(() => observations.filter((row) => row.agent?.id === agent.id).length) + .toBeGreaterThan(1); + // Fetching provides a round trip after creation so its queued update reaches the client. + expect((await ctx.client.fetchAgent({ agentId: agent.id }))?.agent.status).toBe("running"); + const relevant = observations.filter( + (row) => row.agent?.id === agent.id || row.agentId === agent.id, + ); + const firstRunning = relevant.findIndex((row) => row.agent?.status === "running"); + expect(firstRunning).toBeGreaterThanOrEqual(0); + expect( + relevant.slice(firstRunning).filter((row) => row.list === "done" && row.kind === "upsert"), + ).toEqual([]); + const timestamps = relevant.flatMap((row) => + row.agent ? [Date.parse(row.agent.updatedAt)] : [], + ); + expect(timestamps).toEqual([...timestamps].sort((a, b) => a - b)); + } finally { + await ctx.cleanup(); + } +}, 60_000); diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index 42c676b50b..00c8529482 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -4512,7 +4512,10 @@ export class Session { }, ); createdAgentId = snapshot.id; - await this.agentUpdates.forwardLiveAgent(snapshot); + // `snapshot` predates the initial prompt; subscribers keep the last state they receive. + await this.agentUpdates.forwardLiveAgent( + this.agentManager.getAgent(snapshot.id) ?? liveSnapshot, + ); if (resolvedIntent.createdDirectoryWorkspace && trimmedPrompt) { this.workspaceAutoName.scheduleForDirectory( { diff --git a/packages/server/src/server/session.workspaces.test.ts b/packages/server/src/server/session.workspaces.test.ts index 9e73c9cad4..343c0a8843 100644 --- a/packages/server/src/server/session.workspaces.test.ts +++ b/packages/server/src/server/session.workspaces.test.ts @@ -1393,6 +1393,136 @@ test("create_agent_request does not title an existing workspace from the agent p } }); +test("create_agent_request does not publish the pre-prompt snapshot after the prompt starts", async () => { + vi.useFakeTimers(); + const workdir = mkdtempSync(path.join(tmpdir(), "paseo-create-agent-live-state-")); + const logger = createTestLogger(); + const agentStorage = new AgentStorage(path.join(workdir, "agents"), asSessionLogger(logger)); + // The test session's turn starts and then reports nothing, like a provider + // that stays quiet until its turn ends. + const agentManager = new AgentManager({ + clients: { codex: new CreateAgentTestClient() }, + registry: agentStorage, + logger: asSessionLogger(logger), + idFactory: () => "00000000-0000-4000-8000-000000000553", + }); + try { + const cwd = path.join(workdir, "repo"); + mkdirSync(cwd, { recursive: true }); + + const projectRegistry = new FileBackedProjectRegistry( + path.join(workdir, "projects.json"), + asSessionLogger(logger), + ); + const workspaceRegistry = new FileBackedWorkspaceRegistry( + path.join(workdir, "workspaces.json"), + asSessionLogger(logger), + ); + + await projectRegistry.upsert( + createPersistedProjectRecord({ + projectId: "proj-live-state", + rootPath: cwd, + kind: "git", + displayName: "repo", + createdAt: "2026-05-07T00:00:00.000Z", + updatedAt: "2026-05-07T00:00:00.000Z", + }), + ); + await workspaceRegistry.upsert( + createPersistedWorkspaceRecord({ + workspaceId: "ws-live-state", + projectId: "proj-live-state", + cwd, + kind: "local_checkout", + displayName: "repo", + title: null, + createdAt: "2026-05-07T00:00:00.000Z", + updatedAt: "2026-05-07T00:00:00.000Z", + }), + ); + + const agentUpdates: Extract["payload"][] = []; + const session = asTestSession( + new Session({ + workspaceRuntimeStore: createWorkspaceRuntimeStore(), + messageReceipts: createMessageReceiptsStub(), + agentMessages: createAgentMessageDeliveryStub(), + creationService: createTestCreationService(), + clientId: "test-client", + permissions: OWNER_PERMISSIONS, + appVersion: null, + onMessage: (message) => { + if (message.type === "agent_update") agentUpdates.push(message.payload); + }, + logger: asSessionLogger(logger), + downloadTokenStore: asDownloadTokenStore(), + pushNotifications: asPushNotifications(), + paseoHome: path.join(workdir, "paseo-home"), + agentManager, + agentStorage, + projectRegistry, + workspaceRegistry, + scheduleService: asScheduleService(), + checkoutDiffManager: asCheckoutDiffManager({ + subscribe: async () => ({ + initial: { cwd, files: [], error: null }, + unsubscribe: () => {}, + }), + scheduleRefreshForCwd: () => {}, + onWorkspaceStateMayHaveChanged: () => {}, + invalidateForge: () => {}, + getMetrics: () => ({ + checkoutDiffTargetCount: 0, + checkoutDiffSubscriptionCount: 0, + checkoutDiffWatcherCount: 0, + checkoutDiffFallbackRefreshTargetCount: 0, + }), + dispose: () => {}, + }), + workspaceGitService: createNoopWorkspaceGitService(), + daemonConfigStore: asDaemonConfigStore({ + get: () => ({ mcp: { injectIntoAgents: false }, providers: {} }), + onChange: () => () => {}, + }), + mcpBaseUrl: null, + stt: null, + tts: null, + generateWorkspaceName: async () => null, + providerSnapshotManager: createProviderSnapshotManagerStub().manager, + terminalManager: null, + }), + ); + await activateAgentUpdatesSubscription(session, "sub-live-state"); + + await session.handleMessage({ + type: "create_agent_request", + requestId: "req-create-live-state", + workspaceId: "ws-live-state", + config: { provider: "codex", cwd }, + initialPrompt: "Print the report", + attachments: [], + }); + await vi.runAllTimersAsync(); + + const [createdAgent] = agentManager.listAgents(); + expect(createdAgent?.lifecycle).toBe("running"); + const upserts = agentUpdates.flatMap((update) => + update.kind === "upsert" && update.agent.id === createdAgent?.id ? [update.agent] : [], + ); + expect(upserts.length).toBeGreaterThan(0); + // A client keeps the last update it hears, so the latest one must be the running agent. + expect(upserts.at(-1)).toMatchObject({ status: "running" }); + const updatedAt = upserts.map((agent) => Date.parse(agent.updatedAt)); + expect(updatedAt).toEqual([...updatedAt].sort((left, right) => left - right)); + } finally { + // Drain snapshot writes before removing their storage directory. + await agentManager.flush(); + vi.useRealTimers(); + rmSync(workdir, { recursive: true, force: true }); + } +}); + test("unsupported persisted agents are excluded from active lists but preserved in history payloads", async () => { const session = createSessionForWorkspaceTests({ appVersion: "0.1.45" }); const storedRecord = { From 7d9741ef778b9241b5f7ec2f841737ab74327d11 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sat, 31 Oct 2026 22:50:27 +0000 Subject: [PATCH 156/173] fix(app): expose the SSL checkbox checked state on web (#8399) The web renderer does not map accessibilityState.checked onto aria-checked. Supply the checked property explicitly so accessibility clients agree with the checkmark and connection URI. Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../app/e2e/browser/settings-navigation.spec.ts | 13 +++++++++++++ packages/app/e2e/support/helpers/settings.ts | 15 +++++++++++++++ packages/app/src/components/add-host-modal.tsx | 1 + 3 files changed, 29 insertions(+) diff --git a/packages/app/e2e/browser/settings-navigation.spec.ts b/packages/app/e2e/browser/settings-navigation.spec.ts index 3ec921a663..aa381f1348 100644 --- a/packages/app/e2e/browser/settings-navigation.spec.ts +++ b/packages/app/e2e/browser/settings-navigation.spec.ts @@ -38,6 +38,9 @@ import { fillDirectHostUri, expectDirectHostFormValues, expectDirectHostSslEnabled, + expectDirectHostSslDisabled, + fillDirectHostAddress, + toggleDirectHostSsl, expectDirectHostUriValue, expectDirectHostUriHidden, expectDiagnosticsContent, @@ -284,6 +287,16 @@ test.describe("Settings sidebar navigation", () => { await expectAddHostMethodOptions(page); await selectHostConnectionType(page, "direct"); + await fillDirectHostAddress(page, "example.paseo.test", "7443"); + await expectDirectHostSslDisabled(page); + await toggleDirectHostSsl(page); + await expectDirectHostSslEnabled(page); + await toggleHostAdvanced(page); + await expectDirectHostUriValue(page, "tcp://example.paseo.test:7443?ssl=true"); + await toggleHostAdvanced(page); + await toggleDirectHostSsl(page); + await expectDirectHostSslDisabled(page); + await toggleHostAdvanced(page); await fillDirectHostUri(page, "tcp://example.paseo.test:7443?ssl=true&password=shared-secret"); await toggleHostAdvanced(page); diff --git a/packages/app/e2e/support/helpers/settings.ts b/packages/app/e2e/support/helpers/settings.ts index a2befccfbf..796d0b45f5 100644 --- a/packages/app/e2e/support/helpers/settings.ts +++ b/packages/app/e2e/support/helpers/settings.ts @@ -351,9 +351,24 @@ export async function expectDirectHostFormValues( } export async function expectDirectHostSslEnabled(page: Page): Promise { + await expect(page.getByRole("checkbox", { name: "Use SSL", exact: true })).toBeChecked(); await expect(page.getByTestId("direct-ssl-toggle-checked")).toBeVisible(); } +export async function fillDirectHostAddress(page: Page, host: string, port: string): Promise { + await page.getByRole("textbox", { name: "Host", exact: true }).fill(host); + await page.getByRole("textbox", { name: "Port", exact: true }).fill(port); +} + +export async function toggleDirectHostSsl(page: Page): Promise { + await page.getByRole("checkbox", { name: "Use SSL", exact: true }).click(); +} + +export async function expectDirectHostSslDisabled(page: Page): Promise { + await expect(page.getByRole("checkbox", { name: "Use SSL", exact: true })).not.toBeChecked(); + await expect(page.getByTestId("direct-ssl-toggle-checked")).toHaveCount(0); +} + export async function expectDirectHostUriValue(page: Page, uri: string): Promise { await expect(page.getByTestId("direct-host-uri-input")).toHaveValue(uri); } diff --git a/packages/app/src/components/add-host-modal.tsx b/packages/app/src/components/add-host-modal.tsx index aa0c65b638..5d8fc90cff 100644 --- a/packages/app/src/components/add-host-modal.tsx +++ b/packages/app/src/components/add-host-modal.tsx @@ -476,6 +476,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod accessibilityRole="checkbox" accessibilityLabel={t("pairing.direct.fields.useSsl")} accessibilityState={useTlsAccessibilityState} + aria-checked={useTls} testID="direct-ssl-toggle" > From 2d7adfc450bd41a3771bbaf51a3d797165da6065 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sat, 31 Oct 2026 23:58:14 +0000 Subject: [PATCH 157/173] fix(app): restore directory subscriptions after demand returns (#8403) Invalidate refresh satisfaction when subscriptions are released, and retry if demand returns before the overtaken refresh completes. Otherwise the same connection source can stay satisfied with no live list listeners. Cover both demand sources and completion orderings with live delta checks. Co-authored-by: Okan YILDIRIM <63511519+ragokan@users.noreply.github.com> --- .../src/runtime/directory-sync/index.test.ts | 96 ++++++++++++++++++- .../app/src/runtime/directory-sync/index.ts | 17 ++-- 2 files changed, 103 insertions(+), 10 deletions(-) diff --git a/packages/app/src/runtime/directory-sync/index.test.ts b/packages/app/src/runtime/directory-sync/index.test.ts index 6fae0a7e92..e4db5dfb71 100644 --- a/packages/app/src/runtime/directory-sync/index.test.ts +++ b/packages/app/src/runtime/directory-sync/index.test.ts @@ -16,7 +16,8 @@ import { normalizeWorkspaceDescriptor, useSessionStore, } from "@/stores/session-store"; -import { normalizeAgentSnapshot } from "@/utils/agent-snapshots"; +import { normalizeAgentSnapshot, projectAgentSnapshot } from "@/utils/agent-snapshots"; +import { deriveProjectPlacementFromCwd } from "@/utils/project-placement"; import { selectWorkspaceDirectoryServerIds } from "@/stores/session-store-hooks/selectors"; import { useWorkspaceLabels } from "@/workspace-labels"; import type { DirectoryReplicaMutation } from "@/runtime/replica-cache"; @@ -41,12 +42,15 @@ class FakeDirectoryClient { supportsWorkspaceLabels = false; listWorkspaceLabelsCalls = 0; fetchAgentsCalls = 0; + observeAgentsCalls = 0; lastAgentOptions: unknown; fetchWorkspacesCalls = 0; + observeWorkspacesCalls = 0; lastWorkspaceOptions: unknown; listProjectsCalls = 0; lastProjectOptions: unknown; projectResult: ProjectListResult | null = null; + readonly listSnapshots: Promise[] = []; private pendingAgentFetch: Promise | null = null; private pendingWorkspaceFetch: Promise | null = null; private pendingProjectFetch: Promise | null = null; @@ -151,15 +155,22 @@ class FakeDirectoryClient { } observeAgents(options: Parameters[0]) { - return subscriptionFixture(this.fetchAgents({ ...options, subscribe: {} }), (receive) => - this.on("agent_update", receive), + this.observeAgentsCalls += 1; + const subscription = subscriptionFixture( + this.fetchAgents({ ...options, subscribe: {} }), + (receive) => this.on("agent_update", receive), ); + this.listSnapshots.push(subscription.ready); + return subscription; } observeWorkspaces(options: Parameters[0]) { - return subscriptionFixture(this.fetchWorkspaces(options), (receive) => + this.observeWorkspacesCalls += 1; + const subscription = subscriptionFixture(this.fetchWorkspaces(options), (receive) => this.on("workspace_update", receive), ); + this.listSnapshots.push(subscription.ready); + return subscription; } observeEvents(events: readonly SessionOutboundMessage["type"][]) { @@ -592,6 +603,83 @@ describe("DirectorySync session readiness", () => { directory.dispose(); }); + it.each([ + ["full", "before"], + ["full", "after"], + ["route", "before"], + ["route", "after"], + ] as const)( + "restores live directory updates when %s demand returns %s refresh completion", + async (demand, timing) => { + const serverId = `released-directory-${demand}-${timing}`; + const { client, directory } = createDirectory(serverId); + const store = useSessionStore.getState(); + store.initializeSession(serverId, client as unknown as DaemonClient, 1); + store.updateSessionServerInfo(serverId, { + serverId, + hostname: null, + version: "test", + features: { workspaceMultiplicity: true, projectList: true }, + }); + const source = {}; + function setDemand(demanded: boolean): void { + if (demand === "full") directory.setDemand(source, demanded); + else directory.setAgentRouteDemand(demanded ? ["agent-1"] : []); + } + const releaseProjects = client.holdProjectFetch(); + const projects: ProjectListResult = { requestId: "projects", projects: [] }; + + try { + setDemand(true); + const refresh = directory.refreshDemand(); + await expect + .poll(() => [client.observeAgentsCalls, client.observeWorkspacesCalls]) + .toEqual([1, 1]); + + await Promise.all(client.listSnapshots); + setDemand(false); + if (timing === "before") setDemand(true); + releaseProjects(projects); + await refresh; + if (timing === "after") setDemand(true); + + await expect + .poll(() => [client.observeAgentsCalls, client.observeWorkspacesCalls]) + .toEqual([2, 2]); + client.emit({ + type: "agent_update", + payload: { + kind: "upsert", + agent: { + ...projectAgentSnapshot(createAgent(serverId, "agent-1")), + title: "Live title", + }, + project: deriveProjectPlacementFromCwd("/repo"), + }, + }); + client.emit({ + type: "workspace_update", + payload: { + kind: "upsert", + workspace: { ...createWorkspaceEntry("workspace-1"), name: "Live workspace" }, + }, + }); + + await expect + .poll(() => { + const session = useSessionStore.getState().sessions[serverId]; + return [ + session.agents.get("agent-1")?.title, + session.workspaces.get("workspace-1")?.name, + ]; + }) + .toEqual(["Live title", "Live workspace"]); + } finally { + directory.dispose(); + } + }, + ); + it("publishes cached directory data before the authoritative request completes", async () => { const serverId = "cached-directory"; serverIds.add(serverId); diff --git a/packages/app/src/runtime/directory-sync/index.ts b/packages/app/src/runtime/directory-sync/index.ts index b59440d782..1ffb4fae5f 100644 --- a/packages/app/src/runtime/directory-sync/index.ts +++ b/packages/app/src/runtime/directory-sync/index.ts @@ -160,6 +160,7 @@ export class DirectorySync { private readonly fullDemandSources = new Set(); private readonly scriptStatusDemand = new Map(); private demandRefresh: Promise | null = null; + private subscriptionGeneration = 0; private satisfiedDemandSource: DirectorySourceToken | null = null; private cursors: DirectoryCheckpoint = {}; @@ -262,6 +263,7 @@ export class DirectorySync { } private releaseSubscriptions(): void { + this.subscriptionGeneration += 1; for (const subscription of [ this.agentSubscription, this.workspaceSubscription, @@ -362,6 +364,7 @@ export class DirectorySync { this.observeDirectoryEvents(); this.observeScriptStatusEvents(); const source = this.connection.source; + const subscriptionGeneration = this.subscriptionGeneration; if ( !force && this.satisfiedDemandSource?.clientGeneration === source.clientGeneration && @@ -378,17 +381,19 @@ export class DirectorySync { ]).then(() => undefined); this.demandRefresh = refresh .then(() => { - this.satisfiedDemandSource = source; + if (this.subscriptionGeneration === subscriptionGeneration) { + this.satisfiedDemandSource = source; + } return undefined; }) .finally(() => { this.demandRefresh = null; const current = this.connection.source; - if ( - this.hasDemand() && - (current.clientGeneration !== source.clientGeneration || - current.connectionEpoch !== source.connectionEpoch) - ) { + const sourceChanged = + current.clientGeneration !== source.clientGeneration || + current.connectionEpoch !== source.connectionEpoch; + const subscriptionsReleased = this.subscriptionGeneration !== subscriptionGeneration; + if (this.hasDemand() && (sourceChanged || subscriptionsReleased)) { void this.requestDemandRefresh().catch(() => undefined); } }); From 5afa1a9f8ef4b069ff84278668c1fd030df42273 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 00:01:29 +0000 Subject: [PATCH 158/173] test(server): isolate cold Git filter from control work (#8397) Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- ...rkspace-git-service.observation.integration.test.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/server/src/server/workspace-git-service.observation.integration.test.ts b/packages/server/src/server/workspace-git-service.observation.integration.test.ts index c8d97390ed..371502748d 100644 --- a/packages/server/src/server/workspace-git-service.observation.integration.test.ts +++ b/packages/server/src/server/workspace-git-service.observation.integration.test.ts @@ -583,16 +583,21 @@ test("Git refresh, command tracing and 10,000 ignored alias events do no synchro // the cold filter. Allocations made by the filter still count. global.gc(); await tick(); - // Unrelated callbacks must not consume the synchronous filter's budget. + await marker('FILTER_START'); + // Schedule the control only after marker IO settles, so it cannot run + // and allocate garbage before the cold filter starts. No await may + // separate this scheduling from the synchronous measurement. const threadCpuUsage = Reflect.get(process, 'threadCpuUsage'); + let unrelatedWorkStarted = false; const unrelatedWork = tick().then(() => { + unrelatedWorkStarted = true; const started = threadCpuUsage(); while (true) { const cpu = threadCpuUsage(started); if (cpu.user + cpu.system >= 80000) break; } }); - await marker('FILTER_START'); + assert.equal(unrelatedWorkStarted, false, 'control work must not contaminate the cold filter'); hook.enable(); let blockingMs; try { @@ -609,6 +614,7 @@ test("Git refresh, command tracing and 10,000 ignored alias events do no synchro await marker('FILTER_END'); } await unrelatedWork; + assert.equal(unrelatedWorkStarted, true, 'control work must run outside the filter span'); assert.equal(fsCalls, 0, "filesystem calls"); assert.equal(notifications, 0, "ignored event notification"); assert.ok(blockingMs < 20, 'blocking filter work: ' + blockingMs); From 86c60d367c9dcc2edbfee29a06ee49ab6b77f28f Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 01:05:02 +0000 Subject: [PATCH 159/173] fix(claude): keep a resumed subagent on its row after the session reopens (#8408) SendMessage resumes a finished Claude subagent under its original task_id but a new tool_use_id, and the child's frames still name the original Task call as their parent. In the same process the live source already maps the new tool id onto the original row. After the session reopens, the child is only known from its transcript, so the resume was declared as a new subagent keyed by the SendMessage id: a second row, and every child frame dropped as undeclared. That row never showed the model or the child's reply. Replay now hands the live source each restored child's task id, id and presentation. The first task_started for that task id adopts the restored row, so the resume takes the same path it takes without a reopen. Co-authored-by: luke Co-authored-by: RoundRedDot Co-authored-by: Claude Opus 5.5 Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../claude/agent.sub-agent-replay.test.ts | 126 ++++++++++++++++++ .../server/agent/providers/claude/agent.ts | 1 + .../claude/subagents/live-source.test.ts | 36 +++++ .../providers/claude/subagents/live-source.ts | 44 +++++- .../claude/subagents/replay-source.test.ts | 44 ++++++ .../claude/subagents/replay-source.ts | 27 ++-- 6 files changed, 268 insertions(+), 10 deletions(-) diff --git a/packages/server/src/server/agent/providers/claude/agent.sub-agent-replay.test.ts b/packages/server/src/server/agent/providers/claude/agent.sub-agent-replay.test.ts index 4728767307..91007aa7ce 100644 --- a/packages/server/src/server/agent/providers/claude/agent.sub-agent-replay.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.sub-agent-replay.test.ts @@ -8,6 +8,7 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; import { createTestLogger } from "../../../../test-utils/test-logger.js"; import type { AgentStreamEvent } from "../../agent-sdk-types.js"; +import { streamSession } from "../test-utils/session-stream-adapter.js"; import { ClaudeAgentClient } from "./agent.js"; import { claudeProjectDirSync } from "./project-dir.js"; @@ -77,6 +78,29 @@ function sidechainEntry(options: { agentId?: string; stopReason?: string | null }); } +function buildQueryMock(events: unknown[]) { + let index = 0; + return { + next: vi.fn(async () => { + if (index >= events.length) return { done: true, value: undefined }; + const value = events[index]; + index += 1; + return { done: false, value }; + }), + interrupt: vi.fn(async () => undefined), + return: vi.fn(async () => undefined), + close: vi.fn(() => undefined), + setPermissionMode: vi.fn(async () => undefined), + setModel: vi.fn(async () => undefined), + supportedModels: vi.fn(async () => []), + supportedCommands: vi.fn(async () => []), + rewindFiles: vi.fn(async () => ({ canRewind: true })), + [Symbol.asyncIterator]() { + return this; + }, + }; +} + describe("ClaudeAgentSession persisted subagent replay", () => { const logger = createTestLogger(); const queryFactory = vi.fn(() => { @@ -1262,4 +1286,106 @@ describe("ClaudeAgentSession persisted subagent replay", () => { ); expect(items).toEqual([{ type: "assistant_message", text: report }]); }); + + test("keeps a subagent resumed after the session reopens on the row its transcript restored", async () => { + // Verified on the wire (Claude Code 2.1.309): SendMessage resumes a finished subagent under its + // original task_id but a new tool_use_id, and the child's frames still name the original Task + // call as their parent. A reopened session only knows that child from its transcript. + writeSession({ + parentLines: [taskToolUse(), taskToolResult()], + meta: JSON.stringify({ agentType: "general-purpose", toolUseId: TOOL_USE_ID }), + sidechainLines: [ + JSON.stringify({ + type: "assistant", + isSidechain: true, + agentId: AGENT_ID, + sessionId: "replay-session", + timestamp: "2026-07-26T06:27:50.000Z", + effort: "high", + message: { + role: "assistant", + model: "claude-sonnet-5", + content: [{ type: "text", text: "summary of the docs" }], + stop_reason: "end_turn", + }, + }), + ], + }); + const liveQuery = vi.fn(() => + buildQueryMock([ + { + type: "system", + subtype: "init", + session_id: "replay-session", + permissionMode: "default", + }, + { + type: "system", + subtype: "task_started", + task_id: AGENT_ID, + tool_use_id: "toolu_send_message", + description: "Summarize the docs", + subagent_type: "general-purpose", + task_type: "local_agent", + is_backgrounded: true, + prompt: "Summarize them again", + }, + { + type: "assistant", + parent_tool_use_id: TOOL_USE_ID, + session_id: "replay-session", + message: { + id: "msg_resumed_child", + role: "assistant", + model: "claude-opus-5", + content: [{ type: "text", text: "summary again" }], + }, + }, + { + type: "system", + subtype: "task_updated", + task_id: AGENT_ID, + patch: { status: "completed" }, + }, + { + type: "result", + subtype: "success", + usage: { input_tokens: 1, cache_read_input_tokens: 0, output_tokens: 1 }, + total_cost_usd: 0, + }, + ]), + ); + const session = await new ClaudeAgentClient({ + logger, + queryFactory: liveQuery, + resolveVersion: async () => "2.1.309", + resolveBinary: async () => "/test/claude/bin", + }).resumeSession({ provider: "claude", sessionId: "replay-session" }, { cwd }); + const events: AgentStreamEvent[] = []; + for await (const event of streamSession(session, "Ask it to summarize again")) { + events.push(event); + if (event.type === "turn_completed" || event.type === "turn_failed") break; + } + await session.close(); + + const live = events.flatMap((event) => + event.type === "provider_subagent" ? [event.event] : [], + ); + expect(new Set(live.map((event) => event.id))).toEqual(new Set([TOOL_USE_ID])); + expect(live).toContainEqual( + expect.objectContaining({ + type: "upsert", + id: TOOL_USE_ID, + subtitle: "general-purpose · Opus 5 · High", + }), + ); + expect(live).toContainEqual( + expect.objectContaining({ + type: "timeline", + id: TOOL_USE_ID, + item: expect.objectContaining({ type: "assistant_message", text: "summary again" }), + }), + ); + expect(live.at(-1)).toMatchObject({ type: "upsert", id: TOOL_USE_ID, status: "completed" }); + }); }); diff --git a/packages/server/src/server/agent/providers/claude/agent.ts b/packages/server/src/server/agent/providers/claude/agent.ts index ae48883654..d232185cbb 100644 --- a/packages/server/src/server/agent/providers/claude/agent.ts +++ b/packages/server/src/server/agent/providers/claude/agent.ts @@ -5455,6 +5455,7 @@ class ClaudeAgentSession implements AgentSession { convertEntry: (entry) => this.convertHistoryEntry(entry), })), ]; + this.taskProtocolSource.restore(subagentReplay.restored); const restoredProviderSubagentIds = new Set( observations .filter((observation) => observation.kind === "declared") diff --git a/packages/server/src/server/agent/providers/claude/subagents/live-source.test.ts b/packages/server/src/server/agent/providers/claude/subagents/live-source.test.ts index b0bfc3d755..b12ab8eb6a 100644 --- a/packages/server/src/server/agent/providers/claude/subagents/live-source.test.ts +++ b/packages/server/src/server/agent/providers/claude/subagents/live-source.test.ts @@ -156,6 +156,42 @@ describe("ClaudeTaskProtocolSource", () => { ]); }); + it("resumes a child a reopened session restored on its original row", () => { + const source = new ClaudeTaskProtocolSource(); + source.restore([ + { + taskId: "a1730a6215e1f5cf6", + id: "toolu_original", + presentation: { title: "general-purpose", model: "claude-sonnet-5", effort: "high" }, + }, + ]); + + // Restored is not running: a canceled turn and an unannounced frame leave it alone. + expect(source.cancelRunningForegroundTasks()).toEqual([]); + expect(source.resolveSubagentId("toolu_original")).toBeUndefined(); + + expect( + source.observe(taskStarted({ tool_use_id: "toolu_resumed", prompt: "Resumed prompt" })), + ).toEqual([ + { kind: "status", id: "toolu_original", status: "running" }, + { + kind: "timeline", + id: "toolu_original", + item: { type: "user_message", text: "Resumed prompt" }, + }, + ]); + expect(source.resolveSubagentId("toolu_original")).toBe("toolu_original"); + expect(source.resolveSubagentId("toolu_resumed")).toBe("toolu_original"); + expect( + source.observeSidechainFrame( + { type: "assistant", message: { model: "claude-opus-5" } } as unknown as SDKMessage, + "toolu_original", + ), + ).toEqual([ + { kind: "subtitle", id: "toolu_original", subtitle: "general-purpose · Opus 5 · High" }, + ]); + }); + it("declares a distinct task separately", () => { const source = new ClaudeTaskProtocolSource(); source.observe(taskStarted({ task_id: "first", tool_use_id: "toolu_first" })); diff --git a/packages/server/src/server/agent/providers/claude/subagents/live-source.ts b/packages/server/src/server/agent/providers/claude/subagents/live-source.ts index af941aa24b..b7b3201897 100644 --- a/packages/server/src/server/agent/providers/claude/subagents/live-source.ts +++ b/packages/server/src/server/agent/providers/claude/subagents/live-source.ts @@ -121,6 +121,16 @@ function readString(value: unknown): string | undefined { return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined; } +/** + * A subagent a reopened session rebuilt from its transcript. Its `taskId` (the transcript's + * agentId) is the task id Claude announces again when SendMessage resumes the child. + */ +export interface ClaudeRestoredSubagent { + taskId: string; + id: string; + presentation: ClaudeSubagentPresentationFacts; +} + export interface ClaudeTaskProtocolSourceInput { /** * The parent's Task tool input, by tool_use id. @@ -162,6 +172,14 @@ export class ClaudeTaskProtocolSource { private readonly backgroundedIds = new Set(); /** Last status emitted per subagent, so a redundant announcement is not re-broadcast. */ private readonly lastStatusById = new Map(); + /** + * Children a reopened session restored from its transcript, by task id. Claude resumes one under + * its old task id with a new tool id, while its frames keep the original Task call as parent. + * Without this the resume reads as a new task: a second row, and every frame dropped as + * undeclared. Held apart from the declared table so a restored child is left alone until + * Claude announces it again. + */ + private readonly restoredByTaskId = new Map(); /** Claude facts stay inside the provider boundary; clients receive one compact subtitle. */ private readonly presentationById = new Map(); private readonly lastSubtitleById = new Map(); @@ -246,6 +264,14 @@ export class ClaudeTaskProtocolSource { } } + /** Remember the children a reopened session restored, for Claude to resume by task id. */ + restore(subagents: Iterable): void { + for (const subagent of subagents) { + if (this.subagentIdByTaskId.has(subagent.taskId)) continue; + this.restoredByTaskId.set(subagent.taskId, subagent); + } + } + /** * Forget the session. * @@ -259,6 +285,7 @@ export class ClaudeTaskProtocolSource { this.ownerSubagentIdByToolUseId.clear(); this.ownerSubagentIdByTaskId.clear(); this.declaredIds.clear(); + this.restoredByTaskId.clear(); this.workflowTaskIds.clear(); this.lastWorkflowResultByTaskId.clear(); this.idsWithExistingParentToolCard.clear(); @@ -315,7 +342,8 @@ export class ClaudeTaskProtocolSource { if (!id || message.skip_transcript === true || !isProviderSubagentTask(message)) return []; this.sawTaskStarted = true; - const existingId = this.subagentIdByTaskId.get(message.task_id); + const existingId = + this.subagentIdByTaskId.get(message.task_id) ?? this.adoptRestored(message.task_id); this.recordBackgrounded(existingId ?? id, message.is_backgrounded); if (existingId) { return this.observeExistingTaskStart(message, id, existingId); @@ -324,6 +352,20 @@ export class ClaudeTaskProtocolSource { return this.observeNewTaskStart(message, id, parentSubagentId); } + /** Declare a restored child under the id its transcript gave it, with what it already showed. */ + private adoptRestored(taskId: string): string | undefined { + const restored = this.restoredByTaskId.get(taskId); + if (!restored) return undefined; + this.restoredByTaskId.delete(taskId); + this.subagentIdByTaskId.set(taskId, restored.id); + this.canonicalIdByToolUseId.set(restored.id, restored.id); + this.declaredIds.add(restored.id); + this.presentationById.set(restored.id, restored.presentation); + const subtitle = buildClaudeSubagentSubtitle(restored.presentation); + if (subtitle) this.lastSubtitleById.set(restored.id, subtitle); + return restored.id; + } + private observeExistingTaskStart( message: TaskStartedMessage, toolUseId: string, diff --git a/packages/server/src/server/agent/providers/claude/subagents/replay-source.test.ts b/packages/server/src/server/agent/providers/claude/subagents/replay-source.test.ts index 3bde4b813b..fc48e9db3a 100644 --- a/packages/server/src/server/agent/providers/claude/subagents/replay-source.test.ts +++ b/packages/server/src/server/agent/providers/claude/subagents/replay-source.test.ts @@ -85,6 +85,50 @@ describe("parseClaudeSubagentMeta", () => { }); describe("observeReplaySubagents", () => { + it("restores a resumed child on its original row after consuming async history", async () => { + async function* entries(): AsyncGenerator { + yield { type: "assistant", message: { model: "claude-opus-5" } }; + yield { + type: "assistant", + effort: "high", + message: { model: "claude-sonnet-5", usage: { input_tokens: 10, output_tokens: 2 } }, + }; + } + const replay = await observeReplaySubagents({ + subagents: [{ agentId: AGENT_ID, meta: { toolUseId: TOOL_USE_ID }, entries: entries() }], + parent: parentWithTaskCall(), + convertEntry: async () => [], + }); + expect(replay.restored).toEqual([ + { + taskId: AGENT_ID, + id: TOOL_USE_ID, + presentation: { + title: "general-purpose", + model: "claude-sonnet-5", + effort: "high", + usage: { totalTokens: 12 }, + }, + }, + ]); + const live = new ClaudeTaskProtocolSource(); + live.restore(replay.restored); + expect( + live.observe({ + type: "system", + subtype: "task_started", + task_id: AGENT_ID, + tool_use_id: "resumed-tool", + description: "Resume the captured task", + task_type: "local_agent", + is_backgrounded: true, + uuid: "00000000-0000-0000-0000-000000000000", + session_id: "reopened-session", + }), + ).toEqual([{ kind: "status", id: TOOL_USE_ID, status: "running" }]); + expect(live.resolveSubagentId("resumed-tool")).toBe(TOOL_USE_ID); + }); + it("links a subagent to its Task call through meta.toolUseId", async () => { const observations = ( await observeReplaySubagents({ diff --git a/packages/server/src/server/agent/providers/claude/subagents/replay-source.ts b/packages/server/src/server/agent/providers/claude/subagents/replay-source.ts index 02cbb783f0..51e5ff9c09 100644 --- a/packages/server/src/server/agent/providers/claude/subagents/replay-source.ts +++ b/packages/server/src/server/agent/providers/claude/subagents/replay-source.ts @@ -5,6 +5,7 @@ import { normalizeProviderReplayTimestamp } from "../../../provider-history-time import type { ProviderSubagentStatus } from "../../../provider-subagents/store.js"; import { isClaudeInterruptPlaceholderText } from "../interrupt-placeholder.js"; import { resolveObservedClaudeModelId } from "../models.js"; +import type { ClaudeRestoredSubagent } from "./live-source.js"; import type { SubagentObservation } from "./observation.js"; import { buildClaudeSubagentSubtitle, type ClaudeSubagentUsage } from "./presentation.js"; @@ -246,6 +247,7 @@ async function observeSubagent( parent: ClaudeReplayParentFacts, convertEntry: (entry: ClaudeReplayEntry) => AgentTimelineItem[] | Promise, toolOwners: Map, + restored: ClaudeRestoredSubagent[], parentSubagentId?: string, ): Promise { const link = resolveParentLink(subagent, parent); @@ -276,13 +278,14 @@ async function observeSubagent( const observations = [ declareSubagent(subagent, link, toolCall, parentSubagentId, firstTimestamp), ]; - const subtitle = observeSubtitle( - link, - toolCall?.title ?? subagent.meta?.agentType, - runtime, - usage, - lastTimestamp, - ); + const title = toolCall?.title ?? subagent.meta?.agentType; + // The agentId is the task_id Claude resumes this child under, so live can find it again. + restored.push({ + taskId: subagent.agentId, + id: link.id, + presentation: { ...(title ? { title } : {}), ...runtime, ...(usage ? { usage } : {}) }, + }); + const subtitle = observeSubtitle(link, title, runtime, usage, lastTimestamp); if (subtitle) observations.push(subtitle); for (const observation of timeline) observations.push(observation); const terminalStatus = link.status ?? childTerminalStatus; @@ -337,9 +340,14 @@ export async function observeReplaySubagents(input: { subagents: readonly ClaudeReplaySubagentInput[]; parent: ClaudeReplayParentFacts; convertEntry: (entry: ClaudeReplayEntry) => AgentTimelineItem[] | Promise; -}): Promise<{ observations: SubagentObservation[]; toolOwners: ReadonlyMap }> { +}): Promise<{ + observations: SubagentObservation[]; + toolOwners: ReadonlyMap; + restored: readonly ClaudeRestoredSubagent[]; +}> { const observations: SubagentObservation[] = []; const toolOwners = new Map(); + const restored: ClaudeRestoredSubagent[] = []; const unresolved = [...input.subagents].sort( (left, right) => (left.meta?.spawnDepth ?? 1) - (right.meta?.spawnDepth ?? 1), ); @@ -364,6 +372,7 @@ export async function observeReplaySubagents(input: { parent, input.convertEntry, toolOwners, + restored, ownerId, )) { observations.push(observation); @@ -373,7 +382,7 @@ export async function observeReplaySubagents(input: { madeProgress = true; } } - return { observations, toolOwners }; + return { observations, toolOwners, restored }; } function resolveReplayOwner( From da75aa7a4aeca07fde29df038e1aec97d6e7d7e4 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sun, 1 Nov 2026 10:33:59 +0700 Subject: [PATCH 160/173] Fix terminal emoji size and alignment (#8375) * fix(terminal): render emoji at their intended width The native grid scales glyphs to the columns assigned by the terminal buffer. Use grapheme widths across current hosts and clients so emoji fit their slots and replay preserves cursor positions. * fix(terminal): make width regression test portable * test(terminal): wait for replay fixture output to finish A trailing newline could arrive after the readiness marker and change the retained history between replay captures. --- docs/terminal-rendering.md | 16 +++- package-lock.json | 91 ++++++++++--------- .../e2e/mobile/terminal-rendering/check.mjs | 3 + .../src/androidTest/assets/grapheme-rows.json | 20 ++-- .../paseo/terminal/TerminalRowLayoutTest.kt | 8 -- packages/app/package.json | 9 +- .../components/terminal-emulator-contract.ts | 2 + .../terminal-emulator-native-grid.native.tsx | 3 + .../app/src/components/terminal-emulator.tsx | 10 ++ packages/app/src/components/terminal-pane.tsx | 7 ++ packages/app/src/terminal/character-widths.ts | 9 ++ .../headless-terminal-state.test.ts | 48 ++++++++++ .../headless-terminal-state.ts | 10 ++ .../native-renderer/terminal-frame.test.ts | 14 ++- .../terminal-emulator-runtime.browser.test.ts | 61 +++++++++++++ .../runtime/terminal-emulator-runtime.test.ts | 6 ++ .../runtime/terminal-emulator-runtime.ts | 29 ++++-- packages/protocol/src/messages.ts | 2 + packages/server/package.json | 3 +- .../websocket-server.relay-reconnect.test.ts | 1 + .../server/src/server/websocket-server.ts | 2 + .../src/terminal/headless-terminal.test.ts | 60 ++++++++++++ .../server/src/terminal/headless-terminal.ts | 22 +++++ packages/server/src/terminal/terminal.test.ts | 65 +++++++++++++ packages/server/src/terminal/terminal.ts | 12 +-- .../src/terminal/test-utils/terminal-state.ts | 5 +- .../terminal/worker-terminal-manager.test.ts | 3 +- 27 files changed, 422 insertions(+), 99 deletions(-) create mode 100644 packages/app/src/terminal/character-widths.ts create mode 100644 packages/server/src/terminal/headless-terminal.test.ts create mode 100644 packages/server/src/terminal/headless-terminal.ts diff --git a/docs/terminal-rendering.md b/docs/terminal-rendering.md index fd304aa144..4c418595fc 100644 --- a/docs/terminal-rendering.md +++ b/docs/terminal-rendering.md @@ -6,15 +6,25 @@ Web and Electron draw terminals with xterm.js. iOS and Android keep an `@xterm/h xterm decides which column every cell occupies. The native views never let text advance move a cell. Each row is shaped once, one run per font face, so Hangul jamo, ligatures, combining marks, conjuncts and fallback fonts see their neighbours. Each shaped cluster is then drawn at its first cell's column, centred in the columns it owns, and scaled down when its glyphs are wider. Cursor, selection, hit-testing and copy all use xterm's columns, so they stay correct whatever the font does. -A cluster is the run of cells the shaper merged, and it is drawn once from the shaped row. Drawing part of a cluster on its own reshapes it: a half-form conjunct such as `स्ते` comes apart into `स्` with a visible virama. So colour and selection never split a cluster. A cluster whose cells differ in colour is drawn once per colour, clipped to that colour's columns. +A cluster is the run of cells the shaper merged, and it is drawn once from the shaped row. xterm usually keeps a conjunct in one cell (see [Character widths](#character-widths)), but a colour change inside it leaves `क्` and `ष` in separate cells that still shape together. Drawing part of a cluster on its own reshapes it: the conjunct comes apart into `क्` with a visible virama. So colour and selection never split a cluster. A cluster whose cells differ in colour is drawn once per colour, clipped to that colour's columns. -Android also groups cells with `android.icu.text.BreakIterator`, because Minikin's advances and cursor boundaries alone split some conjuncts. Grapheme rules follow the OS ICU version. Android 10 (API 29) splits `स्ते` after the virama and renders it incorrectly. The tested corpus passed on API 33, 34 and 35; API 30–32 have not been tested. We accept that version-dependent limitation to avoid bundling approximately 14 MB of ICU4J data. CoreText keeps this conjunct together on iOS. This renderer does not guarantee identical shaping across OS versions. +Android also groups cells with `android.icu.text.BreakIterator`, because Minikin's advances and cursor boundaries alone split some clusters that span cells. Grouping only merges whole cells, so a conjunct xterm keeps in one cell cannot be split by the OS. Grapheme rules follow the OS ICU version, and we accept that to avoid bundling approximately 14 MB of ICU4J data. Before the buffers used grapheme widths, Android 10 (API 29) split `स्ते` across its two cells. This renderer does not guarantee identical shaping across OS versions. `TerminalRowLayoutTest.kt` is the Android regression test. It draws the rows of `grapheme-rows.json` and compares each with its grapheme clusters drawn one at a time, and with a wrong clustering that must not match. `terminal-frame.test.ts` checks that those rows are what xterm produces and that the clusters are UAX #29 grapheme clusters. Run it with `./gradlew :paseo-terminal:connectedDebugAndroidTest` from `packages/app/android`, with `ANDROID_SERIAL` set. The view reports ready only after it has measured its grid size. The pane attaches with that size, so the daemon replays the terminal at the client's size. Before this, the replay arrived at the PTY's old size, the resize came after it, and the shell's redraw landed on the wrong rows. -Emoji widths come from the headless buffer, which uses xterm's default Unicode 6 table. `👍` gets one column, and `👋🏽` and `🇰🇷` get two cells drawn as one cluster. Web loads the Unicode 11 addon, so the same output can wrap differently on web and native. +## Character widths + +The daemon, native and web buffers all load `@xterm/addon-unicode-graphemes`: the daemon through `packages/server/src/terminal/headless-terminal.ts`, native in `createNativeHeadlessTerminal`, web in `terminal-emulator-runtime.ts`. Each emoji cluster takes one two-column cell, including VS16 (`❤️`), skin tones (`👋🏽`), flags (`🇰🇷`) and ZWJ sequences (`👨‍👩‍👧`). That is the width colour-emoji fonts draw at. Under xterm's default Unicode 6 table `😀` got one column, and the native views scaled it to half size to fit. + +Every buffer must use the same table. The daemon answers cursor-position reports (`CSI 6n`) from its buffer, and a client re-parses the daemon's ANSI replay with its own table. A disagreement moves the cursor and the later cells of any row that holds a disputed cluster: after replay from a Unicode 6 daemon, the cursor that followed `A😀😀😀B` lands inside the third emoji. + +Daemons that use grapheme widths advertise `server_info.features["terminal-grapheme-widths"]`. `terminal-pane.tsx` reads it once and passes `characterWidths` to the emulator. Against an older daemon the app keeps each renderer's previous table: xterm's default on native, Unicode 11 on web. An older app against a newer daemon cannot match it, because every client shares the daemon's one buffer. A terminal kept by a worker from an unreleased pre-grapheme build keeps that worker's table until it exits. + +The table follows Unicode grapheme clusters, as Node's `string-width` does for Ink-based agent TUIs. Indic conjuncts follow the same rule: `क्ष` and `स्ते` take one column, and the native views scale them down to fit it. Shells measure with the C library's `wcwidth` instead. glibc counts `❤️` as one column, `👋🏽` as four and `क्ष` as two, so a line editor that measures those disagrees with the terminal. + +Use `@xterm/addon-unicode-graphemes` 0.5.0-beta.330 or later. Earlier versions read their width table from the wrong offset when Node decodes it into a pooled `Buffer`, which gives wrong widths or a load error depending on earlier allocations. `headless-terminal.test.ts` forces that case in a fresh process. ## Ink outside the row diff --git a/package-lock.json b/package-lock.json index 30ceb1cb4c..49f6258e60 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14740,16 +14740,52 @@ "node": ">=10.0.0" } }, + "node_modules/@xterm/addon-image": { + "version": "0.10.0-beta.331", + "resolved": "https://registry.npmjs.org/@xterm/addon-image/-/addon-image-0.10.0-beta.331.tgz", + "integrity": "sha512-ShBTb3QF0ul/i55lfRdJpcu0hlA4aJdqRdzzHdOCws2WUzSsG0SCfMhLjzaoO1dVUGNj2Z7PNLqiXnlyqOinbg==", + "license": "MIT", + "peerDependencies": { + "@xterm/xterm": "^6.1.0-beta.336" + } + }, "node_modules/@xterm/addon-serialize": { "version": "0.14.0", "resolved": "https://registry.npmjs.org/@xterm/addon-serialize/-/addon-serialize-0.14.0.tgz", "integrity": "sha512-uteyTU1EkrQa2Ux6P/uFl2fzmXI46jy5uoQMKEOM0fKTyiW7cSn0WrFenHm5vO5uEXX/GpwW/FgILvv3r0WbkA==", "license": "MIT" }, + "node_modules/@xterm/addon-unicode-graphemes": { + "version": "0.5.0-beta.330", + "resolved": "https://registry.npmjs.org/@xterm/addon-unicode-graphemes/-/addon-unicode-graphemes-0.5.0-beta.330.tgz", + "integrity": "sha512-Zoiv/8tmku4LcU7bEL6zer+DNN6p6F8VCkyviSmbDxpA/W9zSnWDiD/ZpwFDQqegwjSptGzBNMhW2Os1sa+lUw==", + "license": "MIT", + "peerDependencies": { + "@xterm/xterm": "^6.1.0-beta.336" + } + }, + "node_modules/@xterm/addon-webgl": { + "version": "0.20.0-beta.329", + "resolved": "https://registry.npmjs.org/@xterm/addon-webgl/-/addon-webgl-0.20.0-beta.329.tgz", + "integrity": "sha512-bwqMma7X4cCBfwmWqKuhxNLkIXKW0lJTapaQ0g/9Kq7n6D6VCL4dYQCQ6DoeHv27ncJD4WzeoDTCEeSn0cspfg==", + "license": "MIT", + "peerDependencies": { + "@xterm/xterm": "^6.1.0-beta.336" + } + }, "node_modules/@xterm/headless": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/@xterm/headless/-/headless-6.0.0.tgz", - "integrity": "sha512-5Yj1QINYCyzrZtf8OFIHi47iQtI+0qYFPHmouEfG8dHNxbZ9Tb9YGSuLcsEwj9Z+OL75GJqPyJbyoFer80a2Hw==", + "version": "6.1.0-beta.334", + "resolved": "https://registry.npmjs.org/@xterm/headless/-/headless-6.1.0-beta.334.tgz", + "integrity": "sha512-QkwuIeP9dXlk/eOsAbqX8AvtS/W8EhRo6dkl2YYZr+jWAWSfDDMi+zPlegWUflSdsRKMURMvzvvkVZr6GztK4g==", + "license": "MIT", + "workspaces": [ + "addons/*" + ] + }, + "node_modules/@xterm/xterm": { + "version": "6.1.0-beta.336", + "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.1.0-beta.336.tgz", + "integrity": "sha512-QrvZZsffXsLW4Z3sba9GqimLvVwlb8b3W1NwZ+l6DdRnpH5pg5cFGWg2ceIburmfaGQ07YJHNekwxxlTcHZ3BA==", "license": "MIT", "workspaces": [ "addons/*" @@ -37626,13 +37662,14 @@ "@tanstack/react-virtual": "^3.13.21", "@xterm/addon-clipboard": "^0.3.0-beta.213", "@xterm/addon-fit": "^0.12.0-beta.213", - "@xterm/addon-image": "^0.10.0-beta.213", + "@xterm/addon-image": "0.10.0-beta.331", "@xterm/addon-ligatures": "^0.11.0-beta.213", "@xterm/addon-search": "^0.17.0-beta.213", + "@xterm/addon-unicode-graphemes": "0.5.0-beta.330", "@xterm/addon-unicode11": "^0.10.0-beta.213", "@xterm/addon-web-links": "^0.13.0-beta.213", - "@xterm/addon-webgl": "0.20.0-beta.291", - "@xterm/xterm": "6.1.0-beta.292", + "@xterm/addon-webgl": "0.20.0-beta.329", + "@xterm/xterm": "6.1.0-beta.336", "buffer": "^6.0.3", "expo": "~57.0.30", "expo-asset": "~57.0.20", @@ -37710,7 +37747,7 @@ "@vitest/browser": "^4.1.7", "@vitest/browser-playwright": "^4.1.7", "@xterm/addon-serialize": "0.14.0", - "@xterm/headless": "^6.1.0-beta.213", + "@xterm/headless": "6.1.0-beta.334", "babel-preset-expo": "~57.0.16", "dotenv": "^17.2.3", "eas-cli": "^16.24.1", @@ -38489,15 +38526,6 @@ "@xterm/xterm": "^6.1.0-beta.213" } }, - "packages/app/node_modules/@xterm/addon-image": { - "version": "0.10.0-beta.213", - "resolved": "https://registry.npmjs.org/@xterm/addon-image/-/addon-image-0.10.0-beta.213.tgz", - "integrity": "sha512-L3QxLkj8g8TioVea9p1oVze52Jr75rRZPPLm1tgZl0X2EGJGFHnQzE3QRsgmYWI7R5j3kwwi3MRAkOAgvOK8uA==", - "license": "MIT", - "peerDependencies": { - "@xterm/xterm": "^6.1.0-beta.213" - } - }, "packages/app/node_modules/@xterm/addon-ligatures": { "version": "0.11.0-beta.213", "resolved": "https://registry.npmjs.org/@xterm/addon-ligatures/-/addon-ligatures-0.11.0-beta.213.tgz", @@ -38541,34 +38569,6 @@ "@xterm/xterm": "^6.1.0-beta.213" } }, - "packages/app/node_modules/@xterm/addon-webgl": { - "version": "0.20.0-beta.291", - "resolved": "https://registry.npmjs.org/@xterm/addon-webgl/-/addon-webgl-0.20.0-beta.291.tgz", - "integrity": "sha512-gH7r5g8f2NWMhBtaeApuwLQTJmX4uq7zT0okjeNWkFAD0nxzbUPB+kt6sogZZ5K90XYPt2OLu/bhuvF6DmKqOQ==", - "license": "MIT", - "peerDependencies": { - "@xterm/xterm": "^6.1.0-beta.292" - } - }, - "packages/app/node_modules/@xterm/headless": { - "version": "6.1.0-beta.213", - "resolved": "https://registry.npmjs.org/@xterm/headless/-/headless-6.1.0-beta.213.tgz", - "integrity": "sha512-D08E4Bl0HRhYZRL2o5PxD4FNQN9qXpI8QSw3CkKrsym5dtTRAqsynVYE8V8echQrxfb+EpR0CB5reM7tEGZ/fA==", - "dev": true, - "license": "MIT", - "workspaces": [ - "addons/*" - ] - }, - "packages/app/node_modules/@xterm/xterm": { - "version": "6.1.0-beta.292", - "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.1.0-beta.292.tgz", - "integrity": "sha512-17zqK5tM/l6qeD7McF42OrEJ6w3XqJ2vFVKdWqu0cYLzdFqMWAHp2oFNc8Fj5DmqDSl1E1FZEg6IFflDllTvLA==", - "license": "MIT", - "workspaces": [ - "addons/*" - ] - }, "packages/app/node_modules/babel-plugin-syntax-hermes-parser": { "version": "0.36.1", "resolved": "https://registry.npmjs.org/babel-plugin-syntax-hermes-parser/-/babel-plugin-syntax-hermes-parser-0.36.1.tgz", @@ -40690,7 +40690,8 @@ "@opencode-ai/sdk": "1.14.46", "@opencode/client": "2.0.10", "@xterm/addon-serialize": "0.14.0", - "@xterm/headless": "^6.0.0", + "@xterm/addon-unicode-graphemes": "0.5.0-beta.330", + "@xterm/headless": "6.1.0-beta.334", "ai": "5.0.78", "ajv": "^8.20.0", "bcryptjs": "^3.0.3", diff --git a/packages/app/e2e/mobile/terminal-rendering/check.mjs b/packages/app/e2e/mobile/terminal-rendering/check.mjs index fbf4529bb3..92287e0586 100644 --- a/packages/app/e2e/mobile/terminal-rendering/check.mjs +++ b/packages/app/e2e/mobile/terminal-rendering/check.mjs @@ -1,5 +1,6 @@ import assert from "node:assert/strict"; import { writeFileSync } from "node:fs"; +import { UnicodeGraphemesAddon } from "@xterm/addon-unicode-graphemes"; import xterm from "@xterm/headless"; import { PNG } from "pngjs"; import { ACCENT, fixtureLines, fixtureOutput, RULER_CELLS, SELECT_LINE } from "./fixture.mjs"; @@ -82,6 +83,8 @@ async function fixtureTerminal(size) { rows: size.rows, allowProposedApi: true, }); + // The app's buffer uses grapheme widths; the expected cells must too. + terminal.loadAddon(new UnicodeGraphemesAddon()); await new Promise((done) => terminal.write(fixtureOutput(size.columns).replaceAll("\n", "\r\n"), done), ); diff --git a/packages/app/modules/paseo-terminal/android/src/androidTest/assets/grapheme-rows.json b/packages/app/modules/paseo-terminal/android/src/androidTest/assets/grapheme-rows.json index 31c2b0c8d7..351ed32e73 100644 --- a/packages/app/modules/paseo-terminal/android/src/androidTest/assets/grapheme-rows.json +++ b/packages/app/modules/paseo-terminal/android/src/androidTest/assets/grapheme-rows.json @@ -1,21 +1,21 @@ [ { "output": "स्ते", - "row": "2,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1;8,4294638330,0,0;स्ते ", - "clusterStarts": [0, 2, 3, 4, 5, 6, 7], - "contrastStarts": [0, 1, 2, 3, 4, 5, 6, 7] + "row": "4,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1;8,4294638330,0,0;स्ते ", + "clusterStarts": [0, 1, 2, 3, 4, 5, 6, 7], + "contrastStarts": [0, 2, 3, 4, 5, 6, 7] }, { "output": "क्ष", - "row": "2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1;8,4294638330,0,0;क्ष ", - "clusterStarts": [0, 2, 3, 4, 5, 6, 7], - "contrastStarts": [0, 1, 2, 3, 4, 5, 6, 7] + "row": "3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1;8,4294638330,0,0;क्ष ", + "clusterStarts": [0, 1, 2, 3, 4, 5, 6, 7], + "contrastStarts": [0, 2, 3, 4, 5, 6, 7] }, { "output": "নক্ষত্র", - "row": "1,1,2,1,1,1,2,1,1,1,1,1,1,1,1,1;8,4294638330,0,0;নক্ষত্র ", - "clusterStarts": [0, 1, 3, 5, 6, 7], - "contrastStarts": [0, 1, 2, 3, 4, 5, 6, 7] + "row": "1,1,3,1,3,1,1,1,1,1,1,1,1,1,1,1;8,4294638330,0,0;নক্ষত্র ", + "clusterStarts": [0, 1, 2, 3, 4, 5, 6, 7], + "contrastStarts": [0, 2, 3, 4, 5, 6, 7] }, { "output": "क्अ", @@ -31,7 +31,7 @@ }, { "output": "अ्क", - "row": "2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1;8,4294638330,0,0;अ्क ", + "row": "3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1;8,4294638330,0,0;अ्क ", "clusterStarts": [0, 1, 2, 3, 4, 5, 6, 7], "contrastStarts": [0, 2, 3, 4, 5, 6, 7] } diff --git a/packages/app/modules/paseo-terminal/android/src/androidTest/java/sh/paseo/terminal/TerminalRowLayoutTest.kt b/packages/app/modules/paseo-terminal/android/src/androidTest/java/sh/paseo/terminal/TerminalRowLayoutTest.kt index 8e889bccf2..632065eab0 100644 --- a/packages/app/modules/paseo-terminal/android/src/androidTest/java/sh/paseo/terminal/TerminalRowLayoutTest.kt +++ b/packages/app/modules/paseo-terminal/android/src/androidTest/java/sh/paseo/terminal/TerminalRowLayoutTest.kt @@ -1,6 +1,5 @@ package sh.paseo.terminal -import android.os.Build import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Paint @@ -44,13 +43,6 @@ class TerminalRowLayoutTest { val output = row.getString("output") val (toExpected, toContrast) = difference(drawn, expected) to difference(drawn, contrast) Log.i("TerminalRowLayoutTest", "$output expected=$toExpected contrast=$toContrast") - // Android 10's platform ICU splits this conjunct. Keep its observed raster baseline - // explicit rather than claiming this supported OS passes the modern grapheme corpus. - if (Build.VERSION.SDK_INT == 29 && output == "स्ते") { - assertTrue("Android 10 unexpectedly matches modern conjunct clustering", toExpected > MATCH_TOLERANCE) - assertTrue("Android 10 split-conjunct baseline changed", toContrast <= MATCH_TOLERANCE) - continue - } assertTrue("$output differs from its grapheme clusters by $toExpected", toExpected <= MATCH_TOLERANCE) assertTrue("$output also matches the wrong clusters", toContrast > MATCH_TOLERANCE) } diff --git a/packages/app/package.json b/packages/app/package.json index 4fcd5d4737..e6cc1d4029 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -71,13 +71,14 @@ "@tanstack/react-virtual": "^3.13.21", "@xterm/addon-clipboard": "^0.3.0-beta.213", "@xterm/addon-fit": "^0.12.0-beta.213", - "@xterm/addon-image": "^0.10.0-beta.213", + "@xterm/addon-image": "0.10.0-beta.331", "@xterm/addon-ligatures": "^0.11.0-beta.213", "@xterm/addon-search": "^0.17.0-beta.213", + "@xterm/addon-unicode-graphemes": "0.5.0-beta.330", "@xterm/addon-unicode11": "^0.10.0-beta.213", "@xterm/addon-web-links": "^0.13.0-beta.213", - "@xterm/addon-webgl": "0.20.0-beta.291", - "@xterm/xterm": "6.1.0-beta.292", + "@xterm/addon-webgl": "0.20.0-beta.329", + "@xterm/xterm": "6.1.0-beta.336", "buffer": "^6.0.3", "expo": "~57.0.30", "expo-asset": "~57.0.20", @@ -155,7 +156,7 @@ "@vitest/browser": "^4.1.7", "@vitest/browser-playwright": "^4.1.7", "@xterm/addon-serialize": "0.14.0", - "@xterm/headless": "^6.1.0-beta.213", + "@xterm/headless": "6.1.0-beta.334", "babel-preset-expo": "~57.0.16", "dotenv": "^17.2.3", "eas-cli": "^16.24.1", diff --git a/packages/app/src/components/terminal-emulator-contract.ts b/packages/app/src/components/terminal-emulator-contract.ts index 12638161a1..b4e3dd93e1 100644 --- a/packages/app/src/components/terminal-emulator-contract.ts +++ b/packages/app/src/components/terminal-emulator-contract.ts @@ -12,6 +12,7 @@ import type { } from "../terminal/local-links/terminal-local-link-provider"; import type { TerminalClipboardWriter } from "../terminal/native-renderer/terminal-selection"; import type { TerminalFile } from "../terminal/file-paste"; +import type { TerminalCharacterWidths } from "../terminal/character-widths"; import type { PendingTerminalModifiers } from "../utils/terminal-keys"; import type { TerminalRendererReadyChange } from "../utils/terminal-renderer-readiness"; @@ -32,6 +33,7 @@ export interface TerminalEmulatorProps { ref: Ref; streamKey: string; supportsTerminalInputModeReplay: boolean; + characterWidths: TerminalCharacterWidths; testId?: string; xtermTheme?: ITheme; scrollbackLines: number; diff --git a/packages/app/src/components/terminal-emulator-native-grid.native.tsx b/packages/app/src/components/terminal-emulator-native-grid.native.tsx index d2b92b213a..ad71316f3c 100644 --- a/packages/app/src/components/terminal-emulator-native-grid.native.tsx +++ b/packages/app/src/components/terminal-emulator-native-grid.native.tsx @@ -93,6 +93,7 @@ function NativeTerminalEmulator({ testId = "terminal-surface", xtermTheme = DEFAULT_XTERM_THEME, scrollbackLines, + characterWidths, fontFamily, fontSize, keyboardInset = 0, @@ -373,6 +374,7 @@ function NativeTerminalEmulator({ rows: size.rows, cols: size.cols, scrollbackLines, + characterWidths, }); terminalRef.current = terminal; screenModelRef.current = createNativeTerminalScreenModel({ terminal }); @@ -387,6 +389,7 @@ function NativeTerminalEmulator({ resetInputModeTracker, resolveTerminalScreen, scrollbackLines, + characterWidths, clearSelection, ]); diff --git a/packages/app/src/components/terminal-emulator.tsx b/packages/app/src/components/terminal-emulator.tsx index fa6ac9faba..7504843c54 100644 --- a/packages/app/src/components/terminal-emulator.tsx +++ b/packages/app/src/components/terminal-emulator.tsx @@ -27,6 +27,7 @@ import { } from "../terminal/runtime/terminal-emulator-runtime"; import { encodeTerminalPaste } from "../terminal/runtime/terminal-paste"; import type { TerminalFile } from "../terminal/file-paste"; +import type { TerminalCharacterWidths } from "../terminal/character-widths"; import type { TerminalLocalFileLinkSource, TerminalLocalFileLinkTarget, @@ -96,6 +97,7 @@ interface TerminalEmulatorProps { ref: Ref; streamKey: string; supportsTerminalInputModeReplay: boolean; + characterWidths: TerminalCharacterWidths; testId?: string; xtermTheme?: ITheme; scrollbackLines: number; @@ -154,6 +156,7 @@ export default function TerminalEmulator({ cursor: "#e6e6e6", }, scrollbackLines, + characterWidths, fontFamily, fontSize, swipeGesturesEnabled = false, @@ -183,6 +186,8 @@ export default function TerminalEmulator({ const fontSizeRef = useRef(fontSize); const scrollbackLinesRef = useRef(scrollbackLines); scrollbackLinesRef.current = scrollbackLines; + const characterWidthsRef = useRef(characterWidths); + characterWidthsRef.current = characterWidths; fontFamilyRef.current = fontFamily; fontSizeRef.current = fontSize; const themeKey = useMemo(() => buildXtermThemeKey(xtermTheme), [xtermTheme]); @@ -315,6 +320,10 @@ export default function TerminalEmulator({ runtimeRef.current?.setScrollback({ lines: scrollbackLines }); }, [scrollbackLines]); + useEffect(() => { + runtimeRef.current?.setCharacterWidths({ widths: characterWidths }); + }, [characterWidths]); + useEffect(() => { const root = rootRef.current; if (!root || !swipeGesturesEnabled) { @@ -447,6 +456,7 @@ export default function TerminalEmulator({ }, }); runtime.setPendingModifiers({ pendingModifiers: pendingModifiersRef.current }); + runtime.setCharacterWidths({ widths: characterWidthsRef.current }); runtime.mount({ root, host, diff --git a/packages/app/src/components/terminal-pane.tsx b/packages/app/src/components/terminal-pane.tsx index d60556e0fa..4c5e74ef6d 100644 --- a/packages/app/src/components/terminal-pane.tsx +++ b/packages/app/src/components/terminal-pane.tsx @@ -1,5 +1,6 @@ import { TerminalFind, type TerminalPaneFindHandle } from "@/terminal/find"; import type { TerminalFindResult } from "@/terminal/runtime/terminal-emulator-runtime"; +import type { TerminalCharacterWidths } from "@/terminal/character-widths"; import { LoadingSpinner } from "@/components/ui/loading-spinner"; import { useRetainedPanelActive } from "@/components/retained-panel"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; @@ -304,6 +305,11 @@ export function TerminalPane({ const supportsTerminalSizeOwnership = useSessionStore( (state) => state.sessions[serverId]?.serverInfo?.features?.["terminal-size-ownership"] === true, ); + const characterWidths: TerminalCharacterWidths = useSessionStore((state) => + state.sessions[serverId]?.serverInfo?.features?.["terminal-grapheme-widths"] === true + ? "graphemes" + : "legacy", + ); const setFocusedTerminalId = useSessionStore((state) => state.setFocusedTerminalId); const scopeKey = useMemo(() => terminalScopeKey({ serverId, cwd }), [serverId, cwd]); @@ -1171,6 +1177,7 @@ export function TerminalPane({ dom={TERMINAL_EMULATOR_DOM_PROPS} streamKey={terminalStreamKey} supportsTerminalInputModeReplay={supportsTerminalInputModeReplay} + characterWidths={characterWidths} testId="terminal-surface" xtermTheme={xtermTheme} scrollbackLines={settings.terminalScrollbackLines} diff --git a/packages/app/src/terminal/character-widths.ts b/packages/app/src/terminal/character-widths.ts new file mode 100644 index 0000000000..efb64da6d8 --- /dev/null +++ b/packages/app/src/terminal/character-widths.ts @@ -0,0 +1,9 @@ +/** + * The table a terminal buffer measures characters with. + * + * The daemon answers cursor reports and replays the screen from its own buffer, + * so the app measures with the table the host advertises. `graphemes` gives each + * emoji cluster one two-column cell. `legacy` is what each renderer used before + * hosts advertised grapheme widths. See docs/terminal-rendering.md. + */ +export type TerminalCharacterWidths = "graphemes" | "legacy"; diff --git a/packages/app/src/terminal/native-renderer/headless-terminal-state.test.ts b/packages/app/src/terminal/native-renderer/headless-terminal-state.test.ts index c1025568c9..546982906f 100644 --- a/packages/app/src/terminal/native-renderer/headless-terminal-state.test.ts +++ b/packages/app/src/terminal/native-renderer/headless-terminal-state.test.ts @@ -159,4 +159,52 @@ describe("native headless terminal state", () => { { char: "B", width: 1 }, ]); }); + + // Apple Color Emoji and Noto Color Emoji are two cells wide. The native + // renderer scales a cluster to its column slot, so a one-column emoji + // renders at half size. Each emoji cluster must occupy one wide cell. + test.each([ + ["presentation emoji", "😀"], + ["thumbs up", "👍"], + ["check mark", "✅"], + ["VS16 heart", "❤️"], + ["skin-tone modifier", "👋🏽"], + ["regional-indicator flag", "🇰🇷"], + ["ZWJ family", "👨‍👩‍👧"], + ["ZWJ technologist", "👩‍💻"], + ])("gives a %s cluster one two-column cell", async (_name, cluster) => { + const terminal = createNativeHeadlessTerminal({ rows: 2, cols: 12 }); + + await terminal.write(`A${cluster}B`); + const [row] = terminal.getBufferWindow({ startRow: 0, rowCount: 1 }).rows; + + expect(row.slice(0, 4).map((cell) => ({ char: cell.char, width: cell.width }))).toEqual([ + { char: "A", width: 1 }, + { char: cluster, width: 2 }, + { char: " ", width: 0 }, + { char: "B", width: 1 }, + ]); + expect(terminal.getViewportState().cursor.col).toBe(4); + }); + + // A host without grapheme widths answers cursor reports and replays with + // xterm's default table. The native buffer matches it so the cursor lands + // where the host put it. + test("measures with xterm's default table for hosts without grapheme widths", async () => { + const terminal = createNativeHeadlessTerminal({ + rows: 2, + cols: 12, + characterWidths: "legacy", + }); + + await terminal.write("A😀B"); + const [row] = terminal.getBufferWindow({ startRow: 0, rowCount: 1 }).rows; + + expect(row.slice(0, 3).map((cell) => ({ char: cell.char, width: cell.width }))).toEqual([ + { char: "A", width: 1 }, + { char: "😀", width: 1 }, + { char: "B", width: 1 }, + ]); + expect(terminal.getViewportState().cursor.col).toBe(3); + }); }); diff --git a/packages/app/src/terminal/native-renderer/headless-terminal-state.ts b/packages/app/src/terminal/native-renderer/headless-terminal-state.ts index 5fd87f7315..4347588861 100644 --- a/packages/app/src/terminal/native-renderer/headless-terminal-state.ts +++ b/packages/app/src/terminal/native-renderer/headless-terminal-state.ts @@ -1,3 +1,5 @@ +import { UnicodeGraphemesAddon } from "@xterm/addon-unicode-graphemes"; +import type { TerminalCharacterWidths } from "../character-widths"; import { Terminal as HeadlessTerminal, type IBufferCell, @@ -17,6 +19,8 @@ export interface NativeHeadlessTerminalOptions { rows: number; cols: number; scrollbackLines?: number; + /** Defaults to `graphemes`, the table current daemons use. */ + characterWidths?: TerminalCharacterWidths; } export interface NativeHeadlessTerminal { @@ -297,6 +301,12 @@ export function createNativeHeadlessTerminal( scrollback: options.scrollbackLines ?? 1000, allowProposedApi: true, }); + // Grapheme widths give each emoji cluster one two-column cell, the width the + // native renderer draws it at. Legacy hosts measure with xterm's default + // table, so their cursor reports and replay stay consistent with it. + if ((options.characterWidths ?? "graphemes") === "graphemes") { + terminal.loadAddon(new UnicodeGraphemesAddon()); + } const decoder = new TextDecoder(); let coordinateEpoch = 0; const coordinateStorage = new Map(); diff --git a/packages/app/src/terminal/native-renderer/terminal-frame.test.ts b/packages/app/src/terminal/native-renderer/terminal-frame.test.ts index ea8b7a0cf3..850fd4d183 100644 --- a/packages/app/src/terminal/native-renderer/terminal-frame.test.ts +++ b/packages/app/src/terminal/native-renderer/terminal-frame.test.ts @@ -90,18 +90,16 @@ describe("native terminal frame", () => { test("keeps combining marks and joiners inside the cell xterm assigned them", async () => { const { frame } = await frameFor("éx̸ 각 क्ष 👩‍💻"); - expect(cellLayout(frame.rows[0]).slice(0, 11)).toEqual([ + expect(cellLayout(frame.rows[0]).slice(0, 9)).toEqual([ { text: "é", col: 0, span: 1 }, { text: "x̸", col: 1, span: 1 }, { text: " ", col: 2, span: 1 }, { text: "각", col: 3, span: 2 }, { text: " ", col: 5, span: 1 }, - { text: "क्", col: 6, span: 1 }, - { text: "ष", col: 7, span: 1 }, - { text: " ", col: 8, span: 1 }, - { text: "👩‍", col: 9, span: 1 }, - { text: "💻", col: 10, span: 1 }, - { text: " ", col: 11, span: 1 }, + { text: "क्ष", col: 6, span: 1 }, + { text: " ", col: 7, span: 1 }, + { text: "👩‍💻", col: 8, span: 2 }, + { text: " ", col: 10, span: 1 }, ]); }); @@ -237,7 +235,7 @@ test("builds native frames after replay commits at captured geometry and the lat expect(frame.columns).toBe(50); expect(frame.rows).toHaveLength(10); expect(frame.rows[0].text.trimEnd()).toBe("LIVE-界🙂"); - expect(frame.rows[0].styles.slice(0, 4)).toEqual([8, RED, 0, 0]); + expect(frame.rows[0].styles.slice(0, 4)).toEqual([9, RED, 0, 0]); expect(encodeTerminalFrame(frame).rows[0]).toContain("LIVE-界🙂"); } finally { drain.dispose(); diff --git a/packages/app/src/terminal/runtime/terminal-emulator-runtime.browser.test.ts b/packages/app/src/terminal/runtime/terminal-emulator-runtime.browser.test.ts index 7f54361265..3b58c54376 100644 --- a/packages/app/src/terminal/runtime/terminal-emulator-runtime.browser.test.ts +++ b/packages/app/src/terminal/runtime/terminal-emulator-runtime.browser.test.ts @@ -821,6 +821,67 @@ describe("incremental replay lifecycle", () => { expect(mounted.inputs).toHaveLength(1); expect(mounted.inputs[0]?.startsWith("\x1b]4;1;rgb:")).toBe(true); }); + + it("measures emoji clusters with the daemon's grapheme widths and copies them intact", async () => { + const mounted = createTerminalHost({ width: 720, height: 360 }); + const text = "A😀B❤️C👋🏽D👨‍👩‍👧E"; + await new Promise((resolve) => + mounted.runtime.write({ data: terminalOutput(text), onCommitted: resolve }), + ); + + const terminal = window.__paseoTerminal; + if (!terminal) { + throw new Error("Expected the browser terminal to be mounted"); + } + const line = terminal.buffer.active.getLine(terminal.buffer.active.cursorY); + const cells = Array.from({ length: 13 }, (_, col) => { + const cell = line?.getCell(col); + return { chars: cell?.getChars(), width: cell?.getWidth() }; + }); + + expect(cells).toEqual([ + { chars: "A", width: 1 }, + { chars: "😀", width: 2 }, + { chars: "", width: 0 }, + { chars: "B", width: 1 }, + { chars: "❤️", width: 2 }, + { chars: "", width: 0 }, + { chars: "C", width: 1 }, + { chars: "👋🏽", width: 2 }, + { chars: "", width: 0 }, + { chars: "D", width: 1 }, + { chars: "👨‍👩‍👧", width: 2 }, + { chars: "", width: 0 }, + { chars: "E", width: 1 }, + ]); + expect(terminal.buffer.active.cursorX).toBe(13); + + terminal.select(0, terminal.buffer.active.cursorY, 13); + expect(terminal.getSelection()).toBe(text); + }); + + // A host without grapheme widths answers cursor reports and replays with its + // own table. The web client keeps the Unicode 11 table it used before. + it("measures with the legacy table for hosts without grapheme widths", async () => { + const mounted = createTerminalHost({ width: 720, height: 360 }); + const terminal = window.__paseoTerminal; + if (!terminal) { + throw new Error("Expected the browser terminal to be mounted"); + } + const buffer = terminal.buffer; + async function cursorAfter(text: string): Promise { + await new Promise((resolve) => + mounted.runtime.write({ data: terminalOutput(`\r\n${text}`), onCommitted: resolve }), + ); + return buffer.active.cursorX; + } + + mounted.runtime.setCharacterWidths({ widths: "legacy" }); + expect([await cursorAfter("A😀B"), await cursorAfter("A❤️B")]).toEqual([4, 3]); + + mounted.runtime.setCharacterWidths({ widths: "graphemes" }); + expect([await cursorAfter("A😀B"), await cursorAfter("A❤️B")]).toEqual([4, 4]); + }); }); it("restores fitted web geometry after replay before live output", async () => { diff --git a/packages/app/src/terminal/runtime/terminal-emulator-runtime.test.ts b/packages/app/src/terminal/runtime/terminal-emulator-runtime.test.ts index 8b90839154..7b1568b60e 100644 --- a/packages/app/src/terminal/runtime/terminal-emulator-runtime.test.ts +++ b/packages/app/src/terminal/runtime/terminal-emulator-runtime.test.ts @@ -36,6 +36,12 @@ vi.mock("@xterm/addon-unicode11", () => ({ }, })); +vi.mock("@xterm/addon-unicode-graphemes", () => ({ + UnicodeGraphemesAddon: class UnicodeGraphemesAddon { + dispose(): void {} + }, +})); + vi.mock("@xterm/addon-web-links", () => ({ WebLinksAddon: class WebLinksAddon { dispose(): void {} diff --git a/packages/app/src/terminal/runtime/terminal-emulator-runtime.ts b/packages/app/src/terminal/runtime/terminal-emulator-runtime.ts index 0e1f88dafb..05cf0182d1 100644 --- a/packages/app/src/terminal/runtime/terminal-emulator-runtime.ts +++ b/packages/app/src/terminal/runtime/terminal-emulator-runtime.ts @@ -3,10 +3,12 @@ import { FitAddon } from "@xterm/addon-fit"; import { ImageAddon } from "@xterm/addon-image"; import { SearchAddon } from "@xterm/addon-search"; import { Unicode11Addon } from "@xterm/addon-unicode11"; +import { UnicodeGraphemesAddon } from "@xterm/addon-unicode-graphemes"; import { WebLinksAddon } from "@xterm/addon-web-links"; import { WebglAddon } from "@xterm/addon-webgl"; import { LigaturesAddon } from "@xterm/addon-ligatures/lib/addon-ligatures.mjs"; import { Terminal, type ITheme, type IMarker } from "@xterm/xterm"; +import type { TerminalCharacterWidths } from "../character-widths"; import { type TerminalInputModeState, TerminalInputModeTracker, @@ -232,6 +234,12 @@ function findFileOnlyPaste(transfer: DataTransfer | null): File | null { return null; } +// Grapheme widths match the daemon and native buffers. Legacy hosts keep the +// Unicode 11 table web used before. See docs/terminal-rendering.md. +function applyCharacterWidths(terminal: Terminal, widths: TerminalCharacterWidths): void { + terminal.unicode.activeVersion = widths === "graphemes" ? "15-graphemes" : "11"; +} + export class TerminalEmulatorRuntime { constructor( private readonly options: FindShortcutPlatform = { isMac: isMacUserAgent() }, @@ -244,6 +252,7 @@ export class TerminalEmulatorRuntime { shift: false, alt: false, }; + private characterWidths: TerminalCharacterWidths = "graphemes"; private terminal: Terminal | null = null; private fitAddon: FitAddon | null = null; private searchAddon: SearchAddon | null = null; @@ -331,6 +340,16 @@ export class TerminalEmulatorRuntime { this.pendingModifiers = input.pendingModifiers; } + setCharacterWidths(input: { widths: TerminalCharacterWidths }): void { + this.characterWidths = input.widths; + const terminal = this.terminal; + if (!terminal) { + return; + } + applyCharacterWidths(terminal, input.widths); + this.refreshVisibleRows(); + } + private loadSearchAddon(terminal: Terminal): void { const searchAddon = new SearchAddon({ highlightLimit: FIND_HIGHLIGHT_LIMIT }); terminal.loadAddon(searchAddon); @@ -555,11 +574,12 @@ export class TerminalEmulatorRuntime { theme: withOverviewRulerBorderHidden(input.theme), }); const fitAddon = new FitAddon(); - const unicode11Addon = new Unicode11Addon(); let webglAddon: WebglAddon | null = null; let imageAddon: ImageAddon | null = null; terminal.loadAddon(fitAddon); - terminal.loadAddon(unicode11Addon); + terminal.loadAddon(new Unicode11Addon()); + terminal.loadAddon(new UnicodeGraphemesAddon()); + applyCharacterWidths(terminal, this.characterWidths); terminal.loadAddon(new WebLinksAddon(openExternalLink)); const localFileLinkProvider = terminal.registerLinkProvider( createTerminalLocalFileLinkProvider(terminal, { @@ -594,11 +614,6 @@ export class TerminalEmulatorRuntime { terminal.open(input.host); this.themeBackgroundElements = this.collectThemeBackgroundElements(input); this.applyThemeBackground(input.theme); - try { - terminal.unicode.activeVersion = "11"; - } catch { - // Ignore if unicode API isn't available in this build/runtime. - } const disposeImageAddon = (): void => { try { diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index dc63d56b75..18654bf337 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -3751,6 +3751,8 @@ export const ServerInfoStatusPayloadSchema = z "terminal-input-mode-replay": z.boolean().optional(), // COMPAT(terminalSizeOwnership): added in v0.2.6, remove gate after 2027-02-02. "terminal-size-ownership": z.boolean().optional(), + // COMPAT(terminalGraphemeWidths): added in v0.15.0, remove gate after 2027-05-01. + "terminal-grapheme-widths": z.boolean().optional(), // COMPAT(rewind): added in v0.1.X, drop the gate when floor >= v0.1.X. rewind: z.boolean().optional(), // COMPAT(agentTimelinePromptIndex): added in v0.2.X, drop the gate when floor >= v0.2.X. diff --git a/packages/server/package.json b/packages/server/package.json index 0feadfe9cd..72a21944ef 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -117,7 +117,8 @@ "@opencode-ai/sdk": "1.14.46", "@opencode/client": "2.0.10", "@xterm/addon-serialize": "0.14.0", - "@xterm/headless": "^6.0.0", + "@xterm/addon-unicode-graphemes": "0.5.0-beta.330", + "@xterm/headless": "6.1.0-beta.334", "ai": "5.0.78", "ajv": "^8.20.0", "bcryptjs": "^3.0.3", diff --git a/packages/server/src/server/websocket-server.relay-reconnect.test.ts b/packages/server/src/server/websocket-server.relay-reconnect.test.ts index 2d48a93c87..c99d5ac9cc 100644 --- a/packages/server/src/server/websocket-server.relay-reconnect.test.ts +++ b/packages/server/src/server/websocket-server.relay-reconnect.test.ts @@ -1157,6 +1157,7 @@ describe("relay external socket reconnect behavior", () => { expect(serverInfo.features?.workspaceMarkUnread).toBe(true); expect(serverInfo.features?.["terminal-input-mode-replay"]).toBe(true); expect(serverInfo.features?.["terminal-size-ownership"]).toBe(true); + expect(serverInfo.features?.["terminal-grapheme-widths"]).toBe(true); expect(serverInfo.features?.agentTurnIdentity).toBeUndefined(); expect(serverInfo.permissions).toEqual(DAEMON_PERMISSIONS); await server.close(); diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index 7bfc4d5a0f..7089812d21 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -2077,6 +2077,8 @@ export class VoiceAssistantWebSocketServer { "terminal-input-mode-replay": true, // COMPAT(terminalSizeOwnership): added in v0.2.6, remove gate after 2027-02-02. "terminal-size-ownership": true, + // COMPAT(terminalGraphemeWidths): added in v0.15.0, remove gate after 2027-05-01. + "terminal-grapheme-widths": true, workspaceTerminals: true, // COMPAT(rewind): added in v0.1.X, drop the gate when floor >= v0.1.X. rewind: true, diff --git a/packages/server/src/terminal/headless-terminal.test.ts b/packages/server/src/terminal/headless-terminal.test.ts new file mode 100644 index 0000000000..d971f0d3f5 --- /dev/null +++ b/packages/server/src/terminal/headless-terminal.test.ts @@ -0,0 +1,60 @@ +import { spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { describe, expect, it } from "vitest"; +import { createHeadlessTerminal } from "./headless-terminal.js"; + +const EMOJI_ROW = "A😀👍❤️👋🏽🇰🇷👨‍👩‍👧B"; +// A, six two-column emoji clusters, B. +const EMOJI_ROW_END_COL = 1 + 6 * 2 + 1; + +async function cursorColAfter(text: string): Promise { + const terminal = createHeadlessTerminal({ rows: 2, cols: 40 }); + try { + await new Promise((resolve) => terminal.write(text, resolve)); + return terminal.buffer.active.cursorX; + } finally { + terminal.dispose(); + } +} + +describe("createHeadlessTerminal", () => { + it("gives each emoji cluster one two-column cell", async () => { + expect(await cursorColAfter(EMOJI_ROW)).toBe(EMOJI_ROW_END_COL); + }); + + it("keeps ASCII and CJK widths", async () => { + expect(await cursorColAfter("ABC")).toBe(3); + expect(await cursorColAfter("中文")).toBe(4); + }); + + // The width table is decoded into a Node Buffer when the module loads. A + // Buffer carved out of Node's shared pool starts at a non-zero byteOffset, + // and an addon that reads the table header from offset 0 gets wrong widths + // or fails to load. Whether the pool offset is zero depends on earlier + // allocations, so the test forces a non-zero offset in a fresh process + // before the module loads. Zero bytes in front of the table make the + // misread header deterministic. + it("decodes widths correctly when Node's buffer pool offset is non-zero", () => { + const moduleUrl = new URL("./headless-terminal.ts", import.meta.url).href; + const script = ` + Buffer.poolSize = 8 * 1024 * 1024; + const occupied = Buffer.from(new Uint8Array(3 * 1024 * 1024)); + if (occupied.byteOffset !== 0 || occupied.buffer.byteLength !== Buffer.poolSize) { + throw new Error("expected a fresh shared pool"); + } + const { createHeadlessTerminal } = await import(${JSON.stringify(moduleUrl)}); + const terminal = createHeadlessTerminal({ rows: 2, cols: 40 }); + await new Promise((resolve) => terminal.write(${JSON.stringify(EMOJI_ROW)}, resolve)); + process.stdout.write(String(terminal.buffer.active.cursorX)); + terminal.dispose(); + `; + const result = spawnSync( + process.execPath, + ["--import", "tsx", "--input-type=module", "--eval", script], + { cwd: fileURLToPath(new URL(".", import.meta.url)), encoding: "utf8" }, + ); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toBe(String(EMOJI_ROW_END_COL)); + }); +}); diff --git a/packages/server/src/terminal/headless-terminal.ts b/packages/server/src/terminal/headless-terminal.ts new file mode 100644 index 0000000000..4e106c243b --- /dev/null +++ b/packages/server/src/terminal/headless-terminal.ts @@ -0,0 +1,22 @@ +import { UnicodeGraphemesAddon } from "@xterm/addon-unicode-graphemes"; +import xterm, { type Terminal } from "@xterm/headless"; + +export interface HeadlessTerminalOptions { + rows: number; + cols: number; + scrollback?: number; +} + +/** + * A headless xterm that measures text the way Paseo clients render it. + * + * Grapheme-cluster widths give every emoji cluster (VS16, skin-tone, flags, + * ZWJ sequences) one two-column cell, matching color-emoji fonts. Clients + * replay this buffer's ANSI with the same table, so cells and the cursor line + * up after reconnect. See docs/terminal-rendering.md. + */ +export function createHeadlessTerminal(options: HeadlessTerminalOptions): Terminal { + const terminal = new xterm.Terminal({ ...options, allowProposedApi: true }); + terminal.loadAddon(new UnicodeGraphemesAddon()); + return terminal; +} diff --git a/packages/server/src/terminal/terminal.test.ts b/packages/server/src/terminal/terminal.test.ts index 69e6468673..e4f8544050 100644 --- a/packages/server/src/terminal/terminal.test.ts +++ b/packages/server/src/terminal/terminal.test.ts @@ -563,6 +563,71 @@ describe("createTerminal", () => { expect(state.grid[0][1].char).toBe(""); }); + it("reports the cursor column after an emoji cluster in DSR replies", async () => { + // Programs that measure the cursor (prompts, TUIs) must see the same + // column the client renders: an emoji occupies two cells. + const program = ` + process.stdin.setRawMode(true); + process.stdin.once("data", (reply) => { + process.stdout.write("\\r\\nREPLY " + JSON.stringify(reply.toString()).slice(2, -1)); + }); + process.stdout.write("A😀\\x1b[6n"); + setInterval(() => {}, 100000); + `; + const session = trackSession( + await createTerminal({ + workspaceId: "ws-test", + cwd: realpathSync(tmpdir()), + cols: 40, + rows: 5, + command: process.execPath, + args: ["-e", program], + }), + ); + + const state = await waitForState(session, (current) => + getRowText(current, 1).startsWith("REPLY"), + ); + + expect(getRowText(state, 1)).toBe("REPLY u001b[1;4R"); + }); + + it("replays emoji clusters at their columns with the cursor after them", async () => { + const text = "A😀B❤️C👋🏽D👨‍👩‍👧E"; + const session = trackSession( + await createTerminal({ + workspaceId: "ws-test", + cwd: realpathSync(tmpdir()), + cols: 40, + rows: 5, + command: process.execPath, + args: [ + "-e", + `process.stdout.write(${JSON.stringify(text)}); setInterval(() => {}, 100000);`, + ], + }), + ); + + const state = await waitForState(session, (current) => rowHasChar(current.grid[0], "E")); + + expect(state.grid[0].slice(0, 13).map((cell) => cell.char)).toEqual([ + "A", + "😀", + "", + "B", + "❤️", + "", + "C", + "👋🏽", + "", + "D", + "👨‍👩‍👧", + "", + "E", + ]); + expect(state.cursor).toEqual({ row: 0, col: 13 }); + }); + it("captures exit diagnostics from the terminal buffer", async () => { const session = trackSession( await createTerminal({ diff --git a/packages/server/src/terminal/terminal.ts b/packages/server/src/terminal/terminal.ts index 3294c11b93..b09bc8bbf6 100644 --- a/packages/server/src/terminal/terminal.ts +++ b/packages/server/src/terminal/terminal.ts @@ -1,5 +1,5 @@ import * as pty from "node-pty"; -import xterm, { type Terminal as TerminalType } from "@xterm/headless"; +import type { Terminal as TerminalType } from "@xterm/headless"; import { randomUUID } from "crypto"; import { accessSync, @@ -25,6 +25,7 @@ import { findExecutable, findExecutableWithoutProbing, } from "../executable-resolution/executable-resolution.js"; +import { createHeadlessTerminal } from "./headless-terminal.js"; import { createTerminalSerializer } from "./terminal-serializer.js"; import { captureTerminalLines, @@ -36,7 +37,6 @@ import { TerminalInputModeTracker } from "@getpaseo/protocol/terminal-input-mode import { TerminalActivityTracker } from "./activity/terminal-activity-tracker.js"; import type { TerminalActivity, TerminalActivityState } from "@getpaseo/protocol/terminal-activity"; -const { Terminal } = xterm; const require = createRequire(import.meta.url); let nodePtySpawnHelperChecked = false; const TERMINAL_TITLE_DEBOUNCE_MS = 150; @@ -796,13 +796,7 @@ export async function createTerminal( const activityChangeListeners = new Set<(transition: TerminalActivityTransition) => void>(); let titleChangeSubscription: { dispose(): void } | null = null; - // Create xterm.js headless terminal - const terminal = new Terminal({ - rows, - cols, - scrollback: 10000, - allowProposedApi: true, - }); + const terminal = createHeadlessTerminal({ rows, cols, scrollback: 10000 }); const serialize = createTerminalSerializer(terminal); diff --git a/packages/server/src/terminal/test-utils/terminal-state.ts b/packages/server/src/terminal/test-utils/terminal-state.ts index 0fd4777b4c..fb5f5d610a 100644 --- a/packages/server/src/terminal/test-utils/terminal-state.ts +++ b/packages/server/src/terminal/test-utils/terminal-state.ts @@ -1,15 +1,14 @@ -import xterm from "@xterm/headless"; import type { TerminalState } from "@getpaseo/protocol/messages"; +import { createHeadlessTerminal } from "../headless-terminal.js"; import type { LocalTerminalSession } from "../terminal.js"; /** Observe the public ANSI replay using a real receiver; no production cell extraction API. */ export async function readTerminalState(session: LocalTerminalSession): Promise { const { metadata, data } = session.serializeReplay(); - const terminal = new xterm.Terminal({ + const terminal = createHeadlessTerminal({ rows: metadata.rows, cols: metadata.cols, scrollback: 10000, - allowProposedApi: true, }); try { await new Promise((resolve) => terminal.write(data, resolve)); diff --git a/packages/server/src/terminal/worker-terminal-manager.test.ts b/packages/server/src/terminal/worker-terminal-manager.test.ts index 2605e62965..b0ef983a8e 100644 --- a/packages/server/src/terminal/worker-terminal-manager.test.ts +++ b/packages/server/src/terminal/worker-terminal-manager.test.ts @@ -1863,7 +1863,8 @@ it("completes a replay larger than the socket budget while a sibling stays usabl ...nodeTerminalCommand(` const row = Array.from({length: 1000}, (_, i) => "\\x1b[" + (31 + i % 2) + "mX").join(""); for (let i = 0; i < 900; i++) process.stdout.write(row + "\\r\\n"); - process.stdout.write("READY-WIDE\\r\\n"); + // Seeing the marker must mean no trailing newline can still add history. + process.stdout.write("READY-WIDE"); process.stdin.on("data", data => { if (data.toString().includes("small")) { process.stdout.write("SAME-TERMINAL-LIVE\\r\\n"); return; } process.stdout.write("q".repeat(8 * 1024 * 1024) + "\\r\\nRECOVERED-LIVE\\r\\n", () => require("node:fs").writeFileSync(${JSON.stringify(overflowProgress)}, "done")); }); setInterval(() => {}, 1000); `), From 82d5f6c580fccf500ed718aa8dad1be03639df7a Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sun, 1 Nov 2026 10:34:06 +0700 Subject: [PATCH 161/173] fix(app): keep layout sized to the window after rotation (#8377) A style update racing a window resize could recommit old root constraints. Rebuild the style update from the current root on each commit attempt. --- patches/react-native-unistyles+3.2.4.patch | 56 ++++++++++++++++++++++ scripts/postinstall-patches.mjs | 3 ++ 2 files changed, 59 insertions(+) diff --git a/patches/react-native-unistyles+3.2.4.patch b/patches/react-native-unistyles+3.2.4.patch index af825a6afa..c3da63a8ac 100644 --- a/patches/react-native-unistyles+3.2.4.patch +++ b/patches/react-native-unistyles+3.2.4.patch @@ -705,3 +705,59 @@ index a9c1804..f5a3c20 100644 return Insets( this._insets.top / density, +diff --git a/node_modules/react-native-unistyles/cxx/shadowTree/ShadowTreeManager.cpp b/node_modules/react-native-unistyles/cxx/shadowTree/ShadowTreeManager.cpp +index 01026dc..3786ec4 100644 +--- a/node_modules/react-native-unistyles/cxx/shadowTree/ShadowTreeManager.cpp ++++ b/node_modules/react-native-unistyles/cxx/shadowTree/ShadowTreeManager.cpp +@@ -17,13 +17,16 @@ void shadow::ShadowTreeManager::updateShadowTree(jsi::Runtime& rt) { + } + + #if REACT_NATIVE_VERSION_MINOR >= 81 +- std::unordered_map tagToProps; ++ // Paseo backport of https://github.com/jpudysz/react-native-unistyles/pull/1357. ++ // UIManager::updateShadowTree commits a root cloned before the commit, so when a ++ // window-size commit (rotation, keyboard) lands in between, the retried Unistyles ++ // commit puts the previous layout constraints back and the app stays laid out for ++ // the old size. Commit here instead and clone from the root the commit hands us. ++ std::unordered_set affectedSurfaces; + + for (const auto& [family, props] : updates) { + auto safeProps = props.isObject() ? props : folly::dynamic::object(); + +- tagToProps.insert({family->getTag(), safeProps}); +- + auto* mutableFamily = const_cast(family); + + if (mutableFamily->nativeProps_DEPRECATED && mutableFamily->nativeProps_DEPRECATED->isObject()) { +@@ -31,9 +34,30 @@ void shadow::ShadowTreeManager::updateShadowTree(jsi::Runtime& rt) { + } else { + mutableFamily->nativeProps_DEPRECATED = std::make_unique(safeProps); + } ++ ++ affectedSurfaces.insert(family->getSurfaceId()); + } + +- UIManagerBinding::getBinding(rt)->getUIManager().updateShadowTree(std::move(tagToProps)); ++ const auto& shadowTreeRegistry = UIManagerBinding::getBinding(rt)->getUIManager().getShadowTreeRegistry(); ++ ++ shadowTreeRegistry.enumerate([&updates, &affectedSurfaces](const ShadowTree& shadowTree, bool&){ ++ if (!affectedSurfaces.contains(shadowTree.getSurfaceId())) { ++ return; ++ } ++ ++ auto transaction = [&updates](const RootShadowNode& oldRootShadowNode) -> RootShadowNode::Unshared { ++ auto affectedNodes = shadow::ShadowTreeManager::findAffectedNodes(oldRootShadowNode, updates); ++ ++ return std::static_pointer_cast(shadow::ShadowTreeManager::cloneShadowTree( ++ oldRootShadowNode, ++ updates, ++ affectedNodes ++ )); ++ }; ++ ++ // mountSynchronously: this is an update from C++, not React ++ shadowTree.commit(transaction, {false, true}); ++ }); + #else + const auto& shadowTreeRegistry = UIManagerBinding::getBinding(rt)->getUIManager().getShadowTreeRegistry(); + diff --git a/scripts/postinstall-patches.mjs b/scripts/postinstall-patches.mjs index fbf87241c7..3dbbeddcaf 100644 --- a/scripts/postinstall-patches.mjs +++ b/scripts/postinstall-patches.mjs @@ -28,6 +28,9 @@ const patchedPackages = [ // withUnistyles: also keep the uniProps filter until upstream consumes its control prop. // Android configuration: backport 3.5.3; remove the two NativePlatform hunks at >= 3.5.3. // https://github.com/jpudysz/react-native-unistyles/compare/v3.5.2...v3.5.3 + // Layout constraints: backport of https://github.com/jpudysz/react-native-unistyles/pull/1357 + // (commit from the root the commit hands us, so a concurrent window-size commit is kept). + // Remove the ShadowTreeManager hunk when the installed release includes that PR. { nodeModulesPath: "node_modules/react-native-unistyles", patchPrefix: "react-native-unistyles+", From b2666a0aec4a309aa550dd3f344a997eed831cb2 Mon Sep 17 00:00:00 2001 From: "paseo-ai[bot]" <266920839+paseo-ai[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 03:43:24 +0000 Subject: [PATCH 162/173] fix: update lockfile signatures and Nix hash [skip ci] --- nix/npm-deps.hash | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nix/npm-deps.hash b/nix/npm-deps.hash index c7a63567f9..530da9108f 100644 --- a/nix/npm-deps.hash +++ b/nix/npm-deps.hash @@ -1 +1 @@ -sha256-zFjdXeRpqrjEZk44ZCvEOTnVVGX0ASfDPktYNiWZpsw= +sha256-WPPLqWQzoUdjZNbZW6XWpy+A6XHXDyc0QW0FH6ubgMw= From 8efb21f55ca55ac8df24ec69ac49651732ea40f7 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 03:55:48 +0000 Subject: [PATCH 163/173] fix(server): close abandoned workspace service connections (#8421) * fix(server): close the upstream connection when a proxied client leaves The service proxy piped the service's response to the client but never destroyed the upstream request when the client went away. The upstream socket stayed open and unread, so a Server-Sent Events service kept writing into it and grew in memory. The proxy now destroys the upstream request when the client response closes before it finished, without logging that deliberate abort as an unreachable upstream, and a WebSocket upgrade closes the service socket when the client socket closes. Fixes #8149 * test(server): publish terminal activity fixture atomically File existence did not mean the child had finished writing its JSON. Publish the completed fixture by rename so a concurrent reader cannot parse an empty file. Co-authored-by: Dominic Anaeto * test(server): keep rollback listener ports distinct Selecting both free ports before binding either lets the OS return the same port twice. Hold the intentionally occupied main port before selecting the standalone port so the rollback probe cannot reach the wrong server. --------- Co-authored-by: Dominic Anaeto Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../server/src/server/bootstrap.smoke.test.ts | 2 +- .../server/src/server/service-proxy.test.ts | 277 ++++++++++++++++-- packages/server/src/server/service-proxy.ts | 10 + .../server/terminal-activity-route.test.ts | 8 +- 4 files changed, 264 insertions(+), 33 deletions(-) diff --git a/packages/server/src/server/bootstrap.smoke.test.ts b/packages/server/src/server/bootstrap.smoke.test.ts index 76fa8cc7d1..ac045741f1 100644 --- a/packages/server/src/server/bootstrap.smoke.test.ts +++ b/packages/server/src/server/bootstrap.smoke.test.ts @@ -670,11 +670,11 @@ describe("paseo daemon bootstrap", () => { test("rolls back standalone listener without starting plugins when main listen fails", async () => { const mainPort = await findFreePort(); - const standalonePort = await findFreePort(); const occupiedMain = http.createServer((_req, res) => { res.end("occupied-main"); }); await new Promise((resolve) => occupiedMain.listen(mainPort, "127.0.0.1", resolve)); + const standalonePort = await findFreePort(); const paseoHomeRoot = await mkdtemp(path.join(os.tmpdir(), "paseo-main-rollback-")); const paseoHome = path.join(paseoHomeRoot, ".paseo"); diff --git a/packages/server/src/server/service-proxy.test.ts b/packages/server/src/server/service-proxy.test.ts index 5764b19539..eb679d5629 100644 --- a/packages/server/src/server/service-proxy.test.ts +++ b/packages/server/src/server/service-proxy.test.ts @@ -1,7 +1,9 @@ +import { type EventEmitter, once } from "node:events"; import { readdirSync, readFileSync, statSync } from "node:fs"; import path from "node:path"; import http from "node:http"; import net from "node:net"; +import type { Duplex } from "node:stream"; import express from "express"; import { describe, expect, it } from "vitest"; import pino from "pino"; @@ -332,48 +334,39 @@ describe("service proxy subsystem shape", () => { }); }); -interface ForwardedFixture { +interface ProxiedServiceFixture { upstreamPort: number; daemonPort: number; + daemon: http.Server; hostname: string; close(): Promise; } /** - * Runs a real workspace service behind a real daemon listener. The upstream - * echoes the headers it received so tests can assert what actually crossed the - * proxy, not what a helper returned. + * Runs a real workspace service behind a real daemon listener that serves the + * service proxy for both HTTP and upgrades. */ -async function startForwardedHeadersFixture(upstreamHost = "127.0.0.1"): Promise { - const upstream = http.createServer((req, res) => { - let body = ""; - req.on("data", (chunk: Buffer) => { - body += chunk.toString(); +async function startProxiedService( + upstream: http.Server, + options: { upstreamHost?: string; logger?: pino.Logger } = {}, +): Promise { + const { upstreamHost = "127.0.0.1", logger: proxyLogger = logger } = options; + // Upgraded sockets keep the server alive; close() alone would hang. + const sockets = new Set(); + function trackConnections(server: http.Server) { + server.on("connection", (socket: net.Socket) => { + sockets.add(socket); + socket.once("close", () => sockets.delete(socket)); }); - req.on("end", () => { - res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify({ ...req.headers, method: req.method, url: req.url, body })); - }); - }); - const upgradeSockets: net.Socket[] = []; - upstream.on("upgrade", (req, socket) => { - upgradeSockets.push(socket); - // The client resets this connection once it has the echo, so the reset - // reaches us as an 'error'. A raw upgrade socket has no default handler — - // without this the event goes unhandled and takes down the test process. - socket.on("error", () => socket.destroy()); - const payload = JSON.stringify(req.headers); - socket.write( - `HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nX-Echo-Length: ${payload.length}\r\n\r\n${payload}`, - ); - }); + } + trackConnections(upstream); await new Promise((resolve, reject) => { upstream.once("error", reject); upstream.listen(0, upstreamHost, resolve); }); const upstreamPort = (upstream.address() as net.AddressInfo).port; - const serviceProxy = createServiceProxySubsystem({ logger }); + const serviceProxy = createServiceProxySubsystem({ logger: proxyLogger }); const route = serviceProxy.registerWorkspaceService({ workspaceId: "workspace-a", projectSlug: "repo", @@ -390,24 +383,51 @@ async function startForwardedHeadersFixture(upstreamHost = "127.0.0.1"): Promise res.status(404).send("404 Not Found"); }); const daemon = http.createServer(app); + trackConnections(daemon); daemon.on("upgrade", serviceProxy.upgradeHandler({ passthroughUnknown: false })); await new Promise((resolve) => daemon.listen(daemonPort, "127.0.0.1", resolve)); return { upstreamPort, daemonPort, + daemon, hostname: route.hostname, async close() { - // Upgraded sockets keep the server alive; close() alone would hang. - for (const socket of upgradeSockets) socket.destroy(); - daemon.closeAllConnections(); + for (const socket of sockets) socket.destroy(); await new Promise((resolve) => daemon.close(() => resolve())); - upstream.closeAllConnections(); await new Promise((resolve) => upstream.close(() => resolve())); }, }; } +/** + * The upstream echoes the headers it received so tests can assert what + * actually crossed the proxy, not what a helper returned. + */ +function startForwardedHeadersFixture(upstreamHost = "127.0.0.1"): Promise { + const upstream = http.createServer((req, res) => { + let body = ""; + req.on("data", (chunk: Buffer) => { + body += chunk.toString(); + }); + req.on("end", () => { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ ...req.headers, method: req.method, url: req.url, body })); + }); + }); + upstream.on("upgrade", (req, socket) => { + // The client resets this connection once it has the echo, so the reset + // reaches us as an 'error'. A raw upgrade socket has no default handler — + // without this the event goes unhandled and takes down the test process. + socket.on("error", () => socket.destroy()); + const payload = JSON.stringify(req.headers); + socket.write( + `HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nX-Echo-Length: ${payload.length}\r\n\r\n${payload}`, + ); + }); + return startProxiedService(upstream, { upstreamHost }); +} + function upgradeThroughProxy( port: number, host: string, @@ -651,3 +671,198 @@ describe("service proxy forwarded headers", () => { } }); }); + +function closed(emitter: EventEmitter): Promise { + return new Promise((resolve) => { + emitter.once("close", () => resolve()); + }); +} + +async function within(promise: Promise, ms: number, failure: string): Promise { + let timer: NodeJS.Timeout | undefined; + const timeout = new Promise((_resolve, reject) => { + timer = setTimeout(() => reject(new Error(`${failure} after ${ms}ms`)), ms); + }); + try { + return await Promise.race([promise, timeout]); + } finally { + clearTimeout(timer); + } +} + +function requestThroughProxy( + fixture: ProxiedServiceFixture, + requestPath: string, +): http.ClientRequest { + return http.get({ + hostname: "127.0.0.1", + port: fixture.daemonPort, + path: requestPath, + headers: { host: fixture.hostname }, + }); +} + +const STRAY_WARNING_GRACE_MS = 100; + +function createUpgradeUpstream(onUpgrade: (socket: Duplex) => void): http.Server { + const upstream = http.createServer(); + upstream.on("upgrade", (_req, socket) => { + socket.on("error", () => socket.destroy()); + socket.on("end", () => socket.end()); + socket.write( + "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n", + ); + onUpgrade(socket); + }); + return upstream; +} + +function openUpgradeThroughProxy(fixture: ProxiedServiceFixture): Promise { + return new Promise((resolve, reject) => { + const socket = net.connect({ host: "127.0.0.1", port: fixture.daemonPort }, () => { + const lines = [ + "GET /ws HTTP/1.1", + `Host: ${fixture.hostname}`, + "Upgrade: websocket", + "Connection: Upgrade", + "", + "", + ]; + socket.write(lines.join("\r\n")); + }); + let raw = ""; + socket.on("data", (chunk: Buffer) => { + raw += chunk.toString(); + if (raw.includes("\r\n\r\n")) resolve(socket); + }); + socket.on("close", () => reject(new Error("upgrade closed before the 101 arrived"))); + socket.on("error", reject); + }); +} + +describe("service proxy connection teardown", () => { + it("closes the upstream connection when a client leaves an event stream", async () => { + const upstreamResponse = Promise.withResolvers(); + const upstream = http.createServer((_req, res) => { + res.writeHead(200, { "content-type": "text/event-stream" }); + res.write("data: open\n\n"); + upstreamResponse.resolve(res); + }); + const fixture = await startProxiedService(upstream); + try { + const request = requestThroughProxy(fixture, "/events"); + const [response] = (await once(request, "response")) as [http.IncomingMessage]; + await once(response, "data"); + const upstreamClosed = closed(await upstreamResponse.promise); + + request.destroy(); + + await within(upstreamClosed, 1000, "the service still holds the event stream"); + } finally { + await fixture.close(); + } + }, 5000); + + it("aborts the upstream request when a client leaves before the response starts", async () => { + const warnings: unknown[] = []; + const proxyLogger = pino( + { level: "warn" }, + { write: (line: string) => warnings.push(JSON.parse(line)) }, + ); + const upstreamResponse = Promise.withResolvers(); + const upstream = http.createServer((_req, res) => { + upstreamResponse.resolve(res); + }); + const fixture = await startProxiedService(upstream, { logger: proxyLogger }); + try { + const request = requestThroughProxy(fixture, "/slow"); + request.on("error", () => undefined); + const upstreamClosed = closed(await upstreamResponse.promise); + + request.destroy(); + + await within(upstreamClosed, 1000, "the service still holds the abandoned request"); + await new Promise((resolve) => setTimeout(resolve, STRAY_WARNING_GRACE_MS)); + expect(warnings).toEqual([]); + } finally { + await fixture.close(); + } + }, 5000); + + it("lets a complete response finish without resetting the service", async () => { + const upstreamResponse = Promise.withResolvers(); + const upstream = http.createServer((_req, res) => { + res.writeHead(200, { "content-type": "text/plain" }); + res.write("first;"); + upstreamResponse.resolve(res); + }); + const fixture = await startProxiedService(upstream); + try { + const response = httpGet(fixture.daemonPort, fixture.hostname, { path: "/" }); + const res = await upstreamResponse.promise; + const upstreamClosed = closed(res); + + res.end("second"); + + await expect(response).resolves.toEqual({ status: 200, body: "first;second" }); + await within(upstreamClosed, 1000, "the service response never closed"); + expect(res.writableFinished).toBe(true); + } finally { + await fixture.close(); + } + }, 5000); + + it("closes the upstream WebSocket when the daemon drops the client socket", async () => { + const upstreamSocket = Promise.withResolvers(); + const fixture = await startProxiedService( + createUpgradeUpstream((socket) => upstreamSocket.resolve(socket)), + ); + const daemonSide = Promise.withResolvers(); + fixture.daemon.on("upgrade", (_req, socket) => daemonSide.resolve(socket)); + try { + const client = await openUpgradeThroughProxy(fixture); + const upstreamClosed = closed(await upstreamSocket.promise); + + (await daemonSide.promise).destroy(); + + await within(upstreamClosed, 1000, "the service still holds the WebSocket"); + client.destroy(); + } finally { + await fixture.close(); + } + }, 5000); + + it("closes the upstream WebSocket when the client disconnects", async () => { + const upstreamSocket = Promise.withResolvers(); + const fixture = await startProxiedService( + createUpgradeUpstream((socket) => upstreamSocket.resolve(socket)), + ); + try { + const client = await openUpgradeThroughProxy(fixture); + const upstreamClosed = closed(await upstreamSocket.promise); + + client.destroy(); + + await within(upstreamClosed, 1000, "the service still holds the WebSocket"); + } finally { + await fixture.close(); + } + }, 5000); + + it("closes the client WebSocket when the service closes it", async () => { + const upstreamSocket = Promise.withResolvers(); + const fixture = await startProxiedService( + createUpgradeUpstream((socket) => upstreamSocket.resolve(socket)), + ); + try { + const client = await openUpgradeThroughProxy(fixture); + const clientClosed = closed(client); + + (await upstreamSocket.promise).destroy(); + + await within(clientClosed, 1000, "the client WebSocket is still open"); + } finally { + await fixture.close(); + } + }, 5000); +}); diff --git a/packages/server/src/server/service-proxy.ts b/packages/server/src/server/service-proxy.ts index ef93a27f9a..24bfd80c93 100644 --- a/packages/server/src/server/service-proxy.ts +++ b/packages/server/src/server/service-proxy.ts @@ -342,7 +342,14 @@ function proxyHttpRequest({ proxyRes.pipe(res, { end: true }); }, ); + let clientClosed = false; + res.on("close", () => { + if (res.writableFinished) return; + clientClosed = true; + proxyReq.destroy(); + }); proxyReq.on("error", (err) => { + if (clientClosed) return; logger.warn( { err, hostname: route.hostname, port: route.port }, "Service proxy: upstream unreachable", @@ -399,6 +406,9 @@ function proxyUpgradeRequest({ socket.on("error", () => { targetSocket.destroy(); }); + socket.on("close", () => { + targetSocket.destroy(); + }); } function sameRouteOwner(left: ServiceProxyRouteEntry, right: ServiceProxyRouteEntry): boolean { diff --git a/packages/server/src/server/terminal-activity-route.test.ts b/packages/server/src/server/terminal-activity-route.test.ts index afc97d77e8..e047c56ab9 100644 --- a/packages/server/src/server/terminal-activity-route.test.ts +++ b/packages/server/src/server/terminal-activity-route.test.ts @@ -95,7 +95,13 @@ it("accepts terminalId and token reports through the route into the tracker", as command: process.execPath, args: [ "-e", - `require("node:fs").writeFileSync(${JSON.stringify(envPath)}, JSON.stringify({ terminalId: process.env.PASEO_TERMINAL_ID, token: process.env.PASEO_ACTIVITY_TOKEN, url: process.env.PASEO_TERMINAL_ACTIVITY_URL })); setInterval(() => {}, 1000);`, + ` + const fs = require("node:fs"); + const envPath = ${JSON.stringify(envPath)}; + fs.writeFileSync(envPath + ".tmp", JSON.stringify({ terminalId: process.env.PASEO_TERMINAL_ID, token: process.env.PASEO_ACTIVITY_TOKEN, url: process.env.PASEO_TERMINAL_ACTIVITY_URL })); + fs.renameSync(envPath + ".tmp", envPath); + setInterval(() => {}, 1000); + `, ], }); await waitForCondition(() => existsSync(envPath), 10000); From 60f29a435073ef50fe3bfacacbb1bdb9c2ee1c02 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sun, 1 Nov 2026 06:31:01 +0100 Subject: [PATCH 164/173] docs(worktrees): add nested worktreeinclude reference --- packages/website/src/docs.ts | 8 ++- .../src/plugin-docs-navigation.test.ts | 19 ++++++ .../{worktrees.md => worktrees/index.md} | 11 +--- .../index.zh-CN.md} | 11 +--- public-docs/worktrees/worktreeinclude.md | 61 +++++++++++++++++++ .../worktrees/worktreeinclude.zh-CN.md | 61 +++++++++++++++++++ 6 files changed, 150 insertions(+), 21 deletions(-) rename public-docs/{worktrees.md => worktrees/index.md} (91%) rename public-docs/{worktrees.zh-CN.md => worktrees/index.zh-CN.md} (92%) create mode 100644 public-docs/worktrees/worktreeinclude.md create mode 100644 public-docs/worktrees/worktreeinclude.zh-CN.md diff --git a/packages/website/src/docs.ts b/packages/website/src/docs.ts index 1325cd933f..896d86daf9 100644 --- a/packages/website/src/docs.ts +++ b/packages/website/src/docs.ts @@ -186,7 +186,13 @@ function insertDocByPath(nodes: DocsNavNode[], doc: Doc, stripTopDirectory = fal // A section's top-level directory and its category name the same thing, so // only directories below it become collapsible groups. - if (stripTopDirectory) directories.shift(); + if ( + stripTopDirectory && + directories[0] && + doc.frontmatter.category?.toLowerCase().endsWith(directories[0].toLowerCase()) + ) { + directories.shift(); + } let current = nodes; let parent: Extract | undefined; diff --git a/packages/website/src/plugin-docs-navigation.test.ts b/packages/website/src/plugin-docs-navigation.test.ts index 93f0cf7736..a3e537620a 100644 --- a/packages/website/src/plugin-docs-navigation.test.ts +++ b/packages/website/src/plugin-docs-navigation.test.ts @@ -2,6 +2,25 @@ import { describe, expect, it } from "vitest"; import { buildDocsNavTree, getDoc, getDocs, getLegacyDocsRedirect, parseHeadings } from "./docs"; describe("plugin documentation", () => { + it.each(["en", "zh-CN"] as const)( + "nests local file copying under Git worktrees in %s", + (locale) => { + const workspaces = buildDocsNavTree(getDocs(locale)).find( + (node) => node.type === "category" && node.label === "Workspaces", + ); + expect(workspaces).toMatchObject({ + children: expect.arrayContaining([ + expect.objectContaining({ + type: "group", + href: "/docs/worktrees", + children: [expect.objectContaining({ href: "/docs/worktrees/worktreeinclude" })], + }), + ]), + }); + expect(getDoc("worktrees/worktreeinclude", locale)).toBeDefined(); + }, + ); + it("groups current guides by task without version navigation", () => { const plugins = buildDocsNavTree(getDocs("en")).find( (node) => node.type === "category" && node.label === "Plugins", diff --git a/public-docs/worktrees.md b/public-docs/worktrees/index.md similarity index 91% rename from public-docs/worktrees.md rename to public-docs/worktrees/index.md index baaea2e177..faabb2d81f 100644 --- a/public-docs/worktrees.md +++ b/public-docs/worktrees/index.md @@ -84,16 +84,7 @@ Add `--forge ` when Paseo cannot infer the forge from the source checkout. ## Copy local files with .worktreeinclude -Create `.worktreeinclude` at the root of your source checkout to copy selected gitignored files into new worktrees: - -```gitignore -.env -config/*.local.json -``` - -Patterns use gitignore syntax. A file must match `.worktreeinclude` and be gitignored to be copied. Tracked files are never copied, and existing destination files are never overwritten. Without `.worktreeinclude`, no local files are copied. Symlinked directories and nested repositories inside an included path cause the copy to fail and abort worktree creation. - -The built-in `worktree-include` plugin copies from the checkout you create the worktree from, including when that checkout is another worktree. Copying finishes before setup, terminals, and the first agent. A copy failure aborts creation and removes the new worktree. Copies use copy-on-write clones on APFS and btrfs when supported, with a regular copy elsewhere. +Use [`.worktreeinclude`](/docs/worktrees/worktreeinclude) to copy selected gitignored files, such as `.env`, from your source checkout before setup runs. ## paseo.json diff --git a/public-docs/worktrees.zh-CN.md b/public-docs/worktrees/index.zh-CN.md similarity index 92% rename from public-docs/worktrees.zh-CN.md rename to public-docs/worktrees/index.zh-CN.md index e84d0a8a25..cce65fc090 100644 --- a/public-docs/worktrees.zh-CN.md +++ b/public-docs/worktrees/index.zh-CN.md @@ -82,16 +82,7 @@ paseo workspace create \ ## 使用 .worktreeinclude 复制本地文件 {#copy-local-files-with-worktreeinclude} -在源检出的根目录创建 `.worktreeinclude`,将选定的 Git 忽略文件复制到新的 worktree: - -```gitignore -.env -config/*.local.json -``` - -模式使用 gitignore 语法。只有同时匹配 `.worktreeinclude` 且被 Git 忽略的文件才会复制。已跟踪的文件不会被复制,目标中已存在的文件不会被覆盖。没有 `.worktreeinclude` 时,不会复制任何本地文件。包含路径中的符号链接目录和嵌套仓库会导致复制失败,并中止 worktree 创建。 - -内置的 `worktree-include` 插件从你创建 worktree 时所选的检出复制文件,即使源检出本身也是 worktree。复制会在 setup、终端和第一个 Agent 运行之前完成。复制失败会中止创建并删除新的 worktree。支持时会在 APFS 和 btrfs 上使用写时复制克隆,否则执行普通复制。 +使用 [`.worktreeinclude`](/docs/worktrees/worktreeinclude),在 setup 运行前将 `.env` 等选定的 Git 忽略文件从源检出复制到新 worktree。 ## paseo.json {#paseojson} diff --git a/public-docs/worktrees/worktreeinclude.md b/public-docs/worktrees/worktreeinclude.md new file mode 100644 index 0000000000..50c5f0370a --- /dev/null +++ b/public-docs/worktrees/worktreeinclude.md @@ -0,0 +1,61 @@ +--- +title: .worktreeinclude +description: Copy gitignored local files into new Paseo worktrees. +nav: .worktreeinclude +order: 12 +category: Workspaces +--- + +# .worktreeinclude + +Add `.worktreeinclude` at the root of your source checkout to copy local configuration into new [Git worktrees](/docs/worktrees). Paseo copies matching gitignored files before setup, terminals, and the first Agent start. + +## Copy your local configuration + +For a project whose `.gitignore` includes `.env` and `config/*.local.json`, create this `.worktreeinclude`: + +```gitignore +.env +config/*.local.json +``` + +When you create a worktree through Paseo, an existing `.env` and matching files such as `config/dev.local.json` are copied to the same relative paths in the new worktree. Their contents stay out of Git. + +Commit `.worktreeinclude` to share the patterns with your team. Each teammate supplies their own ignored files in the checkout they create worktrees from. + +## Pattern syntax + +Use gitignore syntax, with one pattern per line. Comments start with `#`. Prefix a pattern with `!` to exclude a match: + +```gitignore +# Local environment and configuration +.env +config/*.local.json +!config/production.local.json +``` + +A pattern only selects files that Git already ignores. Adding a path here does not ignore it, so also configure `.gitignore` when needed. Tracked files and untracked files that Git does not ignore are excluded. + +## When files are copied + +The built-in `worktree-include` plugin reads the file from the checkout you create the worktree from. That source can itself be another worktree. Keep the plugin enabled for copying to run. + +- Without `.worktreeinclude`, the plugin copies nothing. +- Matching files must exist in the source checkout. +- Existing destination files are skipped, preserving their contents. +- Copies happen during creation, with no ongoing synchronization between checkouts. +- A copy error aborts creation and removes the new worktree. Avoid including symlinked directories or nested repositories, which cannot be copied as files. + +## Run commands during setup + +Use `.worktreeinclude` for files that already exist locally. Use a [setup hook](/docs/worktrees#setup-and-teardown) to install dependencies, generate files, or fetch secrets: + +```json +{ + "worktree": { + "setup": "npm ci" + } +} +``` + +Put this configuration in `paseo.json` on the base branch used for the new worktree. Copied files are available when setup runs. diff --git a/public-docs/worktrees/worktreeinclude.zh-CN.md b/public-docs/worktrees/worktreeinclude.zh-CN.md new file mode 100644 index 0000000000..e80e386a01 --- /dev/null +++ b/public-docs/worktrees/worktreeinclude.zh-CN.md @@ -0,0 +1,61 @@ +--- +title: .worktreeinclude +description: 将 Git 忽略的本地文件复制到新的 Paseo worktree。 +nav: .worktreeinclude +order: 12 +category: Workspaces +--- + +# .worktreeinclude + +在源检出的根目录添加 `.worktreeinclude`,将本地配置复制到新的 [Git worktree](/docs/worktrees)。Paseo 会在 setup、终端和首个 Agent 启动之前复制匹配的 Git 忽略文件。 + +## 复制本地配置 {#copy-your-local-configuration} + +如果项目的 `.gitignore` 包含 `.env` 和 `config/*.local.json`,创建以下 `.worktreeinclude`: + +```gitignore +.env +config/*.local.json +``` + +通过 Paseo 创建 worktree 时,已有的 `.env` 和 `config/dev.local.json` 等匹配文件会被复制到新 worktree 中的相同相对路径。文件内容仍不会纳入 Git。 + +提交 `.worktreeinclude`,与团队共享这些模式。每位团队成员在用于创建 worktree 的检出中提供自己的忽略文件。 + +## 模式语法 {#pattern-syntax} + +使用 gitignore 语法,每行一个模式。注释以 `#` 开头。模式前加 `!` 可排除匹配项: + +```gitignore +# Local environment and configuration +.env +config/*.local.json +!config/production.local.json +``` + +模式只会选择 Git 已忽略的文件。在此添加路径不会使 Git 忽略该文件,需要时还应配置 `.gitignore`。已跟踪的文件和未被 Git 忽略的未跟踪文件都不会被复制。 + +## 文件复制时机 {#when-files-are-copied} + +内置的 `worktree-include` 插件从用于创建 worktree 的检出读取该文件。源检出也可以是另一个 worktree。保持该插件启用才能执行复制。 + +- 没有 `.worktreeinclude` 时,插件不会复制任何文件。 +- 匹配的文件必须存在于源检出中。 +- 目标中已存在的文件会被跳过,保留原有内容。 +- 复制发生在创建期间,之后不会在检出之间持续同步。 +- 复制错误会中止创建并删除新 worktree。避免包含符号链接目录或嵌套仓库,因为它们无法作为文件复制。 + +## 在 setup 期间运行命令 {#run-commands-during-setup} + +使用 `.worktreeinclude` 复制本地已有文件。使用 [setup 钩子](/docs/worktrees#setup-and-teardown) 安装依赖、生成文件或获取密钥: + +```json +{ + "worktree": { + "setup": "npm ci" + } +} +``` + +将此配置放入新 worktree 所用基准分支的 `paseo.json` 中。setup 运行时,复制的文件已可使用。 From ef77b823ae6d4c2c1a11dad3df5a34c6ececa8f3 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sun, 1 Nov 2026 12:56:41 +0700 Subject: [PATCH 165/173] chore(release): reconcile 0.15.0-beta.1 metadata (#8443) * docs(changelog): prepare 0.15.0-beta.1 (cherry picked from commit 7e5ad53491ac38372ead1f9773a82d284ce491fa) * chore(release): cut 0.15.0-beta.1 (cherry picked from commit 8bd38fb23645652078cb629baa2e65e0b6baa65a) * test(docs): follow nested worktrees page --- CHANGELOG.md | 78 +++++++++++++++++++-- CHANGELOG.zh-CN.md | 80 ++++++++++++++++++++-- nix/npm-deps.hash | 2 +- package-lock.json | 56 +++++++-------- package.json | 2 +- packages/app/package.json | 2 +- packages/cli/package.json | 8 +-- packages/client/package.json | 6 +- packages/desktop/package.json | 2 +- packages/expo-two-way-audio/package.json | 2 +- packages/highlight/package.json | 2 +- packages/plugin/package.json | 10 +-- packages/protocol/package.json | 2 +- packages/relay/package.json | 2 +- packages/server/package.json | 12 ++-- packages/website/package.json | 2 +- packages/website/src/schedule-docs.test.ts | 2 +- plugins/package.json | 2 +- 18 files changed, 202 insertions(+), 70 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e47984dbf7..6ee9a07b36 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,15 +1,81 @@ # Changelog -Not released yet. These changes are on `main` but not in 0.14.0; the next release entry includes them. +## 0.15.0-beta.1 - 2026-11-01 -Added: +Daemon restarts now keep terminal programs running and automatically resume interrupted agents in their existing conversations. -- Copy gitignored files selected by `.worktreeinclude` into new worktrees before setup and agents, using the built-in `worktree-include` plugin ([#8100](https://github.com/getpaseo/paseo/pull/8100)) -- Let plugins choose worktree paths and creation options through `worktree.create.before`, with listing, archive, deletion, and recovery at custom locations; includes a sibling-directory placement example ([#8117](https://github.com/getpaseo/paseo/pull/8117)) +Mobile terminals have native rendering and draggable text-selection handles. Reconnecting restores up to 10,000 lines of terminal history. -Improved: +Worktree setup can copy ignored files and use plugin-defined locations before agents start. -- Added `server.addHook` with `subject.operation.position` names and the awaited `worktree.create.after` hook before setup and agents; deprecated the previous plugin hook registration methods without changing their behavior ([#8081](https://github.com/getpaseo/paseo/pull/8081)) +### Added + +- Insert known agent commands from replies into the Composer draft ([#8371](https://github.com/getpaseo/paseo/pull/8371)) +- Reuse running OpenCode v2 services ([#7435](https://github.com/getpaseo/paseo/pull/7435) by [@mcowger](https://github.com/mcowger)) +- Kept terminal programs running across daemon restarts, crashes and supported updates ([#7644](https://github.com/getpaseo/paseo/pull/7644), [#8155](https://github.com/getpaseo/paseo/pull/8155) by [@sebastianarena](https://github.com/sebastianarena)) +- Automatically resume interrupted agents in their existing conversations after a host restart ([#8127](https://github.com/getpaseo/paseo/pull/8127) by [@coolwindX](https://github.com/coolwindX), [@suntianc](https://github.com/suntianc)) +- Added draggable terminal text-selection handles on iOS and Android ([#8348](https://github.com/getpaseo/paseo/pull/8348)) +- Let phones and tablets rotate with the system orientation setting ([#8256](https://github.com/getpaseo/paseo/pull/8256) by [@magiclaw](https://github.com/magiclaw), [@yzim](https://github.com/yzim)) +- Copy ignored files selected by `.worktreeinclude` into new worktrees before setup and agents start ([#8100](https://github.com/getpaseo/paseo/pull/8100) by [@cprecioso](https://github.com/cprecioso)) +- Added daemon-wide support for `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY` ([#8177](https://github.com/getpaseo/paseo/pull/8177)) +- Fetch usage only while displayed, with a host setting to disable usage checks entirely ([#8181](https://github.com/getpaseo/paseo/pull/8181)) + +### Improved + +- Replaced mobile terminal text rendering to align CJK characters, emoji, styled text and the cursor with terminal columns ([#8336](https://github.com/getpaseo/paseo/pull/8336), [#8375](https://github.com/getpaseo/paseo/pull/8375)) +- Restore the configured terminal scrollback on reconnect, up to 10,000 retained lines ([#8282](https://github.com/getpaseo/paseo/pull/8282) by [@DrakenKor](https://github.com/DrakenKor), [@lennartschoch](https://github.com/lennartschoch)) +- Load paginated Codex histories when importing or reopening sessions ([#8171](https://github.com/getpaseo/paseo/pull/8171) by [@dundunHa](https://github.com/dundunHa), [@hr95savage](https://github.com/hr95savage)) +- Stopped rereading and retaining an unused copy of Codex history when reopening a cached chat ([#8132](https://github.com/getpaseo/paseo/pull/8132)) +- Split large daemon responses across relay frames instead of disconnecting at the frame limit ([#8302](https://github.com/getpaseo/paseo/pull/8302)) +- Truncate oversized chat entries before sending them to the app, including large tool results and embedded data ([#8274](https://github.com/getpaseo/paseo/pull/8274)) +- Show subagent activity in its own panel instead of duplicating it inside the parent’s tool card ([#8276](https://github.com/getpaseo/paseo/pull/8276)) +- Show exact usage reset times alongside more precise countdowns ([#8162](https://github.com/getpaseo/paseo/pull/8162)) + +### Plugins + +- Fixed discarded messages returning after rewinding plugin conversations ([#8368](https://github.com/getpaseo/paseo/pull/8368) by [@mcowger](https://github.com/mcowger), [@omercnet](https://github.com/omercnet)) +- Reduced plugin downloads with smaller client bundles and a cache reused across reconnects and app launches ([#8040](https://github.com/getpaseo/paseo/pull/8040), [#8076](https://github.com/getpaseo/paseo/pull/8076) by [@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev)) +- Preserved plugin screens and local state during temporary host disconnections ([#8105](https://github.com/getpaseo/paseo/pull/8105) by [@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev)) +- Let plugins choose worktree locations and creation options through `worktree.create.before` ([#8117](https://github.com/getpaseo/paseo/pull/8117) by [@mcowger](https://github.com/mcowger)) +- Added `server.addHook` with an awaited `worktree.create.after` hook before workspace setup and agents start ([#8081](https://github.com/getpaseo/paseo/pull/8081)) +- Released redundant plugin streaming snapshots instead of retaining them for the session’s lifetime ([#7675](https://github.com/getpaseo/paseo/pull/7675) by [@suntianc](https://github.com/suntianc)) + +### Fixed + +- Fixed rewinding Claude conversations to messages sent during an active turn ([#8372](https://github.com/getpaseo/paseo/pull/8372) by [@tieo](https://github.com/tieo)) +- Fixed duplicate rows and missing replies when resuming Claude subagents after reopening a session ([#8408](https://github.com/getpaseo/paseo/pull/8408) by [@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev)) +- Fixed Codex agents created without a prompt failing after their runtime reopens ([#8393](https://github.com/getpaseo/paseo/pull/8393) by [@babo-jeonguk](https://github.com/babo-jeonguk)) +- Fixed newly running agents appearing as finished immediately after creation ([#8396](https://github.com/getpaseo/paseo/pull/8396) by [@luoph](https://github.com/luoph)) +- Fixed ACP startup exits waiting for a timeout instead of reporting the process error ([#8384](https://github.com/getpaseo/paseo/pull/8384) by [@Peanut-HZM](https://github.com/Peanut-HZM)) +- Fixed skills missing from new ACP agents when commands arrive in multiple batches ([#8387](https://github.com/getpaseo/paseo/pull/8387) by [@Peanut-HZM](https://github.com/Peanut-HZM)) +- Fixed sidebar titles and statuses stopping updates after directory subscriptions are released ([#8403](https://github.com/getpaseo/paseo/pull/8403) by [@ragokan](https://github.com/ragokan)) +- Kept the open workspace visible in collapsed sidebar groups ([#8395](https://github.com/getpaseo/paseo/pull/8395) by [@0xroylee](https://github.com/0xroylee)) +- Fixed relative chat links opening missing files instead of files in nested repositories ([#8361](https://github.com/getpaseo/paseo/pull/8361) by [@apple-ouyang](https://github.com/apple-ouyang)) +- Accepted host:port and pasted URLs in the Direct connection Host field ([#8223](https://github.com/getpaseo/paseo/pull/8223) by [@DaydreamCoding](https://github.com/DaydreamCoding)) +- Fixed terminal Ctrl+V paste over plain HTTP on non-Mac keyboards ([#8230](https://github.com/getpaseo/paseo/pull/8230) by [@DaydreamCoding](https://github.com/DaydreamCoding)) +- Stopped failed history loads from repeatedly reopening the provider, with Retry available in the chat ([#8278](https://github.com/getpaseo/paseo/pull/8278)) +- Fixed Claude settings files being discarded when Paseo adds its own launch settings ([#8148](https://github.com/getpaseo/paseo/pull/8148) by [@yayugu](https://github.com/yayugu)) +- Fixed steering messages replacing a turn that was still starting and losing its original prompt ([#6192](https://github.com/getpaseo/paseo/pull/6192)) +- Fixed Pi tool-result images missing during streaming and after reopening the chat ([#8280](https://github.com/getpaseo/paseo/pull/8280) by [@duyiliu](https://github.com/duyiliu)) +- Fixed completed `edxeth/pi-subagents` children remaining marked as working ([#8176](https://github.com/getpaseo/paseo/pull/8176) by [@Zeno2019](https://github.com/Zeno2019)) +- Fixed Claude background subagent status after reopening a conversation ([#6259](https://github.com/getpaseo/paseo/pull/6259)) +- Fixed reused plugin subagents showing their previous completed status during new work ([#8080](https://github.com/getpaseo/paseo/pull/8080) by [@bccy](https://github.com/bccy)) +- Fixed custom Codex providers with reserved names such as `ollama` ([#6954](https://github.com/getpaseo/paseo/pull/6954) by [@mr860819](https://github.com/mr860819)) +- Fixed the MiniMax Code catalog command failing to select an executable ([#8201](https://github.com/getpaseo/paseo/pull/8201) by [@Peanut-HZM](https://github.com/Peanut-HZM)) +- Fixed Android keeping the wrong layout after folding or unfolding while backgrounded ([#8285](https://github.com/getpaseo/paseo/pull/8285)) +- Fixed Android workspace layouts and header fades retaining their old size after rotation ([#8349](https://github.com/getpaseo/paseo/pull/8349), [#8377](https://github.com/getpaseo/paseo/pull/8377)) +- Fixed deleted agents leaving unclosable tabs in another window ([#8248](https://github.com/getpaseo/paseo/pull/8248) by [@loganmeyer](https://github.com/loganmeyer)) +- Fixed transcript text retaining old theme colors after the theme changes while the window is hidden ([#8199](https://github.com/getpaseo/paseo/pull/8199) by [@Nurshot](https://github.com/Nurshot), [@dansabin](https://github.com/dansabin)) +- Fixed web menus snapping back to their loading size after content arrives ([#8180](https://github.com/getpaseo/paseo/pull/8180) by [@babo-jeonguk](https://github.com/babo-jeonguk)) +- Fixed split dividers drifting ahead of or behind the pointer while dragging ([#6011](https://github.com/getpaseo/paseo/pull/6011)) +- Fixed delayed native filesystem watcher startup leaving Git updates unobserved ([#8107](https://github.com/getpaseo/paseo/pull/8107)) +- Fixed bundled skill arguments being passed incorrectly to Codex and Pi ([#8252](https://github.com/getpaseo/paseo/pull/8252) by [@AspireOne](https://github.com/AspireOne)) + +### Notes + +- The first upgrade from 0.14.0 still closes terminals; terminal preservation starts once the new daemon is installed, and Windows desktop app upgrades still close them +- Automatic agent recovery is on by default and sends `Resume working.`; change the prompt or disable it in Host settings → Agents +- Before downgrading to 0.14.0, restore a backed-up `config.json` or remove the saved agent-resume and usage-check settings ## 0.14.0 - 2026-10-29 diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index f87cb58805..532ed24887 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -1,15 +1,81 @@ -# 更新日志 +# Changelog -尚未发布。以下变更已合入 `main`,但不包含在 0.14.0 中;下一个版本的条目会包含它们。 +## 0.15.0-beta.1 - 2026-11-01 -新增: +daemon 重启后,终端中的程序继续运行,被中断的 Agent 会自动在原有会话中恢复工作。 -- 在 setup 和 Agent 启动前,使用内置的 `worktree-include` 插件将 `.worktreeinclude` 选中的被 gitignore 忽略的文件复制到新工作树 ([#8100](https://github.com/getpaseo/paseo/pull/8100)) -- 插件可通过 `worktree.create.before` 选择工作树路径和创建选项,自定义位置的工作树支持列出、归档、删除和恢复;附带同级目录放置示例 ([#8117](https://github.com/getpaseo/paseo/pull/8117)) +移动端终端采用原生渲染,并提供可拖动的文本选择手柄。重新连接时最多恢复 10,000 行终端历史。 -改进: +worktree 初始化支持复制被忽略的文件,并在 Agent 启动前使用插件指定的位置。 -- 新增采用 `subject.operation.position` 命名的 `server.addHook` 和在 setup 及 Agent 之前等待的 `worktree.create.after` 钩子,弃用原有的插件钩子注册方法并保留原有行为 ([#8081](https://github.com/getpaseo/paseo/pull/8081)) +### 新增 + +- 点击回复中的已知 Agent 命令,将其插入 Composer 草稿 ([#8371](https://github.com/getpaseo/paseo/pull/8371)) +- 复用已运行的 OpenCode v2 服务 ([#7435](https://github.com/getpaseo/paseo/pull/7435),贡献者:[@mcowger](https://github.com/mcowger)) +- 让终端中的程序在 daemon 重启、崩溃和支持的更新过程中继续运行 ([#7644](https://github.com/getpaseo/paseo/pull/7644), [#8155](https://github.com/getpaseo/paseo/pull/8155),贡献者:[@sebastianarena](https://github.com/sebastianarena)) +- 主机重启后,自动在原有会话中恢复被中断的 Agent ([#8127](https://github.com/getpaseo/paseo/pull/8127),贡献者:[@coolwindX](https://github.com/coolwindX), [@suntianc](https://github.com/suntianc)) +- 在 iOS 和 Android 终端中新增可拖动的文本选择手柄 ([#8348](https://github.com/getpaseo/paseo/pull/8348)) +- 让手机和平板遵循系统屏幕旋转设置 ([#8256](https://github.com/getpaseo/paseo/pull/8256),贡献者:[@magiclaw](https://github.com/magiclaw), [@yzim](https://github.com/yzim)) +- 通过 `.worktreeinclude` 选择要复制到新 worktree 的被忽略文件,在初始化和 Agent 启动前完成复制 ([#8100](https://github.com/getpaseo/paseo/pull/8100),贡献者:[@cprecioso](https://github.com/cprecioso)) +- 让 daemon 的网络请求支持 `HTTP_PROXY`、`HTTPS_PROXY` 和 `NO_PROXY` ([#8177](https://github.com/getpaseo/paseo/pull/8177)) +- 仅在显示用量时查询用量,并提供主机设置以完全关闭用量查询 ([#8181](https://github.com/getpaseo/paseo/pull/8181)) + +### 改进 + +- 更换移动端终端文本渲染方式,让中日韩字符、表情符号、带样式文本和光标对齐终端列 ([#8336](https://github.com/getpaseo/paseo/pull/8336), [#8375](https://github.com/getpaseo/paseo/pull/8375)) +- 重新连接时恢复设置指定的终端回滚历史,最多保留 10,000 行 ([#8282](https://github.com/getpaseo/paseo/pull/8282),贡献者:[@DrakenKor](https://github.com/DrakenKor), [@lennartschoch](https://github.com/lennartschoch)) +- 导入或重新打开 Codex 会话时加载分页历史 ([#8171](https://github.com/getpaseo/paseo/pull/8171),贡献者:[@dundunHa](https://github.com/dundunHa), [@hr95savage](https://github.com/hr95savage)) +- 重新打开已有缓存的 Codex 聊天时,不再重复读取并保留未使用的历史副本 ([#8132](https://github.com/getpaseo/paseo/pull/8132)) +- 将 daemon 的大型响应拆分为多个 relay 帧,避免达到单帧限制时断开连接 ([#8302](https://github.com/getpaseo/paseo/pull/8302)) +- 向应用发送聊天条目前截断超大内容,包括大型工具结果和内嵌数据 ([#8274](https://github.com/getpaseo/paseo/pull/8274)) +- 在子 Agent 自己的面板中显示活动,不再在父 Agent 的工具卡片中重复显示 ([#8276](https://github.com/getpaseo/paseo/pull/8276)) +- 在更精确的倒计时旁显示用量限制的具体重置时间 ([#8162](https://github.com/getpaseo/paseo/pull/8162)) + +### 插件 + +- 修复了插件会话回退后已丢弃的消息重新出现的问题 ([#8368](https://github.com/getpaseo/paseo/pull/8368),贡献者:[@mcowger](https://github.com/mcowger), [@omercnet](https://github.com/omercnet)) +- 通过缩小客户端代码包并在重连和应用启动时复用缓存,减少插件下载量 ([#8040](https://github.com/getpaseo/paseo/pull/8040), [#8076](https://github.com/getpaseo/paseo/pull/8076),贡献者:[@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev)) +- 在主机暂时断开连接期间保留插件页面和本地状态 ([#8105](https://github.com/getpaseo/paseo/pull/8105),贡献者:[@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev)) +- 让插件通过 `worktree.create.before` 指定 worktree 的位置和创建选项 ([#8117](https://github.com/getpaseo/paseo/pull/8117),贡献者:[@mcowger](https://github.com/mcowger)) +- 新增 `server.addHook`,并在工作区初始化和 Agent 启动前等待 `worktree.create.after` hook 完成 ([#8081](https://github.com/getpaseo/paseo/pull/8081)) +- 释放多余的插件流式快照,不再将其保留到会话结束 ([#7675](https://github.com/getpaseo/paseo/pull/7675),贡献者:[@suntianc](https://github.com/suntianc)) + +### 修复 + +- 修复了无法将 Claude 会话回退到运行过程中发送的消息的问题 ([#8372](https://github.com/getpaseo/paseo/pull/8372),贡献者:[@tieo](https://github.com/tieo)) +- 修复了重新打开会话后恢复 Claude 子 Agent 时出现重复行和回复缺失的问题 ([#8408](https://github.com/getpaseo/paseo/pull/8408),贡献者:[@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev)) +- 修复了未发送提示词的 Codex Agent 在运行时重新打开后无法使用的问题 ([#8393](https://github.com/getpaseo/paseo/pull/8393),贡献者:[@babo-jeonguk](https://github.com/babo-jeonguk)) +- 修复了刚开始运行的 Agent 在创建后立即显示为已完成的问题 ([#8396](https://github.com/getpaseo/paseo/pull/8396),贡献者:[@luoph](https://github.com/luoph)) +- 修复了 ACP 启动进程退出后仍等待超时而未及时报告错误的问题 ([#8384](https://github.com/getpaseo/paseo/pull/8384),贡献者:[@Peanut-HZM](https://github.com/Peanut-HZM)) +- 修复了命令分批到达时新 ACP Agent 的技能列表不完整的问题 ([#8387](https://github.com/getpaseo/paseo/pull/8387),贡献者:[@Peanut-HZM](https://github.com/Peanut-HZM)) +- 修复了目录订阅释放后侧栏标题和状态停止更新的问题 ([#8403](https://github.com/getpaseo/paseo/pull/8403),贡献者:[@ragokan](https://github.com/ragokan)) +- 在折叠的侧栏分组中保持当前工作区可见 ([#8395](https://github.com/getpaseo/paseo/pull/8395),贡献者:[@0xroylee](https://github.com/0xroylee)) +- 修复了聊天中的相对链接未打开嵌套仓库中的文件而指向不存在文件的问题 ([#8361](https://github.com/getpaseo/paseo/pull/8361),贡献者:[@apple-ouyang](https://github.com/apple-ouyang)) +- 在直接连接的主机字段中支持 host:port 和粘贴的 URL ([#8223](https://github.com/getpaseo/paseo/pull/8223),贡献者:[@DaydreamCoding](https://github.com/DaydreamCoding)) +- 修复了非 Mac 键盘通过普通 HTTP 访问网页终端时 Ctrl+V 无法粘贴的问题 ([#8230](https://github.com/getpaseo/paseo/pull/8230),贡献者:[@DaydreamCoding](https://github.com/DaydreamCoding)) +- 停止在历史加载失败后反复重新打开 Provider,可在聊天中手动重试 ([#8278](https://github.com/getpaseo/paseo/pull/8278)) +- 修复了 Paseo 添加自身启动设置时丢弃 Claude 设置文件的问题 ([#8148](https://github.com/getpaseo/paseo/pull/8148),贡献者:[@yayugu](https://github.com/yayugu)) +- 修复了引导消息替换尚在启动的轮次并丢失原始提示词的问题 ([#6192](https://github.com/getpaseo/paseo/pull/6192)) +- 修复了 Pi 工具结果中的图片在流式输出和重新打开聊天后缺失的问题 ([#8280](https://github.com/getpaseo/paseo/pull/8280),贡献者:[@duyiliu](https://github.com/duyiliu)) +- 修复了 `edxeth/pi-subagents` 子 Agent 完成后仍显示为工作中的问题 ([#8176](https://github.com/getpaseo/paseo/pull/8176),贡献者:[@Zeno2019](https://github.com/Zeno2019)) +- 修复了重新打开会话后的 Claude 后台子 Agent 状态 ([#6259](https://github.com/getpaseo/paseo/pull/6259)) +- 修复了复用的插件子 Agent 开始新任务时仍显示上次已完成状态的问题 ([#8080](https://github.com/getpaseo/paseo/pull/8080),贡献者:[@bccy](https://github.com/bccy)) +- 修复了使用 `ollama` 等保留名称的自定义 Codex Provider ([#6954](https://github.com/getpaseo/paseo/pull/6954),贡献者:[@mr860819](https://github.com/mr860819)) +- 修复了 MiniMax Code 目录命令无法选定可执行文件的问题 ([#8201](https://github.com/getpaseo/paseo/pull/8201),贡献者:[@Peanut-HZM](https://github.com/Peanut-HZM)) +- 修复了 Android 应用在后台折叠或展开后保留错误布局的问题 ([#8285](https://github.com/getpaseo/paseo/pull/8285)) +- 修复了 Android 屏幕旋转后工作区布局和顶栏渐变保留旧尺寸的问题 ([#8349](https://github.com/getpaseo/paseo/pull/8349), [#8377](https://github.com/getpaseo/paseo/pull/8377)) +- 修复了删除 Agent 后,另一个窗口留下无法关闭的标签页的问题 ([#8248](https://github.com/getpaseo/paseo/pull/8248),贡献者:[@loganmeyer](https://github.com/loganmeyer)) +- 修复了窗口隐藏期间切换主题后,聊天文本保留旧主题颜色的问题 ([#8199](https://github.com/getpaseo/paseo/pull/8199),贡献者:[@Nurshot](https://github.com/Nurshot), [@dansabin](https://github.com/dansabin)) +- 修复了网页菜单加载内容后跳回加载时尺寸的问题 ([#8180](https://github.com/getpaseo/paseo/pull/8180),贡献者:[@babo-jeonguk](https://github.com/babo-jeonguk)) +- 修复了拖动分隔线时,分隔线偏离指针的问题 ([#6011](https://github.com/getpaseo/paseo/pull/6011)) +- 修复了原生文件监听器启动延迟导致 Git 更新未被监听的问题 ([#8107](https://github.com/getpaseo/paseo/pull/8107)) +- 修复了内置 skill 参数未正确传递给 Codex 和 Pi 的问题 ([#8252](https://github.com/getpaseo/paseo/pull/8252),贡献者:[@AspireOne](https://github.com/AspireOne)) + +### 说明 + +- 首次从 0.14.0 升级时仍会关闭终端;安装新 daemon 后才支持保留终端,Windows 桌面应用升级仍会关闭终端 +- Agent 自动恢复默认开启,并发送 `Resume working.`;可在主机设置 → Agent 中修改提示词或关闭此功能 +- 降级到 0.14.0 前,请恢复备份的 `config.json`,或删除已保存的 Agent 恢复和用量查询设置 ## 0.14.0 - 2026-10-29 diff --git a/nix/npm-deps.hash b/nix/npm-deps.hash index 530da9108f..3efbb30b52 100644 --- a/nix/npm-deps.hash +++ b/nix/npm-deps.hash @@ -1 +1 @@ -sha256-WPPLqWQzoUdjZNbZW6XWpy+A6XHXDyc0QW0FH6ubgMw= +sha256-CeT2PtYIAFwvBC9LIku8VkTl0pvKxYzSCn0QW2ManfU= diff --git a/package-lock.json b/package-lock.json index 49f6258e60..4b9481ff8e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "paseo", - "version": "0.14.0", + "version": "0.15.0-beta.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "paseo", - "version": "0.14.0", + "version": "0.15.0-beta.1", "hasInstallScript": true, "license": "Apache-2.0", "workspaces": [ @@ -37632,7 +37632,7 @@ }, "packages/app": { "name": "@getpaseo/app", - "version": "0.14.0", + "version": "0.15.0-beta.1", "dependencies": { "@codemirror/commands": "6.10.4", "@codemirror/language": "6.12.4", @@ -39800,12 +39800,12 @@ }, "packages/cli": { "name": "@getpaseo/cli", - "version": "0.14.0", + "version": "0.15.0-beta.1", "dependencies": { "@clack/prompts": "^1.0.0", - "@getpaseo/client": "0.14.0", - "@getpaseo/protocol": "0.14.0", - "@getpaseo/server": "0.14.0", + "@getpaseo/client": "0.15.0-beta.1", + "@getpaseo/protocol": "0.15.0-beta.1", + "@getpaseo/server": "0.15.0-beta.1", "chalk": "^5.3.0", "commander": "^12.0.0", "mime-types": "^2.1.35", @@ -40052,10 +40052,10 @@ }, "packages/client": { "name": "@getpaseo/client", - "version": "0.14.0", + "version": "0.15.0-beta.1", "dependencies": { - "@getpaseo/protocol": "0.14.0", - "@getpaseo/relay": "0.14.0", + "@getpaseo/protocol": "0.15.0-beta.1", + "@getpaseo/relay": "0.15.0-beta.1", "ws": "^8.20.0", "zod": "^4.4.3" }, @@ -40067,7 +40067,7 @@ }, "packages/desktop": { "name": "@getpaseo/desktop", - "version": "0.14.0", + "version": "0.15.0-beta.1", "license": "Apache-2.0", "dependencies": { "@getpaseo/cli": "*", @@ -40311,7 +40311,7 @@ }, "packages/expo-two-way-audio": { "name": "@getpaseo/expo-two-way-audio", - "version": "0.14.0", + "version": "0.15.0-beta.1", "license": "MIT", "devDependencies": { "@types/jest": "^29.5.14", @@ -40357,7 +40357,7 @@ }, "packages/highlight": { "name": "@getpaseo/highlight", - "version": "0.14.0", + "version": "0.15.0-beta.1", "dependencies": { "@codemirror/language": "6.12.4", "@codemirror/legacy-modes": "^6.5.3", @@ -40386,15 +40386,15 @@ }, "packages/plugin": { "name": "@getpaseo/plugin", - "version": "0.14.0", + "version": "0.15.0-beta.1", "dependencies": { "@agentclientprotocol/sdk": "^1.4.0", "i18next": "^26.3.0", "use-sync-external-store": "^1.6.0" }, "devDependencies": { - "@getpaseo/client": "0.14.0", - "@getpaseo/protocol": "0.14.0", + "@getpaseo/client": "0.15.0-beta.1", + "@getpaseo/protocol": "0.15.0-beta.1", "@types/node": "^20.9.0", "@types/react": "~19.2.0", "react": "19.2.3", @@ -40404,8 +40404,8 @@ "zod": "^4.4.3" }, "peerDependencies": { - "@getpaseo/client": "0.14.0", - "@getpaseo/protocol": "0.14.0", + "@getpaseo/client": "0.15.0-beta.1", + "@getpaseo/protocol": "0.15.0-beta.1", "react": ">=19.1.0 <20", "react-native": ">=0.81.5", "zod": "^4.4.3" @@ -40427,7 +40427,7 @@ }, "packages/protocol": { "name": "@getpaseo/protocol", - "version": "0.14.0", + "version": "0.15.0-beta.1", "dependencies": { "semver": "^7.8.5", "zod": "^4.4.3" @@ -40454,7 +40454,7 @@ }, "packages/relay": { "name": "@getpaseo/relay", - "version": "0.14.0", + "version": "0.15.0-beta.1", "dependencies": { "@noble/ciphers": "^2.4.0", "@noble/curves": "^2.4.0", @@ -40675,16 +40675,16 @@ }, "packages/server": { "name": "@getpaseo/server", - "version": "0.14.0", + "version": "0.15.0-beta.1", "dependencies": { "@agentclientprotocol/sdk": "^0.17.1", "@anthropic-ai/claude-agent-sdk": "0.3.246", "@anthropic-ai/sdk": "^0.104.2", - "@getpaseo/client": "0.14.0", - "@getpaseo/highlight": "0.14.0", - "@getpaseo/plugin": "0.14.0", - "@getpaseo/protocol": "0.14.0", - "@getpaseo/relay": "0.14.0", + "@getpaseo/client": "0.15.0-beta.1", + "@getpaseo/highlight": "0.15.0-beta.1", + "@getpaseo/plugin": "0.15.0-beta.1", + "@getpaseo/protocol": "0.15.0-beta.1", + "@getpaseo/relay": "0.15.0-beta.1", "@isaacs/ttlcache": "^2.1.4", "@modelcontextprotocol/sdk": "1.29.0", "@opencode-ai/sdk": "1.14.46", @@ -41631,7 +41631,7 @@ }, "packages/website": { "name": "@getpaseo/website", - "version": "0.14.0", + "version": "0.15.0-beta.1", "dependencies": { "@cloudflare/vite-plugin": "^1.29.1", "@cloudflare/workers-types": "^4.20260317.1", @@ -43241,7 +43241,7 @@ }, "plugins": { "name": "@getpaseo/builtin-plugins", - "version": "0.14.0", + "version": "0.15.0-beta.1", "dependencies": { "@getpaseo/plugin": "*", "zod": "^4.4.3" diff --git a/package.json b/package.json index 938497a362..cbcb507539 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "paseo", - "version": "0.14.0", + "version": "0.15.0-beta.1", "private": true, "description": "Paseo: voice-controlled development environment for local AI coding agents", "keywords": [ diff --git a/packages/app/package.json b/packages/app/package.json index e6cc1d4029..e269af14ae 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/app", - "version": "0.14.0", + "version": "0.15.0-beta.1", "private": true, "main": "index.ts", "scripts": { diff --git a/packages/cli/package.json b/packages/cli/package.json index 45113dd1bc..6c7fa3155d 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/cli", - "version": "0.14.0", + "version": "0.15.0-beta.1", "description": "Paseo CLI - control your AI coding agents from the command line", "bin": { "paseo": "bin/paseo" @@ -28,9 +28,9 @@ }, "dependencies": { "@clack/prompts": "^1.0.0", - "@getpaseo/client": "0.14.0", - "@getpaseo/protocol": "0.14.0", - "@getpaseo/server": "0.14.0", + "@getpaseo/client": "0.15.0-beta.1", + "@getpaseo/protocol": "0.15.0-beta.1", + "@getpaseo/server": "0.15.0-beta.1", "chalk": "^5.3.0", "commander": "^12.0.0", "mime-types": "^2.1.35", diff --git a/packages/client/package.json b/packages/client/package.json index 6e10c76089..19c0490021 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/client", - "version": "0.14.0", + "version": "0.15.0-beta.1", "description": "Paseo client SDK package", "files": [ "dist", @@ -47,8 +47,8 @@ "test": "vitest run" }, "dependencies": { - "@getpaseo/protocol": "0.14.0", - "@getpaseo/relay": "0.14.0", + "@getpaseo/protocol": "0.15.0-beta.1", + "@getpaseo/relay": "0.15.0-beta.1", "ws": "^8.20.0", "zod": "^4.4.3" }, diff --git a/packages/desktop/package.json b/packages/desktop/package.json index 074e79b64d..6319805fc3 100644 --- a/packages/desktop/package.json +++ b/packages/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/desktop", - "version": "0.14.0", + "version": "0.15.0-beta.1", "private": true, "description": "Paseo desktop app (Electron wrapper)", "homepage": "https://paseo.sh", diff --git a/packages/expo-two-way-audio/package.json b/packages/expo-two-way-audio/package.json index aa86be129b..ff08d35c76 100644 --- a/packages/expo-two-way-audio/package.json +++ b/packages/expo-two-way-audio/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/expo-two-way-audio", - "version": "0.14.0", + "version": "0.15.0-beta.1", "description": "Native module for two way audio streaming", "keywords": [ "ExpoTwoWayAudio", diff --git a/packages/highlight/package.json b/packages/highlight/package.json index 6b1d924e05..dfc43982bf 100644 --- a/packages/highlight/package.json +++ b/packages/highlight/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/highlight", - "version": "0.14.0", + "version": "0.15.0-beta.1", "files": [ "dist", "!dist/**/*.map", diff --git a/packages/plugin/package.json b/packages/plugin/package.json index 32cb48e026..8ed758eb5f 100644 --- a/packages/plugin/package.json +++ b/packages/plugin/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/plugin", - "version": "0.14.0", + "version": "0.15.0-beta.1", "description": "Paseo plugin SDK package", "files": [ "dist", @@ -77,8 +77,8 @@ "use-sync-external-store": "^1.6.0" }, "devDependencies": { - "@getpaseo/client": "0.14.0", - "@getpaseo/protocol": "0.14.0", + "@getpaseo/client": "0.15.0-beta.1", + "@getpaseo/protocol": "0.15.0-beta.1", "@types/node": "^20.9.0", "@types/react": "~19.2.0", "react": "19.2.3", @@ -88,8 +88,8 @@ "zod": "^4.4.3" }, "peerDependencies": { - "@getpaseo/client": "0.14.0", - "@getpaseo/protocol": "0.14.0", + "@getpaseo/client": "0.15.0-beta.1", + "@getpaseo/protocol": "0.15.0-beta.1", "react": ">=19.1.0 <20", "react-native": ">=0.81.5", "zod": "^4.4.3" diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 21d500fd4f..70d783f701 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/protocol", - "version": "0.14.0", + "version": "0.15.0-beta.1", "description": "Paseo shared protocol schemas and wire types", "files": [ "dist", diff --git a/packages/relay/package.json b/packages/relay/package.json index ec1deebff7..86bde64a75 100644 --- a/packages/relay/package.json +++ b/packages/relay/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/relay", - "version": "0.14.0", + "version": "0.15.0-beta.1", "description": "Paseo relay for bridging daemon and client connections", "files": [ "dist", diff --git a/packages/server/package.json b/packages/server/package.json index 72a21944ef..191aee2945 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/server", - "version": "0.14.0", + "version": "0.15.0-beta.1", "description": "Paseo backend server", "files": [ "dist/server", @@ -107,11 +107,11 @@ "@agentclientprotocol/sdk": "^0.17.1", "@anthropic-ai/claude-agent-sdk": "0.3.246", "@anthropic-ai/sdk": "^0.104.2", - "@getpaseo/client": "0.14.0", - "@getpaseo/highlight": "0.14.0", - "@getpaseo/plugin": "0.14.0", - "@getpaseo/protocol": "0.14.0", - "@getpaseo/relay": "0.14.0", + "@getpaseo/client": "0.15.0-beta.1", + "@getpaseo/highlight": "0.15.0-beta.1", + "@getpaseo/plugin": "0.15.0-beta.1", + "@getpaseo/protocol": "0.15.0-beta.1", + "@getpaseo/relay": "0.15.0-beta.1", "@isaacs/ttlcache": "^2.1.4", "@modelcontextprotocol/sdk": "1.29.0", "@opencode-ai/sdk": "1.14.46", diff --git a/packages/website/package.json b/packages/website/package.json index 7e0635c2e9..b45ec39396 100644 --- a/packages/website/package.json +++ b/packages/website/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/website", - "version": "0.14.0", + "version": "0.15.0-beta.1", "private": true, "type": "module", "scripts": { diff --git a/packages/website/src/schedule-docs.test.ts b/packages/website/src/schedule-docs.test.ts index 015d85fe6c..76fca93287 100644 --- a/packages/website/src/schedule-docs.test.ts +++ b/packages/website/src/schedule-docs.test.ts @@ -4,7 +4,7 @@ import { expect, it } from "vitest"; const docsRoot = path.resolve(import.meta.dirname, "../../../public-docs"); -it.each(["schedules.md", "schedules-cli.md", "mcp.md", "worktrees.md"])( +it.each(["schedules.md", "schedules-cli.md", "mcp.md", "worktrees/index.md"])( "%s makes schedule run retention discoverable", async (file) => { const markdown = await readFile(path.join(docsRoot, file), "utf8"); diff --git a/plugins/package.json b/plugins/package.json index aa09dfb568..e7d0a6019f 100644 --- a/plugins/package.json +++ b/plugins/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/builtin-plugins", - "version": "0.14.0", + "version": "0.15.0-beta.1", "private": true, "type": "module", "scripts": { From 6ae6308cfbae5a72c11f2e54eebd32811744a490 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 06:01:30 +0000 Subject: [PATCH 166/173] test(server): control failed Git clone responses in credential test (#8428) Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../plugins/managed-source.posix.test.ts | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/packages/server/src/server/plugins/managed-source.posix.test.ts b/packages/server/src/server/plugins/managed-source.posix.test.ts index 466780b79a..7b694f1ef3 100644 --- a/packages/server/src/server/plugins/managed-source.posix.test.ts +++ b/packages/server/src/server/plugins/managed-source.posix.test.ts @@ -61,10 +61,24 @@ describe("managed Git plugin sources", () => { roots.push(home); const sources = new ManagedPluginSources(home); - const failure = sources.prepareInstall({ - source: "git:https://oauth2:super-secret@127.0.0.1:1/missing.git", + // Own the failure response instead of relying on a closed port and OS connect timing. + const server = createServer((_request, response) => { + response.writeHead(500, { "Content-Type": "text/plain" }); + response.end("clone rejected for oauth2:super-secret\n"); }); - await expect(failure).rejects.not.toThrow(/oauth2|super-secret/); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address() as { port: number }; + try { + const failure = sources.prepareInstall({ + source: `git:http://oauth2:super-secret@127.0.0.1:${address.port}/missing.git`, + }); + await expect(failure).rejects.toThrow("500"); + await expect(failure).rejects.toThrow("clone rejected for [redacted]:[redacted]"); + await expect(failure).rejects.not.toThrow(/oauth2|super-secret/); + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } }); it("normalizes explicit GitHub and Git identifiers to the same Git source", async () => { From 891e62309cd241ad89ac6d960692e746cce8e25c Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sun, 1 Nov 2026 13:35:11 +0700 Subject: [PATCH 167/173] fix(release): use the keychain password for macOS signing setup (#8445) Backport the pinned packaging tool correction in the workflow so existing release tags can be rebuilt without changing their dependencies. --- .github/workflows/desktop-release.yml | 26 ++++++++++++++ scripts/ci-workflow.test.mjs | 52 ++++++++++++++++++++++++++- 2 files changed, 77 insertions(+), 1 deletion(-) diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.yml index 26be12291b..bdbeb9f139 100644 --- a/.github/workflows/desktop-release.yml +++ b/.github/workflows/desktop-release.yml @@ -135,6 +135,32 @@ jobs: env: NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # Backport electron-builder#10172 to the pinned build tool only. + # Remove this step when app-builder-lib is upgraded to a release containing it. + - name: Repair temporary keychain password in signing tool + shell: bash + run: | + node <<'KEYCHAIN_FIX' + const fs = require('node:fs'); + const path = require('node:path'); + const manifestPath = require.resolve('app-builder-lib/package.json'); + if (JSON.parse(fs.readFileSync(manifestPath, 'utf8')).version !== '26.8.1') { + throw new Error('Reassess/remove the signing backport for the new app-builder-lib version'); + } + const sourcePath = path.join(path.dirname(manifestPath), 'out/codeSign/macCodeSign.js'); + let source = fs.readFileSync(sourcePath, 'utf8'); + const replacements = [ + ['importCerts(keychainFile, certPaths, cscPasswords)', 'importCerts(keychainFile, certPaths, cscPasswords, keychainPassword)'], + ['importCerts(keychainFile, paths, keyPasswords)', 'importCerts(keychainFile, paths, keyPasswords, keychainPassword)'], + ['["set-key-partition-list", "-S", "apple-tool:,apple:", "-s", "-k", password, keychainFile]', '["set-key-partition-list", "-S", "apple-tool:,apple:", "-s", "-k", keychainPassword, keychainFile]'], + ]; + for (const [before, after] of replacements) { + if (source.split(before).length !== 2) throw new Error('Unexpected signing tool source; refusing to patch'); + source = source.replace(before, after); + } + fs.writeFileSync(sourcePath, source); + KEYCHAIN_FIX + - name: Set desktop package version from tag shell: bash run: | diff --git a/scripts/ci-workflow.test.mjs b/scripts/ci-workflow.test.mjs index 73a9003312..381f826540 100644 --- a/scripts/ci-workflow.test.mjs +++ b/scripts/ci-workflow.test.mjs @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import { readFileSync, readdirSync, mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { readFileSync, readdirSync, mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; import { spawnSync } from "node:child_process"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -679,3 +679,53 @@ test("macOS jobs use latest runners while preserving release architectures", () // GitHub has no standard macos-latest-intel alias; use the newest Intel image. assert.match(release, /runner: macos-26-intel\n\s+electron_arch: x64/); }); + +test("macOS signing repair keeps certificate and keychain passwords separate", () => { + const workflow = readFileSync(new URL(".github/workflows/desktop-release.yml", repoRoot), "utf8"); + const match = workflow.match(/<<'KEYCHAIN_FIX'\n([\s\S]*?)\n KEYCHAIN_FIX/); + assert.ok(match, "the release workflow repairs the pinned signing tool"); + const script = match[1].replace(/^ /gm, ""); + const original = [ + "return await importCerts(keychainFile, certPaths, cscPasswords);", + "async function importCerts(keychainFile, paths, keyPasswords) {", + '["import", paths[i], "-P", password]', + '["set-key-partition-list", "-S", "apple-tool:,apple:", "-s", "-k", password, keychainFile]', + "}", + ].join("\n"); + const directory = mkdtempSync(join(tmpdir(), "signing-repair-")); + try { + const packageDirectory = join(directory, "node_modules/app-builder-lib"); + mkdirSync(join(packageDirectory, "out/codeSign"), { recursive: true }); + const manifest = join(packageDirectory, "package.json"); + const sourcePath = join(packageDirectory, "out/codeSign/macCodeSign.js"); + for (const [version, source, succeeds] of [ + ["26.8.1", original, true], + ["26.8.1", original.replace("cscPasswords);", "differentArguments);"), false], + ["26.18.0", original, false], + ]) { + writeFileSync(manifest, JSON.stringify({ name: "app-builder-lib", version })); + writeFileSync(sourcePath, source); + const result = spawnSync(process.execPath, ["-e", script], { + cwd: directory, + encoding: "utf8", + }); + const actual = readFileSync(sourcePath, "utf8"); + if (succeeds) { + assert.equal(result.status, 0, result.stderr); + assert.ok( + actual.includes("importCerts(keychainFile, certPaths, cscPasswords, keychainPassword)"), + ); + assert.ok( + actual.includes("importCerts(keychainFile, paths, keyPasswords, keychainPassword)"), + ); + assert.ok(actual.includes('["import", paths[i], "-P", password]')); + assert.ok(actual.includes('"-k", keychainPassword, keychainFile]')); + } else { + assert.notEqual(result.status, 0); + assert.equal(actual, source, "unexpected tool inputs must fail without a partial write"); + } + } + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); From 14519bdb5bb8306179e351ea568bd757bf59234a Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 06:52:48 +0000 Subject: [PATCH 168/173] Read archived Pi chats after their working folder is removed (#8442) * fix(pi): open an archived Pi agent's history after its folder is removed Opening an archived agent's timeline resumes its provider for history. Pi's resumeSession never received the resume purpose, so it launched the Pi RPC process, and its MCP support probe, in the agent's stored working directory. When that folder had been removed, for example with a merged worktree, Node failed the spawn with "spawn ENOENT" and the history could not be read. Starting the process elsewhere is not enough: with --session, Pi checks the cwd stored in the session file's header and, outside interactive mode, exits when that folder is missing. A history resume whose stored folder is no longer a directory now starts Pi from the home directory on a temporary copy of the session file whose header names that directory. The copy streams everything after the header unchanged and is deleted when the session closes. The agent keeps reporting its stored folder and original session file, and the original file is not written to. The directory check moves out of the ACP provider, which already starts history loads from the home directory (#6228), into a shared helper both providers use. Fixes #7969 * test(terminal): keep the argv test child alive through its assertion The POSIX argv test reads the terminal screen while its child can exit and dispose the parser. Keep the child alive until the assertion completes, as other screen tests do, and let the existing session cleanup terminate it. Co-authored-by: Dominic Anaeto --------- Co-authored-by: Dominic Anaeto Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../src/server/agent/providers/acp-agent.ts | 20 +- .../server/agent/providers/pi/agent.test.ts | 320 +++++++++++++++++- .../src/server/agent/providers/pi/agent.ts | 56 ++- .../providers/pi/session-descriptor.test.ts | 104 +++++- .../agent/providers/pi/session-descriptor.ts | 59 +++- .../agent/providers/pi/test-utils/fake-pi.ts | 29 ++ .../agent/providers/resume-process-cwd.ts | 26 ++ packages/server/src/terminal/terminal.test.ts | 7 +- 8 files changed, 586 insertions(+), 35 deletions(-) create mode 100644 packages/server/src/server/agent/providers/resume-process-cwd.ts diff --git a/packages/server/src/server/agent/providers/acp-agent.ts b/packages/server/src/server/agent/providers/acp-agent.ts index 6831274d2d..339c491e46 100644 --- a/packages/server/src/server/agent/providers/acp-agent.ts +++ b/packages/server/src/server/agent/providers/acp-agent.ts @@ -120,6 +120,7 @@ import { } from "../provider-launch-config.js"; import { renderPromptAttachmentAsText } from "../prompt-attachments.js"; import { appendOrReplaceGrowingAssistantMessage, runProviderTurn } from "./provider-runner.js"; +import { resolveResumeProcessCwd } from "./resume-process-cwd.js"; import { buildStringCommandShellInvocation, createStringCommandShellEnvOverlay, @@ -165,18 +166,6 @@ function rejectOnProcessFailure(child: ChildProcess, stderrChunks: string[]): Pr }); } -async function isDirectory(target: string): Promise { - try { - return (await fs.stat(target)).isDirectory(); - } catch (error) { - const code = (error as NodeJS.ErrnoException).code; - if (code === "ENOENT" || code === "ENOTDIR") { - return false; - } - throw error; - } -} - function isRecord(value: unknown): value is Record { return value != null && typeof value === "object" && !Array.isArray(value); } @@ -2883,11 +2872,8 @@ export class ACPAgentSession implements AgentSession, ACPClient { // Loading an archived agent's history runs nothing in its working directory, which // may have been removed with its worktree. session/load still names the original // directory; only the process starts from the home directory. - private async resolveProcessCwd(): Promise { - if (this.resumePurpose !== "history" || (await isDirectory(this.config.cwd))) { - return this.config.cwd; - } - return homedir(); + private resolveProcessCwd(): Promise { + return resolveResumeProcessCwd(this.config.cwd, this.resumePurpose); } private async spawnProcess(): Promise { diff --git a/packages/server/src/server/agent/providers/pi/agent.test.ts b/packages/server/src/server/agent/providers/pi/agent.test.ts index 936bdbc973..7dc3fd184c 100644 --- a/packages/server/src/server/agent/providers/pi/agent.test.ts +++ b/packages/server/src/server/agent/providers/pi/agent.test.ts @@ -5,11 +5,13 @@ import { mkdirSync, mkdtempSync, openSync, + readFileSync, readSync, + realpathSync, rmSync, writeFileSync, } from "node:fs"; -import { tmpdir } from "node:os"; +import { homedir, tmpdir } from "node:os"; import path from "node:path"; import pino from "pino"; import { setImmediate as waitForImmediate } from "node:timers/promises"; @@ -23,6 +25,7 @@ import { PiRpcAgentSession, transformPiModels, } from "./agent.js"; +import { PiCliRuntime } from "./cli-runtime.js"; import { FakePi } from "./test-utils/fake-pi.js"; import { createPiExtensionHost } from "./extensions/index.js"; import { PiExtensionHost } from "./extensions/host.js"; @@ -2719,6 +2722,7 @@ describe("PiRpcAgentClient", () => { const root = mkdtempSync(path.join(tmpdir(), "paseo-pi-import-config-")); const cwd = path.join(root, "workspace"); const sessionsDir = path.join(root, "sessions"); + mkdirSync(cwd, { recursive: true }); mkdirSync(sessionsDir, { recursive: true }); const sessionFile = path.join(sessionsDir, "20260103_session.jsonl"); writeFileSync( @@ -3532,6 +3536,320 @@ describe("PiRpcAgentClient", () => { }); }); +describe("PiRpcAgentClient history resume", () => { + const BUILTIN_MCP_COMMAND = { + name: "mcp", + source: "extension", + sourceInfo: { path: "builtin:mcp" }, + } as const; + const PASEO_MCP_SERVERS = { + paseo: { type: "http", url: "http://127.0.0.1:6767/mcp/agents" }, + } as const; + + interface ArchivedPiSession { + handle: { + provider: string; + sessionId: string; + nativeHandle: string; + metadata: { cwd: string; model?: string }; + }; + sessionFile: string; + header: Record; + body: string; + originalBytes: Buffer; + } + + function createDeletedFolder(): string { + const folder = mkdtempSync(path.join(tmpdir(), "paseo-pi-deleted-cwd-")); + rmSync(folder, { recursive: true, force: true }); + return folder; + } + + function createFileWhereFolderWas(): string { + const folder = createDeletedFolder(); + writeFileSync(folder, "not a directory"); + onTestFinished(() => rmSync(folder, { force: true })); + return folder; + } + + function createExistingFolder(): string { + const folder = mkdtempSync(path.join(tmpdir(), "paseo-pi-existing-cwd-")); + onTestFinished(() => rmSync(folder, { recursive: true, force: true })); + return folder; + } + + function writeArchivedSession(cwd: string, metadata: { model?: string } = {}): ArchivedPiSession { + const dir = mkdtempSync(path.join(tmpdir(), "paseo-pi-archived-session-")); + onTestFinished(() => rmSync(dir, { recursive: true, force: true })); + const sessionFile = path.join(dir, "2026-01-01_pi-session-1.jsonl"); + const header = { + type: "session", + version: 3, + id: "pi-session-1", + timestamp: "2026-01-01T00:00:00.000Z", + cwd, + }; + const body = [ + JSON.stringify({ + type: "message", + id: "entry-1", + parentId: null, + message: { role: "user", content: "Où est le café ☕ ?" }, + }), + JSON.stringify({ + type: "message", + id: "entry-2", + parentId: "entry-1", + message: { role: "assistant", content: [{ type: "text", text: "Dans la cuisine." }] }, + }), + ] + .map((line) => `${line}\n`) + .join(""); + writeFileSync(sessionFile, `${JSON.stringify(header)}\n${body}`); + return { + handle: { + provider: "pi", + sessionId: "pi-session-1", + nativeHandle: sessionFile, + metadata: { cwd, ...metadata }, + }, + sessionFile, + header, + body, + originalBytes: readFileSync(sessionFile), + }; + } + + function readSessionCopy(sessionFile: string): { header: unknown; body: string } { + const content = readUtf8File(sessionFile); + const headerEnd = content.indexOf("\n"); + return { + header: JSON.parse(content.slice(0, headerEnd)), + body: content.slice(headerEnd + 1), + }; + } + + function resumeArchived( + client: PiRpcAgentClient, + archived: ArchivedPiSession, + purpose: "history" | "interactive", + overrides: Partial = {}, + ): Promise { + return client.resumeSession(archived.handle, overrides, undefined, { purpose }); + } + + function writeFakePiProcess(): { + command: [string, ...string[]]; + readLaunches: () => Array<{ cwd: string; session: string | null }>; + } { + const dir = mkdtempSync(path.join(tmpdir(), "paseo-pi-process-")); + onTestFinished(() => rmSync(dir, { recursive: true, force: true })); + const scriptPath = path.join(dir, "fake-pi.cjs"); + const launchesPath = path.join(dir, "launches.jsonl"); + writeFileSync( + scriptPath, + ` +const fs = require("node:fs"); +const readline = require("node:readline"); +const [launchesPath, ...piArgs] = process.argv.slice(2); +const sessionFlag = piArgs.indexOf("--session"); +const sessionFile = sessionFlag === -1 ? null : piArgs[sessionFlag + 1]; +fs.appendFileSync(launchesPath, JSON.stringify({ cwd: process.cwd(), session: sessionFile }) + "\\n"); +if (sessionFile) { + const header = JSON.parse(fs.readFileSync(sessionFile, "utf8").split("\\n", 1)[0]); + if (header.cwd && !fs.existsSync(header.cwd)) { + fs.writeSync( + 2, + "Stored session working directory does not exist: " + header.cwd + "\\nSession file: " + sessionFile + "\\nCurrent working directory: " + process.cwd() + "\\n", + ); + process.exit(1); + } +} +const models = [ + { provider: "openrouter", id: "a" }, + { provider: "openrouter", id: "b" }, +]; +const state = { + sessionId: "pi-session-1", + sessionFile, + model: models[0], + thinkingLevel: "medium", + isStreaming: false, + isCompacting: false, + messageCount: 0, + pendingMessageCount: 0, +}; +const commands = [${JSON.stringify(BUILTIN_MCP_COMMAND)}]; +function handle(request) { + switch (request.type) { + case "get_state": + return state; + case "get_commands": + return { commands }; + case "get_available_models": + return { models }; + case "set_model": + fs.appendFileSync( + sessionFile, + JSON.stringify({ type: "model_change", id: "model-1", provider: request.provider, modelId: request.modelId }) + "\\n", + ); + state.model = models.find((model) => model.id === request.modelId); + return state.model; + default: + return {}; + } +} +readline.createInterface({ input: process.stdin }).on("line", (line) => { + const request = JSON.parse(line); + process.stdout.write( + JSON.stringify({ id: request.id, type: "response", command: request.type, success: true, data: handle(request) }) + "\\n", + ); +}); +`, + ); + return { + command: [process.execPath, scriptPath, launchesPath], + readLaunches: () => + readUtf8File(launchesPath) + .trim() + .split("\n") + .map((line) => JSON.parse(line) as { cwd: string; session: string | null }), + }; + } + + test.each([ + ["is gone", createDeletedFolder], + ["is now a file", createFileWhereFolderWas], + ])( + "a history resume of an agent whose folder %s starts Pi from the home directory on a copy of its session", + async (_folderState, createFolder) => { + const archived = writeArchivedSession(createFolder()); + const pi = new FakePi(); + + const session = await resumeArchived(createClient(pi), archived, "history"); + onTestFinished(() => session.close()); + + expect(pi.recordedLaunches).toHaveLength(1); + const launch = pi.recordedLaunches[0]!; + expect(launch.cwd).toBe(homedir()); + expect(launch.session).not.toBe(archived.sessionFile); + expect(readSessionCopy(launch.session!)).toEqual({ + header: { ...archived.header, cwd: homedir() }, + body: archived.body, + }); + }, + ); + + test("a history resume of an agent whose folder is gone removes its session copy on close and leaves the original unchanged", async () => { + const archived = writeArchivedSession(createDeletedFolder()); + const pi = new FakePi(); + + const session = await resumeArchived(createClient(pi), archived, "history"); + const sessionCopy = pi.recordedLaunches[0]!.session!; + expect(existsSync(sessionCopy)).toBe(true); + await session.close(); + + expect(existsSync(path.dirname(sessionCopy))).toBe(false); + expect(readFileSync(archived.sessionFile)).toEqual(archived.originalBytes); + }); + + test("a history resume of an agent whose folder is gone persists the original session file while Pi reports the copy", async () => { + const storedCwd = createDeletedFolder(); + const archived = writeArchivedSession(storedCwd); + const pi = new FakePi(); + + const session = await resumeArchived(createClient(pi), archived, "history"); + onTestFinished(() => session.close()); + await session.getRuntimeInfo(); + + expect(pi.latestSession().state.sessionFile).toBe(pi.recordedLaunches[0]!.session); + expect(session.describePersistence()).toMatchObject({ + nativeHandle: archived.sessionFile, + metadata: { cwd: storedCwd }, + }); + }); + + test("a history resume of an agent whose folder is gone removes its session copy when Pi fails to start", async () => { + const archived = writeArchivedSession(createDeletedFolder()); + const pi = new FakePi(); + pi.queueSessionSetup((session) => { + session.getStateError = new Error("Pi RPC process exited with code 1 and signal null"); + }); + + await expect(resumeArchived(createClient(pi), archived, "history")).rejects.toThrow( + "Pi RPC process exited with code 1", + ); + + expect(pi.recordedLaunches).toHaveLength(1); + expect(pi.recordedLaunches[0]!.session).not.toBe(archived.sessionFile); + expect(existsSync(path.dirname(pi.recordedLaunches[0]!.session!))).toBe(false); + }); + + test("a history resume of an agent whose folder is gone checks MCP support from the home directory", async () => { + const archived = writeArchivedSession(createDeletedFolder()); + const pi = new FakePi(); + pi.queueCommands([BUILTIN_MCP_COMMAND]); + + const session = await resumeArchived(createClient(pi), archived, "history", { + mcpServers: PASEO_MCP_SERVERS, + }); + onTestFinished(() => session.close()); + + expect(pi.recordedLaunches.map((launch) => launch.cwd)).toEqual([homedir(), homedir()]); + expect(session.capabilities.supportsMcpServers).toBe(true); + }); + + test("an interactive resume of an agent whose folder is gone still fails in its stored folder", async () => { + const storedCwd = createDeletedFolder(); + const archived = writeArchivedSession(storedCwd); + const pi = new FakePi(); + + await expect(resumeArchived(createClient(pi), archived, "interactive")).rejects.toThrow( + `Stored session working directory does not exist: ${storedCwd}`, + ); + + expect(pi.recordedLaunches).toMatchObject([{ cwd: storedCwd, session: archived.sessionFile }]); + }); + + test("a history resume of an agent whose folder exists keeps the stored folder and session file", async () => { + const storedCwd = createExistingFolder(); + const archived = writeArchivedSession(storedCwd); + const pi = new FakePi(); + + const session = await resumeArchived(createClient(pi), archived, "history"); + onTestFinished(() => session.close()); + + expect(pi.recordedLaunches).toMatchObject([{ cwd: storedCwd, session: archived.sessionFile }]); + }); + + test("a history resume of an agent whose folder is gone opens its session in a real Pi process started from the home directory", async () => { + const archived = writeArchivedSession(createDeletedFolder(), { model: "openrouter/b" }); + const fakePiProcess = writeFakePiProcess(); + const logger = pino({ level: "silent" }); + const client = new PiRpcAgentClient({ + logger, + runtime: new PiCliRuntime({ logger, command: fakePiProcess.command }), + }); + + const session = await resumeArchived(client, archived, "history", { + mcpServers: PASEO_MCP_SERVERS, + }); + onTestFinished(() => session.close()); + + const launches = fakePiProcess.readLaunches(); + const home = realpathSync.native(homedir()); + expect(launches.map((launch) => realpathSync.native(launch.cwd))).toEqual([home, home]); + expect(session.capabilities.supportsMcpServers).toBe(true); + const sessionCopy = launches[1]!.session!; + expect(readUtf8File(sessionCopy)).toContain('"type":"model_change"'); + expect(session.describePersistence()?.nativeHandle).toBe(archived.sessionFile); + + await session.close(); + expect(existsSync(path.dirname(sessionCopy))).toBe(false); + expect(readFileSync(archived.sessionFile)).toEqual(archived.originalBytes); + }); +}); + describe("transformPiModels", () => { test("normalizes labels that include the upstream provider prefix", () => { expect( diff --git a/packages/server/src/server/agent/providers/pi/agent.ts b/packages/server/src/server/agent/providers/pi/agent.ts index 9474e98cc8..8051c57fa9 100644 --- a/packages/server/src/server/agent/providers/pi/agent.ts +++ b/packages/server/src/server/agent/providers/pi/agent.ts @@ -2,7 +2,7 @@ import { mapCustomMessageToToolCall } from "../custom-message.js"; import { randomUUID } from "node:crypto"; import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { homedir, tmpdir } from "node:os"; -import { join, resolve as resolvePath } from "node:path"; +import { basename, join, resolve as resolvePath } from "node:path"; import type { Logger } from "pino"; import stripAnsi from "strip-ansi"; import { z } from "zod"; @@ -22,6 +22,7 @@ import { type AgentPersistenceHandle, type AgentPromptInput, type AgentProvider, + type AgentResumeSessionOptions, type AgentRunOptions, type AgentRunResult, type AgentRuntimeInfo, @@ -75,8 +76,13 @@ import { piExtensionRuntimeBridge, type PiExtensionEventOutput, } from "./extensions/index.js"; +import { resolveResumeProcessCwd } from "../resume-process-cwd.js"; import { revertPiConversation } from "./rewind.js"; -import { listPiImportableSessions, readPiImportSessionConfig } from "./session-descriptor.js"; +import { + copyPiSessionFileWithCwd, + listPiImportableSessions, + readPiImportSessionConfig, +} from "./session-descriptor.js"; import type { PiRuntime, PiRuntimeSession, PiStartSessionInput } from "./runtime.js"; import type { PiAgentSessionEvent, @@ -245,6 +251,7 @@ interface PiRpcAgentSessionOptions { initialState: PiSessionState; capabilities: AgentCapabilityFlags; currentModeId?: string | null; + persistedSessionFile?: string; cleanup?: () => void; extensionTimeoutMs?: number; logger: Logger; @@ -492,13 +499,14 @@ function buildResumeConfig( function buildResumeStartInput(input: { resumeConfig: PiResumeConfig; + processCwd: string; sessionFile: string; launchContext: AgentLaunchContext | undefined; mcpConfigFile: PiTempFile | null; paseoExtension: PiTempFile | null; }): PiStartSessionInput { return { - cwd: input.resumeConfig.cwd, + cwd: input.processCwd, env: input.launchContext?.env, session: input.sessionFile, thinkingOptionId: normalizePiThinkingOption(input.resumeConfig.thinkingOptionId) ?? undefined, @@ -618,6 +626,19 @@ function createPiMcpConfigFile( }; } +async function createPiSessionCopy(sessionFile: string, cwd: string): Promise { + const dir = mkdtempSync(join(tmpdir(), "paseo-pi-session-")); + const cleanup = () => rmSync(dir, { recursive: true, force: true }); + const filePath = join(dir, basename(sessionFile)); + try { + await copyPiSessionFileWithCwd({ sourceFile: sessionFile, targetFile: filePath, cwd }); + } catch (error) { + cleanup(); + throw error; + } + return { path: filePath, cleanup }; +} + function createPiPaseoExtensionFile({ systemPrompt, mcpServers = {}, @@ -1232,6 +1253,7 @@ export class PiRpcAgentSession implements AgentSession { this.capabilities = options.capabilities; this.provider = PI_PROVIDER; this.currentModeId = options.currentModeId ?? null; + this.persistedSessionFile = options.persistedSessionFile; this.cleanup = options.cleanup; this.extensionTimeoutMs = options.extensionTimeoutMs ?? DEFAULT_PI_EXTENSION_RESULT_TIMEOUT_MS; this.logger = options.logger; @@ -1262,6 +1284,7 @@ export class PiRpcAgentSession implements AgentSession { private readonly runtimeSession: PiRuntimeSession; private readonly config: AgentSessionConfig; + private readonly persistedSessionFile?: string; private readonly cleanup?: () => void; private readonly extensionTimeoutMs: number; @@ -1496,7 +1519,7 @@ export class PiRpcAgentSession implements AgentSession { return { provider: this.provider, sessionId: this.state.sessionId, - nativeHandle: this.state.sessionFile, + nativeHandle: this.persistedSessionFile ?? this.state.sessionFile, metadata: { cwd: this.config.cwd, ...(this.config.model ? { model: this.config.model } : {}), @@ -2645,6 +2668,7 @@ export class PiRpcAgentClient implements AgentClient { handle: AgentPersistenceHandle, overrides?: Partial, launchContext?: AgentLaunchContext, + options?: AgentResumeSessionOptions, ): Promise { const sessionFile = handle.nativeHandle; if (!sessionFile) { @@ -2653,6 +2677,7 @@ export class PiRpcAgentClient implements AgentClient { const persistenceMetadata = parsePersistenceMetadata(handle.metadata); const resumeConfig = buildResumeConfig(persistenceMetadata, overrides, this.provider); + const processCwd = await resolveResumeProcessCwd(resumeConfig.cwd, options?.purpose); const providerOptions = PiProviderOptionsSchema.parse( resumeConfig.config.providerOptions ?? {}, @@ -2663,7 +2688,7 @@ export class PiRpcAgentClient implements AgentClient { ...launchContext?.env, }; const mcp = await this.prepareMcpInjection( - resumeConfig.cwd, + processCwd, resumeConfig.config.mcpServers, mcpEnv, runtime, @@ -2676,20 +2701,29 @@ export class PiRpcAgentClient implements AgentClient { ), mcpServers: mcp?.kind === "builtin" ? mcp.servers : undefined, }); + const tempFiles = mcpConfigFile ? [mcpConfigFile, paseoExtension] : [paseoExtension]; + const cleanupTempFiles = () => { + for (const tempFile of tempFiles) tempFile.cleanup(); + }; + let sessionCopy: PiTempFile | null = null; let runtimeSession: PiRuntimeSession; try { + if (processCwd !== resumeConfig.cwd) { + sessionCopy = await createPiSessionCopy(sessionFile, processCwd); + tempFiles.push(sessionCopy); + } runtimeSession = await runtime.startSession( buildResumeStartInput({ resumeConfig, - sessionFile, + processCwd, + sessionFile: sessionCopy?.path ?? sessionFile, launchContext, mcpConfigFile, paseoExtension, }), ); } catch (error) { - mcpConfigFile?.cleanup(); - paseoExtension?.cleanup(); + cleanupTempFiles(); throw error; } try { @@ -2702,15 +2736,15 @@ export class PiRpcAgentClient implements AgentClient { }, initialState, capabilities: capabilitiesForSession(mcp !== null), - cleanup: combineCleanup([mcpConfigFile?.cleanup, paseoExtension?.cleanup]), + persistedSessionFile: sessionCopy ? sessionFile : undefined, + cleanup: cleanupTempFiles, extensionTimeoutMs: providerOptions.extensionTimeoutMs, logger: this.logger, usagePollScheduler: this.usagePollScheduler, }); } catch (error) { await runtimeSession.close().catch(() => undefined); - mcpConfigFile?.cleanup(); - paseoExtension?.cleanup(); + cleanupTempFiles(); throw error; } } diff --git a/packages/server/src/server/agent/providers/pi/session-descriptor.test.ts b/packages/server/src/server/agent/providers/pi/session-descriptor.test.ts index 280b558739..c6b0df5dbf 100644 --- a/packages/server/src/server/agent/providers/pi/session-descriptor.test.ts +++ b/packages/server/src/server/agent/providers/pi/session-descriptor.test.ts @@ -1,9 +1,13 @@ -import { mkdtemp, mkdir, utimes, writeFile } from "node:fs/promises"; +import { mkdtemp, mkdir, readFile, rm, utimes, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; -import { expect, test } from "vitest"; +import { expect, onTestFinished, test } from "vitest"; -import { listPiImportableSessions, readPiImportSessionConfig } from "./session-descriptor.js"; +import { + copyPiSessionFileWithCwd, + listPiImportableSessions, + readPiImportSessionConfig, +} from "./session-descriptor.js"; async function writeSession(root: string, lines: unknown[]): Promise { const sessionsDir = path.join(root, "sessions", "project"); @@ -216,3 +220,97 @@ test("Pi import config preserves thinking before a later model in large sessions thinkingOptionId: "low", }); }); + +test("a Pi session copy names the new cwd in its header and keeps every later byte", async () => { + const root = await mkdtemp(path.join(tmpdir(), "paseo-pi-session-copy-")); + onTestFinished(() => rm(root, { recursive: true, force: true })); + const header = { + type: "session", + version: 3, + id: "pi-session-1", + timestamp: "2026-01-01T00:00:00.000Z", + cwd: path.join(root, "removed-worktree"), + }; + const body = Buffer.from( + Array.from( + { length: 2_000 }, + (_, index) => + `${JSON.stringify({ type: "message", id: `entry-${index}`, message: { role: "user", content: `café ☕ ${index}` } })}\n`, + ).join(""), + ); + expect(body.length).toBeGreaterThan(64 * 1024); + const sourceFile = path.join(root, "source.jsonl"); + const targetFile = path.join(root, "copy.jsonl"); + await writeFile(sourceFile, Buffer.concat([Buffer.from(`${JSON.stringify(header)}\n`), body])); + + await copyPiSessionFileWithCwd({ sourceFile, targetFile, cwd: "/home/user" }); + + const copy = await readFile(targetFile); + const headerEnd = copy.indexOf(0x0a); + expect(JSON.parse(copy.subarray(0, headerEnd).toString("utf8"))).toEqual({ + ...header, + cwd: "/home/user", + }); + expect(copy.subarray(headerEnd + 1).equals(body)).toBe(true); +}); + +test("a Pi session copy refuses a file without a session header", async () => { + const root = await mkdtemp(path.join(tmpdir(), "paseo-pi-session-copy-")); + onTestFinished(() => rm(root, { recursive: true, force: true })); + const sourceFile = path.join(root, "source.jsonl"); + await writeFile(sourceFile, `${JSON.stringify({ type: "message", id: "entry-1" })}\n`); + + await expect( + copyPiSessionFileWithCwd({ sourceFile, targetFile: path.join(root, "copy.jsonl"), cwd: "/" }), + ).rejects.toThrow(`Pi session file has no session header: ${sourceFile}`); +}); + +const COPY_BODY = [ + { type: "message", id: "entry-1", message: { role: "user", content: "café ☕" } }, + { type: "message", id: "entry-2", message: { role: "assistant", content: "Dans la cuisine." } }, +] + .map((entry) => `${JSON.stringify(entry)}\n`) + .join(""); + +const COPY_HEADER = { + type: "session", + version: 3, + id: "pi-session-1", + timestamp: "2026-01-01T00:00:00.000Z", + cwd: "/removed-worktree", +}; + +async function copySessionContent(content: string): Promise { + const root = await mkdtemp(path.join(tmpdir(), "paseo-pi-session-copy-")); + onTestFinished(() => rm(root, { recursive: true, force: true })); + const sourceFile = path.join(root, "source.jsonl"); + const targetFile = path.join(root, "copy.jsonl"); + await writeFile(sourceFile, content); + await copyPiSessionFileWithCwd({ sourceFile, targetFile, cwd: "/home/user" }); + return readFile(targetFile); +} + +test.each([ + ["a header line longer than 64 KiB", "", { ...COPY_HEADER, padding: "x".repeat(70 * 1024) }], + ["a header with an empty cwd", "", { ...COPY_HEADER, cwd: "" }], + ["blank lines before the header", "\n\r\n", COPY_HEADER], +])("a Pi session copy accepts %s", async (_headerShape, prefix, header) => { + const copy = await copySessionContent(`${prefix}${JSON.stringify(header)}\n${COPY_BODY}`); + + const headerEnd = copy.indexOf(0x0a); + expect(JSON.parse(copy.subarray(0, headerEnd).toString("utf8"))).toEqual({ + ...header, + cwd: "/home/user", + }); + expect(copy.subarray(headerEnd + 1).equals(Buffer.from(COPY_BODY))).toBe(true); +}); + +test("a Pi session copy reports a missing session file", async () => { + const root = await mkdtemp(path.join(tmpdir(), "paseo-pi-session-copy-")); + onTestFinished(() => rm(root, { recursive: true, force: true })); + const sourceFile = path.join(root, "missing.jsonl"); + + await expect( + copyPiSessionFileWithCwd({ sourceFile, targetFile: path.join(root, "copy.jsonl"), cwd: "/" }), + ).rejects.toThrow(`Pi session file is missing: ${sourceFile}`); +}); diff --git a/packages/server/src/server/agent/providers/pi/session-descriptor.ts b/packages/server/src/server/agent/providers/pi/session-descriptor.ts index 01f55bc0ce..6c0cc300f2 100644 --- a/packages/server/src/server/agent/providers/pi/session-descriptor.ts +++ b/packages/server/src/server/agent/providers/pi/session-descriptor.ts @@ -1,7 +1,8 @@ -import type { Dirent } from "node:fs"; -import { open, readdir, readFile, stat } from "node:fs/promises"; +import { createReadStream, createWriteStream, type Dirent } from "node:fs"; +import { open, readdir, readFile, stat, writeFile } from "node:fs/promises"; import { homedir } from "node:os"; import path from "node:path"; +import { pipeline } from "node:stream/promises"; import type { ImportableProviderSession, @@ -18,6 +19,7 @@ const PI_SESSION_DIR_ENV = "PI_CODING_AGENT_SESSION_DIR"; const HEAD_BYTES = 64 * 1024; const TAIL_BYTES = 256 * 1024; const FULL_SCAN_LINE_LIMIT = 2_000; +const PI_SESSION_HEADER_SCAN_BYTES = 1024 * 1024; // Rank all discovered files cheaply, then parse only a bounded recent window. const IMPORT_CANDIDATE_OVERSCAN = 40; const IMPORT_CANDIDATE_MIN = 400; @@ -100,6 +102,59 @@ export async function listPiImportableSessions( ); } +export async function copyPiSessionFileWithCwd(input: { + sourceFile: string; + targetFile: string; + cwd: string; +}): Promise { + const found = findSessionHeaderLine( + await readSessionFileStart(input.sourceFile, PI_SESSION_HEADER_SCAN_BYTES), + ); + if (!found) { + throw new Error(`Pi session file has no session header: ${input.sourceFile}`); + } + await writeFile(input.targetFile, `${JSON.stringify({ ...found.header, cwd: input.cwd })}\n`, { + mode: 0o600, + }); + await pipeline( + createReadStream(input.sourceFile, { start: found.bodyStart }), + createWriteStream(input.targetFile, { flags: "a" }), + ); +} + +function findSessionHeaderLine( + scanned: Buffer, +): { header: Record; bodyStart: number } | null { + let lineStart = 0; + while (lineStart < scanned.length) { + const newline = scanned.indexOf(0x0a, lineStart); + const bodyStart = newline === -1 ? scanned.length : newline + 1; + const line = scanned.subarray(lineStart, bodyStart).toString("utf8").trim(); + if (line) { + const header = parseJsonRecord(line); + return header?.type === "session" ? { header, bodyStart } : null; + } + lineStart = bodyStart; + } + return null; +} + +async function readSessionFileStart(filePath: string, maxBytes: number): Promise { + const handle = await open(filePath, "r").catch((error: unknown) => { + if ((error as NodeJS.ErrnoException).code === "ENOENT") { + throw new Error(`Pi session file is missing: ${filePath}`); + } + throw error; + }); + try { + const buffer = Buffer.alloc(maxBytes); + const { bytesRead } = await handle.read(buffer, 0, maxBytes, 0); + return buffer.subarray(0, bytesRead); + } finally { + await handle.close().catch(() => undefined); + } +} + export async function readPiImportSessionConfig(filePath: string): Promise { const descriptor = await readPiSessionDescriptor(filePath); if (!descriptor) return {}; diff --git a/packages/server/src/server/agent/providers/pi/test-utils/fake-pi.ts b/packages/server/src/server/agent/providers/pi/test-utils/fake-pi.ts index 983b86c19d..90a80e4c66 100644 --- a/packages/server/src/server/agent/providers/pi/test-utils/fake-pi.ts +++ b/packages/server/src/server/agent/providers/pi/test-utils/fake-pi.ts @@ -1,3 +1,5 @@ +import { existsSync, readFileSync } from "node:fs"; + import type { PiRuntime, PiRuntimeLaunch, @@ -75,6 +77,12 @@ export class FakePi implements PiRuntime { const session = new FakePiSession(launch, this.removedModels); session.commands = this.queuedCommands.shift() ?? []; this.queuedSessionSetups.shift()?.(session); + const missingSessionCwd = launch.noSession ? null : readMissingSessionCwd(launch.session); + if (missingSessionCwd !== null) { + session.getStateError = new Error( + `Pi RPC process exited with code 1 and signal null\nStored session working directory does not exist: ${missingSessionCwd}\nSession file: ${launch.session}\nCurrent working directory: ${launch.cwd}`, + ); + } this.sessions.push(session); return session; } @@ -101,6 +109,27 @@ export class FakePi implements PiRuntime { } } +function readMissingSessionCwd(sessionFile: string | undefined): string | null { + if (!sessionFile || !existsSync(sessionFile)) { + return null; + } + const [headerLine = ""] = readFileSync(sessionFile, "utf8").split("\n", 1); + let header: unknown; + try { + header = JSON.parse(headerLine); + } catch { + return null; + } + if (typeof header !== "object" || header === null || !("cwd" in header)) { + return null; + } + const { type, cwd } = header as { type?: unknown; cwd?: unknown }; + if (type !== "session" || typeof cwd !== "string" || !cwd || existsSync(cwd)) { + return null; + } + return cwd; +} + export class FakePiSession implements PiRuntimeSession { readonly environment: Record; readonly prompts: Array<{ message: string; imageCount: number }> = []; diff --git a/packages/server/src/server/agent/providers/resume-process-cwd.ts b/packages/server/src/server/agent/providers/resume-process-cwd.ts new file mode 100644 index 0000000000..d32637a9a6 --- /dev/null +++ b/packages/server/src/server/agent/providers/resume-process-cwd.ts @@ -0,0 +1,26 @@ +import { stat } from "node:fs/promises"; +import { homedir } from "node:os"; + +import type { AgentResumePurpose } from "../agent-sdk-types.js"; + +export async function resolveResumeProcessCwd( + cwd: string, + purpose: AgentResumePurpose | undefined, +): Promise { + if (purpose !== "history" || (await isDirectory(cwd))) { + return cwd; + } + return homedir(); +} + +async function isDirectory(target: string): Promise { + try { + return (await stat(target)).isDirectory(); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code === "ENOENT" || code === "ENOTDIR") { + return false; + } + throw error; + } +} diff --git a/packages/server/src/terminal/terminal.test.ts b/packages/server/src/terminal/terminal.test.ts index e4f8544050..3d1fcca545 100644 --- a/packages/server/src/terminal/terminal.test.ts +++ b/packages/server/src/terminal/terminal.test.ts @@ -410,7 +410,12 @@ describe("createTerminal", () => { cwd: realpathSync(tmpdir()), cols: 500, command: process.execPath, - args: ["-e", "process.stdout.write(JSON.stringify(process.argv.slice(1)))", nastyPrompt], + // Keep the PTY alive until the screen assertion; exit disposes its parser. + args: [ + "-e", + "process.stdout.write(JSON.stringify(process.argv.slice(1))); setInterval(() => {}, 100000)", + nastyPrompt, + ], }), ); From fa89738e3a937e83d10b8998ee0d96f3708947dd Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sun, 1 Nov 2026 14:46:52 +0700 Subject: [PATCH 169/173] chore(desktop): upgrade packaging tool and remove signing backport (#8450) * chore(desktop): upgrade packaging tool and remove signing backport * fix(nix): resolve the desktop workspace packaging tool --- .github/workflows/desktop-release.yml | 26 - nix/desktop-package.nix | 2 +- nix/npm-deps.hash | 2 +- package-lock.json | 2313 +++++++++++-------------- packages/desktop/package.json | 2 +- scripts/ci-workflow.test.mjs | 83 +- 6 files changed, 1060 insertions(+), 1368 deletions(-) diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.yml index bdbeb9f139..26be12291b 100644 --- a/.github/workflows/desktop-release.yml +++ b/.github/workflows/desktop-release.yml @@ -135,32 +135,6 @@ jobs: env: NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - # Backport electron-builder#10172 to the pinned build tool only. - # Remove this step when app-builder-lib is upgraded to a release containing it. - - name: Repair temporary keychain password in signing tool - shell: bash - run: | - node <<'KEYCHAIN_FIX' - const fs = require('node:fs'); - const path = require('node:path'); - const manifestPath = require.resolve('app-builder-lib/package.json'); - if (JSON.parse(fs.readFileSync(manifestPath, 'utf8')).version !== '26.8.1') { - throw new Error('Reassess/remove the signing backport for the new app-builder-lib version'); - } - const sourcePath = path.join(path.dirname(manifestPath), 'out/codeSign/macCodeSign.js'); - let source = fs.readFileSync(sourcePath, 'utf8'); - const replacements = [ - ['importCerts(keychainFile, certPaths, cscPasswords)', 'importCerts(keychainFile, certPaths, cscPasswords, keychainPassword)'], - ['importCerts(keychainFile, paths, keyPasswords)', 'importCerts(keychainFile, paths, keyPasswords, keychainPassword)'], - ['["set-key-partition-list", "-S", "apple-tool:,apple:", "-s", "-k", password, keychainFile]', '["set-key-partition-list", "-S", "apple-tool:,apple:", "-s", "-k", keychainPassword, keychainFile]'], - ]; - for (const [before, after] of replacements) { - if (source.split(before).length !== 2) throw new Error('Unexpected signing tool source; refusing to patch'); - source = source.replace(before, after); - } - fs.writeFileSync(sourcePath, source); - KEYCHAIN_FIX - - name: Set desktop package version from tag shell: bash run: | diff --git a/nix/desktop-package.nix b/nix/desktop-package.nix index 00ed6cd926..48cbd9bbb7 100644 --- a/nix/desktop-package.nix +++ b/nix/desktop-package.nix @@ -127,7 +127,7 @@ buildNpmPackage { # The Nix output is not a distributable DMG, so leave it unsigned and # disable the hardened runtime that requires a matching signature. CSC_IDENTITY_AUTO_DISCOVERY=false \ - ../../node_modules/.bin/electron-builder \ + npm exec --offline -- electron-builder \ --config electron-builder.yml \ --dir \ --mac \ diff --git a/nix/npm-deps.hash b/nix/npm-deps.hash index 3efbb30b52..7e151568f6 100644 --- a/nix/npm-deps.hash +++ b/nix/npm-deps.hash @@ -1 +1 @@ -sha256-CeT2PtYIAFwvBC9LIku8VkTl0pvKxYzSCn0QW2ManfU= +sha256-KN/AVZV/o0TleLLpmggSrdJqjFDJ/NJYVHiC54xb4jQ= diff --git a/package-lock.json b/package-lock.json index 4b9481ff8e..dbb64e68a4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2788,58 +2788,6 @@ "@jridgewell/sourcemap-codec": "^1.4.10" } }, - "node_modules/@develar/schema-utils": { - "version": "2.6.5", - "resolved": "https://registry.npmjs.org/@develar/schema-utils/-/schema-utils-2.6.5.tgz", - "integrity": "sha512-0cp4PsWQ/9avqTVMCtZ+GirikIA36ikvjtHweU4/j8yLtgObI0+JUPhYFScgwlteveGB1rt3Cm8UhN04XayDig==", - "dev": true, - "license": "MIT", - "dependencies": { - "ajv": "^6.12.0", - "ajv-keywords": "^3.4.1" - }, - "engines": { - "node": ">= 8.9.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/webpack" - } - }, - "node_modules/@develar/schema-utils/node_modules/ajv": { - "version": "6.14.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz", - "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==", - "dev": true, - "license": "MIT", - "dependencies": { - "fast-deep-equal": "^3.1.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/@develar/schema-utils/node_modules/ajv-keywords": { - "version": "3.5.2", - "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz", - "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "ajv": "^6.9.1" - } - }, - "node_modules/@develar/schema-utils/node_modules/json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true, - "license": "MIT" - }, "node_modules/@dnd-kit/accessibility": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz", @@ -3131,84 +3079,6 @@ "url": "https://github.com/sponsors/gjtorikian/" } }, - "node_modules/@electron/rebuild": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/@electron/rebuild/-/rebuild-4.0.3.tgz", - "integrity": "sha512-u9vpTHRMkOYCs/1FLiSVAFZ7FbjsXK+bQuzviJZa+lG7BHZl1nz52/IcGvwa3sk80/fc3llutBkbCq10Vh8WQA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@malept/cross-spawn-promise": "^2.0.0", - "debug": "^4.1.1", - "detect-libc": "^2.0.1", - "got": "^11.7.0", - "graceful-fs": "^4.2.11", - "node-abi": "^4.2.0", - "node-api-version": "^0.2.1", - "node-gyp": "^11.2.0", - "ora": "^5.1.0", - "read-binary-file-arch": "^1.0.6", - "semver": "^7.3.5", - "tar": "^7.5.6", - "yargs": "^17.0.1" - }, - "bin": { - "electron-rebuild": "lib/cli.js" - }, - "engines": { - "node": ">=22.12.0" - } - }, - "node_modules/@electron/rebuild/node_modules/chownr": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", - "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" - } - }, - "node_modules/@electron/rebuild/node_modules/minizlib": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", - "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", - "dev": true, - "license": "MIT", - "dependencies": { - "minipass": "^7.1.2" - }, - "engines": { - "node": ">= 18" - } - }, - "node_modules/@electron/rebuild/node_modules/tar": { - "version": "7.5.12", - "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.12.tgz", - "integrity": "sha512-9TsuLcdhOn4XztcQqhNyq1KOwOOED/3k58JAvtULiYqbO8B/0IBAAIE1hj0Svmm58k27TmcigyDI0deMlgG3uw==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "@isaacs/fs-minipass": "^4.0.0", - "chownr": "^3.0.0", - "minipass": "^7.1.2", - "minizlib": "^3.1.0", - "yallist": "^5.0.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@electron/rebuild/node_modules/yallist": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", - "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" - } - }, "node_modules/@electron/universal": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/@electron/universal/-/universal-2.0.3.tgz", @@ -3259,6 +3129,45 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/@electron/windows-sign": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/@electron/windows-sign/-/windows-sign-1.2.2.tgz", + "integrity": "sha512-dfZeox66AvdPtb2lD8OsIIQh12Tp0GNCRUDfBHIKGpbmopZto2/A8nSpYYLoedPIHpqkeblZ/k8OV0Gy7PYuyQ==", + "dev": true, + "license": "BSD-2-Clause", + "optional": true, + "peer": true, + "dependencies": { + "cross-dirname": "^0.1.0", + "debug": "^4.3.4", + "fs-extra": "^11.1.1", + "minimist": "^1.2.8", + "postject": "^1.0.0-alpha.6" + }, + "bin": { + "electron-windows-sign": "bin/electron-windows-sign.js" + }, + "engines": { + "node": ">=14.14" + } + }, + "node_modules/@electron/windows-sign/node_modules/fs-extra": { + "version": "11.4.1", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.1.tgz", + "integrity": "sha512-KYAb4c9BJQI6QqGKthV68OHe0badztdXJWKo0WtBA9IuCFPTKvE5ZdUBglP833aMjhaSPNO4A5j/EkzZtGlKjA==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=14.14" + } + }, "node_modules/@emnapi/core": { "version": "1.8.1", "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.8.1.tgz", @@ -9135,81 +9044,6 @@ "node": ">=12.4.0" } }, - "node_modules/@npmcli/agent": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@npmcli/agent/-/agent-3.0.0.tgz", - "integrity": "sha512-S79NdEgDQd/NGCay6TCoVzXSj74skRZIKJcpJjC5lOq34SZzyI6MqtiiWoiVWoVrTcGjNeC4ipbh1VIHlpfF5Q==", - "dev": true, - "license": "ISC", - "dependencies": { - "agent-base": "^7.1.0", - "http-proxy-agent": "^7.0.0", - "https-proxy-agent": "^7.0.1", - "lru-cache": "^10.0.1", - "socks-proxy-agent": "^8.0.3" - }, - "engines": { - "node": "^18.17.0 || >=20.5.0" - } - }, - "node_modules/@npmcli/agent/node_modules/agent-base": { - "version": "7.1.4", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", - "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 14" - } - }, - "node_modules/@npmcli/agent/node_modules/http-proxy-agent": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", - "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", - "dev": true, - "license": "MIT", - "dependencies": { - "agent-base": "^7.1.0", - "debug": "^4.3.4" - }, - "engines": { - "node": ">= 14" - } - }, - "node_modules/@npmcli/agent/node_modules/https-proxy-agent": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", - "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", - "dev": true, - "license": "MIT", - "dependencies": { - "agent-base": "^7.1.2", - "debug": "4" - }, - "engines": { - "node": ">= 14" - } - }, - "node_modules/@npmcli/agent/node_modules/lru-cache": { - "version": "10.4.3", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", - "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", - "dev": true, - "license": "ISC" - }, - "node_modules/@npmcli/fs": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/@npmcli/fs/-/fs-4.0.0.tgz", - "integrity": "sha512-/xGlezI6xfGO9NwuJlnwz/K14qD1kCSAGtacBHnGzeAIuJGazcp45KP5NuyARXoKb7cwulAGWVsbeSxdG/cb0Q==", - "dev": true, - "license": "ISC", - "dependencies": { - "semver": "^7.3.5" - }, - "engines": { - "node": "^18.17.0 || >=20.5.0" - } - }, "node_modules/@oclif/core": { "version": "1.26.2", "resolved": "https://registry.npmjs.org/@oclif/core/-/core-1.26.2.tgz", @@ -10499,6 +10333,61 @@ "node": "^20.19.0 || >=22.12.0" } }, + "node_modules/@peculiar/asn1-schema": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-2.11.1.tgz", + "integrity": "sha512-jaU9OaCcbZUdyXx9hMETZB9xoNmxTGjOGFqd3cOwKFkpKnyKd9WxF3uqj4PvX4cyOMP9bSdHg5YyML2qtx/d/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@peculiar/utils": "^2.0.2", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/json-schema": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/@peculiar/json-schema/-/json-schema-1.1.12.tgz", + "integrity": "sha512-coUfuoMeIB7B8/NMekxaDzLhaYmp0HZNPEjYRm9goRou8UZIC3z21s0sL9AWoCw4EG876QyO3kYrc61WNF9B/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@peculiar/utils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@peculiar/utils/-/utils-2.0.3.tgz", + "integrity": "sha512-+oL3HPFRIZ1St2K50lWCXiioIgSoxzz7R1J3uF6neO2yl1sgmpgY6XXJH4BdpoDkMWznQTeYF6oWNDZLCdQ4eQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "^2.8.1" + } + }, + "node_modules/@peculiar/webcrypto": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/@peculiar/webcrypto/-/webcrypto-1.7.2.tgz", + "integrity": "sha512-ktTSACRJ5WdpfjHjFT2EWJQQPacGv1cPCDfEbdmpAHOxdFiYqPe4lfnXGA3D8Dg9/0kHPYSvyRlgujIOVlTdvQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.7.0", + "@peculiar/json-schema": "^1.1.12", + "@peculiar/utils": "^2.0.2", + "tslib": "^2.8.1", + "webcrypto-core": "^1.9.2" + }, + "engines": { + "node": ">=14.18.0" + } + }, "node_modules/@pinojs/redact": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz", @@ -13470,18 +13359,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/plist": { - "version": "3.0.5", - "resolved": "https://registry.npmjs.org/@types/plist/-/plist-3.0.5.tgz", - "integrity": "sha512-E6OCaRmAe4WDmWNsL/9RMqdkkzDCY1etutkflWk4c+AcjDU07Pcz1fQwTX0TQz+Pxqn9i4L1TU3UFpjnrcDgxA==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@types/node": "*", - "xmlbuilder": ">=11.0.1" - } - }, "node_modules/@types/prop-types": { "version": "15.7.15", "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz", @@ -13632,14 +13509,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/verror": { - "version": "1.10.11", - "resolved": "https://registry.npmjs.org/@types/verror/-/verror-1.10.11.tgz", - "integrity": "sha512-RlDm9K7+o5stv0Co8i8ZRGxDbrTxhJtgjqjFyVh/tXQyl/rYtTKlnTvZ88oSTeYREWurwx20Js4kTuKCsFkUtg==", - "dev": true, - "license": "MIT", - "optional": true - }, "node_modules/@types/ws": { "version": "8.18.1", "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz", @@ -14798,13 +14667,6 @@ "dev": true, "license": "BSD-2-Clause" }, - "node_modules/7zip-bin": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/7zip-bin/-/7zip-bin-5.2.0.tgz", - "integrity": "sha512-ukTPVhqG4jNzMro2qA9HSCSSVJN3aN7tlb+hfqYCt3ER0yWroeA2VR38MNrOHLQ/cVj+DaIMad0kFCtWWowh/A==", - "dev": true, - "license": "MIT" - }, "node_modules/abab": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/abab/-/abab-2.0.6.tgz", @@ -15089,276 +14951,6 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, - "node_modules/app-builder-bin": { - "version": "5.0.0-alpha.12", - "resolved": "https://registry.npmjs.org/app-builder-bin/-/app-builder-bin-5.0.0-alpha.12.tgz", - "integrity": "sha512-j87o0j6LqPL3QRr8yid6c+Tt5gC7xNfYo6uQIQkorAC6MpeayVMZrEDzKmJJ/Hlv7EnOQpaRm53k6ktDYZyB6w==", - "dev": true, - "license": "MIT" - }, - "node_modules/app-builder-lib": { - "version": "26.8.1", - "resolved": "https://registry.npmjs.org/app-builder-lib/-/app-builder-lib-26.8.1.tgz", - "integrity": "sha512-p0Im/Dx5C4tmz8QEE1Yn4MkuPC8PrnlRneMhWJj7BBXQfNTJUshM/bp3lusdEsDbvvfJZpXWnYesgSLvwtM2Zw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@develar/schema-utils": "~2.6.5", - "@electron/asar": "3.4.1", - "@electron/fuses": "^1.8.0", - "@electron/get": "^3.0.0", - "@electron/notarize": "2.5.0", - "@electron/osx-sign": "1.3.3", - "@electron/rebuild": "^4.0.3", - "@electron/universal": "2.0.3", - "@malept/flatpak-bundler": "^0.4.0", - "@types/fs-extra": "9.0.13", - "async-exit-hook": "^2.0.1", - "builder-util": "26.8.1", - "builder-util-runtime": "9.5.1", - "chromium-pickle-js": "^0.2.0", - "ci-info": "4.3.1", - "debug": "^4.3.4", - "dotenv": "^16.4.5", - "dotenv-expand": "^11.0.6", - "ejs": "^3.1.8", - "electron-publish": "26.8.1", - "fs-extra": "^10.1.0", - "hosted-git-info": "^4.1.0", - "isbinaryfile": "^5.0.0", - "jiti": "^2.4.2", - "js-yaml": "^4.1.0", - "json5": "^2.2.3", - "lazy-val": "^1.0.5", - "minimatch": "^10.0.3", - "plist": "3.1.0", - "proper-lockfile": "^4.1.2", - "resedit": "^1.7.0", - "semver": "~7.7.3", - "tar": "^7.5.7", - "temp-file": "^3.4.0", - "tiny-async-pool": "1.3.0", - "which": "^5.0.0" - }, - "engines": { - "node": ">=14.0.0" - }, - "peerDependencies": { - "dmg-builder": "26.8.1", - "electron-builder-squirrel-windows": "26.8.1" - } - }, - "node_modules/app-builder-lib/node_modules/@electron/get": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/@electron/get/-/get-3.1.0.tgz", - "integrity": "sha512-F+nKc0xW+kVbBRhFzaMgPy3KwmuNTYX1fx6+FxxoSnNgwYX6LD7AKBTWkU0MQ6IBoe7dz069CNkR673sPAgkCQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "debug": "^4.1.1", - "env-paths": "^2.2.0", - "fs-extra": "^8.1.0", - "got": "^11.8.5", - "progress": "^2.0.3", - "semver": "^6.2.0", - "sumchecker": "^3.0.1" - }, - "engines": { - "node": ">=14" - }, - "optionalDependencies": { - "global-agent": "^3.0.0" - } - }, - "node_modules/app-builder-lib/node_modules/@electron/get/node_modules/fs-extra": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz", - "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==", - "dev": true, - "license": "MIT", - "dependencies": { - "graceful-fs": "^4.2.0", - "jsonfile": "^4.0.0", - "universalify": "^0.1.0" - }, - "engines": { - "node": ">=6 <7 || >=8" - } - }, - "node_modules/app-builder-lib/node_modules/@electron/get/node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - } - }, - "node_modules/app-builder-lib/node_modules/balanced-match": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", - "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", - "dev": true, - "license": "MIT", - "engines": { - "node": "18 || 20 || >=22" - } - }, - "node_modules/app-builder-lib/node_modules/brace-expansion": { - "version": "5.0.4", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.4.tgz", - "integrity": "sha512-h+DEnpVvxmfVefa4jFbCf5HdH5YMDXRsmKflpf1pILZWRFlTbJpxeU55nJl4Smt5HQaGzg1o6RHFPJaOqnmBDg==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^4.0.2" - }, - "engines": { - "node": "18 || 20 || >=22" - } - }, - "node_modules/app-builder-lib/node_modules/chownr": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", - "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" - } - }, - "node_modules/app-builder-lib/node_modules/ci-info": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.3.1.tgz", - "integrity": "sha512-Wdy2Igu8OcBpI2pZePZ5oWjPC38tmDVx5WKUXKwlLYkA0ozo85sLsLvkBbBn/sZaSCMFOGZJ14fvW9t5/d7kdA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/sibiraj-s" - } - ], - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/app-builder-lib/node_modules/dotenv": { - "version": "16.6.1", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz", - "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://dotenvx.com" - } - }, - "node_modules/app-builder-lib/node_modules/isexe": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.5.tgz", - "integrity": "sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" - } - }, - "node_modules/app-builder-lib/node_modules/jsonfile": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", - "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==", - "dev": true, - "license": "MIT", - "optionalDependencies": { - "graceful-fs": "^4.1.6" - } - }, - "node_modules/app-builder-lib/node_modules/minimatch": { - "version": "10.2.4", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.4.tgz", - "integrity": "sha512-oRjTw/97aTBN0RHbYCdtF1MQfvusSIBQM0IZEgzl6426+8jSC0nF1a/GmnVLpfB9yyr6g6FTqWqiZVbxrtaCIg==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "brace-expansion": "^5.0.2" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/app-builder-lib/node_modules/minizlib": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", - "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", - "dev": true, - "license": "MIT", - "dependencies": { - "minipass": "^7.1.2" - }, - "engines": { - "node": ">= 18" - } - }, - "node_modules/app-builder-lib/node_modules/tar": { - "version": "7.5.12", - "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.12.tgz", - "integrity": "sha512-9TsuLcdhOn4XztcQqhNyq1KOwOOED/3k58JAvtULiYqbO8B/0IBAAIE1hj0Svmm58k27TmcigyDI0deMlgG3uw==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "@isaacs/fs-minipass": "^4.0.0", - "chownr": "^3.0.0", - "minipass": "^7.1.2", - "minizlib": "^3.1.0", - "yallist": "^5.0.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/app-builder-lib/node_modules/universalify": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", - "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 4.0.0" - } - }, - "node_modules/app-builder-lib/node_modules/which": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/which/-/which-5.0.0.tgz", - "integrity": "sha512-JEdGzHwwkrbWoGOlIHqQ5gtprKGOenpDHpxE9zVR1bWbOtYRyPPHMe9FaP6x61CmNaTThSkb0DAJte5jD+DmzQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "isexe": "^3.1.1" - }, - "bin": { - "node-which": "bin/which.js" - }, - "engines": { - "node": "^18.17.0 || >=20.5.0" - } - }, - "node_modules/app-builder-lib/node_modules/yallist": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", - "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" - } - }, "node_modules/arg": { "version": "5.0.2", "resolved": "https://registry.npmjs.org/arg/-/arg-5.0.2.tgz", @@ -15598,15 +15190,19 @@ "safer-buffer": "~2.1.0" } }, - "node_modules/assert-plus": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", - "integrity": "sha512-NfJ4UzBCcQGLDlQq7nHxH+tv3kyZ0hHQqF5BO6J7tNJeP5do1llPr8dZ8zHonfhAu0PHAdMkSo+8o0wxg9lZWw==", + "node_modules/asn1js": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.1.0.tgz", + "integrity": "sha512-HWYi1THkOqguCiO+vwj09ZkQFD2kKEsejYHAYCtX0D80WVdoDnvRc9IukXX/jeb0T9NRWJnRtqwdbHltnFjwXA==", "dev": true, - "license": "MIT", - "optional": true, + "license": "BSD-3-Clause", + "dependencies": { + "pvtsutils": "^1.3.6", + "pvutils": "^1.2.0", + "tslib": "^2.8.1" + }, "engines": { - "node": ">=0.8" + "node": ">=12.0.0" } }, "node_modules/assertion-error": { @@ -15711,6 +15307,13 @@ "integrity": "sha512-aDczADvlvTGajTDjcjpJMqRkOF6Qdz3YbPZm/PyW6tKPkx2hlYBzxMhEywM/tU72HrVZjgl5VCdRuMlA7pZ8Gw==", "license": "MIT" }, + "node_modules/aws4": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.13.2.tgz", + "integrity": "sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw==", + "dev": true, + "license": "MIT" + }, "node_modules/axios": { "version": "1.13.6", "resolved": "https://registry.npmjs.org/axios/-/axios-1.13.6.tgz", @@ -16153,6 +15756,13 @@ "integrity": "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==", "license": "MIT" }, + "node_modules/bluebird": { + "version": "3.7.2", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz", + "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==", + "dev": true, + "license": "MIT" + }, "node_modules/body-parser": { "version": "1.20.4", "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.4.tgz", @@ -16354,31 +15964,6 @@ "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", "license": "MIT" }, - "node_modules/builder-util": { - "version": "26.8.1", - "resolved": "https://registry.npmjs.org/builder-util/-/builder-util-26.8.1.tgz", - "integrity": "sha512-pm1lTYbGyc90DHgCDO7eo8Rl4EqKLciayNbZqGziqnH9jrlKe8ZANGdityLZU+pJh16dfzjAx2xQq9McuIPEtw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/debug": "^4.1.6", - "7zip-bin": "~5.2.0", - "app-builder-bin": "5.0.0-alpha.12", - "builder-util-runtime": "9.5.1", - "chalk": "^4.1.2", - "cross-spawn": "^7.0.6", - "debug": "^4.3.4", - "fs-extra": "^10.1.0", - "http-proxy-agent": "^7.0.0", - "https-proxy-agent": "^7.0.0", - "js-yaml": "^4.1.0", - "sanitize-filename": "^1.6.3", - "source-map-support": "^0.5.19", - "stat-mode": "^1.0.0", - "temp-file": "^3.4.0", - "tiny-async-pool": "1.3.0" - } - }, "node_modules/builder-util-runtime": { "version": "9.5.1", "resolved": "https://registry.npmjs.org/builder-util-runtime/-/builder-util-runtime-9.5.1.tgz", @@ -16392,44 +15977,6 @@ "node": ">=12.0.0" } }, - "node_modules/builder-util/node_modules/agent-base": { - "version": "7.1.4", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", - "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 14" - } - }, - "node_modules/builder-util/node_modules/http-proxy-agent": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", - "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", - "dev": true, - "license": "MIT", - "dependencies": { - "agent-base": "^7.1.0", - "debug": "^4.3.4" - }, - "engines": { - "node": ">= 14" - } - }, - "node_modules/builder-util/node_modules/https-proxy-agent": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", - "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", - "dev": true, - "license": "MIT", - "dependencies": { - "agent-base": "^7.1.2", - "debug": "4" - }, - "engines": { - "node": ">= 14" - } - }, "node_modules/bunyan": { "version": "1.8.15", "resolved": "https://registry.npmjs.org/bunyan/-/bunyan-1.8.15.tgz", @@ -16458,98 +16005,14 @@ "node": ">= 0.8" } }, - "node_modules/cacache": { - "version": "19.0.1", - "resolved": "https://registry.npmjs.org/cacache/-/cacache-19.0.1.tgz", - "integrity": "sha512-hdsUxulXCi5STId78vRVYEtDAjq99ICAUktLTeTYsLoTE6Z8dS0c8pWNCxwdrk9YfJeobDZc2Y186hD/5ZQgFQ==", + "node_modules/bytestreamjs": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/bytestreamjs/-/bytestreamjs-2.0.1.tgz", + "integrity": "sha512-U1Z/ob71V/bXfVABvNr/Kumf5VyeQRBEm6Txb0PQ6S7V5GpBM3w4Cbqz/xPDicR5tN0uvDifng8C+5qECeGwyQ==", "dev": true, - "license": "ISC", - "dependencies": { - "@npmcli/fs": "^4.0.0", - "fs-minipass": "^3.0.0", - "glob": "^10.2.2", - "lru-cache": "^10.0.1", - "minipass": "^7.0.3", - "minipass-collect": "^2.0.1", - "minipass-flush": "^1.0.5", - "minipass-pipeline": "^1.2.4", - "p-map": "^7.0.2", - "ssri": "^12.0.0", - "tar": "^7.4.3", - "unique-filename": "^4.0.0" - }, + "license": "BSD-3-Clause", "engines": { - "node": "^18.17.0 || >=20.5.0" - } - }, - "node_modules/cacache/node_modules/chownr": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", - "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" - } - }, - "node_modules/cacache/node_modules/fs-minipass": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-3.0.3.tgz", - "integrity": "sha512-XUBA9XClHbnJWSfBzjkm6RvPsyg3sryZt06BEQoXcF7EK/xpGaQYJgQKDJSUH5SGZ76Y7pFx1QBnXz09rU5Fbw==", - "dev": true, - "license": "ISC", - "dependencies": { - "minipass": "^7.0.3" - }, - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - } - }, - "node_modules/cacache/node_modules/lru-cache": { - "version": "10.4.3", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", - "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", - "dev": true, - "license": "ISC" - }, - "node_modules/cacache/node_modules/minizlib": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", - "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", - "dev": true, - "license": "MIT", - "dependencies": { - "minipass": "^7.1.2" - }, - "engines": { - "node": ">= 18" - } - }, - "node_modules/cacache/node_modules/tar": { - "version": "7.5.12", - "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.12.tgz", - "integrity": "sha512-9TsuLcdhOn4XztcQqhNyq1KOwOOED/3k58JAvtULiYqbO8B/0IBAAIE1hj0Svmm58k27TmcigyDI0deMlgG3uw==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "@isaacs/fs-minipass": "^4.0.0", - "chownr": "^3.0.0", - "minipass": "^7.1.2", - "minizlib": "^3.1.0", - "yallist": "^5.0.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/cacache/node_modules/yallist": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", - "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" + "node": ">=6.0.0" } }, "node_modules/cacheable-lookup": { @@ -16986,40 +16449,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/cli-truncate": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-2.1.0.tgz", - "integrity": "sha512-n8fOixwDD6b/ObinzTrp1ZKFzbgvKZvuz/TvejnLn1aQfC6r52XEx85FmuC+3HI+JM7coBRXUvNqEU2PHVrHpg==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "slice-ansi": "^3.0.0", - "string-width": "^4.2.0" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/cli-truncate/node_modules/slice-ansi": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-3.0.0.tgz", - "integrity": "sha512-pSyv7bSTC7ig9Dcgbw9AuRNUb5k5V6oDudjZoMBSr13qpLBG7tB+zgCkARjq7xIUgdz5P1Qe8u+rSGdouOOIyQ==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "ansi-styles": "^4.0.0", - "astral-regex": "^2.0.0", - "is-fullwidth-code-point": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/client-only": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz", @@ -17405,43 +16834,6 @@ "layout-base": "^1.0.0" } }, - "node_modules/crc": { - "version": "3.8.0", - "resolved": "https://registry.npmjs.org/crc/-/crc-3.8.0.tgz", - "integrity": "sha512-iX3mfgcTMIq3ZKLIsVFAbv7+Mc10kxabAGQb8HvjA1o3T1PIYprbakQ65d3I+2HGHt6nSKkM9PYjgoJO2KcFBQ==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "buffer": "^5.1.0" - } - }, - "node_modules/crc/node_modules/buffer": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", - "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "optional": true, - "dependencies": { - "base64-js": "^1.3.1", - "ieee754": "^1.1.13" - } - }, "node_modules/create-jest": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/create-jest/-/create-jest-29.7.0.tgz", @@ -17478,6 +16870,15 @@ "integrity": "sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==", "license": "MIT" }, + "node_modules/cross-dirname": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/cross-dirname/-/cross-dirname-0.1.0.tgz", + "integrity": "sha512-+R08/oI0nl3vfPcqftZRpytksBXDzOUveBq/NBVx0sUp1axwzPQrKinNx5yd5sxPu8j1wIy8AfnVQ+5eFdha6Q==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true + }, "node_modules/cross-env": { "version": "10.1.0", "resolved": "https://registry.npmjs.org/cross-env/-/cross-env-10.1.0.tgz", @@ -18680,76 +18081,6 @@ "node": ">=8" } }, - "node_modules/dmg-builder": { - "version": "26.8.1", - "resolved": "https://registry.npmjs.org/dmg-builder/-/dmg-builder-26.8.1.tgz", - "integrity": "sha512-glMJgnTreo8CFINujtAhCgN96QAqApDMZ8Vl1r8f0QT8QprvC1UCltV4CcWj20YoIyLZx6IUskaJZ0NV8fokcg==", - "dev": true, - "license": "MIT", - "dependencies": { - "app-builder-lib": "26.8.1", - "builder-util": "26.8.1", - "fs-extra": "^10.1.0", - "iconv-lite": "^0.6.2", - "js-yaml": "^4.1.0" - }, - "optionalDependencies": { - "dmg-license": "^1.0.11" - } - }, - "node_modules/dmg-license": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/dmg-license/-/dmg-license-1.0.11.tgz", - "integrity": "sha512-ZdzmqwKmECOWJpqefloC5OJy1+WZBBse5+MR88z9g9Zn4VY+WYUkAyojmhzJckH5YbbZGcYIuGAkY5/Ys5OM2Q==", - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "dependencies": { - "@types/plist": "^3.0.1", - "@types/verror": "^1.10.3", - "ajv": "^6.10.0", - "crc": "^3.8.0", - "iconv-corefoundation": "^1.1.7", - "plist": "^3.0.4", - "smart-buffer": "^4.0.2", - "verror": "^1.10.0" - }, - "bin": { - "dmg-license": "bin/dmg-license.js" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/dmg-license/node_modules/ajv": { - "version": "6.14.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz", - "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "fast-deep-equal": "^3.1.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/dmg-license/node_modules/json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true, - "license": "MIT", - "optional": true - }, "node_modules/dnssd-advertise": { "version": "1.1.6", "resolved": "https://registry.npmjs.org/dnssd-advertise/-/dnssd-advertise-1.1.6.tgz", @@ -18941,6 +18272,16 @@ "node": ">= 0.4" } }, + "node_modules/duplexer2": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.1.4.tgz", + "integrity": "sha512-asLFVfWWtJ90ZyOUHMqk7/S2w2guQKxUI2itj3d92ADHhxUSbCMGi1f1cBcJ7xM1To+pE/Khbwo1yuNbMEPKeA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "readable-stream": "^2.0.2" + } + }, "node_modules/eas-cli": { "version": "16.32.0", "resolved": "https://registry.npmjs.org/eas-cli/-/eas-cli-16.32.0.tgz", @@ -19261,48 +18602,6 @@ "node": ">= 22.12.0" } }, - "node_modules/electron-builder": { - "version": "26.8.1", - "resolved": "https://registry.npmjs.org/electron-builder/-/electron-builder-26.8.1.tgz", - "integrity": "sha512-uWhx1r74NGpCagG0ULs/P9Nqv2nsoo+7eo4fLUOB8L8MdWltq9odW/uuLXMFCDGnPafknYLZgjNX0ZIFRzOQAw==", - "dev": true, - "license": "MIT", - "dependencies": { - "app-builder-lib": "26.8.1", - "builder-util": "26.8.1", - "builder-util-runtime": "9.5.1", - "chalk": "^4.1.2", - "ci-info": "^4.2.0", - "dmg-builder": "26.8.1", - "fs-extra": "^10.1.0", - "lazy-val": "^1.0.5", - "simple-update-notifier": "2.0.0", - "yargs": "^17.6.2" - }, - "bin": { - "electron-builder": "cli.js", - "install-app-deps": "install-app-deps.js" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/electron-builder/node_modules/ci-info": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.4.0.tgz", - "integrity": "sha512-77PSwercCZU2Fc4sX94eF8k8Pxte6JAwL4/ICZLFjJLqegs7kCuAsqqj/70NQF6TvDpgFjkubQB2FW2ZZddvQg==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/sibiraj-s" - } - ], - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/electron-log": { "version": "5.4.3", "resolved": "https://registry.npmjs.org/electron-log/-/electron-log-5.4.3.tgz", @@ -19312,36 +18611,6 @@ "node": ">= 14" } }, - "node_modules/electron-publish": { - "version": "26.8.1", - "resolved": "https://registry.npmjs.org/electron-publish/-/electron-publish-26.8.1.tgz", - "integrity": "sha512-q+jrSTIh/Cv4eGZa7oVR+grEJo/FoLMYBAnSL5GCtqwUpr1T+VgKB/dn1pnzxIxqD8S/jP1yilT9VrwCqINR4w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/fs-extra": "^9.0.11", - "builder-util": "26.8.1", - "builder-util-runtime": "9.5.1", - "chalk": "^4.1.2", - "form-data": "^4.0.5", - "fs-extra": "^10.1.0", - "lazy-val": "^1.0.5", - "mime": "^2.5.2" - } - }, - "node_modules/electron-publish/node_modules/mime": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/mime/-/mime-2.6.0.tgz", - "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==", - "dev": true, - "license": "MIT", - "bin": { - "mime": "cli.js" - }, - "engines": { - "node": ">=4.0.0" - } - }, "node_modules/electron-to-chromium": { "version": "1.5.307", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.307.tgz", @@ -19364,6 +18633,66 @@ "tiny-typed-emitter": "^2.1.0" } }, + "node_modules/electron-winstaller": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/electron-winstaller/-/electron-winstaller-5.4.0.tgz", + "integrity": "sha512-bO3y10YikuUwUuDUQRM4KfwNkKhnpVO7IPdbsrejwN9/AABJzzTQ4GeHwyzNSrVO+tEH3/Np255a3sVZpZDjvg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@electron/asar": "^3.2.1", + "debug": "^4.1.1", + "fs-extra": "^7.0.1", + "lodash": "^4.17.21", + "temp": "^0.9.0" + }, + "engines": { + "node": ">=8.0.0" + }, + "optionalDependencies": { + "@electron/windows-sign": "^1.1.2" + } + }, + "node_modules/electron-winstaller/node_modules/fs-extra": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-7.0.1.tgz", + "integrity": "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "graceful-fs": "^4.1.2", + "jsonfile": "^4.0.0", + "universalify": "^0.1.0" + }, + "engines": { + "node": ">=6 <7 || >=8" + } + }, + "node_modules/electron-winstaller/node_modules/jsonfile": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", + "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==", + "dev": true, + "license": "MIT", + "peer": true, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/electron-winstaller/node_modules/universalify": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", + "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 4.0.0" + } + }, "node_modules/electron/node_modules/@types/node": { "version": "24.13.3", "resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.3.tgz", @@ -21719,17 +21048,6 @@ "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", "license": "MIT" }, - "node_modules/extsprintf": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.4.1.tgz", - "integrity": "sha512-Wrk35e8ydCKDj/ArClo1VrPVmN8zph5V4AtHwIuHhvMXsKf73UT3BOD+azBIW+3wOJ4FhEH7zyaJCFvChjYvMA==", - "dev": true, - "engines": [ - "node >=0.6.0" - ], - "license": "MIT", - "optional": true - }, "node_modules/fake-indexeddb": { "version": "6.2.5", "resolved": "https://registry.npmjs.org/fake-indexeddb/-/fake-indexeddb-6.2.5.tgz", @@ -23439,32 +22757,6 @@ } } }, - "node_modules/iconv-corefoundation": { - "version": "1.1.7", - "resolved": "https://registry.npmjs.org/iconv-corefoundation/-/iconv-corefoundation-1.1.7.tgz", - "integrity": "sha512-T10qvkw0zz4wnm560lOEg0PovVqUXuOFhhHAkixw8/sycy7TJt7v/RrkEKEQnAw2viPSJu6iAkErxnzR0g8PpQ==", - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "dependencies": { - "cli-truncate": "^2.1.0", - "node-addon-api": "^1.6.3" - }, - "engines": { - "node": "^8.11.2 || >=10" - } - }, - "node_modules/iconv-corefoundation/node_modules/node-addon-api": { - "version": "1.7.2", - "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-1.7.2.tgz", - "integrity": "sha512-ibPK3iA+vaY1eEjESkQkM0BbCqFOaZMiXRTtdB0u7b4djtY6JnsjvPdUHVMg6xQt3B8fpTTWHI9A+ADjM9frzg==", - "dev": true, - "license": "MIT", - "optional": true - }, "node_modules/iconv-lite": { "version": "0.6.3", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", @@ -27064,49 +26356,6 @@ "dev": true, "license": "ISC" }, - "node_modules/make-fetch-happen": { - "version": "14.0.3", - "resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-14.0.3.tgz", - "integrity": "sha512-QMjGbFTP0blj97EeidG5hk/QhKQ3T4ICckQGLgz38QF7Vgbk6e6FTARN8KhKxyBbWn8R0HU+bnw8aSoFPD4qtQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "@npmcli/agent": "^3.0.0", - "cacache": "^19.0.1", - "http-cache-semantics": "^4.1.1", - "minipass": "^7.0.2", - "minipass-fetch": "^4.0.0", - "minipass-flush": "^1.0.5", - "minipass-pipeline": "^1.2.4", - "negotiator": "^1.0.0", - "proc-log": "^5.0.0", - "promise-retry": "^2.0.1", - "ssri": "^12.0.0" - }, - "engines": { - "node": "^18.17.0 || >=20.5.0" - } - }, - "node_modules/make-fetch-happen/node_modules/negotiator": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", - "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/make-fetch-happen/node_modules/proc-log": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-5.0.0.tgz", - "integrity": "sha512-Azwzvl90HaF0aCz1JrDdXQykFakSSNPaPoiZ9fm5qJIMHioDZEi7OAdRwSm6rSoPtY3Qutnm3L7ogmg3dc+wbQ==", - "dev": true, - "license": "ISC", - "engines": { - "node": "^18.17.0 || >=20.5.0" - } - }, "node_modules/makeerror": { "version": "1.0.12", "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz", @@ -29307,115 +28556,6 @@ "node": ">=16 || 14 >=14.17" } }, - "node_modules/minipass-collect": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/minipass-collect/-/minipass-collect-2.0.1.tgz", - "integrity": "sha512-D7V8PO9oaz7PWGLbCACuI1qEOsq7UKfLotx/C0Aet43fCUB/wfQ7DYeq2oR/svFJGYDHPr38SHATeaj/ZoKHKw==", - "dev": true, - "license": "ISC", - "dependencies": { - "minipass": "^7.0.3" - }, - "engines": { - "node": ">=16 || 14 >=14.17" - } - }, - "node_modules/minipass-fetch": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/minipass-fetch/-/minipass-fetch-4.0.1.tgz", - "integrity": "sha512-j7U11C5HXigVuutxebFadoYBbd7VSdZWggSe64NVdvWNBqGAiXPL2QVCehjmw7lY1oF9gOllYbORh+hiNgfPgQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "minipass": "^7.0.3", - "minipass-sized": "^1.0.3", - "minizlib": "^3.0.1" - }, - "engines": { - "node": "^18.17.0 || >=20.5.0" - }, - "optionalDependencies": { - "encoding": "^0.1.13" - } - }, - "node_modules/minipass-flush": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/minipass-flush/-/minipass-flush-1.0.5.tgz", - "integrity": "sha512-JmQSYYpPUqX5Jyn1mXaRwOda1uQ8HP5KAT/oDSLCzt1BYRhQU0/hDtsB1ufZfEEzMZ9aAVmsBw8+FWsIXlClWw==", - "dev": true, - "license": "ISC", - "dependencies": { - "minipass": "^3.0.0" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/minipass-flush/node_modules/minipass": { - "version": "3.3.6", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", - "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", - "dev": true, - "license": "ISC", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/minipass-pipeline": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/minipass-pipeline/-/minipass-pipeline-1.2.4.tgz", - "integrity": "sha512-xuIq7cIOt09RPRJ19gdi4b+RiNvDFYe5JH+ggNvBqGqpQXcru3PcRmOZuHBKWK1Txf9+cQ+HMVN4d6z46LZP7A==", - "dev": true, - "license": "ISC", - "dependencies": { - "minipass": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/minipass-pipeline/node_modules/minipass": { - "version": "3.3.6", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", - "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", - "dev": true, - "license": "ISC", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/minipass-sized": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/minipass-sized/-/minipass-sized-1.0.3.tgz", - "integrity": "sha512-MbkQQ2CTiBMlA2Dm/5cY+9SWFEN8pzzOXi6rlM5Xxq0Yqbda5ZQy9sU75a673FE9ZK0Zsbr6Y5iP6u9nktfg2g==", - "dev": true, - "license": "ISC", - "dependencies": { - "minipass": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/minipass-sized/node_modules/minipass": { - "version": "3.3.6", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", - "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", - "dev": true, - "license": "ISC", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/minizlib": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.0.1.tgz", @@ -29826,31 +28966,6 @@ "node": ">= 6.13.0" } }, - "node_modules/node-gyp": { - "version": "11.5.0", - "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-11.5.0.tgz", - "integrity": "sha512-ra7Kvlhxn5V9Slyus0ygMa2h+UqExPqUIkfk7Pc8QTLT956JLSy51uWFwHtIYy0vI8cB4BDhc/S03+880My/LQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "env-paths": "^2.2.0", - "exponential-backoff": "^3.1.1", - "graceful-fs": "^4.2.6", - "make-fetch-happen": "^14.0.3", - "nopt": "^8.0.0", - "proc-log": "^5.0.0", - "semver": "^7.3.5", - "tar": "^7.4.3", - "tinyglobby": "^0.2.12", - "which": "^5.0.0" - }, - "bin": { - "node-gyp": "bin/node-gyp.js" - }, - "engines": { - "node": "^18.17.0 || >=20.5.0" - } - }, "node_modules/node-gyp-build": { "version": "4.8.4", "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz", @@ -29878,92 +28993,6 @@ "node-gyp-build-optional-packages-test": "build-test.js" } }, - "node_modules/node-gyp/node_modules/chownr": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", - "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" - } - }, - "node_modules/node-gyp/node_modules/isexe": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.5.tgz", - "integrity": "sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" - } - }, - "node_modules/node-gyp/node_modules/minizlib": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", - "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", - "dev": true, - "license": "MIT", - "dependencies": { - "minipass": "^7.1.2" - }, - "engines": { - "node": ">= 18" - } - }, - "node_modules/node-gyp/node_modules/proc-log": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-5.0.0.tgz", - "integrity": "sha512-Azwzvl90HaF0aCz1JrDdXQykFakSSNPaPoiZ9fm5qJIMHioDZEi7OAdRwSm6rSoPtY3Qutnm3L7ogmg3dc+wbQ==", - "dev": true, - "license": "ISC", - "engines": { - "node": "^18.17.0 || >=20.5.0" - } - }, - "node_modules/node-gyp/node_modules/tar": { - "version": "7.5.12", - "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.12.tgz", - "integrity": "sha512-9TsuLcdhOn4XztcQqhNyq1KOwOOED/3k58JAvtULiYqbO8B/0IBAAIE1hj0Svmm58k27TmcigyDI0deMlgG3uw==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "@isaacs/fs-minipass": "^4.0.0", - "chownr": "^3.0.0", - "minipass": "^7.1.2", - "minizlib": "^3.1.0", - "yallist": "^5.0.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/node-gyp/node_modules/which": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/which/-/which-5.0.0.tgz", - "integrity": "sha512-JEdGzHwwkrbWoGOlIHqQ5gtprKGOenpDHpxE9zVR1bWbOtYRyPPHMe9FaP6x61CmNaTThSkb0DAJte5jD+DmzQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "isexe": "^3.1.1" - }, - "bin": { - "node-which": "bin/which.js" - }, - "engines": { - "node": "^18.17.0 || >=20.5.0" - } - }, - "node_modules/node-gyp/node_modules/yallist": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", - "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" - } - }, "node_modules/node-int64": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", @@ -30627,19 +29656,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/p-map": { - "version": "7.0.4", - "resolved": "https://registry.npmjs.org/p-map/-/p-map-7.0.4.tgz", - "integrity": "sha512-tkAQEw8ysMzmkhgw8k+1U/iPhWNhykKnSk4Rd5zLoPJCuJaGRPo6YposrZgaxHKzDHdDWWZvE/Sk7hsL2X/CpQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/p-memoize": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/p-memoize/-/p-memoize-8.0.0.tgz", @@ -31145,6 +30161,40 @@ "node": ">=8" } }, + "node_modules/pkijs": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/pkijs/-/pkijs-3.4.3.tgz", + "integrity": "sha512-V9kOzaItwDgqlryhXysQsAXUEKi5O7kqWUaP3dXI7MLvkPqWWMb4wVb1QAtmEDCKI+XIAINsZoNKMFF7sZb1eg==", + "dev": true, + "license": "BSD-3-Clause", + "workspaces": [ + "website" + ], + "dependencies": { + "@noble/hashes": "1.8.0", + "asn1js": "^3.0.6", + "bytestreamjs": "^2.0.1", + "pvtsutils": "^1.3.6", + "pvutils": "^1.1.3", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/pkijs/node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/playwright": { "version": "1.58.2", "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.58.2.tgz", @@ -31294,6 +30344,36 @@ "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", "license": "MIT" }, + "node_modules/postject": { + "version": "1.0.0-alpha.6", + "resolved": "https://registry.npmjs.org/postject/-/postject-1.0.0-alpha.6.tgz", + "integrity": "sha512-b9Eb8h2eVqNE8edvKdwqkrY6O7kAwmI8kcnBv1NScolYJbo59XUF0noFq+lxbC1yN20bmC0WBEbDC5H/7ASb0A==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "commander": "^9.4.0" + }, + "bin": { + "postject": "dist/cli.js" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/postject/node_modules/commander": { + "version": "9.5.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-9.5.0.tgz", + "integrity": "sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": "^12.20.0 || >=14" + } + }, "node_modules/prelude-ls": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", @@ -31565,6 +30645,26 @@ ], "license": "MIT" }, + "node_modules/pvtsutils": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz", + "integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "^2.8.1" + } + }, + "node_modules/pvutils": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.2.0.tgz", + "integrity": "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=16.0.0" + } + }, "node_modules/qrcode": { "version": "1.5.4", "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz", @@ -33156,6 +32256,70 @@ "node": ">=0.10.0" } }, + "node_modules/rimraf": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz", + "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==", + "deprecated": "Rimraf versions prior to v4 are no longer supported", + "dev": true, + "license": "ISC", + "peer": true, + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + } + }, + "node_modules/rimraf/node_modules/brace-expansion": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/rimraf/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "dev": true, + "license": "ISC", + "peer": true, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/rimraf/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "license": "ISC", + "peer": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, "node_modules/roarr": { "version": "2.15.4", "resolved": "https://registry.npmjs.org/roarr/-/roarr-2.15.4.tgz", @@ -34120,17 +33284,6 @@ "node": ">=8.0.0" } }, - "node_modules/smart-buffer": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", - "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 6.0.0", - "npm": ">= 3.0.0" - } - }, "node_modules/smol-toml": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.6.0.tgz", @@ -34144,46 +33297,6 @@ "url": "https://github.com/sponsors/cyyynthia" } }, - "node_modules/socks": { - "version": "2.8.7", - "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.7.tgz", - "integrity": "sha512-HLpt+uLy/pxB+bum/9DzAgiKS8CX1EvbWxI4zlmgGCExImLdiad2iCwXT5Z4c9c3Eq8rP2318mPW2c+QbtjK8A==", - "dev": true, - "license": "MIT", - "dependencies": { - "ip-address": "^10.0.1", - "smart-buffer": "^4.2.0" - }, - "engines": { - "node": ">= 10.0.0", - "npm": ">= 3.0.0" - } - }, - "node_modules/socks-proxy-agent": { - "version": "8.0.5", - "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz", - "integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==", - "dev": true, - "license": "MIT", - "dependencies": { - "agent-base": "^7.1.2", - "debug": "^4.3.4", - "socks": "^2.8.3" - }, - "engines": { - "node": ">= 14" - } - }, - "node_modules/socks-proxy-agent/node_modules/agent-base": { - "version": "7.1.4", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", - "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 14" - } - }, "node_modules/sonic-boom": { "version": "4.2.1", "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz", @@ -34312,19 +33425,6 @@ "node": ">=20.16.0" } }, - "node_modules/ssri": { - "version": "12.0.0", - "resolved": "https://registry.npmjs.org/ssri/-/ssri-12.0.0.tgz", - "integrity": "sha512-S7iGNosepx9RadX82oimUkvr0Ct7IjJbEbs4mJcTxst8um95J3sDYU1RBEOvdu6oL1Wek2ODI5i4MAw+dZ6cAQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "minipass": "^7.0.3" - }, - "engines": { - "node": "^18.17.0 || >=20.5.0" - } - }, "node_modules/stable-hash": { "version": "0.0.5", "resolved": "https://registry.npmjs.org/stable-hash/-/stable-hash-0.0.5.tgz", @@ -35071,6 +34171,21 @@ "node": ">=8" } }, + "node_modules/temp": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/temp/-/temp-0.9.4.tgz", + "integrity": "sha512-yYrrsWnrXMcdsnu/7YMYAofM1ktpL5By7vZhf15CrXijWWrEYZks5AXBudalfSWJLlnen/QUJUB5aoB0kqZUGA==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "mkdirp": "^0.5.1", + "rimraf": "~2.6.2" + }, + "engines": { + "node": ">=6.0.0" + } + }, "node_modules/temp-dir": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/temp-dir/-/temp-dir-2.0.0.tgz", @@ -35092,6 +34207,20 @@ "fs-extra": "^10.0.0" } }, + "node_modules/temp/node_modules/mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "minimist": "^1.2.6" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, "node_modules/terminal-link": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/terminal-link/-/terminal-link-2.1.1.tgz", @@ -36074,32 +35203,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/unique-filename": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/unique-filename/-/unique-filename-4.0.0.tgz", - "integrity": "sha512-XSnEewXmQ+veP7xX2dS5Q4yZAvO40cBN2MWkJ7D/6sW4Dg6wYBNwM1Vrnz1FhH5AdeLIlUXRI9e28z1YZi71NQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "unique-slug": "^5.0.0" - }, - "engines": { - "node": "^18.17.0 || >=20.5.0" - } - }, - "node_modules/unique-slug": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/unique-slug/-/unique-slug-5.0.0.tgz", - "integrity": "sha512-9OdaqO5kwqR+1kVgHAhsp5vPNU0hnxRa26rBFNfNgM7M6pNtgzeBn3s/xbyCQL3dcjzOatcef6UUHpB/6MaETg==", - "dev": true, - "license": "ISC", - "dependencies": { - "imurmurhash": "^0.1.4" - }, - "engines": { - "node": "^18.17.0 || >=20.5.0" - } - }, "node_modules/unique-string": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/unique-string/-/unique-string-2.0.0.tgz", @@ -36283,6 +35386,35 @@ "mkdirp": "bin/cmd.js" } }, + "node_modules/unzipper": { + "version": "0.12.5", + "resolved": "https://registry.npmjs.org/unzipper/-/unzipper-0.12.5.tgz", + "integrity": "sha512-tXYOi9R57Uj/2Z25SOs5RRSzq886MBQj2gY8dPL+xl/kv6s6SvByoKfAtvfVeEuhntWDgjd2o9p2lb4TVPAz0A==", + "dev": true, + "license": "MIT", + "dependencies": { + "bluebird": "~3.7.2", + "duplexer2": "~0.1.4", + "fs-extra": "11.3.1", + "graceful-fs": "^4.2.2", + "node-int64": "^0.4.0" + } + }, + "node_modules/unzipper/node_modules/fs-extra": { + "version": "11.3.1", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.1.tgz", + "integrity": "sha512-eXvGGwZ5CL17ZSwHWd3bbgk7UUpF6IFHtP57NYYakPvHOs8GDgDe5KJI36jIJzDkJ6eJjuzRA8eBQb6SkKue0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=14.14" + } + }, "node_modules/update-browserslist-db": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", @@ -36496,22 +35628,6 @@ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc" } }, - "node_modules/verror": { - "version": "1.10.1", - "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.1.tgz", - "integrity": "sha512-veufcmxri4e3XSrT0xwfUR7kguIkaxBeosDg00yDWhk49wdwkSUrvvsm7nc75e1PUyvIeZj6nS8VQRYz2/S4Xg==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "assert-plus": "^1.0.0", - "core-util-is": "1.0.2", - "extsprintf": "^1.2.0" - }, - "engines": { - "node": ">=0.6.0" - } - }, "node_modules/vfile": { "version": "6.0.3", "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz", @@ -36919,6 +36035,20 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/webcrypto-core": { + "version": "1.9.2", + "resolved": "https://registry.npmjs.org/webcrypto-core/-/webcrypto-core-1.9.2.tgz", + "integrity": "sha512-gsXecm82UQNlTBURJGuqOWy1Ww08S3kZUcr3aOJS02Pk0xLtkfeUAVC0u0xhgdonFme80edSJUIJyuvL/7250Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.7.0", + "@peculiar/json-schema": "^1.1.12", + "@peculiar/utils": "^2.0.2", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + } + }, "node_modules/webidl-conversions": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", @@ -40082,13 +39212,94 @@ "@types/node": "24.6.0", "@types/ws": "^8.5.14", "electron": "44.2.0", - "electron-builder": "26.8.1", + "electron-builder": "26.18.0", "typescript": "5.9.3", "unzip-crx-3": "^0.2.0", "vitest": "^4.1.6", "wait-on": "8.0.5" } }, + "packages/desktop/node_modules/@electron/get": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@electron/get/-/get-3.1.0.tgz", + "integrity": "sha512-F+nKc0xW+kVbBRhFzaMgPy3KwmuNTYX1fx6+FxxoSnNgwYX6LD7AKBTWkU0MQ6IBoe7dz069CNkR673sPAgkCQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.1.1", + "env-paths": "^2.2.0", + "fs-extra": "^8.1.0", + "got": "^11.8.5", + "progress": "^2.0.3", + "semver": "^6.2.0", + "sumchecker": "^3.0.1" + }, + "engines": { + "node": ">=14" + }, + "optionalDependencies": { + "global-agent": "^3.0.0" + } + }, + "packages/desktop/node_modules/@electron/get/node_modules/fs-extra": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz", + "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^4.0.0", + "universalify": "^0.1.0" + }, + "engines": { + "node": ">=6 <7 || >=8" + } + }, + "packages/desktop/node_modules/@electron/get/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "packages/desktop/node_modules/@electron/rebuild": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@electron/rebuild/-/rebuild-4.2.1.tgz", + "integrity": "sha512-IS4pG3BysRrCLJ8xTAfvg+IQDbiUoAzdJy2SfjcYKnLDy5DpCdjnPdhS5Zf5UMfrkB24xu0KC+TqcOxg+eG+6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@malept/cross-spawn-promise": "^2.0.0", + "debug": "^4.1.1", + "node-abi": "^4.2.0", + "node-api-version": "^0.2.1", + "node-gyp": "^12.2.0", + "read-binary-file-arch": "^1.0.6" + }, + "bin": { + "electron-rebuild": "lib/cli.js" + }, + "engines": { + "node": ">=22.12.0" + } + }, + "packages/desktop/node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "packages/desktop/node_modules/@types/node": { "version": "24.6.0", "resolved": "https://registry.npmjs.org/@types/node/-/node-24.6.0.tgz", @@ -40185,6 +39396,482 @@ "url": "https://opencollective.com/vitest" } }, + "packages/desktop/node_modules/abbrev": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-4.0.0.tgz", + "integrity": "sha512-a1wflyaL0tHtJSmLSOVybYhy22vRih4eduhhrkcjgrWGnRfrZtovJ2FRjxuTtkkj47O/baf0R86QU5OuYpz8fA==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "packages/desktop/node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "packages/desktop/node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "packages/desktop/node_modules/app-builder-lib": { + "version": "26.18.0", + "resolved": "https://registry.npmjs.org/app-builder-lib/-/app-builder-lib-26.18.0.tgz", + "integrity": "sha512-lx+KkuCSZHcbECf4R3IAcC9VOFk0+cMUwljO63s5y8yqS1Lw0sRGmjPaWsPwP3zv3ohZYbMhUvjXeiQXXZhJXA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@electron/asar": "3.4.1", + "@electron/fuses": "^1.8.0", + "@electron/get": "^3.0.0", + "@electron/notarize": "2.5.0", + "@electron/osx-sign": "1.3.3", + "@electron/rebuild": "^4.2.1", + "@electron/universal": "2.0.3", + "@malept/flatpak-bundler": "^0.4.0", + "@noble/hashes": "^1.8.0", + "@peculiar/webcrypto": "^1.7.1", + "@types/fs-extra": "9.0.13", + "ajv": "^8.18.0", + "asn1js": "^3.0.10", + "async-exit-hook": "^2.0.1", + "builder-util": "26.16.0", + "builder-util-runtime": "9.7.0", + "chromium-pickle-js": "^0.2.0", + "ci-info": "4.3.1", + "debug": "^4.3.4", + "dotenv": "^16.4.5", + "dotenv-expand": "^11.0.6", + "ejs": "^3.1.8", + "electron-publish": "26.18.0", + "fs-extra": "^10.1.0", + "hosted-git-info": "^4.1.0", + "isbinaryfile": "^5.0.0", + "jiti": "^2.4.2", + "js-yaml": "^4.1.0", + "json5": "^2.2.3", + "lazy-val": "^1.0.5", + "minimatch": "^10.2.5", + "pkijs": "^3.4.0", + "plist": "3.1.0", + "proper-lockfile": "^4.1.2", + "resedit": "^1.7.0", + "semver": "~7.7.3", + "tar": "^7.5.7", + "temp-file": "^3.4.0", + "tiny-async-pool": "1.3.0", + "unzipper": "^0.12.3", + "which": "^5.0.0" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "dmg-builder": "26.18.0", + "electron-builder-squirrel-windows": "26.18.0" + } + }, + "packages/desktop/node_modules/app-builder-lib/node_modules/ci-info": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.3.1.tgz", + "integrity": "sha512-Wdy2Igu8OcBpI2pZePZ5oWjPC38tmDVx5WKUXKwlLYkA0ozo85sLsLvkBbBn/sZaSCMFOGZJ14fvW9t5/d7kdA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/sibiraj-s" + } + ], + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "packages/desktop/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "packages/desktop/node_modules/brace-expansion": { + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "packages/desktop/node_modules/builder-util": { + "version": "26.16.0", + "resolved": "https://registry.npmjs.org/builder-util/-/builder-util-26.16.0.tgz", + "integrity": "sha512-RLyJhB7Si3YkzKR9ubQslWuXW3Vhs3CGe1i+SeixBZ0qTd1mk3XBmssvY22TlB6CS5blyko8Gu1JzpYk8UkYAg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/debug": "^4.1.6", + "builder-util-runtime": "9.7.0", + "chalk": "^4.1.2", + "cross-spawn": "^7.0.6", + "debug": "^4.3.4", + "fs-extra": "^10.1.0", + "http-proxy-agent": "^7.0.0", + "https-proxy-agent": "^7.0.0", + "js-yaml": "^4.1.0", + "sanitize-filename": "^1.6.3", + "source-map-support": "^0.5.19", + "stat-mode": "^1.0.0", + "temp-file": "^3.4.0", + "tiny-async-pool": "1.3.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "packages/desktop/node_modules/builder-util-runtime": { + "version": "9.7.0", + "resolved": "https://registry.npmjs.org/builder-util-runtime/-/builder-util-runtime-9.7.0.tgz", + "integrity": "sha512-g/kR520giAFYkSXTzcmF3kqQq7wi8F6N6SzeDgZrqTBN+VHdmgWOyTdD1yD7AATDId/yXLvuP34CxW46/BwCdw==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.3.4", + "sax": "^1.2.4" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "packages/desktop/node_modules/chownr": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", + "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, + "packages/desktop/node_modules/ci-info": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.4.0.tgz", + "integrity": "sha512-77PSwercCZU2Fc4sX94eF8k8Pxte6JAwL4/ICZLFjJLqegs7kCuAsqqj/70NQF6TvDpgFjkubQB2FW2ZZddvQg==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/sibiraj-s" + } + ], + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "packages/desktop/node_modules/dmg-builder": { + "version": "26.18.0", + "resolved": "https://registry.npmjs.org/dmg-builder/-/dmg-builder-26.18.0.tgz", + "integrity": "sha512-ozCGC54wi2C1RkS2v69y9lQxvoQ1Coh+iT8CmWiyY8y1ZuOKVvuNson2Hd+HEOs9+EZNNsOBbzKgQZ4SNqWd0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "app-builder-lib": "26.18.0", + "builder-util": "26.16.0", + "fs-extra": "^10.1.0", + "js-yaml": "^4.1.0" + } + }, + "packages/desktop/node_modules/dotenv": { + "version": "16.6.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz", + "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "packages/desktop/node_modules/electron-builder": { + "version": "26.18.0", + "resolved": "https://registry.npmjs.org/electron-builder/-/electron-builder-26.18.0.tgz", + "integrity": "sha512-ASgIuQnOq4RuD8jMhS9hI0LS3EMRT1I/M5R6utqifB/BHN80IcCjBdt+DED+NmNPvmBgEtrlExXZitNdA7kXOg==", + "dev": true, + "license": "MIT", + "dependencies": { + "app-builder-lib": "26.18.0", + "builder-util": "26.16.0", + "builder-util-runtime": "9.7.0", + "chalk": "^4.1.2", + "ci-info": "^4.2.0", + "dmg-builder": "26.18.0", + "fs-extra": "^10.1.0", + "lazy-val": "^1.0.5", + "simple-update-notifier": "2.0.0", + "yargs": "^17.6.2" + }, + "bin": { + "electron-builder": "cli.js", + "install-app-deps": "install-app-deps.js" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "packages/desktop/node_modules/electron-builder-squirrel-windows": { + "version": "26.18.0", + "resolved": "https://registry.npmjs.org/electron-builder-squirrel-windows/-/electron-builder-squirrel-windows-26.18.0.tgz", + "integrity": "sha512-a2elgTipboXNIsxqS1HOmHMGp4Pd3LJgIZOdIFTOskBSawvxKyZWYWQ1d7KKA4CtINSchYCYEKzhxRqiKZev9Q==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "app-builder-lib": "26.18.0", + "builder-util": "26.16.0", + "electron-winstaller": "5.4.0" + } + }, + "packages/desktop/node_modules/electron-publish": { + "version": "26.18.0", + "resolved": "https://registry.npmjs.org/electron-publish/-/electron-publish-26.18.0.tgz", + "integrity": "sha512-MagnqaZSALSWjcdKu5HEVhYUZD/2BDL3q7XzrqWwub6gf/UfD3ItMgmthVDv9w5y9E0gH1C3JWqKaXwf6f4ROg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/fs-extra": "^9.0.11", + "aws4": "^1.13.2", + "builder-util": "26.16.0", + "builder-util-runtime": "9.7.0", + "chalk": "^4.1.2", + "form-data": "^4.0.5", + "fs-extra": "^10.1.0", + "lazy-val": "^1.0.5", + "mime": "^2.5.2" + } + }, + "packages/desktop/node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "packages/desktop/node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "packages/desktop/node_modules/isexe": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.5.tgz", + "integrity": "sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, + "packages/desktop/node_modules/jsonfile": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", + "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==", + "dev": true, + "license": "MIT", + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "packages/desktop/node_modules/mime": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.6.0.tgz", + "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==", + "dev": true, + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "packages/desktop/node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "packages/desktop/node_modules/minizlib": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", + "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "minipass": "^7.1.2" + }, + "engines": { + "node": ">= 18" + } + }, + "packages/desktop/node_modules/node-gyp": { + "version": "12.4.0", + "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-12.4.0.tgz", + "integrity": "sha512-OMcPNvqTCFUnNaBlmdgq+lfNqY7gTiSmNRDjY3uAXRyudeKZEZxu3CLtjMQrx4zZxCX2b/mpNqTtwuCJgXhHkw==", + "dev": true, + "license": "MIT", + "dependencies": { + "env-paths": "^2.2.0", + "exponential-backoff": "^3.1.1", + "graceful-fs": "^4.2.6", + "nopt": "^9.0.0", + "proc-log": "^6.0.0", + "semver": "^7.3.5", + "tar": "^7.5.4", + "tinyglobby": "^0.2.12", + "undici": "^6.25.0", + "which": "^6.0.0" + }, + "bin": { + "node-gyp": "bin/node-gyp.js" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "packages/desktop/node_modules/node-gyp/node_modules/isexe": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-4.0.0.tgz", + "integrity": "sha512-FFUtZMpoZ8RqHS3XeXEmHWLA4thH+ZxCv2lOiPIn1Xc7CxrqhWzNSDzD+/chS/zbYezmiwWLdQC09JdQKmthOw==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=20" + } + }, + "packages/desktop/node_modules/node-gyp/node_modules/which": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/which/-/which-6.0.1.tgz", + "integrity": "sha512-oGLe46MIrCRqX7ytPUf66EAYvdeMIZYn3WaocqqKZAxrBpkqHfL/qvTyJ/bTk5+AqHCjXmrv3CEWgy368zhRUg==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^4.0.0" + }, + "bin": { + "node-which": "bin/which.js" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "packages/desktop/node_modules/nopt": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-9.0.0.tgz", + "integrity": "sha512-Zhq3a+yFKrYwSBluL4H9XP3m3y5uvQkB/09CwDruCiRmR/UJYnn9W4R48ry0uGC70aeTPKLynBtscP9efFFcPw==", + "dev": true, + "license": "ISC", + "dependencies": { + "abbrev": "^4.0.0" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "packages/desktop/node_modules/proc-log": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-6.1.0.tgz", + "integrity": "sha512-iG+GYldRf2BQ0UDUAd6JQ/RwzaQy6mXmsk/IzlYyal4A4SNFw54MeH4/tLkF4I5WoWG9SQwuqWzS99jaFQHBuQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "packages/desktop/node_modules/tar": { + "version": "7.5.22", + "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.22.tgz", + "integrity": "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/fs-minipass": "^4.0.0", + "chownr": "^3.0.0", + "minipass": "^7.1.2", + "minizlib": "^3.1.0", + "yallist": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "packages/desktop/node_modules/undici": { + "version": "6.29.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-6.29.1.tgz", + "integrity": "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.17" + } + }, "packages/desktop/node_modules/undici-types": { "version": "7.13.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.13.0.tgz", @@ -40192,6 +39879,16 @@ "dev": true, "license": "MIT" }, + "packages/desktop/node_modules/universalify": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", + "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4.0.0" + } + }, "packages/desktop/node_modules/vitest": { "version": "4.1.6", "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.6.tgz", @@ -40309,6 +40006,32 @@ } } }, + "packages/desktop/node_modules/which": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/which/-/which-5.0.0.tgz", + "integrity": "sha512-JEdGzHwwkrbWoGOlIHqQ5gtprKGOenpDHpxE9zVR1bWbOtYRyPPHMe9FaP6x61CmNaTThSkb0DAJte5jD+DmzQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^3.1.1" + }, + "bin": { + "node-which": "bin/which.js" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "packages/desktop/node_modules/yallist": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", + "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, "packages/expo-two-way-audio": { "name": "@getpaseo/expo-two-way-audio", "version": "0.15.0-beta.1", diff --git a/packages/desktop/package.json b/packages/desktop/package.json index 6319805fc3..23198969dc 100644 --- a/packages/desktop/package.json +++ b/packages/desktop/package.json @@ -41,7 +41,7 @@ "@types/node": "24.6.0", "@types/ws": "^8.5.14", "electron": "44.2.0", - "electron-builder": "26.8.1", + "electron-builder": "26.18.0", "typescript": "5.9.3", "unzip-crx-3": "^0.2.0", "vitest": "^4.1.6", diff --git a/scripts/ci-workflow.test.mjs b/scripts/ci-workflow.test.mjs index 381f826540..97720f46ec 100644 --- a/scripts/ci-workflow.test.mjs +++ b/scripts/ci-workflow.test.mjs @@ -680,51 +680,46 @@ test("macOS jobs use latest runners while preserving release architectures", () assert.match(release, /runner: macos-26-intel\n\s+electron_arch: x64/); }); -test("macOS signing repair keeps certificate and keychain passwords separate", () => { - const workflow = readFileSync(new URL(".github/workflows/desktop-release.yml", repoRoot), "utf8"); - const match = workflow.match(/<<'KEYCHAIN_FIX'\n([\s\S]*?)\n KEYCHAIN_FIX/); - assert.ok(match, "the release workflow repairs the pinned signing tool"); - const script = match[1].replace(/^ /gm, ""); - const original = [ - "return await importCerts(keychainFile, certPaths, cscPasswords);", - "async function importCerts(keychainFile, paths, keyPasswords) {", - '["import", paths[i], "-P", password]', - '["set-key-partition-list", "-S", "apple-tool:,apple:", "-s", "-k", password, keychainFile]', - "}", - ].join("\n"); - const directory = mkdtempSync(join(tmpdir(), "signing-repair-")); +test("Nix desktop packaging resolves the workspace-local builder", () => { + const source = readFileSync(new URL("nix/desktop-package.nix", repoRoot), "utf8"); + const invocation = source.match(/^\s+([^\n]*electron-builder) \\\n/m)?.[1]; + assert.ok(invocation, "Nix invokes the desktop packaging tool"); + const directory = mkdtempSync(join(tmpdir(), "nix-builder-resolution-")); try { - const packageDirectory = join(directory, "node_modules/app-builder-lib"); - mkdirSync(join(packageDirectory, "out/codeSign"), { recursive: true }); - const manifest = join(packageDirectory, "package.json"); - const sourcePath = join(packageDirectory, "out/codeSign/macCodeSign.js"); - for (const [version, source, succeeds] of [ - ["26.8.1", original, true], - ["26.8.1", original.replace("cscPasswords);", "differentArguments);"), false], - ["26.18.0", original, false], - ]) { - writeFileSync(manifest, JSON.stringify({ name: "app-builder-lib", version })); - writeFileSync(sourcePath, source); - const result = spawnSync(process.execPath, ["-e", script], { - cwd: directory, - encoding: "utf8", - }); - const actual = readFileSync(sourcePath, "utf8"); - if (succeeds) { - assert.equal(result.status, 0, result.stderr); - assert.ok( - actual.includes("importCerts(keychainFile, certPaths, cscPasswords, keychainPassword)"), - ); - assert.ok( - actual.includes("importCerts(keychainFile, paths, keyPasswords, keychainPassword)"), - ); - assert.ok(actual.includes('["import", paths[i], "-P", password]')); - assert.ok(actual.includes('"-k", keychainPassword, keychainFile]')); - } else { - assert.notEqual(result.status, 0); - assert.equal(actual, source, "unexpected tool inputs must fail without a partial write"); - } - } + const desktop = join(directory, "packages/desktop"); + mkdirSync(join(desktop, "node_modules/.bin"), { recursive: true }); + mkdirSync(join(desktop, "node_modules/electron-builder")); + writeFileSync( + join(desktop, "node_modules/electron-builder/package.json"), + JSON.stringify({ + name: "electron-builder", + version: "1.0.0", + bin: { "electron-builder": "../.bin/electron-builder" }, + }), + ); + writeFileSync( + join(directory, "package.json"), + JSON.stringify({ private: true, workspaces: ["packages/desktop"] }), + ); + writeFileSync( + join(desktop, "package.json"), + JSON.stringify({ + name: "desktop-fixture", + private: true, + devDependencies: { "electron-builder": "1.0.0" }, + }), + ); + writeFileSync( + join(desktop, "node_modules/.bin/electron-builder"), + '#!/bin/sh\nprintf "workspace-builder\\n"\n', + { mode: 0o755 }, + ); + const result = spawnSync("sh", ["-c", `${invocation} --version`], { + cwd: desktop, + encoding: "utf8", + }); + assert.equal(result.status, 0, result.stderr); + assert.equal(result.stdout.trim(), "workspace-builder"); } finally { rmSync(directory, { recursive: true, force: true }); } From 81301474265fbe3b0a798d519b71ffc31e6d255d Mon Sep 17 00:00:00 2001 From: Dominic <33105147+DAnaeto@users.noreply.github.com> Date: Sun, 1 Nov 2026 05:04:25 -0500 Subject: [PATCH 170/173] fix(app): stop the terminal from typing its version reply into the shell (#8419) The browser terminal is a renderer and leaves protocol replies to the daemon, but it still answered XTVERSION (CSI > q) and DECRQSS (DCS $ q ... ST). Those replies went out through onData as if the user had typed them, so a query from a program in the shell left text like ">|xterm.js(6.1.0-beta.292)" on the next input line. Both queries are now swallowed with the other protocol queries. Fixes #8111 --- .../terminal/runtime/terminal-emulator-runtime.browser.test.ts | 2 ++ packages/app/src/terminal/runtime/terminal-emulator-runtime.ts | 2 ++ 2 files changed, 4 insertions(+) diff --git a/packages/app/src/terminal/runtime/terminal-emulator-runtime.browser.test.ts b/packages/app/src/terminal/runtime/terminal-emulator-runtime.browser.test.ts index 3b58c54376..bf044237b0 100644 --- a/packages/app/src/terminal/runtime/terminal-emulator-runtime.browser.test.ts +++ b/packages/app/src/terminal/runtime/terminal-emulator-runtime.browser.test.ts @@ -717,11 +717,13 @@ describe("terminal emulator runtime in a real browser", () => { { name: "DA1-zero", bytes: "\x1b[0c" }, { name: "DA2", bytes: "\x1b[>c" }, { name: "DA3", bytes: "\x1b[=c" }, + { name: "XTVERSION", bytes: "\x1b[>q" }, { name: "DSR-5", bytes: "\x1b[5n" }, { name: "DSR-6", bytes: "\x1b[6n" }, { name: "DSR-?6", bytes: "\x1b[?6n" }, { name: "DECRQM", bytes: "\x1b[1$p" }, { name: "DECRQM-?", bytes: "\x1b[?1$p" }, + { name: "DECRQSS", bytes: "\x1bP$qm\x1b\\" }, { name: "OSC-10-foreground-color", bytes: "\x1b]10;?\x07" }, { name: "OSC-11-background-color", bytes: "\x1b]11;?\x07" }, { name: "OSC-12-cursor-color", bytes: "\x1b]12;?\x07" }, diff --git a/packages/app/src/terminal/runtime/terminal-emulator-runtime.ts b/packages/app/src/terminal/runtime/terminal-emulator-runtime.ts index 05cf0182d1..b1cab84d0e 100644 --- a/packages/app/src/terminal/runtime/terminal-emulator-runtime.ts +++ b/packages/app/src/terminal/runtime/terminal-emulator-runtime.ts @@ -647,6 +647,7 @@ export class TerminalEmulatorRuntime { terminal.parser.registerCsiHandler({ final: "c" }, () => true); terminal.parser.registerCsiHandler({ prefix: ">", final: "c" }, () => true); terminal.parser.registerCsiHandler({ prefix: "=", final: "c" }, () => true); + terminal.parser.registerCsiHandler({ prefix: ">", final: "q" }, () => true); terminal.parser.registerCsiHandler({ final: "n" }, () => true); terminal.parser.registerCsiHandler({ prefix: "?", final: "n" }, () => true); terminal.parser.registerCsiHandler({ final: "R" }, () => true); @@ -655,6 +656,7 @@ export class TerminalEmulatorRuntime { { prefix: "?", intermediates: "$", final: "p" }, () => true, ); + terminal.parser.registerDcsHandler({ intermediates: "$", final: "q" }, () => true); for (const code of [10, 11, 12]) { terminal.parser.registerOscHandler(code, (data) => data.trim() === "?"); } From 9b0542d127ec6452e09c5f4d01e7da328aea5fc0 Mon Sep 17 00:00:00 2001 From: Dominic <33105147+DAnaeto@users.noreply.github.com> Date: Sun, 1 Nov 2026 05:59:33 -0500 Subject: [PATCH 171/173] fix(server): retry a connected host that failed the capability check (#8423) * fix(server): retry a connected host that failed the capability check Every failure in a connected host's acceptance step was terminal: the row went to "error" with no retry, and the status listener ignored later reconnects. A host rejected with unsupported_capability stayed unusable after it was updated, until the registration was saved again or the managing daemon restarted. Capability and other non-identity acceptance failures now go "offline" with nextRetryAt and retry with capped backoff (1.5 s doubling to 30 s), so an updated host comes online by itself. Self, duplicate, changed-identity and authentication failures stay terminal. Fixes #7971 * fix(server): keep a retried host's relay security floor and update guidance A scheduled capability retry built a new transport factory, which dropped the relay security floor learned from a protected handshake, so the retry could negotiate legacy encryption and send credentials. Retries now reuse the registration's transport factory (createHostClient accepts one). The update guidance also stays visible while a retry connects, the backoff resets after a successful acceptance, and disabling or removing a host cancels its pending retry. --- docs/connected-hosts.md | 5 +- packages/client/src/node/index.ts | 7 +- .../server/connected-hosts/hosts.e2e.test.ts | 205 ++++++++++++++++++ .../src/server/connected-hosts/index.ts | 90 +++++--- 4 files changed, 278 insertions(+), 29 deletions(-) diff --git a/docs/connected-hosts.md b/docs/connected-hosts.md index 20c86c1295..7e8b67ee62 100644 --- a/docs/connected-hosts.md +++ b/docs/connected-hosts.md @@ -74,7 +74,10 @@ registrations remain inspectable; a changed destination requires explicit identi Both daemons advertise `connectedHosts`; the shared link additionally requires `hostMultiplexing`. A completes capability and pinned-identity checks on each physical recovery before admitting channels. There is no local fallback. An older daemon continues to serve existing local -operations; requesting this feature gives update guidance. +operations; requesting this feature gives update guidance. The registry retries an older destination +with capped backoff, so it comes online once updated. Self, duplicate, changed-identity, and +authentication failures stay in `error` until an update changes the connection, `enabled`, or +`replaceIdentity`, or A restarts. Disposing a routed API releases its observations and session. It does not remove the saved host or affect sibling API scopes. Disposing the origin cascades to its derived scopes. Observations restore diff --git a/packages/client/src/node/index.ts b/packages/client/src/node/index.ts index 30d2b8744f..464d16332d 100644 --- a/packages/client/src/node/index.ts +++ b/packages/client/src/node/index.ts @@ -204,15 +204,16 @@ export function createHostTransportFactory( } export function createHostClient( connection: string, - config: Omit & HostTransportOptions, + config: Omit & HostTransportOptions, budget?: HostTransportBudget, ): DaemonClient { const target = parseHostTarget(connection); - const { webSocketAgent, ...clientConfig } = config; + const { webSocketAgent, transportFactory, ...clientConfig } = config; return new DaemonClient({ ...clientConfig, url: "ws://host-connector/ws", ...(target.password ? { password: target.password } : {}), - transportFactory: createHostTransportFactory(connection, budget, { webSocketAgent }), + transportFactory: + transportFactory ?? createHostTransportFactory(connection, budget, { webSocketAgent }), }); } diff --git a/packages/server/src/server/connected-hosts/hosts.e2e.test.ts b/packages/server/src/server/connected-hosts/hosts.e2e.test.ts index 4c6d79aced..264589f82e 100644 --- a/packages/server/src/server/connected-hosts/hosts.e2e.test.ts +++ b/packages/server/src/server/connected-hosts/hosts.e2e.test.ts @@ -784,6 +784,211 @@ test("old capabilities fail before execution and authentication errors recover t expect((await online(paseo)).hosts[0]!.serverId).toBe(b.daemon.getServerId()); }); +async function updatableDestination() { + let features: { connectedHosts: boolean; hostMultiplexing: boolean } | undefined; + let holding = false; + const held: (() => void)[] = []; + let connections = 0; + const http = createServer(); + const ws = new WebSocketServer({ server: http }); + ws.on("connection", (socket) => { + connections++; + socket.on("message", (data) => { + const frame = JSON.parse(data.toString()); + if (frame.type === "ping") socket.send(JSON.stringify({ type: "pong" })); + if (frame.type !== "hello") return; + const reply = () => + socket.send( + JSON.stringify({ + type: "session", + message: { + type: "status", + payload: { + status: "server_info", + serverId: "srv_updated", + hostname: "updated", + version: "0.12.0", + ...(features ? { features } : {}), + }, + }, + }), + ); + if (holding) held.push(reply); + else reply(); + }); + }); + http.listen(0, "127.0.0.1"); + await once(http, "listening"); + cleanup.push(async () => { + for (const socket of ws.clients) socket.terminate(); + await new Promise((resolve) => ws.close(() => resolve())); + await new Promise((resolve) => http.close(() => resolve())); + }); + const address = http.address(); + if (!address || typeof address === "string") throw new Error("Missing destination port"); + return { + port: address.port, + connections: () => connections, + hold: () => { + holding = true; + }, + update: () => { + features = { connectedHosts: true, hostMultiplexing: true }; + holding = false; + for (const reply of held.splice(0)) reply(); + }, + }; +} +async function capabilityRetry(paseo: ReturnType): Promise { + let retryAt = ""; + await expect + .poll( + async () => { + const row = (await paseo.hosts.list()).hosts[0]; + retryAt = row?.nextRetryAt ?? ""; + return row; + }, + { timeout: 5000 }, + ) + .toMatchObject({ + status: "offline", + nextRetryAt: expect.any(String), + error: { code: "unsupported_capability" }, + }); + return Date.parse(retryAt); +} + +test("a destination updated past unsupported_capability keeps its guidance while retrying and comes online, while duplicate_host stays terminal", async () => { + const destination = await updatableDestination(); + const a = await daemon(); + const { paseo } = await api(a); + const host = await paseo.hosts.add({ connection: `127.0.0.1:${destination.port}` }); + await capabilityRetry(paseo); + destination.hold(); + await expect + .poll(async () => (await paseo.hosts.list()).hosts[0], { timeout: 5000 }) + .toMatchObject({ status: "connecting", error: { code: "unsupported_capability" } }); + await expect(paseo.hosts.client("srv_updated")).rejects.toMatchObject({ + code: "unsupported_capability", + }); + destination.update(); + expect((await online(paseo)).hosts[0]).toMatchObject({ + registrationId: host.registrationId, + serverId: "srv_updated", + nextRetryAt: null, + error: null, + }); + await paseo.hosts.add({ connection: `ws://127.0.0.1:${destination.port}/ws` }); + await expect + .poll(async () => (await paseo.hosts.list()).hosts[1], { timeout: 5000 }) + .toMatchObject({ status: "error", nextRetryAt: null, error: { code: "duplicate_host" } }); +}); + +test("disabling or removing a host cancels its pending capability retry", async () => { + const destination = await updatableDestination(); + const a = await daemon(); + const { paseo } = await api(a); + const host = await paseo.hosts.add({ connection: `127.0.0.1:${destination.port}` }); + let retryAt = await capabilityRetry(paseo); + let connections = destination.connections(); + await paseo.hosts.update(host.registrationId, { enabled: false }); + await new Promise((resolve) => setTimeout(resolve, retryAt - Date.now() + 500)); + expect(destination.connections()).toBe(connections); + await paseo.hosts.update(host.registrationId, { enabled: true }); + retryAt = await capabilityRetry(paseo); + connections = destination.connections(); + await paseo.hosts.remove(host.registrationId); + await new Promise((resolve) => setTimeout(resolve, retryAt - Date.now() + 500)); + expect(destination.connections()).toBe(connections); +}); + +import { + createDaemonChannel, + exportPublicKey, + generateKeyPair, + openDaemonSecureChannel, + type Transport, +} from "@getpaseo/relay/e2ee"; +test("a capability retry over a relay keeps the protected endpoint security it negotiated", async () => { + const keys = generateKeyPair(); + const legacyReceived: unknown[] = []; + let connections = 0; + let retryClosed = false; + const http = createServer(); + const ws = new WebSocketServer({ server: http }); + ws.on("connection", (socket) => { + connections++; + const wire: Transport = { + send: (data) => socket.send(data), + close: (code, reason) => socket.close(code, reason), + onmessage: null, + onclose: null, + onerror: null, + }; + socket.on("message", (data, isBinary) => { + const bytes = Buffer.from(data as Buffer); + wire.onmessage?.({ + data: isBinary + ? bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) + : bytes.toString(), + isBinary, + }); + }); + socket.on("close", (code, reason) => wire.onclose?.(code, reason.toString())); + if (connections > 1) { + socket.on("close", () => { + retryClosed = true; + }); + void createDaemonChannel(wire, keys, { + onmessage: (data) => legacyReceived.push(data), + }).catch(() => {}); + return; + } + const channel = openDaemonSecureChannel(wire, { + daemonKeyPair: keys, + events: { + onmessage: (data) => { + if (typeof data !== "string" || JSON.parse(data).type !== "hello") return; + void channel.then((secure) => + secure.send( + JSON.stringify({ + type: "session", + message: { + type: "status", + payload: { + status: "server_info", + serverId: "srv_relayed", + hostname: "relayed", + version: "0.12.0", + }, + }, + }), + ), + ); + }, + }, + }); + void channel.catch(() => {}); + }); + http.listen(0, "127.0.0.1"); + await once(http, "listening"); + cleanup.push(async () => { + for (const socket of ws.clients) socket.terminate(); + await new Promise((resolve) => ws.close(() => resolve())); + await new Promise((resolve) => http.close(() => resolve())); + }); + const address = http.address(); + if (!address || typeof address === "string") throw new Error("Missing relay port"); + const a = await daemon(); + const { paseo } = await api(a); + await paseo.hosts.add({ + connection: `relay://127.0.0.1:${address.port}/srv_relayed?key=${encodeURIComponent(exportPublicKey(keys.publicKey))}`, + }); + await capabilityRetry(paseo); + await expect.poll(() => retryClosed, { timeout: 15000 }).toBe(true); + expect(legacyReceived).toEqual([]); +}); + test("an unreachable saved target becomes online after its daemon starts without being added again", async () => { const reservation = createServer(); reservation.listen(0, "127.0.0.1"); diff --git a/packages/server/src/server/connected-hosts/index.ts b/packages/server/src/server/connected-hosts/index.ts index 15b1e16b97..bfff76239c 100644 --- a/packages/server/src/server/connected-hosts/index.ts +++ b/packages/server/src/server/connected-hosts/index.ts @@ -7,10 +7,12 @@ import { z } from "zod"; import { createHostClient, createHostChannelTransport, + createHostTransportFactory, parseHostTarget, HostTransportBudget, } from "@getpaseo/client/node"; import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; +import type { DaemonTransportFactory } from "@getpaseo/client/internal/daemon-client-transport-types"; import { HostSummarySchema, HostAddSchema, @@ -235,23 +237,30 @@ export class ConnectedHosts { if (route.registrationId === id) route.close(code, "Host access was disabled, replaced or removed"); } - private start(row: Saved): void { + private start( + row: Saved, + resume?: { failures: number; transports: DaemonTransportFactory }, + ): void { if (!row.enabled || this.closed) return; - let stopped = false; - const client = createHostClient( - row.connection, - { - clientId: `host-link-${this.self.serverId}-${row.registrationId}`, - connectTimeoutMs: 10000, + const transports = + resume?.transports ?? + createHostTransportFactory(row.connection, this.budget, { webSocketAgent: webSocketProxyAgent, - }, - this.budget, - ); + }); + let stopped = false; + let attempts = resume?.failures ?? 0; + let retry: ReturnType | undefined; + const client = createHostClient(row.connection, { + clientId: `host-link-${this.self.serverId}-${row.registrationId}`, + connectTimeoutMs: 10000, + transportFactory: transports, + }); const live: Live = { client, accepted: false, stop: () => { stopped = true; + clearTimeout(retry); void client.close(); }, }; @@ -285,7 +294,7 @@ export class ConnectedHosts { if (info.features?.connectedHosts !== true || info.features?.hostMultiplexing !== true) throw new HostError( "unsupported_capability", - "Update the destination daemon to use connected hosts.", + "Update the destination daemon to use connected hosts; retrying automatically.", ); // Pin and persist under the same writer as management to prevent discovery races. await this.mutate(async () => { @@ -304,16 +313,22 @@ export class ConnectedHosts { if (stopped || client.getLastServerInfoMessage() !== info || !client.isConnected) return; Object.assign(row, next); live.accepted = true; + attempts = 0; this.changed(); }); } catch (error) { if (stopped) return; - row.status = "error"; row.error = connectionFailure(error, client.authFailureReason !== null) ?? { code: "host_offline", message: "Host connection failed", }; - row.nextRetryAt = null; + if (terminalFailures.has(row.error.code)) { + row.status = "error"; + row.nextRetryAt = null; + } else { + stopped = true; + retry = this.scheduleAcceptanceRetry(row, attempts, transports); + } this.changed(); await client.close(); } @@ -329,18 +344,17 @@ export class ConnectedHosts { if (route.registrationId === row.registrationId) route.close(); row.status = state.status === "connecting" ? "connecting" : "offline"; row.nextRetryAt = state.status === "disconnected" ? (state.nextRetryAt ?? null) : null; - row.error = - state.status === "disconnected" - ? (connectionFailure( - Object.assign(new Error("Check the SSH configuration and daemon credentials"), { - code: state.failureCode, - }), - client.authFailureReason !== null, - ) ?? { - code: "host_offline", - message: "Cannot reach host. Check the connection; retrying automatically.", - }) - : null; + if (state.status === "disconnected") + row.error = connectionFailure( + Object.assign(new Error("Check the SSH configuration and daemon credentials"), { + code: state.failureCode, + }), + client.authFailureReason !== null, + ) ?? { + code: "host_offline", + message: "Cannot reach host. Check the connection; retrying automatically.", + }; + else if (row.error?.code !== "unsupported_capability") row.error = null; if (row.error?.code === "authentication_failed") { row.status = "error"; row.nextRetryAt = null; @@ -351,6 +365,18 @@ export class ConnectedHosts { }); void client.connect().catch(() => {}); } + private scheduleAcceptanceRetry( + row: Saved, + failures: number, + transports: DaemonTransportFactory, + ): ReturnType { + const delay = acceptanceRetryDelayMs(failures); + row.status = "offline"; + row.nextRetryAt = new Date(Date.now() + delay).toISOString(); + const retry = setTimeout(() => this.start(row, { failures: failures + 1, transports }), delay); + retry.unref(); + return retry; + } async openRoute(input: { serverId: string; scopeId: string; @@ -531,6 +557,20 @@ export class ConnectedHosts { } } +const ACCEPTANCE_RETRY_BASE_MS = 1500; +const ACCEPTANCE_RETRY_MAX_MS = 30_000; + +function acceptanceRetryDelayMs(failures: number): number { + return Math.min(ACCEPTANCE_RETRY_BASE_MS * 2 ** failures, ACCEPTANCE_RETRY_MAX_MS); +} + +const terminalFailures = new Set([ + "server_id_mismatch", + "self_host", + "duplicate_host", + "authentication_failed", +]); + function connectionFailure(error: unknown, authenticationFailed: boolean): HostSummary["error"] { if (error instanceof HostError) return { code: error.code, message: error.message }; if (error instanceof Error && "code" in error && error.code === "authentication_failed") From 4fe44038e3fd31200bdd88fd13d6ec8617051e5c Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:35:50 +0000 Subject: [PATCH 172/173] test(server): check subdirectory diffs before and after commit (#8466) Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../checkout-diff-content.e2e.test.ts | 72 +++++++++---------- 1 file changed, 34 insertions(+), 38 deletions(-) diff --git a/packages/server/src/server/daemon-e2e/checkout-diff-content.e2e.test.ts b/packages/server/src/server/daemon-e2e/checkout-diff-content.e2e.test.ts index fe83c21305..56e7cdefb8 100644 --- a/packages/server/src/server/daemon-e2e/checkout-diff-content.e2e.test.ts +++ b/packages/server/src/server/daemon-e2e/checkout-diff-content.e2e.test.ts @@ -88,13 +88,9 @@ test.each(["uncommitted", "base", "commit"] as const)( 60_000, ); -test.each( - (["uncommitted", "base"] as const).flatMap((mode) => - (["single", "batch", "rename"] as const).map((shape) => ({ mode, shape })), - ), -)( - "$mode $shape diff includes hunks from a repository subdirectory", - async ({ mode, shape }) => { +test.each(["single", "batch", "rename"] as const)( + "%s diff includes hunks from a repository subdirectory before and after commit", + async (shape) => { const ctx = await createDaemonTestContext(); const cwd = mkdtempSync(join(tmpdir(), "checkout-diff-subdirectory-")); @@ -112,9 +108,7 @@ test.each( } git(cwd, "add", "."); git(cwd, "-c", "commit.gpgsign=false", "commit", "-m", "initial"); - if (mode === "base") { - git(cwd, "checkout", "-b", "feature"); - } + git(cwd, "checkout", "-b", "feature"); const filename = shape === "rename" ? "renamed.txt" : "normal.txt"; if (shape === "rename") { git(cwd, "mv", "sub/normal.txt", `sub/${filename}`); @@ -123,36 +117,38 @@ test.each( if (shape === "batch") { writeFileSync(join(cwd, "sibling.txt"), "new sibling\n"); } - if (mode === "base") { - git(cwd, "add", "."); - git(cwd, "-c", "commit.gpgsign=false", "commit", "-m", "edit"); + async function expectSubdirectoryDiff(mode: "uncommitted" | "base") { + const compare = { mode, baseRef: "main" }; + const rootDiff = await ctx.client.getCheckoutDiff(cwd, compare); + const subdirectoryDiff = await ctx.client.getCheckoutDiff(subdirectory, compare); + const subscription = ctx.client.observeCheckoutDiff(subdirectory, compare); + const liveDiff = await subscription.ready; + await subscription.release(); + + expect(rootDiff.error).toBeNull(); + expect(subdirectoryDiff.error).toBeNull(); + expect(liveDiff.error).toBeNull(); + expect(liveDiff.files).toEqual(rootDiff.files); + expect(rootDiff.files).toHaveLength(shape === "batch" ? 2 : 1); + const file = rootDiff.files.find((candidate) => candidate.path === `sub/${filename}`); + expect(file).toMatchObject({ + additions: 1, + deletions: 1, + ...(shape === "rename" ? { oldPath: "sub/normal.txt" } : {}), + }); + expect(file?.hunks.flatMap((hunk) => hunk.lines)).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: "remove", content: "before" }), + expect.objectContaining({ type: "add", content: "after" }), + ]), + ); + expect(subdirectoryDiff.files).toEqual(rootDiff.files); } - const compare = { mode, baseRef: "main" }; - const rootDiff = await ctx.client.getCheckoutDiff(cwd, compare); - const subdirectoryDiff = await ctx.client.getCheckoutDiff(subdirectory, compare); - const subscription = ctx.client.observeCheckoutDiff(subdirectory, compare); - const liveDiff = await subscription.ready; - await subscription.release(); - - expect(rootDiff.error).toBeNull(); - expect(subdirectoryDiff.error).toBeNull(); - expect(liveDiff.error).toBeNull(); - expect(liveDiff.files).toEqual(rootDiff.files); - expect(rootDiff.files).toHaveLength(shape === "batch" ? 2 : 1); - const file = rootDiff.files.find((candidate) => candidate.path === `sub/${filename}`); - expect(file).toMatchObject({ - additions: 1, - deletions: 1, - ...(shape === "rename" ? { oldPath: "sub/normal.txt" } : {}), - }); - expect(file?.hunks.flatMap((hunk) => hunk.lines)).toEqual( - expect.arrayContaining([ - expect.objectContaining({ type: "remove", content: "before" }), - expect.objectContaining({ type: "add", content: "after" }), - ]), - ); - expect(subdirectoryDiff.files).toEqual(rootDiff.files); + await expectSubdirectoryDiff("uncommitted"); + git(cwd, "add", "."); + git(cwd, "-c", "commit.gpgsign=false", "commit", "-m", "edit"); + await expectSubdirectoryDiff("base"); } finally { await ctx.cleanup(); rmSync(cwd, { recursive: true, force: true }); From 919e44b3195452a8dcdc0bbbfa7e7a7d3b8ca252 Mon Sep 17 00:00:00 2001 From: Dominic <33105147+DAnaeto@users.noreply.github.com> Date: Sun, 1 Nov 2026 07:59:34 -0500 Subject: [PATCH 173/173] fix(server): start configured plugins concurrently (#8427) The daemon accepts connections only after its configured plugins have started, and PluginService.start started them one at a time, so each plugin's build and process launch added to daemon startup. Configured plugins now start together. Their providers and usage sources are still published in config order: a plugin that finishes early waits for the plugins listed before it, so when two plugins claim the same provider or usage-source ID, the one listed first keeps it, as before. A failing plugin still fails on its own. Fixes #7979 --- .../src/server/plugins/index.posix.test.ts | 168 +++++++++++++++++- packages/server/src/server/plugins/index.ts | 28 ++- 2 files changed, 185 insertions(+), 11 deletions(-) diff --git a/packages/server/src/server/plugins/index.posix.test.ts b/packages/server/src/server/plugins/index.posix.test.ts index 1f8b3f124b..60216ff0fa 100644 --- a/packages/server/src/server/plugins/index.posix.test.ts +++ b/packages/server/src/server/plugins/index.posix.test.ts @@ -20,6 +20,7 @@ import { DaemonConfigStore } from "../daemon-config-store.js"; import { PluginService } from "./index.js"; import { BuiltinPluginLoader } from "./builtin/index.js"; import { ManagedPluginSources } from "./managed-source.js"; +import type { PluginProviderMetadata } from "./plugin-process-protocol.js"; import { startNpmRegistry, npmPluginPackages, @@ -179,6 +180,55 @@ function createPluginSelectivePausedRuntime(pausedPluginId: string) { return { runtime, started, releaseStart, starts }; } +function createGatedRuntime(providers: Record = {}) { + const gates = new Map>(); + const gate = (pluginId: string) => { + const existing = gates.get(pluginId); + if (existing) return existing; + const created = Promise.withResolvers(); + gates.set(pluginId, created); + return created; + }; + const begun: string[] = []; + const running = new Set(); + const runtime: TestPluginRuntime = { + ...emptyUsageRuntime, + catalog: () => [...running].map((id) => ({ id, clientBundle: "bundle" })), + invoke: async () => undefined, + getLogs: () => [], + clearLogs: () => undefined, + getProviderRegistrations: (pluginId) => + running.has(pluginId) ? (providers[pluginId] ?? []) : [], + startPlugin: async (pluginId) => { + begun.push(pluginId); + await gate(pluginId).promise; + running.add(pluginId); + }, + stopPluginById: async (pluginId) => running.delete(pluginId), + stopAll: async () => { + running.clear(); + }, + subscribe: () => () => undefined, + bindPaseoSessionHost: () => undefined, + }; + return { + runtime, + begun, + finish: (pluginId: string) => gate(pluginId).resolve(), + fail: (pluginId: string, error: Error) => gate(pluginId).reject(error), + }; +} + +function nextNotification(service: PluginService, pluginId: string): Promise { + return new Promise((resolve) => { + const unsubscribe = service.subscribe((notified) => { + if (notified !== pluginId) return; + unsubscribe(); + resolve(); + }); + }); +} + describe("PluginService", () => { it.each([ { shadow: false, runtime: "subprocess" }, @@ -372,15 +422,127 @@ describe("PluginService", () => { "startup-first": { source: "directory", path: first }, "startup-second": { source: "directory", path: second }, }); - const snapshots: string[][] = []; - service.subscribe(() => snapshots.push(catalogIds(service))); + const notifications: { pluginId: string; running: boolean }[] = []; + service.subscribe((pluginId) => + notifications.push({ pluginId, running: catalogIds(service).includes(pluginId) }), + ); await service.start(); - expect(snapshots).toEqual([["startup-first"], ["startup-first", "startup-second"]]); + expect(notifications).toEqual([ + { pluginId: "startup-first", running: true }, + { pluginId: "startup-second", running: true }, + ]); + expect(catalogIds(service)).toEqual(["startup-first", "startup-second"]); await service.stopAllPlugins(); }, 20_000); + it("starts configured plugins concurrently and publishes them in config order", async () => { + const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-home-")); + roots.push(home); + const gated = createGatedRuntime(); + const service = createService( + home, + { + alpha: { source: "directory", path: "/plugins/alpha" }, + beta: { source: "directory", path: "/plugins/beta" }, + gamma: { source: "directory", path: "/plugins/gamma" }, + }, + { runtime: gated.runtime }, + ); + const notified: string[] = []; + service.subscribe((pluginId) => notified.push(pluginId)); + let started = false; + const starting = (async () => { + await service.start(); + started = true; + })(); + + await expect.poll(() => gated.begun).toEqual(["alpha", "beta", "gamma"]); + + gated.finish("gamma"); + const alphaPublished = nextNotification(service, "alpha"); + gated.finish("alpha"); + await alphaPublished; + expect(notified).toEqual(["alpha"]); + expect(started).toBe(false); + + gated.finish("beta"); + await starting; + expect(notified).toEqual(["alpha", "beta", "gamma"]); + expect(catalogIds(service)).toEqual(["alpha", "beta", "gamma"]); + await service.stopAllPlugins(); + }); + + it("starts the other configured plugins when one fails while they are still starting", async () => { + const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-home-")); + roots.push(home); + const gated = createGatedRuntime(); + const service = createService( + home, + { + broken: { source: "directory", path: "/plugins/broken" }, + healthy: { source: "directory", path: "/plugins/healthy" }, + }, + { runtime: gated.runtime }, + ); + const notified: string[] = []; + service.subscribe((pluginId) => notified.push(pluginId)); + const starting = service.start(); + + await expect.poll(() => gated.begun).toEqual(["broken", "healthy"]); + const brokenPublished = nextNotification(service, "broken"); + gated.fail("broken", new Error("startup exploded")); + await brokenPublished; + gated.finish("healthy"); + await starting; + + expect(notified).toEqual(["broken", "healthy"]); + expect(catalogIds(service)).toEqual(["healthy"]); + expect(await service.listPlugins()).toMatchObject([ + { id: "broken", status: "failed", error: "startup exploded" }, + { id: "healthy", status: "running" }, + ]); + await service.stopAllPlugins(); + }); + + it("keeps a provider ID with the plugin listed first when both start at once", async () => { + const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-home-")); + roots.push(home); + const gated = createGatedRuntime({ + first: [{ id: "shared-agent", label: "First agent" }], + second: [{ id: "shared-agent", label: "Second agent" }], + }); + const service = createService( + home, + { + first: { source: "directory", path: "/plugins/first" }, + second: { source: "directory", path: "/plugins/second" }, + }, + { runtime: gated.runtime }, + ); + const starting = service.start(); + + await expect.poll(() => gated.begun).toEqual(["first", "second"]); + gated.finish("second"); + gated.finish("first"); + await starting; + + expect(service.getProviderRegistrations()).toMatchObject([ + { id: "shared-agent", label: "First agent" }, + ]); + expect(catalogIds(service)).toEqual(["first"]); + expect(await service.listPlugins()).toMatchObject([ + { id: "first", status: "running" }, + { + id: "second", + status: "failed", + error: 'Plugin second cannot register provider ID "shared-agent" twice', + }, + ]); + await service.stopAllPlugins(); + }); + it("uses an explicit config key, exposes reload failure, and retries from disk", async () => { const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-home-")); roots.push(home); diff --git a/packages/server/src/server/plugins/index.ts b/packages/server/src/server/plugins/index.ts index 5dad547d5c..65faa39f75 100644 --- a/packages/server/src/server/plugins/index.ts +++ b/packages/server/src/server/plugins/index.ts @@ -230,11 +230,18 @@ export class PluginService { } }); if (config.pluginsEnabled === true) { - for (const [pluginId, source] of Object.entries(config.plugins ?? {})) { - if (source.enabled === false) continue; - await this.startConfigured(pluginId); - this.notify(pluginId); - } + let earlierPublished: Promise = Promise.resolve(); + await Promise.all( + Object.entries(config.plugins ?? {}) + .filter(([, source]) => source.enabled !== false) + .map(async ([pluginId]) => { + const publishTurn = earlierPublished; + const starting = this.startConfigured(pluginId, publishTurn); + earlierPublished = Promise.all([publishTurn, starting]); + await starting; + this.notify(pluginId); + }), + ); } this.configStore.onFieldChange("pluginsEnabled", (value) => { this.handleGlobalSwitch(value === true); @@ -560,12 +567,12 @@ export class PluginService { }).catch((error) => this.logger.error({ err: error }, "Failed to enable plugins")); } - private async startConfigured(pluginId: string): Promise { + private async startConfigured(pluginId: string, publishTurn?: Promise): Promise { const source = this.configStore.get().plugins?.[pluginId]; if (!source || source.enabled === false || !this.canPublish(pluginId)) return; this.errors.delete(pluginId); try { - await this.startPlugin(pluginId, source.path); + await this.startPlugin(pluginId, source.path, publishTurn); } catch (error) { if (this.canPublish(pluginId)) this.recordFailure(pluginId, error); } @@ -594,8 +601,13 @@ export class PluginService { ); } - private async startPlugin(pluginId: string, sourcePath: string): Promise { + private async startPlugin( + pluginId: string, + sourcePath: string, + publishTurn?: Promise, + ): Promise { await this.runtime.startPlugin(pluginId, sourcePath, () => this.canPublish(pluginId)); + await publishTurn; try { await this.publishProviderRegistrations(pluginId, sourcePath); this.publishUsageSources(pluginId);

zRJv;nihLDvQJ_BwOaefR8cD74Asa@KgW9&A zDFzFe7UKm41vNiT5d@`Bp`2%rKEg*4@ZD)M?+6vXd42U{bMM05;^A+Jo7fXMclMtP z*zHDTR8~=KXP14KZIV~IsWrj>lk+PHQ`1~C14e5Pn5U;JrEpV95I+)SF}F?Ur*xsl zLHce6iuOj&0%Z-2t<_cfzKpCaB&121CBN>nLGlb`J` zrW=qGFL9*;RH(kZoT#YijhOPUqkj6VAj#{`pMG1_;nPyyQOyZIYE@kb=#( zgs?Rk`TO{FvmZ-JEPaV${?;fpG~?r}*nO$#2qi5jlhlA<0t=`A{!tbFx+aIZ`WScm z10f*{2|hkKEHGqYdr!cWJ+Ve85l*}ssdq;a~(ROv}-xXya-5W0! z`k%Q-a3y}KGD1gBy}iK*<~*bd;ZfWbyS}P_-^WCDn(c=Df3W~4s=Gex&NTaIs;D?h zNlnhWDM9Ej6gqk7=}IsJaXjpPNd#eVdJT{KPL|!ck+}5FFK6B2081X|?*|QRFOYn0 zAR$3L0A5p?+S(^WkJIs}Cqcz&02-t1I`ch10H8i)H40;TM6j7E>6=yKLmvZ zq`!^k${j!=wb7n}j0`9~YOgLWL3CGHUcNO^>ISz+D2}K>Ek0O@T&EjBO+e9?=d0~| z?kL&t!uEk{Bw;GvCXmCfZ`S{yyAm=L9mZHN7#b_l^J0=GKRX!N2VCyYrVz_$=a1pN zJ=wL)#>T9oqM6xQ+m${qn77mVoe!0j4Ngr>nfCg&wv8waKo`*g#y(J8Z>+CFx;BGy zx~EkMjFVxQJC^vg-qqsue7rlizr0qQd2iUGQ~garKEI&gSuDi?&z}kNGF795r+RuE z@D0zr*JAevLy1hwTQ?>2bak_`g~+FaFjI+`blKPzAotvcg8ee4Yg06K`AVDFYV0$F3l7p6H|wObeF!jw=v)}C=5$4ZV3zX^7HG>3A3@? z7Zg;VX*aaNS#q?sRd_bVA6@aKIPA@EZ*XfqT{wsixrBumdlD;)im2sNppLTg5^Dgb zM9KJh@`3QTZy#okGn+aP_v7**(th~)CnrB2S>aA9EfEGNVY0C(8lV3z9Wcym4@Vlg zgw@c!`NStlYmb?IvbIJ&sHR>8b#1^H`FPiUaJA`q(X@;bwqIwK}iEyOd~7SWNd zRARp8$>iI&GyQ2b3vYr|$=~oG@sbNNneqgJdMz=Jn<*__$--V262iZ9c9J48R9}C< z8_rs_cw#7m4=yi1+}I*NIYFtZ6(_mnN<~FQN5|!8eZy-4!d0g#F}f6{gYVDSV_`xCXo3f+xp>v>?t-9hJ09^R@NJEWD)mktE-2c2&}SvhE8r}WxOY4(ca$HP_Y;n zj*!!cs0 zq4=QvH-;Q>qqfd;Z9_xP`D%Q+K{#EHwY`0qO?RF2bCS@JpFf}G{9IfF$`rQn+IoRT zTsOHDb^##w6nC=q)Z08Gfhs* z1=On+S*|?;0~3Eje}P8I2n{#i?QQ4c6?l(vLu{_02o531ma{Oqr#!(x08=g5otiF~`A8Fgfs=9V6|A44lW2X|6p4SP`Rpk+KY z{f8Wpx3N-$@i$z6Z4gK*2S43f1y|%PF2}_4!wI*bI>)FLJ7@&+rSwmt*r0iU__T8 zn;4e(J;{cw2$idkA1CBXiN$E?v0mc8zZ0&Y9fpk&W=?dwka!&v{`H+xX~;-E$7{Ca zrtgIPCu3gan7g9x)y9|7=T^C0qyGG?)auA5teVBQ=nJrX$Zcb!hCbvwTL9g{((;bW zygfyU1YUrU6$y$IS$jI(l+3p?^!`_v&uMv((aJFDer294XYP z`36eX9HTCUy$3i(q!aCh*!M0xSzV}9+oLSs;~=|av|MFsDB&iKLMa!6u# z020@G!F~NNzm~o(0%7*L<|ls+tN{)_KJu3vu+62&bnep*JhT*&RaE@`$_3XPgFXFjRFk~rC$3>3;(bKRQU29%f_n#f z4?AfVYwq9Z%?#vzm9%xNNs!+8RBaHuOP#z2h;eMOgHFRGD8e_yZ~D$^mtl{1w@|zt z+Zty2;D4qiCB>3OXr&iJ@s$|)aaKOQ1^FAaoL4FC+NWU%ViHb)2u2IB-(@}Ug833% zE$p{()S1YV;5B>Xn3BXKJEo_eEp~n+h5<2}74^~6+nL(g`l05?eVO5pHBe@DmE$Sp zsrp~HV-jRBaHj!-BhZDPRj)WfnYy1ZAgqt%CXZvoy-7^vSLjHNAr=I2d=XTVTff6k zlgHi9qnI?JOMpbO!fx@3T<)k|Puk*uY8^+@uUCmBHpFu?sA}ddMoh>QoS>|vL#+3n z_W7eLV8QtQ__Y3O<&OK9FTQobC~kiYX#i3J>hlD}=BH6_J3eq2Xh@vP;2JGU+z9eP zZ6fxO*TAi;-@A9|%GOd&I9%B3q;2KG`kBc~$PBU4yno4?l<*7POYR#|Ax}J(Wb=Amymzxzk9CyNJ6;+xPmO5O0@;T_-`J1P=`hgQ%S7>==NnqLWK3X z8YDM0K8%gFiAjG*`>?j;ITvlT&~kNNGs8`6X9r}b$AeP#aI}`S^rUQOaUx zWhUN>;Z?m8Bb2RZ>(WhbSN2l~Uo9t6+N!!Dxg}Y?h%xJkpMO9I(e~h;!DM-`@{}Pg zgBK*+V1J>&9-#5TG4WjPv5_F^2!BOkDA zRU%by<`tD!HLJFy$l-=U_=cvh31bdUfdsF32CZU7A>cJ)r9U}ezV(*YzI~Ig*#Gi_ zJhd*_%=7kk!=mbdEJgXoXl-nm*exaHi8P4aXXf@1vYTPC(-oK5M_5#;^LP~%MbsD9 zvr+q$%c$F0d8N%Wi0;w!VEmrCywBt4iRB0CbsqpzLnmd;d}I20jwX?(WA-gE2NI8A zxV`7mGwkmS#>@4(=s<7KeS;RmSgeI`E^GJq|Vx5MbmG$N=KfSt`oLu6^ z_1q`pJIKVy;e@1j?{rTkhIH|Zxvu)uGWIWV^GSLaE+7}$W92}BeczdCaqE1+N zQ|Xb1`>NX;QS{uVCjKSt0i82+Qtw9Px)FM;PtTh6)b*EDTk!)TMSa^d{HSU@JCRAA9f+UFVSY~~}*AM(xJTXmy#``F#C2q`6- zeCtLrr`%LC*w8?<-!r?X~qFU>r1!jE~-0w^#?E?=gD zU%?Xcr3y(;dT4o%{XuZ$(B&h_4`B(hVWPs{kt3DPE$6ow+^UHtZd91`q^Cv8{@vae z`cv_Tz5VsukE@D`B<51d@aM5UA~+Lu&I~dOe952a?4;CCWsyAR_6#)?bEw@A!aTJ5 z!@c+1BtOQ8Q>rv8z{kgj`$KY?OkI6_XBYDu85L$tC&|U&;H9!MLlZ9iEakF?9ZDs;>70_>fiy1`zN({e_G37OpRi`wk*&{|Moy71Y%QGl5UvN8S zq-WLCko{~^&sSL1DLOnh{M4oa^~$r~SdhJNaSL0;375uF} ztDBZSHfc>uPsd}T;qHZqhA@rz{X3n*O?H|p`UpuR;Y?z`qRj@W1^Gj_ zWnnr>wLW(~Ti1ukfgbQKC0w=)^6YtMjS$Yo8uaU4p)z8`M4rop*cTB}3NzToXFa8& zr7ijNCmvBPp{2#nI!h#%Mr-S(9g=)T2bI~(AbWS-Cmm*n;CLMhwu=Ev*tD?>?+l+D z%kt7Q=M9dHsqj(YSCTVsl*R|+s=Xlj)J+hHQmt%yMYZ~%yY8NCI|-r*`xnubf^TnY zxbfq>6-HCgF0eaj(E&hq{>dsIwaPnHaRas2U5~!pFrKf8RVOejGqN%Y&zaMVCErbJ42Gq9 zS!HE?y@ePCDfM>-k>t@W#SNpalnu$L!_yYg_vwq&xe>*0bZiBiqzG4qwRb)}H!10( zd|=>KR+4U{)oEB2it=3p{IDwmrzSvK)gEys{xbtS0k(`L43RS||C8E_!#obKaj5eO=0@#|JOqcl5``&__ zaMGh#32ki(T;uv}eq)JMlT>?`@8?5)*-tc@rJ?_?AtP=L#vi6PROMi0{g|I$R#kR* zZIpjLMMco&Y?0-VX&PkTYa!7|x}He{$Yo&E=`9di`~?q(T^um@{(*=vnQxFll>aX@ zDJ}N@__4Ad;`xXY6`0O?t_|mcA*(ogIX;ZLz(Ek4eDcaoy3qgOn=&J+N{Hv5iInJs zJ^8>-8((4_#Vi)4`e6G2esJS%KTb;j!~5mqIV5O>(s2n4I8hjK+Q0Iip`+C9gA3hr+%I|YAC?LA2GXMR*oR14`|6!Cc1XrT7 z{9im~zr=ou)dh|9)YP*XV`y$nCd)E^j?>e(`mOYx{fCwoJY%ekkk$(_kdxIRNf5q3 z?#FLU10R5EnCvLP;TL>O1)>7o-Q6>!K!HMdXxbL&0TbthF0eQD06o*P* z2(PtJ^!YAYuN=uR7LS=+xnF|Lv`*yi2_H)02_J9P7`zj7{&{gU=ji10N*ooBw(`a1Iz**59gbgt zEqaG3TneiDB_Px}GkgLrPL>1jga!ew9I+@YJu18{P^zOECeQFN*+|( zio$c`P<3l}K580V7v!i~ETwzrOjnfaH`}k@{lp>VnM0%fezcl4P#U zXLE|quz2j7q?(%7bD?{GW=;=9SyA;bKFzb>XM!9)w^RJHAy!PTiK*nWYjFxfmg zDe37~W;$5h`)>u~9zCiK{T-YQIhZak%rc+hZE7dVq73D~j&IA);01rs_mJ2*s*2@! zy6x98)8aR0{$Be4+zDF_hOx3A#U%Iw;^V+=)Ltuk<*{&exm^fU6Rfgl@bwT2NCaLU zmil=d%^qFtCI8xLbO!E&@XMDk5k+ec2K<^2_6Kw-_jmqGM*($O$oR7!81#d65m`*) z^0uE}W?9+lw0$xtOwb_y!l2yvI+YHHA&K$v=(Dtxlt`kiiTv$9+~y9*^xYwJMe^!o zfDIh%cF+B;j!>Wf8Bw}ANj7*PdN}&}^77Kb`_z*97zjXHpp}+vV|ex7n}UyZ2IcfL zI3#3Y4%C9SU4@z>IYP&4c{p?4+4u5+=H7DrQ}p`nZ#O!B2Cq>O5X%ZQU!JCMJBghA zb{^i3;%e4aQ8BW%#yVpz`pA99`f(v0Nh~a&GqAmWf)`&KMS9`7{liCKYqnwHbHrke z-RuYCu+0Nt0nax3Fvqr>uBSOJb^_b|);YUg{qHWiiFO_ij{dGLGztMX&PPQ1b=DJi zD|rz<;yLOoEAI@;UA^K&?G0pC*VJSLa&%W$hcF{!ZdMj`s&>mC`o_$7C5Q{P9`6HT ztpoGKYo|JuTU|>)SZ2xZ66df33X45o+0u76_@AaCv>@>tEYCw6 z-}_x|gVsU7@A9B0v6rDN#7vbf$duoP^Z=zk5*(4$98qS5RHT818{f_|I!Fk-qin{DjI2FHmmL@N`>KRa>X}$9v0}D zVbdFA7Aib9?23KobBayQYvyfd_v8MYH-^fy?N8*$sMkm(=+C=VPiU(KSr#yen2y%R z@a}=YXioXz|6FEqL>p3Y2>a0rJ&U_#k^2^wTRl3my9_!sFml+TA@4vXLQQUW(t- zHGZAZUJTI;x>uJ+SK5`U6xYiRFBYi8FvI6wknIBB!_VV|6Lj}}Ld-|dYRG6@L|vIt z$D>*;s4UpzG&Eko0$tLW6bS8v^l4(Voy{6K5C^6YJly9Cwu6l__m-|{E`o1S$@I>58KYb#6uphzvzNEM~Q4_K&cV8f~UAQMn*K74DO0q?dBA0;F{{{mpdJ)Adi+kTL;%CVgiC@ zw{1=;s%fAE^`+&-E_C1}w*rMBJ=6YWIecCkftBU9*0b4-(kteN52^R`Q6CS12>B2M zAVBypP}6|x=VqZ|VtVqsVgS4eRMPIf1Q&d8a-M~q2ZA>SDlK_SG^KXauNvRKdNmAR z0pLoomSbpyC}Tyh8kgU>{Rl*@{`A!6@+27sE2RJP*|kW>lC_94^crxpP>3igQ{TTY zxp+CP*HG$A~j8oVdl&kBE?XVy_2#*ba&hPThD?dP zE#0;#W1lh}lV1RH;xX`~aE7ca;JpOvT|hpFGAAfRE4BVH$0X1#tt=4jSb$^(IW{m^ z%xW9uVzsy5hJ0B^9T-5;5fC62x`L-KeTz6&Sq93#aeq>#_A~zzTnEXQ=_hp&Dzh)v z$$;~rTZ_;3pJHkW_5W0E8tyV_!4?pRKRj7myTcXr?=ye+VvI;lL2(D2A?8{-{*O(> zkaMS83jw?%Z-7f2{DOOJU7hd&H2nYmh@~t$X)E{01J z|F;z)$2%DFfz{^vI;FoVM6koW5e>~tXS!2U9;oSH{~9=h&He)=6|RY;+4+8YsZ~1D z?b|-*yP9By4B=PTZ(|sVg_Ef? z!1p_ttFr-Km0k&~5G#Pi^@NnC%)$B!V60m8odbajl2n;S&_;=@Huy;WC-;@*sP z_)8GD%A1f%95O|(tFEuFt)im+^r?o5%JSM86Q%r+0%$GE*jQ zPWxe?@2K|m#)#asLe;w3wD%(mj-QU-+r!kivf+&v01Pg_9SE$&x>RVZ4coeovh8hJisk5b#`E^`HxpC2H zi1e@|mDc(Go!=$=RZ`Nz*4FykT7b!CZGHV%42>aj2tXhqC0%H9+?gl9)_nWUkA{}d zK}t-|Z4`(yy1F_&uAd>g%%^D*9e+`zuR2t^+r^&d=6O-aDGkZ=%*Q zn_JzUdwy@Z5aN>9DS_YgEyL$KdY6cX9s@J&d%H|xf>u{%5j zghepffJcE8z7Z~gZ0J9!m7^dLYpwf`Uk5(EQg-sU} z9BkFH!QZ-!c0}CLmu+b27{=(FXwZeJg17GG%g1Km{Y%;Cd1!U|XR~Dn8k^H(?i0*e z_tOK9K28wPk@K!70*gmqA6!3v1>87$rlZrL1R4~P%VV}aw8ha3zn~LANNV)(_(Emh zDD=GBAGoEEH)JzY%XsTnZ*Q;3@lIPL>yL&b`sgGeBmigcHFI1=d3jp}KHfIJweM7& zGu}Z(8{t|oSVV_7$SO7$J=F$+&Rbq{rcanSqL#xcF;q1${S`eJyx=yrpQ_})caL`D zSGUsk58>x(;pRXNLP3!Z2)G2g`To9YivZA$)A1-rx348bP9QIYQ>@mgBMHtq6JMY9 zV4lq>>2-6A!=QqAB=x*dqu~Vp@8L2y(SFh$Vsm0aOpJPe4iDF+Ys|r=Kc}JmkAy4a z7ZI;q=r?VNIl3ALEsM9DDBGVM(RC7I_l=gR^pbteaGEH+0$zSpekIU#AXMWnC+9*J z-Tj}#)An2ukyc^VBN6AQ6WoBfKIq0tcOAckP0@XCd>Sb_&kt^C2wJ0R1eb4{=g)&j zCzD3nN{m@2Lz*9?s(kD|L> zAouJ>n8A5eLWda(#|I_`MyQsw12|`n-hMUN>~j=O5cD{X7BL2SUqEfE@6D0eq-6h3 zan7jFMS@$QhNlSazk9iozuq=fnX7lz1nbnRgFG(=TyWnpk(ql;=R?oOhrCPPN3w4I zC6fO^(f|+)1@67PR~Sa46&4sMLHvDe>@YLTOyV?)38HO+J3S4Hn#PN#NAm_~pd^Dm z_v=u0p3BWqdy(i|kZ6N=9MXEWgXBXTwO;IT=)BNxNZMV^u7C;ui(TUxklm`(#JAP* z*-kCN3Sa&8r}OVub+cP2Z|1NEd00euyBrzm=dSs0D@Z76GAV(Y1!tde_>xwr)) zQ!pPMyC2EKTY(K=6!1+m7nndK3EySdk3o^n-1YSW$aT>=sl>5xxLQv3QD#aRA+cIm zsD1u58J}V5(JY*r?K7u49Tj~CT)PJc4sLE;*}#faw&?R2cvvB3mxq|V*rg=V2_6<7 za&x`BysGSIaE~Z>Kai4<-C}hwtJYYs67z3qySWk8j>ul4Y*75HuA7(2U$H0r=IOvn9CZ^SRK`{~u*5!za%r1G*{ z>NXPStmI>#9*jXf>S)|<{@9ybxLhuOu(!;{oz$+vNBiT)4-Ji$iRxyWNeHD)>4#Gd z>Ni7c=~A)xSXfv?<0(?D(GhKbBy!uhf3&nbdlwpv+@@AYlk+1QAkS=Fk2fEbK?cG@9L&As{+t1vd?Og9GnNlO4Bj}sM9IJ6(h6+`jG8ua!hT2>W4I(7uO>_?Px1Ha^vs@Y`Up#d(925^Lf9ToF0H z6*+N~N{@(3NWd|LZR7f-y4+ctTM{Bry&H%I^^fsU(JEylk!~%r{ z6}`c7IWWuQKdl76VnGR*kyzfIEPs4Qz-C3jf3@e^w*YxA1*o!T4<@NZH_XD4bL z^URWhoN}GBdXp$qa9T@L6c%B-%X6!B^@k|IX1kP%yTlHzwjnm*o&hIr(PDkO5Q^n| z!gD)9!PhqvN~kQf;GXoW^W&diw&hHxK}G)MTM@O1A{nWm`v?Zx7h0)zdv}>DOS0m3 zE6?_NbKxup`kkNN6)?p$v%WYhGBbqtG0HXX9k|%fKES?W{nO-+&;o}bQj%4Q7Lf5p zj6ctV!f7KILYs<>F_Y-9`Ir-MNk~X2RgN}l89<>a%EBTu2kMz%aUpK*)`^Lf%>%cN zCc%5&ES0Vs_ZBnmRBAgo;IpcBsSLH2HK*=}CL$#?{s~6!q;?RmG7M}r^fEfg73Qql zGJcr((E|+)Eq4Vp9gLz%I5&i_+rfeY9HkHnu=Xiw9#j&o4CU~{Szbe5T|MrOlnmT# z(pIOlLeE~cOy3^l&!2VI$2saB$JwQ16R&@Ke#k4##8k~NH`(#_W833U;2!E4<__-I z3-D9f%*;}qEcOP+Q{6Bxwd2NjLXE>g%4Mygf0Zhg_Lq#Q;o<3d?eIW-1#L0k%Rvx4 zJ5m{x%^P`OcD!@?+TZUwStfogj#aE%_X3XAy|2aISY7jW)SVI(XY)i$cCM~Cjce?* zLhd^jbInalg?ZqM0=9u9F#(sTiZNdx82Rc?jo&ptwoA`y{#QDLb$cI(sZMsQ}dE z0fVRA-ODKDll26U3~RGhK^Mf7GwTgpVz~LqUYgk51S>;>D^DPN7CKzb2Ms7MtV%m@ zad92(D7V=EURbb$WQbj3T|L!CP9<1y9JTka+1Q7)q+gycuOoD2-8@8_=2S^d!zwO5A-L}4p?o1-<-D0R?F(+AIlwjxpg<(&%( zhLn_$Hd9 z+@sw*n&G{}&MuYD(fJFcljo`y8egMDu0^A-!BOp+)F{U|}`q1O8H~Hdj`de?) zZ*Sj7@Dg0MW0hVmb19{|?;fN2pBL#hAi4@T7#h4aF1S42RfYQVaTNL4JwiTb35i$L zy`aOdwxjXgnhAl@Ama;=qdkwB7fTvOqrS#eB`Xg^+dO)fa_HYS-rLK|#bwZ9y~alu zJ4D3I6Cm5XQ9^L{J#>eBXj^#k2Mi42fNZ}yi?sdzX@6(Iq&uaY7F4GkNi#D@f;HjO zci#KgN}E)d)z=p^Ha=Cv?D*1=JtRU;OqU+MCSy9LwD<{_TNP#s_XUIu@G!A@8yi!n zJ&iC8CG0d={Oz$aFm`|QRlluTxMVC7d#3&IV8TvaU43Fy4RpGzdB(;sGJG@RZQ0n^ z-aSl6NN6Xv*$L{bVP`=PX3Mz~3l8NF{3a&74q&e}08Wi%$mGMzXJdZy?G9d*?kcsmD|2`Hn zf+sTo$Gz`F?atr1mE}|J+tx{PRd-;PRD(Z0UI25Ve<+6?EBPxUL#9+37#+szphHkx zDkWS~KtSTtutT4dr$m^c!CMbq#kr4wfYJX%N?dJ;RN|I@9r87bz_7$5iRitUpPx@0 zJaac8iSmN`fu)O$P3?bvx^g2;s)D#RX%k6LTN`}+)_xjSkvq7!{GKSyvv|nL#s(fh zL{wfMtE-tfI65XK8YIL1K=3=!At0X};^G0FCD2mA@q;N5?H`c>2Krf&VBdhHVr~!W zW66eclgAOLuiv~m9C~a3o-g3VD9OO^JJ?Sw_bI3;MDYi<7yrt(XV};I^40ns9-67^ z>KZq1mo`6x2K_eLhy2)2pY}k67THP9#pQRneh9)YIF7-~Ob>!K-@MV&&=_y_(NW=| z*Mnp$QUU_2z97gX$5w#bge-XVWqdsNsurAWr>|^ohLqgo(<5$o1+ydA2*e+g9HLan zKr{LWu#HERU{c||H4`S~^L2m=ELq6LqR&8 zs)`1DMbxBoHc}4Uq~7rIfalDV9I2k}TQFe*NlDv0KQlAgu;)+~^8we`_;}Ol`cJ>} zMQtODj~^`o&rB6?EV8tR>`Ms^5Hg`KJQKU1edxZV@V=c1%@KU5f_FcbU13KjVWxR@6_M5+tqsJgP_<8r!tx&LCKiumcN# zvK_y5Yl|~W(75fGkZG={$i_AqDCHpPU0=`e-AFJH7a!VN7DcasJuVQNJImMFz;jJB zslXu9t|ArM73$y9Zm@hNrG{thlU9{gR4}GXvwVSr1#;LXvwkIMX=#az(1QM^BSkoJ zw%H?|UXb#9aOYM}NK2cjvabA8=68NPv|5-Fytli13DuOTsrSgSrmo&QS-CnggzMGc zt$@%`rcwM>iucPWH~+&n3;j8;-5di1#4NQNzSePY%<*xHIrZ6uDH&C)i7_W=e{rcT zcF$U&Q*?B&2o3cbb^#Nt#mlq2J9*%(F%Itruq*BA-(k=?J$7??@d7rx1wfHP`^WnP zU{OQQc=n@dTUi$b9S9sWBx5h2w;l$g58@x!#$n+r)~&d>FH$_0B>v9Q+$M`ga5ww`skbb2Zb_u`xQ0}Y?gn(c@2m5p%^VQbKb+V->>&*=D|d?>+|Oy zj*m5|(NIt6z)Z~>@j7%GDo!!9BtMup?iNG-sJc4IrMFpM3hO9ap|!CI7ypva{7TsC z*FNInPo$-*ntUYfRsSx6&(y4}1yei4 z4TiCnc0Krhx@|r~r5=jvi}o1JU%0-NKu`ugaUrLP^+ymnF;(yStNUd~^NE?@L-f7J zGc#{911!<5cTe;>#MVDphf#9V{Q$0_6Q;e!FZnCY-PI`lC_0=&n?7dg6iCPE(bHS!9=dm<|(7-u*s0QXF*}1 zI%}dnIYk@^C)jAAXQA1(<>rz|OD`)b_IupH{kQl4!KeLbYC!`^LFHrY+fzc5@{^JLt*?k$^HKg9nNRmQ`pZztEp6%Y?&hriN9=+U)q)=D8 zudlekwL01Zy5Nnm4cyh|;@$QcbWj)*6BApN%C;_HvDZxfxO?~Rkn_xJKmS!Az@OS> z^90mjSRmlEME*cfz8{vj@w2WUZC~_^Wlq5=v-GOvEUWg} z{Zcbq@47aa`Hn}ltd7H=*>h_KtqwEQf{0{{6PiaI1e3j7Q1dkDIo5gd(_D=IW*KXE z>9#&9F8Geue7w$?ETb}UKzH#4xM-c-K#M)tp3}h>Ru+Xl2E1#4orj>KvzXVebmI^J zBY++2M#slt^OM-M@?F=|HZr&A^b*+^8Fcdx!(QW}>*ff4is%%ki(9~wS`eF=FSHU^L?!TxQfSdC9no(+S;0-#s&r6Ol^Z98fogAR50+Xv|0`{u=$+}`vTc#0Y$|W zmkOXy)Yqf7^z@{HiPj9=zu5y1UJQr0sfh{BY?L2=>1q|bb07-RE#31MZjUA*GVu1z3DMhHM zR+_Vu6L>=-n(*>ViSt}dO*`vA*8!KAq8q_67ufT&Ti^$a64uG=Kkw zi=E-_T_m%&Fo9o&%@G9+t-dzjfEftCpn+zOwg;!@3j{m~l#LR|SOS?{y=n zSrrPy(QH95dk*`DBlO$ih7I|PDDaQIK|bMN>5 zti^%_!_wKH)s!gP_qSPA@0SF2T>Wz%FxGEGB><1_)=pG~(;3sL&yt%*^WJhTo z7vL-OKc7mJee+OI7*I0eBI=%5#~qPMggP0`dj50I)z#G&*JHP1b5?I-N=oO}W(rSp zUepbuZCuL0Omp+)8XE2??IRVn(CG^AzJ7gkN%!{s(&7*T`O3RGP*%~90)BcVmh_`w zU(L3B8pTW`N_*o*u4;Y+HuX49-7b$(`$3xb>S&6Wa5RZIY$cuof;Lss zp$-^&KI~9J@HV$lBcNaGzAIICa9b)q4MDr4me`B=_)EHc33bgSw+25#359W$4V#hh zqW9FeMh*l-TgL7a6_q}gUibl*{lAR!YP<8xioJ!=JIHlGuwc7IK1ATD6 z#(`?5jZdotN4h+7kbboAXcMSZ^K-dE8B(pGJif6&jwZBbw*!F-giuZdHEzGBCrA^g z$D$?1H&MYN4Myu(fEZbu&eyZQQH3r}`LyJn@!#8`%AnI)sYusGyP0M{Bx0*>+s6!` z?2#^3J#^I_rJj})!e;C8=EsEvpNCTV1eV)zqBuZs{S35G*)!K9-f;?ACoi@_$yrjv zYH#8HYE(U~I2KT<Kdnl%w5)7;>bL zm3)QlP0>8Zkil_}vB&p{lXEE*WbYP%FlKynDJd zcHK`!-)K@q^@*HVs*a)$B_SP*b%85N2g3(Hu;WDZ`yCBdqD8u)ezU4S;hJjFi@!!S)0X{poiad9!tmSai6 z?8cZbh-?&1O4ZwgH2eASc4BM{a&6F^r6U(QTdZtDm;Xp_lN3EbwICik>%2FC4HZsC zPsE4^i>&0PN={Dxbh5UgM~NQC;<7;Tla+VXZD;+~&!z=!)p1yZ^JMzI)%KeR@^ZBO zTI*iyTw6A{Ra3SWqy0RTD>F0Giw>vSbv#FazLnSi<>~H@8y$;dxvvk-vi$N}w2oFU z(K{wD(oMH!+KZO3wlEZQ^s31cJ}D26p5{d}whrzB;&%iD(}CRv z7~HEc>z7R29KLEx*N*J}lvQ+aAdW;&SUtN~T*Phm<%?l^KPf|5TV$8v(xPVeES)k- zmp3Yq`geER{n5=18~aR+&CL~zMJe0cxx8*R3ReO19;d53{QUA6jb&$@k4%TFElxXy zae}-~+aY{d&R6OAKV1x_r{gOIQoVKs z!ZzMgRD?H_l||M&A%$+q^VGDq@`8q`_VAuvnCzS}Jz=27KCgWDyWdNFVjPa$yWQ|t z%HVHp{S<19A<$-qNuf5D@sJ=R!v}RUle0WfOu+N}gVqEz z<*S;k+s%=NdqN8nQt2?`{zG$PWBdoLU>L{j;fM~LI2>+FCisKV>^*OojpUFkN^%$o zRS|3iJCP-Xl7=j^QZdw+u;#p;)ipbY$gtbMIgn%2UhAXz7aGpx(N@b?azA zP9SUYZ7EekrMSm*p2SU)Fc^I6;E{)Oo-`_=a*izpZ9*Fbvx;Q9I;~RHE?ys- zPGj4H7nmI48i8>u;R~JgQGZytrxhGq9g@}fnIXGs)LhFK9<`QO%=V#syRMM6L}iz0 za=vw)3tBV3v4$KetR#UCUjFI47rmXv_o5$)r zGaWj&oDQa5?{?xKYc=hcpajUmZcrvo9E866n> zypPi8^Zh|?5(n~^=bHt7XXYPIY^7pbv#s8%T$E!< z##qMq^a5OF>;7psNhu&qui5@&tqo5Yx}AolQRFlG#p{ad-q~;@+HIV`^#fZt ziGX)9cF0Fz#25Hu%B*^5)>WAJ&>rkuO6qZVI5AQzvLv=AxWELMLnx9;M@(%jY0xnx zA4|fFD>;|Wma5Ar%|w&!!cZz)MMVVDwufq1RT?xQKsG39EU>NWCtons!0#iIG7G0)CK2$|i%ROh zxg;~M7HV8Oi+(Rl3K>5J2^FK&f;#JB6i!=gsIeAM=tt|(hY%znTH1#?KjguQ1R|~2pU?bXAA7^m zXP{mWmHZ3bUXL3l*sYLPp{YVV9MK_;9~3y?H9?QJXViY5V3gR8jK16#k4Lj9=Oj@p zC3b?umOOKKYK&eV7J?EpG6*oj2T>XF+z|Jn(1aB%$8dwy*Zpn{>I>~ie9r@QJvvF;y7Uivr)#vf!I2?>; z|Ao($xZHny~+ZVn?0#ACr;2r+{+?DhxhH^U;L3CH9S)AY`f+lqE^ z%l61P<#WTs@Yp7>Q<~r%6o|kl2hxR>if&5Rd&j{PwFL81+;m0^Q!TtXzkI4IPW5#{ z3LpKXqyiC4&LxC!XK}o`PABX|sueCK8>PTnlJXJ4y96Js1|PLD4@cKKRnhR2%B0JL zB+Uh@Bk^)6P|ZXasv3mM+ReI+cBh3zF=!LW$l}5#D?^l{>&V`zre;01#_yl(4#yg_ z{Rz;_8{ga!ibVZ)EQN{%)yNXAA~6HMsYolarSYvSW|2jor8#5`Hs^P6XL0j0N693haaKN5m2aQ&EKl4 zW837#6m4w&c+x@P5C;II-)Le2NT&+X|P6hR9pW2-D6eG|b-vNw`Dt8}WV zvWqay`Sx_p#)!W{IN+C&WFF8z)^3HOo=)4&GBPq~ia_#6p&pR-a}v>6HN90?$(9RD5SY5oKzVdOM!>KoKOqIpFkxGBprVULMsK*|hFY)u z0z(X3Db@jtGJ;vYswP)B!q2udIP(}QTU*5P^72@5vMIgh(=6UO9u5wdb7Kwv*CsG{ zN2>-+zhzRvTo$&$@6kPjCO+awqvMNu>}-DHo8tnD-HvoE8#;wI82QAd*TB}*$_;{w z=AMlcr^<>-*$+&X3Blq14uPb1#A7$ng)1*$hvO2+6--Gc;vG8Tl#1z*>1najyfYRE zn|Gb*qCzM02plXaEEKcLpK|6`x4(1IhN%R=$W*0wCr{vt)YbiAX>KA~6;*TQV8DKs zf^fKa%Ok~j;p0x6&~!B{NgkF0pNGCuStS)e@`nGb0A--Fm6g}Pm*?L`Ghk-Kok8T% z1Pk*~Fe5+l?#o`P(WSnKXc6i!$Ch`Pu4=GKBgx^C*;roy{KA50eF>$;$r9_o31qC_ z%ad2s^~%Nz*njLG*S}g}v*lAV>Bch>(G0ccqOK112G?m+y(}TVk zv1bg;^gD)}C!kt5N;={)D*;*JwW|C86>W?LCydRCg2la^F_cq=4{!RbyY3X}G`?{GYy2e@H>w&laq z7*CeX)@FAw!KKmp2A&uAE-vYVjFYOqOo7vaXBIbR%*ChB@_@nMhE3)PS`2)o{maD8 zuGo%xuijr-Xl?B7Uldw((K_|?(eBY*IqW=V{=u_Hc|9t4Cf&_M%9tu*qB!b;a-^vO zao>&024nsp6RUE7>{Oany~<4cui7vpB~hHV;m*4K0@QsT%K`)68yEBz?s1WPELE9 zOcki*{zuip8EH_JC9zto}$V-0~t2tDH9~8kzStz9XZ?FzxM2(Qo@#fDPA$AfUBrGon)R%DC@ zG$17vw|r3Gd-!T(f3g_iAh&B;lF^{J(N%?xb*Hzxim`nMO65)tgyW=H5m3>i{jaf> z!hcxM@+r(lC@J9uKAQDGeq&*ZHVL!mH#|Hd&E7J}rXNII!j|dND1xtfbUNTvBULOw zGEDFrj?y;f79>Vr?lKj^^N@0Mxc%u57@VAj~Hs4INN1j|)@NP;wAFGjS*~^Fh zqNOOMuQnx_i+v#?iVR9Q$G^^ga0-z)*x4a`hpMF4s)o__^V5Q=;qy3^BvV-zxBl{N zUMW|wN`#^tFM`$+3AMnv=%(1BNb?ye+uDgOyqccf#l+P01HSReVUyEY%KcZZm6&vm zjzuMPt?D(#_!lx+-0hIWPE-d1wx3LCaqfzgvE6I<8BGI24E*P68TU@oEUDnVt}Sqc6y|J`QpR?UWAthL%;9fBlt3K`dS_G8 zLgSXFS$KP-1Q+7`kJ}D=??h!7;d78yWkQX{ckxB$V%jvviGpF=-nMSG_B%9B9EfsJc3Tku|%_lDf7&^X;UL)aZm5);kB!yYcU9%emvER zX(bI`Z$}UW*w{EbCw{l_`JJ2b1*J9 z;N;Kg8v0XRGXxSUZp>Yc5|4Od-Ci5E_ck~Pdfrqzpox&1gbpWP=?+u<{XS5WsVkH--G_Db7 zOZ86Ca?HwHora&CIYy3-AE~UxZcpQ=eZJz{1&b*le%Vjj1R%?lBvN3&g4=rL`%@*} zaKN|^yJW@&@$@wp<~0`IoSej{$!wRksXaPBXCY;~?De}`fHF-GY@3C!u&_YA2W^vV*cH5S`-;Nmn<@?kzjYDCz`Y(c*M9(SH_Hmo0&V0U{3C9+eb z3)`}OAl$3sbfV!YmcsqE>O_ez`yFK*eTw`CEye$BAKW1OCdaePj~^LQPh4mPM|h46)uMmTPTXH5 zk9hF>s#*yU`c-HaU>;!3mY$=a0jF(GF;5qswdIA}umn$o7(oiUCKts*9afcyIPj0% z&5GdFDjs)98JKN@Y+ZM>N=vtZuZqoPgvR32H0CjIe@Ih|P^k|n;+^7IV-8?F4P%#0 zR(Zb7WBCUN$U@K4wW*V`=UI+%D@h6+OsG-m_`zAetyGw6P)0}^Hlr(+@|B?Z<)q&P zs?8c3j_Jc{<0emfUrI@wk(-NWN85?eQ4;Khj2q5|`7TCs&s%+50$x~@-A$*JPy>rA zKmRG&IUJ{&rdkcO4zd>4%Xt6OL#J);*c)Ja`Ywx#N z1h*1E)4q$QWJvj=O2#;UAE=Xu+xGU7X9_p4PFp^CzZHIshrsxA1e|vNnnphn>#d&> zNVN&{g>M6{VBz_Gh7++^=9~tw#SHmV z;3|uRZk&5a*!Dstbtr?O4@Y14jbeR1l!k1er=fO|%qn}_GUg+U+O9z&J=pidOp1eI zMJEuMi*@)HeQ{AWrkf5>jXAyj)bFJ~VFGdY<`>we7e(aiq0)()6(~g$T=+p{tm^O~A^R*?d{ZF0TvO8XO`x+MO}#bp z+S}(k&E4%*7z6kIejmH8%dd5uYJ1Rf19Th(AjoTNP32yEN`Jp=@ZedEIkHRUcCEr^ zWq7Y>QasdZ3ONb14U$4sG_o7Y@T5nsL!-jih>s7gT!@ypl%j0EOct14JnX3uI!(x%womKTE?&orckC96bHJ|18kcEKC8Awy3rkR=W^4kCDXSy#KT-<9{0>)+29weyVokSJ#@CFdn+MKVl z(BOGI*w>xV@E=w)>+M2SvZR|Sq5($H-IW~n`1>EZ_;o(kaSKd?F5ksek9ypj)co4w zF6eb!u-tRjqCyor?2?N7Ev6;ZrY%eAE#!3eaTR83AyH_`Wc`-&0DfbI4t@`dnDslz zX;n462Cud~;GPq?R(&GmMBCO-2^OH=uhknljmvahvxBQUXKbs(vecTq@|i^GE^4_# ziiG%iR-tN{8o=+>_P|H6s4i(f%*=BVckclGf{o6h+gZH8-HCO#vpZ1BQ>*(RMZ#Z_ zNQ&_mR_Jg`k+s-g$g$M0L~o=_zE@wiI*Ey}B`~I$DQJMXy0!da<8Vz342-uS#xY`?1qMh1Zj$$30b*0nU0d7@eSOj+KT#_Kqoo!I;>7U zdgfioh|c${UOHy8%4x2!)6Xkjs*Bp88$Dd)&v)vYLSlwTsyb3qX$`!0a{?w)V!CR0@jYJUok@}(G7AuyQ(Ah zeYy=!$nRF#q%EK@7BUv0^^;l;mGz(5G4_wWKyI(mESx@{Mn<&4}= zk0cjAs2A3&r~LMt%};5sc94GE%wX$UMomGibeza|*T0mj@7aCu{7vLAMszR`WiZa-o~X8{~!a#wA6&dOj$28H?66z!H1hVx<} zEi)54VkoN8iVe^Dk1O*#u|q+6%wG}3gvMh(fBxE1g2UD*4%T_or%}MQrM3JTFOgjM z+VXhT5(syC65%64n(d|coN0Kzjw{IWgg9FQ(iyP91w&Q*ym6hMJm33EI?5{v$GzJX zr_woh8BgKqAoOlTbJ|;`E{)Ko(Z;cOxdeTm5b!fI-sP~qD9~ZIjL9UQX~Mvk)nda zT8B^Sfyl)iJ8vNlJwKxjLtw!9f!jDQ?x`6A+~=x~7U%jGebq;-zPnm>ghMmZ!@cu0 zL2(|Z@~J^*gbREKqxi$usrSQ}GAzbUc6ML62-jV(x?Pb>&~_%I%OWPHr+bRAiHEVi z0^oFX1x?4XD(my%D#Qg4iU^)gyGBjGr~7~`aKB(HU?&55b;=@@O$SX$`&wBIp-}b9 z-ovu5aSc^GK%1{R>+sFokV{CO*6FCVR$2Q;MFjn$xd#1Bme$196y3+=CR?ca!!LTAPeK? zg#&Sj!sr9(A1#lLj%FjgUsh#9^AK6~{NIt99RyM+prsy4WCt8^%q+OaYJmj%tSYgt zHI0l&m@FxCylxt`G&E>Ei1sXqCIeXTeMaKm=&HqjSVQs%SH9}J!}fbTY0hHP(l*NC zMzVEq@IT1*ARr(puc&xE4;Si+#R;GvW+JYUrO-{c_`w` zSKnZ$=!qu5z9-^w4#E2cFvXmloYPp2AAYj4v9&sEK-2wMUzfY^y!@H&!pJySIJG#O zL?j@9x1?ua;Bzp(R@dV){vQ`GFt9&9{!vZsqZw%;Py#k~cZ+K35$~9~MeW(z+}zyOmIB9X*(UKd`c4S9>#<+YalEz3u1E@H^_n#16#9&bv#3 z{xAI0qP%@(NwARJb&iq(F)aO=>-T2~kP8L@ zzTNj`PD@{mi7HYp5l{}!l9U9!uEw|^kmT2<1w(Q^Fqbc;BFIirNy#U00Xe(nsxAl3 zZ}vF(LP*|_$(dId$?eVW$my-q`uC=QE5OZ~XIDC6xeVi|Mf(q837)@>23GAXYj>ii zGShOIY8lAd8VMOaanhFZhVAn@hY>qMBa_XOg~chLA-&#RU<177`Lxf)Cz7uz(nXte z?iY#vTcRES=lSQ4TC@Gyumv7>6gUo)u&-Pd+KS1A0+N4UDg^_W7oLDE{#0~vNMP!* zg2zBsfj$8R2djR83dO{4$LD_B;&DdIC=k&#gVZ;Pg>q_r)-TC0I4~f++Y^eSRbv=> z=0*8|PuIhJm}&%&Hj(u(epFP*1r+0-ZsLx>W?+OP#$kFw6a&^SoDMXR zbiAuEAXBM2&1a#__H5yxB7Bng&W=B4RzPpM1cC))mrg)}ncGjGgw6V_Vf+CF1R77o zz!~o4O6avAj6YHE9o(MsrvK}$|3QJ%?2qS_A9Z-KTg9QO&!-+g3ZIPppE=|amK-zS zzT9nv>$7(y|DG5jc{xY4AJKE@pybV`;OJ~2f4yXW6%~LAaXS6+Fjo^Xu=V5RrlyR< z(Es^nd|Yv)0oc{k;Ri$6NU!&~ufv8+wD6nz&Q2}myK;o~Z*HTfoh4WKbk6j-3W(|a zf-ASoO$4xNrNOHZkt|yJRq}giR$x_cM&6*6@OA)$cM571GRM0cQjM5{IPY?#T0$X% zPG2ua$N1%VNzq=-Z{_-Le!=Is(xLgcvPHA&iyv#s!$4JqIi z!%e#h*i>_O01rd}e~t@8irVQ;zJIaRt%A3TJLHNE?o7a$lT^y6c)$YUWU%!cS=$j) znCuS9W(&^$ZVR#grJwmr_lCH^J={o8F%ysMJgO5V*8-ZpTN8Dv>}W6(UDRc35tHFt$DK@N&zdu@_ww$2M{TYAgfvm1Ue$- zqI>d4DPKGHtA~R2?$`VYJi8OxjV{-fs>VhIs#1?=xlrZCMVBOg7sHnQvYxXlw!#b# zcUV~9`g3DYR>s5o(Isw7EF4Wt7vP*fe?Gxu{!_<=6$zvLk{6r8UiR?g@sv*&=HRfj z#kT7jwVdDB+Q6t+M2?MOXsd-mJBq48%+j*-t5~UGHW}I-R;0LRqi0DZI&VD61hN?{ zbyH*Gxo{#?OCGL{>P;9lgxu>aOHi65Aw;py2q7A~!vu^vLeG ziZOn10Ske?k{1%c<0e#Gr6h+6G1@`?^M0lSx8Dn9oBPRh7gcs)rOwm)IqMb+<`=rI z#1?%Dq-14cznRh>2=U@J<8MG+QnBKByS1?!d_tF(qs-W%jT=w2B|VnregPFHkn2nM!Yu7_I&lmI5enUH z!eWt9`ENZucw2p?^x+`He%M`h{-C2q{LLE>)Rf7KDaV0QEd>>QyveBu`SHU@Y)^Y( zWi5jQCl!%FoKR6b=My-%+bixOuoRdwyNk~TvtK3LaLRM?KOwh)yy1+!^5guzWv*hV zgY604xGB-FrErf$9=yNe0Kc80Q07oOnf6r;EH6t-Pgi+GBURtCtFIQRmjw&cncv!U z?jJ0bSSqJz*MbDq1Gzt-+!fTUchN3MU)N5Tz(9LP0Gj+3a!xKFATP|$PC{WT`uGl| zqH+Rel#tPJR{&Rmiw4vXyd)lJ$m|_oQ27I*d12$usKmGQP zSD*uz&A0;?sz~xeF<0;zXxT4XKOS%!`%dmgjb22#%T)O7nHsN+UT=)Ln9N@m{GYYl zxD(+s2`@+JYvSRLB`#>_0+pF9L4hho3r7Cg9cJPZTkvWiAjc7HAR7H#;^RXD2aA3~fO#4)qh(rcI?mB+_{{`tFh(R%Z*OSk*DM|Ju;#`~ zr`=60Vd;WJeF62?YhqVlu%&4q??dY7RqnfhqFo8a`@|>w)-U;h|L5V40eI-5+3eES zGJR;inj(gq7*Yr34>-(18EW0nOB~0lV%fVH-S^&;7&KTalH<9xycah|dsG(6HqJri ziN9!K=s%bN7|GAiuf2f>5&MCFb#EeJZ~J#WcKDTZ&WEUtrV%Kx&(p54dkP{4K(Xki z_MBvV)vmtOLAy8dWj7ukoC{)Rc0A2Ows`Aew~K~6!9ZW2x|UJEsYuDD!+cWw>B39X z8AWHlDN%X=?~(^>NL6LD?BQR`KAhaz={sO4N^kEq6XkKc{jTGv{A9eHkZ9U2-!()vL7 z?IS3+MbZ!Oklcv2df+w}pvzv*cfZ0^PGL}bEQOMvwqbLn4ZjHqpRlpDMJMLx=I5^z zvZG6r4RizLIq=+&lv2dnHO^KfB;JV5G*`S={QenN$w$J1&V(w>Df$NR9@f>dZkNIe z-Gm0v^5`3QmJ9RycV?g8VwiNP#;EfT`OWo~gcqIHX6pP6RSgg-Z=qQWo>pDlQVL@T zNToAB8%0DTV*CXM?6S%rsP{)mAFimY#EuDDsjr8g;VK#>h!F|}%{1Hbw!a`#l-j_( zUVEmY5Ckn3XmbT8AB0M(LTZI%&lUya7-kJ=w?lp$@A z{B+H+g&+-%a$fjz5Mejo+jG15@vgUD%6x!_9h^{r#c)smt4sV=Z831^AY678cn?VN z%;7G1b>M-CZh2OgtQ$#MjzTCj{oCk%zl*M4qyDrnEz@;Op}9%AWJQBC1LeNa zGhXf2xIZqhK!dXnzVK0@>N0oUJIPT$)_v(GDlRY6fQu)o%XE$KA18<)c;VF>t|UUw zN9VB^^Yr#UZ^Cwf+J4Gf)9$W(hHRs?aNvIF_5Av&l868GptR=hw?K`fVR5B>N^(^q zTg`2|Y{%SZb*~;)dfJHz+J<2>wkj=3=utn)>Y6qVVmag82x@F!tLLGT1*qQ=ljTgJ z0w$NG=T~}yu$3H5>-H_G7@D1OjhEcT+cjJpBUj6dFWr>D9$)^D(qQZrC{_uWcHW?) zZ?t=NsMvNIgM^seU+E6E{f7sr7L!*puD#L9}~|9cxi zjI5LAuCHA!Ee`;aQZ^y1Jg8+VeoGfd!J1l2L=kO-)UKpDKR>ACC=R4O$$x0L!d`!eBt@(vtM& z&ugb^KJVXWZdK*vL<1)CH*XXQ3wOrG7{k%Euw%I0+}fXdLdfGc}r#fLUQT0~c? zT3?~KJv3C}3lO5AXjjE-UU*~cPVM@naHNCSirHEG5=)VPAHSoq-1=H{1AWAdLr7=? zAT#$+PI&+T2&~QaC`SQ;bT;tZfS4|3ztP!YyTCO6w-Iu2aq+#!C&@kj#r;MO^I|f; zmz=z?R4KQ^7eZ2C>UC*`xaoR(x_I+DIByXc&$lnQ-yv2oGBA95x2t-5vIg~gDfuro z2rM}|v?ecmRY%%@-v}2UA0I1g_rvw|H9(*8L)!2&O!D&c^E-TQiFsX-s#~3QBpKcY z57^k)#1fW4yxokgtUMq8WCIJ1h_3ktZTt; z$==k|^Z{pTtj;vxMt|t9cmj;k;ZUPDx5G4hLkN>jOtJhM6?{*-+qS6S15DO zIUM-FDGneb)X{3A-Ydc~%#i>4(j;iGb@0F6tH~&x8Y2HJuZ=WNOX-`~b0*+0+NvwD z{O9xv@cy4c#$Kcrx>~#Eq+4fi6($n?%`!Sf?YJtIbRKjRb4SLnn&TY7`|;loopSj8 z?@eb-!bij>qrMH%w$obX%a$gq(AjmW5_;Ku+XYYs)xXat3j^jiux2CFyu9a6CP&wf z&D{-1Ht55Ivc_XwYHDer8C9b?*FS>)c-|5T&oh6&N(Mi@rR~M)_7R=wjx59xSIoF{ zXi0cW?C16k&i^kKE4UQ9_e^332M0Ro0EhohgeT}7MilpymHNyfQdlEgnuVq1UWkDU zX9F53q+_}GusGDHC~p`M-Xw^J=+`HkQ_DAjc#E_I;p*GVv)6F{7L>nHE(xp)C^w{#}3}UlD?e7MBWPy>9$QX$3 z`6um8J7K(sX32>VlvbP1pNZbT=kvPUU23qLtK;V2D2^5FxjoxJw@8S^%FW3MTLdU| zI2(X?7Vq@B+6Sl=?s%&lpY$C2oVedtdI_PTK(SxQQ7L z$LNHU+4VL7sI?v^%l&nKZPp5!Xe5I2hCo%!9}6o6oHFq132e%4n_bY#UwzlOZ-LiT zcuaSa`9}SFH`brKrg=BXsz>&mjVE_^DYD?UU0q%EJAHKu%dS&$TMx8@)KZxYmg`Ir zrGR#b#eMc0hziu(!_{^#>~Fk2e;DH7)Pa*iCC$yZfCmY9?qm3z&5z%zTU#?=YLSg4 z$S|Q$;+MaF*0Z#LQF7UGC( zZ`zMHKLohhdEU7zj7@p+^RTn?b8>dCx3-4)-0lNOUu!y8t<7-Ji@rjhVCCWApfQKp zgHBSNlO2N*J_HB_fWvKZm*&$^g=9*%-+=b&?n+jelKg+U z2SO}*i-#xRkJ0LKi7dy#&VCFCQozxPNnBC^0RiB+MRkosNR*`1ARn)yWdjP(dnyAo z@t9oCRy?2GH6aQn9m+IP{x% ztms6%tJBkLoSff5Ihw4%;lHH+I+HCd_(>NCG(;j^OKF0d&hNIgTO;Sp%*4b5ngH9* zDWbh%aL4H+H1|`TIF;C@C~tOP(p$V#6RL?(I{pOdy83qCT;WL&I~kRnJEjzUpUH6G z$B(xWKdGFMNCo?~b#(XGY>S|0<6PsklapEy#om`En(lRidosWw}ZgU(cu6(~F zmVHGs+l9&gf#4GQ|GEJH0-cj4JO$fYbezn}E@9@K)QiNjvXQUvhhtM@&qw!>ZVIkk z45`LOM2Tld>e)!5v3k}UQ$G#!ZhdT+VYuJJ!vk1^lPKy>eM-eik!D%Fk;8GgF$hTu zYEip(4oabn@;U#O(&7PQp2Fk<^mj(u+VPN~tG4sS*;)2w%FLvIpZAl_Gd#iK#u%Oy z1KWtC-I5_FiJR2)81N9fk96CW{sbBf5sUsvh=`?3Qk^JFc2}`R+3K2Q$Xv>T1^i zp2yIv0|!MWIK79|$>@rd62>|;ntV76(}$r-mKrmW&Dk7f5H)r6`U>|=St57;1Ui?w zjm^Kw$6Rj+(jyO%suv0+l}s+|FgcyFsF&ViSHq?8wR=~t|G<>GeV0o}*g?3NAZ*Ddxf zJqaQmtKk(RH&J z<2RG#BItw&qS|%v#Mrb<2>i(a6;d5 zjKlld;%r*Vzu{YKYTh?3AKGX6ksyXnVS-E3OVATyFGYs(z0ZctFCin5Ec?wi;taW& zLC8OI&$BP!>;hW-&=5|fc!)B_^z?M13-e(X?YGgmjw3|Z;Eg>mEY44<1lC~jyeVAK zdfO{V7+a_EyU3HVcZg~}q{CsOb8TkkBOl)=QSwQYL3DKVt3XooMsu6& ze-$2%VOdLe^7Ql+AjB|A%gb%Ny)(XludADianU;XFxx)@$o{~@6Q(izBC=Diz-4a` z+=xS#l;Sd&$4y{gTrG1$?cKTewWo3koXM$QPc&jP)RB{xw%F`o1Ss`NJpdB2w6K^( zIqo#3QSAP=oB}F1S|@<}(9qBT8^y^|!@)?(UuXu*f-WvD)P7SB(^wv^uE06anTH%+ zH#&kCXCzDj$z*0^P*GC@59N1%xd)gI)?1u{&BDXN0H`7pbxodtG#F%l^C?yf{f&d7P7n=dR#iJ=t-8Ub=F85`~G?QI(~hzprYzM>C)K?)%N$3tPh z($z{)Mu%zCcl;lt05ECupn!Sr{+w<2AI+8>9v*_hZ>_99ecA@lF%X=4U*fJ-mjkrS z#u2D_fEQl_jx;67_x@zs#=c*Lpuoa%SrxXmdJha}zUkJm{*Mdbj3X?&KdNvzT_;*; zvPFNxd)#-nSU2zYh(^e-E#bcF2B15@?U9g>ki|TebBIi{H*s}xUxXVY384O^-LUV? z%>WJy(ksl_U}O6De}juN-16cglIWC~yQ}N$?Cj5RVAS>bvp<&UakehtbxDERM+N2j z_~&zfyZZ@2)n%1lGXes_;xTZ9YyT$?R7F$M$^MuggLOTCNQg;t?d9DuO^wt5EO;W@iq6;c$$ z0`y;v))-fSElBC`zOhkKQsO5jAto-VqI9&dC;`q34<(RyDN|tac${WgNCh@qIjyX$ zNJ&WrRxK~&x=kcK$6>VLf%KH0Ex;zuH(nGEI&%SLk1-EgJ z!`gZ?JmgVwsHG|Cq&EKSjGQ#rjgGFmP9LnSmFL>Ikya#t_ypK$HGmG|LD3jJVvt!b zRvO+#mkDFCG$Uj4?5mchC@AV;yWs@Qt`hRqCfnx2yVy^Q&F=}wO}=$cHeXhUm>e4# z_syEL@bA=R-Z%OF~$}5}WC&mT~mIxIZ@v?KHsXqa5!eUvjZa5Js1f#PhS&P?%4_qR$ zY8=6m693+hvb1JAc`wU+NT8DJ{r{%)#u8a~Oy1wg{N=Ui=0 zI`-viW_Qw1mb;%VT{b`&63Rfoi4)kv@Qh?+!n}b{!a57XaYJlRA)Y2nk3IA`DlMCK zYKcSOzY+Ue5&S3z*hWfg?6_ zI{0xLb}6ADlJKM~8RBf^n7;q-_8Si+6)SIUuoJFWWWSUwV>EWJINNDN zmDbN2)QMYJyD4lR_#Gm*=!y)Vk;2~L#EJqo;q^wNBl)+GZN)%o!(c9eTm}mxEg2?C zmuz&_Z7aol#?_g-VFm}_U8BVFyHwBG6E&BWtx)mCOe=AdO|rQSX~fT6-`u##${qH^ zCSi^$^Dqc&(8;(Js*!W+y;0SbYeYvVn6Yn@hyoY}e4Tk2F_eWU*>>=f%x>;`6%v<^ zZ}5x>_^!79jVC||^NmQ9`xsv%CmZe2Y0YE8_}x$L^G#U9Z>FtPdxWm z_D=2Dk&YwvjUCKtxc&}JFE}}-=;vgRm_slDL(d{_{wOFzL%g)fQwzgl{-GqfI@;o-bGP2VP98>ueA89$?MiyDF@n=ND8D+$<&yv%;b^WU3 zL7W%;l?zrOCS4MvM?5$G%wF~^P3&KhFxI}F4WsVnEpgQ9x%PNI;Xf4@3=RMJ=EE|d zq6*GzWp3dQ=k&&lp^abAsJ)w~y&Y{xk;aC)3}yVr-xIazV__8zthZ=iJCc4AAInS`i_PzFx#;48~QpG$3#o`i9U@=%0hWFo{i zL>@?Tyylecmtj13CO&EwL(fBMY1E-;v5Twh%-}`*ok7UC);1&IS^}5dE&}!B<0GG6 z;CtbWAShhK4|t4#%sNS6CPT1 z%dQ9K$y!NEZq1uvE<;V1Q#+hX)@~2Q?@Jr!F1OL@G4nS(dE&H=S!R`~Vk5)^(y zlf|>Q&-xS1Jma!F>!27h!4jy|_73c=Kn8dXTYI0BFjUY8i6wT-9=URNn)?FJ^3cXj z)*4lS>UI)(AAZV$RWQ^`jZa2KiZH5dY!=qm;e`S)!|=q+aU4g>&82LUrqsyMAz2;l zx01C%7{UB3EC7Cf7JnKR>S`6wToZZ4ysG7IJIDt>0GoSHVCRCC=>U zl3q1mbj_miS^MlQZq+RDJ`LUJls3-ZpO|hhxz#)Lzs&{HhbmsiBiM*GF2oei;i__0 z#J9V@qq26R@s~0!7M4ZUcw(o>3Jrd+@T??-BIxWvF_g^=M?;2l4K09ySbhlWOf$8Z zZhvvb9f}=Rv#k`hT^TOQRU6Jf8<}z;&KnV4;`{ssF7^g;^_ z<=!V-H$GYkqWPJb9(*Tf=Ts1Q0e}c45J8ifnF)XfpgOu+{Y)BUyE8^<_%%K~O#9R4 z&k-cNa|;UtOD89GcJmIjf45`Z(-2R+>`Dpm;LTZa=lg@2dZ1%iNKL9t^Hfus=cp>I z+ukEB^)A0S^*GX9IF*&7;E3xL8&9m2w&shcb^NwN*vQJui&1RD#m9$%PlDg<`N7uF zv7xT+@_2O@sD?jM0to-$04QsA_YV)7)(f+<123O1%{6+synELU&~Q+N7+`Q1U^|cM z14YOFVtsr&876sThaWUNs2oxH%G@@3qJZ=Q=#3FmxzO4)KC%ap@_Al&g%SFqnpebk zfLazsd2({{;_9lMmjZUy79kiEzRD^pQ5YD$B(}Lfe#ANQkTwhCWn{cS>U}|mO}Sic zsRk9@%)%1%Ul9P-nA3nOvYD`yU+jqY$QA-TEZwc>rD zMNF!OJCa9Xt$uGGy!_v~5T_)i+8pt4Iudr|H+p#(85$yWLHz*!Ywdbx-YD_k9MI`z zzrZly^4Xx{K~WeIK!!6TLI&#^77_98MU*&9Bmp5I5SBt02f;nVfX{)Hfv5(Oo;6=a z0;?gU=fc+=9UY*M^d+na63t{91R`fd7%vF=pC3$2J{f8^xSs4z7DnPG)6)=otWw)w z-OEZKA-)G}hOFI6GpHMBG&lqWW z(`Qmx@G*uk8ywPLc_RMp5|oTsS3dSrWn&5n0~&nTDqj(NA2$y@$j0T zR{L7pT_VynuK8`)ZEn)F}>%%t}F{%inlF-52b>`CC?KPL>58$5^m0!fd$vU+_`Qf4Nt1QrB zjD63C6BHoT+&kMI_GbrLRB9OVQFW)Vbf^R%!<9|tk>Cn~OC;v=e6H))=)6CZVW%k; zK@#XKo5E#xFjrky2ggEw1;zvI*#ehyQS8FqT`2&%U7S;AYmOj9$cKQAc)ApggT459 zBUeFP9RWw3_rn|QnaN2?XdEtBLIo!E5Teb!RR9PRXm`@c>$6No(#whwQLz#pi*X50 z&ds^+O}$P>8liv-k-q4+lB5mR#3o2#?sB9-Z6iO4+?1MOOY$c?mLT_OpQ4#X1tDT-69{>pxP!2k4 z&>XG4PTvOd_zr&O{pZO9WOA7$N05FvZN|&w8vq<916$v~!Td`=#zu5vQospOV$$S= z;vhsA>*%}#3^2&)0Mo1@e{}CQ1)T|St$POtI8|V$_wz!>!~hJaNMi2^h~&w52Dm^S z9i5RbpaKHRzr(E~H`1Q&_Mm3j9_bi2kQ&DK{R8NNQ<6j<{+9aZ_XQOCloi3X8`@Iu z*Ulp9e>5mPTxxx;vEn|tobS#k(pUX+~`o( zx-~h0D6oY5ta68K1S>5uF;o~7vyV%SZh!+74JSOk$p$9mwSmDwIcaH;OgcS`HX=^z zg@lxpFP(;?X4n(@63HlmJ=ELh=WNL^yKnin?^tawUeQDvy2c^)p^ZbueR zNO}Y=O)k0-n333D)*!V`pJdr)TT)mjb792!)&B0}#gOW{&Z&BD@On2gdzBx%R>YS# zGo-xyAL5U6_7fY%_~$+B41ei6?k4`j0!(OAT_a^XZ@>##qQu22Z({C^avFuHk~I@w zQ$Ivs!3?`x=LaJ|5_q2qZ!Xwd7}W)3)z=fo*{6zZRthW?r!dlSJGd<2Z*;WYC{Ftg z1=2`ubLpO~a-n?>+3`$yv#mwYkX?b}!R#~+yGzfrj1quE&!l*mgd--s^+l1KX-EO< z&b4)5YKSx6Q-ueXWsdCco&juU*{q`hoLDl_MisE$y%UOabRFBIuKDn1zUXp{U( zqW#rQrgT8rSH#*6TMceHcTD0dZ?PYx%WS ze6f)4G0*JBBL{|0&sak5?bB7>BukkZ&|^~I$Oyjtye~xBI*3&61|fyn_acCPVT97O z)t-uh(U=C2r1{b_yZ(*AkKn0&-X;EDa;?UUk4`ir8pE$>THV{c)lIw3-`#CT1* zKuMJlYNAktgavz*fVCH^ADP7T4LtLOhkTWnzG4r#=y($Xsa!YG8$ z>J|y?xnU*|!J?V=W+iS{>Ub4qyT&&H)7U+9(foI`){B9BsQpt~6r;%;us*toZ#Bx( z6a`}?_dL5xYn}~P{QIMLJ|w^*dyZy#w2ZH<8S;abe@<9N(K67EQ+9oEG?&a*_$ zzf0`w9HFHzW+aK(JQWWY7m#mwGigSd_O4k}+PuNy*Wb;K^&NN zZH!FELhyDyCj$D~UT&7K)Ym2wOZ3#`w0~>t8{{~U{EE8uKJJz1%-Cg00k(2%#jc8d z(Laro2yW4-8D+4PnY$ogUBV++i1(vK(4~A z_oyx#G@G7$!}iY3syx^~vh&41RvxdoPmAr?KQkrfy9#5uaAyJvdtq`i`#dUBNp`oC#v$N;dk2tLc zf38AYTL8|A;^M(r3Y=HO1TBX*@AfCDU(G*H2FNfF`8Yp(N#$SDRi?g++v}cS@}w+$ zp~s?!2osz1X@gEoNY%^rdVz*`w*&>c>ZPnpg(ZpQUkU`Dm!K>~#tdf)o3k)FI$95; z=k-QYm+Cd^0%;ZyUxBJ;Zmzt%9JF6EmY@hXNp=#-$;kmeA`B4fnImu+{^d*FdPHLx zo>XMe1n?{F!L}D5_&KR#hEeWB4}q>VpfrI|@^=kp4?cn=8v!NMXiw-dD9@mEiMV)q zWr$D>qN5Gny7A~zkflO|-FQg*UlAs6kn?#g?euv(FI#)z_UN=lU=NE)`R{4DsaUjr z@5QEoq#OEyZLNpc0PL5CPiI6_o(gHEvP+A%hO-w|zVNnU=u-Xq8iSu?%R=YoSWaA3(7nwQc=H!_9+AKA2 zb93iI?i3QJMIx_3Ml__uqm+=d^a#zTh*KmbC!1GlX=;+aCKup8Mlu%?VH!z$y59y* z7{O|9syGXPE_Kin6g>(|k?y79$K9kpSr4CdTM0X;SiCvX_wM_)Y`)AfCc?z}reqnN`ZPgXBLha^Cj4(A|$ z3Sj%qvzzYY{tIb|8advAB8Q~(Sb-2ilvjJn5RoyKos;#hC*%{I7cX*5|59SSk{}V~ z%>)F7(^;U7v_#cZV`HO0g!U)<--V*tS3ozQl%kVX)p_37dwKB=a(I~c13g|B=J%v; z-yYUN8O>IL(GDX=fu{td+)9zzzJr!i%o2!}V}QVtXyt{#q5~L*E!yDI+8TL7HF(PQ z+#vGrmq61|^An$hpIJ=eS1i(vH^2;Y4nE`Q^>$CJUlqcJw4WM!q7;mY9s7Ay&fjg^7(}J` zy&OS%F5HfoUu2I&2?pons0RQLzk|RqfbLO@>oaKWKEfq80#72o%mpaE zn{RjNf>6FgMXV5F5)l(qqRT@&n)Ultf-xSgf>tqqS{F=M0U8aEVTtkz=&ZzWKl=N_ zqkY{0&;`hd2}YxBwT;33^wQ3WShv>R*wyv9`yFsj0-9~vZJSv9WBYH<&6=+vnFxpx zjQXvB?7+vzk8=A0CC{S>A-Hj3*{;8BZl;3w0xyIPf_t&SExLX{qq4WxKC1T10%{4# zp0;{vkKa^M@Sl=>2X?xSx3-?cNo5@g4MPa|cci8daDA0w>UV40Cf&L5!zm?Y(hX?|ug?B?L z6xGU47<3}AUILI@!M1CFm4Xm8l7U%^rb0kiQuwN->lS$3qADkc795Rd2AelIJspj~ z1i9P#kw~QV6_dz!D{K|iJ<`vXsg&k`T6@Y;u{8429hJ;~>JDB>P!6QZv3?{}K=_i)@s`;2 z!chql_1Uu&z{ml-iEX~>7ttncG;{ykJWVgo0Xl*(%)>gW%>-pf%I5es;tS0_r+Rtc z4sKQJnuP(Loff**&Hi{Ca;31Lk39qll$qgsh)&-4;?Y^DSEUGz5XEDD(e4<su{>^m52#eTeq-t`MduEcWlBgj0`*gq(8!AD!pa zOC#TE-M<9ud}A+sR^vDtPmz0p3_bFH-ZTg0 z-!L(5j_EQyU?FF-(lr}7Z*FIw(ec}~KILy}2geL-sCm!AK5f_Pktc7)4;9_t8;v3F z#4am+*prd_Cl3a{>wn7AM&*f!D=ZV(V&gaGQYH72zVRcw8UFV%smhhs?y7$e%>PH( zDuuQhLm>Vl-u5>puB6V;xbjp%$Ip21^!1*kD?b+U$Y2AcLjSFe|4*iBhZ02r&m=gL zZJ+m>OzFM%M~dcmBS%C7S(T4+=$Fenp9#ho2F4T!5T2@%J;tN|eO$mv_Pa?iCicG0 zQq>&reDh5z7q`uKGkeUO5!TDNBEKrWC;NAmKKz%XA{WclxPmTT>s5A#6z`*A2{gL& zrms%uTY55&^mv12(}^W8`#oL{Dr@5{+ji#-O`tHtx1L6H|Aop~E85so&mWP5Dyj%Z zBK>%Meg%Jr|M%apHI_(U1f$xu(m}SoZ3ZD>Ec= z9S{g=x;*~sRAD60ar-yNl4wmk&)1CY6RqArGG*g^Ef?Zwj7i9OyZCTfb}V^X=6k zBm=eWU*LE}Ch4Zs-;p^xY;y7+lX$JIt}FtcAjjEr^f0O(G@78Q{3a;ub;Rw#J?Xub3-m4n%yB9 zXB><9H~#?lcCR?P1ApVVF||2WaB#f){hl= z>0Xh6IZd*Y*QU|8x~vQ$&=oSD2ZxtK$IWk13Xb*{QcB;Dg&m5&i(RA70lZ7(-#i}pET7#z&0TFRt2IA95qV$uOf)_=M>JhF zJ2&4l!Y|#rtYMEiKum>b6**ey_&Nc-G00HQ9pir$TnLfg-A@0@R$rftAgm3mXxpA! zmKrk{p%@$!Ksg-@thanTJUpzdm2T9hMPRA@r+-f)3foeW@YcK)5T~o#J%T}W0v*2Tt94X%dZ{+^O1MFd`(ryBXE)nzm?rwm_h(S8y8RBgY#UlaVT#K*%wD`u#C{e0@s$EP4HC8p z;#cvHbU#1Fyb2;mELqw7C>1hx)P8m?8_po1F*YeAIqc7fx;>Q0diJfh-;)avE=jpk z%eNv!j7@c$tBiw799$fuoP0C<%rVc2in!dXY8_y-E-vYU{Yu_%=E|n!^D3z{8qZ&X zQyLo=7m5dOogG>Sus} zt}b6xW8(vGRRE5O+GM#&h-nY#l0gMDI5fluirB_G5Wm3%l@38i$Z0*$-~ZNrLtI7% z1@ZLk43KIeXh3I1ky-&(0F-yi9*QHqT4~rWvdS+ zb=GHuULHB=PPgF;9iiZXJlu?CU5~McaiPs zhQtVbK{_iOnePjI`{Laz>*$~ywCV~xw~mIZ`W^%{WygEJbH35szUqUN#$%YkRDPdSPY7hpQr$-9 zr$=btm29baNI{|;1{@sfV4xC!NaLQG=2VnHs3>bFLfuR1CvCOiA)T8=-p2EK zcvKsVA^dE?DuW$}iH}DU^1}k$DR}s5a%i?cEUyk5EvJg0 z<)=!#Y%UW&2cJB8|NP)94Q3)5Dc`_mi=>7IzOc|UvkHTDxWVeilP*HxHn}ovCYVwP zXZ`3Yzhb@S)Q$}ZR>ZHzA!Pzc^jg&xDh39tV0QuKw!{7P3D|)!B&L(yo&F7AzHX|#KGrP_Dmg&VBAH^$Tb%SFAI+syS_}sWf+?F%yr>WvCiewkH=dr z9KzJu+cmkG=KEhIY9zDw187rxx05o>_cg*k%Z`R@%nP3()v?+$={OI2XkHz@o!6~; z%jja-x-ud>G}JKUP#Ie2d@u)F)PkPgdwuOHBGQ@2dOSV^x;TvSi3u13U%}2!F(f2` zP-rq`b8`)mPKma_KzPAWKyh+%)(B}HOWN4*uh>6&UggLn1Eu7P2#`0t_%qjd3-D8s zSh--Y2Yk*mDM3xZG&W?>k3oovh=@@5wu816Fx7)nV=HJ}u%B0%7+R6EeptPzDJfxK zF}Jq=TK)JX_tZOY4Iu^;Fp&m{FhKtl{WGjj&zjSFEKpE?{^I1%3OFBl((3(|ayFG{`3PJ@qZZZ3R^y!VqKru_JMSQZ@Y49#pU42`BR z*O^qO4!^I3B$YRX!g6cm%1)!8$W3u_w5k`X7SqzuKw9eKp=dy|LE!2`z88EwGT?F4 z7#|z!bZIsHCLjK5)QxBOtf((d_8L8%Q)89-Q& z2!I@7eIIO{`8paJ+)khKDk>{`D*-+Q6pj!?WFpVuZ6lluOG`Wo`{@00Wp zbbd17sP9ii4wc@wueU!8!v8q(d`QHR^YYmoe`>m)j(9Yfjac?xgSVl-TRN;sx@1wn-+wX}}q822dJ5Z{Z>*PeGG_9cY z26)?4W3R+1TD`AgBwQWlXk4zQNXZ>K*66`!q#oX(ufQ!^#SyzgJIG_vBAspd7@n}R zgYSk+Q=(l_&hSvcOH@~>J*|l7) z=GCWf1S?-pP9%yyKq(^42DGKQWJ^COy{d&87ML_~zDo%fBZO24siPe@9NkbZ1x3U^sv zR|Wm$8X>HCfOOMqZ~U^~4|)&sprxc(uv@gdJfnQ4wPRxDxToXQ3Og4w3lldF6Y~WB z8R|-O`p$2ZJrJr4lSWjvD?zGVmfDQhX}yU3hdzo-vAR?{ zX>my{zEmgY`>?ResS!3yB)t#CKSa!Tj+B*@q{_CoR5hfev^+da#kw_kjm_w*aSHy_ zVkTn{mYzmdM*7$Lvn5kgmvwVn8ikf^7M6SEbyw_!N_xvYmQJtDRn_<{QJlimy&j5y zU^=NyO{?;Q!W@qcP)S4QLn|3-zLj=1c$&Le~F z&1l!B9~z;e?7t*mf}GoL<&b+MRc^~gT@$A1G-PVD6{`TueE061drTHYVQ#LeyE{SM z*on1I&+Fd{M0U^b`b~0Fl(56uKECm0gW% z8_O^!bNU^W%-6CP?0XDn z)z%Iw7r#wL(stN%_+>+v2St~p&J4ER*G_mURQ0^v-0uGh!o^{CvJdqyFPaC~KK#Q1 zk_ZwJRF#zQ)+YN4y2IMRms$x51tmGtA2##KOSZP0!#?II<-SB~*LTlfaGcPvM>b^- z`aTd$Jzr2z=Zo5*tUC3h$`O4f&r_VS?WH1Y)K}!;lzc>^E}F5bAI^QII0T+kfqk^s zpA_&Usaq7xClIb%@{=KQ<{QntGVCoa_mY$HL}VOUSFDItTvSvW@=VkgCllTXDSKl6 zFVmLYPYblIr_5G2hP5_h*(thI(B+gb%N|5ziHBL{ER!~aa3xBM(@Jdc)y#v+GT z+p`Hdta^KAVOvL9K|YYp!|kBa^_Wz1X_}4&Z>TjzSF}Go@C8L+zN69>cO6Uu7JL0(`&pbxwnGsJhS7wn6pusP+`*>YB-EVFJa(0?JbIhWll5FP z23nyD*l^{@mo%BoosKQL2M3)0ogk_sPLQ~~Cp+V@pyer#rlw;L<#dsU0heVBy6j}_ zB&T_v;@`e^wVW()0&Oj2YCQU6lNWpjF2XZUx5L_HAzBLWlTJ0VVvsmS$%Sa~0>7t| zMj!;Dx2HBQZ)4U}uV-jUf~7*GRPJiH`uw5!Zjp4!+XFVHMI(HLxaItI&qfLNhUfOz z`xT7vDAqjTA56GzO}D#*u0lVwPt%@m_(yQm>|XoANBDOTbt0$IrYZez+)7TT8#@r{1~Rc!knBD%MZPR$J>bd~r01jW_%CO$K!)gN zDKg9iIA=)zU&XaRR3rouh@3%b_-mRywIi?vWdh2)@wlzub_PVMoejMOdRA>@3OfU9 zYd&lh(%0X?g*of?Wh+vwG9i-e-0h5h|+9S*PWv&5NTXVz$c z!83hyUCF)Jy2OuI`s*J^*mU$FW*t>V5R4|V5 zzJHF;l44j$x&h3tw0CMcI)zRP7x~$TtKn^zmkvzbbxwqc<5=$~94CkQpVlr9xE+U? z(1|(3+BzT@vLFqE0@RkgTyR!Suh->92k~%8pkjYb)6vRCBig>Z1wuxDmeR&cT(u}_ zWo(Wv9=o*xG@t7xAqxXwU4TS58?L=*4*aVFQQ$Ig29#47@5J)RKF|S-`G|NW7B1>fhnG|c3n_IKZ~mR> zaby_+-M|L+z*vAM;d?K8oxw=JQWA+f*mP`~8-?D#5Ez@QCR8o;jwlI&_sj-9vK6kXgXjxA*a(^GKt^ZgADSvkM zIhW|8QArrd1h$OK2N%L*YlyNoa+mw*B`gCaI280Lu`7mOCejFs(OF4|VbH2SLr4A~ zD`P6Y?95RUUE*haU%1&FPsC<4f3>!R4z`hCok++%Ya7`&H8#FD8*aAUl8(jo@+S^h zkItGlKVfd}w4zZhc_OpfUUsf_%}ZETl$|FlAl=7KbPfDxfV776u{6Bs&1@3)s1@{ zgWi&cjtrR$$^ijZm|_hs9i|Q48AdfhZ3EpjCtsXZtzD_X%wCn|V=Y^LhpYPnvPg%Z zq;6om-5UxoBFBwqQAoeOR!t=&LPuq=$Gpp%mPV>9K~aD7Dm!$`=BK4@%J|iQ>m%K# zSkBM)L~V?&^4u2F14vXOa|#MXY1qTF5y$UlG`Ffnaq_0X7so$YfDPzoeQ%9_G1Dxms2s z`PdELCC~HOwy)w)BD=J;&b7RzxH!}K^07iy!V9jzaDJcnDr^>{`lM;lTM&1yknQfpUCE_5O&d^G9|1<(b z%%h`%&-u{b2Y+8nz*&(%#AYPH^zmg$`Q3}8e`ms^IvsImY{agPY^tutfj3cn))A#- zfG&RXS%G{k)Ew$N3M#51IgOa8XwWvL-r_Z-63x!MB>T-9I@6S$-Q6|JT59)XiDI-+ zH4T*S?mL>_kgnj(p3(C~=JZreHN8EmGhQUghMwvX2Vo|m#KflWh1osU)e}g@9$cp1 zJ9LLx7k4V`-1h4r_;;vaFc0tzs6%AzwC$yQ_|m;_kl(0fb20}glPOWocO&v6IL*yT z_~!_5)e|^J`>^l;(hCd>q@<(-nDtwyU2NM*U@HOXGrp*6U&@3+8HGS-$a3h;1hKPz zhbsj$l7=9UcJ>Kvn5;PxCQm_rzMr`(qS^_eFe)&jcov`YBKaE-a3cAu8^-&-T{U@k z3glZ^T$o3T^=j5ui=f>0Rznq5WYE(>YHN&(i(@heF$X+A_=2UdF3q+@(Uu%6Albte zog}Ipc6)oKsaX` z+#FmeT8sfGc|1~}QW%6M(u&nG1u|$rYl(l9LVC{%!wG`lT?zeC2fkEWg?|9xp@oe#d*_tJH%kdnU^qB$A z(6PhI+?ERKFcR@BHUgSUdwTV`H^m-HV;p*o#UMYrJa50N@c3~+|N0)GY=U3sl-$Kq zg66}{8{y7obldh296Dc2uQ@@iAV0Ph1Q@t+2x)XQrdGV)o}Nf~paL@31YVPJfG;xy zObQ@jo_#Gv+!6c^H~{^ib6cFK&CN~F#U2v{)6vq}LVSE7V`s;F6ZxAw0yrs{q((xI zOj!5A8f#fV47bX(-!{9oWs(km^%M8Aod-zAF8X~5DpZW3ynMR3;Bn9ZBvk{YPYLC_ z<8VfMb8{M+UdS1Sd$$$Rh)Yf6966{cVFBa-Dn zJAJY%lsp$;$y8Nwm7|iA3lZ&l;54Dg?CtI6=I0UjSkaz4IXWWX31ovXq>t>k@&56E zLkr;V!Lsnvxvpp-2c(EAxIYjyImyOp%|}2sX({^vSn?>46LJ1&|}c^V2Zg zPs6kvEH|fVmTJ|=R*w)=01f~U07UWf8cE2{CVvr6TP&bn^;l39 zPZ9h)o-5}s4`hw$z1hEVczkoJt5tXetqEYrw}CV1oe4T(1FWI|b@~_p#&4P;Z@_XQ zL-Wl6W;y8=JO&E5mX9GVROu+C0&##HwMF`p>3AHdv`QtIj?&c1>kEgyehQ5D46XQU z5^@?a$4I8>Rb{?k7JyNNMy=hZV}+XXE4S=dG#+>p&{bk~C~NgH+v_&Ev(JL2fH3vt zEFc=pQLevCDHV5jcbgXir(9Bu(V7TEsOU%;CuD-OLxpA=DMvh74TAdA*J#K+hIySd ztOiP@0I(0~Dn3UiFX~kJ1#SWc>C7)le)jhDK_PH$ZEk*8ZX!NjW0h-&E3c`ph9vb3 zjB~Qw3Xe(V_yCoqkIeLO!0$x~lz$HhBJlxh*cQ%6l;wG7Awr8Y*j`@Xr$a+Ty@-$I z*A}t^OiOlDRb5K|3&Q(}7*a|oIusNXuo67+GXz%P#M?MAEl*`br)r7v<{I2sH``RO zB~i(erfmG&u^Z_y`Svi0xIC|I%^+K%EG2wdnMkwqFnXe;Z2hgA{IjSOd!y$R7#E-+ z&Cv<`cvg8_0m;t9$NFm--7*;Lll>-IGtbng8Z)mMl8CBvLSFvFy39m+TicG}IoJMa zi(*{IJ4x$Vva`h#6v{vVF9t*Q<R=FbAGJ8;;u*) z*JSi0Ax9DE!Np89I3&?LSROyhvy52t7r7WaFFoZvnpUNE3$e+o723e&2uwsOYHHL~ zmEt6b1e2~E>>X+M z3-S3@g`&9>b}++FqEdghDc*AFBhIZ2b4t(SDMtayjWu87{mJW`HMcGtTWXZzHj_Oh z80Tl3m|aiTnf5|DIZB)mU8^)Bx-+VLMC&+cCA8?y%-Lh)IT{I~yW9sDvY{3OuFKECqVdfor^nfi}s z2ecq$&USxq4?H-4VO;?PKKiuP0EjaFq|7eKn zh5@-}-T2=Un(_i0jnm#Aw(rmZzpO}$@elZ(26m%G_kXktC<>M)rX=f(@AI#E{?w{B4gC8}f__M1G#zOY@iT?$?=%C|bqi~^$^7HfmV*JhE zL|H8R^fF9XaX`BTI29`Xa2PfhEeXbp>9}=n@}|^ORJV6`raYd%RXdB_?knHHciatk z!z4@*K}_Yq^FIutdMbI9wYo!h`PfjKI_uv*FpiU;+PWN~D0Ine;x{+a{QI+)|JgqN ze}3uox`m+eR>EO=3IspH=K$e;40Q}Vg|>2WTC#S(Le9c&ac1YN4;y70os7n z*4EbEUWxGZi4I{*MFP?^3h6dKzZc<3O7Y)$si=dt#S@I)$jZt_rIwXYruTDy@^t*7 z8{QAuM@&G_=J)9n9F)DNmNqRPh7MIg8}p5H!aBI-)|^X<>IHAqdK5@C$O}!)iI=8| zWmN+KozBkAa1CUii~?!{I*>jq9;#R?h32Cmo?l#mY*E{ZeDI`ncX<_~hXz~!oK48# z`iPRiI01x}j6kxs527ZPYC-1M_VMv6dRS#YnGtY#^89e>0VY3a`LP^M43B{NDp-NQ z086xVFbW2U?K<8mXKjl=%XN3Z&B-+tm&QXqZxPr9QBm^%K;_mQi(i*>ak&DrBq*d7 z6=852RJ6W@MM!*Q76&(tqWPor8wRGvQMr)$DP~!IH=I?S|I*39pPe?%2$j7HS zNJg8TQGJ2%du*N+xy2hzfdhGUb>Pc)T5SsimxmzhLVq6opU(p|C7cB=Xm7Zjvvj`) z0Rr7Sj#`>?aj!k@Ynr`+1r$bCf8Unmb3U2|od2OMCKf=ICnNKE1!=`;cOtQd@!vIYO`q4db(>))Exs7@$M&hww?y}?t&q4lM z=;!@-miF6QmM-wx)_eZPhvw@}#-A|STt1KYpq3ZxT3FClU%dd~W=D-zJ>2~Kq;a&b zU+dIZ6XQRE%bwQTIF~)6G4;URUJY|#kimsOA)l|9^n-=jJz;moQVEVTi_KDmg_mAz zHnh9`S&p~9?CJm|iQqZyIUD9jt8SqK{vq&dE7sOtg3wa0#~Zx5dJpgGc2W>?hV-2P zU&7XNH4slqQWDYj2Z#gd#M676EKMybv~&gRlGS`1tVpZ6>9BLu{{77%xNwGFtw#nxozSQae+}U^}Z+!4@ZSse!Q&V z=HTS?S27(+@rzb1)djjAL_(k-^c4e51A!TcC|kgiMm zNRQ{a{IKM}!m~;}g7o$J@v2#_mW&_}v)O8vrG#>r^nL~Y+qZ8N(4&W|G;K^LNXa1@ z`4`|GCw+bkQ5I8XWIgd)A;y!5;k-JDiPQ5p57C|SV3{|!|n8w@y%&0aC1$$ zG@bF*%{^U5kbZmPB+BXwM4XJx_egm$(z5(#1C;>&fG#^dyMj;wTwR*`F8)^;Sy`}l z7_}~4fsD!VV(4xE)e(Q>w{Mkp>sugESXP?CuK>UyPQ$6ZpjXOx;`6xNuW7n?-2;dD z+lHrnp1gdY13c&7Zy%0)70h+K(n(12Z|F&CtOTm`!@qyfZ{rzCHcO*fW zO4HNB5wtr0{c40_zb82z%23Q}v9!{cwe7Ngw4~QyYJ3|VQpfuxW!9)On#TXmU zYVp76*Z?Bi{b=^?$7o}gl`obn%KjI|mX^B%1D7MeibE#5ubUmSg;r8>a{ksh`uzsG z4IudF^L#FDo zci)Y-DGizd5YXwY=jEX%h^8DVb;jinaJM>pD=A^<_L+jh4MjaT+$_JRCcM0WQ&Ch; z!$ZDUG3!lGVz%F2hE;3GEq$(6Fw~&byW3v*z&}Q>`%nPS(H0W@Eli&szv6HbgaH3E zd9}@>hEEI%uoc-r!u@#ncRGI91S}58p|NPfk0Zl$?d@zD+Ka)8%Y9HGFuC=aneBaj zrc2Dcyr*EUA1kXpxMXN%DG0Q*7kgr?5LDGfhBTd%C+H0ZMRGqqJprataY!$y@Q1*|z}LbPKvR#OBn*K2p@Nt_ zk~C^C6j)1v34&RxnnHZW`sXY7AWH*~L~HBmMTy*8;}z&>uINK)!otE*Glnv;OK2ni z_qZ^GttVK)7Uxr)ZoKPR*b0T)okc`*; z20bFrK?c>bL@$05SaQL+RykyC`@3dSt@Cy5@rn=yw(a)Y^@!I0MiTCJWGT1~Z{;OO z7%N0TFmV!DJYK$813VECQ}&eQD6iZ4ooR?W#&KS6Q%W1myDjlB9Qs35hi+cL*8N`q z=J6%*)Xe)_s`|D-9?uZjoOXmUyu5|kfX#?G9s@&b3p+@&K<9M; z%Fx=B%u?6?BDu9}2WXRuoB4@TF)DjC6cZaJCzh+^EDrAU>&^bq_A|b3EO5NMZ`GPr zzJgqTyHetV=w~Ja*wGX3p_Su%W{3Z35lLXHn}SNP*x6o1J3vs&wk3E{eM0hPHpE2R zDBE$C#$K9yrHY13m*4*l^V%-O*OMCfXs)dsx$Y3j)9iIZY!f`kcYfnW>4^Rx{jvK% zV2aFE@`7IMaBei|n{qVeo7swbExp^qhdGDxRsHg_@;xl1{QN^S42-aGq&>fd^%~7q zJ9c}GQ;cMiuuB59Wh5=CHw)JPeK@=Q_fqwP%03m8@f=6eI-B@XF>~Zc$bBv5a7R)+ zo`Vbu*q?_z$f0V63v1RL^XNUD;h5*%3P17k>JpnAbS*r1p=;F z7`LCaYpEyOiqY6;Yk3`_(C>wBAnDUaoasPm^}ooy79QG;MNdVN-UkFgfG7(vKX!4T z(3enAArI6ohbJds;>C`ore{Gv(qmoF|?M?hZ=8fad(PO=UTMnKzr?~aWRrJ<*X(3>M{DEk9|sThKZ zw!eR8mQmgY(`JCnyt$#Ft*a|ZaO0yR?9c5KG8S~w(JFAh4bXz{GPo0Hn{SSpL-0YY zt(*x|3PBiD$gM$XM3Lv=QSq&ff3t7VtXfGOQBkg4k>L|SC;)#8MX73B3xba__|IfQ zrH7mNC0M$~8#00pc|t3p+`txtP>iGw$1kd(krZq_3~bCm)sRT)l+}2Pj65ACDH-kz zi|K3v95M#-N7EA)q4aq49)eE!NO|7I*0Or(9Q^T6c{b!1#hIP##Wd)`u$eoeDd$O# zjG^-7NQ@gkN3Ul#=a-vLK?g$}5?R4wgB0HN@ZUwwqm2qf@DzWoJ32AZ?X=Yo%-9e2 z_rNJ~ct}i<1zPR1eITMun8;cu{0vMaxtZ-6y1I(w8`I8OaZ~)jN0JOn9`6MV5N zP@F(JQn?2MxyGnViwI85S}^9vLH}5)aIS(Vt&RmSd|X}{%uG$eEyP3dQHa+=ZBjsE zi53K6CFUZXX|6&MdXWgp#((q9k+`Oh_K>-_ z$kqZ06FM4>AvsE&l!w*|rX8+un^stbEjNii5}M8n^=nmSWzdIm;k$CRCY)y{6stG( z%VLbSM$710)V!-j603W(B~Z$pgQn<;*ntu@nu(F&NUr?zh*?OpTHBH_$*qb5E`z+; zgPJ%=nC=BNqC$^bEYdp>k5fbuye!K(mz#o8p0F5-z z5doKhTkT~Z=zo>Hlv0=3Euy8p--Zf)E#Ttn;xTg$3k|gVKkGr}MXpRE9c%K=9ESSd zy`DI3apO`3MF@WJ~ zO;w{{@^X(&SJ=?!3tGuFTi~gM`2-yM9 z>k}?MK0a8hAh7`xl)!LS76t|=;QP=6d4xQDV-NOss4a@5t!j8g?G9z&(C2iR# zmIM^zS@;B5d!foBH1;O`Me!8q&-R8wg(lKV=fkCy!w-r(7?ilnW2Gak_YzW|eeH#& zK!6$Go#|DZOS2pE23sb6U8#TmZ~(I)W(8Ej)kFEA z{*%96XpEKbJ4%2yiT5+K&cCsVe~yn?nVF9c4})R%efVc?1_)FzgxG*DO>Xuo7_ab^ z7wWg5C?@8rgGm0U7LPxpw1`d;+<`P~EP^uk;39Hcaf12*XMqF{^%|!adN2vrTa1Xv zPsC7oDAENgZEH)l73KL8D-@%d4CZRKfM>3{Tnua=MmDr;;OkaOl<7(j-+UG`C_+JK z9~ra&QTb$f80#1>3fN2R+5|E=Sch^(?I1IXhcW13S$^C8-SVrr3W9}_&)C1_-5$sZ)Z?xdSc4?V2p$aNI42iY z@UF?0LE7EfR=vv}4)_vD%G_M@T#%qAm?(aGSDy$8Ezi6qik#Ft!ymA68a((srFl%^5~z)+KXiMhw1EoA_a%3dIWq-i50& zF$p5VG{t_XAGq7Oib+r%JXiPO5c%nfh+GN{3bD>`u3->vU@; zw(G)^j!G>nFDuhw8KcMMx-H76eiMYj^&Q8K?R$vTXXU@@?Nh$iN0CkPMl+fgLA%eJ zj=+V^kE05}kioC3E!JY_cXjK~|9PNT$B78(m>0tqd$kqKr;tqHp&E1V4^toNLB5G} zgY;D_H$P_T-N6tpljKstG09*;VFrf_?i<~B^FAR>b)Fd`OjC3C6v+b7m|NKduTV!@ z$T>qoFw^mK{$7-N!o+q8(BsTg*q+tr!9!orCyMcS%C0aewsOpgX){)PMg_(*|9Q?Y z64d=ct#e-ZiTg1L%H;D1-g8c?B8ag6|F3(PP=!xkf)S!1O-1&^6572XPIBh*{jZNj!PdytcVWz}kxSMl zw#UgtLLBhd06r^KRtlyRs$Ml#2nPWNTVO&f2Tue~RXwY}SN65e2dn8@%o8!{eRytmFNW^|5Oi3!_VD+MdRU&aqS9s&fGIdI$jSdJ!`G4w&cQ;53F zK60Y3hX&h@s)TI|MXfN9lBS(4vhf_?jWbRV~#I~>~P}y80NNn5Hp4b2xmQ_?%UtikYy~bl=?h9qV zMQsq9Vr``Vpz^X(V_jU7!8B=M)YKd$I}du_2ZKul-*wz#dTXf8$K^Er6OHpJXdPjsz`+wY@#uLx|R9Um7z4GO%S*#7ae(GY~4Ha0f6=O$}wLe0%r6nLD)0Q^rE6oie| zVmd&l#KY6Pv%Aa8TuY0XP04HDEk|Nor^+fqFMdIpNQ4uAm%*)xH;4!>>D6KL<`9Tp&;E_iDyS+fECe$lW;X!MnSA)$F6Zqk)bD70Nz3Hh#Z$m$mk*LF+H4`_twt zEmrE-E(mt(9~}pP!F3bA7u$DiazlIv2#tW)oWljd`5$>I9qk=yC8nS$2%DRY%eA)c zj8!&~^FSd}5+;f+H;hU@9`#QV(nX&T44(qLjqI_svR3;mEXNl6@4?qi?1YRd$UhHj zdqK>k%3fQTaP#M95he3y-*oG@unPt@&;ruvw>H-j>Q`fPNB}z;`LA)|AZ6;W!u@Fs zsSU}l_1!0(Xj9n*p6k9$Ln}iAU%0UJ%yx;ijhUJ2lMd$V6V@N!z6rUO(y==#o0}hv zj`DE=Z5Xf*i+I(04TQ0RDi%CEA|HUzwgm*JN)8>|-@mU^XzhAh{ruV+6ms_TKq6t! z!Y2F{lDzcQ9+4lsuc(FD$y$%a+G3SZkMGqrH6mVTSPZad2hX5mVJd?vN{L<`lDF(? z@W9{44C+-*$fZ$GQZ#{0GC$|$U?|`5FPGmkIc-{=a<(%$KmZ|Aw}5RdD1b0G*RAc5YohT1N5)i&#Jt-%B z6&$kD0&g?5cJDdN?k$yqE|wA64Ze|iR@hHV(UKBNQK&&tUQF6Rc#!r92uzBL0iuAd zEinRul#A=%tjuMM*KcRm)<$&AC|F^HgkbOP;Gq_PO$3T0fr605{ltLRO4j#KWBy=v zK6|;HCrc1~wU{6J7?v@Nlo93{;VFr>kptNQa3Ir?nPCZ&`}JE5G;gO6jms&aeH2mX z6gN54ulcmrXfiOK<*E)2xx;xT6e>~=deCo8a5F?*c6UM4N`G`javowqYFYud}i8}f;jHeS1ji5cpV zj~~M@@Kg5o{tVyygnRDd8~h>TTls0|b|y19^o~mQtG%7lNBzYEbso6|m5t@4DJ|dD z>K?}s-_}D>)AP@N4Egy5f{=x*u=JK2%L0i6gHj^^1y7*0$Pm^G8Tp`L3MAiP^iJ<< zHt58NMcj{|pe!rM?Fz5+^D8T=FQvGQao!zzDgu!Ei8+FfP9v!fz(Nd5#LdZnh|69+XC@+?YTwpfR9AJhxmNz? z2G$^ym26x6kb3n`sTp=j@W(Yym-`LF!|zKL(fyV^f~ZN0IxvDrSeFtpNk97B_dgq5 zNH7kt`nynnpeb;{uMm>aY&V!^4U&tq5n(#Mm7L%H2w})al}z#~sRrHED}<}-i_*>j z_Og1q&j0SK@@@~=ww5v^tJC@}{HL4FyW%JR(7gH|(H$LXmRCPpVTaZlf?1CIr&c%4 z&eT5XTuOk2vrpZunuK8EHj?cmu>w)a18WaJ`M`cPvx+k>8lV;*tB{5Hg=a^D2Ol zSI?k^a$EB7akjfXYOeWwMe|bal7Qel^Y5{$68XgGV5pMm8{=GtYI68pj~o%Uc7u}& z1J>X43e+KJni7x8UXgu>IdT%p6q?VJLJn0|O*dV8`tJ6fn!mdF0(FHh&q%^OGrCYrnI7 z!Xu0Ksf$<5PM5qKO2_xlsnaR9Ht5FM^f1_Cl}N+cUP_W^*_1KcpOrkpP|%zq$xux# zZZNxKc0(l5ppC>-0~dQuM5L!sdZ{kVlzG`@KVkEK*Qxjdp`!hQ?SY1d7K(TU_aKU; zia`u%AEq@`u{D}P*0(pL*DxeWZ$j_-xbbZw4wa}T!qc-HM>2$=LmTKDU!TebqF zGG&`6hu>s~9G?q&R?K@neloS$t;7*d#2}iuevs6((M4!4wCKH&Nj2zOGZopBxRZ2# z20>UQ4RUhg?Z34J#RU&$EUm1sE9t!a0M*C*-@luh-9d1=wz^78rc#9XX!w$@=vz$x zN7@HHA2|-A6E-j<^)F)o_V(8yRGoX3(B}_E!I5zm`LeaL{lC7al0&Mk%n=t4m1Fd?P9=eZJ@&a25tr$dwVcI!o=O32l7wQ4TfETZc@MAlo0ku-z|5x?ayU#A~G&Ue66`? z+;h!-qk>Os^V_;Rxvf5M%&(3L;naMy-xty|(WsM@E0j8jU@M2P@y7_k>1E0Z@xHw* zDo{qp*heLA_iaXi{yccJhURJyjSAM#tC5bGK$Uwmy9qW0!Gk}bcDj>-@S{|XTYYS< z7l*T*1FzDHE#`0bL|CZSH{%z&p>Wx`&R|s`6AjuhEjc40;$*ENNE3>~ktKsh=3B0rqr7y}5!?~8 zC}J43IyH2309aOS{h5iZ>;XtAKm;WzNxQb@r{D5kTm#JZHCY&n?t+JZfTpu&bGmgJ z10L4SkS=i7z7?3XS)5v5_b-pe*q*E4*75MbfI`%R)&YG68rV$~6qLimLqM{DeXpsZ z0lK=Nb%(O_)_FTb&;HWZP&qB&DbU@@qPHEk{f)`NpHNgnz6ps|apKiIOJ4)}YFkXh z=I-JC&lPiLnnYqqs9|tak^AzWLxh=L6Ua(2aBy(sW2n7u+xzxwA2+w5#J99={gV;< zt`*T(L|hWGkJ$FvthlcXwV0Z#O|lZLQpw%}Ufqf=&D|=PVdr|ThRXTT$EOLxok1*z zJR4zJhQ?zk+ENdraGq2V)Uq@G@MlE#%^z|ighM#Bf{5p5e_Hi#79SEmT9!}#-j!M zKSv}?41A)&U%sHsR2#IVa`Y@cE(1S15SYg`dV70=3M-TrKr913kqC46S$=D4ON%F8 zCPimt4I-M3r&=^zJ=oQ&vrzIogW&~5MV~NrdNG8(mj4E`C9OvbD`Z#`=zm8I8Di=GV!p6qGGAs?yG-8&i@ zqhi^SLU^=ga;0J!jID-!v$Wpm&bdY`8S&t=JvB>J3g|cA{p)1`#PpWgl;1ALVC*dENt%nVCS{rm|r8Z_R5&J)!E7^m$HBtFVHmBHmu>}pz? z^C@Y0g1)VIbl`V<9~&#k17fHEaG^*_!i&)ME&yH5-JP|y^;Fzmtj8TfwLpa=sIE5% z+|C`_lvY<&MPp{YbrCiJGrx#y3PuXQ&n11ogTpD^ph}#?Ot`ewP!T#Gk^zURW{s@4 zuv6B(7tW0ovAj@da@8h@GY(X--B>(Pt)_O(Gf4$K9gYKqzL|^ynrXYf3q@{YCyknf zq*mw7C~rwagX)tH*Hm#(vu1rE4@IpifG%i-9)?^HMoRt zAP-?8nV>rrqfmd2S?mio%BKu1RE;)Twf`djYo%%co-Ue$qmDHNH zR;^6}rD&H!sWOExF$OMKJ}W+K)fx*1uTS?p`%v=h&VXk2ygnTk{VR+qE;s-Yo3XR3 zOwWa6&xePvj=r;(xtAC`&)yvsNh);el8(~mc46hA&Gih2yT__LXbrJ|Vd=_hm5T|J z8HlK`Tocjb3M{EXzkTYD($qZvHF1h6GVA;ME)lo9x_T#i{8R(nK4q8s zV|9W4_K_i}mvCJGNcGuzEX9YBioYt)9cE|J@fABi6LcDY=NKzbX>!q0V!Xa-vMb3IgvntxekgpkMo86}^xGHl?$8;}!YO4_irYs_ygNN| zj?|KiXGkhN7*bi*M}%V>K@&DW&W5IL<6@*ad!zbGr=M|Gs)SE+FPI2As$7PKDI`a> zMry`HnTWoKz(Bqz^iBfr{UF4r?5(Y@QV+*PkcD~0Q>}y{61j#MRUy@*tkk3gJ)&Y& zh4bYp!7g2q;nO818h@2#1m?i|&I2ZmUkW}dDL6>u@U1jcPUh(*n$$?s)`-}}L}`Ja zZ3jf>q0>jBT(0<7gpq3!F2kbQBg#B%uO%c_Iu(jbhfaMr-s^fA%EQ(dZdBW>Efd&p z=1$c$hD}`!RK9E`sbUs%5h4B6Pl|a~Ts)1qr+Ff;2$+Uc)?xe8P6f1}pr%9O{qHU; zp??Bn+(68ysMI8c>Y<7uWDxTXRQA86S1d$coxiFi$8VkrN0va^4?w6adIgD1wzj56 zvnhwg;1(ucp9-Vv!(Empl4edQ(2|SXahrq7Cb(hXNM5cC5HveB?J0^q8v0)UL!K=0Q>mpU zK?yEJY%0`+8gB5tFUrNGW3h=UY}8|%oR5)hp-Nzh#{%b|b*Z~ckiH7*5!u2FRJC=4 zwLu5TJ_i1Dj6XC_VDSd~u>f&@X4vecXFj=MN#1jO58E6|V4#8sTjqkSggI=xM9&(E zUDOn{PP8t#QW7iX2eSgvvezNltkKh=6?E31vYe3nEOSVFpg4bO zdrolYg#SdY4RF@s=Qy0|I(fMfQp8OvvZVQ@L^Z2w&h4K*Q0e_8gNlY6UTLDdev?+t zi_V-O;c{Vc8r;pEtvH-|9bJMmz5lrsiJ!@ptvK^?-_*X9z{KW@GPgPmb*u^YltjTd zHD+uTNwL{!;jInUuGes4xjy?z2F9Bk5m4jS*cKX?NkkC~uFuM30U2>T)Tgg{4r^QLuay9Y|^5w`ZO1= z`?^3*wlsBVmhXPYj!&XdCURdtPy(NO+TM?tBk7~wPiijp)7oeK_yWh&(u`KQJLU#H zg%4!}Dv`x=Fx2N6sn0ZprmW)}bcGMhL-tIPjC7V|2N7xF5xQX6Q=e?td-19OSI`x};~HmOe%^u)v( z>NJJMWfE|$7nCeXi_&7~wd!WZU3gC+LjnC8P{%qGQ!5@{;WvYdIr|_Nl>|?u1I_!tZLZb6Nr^!?%IO}+UsWI`fCJSWjMSk zGagO@-`UdoZbi+AmOCBW5ju1h#ZnIn)XBnx6;mbF)%ScUJ`1LueiAb0VJPm(5-rRq z)7u?_aHCVrF79ueBg+M|qmD&O2m4~{x%&sRNmQ*0rT1e>u0O?Ve`Ec#hkuw7aRP^i zFI#%Ot>zj^Ldi4BOSXccc!kbd(L(JXzBxCqKN0rGdL%ptmZuOe!jC92_P@_g3EgMV zjW9TjYM*xQ8#>-rolnozp8SPL#bHpktbJKY&iXQrRJq-L1lKsq`WL}yHIP=Z^i6YS zr%wPK`oLgMLr@f*TAV&|2iy2yt{Nf16HOtT`eY-jU3;0?iX8lXr04IkB`KA22QIi_ zH93h7lv-G1L(C}($B%gL#mdY))x(&Si@(~TxO%8JJe>@%sRtn^%kKYyEtU(Sf3Mc@ zm5$m2&9BG*V8`Cqvz#N7=nJ|{h+H^!%8lBP>5+AZi{Hd=?(JNm;~ z1We2>4(*jnZgVZp<0Q^JP99ROg~M!>icf0O73?>FS7HvukDoLE!Ho2vA8CJ8+2wH~ z4D#aGqie64Z~-;)_r`vv+aC|lR@@WL5B)(S+pauVbRO-c@2Uw7}_{&;hpLuMQ3VTb*4v;X>b9n6KT z1?M&_8LcN(ye0^S5gd{>8#ezqrCj_5LB2EK)Av8P=5%IRr3kl3l0U{p&NAX9tB_jd zlq(~D?OFVh-T>6u_GJG~j^@f+ZAY)nNnu|d~5 zeC6Hv0tv@1y-mE1T$;J^epqgpqYHwmvjf7rq0}*XJ*>*n9|F(G%AQ#!1Z}L3TDC~s z!jb}~#H}UpI?e>sJKr@vbS2~6GrfDU_z=aBaVYT1lO>FF8<_k1GT17)6r z{IHZ_X(7HCB`KdHQ!}-%OojrwGM9G!8{ZQFq<3o6dHo4fxqcUMxr{`V$ePuUys zpfAJVDjT7H+p5WH@0L{R8}Jgg(WrcbyjkwapPYMLAP2i|QEklmzjtturfSDD5FoQ$ z$-N}DI84dd+3At#JsI}=Kpg#3+EK^+tKAZhFy_{YrytI6QH{@@VjB{)UBNTmy7mwv zdjaST_~*jXd41);LoF9vZA49=^0M+ZK$OzuTdjV7b?F{syEffvAx_`g%Ye3hDR*!Cb zB5ZU_ZN_VcK-ocj!lYVdy&!saC5i@359QEDM$O(N{Hw0<5!YLD3ty5d%I+ol;h}@C4G)BLpNsLLAMh0*#WI`57n{_avX;p_}fT zE&vr8$h#e+7k)mE3;3V~C(KAKSQiRsW8>i2dAy+4nIm#HrYv$fWhHVRsqD9f8qnov zY#O5VYnggH&>ipm6vAH2vbAV-byZI^a?uS)AGtp5&I9Xvdx`)u~zsH}! zBg%i&_Z|_sED*W7EF-_)ChP%XI&|~#kFI6^;VJ%eH#O_Y1p=SMrFOuTHu=NSi17V% zoIe##P@MFqS6@Qk?(v1Jop`MrH}dJ7dw>Tg-@Q$U^FHXsq$hivD--_P5I223d4C4}_x5bw^PjxOF==5S z{AbQ3+Kzmj3V*)rLllwbQu4bU~V7-&Y4UCYJzK0X|Ol5TVY z(k72q5AV+WS5or+q}pB zs|74jB|sn1u}&!vY2vttIy1h*{D3DTGoS}kG3kH(HxSj-P!c0P)XL zJ&lM~fg-944{Iu-5F#i=oPc|W^%uN5-tN2cQ!FjvOj?>)w#OuqJ0#jDe+g~5ig_Ds ze!n-F(7sryK4h{-e7jmAs$xK7c^m%?Uw{p#7nnnC z{)2mL_5u|;S=c83V4Z0+3BY2lXQ1(|q^1 z1C-K>O1B_tC7ev--)u%vsG&3L>JQ0Z&R_m*)Yxhc)l80vMgtj#Nx{E@A<{nMVrmi) zoNFw;ivrB2$b6IsFo5X-SWIxdb`tWQ_IP{XJG-xHPOUANiKp(-^6C85F#6w3?*M2W zp)lFFh+0%-KnoP}F&%8Ii8ncTe=K$hqk-<+2>RA$O5B!kKpAijoEC9uU?`L^sGK}z z_1uMTZx?|cG6osT^YY^JRo%<|=^Mv&j3A-&!CA2V0=`!O^4jm+dLtw`F-uftSe2?fId)?BLmDKpxHSggs@O1&LfPio7CA0AzvGC5`o~yT()(LPjolXir^aEC4 zWC0i&zTjo!ykrK&5^M5b`==xo?83N?&Qs0M0jAKU6%ZL@3OoSYkgOP(~|n~z2~t9&=E!d^~<4VkLr4!!1Ire6iI6L+>OiU&u=^*iv;UJ z{RD6{87QxWdBUFCU0`6@J8sby)wU4ZEJ^c!0T!G9Kn;9(J{9@bakl^`=>W~gU$LG@ z)?;`RPOQk?kGpk`;0K#KIIJ&rU&jI`5HNhb3@r9MvxDY%z**m<;N6Zoz`zav7I{gd z1+rZ&Ma4DV?(@3V%W#p-$Q4qNo3@_ON%q?<%op6^2k;#-Zo;=Q(Y@3}NWDNIxp^T?b~p47S1IMa6`E$s!gO_5<@k6z@`64UAEy(m z&<%i#P)0ORHKTxfjt(p+l#gAfPa_w*RU%}^qrJ^Ex6>~h>un=i?uItL&y|&5i$cPY z6tS=h1tTbE~TFh^>tZ1qDe25@ry2 zzhDUG=+ZklST44RGc0ygC#;HhSmtZ44eqsVmi|ADuV=2C>p0_0j2lICwMTxRG#dXt zY3}J-Shfpz@pcKjSHZpTKB~FM%mnws8@t~VdyB>|fB*b+6ug?dc|Y#syWV*R#PC5T zPvEs8Hdj`y2)Z9Om6qmU3iG}8kro1uKVJ5(%RGxO7GoE{o|LMkvcKHiJjIuRIuiFn zlRprT#S$G>vZ<3`A}IkrXuQd2efQIMBM*yWvBKHpRYB3b%`HnXe7meKPyyZ`xjaG`7h_hV9(zA@IXG&WneBj;^BkNFBAZh6LX0!-C;gM|MeE7@F01hIH7A8` z2DFWz#xecR9>LN?-yfxp^M(J?>~?Tb=V$-k&u>8JX0-(rcWq|L?)P|KG9D=-b`7SPet~pV<$`Ef zzVyXxaHeQ~{<||AhUvjbb@1dzm?DpwHd!VdJ^_fm?5~m$-Tru*BZtA!I9+r~@k#=H_<9i6 zg2!e!M%u`0OOkH^jP-K;or9a}z4tSNoBZSLmULdgv$RSTI0iBy8&4-mz7Lz9xHolf z)^0YH1MW`^rcjo)e#O0fj|+HI=hJFEcJ7R8bN`E+>ZToa3O`OPaE*aP@Ta7xC{N|& ze+y^T7c89ixfCJK=RW}EbJ~8yHiUh{;;xlTH zz{;9uT{Ly5`0kRwI72RX?|ujL=dk;3y=fq5Rz;Qp3t8M{2B)Os>AK-&LqyS7HCt?8 z!()YLh-X(=@-I8YVXmChDFN8!#3hDfULl4CC-=(GDd)O892enxUVcB>A%`DPOAZHL zH5g}MYH2x6{=%o?@4TUrMxj}G>~&j1{)cs-YF84>}D zl)!D+0-`(u*I$pclF85GLEbVomggcVQs+MYQ;2FmVNU&NWLbyV=f_JNrmv z2<$;7yuk3M&7cD+-)+&EY{g8s7TwvMTDV=DpTU_iWI_ws8E#2F?YF1DSeGgaBbgS; zCCQt6E5*g?EnaDO`DBWcFf&*E(hd3V(;$MUVe{~Cd(Wnn4n=(~eY?ha{@Gc4pms2P z(0!Bi0vQ#yB07g5DkU9P!4m92x2f2Pu>>V%G+WyH!lhyt$`+3Er~=C{egX3lr8jut z>Jz3*tPw~o7X2Zz^;iuI0+iCp(WvmQVE?j<#!bwRaN&bF=;di@xMpoR8Zl9L-lY!dHf0HbOtC;twM9*(ywwm{81EeX+6XA z;q<=fddsGQCi_D?lRhGOB57-b-OncZQVqm1gu6j(au!Vrrawmn=F@J`H!k>g6cRRu zh8;TWV_tVsw^Mf%Pta;CsR>Jt1}~kHAC<7|w*t-(QuP{x>3F`Ia3rds@XBd=4=x#qf3rT%*h~hfbicjtxGvu zs#7kCb2N2MhNcKZ&iv%MGI8<48sl49zeyl@yi2odz~$#~4*0VqK&RNA-uQp?c)zcm=bg-Kl^Yr~2PH60sGSNU1~aZm|EuK+tV} z3fLz_C>cBzNSV-6e^_;S|DZo7{vj#LG9@^eqJZ%3)v3kzS#=i@Lca#-ohr6dw!hVh z(^LDO$r9w0F?1>e`CVj3sM%<(Sp38)i#u?RW_nZzyhoz7BVlYOOL-IznG@grN#5JT ztv-K-vt#;qUkpX3S#bTFn4qz(r~3B^LzW9O35q6U=aM`I@e&v{n#*ZEERHGU_VRS2 zjLuE_ej3J z9ron0v}gi>o~prQDj@dv#|6C@-E%%-T1T9==K6unWZJBG$+;O*?@Z zw3fBm-f~x}Tx&E|C;BPnWI094hs^R7sD4#&c;oOT6?ZAeevY4-xHCrN;VT|*Q!a598@{N}F#?Ov2O-mNLmd`_)iMWMTCSGK$gjWz1|c=$*Lku^?Cv90*|#*M=%Pl6Ji zaycfJuXUR^ML0%d>9QOcPe(IYM~mN0_YBJ`$WqG)%G&O)%&9g3>a&x&0qd1s_FMu2 za%nv=&DX1Joaoc2T1N3FySJ2<7#b}qx+PjWud$onMu^BB(W%lhGM0Sip*gPUK9sLl zYe7)VerphWKNUoGmU3Gzlmc9|5-NBq%U|YLgEhldM66E5dK9iwnCh|>zgRtBv0O#2 zX|Kp;yR)e06t$zj&v}i_8C+1niUC}6p`e+rpaKV_2b!n?YOZK2}7;A5HX%Be=wKeBVsPa!pN2 zUA3W1F2clF+Bb9oU21Bl3n3cq=;(;|!_w5k!h2N4X&C${ig=`{o>IFp0Wn-HKI4`n3U51lP7;+zqqW>G|On8;N zg{%#aOqkxK>q6XxihYz~EE~m|~svzx)laf(8YLwAD~E z%H@P&i&W5!=5-I;6=6~=T@-6lQO5DiOFw;u>-xW1KzE{?f_wfT4TY(o*|+)=Du1Gi zGF_lZGVJm1@`)30Gv#B zeax-bS7@6P-%pqObI0bac3xg9_LMJFI1Kq?VuL@oARDdu-Hae*hnnNLRsKP#h1kB? z^l=yc_=qYDqOGKvbt+P-T*4!#GP00$8>fq@JAi?%w>nb?CzQ3WH<(KwHh(~@e0C8 ztqT(VG&Vy(tN2GFaUF`nKkfXBL2ca5a89Cl9f8BzziB!e3RoSQRa&$T-^zSc7@Vs+ z&7q2SlmMARP+>4SxO!k0S61tBWoinl0qY}{h&nM2#YJnt{iO{y@u9+z2B+MP^M0tC z_9~&|>?hw!zS;_e5ISc(=@5k*+D0{H$T%+Z@0_M6XYBiM`2EBAs&Ni!>`Q$H1>i<0 z?_~U49&<2HGqnrPFkPV}?6lbnrV3rE(~JXPN`7Y|D4J`<%<1yC?df(GT6uZO9CyyT zS4_-Ml&=4*5;*IKBd(6nM|{FzkwT<0?3YuJLB=UtFpGFq)1aW%Qy|Sx;W`?EPxq-7 zfFR%2JDi?596AX(T!eh^j&}#sl~%B_=Abi&h^(6F9z@r5|0-_ep?0cU(;q0)(2e|oqf7xV%bP>KP$kdKDXsTqt6 z%?Ge%fOBNVq*R|FO}QbQtValoA7oWHGUDdu)Hk|a=X{T0Sr#zdq86e8@vkd*mz?w7 z{>Tw%DJ+CR0PITELn+-IV|8`djC{N=nIZwgH(Mxg-ayCL0v870iikLG!|`NuTVV*s z91TSis-qiy1B0|iLtMPEn8X!jl!ZG-fN}K<|K-Bo(C~E}#n6XexjLI5_L}!SlyZnH zGA?L&fP%C8`NdN2Vg@c_Yc%9*v45Z31km8UiPo@5+-JxX717Yr>NoICZFg2YDn}@B zefN7xa)(80P@eF}4_xdAMqFj{mrz$=z6pJfxX=FLKVr$V|%|ojDMMTD$@5%e&?j@88E%t~kOeg=6*|E=r{H#fDX&|4B!t^tQPhk=t zYJWNrvmihZDeaAlhZXSn6aS`ssps2E`{jYd#~%t=2{tb zQB+1QGQW0`krlFUk`-~Sa3izGh?`wTTtw0D?fd)vK7YV{yzhOV&$;jOI`8v*-F|qn zLlcfC3r~+%KPW_+r@b271$Ig=4IPytX>qvwAgYA z#!d;ao!YYF650b6gv?C# zTjv($&pD2uH#_XvFW;o9jFdHFuRf(oD?d&ES3|+vQgED{GuxSs`3IXb%>d<_K@BO~ zVG|2iVyQe3?pZ9+WSx)Q3DAFdJB1H@M+hb^g55`sxthuUkfD z%+*ElzEAA5RC3~iO<))VWuglW)fx&v8p~hR7XP#AP*+m2Xwpz`Ohx?SW_(v#H<;S<+=H`gB^>bJlH39OGcCB>)EVid(28f|;@J35Ag44IgK)Y>Zuijzm^x1F~d)wkwJ0Ymz-;-Za-1L4;Ny_pbxB;Ni2Wz)l^4u#9x+l$7^h&=bI<(BRnzz@E&AHdJXwTr_ z0%+Z4V-A>FT4qk7xVATG|N9=a`T?pAm)i5Jk^ zMKLGDx@xE^$;p1gJ%gE);1JU3RDAhfRQ);)x$vEp!J)m_j zoN|b>4s?*HRNd`ro7bY)Z}z3~LR?(@y0Dokc~6^TY@;ey z`FVS>2OgRFOL{9~4(r-HL?SVDxeB#_9%UTm8P60=Kij58U634Nkl%4t)^E48`^JQy zpI@n#aH;&N!=^?J&YMx zCG%|-vJYtglPauttrrP1AdaNaLxs?=0L0%{1!>NjN$oxB%0K8nIgLY~sYY7)_+Nfp zC_n-Eoa{Z}6g`|QjMaDr;&puX{?@={H*K{=@`X{ts+t#ev9>ERGtOv&Yb$wT$rYtH ztV{o51hX47XCcDaK4hf($XCTUlq}j0F>A|BMt%8q7UdS2_=_*R&v5QN(m1r~o?>;3 zu--p)&@x4k=QzoMJ3ByD#HXob(t=&M>|q zrGHQS`Y>mgu-HlKyXu7(QhYmmk~Oa6Znq<50nOlHsp_5*X?8j+BXzgLS8qP%CA6S& zMm%Jkbuy%mLT3|;%mvZe#DEBk6{}Fc42O$a3&kxV7&94JFFYdY;^ZTa-)0;(SA|_V zIi=Iw%zJ_kl7f89h;KtWes=S)SJMe;H!zEB;UIz3v@vTx$G3_zG4=CkMgG}wfBbKI zWR`!8JPpezA6FTsu8CzdsKV}UfoG9_`Ye8W>*qVRDB{*V!CL>hE)8ZwUc$!Cdn_iB zuIMQ)cK@2y>5E2W%#yde}Ue}xY$5Nb4xvO{x9`bK=LfD&9gM1l?qdSBFnw65tZaW|HfT8I1 zv>?WEy9a zQU&&~L_)SqYD`hY!Pjs9O7x4mXsPL?wiy(0&`KOP zKpnY-*A$Hk&()Rt)t~eqoxS(tpBRca7?+4Evaz zWOQd);C6r5CNKU*`cLr(=eO)lUSO?qNiQ)*Ylf{UGv5pb)qCOrg4iM}-!h{;m?#?( z_3>6tW3DAjkgk@(eIl~6>|UbBvCJsqMqmr4GFPLn6}iAgazp!NNA=mfPcD~&c_*u0 zs{A<#^i^_~J;~zuzUUVe`<&03Gf0s!z#`$~orrsk+^}b|(wC*J6VLV(C;J#lPKpJ( zD}AkK8*24JM=q?;-o^PTleWVi1i$Jw^E=VVA0L5w2T2@mEl_H%>@i$3z(2-tBgiKB zdKV-R^1vyVhld9^JXCr;DYyPPV-eJ0(;Kt9d?FHl!aZLJZW;qKwYs`Ga5jprEs*AQ z7xrz>N^fHO%n)Ou253WIMrH~y{!fm71MuHnT-G^(1gh`XDOkWKOi5c5_#~r~gF+yknR}^3uq~dah)#`5|dWoz$w&@gte`B7OqT2)-uAIt}E>x<^Z@S;IPbS{kEfXw+6HdW%6&1K+GMT(BUTqGX z$~jUB$Aal?;S>}!AN4fVEXzzBcVdv)XI>F`6+3eWUmJcv{3Y}P8{x9_4L7u5?qfrD zHSrE7*HdDC$#QUj=PUr=`=};s;_il~ESu!DgMV!Yk>h@zC@(_puOLufjoua+n!a8? zD)H-T?c*SQeO|`16U$$L19aYvho9ses720IpU(^_B-c)cH&Kg{;qeV+rxNd|76HXG zZB*59DVzGS5P=d5-p7@hZnghK22@ww-R7(5@h4YDL*2L?fJ*U0=lYMTh6WT{JY%`G zXKN8*fQwN&K=wcb4`0G}fp9pq7FHEkVco|vs%}Lams$f#Xa6OIfaMP(#X9#Rf#~uF zw&pBFHbNbKNQvQug1D%@`9|N^dN^-q$Dh~3Xrj?~`X2BsFE5s3B|65e#ZNr| zrXTed$$89a z$>KkH<@z2J2AD73Hd=uy1ZG@X)ygG$p7An#|&4?Pqc1i(>UI~1xnxv;26{XK8r z7u!e9>Ub(e=zn?b*rx=0k>X)`^%%x-S8efUXgx+*5-b5nE?p z-whyXT;k0dIgCmn)CVp%3?4x~Gkm|b%68kdUeAL!_6wiF9SSLLwyDV{d@;Y)R~rGd z;_f-&$V#>75}xmk-C&_?3KCmn^wT5N^~!DIYyU2CvRE~ZXYnE;3d_YXtU_=Jo4_7y z3;S}p8ZX_{@sPiEjZe{Ev&O8U{o}Gf-KQA-uq*|G^nJb^-_X!DvPkv>;>1wHZHGY1 z59G0nDq*=cj*=T1v{|`RB0_`~N@oVXfpwZW7z7j z;4uvNvA2R0bDDsDSJW2g7`C-iIyi!f853|!2F4y*&Ppupg7p+#F-}lbTSlYGi`=wV zbpGvN%aWPs3<9Q%COVModNDZ&c-$?-X)6DA=A~8tK7L&rKRqm%Bi%jox?k804^v{v9gAsngY}L z;u0>>rl5t}ZZRj?+T7Y2Lcmc2YaSn8-@z8sS#uM1@@x3hADykSpmf--sz)gX#S)~M z%<<%%P3iwIbJsCrbtPW`01mUzmOC`AeUjwtIlg=6PMx@d$n-TfBT^$Dg?xH z3>AFbvcIE@HC$E-tw9=$Eq#g@OH-~{Y$`5Da(72C>nq$auqnd*P;geV7h|dNj&900 zYC zq-_K7gQZKuk~C`+ { test.describe("Workspace navigation regression", () => { test.describe.configure({ timeout: 240_000 }); + test("removes a foreign pinned agent when restoring a saved workspace layout", async ({ + page, + }, testInfo) => { + const serverId = getServerId(); + const firstWorkspace = await seedWorkspace({ + repoPrefix: "workspace-owner-", + title: "Original workspace", + }); + const secondWorkspace = await seedWorkspace({ + repoPrefix: "workspace-restored-", + title: "Restored workspace", + }); + try { + const firstAgent = await createMockIdleAgent(firstWorkspace.client, { + cwd: firstWorkspace.repoPath, + workspaceId: firstWorkspace.workspaceId, + title: "Original workspace agent", + }); + const secondAgent = await createMockIdleAgent(secondWorkspace.client, { + cwd: secondWorkspace.repoPath, + workspaceId: secondWorkspace.workspaceId, + title: "Restored workspace agent", + }); + await gotoAppShell(page); + await openWorkspaceWithAgents(page, [firstAgent, secondAgent]); + await seedForeignPinnedAgentTab(page, { + serverId, + workspaceId: secondWorkspace.workspaceId, + agentId: firstAgent.id, + }); + + await page.reload(); + await waitForSidebarHydration(page); + await waitForWorkspaceTabsVisible(page); + await expectWorkspaceHeader(page, { + title: secondWorkspace.workspaceName, + subtitle: secondWorkspace.projectDisplayName, + }); + await testInfo.attach("hydrated-workspace", { + body: await page.screenshot({ path: testInfo.outputPath("hydrated-workspace.png") }), + contentType: "image/png", + }); + await expectAgentAbsentFromWorkspaceLayout(page, { + serverId, + workspaceId: secondWorkspace.workspaceId, + agentId: firstAgent.id, + }); + await expectOnlyWorkspaceAgentTabsVisible(page, [secondAgent.id]); + await testInfo.attach("restored-workspace", { + body: await page.screenshot({ path: testInfo.outputPath("restored-workspace.png") }), + contentType: "image/png", + }); + + await switchWorkspaceViaSidebar({ + page, + serverId, + workspaceId: firstWorkspace.workspaceId, + }); + await waitForWorkspaceTabsVisible(page); + await expectOnlyWorkspaceAgentTabsVisible(page, [firstAgent.id]); + const agents = await firstWorkspace.client.fetchAgents(); + expect( + agents.entries.find(({ agent }) => agent.id === firstAgent.id)?.agent.workspaceId, + ).toBe(firstWorkspace.workspaceId); + expect( + agents.entries.find(({ agent }) => agent.id === secondAgent.id)?.agent.workspaceId, + ).toBe(secondWorkspace.workspaceId); + await testInfo.attach("original-workspace", { + body: await page.screenshot({ path: testInfo.outputPath("original-workspace.png") }), + contentType: "image/png", + }); + } finally { + await secondWorkspace.cleanup(); + await firstWorkspace.cleanup(); + } + }); + test("keeps an offline notification on the agent route until the host connects", async ({ page, }) => { diff --git a/packages/app/e2e/support/helpers/workspace-layout.ts b/packages/app/e2e/support/helpers/workspace-layout.ts index 80c2536fbf..2888fa232a 100644 --- a/packages/app/e2e/support/helpers/workspace-layout.ts +++ b/packages/app/e2e/support/helpers/workspace-layout.ts @@ -1,12 +1,47 @@ import { expect, type Page } from "@playwright/test"; import { z } from "zod"; import { WorkspaceLayoutPersistedStateSchema } from "../../../src/stores/workspace-layout-storage"; +import { openTabInLayoutFocused } from "../../../src/stores/workspace-layout-actions"; import { buildWorkspaceTabPersistenceKey, type WorkspaceTab, } from "../../../src/workspace-tabs/model"; import { getServerId } from "./server-id"; +export async function seedForeignPinnedAgentTab( + page: Page, + input: { serverId: string; workspaceId: string; agentId: string }, +): Promise { + const raw = await page.evaluate(() => localStorage.getItem("workspace-layout-state")); + if (raw === null) throw new Error("Workspace layout was not persisted"); + const stored = z + .object({ state: WorkspaceLayoutPersistedStateSchema, version: z.number().optional() }) + .parse(JSON.parse(raw)); + const key = buildWorkspaceTabPersistenceKey(input); + const layout = key ? stored.state.layoutByWorkspace[key] : null; + if (!key || !layout) throw new Error(`No persisted layout for workspace ${input.workspaceId}`); + const opened = openTabInLayoutFocused({ + layout, + target: { kind: "agent", agentId: input.agentId }, + now: 1, + placement: { mode: "focused" }, + explorerSidebarPaneId: stored.state.explorerSidebarPaneIdByWorkspace?.[key] ?? null, + }); + if (!opened) throw new Error("Failed to seed foreign agent tab"); + stored.state = WorkspaceLayoutPersistedStateSchema.parse({ + ...stored.state, + layoutByWorkspace: { ...stored.state.layoutByWorkspace, [key]: opened.layout }, + pinnedAgentIdsByWorkspace: { + ...stored.state.pinnedAgentIdsByWorkspace, + [key]: [...(stored.state.pinnedAgentIdsByWorkspace?.[key] ?? []), input.agentId], + }, + }); + await page.evaluate( + (value) => localStorage.setItem("workspace-layout-state", value), + JSON.stringify(stored), + ); +} + /** Seed the reported hidden Explorer-only layout with 2,250 saved agent draft tabs. */ export async function seedCorruptedWorkspaceLayout(page: Page, workspaceId: string): Promise { const raw = await page.evaluate(() => localStorage.getItem("workspace-layout-state")); diff --git a/packages/app/src/stores/workspace-layout-actions.ts b/packages/app/src/stores/workspace-layout-actions.ts index 79e0b4fc76..cd727a6915 100644 --- a/packages/app/src/stores/workspace-layout-actions.ts +++ b/packages/app/src/stores/workspace-layout-actions.ts @@ -271,6 +271,7 @@ export interface WorkspaceTabSnapshot { terminalsHydrated: boolean; activeAgentIds: Iterable; autoOpenAgentIds: Iterable; + foreignAgentIds?: Iterable; knownTerminalIds?: Iterable; standaloneTerminalIds: Iterable; hasActivePendingTerminalCreate?: boolean; @@ -2443,13 +2444,16 @@ export function reconcileWorkspaceTabs( const hiddenAgentIds = new Set(state.hiddenAgentIds ?? []); const activeAgentIds = normalizeStringSet(snapshot.activeAgentIds); const autoOpenAgentIds = normalizeStringSet(snapshot.autoOpenAgentIds); - // An explicit open owns the tab until the agent joins the active directory. - // From then on it follows the normal server archive lifecycle. Detail/cache - // hydration never decides whether the user's target is allowed to stay open. + const foreignAgentIds = normalizeStringSet(snapshot.foreignAgentIds ?? []); + // Explicit opens survive absent directory entries, but not known foreign ownership. + // Once an agent joins this workspace's active directory, normal archive rules apply. const pinnedAgentIds = new Set( - [...(state.pinnedAgentIds ?? [])].filter( - (agentId) => !snapshot.agentsHydrated || !activeAgentIds.has(agentId), - ), + [...(state.pinnedAgentIds ?? [])].filter((agentId) => { + if (!snapshot.agentsHydrated) { + return true; + } + return !activeAgentIds.has(agentId) && !foreignAgentIds.has(agentId); + }), ); const standaloneTerminalIds = normalizeStringSet(snapshot.standaloneTerminalIds); const knownTerminalIds = snapshot.knownTerminalIds diff --git a/packages/app/src/workspace-tabs/agent-visibility.test.ts b/packages/app/src/workspace-tabs/agent-visibility.test.ts index 59f96fccbc..cc5b8f6e04 100644 --- a/packages/app/src/workspace-tabs/agent-visibility.test.ts +++ b/packages/app/src/workspace-tabs/agent-visibility.test.ts @@ -1,6 +1,7 @@ import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; import { afterEach, describe, expect, it } from "vitest"; import { useSessionStore, type Agent } from "@/stores/session-store"; +import { createWorkspaceLayoutStore } from "@/stores/workspace-layout-store"; import { buildWorkspaceTabSnapshot, createWorkspaceAgentVisibilitySelector, @@ -63,6 +64,118 @@ function makeAgent(input: { const WORKSPACE_ID = "ws-1"; describe("workspace agent visibility", () => { + it("removes a restored pinned tab from an unrelated workspace once its owner is known", async () => { + const values = new Map(); + const storage = { + getItem: async (key: string) => values.get(key) ?? null, + setItem: async (key: string, value: string) => { + values.set(key, value); + }, + removeItem: async (key: string) => { + values.delete(key); + }, + }; + const original = createWorkspaceLayoutStore(undefined, storage); + await original.persist.rehydrate(); + const agent = makeAgent({ id: "restored-agent", cwd: "/project-a", workspaceId: "ws-a" }); + for (const workspaceId of ["ws-a", "ws-b"]) { + original.getState().openTab({ + workspaceKey: `srv:${workspaceId}`, + target: { kind: "agent", agentId: agent.id }, + intent: "reveal", + pin: true, + }); + } + const restored = createWorkspaceLayoutStore(undefined, storage); + await restored.persist.rehydrate(); + const sessionAgents = new Map([[agent.id, agent]]); + const beforeHydration = buildWorkspaceTabSnapshot({ + agentVisibility: deriveWorkspaceAgentVisibility({ sessionAgents, workspaceId: "ws-b" }), + agentsHydrated: false, + terminalsHydrated: true, + knownTerminalIds: [], + standaloneTerminalIds: [], + hasActivePendingTerminalCreate: false, + hasActivePendingDraftCreate: false, + }); + restored.getState().reconcileTabs("srv:ws-b", beforeHydration); + expect(restored.getState().pinnedAgentIdsByWorkspace["srv:ws-b"]).toEqual(new Set([agent.id])); + for (const workspaceId of ["ws-a", "ws-b"]) { + restored.getState().reconcileTabs( + `srv:${workspaceId}`, + buildWorkspaceTabSnapshot({ + agentVisibility: deriveWorkspaceAgentVisibility({ sessionAgents, workspaceId }), + agentsHydrated: true, + terminalsHydrated: true, + knownTerminalIds: [], + standaloneTerminalIds: [], + hasActivePendingTerminalCreate: false, + hasActivePendingDraftCreate: false, + }), + ); + } + + expect( + restored + .getState() + .getWorkspaceTabs("srv:ws-a") + .filter((tab) => tab.target.kind === "agent") + .map((tab) => tab.target), + ).toEqual([{ kind: "agent", agentId: agent.id }]); + expect( + restored + .getState() + .getWorkspaceTabs("srv:ws-b") + .filter((tab) => tab.target.kind === "agent"), + ).toEqual([]); + expect(restored.getState().pinnedAgentIdsByWorkspace["srv:ws-b"]).toBeUndefined(); + }); + + it("uses directory ownership before historical details when identifying foreign agents", () => { + const own = makeAgent({ id: "own", cwd: "/repo", workspaceId: WORKSPACE_ID }); + const foreign = makeAgent({ id: "foreign", cwd: "/repo", workspaceId: "ws-2" }); + const unknown = makeAgent({ id: "unknown", cwd: "/repo" }); + const result = deriveWorkspaceAgentVisibility({ + workspaceId: WORKSPACE_ID, + sessionAgents: new Map([ + [own.id, own], + [foreign.id, foreign], + [unknown.id, unknown], + ]), + agentDetails: new Map([ + [own.id, { ...own, workspaceId: "ws-2" }], + [foreign.id, { ...foreign, workspaceId: WORKSPACE_ID }], + [unknown.id, { ...unknown, workspaceId: "ws-2" }], + ]), + }); + + expect(result.activeAgentIds).toEqual(new Set([own.id])); + expect(result.foreignAgentIds).toEqual(new Set([foreign.id])); + }); + + it("recognizes foreign historical ownership without making archived or unknown agents foreign", () => { + const archived = makeAgent({ + id: "archived", + cwd: "/repo", + workspaceId: WORKSPACE_ID, + archivedAt: new Date("2026-03-04T00:01:00.000Z"), + }); + const foreign = { ...archived, id: "foreign", workspaceId: "ws-2" }; + const unknown = { ...archived, id: "unknown", workspaceId: undefined }; + const result = deriveWorkspaceAgentVisibility({ + workspaceId: WORKSPACE_ID, + sessionAgents: new Map(), + agentDetails: new Map([ + [archived.id, archived], + [foreign.id, foreign], + [unknown.id, unknown], + ]), + }); + + expect(result.activeAgentIds).toEqual(new Set()); + expect(result.foreignAgentIds).toEqual(new Set([foreign.id])); + }); + it("keeps subagents active while excluding them from auto-open", () => { const parent = makeAgent({ id: "parent-agent", @@ -86,6 +199,7 @@ describe("workspace agent visibility", () => { expect(result.activeAgentIds).toEqual(new Set(["parent-agent", "child-agent"])); expect(result.autoOpenAgentIds).toEqual(new Set(["parent-agent"])); + expect(result.foreignAgentIds).toEqual(new Set()); }); it("excludes archived subagents from active and auto-open", () => { @@ -295,6 +409,7 @@ describe("workspace agent visibility", () => { }); expect(result.activeAgentIds).toEqual(new Set()); + expect(result.foreignAgentIds).toEqual(new Set(["other-ws-agent"])); }); it("excludes agents without a workspaceId", () => { @@ -308,12 +423,14 @@ describe("workspace agent visibility", () => { }); expect(result.activeAgentIds).toEqual(new Set()); + expect(result.foreignAgentIds).toEqual(new Set()); }); it("builds the tab reconciliation snapshot without callers unpacking agent visibility", () => { const agentVisibility = { activeAgentIds: new Set(["active-agent"]), autoOpenAgentIds: new Set(["root-agent"]), + foreignAgentIds: new Set(["foreign-agent"]), }; expect( @@ -331,6 +448,7 @@ describe("workspace agent visibility", () => { terminalsHydrated: true, activeAgentIds: agentVisibility.activeAgentIds, autoOpenAgentIds: agentVisibility.autoOpenAgentIds, + foreignAgentIds: agentVisibility.foreignAgentIds, knownTerminalIds: ["terminal-1", "script-terminal"], standaloneTerminalIds: ["terminal-1"], hasActivePendingTerminalCreate: false, @@ -469,6 +587,24 @@ describe("workspace agent visibility", () => { expect(after.activeAgentIds).toEqual(new Set([child.id])); expect(after.autoOpenAgentIds).toEqual(new Set([child.id])); }); + + it("recomputes when only a previously unknown agent's foreign ownership becomes known", () => { + seedSession(new Map([[parent.id, parent]])); + const select = createWorkspaceAgentVisibilitySelector({ + serverId: SERVER_ID, + workspaceId: WORKSPACE_ID, + }); + const before = select(useSessionStore.getState()); + useSessionStore + .getState() + .setAgentDetails(SERVER_ID, new Map([[otherWorkspace.id, otherWorkspace]])); + const after = select(useSessionStore.getState()); + + expect(after).not.toBe(before); + expect(after.activeAgentIds).toEqual(before.activeAgentIds); + expect(after.autoOpenAgentIds).toEqual(before.autoOpenAgentIds); + expect(after.foreignAgentIds).toEqual(new Set([otherWorkspace.id])); + }); }); describe("workspaceAgentVisibilityEqual", () => { @@ -476,10 +612,12 @@ describe("workspace agent visibility", () => { const a = { activeAgentIds: new Set(["a", "b"]), autoOpenAgentIds: new Set(["a"]), + foreignAgentIds: new Set(["c"]), }; const b = { activeAgentIds: new Set(["a", "b"]), autoOpenAgentIds: new Set(["a"]), + foreignAgentIds: new Set(["c"]), }; expect(workspaceAgentVisibilityEqual(a, b)).toBe(true); }); @@ -488,10 +626,12 @@ describe("workspace agent visibility", () => { const a = { activeAgentIds: new Set(["a"]), autoOpenAgentIds: new Set(["a"]), + foreignAgentIds: new Set(), }; const b = { activeAgentIds: new Set(["b"]), autoOpenAgentIds: new Set(["a"]), + foreignAgentIds: new Set(), }; expect(workspaceAgentVisibilityEqual(a, b)).toBe(false); }); @@ -500,10 +640,12 @@ describe("workspace agent visibility", () => { const a = { activeAgentIds: new Set(["a", "b"]), autoOpenAgentIds: new Set(["a"]), + foreignAgentIds: new Set(), }; const b = { activeAgentIds: new Set(["a", "b"]), autoOpenAgentIds: new Set(["b"]), + foreignAgentIds: new Set(), }; expect(workspaceAgentVisibilityEqual(a, b)).toBe(false); }); @@ -512,10 +654,12 @@ describe("workspace agent visibility", () => { const a = { activeAgentIds: new Set(), autoOpenAgentIds: new Set(), + foreignAgentIds: new Set(), }; const b = { activeAgentIds: new Set(), autoOpenAgentIds: new Set(), + foreignAgentIds: new Set(), }; expect(workspaceAgentVisibilityEqual(a, b)).toBe(true); }); diff --git a/packages/app/src/workspace-tabs/agent-visibility.ts b/packages/app/src/workspace-tabs/agent-visibility.ts index 3dd1881643..99e127c872 100644 --- a/packages/app/src/workspace-tabs/agent-visibility.ts +++ b/packages/app/src/workspace-tabs/agent-visibility.ts @@ -6,10 +6,7 @@ import { normalizeWorkspaceOpaqueId } from "@/utils/workspace-identity"; export interface WorkspaceAgentVisibility { activeAgentIds: Set; autoOpenAgentIds: Set; -} - -function agentBelongsToWorkspace(agent: Agent, workspaceId: string): boolean { - return normalizeWorkspaceOpaqueId(agent.workspaceId) === workspaceId; + foreignAgentIds: Set; } export function deriveWorkspaceAgentVisibility(input: { @@ -19,17 +16,23 @@ export function deriveWorkspaceAgentVisibility(input: { }): WorkspaceAgentVisibility { const { sessionAgents, agentDetails } = input; const workspaceId = normalizeWorkspaceOpaqueId(input.workspaceId); - if ((!sessionAgents && !agentDetails) || !workspaceId) { + if (!workspaceId) { return { activeAgentIds: new Set(), autoOpenAgentIds: new Set(), + foreignAgentIds: new Set(), }; } const activeAgentIds = new Set(); const autoOpenAgentIds = new Set(); + const foreignAgentIds = new Set(); for (const agent of sessionAgents?.values() ?? []) { - if (!agentBelongsToWorkspace(agent, workspaceId)) { + const ownerId = normalizeWorkspaceOpaqueId(agent.workspaceId); + if (ownerId !== workspaceId) { + if (ownerId) { + foreignAgentIds.add(agent.id); + } continue; } if (!agent.archivedAt) { @@ -42,7 +45,16 @@ export function deriveWorkspaceAgentVisibility(input: { } } } - return { activeAgentIds, autoOpenAgentIds }; + for (const agent of agentDetails?.values() ?? []) { + if (sessionAgents?.has(agent.id)) { + continue; + } + const ownerId = normalizeWorkspaceOpaqueId(agent.workspaceId); + if (ownerId && ownerId !== workspaceId) { + foreignAgentIds.add(agent.id); + } + } + return { activeAgentIds, autoOpenAgentIds, foreignAgentIds }; } interface AgentMapsSnapshot { @@ -99,6 +111,7 @@ export function buildWorkspaceTabSnapshot(input: { terminalsHydrated: input.terminalsHydrated, activeAgentIds: input.agentVisibility.activeAgentIds, autoOpenAgentIds: input.agentVisibility.autoOpenAgentIds, + foreignAgentIds: input.agentVisibility.foreignAgentIds, knownTerminalIds: input.knownTerminalIds, standaloneTerminalIds: input.standaloneTerminalIds, hasActivePendingTerminalCreate: input.hasActivePendingTerminalCreate, @@ -113,7 +126,8 @@ export function workspaceAgentVisibilityEqual( return ( a === b || (setsEqual(a.activeAgentIds, b.activeAgentIds) && - setsEqual(a.autoOpenAgentIds, b.autoOpenAgentIds)) + setsEqual(a.autoOpenAgentIds, b.autoOpenAgentIds) && + setsEqual(a.foreignAgentIds, b.foreignAgentIds)) ); } From 10bc10c99f1cccc3027ee2e7c97a23cad48bd300 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Tue, 27 Oct 2026 09:23:50 +0700 Subject: [PATCH 034/173] Let plugins give specific agents tools (#7938) * feat(plugins): attach tools to individual agent sessions * feat(plugins): reopen idle agent sessions after hook changes Defer automatic plugin changes until the next idle prompt so running turns keep steering. Expose session reload separately from snapshot refresh in the SDK. * docs(plugins): show how to attach tools to agents * test(agent): update permission follow-up adapter --- docs/plugins.md | 3 + packages/client/src/index.test.ts | 63 ++ packages/client/src/index.ts | 11 + packages/plugin/src/boundaries.test.ts | 58 +- packages/plugin/src/server/agent-tools.ts | 39 + packages/plugin/src/server/index.ts | 3 + packages/plugin/src/server/lifecycle.ts | 4 + .../server/src/server/agent/agent-manager.ts | 127 ++- .../server/src/server/agent/agent-prompt.ts | 2 + .../server/agent/create-agent/create.test.ts | 1 + .../src/server/agent/mcp-server.test.ts | 6 + .../server/agent/permission-response.test.ts | 2 + .../src/server/agent/tools/paseo-tools.ts | 11 + .../src/server/agent/tools/plugin-tools.ts | 40 + packages/server/src/server/bootstrap.ts | 7 + .../server/plugins/agent-tools.e2e.test.ts | 752 ++++++++++++++++++ .../src/server/plugins/agent-tools.test.ts | 46 ++ .../server/src/server/plugins/agent-tools.ts | 108 +++ packages/server/src/server/plugins/index.ts | 33 + .../server/plugins/lifecycle/handlers.test.ts | 31 + .../src/server/plugins/lifecycle/index.ts | 89 ++- .../server/plugins/plugin-process-protocol.ts | 24 + .../src/server/plugins/plugin-process.ts | 42 +- packages/server/src/server/plugins/runtime.ts | 141 +++- .../server/src/server/schedule/service.ts | 1 + .../server/test-utils/fake-agent-client.ts | 13 + plugin-examples/agent-tools/README.md | 33 + plugin-examples/agent-tools/index.server.ts | 26 + plugin-examples/agent-tools/paseo-plugin.json | 4 + public-docs/plugins/reference.md | 133 +++- public-docs/plugins/reference.zh-CN.md | 142 +++- 31 files changed, 1937 insertions(+), 58 deletions(-) create mode 100644 packages/plugin/src/server/agent-tools.ts create mode 100644 packages/server/src/server/agent/tools/plugin-tools.ts create mode 100644 packages/server/src/server/plugins/agent-tools.e2e.test.ts create mode 100644 packages/server/src/server/plugins/agent-tools.test.ts create mode 100644 packages/server/src/server/plugins/agent-tools.ts create mode 100644 plugin-examples/agent-tools/README.md create mode 100644 plugin-examples/agent-tools/index.server.ts create mode 100644 plugin-examples/agent-tools/paseo-plugin.json diff --git a/docs/plugins.md b/docs/plugins.md index 21a924c4e8..9cab47214e 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -432,6 +432,9 @@ Server entries register lifecycle observers with `server.on()` and request trans `server.before()`. The [public reference](../public-docs/plugins/reference.md#lifecycle-hooks) owns callback shapes, ordering, and failure behavior. `plugin-examples/lifecycle-logger` registers all eleven hooks; `plugin-examples/lifecycle-actions` demonstrates common automation callbacks. +Session-open hooks also [attach tools to individual agents](../public-docs/plugins/reference.md#attach-tools-to-agents), +as shown in `plugin-examples/agent-tools`. The agent manager stamps their metadata per session; +executable definitions stay in the plugin process. Emit from the operation owner, not a client subscription. Provider history replay must not trigger live hooks. Observers must not be awaited inside agent mutations: a callback can send a prompt or diff --git a/packages/client/src/index.test.ts b/packages/client/src/index.test.ts index a7bb17121c..1b11a3032f 100644 --- a/packages/client/src/index.test.ts +++ b/packages/client/src/index.test.ts @@ -1770,3 +1770,66 @@ test("qualified parents preserve foreign identity without resolving an equal loc await client.close(); expect(localParent.address).toEqual({ serverId: "srv_sdk_test", agentId: "same-parent" }); }); + +test("agent reload reopens through the daemon RPC then returns the observed snapshot; refresh remains a read", async () => { + const { client, ws } = await connectClient(); + try { + const agent = client.agents.ref("agent_sdk"); + const snapshot = createAgent(); + const reloaded = agent.reload({ requestId: "reload-sdk" }); + expect(parseSentSessionMessage(ws.sent.at(-1))).toMatchObject({ + type: "refresh_agent_request", + agentId: "agent_sdk", + requestId: "reload-sdk", + }); + ws.message( + sessionMessage({ + type: "status", + payload: { + status: "agent_refreshed", + requestId: "reload-sdk", + agentId: "agent_sdk", + timelineSize: 0, + }, + }), + ); + await expect + .poll(() => parseSentSessionMessage(ws.sent.at(-1)).type) + .toBe("fetch_agent_request"); + const fetched = parseSentSessionMessage(ws.sent.at(-1)); + ws.message( + sessionMessage({ + type: "fetch_agent_response", + payload: { + requestId: fetched.requestId, + agentId: "agent_sdk", + agent: snapshot, + project: null, + error: null, + }, + }), + ); + expect(await reloaded).toEqual({ agent: snapshot, project: null }); + expect(agent.current()).toEqual(snapshot); + const read = agent.refresh("snapshot-read"); + expect(parseSentSessionMessage(ws.sent.at(-1))).toMatchObject({ + type: "fetch_agent_request", + requestId: "snapshot-read", + }); + ws.message( + sessionMessage({ + type: "fetch_agent_response", + payload: { + requestId: "snapshot-read", + agentId: "agent_sdk", + agent: snapshot, + project: null, + error: null, + }, + }), + ); + expect(await read).toEqual({ agent: snapshot, project: null }); + } finally { + await client.close(); + } +}); diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index 455d377634..1437068f95 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -369,6 +369,11 @@ export interface PaseoAgentHandle { readonly timeline: PaseoAgentTimelineHandle; current(): PaseoAgent | null; refresh(requestId?: string): Promise; + /** + * Reopens the provider session with current configuration, rerunning session-open hooks. + * Interrupts a running turn and returns the refreshed snapshot. + */ + reload(options?: { requestId?: string }): Promise; send(text: string, options?: PaseoAgentSendOptions): Promise; respondToPermission(options: PaseoAgentRespondToPermissionOptions): Promise; /** Sends a prompt and resolves when that turn finishes or needs attention. */ @@ -981,6 +986,12 @@ function createAgentHandleFactory( current = result?.agent ?? null; return result; }, + reload: async (options) => { + await daemonClient.refreshAgent(id, options?.requestId); + const result = await daemonClient.fetchAgent({ agentId: id }); + current = result?.agent ?? null; + return result; + }, send: async (text, options) => { await daemonClient.sendAgentMessage(id, text, options); }, diff --git a/packages/plugin/src/boundaries.test.ts b/packages/plugin/src/boundaries.test.ts index c9b54ecdb7..017b69bda5 100644 --- a/packages/plugin/src/boundaries.test.ts +++ b/packages/plugin/src/boundaries.test.ts @@ -92,7 +92,12 @@ function typeErrors(code: string): string[] { } describe("plugin SDK import boundaries", () => { it("publishes process capabilities without their Windows implementation helpers", () => { - expect(Object.keys(server).sort()).toEqual(["execCommand", "spawnProcess", "terminateProcess"]); + expect(Object.keys(server).sort()).toEqual([ + "defineAgentTool", + "execCommand", + "spawnProcess", + "terminateProcess", + ]); }); it("classifies every published entry", () => { @@ -209,3 +214,54 @@ describe("plugin panel SDK boundary", () => { ).toEqual([]); }); }); + +describe("plugin agent tools SDK boundary", () => { + it("lets a session hook attach typed tools without exposing their transport", () => { + expect( + typeErrors(` + import { z } from "zod"; + import { defineAgentTool, type PluginServerContext, type AgentToolResult, type AgentToolContext, type AgentToolDefinition } from "@getpaseo/plugin/server"; + const tool: AgentToolDefinition = defineAgentTool({ + name: "create_issue", + description: "Create an issue", + input: z.object({ title: z.string(), count: z.string().transform(Number) }), + async execute(input, { agent, paseo, signal }) { + const count: number = input.count; + // @ts-expect-error input is inferred from the schema + input.missing; + return { text: agent.id + input.title, structuredContent: { count } }; + }, + }); + export default function contribute(server: PluginServerContext) { + server.before("agent.session_open", ({ request }) => { + const title: string | null = request.title; + // @ts-expect-error labels are read-only + request.labels.x = "changed"; + if (request.labels.x !== "y") return; + return { ...request, tools: [...request.tools, tool] }; + }); + return () => {}; + } + `), + ).toEqual([]); + }); +}); + +describe("agent session reload SDK boundary", () => { + it("exposes reload separately from snapshot refresh", () => { + expect( + typeErrors(` + import { type PluginServerContext } from "@getpaseo/plugin/server"; + import { type PaseoAgentRefetchResult } from "@getpaseo/client"; + async function reload(server: PluginServerContext, paseo: import("@getpaseo/client").PaseoApi) { + const agent = paseo.agents.ref("chosen-agent"); + const read: PaseoAgentRefetchResult | null = await agent.refresh("read-snapshot"); + const reopened: PaseoAgentRefetchResult | null = await agent.reload({ requestId: "reload-session" }); + await agent.reload(); + // @ts-expect-error reload options can grow without a positional signature change + await agent.reload("reload-session"); + } + `), + ).toEqual([]); + }); +}); diff --git a/packages/plugin/src/server/agent-tools.ts b/packages/plugin/src/server/agent-tools.ts new file mode 100644 index 0000000000..202040cefb --- /dev/null +++ b/packages/plugin/src/server/agent-tools.ts @@ -0,0 +1,39 @@ +import type { PaseoApi } from "@getpaseo/client"; +import type { z } from "zod"; +import type { PluginHookAgent } from "./lifecycle.js"; + +export interface AgentToolContext { + agent: PluginHookAgent; + paseo: PaseoApi; + signal: AbortSignal; +} + +export interface AgentToolResult { + text?: string; + structuredContent?: unknown; + isError?: boolean; +} + +export interface AgentToolDefinition { + name: string; + title?: string; + description: string; + input: z.ZodType; + execute(input: unknown, context: AgentToolContext): AgentToolResult | Promise; +} + +export function defineAgentTool(tool: { + name: string; + title?: string; + description: string; + input: Input; + execute( + input: z.output, + context: AgentToolContext, + ): AgentToolResult | Promise; +}): AgentToolDefinition { + if (!/^[a-z][a-z0-9_]*$/.test(tool.name) || tool.name.length > 64) { + throw new Error(`Invalid agent tool name: ${tool.name}`); + } + return tool; +} diff --git a/packages/plugin/src/server/index.ts b/packages/plugin/src/server/index.ts index 9180023d19..264effafdf 100644 --- a/packages/plugin/src/server/index.ts +++ b/packages/plugin/src/server/index.ts @@ -24,3 +24,6 @@ export type { } from "./lifecycle.js"; export { spawnProcess, execCommand, terminateProcess } from "./process.js"; + +export { defineAgentTool } from "./agent-tools.js"; +export type { AgentToolDefinition, AgentToolResult, AgentToolContext } from "./agent-tools.js"; diff --git a/packages/plugin/src/server/lifecycle.ts b/packages/plugin/src/server/lifecycle.ts index 350039face..f3f2643a04 100644 --- a/packages/plugin/src/server/lifecycle.ts +++ b/packages/plugin/src/server/lifecycle.ts @@ -1,3 +1,4 @@ +import type { AgentToolDefinition } from "./agent-tools.js"; import type { AgentPermissionRequest, AgentPermissionResponse, @@ -36,6 +37,9 @@ export interface PluginSessionOpenRequest { cwd: string; reason: "create" | "resume" | "refresh" | "import"; purpose: "interactive" | "history"; + readonly title: string | null; + readonly labels: Readonly>; + tools: AgentToolDefinition[]; env: Record; } diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index de823660da..1342576f7f 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -1,3 +1,5 @@ +import type { AttachedAgentTool, PluginAgentToolsRuntime } from "../plugins/agent-tools.js"; +import type { AgentToolResult } from "@getpaseo/plugin/server"; import type { RuntimeCleanupCandidate } from "./idle-runtime-cleanup/index.js"; import { ensureAgentLoaded } from "./agent-loading.js"; import { projectTimelineRows } from "./timeline-projection.js"; @@ -333,6 +335,7 @@ export interface AgentManagerOptions { terminalManager?: TerminalManager | null; mcpBaseUrl?: string; mcpAuthToken?: string; + pluginAgentTools?: PluginAgentToolsRuntime; paseoToolsEnabled?: boolean; paseoToolCatalogFactory?: PaseoToolCatalogFactory; resolvePaseoToolPolicy?: (provider: AgentProvider) => ProviderPaseoToolsPolicy | undefined; @@ -766,6 +769,10 @@ export class AgentManager { private readonly agentStreamCoalescer: AgentStreamCoalescer; private mcpBaseUrl: string | null; private readonly mcpAuthToken: string | null; + private sessionOpenGeneration = 0; + private readonly sessionOpenGenerations = new Map(); + private readonly attachedPluginTools = new Map(); + private readonly pluginAgentTools: PluginAgentToolsRuntime | undefined; private paseoToolsEnabled = true; private paseoToolCatalogFactory: PaseoToolCatalogFactory | null = null; private readonly paseoToolPolicies = new Map(); @@ -783,6 +790,7 @@ export class AgentManager { constructor(options: AgentManagerOptions) { this.pluginLifecycle = options.pluginLifecycle; + this.pluginAgentTools = options.pluginAgentTools; this.timelineStore = options.timelineStore ?? new InMemoryAgentTimelineStore(); this.idFactory = options.idFactory ?? (() => randomUUID()); this.registry = options?.registry; @@ -887,6 +895,62 @@ export class AgentManager { this.paseoToolCatalogFactory = factory; } + invalidatePluginSessions(): void { + this.sessionOpenGeneration++; + } + + async reloadStalePluginSession(agentId: string): Promise { + if (!this.needsPluginSessionReload(agentId)) return; + await this.trackAgentRegistrationOperation( + this.runLifecycleMutation(agentId, async () => { + if (!this.needsPluginSessionReload(agentId)) return; + await this.reloadAgentSessionInternal(agentId); + }), + ); + } + + private needsPluginSessionReload(agentId: string): boolean { + const agent = this.getAgent(agentId); + return ( + agent !== null && + agent.lifecycle !== "closed" && + this.sessionOpenGenerations.get(agentId) !== this.sessionOpenGeneration && + !this.hasInFlightRun(agentId) + ); + } + + getPluginTools(agentId: string): readonly AttachedAgentTool[] { + return (this.attachedPluginTools.get(agentId) ?? []).filter((tool) => + this.pluginAgentTools?.isToolPluginAvailable(tool.pluginId, tool.pluginInstanceId), + ); + } + + async executePluginTool( + tool: AttachedAgentTool, + agentId: string, + input: unknown, + signal?: AbortSignal, + ): Promise { + const agent = this.getAgent(agentId); + if (!agent || agent.lifecycle === "closed") throw new Error(`Agent is not live: ${agentId}`); + if (!this.pluginAgentTools) throw new Error("Plugin tools are unavailable"); + const record = await this.registry?.get(agentId); + return this.pluginAgentTools.callTool( + tool.pluginId, + tool.pluginInstanceId, + describeHookAgent({ ...agent, title: record?.title ?? agent.config.title }), + tool.name, + input, + signal, + ); + } + + private detachPluginTools(agentId: string): void { + this.attachedPluginTools.delete(agentId); + this.sessionOpenGenerations.delete(agentId); + this.pluginAgentTools?.detachTools(agentId); + } + getPaseoToolPolicy(agentId: string): ProviderPaseoToolsPolicy | undefined { return this.paseoToolPolicies.get(agentId); } @@ -1312,7 +1376,13 @@ export class AgentManager { storedConfig.cwd, paseoToolPolicy, options?.env, - { reason: "create", purpose: "interactive", workspaceId: options.workspaceId ?? null }, + { + reason: "create", + purpose: "interactive", + workspaceId: options.workspaceId ?? null, + title: options.initialTitle ?? storedConfig.title ?? null, + labels: options.labels ?? {}, + }, ); const providerLaunchConfig = this.resolveProviderLaunchConfig(launchConfig, launchContext); const createOptions = this.buildCreateSessionOptions(options); @@ -1434,6 +1504,8 @@ export class AgentManager { reason: "resume", purpose, workspaceId: options?.workspaceId ?? null, + title: record?.title ?? mergedConfig.title ?? null, + labels: record?.labels ?? options?.labels ?? {}, }, ); const providerLaunchConfig = this.resolveProviderLaunchConfig(launchConfig, launchContext); @@ -1491,7 +1563,12 @@ export class AgentManager { storedConfig.cwd, paseoToolPolicy, undefined, - { reason: "import", purpose: "interactive", workspaceId: input.workspaceId }, + { + reason: "import", + purpose: "interactive", + workspaceId: input.workspaceId, + labels: input.labels ?? {}, + }, ); const providerLaunchConfig = this.resolveProviderLaunchConfig(launchConfig, launchContext); const imported = await client.importSession( @@ -1586,7 +1663,13 @@ export class AgentManager { storedConfig.cwd, paseoToolPolicy, undefined, - { reason: "refresh", purpose: "interactive", workspaceId: existing.workspaceId }, + { + reason: "refresh", + purpose: "interactive", + workspaceId: existing.workspaceId, + title: await this.resolveInitialPersistedTitle(agentId, existing.config, null), + labels: existing.labels, + }, ); const providerLaunchConfig = this.resolveProviderLaunchConfig(launchConfig, launchContext); if ( @@ -1650,6 +1733,7 @@ export class AgentManager { throw error; } finally { if (!handedToRegistration) { + this.detachPluginTools(agentId); if (hadPreviousPaseoToolPolicy) { this.paseoToolPolicies.set(agentId, previousPaseoToolPolicy); } else { @@ -1857,6 +1941,7 @@ export class AgentManager { } catch (error) { persistError = error; } + this.detachPluginTools(agentId); this.emitClosedAgent(closedAgent, { persist: false }); this.logger.trace( { @@ -3940,6 +4025,7 @@ export class AgentManager { private discardRetainedAgentState(agentId: string): void { this.timelineStore.delete(agentId); this.paseoToolPolicies.delete(agentId); + this.detachPluginTools(agentId); for (const event of this.providerSubagents.deleteParent(agentId)) { this.dispatch({ type: "provider_subagent", event }); } @@ -5426,10 +5512,15 @@ export class AgentManager { reason: PluginSessionOpenRequest["reason"]; purpose: PluginSessionOpenRequest["purpose"]; workspaceId?: string | null; + title?: string | null; + labels?: Record; }, ): Promise { + // A plugin changing during this open must still make the resulting session stale. + const generation = this.sessionOpenGeneration; + this.detachPluginTools(agentId); if (this.pluginLifecycle) { - const request: PluginSessionOpenRequest = { + const request = { agentId, provider: client.provider, cwd, @@ -5437,9 +5528,14 @@ export class AgentManager { reason: opening?.reason ?? "resume", purpose: opening?.purpose ?? "interactive", env: { ...env }, + title: opening?.title ?? null, + labels: opening?.labels ?? {}, + tools: [], }; const transformed = await this.pluginLifecycle.before("agent.session_open", request); env = transformed.env; + if (request.purpose === "interactive") + this.attachedPluginTools.set(agentId, transformed.tools as AttachedAgentTool[]); } const context: AgentLaunchContext = { agentId, @@ -5449,17 +5545,26 @@ export class AgentManager { PASEO_AGENT_CWD: cwd, }, }; - if ( + const useNativeTools = this.paseoToolsEnabled && isPaseoToolPolicyEnabled(paseoToolPolicy) && - client.capabilities.supportsNativePaseoTools && - this.paseoToolCatalogFactory + client.capabilities.supportsNativePaseoTools; + if ( + this.paseoToolCatalogFactory && + (useNativeTools || this.getPluginTools(agentId).length > 0) ) { - context.paseoTools = await this.paseoToolCatalogFactory({ - callerAgentId: agentId, - paseoToolPolicy, - }); + try { + const catalog = await this.paseoToolCatalogFactory({ + callerAgentId: agentId, + paseoToolPolicy, + }); + if (useNativeTools) context.paseoTools = catalog; + } catch (error) { + this.detachPluginTools(agentId); + throw error; + } } + this.sessionOpenGenerations.set(agentId, generation); return context; } diff --git a/packages/server/src/server/agent/agent-prompt.ts b/packages/server/src/server/agent/agent-prompt.ts index 08aca8e626..dde5c02bbd 100644 --- a/packages/server/src/server/agent/agent-prompt.ts +++ b/packages/server/src/server/agent/agent-prompt.ts @@ -15,6 +15,7 @@ export type AgentRunController = Pick< | "getAgent" | "tryRunOutOfBand" | "hasInFlightRun" + | "reloadStalePluginSession" | "replaceAgentRun" | "steerOrReplaceActiveTurn" | "streamAgent" @@ -115,6 +116,7 @@ export async function startAgentRun( return { disposition: "out_of_band" }; } try { + await agentManager.reloadStalePluginSession(agentId); return await startAgentRunInner(agentManager, agentId, prompt, logger, options); } catch (error) { if (!isStaleProviderSessionError(error)) throw error; diff --git a/packages/server/src/server/agent/create-agent/create.test.ts b/packages/server/src/server/agent/create-agent/create.test.ts index 5d2c9fddc1..daa5ba9ec1 100644 --- a/packages/server/src/server/agent/create-agent/create.test.ts +++ b/packages/server/src/server/agent/create-agent/create.test.ts @@ -69,6 +69,7 @@ test("session create forwards clientMessageId to the initial prompt run options" getAgent: vi.fn(() => snapshot), tryRunOutOfBand: vi.fn(() => false), hasInFlightRun: vi.fn(() => false), + reloadStalePluginSession: async () => {}, streamAgent, waitForAgentRunStart: vi.fn(async () => undefined), } as unknown as Parameters[0]["agentManager"], diff --git a/packages/server/src/server/agent/mcp-server.test.ts b/packages/server/src/server/agent/mcp-server.test.ts index b8a0d820ec..f2c7da8574 100644 --- a/packages/server/src/server/agent/mcp-server.test.ts +++ b/packages/server/src/server/agent/mcp-server.test.ts @@ -270,6 +270,8 @@ function buildAgentManagerSpies() { hydrateTimelineFromProvider: vi.fn().mockResolvedValue(undefined), appendTimelineItem: vi.fn().mockResolvedValue(undefined), emitLiveTimelineItem: vi.fn().mockResolvedValue(undefined), + getPluginTools: () => [], + reloadStalePluginSession: async () => {}, hasInFlightRun: vi.fn().mockReturnValue(false), steerOrReplaceActiveTurn: async () => ({ status: "inactive" as const }), tryRunOutOfBand: vi.fn().mockReturnValue(false), @@ -617,6 +619,10 @@ class FakeBrowserToolsBroker { } class BoundaryAgentManagerFake { + public getPluginTools(): [] { + return []; + } + private readonly agent = createManagedAgent({ id: "agent-1", cwd: REPO_CWD, diff --git a/packages/server/src/server/agent/permission-response.test.ts b/packages/server/src/server/agent/permission-response.test.ts index 5ac7374e88..710599c588 100644 --- a/packages/server/src/server/agent/permission-response.test.ts +++ b/packages/server/src/server/agent/permission-response.test.ts @@ -40,6 +40,8 @@ class FakePermissionAgentManager { return undefined; } + async reloadStalePluginSession(): Promise {} + hasInFlightRun(): boolean { return this.hasRunInFlight; } diff --git a/packages/server/src/server/agent/tools/paseo-tools.ts b/packages/server/src/server/agent/tools/paseo-tools.ts index 6b84f17161..0ca6c5a3e4 100644 --- a/packages/server/src/server/agent/tools/paseo-tools.ts +++ b/packages/server/src/server/agent/tools/paseo-tools.ts @@ -1,3 +1,4 @@ +import { registerPluginTools } from "./plugin-tools.js"; import type { FinishSubscriptions, FinishRegistration } from "../finish-subscriptions/index.js"; import type { AgentMessageDelivery } from "../agent-messages/index.js"; import { @@ -704,6 +705,7 @@ function createToolCatalog( } const localHostOperations = new Map(); const tools = new Map(); + const builtinNames = new Set(); const hostTools = new Map([ ["create_agent", "createAgent"], ["create_workspace", "createWorkspace"], @@ -738,6 +740,7 @@ function createToolCatalog( // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Tool handlers are schema-validated at registration boundaries. handler: (input: any, context: PaseoToolExecutionContext) => Promise, ) => { + builtinNames.add(name); if (!isPaseoToolEnabled(options.paseoToolPolicy, name)) { return; } @@ -3272,6 +3275,14 @@ function createToolCatalog( }, ); + registerPluginTools({ + agentManager, + callerAgentId, + scope, + tools, + builtinNames, + policy: options.paseoToolPolicy, + }); return toCatalog(); } diff --git a/packages/server/src/server/agent/tools/plugin-tools.ts b/packages/server/src/server/agent/tools/plugin-tools.ts new file mode 100644 index 0000000000..c0c94d11ab --- /dev/null +++ b/packages/server/src/server/agent/tools/plugin-tools.ts @@ -0,0 +1,40 @@ +import { z } from "zod"; +import type { ProviderPaseoToolsPolicy } from "@getpaseo/protocol/provider-config"; +import type { AgentManager } from "../agent-manager.js"; +import { isPaseoToolEnabled } from "../paseo-tool-policy.js"; +import type { PaseoToolDefinition } from "./types.js"; +import { addModelVisibleStructuredContent } from "./paseo-tool-serialization.js"; + +export function registerPluginTools(options: { + agentManager: AgentManager; + callerAgentId?: string; + scope: "agent" | "top-level"; + tools: Map; + builtinNames: Set; + policy?: ProviderPaseoToolsPolicy; +}): void { + const { agentManager, callerAgentId, scope, tools, builtinNames, policy } = options; + if (scope !== "agent" || !callerAgentId) return; + for (const tool of agentManager.getPluginTools(callerAgentId)) { + if (builtinNames.has(tool.name)) { + throw new Error( + `Agent tool ${tool.name} from plugin ${tool.pluginId} collides with Paseo tool ${tool.name}`, + ); + } + if (!isPaseoToolEnabled(policy, tool.name)) continue; + tools.set(tool.name, { + name: tool.name, + title: tool.title, + description: tool.description, + inputSchema: z.fromJSONSchema(tool.inputSchema), + async handler(input, { signal }) { + const result = await agentManager.executePluginTool(tool, callerAgentId, input, signal); + return addModelVisibleStructuredContent({ + content: result.text === undefined ? [] : [{ type: "text", text: result.text }], + structuredContent: result.structuredContent, + isError: result.isError, + }); + }, + }); + } +} diff --git a/packages/server/src/server/bootstrap.ts b/packages/server/src/server/bootstrap.ts index 2eeccfb653..2bbde7de34 100644 --- a/packages/server/src/server/bootstrap.ts +++ b/packages/server/src/server/bootstrap.ts @@ -995,6 +995,7 @@ export async function createPaseoDaemon( const initialAgentManagerState = providerSnapshotManager.getAgentManagerProviderState(); const agentManager = new AgentManager({ pluginLifecycle: pluginRuntime, + pluginAgentTools: pluginRuntime, clients: initialAgentManagerState.clients, providerDefinitions: initialAgentManagerState.providerDefinitions, registry: agentStorage, @@ -1015,6 +1016,10 @@ export async function createPaseoDaemon( const unsubscribePluginProviders = pluginRuntime.subscribeProviderRegistrations(syncPluginProviders); + const unsubscribePluginSessionChanges = pluginRuntime.subscribeSessionOpenChanges(() => { + agentManager.invalidatePluginSessions(); + }); + const detachAgentStoragePersistence = attachAgentStoragePersistence( logger, agentManager, @@ -1914,6 +1919,7 @@ export async function createPaseoDaemon( localCredential = null; await deleteLocalCredential(config.paseoHome); unsubscribePluginProviders(); + unsubscribePluginSessionChanges(); await pluginRuntime.stopAllPlugins().catch(() => undefined); await serviceProxy.stopStandalone().catch(() => undefined); await agentProviderRuntime.shutdown().catch(() => undefined); @@ -1933,6 +1939,7 @@ export async function createPaseoDaemon( // that is still open. Plugins themselves are stopped once every session // they serve has been closed, further down. unsubscribePluginProviders(); + unsubscribePluginSessionChanges(); await hubRelationships.stop(); workspaceReconciliation.dispose(); scriptHealthMonitor.stop(); diff --git a/packages/server/src/server/plugins/agent-tools.e2e.test.ts b/packages/server/src/server/plugins/agent-tools.e2e.test.ts new file mode 100644 index 0000000000..14629aa15e --- /dev/null +++ b/packages/server/src/server/plugins/agent-tools.e2e.test.ts @@ -0,0 +1,752 @@ +import { fileURLToPath } from "node:url"; +import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { expect, test } from "vitest"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; +import { DaemonClient } from "../test-utils/daemon-client.js"; +import { + createTestAgentClient, + type TestAgentClientOptions, +} from "../test-utils/fake-agent-client.js"; +import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js"; +import { BuiltinPluginLoader } from "./builtin/index.js"; +import { serializePaseoToolInputParameters } from "../agent/tools/paseo-tool-serialization.js"; +import type { + AgentClient, + AgentLaunchContext, + AgentSessionConfig, + AgentPromptInput, +} from "../agent/agent-sdk-types.js"; + +function recordingProvider(native: boolean, callbacks: TestAgentClientOptions = {}) { + const launches: { config: AgentSessionConfig; context?: AgentLaunchContext }[] = []; + const turns: { prompt: AgentPromptInput; launchCount: number }[] = []; + const steers: AgentPromptInput[] = []; + const events = { interrupts: 0 }; + const inner = createTestAgentClient("codex", { + ...callbacks, + supportsMcpServers: true, + onStartTurn: (prompt, config) => { + turns.push({ prompt, launchCount: launches.length }); + callbacks.onStartTurn?.(prompt, config); + }, + steerActiveTurn: async (prompt) => { + steers.push(prompt); + return { status: "accepted" }; + }, + onInterrupt: () => { + events.interrupts++; + callbacks.onInterrupt?.(); + }, + }); + const provider: AgentClient = { + provider: inner.provider, + capabilities: { ...inner.capabilities, supportsNativePaseoTools: native }, + createSession: async (config, context, options) => { + launches.push({ config, context }); + return inner.createSession(config, context, options); + }, + resumeSession: async (handle, config, context, options) => { + launches.push({ config: config as AgentSessionConfig, context }); + return inner.resumeSession(handle, config, context, options); + }, + isAvailable: () => inner.isAvailable(), + fetchCatalog: (options) => inner.fetchCatalog(options), + }; + return { provider, launches, turns, steers, events }; +} + +const pluginSource = ` +import { z } from "zod"; +import { defineAgentTool } from "@getpaseo/plugin/server"; +let calls = 0; +const tool = defineAgentTool({ + name: "plugin_echo", description: "Echo for the chosen agent", + input: z.object({ text: z.string().min(1).refine(value => value !== "forbidden", "Forbidden by plugin").describe("Message") }), + async execute(input, { agent, paseo, signal }) { + calls++; + if (input.text === "throw") throw new Error("handler failed"); + return { text: JSON.stringify({ agent, input, calls, sdk: typeof paseo.agents.ref, aborted: signal.aborted }) }; + }, +}); +export default function contribute(server) { + server.before("agent.session_open", ({ request }) => { + if (request.labels.x !== "y") return; + return { ...request, env: { ...request.env, OPEN_INFO: JSON.stringify({ title: request.title, labels: request.labels, reason: request.reason }) }, tools: [...request.tools, tool] }; + }); + return () => {}; +} +`; + +async function setup( + native = false, + source = pluginSource, + policy?: { enabled?: boolean; disabledTools?: string[] }, + providerOptions?: TestAgentClientOptions, +) { + const directory = await mkdtemp(path.join(tmpdir(), "paseo-agent-tools-")); + const recorder = recordingProvider(native, providerOptions); + const daemon = await createTestPaseoDaemon({ + daemonVersion: "0.13.2", + agentClients: { codex: recorder.provider }, + mcpEnabled: true, + providerOverrides: { codex: { paseoTools: policy } }, + }); + const client = new DaemonClient({ + url: `ws://127.0.0.1:${daemon.port}/ws`, + appVersion: "0.13.2", + }); + const mcps: Client[] = []; + async function install(id: string, code: string) { + const pluginDirectory = path.join(directory, id); + await mkdir(pluginDirectory); + await writeFile( + path.join(pluginDirectory, "paseo-plugin.json"), + JSON.stringify({ id, requirements: { paseo: ">=0.13.2" } }), + ); + await writeFile(path.join(pluginDirectory, "index.server.ts"), code); + await client.installDirectoryPlugin(pluginDirectory); + } + await client.connect(); + await client.fetchAgents({ subscribe: {} }); + await client.patchDaemonConfig({ pluginsEnabled: true }); + try { + await install("tools-test", source); + } catch (error) { + await client.close(); + await daemon.close(); + await rm(directory, { recursive: true, force: true }); + throw error; + } + return { + ...recorder, + daemon, + client, + directory, + install, + async create(labels: Record = {}) { + return daemon.daemon.agentManager.createAgent( + { provider: "codex", cwd: directory }, + undefined, + { labels, initialTitle: "Chosen title" }, + ); + }, + async mcp(agentId?: string) { + const server = recorder.launches.at(-1)!.config.mcpServers?.paseo; + let url: string; + if (agentId) url = `http://127.0.0.1:${daemon.port}/mcp/agents?callerAgentId=${agentId}`; + else { + if (server?.type !== "http") throw new Error("Expected HTTP server"); + url = server.url; + } + const mcp = new Client({ name: "plugin-tools-test", version: "1" }); + mcps.push(mcp); + await mcp.connect(new StreamableHTTPClientTransport(new URL(url))); + return mcp; + }, + async close() { + await Promise.all(mcps.map((mcp) => mcp.close())); + await client.close(); + await daemon.close(); + await rm(directory, { recursive: true, force: true }); + }, + }; +} + +test("session hooks attach tools only to matching agents over MCP, with validated input and caller context", async () => { + const h = await setup(); + try { + const a = await h.create({ x: "y" }); + expect(JSON.parse(h.launches.at(-1)!.context!.env!.OPEN_INFO)).toEqual({ + title: "Chosen title", + labels: { x: "y" }, + reason: "create", + }); + const mcpA = await h.mcp(); + const listed = (await mcpA.listTools()).tools.find((tool) => tool.name === "plugin_echo"); + expect(listed).toMatchObject({ + name: "plugin_echo", + inputSchema: { + type: "object", + properties: { text: { type: "string", minLength: 1, description: "Message" } }, + required: ["text"], + }, + }); + const b = await h.create(); + const mcpB = await h.mcp(); + expect((await mcpB.listTools()).tools.map((tool) => tool.name)).not.toContain("plugin_echo"); + const invalid = await mcpA.callTool({ name: "plugin_echo", arguments: { text: "" } }); + expect(invalid.isError).toBe(true); + expect(JSON.stringify(invalid)).toContain("text"); + expect( + await mcpA.callTool({ name: "plugin_echo", arguments: { text: "forbidden" } }), + ).toMatchObject({ + isError: true, + content: [{ type: "text", text: expect.stringContaining("Forbidden by plugin") }], + }); + const result = await mcpA.callTool({ name: "plugin_echo", arguments: { text: "hello" } }); + expect(result.isError).not.toBe(true); + expect(JSON.parse((result.content as { text: string }[])[0].text)).toMatchObject({ + agent: { id: a.id, cwd: h.directory, title: "Chosen title" }, + input: { text: "hello" }, + calls: 1, + sdk: "function", + aborted: false, + }); + expect(a.id).not.toBe(b.id); + expect( + await mcpA.callTool({ name: "plugin_echo", arguments: { text: "throw" } }), + ).toMatchObject({ isError: true, content: [{ type: "text", text: "handler failed" }] }); + expect( + (await mcpA.callTool({ name: "plugin_echo", arguments: { text: "still alive" } })).isError, + ).not.toBe(true); + } finally { + await h.close(); + } +}, 60_000); + +test("native providers get the same attached schema and execution", async () => { + const h = await setup(true); + try { + const a = await h.create({ x: "y" }); + const catalog = h.launches.at(-1)!.context!.paseoTools!; + expect(catalog.getTool("plugin_echo")?.description).toBe("Echo for the chosen agent"); + const mcp = await h.mcp(a.id); + const advertised = (await mcp.listTools()).tools.find((tool) => tool.name === "plugin_echo")!; + expect(serializePaseoToolInputParameters(catalog.getTool("plugin_echo")!)).toEqual( + advertised.inputSchema, + ); + const result = await catalog.executeTool("plugin_echo", { text: "native" }); + expect(JSON.parse(result.content[0].text!)).toMatchObject({ + agent: { id: a.id }, + input: { text: "native" }, + }); + } finally { + await h.close(); + } +}, 60_000); + +test("resume uses the stored title and labels, and close removes the attachment", async () => { + const h = await setup(true); + try { + const a = await h.create({ x: "y" }); + const catalog = h.launches.at(-1)!.context!.paseoTools!; + const handle = a.persistence!; + await h.daemon.daemon.agentManager.setTitle(a.id, "Stored title"); + await h.daemon.daemon.agentManager.closeAgent(a.id); + expect(h.daemon.daemon.agentManager.getPluginTools(a.id)).toEqual([]); + await expect(catalog.executeTool("plugin_echo", { text: "closed" })).rejects.toThrow( + "Agent is not live", + ); + await h.daemon.daemon.agentManager.resumeAgentFromPersistence(handle, a.config, a.id); + expect(JSON.parse(h.launches.at(-1)!.context!.env!.OPEN_INFO)).toEqual({ + title: "Stored title", + labels: { x: "y" }, + reason: "resume", + }); + expect(h.launches.at(-1)!.context!.paseoTools!.getTool("plugin_echo")?.name).toBe( + "plugin_echo", + ); + } finally { + await h.close(); + } +}, 60_000); + +test.each([ + { + name: "Paseo", + source: pluginSource.replace('name: "plugin_echo"', 'name: "list_agents"'), + other: false, + message: /plugin tools-test.*Paseo tool list_agents/, + }, + { + name: "another plugin", + source: pluginSource, + other: true, + message: /plugin tools-test.*plugin other-tools/, + }, + { + name: "the same plugin", + source: pluginSource.replace("tools: [...request.tools, tool]", "tools: [tool, tool]"), + other: false, + message: /Duplicate agent tool: plugin_echo/, + }, +])( + "collisions with $name fail only targeted session opens", + async ({ source, other, message }) => { + const h = await setup(false, source); + try { + if (other) await h.install("other-tools", pluginSource); + await expect(h.create({ x: "y" })).rejects.toThrow(message); + expect(h.launches).toHaveLength(0); + await h.create(); + expect(h.launches).toHaveLength(1); + expect((await (await h.mcp()).listTools()).tools.map((tool) => tool.name)).not.toContain( + "plugin_echo", + ); + } finally { + await h.close(); + } + }, + 60_000, +); + +test("each plugin owns its tool array and callbacks can remove earlier attachments", async () => { + const source = pluginSource.replace( + " return () => {};", + ` + server.before("agent.session_open", ({ request }) => { + if (request.labels.x === "y" && request.tools[0]?.name !== "plugin_echo") throw new Error("Lost plugin-local definitions"); + return { ...request, tools: [] }; + }); + return () => {};`, + ); + const h = await setup(false, source); + try { + await h.install( + "other-tools", + pluginSource + .replace('name: "plugin_echo"', 'name: "other_echo"') + .replace( + ' if (request.labels.x !== "y") return;', + ' if (request.tools.length !== 0) throw new Error("Saw another plugin tools");\n if (request.labels.x !== "y") return;', + ), + ); + await h.create({ x: "y" }); + const names = (await (await h.mcp()).listTools()).tools.map((tool) => tool.name); + expect(names).toContain("other_echo"); + expect(names).not.toContain("plugin_echo"); + } finally { + await h.close(); + } +}, 60_000); + +test("disabled plugins remove tools from existing and new MCP catalogs", async () => { + const h = await setup(); + try { + await h.create({ x: "y" }); + const mcp = await h.mcp(); + expect((await mcp.listTools()).tools.map((tool) => tool.name)).toContain("plugin_echo"); + await h.client.patchDaemonConfig({ pluginsEnabled: false }); + expect((await mcp.listTools()).tools.map((tool) => tool.name)).not.toContain("plugin_echo"); + await h.create({ x: "y" }); + expect((await (await h.mcp()).listTools()).tools.map((tool) => tool.name)).not.toContain( + "plugin_echo", + ); + } finally { + await h.close(); + } +}, 60_000); + +test.each([false, true])( + "provider tools disabled gates plugin tools (native=%s)", + async (native) => { + const h = await setup(native, pluginSource, { enabled: false }); + try { + await h.create({ x: "y" }); + expect(h.launches.at(-1)!.context!.paseoTools).toBeUndefined(); + expect(h.launches.at(-1)!.config.mcpServers?.paseo).toBeUndefined(); + } finally { + await h.close(); + } + }, + 60_000, +); + +test("disabledTools filters plugin tool names", async () => { + const h = await setup(true, pluginSource, { disabledTools: ["plugin_echo"] }); + try { + await h.create({ x: "y" }); + expect(h.launches.at(-1)!.context!.paseoTools!.getTool("plugin_echo")).toBeUndefined(); + } finally { + await h.close(); + } +}, 60_000); + +const waitingSource = pluginSource + .replace("import { z }", 'import { writeFile } from "node:fs/promises";\nimport { z }') + .replace( + " calls++;", + ` + calls++; + if (input.text === "wait") { + await writeFile(agent.cwd + "/started", agent.id); + await new Promise(resolve => signal.addEventListener("abort", resolve, { once: true })); + await writeFile(agent.cwd + "/aborted", agent.id); + return { text: "discard this result" }; + } +`, + ); + +test("caller cancellation aborts the plugin handler and discards its result", async () => { + const h = await setup(true, waitingSource); + try { + const a = await h.create({ x: "y" }); + const catalog = h.launches.at(-1)!.context!.paseoTools!; + const controller = new AbortController(); + const call = catalog.executeTool( + "plugin_echo", + { text: "wait" }, + { signal: controller.signal }, + ); + const rejected = expect(call).rejects.toThrow("Canceled by caller"); + await expect.poll(() => readFile(path.join(h.directory, "started"), "utf8")).toBe(a.id); + controller.abort(new Error("Canceled by caller")); + await rejected; + await expect.poll(() => readFile(path.join(h.directory, "aborted"), "utf8")).toBe(a.id); + } finally { + await h.close(); + } +}, 60_000); + +test("a plugin stopping mid-call returns a tool error", async () => { + const h = await setup(true, waitingSource); + try { + const a = await h.create({ x: "y" }); + const call = h.launches + .at(-1)! + .context!.paseoTools!.executeTool("plugin_echo", { text: "wait" }); + await expect.poll(() => readFile(path.join(h.directory, "started"), "utf8")).toBe(a.id); + await h.client.patchDaemonConfig({ pluginsEnabled: false }); + expect(await call).toMatchObject({ + isError: true, + content: [{ type: "text", text: expect.stringContaining("Plugin stopped") }], + }); + } finally { + await h.close(); + } +}, 60_000); + +test("history sessions ignore attached tools", async () => { + const h = await setup(true); + try { + const a = await h.create({ x: "y" }); + const handle = a.persistence!; + await h.client.archiveAgent(a.id); + await h.daemon.daemon.agentManager.resumeAgentFromPersistence(handle, a.config, a.id); + expect(h.daemon.daemon.agentManager.getPluginTools(a.id)).toEqual([]); + expect(h.launches.at(-1)!.context!.paseoTools?.getTool("plugin_echo")).toBeUndefined(); + } finally { + await h.close(); + } +}, 60_000); + +test("disabled plugins attach no tools to a new native session", async () => { + const h = await setup(true); + try { + await h.client.patchDaemonConfig({ pluginsEnabled: false }); + await h.create({ x: "y" }); + expect(h.launches.at(-1)!.context!.paseoTools!.getTool("plugin_echo")).toBeUndefined(); + } finally { + await h.close(); + } +}, 60_000); + +test("structured tool results get model-visible text when text is omitted", async () => { + const h = await setup( + true, + pluginSource.replace( + " calls++;", + ' return { structuredContent: { status: "created" } };', + ), + ); + try { + await h.create({ x: "y" }); + expect( + await h.launches + .at(-1)! + .context!.paseoTools!.executeTool("plugin_echo", { text: "structured" }), + ).toEqual({ + content: [{ type: "text", text: JSON.stringify({ status: "created" }, null, 2) }], + structuredContent: { status: "created" }, + isError: undefined, + }); + } finally { + await h.close(); + } +}, 60_000); + +test("reloading a plugin retires its old attachments before an agent reopens", async () => { + const h = await setup(true); + try { + const a = await h.create({ x: "y" }); + const mcp = await h.mcp(a.id); + const oldCatalog = h.launches.at(-1)!.context!.paseoTools!; + expect((await mcp.listTools()).tools.map((tool) => tool.name)).toContain("plugin_echo"); + await h.client.reloadPlugin("tools-test"); + expect((await mcp.listTools()).tools.map((tool) => tool.name)).not.toContain("plugin_echo"); + expect(h.daemon.daemon.agentManager.getPluginTools(a.id)).toEqual([]); + expect(await oldCatalog.executeTool("plugin_echo", { text: "retired" })).toMatchObject({ + isError: true, + content: [{ type: "text", text: expect.stringContaining("not available") }], + }); + } finally { + await h.close(); + } +}, 60_000); + +test("built-in plugins attach and execute tools while configured plugins are disabled", async () => { + const root = await mkdtemp(path.join(tmpdir(), "paseo-builtin-tools-")); + const directory = path.join(root, "builtin-tools"); + await mkdir(directory); + await writeFile( + path.join(directory, "paseo-plugin.json"), + JSON.stringify({ id: "builtin-tools", requirements: { paseo: ">=0.13.2" } }), + ); + await writeFile(path.join(directory, "index.server.ts"), pluginSource); + const recorder = recordingProvider(true); + const daemon = await createTestPaseoDaemon({ + daemonVersion: "0.13.2", + agentClients: { codex: recorder.provider }, + pluginsEnabled: false, + builtinPlugins: new BuiltinPluginLoader(root, ["builtin-tools"]), + }); + try { + const a = await daemon.daemon.agentManager.createAgent( + { provider: "codex", cwd: root }, + undefined, + { labels: { x: "y" } }, + ); + const catalog = recorder.launches.at(-1)!.context!.paseoTools!; + expect(catalog.getTool("plugin_echo")?.name).toBe("plugin_echo"); + const result = await catalog.executeTool("plugin_echo", { text: "builtin" }); + expect(result.isError).not.toBe(true); + expect(JSON.parse(result.content[0].text!)).toMatchObject({ + agent: { id: a.id }, + input: { text: "builtin" }, + }); + } finally { + await daemon.close(); + await rm(root, { recursive: true, force: true }); + } +}, 60_000); + +test("a session hook missing tools reports a schema issue", async () => { + const h = await setup( + false, + pluginSource.replace("tools: [...request.tools, tool]", "tools: undefined"), + ); + try { + await expect(h.create({ x: "y" })).rejects.toThrow('"tools"'); + } finally { + await h.close(); + } +}, 60_000); + +async function sendAndFinish(h: Awaited>, agentId: string, text: string) { + const previous = h.turns.length; + await h.client.sendMessage(agentId, text, { activeTurnBehavior: "steer" }); + await expect.poll(() => h.turns.length).toBe(previous + 1); + await expect.poll(() => h.daemon.daemon.agentManager.hasInFlightRun(agentId)).toBe(false); +} + +test("an idle agent reopens once before its next prompt after a session-hook plugin reload", async () => { + const h = await setup(); + try { + const b = await h.create(); + const mcp = await h.mcp(); + expect((await mcp.listTools()).tools.map((tool) => tool.name)).not.toContain("plugin_echo"); + await writeFile( + path.join(h.directory, "tools-test", "index.server.ts"), + pluginSource.replace(' if (request.labels.x !== "y") return;', ""), + ); + await h.client.reloadPlugin("tools-test"); + expect(h.launches).toHaveLength(1); + await sendAndFinish(h, b.id, "first prompt"); + expect(h.launches).toHaveLength(2); + expect(h.turns.map((turn) => turn.launchCount)).toEqual([2]); + expect((await mcp.listTools()).tools.map((tool) => tool.name)).toContain("plugin_echo"); + await sendAndFinish(h, b.id, "second prompt"); + expect(h.launches).toHaveLength(2); + expect(h.turns.map((turn) => turn.launchCount)).toEqual([2, 2]); + expect(h.events.interrupts).toBe(0); + } finally { + await h.close(); + } +}, 60_000); + +test("a busy agent is steered after plugin reload and reopens only at its next idle prompt", async () => { + let release!: () => void; + const blocked = new Promise((resolve) => { + release = resolve; + }); + const h = await setup(true, pluginSource, undefined, { beforeTurnComplete: async () => blocked }); + try { + const a = await h.create({ x: "y" }); + await h.client.sendMessage(a.id, "busy prompt", { activeTurnBehavior: "steer" }); + await expect.poll(() => h.daemon.daemon.agentManager.hasInFlightRun(a.id)).toBe(true); + await expect + .poll(() => h.daemon.daemon.agentManager.getAgent(a.id)!.activeTurnId) + .not.toBeNull(); + const turnId = h.daemon.daemon.agentManager.getAgent(a.id)!.activeTurnId; + await h.client.reloadPlugin("tools-test"); + await h.client.sendMessage(a.id, "steering prompt", { activeTurnBehavior: "steer" }); + expect(h.steers).toHaveLength(1); + expect(h.launches).toHaveLength(1); + expect(h.events.interrupts).toBe(0); + expect(h.daemon.daemon.agentManager.getAgent(a.id)!.activeTurnId).toBe(turnId); + release(); + await expect.poll(() => h.daemon.daemon.agentManager.hasInFlightRun(a.id)).toBe(false); + await sendAndFinish(h, a.id, "idle prompt"); + expect(h.launches).toHaveLength(2); + expect(h.events.interrupts).toBe(0); + expect(h.launches.at(-1)!.context!.paseoTools!.getTool("plugin_echo")?.name).toBe( + "plugin_echo", + ); + await sendAndFinish(h, a.id, "stable prompt"); + expect(h.launches).toHaveLength(2); + } finally { + release(); + await h.close(); + } +}, 60_000); + +const reloadRpcSource = pluginSource + .replace("import { z }", 'import { defineRpc } from "@getpaseo/plugin";\nimport { z }') + .replace( + " return () => {};", + ` + server.handle(defineRpc({ name: "reload_agent", input: z.object({ id: z.string() }), output: z.object({ id: z.string() }) }), async ({ id }, { paseo }) => { + const agent = paseo.agents.ref(id); + await agent.refresh(); + await agent.reload(); + return { id: agent.current().id }; + }); + return () => {}; +`, + ); + +test("a plugin can reload an agent through the SDK and rerun session hooks with reason refresh", async () => { + const h = await setup(true, reloadRpcSource); + try { + const a = await h.create({ x: "y" }); + expect(h.launches).toHaveLength(1); + expect(await h.client.invokePluginRpc("tools-test", "reload_agent", { id: a.id })).toEqual({ + id: a.id, + }); + expect(h.launches).toHaveLength(2); + expect(JSON.parse(h.launches.at(-1)!.context!.env!.OPEN_INFO).reason).toBe("refresh"); + expect(h.launches.at(-1)!.context!.paseoTools!.getTool("plugin_echo")?.name).toBe( + "plugin_echo", + ); + } finally { + await h.close(); + } +}, 60_000); + +test("starting and stopping a session-hook plugin each causes one idle reopen", async () => { + const h = await setup(true); + try { + const a = await h.create({ x: "y" }); + await h.install( + "added-tools", + pluginSource.replace('name: "plugin_echo"', 'name: "added_echo"'), + ); + await sendAndFinish(h, a.id, "after start"); + expect(h.launches).toHaveLength(2); + expect(h.launches.at(-1)!.context!.paseoTools!.getTool("added_echo")?.name).toBe("added_echo"); + await h.client.disablePlugin("added-tools"); + await sendAndFinish(h, a.id, "after stop"); + expect(h.launches).toHaveLength(3); + expect(h.launches.at(-1)!.context!.paseoTools!.getTool("added_echo")).toBeUndefined(); + await sendAndFinish(h, a.id, "stable after stop"); + expect(h.launches).toHaveLength(3); + expect(h.events.interrupts).toBe(0); + } finally { + await h.close(); + } +}, 60_000); + +test("plugins without a session-open hook do not make agent sessions stale", async () => { + const h = await setup(true); + try { + const a = await h.create({ x: "y" }); + await h.install( + "no-session-hook", + "export default function contribute(server) { server.on('agent.created', () => {}); return () => {}; }", + ); + await sendAndFinish(h, a.id, "after unrelated start"); + expect(h.launches).toHaveLength(1); + await h.client.reloadPlugin("no-session-hook"); + await sendAndFinish(h, a.id, "after unrelated reload"); + expect(h.launches).toHaveLength(1); + await h.client.disablePlugin("no-session-hook"); + await sendAndFinish(h, a.id, "after unrelated stop"); + expect(h.launches).toHaveLength(1); + } finally { + await h.close(); + } +}, 60_000); + +test("explicit SDK reload interrupts a running turn before reopening its session", async () => { + let release!: () => void; + const blocked = new Promise((resolve) => { + release = resolve; + }); + const h = await setup(true, reloadRpcSource, undefined, { + beforeTurnComplete: async () => blocked, + onInterrupt: () => release(), + }); + try { + const a = await h.create({ x: "y" }); + await h.client.sendMessage(a.id, "running before explicit reload", { + activeTurnBehavior: "steer", + }); + await expect + .poll(() => h.daemon.daemon.agentManager.getAgent(a.id)!.activeTurnId) + .not.toBeNull(); + expect(await h.client.invokePluginRpc("tools-test", "reload_agent", { id: a.id })).toEqual({ + id: a.id, + }); + expect(h.events.interrupts).toBe(1); + expect(h.launches).toHaveLength(2); + expect(JSON.parse(h.launches.at(-1)!.context!.env!.OPEN_INFO).reason).toBe("refresh"); + } finally { + release(); + await h.close(); + } +}, 60_000); + +test("the agent-tools example appends notes only for labeled agents", async () => { + const h = await setup(); + try { + await h.client.installDirectoryPlugin( + fileURLToPath(new URL("../../../../../plugin-examples/agent-tools", import.meta.url)), + ); + const a = await h.create({ "notes/enabled": "true" }); + const mcpA = await h.mcp(a.id); + expect((await mcpA.listTools()).tools.map((tool) => tool.name)).toContain( + "append_workspace_note", + ); + expect( + await mcpA.callTool({ + name: "append_workspace_note", + arguments: { note: "Run the targeted tests before committing." }, + }), + ).toMatchObject({ + content: [ + { type: "text", text: `Saved note to ${path.join(h.directory, "AGENT_NOTES.md")}` }, + ], + structuredContent: { path: path.join(h.directory, "AGENT_NOTES.md") }, + }); + expect(await readFile(path.join(h.directory, "AGENT_NOTES.md"), "utf8")).toBe( + "Run the targeted tests before committing.\n", + ); + await mcpA.callTool({ + name: "append_workspace_note", + arguments: { note: "Keep existing notes." }, + }); + expect(await readFile(path.join(h.directory, "AGENT_NOTES.md"), "utf8")).toBe( + "Run the targeted tests before committing.\nKeep existing notes.\n", + ); + await h.create(); + const mcpB = await h.mcp(); + expect((await mcpB.listTools()).tools.map((tool) => tool.name)).not.toContain( + "append_workspace_note", + ); + } finally { + await h.close(); + } +}, 60_000); diff --git a/packages/server/src/server/plugins/agent-tools.test.ts b/packages/server/src/server/plugins/agent-tools.test.ts new file mode 100644 index 0000000000..f3bf7b886f --- /dev/null +++ b/packages/server/src/server/plugins/agent-tools.test.ts @@ -0,0 +1,46 @@ +import { expect, test } from "vitest"; +import { z } from "zod"; +import { defineAgentTool } from "@getpaseo/plugin/server"; +import { serializeAgentTool } from "./agent-tools.js"; +import { serializePaseoToolInputParameters } from "../agent/tools/paseo-tool-serialization.js"; + +test("agent tool schemas survive the process boundary and catalog round trip", () => { + const input = z + .object({ + title: z.string().min(1).describe("Issue title"), + state: z.enum(["open", "closed"]), + tags: z.array(z.string()).optional(), + nested: z.object({ enabled: z.boolean() }), + }) + .describe("Create an issue"); + const tool = defineAgentTool({ + name: "create_issue", + description: "Create", + input, + execute: () => ({ text: "done" }), + }); + const metadata = JSON.parse(JSON.stringify(serializeAgentTool(tool))); + const restored = z.fromJSONSchema(metadata.inputSchema); + expect( + serializePaseoToolInputParameters({ + ...metadata, + inputSchema: restored, + handler: async () => ({ content: [] }), + }), + ).toEqual({ + ...metadata.inputSchema, + additionalProperties: {}, + properties: { + ...metadata.inputSchema.properties, + nested: { ...metadata.inputSchema.properties.nested, additionalProperties: {} }, + }, + }); + expect(restored.parse({ title: "Bug", state: "open", nested: { enabled: true } })).toEqual({ + title: "Bug", + state: "open", + nested: { enabled: true }, + }); + expect( + restored.safeParse({ title: "", state: "unknown", nested: { enabled: true } }).success, + ).toBe(false); +}); diff --git a/packages/server/src/server/plugins/agent-tools.ts b/packages/server/src/server/plugins/agent-tools.ts new file mode 100644 index 0000000000..266234b446 --- /dev/null +++ b/packages/server/src/server/plugins/agent-tools.ts @@ -0,0 +1,108 @@ +import { z } from "zod"; +import type { + AgentToolDefinition, + AgentToolResult, + PluginHookContext, + PluginSessionOpenRequest, + PluginHookAgent, +} from "@getpaseo/plugin/server"; +import { toJsonSchemaCompat } from "@modelcontextprotocol/sdk/server/zod-json-schema-compat.js"; + +export const agentToolMetadataSchema = z + .object({ + name: z + .string() + .regex(/^[a-z][a-z0-9_]*$/) + .max(64), + title: z.string().optional(), + description: z.string(), + inputSchema: z.record(z.string(), z.unknown()), + pluginId: z.string().optional(), + pluginInstanceId: z.string().optional(), + }) + .strict(); +export type AgentToolMetadata = z.infer; +export type AttachedAgentTool = AgentToolMetadata & { pluginId: string; pluginInstanceId: string }; +export type SessionOpenWireRequest = Omit & { + tools: AgentToolMetadata[]; +}; + +export interface PluginAgentToolsRuntime { + isToolPluginAvailable(pluginId: string, pluginInstanceId: string): boolean; + detachTools(agentId: string): void; + callTool( + pluginId: string, + pluginInstanceId: string, + agent: PluginHookAgent, + name: string, + input: unknown, + signal?: AbortSignal, + ): Promise; +} + +export function serializeAgentTool(tool: AgentToolDefinition): AgentToolMetadata { + return agentToolMetadataSchema.parse({ + name: tool.name, + title: tool.title, + description: tool.description, + inputSchema: toJsonSchemaCompat(tool.input, { strictUnions: true, pipeStrategy: "input" }), + }); +} + +// This store lives only in the plugin process. Definitions and parsed values never cross IPC. +export class PluginAgentTools { + private readonly agents = new Map(); + private readonly calls = new Map(); + + attach(agentId: string, tools: AgentToolDefinition[]): AgentToolMetadata[] { + const names = new Set(); + const metadata = tools.map((tool) => { + const serialized = serializeAgentTool(tool); + if (names.has(tool.name)) throw new Error(`Duplicate agent tool: ${tool.name}`); + names.add(tool.name); + return serialized; + }); + this.agents.set(agentId, tools); + return metadata; + } + + detach(agentId: string): void { + this.agents.delete(agentId); + for (const call of this.calls.values()) { + if (call.agentId === agentId) call.controller.abort(); + } + } + + cancel(requestId: string): void { + this.calls.get(requestId)?.controller.abort(); + } + + close(): void { + for (const call of this.calls.values()) call.controller.abort(); + this.agents.clear(); + } + + async call( + requestId: string, + agent: PluginHookAgent, + name: string, + input: unknown, + paseo: PluginHookContext["paseo"], + ): Promise { + const controller = new AbortController(); + this.calls.set(requestId, { agentId: agent.id, controller }); + try { + const tool = this.agents.get(agent.id)?.find((definition) => definition.name === name); + if (!tool) throw new Error(`Agent tool not attached: ${name}`); + const parsed = await tool.input.parseAsync(input); + controller.signal.throwIfAborted(); + const result = await tool.execute(parsed, { agent, paseo, signal: controller.signal }); + controller.signal.throwIfAborted(); + return result; + } catch (error) { + return { isError: true, text: error instanceof Error ? error.message : String(error) }; + } finally { + this.calls.delete(requestId); + } + } +} diff --git a/packages/server/src/server/plugins/index.ts b/packages/server/src/server/plugins/index.ts index a5ecea8097..8385dc2122 100644 --- a/packages/server/src/server/plugins/index.ts +++ b/packages/server/src/server/plugins/index.ts @@ -1,3 +1,4 @@ +import type { PluginAgentToolsRuntime } from "./agent-tools.js"; import type { PluginLifecycle } from "./lifecycle/index.js"; import path from "node:path"; import { stat, rm } from "node:fs/promises"; @@ -37,6 +38,10 @@ import type { PluginUsageSourceMetadata } from "./plugin-process-protocol.js"; const BUILTIN_PROVIDER_ID_SET: ReadonlySet = new Set(BUILTIN_PROVIDER_IDS); interface PluginRuntimePort { + subscribeSessionOpenChanges?: PluginRuntime["subscribeSessionOpenChanges"]; + isToolPluginAvailable?: PluginRuntime["isToolPluginAvailable"]; + callTool?: PluginRuntime["callTool"]; + detachTools?: PluginRuntime["detachTools"]; emit?: PluginLifecycle["emit"]; drainEvents?: PluginRuntime["drainEvents"]; before?: PluginLifecycle["before"]; @@ -131,6 +136,34 @@ export class PluginService { this.runtime.emit?.(name, event); }; + subscribeSessionOpenChanges(listener: () => void): () => void { + return this.runtime.subscribeSessionOpenChanges?.(listener) ?? (() => {}); + } + + readonly isToolPluginAvailable: PluginAgentToolsRuntime["isToolPluginAvailable"] = ( + pluginId, + pluginInstanceId, + ) => { + return this.runtime.isToolPluginAvailable?.(pluginId, pluginInstanceId) ?? false; + }; + + readonly detachTools: PluginAgentToolsRuntime["detachTools"] = (agentId) => { + this.runtime.detachTools?.(agentId); + }; + + readonly callTool: PluginAgentToolsRuntime["callTool"] = async ( + pluginId, + pluginInstanceId, + agent, + name, + input, + signal, + ) => { + if (!this.isToolPluginAvailable(pluginId, pluginInstanceId) || !this.runtime.callTool) + return { isError: true, text: `Plugin is not available: ${pluginId}` }; + return this.runtime.callTool(pluginId, pluginInstanceId, agent, name, input, signal); + }; + async drainEvents(): Promise { await this.runtime.drainEvents?.(); } diff --git a/packages/server/src/server/plugins/lifecycle/handlers.test.ts b/packages/server/src/server/plugins/lifecycle/handlers.test.ts index 5e30535953..bafd1f9b94 100644 --- a/packages/server/src/server/plugins/lifecycle/handlers.test.ts +++ b/packages/server/src/server/plugins/lifecycle/handlers.test.ts @@ -93,8 +93,39 @@ test("session-open hooks reject changes to session identity instead of silently reason: "resume", purpose: "interactive", env: {}, + title: null, + labels: {}, + tools: [], }, paseo, ), ).rejects.toThrow("agent.session_open hooks can only change env"); }); + +test.each([{ title: "Changed" }, { labels: { changed: "true" } }])( + "session-open targeting metadata is read-only: %j", + async (patch) => { + const hooks = new PluginHookHandlers(() => {}); + hooks.before("agent.session_open", ({ request }) => ({ ...request, ...patch })); + await expect( + hooks.invoke( + "operation", + "before", + "agent.session_open", + { + agentId: "agent", + workspaceId: null, + provider: "codex", + cwd: "/project", + title: "Original", + labels: {}, + tools: [], + env: {}, + reason: "create", + purpose: "interactive", + }, + paseo, + ), + ).rejects.toThrow("agent.session_open hooks can only change env and tools"); + }, +); diff --git a/packages/server/src/server/plugins/lifecycle/index.ts b/packages/server/src/server/plugins/lifecycle/index.ts index 29d5fda145..2b379eb7f8 100644 --- a/packages/server/src/server/plugins/lifecycle/index.ts +++ b/packages/server/src/server/plugins/lifecycle/index.ts @@ -1,3 +1,11 @@ +import { isDeepStrictEqual } from "node:util"; +import { + serializeAgentTool, + agentToolMetadataSchema, + type SessionOpenWireRequest, + type PluginAgentTools, +} from "../agent-tools.js"; +import type { AgentToolDefinition } from "@getpaseo/plugin/server"; import type { AgentStreamEvent } from "../../agent/agent-sdk-types.js"; import { z } from "zod"; import { CreateAgentRequestMessageSchema } from "@getpaseo/protocol/messages"; @@ -15,6 +23,10 @@ import type { import { WorkspaceCreateRequestSchema } from "@getpaseo/protocol/messages"; import type { PersistedWorkspaceRecord } from "../../workspace-registry.js"; +export type PluginWireBeforeRequests = Omit & { + "agent.session_open": SessionOpenWireRequest; +}; + export const lifecycleEventNames = [ "agent.created", "agent.closed", @@ -38,28 +50,44 @@ const beforeSchemas = { cwd: z.string(), reason: z.enum(["create", "resume", "refresh", "import"]), purpose: z.enum(["interactive", "history"]), + title: z.string().nullable(), + labels: z.record(z.string(), z.string()), + tools: z.array(agentToolMetadataSchema), env: z.record(z.string(), z.string()), }) .strict(), "workspace.create": WorkspaceCreateRequestSchema.omit({ type: true, requestId: true }).strict(), }; +const sessionOpenLocalResultSchema = beforeSchemas["agent.session_open"].extend({ + tools: z.array( + z.custom( + (tool) => + typeof tool === "object" && + tool !== null && + "input" in tool && + "execute" in tool && + typeof tool.execute === "function", + ), + ), +}); + export interface PluginLifecycle { emit( name: Name, event: PluginLifecycleEvents[Name], ): void; - before( + before( name: Name, - request: PluginBeforeRequests[Name], - ): Promise; + request: PluginWireBeforeRequests[Name], + ): Promise; } -export function validateBeforeRequest( +export function validateBeforeRequest( name: Name, value: unknown, -): PluginBeforeRequests[Name] { - return beforeSchemas[name].parse(value) as PluginBeforeRequests[Name]; +): PluginWireBeforeRequests[Name] { + return beforeSchemas[name].parse(value) as PluginWireBeforeRequests[Name]; } export function describeHookWorkspace(workspace: PersistedWorkspaceRecord): PluginHookWorkspace { @@ -129,11 +157,11 @@ export function publishAgentStream( } } -export function validateBeforeResult( +export function validateBeforeResult( name: Name, - input: PluginBeforeRequests[Name], + input: PluginWireBeforeRequests[Name], output: unknown, -): PluginBeforeRequests[Name] { +): PluginWireBeforeRequests[Name] { const result = validateBeforeRequest(name, output); if (name === "agent.session_open") { const previous = beforeSchemas["agent.session_open"].parse(input); @@ -144,9 +172,11 @@ export function validateBeforeResult( previous.provider !== next.provider || previous.cwd !== next.cwd || previous.reason !== next.reason || - previous.purpose !== next.purpose + previous.purpose !== next.purpose || + previous.title !== next.title || + !isDeepStrictEqual(previous.labels, next.labels) ) { - throw new Error("agent.session_open hooks can only change env"); + throw new Error("agent.session_open hooks can only change env and tools"); } } if (name === "agent.create") { @@ -168,7 +198,10 @@ export class PluginHookHandlers implements PluginLifecycleRegistration { private readonly changed: () => void; - constructor(changed: () => void) { + private readonly agentTools: PluginAgentTools | undefined; + + constructor(changed: () => void, agentTools?: PluginAgentTools) { + this.agentTools = agentTools; this.changed = changed; } @@ -209,6 +242,9 @@ export class PluginHookHandlers implements PluginLifecycleRegistration { throw new Error(`Unknown before hook: ${name}`); } const hookName = name as keyof import("@getpaseo/plugin/server").PluginBeforeRequests; + if (hookName === "agent.session_open") { + return await this.openSession(input, { paseo, signal: controller.signal }); + } let request = validateBeforeRequest(hookName, input); for (const handler of this.transforms.get(name) ?? []) { controller.signal.throwIfAborted(); @@ -216,9 +252,7 @@ export class PluginHookHandlers implements PluginLifecycleRegistration { { request: structuredClone(request) }, { paseo, signal: controller.signal }, ); - if (result !== undefined) { - request = validateBeforeResult(hookName, request, result); - } + if (result !== undefined) request = validateBeforeResult(hookName, request, result); } return request; } @@ -236,6 +270,31 @@ export class PluginHookHandlers implements PluginLifecycleRegistration { } } + private async openSession( + input: unknown, + context: PluginHookContext, + ): Promise { + let request = validateBeforeRequest("agent.session_open", input); + this.agentTools?.detach(request.agentId); + let tools: AgentToolDefinition[] = []; + for (const handler of this.transforms.get("agent.session_open") ?? []) { + context.signal.throwIfAborted(); + const result = await handler( + { request: { ...structuredClone(request), tools: [...tools] } }, + context, + ); + if (result === undefined) continue; + const local = sessionOpenLocalResultSchema.parse(result); + const metadata = local.tools.map(serializeAgentTool); + request = validateBeforeResult("agent.session_open", request, { ...local, tools: metadata }); + tools = local.tools; + } + context.signal.throwIfAborted(); + if (request.purpose === "history") request.tools = []; + else this.agentTools?.attach(request.agentId, tools); + return request; + } + cancel(id: string): void { this.active.get(id)?.abort(); } diff --git a/packages/server/src/server/plugins/plugin-process-protocol.ts b/packages/server/src/server/plugins/plugin-process-protocol.ts index b3f363cb29..c3fa5dda26 100644 --- a/packages/server/src/server/plugins/plugin-process-protocol.ts +++ b/packages/server/src/server/plugins/plugin-process-protocol.ts @@ -1,3 +1,4 @@ +import type { PluginHookAgent } from "@getpaseo/plugin/server"; import { UsageScopeSchema, type UsageScope } from "@getpaseo/plugin/server/usage"; import type { ProviderConnectRequest, @@ -31,6 +32,9 @@ export interface PluginUsageSourceMetadata { } export type PluginProcessRequest = + | { type: "tool.call"; requestId: string; agent: PluginHookAgent; name: string; input: unknown } + | { type: "tool.cancel"; requestId: string } + | { type: "tools.detach"; agentId: string } | { type: "provider.status"; requestId: string; @@ -141,6 +145,26 @@ const frameFields = { export const PluginProcessRequestSchema: z.ZodType = z.discriminatedUnion( "type", [ + z + .object({ + type: z.literal("tool.call"), + requestId: z.string(), + agent: z + .object({ + id: z.string(), + workspaceId: z.string().nullable(), + parentAgentId: z.string().nullable(), + provider: z.string(), + cwd: z.string(), + title: z.string().nullable(), + }) + .strict(), + name: z.string(), + input: z.unknown(), + }) + .strict(), + z.object({ type: z.literal("tool.cancel"), requestId: z.string() }).strict(), + z.object({ type: z.literal("tools.detach"), agentId: z.string() }).strict(), z .object({ type: z.literal("provider.status"), diff --git a/packages/server/src/server/plugins/plugin-process.ts b/packages/server/src/server/plugins/plugin-process.ts index 5e6efa1925..e93ded990e 100644 --- a/packages/server/src/server/plugins/plugin-process.ts +++ b/packages/server/src/server/plugins/plugin-process.ts @@ -1,3 +1,4 @@ +import { PluginAgentTools } from "./agent-tools.js"; import { PluginHookHandlers } from "./lifecycle/index.js"; import { evaluateBundle } from "./bundle-evaluator.js"; import { @@ -59,9 +60,10 @@ export function createPluginWorker(options: { handler: RpcHandler; } + const agentTools = new PluginAgentTools(); const hooks = new PluginHookHandlers(() => { send({ type: "hooks.changed", hooks: hooks.catalog() }); - }); + }, agentTools); const handlers = new Map(); const providers = new Map(); const usageSources = new Map(); @@ -322,6 +324,7 @@ export function createPluginWorker(options: { ?.dispose() .catch((error) => console.error("Plugin API cleanup failed", error)); hooks.close(); + agentTools.close(); for (const pending of pendingProviderConnections.values()) pending.tombstoned = true; const currentCleanup = cleanup; cleanup = null; @@ -381,6 +384,42 @@ export function createPluginWorker(options: { } } + function handleToolMessage( + message: PluginProcessRequest, + ): message is Extract< + PluginProcessRequest, + { type: "tool.call" | "tool.cancel" | "tools.detach" } + > { + if (message.type === "tools.detach") { + agentTools.detach(message.agentId); + return true; + } + if (message.type === "tool.cancel") { + agentTools.cancel(message.requestId); + return true; + } + if (message.type === "tool.call") { + if (!paseo) { + send({ type: "error", requestId: message.requestId, error: "Plugin API unavailable" }); + return true; + } + void agentTools + .call(message.requestId, message.agent, message.name, message.input, paseo) + .then((output) => + send({ + type: "result", + requestId: message.requestId, + output: jsonTransportValue(output), + }), + ) + .catch((error) => + send({ type: "error", requestId: message.requestId, error: describeError(error) }), + ); + return true; + } + return false; + } + function handleMessage(rawMessage: unknown): void { const parsed = PluginProcessRequestSchema.safeParse(rawMessage); if (!parsed.success) { @@ -422,6 +461,7 @@ export function createPluginWorker(options: { rejectWhileStopping(message); return; } + if (handleToolMessage(message)) return; if (message.type === "provider.status") { void (async () => { const provider = providers.get(message.providerId); diff --git a/packages/server/src/server/plugins/runtime.ts b/packages/server/src/server/plugins/runtime.ts index 9886a368e7..f5a644ef9d 100644 --- a/packages/server/src/server/plugins/runtime.ts +++ b/packages/server/src/server/plugins/runtime.ts @@ -1,10 +1,16 @@ +import type { PluginWireBeforeRequests } from "./lifecycle/index.js"; +import type { SessionOpenWireRequest, AttachedAgentTool } from "./agent-tools.js"; import type { UsageScope } from "@getpaseo/plugin/server/usage"; import { ProviderStatusSchema, type ProviderStatus, type ProviderStatusRequest, } from "@getpaseo/plugin/server/provider"; -import type { PluginBeforeRequests, PluginLifecycleEvents } from "@getpaseo/plugin/server"; +import type { + PluginLifecycleEvents, + PluginHookAgent, + AgentToolResult, +} from "@getpaseo/plugin/server"; import { validateBeforeRequest, validateBeforeResult } from "./lifecycle/index.js"; import { fork } from "node:child_process"; import { stat } from "node:fs/promises"; @@ -40,6 +46,7 @@ import { evaluateBundle } from "./bundle-evaluator.js"; const CLIENT_ENTRY_FILENAMES = ["index.client.ts", "index.client.tsx"] as const; const SERVER_ENTRY_FILENAMES = ["index.server.ts", "index.server.tsx"] as const; const REQUEST_TIMEOUT_MS = 30_000; +const TOOL_CALL_TIMEOUT_MS = 10 * 60_000; const MAX_LOG_ENTRIES = 500; const MAX_LOG_BYTES = 256 * 1024; const MAX_LOG_LINE_BYTES = 16 * 1024; @@ -69,6 +76,7 @@ interface PendingInvocation { interface LoadedPlugin { id: string; + instanceId: string; requirements: PluginRequirements | undefined; clientBundle: string; methods: ReadonlySet; @@ -302,6 +310,7 @@ export class PluginRuntime { private readonly spawnChild: () => PluginChild; private sessionHost: PluginPaseoSessionHost | null; private readonly listeners = new Set<(pluginId: string, error?: string) => void>(); + private readonly sessionOpenListeners = new Set<() => void>(); constructor( logger: pino.Logger, @@ -324,6 +333,16 @@ export class PluginRuntime { return () => this.listeners.delete(listener); } + subscribeSessionOpenChanges(listener: () => void): () => void { + this.sessionOpenListeners.add(listener); + return () => this.sessionOpenListeners.delete(listener); + } + + private notifySessionOpenChange(loaded: LoadedPlugin): void { + if (!loaded.hooks.before.includes("agent.session_open")) return; + for (const listener of this.sessionOpenListeners) listener(); + } + async startPlugin( pluginId: string, configuredPath: string, @@ -340,6 +359,7 @@ export class PluginRuntime { throw new Error(`Plugin start cancelled: ${pluginId}`); } this.plugins.set(pluginId, loaded); + this.notifySessionOpenChange(loaded); this.appendLog(pluginId, "stdout", "[paseo] Plugin ready"); } @@ -363,6 +383,7 @@ export class PluginRuntime { clientBundle: bundles.clientBundle ?? "", }); this.plugins.set(input.id, loaded); + this.notifySessionOpenChange(loaded); this.appendLog(input.id, "stdout", "[paseo] Plugin ready"); } @@ -378,6 +399,7 @@ export class PluginRuntime { const loaded = this.plugins.get(pluginId); if (!loaded) return false; this.plugins.delete(pluginId); + this.notifySessionOpenChange(loaded); this.rejectPending(loaded, `Plugin stopped: ${pluginId}`); await this.stopPlugin(loaded); return true; @@ -546,14 +568,15 @@ export class PluginRuntime { await Promise.all(this.pendingEvents); } - async before( + async before( name: Name, - input: PluginBeforeRequests[Name], - ): Promise { + input: PluginWireBeforeRequests[Name], + ): Promise { let request = validateBeforeRequest(name, input); const plugins = [...this.plugins.values()].sort((left, right) => { return left.id.localeCompare(right.id); }); + const attached: AttachedAgentTool[] = []; for (const loaded of plugins) { if (!loaded.hooks.before.includes(name)) { continue; @@ -564,15 +587,21 @@ export class PluginRuntime { requestId: randomUUID(), kind: "before", name, - input: request, + input: name === "agent.session_open" ? { ...request, tools: [] } : request, }); request = validateBeforeResult(name, request, output); + if (name === "agent.session_open") { + this.collectAgentTools(attached, loaded, (request as SessionOpenWireRequest).tools); + } } catch (error) { + if (name === "agent.session_open") + this.detachTools((request as SessionOpenWireRequest).agentId); throw new Error(`Plugin ${loaded.id} before ${name} failed: ${describeError(error)}`, { cause: error, }); } } + if (name === "agent.session_open") (request as SessionOpenWireRequest).tools = attached; return request; } @@ -594,25 +623,102 @@ export class PluginRuntime { return output; } + private collectAgentTools( + attached: AttachedAgentTool[], + loaded: LoadedPlugin, + tools: SessionOpenWireRequest["tools"], + ): void { + for (const tool of tools) { + const collision = attached.find((entry) => entry.name === tool.name); + if (collision) + throw new Error( + `Agent tool ${tool.name} from plugin ${loaded.id} collides with plugin ${collision.pluginId}`, + ); + attached.push({ ...tool, pluginId: loaded.id, pluginInstanceId: loaded.instanceId }); + } + } + + isToolPluginAvailable(pluginId: string, pluginInstanceId: string): boolean { + return this.plugins.get(pluginId)?.instanceId === pluginInstanceId; + } + + detachTools(agentId: string): void { + for (const loaded of this.plugins.values()) { + if (loaded.child) void send(loaded.child, { type: "tools.detach", agentId }).catch(() => {}); + } + } + + async callTool( + pluginId: string, + pluginInstanceId: string, + agent: PluginHookAgent, + name: string, + input: unknown, + signal?: AbortSignal, + ): Promise { + const loaded = this.plugins.get(pluginId); + if (!loaded || loaded.instanceId !== pluginInstanceId) + return { isError: true, text: `Plugin is not available: ${pluginId}` }; + const requestId = randomUUID(); + try { + return (await this.request( + loaded, + { type: "tool.call", requestId, agent, name, input }, + signal, + )) as AgentToolResult; + } catch (error) { + if (signal?.aborted) throw error; + return { isError: true, text: describeError(error) }; + } + } + private request( loaded: LoadedPlugin, message: Extract, + signal?: AbortSignal, ): Promise { const child = loaded.child; const pluginId = loaded.id; if (!child) throw new Error(`Plugin ${pluginId} has no server entry`); const requestId = message.requestId; + signal?.throwIfAborted(); return new Promise((resolve, reject) => { - const timeout = setTimeout(() => { + const cancel = () => { + clearTimeout(timeout); loaded.pending.delete(requestId); - if (message.type === "hook") { - void send(child, { type: "hook.cancel", requestId }).catch(() => {}); - } - reject(new Error(`Plugin RPC timed out: ${pluginId}.${message.type}`)); - }, REQUEST_TIMEOUT_MS); - loaded.pending.set(requestId, { resolve, reject, timeout }); + if (message.type === "tool.call") + void send(child, { type: "tool.cancel", requestId }).catch(() => {}); + signal?.removeEventListener("abort", cancel); + reject(signal?.reason ?? new Error("Tool call canceled")); + }; + const timeout = setTimeout( + () => { + loaded.pending.delete(requestId); + signal?.removeEventListener("abort", cancel); + if (message.type === "tool.call") + void send(child, { type: "tool.cancel", requestId }).catch(() => {}); + if (message.type === "hook") { + void send(child, { type: "hook.cancel", requestId }).catch(() => {}); + } + reject(new Error(`Plugin RPC timed out: ${pluginId}.${message.type}`)); + }, + message.type === "tool.call" ? TOOL_CALL_TIMEOUT_MS : REQUEST_TIMEOUT_MS, + ); + signal?.addEventListener("abort", cancel, { once: true }); + loaded.pending.set(requestId, { + resolve: (value) => { + signal?.removeEventListener("abort", cancel); + resolve(value); + }, + reject: (error) => { + signal?.removeEventListener("abort", cancel); + reject(error); + }, + timeout, + }); void send(child, message).catch((error) => { clearTimeout(timeout); + signal?.removeEventListener("abort", cancel); loaded.pending.delete(requestId); reject(error); }); @@ -623,6 +729,7 @@ export class PluginRuntime { const loaded = [...this.plugins.values()]; this.plugins.clear(); for (const plugin of loaded) { + this.notifySessionOpenChange(plugin); this.rejectPending(plugin, `Plugin stopped: ${plugin.id}`); } await Promise.all(loaded.map((plugin) => this.stopPlugin(plugin))); @@ -641,6 +748,7 @@ export class PluginRuntime { if (!serverBundle) { return { id: pluginId, + instanceId: randomUUID(), clientBundle: bundles.clientBundle ?? "", requirements: manifest.requirements, methods: new Set(), @@ -769,6 +877,7 @@ export class PluginRuntime { } loaded = { id: pluginId, + instanceId: randomUUID(), clientBundle, requirements, methods: new Set(ready.methods), @@ -852,7 +961,14 @@ export class PluginRuntime { private handleChildMessage(loaded: LoadedPlugin, message: PluginProcessMessage): void { if (message.type === "hooks.changed") { + const hadSessionOpen = loaded.hooks.before.includes("agent.session_open"); loaded.hooks = message.hooks; + if ( + this.plugins.get(loaded.id) === loaded && + hadSessionOpen !== loaded.hooks.before.includes("agent.session_open") + ) { + for (const listener of this.sessionOpenListeners) listener(); + } return; } if (message.type === "settings.changed") { @@ -1166,6 +1282,7 @@ export class PluginRuntime { const wasPublished = this.plugins.get(loaded.id) === loaded; if (wasPublished) { this.plugins.delete(loaded.id); + this.notifySessionOpenChange(loaded); } this.rejectPending(loaded, `Plugin process exited: ${loaded.id}`); for (const state of loaded.providerConnections.values()) { diff --git a/packages/server/src/server/schedule/service.ts b/packages/server/src/server/schedule/service.ts index 3b462cc5b1..6121b7e6bd 100644 --- a/packages/server/src/server/schedule/service.ts +++ b/packages/server/src/server/schedule/service.ts @@ -226,6 +226,7 @@ type ScheduleAgentManager = Pick< AgentRunController, | "getAgent" | "reloadAgentSession" + | "reloadStalePluginSession" | "tryRunOutOfBand" | "hasInFlightRun" | "replaceAgentRun" diff --git a/packages/server/src/server/test-utils/fake-agent-client.ts b/packages/server/src/server/test-utils/fake-agent-client.ts index 1c7127d144..42ac0c7c79 100644 --- a/packages/server/src/server/test-utils/fake-agent-client.ts +++ b/packages/server/src/server/test-utils/fake-agent-client.ts @@ -60,6 +60,8 @@ interface FakeAgentSessionOptions { closeSession?: () => Promise; onStartTurn?: (prompt: AgentPromptInput, config: AgentSessionConfig) => void; beforeTurnComplete?: (prompt: AgentPromptInput) => Promise; + steerActiveTurn?: AgentSession["steerActiveTurn"]; + onInterrupt?: () => void; historyEvents?: readonly AgentStreamEvent[]; } @@ -68,6 +70,8 @@ export interface TestAgentClientOptions { closeSession?: () => Promise; onStartTurn?: (prompt: AgentPromptInput, config: AgentSessionConfig) => void; beforeTurnComplete?: (prompt: AgentPromptInput) => Promise; + steerActiveTurn?: AgentSession["steerActiveTurn"]; + onInterrupt?: () => void; supportsMcpServers?: boolean; historyEvents?: readonly AgentStreamEvent[]; } @@ -340,6 +344,8 @@ class FakeAgentSession implements AgentSession { private nextTurnOrdinal = 0; private activeForegroundTurnId: string | null = null; + readonly steerActiveTurn: AgentSession["steerActiveTurn"]; + private readonly onInterrupt: (() => void) | undefined; private readonly closeSession: (() => Promise) | undefined; private readonly onStartTurn: TestAgentClientOptions["onStartTurn"]; private readonly beforeTurnComplete: ((prompt: AgentPromptInput) => Promise) | undefined; @@ -354,6 +360,8 @@ class FakeAgentSession implements AgentSession { this.config = options.config; this.id = options.sessionId ?? randomUUID(); this.memoryMarker = options.memoryMarker ?? null; + this.steerActiveTurn = options.steerActiveTurn; + this.onInterrupt = options.onInterrupt; this.closeSession = options.closeSession; this.onStartTurn = options.onStartTurn; this.beforeTurnComplete = options.beforeTurnComplete; @@ -896,6 +904,7 @@ class FakeAgentSession implements AgentSession { } async interrupt(): Promise { + this.onInterrupt?.(); this.interruptSignal.resolve(); } @@ -1234,6 +1243,8 @@ class FakeAgentClient implements AgentClient { closeSession: this.options.closeSession, onStartTurn: this.options.onStartTurn, beforeTurnComplete: this.options.beforeTurnComplete, + steerActiveTurn: this.options.steerActiveTurn, + onInterrupt: this.options.onInterrupt, historyEvents: this.options.historyEvents, }); } @@ -1261,6 +1272,8 @@ class FakeAgentClient implements AgentClient { closeSession: this.options.closeSession, onStartTurn: this.options.onStartTurn, beforeTurnComplete: this.options.beforeTurnComplete, + steerActiveTurn: this.options.steerActiveTurn, + onInterrupt: this.options.onInterrupt, historyEvents: this.options.historyEvents, }); } diff --git a/plugin-examples/agent-tools/README.md b/plugin-examples/agent-tools/README.md new file mode 100644 index 0000000000..e6ece3978e --- /dev/null +++ b/plugin-examples/agent-tools/README.md @@ -0,0 +1,33 @@ +# Agent tools + +Attaches `append_workspace_note` to agents whose `notes/enabled` label is `"true"`. +Calling the tool with `{ "note": "Run the targeted tests before committing." }` appends that +line to `AGENT_NOTES.md` in the calling agent's working directory and returns the file path. +It creates the file if it does not exist. + +Install on a daemon with plugins enabled: + +```bash +paseo plugin install /absolute/path/to/plugin-examples/agent-tools +``` + +Create a labeled agent through the SDK: + +```ts +const agent = await paseo.agents.create({ + config: { provider: "codex/gpt-5.4" }, + cwd: "/projects/shop", + labels: { "notes/enabled": "true" }, +}); +``` + +The session-open callback also runs when an agent resumes or reloads. After changing an existing +agent's labels, call `paseo.agents.ref(id).reload()` to apply the selection immediately. This +interrupts a running turn. `refresh()` reads the agent snapshot without reopening its session. + +From the repository root, `npm run typecheck` includes this example. Outside this repository, +use `paseo plugin init` to create the package and TypeScript setup, then copy `index.server.ts` +and the manifest into that project. + +See [Attach tools to agents](../../public-docs/plugins/reference.md#attach-tools-to-agents) +for targeting, execution, provider gates, collisions, and plugin reload behavior. diff --git a/plugin-examples/agent-tools/index.server.ts b/plugin-examples/agent-tools/index.server.ts new file mode 100644 index 0000000000..600d743fbd --- /dev/null +++ b/plugin-examples/agent-tools/index.server.ts @@ -0,0 +1,26 @@ +import { writeFile } from "node:fs/promises"; +import path from "node:path"; +import { z } from "zod"; +import { defineAgentTool, type PluginServerContext } from "@getpaseo/plugin/server"; + +const appendWorkspaceNote = defineAgentTool({ + name: "append_workspace_note", + description: "Append a note to AGENT_NOTES.md in this agent's working directory.", + input: z.object({ note: z.string().min(1).describe("Note to append") }), + async execute({ note }, { agent, signal }) { + const notePath = path.join(agent.cwd, "AGENT_NOTES.md"); + await writeFile(notePath, `${note}\n`, { encoding: "utf8", flag: "a", signal }); + return { + text: `Saved note to ${notePath}`, + structuredContent: { path: notePath }, + }; + }, +}); + +export default function contribute(server: PluginServerContext) { + server.before("agent.session_open", ({ request }) => { + if (request.labels["notes/enabled"] !== "true") return; + return { ...request, tools: [...request.tools, appendWorkspaceNote] }; + }); + return () => {}; +} diff --git a/plugin-examples/agent-tools/paseo-plugin.json b/plugin-examples/agent-tools/paseo-plugin.json new file mode 100644 index 0000000000..eaec7ffaf6 --- /dev/null +++ b/plugin-examples/agent-tools/paseo-plugin.json @@ -0,0 +1,4 @@ +{ + "id": "agent-tools", + "requirements": { "paseo": ">=0.13.2" } +} diff --git a/public-docs/plugins/reference.md b/public-docs/plugins/reference.md index 81b99b0dd0..69608a83a7 100644 --- a/public-docs/plugins/reference.md +++ b/public-docs/plugins/reference.md @@ -711,6 +711,120 @@ server.before("agent.session_open", ({ request }) => { This runs on create, resume, refresh, and import. To inject only on creation, set `env` in an `agent.create` callback instead. +### Attach tools to agents + +Define a tool in `index.server.ts` and attach it in `before("agent.session_open")`. +This example gives `append_workspace_note` only to agents with the label `notes/enabled: "true"`: + +```ts +import { writeFile } from "node:fs/promises"; +import path from "node:path"; +import { z } from "zod"; +import { defineAgentTool, type PluginServerContext } from "@getpaseo/plugin/server"; + +const appendWorkspaceNote = defineAgentTool({ + name: "append_workspace_note", + description: "Append a note to AGENT_NOTES.md in this agent's working directory.", + input: z.object({ note: z.string().min(1).describe("Note to append") }), + async execute({ note }, { agent, signal }) { + const notePath = path.join(agent.cwd, "AGENT_NOTES.md"); + await writeFile(notePath, `${note}\n`, { encoding: "utf8", flag: "a", signal }); + return { + text: `Saved note to ${notePath}`, + structuredContent: { path: notePath }, + }; + }, +}); + +export default function contribute(server: PluginServerContext) { + server.before("agent.session_open", ({ request }) => { + if (request.labels["notes/enabled"] !== "true") return; + return { ...request, tools: [...request.tools, appendWorkspaceNote] }; + }); + return () => {}; +} +``` + +Set the label when creating an agent with the SDK: + +```ts +const agent = await paseo.agents.create({ + config: { provider: "codex/gpt-5.4" }, + cwd: "/projects/shop", + labels: { "notes/enabled": "true" }, +}); +``` + +Select agents using any of the session-open request fields: + +| Select by | Condition in the callback | +| ---------------- | -------------------------------------------- | +| Label | `request.labels["notes/enabled"] === "true"` | +| Provider | `request.provider === "codex"` | +| Workspace | `request.workspaceId === "workspace-456"` | +| Individual agent | `request.agentId === chosenAgentId` | + +`request.tools` starts empty for each plugin. Each callback sees the tools returned by earlier +callbacks in that plugin; replace the array to add or remove tools. Returning `undefined` preserves +the request. Tools are ignored for `purpose: "history"`. + +Import `defineAgentTool`, `AgentToolDefinition`, `AgentToolContext`, and `AgentToolResult` from +`@getpaseo/plugin/server`. The helper infers the validated input from your Zod schema: + +```ts +declare function defineAgentTool(tool: { + name: string; + title?: string; + description: string; + input: Input; + execute( + input: z.output, + context: AgentToolContext, + ): AgentToolResult | Promise; +}): AgentToolDefinition; + +interface AgentToolResult { + text?: string; + structuredContent?: unknown; + isError?: boolean; +} +``` + +| Execution context | Value | +| ----------------- | --------------------------------------------------------------------------------------------------- | +| `agent` | Calling agent as a `PluginHookAgent`, including `id`, `workspaceId`, `provider`, `cwd`, and `title` | +| `paseo` | SDK connected to this daemon | +| `signal` | Abort signal for this tool call; pass it to file operations or external requests | + +`execute` runs in the plugin process. Closures and the original Zod schema stay there; only tool +metadata and call inputs/results cross the process boundary. Paseo validates input before calling +`execute`. Invalid input returns schema issues to the agent. A thrown error becomes +`{ isError: true, text: message }` and the plugin keeps running. Canceling the call or closing its +transport aborts `signal` and discards the result. Tool calls have a 10 minute ceiling, separate +from the 30 second hook timeout. Closing or reopening an agent session drops its old definitions. + +Return model-visible text in `text`. `structuredContent` must be JSON-serializable; when `text` is +omitted, Paseo formats that value as text for the model. Set `isError: true` to report a tool error. + +Paseo delivers attached tools through its agent tool transport, using MCP or native registration +as the provider supports. The same definition and callback work with either. Attached tools obey +the [same gates as Paseo tools](/docs/mcp#limit-paseo-tools-by-provider). Only that agent sees them. + +Names must match `/^[a-z][a-z0-9_]*$/` and be at most 64 characters. A name colliding with a Paseo +tool or another plugin's tool on the same agent fails the session open and names both owners. +A duplicate name within one plugin also fails the session open. Agents the callback does not +target are unaffected. + +| Change | When the agent receives it | +| -------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Start, stop, or reload a plugin declaring `agent.session_open` | Open sessions become stale. Each reopens before its next idle prompt; a running turn continues without interruption. The next prompt after that reopen reuses the session. | +| Change which agents the callback targets | Run `paseo plugin reload agent-tools` after editing this example, then send the agent a prompt when it is idle. | +| Apply immediately | Call `await paseo.agents.ref(id).reload({ requestId: "reload-notes" })`. `requestId` is optional. This reopens the provider session, reruns hooks with `reason: "refresh"`, and interrupts a running turn. | +| Read the current snapshot | Call `await paseo.agents.ref(id).refresh()`. This reads state without reopening the session. | + +If an automatic reopen fails, the triggering prompt fails with that error. See the +[complete agent-tools example](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools). + ### Choose workspace isolation ```ts @@ -878,11 +992,11 @@ type PluginTurnOutcome = ### Before hooks -| Name | Request fields | Editable | -| -------------------- | ----------------------------------------------------------------------- | --------------------------------------- | -| `agent.create` | `config`, optional `env` | Public agent config except `cwd`; `env` | -| `agent.session_open` | `agentId`, `workspaceId`, `provider`, `cwd`, `reason`, `purpose`, `env` | Only `env` | -| `workspace.create` | `source`, optional `title`, `firstAgentContext` | Entire explicit creation request | +| Name | Request fields | Editable | +| -------------------- | ---------------------------------------------------------------------------------------------------------------- | --------------------------------------- | +| `agent.create` | `config`, optional `env` | Public agent config except `cwd`; `env` | +| `agent.session_open` | `agentId`, `workspaceId`, `provider`, `cwd`, read-only `title` and `labels`, `reason`, `purpose`, `env`, `tools` | `env` and `tools` | +| `workspace.create` | `source`, optional `title`, `firstAgentContext` | Entire explicit creation request | **`agent.create.config`** uses `AgentSessionConfig`: @@ -903,6 +1017,9 @@ type PluginTurnOutcome = "workspaceId": "workspace-456", "provider": "codex", "cwd": "/projects/shop", + "title": "Workspace notes", + "labels": { "notes/enabled": "true" }, + "tools": [], "reason": "resume", "purpose": "interactive", "env": { "COMPANY_ENV": "development" } @@ -912,6 +1029,9 @@ type PluginTurnOutcome = | Field | Values | | ------------- | ----------------------------------------------------------------------------------------------------------------------- | | `workspaceId` | String or `null` | +| `title` | Read-only string or `null`; creation title on create, stored title on resume. | +| `labels` | Read-only string map; creation labels on create, stored labels on resume. | +| `tools` | Editable `AgentToolDefinition[]`, local to this plugin. See [Attach tools to agents](#attach-tools-to-agents). | | `reason` | `create`, `resume`, `refresh`, `import` | | `purpose` | `interactive`, `history` | | `env` | Launch override map; excludes the daemon's inherited environment. Replace the map to add, replace, or remove overrides. | @@ -923,7 +1043,7 @@ Creation request → agent.create hooks (plugin-ID order; registration order within each plugin) → resolve defaults and validate provider configuration → derive launch configuration with Paseo runtime tools and daemon prompt - → agent.session_open hooks (same ordering; env only) + → agent.session_open hooks (same ordering; env and plugin-local tools) → set PASEO_AGENT_ID and PASEO_AGENT_CWD → open provider session and save agent configuration ``` @@ -960,6 +1080,7 @@ saved; environment overrides are not persisted with it. | [lifecycle-logger](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-logger) | All eleven hooks; JSON logs with environment values redacted | | [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | Follow-ups, permissions, environment, provider switching, worktree selection | | [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | MCP injection and Codex sandbox/approval options | +| [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | Label-targeted tools and file operations in the plugin process | Read logger output with `paseo plugin logs lifecycle-logger` or the host's `daemon.log`. diff --git a/public-docs/plugins/reference.zh-CN.md b/public-docs/plugins/reference.zh-CN.md index 62caec83e5..3c84f8cc0c 100644 --- a/public-docs/plugins/reference.zh-CN.md +++ b/public-docs/plugins/reference.zh-CN.md @@ -585,6 +585,117 @@ server.before("agent.session_open", ({ request }) => { 它会在创建、恢复、刷新和导入时运行。如果只想在创建时注入,请改为在 `agent.create` 回调中设置 `env`。 +### 为 Agent 附加工具 {#attach-tools-to-agents} + +在 `index.server.ts` 中定义工具,并在 `before("agent.session_open")` 中附加它。 +此示例只向带有 `notes/enabled: "true"` 标签的 Agent 提供 `append_workspace_note`: + +```ts +import { writeFile } from "node:fs/promises"; +import path from "node:path"; +import { z } from "zod"; +import { defineAgentTool, type PluginServerContext } from "@getpaseo/plugin/server"; + +const appendWorkspaceNote = defineAgentTool({ + name: "append_workspace_note", + description: "Append a note to AGENT_NOTES.md in this agent's working directory.", + input: z.object({ note: z.string().min(1).describe("Note to append") }), + async execute({ note }, { agent, signal }) { + const notePath = path.join(agent.cwd, "AGENT_NOTES.md"); + await writeFile(notePath, `${note}\n`, { encoding: "utf8", flag: "a", signal }); + return { + text: `Saved note to ${notePath}`, + structuredContent: { path: notePath }, + }; + }, +}); + +export default function contribute(server: PluginServerContext) { + server.before("agent.session_open", ({ request }) => { + if (request.labels["notes/enabled"] !== "true") return; + return { ...request, tools: [...request.tools, appendWorkspaceNote] }; + }); + return () => {}; +} +``` + +通过 SDK 创建 Agent 时设置标签: + +```ts +const agent = await paseo.agents.create({ + config: { provider: "codex/gpt-5.4" }, + cwd: "/projects/shop", + labels: { "notes/enabled": "true" }, +}); +``` + +使用会话打开请求中的字段选择 Agent: + +| 选择依据 | 回调中的条件 | +| ---------- | -------------------------------------------- | +| 标签 | `request.labels["notes/enabled"] === "true"` | +| Provider | `request.provider === "codex"` | +| 工作区 | `request.workspaceId === "workspace-456"` | +| 单个 Agent | `request.agentId === chosenAgentId` | + +每个插件的 `request.tools` 都从空数组开始。同一插件中的后续回调会看到前面回调返回的工具; +替换数组即可添加或移除工具。返回 `undefined` 会保留请求。`purpose: "history"` 时会忽略工具。 + +从 `@getpaseo/plugin/server` 导入 `defineAgentTool`、`AgentToolDefinition`、`AgentToolContext` +和 `AgentToolResult`。辅助函数会根据 Zod schema 推断验证后的输入类型: + +```ts +declare function defineAgentTool(tool: { + name: string; + title?: string; + description: string; + input: Input; + execute( + input: z.output, + context: AgentToolContext, + ): AgentToolResult | Promise; +}): AgentToolDefinition; + +interface AgentToolResult { + text?: string; + structuredContent?: unknown; + isError?: boolean; +} +``` + +| 执行 context | 值 | +| ------------ | --------------------------------------------------------------------------------------------------- | +| `agent` | 发起调用的 Agent,以 `PluginHookAgent` 表示,包括 `id`、`workspaceId`、`provider`、`cwd` 和 `title` | +| `paseo` | 已连接到此 daemon 的 SDK | +| `signal` | 此次工具调用的中止信号;请把它传给文件操作或外部请求 | + +`execute` 在插件进程中运行。闭包和原始 Zod schema 保留在该进程中;只有工具元数据和调用的 +输入、结果会跨进程传递。Paseo 在调用 `execute` 前验证输入。无效输入会将 schema 问题返回给 +Agent。抛出的错误会转换为 `{ isError: true, text: message }`,插件继续运行。取消调用或关闭 +其传输连接会中止 `signal` 并丢弃结果。工具调用最长运行 10 分钟,与钩子的 30 秒超时分开。 +关闭或重新打开 Agent 会话会移除旧定义。 + +在 `text` 中返回模型可见的文本。`structuredContent` 必须可序列化为 JSON;省略 `text` 时, +Paseo 会将该值格式化为供模型读取的文本。设置 `isError: true` 可报告工具错误。 + +Paseo 通过 Agent 工具传输提供附加的工具,按 Provider 的支持情况使用 MCP 或原生注册。 +同一份定义和回调适用于这两种方式。附加的工具遵循[与 Paseo 工具相同的限制](/docs/mcp#limit-paseo-tools-by-provider)。 +只有该 Agent 能看到这些工具。 + +名称必须匹配 `/^[a-z][a-z0-9_]*$/`,且不超过 64 个字符。如果名称与同一 Agent 的 Paseo +工具或另一插件的工具冲突,会话打开会失败,并指出双方。一个插件内的重复名称也会导致 +会话打开失败。回调未选中的 Agent 不受影响。 + +| 变更 | Agent 何时收到变更 | +| ------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 启动、停止或重新加载声明了 `agent.session_open` 的插件 | 已打开的会话会标记为过期。每个会话在下一次空闲提示词前重新打开;正在运行的轮次会继续,不会被中断。重新打开后的下一条提示词复用该会话。 | +| 修改回调选择的 Agent | 编辑此示例后运行 `paseo plugin reload agent-tools`,然后在 Agent 空闲时发送提示词。 | +| 立即应用 | 调用 `await paseo.agents.ref(id).reload({ requestId: "reload-notes" })`。`requestId` 可选。这会重新打开 Provider 会话,以 `reason: "refresh"` 再次运行钩子,并中断正在运行的轮次。 | +| 读取当前快照 | 调用 `await paseo.agents.ref(id).refresh()`。这只读取状态,不会重新打开会话。 | + +如果自动重新打开失败,触发它的提示词会返回该错误。参阅 +[完整 agent-tools 示例](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools)。 + ### 选择工作区隔离方式 {#choose-workspace-isolation} ```ts @@ -741,11 +852,11 @@ type PluginTurnOutcome = ### before 钩子 {#before-hooks} -| 名称 | 请求字段 | 可编辑 | -| -------------------- | ----------------------------------------------------------------------- | ----------------------------------- | -| `agent.create` | `config`,可选的 `env` | 除 `cwd` 外的公开 Agent 配置;`env` | -| `agent.session_open` | `agentId`, `workspaceId`, `provider`, `cwd`, `reason`, `purpose`, `env` | 仅 `env` | -| `workspace.create` | `source`,可选的 `title`,`firstAgentContext` | 整个显式创建请求 | +| 名称 | 请求字段 | 可编辑 | +| -------------------- | ------------------------------------------------------------------------------------------------------------ | ----------------------------------- | +| `agent.create` | `config`,可选的 `env` | 除 `cwd` 外的公开 Agent 配置;`env` | +| `agent.session_open` | `agentId`, `workspaceId`, `provider`, `cwd`,只读的 `title` 和 `labels`,`reason`, `purpose`, `env`, `tools` | `env` 和 `tools` | +| `workspace.create` | `source`,可选的 `title`,`firstAgentContext` | 整个显式创建请求 | **`agent.create.config`** 使用 `AgentSessionConfig`: @@ -766,18 +877,24 @@ type PluginTurnOutcome = "workspaceId": "workspace-456", "provider": "codex", "cwd": "/projects/shop", + "title": "Workspace notes", + "labels": { "notes/enabled": "true" }, + "tools": [], "reason": "resume", "purpose": "interactive", "env": { "COMPANY_ENV": "development" } } ``` -| 字段 | 取值 | -| ------------- | ------------------------------------------------------------------------------------ | -| `workspaceId` | 字符串或 `null` | -| `reason` | `create`、`resume`、`refresh`、`import` | -| `purpose` | `interactive`、`history` | -| `env` | 启动覆盖映射;不包括 daemon 继承的环境变量。替换整个映射即可添加、替换或移除覆盖项。 | +| 字段 | 取值 | +| ------------- | -------------------------------------------------------------------------------------------------------- | +| `workspaceId` | 字符串或 `null` | +| `title` | 只读字符串或 `null`;创建时使用创建请求的标题,恢复时使用已保存的标题。 | +| `labels` | 只读的字符串映射;创建时使用创建请求的标签,恢复时使用已保存的标签。 | +| `tools` | 可编辑的 `AgentToolDefinition[]`,仅包含此插件的工具。参阅[为 Agent 附加工具](#attach-tools-to-agents)。 | +| `reason` | `create`、`resume`、`refresh`、`import` | +| `purpose` | `interactive`、`history` | +| `env` | 启动覆盖映射;不包括 daemon 继承的环境变量。替换整个映射即可添加、替换或移除覆盖项。 | ### 顺序与返回值 {#ordering-and-returned-values} @@ -786,7 +903,7 @@ Creation request → agent.create hooks (plugin-ID order; registration order within each plugin) → resolve defaults and validate provider configuration → derive launch configuration with Paseo runtime tools and daemon prompt - → agent.session_open hooks (same ordering; env only) + → agent.session_open hooks (same ordering; env and plugin-local tools) → set PASEO_AGENT_ID and PASEO_AGENT_CWD → open provider session and save agent configuration ``` @@ -822,6 +939,7 @@ Creation request | [lifecycle-logger](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-logger) | 全部十一个钩子;隐去环境变量值的 JSON 日志 | | [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | 后续消息、权限、环境变量、切换 Provider、选择 worktree | | [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | MCP 注入以及 Codex 沙盒/批准选项 | +| [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | 按标签选择 Agent,并在插件进程中执行文件操作的工具 | 用 `paseo plugin logs lifecycle-logger` 或主机的 `daemon.log` 读取 logger 的输出。 From 64b0afe0107b4b9b26f6fc404ac51f03678ae41f Mon Sep 17 00:00:00 2001 From: david828019-oss Date: Tue, 27 Oct 2026 10:38:49 +0800 Subject: [PATCH 035/173] fix(claude): identify SDK processes with the Paseo entrypoint (#7976) Co-authored-by: QTom --- .../agent/providers/claude/agent.env.test.ts | 45 ++++++++++++++++++- .../server/agent/providers/claude/query.ts | 11 ++--- 2 files changed, 48 insertions(+), 8 deletions(-) diff --git a/packages/server/src/server/agent/providers/claude/agent.env.test.ts b/packages/server/src/server/agent/providers/claude/agent.env.test.ts index 0d2748fd62..0806a0dbc6 100644 --- a/packages/server/src/server/agent/providers/claude/agent.env.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.env.test.ts @@ -1,10 +1,11 @@ +import { once } from "node:events"; import type { Query } from "@anthropic-ai/claude-agent-sdk"; import { describe, expect, test, vi } from "vitest"; import { createTestLogger } from "../../../../test-utils/test-logger.js"; import type { AgentLaunchContext } from "../../agent-sdk-types.js"; import { ClaudeAgentClient } from "./agent.js"; -import type { ClaudeQueryInput } from "./query.js"; +import { claudeQuery, type ClaudeQueryInput } from "./query.js"; function createQueryMock(events: unknown[]): Query { let index = 0; @@ -29,6 +30,48 @@ function createQueryMock(events: unknown[]): Query { } describe("Claude SDK env", () => { + test.each(["node", "bun", process.execPath])( + "identifies the spawned %s process as Paseo after clearing parent session env", + async (command) => { + let output = ""; + let exited = Promise.resolve([]); + const query = claudeQuery( + { prompt: "", options: {} }, + { + runtimeSettings: { env: { CLAUDE_CODE_ENTRYPOINT: "sdk-ts" } }, + launchEnv: { CLAUDE_CODE_ENTRYPOINT: "sdk-cli" }, + queryFactory: ({ options }) => { + if (!options.spawnClaudeCodeProcess) { + throw new Error("Missing Claude process launcher"); + } + const child = options.spawnClaudeCodeProcess({ + command, + args: [ + "-e", + "process.stdout.write(JSON.stringify({ entrypoint: process.env.CLAUDE_CODE_ENTRYPOINT, parentSession: process.env.CLAUDECODE ?? null }))", + ], + cwd: process.cwd(), + env: { ...process.env, CLAUDE_CODE_ENTRYPOINT: "sdk-ts", CLAUDECODE: "1" }, + signal: new AbortController().signal, + }); + child.stdout.on("data", (chunk: Buffer) => { + output += chunk.toString(); + }); + exited = once(child, "close"); + return createQueryMock([]); + }, + }, + ); + + try { + expect(await exited).toEqual([0, null]); + expect(JSON.parse(output)).toEqual({ entrypoint: "Paseo", parentSession: null }); + } finally { + query.close(); + } + }, + ); + test("forwards launch-context env through Claude process env", async () => { let capturedEnv: Record | undefined; let capturedPerTaskStopAffordance: boolean | undefined; diff --git a/packages/server/src/server/agent/providers/claude/query.ts b/packages/server/src/server/agent/providers/claude/query.ts index ccd511816a..c8fe4ba036 100644 --- a/packages/server/src/server/agent/providers/claude/query.ts +++ b/packages/server/src/server/agent/providers/claude/query.ts @@ -2,11 +2,10 @@ import { type ChildProcess, type ChildProcessWithoutNullStreams } from "node:chi import { query, type Options, type Query, type SpawnOptions } from "@anthropic-ai/claude-agent-sdk"; import { - createProviderEnv, createProviderEnvSpec, type ProviderRuntimeSettings, } from "../../provider-launch-config.js"; -import { buildSelfNodeCommand } from "../../../paseo-env.js"; +import { buildSelfNodeCommand, createExternalProcessEnv } from "../../../paseo-env.js"; import { spawnProcess } from "../../../../utils/spawn.js"; // Keep the raw SDK query import in this module only. Claude process launch behavior @@ -74,11 +73,9 @@ function applyRuntimeSettingsToClaudeOptions( runtimeSettings, overlays: [launchEnv], }); - const providerEnv = createProviderEnv({ - baseEnv: spawnOptions.env, - runtimeSettings, - overlays: [launchEnv], - }); + // Set our identity after sanitization clears the parent session's entrypoint. + providerEnvSpec.envOverlay.CLAUDE_CODE_ENTRYPOINT = "Paseo"; + const providerEnv = createExternalProcessEnv(spawnOptions.env, providerEnvSpec.envOverlay); const selfNodeCommand = isDefaultRuntime ? buildSelfNodeCommand(resolved.args, providerEnv) : null; From fc0cbbb32391a85b190130f267a8903a61b1b7a3 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Tue, 27 Oct 2026 09:56:21 +0700 Subject: [PATCH 036/173] fix(server): keep workspace reconciliation responsive on slow paths (#7941) * fix(server): keep workspace reconciliation responsive on slow paths Bound asynchronous directory inspection without releasing timed-out filesystem slots. Preserve unavailable records and make workspace archival atomic and idempotent so concurrent user archival cannot be repeated by a scan. * fix(server): wait for healthy reconciliation inspection capacity --- .../server/src/server/websocket-server.ts | 2 +- ...rkspace-reconciliation-observation.test.ts | 4 + .../workspace-reconciliation-service.test.ts | 449 +++++++++++++++++- .../workspace-reconciliation-service.ts | 269 ++++++++--- .../src/server/workspace-registry.test.ts | 26 +- .../server/src/server/workspace-registry.ts | 47 +- 6 files changed, 683 insertions(+), 114 deletions(-) diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index 53172b2835..4473a4004d 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -358,7 +358,7 @@ function createNoopWorkspaceRegistry(): WorkspaceRegistry { get: async () => null, update: async () => null, upsert: async () => {}, - archive: async () => {}, + archive: async () => false, remove: async () => {}, }; } diff --git a/packages/server/src/server/workspace-reconciliation-observation.test.ts b/packages/server/src/server/workspace-reconciliation-observation.test.ts index 8977641bab..44bb9de08e 100644 --- a/packages/server/src/server/workspace-reconciliation-observation.test.ts +++ b/packages/server/src/server/workspace-reconciliation-observation.test.ts @@ -495,6 +495,10 @@ describe("observed workspace placement", () => { expect((await observed.placement("workspace-one"))?.archivedAt).toEqual(expect.any(String)); expect(observed.workspaceBatches).toEqual([["workspace-one"]]); + const archived = await observed.placement("workspace-one"); + await observed.advanceBy(RESCAN_INTERVAL_MS); + expect(await observed.placement("workspace-one")).toEqual(archived); + expect(observed.workspaceBatches).toEqual([["workspace-one"]]); observed.dispose(); }); diff --git a/packages/server/src/server/workspace-reconciliation-service.test.ts b/packages/server/src/server/workspace-reconciliation-service.test.ts index 52c7d41065..e1a8860e3b 100644 --- a/packages/server/src/server/workspace-reconciliation-service.test.ts +++ b/packages/server/src/server/workspace-reconciliation-service.test.ts @@ -31,6 +31,14 @@ function canonicalLocalProjectKey(rootPath: string): string { } function createTestRegistries() { + let archiveGate: { + started: ReturnType; + release: ReturnType; + } | null = null; + const holdNextArchive = () => { + archiveGate = { started: deferred(), release: deferred() }; + return archiveGate; + }; const projects = new Map(); const workspaces = new Map(); @@ -55,6 +63,13 @@ function createTestRegistries() { projects.set(record.projectId, record); return record; }, + update: async (id, updater) => { + const current = projects.get(id); + if (!current) return null; + const updated = updater(current); + projects.set(id, updated); + return updated; + }, upsert: async (record: PersistedProjectRecord) => { projects.set(record.projectId, record); }, @@ -85,17 +100,23 @@ function createTestRegistries() { workspaces.set(record.workspaceId, record); }, archive: async (id: string, archivedAt: string) => { - const existing = workspaces.get(id); - if (existing) { - workspaces.set(id, { ...existing, archivedAt, updatedAt: archivedAt }); + const gate = archiveGate; + archiveGate = null; + if (gate) { + gate.started.resolve(); + await gate.release.promise; } + const existing = workspaces.get(id); + if (!existing || existing.archivedAt) return false; + workspaces.set(id, { ...existing, archivedAt, updatedAt: archivedAt }); + return true; }, remove: async (id: string) => { workspaces.delete(id); }, }; - return { projects, workspaces, projectRegistry, workspaceRegistry }; + return { projects, workspaces, projectRegistry, workspaceRegistry, holdNextArchive }; } function createTestLogger() { @@ -117,6 +138,7 @@ interface CapturedLogRecord { function createCapturingLogger() { const infoRecords: CapturedLogRecord[] = []; + const warnRecords: CapturedLogRecord[] = []; const logger = { child: () => logger, trace: () => undefined, @@ -124,10 +146,12 @@ function createCapturingLogger() { info: (payload: unknown, message?: string) => { infoRecords.push({ payload, message: message ?? "" }); }, - warn: () => undefined, + warn: (payload: unknown, message?: string) => { + warnRecords.push({ payload, message: message ?? "" }); + }, error: () => undefined, }; - return { logger: logger as unknown as pino.Logger, infoRecords }; + return { logger: logger as unknown as pino.Logger, infoRecords, warnRecords }; } function createWorkspaceGitServiceStub( @@ -241,6 +265,419 @@ describe("WorkspaceReconciliationService", () => { tempDirs.length = 0; }); + test("does not emit a duplicate archive when user archival commits before reconciliation's archive", async () => { + const rootPath = realpathSync(mkdtempSync(path.join(tmpdir(), "reconcile-archive-commit-"))); + tempDirs.push(rootPath); + const { projects, workspaces, projectRegistry, workspaceRegistry, holdNextArchive } = + createTestRegistries(); + projects.set( + "p1", + createPersistedProjectRecord({ + projectId: "p1", + rootPath, + projectKey: canonicalLocalProjectKey(rootPath), + kind: "non_git", + displayName: "project", + createdAt: timestamp, + updatedAt: timestamp, + }), + ); + workspaces.set( + "w1", + createPersistedWorkspaceRecord({ + workspaceId: "w1", + projectId: "p1", + cwd: path.join(rootPath, "missing"), + kind: "directory", + displayName: "workspace", + createdAt: timestamp, + updatedAt: timestamp, + }), + ); + const callbacks: string[] = []; + const service = new WorkspaceReconciliationService({ + projectRegistry, + workspaceRegistry, + logger: createTestLogger(), + onWorkspaceArchived: (id) => { + callbacks.push(id); + }, + }); + const gate = holdNextArchive(); + try { + const scan = service.runOnce(); + await gate.started.promise; + expect(await workspaceRegistry.archive("w1", timestamp)).toBe(true); + gate.release.resolve(); + expect((await scan).changesApplied).toEqual([]); + expect(callbacks).toEqual([]); + expect(workspaces.get("w1")?.archivedAt).toBe(timestamp); + } finally { + gate.release.resolve(); + service.dispose(); + } + }); + + test("preserves paths while two inspections saturate capacity, logs once, and recovers after they drain", async () => { + const rootPath = realpathSync(mkdtempSync(path.join(tmpdir(), "reconcile-saturated-"))); + tempDirs.push(rootPath); + const { projects, workspaces, projectRegistry, workspaceRegistry } = createTestRegistries(); + const { logger, warnRecords, infoRecords } = createCapturingLogger(); + projects.set( + "p1", + createPersistedProjectRecord({ + projectId: "p1", + rootPath, + projectKey: canonicalLocalProjectKey(rootPath), + kind: "non_git", + displayName: "project", + createdAt: timestamp, + updatedAt: timestamp, + }), + ); + const ids = ["hung1", "hung2", "healthy"]; + for (const workspaceId of ids) { + workspaces.set( + workspaceId, + createPersistedWorkspaceRecord({ + workspaceId, + projectId: "p1", + cwd: path.join(rootPath, workspaceId), + kind: "directory", + displayName: workspaceId, + createdAt: timestamp, + updatedAt: timestamp, + }), + ); + } + const release = deferred(); + const calls: string[] = []; + let recovered = false; + let ticks = 0; + const probe = setInterval(() => ticks++, 1); + const service = new WorkspaceReconciliationService({ + projectRegistry, + workspaceRegistry, + logger, + inspectionTimeoutMs: 30, + inspectDirectory: async (targetPath) => { + calls.push(targetPath); + if (!recovered && path.basename(targetPath).startsWith("hung")) await release.promise; + return "directory"; + }, + }); + try { + const result = await service.runOnce(); + expect(ticks).toBeGreaterThan(0); + expect(result.durationMs).toBeLessThan(1000); + expect(result.changesApplied).toEqual([]); + expect(calls).toEqual(ids.slice(0, 2).map((id) => path.join(rootPath, id))); + expect([...workspaces.values()].map((workspace) => workspace.archivedAt)).toEqual([ + null, + null, + null, + ]); + expect(warnRecords.filter((record) => record.message.includes("saturated"))).toEqual([ + { + message: "Workspace directory inspection saturated; preserving uninspected workspaces", + payload: { paths: ids.slice(0, 2).map((id) => path.join(rootPath, id)) }, + }, + ]); + recovered = true; + release.resolve(); + await new Promise((resolve) => setImmediate(resolve)); + expect(infoRecords).toEqual([ + { + message: + "Timed-out workspace directory inspections drained; reconciliation capacity restored", + payload: {}, + }, + ]); + calls.length = 0; + await service.runOnce(); + expect(calls).toEqual([...ids.map((id) => path.join(rootPath, id)), rootPath]); + expect(warnRecords.filter((record) => record.message.includes("saturated"))).toHaveLength(1); + } finally { + release.resolve(); + clearInterval(probe); + service.dispose(); + } + }); + + test("inspects every healthy path when one hung inspection times out during a longer scan", async () => { + const rootPath = realpathSync(mkdtempSync(path.join(tmpdir(), "reconcile-long-hung-"))); + tempDirs.push(rootPath); + const { projects, workspaces, projectRegistry, workspaceRegistry } = createTestRegistries(); + projects.set( + "p1", + createPersistedProjectRecord({ + projectId: "p1", + rootPath, + projectKey: canonicalLocalProjectKey(rootPath), + kind: "non_git", + displayName: "project", + createdAt: timestamp, + updatedAt: timestamp, + }), + ); + const healthyIds = Array.from({ length: 12 }, (_, i) => `healthy${i}`); + for (const workspaceId of ["hung", ...healthyIds]) { + workspaces.set( + workspaceId, + createPersistedWorkspaceRecord({ + workspaceId, + projectId: "p1", + cwd: path.join(rootPath, workspaceId), + kind: "directory", + displayName: workspaceId, + createdAt: timestamp, + updatedAt: timestamp, + }), + ); + } + const calls: string[] = []; + let outstanding = 0; + let maximumOutstanding = 0; + const { logger, warnRecords } = createCapturingLogger(); + const service = new WorkspaceReconciliationService({ + projectRegistry, + workspaceRegistry, + logger, + inspectionTimeoutMs: 100, + inspectDirectory: async (targetPath) => { + calls.push(targetPath); + maximumOutstanding = Math.max(maximumOutstanding, ++outstanding); + if (path.basename(targetPath) === "hung") return new Promise(() => {}); + await new Promise((resolve) => setTimeout(resolve, 20)); + outstanding--; + return "directory"; + }, + }); + try { + const result = await service.runOnce(); + expect(result.durationMs).toBeGreaterThan(100); + expect(calls).toEqual( + ["hung", ...healthyIds].map((id) => path.join(rootPath, id)).concat(rootPath), + ); + expect(maximumOutstanding).toBe(2); + expect(outstanding).toBe(1); + expect(workspaces.get("hung")?.archivedAt).toBeNull(); + expect(result.changesApplied).toEqual([]); + expect(warnRecords.filter((record) => record.message.includes("saturated"))).toEqual([]); + } finally { + service.dispose(); + } + }); + + test("times out a hung inspection without archiving it or blocking healthy paths, and retains its IO slot", async () => { + const rootPath = realpathSync(mkdtempSync(path.join(tmpdir(), "reconcile-hung-"))); + tempDirs.push(rootPath); + const { projects, workspaces, projectRegistry, workspaceRegistry } = createTestRegistries(); + projects.set( + "p1", + createPersistedProjectRecord({ + projectId: "p1", + rootPath, + projectKey: canonicalLocalProjectKey(rootPath), + kind: "non_git", + displayName: "project", + createdAt: timestamp, + updatedAt: timestamp, + }), + ); + for (const workspaceId of ["hung", "healthy", "healthy2", "healthy3"]) { + workspaces.set( + workspaceId, + createPersistedWorkspaceRecord({ + workspaceId, + projectId: "p1", + cwd: path.join(rootPath, workspaceId), + kind: "directory", + displayName: workspaceId, + createdAt: timestamp, + updatedAt: timestamp, + }), + ); + } + const calls: string[] = []; + let outstanding = 0; + let maximumOutstanding = 0; + const healthyInspected = deferred(); + const service = new WorkspaceReconciliationService({ + projectRegistry, + workspaceRegistry, + logger: createTestLogger(), + inspectionTimeoutMs: 30, + inspectDirectory: async (targetPath) => { + calls.push(targetPath); + maximumOutstanding = Math.max(maximumOutstanding, ++outstanding); + if (path.basename(targetPath) === "hung") return new Promise(() => {}); + healthyInspected.resolve(); + await new Promise((resolve) => setImmediate(resolve)); + outstanding--; + return "directory"; + }, + }); + try { + const scan = service.runOnce(); + await Promise.race([ + healthyInspected.promise, + scan.then(() => { + throw new Error("Reconciliation did not use its directory inspection capability"); + }), + ]); + expect(outstanding).toBeLessThanOrEqual(2); + expect(workspaces.get("hung")?.archivedAt).toBeNull(); + const result = await scan; + expect(result.changesApplied).toEqual([]); + await service.runOnce(); + expect(calls.filter((cwd) => path.basename(cwd) === "hung")).toHaveLength(1); + expect(calls.filter((cwd) => path.basename(cwd) === "healthy3")).toHaveLength(2); + expect(maximumOutstanding).toBe(2); + expect([...workspaces.values()].map((workspace) => workspace.archivedAt)).toEqual([ + null, + null, + null, + null, + ]); + } finally { + service.dispose(); + } + }); + + test.each(["missing", "directory"] as const)( + "does not process or archive a workspace archived during %s inspection", + async (state) => { + const rootPath = realpathSync( + mkdtempSync(path.join(tmpdir(), "reconcile-inspection-archive-")), + ); + tempDirs.push(rootPath); + const { projects, workspaces, projectRegistry, workspaceRegistry } = createTestRegistries(); + projects.set( + "p1", + createPersistedProjectRecord({ + projectId: "p1", + rootPath, + projectKey: canonicalLocalProjectKey(rootPath), + kind: "non_git", + displayName: "project", + createdAt: timestamp, + updatedAt: timestamp, + }), + ); + const cwd = path.join(rootPath, "missing"); + workspaces.set( + "w1", + createPersistedWorkspaceRecord({ + workspaceId: "w1", + projectId: "p1", + cwd, + kind: "directory", + displayName: "workspace", + createdAt: timestamp, + updatedAt: timestamp, + }), + ); + const started = deferred(); + const release = deferred(); + const archivedCallbacks: string[] = []; + const checkouts = new TestCheckouts(); + const service = new WorkspaceReconciliationService({ + projectRegistry, + workspaceRegistry, + logger: createTestLogger(), + workspaceGitService: checkouts, + onWorkspaceArchived: (id) => { + archivedCallbacks.push(id); + }, + inspectDirectory: async (targetPath) => { + if (targetPath === cwd) { + started.resolve(); + await release.promise; + return state; + } + return "directory"; + }, + }); + try { + const scan = service.runOnce(); + await Promise.race([ + started.promise, + scan.then(() => { + throw new Error("Reconciliation did not use its directory inspection capability"); + }), + ]); + await workspaceRegistry.archive("w1", "2026-01-01T00:00:00.000Z"); + const archived = workspaces.get("w1"); + release.resolve(); + const result = await scan; + expect(workspaces.get("w1")).toEqual(archived); + expect(archivedCallbacks).toEqual([]); + expect(checkouts.reads).toEqual([rootPath]); + expect(result.changesApplied).toEqual([]); + } finally { + release.resolve(); + service.dispose(); + } + }, + ); + + test("keeps the event loop responsive while inspecting 20000 real workspace paths", async () => { + const rootPath = realpathSync(mkdtempSync(path.join(tmpdir(), "reconcile-many-"))); + tempDirs.push(rootPath); + const { projects, workspaces, projectRegistry, workspaceRegistry } = createTestRegistries(); + projects.set( + "p1", + createPersistedProjectRecord({ + projectId: "p1", + rootPath, + projectKey: canonicalLocalProjectKey(rootPath), + kind: "non_git", + displayName: "project", + createdAt: timestamp, + updatedAt: timestamp, + }), + ); + for (let i = 0; i < 20000; i++) { + const workspaceId = `w${i}`; + workspaces.set( + workspaceId, + createPersistedWorkspaceRecord({ + workspaceId, + projectId: "p1", + cwd: path.join(rootPath, workspaceId), + kind: "directory", + displayName: workspaceId, + createdAt: timestamp, + updatedAt: timestamp, + }), + ); + } + const service = new WorkspaceReconciliationService({ + projectRegistry, + workspaceRegistry, + logger: createTestLogger(), + }); + let last = performance.now(); + let longestGap = 0; + const probe = setInterval(() => { + const now = performance.now(); + longestGap = Math.max(longestGap, now - last); + last = now; + }, 1); + let result; + try { + result = await service.runOnce(); + await new Promise((resolve) => setTimeout(resolve, 1)); + } finally { + clearInterval(probe); + service.dispose(); + } + expect(longestGap).toBeLessThan(20); + expect(result.changesApplied).toHaveLength(20000); + expect([...workspaces.values()].every((workspace) => workspace.archivedAt !== null)).toBe(true); + }, 30000); + test("preserves workspace archival that lands during boot reconciliation", async () => { const workspaceRoot = realpathSync(mkdtempSync(path.join(tmpdir(), "reconcile-archive-race-"))); tempDirs.push(workspaceRoot); diff --git a/packages/server/src/server/workspace-reconciliation-service.ts b/packages/server/src/server/workspace-reconciliation-service.ts index eb79dbacd2..5333da8f83 100644 --- a/packages/server/src/server/workspace-reconciliation-service.ts +++ b/packages/server/src/server/workspace-reconciliation-service.ts @@ -1,4 +1,6 @@ -import { statSync, watch as watchPath } from "node:fs"; +import { watch as watchPath } from "node:fs"; +import { stat } from "node:fs/promises"; +import { setImmediate as yieldToLoop } from "node:timers/promises"; import type { ProjectCheckoutLitePayload } from "@getpaseo/protocol/messages"; import type pino from "pino"; import type { @@ -19,6 +21,8 @@ import { deriveProjectKey } from "./project-key.js"; const DEFAULT_RESCAN_INTERVAL_MS = 5 * 60_000; const DEFAULT_DEBOUNCE_MS = 100; +const INSPECTION_CONCURRENCY = 2; +const DEFAULT_INSPECTION_TIMEOUT_MS = 5000; export type ProjectUpdate = | { kind: "upsert"; project: PersistedProjectRecord } @@ -95,6 +99,8 @@ export interface WorkspaceReconciliationServiceOptions { clock?: ReconciliationClock; rescanIntervalMs?: number; debounceMs?: number; + inspectDirectory?: (targetPath: string) => Promise; + inspectionTimeoutMs?: number; } interface ProjectReconciliationInput { @@ -110,9 +116,17 @@ interface CachedCheckoutRead { checkout: Promise; } -type DirectoryState = "directory" | "missing" | "unreadable"; +export type DirectoryState = "directory" | "missing" | "unreadable"; export class WorkspaceReconciliationService { + // Timed-out fs operations retain their slot until the OS returns. Never use + // the deadline to admit more work into libuv's shared threadpool. + private readonly timedOutPaths = new Set(); + private inspectionSaturated = false; + private readonly inspectionWaiters = new Set<() => void>(); + private readonly pendingInspections = new Map>(); + private readonly directoryInspection: (targetPath: string) => Promise; + private readonly inspectionTimeoutMs: number; private readonly serverId: string | undefined; private readonly projectRegistry: ProjectRegistry; private readonly workspaceRegistry: WorkspaceRegistry; @@ -136,6 +150,10 @@ export class WorkspaceReconciliationService { private reconcileQueuedMode: "metadata" | "full" | null = null; constructor(options: WorkspaceReconciliationServiceOptions) { + this.directoryInspection = + options.inspectDirectory ?? + (async (targetPath) => ((await stat(targetPath)).isDirectory() ? "directory" : "missing")); + this.inspectionTimeoutMs = options.inspectionTimeoutMs ?? DEFAULT_INSPECTION_TIMEOUT_MS; this.serverId = options.serverId; this.projectRegistry = options.projectRegistry; this.workspaceRegistry = options.workspaceRegistry; @@ -180,6 +198,7 @@ export class WorkspaceReconciliationService { dispose(): void { this.disposed = true; + this.wakeInspectionWaiters(); this.unsubscribeRegistry?.(); this.unsubscribeRegistry = null; if (this.rescanTimer) this.clock.clearInterval(this.rescanTimer); @@ -197,16 +216,23 @@ export class WorkspaceReconciliationService { this.workspaceRegistry.list(), ]); const workspacesByProject = new Map(); - for (const workspace of workspaces) { - if (workspace.archivedAt || this.inspectDirectory(workspace.cwd) !== "directory") continue; + const workspaceStates = await mapBounded( + workspaces.filter((w) => !w.archivedAt), + async (workspace) => ({ workspace, state: await this.inspectDirectory(workspace.cwd) }), + ); + for (const { workspace, state } of workspaceStates) { + if (state !== "directory") continue; + if ((await this.workspaceRegistry.get(workspace.workspaceId))?.archivedAt !== null) continue; const siblings = workspacesByProject.get(workspace.projectId) ?? []; siblings.push(workspace); workspacesByProject.set(workspace.projectId, siblings); } + const projectStates = await mapBounded( + projects.filter((p) => !p.archivedAt), + async (project) => ({ project, state: await this.inspectDirectory(project.rootPath) }), + ); await this.reconcileGitMetadataForProjects( - projects.filter( - (project) => !project.archivedAt && this.inspectDirectory(project.rootPath) === "directory", - ), + projectStates.filter(({ state }) => state === "directory").map(({ project }) => project), workspacesByProject, changes, ); @@ -222,23 +248,30 @@ export class WorkspaceReconciliationService { const allWorkspaces = await this.workspaceRegistry.list(); const activeProjects = allProjects.filter((p) => !p.archivedAt); + const activeProjectsById = new Map( + activeProjects.map((project) => [project.projectId, project]), + ); const activeWorkspaces = allWorkspaces.filter((w) => !w.archivedAt); - const workspaceDirectoryStates = activeWorkspaces.map((workspace) => ({ + const workspaceDirectoryStates = await mapBounded(activeWorkspaces, async (workspace) => ({ workspace, - state: this.inspectDirectory(workspace.cwd), + state: await this.inspectDirectory(workspace.cwd), + })); + // Read project roots after workspaces: losing a volume can withhold an + // archive, never turn a workspace's absence into proof of deletion. + const projectStates = await mapBounded(activeProjects, async (project) => ({ + project, + state: await this.inspectDirectory(project.rootPath), })); - // Project roots are read after the workspace directories, so a volume that - // goes away mid-pass leaves its project unreachable rather than its workspaces - // alone. The skew can only withhold an archive, never produce one. const reachableProjectIds = new Set( - activeProjects - .filter((project) => this.inspectDirectory(project.rootPath) === "directory") - .map((project) => project.projectId), + projectStates + .filter(({ state }) => state === "directory") + .map(({ project }) => project.projectId), ); const workspacesByProject = new Map(); for (const { workspace, state } of workspaceDirectoryStates) { if (state !== "directory") continue; + if ((await this.workspaceRegistry.get(workspace.workspaceId))?.archivedAt !== null) continue; const list = workspacesByProject.get(workspace.projectId) ?? []; list.push(workspace); workspacesByProject.set(workspace.projectId, list); @@ -255,26 +288,29 @@ export class WorkspaceReconciliationService { state === "missing" && reachableProjectIds.has(workspace.projectId), ) .map(({ workspace }) => workspace); - await Promise.all( - missingWorkspaces.map(async (workspace) => { - const timestamp = new Date().toISOString(); - await this.workspaceRegistry.archive(workspace.workspaceId, timestamp); - await this.onWorkspaceArchived?.(workspace.workspaceId); - changes.push({ - kind: "workspace_archived", - workspaceId: workspace.workspaceId, - directory: workspace.cwd, - reason: "directory_missing", - }); - - // Update the in-memory list for the project orphan check below - const siblings = workspacesByProject.get(workspace.projectId); - if (siblings) { - const updated = siblings.filter((w) => w.workspaceId !== workspace.workspaceId); - workspacesByProject.set(workspace.projectId, updated); - } - }), - ); + await mapBounded(missingWorkspaces, async (workspace) => { + const current = await this.workspaceRegistry.get(workspace.workspaceId); + const project = await this.projectRegistry.get(workspace.projectId); + if ( + !current || + current.archivedAt || + current.cwd !== workspace.cwd || + current.projectId !== workspace.projectId || + !project || + project.archivedAt || + project.rootPath !== activeProjectsById.get(project.projectId)?.rootPath + ) + return; + const timestamp = new Date().toISOString(); + if (!(await this.workspaceRegistry.archive(workspace.workspaceId, timestamp))) return; + await this.onWorkspaceArchived?.(workspace.workspaceId); + changes.push({ + kind: "workspace_archived", + workspaceId: workspace.workspaceId, + directory: workspace.cwd, + reason: "directory_missing", + }); + }); // 2. Reconcile mutable git metadata without changing identity or membership. // Projects persist until explicitly removed, even when they currently have @@ -351,13 +387,17 @@ export class WorkspaceReconciliationService { } private async reconcileProject(input: ProjectReconciliationInput): Promise { - const { project, siblings, currentGit, readCheckout, changes } = input; + const { siblings, currentGit, readCheckout, changes } = input; const workspaceCheckouts = await Promise.all( - siblings.map(async (workspace) => ({ - workspace, - checkout: await readCheckout(workspace.cwd), - })), + siblings.map(async (workspace) => { + const current = await this.workspaceRegistry.get(workspace.workspaceId); + if (!current || current.cwd !== workspace.cwd || current.projectId !== workspace.projectId) + return null; + return { workspace: current, checkout: await readCheckout(current.cwd) }; + }), ); + const project = await this.projectRegistry.get(input.project.projectId); + if (!project || project.archivedAt || project.rootPath !== input.project.rootPath) return; const projectUpdates: Partial> = {}; const mappedKind = deriveProjectKind(currentGit); const projectKey = deriveProjectKey({ @@ -377,40 +417,47 @@ export class WorkspaceReconciliationService { if (Object.keys(projectUpdates).length > 0) { const timestamp = new Date().toISOString(); - await this.projectRegistry.upsert({ - ...project, - ...projectUpdates, - updatedAt: timestamp, - }); - changes.push({ - kind: "project_updated", - projectId: project.projectId, - directory: project.rootPath, - fields: projectUpdates, + let applied = false; + await this.projectRegistry.update(project.projectId, (current) => { + if (current.archivedAt || current.rootPath !== project.rootPath) return current; + applied = true; + return { ...current, ...projectUpdates, updatedAt: timestamp }; }); + if (applied) + changes.push({ + kind: "project_updated", + projectId: project.projectId, + directory: project.rootPath, + fields: projectUpdates, + }); } await Promise.all( - workspaceCheckouts.map(async ({ workspace, checkout: wsGit }) => { + workspaceCheckouts.map(async (entry) => { + if (!entry) return; + const { workspace, checkout: wsGit } = entry; const timestamp = new Date().toISOString(); - const update = reconcileWorkspacePlacement({ - workspace, - checkout: wsGit, - updatedAt: timestamp, + if (!reconcileWorkspacePlacement({ workspace, checkout: wsGit, updatedAt: timestamp })) + return; + let fields: Partial | null = null; + await this.workspaceRegistry.update(workspace.workspaceId, (current) => { + if (current.cwd !== workspace.cwd || current.projectId !== workspace.projectId) + return current; + const update = reconcileWorkspacePlacement({ + workspace: current, + checkout: wsGit, + updatedAt: timestamp, + }); + if (!update) return current; + fields = update.fields; + return { ...current, ...fields, updatedAt: timestamp }; }); - if (!update) return; - - const updated = await this.workspaceRegistry.update(workspace.workspaceId, (current) => ({ - ...current, - ...update.fields, - updatedAt: timestamp, - })); - if (!updated) return; + if (!fields) return; changes.push({ kind: "workspace_updated", workspaceId: workspace.workspaceId, directory: workspace.cwd, - fields: update.fields, + fields, }); }), ); @@ -537,16 +584,74 @@ export class WorkspaceReconciliationService { return this.workspaceGitService.getCheckout(cwd); } - private inspectDirectory(targetPath: string): DirectoryState { + private wakeInspectionWaiters(): void { + for (const wake of this.inspectionWaiters) wake(); + this.inspectionWaiters.clear(); + } + + private async inspectDirectory(targetPath: string): Promise { + // A healthy in-flight inspection owns capacity temporarily. Wait for it; + // only unresolved operations that have all timed out justify skipping paths. + while ( + !this.disposed && + !this.pendingInspections.has(targetPath) && + this.pendingInspections.size >= INSPECTION_CONCURRENCY + ) { + if (this.timedOutPaths.size === INSPECTION_CONCURRENCY) return "unreadable"; + await new Promise((resolve) => this.inspectionWaiters.add(resolve)); + } + if (this.disposed) return "unreadable"; + let pending = this.pendingInspections.get(targetPath); + if (!pending) { + pending = Promise.resolve() + .then(() => this.directoryInspection(targetPath)) + .catch((error) => { + if (isMissingPathError(error)) return "missing" as const; + this.logger.warn( + { err: error, targetPath }, + "Skipped workspace reconciliation after directory inspection failed", + ); + return "unreadable" as const; + }) + .finally(() => { + this.pendingInspections.delete(targetPath); + this.timedOutPaths.delete(targetPath); + this.wakeInspectionWaiters(); + if (this.inspectionSaturated && this.timedOutPaths.size === 0) { + this.inspectionSaturated = false; + this.logger.info( + {}, + "Timed-out workspace directory inspections drained; reconciliation capacity restored", + ); + } + }); + this.pendingInspections.set(targetPath, pending); + } + let timer: ReturnType | undefined; try { - return statSync(targetPath).isDirectory() ? "directory" : "missing"; - } catch (error) { - if (isMissingPathError(error)) return "missing"; - this.logger.warn( - { err: error, targetPath }, - "Skipped workspace reconciliation after directory inspection failed", - ); - return "unreadable"; + return await Promise.race([ + pending, + new Promise((resolve) => { + timer = setTimeout(() => { + this.timedOutPaths.add(targetPath); + this.wakeInspectionWaiters(); + if (!this.inspectionSaturated && this.timedOutPaths.size === INSPECTION_CONCURRENCY) { + this.inspectionSaturated = true; + this.logger.warn( + { paths: [...this.timedOutPaths] }, + "Workspace directory inspection saturated; preserving uninspected workspaces", + ); + } + this.logger.warn( + { targetPath }, + "Skipped workspace reconciliation after directory inspection timed out", + ); + resolve("unreadable"); + }, this.inspectionTimeoutMs); + }), + ]); + } finally { + clearTimeout(timer); } } } @@ -555,3 +660,21 @@ function isMissingPathError(error: unknown): boolean { if (typeof error !== "object" || error === null || !("code" in error)) return false; return error.code === "ENOENT" || error.code === "ENOTDIR"; } + +// Two workers bound admission; yielding also bounds passes whose adapters settle +// immediately (including unavailable paths after both IO slots time out). +async function mapBounded(items: T[], visit: (item: T) => Promise): Promise { + const results: R[] = []; + let next = 0; + await Promise.all( + Array.from({ length: Math.min(INSPECTION_CONCURRENCY, items.length) }, async () => { + let count = 0; + while (next < items.length) { + const index = next++; + results[index] = await visit(items[index]!); + if (++count % 32 === 0) await yieldToLoop(); + } + }), + ); + return results; +} diff --git a/packages/server/src/server/workspace-registry.test.ts b/packages/server/src/server/workspace-registry.test.ts index 6c27027edc..d72da7c072 100644 --- a/packages/server/src/server/workspace-registry.test.ts +++ b/packages/server/src/server/workspace-registry.test.ts @@ -474,7 +474,7 @@ describe("workspace registries", () => { expect(await workspaceRegistry.list()).toEqual([]); }); - test("refreshes workspace archive timestamps when an archive is repeated", async () => { + test("preserves the first workspace archive and reports whether a queued archive applied", async () => { await workspaceRegistry.initialize(); await workspaceRegistry.upsert( createPersistedWorkspaceRecord({ @@ -488,12 +488,24 @@ describe("workspace registries", () => { }), ); - await workspaceRegistry.archive("workspace-one", "2026-03-02T00:00:00.000Z"); - await workspaceRegistry.archive("workspace-one", "2026-03-03T00:00:00.000Z"); - - expect(await workspaceRegistry.get("workspace-one")).toMatchObject({ - archivedAt: "2026-03-03T00:00:00.000Z", - updatedAt: "2026-03-03T00:00:00.000Z", + const events: WorkspaceMutation[] = []; + workspaceRegistry.subscribeToMutations((event) => { + events.push(event); + }); + expect( + await Promise.all([ + workspaceRegistry.archive("workspace-one", "2026-03-02T00:00:00.000Z"), + workspaceRegistry.archive("workspace-one", "2026-03-03T00:00:00.000Z"), + ]), + ).toEqual([true, false]); + expect(events.map((event) => event.kind)).toEqual(["archive"]); + const reloaded = new FileBackedWorkspaceRegistry( + path.join(tmpDir, "projects", "workspaces.json"), + logger, + ); + expect(await reloaded.get("workspace-one")).toMatchObject({ + archivedAt: "2026-03-02T00:00:00.000Z", + updatedAt: "2026-03-02T00:00:00.000Z", }); }); diff --git a/packages/server/src/server/workspace-registry.ts b/packages/server/src/server/workspace-registry.ts index 0e0fb4e62c..61fcb4f720 100644 --- a/packages/server/src/server/workspace-registry.ts +++ b/packages/server/src/server/workspace-registry.ts @@ -167,7 +167,7 @@ export interface WorkspaceRegistry { workspaceId: string, archivedAt: string, context?: WorkspaceArchiveContext, - ): Promise; + ): Promise; remove(workspaceId: string): Promise; /** Central lifecycle seam for daemon-global workspace observers. */ subscribeToMutations?( @@ -247,20 +247,6 @@ class FileBackedRegistry { }); } - async archive(id: string, archivedAt: string): Promise { - await this.archiveIfPresent(id, archivedAt); - } - - protected async archiveIfPresent(id: string, archivedAt: string): Promise { - return this.mutateCache((records) => { - const existing = records.get(id); - if (!existing) return null; - const next = this.schema.parse({ ...existing, updatedAt: archivedAt, archivedAt }); - records.set(id, next); - return next; - }); - } - protected async archiveIfActive(id: string, archivedAt: string): Promise { return this.mutateCache((records) => { const existing = records.get(id); @@ -485,7 +471,7 @@ export class FileBackedProjectRegistry return project; } - override async archive(projectId: string, archivedAt: string): Promise { + async archive(projectId: string, archivedAt: string): Promise { const project = await this.archiveIfActive(projectId, archivedAt); if (!project) return; await this.notifyMutation({ kind: "archive", projectId, project }); @@ -565,21 +551,28 @@ export class FileBackedWorkspaceRegistry }); } - override async archive( + async archive( workspaceId: string, archivedAt: string, context?: WorkspaceArchiveContext, - ): Promise { - const workspace = await super.update(workspaceId, (existing) => ({ - ...existing, - updatedAt: archivedAt, - archivedAt, - ...(context?.autoArchivedChangeRequestUrl - ? { autoArchivedChangeRequestUrl: context.autoArchivedChangeRequestUrl } - : {}), - })); - if (!workspace) return; + ): Promise { + const [workspace] = await this.mutateMany((records) => { + const existing = records.get(workspaceId); + if (!existing || existing.archivedAt) return []; + return [ + { + ...existing, + updatedAt: archivedAt, + archivedAt, + ...(context?.autoArchivedChangeRequestUrl + ? { autoArchivedChangeRequestUrl: context.autoArchivedChangeRequestUrl } + : {}), + }, + ]; + }); + if (!workspace) return false; await this.notifyMutation({ kind: "archive", workspaceId, workspace }); + return true; } override async remove(workspaceId: string): Promise { From 8d971876bf720cce616d8686439894c57b127cc1 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Tue, 27 Oct 2026 09:56:27 +0700 Subject: [PATCH 037/173] fix(omp): keep transcript replay responsive (#7948) * fix(omp): keep transcript replay responsive Index transcript branches in bounded asynchronous chunks and retain payloads only for the active chain, so large histories do not block unrelated daemon requests. * test(omp): enforce responsive history replay in CI Use a smaller structured transcript and a short selected chain to expose whole-file parsing without making large-output GC part of the CI gate. Disable unrelated provider discovery and route the regression through the existing integration job. * test(ci): include OMP replay in the routing contract --- packages/server/package.json | 2 +- .../server/agent/providers/omp/agent.test.ts | 11 ++ .../providers/omp/history-mapper.test.ts | 53 +++++- .../agent/providers/omp/history.e2e.test.ts | 104 ++++++++++++ .../src/server/agent/providers/omp/history.ts | 154 +++++++++++++++--- scripts/ci-workflow.test.mjs | 4 +- 6 files changed, 302 insertions(+), 26 deletions(-) create mode 100644 packages/server/src/server/agent/providers/omp/history.e2e.test.ts diff --git a/packages/server/package.json b/packages/server/package.json index 4aeb01dc3f..f39d284343 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -89,7 +89,7 @@ "speech:transcribe:local": "tsx scripts/transcribe-local-wav.ts", "test": "npm run test:unit && npm run test:integration", "test:unit": "vitest run --fileParallelism --exclude \"**/*.e2e.test.ts\"", - "test:integration": "vitest run --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts && vitest run --maxWorkers=1 src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses\"", + "test:integration": "vitest run --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts && vitest run --maxWorkers=1 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history\"", "test:hub-cli-contract": "vitest run --maxWorkers=1 src/server/hub/hub-cli-contract.test.ts", "test:integration:all": "npm run test:e2e", "test:integration:real": "vitest run real.e2e.test.ts", diff --git a/packages/server/src/server/agent/providers/omp/agent.test.ts b/packages/server/src/server/agent/providers/omp/agent.test.ts index 983f9cf55f..7b56c9bdec 100644 --- a/packages/server/src/server/agent/providers/omp/agent.test.ts +++ b/packages/server/src/server/agent/providers/omp/agent.test.ts @@ -1133,6 +1133,17 @@ describe("OMP agent client and session", () => { messageId: "assistant-history", }, ]); + await expect( + omp.runPrompt("continue after resume", "resumed follow-up complete"), + ).resolves.toMatchObject({ + finalText: "resumed follow-up complete", + }); + expect(omp.timeline()).toContainEqual( + expect.objectContaining({ + type: "assistant_message", + text: "resumed follow-up complete", + }), + ); expect(omp.usageSession()).toMatchObject({ provider: "omp", sessionKey: expect.any(String) }); await omp.close(); expect(omp.usageSession()).toBeNull(); diff --git a/packages/server/src/server/agent/providers/omp/history-mapper.test.ts b/packages/server/src/server/agent/providers/omp/history-mapper.test.ts index e64a93fd64..03c0ebe5ae 100644 --- a/packages/server/src/server/agent/providers/omp/history-mapper.test.ts +++ b/packages/server/src/server/agent/providers/omp/history-mapper.test.ts @@ -1,4 +1,5 @@ import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { describe, expect, test } from "vitest"; @@ -8,7 +9,7 @@ import { streamOmpCoreHistory, type OmpCapturedUserMessageEntry } from "./messag import type { OmpAgentMessage } from "./rpc-types.js"; import { FakeOmp } from "./test-utils/fake-omp.js"; import { OMP_HISTORY_MAPPER_HOOKS } from "./history-hooks.js"; -import { readOmpHistoryTodoState, streamOmpHistory } from "./history.js"; +import { readActiveOmpEntryChain, readOmpHistoryTodoState, streamOmpHistory } from "./history.js"; async function collectHistory( messages: OmpAgentMessage[], @@ -1245,3 +1246,53 @@ describe("OMP history mapper", () => { ); }); }); + +test("indexes out-of-order branches, duplicate IDs and cycles before selecting history", async () => { + const directory = await mkdtemp(join(tmpdir(), "omp-history-branches-")); + const sessionFile = join(directory, "session.jsonl"); + const root = { id: "root", parentId: null }; + const earlyLeaf = { + id: "early", + parentId: "root", + message: { role: "user", content: "你好🌍".repeat(15000) }, + }; + const branch = { id: "branch", parentId: "root" }; + const active = { id: "active", parentId: "branch" }; + const duplicate = { + id: "branch", + parentId: "root", + message: { role: "user", content: "replacement" }, + }; + try { + await writeFile( + sessionFile, + [earlyLeaf, active, root, branch, duplicate] + .map((entry) => JSON.stringify(entry)) + .join("\n") + '\n{"id":', + ); + // The final record is a branch ancestor, not the active leaf. Latest duplicate wins + // when following parents; the invalid tail contributes neither a leaf nor a parent. + await expect(readActiveOmpEntryChain(sessionFile)).resolves.toEqual([root, duplicate, active]); + await expect(readActiveOmpEntryChain(sessionFile, "early")).resolves.toEqual([root, earlyLeaf]); + await expect(readActiveOmpEntryChain(sessionFile, "missing")).resolves.toEqual([ + root, + duplicate, + active, + ]); + const cycle = [ + { id: "a", parentId: "b" }, + { id: "b", parentId: "a" }, + ]; + await writeFile(sessionFile, cycle.map((entry) => JSON.stringify(entry)).join("\n")); + await expect(readActiveOmpEntryChain(sessionFile)).resolves.toEqual(cycle); + await writeFile(sessionFile, "null\n{}\ninvalid\n"); + await expect(readActiveOmpEntryChain(sessionFile)).resolves.toEqual([]); + await expect(readActiveOmpEntryChain(directory)).rejects.toMatchObject({ code: "EISDIR" }); + await expect(readActiveOmpEntryChain(join(directory, "missing"))).rejects.toMatchObject({ + code: "ENOENT", + }); + await expect(readOmpHistoryTodoState(join(directory, "missing"))).resolves.toBeNull(); + } finally { + await rm(directory, { recursive: true, force: true }); + } +}); diff --git a/packages/server/src/server/agent/providers/omp/history.e2e.test.ts b/packages/server/src/server/agent/providers/omp/history.e2e.test.ts new file mode 100644 index 0000000000..77521a9687 --- /dev/null +++ b/packages/server/src/server/agent/providers/omp/history.e2e.test.ts @@ -0,0 +1,104 @@ +import { BUILTIN_PROVIDER_IDS } from "@getpaseo/protocol/provider-manifest"; +import { mkdtemp, open, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { performance } from "node:perf_hooks"; +import { setTimeout as delay } from "node:timers/promises"; +import { expect, test } from "vitest"; +import { createTestPaseoDaemon } from "../../../test-utils/paseo-daemon.js"; +import { DaemonClient } from "../../../test-utils/daemon-client.js"; +import { readActiveOmpEntryChain } from "./history.js"; + +test("replays selected OMP history without blocking the event loop", async () => { + const directory = await mkdtemp(join(tmpdir(), "omp-history-budget-")); + const sessionFile = join(directory, "session.jsonl"); + const started = performance.now(); + try { + const daemon = await createTestPaseoDaemon({ + // This regression exercises file replay and daemon requests, not executable discovery. + providerOverrides: Object.fromEntries( + BUILTIN_PROVIDER_IDS.map((id) => [id, { enabled: false }]), + ), + }); + const client = new DaemonClient({ + url: `ws://127.0.0.1:${daemon.port}/ws`, + appVersion: "0.13.2", + }); + try { + await client.connect(); + await client.fetchAgents({ subscribe: {} }); + await client.getDaemonStatus(); + const file = await open(sessionFile, "w"); + // Structured message blocks expose document-sized parsing at a modest byte size. + // Replay an earlier active entry so inactive payload retention cannot drive the probe. + const text = Array.from({ length: 64 }, () => ({ type: "text", text: "x" })); + let bytes = 0; + let count = 0; + try { + while (bytes < 28 * 1024 * 1024) { + const line = + JSON.stringify({ + type: "message", + id: `row-${count}`, + parentId: count ? `row-${count - 1}` : null, + message: { role: "user", content: text }, + }) + "\n"; + bytes += Buffer.byteLength(line); + await file.write(line); + count++; + } + } finally { + await file.close(); + } + let last = performance.now(); + let longestGap = 0; + const probe = setInterval(() => { + const now = performance.now(); + longestGap = Math.max(longestGap, now - last); + last = now; + }, 5); + try { + const replayState = { finished: false }; + let repliesDuringReplay = 0; + const replay = readActiveOmpEntryChain(sessionFile, "row-0").finally(() => { + replayState.finished = true; + }); + // A real WebSocket RPC served by the isolated daemon on the same event loop. + const requests = (async () => { + while (!replayState.finished) { + await client.getDaemonStatus(); + if (!replayState.finished) repliesDuringReplay++; + await delay(10); + } + })(); + const [entries] = await Promise.all([replay, requests]); + await delay(10); + console.log( + JSON.stringify({ + bytes, + count, + longestGap, + repliesDuringReplay, + generationAndLoadMs: performance.now() - started, + }), + ); + expect(entries).toEqual([ + { + type: "message", + id: "row-0", + parentId: null, + message: { role: "user", content: text }, + }, + ]); + expect(longestGap).toBeLessThan(50); + expect(repliesDuringReplay).toBeGreaterThan(0); + } finally { + clearInterval(probe); + } + } finally { + await client.close().finally(() => daemon.close()); + } + } finally { + await rm(directory, { recursive: true, force: true }); + } +}, 30000); diff --git a/packages/server/src/server/agent/providers/omp/history.ts b/packages/server/src/server/agent/providers/omp/history.ts index 2c818dfc5a..5102dfd44b 100644 --- a/packages/server/src/server/agent/providers/omp/history.ts +++ b/packages/server/src/server/agent/providers/omp/history.ts @@ -1,4 +1,5 @@ -import { readFile } from "node:fs/promises"; +import { open, type FileHandle } from "node:fs/promises"; +import { setImmediate } from "node:timers/promises"; import { basename, extname, join } from "node:path"; import type { AgentProvider, AgentStreamEvent, AgentTimelineItem } from "../../agent-sdk-types.js"; import { normalizeProviderReplayTimestamp } from "../../provider-history-timestamps.js"; @@ -96,7 +97,9 @@ export async function* streamOmpHistory(input: { const messages: OmpAgentMessage[] = []; const replayEntries: OmpReplayEntry[] = []; const userEntries: OmpCapturedUserMessageEntry[] = []; + let prepared = 0; for (const entry of entries) { + if (++prepared % 32 === 0) await setImmediate(); if (entry.type === "compaction") { replayEntries.push({ entry, item: mapCompactionEntry(entry) }); continue; @@ -115,7 +118,9 @@ export async function* streamOmpHistory(input: { OMP_HISTORY_MAPPER_HOOKS, input.bridgedTools, ); + let replayed = 0; for (const replayEntry of replayEntries) { + if (++replayed % 32 === 0) await setImmediate(); const timestamp = normalizeProviderReplayTimestamp(replayEntry.entry.timestamp); const events: AgentStreamEvent[] = "item" in replayEntry @@ -329,34 +334,139 @@ function stripExtension(filePath: string): string { return extension ? filePath.slice(0, -extension.length) : filePath; } -export async function readActiveOmpEntryChain( - sessionFile: string, - activeEntryId?: string, -): Promise { - const content = await readFile(sessionFile, "utf8"); - const entries = content.split("\n").flatMap((line) => { - if (!line.trim()) return []; - try { - const value = JSON.parse(line) as OmpSessionEntry; - return value && typeof value === "object" && typeof value.id === "string" ? [value] : []; - } catch { - return []; +interface OmpEntryLocation { + id: string; + parentId?: string | null; + offset: number; +} + +// Yield after each bounded IO chunk, including chunks containing only tiny or invalid records. +// Keep bytes until a complete line so multi-byte UTF-8 characters survive chunk boundaries. +async function* readOmpLines( + file: FileHandle, + size: number, +): AsyncGenerator<{ + line: Buffer; + offset: number; +}> { + const chunkSize = 64 * 1024; + let fragments: Buffer[] = []; + let lineOffset = 0; + for (let position = 0; position < size; ) { + const chunk = Buffer.allocUnsafe(Math.min(chunkSize, size - position)); + const { bytesRead } = await file.read(chunk, 0, chunk.length, position); + if (!bytesRead) break; + let start = 0; + for (let index = 0; index < bytesRead; index++) { + if (chunk[index] !== 10) continue; + const tail = chunk.subarray(start, index); + const line = fragments.length ? Buffer.concat([...fragments, tail]) : tail; + yield { line, offset: lineOffset }; + fragments = []; + start = index + 1; + lineOffset = position + start; } - }); - if (entries.length === 0) return []; - const byId = new Map(entries.map((entry) => [entry.id!, entry])); - const parentIds = new Set(entries.flatMap((entry) => (entry.parentId ? [entry.parentId] : []))); - const leaves = entries.filter((entry) => !parentIds.has(entry.id!)); - let current: OmpSessionEntry | undefined = - (activeEntryId ? byId.get(activeEntryId) : undefined) ?? leaves.at(-1) ?? entries.at(-1); - const chain: OmpSessionEntry[] = []; + if (start < bytesRead) fragments.push(chunk.subarray(start, bytesRead)); + position += bytesRead; + await setImmediate(); + } + if (fragments.length) yield { line: Buffer.concat(fragments), offset: lineOffset }; +} + +function parseOmpEntry(line: Buffer): OmpSessionEntry | null { + try { + const value: unknown = JSON.parse(line.toString("utf8")); + return value && typeof value === "object" && typeof Reflect.get(value, "id") === "string" + ? (value as OmpSessionEntry) + : null; + } catch { + // OMP can leave a partial last record; malformed records have always been ignored. + return null; + } +} + +async function selectOmpChain( + locations: readonly OmpEntryLocation[], + byId: ReadonlyMap, + parentIds: ReadonlySet, + activeEntryId?: string, +): Promise { + let current = activeEntryId ? byId.get(activeEntryId) : undefined; + if (!current) { + for (let index = locations.length - 1; index >= 0; index--) { + const location = locations[index]!; + if (!parentIds.has(location.id)) { + current = location; + break; + } + if (index % 256 === 0) await setImmediate(); + } + current ??= locations.at(-1); + } + const chain: OmpEntryLocation[] = []; const seen = new Set(); while (current?.id && !seen.has(current.id)) { chain.push(current); seen.add(current.id); current = current.parentId ? byId.get(current.parentId) : undefined; + if (chain.length % 256 === 0) await setImmediate(); + } + return chain; +} + +export async function readActiveOmpEntryChain( + sessionFile: string, + activeEntryId?: string, +): Promise { + const file = await open(sessionFile, "r"); + try { + const stat = await file.stat(); + if (stat.isDirectory()) { + throw Object.assign( + new Error(`EISDIR: illegal operation on a directory, read '${sessionFile}'`), + { + code: "EISDIR", + }, + ); + } + // One descriptor and a fixed byte boundary exclude appends made while replay is yielding. + // Retain graph metadata only: abandoned branches must not retain their message payloads. + const locations: OmpEntryLocation[] = []; + const byId = new Map(); + const parentIds = new Set(); + for await (const { line, offset } of readOmpLines(file, stat.size)) { + const entry = parseOmpEntry(line); + if (!entry) continue; + const location = { id: entry.id!, parentId: entry.parentId, offset }; + locations.push(location); + byId.set(location.id, location); + if (location.parentId) parentIds.add(location.parentId); + } + const chain = await selectOmpChain(locations, byId, parentIds, activeEntryId); + if (chain.length === 0) return []; + const selected = new Map(); + for (let index = 0; index < chain.length; index++) { + selected.set(chain[index]!.offset, chain.length - index - 1); + if (index % 256 === 0) await setImmediate(); + } + const entries: OmpSessionEntry[] = []; + for await (const { line, offset } of readOmpLines(file, stat.size)) { + const index = selected.get(offset); + if (index === undefined) continue; + const entry = parseOmpEntry(line); + // Truncation in place invalidates the indexed snapshot; never publish a partial chain. + if (!entry || entry.id !== chain[chain.length - index - 1]!.id) { + throw new Error(`OMP transcript changed during replay: ${sessionFile}`); + } + entries[index] = entry; + selected.delete(offset); + if (selected.size === 0) break; + } + if (selected.size) throw new Error(`OMP transcript changed during replay: ${sessionFile}`); + return entries; + } finally { + await file.close(); } - return chain.toReversed(); } function mapEntryMessage(entry: OmpSessionEntry): OmpAgentMessage | null { diff --git a/scripts/ci-workflow.test.mjs b/scripts/ci-workflow.test.mjs index 4842870cc3..c7e631c529 100644 --- a/scripts/ci-workflow.test.mjs +++ b/scripts/ci-workflow.test.mjs @@ -483,14 +483,14 @@ test("Windows units and integration run independently with complete routed cover assert.equal(scripts.test, "npm run test:unit && npm run test:integration"); assert.equal(scripts["test:unit"], 'vitest run --fileParallelism --exclude "**/*.e2e.test.ts"'); const invocations = scripts["test:integration"].split(" && "); - // Each vitest start costs about half a minute on Windows, so the four + // Each vitest start costs about half a minute on Windows, so the // name-filtered files share one invocation and one combined filter. assert.equal(invocations.length, 2); assert.ok(invocations.every((command) => command.startsWith("vitest run --maxWorkers=1 "))); assert.doesNotMatch(invocations[0], / -t /); assert.equal( invocations[1], - 'vitest run --maxWorkers=1 src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts -t "merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses"', + 'vitest run --maxWorkers=1 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts -t "merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history"', ); const serverConfig = readFileSync(new URL("packages/server/vitest.config.ts", repoRoot), "utf8"); assert.doesNotMatch(serverConfig, /maxWorkers/); From 9c7d4ace653aee635c33358e7034419b7464acb9 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Tue, 27 Oct 2026 09:56:31 +0700 Subject: [PATCH 038/173] fix(server): reject oversized provider stdout before parsing (#7960) Admit raw UTF-8 line bytes before accumulation and fail the provider session explicitly on overflow. Share line framing so fragmented JSONL input no longer repeatedly scans and copies the complete prefix. --- .../codex/app-server-transport.test.ts | 26 ++++++ .../providers/codex/app-server-transport.ts | 72 ++++++++--------- .../providers/jsonl-frame-decoder.test.ts | 66 +++++++++++++++ .../agent/providers/jsonl-frame-decoder.ts | 81 ++++++++++++++++--- .../agent/providers/jsonl-rpc-process.test.ts | 22 +++++ .../agent/providers/jsonl-rpc-process.ts | 23 ++++-- .../src/server/workspace-registry.test.ts | 29 +++++++ 7 files changed, 263 insertions(+), 56 deletions(-) diff --git a/packages/server/src/server/agent/providers/codex/app-server-transport.test.ts b/packages/server/src/server/agent/providers/codex/app-server-transport.test.ts index cc32a3c013..3018461ba9 100644 --- a/packages/server/src/server/agent/providers/codex/app-server-transport.test.ts +++ b/packages/server/src/server/agent/providers/codex/app-server-transport.test.ts @@ -183,3 +183,29 @@ describe("Codex app-server transport", () => { codex.child.stdin.end(); }); }); + +describe("Codex stdout byte admission", () => { + test("fails pending requests and the session before joining an oversized line", async () => { + const child = createCodexAppServerChildProcess(); + const client = new CodexAppServerClient(child, createTestLogger()); + const terminations: Error[] = []; + client.setUnexpectedTerminationHandler((error) => terminations.push(error)); + const request = client.request("thread/resume", {}, 1000).catch((error: Error) => error); + const chunk = Buffer.alloc(64 * 1024, "x"); + child.stdout.write('{"id":1,"result":"'); + for (let index = 0; index < 2048; index++) child.stdout.write(chunk); + const error = await request; + expect(error).toMatchObject({ + name: "ProviderStreamLimitError", + code: "PROVIDER_STREAM_LINE_TOO_LARGE", + limitBytes: 128 * 1024 * 1024, + }); + expect(terminations).toEqual([error]); + expect(client.hasPendingRequests()).toBe(false); + child.stdout.write('"}\n{"id":1,"result":"late"}\n'); + await expect(client.request("model/list")).rejects.toThrow("closed"); + await client.dispose(); + child.stdout.end(); + child.stderr.end(); + }); +}); diff --git a/packages/server/src/server/agent/providers/codex/app-server-transport.ts b/packages/server/src/server/agent/providers/codex/app-server-transport.ts index 29b8cf8880..dfd4adfac4 100644 --- a/packages/server/src/server/agent/providers/codex/app-server-transport.ts +++ b/packages/server/src/server/agent/providers/codex/app-server-transport.ts @@ -1,10 +1,15 @@ import type { ChildProcessWithoutNullStreams } from "node:child_process"; -import { StringDecoder } from "node:string_decoder"; import type { Logger } from "pino"; import { z } from "zod"; import { terminateWithTreeKill } from "../../../../utils/tree-kill.js"; +import { ProviderLineReader, ProviderStreamLimitError } from "../jsonl-frame-decoder.js"; + +// A measured long-thread resume was 19.75 MB; preserve the existing 32 MiB fixture +// with 4x margin for longer threads. This is provider stdout, not the client protocol. +export const CODEX_PROVIDER_LINE_BYTES = 128 * 1024 * 1024; + const DEFAULT_TIMEOUT_MS = 14 * 24 * 60 * 60 * 1000; const APP_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT_MS = 2_000; const APP_SERVER_FORCE_SHUTDOWN_TIMEOUT_MS = 1_000; @@ -167,39 +172,6 @@ function readProviderTurnId(params: unknown): string | undefined { return isRecord(turn) && typeof turn.id === "string" ? turn.id : undefined; } -/** - * Splits stdout into lines on "\n" only. `node:readline` additionally treats U+2028 and U+2029 - * as line terminators, but Codex emits those characters raw inside JSON strings, so readline - * would cut a single JSON-RPC message into pieces that fail to parse. - */ -function createNewlineLineReader( - input: NodeJS.ReadableStream, - onLine: (line: string) => void, -): { close(): void } { - const decoder = new StringDecoder("utf8"); - // Text after the last "\n", kept as parts and joined once its line ends, so a large line - // arriving in many chunks is scanned and copied once instead of once per chunk. - let unterminated: string[] = []; - const onData = (chunk: Buffer | string): void => { - const text = typeof chunk === "string" ? chunk : decoder.write(chunk); - let lineStart = 0; - let index = text.indexOf("\n"); - while (index !== -1) { - unterminated.push(text.slice(lineStart, index)); - const line = unterminated.join(""); - unterminated = []; - onLine(line.endsWith("\r") ? line.slice(0, -1) : line); - lineStart = index + 1; - index = text.indexOf("\n", lineStart); - } - if (lineStart < text.length) { - unterminated.push(text.slice(lineStart)); - } - }; - input.on("data", onData); - return { close: () => void input.off("data", onData) }; -} - export class CodexAppServerClient { private readonly stdoutLineReader: { close(): void }; private activeProviderRequests = 0; @@ -216,11 +188,24 @@ export class CodexAppServerClient { private readonly logger: Logger, private readonly getTraceContext: () => CodexAppServerTraceContext = () => ({}), ) { - this.stdoutLineReader = createNewlineLineReader(child.stdout, (line) => { - void this.handleLine(line).catch((error) => { - this.logger.warn({ error, line }, "Failed to handle Codex app-server stdout line"); - }); - }); + // Split only on LF: U+2028/U+2029 are valid raw characters inside Codex JSON. + const reader = new ProviderLineReader( + CODEX_PROVIDER_LINE_BYTES, + (line) => { + void this.handleLine(line).catch((error) => { + this.logger.warn({ error, line }, "Failed to handle Codex app-server stdout line"); + }); + }, + (error) => this.handleStreamLimit(error), + ); + const onData = (chunk: Buffer | string) => reader.write(chunk); + child.stdout.on("data", onData); + this.stdoutLineReader = { + close: () => { + reader.close(); + child.stdout.off("data", onData); + }, + }; child.stderr.on("data", (chunk) => { this.stderrBuffer += chunk.toString(); @@ -318,6 +303,15 @@ export class CodexAppServerClient { } } + private handleStreamLimit(failure: ProviderStreamLimitError): void { + // A rejected response/notification cannot be replayed safely. Fail the session, + // including live turns with no pending RPC, rather than dropping a stream unit. + this.handleUnexpectedTermination(failure); + void this.dispose().catch((err) => { + this.logger.warn({ err }, "Failed to terminate oversized Codex stdout producer"); + }); + } + private handleUnexpectedTermination(error: Error): void { if (this.disposed) { return; diff --git a/packages/server/src/server/agent/providers/jsonl-frame-decoder.test.ts b/packages/server/src/server/agent/providers/jsonl-frame-decoder.test.ts index af2bdabf01..c1c81bdae8 100644 --- a/packages/server/src/server/agent/providers/jsonl-frame-decoder.test.ts +++ b/packages/server/src/server/agent/providers/jsonl-frame-decoder.test.ts @@ -1,3 +1,5 @@ +import { performance } from "node:perf_hooks"; +import { setTimeout as delay } from "node:timers/promises"; import { describe, expect, it } from "vitest"; import { JsonlFrameDecoder, type JsonlFrameProblem } from "./jsonl-frame-decoder.js"; @@ -36,6 +38,16 @@ describe("JsonlFrameDecoder", () => { expect(problems).toEqual([]); }); + it("preserves UTF-8 characters split across raw stdout buffers", () => { + const { decoder, frames, problems } = decoderHarness(); + const bytes = Buffer.from('{"type":"notice","text":"é🙂"}\n'); + const split = bytes.indexOf(Buffer.from("🙂")) + 1; + decoder.write(bytes.subarray(0, split)); + decoder.write(bytes.subarray(split)); + expect(frames).toEqual([{ type: "notice", text: "é🙂" }]); + expect(problems).toEqual([]); + }); + it("reassembles a large ordered v2 frame", () => { const { decoder, frames, problems } = decoderHarness(); const frame = { type: "models", value: "x".repeat(1024 * 1024) }; @@ -55,3 +67,57 @@ describe("JsonlFrameDecoder", () => { expect(problems).toEqual(["out-of-order-chunk"]); }); }); + +describe("provider line admission", () => { + it("keeps the loop responsive while accumulating a fragmented provider response", async () => { + const { decoder, frames, problems } = decoderHarness(); + const part = "x".repeat(512); + let last = performance.now(); + let longestGap = 0; + const probe = setInterval(() => { + const now = performance.now(); + longestGap = Math.max(longestGap, now - last); + last = now; + }, 1); + try { + await delay(5); + decoder.write('{"type":"notice","text":"'); + // 1 MiB is enough to expose the former rescan of every accumulated prefix. + for (let index = 0; index < 2048; index++) decoder.write(part); + decoder.write('"}\n'); + await delay(5); + expect(frames).toEqual([{ type: "notice", text: part.repeat(2048) }]); + expect(problems).toEqual([]); + expect(longestGap).toBeLessThan(50); + } finally { + clearInterval(probe); + } + }); + + it("rejects an unterminated over-cap UTF-8 line and stops accepting frames", () => { + const frames: Record[] = []; + const failures: Array<{ problem: string; detail: unknown }> = []; + const decoder = new JsonlFrameDecoder({ + frame: (frame) => frames.push(frame), + problem: (problem, detail) => failures.push({ problem, detail }), + }); + // 64 MiB of UTF-8, only 32 Mi UTF-16 code units. No newline or JSON parse needed. + const chunk = "é".repeat(32 * 1024); + for (let index = 0; index < 1024; index++) decoder.write(chunk); + expect(failures).toEqual([]); + decoder.write("é"); + expect(failures).toEqual([ + { + problem: "line-too-large", + detail: expect.objectContaining({ + name: "ProviderStreamLimitError", + code: "PROVIDER_STREAM_LINE_TOO_LARGE", + limitBytes: 64 * 1024 * 1024, + }), + }, + ]); + decoder.write('\n{"type":"ready"}\n'); + expect(frames).toEqual([]); + expect(failures).toHaveLength(1); + }); +}); diff --git a/packages/server/src/server/agent/providers/jsonl-frame-decoder.ts b/packages/server/src/server/agent/providers/jsonl-frame-decoder.ts index 1662e7719c..8b1b9767de 100644 --- a/packages/server/src/server/agent/providers/jsonl-frame-decoder.ts +++ b/packages/server/src/server/agent/providers/jsonl-frame-decoder.ts @@ -1,3 +1,60 @@ +// Provider-process stdout only; these are not app/daemon wire limits. +export const JSONL_PROVIDER_LINE_BYTES = 64 * 1024 * 1024; + +export class ProviderStreamLimitError extends Error { + readonly code = "PROVIDER_STREAM_LINE_TOO_LARGE"; + + constructor(readonly limitBytes: number) { + super( + `Provider stdout line exceeds ${limitBytes} bytes. Start a new thread or reduce the provider response size.`, + ); + this.name = "ProviderStreamLimitError"; + } +} + +/** Admits raw UTF-8 bytes before retaining, decoding or joining a complete line. */ +export class ProviderLineReader { + private parts: Buffer[] = []; + private bytes = 0; + private stopped = false; + + constructor( + private readonly limitBytes: number, + private readonly onLine: (line: string) => void, + private readonly onLimit: (error: ProviderStreamLimitError) => void, + ) {} + + write(chunk: Buffer | string): void { + if (this.stopped) return; + const buffer = typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk; + let start = 0; + while (start < buffer.byteLength && !this.stopped) { + const newline = buffer.indexOf(10, start); + const end = newline === -1 ? buffer.byteLength : newline; + const length = end - start; + if (length > this.limitBytes - this.bytes) { + this.close(); + this.onLimit(new ProviderStreamLimitError(this.limitBytes)); + return; + } + if (length) this.parts.push(buffer.subarray(start, end)); + this.bytes += length; + if (newline === -1) return; + const line = Buffer.concat(this.parts, this.bytes).toString("utf8"); + this.parts = []; + this.bytes = 0; + this.onLine(line.endsWith("\r") ? line.slice(0, -1) : line); + start = newline + 1; + } + } + + close(): void { + this.stopped = true; + this.parts = []; + this.bytes = 0; + } +} + const V2_FRAME_BYTES = 1024 * 1024; const V2_REASSEMBLED_BYTES = 64 * 1024 * 1024; const V2_CHUNK_BYTES = 256 * 1024; @@ -5,6 +62,7 @@ const V2_BASE64_CHARS = Math.ceil(V2_CHUNK_BYTES / 3) * 4; const V2_MAX_CHUNKS = Math.ceil(V2_REASSEMBLED_BYTES / V2_CHUNK_BYTES); export type JsonlFrameProblem = + | "line-too-large" | "invalid-json" | "invalid-chunk" | "invalid-base64" @@ -78,7 +136,7 @@ function chunkBytes(data: string): Buffer | null { } export class JsonlFrameDecoder { - private lineBuffer = ""; + private readonly lines: ProviderLineReader; private assembly: ChunkAssembly | null = null; constructor( @@ -86,17 +144,18 @@ export class JsonlFrameDecoder { frame(message: Record): void; problem(problem: JsonlFrameProblem, detail?: unknown): void; }, - ) {} + ) { + this.lines = new ProviderLineReader( + JSONL_PROVIDER_LINE_BYTES, + (line) => { + if (line.trim()) this.consumeLine(line); + }, + (error) => this.drop("line-too-large", error), + ); + } - write(text: string): void { - this.lineBuffer += text; - let newline = this.lineBuffer.indexOf("\n"); - while (newline !== -1) { - const line = this.lineBuffer.slice(0, newline).replace(/\r$/, ""); - this.lineBuffer = this.lineBuffer.slice(newline + 1); - if (line.trim()) this.consumeLine(line); - newline = this.lineBuffer.indexOf("\n"); - } + write(chunk: Buffer | string): void { + this.lines.write(chunk); } private consumeLine(line: string): void { diff --git a/packages/server/src/server/agent/providers/jsonl-rpc-process.test.ts b/packages/server/src/server/agent/providers/jsonl-rpc-process.test.ts index 7dfbb6abb8..141b8f36f0 100644 --- a/packages/server/src/server/agent/providers/jsonl-rpc-process.test.ts +++ b/packages/server/src/server/agent/providers/jsonl-rpc-process.test.ts @@ -471,3 +471,25 @@ describe("JsonlRpcProcess", () => { } }); }); + +describe("JSONL stdout byte admission", () => { + test("fails pending requests and publishes the typed failure to live-turn consumers", async () => { + const child = createInMemoryChildProcess(); + const process = startProcess({ child }); + const exit = new Promise((resolve) => process.onExit(resolve)); + const request = process.request({ type: "hang" }, 1000).catch((error: Error) => error); + const chunk = Buffer.alloc(64 * 1024, "x"); + child.stdout.write('{"type":"notice","text":"'); + for (let index = 0; index < 1024; index++) child.stdout.write(chunk); + const error = await request; + expect(error).toMatchObject({ + name: "ProviderStreamLimitError", + code: "PROVIDER_STREAM_LINE_TOO_LARGE", + limitBytes: 64 * 1024 * 1024, + }); + expect((await exit).error).toBe(error); + await process.close(); + child.stdout.end(); + child.stderr.end(); + }); +}); diff --git a/packages/server/src/server/agent/providers/jsonl-rpc-process.ts b/packages/server/src/server/agent/providers/jsonl-rpc-process.ts index 9d8b9af623..ddf85eb316 100644 --- a/packages/server/src/server/agent/providers/jsonl-rpc-process.ts +++ b/packages/server/src/server/agent/providers/jsonl-rpc-process.ts @@ -3,7 +3,7 @@ import type { Logger } from "pino"; import { spawnProcess } from "../../../utils/spawn.js"; import { terminateWithTreeKill } from "../../../utils/tree-kill.js"; -import { JsonlFrameDecoder } from "./jsonl-frame-decoder.js"; +import { JsonlFrameDecoder, ProviderStreamLimitError } from "./jsonl-frame-decoder.js"; export { supportsJsonlRpcProtocolV2 } from "./jsonl-frame-decoder.js"; /** Default wall-clock timeout for control-plane / short RPC calls. */ @@ -81,6 +81,7 @@ export class JsonlRpcProcess { private stderrBuffer = ""; private nextRequestId = 1; private disposed = false; + private streamFailure: ProviderStreamLimitError | null = null; private exited = false; private closing: Promise | null = null; private readonly frameDecoder: JsonlFrameDecoder; @@ -90,6 +91,14 @@ export class JsonlRpcProcess { this.frameDecoder = new JsonlFrameDecoder({ frame: (message) => this.dispatchFrame(message), problem: (problem, detail) => { + if (problem === "line-too-large" && detail instanceof ProviderStreamLimitError) { + // Stop the producer: silently skipping a response or turn event loses state. + this.streamFailure = detail; + void this.close(detail).catch((err) => { + this.options.logger.warn({ err }, `Failed to close ${this.diagnosticName}`); + }); + return; + } this.options.logger.warn( { problem, detail }, `Ignoring invalid ${this.diagnosticName} frame`, @@ -98,7 +107,7 @@ export class JsonlRpcProcess { }); this.child = (options.spawn ?? spawnJsonlRpcProcess)(options.launch); this.child.stdout.on("data", (chunk) => { - this.handleStdoutChunk(chunk.toString()); + this.handleStdoutChunk(chunk); }); this.child.stderr.on("data", (chunk) => { this.stderrBuffer += chunk.toString(); @@ -114,9 +123,11 @@ export class JsonlRpcProcess { }); this.child.on("exit", (code, signal) => { this.exited = true; - const error = new Error( - `${this.diagnosticName} process exited with code ${code ?? "null"} and signal ${signal ?? "null"}\n${this.stderrBuffer}`.trim(), - ); + const error = + this.streamFailure ?? + new Error( + `${this.diagnosticName} process exited with code ${code ?? "null"} and signal ${signal ?? "null"}\n${this.stderrBuffer}`.trim(), + ); const exit = { code, signal, error }; for (const subscriber of this.exitSubscribers) { subscriber(exit); @@ -254,7 +265,7 @@ export class JsonlRpcProcess { } } - private handleStdoutChunk(chunk: string): void { + private handleStdoutChunk(chunk: Buffer | string): void { this.frameDecoder.write(chunk); } diff --git a/packages/server/src/server/workspace-registry.test.ts b/packages/server/src/server/workspace-registry.test.ts index d72da7c072..15031e7b69 100644 --- a/packages/server/src/server/workspace-registry.test.ts +++ b/packages/server/src/server/workspace-registry.test.ts @@ -116,6 +116,35 @@ describe("workspace registries", () => { expect(await projectRegistry.list()).toEqual([]); }); + test("writes once per mutation and skips missing-record mutations", async () => { + let writes = 0; + const registry = new FileBackedProjectRegistry( + path.join(tmpDir, "projects", "write-count.json"), + logger, + { + writeRecords: async (filePath, records) => { + writes++; + await writeJsonFileAtomic(filePath, records); + }, + }, + ); + const project = createPersistedProjectRecord({ + projectId: "counted", + rootPath: tmpDir, + kind: "git", + displayName: "Counted", + createdAt: "2026-03-01T00:00:00.000Z", + updatedAt: "2026-03-01T00:00:00.000Z", + }); + await registry.upsert(project); + expect(writes).toBe(1); + await registry.update("missing", (current) => current); + await registry.remove("missing"); + expect(writes).toBe(1); + await registry.update(project.projectId, (current) => ({ ...current, customName: "Changed" })); + expect(writes).toBe(2); + }); + test("preserves a concurrent project update when archiving", async () => { let pauseNextWrite = false; let releaseWrite!: () => void; From 6077bc6219c0e25003ec84a331c5f75e6cea42af Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Tue, 27 Oct 2026 09:56:36 +0700 Subject: [PATCH 039/173] Keep daemon diff highlighting responsive and bounded (#7945) * fix(server): keep diff highlighting responsive and bounded Tiny patches previously parsed both full source versions synchronously. Yield between parser work units and admit source by UTF-8 bytes, keeping large patches renderable without tokens. Cancel obsolete highlighting when a newer diff supersedes it. * fix(server): keep diff cancellation with its requester Independent commit viewers must not cancel each other. Use request-source cancellation for commit highlighting and cache invalidation for checkout highlighting. Oversized source versions use the existing budgeted hunk reconstruction so large lockfiles retain useful syntax tokens. --- .../src/__tests__/highlighter.test.ts | 54 ++++++ .../highlight/src/budgeted-highlighter.ts | 49 +++++ packages/highlight/src/index.ts | 1 + .../src/server/checkout-diff-cache.test.ts | 19 ++ .../server/src/server/checkout-diff-cache.ts | 12 +- .../checkout-diff-content.e2e.test.ts | 78 +++++++- packages/server/src/server/session.ts | 2 +- .../session/checkout/checkout-session.ts | 7 +- .../src/server/utils/diff-highlighter.test.ts | 155 +++++++++++++++- .../src/server/utils/diff-highlighter.ts | 171 +++++++++++++----- .../src/server/workspace-git-service.ts | 15 +- .../checkout-git.commit-file-diff.test.ts | 42 +++++ packages/server/src/utils/checkout-git.ts | 27 ++- 13 files changed, 567 insertions(+), 65 deletions(-) create mode 100644 packages/highlight/src/budgeted-highlighter.ts diff --git a/packages/highlight/src/__tests__/highlighter.test.ts b/packages/highlight/src/__tests__/highlighter.test.ts index fde3f9d740..095f9689a8 100644 --- a/packages/highlight/src/__tests__/highlighter.test.ts +++ b/packages/highlight/src/__tests__/highlighter.test.ts @@ -1,4 +1,6 @@ import { describe, it, expect } from "vitest"; +import { setImmediate } from "node:timers/promises"; +import { highlightCodeWithBudget, HIGHLIGHT_MAX_SOURCE_BYTES } from "../budgeted-highlighter.js"; import type { HighlightToken } from "../types.js"; import { highlightCode, highlightCodeInSteps, highlightLine } from "../highlighter.js"; @@ -420,3 +422,55 @@ describe("highlightLine", () => { expect(tokens).toEqual([{ text: "hello", style: null }]); }); }); + +describe("highlightCodeWithBudget", () => { + it("yields to IO while producing byte-identical output below the source budget", async () => { + const code = "const value = Math.max(42, 7);\n".repeat(3_000); + const expected = JSON.stringify(highlightCode(code, "file.ts")); + let ticks = 0; + let longestGap = 0; + let lastTick = performance.now(); + const timer = setInterval(() => { + const now = performance.now(); + longestGap = Math.max(longestGap, now - lastTick); + lastTick = now; + ticks++; + }, 1); + try { + const actual = await highlightCodeWithBudget(code, "file.ts", { + yieldToEventLoop: setImmediate, + }); + await new Promise((resolve) => setTimeout(resolve, 5)); + expect(ticks).toBeGreaterThan(1); + expect(longestGap).toBeLessThan(50); + expect(JSON.stringify(actual)).toBe(expected); + } finally { + clearInterval(timer); + } + }); + + it("budgets UTF-8 bytes before parsing, including multibyte text", async () => { + expect( + await highlightCodeWithBudget("é".repeat(HIGHLIGHT_MAX_SOURCE_BYTES / 2 + 1), "file.ts", { + yieldToEventLoop: setImmediate, + }), + ).toBeNull(); + expect( + await highlightCodeWithBudget("a".repeat(HIGHLIGHT_MAX_SOURCE_BYTES + 1), "file.ts", { + yieldToEventLoop: setImmediate, + }), + ).toBeNull(); + }); + + it("stops a parser that is cancelled between real event-loop turns", async () => { + const controller = new AbortController(); + const pending = highlightCodeWithBudget( + "const value = Math.max(42, 7);\n".repeat(3_000), + "file.ts", + { yieldToEventLoop: setImmediate, signal: controller.signal }, + ); + await setImmediate(); + controller.abort(); + expect(await pending).toBeNull(); + }); +}); diff --git a/packages/highlight/src/budgeted-highlighter.ts b/packages/highlight/src/budgeted-highlighter.ts new file mode 100644 index 0000000000..e949a619ff --- /dev/null +++ b/packages/highlight/src/budgeted-highlighter.ts @@ -0,0 +1,49 @@ +import { highlightCodeInSteps } from "./highlighter.js"; +import type { HighlightToken } from "./types.js"; + +// Full source, rather than patch size, bounds parser and token allocation work. +// Each token consumes a source code unit or an empty line: at most the byte cap + 1 records. +export const HIGHLIGHT_MAX_SOURCE_BYTES = 768 * 1024; +const SLICE_MS = 4; + +/** + * Returns null when source exceeds the budget or the request is cancelled. + * The host supplies a real event-loop yield (setImmediate on the daemon). + * Existing synchronous highlighting remains available for its existing consumers. + */ +export async function highlightCodeWithBudget( + code: string, + filename: string, + options: { yieldToEventLoop: () => Promise; signal?: { readonly aborted: boolean } }, +): Promise { + if (options.signal?.aborted || exceedsSourceBudget(code)) return null; + const steps = highlightCodeInSteps(code, filename); + let sliceStarted = Date.now(); + try { + for (;;) { + if (options.signal?.aborted) return null; + const step = steps.next(); + if (step.done) return step.value; + if (Date.now() - sliceStarted >= SLICE_MS) { + await options.yieldToEventLoop(); + sliceStarted = Date.now(); + } + } + } finally { + steps.return([]); + } +} + +function exceedsSourceBudget(code: string): boolean { + if (code.length > HIGHLIGHT_MAX_SOURCE_BYTES) return true; + let bytes = 0; + for (const char of code) { + const point = char.codePointAt(0)!; + if (point < 0x80) bytes++; + else if (point < 0x800) bytes += 2; + else if (point < 0x10000) bytes += 3; + else bytes += 4; + if (bytes > HIGHLIGHT_MAX_SOURCE_BYTES) return true; + } + return false; +} diff --git a/packages/highlight/src/index.ts b/packages/highlight/src/index.ts index a69820ee28..da468e2f87 100644 --- a/packages/highlight/src/index.ts +++ b/packages/highlight/src/index.ts @@ -15,3 +15,4 @@ export { isSyntaxThemeId, resolveSyntaxColors, } from "./themes.js"; +export { highlightCodeWithBudget, HIGHLIGHT_MAX_SOURCE_BYTES } from "./budgeted-highlighter.js"; diff --git a/packages/server/src/server/checkout-diff-cache.test.ts b/packages/server/src/server/checkout-diff-cache.test.ts index 37f9283320..a587f89894 100644 --- a/packages/server/src/server/checkout-diff-cache.test.ts +++ b/packages/server/src/server/checkout-diff-cache.test.ts @@ -132,3 +132,22 @@ test.each(["base", "uncommitted"] as const)( expect(await read("next", "next-after")).toEqual({ diff: "next-after" }); }, ); + +test("superseding a diff cancels its highlighting while identical readers share work", async () => { + const cache = new CheckoutDiffCache(() => 0); + const release = Promise.withResolvers<{ diff: string }>(); + let activeSignal: AbortSignal | undefined; + const load = (signal: AbortSignal) => { + activeSignal = signal; + return release.promise; + }; + const first = cache.read({ cwd: "repo", compare: { mode: "base" }, load }); + await Promise.resolve(); + expect(activeSignal).toBeDefined(); + expect(activeSignal!.aborted).toBe(false); + expect(cache.read({ cwd: "repo", compare: { mode: "base" }, load })).toBe(first); + cache.invalidate("repo", "base"); + expect(activeSignal!.aborted).toBe(true); + release.resolve({ diff: "old snapshot" }); + await first; +}); diff --git a/packages/server/src/server/checkout-diff-cache.ts b/packages/server/src/server/checkout-diff-cache.ts index 4547cdf2e5..71d7d95497 100644 --- a/packages/server/src/server/checkout-diff-cache.ts +++ b/packages/server/src/server/checkout-diff-cache.ts @@ -4,6 +4,7 @@ import type { CheckoutDiffCompare, CheckoutDiffResult } from "../utils/checkout- interface ActiveRead { promise: Promise; invalidated: boolean; + controller: AbortController; } interface CachedDiff { @@ -17,7 +18,7 @@ interface CheckoutDiffReadInput { compare: CheckoutDiffCompare; force?: boolean; reason?: string; - load: () => Promise; + load: (signal: AbortSignal) => Promise; } /** Completed payloads are bounded; active work survives invalidation and eviction. */ @@ -51,6 +52,7 @@ export class CheckoutDiffCache { if (pending) { if (force) { pending.invalidated = true; + pending.controller.abort(); this.values.delete(key); } if (!pending.invalidated) return pending.promise; @@ -66,8 +68,9 @@ export class CheckoutDiffCache { // Defer load until ownership is installed, including synchronous invalidations. const read: ActiveRead = { invalidated: false, + controller: new AbortController(), promise: Promise.resolve() - .then(load) + .then(() => load(read.controller.signal)) .then((value) => { // Never repopulate the cache with a snapshot invalidated during its build. if (!read.invalidated) @@ -86,7 +89,10 @@ export class CheckoutDiffCache { if (cachedCwd !== cwd || (cachedMode !== mode && cachedMode !== "all")) continue; this.values.delete(key); const pending = this.active.get(key); - if (pending) pending.invalidated = true; + if (pending) { + pending.invalidated = true; + pending.controller.abort(); + } } } } diff --git a/packages/server/src/server/daemon-e2e/checkout-diff-content.e2e.test.ts b/packages/server/src/server/daemon-e2e/checkout-diff-content.e2e.test.ts index 09da7506c9..fe83c21305 100644 --- a/packages/server/src/server/daemon-e2e/checkout-diff-content.e2e.test.ts +++ b/packages/server/src/server/daemon-e2e/checkout-diff-content.e2e.test.ts @@ -1,6 +1,7 @@ -import { execFileSync } from "node:child_process"; +import { execFile, execFileSync } from "node:child_process"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; -import { rm } from "node:fs/promises"; +import { rm, writeFile } from "node:fs/promises"; +import { promisify } from "node:util"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { expect, test } from "vitest"; @@ -223,3 +224,76 @@ test("All changes subscriptions refresh on file edits and commits", async () => await rm(cwd, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); } }, 60_000); + +test("large source diffs stay renderable for reads, subscriptions, and commit files", async () => { + const ctx = await createDaemonTestContext(); + const cwd = mkdtempSync(join(tmpdir(), "checkout-diff-budget-")); + const runGit = promisify(execFile); + try { + git(cwd, "init", "-b", "main"); + git(cwd, "config", "user.name", "Test"); + git(cwd, "config", "user.email", "test@example.com"); + git(cwd, "config", "core.autocrlf", "false"); + const original = "const value = Math.max(42, 7);\n".repeat(Math.ceil((5 * 1024 * 1024) / 30)); + writeFileSync(join(cwd, "generated.ts"), original); + git(cwd, "add", "."); + git(cwd, "-c", "commit.gpgsign=false", "commit", "-m", "initial"); + await writeFile(join(cwd, "generated.ts"), original.replace("42", "43")); + const pending = ctx.client.getCheckoutDiff(cwd, { mode: "uncommitted" }); + const rpcStarted = performance.now(); + await ctx.client.fetchAgents({}); + const rpcMs = performance.now() - rpcStarted; + const initial = await pending; + expect(initial.error).toBeNull(); + const check = (file: (typeof initial.files)[number] | null | undefined, value: string) => { + expect(file).toMatchObject({ path: "generated.ts", additions: 1, deletions: 1 }); + const lines = file!.hunks.flatMap((hunk) => hunk.lines); + expect(lines.filter((line) => line.type === "add").map((line) => line.content)).toEqual([ + `const value = Math.max(${value}, 7);`, + ]); + expect(lines.find((line) => line.type === "add")?.tokens).toContainEqual({ + text: value, + style: "number", + }); + }; + check(initial.files[0], "43"); + const subscription = ctx.client.observeCheckoutDiff(cwd, { mode: "uncommitted" }); + try { + let latest = await subscription.ready; + check(latest.files[0], "43"); + subscription.subscribe({ + snapshot: (snapshot) => { + latest = snapshot; + }, + update: (message) => { + if (message.type === "checkout_diff_update") latest = message.payload; + }, + }); + await writeFile(join(cwd, "generated.ts"), original.replace("42", "44")); + await expect + .poll( + () => + latest.files[0]?.hunks.flatMap((hunk) => hunk.lines).find((line) => line.type === "add") + ?.content, + { timeout: 15_000 }, + ) + .toBe("const value = Math.max(44, 7);"); + check(latest.files[0], "44"); + } finally { + await subscription.release(); + } + await runGit("git", ["add", "."], { cwd }); + await runGit("git", ["-c", "commit.gpgsign=false", "commit", "-m", "edit"], { cwd }); + const { stdout } = await runGit("git", ["rev-parse", "HEAD"], { cwd }); + const commit = await ctx.client.getCommitFileDiff(cwd, stdout.trim(), "generated.ts"); + check(commit.file, "44"); + console.info({ + sourceBytes: Buffer.byteLength(original), + cheapRpcMs: rpcMs, + isolatedDaemonPort: ctx.daemon.port, + }); + } finally { + await ctx.cleanup(); + await rm(cwd, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); + } +}, 60_000); diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index f573b1dd95..db4939aa31 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -2964,7 +2964,7 @@ export class Session { case "checkout.commits.list.request": return this.checkoutSession.handleCommitsListRequest(msg); case "checkout.commits.file_diff.request": - return this.checkoutSession.handleCommitFileDiffRequest(msg); + return this.checkoutSession.handleCommitFileDiffRequest(msg, this.delivery.requestSignal); case "validate_branch_request": return this.checkoutSession.handleValidateBranchRequest(msg); case "branch_suggestions_request": diff --git a/packages/server/src/server/session/checkout/checkout-session.ts b/packages/server/src/server/session/checkout/checkout-session.ts index 419d418050..ceb69e9623 100644 --- a/packages/server/src/server/session/checkout/checkout-session.ts +++ b/packages/server/src/server/session/checkout/checkout-session.ts @@ -290,7 +290,10 @@ export class CheckoutSession { } } - async handleCommitFileDiffRequest(msg: CheckoutCommitFileDiffRequest): Promise { + async handleCommitFileDiffRequest( + msg: CheckoutCommitFileDiffRequest, + signal: AbortSignal, + ): Promise { const { cwd, sha, path, requestId } = msg; try { @@ -298,7 +301,7 @@ export class CheckoutSession { if (path.length === 0 || isAbsolute(path) || path.split(/[\\/]/).includes("..")) { throw new Error(`Invalid path: ${path}`); } - const file = await getCommitFileDiff({ cwd: expandTilde(cwd), sha, path }); + const file = await getCommitFileDiff({ cwd: expandTilde(cwd), sha, path, signal }); this.host.emit({ type: "checkout.commits.file_diff.response", payload: { cwd, sha, path, file, error: null, requestId }, diff --git a/packages/server/src/server/utils/diff-highlighter.test.ts b/packages/server/src/server/utils/diff-highlighter.test.ts index fda98d6cbf..3ecb0372ad 100644 --- a/packages/server/src/server/utils/diff-highlighter.test.ts +++ b/packages/server/src/server/utils/diff-highlighter.test.ts @@ -1,7 +1,11 @@ -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdtempSync, rmSync, writeFileSync, readFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; +import { setImmediate } from "node:timers/promises"; +import { performance } from "node:perf_hooks"; +import { SessionDelivery } from "../session/owned-subscriptions/index.js"; +import { highlightCode, highlightCodeWithBudget } from "@getpaseo/highlight"; import { parseDiff, reconstructNewFile, @@ -819,3 +823,152 @@ index 1111111..2222222 100644 } }); }); + +describe("diff highlighting budget", () => { + it.each(["supplied", "local"] as const)( + "keeps a one-line diff on a 5 MiB %s source responsive using hunk tokens", + async (source) => { + const cwd = mkdtempSync(join(tmpdir(), "diff-highlight-budget-")); + const oldFileContent = "const value = Math.max(42, 7);\n".repeat( + Math.ceil((5 * 1024 * 1024) / 30), + ); + const newFileContent = oldFileContent.replace("42", "43"); + writeFileSync(join(cwd, "example.ts"), newFileContent); + const file = parseDiff(`diff --git a/example.ts b/example.ts +--- a/example.ts ++++ b/example.ts +@@ -1 +1 @@ +-const value = Math.max(42, 7); ++const value = Math.max(43, 7);`)[0]; + let lastTick = performance.now(); + let longestGap = 0; + const timer = setInterval(() => { + const now = performance.now(); + longestGap = Math.max(longestGap, now - lastTick); + lastTick = now; + }, 1); + try { + await setImmediate(); + const highlighted = await highlightDiffWithFileContent( + file, + cwd, + source === "supplied" ? { oldFileContent } : {}, + ); + await new Promise((resolve) => setTimeout(resolve, 5)); + console.info({ sourceBytes: Buffer.byteLength(oldFileContent), longestGap }); + expect(longestGap).toBeLessThan(50); + expect(highlighted).toEqual(highlightDiffFromHunks(file)); + } finally { + clearInterval(timer); + rmSync(cwd, { recursive: true, force: true }); + } + }, + 30_000, + ); + + it("preserves byte-identical tokens below the budget, including multiline syntax", async () => { + const oldFileContent = "/*\nold comment\n*/\nconst value = 42;"; + const newFileContent = oldFileContent.replace("old", "new"); + const file = parseDiff(`diff --git a/example.ts b/example.ts +--- a/example.ts ++++ b/example.ts +@@ -2 +2 @@ +-old comment ++new comment`)[0]; + const highlighted = await highlightDiffWithFileContent(file, ".", { + oldFileContent, + newFileContent, + }); + expect(JSON.stringify(highlighted.hunks[0].lines[1].tokens)).toBe( + JSON.stringify(highlightCode(oldFileContent, file.path)[1]), + ); + expect(JSON.stringify(highlighted.hunks[0].lines[2].tokens)).toBe( + JSON.stringify(highlightCode(newFileContent, file.path)[1]), + ); + }); +}); + +it("disconnecting the requesting source stops a parser between highlight steps", async () => { + const delivery = new SessionDelivery(() => {}); + const source = {}; + delivery.attach(source, true); + const yielded = Promise.withResolvers(); + let result: Awaited> = []; + const pending = delivery.request(source, { type: "ping", requestId: "highlight" }, async () => { + result = await highlightCodeWithBudget( + "const value = Math.max(42, 7);\n".repeat(3_000), + "file.ts", + { + signal: delivery.requestSignal, + yieldToEventLoop: () => { + yielded.resolve(); + return setImmediate(); + }, + }, + ); + }); + await yielded.promise; + await delivery.detach(source); + await pending; + expect(result).toBeNull(); +}); + +it("keeps real session.ts diffs highlighted and byte-identical under the source budget", async () => { + const cwd = mkdtempSync(join(tmpdir(), "diff-highlight-real-source-")); + try { + const oldFileContent = readFileSync(new URL("../session.ts", import.meta.url), "utf8"); + const newFileContent = oldFileContent.replace( + "WorkspaceRuntimeStore", + "WorkspaceRuntimeSnapshot", + ); + writeFileSync(join(cwd, "session.ts"), newFileContent); + const oldLine = oldFileContent.split("\n")[0]; + const newLine = newFileContent.split("\n")[0]; + const [file] = parseDiff(`diff --git a/session.ts b/session.ts +--- a/session.ts ++++ b/session.ts +@@ -1 +1 @@ +-${oldLine} ++${newLine}`); + const highlighted = await highlightDiffWithFileContent(file, cwd, { oldFileContent }); + const removed = highlighted.hunks[0].lines.find((line) => line.type === "remove"); + const added = highlighted.hunks[0].lines.find((line) => line.type === "add"); + expect(removed?.tokens).toEqual(highlightCode(oldFileContent, "session.ts")[0]); + expect(added?.tokens).toEqual(highlightCode(newFileContent, "session.ts")[0]); + expect(added?.tokens?.some((token) => token.style !== null)).toBe(true); + } finally { + rmSync(cwd, { recursive: true, force: true }); + } +}); + +it("highlights a one-line hunk from an over-budget JSON source without blocking the loop", async () => { + const cwd = mkdtempSync(join(tmpdir(), "diff-highlight-large-json-")); + const oldFileContent = `{\n${' "value": 42,\n'.repeat(100_000)} "last": true\n}`; + const newFileContent = oldFileContent.replace("42", "43"); + writeFileSync(join(cwd, "package-lock.json"), newFileContent); + const [file] = parseDiff(`diff --git a/package-lock.json b/package-lock.json +--- a/package-lock.json ++++ b/package-lock.json +@@ -2 +2 @@ +- "value": 42, ++ "value": 43,`); + let last = performance.now(), + longestGap = 0; + const timer = setInterval(() => { + const now = performance.now(); + longestGap = Math.max(longestGap, now - last); + last = now; + }, 1); + try { + const result = await highlightDiffWithFileContent(file, cwd, { oldFileContent }); + await new Promise((resolve) => setTimeout(resolve, 5)); + expect(longestGap).toBeLessThan(50); + expect(result.hunks[0].lines.find((line) => line.type === "add")?.tokens).toContainEqual({ + text: "43", + style: "number", + }); + } finally { + clearInterval(timer); + rmSync(cwd, { recursive: true, force: true }); + } +}); diff --git a/packages/server/src/server/utils/diff-highlighter.ts b/packages/server/src/server/utils/diff-highlighter.ts index 3c2df279e2..e3a0460322 100644 --- a/packages/server/src/server/utils/diff-highlighter.ts +++ b/packages/server/src/server/utils/diff-highlighter.ts @@ -1,6 +1,14 @@ -import { readFile } from "node:fs/promises"; +import { open } from "node:fs/promises"; +import { constants } from "node:fs"; +import { setImmediate } from "node:timers/promises"; import { resolve } from "node:path"; -import { highlightCode, isLanguageSupported, type HighlightToken } from "@getpaseo/highlight"; +import { + highlightCode, + highlightCodeWithBudget, + HIGHLIGHT_MAX_SOURCE_BYTES, + isLanguageSupported, + type HighlightToken, +} from "@getpaseo/highlight"; import { unquoteGitPath } from "../../utils/git-quoted-path.js"; const MAX_DIFF_HIGHLIGHT_LINE_CHARS = 10_000; @@ -30,11 +38,13 @@ export interface ParsedDiffFile { } interface HighlightDiffWithFileContentOptions { + signal?: AbortSignal; oldFileContent?: string | null; newFileContent?: string | null; } interface ParseAndHighlightDiffOptions { + signal?: AbortSignal; getOldFileContent?: (file: ParsedDiffFile) => Promise; getNewFileContent?: (file: ParsedDiffFile) => Promise; } @@ -269,20 +279,71 @@ function buildTokenLookup( return lookup; } -function buildFullFileTokenLookup( +async function buildFullFileTokenLookup( fileContent: string, path: string, -): Map | null { - if (hasOversizedLine(fileContent)) return null; + signal?: AbortSignal, +): Promise | null> { + const highlighted = await highlightCodeWithBudget(fileContent, path, { + yieldToEventLoop: setImmediate, + signal, + }); + if (!highlighted) return null; + return new Map(highlighted.map((tokens, index) => [index + 1, tokens])); +} - const lookup = new Map(); - const highlighted = highlightCode(fileContent, path); - - for (let i = 0; i < highlighted.length; i++) { - lookup.set(i + 1, highlighted[i]); +async function readHighlightSource(path: string): Promise { + let handle; + try { + handle = await open(path, constants.O_RDONLY | constants.O_NONBLOCK); + const stat = await handle.stat(); + if (!stat.isFile() || stat.size > HIGHLIGHT_MAX_SOURCE_BYTES) return null; + const buffer = Buffer.alloc(Math.min(stat.size, HIGHLIGHT_MAX_SOURCE_BYTES) + 1); + let offset = 0; + while (offset < buffer.length) { + const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, null); + if (bytesRead === 0) break; + offset += bytesRead; + } + // A full buffer includes the extra byte: the source grew after stat. + return offset === buffer.length ? null : buffer.toString("utf8", 0, offset); + } catch { + return null; + } finally { + await handle?.close(); } +} - return lookup; +function exceedsSourceBudget(content: string): boolean { + return ( + content.length > HIGHLIGHT_MAX_SOURCE_BYTES || + Buffer.byteLength(content) > HIGHLIGHT_MAX_SOURCE_BYTES + ); +} + +async function buildBudgetedReconstructedTokens(file: ParsedDiffFile, signal?: AbortSignal) { + const newLines = reconstructNewFile(file.hunks); + const oldLines = reconstructOldFile(file.hunks); + const build = async (lines: Map) => { + // Sparse hunks can be far apart. Admit the span before filling its gaps. + const numbers = Array.from(lines.keys()); + if (numbers.length && numbers[numbers.length - 1] - numbers[0] > HIGHLIGHT_MAX_SOURCE_BYTES) + return null; + let bytes = 0; + for (const line of lines.values()) { + bytes += Buffer.byteLength(line) + 1; + if (bytes > HIGHLIGHT_MAX_SOURCE_BYTES) return null; + } + const highlighted = await highlightCodeWithBudget(buildFileContent(lines), file.path, { + yieldToEventLoop: setImmediate, + signal, + }); + return highlighted ? buildTokenLookup(lines, highlighted) : null; + }; + const newTokensByLine = await build(newLines); + if (!newTokensByLine) return null; + const oldTokensByLine = await build(oldLines); + return oldTokensByLine ? { newTokensByLine, oldTokensByLine } : null; } function buildReconstructedTokenLookups(file: ParsedDiffFile): { @@ -328,36 +389,50 @@ export async function highlightDiffWithFileContent( cwd: string, options: HighlightDiffWithFileContentOptions = {}, ): Promise { - if (!isLanguageSupported(file.path) || hasOversizedDiffLine(file)) { - return file; - } + if (!isDiffHighlightEligible(file, options)) return file; - let newTokensByLine: Map | null = null; - const oldTokensByLine = - typeof options.oldFileContent === "string" - ? buildFullFileTokenLookup(options.oldFileContent, file.path) - : null; - if (typeof options.newFileContent === "string") { - newTokensByLine = buildFullFileTokenLookup(options.newFileContent, file.path); - } else { - try { - const fileContent = await readFile(resolve(cwd, file.path), "utf-8"); - newTokensByLine = buildFullFileTokenLookup(fileContent, file.path); - } catch { - // Deleted or unavailable files use reconstructed tokens below. - } - } + const newContent = + typeof options.newFileContent === "string" + ? options.newFileContent + : await readHighlightSource(resolve(cwd, file.path)); + if (options.signal?.aborted) return file; - if (newTokensByLine && oldTokensByLine) - return applyTokensToHunks(file, newTokensByLine, oldTokensByLine); - const reconstructedTokens = buildReconstructedTokenLookups(file); + const oldTokens = await highlightAvailableSource( + options.oldFileContent, + file.path, + options.signal, + ); + if (options.signal?.aborted) return file; + const newTokens = await highlightAvailableSource(newContent, file.path, options.signal); + if (options.signal?.aborted) return file; + if (oldTokens && newTokens) return applyTokensToHunks(file, newTokens, oldTokens); + const reconstructed = await buildBudgetedReconstructedTokens(file, options.signal); + if (!reconstructed || options.signal?.aborted) return file; return applyTokensToHunks( file, - newTokensByLine ?? reconstructedTokens.newTokensByLine, - oldTokensByLine ?? reconstructedTokens.oldTokensByLine, + newTokens ?? reconstructed.newTokensByLine, + oldTokens ?? reconstructed.oldTokensByLine, ); } +function isDiffHighlightEligible( + file: ParsedDiffFile, + options: HighlightDiffWithFileContentOptions, +): boolean { + return !options.signal?.aborted && isLanguageSupported(file.path) && !hasOversizedDiffLine(file); +} + +async function highlightAvailableSource( + content: string | null | undefined, + path: string, + signal?: AbortSignal, +): Promise | null> { + // Preserve the existing hunk-context fallback for oversized individual lines. + if (typeof content !== "string" || exceedsSourceBudget(content) || hasOversizedLine(content)) + return null; + return buildFullFileTokenLookup(content, path, signal); +} + function applyTokensToHunks( file: ParsedDiffFile, newTokensByLine: Map, @@ -406,20 +481,24 @@ export async function parseAndHighlightDiff( ): Promise { const files = parseDiff(diffText); - const highlightedFiles = await Promise.all( - files.map(async (file) => { - const [oldFileContent, newFileContent] = await Promise.all([ - options.getOldFileContent?.(file), - options.getNewFileContent?.(file), - ]); - - return highlightDiffWithFileContent(file, cwd, { + const highlightedFiles: ParsedDiffFile[] = []; + for (const file of files) { + if (options.signal?.aborted) { + highlightedFiles.push(file); + continue; + } + const [oldFileContent, newFileContent] = await Promise.all([ + options.getOldFileContent?.(file), + options.getNewFileContent?.(file), + ]); + highlightedFiles.push( + await highlightDiffWithFileContent(file, cwd, { oldFileContent: oldFileContent ?? undefined, newFileContent: newFileContent ?? undefined, - }); - }), - ); - + signal: options.signal, + }), + ); + } return highlightedFiles; } diff --git a/packages/server/src/server/workspace-git-service.ts b/packages/server/src/server/workspace-git-service.ts index dcd2ead214..493daa1ddd 100644 --- a/packages/server/src/server/workspace-git-service.ts +++ b/packages/server/src/server/workspace-git-service.ts @@ -815,11 +815,16 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { cwd: normalizedCwd, compare: normalizedOptions, ...readOptions, - load: () => - this.deps.getCheckoutDiff(normalizedCwd, normalizedOptions, { - paseoHome: this.paseoHome, - worktreesRoot: this.worktreesRoot, - }), + load: (signal) => + this.deps.getCheckoutDiff( + normalizedCwd, + normalizedOptions, + { + paseoHome: this.paseoHome, + worktreesRoot: this.worktreesRoot, + }, + signal, + ), }); } diff --git a/packages/server/src/utils/checkout-git.commit-file-diff.test.ts b/packages/server/src/utils/checkout-git.commit-file-diff.test.ts index 576e9b0c80..efda5be92c 100644 --- a/packages/server/src/utils/checkout-git.commit-file-diff.test.ts +++ b/packages/server/src/utils/checkout-git.commit-file-diff.test.ts @@ -4,6 +4,7 @@ import { tmpdir } from "os"; import { join } from "path"; import { afterEach, describe, expect, it } from "vitest"; import { getCommitFileDiff, listCheckoutCommits } from "./checkout-git.js"; +import { SessionDelivery } from "../server/session/owned-subscriptions/index.js"; import { startGitCommandMetrics, stopGitCommandMetrics } from "./run-git-command.js"; const tempDirs: string[] = []; @@ -302,3 +303,44 @@ describe("getCommitFileDiff", () => { expect(file?.deletions).toBe(0); }); }); + +it("identical commit-file requests from two requesters both retain syntax tokens", async () => { + const repoDir = initRepo(); + const original = "const value = Math.max(42, 7);\n".repeat(3_000); + commitFile(repoDir, "file.ts", original, "initial"); + commitFile(repoDir, "file.ts", original.replace("42", "43"), "edit"); + const input = { cwd: repoDir, sha: headSha(repoDir), path: "file.ts" }; + const results = await Promise.all([getCommitFileDiff(input), getCommitFileDiff(input)]); + for (const file of results) { + expect( + file?.hunks[0].lines + .find((line) => line.type === "add") + ?.tokens?.some((token) => token.style !== null), + ).toBe(true); + } +}); + +it("a disconnected requester cancels commit highlighting before its sources arrive", async () => { + const repoDir = initRepo(); + commitFile(repoDir, "file.ts", "const value = 42;\n", "initial"); + commitFile(repoDir, "file.ts", "const value = 43;\n", "edit"); + const delivery = new SessionDelivery(() => {}); + const source = {}; + delivery.attach(source, true); + const request = { + type: "checkout.commits.file_diff.request" as const, + cwd: repoDir, + sha: headSha(repoDir), + path: "file.ts", + requestId: "disconnect", + }; + const results: Awaited>[] = []; + const pending = delivery.request(source, request, async () => { + results.push(await getCommitFileDiff({ ...request, signal: delivery.requestSignal })); + }); + await delivery.detach(source); + await pending; + expect( + results[0]?.hunks.flatMap((hunk) => hunk.lines).every((line) => line.tokens === undefined), + ).toBe(true); +}); diff --git a/packages/server/src/utils/checkout-git.ts b/packages/server/src/utils/checkout-git.ts index fbbb494b4a..a39b6445e2 100644 --- a/packages/server/src/utils/checkout-git.ts +++ b/packages/server/src/utils/checkout-git.ts @@ -2719,10 +2719,12 @@ export async function getCommitFileDiff({ cwd, sha, path, + signal, }: { cwd: string; sha: string; path: string; + signal?: AbortSignal; }): Promise { const worktreeRoot = await requireGitWorktreeRoot(cwd); const renames = await getCommitRenames(worktreeRoot, sha); @@ -2750,6 +2752,7 @@ export async function getCommitFileDiff({ } const parsedFiles = await parseAndHighlightDiff(stdout, worktreeRoot, { + signal, getOldFileContent: (file) => readGitFileContentAtRef(worktreeRoot, `${sha}^`, file.path), getNewFileContent: (file) => readGitFileContentAtRef(worktreeRoot, sha, file.path), }); @@ -3132,6 +3135,7 @@ export function warmCheckoutShortstatInBackground( } interface AppendStructuredTrackedDiffsInput { + signal?: AbortSignal; cwd: string; trackedChanges: CheckoutFileChange[]; trackedNumstatByPath: Map; @@ -3147,6 +3151,7 @@ interface AppendStructuredTrackedDiffsInput { } async function buildHighlightedTrackedDiffFile(input: { + signal?: AbortSignal; cwd: string; change: CheckoutFileChange; parsedFile: ParsedDiffFile; @@ -3169,6 +3174,7 @@ async function buildHighlightedTrackedDiffFile(input: { : null, ]); const highlightedFile = await highlightDiffWithFileContent(parsedFile, cwd, { + signal: input.signal, oldFileContent, newFileContent, }); @@ -3254,6 +3260,7 @@ async function appendStructuredTrackedDiffs( const parsedFile = parsedTrackedByPath.get(change.path); if (parsedFile) { const file = await buildHighlightedTrackedDiffFile({ + signal: input.signal, cwd, change, parsedFile, @@ -3295,6 +3302,7 @@ async function appendStructuredTrackedDiffs( } interface ProcessUntrackedChangeInput { + signal?: AbortSignal; cwd: string; change: CheckoutFileChange; ignoreWhitespace: boolean; @@ -3345,7 +3353,7 @@ async function processUntrackedChange(input: ProcessUntrackedChangeInput): Promi } appendDiff(text); - const parsed = await parseAndHighlightDiff(text, cwd); + const parsed = await parseAndHighlightDiff(text, cwd, { signal: input.signal }); const parsedFile = parsed[0] ?? ({ @@ -3541,6 +3549,7 @@ export async function getCheckoutDiff( cwd: string, compare: CheckoutDiffCompare, context?: CheckoutContext, + signal?: AbortSignal, ): Promise { cwd = await requireGitWorktreeRoot(cwd); @@ -3552,10 +3561,15 @@ export async function getCheckoutDiff( const index = compare.mode === "all" ? await prepareAllChangesIndex(cwd, refsForDiff.baseRef) : null; try { - return await readCheckoutDiff(cwd, compare, { - ...refsForDiff, - indexEnv: index ? { GIT_INDEX_FILE: index.indexFile } : undefined, - }); + return await readCheckoutDiff( + cwd, + compare, + { + ...refsForDiff, + indexEnv: index ? { GIT_INDEX_FILE: index.indexFile } : undefined, + }, + signal, + ); } finally { await index?.cleanup(); } @@ -3565,6 +3579,7 @@ async function readCheckoutDiff( cwd: string, compare: CheckoutDiffCompare, refsForDiff: CheckoutDiffRefs, + signal?: AbortSignal, ): Promise { const ignoreWhitespace = compare.ignoreWhitespace === true; let effectiveRefsForDiff = refsForDiff; @@ -3625,6 +3640,7 @@ async function readCheckoutDiff( if (compare.includeStructured) { const didAppendTrackedDiffs = await appendStructuredTrackedDiffs({ + signal, cwd, trackedChanges, trackedNumstatByPath: trackedDiff.trackedNumstatByPath, @@ -3652,6 +3668,7 @@ async function readCheckoutDiff( break; } const didAppendUntrackedDiff = await processUntrackedChange({ + signal, cwd, change, ignoreWhitespace, From a25f4f506541ebadcb3175be5ee013fcf1ca4dbc Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Tue, 27 Oct 2026 09:56:42 +0700 Subject: [PATCH 040/173] perf(server): serve timeline pages from retained projection (#7958) * perf(server): select timeline pages from retained projection Keep page selection and source coverage indexes with the retained projection so bounded fetches and last-message lookups do not copy or reproject history. Omitted after limits use the existing 200-item store default; explicit zero remains unlimited for released CLI clients. * test(server): keep timeline page oracle outside production builds --- .../server/agent/agent-timeline-store.test.ts | 153 ++++++++ .../src/server/agent/agent-timeline-store.ts | 23 +- .../test-utils/timeline-page-reference.ts | 249 +++++++++++++ .../server/agent/timeline-projection.test.ts | 2 +- .../src/server/agent/timeline-projection.ts | 330 ++++++++++-------- .../daemon-e2e/cli-logs-follow.e2e.test.ts | 50 +++ packages/server/src/server/session.ts | 4 +- 7 files changed, 638 insertions(+), 173 deletions(-) create mode 100644 packages/server/src/server/agent/test-utils/timeline-page-reference.ts diff --git a/packages/server/src/server/agent/agent-timeline-store.test.ts b/packages/server/src/server/agent/agent-timeline-store.test.ts index 895aec2684..eb46916fe3 100644 --- a/packages/server/src/server/agent/agent-timeline-store.test.ts +++ b/packages/server/src/server/agent/agent-timeline-store.test.ts @@ -1,4 +1,6 @@ import { describe, expect, it } from "vitest"; +import { selectReferenceProjectedTimelinePage } from "./test-utils/timeline-page-reference.js"; +import type { AgentTimelineItem } from "./agent-sdk-types.js"; import { InMemoryAgentTimelineStore } from "./agent-timeline-store.js"; describe("InMemoryAgentTimelineStore", () => { @@ -177,7 +179,10 @@ describe("projected sequence ownership", () => { store.append("a", { type: "assistant_message", text: "Answer" }); store.append("a", { ...tool, status: "completed" }); store.initialize("b", { rows: store.getRows("a") }); + expect(store.getLastItem("b")).toMatchObject({ type: "tool_call", status: "completed" }); + expect(store.getLastAssistantMessage("b")).toBe("Answer"); expect(store.append("b", { type: "user_message", text: "next" }).seq).toBe(4); + expect(store.getLastItem("b")).toEqual({ type: "user_message", text: "next" }); expect(store.fetch("b").rows.map((row) => row.seqStart)).toEqual([1, 2, 4]); }); it("returns the last projected assistant message without joining different messages", () => { @@ -211,3 +216,151 @@ it("includes transitive tool updates in a contiguous projected tail", () => { expect(tail.rows.map((row) => row.seqStart)).toEqual([1, 2, 3, 5]); expect(tail).toMatchObject({ startSeq: 1, endSeq: 6, hasOlder: false }); }); + +it("serves tail 200 from 100,000 retained rows without stalling the loop", async () => { + const store = new InMemoryAgentTimelineStore(); + store.initialize("large"); + for (let index = 0; index < 100_000; index++) { + store.append("large", { type: "user_message", text: String(index) }); + } + // Generation and its GC are outside the measured request window. + await new Promise((resolve) => setImmediate(resolve)); + const started = performance.now(); + const probe = new Promise((resolve) => + setImmediate(() => resolve(performance.now() - started)), + ); + let page = store.fetch("large", { limit: 200 }); + for (let repeat = 1; repeat < 8; repeat++) page = store.fetch("large", { limit: 200 }); + const duration = performance.now() - started; + const loopGap = await probe; + console.info({ duration, loopGap }); + expect(page.rows).toHaveLength(200); + expect(page.startSeq).toBe(99_801); + expect(page.endSeq).toBe(100_000); + // CI runners can pause for scheduling/GC; the local per-request 2 ms gate + // is measured separately. Eight requests amplify the old full-history work. + expect(duration).toBeLessThan(50); + expect(loopGap).toBeLessThan(50); +}); + +it("matches the previous reprojecting selector on seeded randomized timelines", () => { + let seed = 0x76aabbcc; + const random = (bound: number) => { + seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; + return Math.floor((seed / 0x1_0000_0000) * bound); + }; + for (let scenario = 0; scenario < 100; scenario++) { + const store = new InMemoryAgentTimelineStore(); + store.initialize("a", { epoch: "e" }); + for (let seq = 1; seq <= 100; seq++) { + const identity = String(random(8)); + const text = String(seq); + const items: AgentTimelineItem[] = [ + { type: "user_message", text }, + { type: "assistant_message", text }, + { type: "assistant_message", text, messageId: identity }, + { type: "reasoning", text }, + { + type: "tool_call", + callId: identity, + name: "shell", + status: "running", + error: null, + detail: { type: "plain_text", label: text }, + }, + { + type: "plugin", + id: identity, + pluginId: "test", + kind: "state", + version: 1, + data: { text }, + }, + ]; + store.append("a", items[random(items.length)], { turnId: String(random(3)) }); + } + // Include rehydration of already-projected rows, with non-monotonic seqEnd. + store.initialize("b", { rows: store.getRows("a"), epoch: "e" }); + for (const agentId of ["a", "b"]) { + assertSelectionMatchesReference(store, agentId); + store.append(agentId, { type: "assistant_message", text: "later" }); + assertSelectionMatchesReference(store, agentId); + } + } +}); + +function assertSelectionMatchesReference(store: InMemoryAgentTimelineStore, agentId: string): void { + for (const direction of ["tail", "before", "after"] as const) { + for (const limit of [0, 1, 7, 200]) { + for (const cursorSeq of [0, 1, 25, 50, 99, 100, 150]) { + const actual = store.fetch(agentId, { + direction, + limit, + cursor: { epoch: "e", seq: cursorSeq }, + }); + const expected = selectReferenceProjectedTimelinePage({ + rows: store.getRows(agentId), + bounds: actual.window, + direction, + limit, + cursorSeq, + }); + expect({ + ...expected, + entries: undefined, + rows: expected.entries.map((entry) => Object.assign({ seq: entry.seqEnd }, entry)), + }).toEqual({ + entries: undefined, + rows: actual.rows, + startSeq: actual.startSeq, + endSeq: actual.endSeq, + hasOlder: actual.hasOlder, + hasNewer: actual.hasNewer, + }); + } + } + } +} + +it("continues a scroll across appends and lifecycle collapse without losing source coverage", () => { + const store = new InMemoryAgentTimelineStore(); + store.initialize("a", { epoch: "e" }); + const tool: AgentTimelineItem = { + type: "tool_call", + callId: "t", + name: "shell", + status: "running", + error: null, + detail: { type: "plain_text", label: "work" }, + }; + store.append("a", tool); + for (let seq = 2; seq <= 5; seq++) store.append("a", { type: "user_message", text: String(seq) }); + const first = store.fetch("a", { direction: "after", cursor: { epoch: "e", seq: 0 }, limit: 2 }); + expect(first.endSeq).toBe(2); + store.append("a", { ...tool, status: "completed" }); + store.append("a", { type: "assistant_message", text: "Done" }); + expect(first.rows[0].item).toMatchObject({ status: "running" }); + const second = store.fetch("a", { + direction: "after", + cursor: { epoch: "e", seq: first.endSeq! }, + limit: 2, + }); + expect(second.rows.map((row) => row.seqStart)).toEqual([3, 4]); + expect(second.endSeq).toBe(4); + const third = store.fetch("a", { + direction: "after", + cursor: { epoch: "e", seq: second.endSeq! }, + limit: 2, + }); + expect(third.rows.map((row) => row.seqStart)).toEqual([1, 5]); + expect(third.rows[0].item).toMatchObject({ status: "completed" }); + expect(third.endSeq).toBe(6); + const last = store.fetch("a", { + direction: "after", + cursor: { epoch: "e", seq: third.endSeq! }, + limit: 2, + }); + expect(last.rows.map((row) => row.item)).toEqual([{ type: "assistant_message", text: "Done" }]); + expect(last.endSeq).toBe(7); + expect(last.hasNewer).toBe(false); +}); diff --git a/packages/server/src/server/agent/agent-timeline-store.ts b/packages/server/src/server/agent/agent-timeline-store.ts index 6a37e11ef0..b9727e33e9 100644 --- a/packages/server/src/server/agent/agent-timeline-store.ts +++ b/packages/server/src/server/agent/agent-timeline-store.ts @@ -1,9 +1,5 @@ import { randomUUID } from "node:crypto"; -import { - TimelineProjection, - selectProjectedTimelinePage, - type ProjectedTimelineRow, -} from "./timeline-projection.js"; +import { TimelineProjection, type ProjectedTimelineRow } from "./timeline-projection.js"; import type { AgentTimelineItem } from "./agent-sdk-types.js"; import type { AgentTimelineFetchOptions, @@ -43,8 +39,7 @@ export class InMemoryAgentTimelineStore { ? options.rows.map(cloneRow) : this.buildRowsFromItems(options?.items ?? [], options?.nextSeq ?? 1, timestamp); const nextSeq = rows.reduce((next, row) => Math.max(next, row.seq + 1), options?.nextSeq ?? 1); - const projection = new TimelineProjection(); - for (const row of rows) projection.append(row); + const projection = new TimelineProjection(rows); this.states.set(agentId, { epoch: options?.epoch ?? randomUUID(), projection, @@ -97,18 +92,17 @@ export class InMemoryAgentTimelineStore { const state = this.requireState(agentId); const direction = options?.direction ?? "tail"; const cursor = options?.cursor; - const rows = state.projection.getRows(); + const hasRows = state.minSeq !== 0; const window = { minSeq: state.minSeq, maxSeq: state.nextSeq - 1, nextSeq: state.nextSeq }; const staleCursor = cursor !== undefined && cursor.epoch !== state.epoch; const gap = !staleCursor && direction === "after" && cursor !== undefined && - rows.length > 0 && + hasRows && cursor.seq < state.minSeq - 1; const reset = staleCursor || gap; - const page = selectProjectedTimelinePage({ - rows, + const page = state.projection.selectPage({ bounds: window, direction: reset ? "tail" : direction, cursorSeq: cursor?.seq, @@ -150,14 +144,11 @@ export class InMemoryAgentTimelineStore { getLastItem(agentId: string): AgentTimelineItem | null { const state = this.requireState(agentId); - return state.projection.getRows().find((row) => row.seqEnd === state.nextSeq - 1)?.item ?? null; + return state.projection.getLastItem(state.nextSeq - 1); } getLastAssistantMessage(agentId: string): string | null { - const row = this.requireState(agentId) - .projection.getRows() - .findLast((candidate) => candidate.item.type === "assistant_message"); - return row?.item.type === "assistant_message" ? row.item.text : null; + return this.requireState(agentId).projection.getLastAssistantMessage(); } private requireState(agentId: string): AgentTimelineState { diff --git a/packages/server/src/server/agent/test-utils/timeline-page-reference.ts b/packages/server/src/server/agent/test-utils/timeline-page-reference.ts new file mode 100644 index 0000000000..8e9ab228a6 --- /dev/null +++ b/packages/server/src/server/agent/test-utils/timeline-page-reference.ts @@ -0,0 +1,249 @@ +// Frozen pre-index page selection: differential oracle for retained projection tests. +import type { AgentTimelineRow } from "../agent-timeline-store-types.js"; +import { + TimelineProjection, + projectTimelineRows, + type TimelineProjectionEntry, + type ProjectedTimelineRow, + type TimelineLimitDirection, + type ProjectedTimelinePageSelection, +} from "../timeline-projection.js"; + +function makeCanonicalEntries(rows: readonly AgentTimelineRow[]): TimelineProjectionEntry[] { + return rows.map((row) => { + if ("seqStart" in row) return { ...(row as ProjectedTimelineRow) }; + return { + item: row.item, + timestamp: row.timestamp, + ...(row.turnId ? { turnId: row.turnId } : {}), + ...(row.providerMessageId ? { providerMessageId: row.providerMessageId } : {}), + seqStart: row.seq, + seqEnd: row.seq, + sourceSeqRanges: [{ startSeq: row.seq, endSeq: row.seq }], + collapsed: [], + }; + }); +} + +function getTimelineBounds( + rows: readonly AgentTimelineRow[], +): { minSeq: number; maxSeq: number } | null { + const first = rows[0]; + const last = rows[rows.length - 1]; + if (!first || !last) { + return null; + } + const entries = makeCanonicalEntries(rows); + return { + minSeq: entries.reduce((min, e) => Math.min(min, e.seqStart), Infinity), + maxSeq: entries.reduce((max, e) => Math.max(max, e.seqEnd), 0), + }; +} + +function firstSourceSeqInRange( + entry: TimelineProjectionEntry, + startSeq: number, + endSeq: number, +): number | null { + for (const range of entry.sourceSeqRanges) { + const firstSeq = Math.max(range.startSeq, startSeq); + if (firstSeq <= Math.min(range.endSeq, endSeq)) return firstSeq; + } + return null; +} + +interface ProjectedEntryCandidate { + entry: TimelineProjectionEntry; + index: number; + firstSourceSeq: number; +} + +function selectProjectedEntriesAfter(input: { + entries: readonly TimelineProjectionEntry[]; + startSeq: number; + maxSeq: number; + limit: number; +}): { entries: TimelineProjectionEntry[]; endSeq: number | null } { + const eligible = input.entries + .map((entry, index) => ({ + entry, + index, + firstSourceSeq: firstSourceSeqInRange(entry, input.startSeq, input.maxSeq), + })) + .filter((candidate): candidate is ProjectedEntryCandidate => candidate.firstSourceSeq !== null) + .sort((left, right) => left.firstSourceSeq - right.firstSourceSeq || left.index - right.index); + const selected = input.limit === 0 ? eligible : eligible.slice(0, input.limit); + const selectedEntries = selected + .sort((left, right) => left.index - right.index) + .map((candidate) => candidate.entry); + if (selectedEntries.length === 0) return { entries: [], endSeq: null }; + + const selectedRanges = selectedEntries + .flatMap((entry) => entry.sourceSeqRanges) + .sort((left, right) => left.startSeq - right.startSeq || left.endSeq - right.endSeq); + // Wide projected entries can include future, discontiguous source ranges. The + // page cursor advances only through source rows covered without a gap. + let endSeq = input.startSeq - 1; + for (const range of selectedRanges) { + if (range.endSeq <= endSeq) continue; + if (range.startSeq > endSeq + 1) break; + endSeq = Math.min(range.endSeq, input.maxSeq); + } + + return { + entries: selectedEntries, + endSeq: endSeq >= input.startSeq ? endSeq : null, + }; +} + +function selectProjectedEntriesBefore(input: { + entries: readonly TimelineProjectionEntry[]; + endSeq: number; + limit: number; +}): { entries: TimelineProjectionEntry[]; startSeq: number | null; hasOlder: boolean } { + // Older history follows projected display order. Lifecycle updates can move an + // entry's seqEnd without moving its display anchor, so seqStart keeps the full + // projected item on exactly one backward page. + const eligible = input.entries.filter((entry) => entry.seqStart <= input.endSeq); + const selected = + input.limit === 0 || input.limit >= eligible.length + ? eligible + : eligible.slice(eligible.length - input.limit); + + return { + entries: selected, + startSeq: selected[0]?.seqStart ?? null, + hasOlder: selected.length < eligible.length, + }; +} + +function selectProjectedEntriesTail( + projectedAll: TimelineProjectionEntry[], + limit: number, + bounds: { minSeq: number; maxSeq: number }, +): ProjectedTimelinePageSelection { + let start = limit === 0 ? 0 : Math.max(0, projectedAll.length - limit); + // Include earlier display anchors with updates in the selected source window, + // so a tail certifies contiguous coverage even with interleaved tool updates. + for (let i = start - 1; i >= 0; i--) { + if (projectedAll[i].seqEnd >= projectedAll[start].seqStart) start = i; + } + const selected = projectedAll.slice(start); + return { + entries: selected, + startSeq: selected[0]?.seqStart ?? null, + endSeq: bounds.maxSeq, + hasOlder: start > 0, + hasNewer: false, + }; +} + +export function selectReferenceProjectedTimelinePage(input: { + rows: readonly AgentTimelineRow[]; + bounds?: { minSeq: number; maxSeq: number }; + direction: TimelineLimitDirection; + cursorSeq?: number; + limit?: number; +}): ProjectedTimelinePageSelection { + const limit = input.limit === undefined ? 0 : Math.max(0, Math.floor(input.limit)); + const bounds = input.bounds ?? getTimelineBounds(input.rows); + const projectedAll = projectTimelineRows({ rows: input.rows, mode: "projected" }); + if (!bounds) { + return { + entries: [], + startSeq: null, + endSeq: null, + hasOlder: false, + hasNewer: false, + }; + } + + if (projectedAll.length === 0) { + if (input.direction === "after") { + const cursorSeq = input.cursorSeq ?? bounds.minSeq - 1; + return { + entries: [], + startSeq: null, + endSeq: null, + hasOlder: cursorSeq >= bounds.minSeq, + hasNewer: cursorSeq < bounds.maxSeq, + }; + } + if (input.direction === "before") { + const cursorSeq = input.cursorSeq ?? bounds.maxSeq + 1; + return { + entries: [], + startSeq: null, + endSeq: null, + hasOlder: cursorSeq > bounds.minSeq, + hasNewer: cursorSeq <= bounds.maxSeq, + }; + } + return { + entries: [], + startSeq: null, + endSeq: null, + hasOlder: false, + hasNewer: false, + }; + } + + if (input.direction === "tail") { + return selectProjectedEntriesTail(projectedAll, limit, bounds); + } + + if (input.direction === "after") { + const cursorSeq = input.cursorSeq ?? bounds.minSeq - 1; + const startSeq = Math.max(bounds.minSeq, cursorSeq + 1); + const selected = selectProjectedEntriesAfter({ + entries: projectedAll, + startSeq, + maxSeq: bounds.maxSeq, + limit, + }); + return { + entries: selected.entries, + startSeq: selected.endSeq === null ? null : startSeq, + endSeq: selected.endSeq, + hasOlder: startSeq > bounds.minSeq, + hasNewer: selected.endSeq !== null && selected.endSeq < bounds.maxSeq, + }; + } + + const cursorSeq = input.cursorSeq ?? bounds.maxSeq + 1; + const endSeq = Math.min(bounds.maxSeq, cursorSeq - 1); + if (endSeq < bounds.minSeq) { + return { + entries: [], + startSeq: null, + endSeq: null, + hasOlder: false, + hasNewer: endSeq < bounds.maxSeq, + }; + } + + const selected = selectProjectedEntriesBefore({ entries: projectedAll, endSeq, limit }); + return { + entries: selected.entries, + startSeq: selected.startSeq, + endSeq, + hasOlder: selected.hasOlder, + hasNewer: endSeq < bounds.maxSeq, + }; +} + +// Existing selection fixtures exercise the retained owner through its public API. +export function selectProjectedTimelinePage( + input: Parameters[0], +) { + const projection = new TimelineProjection(input.rows); + const bounds = input.bounds ?? getTimelineBounds(input.rows) ?? { minSeq: 0, maxSeq: 0 }; + const page = projection.selectPage({ ...input, bounds }); + return { + ...page, + entries: page.entries.map((row) => { + const { seq: _seq, ...entry } = row as ProjectedTimelineRow; + return entry; + }), + }; +} diff --git a/packages/server/src/server/agent/timeline-projection.test.ts b/packages/server/src/server/agent/timeline-projection.test.ts index 2d8cf9d4a1..f2f832ffcf 100644 --- a/packages/server/src/server/agent/timeline-projection.test.ts +++ b/packages/server/src/server/agent/timeline-projection.test.ts @@ -1,9 +1,9 @@ +import { selectProjectedTimelinePage } from "./test-utils/timeline-page-reference.js"; import { describe, expect, test } from "vitest"; import type { AgentTimelineRow } from "./agent-manager.js"; import { projectTimelineRows, - selectProjectedTimelinePage, selectTimelineWindowByProjectedLimit, } from "./timeline-projection.js"; diff --git a/packages/server/src/server/agent/timeline-projection.ts b/packages/server/src/server/agent/timeline-projection.ts index 1f72cdc498..3a65f28531 100644 --- a/packages/server/src/server/agent/timeline-projection.ts +++ b/packages/server/src/server/agent/timeline-projection.ts @@ -295,12 +295,43 @@ function mergeAssistantChunks(entries: readonly WorkingEntry[]): WorkingEntry[] /** A retained item. `seq` is its latest source event, not its display anchor. */ export type ProjectedTimelineRow = AgentTimelineRow & TimelineProjectionEntry; +interface ProjectedTimelinePageOptions { + bounds: { minSeq: number; maxSeq: number }; + direction: TimelineLimitDirection; + cursorSeq?: number; + limit?: number; +} + /** Owns projected state; source events are consumed, never retained. */ export class TimelineProjection { private readonly rows: ProjectedTimelineRow[] = []; private readonly identities = new Map(); + private lastAssistantRowIndex: number | null = null; + // Disjoint source-coverage spans in display order. A tail starting inside a + // span must include its first anchor to cover interleaved lifecycle updates. + private readonly spans: { start: number; endSeq: number }[] = []; + + private readonly sourceRanges: { startSeq: number; endSeq: number; rowIndex: number }[] = []; + + constructor(rows: readonly AgentTimelineRow[] = []) { + for (const row of rows) this.appendProjected(row); + for (const [rowIndex, row] of this.rows.entries()) { + for (const range of row.sourceSeqRanges) this.sourceRanges.push({ ...range, rowIndex }); + } + this.sourceRanges.sort((a, b) => a.startSeq - b.startSeq); + } append(row: AgentTimelineRow): void { + const rowIndex = this.appendProjected(row); + const last = this.sourceRanges.at(-1); + if (last && last.rowIndex === rowIndex && last.endSeq + 1 === row.seq) { + last.endSeq = row.seq; + } else { + this.sourceRanges.push({ startSeq: row.seq, endSeq: row.seq, rowIndex }); + } + } + + private appendProjected(row: AgentTimelineRow): number { const entry = makeCanonicalEntries([row])[0]; const identity = timelineItemIdentity(row.item); const index = identity === null ? undefined : this.identities.get(identity); @@ -308,7 +339,8 @@ export class TimelineProjection { const merged = existing ? mergeIdentityEntries(existing, entry) : null; if (merged && index !== undefined) { this.rows[index] = { ...merged, seq: merged.seqEnd }; - return; + this.extendSpan(index); + return index; } const previous = this.rows.at(-1); const adjacent = previous @@ -317,16 +349,159 @@ export class TimelineProjection { if (previous && adjacent.length === 1) { const mergedText = adjacent[0]; this.rows[this.rows.length - 1] = { ...mergedText, seq: mergedText.seqEnd }; - return; + this.extendSpan(this.rows.length - 1); + return this.rows.length - 1; } if (identity !== null) this.identities.set(identity, this.rows.length); + if (entry.item.type === "assistant_message") this.lastAssistantRowIndex = this.rows.length; this.rows.push({ ...entry, seq: entry.seqEnd }); + const last = this.spans.at(-1); + if (last && last.endSeq >= entry.seqStart) { + last.endSeq = Math.max(last.endSeq, entry.seqEnd); + } else { + this.spans.push({ start: this.rows.length - 1, endSeq: entry.seqEnd }); + } + return this.rows.length - 1; + } + + private spanIndex(rowIndex: number): number { + let low = 0; + let high = this.spans.length; + while (low + 1 < high) { + const middle = (low + high) >>> 1; + if (this.spans[middle].start <= rowIndex) low = middle; + else high = middle; + } + return low; + } + + private extendSpan(rowIndex: number): void { + const index = this.spanIndex(rowIndex); + const span = this.spans[index]; + span.endSeq = Math.max(span.endSeq, this.rows[rowIndex].seqEnd); + let end = index + 1; + while (end < this.spans.length && this.rows[this.spans[end].start].seqStart <= span.endSeq) { + span.endSeq = Math.max(span.endSeq, this.spans[end].endSeq); + end++; + } + this.spans.splice(index + 1, end - index - 1); } getRows(): ProjectedTimelineRow[] { return this.rows.map((row) => ({ ...row })); } + selectPage(input: ProjectedTimelinePageOptions): ProjectedTimelinePageSelection { + if (this.rows.length === 0) { + const cursor = + input.cursorSeq ?? + (input.direction === "before" ? input.bounds.maxSeq + 1 : input.bounds.minSeq - 1); + return { + entries: [], + startSeq: null, + endSeq: null, + hasOlder: + input.direction === "after" + ? cursor >= input.bounds.minSeq + : input.direction === "before" && cursor > input.bounds.minSeq, + hasNewer: + input.direction === "after" + ? cursor < input.bounds.maxSeq + : input.direction === "before" && cursor <= input.bounds.maxSeq, + }; + } + switch (input.direction) { + case "tail": + return this.selectTail(input); + case "after": + return this.selectAfter(input); + case "before": + return this.selectBefore(input); + } + } + + private selectTail(input: ProjectedTimelinePageOptions): ProjectedTimelinePageSelection { + const limit = Math.max(0, Math.floor(input.limit ?? 0)); + const requestedStart = limit === 0 ? 0 : Math.max(0, this.rows.length - limit); + const start = this.spans[this.spanIndex(requestedStart)].start; + return { + entries: this.rows.slice(start), + startSeq: this.rows[start].seqStart, + endSeq: input.bounds.maxSeq, + hasOlder: start > 0, + hasNewer: false, + }; + } + + private selectAfter(input: ProjectedTimelinePageOptions): ProjectedTimelinePageSelection { + const startSeq = Math.max( + input.bounds.minSeq, + (input.cursorSeq ?? input.bounds.minSeq - 1) + 1, + ); + let low = 0; + let high = this.sourceRanges.length; + while (low < high) { + const middle = (low + high) >>> 1; + if (this.sourceRanges[middle].endSeq < startSeq) low = middle + 1; + else high = middle; + } + const indexes = new Set(); + const limit = Math.max(0, Math.floor(input.limit ?? 0)); + for (let i = low; i < this.sourceRanges.length; i++) { + const range = this.sourceRanges[i]; + if (range.startSeq > input.bounds.maxSeq) break; + indexes.add(range.rowIndex); + if (limit > 0 && indexes.size === limit) break; + } + const entries = [...indexes].sort((a, b) => a - b).map((index) => this.rows[index]); + const selected = selectProjectedEntriesAfter({ + entries, + startSeq, + maxSeq: input.bounds.maxSeq, + limit, + }); + return { + entries: selected.entries, + startSeq: selected.endSeq === null ? null : startSeq, + endSeq: selected.endSeq, + hasOlder: startSeq > input.bounds.minSeq, + hasNewer: selected.endSeq !== null && selected.endSeq < input.bounds.maxSeq, + }; + } + + private selectBefore(input: ProjectedTimelinePageOptions): ProjectedTimelinePageSelection { + const endSeq = Math.min(input.bounds.maxSeq, (input.cursorSeq ?? input.bounds.maxSeq + 1) - 1); + if (endSeq >= input.bounds.minSeq) { + let low = 0; + let high = this.rows.length; + while (low < high) { + const middle = (low + high) >>> 1; + if (this.rows[middle].seqStart <= endSeq) low = middle + 1; + else high = middle; + } + const limit = Math.max(0, Math.floor(input.limit ?? 0)); + const start = limit === 0 ? 0 : Math.max(0, low - limit); + return { + entries: this.rows.slice(start, low), + startSeq: this.rows[start]?.seqStart ?? null, + endSeq, + hasOlder: start > 0, + hasNewer: endSeq < input.bounds.maxSeq, + }; + } + return { entries: [], startSeq: null, endSeq: null, hasOlder: false, hasNewer: true }; + } + + getLastItem(seq: number): AgentTimelineItem | null { + const last = this.sourceRanges.at(-1); + return last?.endSeq === seq ? this.rows[last.rowIndex].item : null; + } + + getLastAssistantMessage(): string | null { + const row = this.lastAssistantRowIndex === null ? null : this.rows[this.lastAssistantRowIndex]; + return row?.item.type === "assistant_message" ? row.item.text : null; + } + enrichSubmittedUserMessage( clientMessageId: string, providerMessageId: string, @@ -444,21 +619,6 @@ export function selectTimelineWindowByProjectedLimit(input: { }; } -function getTimelineBounds( - rows: readonly AgentTimelineRow[], -): { minSeq: number; maxSeq: number } | null { - const first = rows[0]; - const last = rows[rows.length - 1]; - if (!first || !last) { - return null; - } - const entries = makeCanonicalEntries(rows); - return { - minSeq: entries.reduce((min, e) => Math.min(min, e.seqStart), Infinity), - maxSeq: entries.reduce((max, e) => Math.max(max, e.seqEnd), 0), - }; -} - function firstSourceSeqInRange( entry: TimelineProjectionEntry, startSeq: number, @@ -515,142 +675,6 @@ function selectProjectedEntriesAfter(input: { }; } -function selectProjectedEntriesBefore(input: { - entries: readonly TimelineProjectionEntry[]; - endSeq: number; - limit: number; -}): { entries: TimelineProjectionEntry[]; startSeq: number | null; hasOlder: boolean } { - // Older history follows projected display order. Lifecycle updates can move an - // entry's seqEnd without moving its display anchor, so seqStart keeps the full - // projected item on exactly one backward page. - const eligible = input.entries.filter((entry) => entry.seqStart <= input.endSeq); - const selected = - input.limit === 0 || input.limit >= eligible.length - ? eligible - : eligible.slice(eligible.length - input.limit); - - return { - entries: selected, - startSeq: selected[0]?.seqStart ?? null, - hasOlder: selected.length < eligible.length, - }; -} - -function selectProjectedEntriesTail( - projectedAll: TimelineProjectionEntry[], - limit: number, - bounds: { minSeq: number; maxSeq: number }, -): ProjectedTimelinePageSelection { - let start = limit === 0 ? 0 : Math.max(0, projectedAll.length - limit); - // Include earlier display anchors with updates in the selected source window, - // so a tail certifies contiguous coverage even with interleaved tool updates. - for (let i = start - 1; i >= 0; i--) { - if (projectedAll[i].seqEnd >= projectedAll[start].seqStart) start = i; - } - const selected = projectedAll.slice(start); - return { - entries: selected, - startSeq: selected[0]?.seqStart ?? null, - endSeq: bounds.maxSeq, - hasOlder: start > 0, - hasNewer: false, - }; -} - -export function selectProjectedTimelinePage(input: { - rows: readonly AgentTimelineRow[]; - bounds?: { minSeq: number; maxSeq: number }; - direction: TimelineLimitDirection; - cursorSeq?: number; - limit?: number; -}): ProjectedTimelinePageSelection { - const limit = input.limit === undefined ? 0 : Math.max(0, Math.floor(input.limit)); - const bounds = input.bounds ?? getTimelineBounds(input.rows); - const projectedAll = projectTimelineRows({ rows: input.rows, mode: "projected" }); - if (!bounds) { - return { - entries: [], - startSeq: null, - endSeq: null, - hasOlder: false, - hasNewer: false, - }; - } - - if (projectedAll.length === 0) { - if (input.direction === "after") { - const cursorSeq = input.cursorSeq ?? bounds.minSeq - 1; - return { - entries: [], - startSeq: null, - endSeq: null, - hasOlder: cursorSeq >= bounds.minSeq, - hasNewer: cursorSeq < bounds.maxSeq, - }; - } - if (input.direction === "before") { - const cursorSeq = input.cursorSeq ?? bounds.maxSeq + 1; - return { - entries: [], - startSeq: null, - endSeq: null, - hasOlder: cursorSeq > bounds.minSeq, - hasNewer: cursorSeq <= bounds.maxSeq, - }; - } - return { - entries: [], - startSeq: null, - endSeq: null, - hasOlder: false, - hasNewer: false, - }; - } - - if (input.direction === "tail") { - return selectProjectedEntriesTail(projectedAll, limit, bounds); - } - - if (input.direction === "after") { - const cursorSeq = input.cursorSeq ?? bounds.minSeq - 1; - const startSeq = Math.max(bounds.minSeq, cursorSeq + 1); - const selected = selectProjectedEntriesAfter({ - entries: projectedAll, - startSeq, - maxSeq: bounds.maxSeq, - limit, - }); - return { - entries: selected.entries, - startSeq: selected.endSeq === null ? null : startSeq, - endSeq: selected.endSeq, - hasOlder: startSeq > bounds.minSeq, - hasNewer: selected.endSeq !== null && selected.endSeq < bounds.maxSeq, - }; - } - - const cursorSeq = input.cursorSeq ?? bounds.maxSeq + 1; - const endSeq = Math.min(bounds.maxSeq, cursorSeq - 1); - if (endSeq < bounds.minSeq) { - return { - entries: [], - startSeq: null, - endSeq: null, - hasOlder: false, - hasNewer: endSeq < bounds.maxSeq, - }; - } - - const selected = selectProjectedEntriesBefore({ entries: projectedAll, endSeq, limit }); - return { - entries: selected.entries, - startSeq: selected.startSeq, - endSeq, - hasOlder: selected.hasOlder, - hasNewer: endSeq < bounds.maxSeq, - }; -} - /** * Apply a projected-count limit to a flat AgentTimelineItem[] without seq metadata. * Used by callers that only have items in hand (e.g. MCP tools reading diff --git a/packages/server/src/server/daemon-e2e/cli-logs-follow.e2e.test.ts b/packages/server/src/server/daemon-e2e/cli-logs-follow.e2e.test.ts index d8388f9dd2..55750831c8 100644 --- a/packages/server/src/server/daemon-e2e/cli-logs-follow.e2e.test.ts +++ b/packages/server/src/server/daemon-e2e/cli-logs-follow.e2e.test.ts @@ -87,3 +87,53 @@ test("logs --follow preserves the same assistant text as one-shot logs", async ( await daemon.close(); } }, 60_000); + +test("omitted after limit pages forward while explicit zero preserves complete CLI history", async () => { + const daemon = await createTestPaseoDaemon(); + const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); + try { + await client.connect(); + await client.fetchAgents({ subscribe: {} }); + const agent = await client.createAgent({ provider: "claude", cwd: daemon.paseoHome }); + const initial = await client.fetchAgentTimeline(agent.id, { direction: "tail", limit: 0 }); + const cursor = { epoch: initial.epoch, seq: initial.window.maxSeq }; + for (let index = 0; index < 451; index++) { + await daemon.daemon.agentManager.appendTimelineItem(agent.id, { + type: "user_message", + text: String(index), + }); + } + const first = await client.fetchAgentTimeline(agent.id, { direction: "after", cursor }); + expect(first.entries).toHaveLength(200); + expect(first.hasNewer).toBe(true); + expect(first.endCursor).toEqual({ epoch: cursor.epoch, seq: cursor.seq + 200 }); + const second = await client.fetchAgentTimeline(agent.id, { + direction: "after", + cursor: first.endCursor!, + }); + const third = await client.fetchAgentTimeline(agent.id, { + direction: "after", + cursor: second.endCursor!, + }); + expect(second.entries).toHaveLength(200); + expect(third.entries).toHaveLength(51); + expect(third.hasNewer).toBe(false); + expect( + [...first.entries, ...second.entries, ...third.entries].map((entry) => entry.item), + ).toEqual( + Array.from({ length: 451 }, (_, index) => ({ type: "user_message", text: String(index) })), + ); + const allAfter = await client.fetchAgentTimeline(agent.id, { + direction: "after", + cursor, + limit: 0, + }); + const allTail = await client.fetchAgentTimeline(agent.id, { direction: "tail", limit: 0 }); + expect(allAfter.entries).toHaveLength(451); + expect(allAfter.hasNewer).toBe(false); + expect(allTail.entries).toHaveLength(initial.entries.length + 451); + } finally { + await client.close(); + await daemon.close(); + } +}, 60_000); diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index db4939aa31..da7bf99b72 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -7787,8 +7787,6 @@ export class Session { ): Promise { const direction: AgentTimelineFetchDirection = msg.direction ?? (msg.cursor ? "after" : "tail"); const projection = "projected" as const; - const requestedLimit = msg.limit; - const pageLimit = requestedLimit ?? (direction === "after" ? 0 : 200); const cursor: AgentTimelineCursor | undefined = msg.cursor ? { epoch: msg.cursor.epoch, @@ -7807,7 +7805,7 @@ export class Session { const fetchedControlTimeline = this.agentManager.fetchTimeline(msg.agentId, { direction, cursor, - limit: pageLimit, + limit: msg.limit, }); const selectedTimeline = { timeline: fetchedControlTimeline, From f14a4cc112583f317c44114f7ad5fa7e28e101f8 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Tue, 27 Oct 2026 09:56:47 +0700 Subject: [PATCH 041/173] fix(server): keep password-protected config reload responsive (#7959) * fix(server): keep password-protected config reload responsive Resolve authentication only during startup. Runtime config writes and reloads share an async queue so durable state and live owners stay ordered, including overlapping plugin changes and rollback. * test(server): adapt config consumers to async service-port reads Provide the service-port capability in the existing Session and tool-bridge fixtures. Use the platform temporary directory for the plugin agent fixture so its working directory exists on Windows. --- .../mutable-provider-config-owner.test.ts | 26 +- .../src/server/agent/plugin-provider.test.ts | 2 +- .../opencode/bridge-input-errors.test.ts | 1 + packages/server/src/server/bootstrap.test.ts | 12 +- packages/server/src/server/bootstrap.ts | 18 +- packages/server/src/server/config.test.ts | 31 +- packages/server/src/server/config.ts | 131 +++++---- .../src/server/daemon-config-store.test.ts | 264 ++++++++++-------- .../server/src/server/daemon-config-store.ts | 62 +++- .../internal/selection-store.test.ts | 2 +- .../internal/selection-store.ts | 2 +- .../src/server/persisted-config.test.ts | 90 +++--- .../server/src/server/persisted-config.ts | 82 +++++- .../src/server/plugins/index.posix.test.ts | 53 +++- packages/server/src/server/plugins/index.ts | 80 ++++-- .../plugins/plugin-paseo-api.e2e.test.ts | 57 ++++ packages/server/src/server/private-files.ts | 28 ++ packages/server/src/server/session.test.ts | 1 + packages/server/src/server/session.ts | 21 +- .../session/daemon/daemon-session.test.ts | 16 +- .../server/session/daemon/daemon-session.ts | 10 +- .../workspace-scripts-service.test.ts | 22 ++ .../workspace-scripts-service.ts | 5 +- .../terminal-agent-hook-setting.test.ts | 6 +- 24 files changed, 707 insertions(+), 315 deletions(-) diff --git a/packages/server/src/server/agent/mutable-provider-config-owner.test.ts b/packages/server/src/server/agent/mutable-provider-config-owner.test.ts index 53270c1a78..0307eabda6 100644 --- a/packages/server/src/server/agent/mutable-provider-config-owner.test.ts +++ b/packages/server/src/server/agent/mutable-provider-config-owner.test.ts @@ -99,16 +99,17 @@ afterEach(() => { }); describe("mutable provider config owner", () => { - test("publishes provider changes after commit and emits nothing on rollback", () => { + test("publishes provider changes after commit and emits nothing on rollback", async () => { const paseoHome = mkdtempSync(path.join(tmpdir(), "paseo-provider-config-owner-")); tempDirs.push(paseoHome); const store = new DaemonConfigStore(paseoHome, mutableConfig({ version: 1 })); const manager = new ProviderSnapshotManager({ logger: createTestLogger(), - providerOverrides: { codex: { enabled: true } }, + providerOverrides: CONTROLLED_PROVIDERS, + extraClients: { codex: controlledCodexClient(async () => catalog("initial")) }, }); const cwd = path.resolve("/tmp/provider-config-owner"); - manager.getSnapshot(cwd); + await manager.refreshSnapshotForCwd({ cwd }); const events: string[] = []; manager.on("change", ({ current }) => events.push(current.cwd)); let agentManagerState = manager.getAgentManagerProviderState(); @@ -125,7 +126,7 @@ describe("mutable provider config owner", () => { }); try { - store.patch({ providers: { codex: { enabled: false } } }); + await store.patch({ providers: { codex: { enabled: false } } }); expect(events).toEqual([cwd]); expect(agentManagerState.providerDefinitions.codex).toMatchObject({ enabled: false }); @@ -133,7 +134,7 @@ describe("mutable provider config owner", () => { const unsubscribeFailure = store.onApply(() => { throw new Error("later owner failed"); }); - expect(() => store.patch({ providers: { codex: { enabled: true } } })).toThrow( + await expect(store.patch({ providers: { codex: { enabled: true } } })).rejects.toThrow( "later owner failed", ); unsubscribeFailure(); @@ -150,7 +151,7 @@ describe("mutable provider config owner", () => { } }); - test("does no provider work for unrelated CORS, Git, and app URL reloads", () => { + test("does no provider work for unrelated CORS, Git, and app URL reloads", async () => { const paseoHome = mkdtempSync(path.join(tmpdir(), "paseo-provider-config-owner-")); tempDirs.push(paseoHome); const initial: PersistedConfig = { @@ -174,9 +175,10 @@ describe("mutable provider config owner", () => { }); const manager = new ProviderSnapshotManager({ logger: createTestLogger(), - providerOverrides: { codex: { enabled: true } }, + providerOverrides: CONTROLLED_PROVIDERS, + extraClients: { codex: controlledCodexClient(async () => catalog("initial")) }, }); - manager.getSnapshot("/tmp/provider-config-owner"); + await manager.refreshSnapshotForCwd({ cwd: "/tmp/provider-config-owner" }); const events: string[] = []; manager.on("change", ({ current }) => events.push(current.cwd)); let registryUpdates = 0; @@ -200,7 +202,7 @@ describe("mutable provider config owner", () => { }; writeFileSync(configPath, `${JSON.stringify(reloaded, null, 2)}\n`, "utf-8"); - expect(store.reload().appliedPaths).toEqual([ + expect((await store.reload()).appliedPaths).toEqual([ "app.baseUrl", "daemon.cors.allowedOrigins", "daemon.git.maxProcessConcurrency", @@ -245,7 +247,7 @@ describe("mutable provider config owner", () => { await vi.waitFor(() => expect(catalogResolvers).toHaveLength(1)); expect(events).toEqual([]); - store.patch({ providers: { codex: { enabled: true, label: "Reloaded Codex" } } }); + await store.patch({ providers: { codex: { enabled: true, label: "Reloaded Codex" } } }); expect(events).toEqual(["loading:none"]); await vi.waitFor(() => expect(catalogResolvers).toHaveLength(2)); @@ -311,9 +313,9 @@ describe("mutable provider config owner", () => { expect(events).toEqual([]); const before = manager.getSnapshot(cwd); - expect(() => + await expect( store.patch({ providers: { codex: { enabled: true, label: "Rejected Codex" } } }), - ).toThrow("later owner failed"); + ).rejects.toThrow("later owner failed"); expect(events).toEqual([]); expect(observedDuringApply).toEqual([{ label: "Codex", snapshot: before }]); expect(observedDuringApply[0]!.snapshot).toBe(before); diff --git a/packages/server/src/server/agent/plugin-provider.test.ts b/packages/server/src/server/agent/plugin-provider.test.ts index 3131447098..72bc0f475b 100644 --- a/packages/server/src/server/agent/plugin-provider.test.ts +++ b/packages/server/src/server/agent/plugin-provider.test.ts @@ -310,7 +310,7 @@ describe("PluginAgentClientRegistry", () => { }); const own = { nested: { replace: "agent" } }; const agent = await manager.createAgent( - { provider: "plugin-direct", cwd: "/tmp", providerOptions: own }, + { provider: "plugin-direct", cwd: tmpdir(), providerOptions: own }, undefined, { workspaceId: undefined }, ); diff --git a/packages/server/src/server/agent/providers/opencode/bridge-input-errors.test.ts b/packages/server/src/server/agent/providers/opencode/bridge-input-errors.test.ts index 1396d1f784..277cad58fe 100644 --- a/packages/server/src/server/agent/providers/opencode/bridge-input-errors.test.ts +++ b/packages/server/src/server/agent/providers/opencode/bridge-input-errors.test.ts @@ -56,6 +56,7 @@ test("bridge preserves tool failure messages and classifies invalid requests as getDaemonTcpHost: null, serviceProxyPublicBaseUrl: null, resolveScriptHealth: null, + getGlobalServicePorts: async () => undefined, logger, emit: () => {}, publishStatusUpdate: () => {}, diff --git a/packages/server/src/server/bootstrap.test.ts b/packages/server/src/server/bootstrap.test.ts index 0881e828d0..23d3dcd1a7 100644 --- a/packages/server/src/server/bootstrap.test.ts +++ b/packages/server/src/server/bootstrap.test.ts @@ -141,11 +141,11 @@ function liveCleanupHost() { test("bootstrap's host toggle prevents collection live, persists, and leaves other hosts enabled", async () => { const host = liveCleanupHost(); const other = liveCleanupHost(); - host.store.patch({ idleRuntimeCleanup: false }); + await host.store.patch({ idleRuntimeCleanup: false }); expect(loadPersistedConfig(host.home).agents?.idleRuntimeCleanup).toBe(false); expect((await host.sweep()).collected).toEqual([]); expect((await other.sweep()).collected).toHaveLength(1); - host.store.patch({ idleRuntimeCleanup: true }); + await host.store.patch({ idleRuntimeCleanup: true }); host.protect(true); expect((await host.sweep()).collected).toEqual([]); host.protect(false); @@ -160,7 +160,7 @@ test("bootstrap's config-file reload binding disables and enables eligible colle path.join(host.home, "config.json"), JSON.stringify({ version: 1, agents: { idleRuntimeCleanup: enabled } }), ); - expect(host.store.reload()).toEqual({ + expect(await host.store.reload()).toEqual({ appliedPaths: ["agents.idleRuntimeCleanup"], restartRequiredPaths: [], overrideControlledPaths: [], @@ -173,12 +173,12 @@ test.each([false, true])( "failed config apply restores prior idle cleanup behavior (previous: %s)", async (previous) => { const host = liveCleanupHost(); - host.store.patch({ idleRuntimeCleanup: previous }); + await host.store.patch({ idleRuntimeCleanup: previous }); const persistedBefore = loadPersistedConfig(host.home); const refuse = host.store.onApply(() => { throw new Error("Another live owner refused"); }); - expect(() => host.store.patch({ idleRuntimeCleanup: !previous })).toThrow( + await expect(host.store.patch({ idleRuntimeCleanup: !previous })).rejects.toThrow( "Another live owner refused", ); expect(host.store.get().idleRuntimeCleanup).toBe(previous); @@ -191,6 +191,6 @@ test.each([false, true])( test("disposing bootstrap's binding stops configuration delivery", async () => { const host = liveCleanupHost(); host.unsubscribe(); - host.store.patch({ idleRuntimeCleanup: false }); + await host.store.patch({ idleRuntimeCleanup: false }); expect((await host.sweep()).collected).toHaveLength(1); }); diff --git a/packages/server/src/server/bootstrap.ts b/packages/server/src/server/bootstrap.ts index 2bbde7de34..83ef2acb83 100644 --- a/packages/server/src/server/bootstrap.ts +++ b/packages/server/src/server/bootstrap.ts @@ -161,7 +161,11 @@ import { CheckoutDiffManager } from "./checkout-diff-manager.js"; import { ScheduleService } from "./schedule/service.js"; import { DaemonConfigStore, type MutableDaemonConfig } from "./daemon-config-store.js"; import { createOrchestrationSkills } from "./orchestration-skills/index.js"; -import { resolveConfigFromPersisted, type CliConfigOverrides } from "./config.js"; +import { + resolveReloadableConfig, + type ResolvedDaemonSettings, + type CliConfigOverrides, +} from "./config.js"; import { resolvePaseoToolPolicy } from "./agent/paseo-tool-policy.js"; import { BrowserToolsBroker } from "./browser-tools/broker.js"; import { DaemonConfigBrowserToolsPolicy } from "./browser-tools/policy.js"; @@ -196,7 +200,7 @@ import type { AgentProviderRuntimeSettingsMap, ProviderOverride, } from "./agent/provider-launch-config.js"; -import { loadPersistedConfig, type PersistedConfig } from "./persisted-config.js"; +import { type PersistedConfig } from "./persisted-config.js"; import { createServiceProxySubsystem, type ServiceProxySubsystem } from "./service-proxy.js"; import { releaseWorkspaceServicePortPlan } from "./workspace-service-port-registry.js"; import { ScriptHealthMonitor } from "./script-health-monitor.js"; @@ -551,7 +555,7 @@ function resolveExpressTrustProxySetting(config: PaseoDaemonConfig): true | stri return config.trustedProxies ?? ["loopback"]; } -function createInitialRelayConfig(config: PaseoDaemonConfig): MutableDaemonConfig["relay"] { +function createInitialRelayConfig(config: ResolvedDaemonSettings): MutableDaemonConfig["relay"] { return { enabled: config.relayEnabled ?? true, requireProtectedSecurity: config.relayRequireProtectedSecurity ?? false, @@ -562,7 +566,7 @@ function resolveReloadEnv(config: PaseoDaemonConfig): NodeJS.ProcessEnv { return config.configReload?.env ?? process.env; } -function createInitialMutableDaemonConfig(config: PaseoDaemonConfig): MutableDaemonConfig { +function createInitialMutableDaemonConfig(config: ResolvedDaemonSettings): MutableDaemonConfig { const providers = config.providerOverrides ?? {}; const initialConfig: MutableDaemonConfig = { @@ -638,14 +642,14 @@ export async function createPaseoDaemon( }), reloadSource: { resolve: (persisted) => { - const reloaded = resolveConfigFromPersisted(config.paseoHome, persisted, { + const reloaded = resolveReloadableConfig(persisted, { env: resolveReloadEnv(config), cli: config.configReload?.cli, relayEnabledFallback: config.configReload?.relayEnabledFallback, }); return { mutable: createInitialMutableDaemonConfig(reloaded), - overrideControlledPaths: reloaded.configReload?.overrideControlledPaths ?? [], + overrideControlledPaths: reloaded.overrideControlledPaths, }; }, }, @@ -1541,7 +1545,7 @@ export async function createPaseoDaemon( spawnWorkspaceScript, assertAutomationAllowed: (workspaceId) => assertWorkspaceAutomationAllowedForWorkspace(workspaceRegistry, workspaceId), - globalServicePorts: loadPersistedConfig(config.paseoHome).worktrees?.servicePorts, + getGlobalServicePorts: () => daemonConfigStore.readServicePorts(), }), markWorkspaceArchiving: markWorkspaceArchivingExternal, clearWorkspaceArchiving: clearWorkspaceArchivingExternal, diff --git a/packages/server/src/server/config.test.ts b/packages/server/src/server/config.test.ts index e8c5f2faa0..72d1c30f7d 100644 --- a/packages/server/src/server/config.test.ts +++ b/packages/server/src/server/config.test.ts @@ -4,7 +4,12 @@ import path from "node:path"; import { pathToFileURL } from "node:url"; import { afterEach, describe, expect, test } from "vitest"; -import { loadConfig, resolveBundledWebUiDistDir, resolveConfigFromPersisted } from "./config.js"; +import { + loadConfig, + resolveBundledWebUiDistDir, + resolveConfigFromPersisted, + resolveReloadableConfig, +} from "./config.js"; import { loadPersistedConfig } from "./persisted-config.js"; const roots: string[] = []; @@ -14,6 +19,30 @@ describe("server config", () => { await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); }); + test("resolves reloadable settings without resolving the startup password", async () => { + const paseoHome = await mkdtemp(path.join(os.tmpdir(), "paseo-config-auth-reload-")); + roots.push(paseoHome); + const env = { PASEO_PASSWORD: "synthetic-audit-password" }; + const persisted = loadPersistedConfig(paseoHome); + const startup = resolveConfigFromPersisted(paseoHome, persisted, { env }); + const started = performance.now(); + const timer = new Promise((resolve) => + setTimeout(() => resolve(performance.now() - started), 0), + ); + const reloaded = resolveReloadableConfig( + { + ...persisted, + daemon: { ...persisted.daemon, browserTools: { enabled: true } }, + }, + { env }, + ); + const gap = await timer; + expect(reloaded).not.toHaveProperty("auth"); + expect(reloaded.browserToolsEnabled).toBe(true); + expect(startup.auth?.password).toBeTypeOf("string"); + expect(gap).toBeLessThan(50); + }); + test("records when the daemon is managed by Paseo Desktop", async () => { const paseoHome = await mkdtemp(path.join(os.tmpdir(), "paseo-config-desktop-managed-")); roots.push(paseoHome); diff --git a/packages/server/src/server/config.ts b/packages/server/src/server/config.ts index 74a8037d07..add78aa7f5 100644 --- a/packages/server/src/server/config.ts +++ b/packages/server/src/server/config.ts @@ -568,31 +568,43 @@ interface ResolveConfigFromPersistedOptions { relayEnabledFallback?: boolean; } +// Startup values, including authentication, never enter runtime settings resolution. +export type ResolvedDaemonSettings = Pick< + PaseoDaemonConfig, + | "corsAllowedOrigins" + | "hostnames" + | "trustedProxies" + | "mcpEnabled" + | "mcpInjectIntoAgents" + | "browserToolsEnabled" + | "git" + | "autoArchiveAfterMerge" + | "enableTerminalAgentHooks" + | "appendSystemPrompt" + | "terminalProfiles" + | "agentProfiles" + | "skillSelection" + | "pluginsEnabled" + | "plugins" + | "relayEnabled" + | "relayRequireProtectedSecurity" + | "appBaseUrl" + | "idleRuntimeCleanup" + | "providerCatalogRefreshTimeoutMs" + | "metadataGeneration" + | "providerOverrides" +>; + export function resolveConfigFromPersisted( paseoHome: string, persisted: PersistedConfig, options?: ResolveConfigFromPersistedOptions, ): PaseoDaemonConfig { - const resolvedOptions = options ?? {}; - const env = configurationEnvironment(resolvedOptions.env ?? process.env); - const cli = resolvedOptions.cli; + const env = configurationEnvironment(options?.env ?? process.env); + const cli = options?.cli; const relayEnabledFallback = - resolvedOptions.relayEnabledFallback ?? persisted.daemon?.relay?.enabled === undefined; - - const listen = resolveListenAddress(env, cli, persisted); - const { - mcpEnabled, - mcpInjectIntoAgents, - browserToolsEnabled, - autoArchiveAfterMerge, - appendSystemPrompt, - terminalProfiles, - agentProfiles, - hostnames, - trustedProxies, - appBaseUrl, - } = resolveStaticLoadConfigSettings(env, cli, persisted); - + options?.relayEnabledFallback ?? persisted.daemon?.relay?.enabled === undefined; + const { overrideControlledPaths, ...settings } = resolveReloadableConfig(persisted, options); const relay = resolveRelayConfig({ env, persisted, @@ -600,42 +612,14 @@ export function resolveConfigFromPersisted( cliRelayUseTls: cli?.relayUseTls, enabledFallback: relayEnabledFallback, }); - const serviceProxy = resolveServiceProxyConfig(env, persisted); - const webUi = resolveWebUiConfig(paseoHome, env, cli, persisted); - - const { openai, speech } = resolveSpeechConfig({ - paseoHome, - env, - persisted, - }); - + const { openai, speech } = resolveSpeechConfig({ paseoHome, env, persisted }); const voiceLlm = resolveVoiceLlmConfig(env, persisted); - const providerOverrides = extractProviderOverrides( - persisted.agents?.providers as Record | undefined, - ); - - const overrideControlledPaths = resolveOverrideControlledPaths(env, cli, persisted); - return { - listen, + ...settings, + listen: resolveListenAddress(env, cli, persisted), paseoHome, desktopManaged: env.PASEO_DESKTOP_MANAGED === "1", worktreesRoot: resolveWorktreesRoot(paseoHome, persisted), - corsAllowedOrigins: resolveCorsAllowedOrigins(env, persisted), - hostnames, - trustedProxies, - mcpEnabled, - mcpInjectIntoAgents, - browserToolsEnabled, - git: resolveGitProcessConfig(env, persisted), - autoArchiveAfterMerge, - enableTerminalAgentHooks: persisted.daemon?.enableTerminalAgentHooks ?? false, - appendSystemPrompt, - terminalProfiles, - agentProfiles, - skillSelection: persisted.agents?.skills?.selection, - pluginsEnabled: persisted.pluginsEnabled ?? false, - plugins: persisted.plugins, pluginRegistries: persisted.pluginRegistries, pluginRegistryUrl: env.PASEO_PLUGIN_REGISTRY, mcpDebug: env.MCP_DEBUG === "1", @@ -643,27 +627,20 @@ export function resolveConfigFromPersisted( agentStoragePath: path.join(paseoHome, "agents"), staticDir: "public", agentClients: {}, - relayEnabled: relay.enabled, relayEnabledMutable: relay.enabledMutable, - relayRequireProtectedSecurity: relay.requireProtectedSecurity, relayEndpoint: relay.endpoint, relayPublicEndpoint: relay.publicEndpoint, relayUseTls: relay.useTls, relayPublicUseTls: relay.publicUseTls, - serviceProxy, - webUi, - appBaseUrl, + serviceProxy: resolveServiceProxyConfig(env, persisted), + webUi: resolveWebUiConfig(paseoHome, env, cli, persisted), auth: resolveAuthConfig(env, persisted), openai, speech, voiceLlmProvider: voiceLlm.provider, voiceLlmProviderExplicit: voiceLlm.providerExplicit, voiceLlmModel: voiceLlm.model, - agentProviderSettings: extractAgentProviderSettings(providerOverrides), - idleRuntimeCleanup: persisted.agents?.idleRuntimeCleanup ?? true, - providerCatalogRefreshTimeoutMs: persisted.agents?.catalogRefreshTimeoutMs, - metadataGeneration: persisted.agents?.metadataGeneration, - providerOverrides, + agentProviderSettings: extractAgentProviderSettings(settings.providerOverrides), log: resolveLogConfigFromEnv(env, persisted), configReload: { env: { ...env }, @@ -675,6 +652,40 @@ export function resolveConfigFromPersisted( }; } +export function resolveReloadableConfig( + persisted: PersistedConfig, + options?: ResolveConfigFromPersistedOptions, +): ResolvedDaemonSettings & { overrideControlledPaths: string[] } { + const env = configurationEnvironment(options?.env ?? process.env); + const cli = options?.cli; + const relay = resolveRelayConfig({ + env, + persisted, + cliRelayEnabled: cli?.relayEnabled, + cliRelayUseTls: cli?.relayUseTls, + enabledFallback: + options?.relayEnabledFallback ?? persisted.daemon?.relay?.enabled === undefined, + }); + return { + ...resolveStaticLoadConfigSettings(env, cli, persisted), + corsAllowedOrigins: resolveCorsAllowedOrigins(env, persisted), + git: resolveGitProcessConfig(env, persisted), + enableTerminalAgentHooks: persisted.daemon?.enableTerminalAgentHooks ?? false, + skillSelection: persisted.agents?.skills?.selection, + pluginsEnabled: persisted.pluginsEnabled ?? false, + plugins: persisted.plugins, + relayEnabled: relay.enabled, + relayRequireProtectedSecurity: relay.requireProtectedSecurity, + idleRuntimeCleanup: persisted.agents?.idleRuntimeCleanup ?? true, + providerCatalogRefreshTimeoutMs: persisted.agents?.catalogRefreshTimeoutMs, + metadataGeneration: persisted.agents?.metadataGeneration, + providerOverrides: extractProviderOverrides( + persisted.agents?.providers as Record | undefined, + ), + overrideControlledPaths: resolveOverrideControlledPaths(env, cli, persisted), + }; +} + export function loadConfig( paseoHome: string, options?: Omit, diff --git a/packages/server/src/server/daemon-config-store.test.ts b/packages/server/src/server/daemon-config-store.test.ts index f4c1a02de9..e3b6f48895 100644 --- a/packages/server/src/server/daemon-config-store.test.ts +++ b/packages/server/src/server/daemon-config-store.test.ts @@ -101,7 +101,7 @@ describe("DaemonConfigStore", () => { } }); - test("patch persists relay state and emits its field change", () => { + test("patch persists relay state and emits its field change", async () => { const paseoHome = mkdtempSync(path.join(tmpdir(), "paseo-daemon-config-store-")); tempDirs.push(paseoHome); const store = new DaemonConfigStore(paseoHome, { @@ -117,13 +117,13 @@ describe("DaemonConfigStore", () => { const changes: unknown[] = []; store.onFieldChange("relay.enabled", (value) => changes.push(value)); - store.patch({ relay: { enabled: true } }); + await store.patch({ relay: { enabled: true } }); expect(changes).toEqual([true]); expect(loadPersistedConfig(paseoHome).daemon?.relay?.enabled).toBe(true); }); - test("patch persists the relay protected security requirement independently of relay enablement", () => { + test("patch persists the relay protected security requirement independently of relay enablement", async () => { const paseoHome = mkdtempSync(path.join(tmpdir(), "paseo-daemon-config-store-")); tempDirs.push(paseoHome); const store = new DaemonConfigStore( @@ -145,14 +145,14 @@ describe("DaemonConfigStore", () => { const changes: unknown[] = []; store.onFieldChange("relay.requireProtectedSecurity", (value) => changes.push(value)); - store.patch({ relay: { requireProtectedSecurity: true } }); + await store.patch({ relay: { requireProtectedSecurity: true } }); expect(changes).toEqual([true]); expect(store.get().relay).toEqual({ enabled: true, requireProtectedSecurity: true }); expect(loadPersistedConfig(paseoHome).daemon?.relay?.requireProtectedSecurity).toBe(true); }); - test("patch round-trips agent profiles through the strictly-parsed persisted config", () => { + test("patch round-trips agent profiles through the strictly-parsed persisted config", async () => { const paseoHome = mkdtempSync(path.join(tmpdir(), "paseo-daemon-config-store-")); tempDirs.push(paseoHome); const store = new DaemonConfigStore(paseoHome, { @@ -166,7 +166,7 @@ describe("DaemonConfigStore", () => { appendSystemPrompt: "", }); - store.patch({ + await store.patch({ agentProfiles: [ { id: "profile_ui", @@ -198,7 +198,7 @@ describe("DaemonConfigStore", () => { expect(store.get().agentProfiles).toHaveLength(1); }); - test("patch replaces the whole agent profile list rather than merging entries", () => { + test("patch replaces the whole agent profile list rather than merging entries", async () => { const paseoHome = mkdtempSync(path.join(tmpdir(), "paseo-daemon-config-store-")); tempDirs.push(paseoHome); const store = new DaemonConfigStore(paseoHome, { @@ -216,13 +216,13 @@ describe("DaemonConfigStore", () => { ], }); - store.patch({ agentProfiles: [{ id: "a", name: "Keep", provider: "claude" }] }); + await store.patch({ agentProfiles: [{ id: "a", name: "Keep", provider: "claude" }] }); expect(store.get().agentProfiles).toEqual([{ id: "a", name: "Keep", provider: "claude" }]); expect(loadPersistedConfig(paseoHome).daemon?.agentProfiles).toHaveLength(1); }); - test("rolls back config when a field transition fails", () => { + test("rolls back config when a field transition fails", async () => { const paseoHome = mkdtempSync(path.join(tmpdir(), "paseo-daemon-config-store-")); tempDirs.push(paseoHome); const store = new DaemonConfigStore(paseoHome, { @@ -241,14 +241,14 @@ describe("DaemonConfigStore", () => { } }); - expect(() => store.patch({ relay: { enabled: true } })).toThrow( + await expect(store.patch({ relay: { enabled: true } })).rejects.toThrow( "Relay transport failed to start", ); expect(store.get().relay?.enabled).toBe(false); expect(loadPersistedConfig(paseoHome).daemon?.relay?.enabled).toBe(false); }); - test("rolls back live owners when a later transactional owner fails", () => { + test("rolls back live owners when a later transactional owner fails", async () => { const paseoHome = mkdtempSync(path.join(tmpdir(), "paseo-daemon-config-store-")); tempDirs.push(paseoHome); const store = new DaemonConfigStore(paseoHome, { @@ -272,7 +272,7 @@ describe("DaemonConfigStore", () => { throw new Error("Provider refresh failed"); }); - expect(() => store.patch({ browserTools: { enabled: true } })).toThrow( + await expect(store.patch({ browserTools: { enabled: true } })).rejects.toThrow( "Provider refresh failed", ); expect(browserToolsEnabled).toBe(false); @@ -280,7 +280,7 @@ describe("DaemonConfigStore", () => { expect(loadPersistedConfig(paseoHome).daemon?.browserTools?.enabled).toBeUndefined(); }); - test("rejects relay patches when a launch override owns the setting", () => { + test("rejects relay patches when a launch override owns the setting", async () => { const paseoHome = mkdtempSync(path.join(tmpdir(), "paseo-daemon-config-store-")); tempDirs.push(paseoHome); const store = new DaemonConfigStore( @@ -299,12 +299,12 @@ describe("DaemonConfigStore", () => { { relayEnabledMutable: false }, ); - expect(() => store.patch({ relay: { enabled: true } })).toThrow( + await expect(store.patch({ relay: { enabled: true } })).rejects.toThrow( "Relay is controlled by a daemon launch override", ); }); - test("unrelated patches do not persist a one-launch relay override", () => { + test("unrelated patches do not persist a one-launch relay override", async () => { const paseoHome = mkdtempSync(path.join(tmpdir(), "paseo-daemon-config-store-")); tempDirs.push(paseoHome); const persisted = loadPersistedConfig(paseoHome); @@ -331,12 +331,12 @@ describe("DaemonConfigStore", () => { { relayEnabledMutable: false }, ); - store.patch({ browserTools: { enabled: true } }); + await store.patch({ browserTools: { enabled: true } }); expect(loadPersistedConfig(paseoHome).daemon?.relay?.enabled).toBe(false); }); - test("unrelated patches persist only requested file intent", () => { + test("unrelated patches persist only requested file intent", async () => { const paseoHome = mkdtempSync(path.join(tmpdir(), "paseo-daemon-config-store-")); tempDirs.push(paseoHome); const before = loadPersistedConfig(paseoHome); @@ -362,7 +362,7 @@ describe("DaemonConfigStore", () => { { relayEnabledMutable: false }, ); - store.patch({ + await store.patch({ appendSystemPrompt: "Only this field", // Reload-only runtime state is accepted as unknown wire data for forward // compatibility but is not part of the patch capability. @@ -376,7 +376,7 @@ describe("DaemonConfigStore", () => { }); }); - test("patch persists provider enabled flags into config.json", () => { + test("patch persists provider enabled flags into config.json", async () => { const paseoHome = mkdtempSync(path.join(tmpdir(), "paseo-daemon-config-store-")); tempDirs.push(paseoHome); @@ -417,7 +417,7 @@ describe("DaemonConfigStore", () => { undefined, ); - store.patch({ + await store.patch({ providers: { gemini: { enabled: false }, }, @@ -432,7 +432,7 @@ describe("DaemonConfigStore", () => { }); }); - test("patch persists provider Paseo-tool policy without changing availability", () => { + test("patch persists provider Paseo-tool policy without changing availability", async () => { const paseoHome = mkdtempSync(path.join(tmpdir(), "paseo-daemon-config-store-")); tempDirs.push(paseoHome); writeFileSync( @@ -449,14 +449,14 @@ describe("DaemonConfigStore", () => { appendSystemPrompt: "", }); - store.patch({ + await store.patch({ providers: { claude: { paseoTools: { enabled: true, disabledTools: ["list_agents"] }, }, }, }); - store.patch({ + await store.patch({ providers: { claude: { paseoTools: { disabledTools: ["create_agent"] }, @@ -474,7 +474,7 @@ describe("DaemonConfigStore", () => { }); }); - test("patch removes provider entries from config.json", () => { + test("patch removes provider entries from config.json", async () => { const paseoHome = mkdtempSync(path.join(tmpdir(), "paseo-daemon-config-store-")); tempDirs.push(paseoHome); @@ -519,7 +519,7 @@ describe("DaemonConfigStore", () => { undefined, ); - const next = store.patch({ removeProviders: ["gemini"] }); + const next = await store.patch({ removeProviders: ["gemini"] }); expect(next.providers.gemini).toBeUndefined(); expect(next.providers.claude).toEqual({ enabled: false }); @@ -528,7 +528,7 @@ describe("DaemonConfigStore", () => { expect(persisted.agents?.providers?.claude).toEqual({ enabled: false }); }); - test("patch removes the providers object when the last provider is deleted", () => { + test("patch removes the providers object when the last provider is deleted", async () => { const paseoHome = mkdtempSync(path.join(tmpdir(), "paseo-daemon-config-store-")); tempDirs.push(paseoHome); @@ -567,13 +567,13 @@ describe("DaemonConfigStore", () => { undefined, ); - store.patch({ removeProviders: ["gemini"] }); + await store.patch({ removeProviders: ["gemini"] }); const persisted = loadPersistedConfig(paseoHome); expect(persisted.agents?.providers).toBeUndefined(); }); - test("patch removes deleted providers from metadata generation", () => { + test("patch removes deleted providers from metadata generation", async () => { const paseoHome = mkdtempSync(path.join(tmpdir(), "paseo-daemon-config-store-")); tempDirs.push(paseoHome); @@ -629,7 +629,7 @@ describe("DaemonConfigStore", () => { undefined, ); - const next = store.patch({ removeProviders: ["gemini"] }); + const next = await store.patch({ removeProviders: ["gemini"] }); expect(next.metadataGeneration.providers).toEqual([{ provider: "claude", model: "haiku" }]); const persisted = loadPersistedConfig(paseoHome); @@ -638,7 +638,7 @@ describe("DaemonConfigStore", () => { }); }); - test("patch persists provider removal when in-memory config is already clean", () => { + test("patch persists provider removal when in-memory config is already clean", async () => { const paseoHome = mkdtempSync(path.join(tmpdir(), "paseo-daemon-config-store-")); tempDirs.push(paseoHome); @@ -680,7 +680,7 @@ describe("DaemonConfigStore", () => { undefined, ); - const next = store.patch({ removeProviders: ["gemini"] }); + const next = await store.patch({ removeProviders: ["gemini"] }); expect(next.providers.gemini).toBeUndefined(); const persisted = loadPersistedConfig(paseoHome); @@ -688,7 +688,7 @@ describe("DaemonConfigStore", () => { expect(persisted.agents?.metadataGeneration).toEqual({ providers: [] }); }); - test("patch persists append system prompt into config.json", () => { + test("patch persists append system prompt into config.json", async () => { const paseoHome = mkdtempSync(path.join(tmpdir(), "paseo-daemon-config-store-")); tempDirs.push(paseoHome); @@ -706,7 +706,7 @@ describe("DaemonConfigStore", () => { undefined, ); - store.patch({ + await store.patch({ appendSystemPrompt: "Prefer terse replies.", }); @@ -714,7 +714,7 @@ describe("DaemonConfigStore", () => { expect(persisted.daemon?.appendSystemPrompt).toBe("Prefer terse replies."); }); - test("patch persists browser tools opt-in into config.json", () => { + test("patch persists browser tools opt-in into config.json", async () => { const paseoHome = mkdtempSync(path.join(tmpdir(), "paseo-daemon-config-store-")); tempDirs.push(paseoHome); @@ -731,13 +731,13 @@ describe("DaemonConfigStore", () => { undefined, ); - store.patch({ browserTools: { enabled: true } }); + await store.patch({ browserTools: { enabled: true } }); const persisted = loadPersistedConfig(paseoHome); expect(persisted.daemon?.browserTools).toEqual({ enabled: true }); }); - test("patch persists provider additional models into config.json", () => { + test("patch persists provider additional models into config.json", async () => { const paseoHome = mkdtempSync(path.join(tmpdir(), "paseo-daemon-config-store-")); tempDirs.push(paseoHome); @@ -755,7 +755,7 @@ describe("DaemonConfigStore", () => { undefined, ); - store.patch({ + await store.patch({ providers: { claude: { additionalModels: [ @@ -779,7 +779,7 @@ describe("DaemonConfigStore", () => { }); }); - test("patch persists daemon append system prompt into config.json", () => { + test("patch persists daemon append system prompt into config.json", async () => { const paseoHome = mkdtempSync(path.join(tmpdir(), "paseo-daemon-config-store-")); tempDirs.push(paseoHome); @@ -797,7 +797,7 @@ describe("DaemonConfigStore", () => { undefined, ); - store.patch({ + await store.patch({ appendSystemPrompt: "Prefer terse replies.", }); @@ -805,7 +805,7 @@ describe("DaemonConfigStore", () => { expect(persisted.daemon?.appendSystemPrompt).toBe("Prefer terse replies."); }); - test("patch persists enable terminal agent hooks into config.json", () => { + test("patch persists enable terminal agent hooks into config.json", async () => { const paseoHome = mkdtempSync(path.join(tmpdir(), "paseo-daemon-config-store-")); tempDirs.push(paseoHome); @@ -822,13 +822,13 @@ describe("DaemonConfigStore", () => { undefined, ); - store.patch({ enableTerminalAgentHooks: true }); + await store.patch({ enableTerminalAgentHooks: true }); const persisted = loadPersistedConfig(paseoHome); expect(persisted.daemon?.enableTerminalAgentHooks).toBe(true); }); - test("patch persists metadata generation providers into config.json", () => { + test("patch persists metadata generation providers into config.json", async () => { const paseoHome = mkdtempSync(path.join(tmpdir(), "paseo-daemon-config-store-")); tempDirs.push(paseoHome); @@ -846,7 +846,7 @@ describe("DaemonConfigStore", () => { undefined, ); - store.patch({ + await store.patch({ metadataGeneration: { providers: [ { provider: "claude", model: "haiku" }, @@ -864,7 +864,7 @@ describe("DaemonConfigStore", () => { }); }); - test("patch persists clearing metadata generation providers into config.json", () => { + test("patch persists clearing metadata generation providers into config.json", async () => { const paseoHome = mkdtempSync(path.join(tmpdir(), "paseo-daemon-config-store-")); tempDirs.push(paseoHome); @@ -899,13 +899,13 @@ describe("DaemonConfigStore", () => { undefined, ); - store.patch({ metadataGeneration: { providers: [] } }); + await store.patch({ metadataGeneration: { providers: [] } }); const persisted = loadPersistedConfig(paseoHome); expect(persisted.agents?.metadataGeneration).toEqual({ providers: [] }); }); - test("patch persists the host idle runtime cleanup opt-out for the next daemon start", () => { + test("patch persists the host idle runtime cleanup opt-out for the next daemon start", async () => { const paseoHome = mkdtempSync(path.join(tmpdir(), "paseo-daemon-config-store-")); tempDirs.push(paseoHome); writeFileSync( @@ -930,7 +930,7 @@ describe("DaemonConfigStore", () => { undefined, ); - expect(store.patch({ idleRuntimeCleanup: false }).idleRuntimeCleanup).toBe(false); + expect((await store.patch({ idleRuntimeCleanup: false })).idleRuntimeCleanup).toBe(false); expect(loadPersistedConfig(paseoHome).agents).toEqual({ metadataGeneration: { providers: [{ provider: "claude" }] }, @@ -938,11 +938,11 @@ describe("DaemonConfigStore", () => { }); expect(loadConfig(paseoHome, { env: {} }).idleRuntimeCleanup).toBe(false); - store.patch({ idleRuntimeCleanup: true }); + await store.patch({ idleRuntimeCleanup: true }); expect(loadConfig(paseoHome, { env: {} }).idleRuntimeCleanup).toBe(true); }); - test("patch persists custom ACP provider overrides into config.json", () => { + test("patch persists custom ACP provider overrides into config.json", async () => { const paseoHome = mkdtempSync(path.join(tmpdir(), "paseo-daemon-config-store-")); tempDirs.push(paseoHome); @@ -960,7 +960,7 @@ describe("DaemonConfigStore", () => { undefined, ); - store.patch({ + await store.patch({ providers: { "paseo-e2e-acp": { extends: "acp", @@ -1028,7 +1028,49 @@ describe("DaemonConfigStore reload", () => { writeFileSync(path.join(paseoHome, "config.json"), `${JSON.stringify(config, null, 2)}\n`); } - test("applies mutable edits and reports startup-only edits", () => { + test("applies overlapping plugin mutations to the latest committed sources", async () => { + const { store } = createReloadableStore({ + initialPersisted: { + plugins: { + a: { source: "directory", path: "/a", enabled: false }, + b: { source: "directory", path: "/b", enabled: true }, + }, + }, + }); + const enable = store.patch((current) => ({ + plugins: { + ...current.plugins, + a: { ...current.plugins.a!, enabled: true }, + }, + })); + const disable = store.patch((current) => ({ + plugins: { + ...current.plugins, + b: { ...current.plugins.b!, enabled: false }, + }, + })); + await Promise.all([enable, disable]); + expect(store.get().plugins).toEqual({ + a: { source: "directory", path: "/a", enabled: true }, + b: { source: "directory", path: "/b", enabled: false }, + }); + }); + + test("serializes overlapping patches before committing their combined state", async () => { + const { paseoHome, store } = createReloadableStore(); + const first = store.patch({ appendSystemPrompt: "first" }); + const second = store.patch({ browserTools: { enabled: true } }); + expect(store.get().appendSystemPrompt).toBe(""); + await Promise.all([first, second]); + expect(store.get().appendSystemPrompt).toBe("first"); + expect(store.get().browserTools.enabled).toBe(true); + expect(loadPersistedConfig(paseoHome).daemon).toMatchObject({ + appendSystemPrompt: "first", + browserTools: { enabled: true }, + }); + }); + + test("applies mutable edits and reports startup-only edits", async () => { const { paseoHome, store, persisted } = createReloadableStore(); writeConfig(paseoHome, { ...persisted, @@ -1040,7 +1082,7 @@ describe("DaemonConfigStore reload", () => { }, }); - expect(store.reload()).toEqual({ + expect(await store.reload()).toEqual({ appliedPaths: [ "daemon.browserTools.enabled", "daemon.git.maxProcessConcurrency", @@ -1053,13 +1095,13 @@ describe("DaemonConfigStore reload", () => { expect(store.get().git).toEqual({ maxProcessesPerSecond: 12, maxProcessConcurrency: 3 }); }); - test("reloads idle runtime cleanup in both directions without requiring a restart", () => { + test("reloads idle runtime cleanup in both directions without requiring a restart", async () => { const { paseoHome, store, persisted } = createReloadableStore(); const changes: unknown[] = []; store.onFieldChange("idleRuntimeCleanup", (value) => changes.push(value)); for (const enabled of [false, true]) { writeConfig(paseoHome, { ...persisted, agents: { idleRuntimeCleanup: enabled } }); - expect(store.reload()).toEqual({ + expect(await store.reload()).toEqual({ appliedPaths: ["agents.idleRuntimeCleanup"], restartRequiredPaths: [], overrideControlledPaths: [], @@ -1067,8 +1109,8 @@ describe("DaemonConfigStore reload", () => { expect(store.get().idleRuntimeCleanup).toBe(enabled); } expect(changes).toEqual([false, true]); - store.patch({ idleRuntimeCleanup: false }); - expect(store.reload()).toEqual({ + await store.patch({ idleRuntimeCleanup: false }); + expect(await store.reload()).toEqual({ appliedPaths: [], restartRequiredPaths: [], overrideControlledPaths: [], @@ -1076,7 +1118,7 @@ describe("DaemonConfigStore reload", () => { expect(store.get().idleRuntimeCleanup).toBe(false); }); - test("applies the global plugin switch in both directions", () => { + test("applies the global plugin switch in both directions", async () => { const { paseoHome, store, persisted } = createReloadableStore({ initialPersisted: { version: 1, pluginsEnabled: false }, }); @@ -1084,7 +1126,7 @@ describe("DaemonConfigStore reload", () => { store.onFieldChange("pluginsEnabled", (value) => changes.push(value)); writeConfig(paseoHome, { ...persisted, pluginsEnabled: true }); - expect(store.reload()).toEqual({ + expect(await store.reload()).toEqual({ appliedPaths: ["pluginsEnabled"], restartRequiredPaths: [], overrideControlledPaths: [], @@ -1092,7 +1134,7 @@ describe("DaemonConfigStore reload", () => { expect(store.get().pluginsEnabled).toBe(true); writeConfig(paseoHome, { ...persisted, pluginsEnabled: false }); - expect(store.reload()).toEqual({ + expect(await store.reload()).toEqual({ appliedPaths: ["pluginsEnabled"], restartRequiredPaths: [], overrideControlledPaths: [], @@ -1101,7 +1143,7 @@ describe("DaemonConfigStore reload", () => { expect(changes).toEqual([true, false]); }); - test("classifies every leaf when a parent subtree is added", () => { + test("classifies every leaf when a parent subtree is added", async () => { const { paseoHome, store } = createReloadableStore({ initialPersisted: { version: 1 }, }); @@ -1116,14 +1158,14 @@ describe("DaemonConfigStore reload", () => { }, }); - expect(store.reload()).toEqual({ + expect(await store.reload()).toEqual({ appliedPaths: ["daemon.relay.enabled"], restartRequiredPaths: ["daemon.relay.endpoint", "daemon.relay.useTls"], overrideControlledPaths: [], }); }); - test("classifies every leaf when the daemon subtree is removed", () => { + test("classifies every leaf when the daemon subtree is removed", async () => { const { paseoHome, store } = createReloadableStore({ initialPersisted: { version: 1, @@ -1144,7 +1186,7 @@ describe("DaemonConfigStore reload", () => { }); writeConfig(paseoHome, { version: 1 }); - expect(store.reload()).toEqual({ + expect(await store.reload()).toEqual({ appliedPaths: ["daemon.browserTools.enabled"], restartRequiredPaths: [ "daemon.listen", @@ -1158,7 +1200,7 @@ describe("DaemonConfigStore reload", () => { expect(store.get().relay?.enabled).toBe(false); }); - test("keeps overridden leaves separate from restart-required siblings", () => { + test("keeps overridden leaves separate from restart-required siblings", async () => { const { paseoHome, store } = createReloadableStore({ initialPersisted: { version: 1 }, overrideControlledPaths: ["daemon.relay.enabled"], @@ -1170,25 +1212,25 @@ describe("DaemonConfigStore reload", () => { }, }); - expect(store.reload()).toEqual({ + expect(await store.reload()).toEqual({ appliedPaths: [], restartRequiredPaths: ["daemon.relay.endpoint"], overrideControlledPaths: ["daemon.relay.enabled"], }); }); - test("invalid JSON and invalid schema apply nothing", () => { + test("invalid JSON and invalid schema apply nothing", async () => { const { paseoHome, store } = createReloadableStore(); writeFileSync(path.join(paseoHome, "config.json"), "{ nope\n"); - expect(() => store.reload()).toThrow("Invalid JSON"); + await expect(store.reload()).rejects.toThrow("Invalid JSON"); expect(store.get().browserTools.enabled).toBe(false); writeConfig(paseoHome, { daemon: { browserTools: { enabled: "yes" } } }); - expect(() => store.reload()).toThrow("Invalid config"); + await expect(store.reload()).rejects.toThrow("Invalid config"); expect(store.get().browserTools.enabled).toBe(false); }); - test("removing providers and optional profiles clears live state", () => { + test("removing providers and optional profiles clears live state", async () => { const { paseoHome, store, persisted } = createReloadableStore(); writeConfig(paseoHome, { ...persisted, @@ -1203,10 +1245,10 @@ describe("DaemonConfigStore reload", () => { }, }, }); - store.reload(); + await store.reload(); writeConfig(paseoHome, persisted); - const result = store.reload(); + const result = await store.reload(); expect(result.appliedPaths).toEqual([ "agents.providers", @@ -1218,7 +1260,7 @@ describe("DaemonConfigStore reload", () => { expect(store.get().agentProfiles).toBeUndefined(); }); - test("reports a launch-controlled edit without changing live state", () => { + test("reports a launch-controlled edit without changing live state", async () => { const { paseoHome, store, persisted } = createReloadableStore({ overrideControlledPaths: ["daemon.relay.enabled"], }); @@ -1228,7 +1270,7 @@ describe("DaemonConfigStore reload", () => { daemon: { ...persisted.daemon, relay: { enabled: !initialRelay } }, }); - expect(store.reload()).toEqual({ + expect(await store.reload()).toEqual({ appliedPaths: [], restartRequiredPaths: [], overrideControlledPaths: ["daemon.relay.enabled"], @@ -1236,7 +1278,7 @@ describe("DaemonConfigStore reload", () => { expect(store.get().relay?.enabled).toBe(initialRelay); }); - test("an unrelated patch does not mark a manual override-owned edit as applied", () => { + test("an unrelated patch does not mark a manual override-owned edit as applied", async () => { const { paseoHome, store, persisted } = createReloadableStore({ overrideControlledPaths: ["daemon.relay.enabled"], }); @@ -1244,16 +1286,16 @@ describe("DaemonConfigStore reload", () => { ...persisted, daemon: { ...persisted.daemon, relay: { enabled: true } }, }); - store.patch({ appendSystemPrompt: "patched elsewhere" }); + await store.patch({ appendSystemPrompt: "patched elsewhere" }); - expect(store.reload()).toEqual({ + expect(await store.reload()).toEqual({ appliedPaths: [], restartRequiredPaths: [], overrideControlledPaths: ["daemon.relay.enabled"], }); }); - test("reports startup-only launch overrides instead of restart warnings", () => { + test("reports startup-only launch overrides instead of restart warnings", async () => { const { paseoHome, store, persisted } = createReloadableStore({ overrideControlledPaths: ["daemon.listen", "daemon.relay.endpoint"], }); @@ -1269,16 +1311,16 @@ describe("DaemonConfigStore reload", () => { }, }); - expect(store.reload()).toEqual({ + expect(await store.reload()).toEqual({ appliedPaths: [], restartRequiredPaths: [], overrideControlledPaths: ["daemon.listen", "daemon.relay.endpoint"], }); }); - test("a no-op reload returns empty path lists", () => { + test("a no-op reload returns empty path lists", async () => { const { store } = createReloadableStore(); - expect(store.reload()).toEqual({ + expect(await store.reload()).toEqual({ appliedPaths: [], restartRequiredPaths: [], overrideControlledPaths: [], @@ -1317,25 +1359,25 @@ describe("DaemonConfigStore speech settings", () => { return { paseoHome, store, applied, persisted }; } - test("reads, patches, and clears local STT language without losing it on other saves", () => { + test("reads, patches, and clears local STT language without losing it on other saves", async () => { const { paseoHome, store } = createSpeechStore({ features: { dictation: { stt: { language: "fr" } } }, }); expect(store.get().features?.dictation.stt).toEqual({ provider: "local", language: "fr" }); - store.patch({ features: { voiceMode: { enabled: true } } }); + await store.patch({ features: { voiceMode: { enabled: true } } }); expect(loadPersistedConfig(paseoHome).features?.dictation?.stt).toEqual({ provider: "local", language: "fr", }); - const patched = store.patch({ + const patched = await store.patch({ features: { dictation: { stt: { provider: "local", language: "de" } } }, }); expect(patched.features?.dictation.stt).toEqual({ provider: "local", language: "de" }); - store.patch({ features: { dictation: { stt: { language: null } } } }); + await store.patch({ features: { dictation: { stt: { language: null } } } }); expect(loadPersistedConfig(paseoHome).features?.dictation?.stt).toEqual({ provider: "local" }); }); - test("reports language env overrides for both local STT sites", () => { + test("reports language env overrides for both local STT sites", async () => { const { store } = createSpeechStore( {}, { PASEO_DICTATION_LANGUAGE: "fr", PASEO_VOICE_LANGUAGE: "de" }, @@ -1346,22 +1388,22 @@ describe("DaemonConfigStore speech settings", () => { }); }); - test("keeps voice mode off until it is turned on", () => { + test("keeps voice mode off until it is turned on", async () => { const { paseoHome, store } = createSpeechStore(); expect(store.get().features?.dictation.enabled).toBe(true); expect(store.get().features?.voiceMode.enabled).toBe(false); - const result = store.patch({ features: { voiceMode: { enabled: true } } }); + const result = await store.patch({ features: { voiceMode: { enabled: true } } }); expect(result.features?.voiceMode.enabled).toBe(true); expect(loadPersistedConfig(paseoHome).features?.voiceMode?.enabled).toBe(true); }); - test("stores the OpenAI key without ever returning it", () => { + test("stores the OpenAI key without ever returning it", async () => { const { paseoHome, store, applied } = createSpeechStore(); - const result = store.patch({ + const result = await store.patch({ features: { dictation: { stt: { provider: "openai", apiKey: " sk-test " } } }, }); @@ -1373,26 +1415,26 @@ describe("DaemonConfigStore speech settings", () => { expect(applied).toHaveLength(1); }); - test("applies a replaced key even though the visible settings do not change", () => { + test("applies a replaced key even though the visible settings do not change", async () => { const { store, applied } = createSpeechStore({ version: 1, features: { dictation: { stt: { provider: "openai", apiKey: "sk-old" } } }, }); - store.patch({ features: { dictation: { stt: { apiKey: "sk-new" } } } }); + await store.patch({ features: { dictation: { stt: { apiKey: "sk-new" } } } }); expect(applied.map((next) => next.features?.dictation?.stt)).toEqual([ { provider: "openai", apiKey: "sk-new" }, ]); }); - test("switching provider clears the previous provider's model", () => { + test("switching provider clears the previous provider's model", async () => { const { paseoHome, store } = createSpeechStore({ version: 1, features: { dictation: { stt: { provider: "local", model: "parakeet-tdt-0.6b-v3-int8" } } }, }); - const result = store.patch({ features: { dictation: { stt: { provider: "openai" } } } }); + const result = await store.patch({ features: { dictation: { stt: { provider: "openai" } } } }); expect(result.features?.dictation.stt).toEqual({ provider: "openai", hasApiKey: false }); expect(loadPersistedConfig(paseoHome).features?.dictation?.stt).toEqual({ @@ -1400,62 +1442,62 @@ describe("DaemonConfigStore speech settings", () => { }); }); - test("rejects a local model id outside the catalog without persisting it", () => { + test("rejects a local model id outside the catalog without persisting it", async () => { const { paseoHome, store, applied } = createSpeechStore(); - expect(() => + await expect( store.patch({ features: { voiceMode: { tts: { provider: "local", model: "nope" } } } }), - ).toThrow("Unknown local voice model: nope"); + ).rejects.toThrow("Unknown local voice model: nope"); expect(loadPersistedConfig(paseoHome).features?.voiceMode).toBeUndefined(); expect(applied).toEqual([]); }); - test("reload applies hand-edited speech settings without a restart", () => { + test("reload applies hand-edited speech settings without a restart", async () => { const { paseoHome, store, applied, persisted } = createSpeechStore(); writeFileSync( path.join(paseoHome, "config.json"), `${JSON.stringify({ ...persisted, features: { voiceMode: { enabled: false } } }, null, 2)}\n`, ); - const result = store.reload(); + const result = await store.reload(); expect(result.appliedPaths).toContain("features.voiceMode"); expect(result.restartRequiredPaths).toEqual([]); expect(store.get().features?.voiceMode.enabled).toBe(false); expect(applied).toHaveLength(1); }); - test("merges same-provider fields and replaces the whole variant when provider changes", () => { + test("merges same-provider fields and replaces the whole variant when provider changes", async () => { const { paseoHome, store } = createSpeechStore(); - store.patch({ + await store.patch({ features: { voiceMode: { stt: { provider: "openai", apiKey: "secret", baseUrl: "https://site/v1", model: "first" }, }, }, }); - store.patch({ features: { voiceMode: { stt: { model: "second", baseUrl: null } } } }); + await store.patch({ features: { voiceMode: { stt: { model: "second", baseUrl: null } } } }); expect(loadPersistedConfig(paseoHome).features?.voiceMode?.stt).toEqual({ provider: "openai", apiKey: "secret", model: "second", }); - store.patch({ features: { voiceMode: { stt: { provider: "openai", model: "third" } } } }); + await store.patch({ features: { voiceMode: { stt: { provider: "openai", model: "third" } } } }); expect(store.get().features?.voiceMode.stt).toEqual({ provider: "openai", model: "third", hasApiKey: true, }); - store.patch({ features: { voiceMode: { stt: { apiKey: "new-secret" } } } }); - store.patch({ features: { voiceMode: { stt: { provider: "local" } } } }); - store.patch({ features: { voiceMode: { stt: { provider: "openai" } } } }); + await store.patch({ features: { voiceMode: { stt: { apiKey: "new-secret" } } } }); + await store.patch({ features: { voiceMode: { stt: { provider: "local" } } } }); + await store.patch({ features: { voiceMode: { stt: { provider: "openai" } } } }); expect(store.get().features?.voiceMode.stt).toEqual({ provider: "openai", hasApiKey: false }); }); - test("keeps a saved OpenAI key when a full variant patch omits the write-only key", () => { + test("keeps a saved OpenAI key when a full variant patch omits the write-only key", async () => { const { paseoHome, store } = createSpeechStore({ features: { voiceMode: { stt: { provider: "openai", apiKey: "saved-secret" } } }, }); - const result = store.patch({ + const result = await store.patch({ features: { voiceMode: { stt: { provider: "openai", model: "whisper-1" } } }, }); expect(result.features?.voiceMode.stt).toEqual({ @@ -1471,7 +1513,7 @@ describe("DaemonConfigStore speech settings", () => { expect(JSON.stringify(result)).not.toContain("saved-secret"); }); - test("loads a legacy host, redacts its key and writes the normalized config after any save", () => { + test("loads a legacy host, redacts its key and writes the normalized config after any save", async () => { const { paseoHome, store } = createSpeechStore({ providers: { openai: { apiKey: "legacy-secret", stt: { baseUrl: "https://old/v1" } } }, features: { voiceMode: { enabled: true, stt: { provider: "openai" } } }, @@ -1482,13 +1524,13 @@ describe("DaemonConfigStore speech settings", () => { hasApiKey: true, }); expect(JSON.stringify(store.get())).not.toContain("legacy-secret"); - store.patch({ autoArchiveAfterMerge: true }); + await store.patch({ autoArchiveAfterMerge: true }); const disk = JSON.parse(readFileSync(path.join(paseoHome, "config.json"), "utf8")); expect(disk.providers).not.toHaveProperty("openai"); expect(disk.features.voiceMode.stt.apiKey).toBe("legacy-secret"); }); - test("reports env overrides and removes fallback provenance after saving a key", () => { + test("reports env overrides and removes fallback provenance after saving a key", async () => { const { store } = createSpeechStore( { features: { voiceMode: { stt: { provider: "openai", model: "configured" } } } }, { @@ -1514,7 +1556,7 @@ describe("DaemonConfigStore speech settings", () => { "features.voiceMode.stt.model": "STT_MODEL", }); expect(other.get().features?.voiceMode.stt.hasApiKey).toBe(false); - other.patch({ + await other.patch({ features: { voiceMode: { stt: { apiKey: "saved-secret", baseUrl: "https://saved/v1" } } }, }); expect(other.get().envOverrides).toEqual({ "features.voiceMode.stt.model": "STT_MODEL" }); diff --git a/packages/server/src/server/daemon-config-store.ts b/packages/server/src/server/daemon-config-store.ts index 51957e15f6..57b9a6b916 100644 --- a/packages/server/src/server/daemon-config-store.ts +++ b/packages/server/src/server/daemon-config-store.ts @@ -1,6 +1,7 @@ import { loadPersistedConfig, - savePersistedConfig, + savePersistedConfigAsync, + loadPersistedConfigAsync, type PersistedConfig, } from "./persisted-config.js"; import { ProviderOverrideSchema } from "./agent/provider-launch-config.js"; @@ -335,6 +336,7 @@ export function applyMutableProviderConfigToOverrides( } export class DaemonConfigStore { + private mutations: Promise = Promise.resolve(); private current: MutableDaemonConfig; private readonly paseoHome: string; private readonly logger: LoggerLike | undefined; @@ -376,16 +378,29 @@ export class DaemonConfigStore { return this.current; } - public patch(partial: MutableDaemonConfigPatch): MutableDaemonConfig { - const parsedPatch = pickSupportedPatchFields(MutableDaemonConfigPatchSchema.parse(partial)); - return this.applySupportedPatch(parsedPatch); + public patch( + partial: + | MutableDaemonConfigPatch + | ((current: MutableDaemonConfig) => MutableDaemonConfigPatch), + ): Promise { + return this.enqueue(() => + this.applySupportedPatch( + pickSupportedPatchFields( + MutableDaemonConfigPatchSchema.parse( + typeof partial === "function" ? partial(this.current) : partial, + ), + ), + ), + ); } - public setAgentSkillSelection(selection: AgentSkillSelection): MutableDaemonConfig { - return this.applySupportedPatch({ skills: { selection } }); + public setAgentSkillSelection(selection: AgentSkillSelection): Promise { + return this.enqueue(() => this.applySupportedPatch({ skills: { selection } })); } - private applySupportedPatch(parsedPatch: SupportedMutableConfigPatch): MutableDaemonConfig { + private async applySupportedPatch( + parsedPatch: SupportedMutableConfigPatch, + ): Promise { if (parsedPatch.relay?.enabled !== undefined && !this.relayEnabledMutable) { throw new Error( "Relay is controlled by a daemon launch override. Remove PASEO_RELAY_ENABLED or the relay CLI flag before changing it here.", @@ -414,7 +429,7 @@ export class DaemonConfigStore { return this.current; } - const { previous: persistedBeforePatch, knownNext } = this.persistConfig( + const { previous: persistedBeforePatch, knownNext } = await this.persistConfig( patch, removedProviders, ); @@ -423,7 +438,7 @@ export class DaemonConfigStore { try { this.applyReplacement(next, { removedProviders }); } catch (error) { - savePersistedConfig(this.paseoHome, persistedBeforePatch, this.logger); + await savePersistedConfigAsync(this.paseoHome, persistedBeforePatch, this.logger); throw error; } } @@ -454,12 +469,16 @@ export class DaemonConfigStore { ); } - public reload(): DaemonConfigReloadResult { + public reload(): Promise { + return this.enqueue(() => this.reloadPersisted()); + } + + private async reloadPersisted(): Promise { if (!this.reloadSource) { throw new Error("Daemon config reload is unavailable for this daemon instance"); } - const persisted = loadPersistedConfig(this.paseoHome, this.logger); + const persisted = await loadPersistedConfigAsync(this.paseoHome, this.logger); const resolved = this.reloadSource.resolve(persisted); // Plugin source changes require the plugin lifecycle operation or a daemon // restart. The global switch is independently reloadable. @@ -621,11 +640,24 @@ export class DaemonConfigStore { }; } - private persistConfig( + private enqueue(operation: () => Promise): Promise { + const result = this.mutations.then(operation); + this.mutations = result.catch(() => {}); + return result; + } + + public readServicePorts(): Promise["servicePorts"]> { + return this.enqueue( + async () => + (await loadPersistedConfigAsync(this.paseoHome, this.logger)).worktrees?.servicePorts, + ); + } + + private async persistConfig( patch: Omit, removeProviders: readonly string[], - ): { previous: PersistedConfig; knownNext: PersistedConfig } { - const persisted = loadPersistedConfig(this.paseoHome, this.logger); + ): Promise<{ previous: PersistedConfig; knownNext: PersistedConfig }> { + const persisted = await loadPersistedConfigAsync(this.paseoHome, this.logger); const merge = (source: PersistedConfig) => mergeMutablePatchIntoPersistedConfig({ persisted: source, @@ -635,7 +667,7 @@ export class DaemonConfigStore { }); const nextPersisted = merge(persisted); const knownNext = merge(this.lastKnownPersisted); - savePersistedConfig(this.paseoHome, nextPersisted, this.logger); + await savePersistedConfigAsync(this.paseoHome, nextPersisted, this.logger); return { previous: persisted, knownNext }; } } diff --git a/packages/server/src/server/orchestration-skills/internal/selection-store.test.ts b/packages/server/src/server/orchestration-skills/internal/selection-store.test.ts index 5a42fd0dac..50fb071fef 100644 --- a/packages/server/src/server/orchestration-skills/internal/selection-store.test.ts +++ b/packages/server/src/server/orchestration-skills/internal/selection-store.test.ts @@ -57,7 +57,7 @@ describe("daemon agent skill selection", () => { it("does not expose selection through the generic config patch path", async () => { const { config, root, store } = await createStore(); - config.patch({ + await config.patch({ skills: { selection: { mode: "custom", skills: ["paseo"] } }, } as MutableDaemonConfigPatch); diff --git a/packages/server/src/server/orchestration-skills/internal/selection-store.ts b/packages/server/src/server/orchestration-skills/internal/selection-store.ts index 6fa00af6e6..a3f7f95569 100644 --- a/packages/server/src/server/orchestration-skills/internal/selection-store.ts +++ b/packages/server/src/server/orchestration-skills/internal/selection-store.ts @@ -43,7 +43,7 @@ export function createSkillSelectionStore( }, async set(selection) { const parsed = coerceSkillSelection(selection); - configStore.setAgentSkillSelection(parsed); + await configStore.setAgentSkillSelection(parsed); return parsed; }, async isSet() { diff --git a/packages/server/src/server/persisted-config.test.ts b/packages/server/src/server/persisted-config.test.ts index 019bcbb0f8..fb38e41591 100644 --- a/packages/server/src/server/persisted-config.test.ts +++ b/packages/server/src/server/persisted-config.test.ts @@ -16,9 +16,11 @@ import { describe, expect, test } from "vitest"; import { loadPersistedConfig, + loadPersistedConfigAsync, PersistedConfigSchema, readPersistedConfig, savePersistedConfig, + savePersistedConfigAsync, } from "./persisted-config.js"; import { PRIVATE_DIRECTORY_MODE, PRIVATE_FILE_MODE } from "./private-files.js"; @@ -827,11 +829,14 @@ describe("readPersistedConfig with an unreadable config.json", () => { }); }); -describe.skipIf(process.platform === "win32")("persisted config file permissions", () => { - test("initializes config.json with private permissions", () => { +describe.skipIf(process.platform === "win32").each([ + { name: "startup", load: loadPersistedConfig, save: savePersistedConfig }, + { name: "runtime", load: loadPersistedConfigAsync, save: savePersistedConfigAsync }, +])("persisted config file permissions ($name)", ({ load, save }) => { + test("initializes config.json with private permissions", async () => { const home = createTempHome(); try { - loadPersistedConfig(home); + await load(home); expect(modeOf(path.join(home, "config.json"))).toBe(PRIVATE_FILE_MODE); } finally { @@ -839,14 +844,14 @@ describe.skipIf(process.platform === "win32")("persisted config file permissions } }); - test("repairs permissive config.json permissions when loading", () => { + test("repairs permissive config.json permissions when loading", async () => { const home = createTempHome(); const configPath = path.join(home, "config.json"); try { writeFileSync(configPath, "{}\n", { mode: PERMISSIVE_FILE_MODE }); chmodSync(configPath, PERMISSIVE_FILE_MODE); - loadPersistedConfig(home); + await load(home); expect(modeOf(configPath)).toBe(PRIVATE_FILE_MODE); } finally { @@ -854,11 +859,24 @@ describe.skipIf(process.platform === "win32")("persisted config file permissions } }); - test("saves config.json with private permissions", () => { + test("repairs unreadable owner permissions before reading config.json", async () => { + const home = createTempHome(); + const configPath = path.join(home, "config.json"); + try { + writeFileSync(configPath, "{}\n"); + chmodSync(configPath, 0); + expect(await load(home)).toEqual({}); + expect(modeOf(configPath)).toBe(PRIVATE_FILE_MODE); + } finally { + rmSync(home, { recursive: true, force: true }); + } + }); + + test("saves config.json with private permissions", async () => { const parent = createTempHome(); const home = path.join(parent, "home"); try { - savePersistedConfig(home, { + await save(home, { features: { dictation: { stt: { provider: "openai", apiKey: "secret" } } }, }); @@ -870,37 +888,37 @@ describe.skipIf(process.platform === "win32")("persisted config file permissions }); }); -describe.skipIf(process.platform === "win32")( - "config.json symlinked from another directory", - () => { - test("saving writes through the symlink and leaves it in place", () => { - const parent = createTempHome(); - const home = path.join(parent, "home"); - const dotfiles = path.join(parent, "dotfiles"); - const linkedConfigPath = path.join(dotfiles, "config.json"); - const configPath = path.join(home, "config.json"); - try { - mkdirSync(home); - mkdirSync(dotfiles, { mode: 0o755 }); - chmodSync(dotfiles, 0o755); - writeFileSync(linkedConfigPath, '{ "version": 1 }\n'); - symlinkSync(linkedConfigPath, configPath); +describe.skipIf(process.platform === "win32").each([ + { name: "startup", save: savePersistedConfig }, + { name: "runtime", save: savePersistedConfigAsync }, +])("config.json symlinked from another directory ($name)", ({ save }) => { + test("saving writes through the symlink and leaves it in place", async () => { + const parent = createTempHome(); + const home = path.join(parent, "home"); + const dotfiles = path.join(parent, "dotfiles"); + const linkedConfigPath = path.join(dotfiles, "config.json"); + const configPath = path.join(home, "config.json"); + try { + mkdirSync(home); + mkdirSync(dotfiles, { mode: 0o755 }); + chmodSync(dotfiles, 0o755); + writeFileSync(linkedConfigPath, '{ "version": 1 }\n'); + symlinkSync(linkedConfigPath, configPath); - savePersistedConfig(home, { version: 1, daemon: { relay: { enabled: false } } }); + await save(home, { version: 1, daemon: { relay: { enabled: false } } }); - expect(lstatSync(configPath).isSymbolicLink()).toBe(true); - expect(JSON.parse(readFileSync(linkedConfigPath, "utf8"))).toEqual({ - version: 1, - daemon: { relay: { enabled: false } }, - }); - expect(modeOf(dotfiles)).toBe(0o755); - expect(modeOf(linkedConfigPath)).toBe(PRIVATE_FILE_MODE); - } finally { - rmSync(parent, { recursive: true, force: true }); - } - }); - }, -); + expect(lstatSync(configPath).isSymbolicLink()).toBe(true); + expect(JSON.parse(readFileSync(linkedConfigPath, "utf8"))).toEqual({ + version: 1, + daemon: { relay: { enabled: false } }, + }); + expect(modeOf(dotfiles)).toBe(0o755); + expect(modeOf(linkedConfigPath)).toBe(PRIVATE_FILE_MODE); + } finally { + rmSync(parent, { recursive: true, force: true }); + } + }); +}); describe("speech provider config normalization", () => { test.each([undefined, "local"])( diff --git a/packages/server/src/server/persisted-config.ts b/packages/server/src/server/persisted-config.ts index c6c3f9c7e1..51bfb3d3a4 100644 --- a/packages/server/src/server/persisted-config.ts +++ b/packages/server/src/server/persisted-config.ts @@ -1,3 +1,4 @@ +import { readFile } from "node:fs/promises"; import { PluginRegistriesSchema } from "@getpaseo/protocol/plugin-registry"; import { existsSync, readFileSync } from "node:fs"; import path from "node:path"; @@ -9,7 +10,12 @@ import { ProviderOverridesSchema, } from "./agent/provider-launch-config.js"; import type { AgentProviderRuntimeSettingsMap } from "./agent/provider-launch-config.js"; -import { ensurePrivateFile, writePrivateFileAtomicSync } from "./private-files.js"; +import { + ensurePrivateFile, + ensurePrivateFileAsync, + writePrivateFileAtomic, + writePrivateFileAtomicSync, +} from "./private-files.js"; import { AgentProfileSchema, AgentSkillSelectionSchema } from "@getpaseo/protocol/agent-profile"; import { PluginIdSchema, PluginSourceSchema } from "@getpaseo/protocol/plugin-config"; import { TerminalProfileSchema } from "@getpaseo/protocol/terminal-profile"; @@ -523,6 +529,40 @@ export function loadPersistedConfig(paseoHome: string, logger?: LoggerLike): Per return config; } +/** Runtime config IO. Startup and offline CLI consumers retain their synchronous entry points. */ +export async function loadPersistedConfigAsync( + paseoHome: string, + logger?: LoggerLike, +): Promise { + const log = getLogger(logger); + const configPath = getConfigPath(paseoHome); + let raw: string; + await ensurePrivateFileAsync(configPath); + try { + raw = await readFile(configPath, "utf-8"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") { + throw new Error( + `[Config] Failed to read ${configPath}: ${error instanceof Error ? error.message : String(error)}`, + { cause: error }, + ); + } + try { + raw = JSON.stringify(DEFAULT_PERSISTED_CONFIG, null, 2) + "\n"; + await writePrivateFileAtomic(configPath, raw); + log?.info(`Initialized config file at ${configPath}`); + } catch (initializationError) { + throw new Error( + `[Config] Failed to initialize ${configPath}: ${initializationError instanceof Error ? initializationError.message : String(initializationError)}`, + { cause: initializationError }, + ); + } + } + const config = parseConfigFile(configPath, raw, log); + log?.info(`Loaded from ${configPath}`); + return config; +} + /** Observe the file without initializing a home, identity, or default configuration. */ export function readPersistedConfig( paseoHome: string, @@ -642,16 +682,10 @@ export function savePersistedConfig( const log = getLogger(logger); const configPath = getConfigPath(paseoHome); - const result = PersistedConfigSchema.safeParse(config); - if (!result.success) { - const issues = result.error.issues - .map((i) => ` - ${i.path.join(".")}: ${i.message}`) - .join("\n"); - throw new Error(`[Config] Invalid config to save:\n${issues}`); - } + const data = serializePersistedConfig(config); try { - writePrivateFileAtomicSync(configPath, JSON.stringify(result.data, null, 2) + "\n"); + writePrivateFileAtomicSync(configPath, data); log?.info(`Saved to ${configPath}`); } catch (err) { const message = err instanceof Error ? err.message : String(err); @@ -660,3 +694,33 @@ export function savePersistedConfig( }); } } + +function serializePersistedConfig(config: PersistedConfig): string { + const result = PersistedConfigSchema.safeParse(config); + if (!result.success) { + const issues = result.error.issues + .map((i) => ` - ${i.path.join(".")}: ${i.message}`) + .join("\n"); + throw new Error(`[Config] Invalid config to save:\n${issues}`); + } + + return JSON.stringify(result.data, null, 2) + "\n"; +} + +export async function savePersistedConfigAsync( + paseoHome: string, + config: PersistedConfig, + logger?: LoggerLike, +): Promise { + const configPath = getConfigPath(paseoHome); + const data = serializePersistedConfig(config); + try { + await writePrivateFileAtomic(configPath, data); + getLogger(logger)?.info(`Saved to ${configPath}`); + } catch (error) { + throw new Error( + `[Config] Failed to write ${configPath}: ${error instanceof Error ? error.message : String(error)}`, + { cause: error }, + ); + } +} diff --git a/packages/server/src/server/plugins/index.posix.test.ts b/packages/server/src/server/plugins/index.posix.test.ts index 71fe2b96e9..4ca5aeefd5 100644 --- a/packages/server/src/server/plugins/index.posix.test.ts +++ b/packages/server/src/server/plugins/index.posix.test.ts @@ -526,7 +526,7 @@ describe("PluginService", () => { if (!address || typeof address === "string") throw new Error("Missing registry address"); const url = `http://127.0.0.1:${address.port}`; const store = createStore(home); - store.patch({ pluginsEnabled: false }); + await store.patch({ pluginsEnabled: false }); const service = bindTestSessionHost( new PluginService(pino({ level: "silent" }), store, "0.4.0", { managedSources: new ManagedPluginSources(home, { defaultUrl: url }), @@ -1079,13 +1079,13 @@ export default function contribute(plugin: unknown) { await service.installDirectory({ path: first }); await service.installDirectory({ path: second }); - store.patch({ pluginsEnabled: false }); + await store.patch({ pluginsEnabled: false }); expect(service.catalog()).toEqual([]); await expect(service.invokePluginRpc("second", "anything", {})).rejects.toThrow( "Plugin is not available", ); - store.patch({ pluginsEnabled: true }); + await store.patch({ pluginsEnabled: true }); await service.reloadPlugin("first"); expect((await service.listPlugins()).map(({ id, status }) => ({ id, status }))).toEqual([ { id: "first", status: "running" }, @@ -1100,16 +1100,16 @@ export default function contribute(plugin: unknown) { const store = createStore(home, { slow: { source: "directory", path: "/plugins/slow", enabled: true }, }); - store.patch({ pluginsEnabled: false }); + await store.patch({ pluginsEnabled: false }); const paused = createPausedRuntime(); const service = new PluginService(pino({ level: "silent" }), store, "0.4.0", { runtime: paused.runtime, }); await service.start(); - store.patch({ pluginsEnabled: true }); + await store.patch({ pluginsEnabled: true }); await paused.started; - store.patch({ pluginsEnabled: false }); + await store.patch({ pluginsEnabled: false }); paused.releaseStart(); await service.stopAllPlugins(); @@ -1119,6 +1119,47 @@ export default function contribute(plugin: unknown) { ]); }); + it("persists overlapping enable and disable without losing either source mutation", async () => { + const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-home-")); + roots.push(home); + const store = createStore(home, { + a: { source: "directory", path: "/plugins/a", enabled: false }, + b: { source: "directory", path: "/plugins/b", enabled: true }, + }); + const paused = createPluginSelectivePausedRuntime("unused"); + const service = new PluginService(pino({ level: "silent" }), store, "0.4.0", { + runtime: paused.runtime, + }); + await service.start(); + await Promise.all([service.enablePlugin("a"), service.disablePlugin("b")]); + expect(store.get().plugins).toEqual({ + a: { source: "directory", path: "/plugins/a", enabled: true }, + b: { source: "directory", path: "/plugins/b", enabled: false }, + }); + await service.stopAllPlugins(); + }); + + it("clears a failed disable intent so the previous enabled state can publish", async () => { + const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-home-")); + roots.push(home); + const store = createStore(home, { + slow: { source: "directory", path: "/plugins/slow", enabled: false }, + }); + const paused = createPausedRuntime(); + const service = new PluginService(pino({ level: "silent" }), store, "0.4.0", { + runtime: paused.runtime, + }); + await service.start(); + const enabling = service.enablePlugin("slow"); + await paused.started; + await writeFile(path.join(home, "config.json"), "invalid JSON"); + await expect(service.disablePlugin("slow")).rejects.toThrow("Invalid JSON"); + paused.releaseStart(); + await expect(enabling).resolves.toMatchObject({ enabled: true, status: "running" }); + expect(service.catalog()).toEqual([{ id: "slow", clientBundle: "bundle" }]); + await service.stopAllPlugins(); + }); + it("does not publish an in-flight enable after a later plugin disable", async () => { const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-home-")); roots.push(home); diff --git a/packages/server/src/server/plugins/index.ts b/packages/server/src/server/plugins/index.ts index 8385dc2122..98e7ce5623 100644 --- a/packages/server/src/server/plugins/index.ts +++ b/packages/server/src/server/plugins/index.ts @@ -97,6 +97,10 @@ export class PluginService { private readonly providerListeners = new Set<() => void>(); private lifecycle = Promise.resolve(); private globalStartsBlocked = true; + private readonly pendingOperations = new Map< + string, + { kind: "disable" | "remove"; completion: Promise } + >(); private started = false; private readonly settingsListeners = new Set<(pluginId: string, settingsId: string) => void>(); @@ -298,11 +302,7 @@ export class PluginService { `Plugin ID "${pluginId}" is already configured; choose another ID with --id`, ); } - const sources = { - ...this.configStore.get().plugins, - [pluginId]: { source: "directory" as const, path: directory, enabled: true }, - }; - this.configStore.patch({ plugins: sources }); + await this.patchSource(pluginId, { source: "directory", path: directory, enabled: true }); if (this.canPublish(pluginId)) await this.startConfigured(pluginId); this.notify(pluginId); const installed = await this.requireItem(pluginId); @@ -361,15 +361,17 @@ export class PluginService { await managedSources.discard(candidate); throw error; } - this.patchSource(pluginId, { source: "directory", path: candidate.directory, enabled: true }); + await this.patchSource(pluginId, { + source: "directory", + path: candidate.directory, + enabled: true, + }); try { if (this.canPublish(pluginId)) await this.startExplicit(pluginId, candidate.directory); managedSources.commit(pluginId, candidate.record); } catch (error) { await this.stopPlugin(pluginId); - const sources = { ...this.configStore.get().plugins }; - delete sources[pluginId]; - this.configStore.patch({ plugins: sources }); + await this.removeSource(pluginId); await managedSources.discard(candidate); this.errors.delete(pluginId); this.notify(pluginId); @@ -461,10 +463,11 @@ export class PluginService { } async enablePlugin(pluginId: string): Promise { - const source = this.requireSource(pluginId); - this.patchSource(pluginId, { ...source, enabled: true }); + await this.patchSource(pluginId, (source) => ({ ...source, enabled: true })); this.errors.delete(pluginId); return this.enqueue(async () => { + // Cancellation persistence uses the store queue, so it never waits behind a blocked start. + await this.pendingOperations.get(pluginId)?.completion.catch(() => {}); const current = this.requireSource(pluginId); if (current.enabled !== false && this.configStore.get().pluginsEnabled === true) { await this.startExplicit(pluginId, current.path); @@ -475,8 +478,17 @@ export class PluginService { } async disablePlugin(pluginId: string): Promise { - const source = this.requireSource(pluginId); - this.patchSource(pluginId, { ...source, enabled: false }); + const operation = { + kind: "disable", + completion: this.patchSource(pluginId, (source) => ({ ...source, enabled: false })), + } as const; + this.pendingOperations.set(pluginId, operation); + try { + await operation.completion; + } finally { + if (this.pendingOperations.get(pluginId) === operation) + this.pendingOperations.delete(pluginId); + } const stopping = this.stopPlugin(pluginId); return this.enqueue(async () => { await stopping; @@ -488,10 +500,15 @@ export class PluginService { async removePlugin(pluginId: string): Promise { this.requireSource(pluginId); + const operation = { kind: "remove", completion: this.removeSource(pluginId) } as const; + this.pendingOperations.set(pluginId, operation); + try { + await operation.completion; + } finally { + if (this.pendingOperations.get(pluginId) === operation) + this.pendingOperations.delete(pluginId); + } const stopping = this.stopPlugin(pluginId); - const sources = { ...this.configStore.get().plugins }; - delete sources[pluginId]; - this.configStore.patch({ plugins: sources }); await this.enqueue(async () => { await stopping; this.runtime.clearLogs(pluginId); @@ -564,6 +581,7 @@ export class PluginService { private canPublish(pluginId: string): boolean { const config = this.configStore.get(); return ( + !this.pendingOperations.has(pluginId) && !this.globalStartsBlocked && config.pluginsEnabled === true && config.plugins?.[pluginId]?.enabled !== false && @@ -777,7 +795,10 @@ export class PluginService { await managedSources.discard(candidate); throw new Error(`Plugin is no longer configured: ${pluginId}`); } - this.patchSource(pluginId, { ...activatedSource, path: candidate.directory }); + await this.patchSource(pluginId, (currentSource) => ({ + ...currentSource, + path: candidate.directory, + })); this.errors.delete(pluginId); this.notify(pluginId); let warning: string | undefined; @@ -819,9 +840,28 @@ export class PluginService { return source; } - private patchSource(pluginId: string, source: PluginSource): void { - this.configStore.patch({ - plugins: { ...this.configStore.get().plugins, [pluginId]: source }, + private async patchSource( + pluginId: string, + update: PluginSource | ((source: PluginSource) => PluginSource), + ): Promise { + await this.configStore.patch((current) => { + const source = current.plugins?.[pluginId]; + if (typeof update === "function" && !source) + throw new Error(`Plugin is not configured: ${pluginId}`); + return { + plugins: { + ...current.plugins, + [pluginId]: typeof update === "function" ? update(source!) : update, + }, + }; + }); + } + + private async removeSource(pluginId: string): Promise { + await this.configStore.patch((current) => { + const sources = { ...current.plugins }; + delete sources[pluginId]; + return { plugins: sources }; }); } diff --git a/packages/server/src/server/plugins/plugin-paseo-api.e2e.test.ts b/packages/server/src/server/plugins/plugin-paseo-api.e2e.test.ts index 5da355d5df..729b36fa1c 100644 --- a/packages/server/src/server/plugins/plugin-paseo-api.e2e.test.ts +++ b/packages/server/src/server/plugins/plugin-paseo-api.e2e.test.ts @@ -1,3 +1,6 @@ +import pino from "pino"; +import { createPaseoDaemon } from "../bootstrap.js"; +import { loadConfig } from "../config.js"; import { createRequire } from "node:module"; import { runInNewContext } from "node:vm"; import { fileURLToPath } from "node:url"; @@ -198,6 +201,60 @@ export default function contribute(server: PluginServerContext) { } }, 60_000); +test("password-protected config reload preserves startup auth and session construction does not read config", async () => { + const home = await mkdtemp(path.join(tmpdir(), "paseo-protected-config-reload-")); + roots.push(home); + const password = "synthetic-audit-password"; + const config = loadConfig(home, { env: { PASEO_PASSWORD: password, PASEO_RELAY_ENABLED: "0" } }); + const daemon = await createPaseoDaemon( + { + ...config, + listen: "127.0.0.1:0", + mcpEnabled: false, + agentClients: createTestAgentClients(), + staticDir: home, + }, + pino({ level: "silent" }), + ); + await daemon.start(); + const target = daemon.getListenTarget(); + if (target?.type !== "tcp") throw new Error("Expected TCP daemon"); + const connect = () => + new DaemonClient({ url: `ws://127.0.0.1:${target.port}/ws`, password, appVersion: "0.4.0" }); + const client = connect(); + const replacement = connect(); + try { + await client.connect(); + await client.fetchAgents({ subscribe: {} }); + const configPath = path.join(home, "config.json"); + await writeFile(configPath, JSON.stringify({ daemon: { browserTools: { enabled: true } } })); + let longestGap = 0; + let previous = performance.now(); + const probe = setInterval(() => { + const now = performance.now(); + longestGap = Math.max(longestGap, now - previous); + previous = now; + }, 1); + try { + const reloaded = await client.reloadDaemonConfig(); + longestGap = Math.max(longestGap, performance.now() - previous); + expect(reloaded.appliedPaths).toContain("daemon.browserTools.enabled"); + expect(longestGap).toBeLessThan(50); + } finally { + clearInterval(probe); + } + expect((await client.getDaemonConfig()).config.browserTools.enabled).toBe(true); + // A new physical session uses ready daemon state; corrupt config is reported only by an explicit read. + await writeFile(configPath, "invalid JSON"); + await replacement.connect(); + await replacement.fetchAgents({ subscribe: {} }); + await expect(replacement.reloadDaemonConfig()).rejects.toThrow("Invalid JSON"); + } finally { + await Promise.all([client.close(), replacement.close()]); + await daemon.stop(); + } +}, 60_000); + test("daemon config reload enables and disables configured plugins without restarting", async () => { const pluginDirectory = await mkdtemp(path.join(tmpdir(), "paseo-reload-plugin-")); const paseoHomeRoot = await mkdtemp(path.join(tmpdir(), "paseo-reload-home-")); diff --git a/packages/server/src/server/private-files.ts b/packages/server/src/server/private-files.ts index 0e12457be1..182101149e 100644 --- a/packages/server/src/server/private-files.ts +++ b/packages/server/src/server/private-files.ts @@ -1,3 +1,4 @@ +import { chmod, mkdir, realpath, rename, rm, writeFile } from "node:fs/promises"; import { chmodSync, mkdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs"; import { randomUUID } from "node:crypto"; import path from "node:path"; @@ -52,3 +53,30 @@ function resolveSymlinkedFile(filePath: string): string { throw error; } } + +export async function ensurePrivateFileAsync(filePath: string): Promise { + if (process.platform === "win32") return; + await chmod(filePath, PRIVATE_FILE_MODE).catch(() => {}); +} + +export async function writePrivateFileAtomic(filePath: string, data: string): Promise { + const directory = path.dirname(filePath); + await mkdir(directory, { recursive: true, mode: PRIVATE_DIRECTORY_MODE }); + if (process.platform !== "win32") await chmod(directory, PRIVATE_DIRECTORY_MODE).catch(() => {}); + const destination = await realpath(filePath).catch((error: NodeJS.ErrnoException) => { + if (error.code === "ENOENT") return filePath; + throw error; + }); + const temporary = path.join( + path.dirname(destination), + `.${path.basename(destination)}.${process.pid}.${randomUUID()}`, + ); + try { + await writeFile(temporary, data, { mode: PRIVATE_FILE_MODE }); + await rename(temporary, destination); + await ensurePrivateFileAsync(destination); + } catch (error) { + await rm(temporary, { force: true }); + throw error; + } +} diff --git a/packages/server/src/server/session.test.ts b/packages/server/src/server/session.test.ts index 2fc05d0131..7321312826 100644 --- a/packages/server/src/server/session.test.ts +++ b/packages/server/src/server/session.test.ts @@ -425,6 +425,7 @@ function createSessionForTest(options: SessionForTestOptions = {}): Session { github: asGitHubService(github), workspaceGitService: asWorkspaceGitService(workspaceGitService), daemonConfigStore: asDaemonConfigStore({ + readServicePorts: async () => undefined, get: vi.fn(() => ({ mcp: { injectIntoAgents: false }, providers: {}, diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index da7bf99b72..9f8dcafc95 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -81,7 +81,6 @@ import { type WorkspaceScriptsService, } from "./session/workspace-scripts/workspace-scripts-service.js"; import type { DaemonConfigStore } from "./daemon-config-store.js"; -import { loadPersistedConfig } from "./persisted-config.js"; import { releaseWorkspaceServicePortPlan } from "./workspace-service-port-registry.js"; import { getErrorMessage, getErrorMessageOr } from "@getpaseo/protocol/error-utils"; import { getAgentStatusPriority } from "@getpaseo/protocol/agent-state-bucket"; @@ -1232,7 +1231,7 @@ export class Session { spawnWorkspaceScript, assertAutomationAllowed: (workspaceId) => assertWorkspaceAutomationAllowedForWorkspace(this.workspaceRegistry, workspaceId), - globalServicePorts: loadPersistedConfig(this.paseoHome).worktrees?.servicePorts, + getGlobalServicePorts: () => this.daemonConfigStore.readServicePorts(), }); this.workspaceDirectory = new WorkspaceDirectory({ logger: this.sessionLogger, @@ -2927,8 +2926,7 @@ export class Session { case "daemon.get_pairing_offer.request": return this.daemonSession.handleGetPairingOfferRequest(msg); case "daemon.config.reload.request": - this.daemonSession.handleConfigReloadRequest(msg); - return undefined; + return this.daemonSession.handleConfigReloadRequest(msg); case "hub.management.daemon.connect.request": case "hub.management.daemon.get_status.request": case "hub.management.daemon.disconnect.request": @@ -2939,14 +2937,15 @@ export class Session { case "daemon.update.request": return this.daemonSession.handleUpdateRequest(msg); case "set_daemon_config_request": - this.emit({ - type: "set_daemon_config_response", - payload: { - requestId: msg.requestId, - config: this.daemonConfigStore.patch(msg.config), - }, + return this.daemonConfigStore.patch(msg.config).then((config) => { + return this.emit({ + type: "set_daemon_config_response", + payload: { + requestId: msg.requestId, + config, + }, + }); }); - return undefined; case "read_project_config_request": return this.projectConfigSession.handleReadProjectConfigRequest(msg); case "write_project_config_request": diff --git a/packages/server/src/server/session/daemon/daemon-session.test.ts b/packages/server/src/server/session/daemon/daemon-session.test.ts index cac6a91ea6..e96256c4cf 100644 --- a/packages/server/src/server/session/daemon/daemon-session.test.ts +++ b/packages/server/src/server/session/daemon/daemon-session.test.ts @@ -43,7 +43,7 @@ function makeSubsystem(overrides: { listProviderAvailability?: () => Promise; getWebSocketRuntimeMetrics?: () => DaemonWebSocketRuntimeDiagnosticSnapshot | null; hubRelationships?: HubRelationshipManagement; - reloadConfig?: () => DaemonConfigReloadResult; + reloadConfig?: () => Promise; }) { const emitted: SessionOutboundMessage[] = []; const restartIntents: Parameters[0][] = []; @@ -67,7 +67,7 @@ function makeSubsystem(overrides: { hubRelationships: overrides.hubRelationships, reloadConfig: overrides.reloadConfig ?? - (() => ({ + (async () => ({ appliedPaths: [], restartRequiredPaths: [], overrideControlledPaths: [], @@ -78,16 +78,16 @@ function makeSubsystem(overrides: { } describe("DaemonSession", () => { - test("config reload returns the daemon-owned classification", () => { + test("config reload returns the daemon-owned classification", async () => { const { subsystem, emitted } = makeSubsystem({ - reloadConfig: () => ({ + reloadConfig: async () => ({ appliedPaths: ["daemon.browserTools.enabled"], restartRequiredPaths: ["daemon.listen"], overrideControlledPaths: ["app.baseUrl"], }), }); - subsystem.handleConfigReloadRequest({ + await subsystem.handleConfigReloadRequest({ type: "daemon.config.reload.request", requestId: "reload-1", }); @@ -105,14 +105,14 @@ describe("DaemonSession", () => { ]); }); - test("config reload failures return a correlated RPC error", () => { + test("config reload failures return a correlated RPC error", async () => { const { subsystem, emitted } = makeSubsystem({ - reloadConfig: () => { + reloadConfig: async () => { throw new Error("Invalid config"); }, }); - subsystem.handleConfigReloadRequest({ + await subsystem.handleConfigReloadRequest({ type: "daemon.config.reload.request", requestId: "reload-2", }); diff --git a/packages/server/src/server/session/daemon/daemon-session.ts b/packages/server/src/server/session/daemon/daemon-session.ts index fbe1a06415..ccc9e66e6d 100644 --- a/packages/server/src/server/session/daemon/daemon-session.ts +++ b/packages/server/src/server/session/daemon/daemon-session.ts @@ -53,7 +53,7 @@ export interface DaemonSessionOptions { getObservationMetrics?: () => Record; logger: pino.Logger; hubRelationships?: HubRelationshipManagement; - reloadConfig: () => DaemonConfigReloadResult; + reloadConfig: () => Promise; } /** @@ -79,7 +79,7 @@ export class DaemonSession { private readonly logger: pino.Logger; private readonly selfUpdate: DaemonSelfUpdateSessionController; private readonly hubRelationships: HubRelationshipManagement | null; - private readonly reloadConfig: () => DaemonConfigReloadResult; + private readonly reloadConfig: () => Promise; constructor(options: DaemonSessionOptions) { this.host = options.host; @@ -252,13 +252,13 @@ export class DaemonSession { } } - handleConfigReloadRequest( + async handleConfigReloadRequest( msg: Extract, - ): void { + ): Promise { try { this.host.emit({ type: "daemon.config.reload.response", - payload: { requestId: msg.requestId, ...this.reloadConfig() }, + payload: { requestId: msg.requestId, ...(await this.reloadConfig()) }, }); } catch (error) { this.logger.error({ err: error }, "Failed to reload daemon config"); diff --git a/packages/server/src/server/session/workspace-scripts/workspace-scripts-service.test.ts b/packages/server/src/server/session/workspace-scripts/workspace-scripts-service.test.ts index 18ae1f1366..0e876fd881 100644 --- a/packages/server/src/server/session/workspace-scripts/workspace-scripts-service.test.ts +++ b/packages/server/src/server/session/workspace-scripts/workspace-scripts-service.test.ts @@ -1,3 +1,5 @@ +import { DaemonConfigStore } from "../../daemon-config-store.js"; +import type { PaseoServicePortAllocation } from "@getpaseo/protocol/paseo-config-schema"; import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -82,6 +84,7 @@ interface BuildOptions { spawnThrows?: string; runtimeStore?: Pick; automationError?: Error; + getGlobalServicePorts?: () => Promise; } function buildService(options: BuildOptions = {}) { @@ -111,6 +114,7 @@ function buildService(options: BuildOptions = {}) { getDaemonTcpHost: () => "127.0.0.1", serviceProxyPublicBaseUrl: null, resolveScriptHealth: null, + getGlobalServicePorts: options.getGlobalServicePorts ?? (async () => undefined), logger, emit: (message) => emitted.push(message), publishStatusUpdate: (message) => published.push(message), @@ -152,6 +156,24 @@ afterEach(() => { } }); +test("reads external service-port edits at the next launch without construction IO", async () => { + const home = mkdtempSync(join(tmpdir(), "workspace-service-ports-")); + tempDirs.push(home); + const store = new DaemonConfigStore(home, { + providers: {}, + mcp: { enabled: true, injectIntoAgents: false }, + }); + const { service, spawnCalls } = buildService({ + getGlobalServicePorts: () => store.readServicePorts(), + }); + writeFileSync( + join(home, "config.json"), + JSON.stringify({ worktrees: { servicePorts: { range: "9000-9999" } } }), + ); + await service.start(request); + expect(spawnCalls.map((call) => call.globalServicePorts)).toEqual([{ range: "9000-9999" }]); +}); + describe("buildSnapshot", () => { test("returns no scripts when the service proxy is unavailable", async () => { const { service } = buildService({ serviceProxy: null }); diff --git a/packages/server/src/server/session/workspace-scripts/workspace-scripts-service.ts b/packages/server/src/server/session/workspace-scripts/workspace-scripts-service.ts index 103c3ed16b..54962f5076 100644 --- a/packages/server/src/server/session/workspace-scripts/workspace-scripts-service.ts +++ b/packages/server/src/server/session/workspace-scripts/workspace-scripts-service.ts @@ -62,7 +62,7 @@ export function createWorkspaceScriptsService(deps: { getDaemonTcpHost: (() => string | null) | null; serviceProxyPublicBaseUrl: string | null; resolveScriptHealth: ((hostname: string) => ScriptHealthState | null) | null; - globalServicePorts?: PaseoServicePortAllocation; + getGlobalServicePorts: () => Promise; logger: pino.Logger; emit: (message: SessionOutboundMessage) => void; // Script status is daemon state, so it reaches every client, not only the requester. @@ -81,7 +81,7 @@ export function createWorkspaceScriptsService(deps: { getDaemonTcpHost, serviceProxyPublicBaseUrl, resolveScriptHealth, - globalServicePorts, + getGlobalServicePorts, logger, emit, publishStatusUpdate, @@ -172,6 +172,7 @@ export function createWorkspaceScriptsService(deps: { async function launchProcess(input: { workspaceId: string; scriptName: string }) { const available = requireAvailable(); + const globalServicePorts = await getGlobalServicePorts(); const workspace = await getWorkspace(input.workspaceId); await assertAutomationAllowed(workspace.workspaceId); const project = await projectRegistry.get(workspace.projectId); diff --git a/packages/server/src/terminal/agent-hooks/terminal-agent-hook-setting.test.ts b/packages/server/src/terminal/agent-hooks/terminal-agent-hook-setting.test.ts index aa9e8e01dc..eaa306c185 100644 --- a/packages/server/src/terminal/agent-hooks/terminal-agent-hook-setting.test.ts +++ b/packages/server/src/terminal/agent-hooks/terminal-agent-hook-setting.test.ts @@ -80,7 +80,7 @@ describe("applyTerminalAgentHookSetting", () => { expect(existsSync(paths.opencode)).toBe(true); }); - it("installs on enable and removes hooks on disable when toggled live", () => { + it("installs on enable and removes hooks on disable when toggled live", async () => { const root = createTempDir("paseo-hook-setting-"); const store = createStore(createTempDir("paseo-hook-setting-home-"), false); const paths = hookPaths(root); @@ -88,11 +88,11 @@ describe("applyTerminalAgentHookSetting", () => { applyTerminalAgentHookSetting({ store, install: createInstallEnv(root) }); expect(existsSync(paths.opencode)).toBe(false); - store.patch({ enableTerminalAgentHooks: true }); + await store.patch({ enableTerminalAgentHooks: true }); expect(existsSync(paths.codex)).toBe(true); expect(existsSync(paths.opencode)).toBe(true); - store.patch({ enableTerminalAgentHooks: false }); + await store.patch({ enableTerminalAgentHooks: false }); expect(existsSync(paths.opencode)).toBe(false); }); }); From 67a2459254cfde9d9b186215b7268de12aaa6537 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Tue, 27 Oct 2026 09:56:51 +0700 Subject: [PATCH 042/173] fix(server): keep project config work off the daemon hot path (#7944) Project settings and script health updates synchronously read unbounded user files. Share admitted async snapshots across consumers, budget script validation, and serialize revision-checked edits while keeping lexical project identity. --- .../server/script-status-projection.test.ts | 82 +++-- .../src/server/script-status-projection.ts | 18 +- packages/server/src/server/session.ts | 4 +- .../project-config-session.test.ts | 2 +- .../project-config/project-config-session.ts | 51 +-- .../workspace-scripts-service.test.ts | 26 +- .../workspace-scripts-service.ts | 14 +- .../server/src/server/worktree-bootstrap.ts | 4 +- .../server/src/server/worktree-session.ts | 2 +- .../server/src/utils/build-metadata-prompt.ts | 11 +- .../src/utils/paseo-config-file.test.ts | 232 ++++++++++-- .../server/src/utils/paseo-config-file.ts | 343 ++++++++++++++---- .../server/src/utils/worktree.posix.test.ts | 30 +- packages/server/src/utils/worktree.ts | 42 +-- 14 files changed, 615 insertions(+), 246 deletions(-) diff --git a/packages/server/src/server/script-status-projection.test.ts b/packages/server/src/server/script-status-projection.test.ts index 3c963f907c..b6ef6e18f5 100644 --- a/packages/server/src/server/script-status-projection.test.ts +++ b/packages/server/src/server/script-status-projection.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it, vi } from "vitest"; +import { describe, expect, it } from "vitest"; import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import path from "node:path"; import { tmpdir } from "node:os"; @@ -7,6 +7,7 @@ import { ScriptRouteStore } from "./script-proxy.js"; import { buildWorkspaceScriptPayloads, createScriptStatusEmitter, + readPaseoConfigForProjection, } from "./script-status-projection.js"; import { WorkspaceScriptPayloadSchema } from "@getpaseo/protocol/messages"; import type { ScriptHealthState } from "./script-health-monitor.js"; @@ -50,7 +51,7 @@ function createWorkspaceRepo(options?: { }; } -function buildPayloads(input: { +async function buildPayloads(input: { workspaceId: string; workspaceDirectory: string; paseoConfig?: PaseoConfig | null; @@ -63,7 +64,9 @@ function buildPayloads(input: { resolveHealth?: (hostname: string) => ScriptHealthState | null; }) { const paseoConfig = - input.paseoConfig !== undefined ? input.paseoConfig : loadConfig(input.workspaceDirectory); + input.paseoConfig !== undefined + ? input.paseoConfig + : await loadConfig(input.workspaceDirectory); const { routeStore, serviceProxy, ...rest } = input; return buildWorkspaceScriptPayloads({ ...rest, @@ -72,8 +75,8 @@ function buildPayloads(input: { }); } -function loadConfig(repoRoot: string): PaseoConfig | null { - const result = readPaseoConfig(repoRoot); +async function loadConfig(repoRoot: string): Promise { + const result = await readPaseoConfig(repoRoot); return result.ok ? result.config : null; } @@ -93,7 +96,7 @@ describe("script-status-projection", () => { ).toBeNull(); }); - it("projects plain scripts and services differently", () => { + it("projects plain scripts and services differently", async () => { const workspaceId = "workspace-plain-and-service"; const workspace = createWorkspaceRepo({ paseoConfig: { @@ -116,7 +119,7 @@ describe("script-status-projection", () => { try { expect( - buildPayloads({ + await buildPayloads({ workspaceId, workspaceDirectory: workspace.repoDir, routeStore, @@ -154,7 +157,7 @@ describe("script-status-projection", () => { } }); - it("builds service hostnames from service-provided git metadata", () => { + it("builds service hostnames from service-provided git metadata", async () => { const workspaceId = "workspace-service-metadata"; const workspace = createWorkspaceRepo({ branchName: "local-branch-that-should-not-be-read", @@ -168,7 +171,7 @@ describe("script-status-projection", () => { const runtimeStore = new WorkspaceScriptRuntimeStore(); try { - const payloads = buildPayloads({ + const payloads = await buildPayloads({ workspaceId, workspaceDirectory: workspace.repoDir, serviceProxy: routeStore, @@ -200,7 +203,7 @@ describe("script-status-projection", () => { } }); - it("projects local and public service URLs while keeping proxyUrl public-first", () => { + it("projects local and public service URLs while keeping proxyUrl public-first", async () => { const workspaceId = "workspace-public-service"; const workspace = createWorkspaceRepo({ paseoConfig: { @@ -214,7 +217,7 @@ describe("script-status-projection", () => { try { expect( - buildPayloads({ + await buildPayloads({ workspaceId, workspaceDirectory: workspace.repoDir, routeStore, @@ -243,7 +246,7 @@ describe("script-status-projection", () => { } }); - it("overlays runtime, route, and health state for running services", () => { + it("overlays runtime, route, and health state for running services", async () => { const workspaceId = "workspace-running-service"; const workspace = createWorkspaceRepo({ branchName: "feature/card", @@ -273,7 +276,7 @@ describe("script-status-projection", () => { try { expect( - buildPayloads({ + await buildPayloads({ workspaceId, workspaceDirectory: workspace.repoDir, routeStore, @@ -301,7 +304,7 @@ describe("script-status-projection", () => { } }); - it("maps internal pending health to null on the wire", () => { + it("maps internal pending health to null on the wire", async () => { const workspaceId = "workspace-pending-health"; const workspace = createWorkspaceRepo({ paseoConfig: { @@ -330,7 +333,7 @@ describe("script-status-projection", () => { try { expect( - buildPayloads({ + await buildPayloads({ workspaceId, workspaceDirectory: workspace.repoDir, routeStore, @@ -358,7 +361,7 @@ describe("script-status-projection", () => { } }); - it("includes orphaned running runtime entries even after config removal", () => { + it("includes orphaned running runtime entries even after config removal", async () => { const workspaceId = "workspace-orphaned-service"; const workspace = createWorkspaceRepo(); const routeStore = new ScriptRouteStore(); @@ -381,7 +384,7 @@ describe("script-status-projection", () => { try { expect( - buildPayloads({ + await buildPayloads({ workspaceId, workspaceDirectory: workspace.repoDir, routeStore, @@ -408,7 +411,7 @@ describe("script-status-projection", () => { } }); - it("projects orphaned plain scripts as scripts instead of services", () => { + it("projects orphaned plain scripts as scripts instead of services", async () => { const workspaceId = "workspace-orphaned-script"; const workspace = createWorkspaceRepo(); const routeStore = new ScriptRouteStore(); @@ -424,7 +427,7 @@ describe("script-status-projection", () => { try { expect( - buildPayloads({ + await buildPayloads({ workspaceId, workspaceDirectory: workspace.repoDir, routeStore, @@ -449,7 +452,7 @@ describe("script-status-projection", () => { } }); - it("readPaseoConfig fails with configPath and error when paseo.json is malformed", () => { + it("readPaseoConfig fails with configPath and error when paseo.json is malformed", async () => { const workspace = createWorkspaceRepo(); const configPath = path.join(workspace.repoDir, "paseo.json"); writeFileSync( @@ -458,7 +461,7 @@ describe("script-status-projection", () => { ); try { - const result = readPaseoConfig(workspace.repoDir); + const result = await readPaseoConfig(workspace.repoDir); expect(result.ok).toBe(false); if (result.ok) throw new Error("unreachable"); expect(result.configPath).toBe(configPath); @@ -468,7 +471,7 @@ describe("script-status-projection", () => { } }); - it("buildWorkspaceScriptPayloads given paseoConfig=null still surfaces orphaned runtime scripts", () => { + it("buildWorkspaceScriptPayloads given paseoConfig=null still surfaces orphaned runtime scripts", async () => { const workspaceId = "workspace-null-config"; const workspace = createWorkspaceRepo(); const routeStore = new ScriptRouteStore(); @@ -484,7 +487,7 @@ describe("script-status-projection", () => { try { expect( - buildPayloads({ + await buildPayloads({ workspaceId, workspaceDirectory: workspace.repoDir, paseoConfig: null, @@ -538,7 +541,12 @@ describe("script-status-projection", () => { exitCode: null, }); - const session = { emit: vi.fn() }; + const messages: unknown[] = []; + const session = { + emit: (message: unknown) => { + messages.push(message); + }, + }; const emitUpdate = createScriptStatusEmitter({ sessions: () => [session], serviceProxy: routeStore, @@ -550,7 +558,11 @@ describe("script-status-projection", () => { }); try { - emitUpdate(workspaceId, [ + const originalConfig = await readPaseoConfigForProjection( + workspace.repoDir, + createTestLogger(), + ); + await emitUpdate(workspaceId, [ { scriptName: "api", hostname: "api--repo.localhost", @@ -558,9 +570,25 @@ describe("script-status-projection", () => { health: "healthy", }, ]); - await Promise.resolve(); - expect(session.emit).toHaveBeenCalledWith({ + expect(await readPaseoConfigForProjection(workspace.repoDir, createTestLogger())).toBe( + originalConfig, + ); + await emitUpdate(workspaceId, [ + { scriptName: "api", hostname: "api--repo.localhost", port: 3001, health: "unhealthy" }, + ]); + expect(messages.at(-1)).toMatchObject({ + payload: { + scripts: [ + { scriptName: "api", health: "unhealthy" }, + { scriptName: "typecheck", health: null }, + ], + }, + }); + expect(await readPaseoConfigForProjection(workspace.repoDir, createTestLogger())).toBe( + originalConfig, + ); + expect(messages).toContainEqual({ type: "script_status_update", payload: { workspaceId, diff --git a/packages/server/src/server/script-status-projection.ts b/packages/server/src/server/script-status-projection.ts index 2d02751fc6..a66f5fb073 100644 --- a/packages/server/src/server/script-status-projection.ts +++ b/packages/server/src/server/script-status-projection.ts @@ -33,11 +33,11 @@ interface BuildWorkspaceScriptPayloadsOptions { resolveHealth?: (hostname: string) => ScriptHealthState | null; } -export function readPaseoConfigForProjection( +export async function readPaseoConfigForProjection( workspaceDirectory: string, logger: Logger, -): PaseoConfig | null { - const result = readPaseoConfig(workspaceDirectory); +): Promise { + const result = await readPaseoConfig(workspaceDirectory); if (result.ok) { return result.config; } @@ -288,9 +288,9 @@ export function createScriptStatusEmitter({ serviceProxyPublicBaseUrl?: string | null; resolveWorkspaceDirectory: (workspaceId: string) => string | null | Promise; logger: Logger; -}): (workspaceId: string, scripts: ScriptHealthEntry[]) => void { - return (workspaceId, scripts) => { - void (async () => { +}): (workspaceId: string, scripts: ScriptHealthEntry[]) => Promise { + return async (workspaceId, scripts) => { + try { const workspaceDirectory = await resolveWorkspaceDirectory(workspaceId); if (!workspaceDirectory) { return; @@ -304,7 +304,7 @@ export function createScriptStatusEmitter({ const projected = buildWorkspaceScriptPayloads({ workspaceId, workspaceDirectory, - paseoConfig: readPaseoConfigForProjection(workspaceDirectory, logger), + paseoConfig: await readPaseoConfigForProjection(workspaceDirectory, logger), serviceProxy, runtimeStore, daemonPort: resolvedDaemonPort, @@ -320,6 +320,8 @@ export function createScriptStatusEmitter({ for (const session of sessions()) { session.emit(message); } - })(); + } catch (error) { + logger.warn({ err: error, workspaceId }, "Failed to project workspace script status"); + } }; } diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index 9f8dcafc95..9d25328079 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -5669,7 +5669,7 @@ export class Session { activityAt: null, createdAt: workspace.createdAt, diffStat, - scripts: this.buildWorkspaceScriptPayloadSnapshot(workspace, resolvedProjectRecord), + scripts: await this.buildWorkspaceScriptPayloadSnapshot(workspace, resolvedProjectRecord), ...(resolvedProjectRecord ? { project: await this.buildProjectPlacementForWorkspace(workspace, resolvedProjectRecord), @@ -7262,7 +7262,7 @@ export class Session { private buildWorkspaceScriptPayloadSnapshot( workspace: PersistedWorkspaceRecord, project: PersistedProjectRecord | null, - ): WorkspaceDescriptorPayload["scripts"] { + ): Promise { return this.workspaceScripts.buildSnapshot(workspace, project); } diff --git a/packages/server/src/server/session/project-config/project-config-session.test.ts b/packages/server/src/server/session/project-config/project-config-session.test.ts index 6e93dff805..f8f6b59304 100644 --- a/packages/server/src/server/session/project-config/project-config-session.test.ts +++ b/packages/server/src/server/session/project-config/project-config-session.test.ts @@ -228,7 +228,7 @@ describe("ProjectConfigSession", () => { requestId: "write-uncommitted-setup", repoRoot, config: { worktree: { setup: "npm install" } }, - expectedRevision: statPaseoConfigPath(repoRoot), + expectedRevision: await statPaseoConfigPath(repoRoot), }); expect(emitted).toEqual([ diff --git a/packages/server/src/server/session/project-config/project-config-session.ts b/packages/server/src/server/session/project-config/project-config-session.ts index 6056d08826..d2e8c419f0 100644 --- a/packages/server/src/server/session/project-config/project-config-session.ts +++ b/packages/server/src/server/session/project-config/project-config-session.ts @@ -1,10 +1,10 @@ -import { realpathSync } from "node:fs"; -import { resolve, sep } from "path"; +import { resolve } from "path"; import type pino from "pino"; import type { SessionInboundMessage, SessionOutboundMessage } from "../../messages.js"; import type { ProjectRegistry } from "../../workspace-registry.js"; import { readPaseoConfigForEdit, + resolveProjectConfigRoot, writePaseoConfigForEdit, type ProjectConfigRpcError, } from "../../../utils/paseo-config-file.js"; @@ -47,7 +47,7 @@ export class ProjectConfigSession { return; } - const result = readPaseoConfigForEdit(repoRoot); + const result = await readPaseoConfigForEdit(repoRoot); if (!result.ok) { this.logger.warn( { repoRoot, requestId: msg.requestId, outcome: result.error.code }, @@ -94,7 +94,7 @@ export class ProjectConfigSession { { repoRoot, requestId: msg.requestId, outcome: "write_attempt" }, "Writing project config", ); - const result = writePaseoConfigForEdit({ + const result = await writePaseoConfigForEdit({ repoRoot, config: msg.config, expectedRevision: msg.expectedRevision, @@ -173,34 +173,21 @@ export class ProjectConfigSession { } private async resolveKnownProjectRoot(repoRoot: string): Promise { - const requestedRoot = canonicalizeConfigRoot(repoRoot); + const requestedRoot = resolve(repoRoot); const projects = await this.projectRegistry.list(); - for (const project of projects) { - if (project.archivedAt !== null) { - continue; - } - const projectRoot = canonicalizeConfigRoot(project.rootPath); - if (requestedRoot === projectRoot) { - return projectRoot; - } - } - return null; + const activeRoots = new Set( + projects + .filter((project) => project.archivedAt === null) + .map((project) => resolve(project.rootPath)), + ); + const root = await resolveProjectConfigRoot(requestedRoot, activeRoots); + if (!root) return null; + // Authorization follows live registry state after alias IO, including archive/removal. + const current = await this.projectRegistry.list(); + return current.some( + (project) => project.archivedAt === null && resolve(project.rootPath) === root, + ) + ? root + : null; } } - -function canonicalizeConfigRoot(repoRoot: string): string { - const resolved = resolve(repoRoot); - try { - return stripTrailingPathSeparators(realpathSync(resolved)); - } catch { - return stripTrailingPathSeparators(resolved); - } -} - -function stripTrailingPathSeparators(path: string): string { - let normalized = path; - while (normalized.length > 1 && normalized.endsWith(sep)) { - normalized = normalized.slice(0, -1); - } - return normalized; -} diff --git a/packages/server/src/server/session/workspace-scripts/workspace-scripts-service.test.ts b/packages/server/src/server/session/workspace-scripts/workspace-scripts-service.test.ts index 0e876fd881..664fcc14de 100644 --- a/packages/server/src/server/session/workspace-scripts/workspace-scripts-service.test.ts +++ b/packages/server/src/server/session/workspace-scripts/workspace-scripts-service.test.ts @@ -178,14 +178,20 @@ describe("buildSnapshot", () => { test("returns no scripts when the service proxy is unavailable", async () => { const { service } = buildService({ serviceProxy: null }); expect( - service.buildSnapshot({ workspaceId: "ws-1", cwd: "/tmp/repo" } as PersistedWorkspaceRecord), + await service.buildSnapshot({ + workspaceId: "ws-1", + cwd: "/tmp/repo", + } as PersistedWorkspaceRecord), ).toEqual([]); }); test("returns no scripts when the runtime store is unavailable", async () => { const { service } = buildService({ scriptRuntimeStore: null }); expect( - service.buildSnapshot({ workspaceId: "ws-1", cwd: "/tmp/repo" } as PersistedWorkspaceRecord), + await service.buildSnapshot({ + workspaceId: "ws-1", + cwd: "/tmp/repo", + } as PersistedWorkspaceRecord), ).toEqual([]); }); @@ -194,7 +200,7 @@ describe("buildSnapshot", () => { tempDirs.push(dir); const { service } = buildService(); expect( - service.buildSnapshot({ workspaceId: "ws-1", cwd: dir } as PersistedWorkspaceRecord), + await service.buildSnapshot({ workspaceId: "ws-1", cwd: dir } as PersistedWorkspaceRecord), ).toEqual([]); }); @@ -229,7 +235,7 @@ describe("buildSnapshot", () => { runtimeStore: { get: () => null }, }); - expect(service.buildSnapshot(workspace, project)[0]?.hostname).toBe( + expect((await service.buildSnapshot(workspace, project))[0]?.hostname).toBe( serviceProxy.projectWorkspaceService({ projectSlug: deriveProjectServiceSlug(project), branchName: workspace.branch, @@ -374,10 +380,12 @@ describe("start", () => { daemonPort: 6767, daemonListenHost: "127.0.0.1", }); - expect(published).toContainEqual({ - type: "script_status_update", - payload: { workspaceId: "ws-1", scripts: [] }, - }); + await expect + .poll(() => published) + .toContainEqual({ + type: "script_status_update", + payload: { workspaceId: "ws-1", scripts: [] }, + }); expect(emitted).toContainEqual({ type: "start_workspace_script_response", payload: { @@ -471,7 +479,7 @@ describe("start", () => { const serviceProxy = createServiceProxySubsystem({ logger }); const { service, spawnCalls } = buildService({ workspace, project, serviceProxy }); - const snapshot = service.buildSnapshot(workspace, project); + const snapshot = await service.buildSnapshot(workspace, project); await service.start({ ...request, workspaceId: workspace.workspaceId }); const started = spawnCalls[0]!; diff --git a/packages/server/src/server/session/workspace-scripts/workspace-scripts-service.ts b/packages/server/src/server/session/workspace-scripts/workspace-scripts-service.ts index 54962f5076..eebad7f1e5 100644 --- a/packages/server/src/server/session/workspace-scripts/workspace-scripts-service.ts +++ b/packages/server/src/server/session/workspace-scripts/workspace-scripts-service.ts @@ -43,7 +43,7 @@ export interface WorkspaceScriptsService { buildSnapshot( workspace: PersistedWorkspaceRecord, project?: PersistedProjectRecord | null, - ): WorkspaceScriptsPayload; + ): Promise; emitStatusUpdate(workspaceId: string, workspaceDirectory: string): Promise; list(workspaceId: string): Promise; launch(input: { workspaceId: string; scriptName: string }): Promise; @@ -110,17 +110,17 @@ export function createWorkspaceScriptsService(deps: { }; } - function buildSnapshot( + async function buildSnapshot( workspace: PersistedWorkspaceRecord, project: PersistedProjectRecord | null = null, - ): WorkspaceScriptsPayload { + ): Promise { if (!serviceProxy || !scriptRuntimeStore) { return []; } return buildWorkspaceScriptPayloads({ workspaceId: workspace.workspaceId, workspaceDirectory: workspace.cwd, - paseoConfig: readPaseoConfigForProjection(workspace.cwd, logger), + paseoConfig: await readPaseoConfigForProjection(workspace.cwd, logger), serviceProxy, runtimeStore: scriptRuntimeStore, daemonPort: getDaemonTcpPort?.() ?? null, @@ -137,7 +137,7 @@ export function createWorkspaceScriptsService(deps: { const project = await projectRegistry.get(workspace.projectId); publishStatusUpdate({ type: "script_status_update", - payload: { workspaceId, scripts: buildSnapshot(workspace, project) }, + payload: { workspaceId, scripts: await buildSnapshot(workspace, project) }, }); } catch (error) { logger.warn({ err: error, workspaceId }, "Failed to project workspace script status"); @@ -203,7 +203,7 @@ export function createWorkspaceScriptsService(deps: { scriptName: string; }): Promise { const { workspace, project } = await launchProcess(input); - const script = buildSnapshot(workspace, project).find( + const script = (await buildSnapshot(workspace, project)).find( (entry) => entry.scriptName === input.scriptName, ); if (!script) { @@ -231,7 +231,7 @@ export function createWorkspaceScriptsService(deps: { // The launcher's terminal exit listener owns route removal and runtime state updates. await available.terminalManager.killTerminalAndWait(runtime.terminalId); - const script = buildSnapshot(workspace, project).find( + const script = (await buildSnapshot(workspace, project)).find( (entry) => entry.scriptName === input.scriptName, ); if (!script) { diff --git a/packages/server/src/server/worktree-bootstrap.ts b/packages/server/src/server/worktree-bootstrap.ts index 6e138e8ab4..d656738bd4 100644 --- a/packages/server/src/server/worktree-bootstrap.ts +++ b/packages/server/src/server/worktree-bootstrap.ts @@ -335,7 +335,7 @@ export async function runWorktreeAutoTerminals(options: { if (!options.terminalManager) return; const terminalManager = options.terminalManager; await Promise.all( - getWorktreeTerminalSpecs(options.workspaceCwd).map(async (spec) => { + (await getWorktreeTerminalSpecs(options.workspaceCwd)).map(async (spec) => { try { const terminal = await terminalManager.createTerminal({ cwd: options.workspaceCwd, @@ -545,7 +545,7 @@ export async function spawnWorkspaceScript( logger, onLifecycleChanged, } = options; - const configResult = readPaseoConfig(repoRoot); + const configResult = await readPaseoConfig(repoRoot); if (!configResult.ok) { throw paseoConfigParseError(configResult); } diff --git a/packages/server/src/server/worktree-session.ts b/packages/server/src/server/worktree-session.ts index 4ba1010bd3..1cbad931eb 100644 --- a/packages/server/src/server/worktree-session.ts +++ b/packages/server/src/server/worktree-session.ts @@ -554,7 +554,7 @@ export async function runWorktreeSetupInBackground( emitSetupProgress("completed", null); } else { const workspaceCwd = options.workspaceCwd ?? worktree.worktreePath; - const setupCommands = getWorktreeSetupCommands(workspaceCwd); + const setupCommands = await getWorktreeSetupCommands(workspaceCwd); const runtimeEnv = await resolveWorktreeRuntimeEnv({ worktreePath: worktree.worktreePath, branchName: worktree.branchName, diff --git a/packages/server/src/utils/build-metadata-prompt.ts b/packages/server/src/utils/build-metadata-prompt.ts index 9f4f008308..b68f660515 100644 --- a/packages/server/src/utils/build-metadata-prompt.ts +++ b/packages/server/src/utils/build-metadata-prompt.ts @@ -1,8 +1,5 @@ -import { readPaseoConfigJson } from "./paseo-config-file.js"; -import { - PaseoConfigSchema, - type PaseoMetadataGeneration, -} from "@getpaseo/protocol/paseo-config-schema"; +import { readPaseoConfig } from "./paseo-config-file.js"; +import { type PaseoMetadataGeneration } from "@getpaseo/protocol/paseo-config-schema"; export type MetadataConfigKey = "title" | "branchName" | "commitMessage" | "pullRequest"; @@ -52,8 +49,8 @@ async function readProjectMetadataOverrides( } try { const repoRoot = await options.workspaceGitService.resolveRepoRoot(options.cwd); - const json = readPaseoConfigJson(repoRoot); - return PaseoConfigSchema.parse(json).metadataGeneration; + const result = await readPaseoConfig(repoRoot); + return result.ok ? result.config?.metadataGeneration : undefined; } catch { return undefined; } diff --git a/packages/server/src/utils/paseo-config-file.test.ts b/packages/server/src/utils/paseo-config-file.test.ts index 02cbd90542..075ddd9720 100644 --- a/packages/server/src/utils/paseo-config-file.test.ts +++ b/packages/server/src/utils/paseo-config-file.test.ts @@ -1,9 +1,20 @@ import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { fileURLToPath } from "node:url"; +import { writeFile, truncate, rm } from "node:fs/promises"; +import { setImmediate as nextTurn } from "node:timers/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { isPlatform } from "../test-utils/platform.js"; -import { getWorktreeSetupCommands, getWorktreeTeardownCommands } from "./worktree.js"; +import { + readPaseoConfig, + PaseoConfigSchema, + PaseoConfigRawSchema, + getWorktreeSetupCommands, + getWorktreeTeardownCommands, +} from "./worktree.js"; import { readPaseoConfigForEdit, statPaseoConfigPath, @@ -21,16 +32,179 @@ describe("paseo config file substrate", () => { rmSync(tempDir, { recursive: true, force: true }); }); - it("returns null config and revision when paseo.json is missing", () => { - const result = readPaseoConfigForEdit(tempDir); + it("rejects an oversized config before parsing its otherwise valid JSON", async () => { + writeFileSync( + join(tempDir, "paseo.json"), + JSON.stringify({ extra: "x".repeat(2 * 1024 * 1024) }), + ); + expect(await readPaseoConfigForEdit(tempDir)).toEqual({ + ok: false, + error: { code: "invalid_project_config" }, + }); + }); + + it("rejects a sparse oversized file without allocating its contents", async () => { + const configPath = join(tempDir, "paseo.json"); + await writeFile(configPath, ""); + await truncate(configPath, 1024 * 1024 * 1024); + expect(await readPaseoConfigForEdit(tempDir)).toEqual({ + ok: false, + error: { code: "invalid_project_config" }, + }); + }); + + it.skipIf(isPlatform("win32"))("rejects a FIFO without waiting for a writer", async () => { + await promisify(execFile)("mkfifo", [join(tempDir, "paseo.json")]); + const modulePath = fileURLToPath(new URL("./paseo-config-file.ts", import.meta.url)); + const script = `import { readPaseoConfigForEdit } from ${JSON.stringify(modulePath)}; + const result = await readPaseoConfigForEdit(${JSON.stringify(tempDir)}); + if (JSON.stringify(result) !== JSON.stringify({ok:false,error:{code:"invalid_project_config"}})) process.exit(1);`; + // Isolate the regression: the old sync reader blocks on the pipe and must be killed. + await promisify(execFile)( + process.execPath, + ["--import", "tsx", "--input-type=module", "-e", script], + { timeout: 2_000 }, + ); + }); + + it("keeps the longest loop stall below 20ms while admitting large configs", async () => { + const config = { + scripts: Object.fromEntries( + Array.from({ length: 7_000 }, (_, i) => [`script${i}`, { command: "echo hi" }]), + ), + worktree: { setup: "npm ci" }, + }; + await writeFile(join(tempDir, "paseo.json"), JSON.stringify(config)); + let previous = performance.now(); + let longestGap = 0; + const probe = setInterval(() => { + const now = performance.now(); + longestGap = Math.max(longestGap, now - previous); + previous = now; + }, 1); + let result: Awaited>; + try { + result = await readPaseoConfigForEdit(tempDir); + await nextTurn(); + longestGap = Math.max(longestGap, performance.now() - previous); + } finally { + clearInterval(probe); + } + expect(result).toEqual({ ok: true, config, revision: await statPaseoConfigPath(tempDir) }); + process.stdout.write(`project config 7,000 scripts max loop gap: ${longestGap.toFixed(2)}ms\n`); + expect(longestGap).toBeLessThan(20); + }); + + it("rejects a 32MiB config with a loop stall below 20ms", async () => { + await writeFile( + join(tempDir, "paseo.json"), + JSON.stringify({ extra: "x".repeat(32 * 1024 * 1024) }), + ); + let previous = performance.now(); + let longestGap = 0; + const probe = setInterval(() => { + const now = performance.now(); + longestGap = Math.max(longestGap, now - previous); + previous = now; + }, 1); + let result: Awaited>; + try { + result = await readPaseoConfigForEdit(tempDir); + await nextTurn(); + longestGap = Math.max(longestGap, performance.now() - previous); + } finally { + clearInterval(probe); + } + process.stdout.write(`project config 32MiB max loop gap: ${longestGap.toFixed(2)}ms\n`); + expect(longestGap).toBeLessThan(20); + expect(result).toEqual({ ok: false, error: { code: "invalid_project_config" } }); + }); + + it.each([ + { + scripts: Object.fromEntries( + Array.from({ length: 130 }, (_, i) => [ + `script${i}`, + { command: "echo hi", extra: { keep: true } }, + ]), + ), + }, + { + scripts: { valid: { command: "echo hi" }, invalid: 42 }, + worktree: { setup: ["one", "", 42] }, + }, + { scripts: ["invalid record"], worktree: { setup: "echo hi" } }, + JSON.parse( + '{"scripts":{"__proto__":{"command":"echo hi"},"constructor":{"command":"echo hi"}}}', + ), + ])("preserves edit and runtime schema behavior with grouped validation (%#)", async (config) => { + await writeFile(join(tempDir, "paseo.json"), JSON.stringify(config)); + const expected = PaseoConfigRawSchema.safeParse(config); + expect(await readPaseoConfigForEdit(tempDir)).toEqual( + expected.success + ? { ok: true, config: expected.data, revision: await statPaseoConfigPath(tempDir) } + : { ok: false, error: { code: "invalid_project_config" } }, + ); + expect(await readPaseoConfig(tempDir)).toEqual({ + ok: true, + config: PaseoConfigSchema.parse(config), + }); + }); + + it("refreshes snapshots after an external edit, repair, and removal", async () => { + const configPath = join(tempDir, "paseo.json"); + await writeFile(configPath, JSON.stringify({ worktree: { setup: "old" } })); + const original = await readPaseoConfig(tempDir); + expect(original).toEqual({ ok: true, config: { worktree: { setup: ["old"], teardown: [] } } }); + await writeFile(configPath, "{ malformed"); + expect(await readPaseoConfigForEdit(tempDir)).toEqual({ + ok: false, + error: { code: "invalid_project_config" }, + }); + await writeFile(configPath, JSON.stringify({ worktree: { setup: "repaired" } })); + expect(await readPaseoConfig(tempDir)).toEqual({ + ok: true, + config: { worktree: { setup: ["repaired"], teardown: [] } }, + }); + await rm(configPath); + expect(await readPaseoConfigForEdit(tempDir)).toEqual({ + ok: true, + config: null, + revision: null, + }); + }); + + it("serializes competing edits so exactly one matching revision commits", async () => { + const results = await Promise.all( + ["first", "second"].map((setup) => + writePaseoConfigForEdit({ + repoRoot: tempDir, + config: { worktree: { setup } }, + expectedRevision: null, + }), + ), + ); + const saved = await readPaseoConfigForEdit(tempDir); + expect(results[0]).toEqual(saved); + expect(results[1]).toEqual({ + ok: false, + error: { + code: "stale_project_config", + currentRevision: await statPaseoConfigPath(tempDir), + }, + }); + }); + + it("returns null config and revision when paseo.json is missing", async () => { + const result = await readPaseoConfigForEdit(tempDir); expect(result).toEqual({ ok: true, config: null, revision: null }); }); - it("returns invalid_project_config for invalid JSON", () => { + it("returns invalid_project_config for invalid JSON", async () => { writeFileSync(join(tempDir, "paseo.json"), "{ invalid json\n"); - const result = readPaseoConfigForEdit(tempDir); + const result = await readPaseoConfigForEdit(tempDir); expect(result).toEqual({ ok: false, @@ -38,7 +212,7 @@ describe("paseo config file substrate", () => { }); }); - it("preserves raw lifecycle string and array forms with a revision token", () => { + it("preserves raw lifecycle string and array forms with a revision token", async () => { writeFileSync( join(tempDir, "paseo.json"), JSON.stringify({ @@ -49,7 +223,7 @@ describe("paseo config file substrate", () => { }), ); - const result = readPaseoConfigForEdit(tempDir); + const result = await readPaseoConfigForEdit(tempDir); expect(result).toEqual({ ok: true, @@ -59,11 +233,11 @@ describe("paseo config file substrate", () => { teardown: ["npm run clean", "npm run reset"], }, }, - revision: statPaseoConfigPath(tempDir), + revision: await statPaseoConfigPath(tempDir), }); }); - it("keeps runtime lifecycle commands normalized for execution", () => { + it("keeps runtime lifecycle commands normalized for execution", async () => { writeFileSync( join(tempDir, "paseo.json"), JSON.stringify({ @@ -74,15 +248,15 @@ describe("paseo config file substrate", () => { }), ); - expect(getWorktreeSetupCommands(tempDir)).toEqual(["npm install"]); - expect(getWorktreeTeardownCommands(tempDir)).toEqual(["npm run clean", "npm run reset"]); + expect(await getWorktreeSetupCommands(tempDir)).toEqual(["npm install"]); + expect(await getWorktreeTeardownCommands(tempDir)).toEqual(["npm run clean", "npm run reset"]); }); - it("writes pretty JSON with a trailing newline when revision matches", () => { + it("writes pretty JSON with a trailing newline when revision matches", async () => { writeFileSync(join(tempDir, "paseo.json"), JSON.stringify({ worktree: { setup: "old" } })); - const expectedRevision = statPaseoConfigPath(tempDir); + const expectedRevision = await statPaseoConfigPath(tempDir); - const result = writePaseoConfigForEdit({ + const result = await writePaseoConfigForEdit({ repoRoot: tempDir, config: { worktree: { setup: "npm install" } }, expectedRevision, @@ -91,7 +265,7 @@ describe("paseo config file substrate", () => { expect(result).toEqual({ ok: true, config: { worktree: { setup: "npm install" } }, - revision: statPaseoConfigPath(tempDir), + revision: await statPaseoConfigPath(tempDir), }); expect(readFileSync(join(tempDir, "paseo.json"), "utf8")).toBe( '{\n "worktree": {\n "setup": "npm install"\n }\n}\n', @@ -101,13 +275,13 @@ describe("paseo config file substrate", () => { // POSIX-only: Windows mtime granularity can collapse the two revisions in this fixture. it.skipIf(isPlatform("win32"))( "rejects stale writes when the current revision changed before rename", - () => { + async () => { writeFileSync(join(tempDir, "paseo.json"), JSON.stringify({ worktree: { setup: "old" } })); - const expectedRevision = statPaseoConfigPath(tempDir); + const expectedRevision = await statPaseoConfigPath(tempDir); writeFileSync(join(tempDir, "paseo.json"), JSON.stringify({ worktree: { setup: "new" } })); - const currentRevision = statPaseoConfigPath(tempDir); + const currentRevision = await statPaseoConfigPath(tempDir); - const result = writePaseoConfigForEdit({ + const result = await writePaseoConfigForEdit({ repoRoot: tempDir, config: { worktree: { setup: "from editor" } }, expectedRevision, @@ -123,7 +297,7 @@ describe("paseo config file substrate", () => { }, ); - it("round-trips unknown top-level, worktree, and script-entry fields", () => { + it("round-trips unknown top-level, worktree, and script-entry fields", async () => { const config = { extraTop: { keep: true }, worktree: { @@ -139,7 +313,7 @@ describe("paseo config file substrate", () => { }, }; - const result = writePaseoConfigForEdit({ + const result = await writePaseoConfigForEdit({ repoRoot: tempDir, config, expectedRevision: null, @@ -148,20 +322,20 @@ describe("paseo config file substrate", () => { expect(result).toEqual({ ok: true, config, - revision: statPaseoConfigPath(tempDir), + revision: await statPaseoConfigPath(tempDir), }); - expect(readPaseoConfigForEdit(tempDir)).toEqual({ + expect(await readPaseoConfigForEdit(tempDir)).toEqual({ ok: true, config, - revision: statPaseoConfigPath(tempDir), + revision: await statPaseoConfigPath(tempDir), }); }); - it("returns write_failed for filesystem write exceptions", () => { + it("returns write_failed for filesystem write exceptions", async () => { const fileRoot = join(tempDir, "not-a-directory"); writeFileSync(fileRoot, "file"); - const result = writePaseoConfigForEdit({ + const result = await writePaseoConfigForEdit({ repoRoot: fileRoot, config: { worktree: { setup: "npm install" } }, expectedRevision: null, @@ -173,10 +347,10 @@ describe("paseo config file substrate", () => { }); }); - it("creates paseo.json when the file is still missing and expected revision is null", () => { + it("creates paseo.json when the file is still missing and expected revision is null", async () => { mkdirSync(join(tempDir, "nested")); - const result = writePaseoConfigForEdit({ + const result = await writePaseoConfigForEdit({ repoRoot: join(tempDir, "nested"), config: { scripts: { dev: { command: "npm run dev" } } }, expectedRevision: null, @@ -185,7 +359,7 @@ describe("paseo config file substrate", () => { expect(result).toEqual({ ok: true, config: { scripts: { dev: { command: "npm run dev" } } }, - revision: statPaseoConfigPath(join(tempDir, "nested")), + revision: await statPaseoConfigPath(join(tempDir, "nested")), }); }); }); diff --git a/packages/server/src/utils/paseo-config-file.ts b/packages/server/src/utils/paseo-config-file.ts index 9b31918e63..b8152c4f22 100644 --- a/packages/server/src/utils/paseo-config-file.ts +++ b/packages/server/src/utils/paseo-config-file.ts @@ -1,8 +1,14 @@ -import { existsSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; +import { constants, type Stats } from "node:fs"; +import { open, realpath, rename, rm, stat, writeFile } from "node:fs/promises"; +import { join, resolve } from "node:path"; +import pLimit from "p-limit"; +import { withTimeout } from "./promise-timeout.js"; +import { setImmediate as nextTurn } from "node:timers/promises"; import { randomUUID } from "node:crypto"; import { PaseoConfigRawSchema, + PaseoConfigSchema, + type PaseoConfig, type PaseoConfigRaw, type PaseoConfigRevision, type ProjectConfigRpcError, @@ -15,15 +21,18 @@ export { } from "@getpaseo/protocol/paseo-config-schema"; export const PASEO_CONFIG_FILE_NAME = "paseo.json"; +// Configuration is deliberately small. Bound both IO and main-thread JSON/schema work. +export const MAX_PASEO_CONFIG_BYTES = 256 * 1024; export type ReadPaseoConfigForEditResult = | { ok: true; config: PaseoConfigRaw | null; revision: PaseoConfigRevision | null } | { ok: false; error: ProjectConfigRpcError }; - +export type ReadPaseoConfigResult = + | { ok: true; config: PaseoConfig | null } + | { ok: false; configPath: string; error: unknown }; export type WritePaseoConfigForEditResult = | { ok: true; config: PaseoConfigRaw; revision: PaseoConfigRevision } | { ok: false; error: ProjectConfigRpcError }; - export interface WritePaseoConfigForEditInput { repoRoot: string; config: PaseoConfigRaw; @@ -34,96 +43,272 @@ export function resolvePaseoConfigPath(repoRoot: string): string { return join(repoRoot, PASEO_CONFIG_FILE_NAME); } -export function statPaseoConfigPath(repoRoot: string): PaseoConfigRevision | null { - const configPath = resolvePaseoConfigPath(repoRoot); - if (!existsSync(configPath)) { - return null; - } - const stats = statSync(configPath); - return { - mtimeMs: stats.mtimeMs, - size: stats.size, - }; +function revision(stats: Stats): PaseoConfigRevision { + return { mtimeMs: stats.mtimeMs, size: stats.size }; } -export function readPaseoConfigJson(repoRoot: string): unknown { - const configPath = resolvePaseoConfigPath(repoRoot); - if (!existsSync(configPath)) { - return null; - } - return JSON.parse(readFileSync(configPath, "utf8")); -} - -export function readPaseoConfigForEdit(repoRoot: string): ReadPaseoConfigForEditResult { +async function inspect(repoRoot: string): Promise { try { - const json = readPaseoConfigJson(repoRoot); - if (json === null) { - return { ok: true, config: null, revision: null }; + return await stat(resolvePaseoConfigPath(repoRoot)); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; + throw error; + } +} + +export async function statPaseoConfigPath(repoRoot: string): Promise { + const stats = await inspect(repoRoot); + return stats ? revision(stats) : null; +} + +function admit(stats: Stats): void { + if (!stats.isFile() || stats.size > MAX_PASEO_CONFIG_BYTES) { + throw new Error(`paseo.json must be a regular file of at most ${MAX_PASEO_CONFIG_BYTES} bytes`); + } +} + +function fingerprint(stats: Stats | null): string { + return stats + ? `${stats.dev}:${stats.ino}:${stats.size}:${stats.mtimeMs}:${stats.ctimeMs}` + : "missing"; +} + +// The record schema validates every script synchronously. Validate bounded groups +// through the same schemas so thousands of script entries do not monopolize a turn. +async function validateConfig(json: unknown): Promise<{ + edit: ReturnType; + runtime: PaseoConfig; +}> { + if (json === null || typeof json !== "object" || Array.isArray(json)) { + return { edit: PaseoConfigRawSchema.safeParse(json), runtime: PaseoConfigSchema.parse(json) }; + } + const scripts = (json as Record).scripts; + if (scripts === null || typeof scripts !== "object" || Array.isArray(scripts)) { + return { edit: PaseoConfigRawSchema.safeParse(json), runtime: PaseoConfigSchema.parse(json) }; + } + const withoutScripts = { ...json, scripts: {} }; + let edit = PaseoConfigRawSchema.safeParse(withoutScripts); + const runtime = PaseoConfigSchema.parse(withoutScripts); + const entries = Object.entries(scripts); + if (entries.length > 32) await nextTurn(); + let lastYield = performance.now(); + for (let offset = 0; offset < entries.length; offset += 32) { + const group = { scripts: Object.fromEntries(entries.slice(offset, offset + 32)) }; + if (edit.success) { + const parsed = PaseoConfigRawSchema.safeParse(group); + if (parsed.success) Object.assign(edit.data.scripts!, parsed.data.scripts); + else edit = parsed; } - return { - ok: true, - config: PaseoConfigRawSchema.parse(json), - revision: statPaseoConfigPath(repoRoot), - }; + Object.assign(runtime.scripts!, PaseoConfigSchema.parse(group).scripts); + if (performance.now() - lastYield >= 2) { + await nextTurn(); + lastYield = performance.now(); + } + } + return { edit, runtime }; +} + +interface Snapshot { + fingerprint: string; + edit: ReadPaseoConfigForEditResult; + runtime: ReadPaseoConfigResult; +} + +/** Owns config admission, snapshots and daemon read/modify/write ordering for every consumer. */ +class ProjectConfigOwner { + // A stalled mount retains its slot until the OS returns; never consume the whole fs pool. + private readonly filesystemOperations = pLimit(2); + private readonly pendingAliases = new Map>(); + private readonly snapshots = new Map(); + private readonly pending = new Map< + string, + { kind: "read" | "write"; promise: Promise } + >(); + + async resolveRoot(repoRoot: string, activeRoots: Set): Promise { + const root = resolve(repoRoot); + if (activeRoots.has(root)) return root; + let pending = this.pendingAliases.get(root); + if (!pending) { + pending = this.filesystemOperations(() => realpath(root)).finally(() => + this.pendingAliases.delete(root), + ); + this.pendingAliases.set(root, pending); + } + try { + const alias = await withTimeout(pending, 5_000, "Project root unavailable"); + return activeRoots.has(alias) ? alias : null; + } catch { + return null; + } + } + + private async serialized( + root: string, + kind: "read" | "write", + operation: () => Promise, + ): Promise { + const previous = this.pending.get(root); + if (kind === "read" && previous?.kind === "read") return previous.promise as Promise; + const next = (async () => { + await previous?.promise.catch(() => undefined); + return this.filesystemOperations(operation); + })(); + this.pending.set(root, { kind, promise: next }); + try { + return await next; + } finally { + if (this.pending.get(root)?.promise === next) this.pending.delete(root); + } + } + + private remember(root: string, snapshot: Snapshot): Snapshot { + this.snapshots.delete(root); + this.snapshots.set(root, snapshot); + // Worktrees come and go; retain only a bounded set of reusable snapshots. + if (this.snapshots.size > 256) this.snapshots.delete(this.snapshots.keys().next().value!); + return snapshot; + } + + async read(repoRoot: string): Promise { + const root = resolve(repoRoot); + return withTimeout( + this.serialized(root, "read", () => this.load(root)), + 5_000, + "Project config unavailable", + ); + } + + private async load(root: string): Promise { + const stats = await inspect(root); + if (stats) admit(stats); + const key = fingerprint(stats); + const cached = this.snapshots.get(root); + if (cached?.fingerprint === key) return this.remember(root, cached); + let json: unknown = null; + if (stats) { + // O_NONBLOCK prevents a regular-file -> FIFO replacement between stat and open + // from waiting for a writer. Check the opened descriptor again before any read. + const handle = await open( + resolvePaseoConfigPath(root), + constants.O_RDONLY | constants.O_NONBLOCK, + ); + try { + const openedStats = await handle.stat(); + admit(openedStats); + const bytes = Buffer.alloc(MAX_PASEO_CONFIG_BYTES + 1); + let length = 0; + while (length < bytes.length) { + const { bytesRead } = await handle.read(bytes, length, bytes.length - length, null); + if (bytesRead === 0) break; + length += bytesRead; + } + if (length > MAX_PASEO_CONFIG_BYTES) throw new Error("paseo.json exceeds byte limit"); + // Never publish bytes under a revision that did not describe the opened file. + if (fingerprint(await handle.stat()) !== fingerprint(openedStats)) { + throw new Error("paseo.json changed while reading; retry the operation"); + } + try { + json = JSON.parse(bytes.toString("utf8", 0, length)); + } catch (error) { + return this.remember(root, { + fingerprint: key, + edit: { ok: false, error: { code: "invalid_project_config" } }, + runtime: { ok: false, configPath: resolvePaseoConfigPath(root), error }, + }); + } + if (fingerprint(openedStats) !== key) { + throw new Error("paseo.json was replaced while reading; retry the operation"); + } + } finally { + await handle.close(); + } + } + const validated = json === null ? null : await validateConfig(json); + const parsed = validated?.edit ?? null; + let edit: ReadPaseoConfigForEditResult = { ok: true, config: null, revision: null }; + if (parsed !== null) { + edit = parsed.success + ? { ok: true, config: parsed.data, revision: stats ? revision(stats) : null } + : { ok: false, error: { code: "invalid_project_config" } }; + } + return this.remember(root, { + fingerprint: key, + edit, + runtime: { ok: true, config: validated?.runtime ?? null }, + }); + } + + async write(input: WritePaseoConfigForEditInput): Promise { + const root = resolve(input.repoRoot); + return this.serialized(root, "write", async () => { + const { edit: parsed } = await validateConfig(input.config); + if (!parsed.success) return { ok: false, error: { code: "invalid_project_config" } }; + const content = `${JSON.stringify(parsed.data, null, 2)}\n`; + if (Buffer.byteLength(content) > MAX_PASEO_CONFIG_BYTES) { + return { ok: false, error: { code: "invalid_project_config" } }; + } + const tempPath = join(root, `.${PASEO_CONFIG_FILE_NAME}.${process.pid}.${randomUUID()}.tmp`); + try { + await writeFile(tempPath, content, { flag: "wx" }); + const savedRevision = revision(await stat(tempPath)); + const currentStats = await inspect(root); + if (currentStats) admit(currentStats); + const currentRevision = currentStats ? revision(currentStats) : null; + if (!paseoConfigRevisionsEqual(currentRevision, input.expectedRevision)) { + return { ok: false, error: { code: "stale_project_config", currentRevision } }; + } + // Serialized against daemon edits. External writers still have the existing + // optimistic stat/rename race; revision tokens remain mtime + size. + await rename(tempPath, resolvePaseoConfigPath(root)); + this.snapshots.delete(root); + return { ok: true, config: parsed.data, revision: savedRevision }; + } catch { + return { ok: false, error: { code: "write_failed" } }; + } finally { + await rm(tempPath, { force: true }).catch(() => undefined); + } + }); + } +} + +const projectConfig = new ProjectConfigOwner(); + +export function resolveProjectConfigRoot( + repoRoot: string, + activeRoots: Set, +): Promise { + return projectConfig.resolveRoot(repoRoot, activeRoots); +} + +export async function readPaseoConfig(repoRoot: string): Promise { + try { + return (await projectConfig.read(repoRoot)).runtime; + } catch (error) { + return { ok: false, configPath: resolvePaseoConfigPath(repoRoot), error }; + } +} + +export async function readPaseoConfigForEdit( + repoRoot: string, +): Promise { + try { + return (await projectConfig.read(repoRoot)).edit; } catch { - return { - ok: false, - error: { code: "invalid_project_config" }, - }; + return { ok: false, error: { code: "invalid_project_config" } }; } } export function writePaseoConfigForEdit( input: WritePaseoConfigForEditInput, -): WritePaseoConfigForEditResult { - const parsed = PaseoConfigRawSchema.safeParse(input.config); - if (!parsed.success) { - return { ok: false, error: { code: "invalid_project_config" } }; - } - - const configPath = resolvePaseoConfigPath(input.repoRoot); - const tempPath = join( - input.repoRoot, - `.${PASEO_CONFIG_FILE_NAME}.${process.pid}.${randomUUID()}.tmp`, - ); - - try { - writeFileSync(tempPath, `${JSON.stringify(parsed.data, null, 2)}\n`); - const currentRevision = statPaseoConfigPath(input.repoRoot); - if (!paseoConfigRevisionsEqual(currentRevision, input.expectedRevision)) { - removeTempPaseoConfig(tempPath); - return { - ok: false, - error: { code: "stale_project_config", currentRevision }, - }; - } - - renameSync(tempPath, configPath); - const revision = statPaseoConfigPath(input.repoRoot); - if (!revision) { - return { ok: false, error: { code: "write_failed" } }; - } - return { ok: true, config: parsed.data, revision }; - } catch { - removeTempPaseoConfig(tempPath); - return { ok: false, error: { code: "write_failed" } }; - } +): Promise { + return projectConfig.write(input); } function paseoConfigRevisionsEqual( left: PaseoConfigRevision | null, right: PaseoConfigRevision | null, ): boolean { - if (left === null || right === null) { - return left === right; - } + if (left === null || right === null) return left === right; return left.mtimeMs === right.mtimeMs && left.size === right.size; } - -function removeTempPaseoConfig(tempPath: string): void { - try { - rmSync(tempPath, { force: true }); - } catch { - // Best-effort cleanup only; callers need the original write outcome. - } -} diff --git a/packages/server/src/utils/worktree.posix.test.ts b/packages/server/src/utils/worktree.posix.test.ts index a550995fb3..7819e2275c 100644 --- a/packages/server/src/utils/worktree.posix.test.ts +++ b/packages/server/src/utils/worktree.posix.test.ts @@ -48,8 +48,8 @@ import { delimiter, dirname, join } from "path"; import { tmpdir } from "os"; import net from "node:net"; -function loadConfigForTest(repoRoot: string): PaseoConfig | null { - const result = readPaseoConfig(repoRoot); +async function loadConfigForTest(repoRoot: string): Promise { + const result = await readPaseoConfig(repoRoot); return result.ok ? result.config : null; } @@ -894,7 +894,7 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { worktreePath: result.worktreePath, branchName: result.branchName, }); - expect(getWorktreeSetupCommands(result.worktreePath)).toEqual([ + expect(await getWorktreeSetupCommands(result.worktreePath)).toEqual([ 'greeting="hello from string setup"\necho "$greeting" > setup.log', ]); expect(readFileSync(join(result.worktreePath, "setup.log"), "utf8").trim()).toBe( @@ -963,7 +963,7 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { expect(readFileSync(join(repoDir, "setup-path.log"), "utf8").trim()).toBe("shim:ok"); }); - it("treats blank lifecycle strings as empty", () => { + it("treats blank lifecycle strings as empty", async () => { writeFileSync( join(repoDir, "paseo.json"), JSON.stringify({ @@ -974,11 +974,11 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { }), ); - expect(getWorktreeSetupCommands(repoDir)).toEqual([]); - expect(getWorktreeTeardownCommands(repoDir)).toEqual([]); + expect(await getWorktreeSetupCommands(repoDir)).toEqual([]); + expect(await getWorktreeTeardownCommands(repoDir)).toEqual([]); }); - it("filters non-string and blank entries from lifecycle arrays", () => { + it("filters non-string and blank entries from lifecycle arrays", async () => { writeFileSync( join(repoDir, "paseo.json"), JSON.stringify({ @@ -999,11 +999,11 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { }), ); - expect(getWorktreeSetupCommands(repoDir)).toEqual([ + expect(await getWorktreeSetupCommands(repoDir)).toEqual([ 'echo "first" > setup-array.log', 'echo "second" >> setup-array.log', ]); - expect(getWorktreeTeardownCommands(repoDir)).toEqual([ + expect(await getWorktreeTeardownCommands(repoDir)).toEqual([ 'echo "first" > "$PASEO_SOURCE_CHECKOUT_PATH/teardown-array.log"', 'echo "second" >> "$PASEO_SOURCE_CHECKOUT_PATH/teardown-array.log"', ]); @@ -1134,7 +1134,7 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { }; writeFileSync(join(repoDir, "paseo.json"), JSON.stringify(paseoConfig)); - expect(getWorktreeTerminalSpecs(repoDir)).toEqual([ + expect(await getWorktreeTerminalSpecs(repoDir)).toEqual([ { name: "Dev Server", command: "npm run dev" }, { command: "cd packages/app && npm run dev" }, ]); @@ -1154,7 +1154,7 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { }; writeFileSync(join(repoDir, "paseo.json"), JSON.stringify(paseoConfig)); - expect(getWorktreeTerminalSpecs(repoDir)).toEqual([ + expect(await getWorktreeTerminalSpecs(repoDir)).toEqual([ { name: "Watch", command: "npm run watch" }, { command: "npm run test" }, ]); @@ -1172,7 +1172,7 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { }), ); - const scriptConfigs = getScriptConfigs(loadConfigForTest(repoDir)); + const scriptConfigs = getScriptConfigs(await loadConfigForTest(repoDir)); const typecheck = scriptConfigs.get("typecheck"); expect(typecheck).toEqual({ @@ -1196,7 +1196,7 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { }), ); - const scriptConfigs = getScriptConfigs(loadConfigForTest(repoDir)); + const scriptConfigs = getScriptConfigs(await loadConfigForTest(repoDir)); const server = scriptConfigs.get("server"); expect(server).toEqual({ @@ -1236,7 +1236,7 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { }), ); - expect(getScriptConfigs(loadConfigForTest(repoDir))).toEqual( + expect(getScriptConfigs(await loadConfigForTest(repoDir))).toEqual( new Map([ ["valid", { command: "npm run valid" }], ["invalidType", { command: "npm run worker" }], @@ -1547,7 +1547,7 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { await deletePaseoWorktree({ cwd: repoDir, worktreePath: created.worktreePath, paseoHome }); - expect(getWorktreeTeardownCommands(repoDir)).toEqual([ + expect(await getWorktreeTeardownCommands(repoDir)).toEqual([ 'cleanup_message="teardown string"\necho "$cleanup_message" > "$PASEO_SOURCE_CHECKOUT_PATH/teardown.log"', ]); expect(readFileSync(join(repoDir, "teardown.log"), "utf8").trim()).toBe("teardown string"); diff --git a/packages/server/src/utils/worktree.ts b/packages/server/src/utils/worktree.ts index ca921fb219..dd6dfe7a44 100644 --- a/packages/server/src/utils/worktree.ts +++ b/packages/server/src/utils/worktree.ts @@ -10,7 +10,7 @@ import { buildStringCommandShellInvocation, createStringCommandShellEnv, } from "./string-command-shell.js"; -import { readPaseoConfigJson, resolvePaseoConfigPath } from "./paseo-config-file.js"; +import { readPaseoConfig } from "./paseo-config-file.js"; export { PaseoConfigRawSchema, PaseoLifecycleCommandRawSchema, @@ -20,7 +20,7 @@ export { type PaseoConfig, type PaseoConfigRaw, } from "@getpaseo/protocol/paseo-config-schema"; -import { PaseoConfigSchema, type PaseoConfig } from "@getpaseo/protocol/paseo-config-schema"; +import { type PaseoConfig } from "@getpaseo/protocol/paseo-config-schema"; import { createPaseoWorktreeChangeRequestHint, normalizeBaseRefName, @@ -246,21 +246,7 @@ export class InvalidGitBranchNameError extends Error { } } -export type ReadPaseoConfigResult = - | { ok: true; config: PaseoConfig | null } - | { ok: false; configPath: string; error: unknown }; - -export function readPaseoConfig(repoRoot: string): ReadPaseoConfigResult { - try { - const json = readPaseoConfigJson(repoRoot); - if (json === null) { - return { ok: true, config: null }; - } - return { ok: true, config: PaseoConfigSchema.parse(json) }; - } catch (error) { - return { ok: false, configPath: resolvePaseoConfigPath(repoRoot), error }; - } -} +export { readPaseoConfig, type ReadPaseoConfigResult } from "./paseo-config-file.js"; export function paseoConfigParseError(failure: { configPath: string; error: unknown }): Error { const detail = failure.error instanceof Error ? failure.error.message : String(failure.error); @@ -269,24 +255,26 @@ export function paseoConfigParseError(failure: { configPath: string; error: unkn }); } -function readPaseoConfigOrThrow(repoRoot: string): PaseoConfig | null { - const result = readPaseoConfig(repoRoot); +async function readPaseoConfigOrThrow(repoRoot: string): Promise { + const result = await readPaseoConfig(repoRoot); if (!result.ok) { throw paseoConfigParseError(result); } return result.config; } -export function getWorktreeSetupCommands(repoRoot: string): string[] { - return readPaseoConfigOrThrow(repoRoot)?.worktree?.setup ?? []; +export async function getWorktreeSetupCommands(repoRoot: string): Promise { + return (await readPaseoConfigOrThrow(repoRoot))?.worktree?.setup ?? []; } -export function getWorktreeTeardownCommands(repoRoot: string): string[] { - return readPaseoConfigOrThrow(repoRoot)?.worktree?.teardown ?? []; +export async function getWorktreeTeardownCommands(repoRoot: string): Promise { + return (await readPaseoConfigOrThrow(repoRoot))?.worktree?.teardown ?? []; } -export function getWorktreeTerminalSpecs(repoRoot: string): WorktreeTerminalConfig[] { - const terminals = readPaseoConfigOrThrow(repoRoot)?.worktree?.terminals; +export async function getWorktreeTerminalSpecs( + repoRoot: string, +): Promise { + const terminals = (await readPaseoConfigOrThrow(repoRoot))?.worktree?.terminals; if (!Array.isArray(terminals) || terminals.length === 0) { return []; } @@ -641,7 +629,7 @@ export async function runWorktreeSetupCommands(options: { onEvent?: (event: WorktreeSetupCommandProgressEvent) => void; }): Promise { // Read paseo.json from the worktree (it will have the same content as the source repo) - const setupCommands = getWorktreeSetupCommands(options.worktreePath); + const setupCommands = await getWorktreeSetupCommands(options.worktreePath); if (setupCommands.length === 0) { return []; } @@ -745,7 +733,7 @@ export async function runWorktreeTeardownCommands(options: { if (getRealpathAwareRelativePath(options.worktreePath, teardownCwd) === null) { throw new Error(`Worktree teardown cwd is outside the worktree: ${teardownCwd}`); } - const teardownCommands = getWorktreeTeardownCommands(teardownCwd); + const teardownCommands = await getWorktreeTeardownCommands(teardownCwd); if (teardownCommands.length === 0) { return []; } From 9bc998fa38e91b76df469f142fbdcdfd5dbaaa59 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Tue, 27 Oct 2026 09:57:35 +0700 Subject: [PATCH 043/173] fix(server): keep Git observation and worktree IO off the event loop (#7943) * fix(server): keep Git observation and worktree IO off the event loop Resolve subscription path identities before callbacks and serialize async worktree metadata mutations by canonical ownership. Git command tracing must not probe the working directory before spawning. * test(server): verify Git trace records without filesystem probes * fix(server): establish Git identities at observation setup Read-only checkout refreshes should not resolve watcher namespaces. Observation tests await setup and compare cross-workspace fan-out without depending on completion order. * fix(server): retain literal symlink targets in Git event identity Canonical realpaths can erase a symlink target spelling when its parent is also a symlink, such as /var on macOS. Resolve these aliases once during setup so deleted and ignored event paths still match without per-event IO. * fix(server): preserve Windows worktree path spelling * fix(server): retain native aliases in worktree ownership * test(server): write Git IO trace markers asynchronously --- .../src/server/git-observation-paths.ts | 106 +++++ .../src/server/paseo-worktree-service.test.ts | 10 +- .../src/server/paseo-worktree-service.ts | 16 +- .../src/server/session.workspaces.test.ts | 7 +- .../workspace-recovery-service.test.ts | 6 +- ...rkspace-create-worktree-source.e2e.test.ts | 1 + ...it-service.observation.integration.test.ts | 180 ++++++++ .../workspace-git-service.observation.test.ts | 23 +- .../workspace-git-service.primitive.test.ts | 4 +- .../src/server/workspace-git-service.ts | 124 +++--- .../server/workspace-registry-bootstrap.ts | 2 +- .../worktree-branch-name-generator.test.ts | 4 +- .../src/server/worktree-core.posix.test.ts | 4 +- .../src/utils/checkout-git.commits.test.ts | 2 +- .../server/src/utils/checkout-git.test.ts | 26 +- packages/server/src/utils/checkout-git.ts | 40 +- packages/server/src/utils/path.ts | 4 +- .../server/src/utils/run-git-command.test.ts | 5 +- packages/server/src/utils/run-git-command.ts | 2 - .../server/src/utils/worktree-metadata.ts | 400 +++++++++++------- .../server/src/utils/worktree.posix.test.ts | 131 +++++- packages/server/src/utils/worktree.test.ts | 11 +- packages/server/src/utils/worktree.ts | 109 +++-- 23 files changed, 906 insertions(+), 311 deletions(-) create mode 100644 packages/server/src/server/git-observation-paths.ts diff --git a/packages/server/src/server/git-observation-paths.ts b/packages/server/src/server/git-observation-paths.ts new file mode 100644 index 0000000000..1ef0a4e571 --- /dev/null +++ b/packages/server/src/server/git-observation-paths.ts @@ -0,0 +1,106 @@ +import { realpath } from "node:fs"; +import { readlink } from "node:fs/promises"; +import { promisify } from "node:util"; +import pLimit from "p-limit"; +import { dirname, resolve as resolvePath, sep } from "node:path"; +import { looksLikeDefiniteWindowsPath, normalizePathPreservingCase } from "../utils/path.js"; + +const nativeRealpath = promisify(realpath.native); +const jsRealpath = promisify(realpath); +const identityIo = pLimit(2); + +/** A subscription owns its lexical namespace, including the OS's real-root alias. */ +export class GitObservationPaths { + private constructor( + private readonly root: string, + private readonly aliases: string[], + private readonly windows: boolean, + ) {} + + static async create(root: string): Promise { + const windows = looksLikeDefiniteWindowsPath(root); + const normalizePath = (value: string) => + windows + ? normalizePathPreservingCase(value, true).replaceAll("\\", "/").toLowerCase() + : normalizePathPreservingCase(value, false); + const aliases = new Set([normalizePath(root)]); + // Sequential: foreign paths must not fan out into the shared libuv pool. + for (const resolve of [nativeRealpath, jsRealpath]) { + try { + aliases.add(normalizePath(await identityIo(() => resolve(root)))); + } catch { + /* Missing roots retain lexical identity. */ + } + } + // A link may name /var/... while realpath returns /private/var/... on macOS. + // Retain literal targets too, including chains, without following links in callbacks. + let current = root; + const visited = new Set(); + for (let remaining = 40; remaining > 0; remaining--) { + const alias = normalizePath(current); + if (visited.has(alias)) break; + visited.add(alias); + aliases.add(alias); + try { + const target = await identityIo(() => readlink(current)); + current = resolvePath(dirname(current), target); + } catch { + break; + } + } + return new GitObservationPaths(root, [...aliases], windows); + } + + relative(candidate: string): string | null { + const normalized = this.normalizeEventPath(candidate); + const comparable = this.windows ? normalized.toLowerCase() : normalized; + for (const alias of this.aliases) { + if (comparable === alias) return ""; + const prefix = alias.endsWith("/") ? alias : `${alias}/`; + if (comparable.startsWith(prefix)) { + // Slice the original spelling, preserving case in ref names on Windows. + return normalized.slice(prefix.length); + } + } + return null; + } + + // Compile excluded subtrees in every established root namespace. The event callback + // only compares strings; neither an ignored root nor an event needs another realpath. + createEventFilter(excludedRoots: Iterable): (candidate: string) => boolean { + const excluded: string[] = []; + for (const root of excludedRoots) { + const relative = this.relative(root); + if (relative === null) continue; + for (const alias of this.aliases) { + const subtree = relative ? `${alias}/${relative}` : alias; + excluded.push(this.windows ? subtree.toLowerCase() : subtree); + } + } + const prefixes = excluded.map((root) => `${root}/`); + return (candidate) => { + const normalized = this.normalizeEventPath(candidate); + const comparable = this.windows ? normalized.toLowerCase() : normalized; + if (this.aliases.includes(comparable)) return false; + for (let i = 0; i < excluded.length; i++) { + if (comparable === excluded[i] || comparable.startsWith(prefixes[i])) return false; + } + return true; + }; + } + + private normalizeEventPath(candidate: string): string { + if (this.windows) return normalizePathPreservingCase(candidate, true).replaceAll("\\", "/"); + if (candidate.includes("/.") || candidate.includes("//") || candidate.endsWith("/")) + return normalizePathPreservingCase(candidate, false); + return candidate; + } + + matches = (candidate: string): boolean => this.relative(candidate) === ""; + + toWatchPath(candidate: string): string { + const relative = this.relative(candidate); + if (relative === null) return candidate; + return relative ? `${this.root}${sep}${relative}` : this.root; + } +} diff --git a/packages/server/src/server/paseo-worktree-service.test.ts b/packages/server/src/server/paseo-worktree-service.test.ts index 66740d2ae2..1579f92d5f 100644 --- a/packages/server/src/server/paseo-worktree-service.test.ts +++ b/packages/server/src/server/paseo-worktree-service.test.ts @@ -548,7 +548,7 @@ test("renames an eligible unnamed branch-off worktree once on first agent contex ); expect(created.worktree.branchName).toBe("dazzling-yak"); - expect(readPaseoWorktreeMetadata(created.worktree.worktreePath)).toMatchObject({ + expect(await readPaseoWorktreeMetadata(created.worktree.worktreePath)).toMatchObject({ version: 2, firstAgentBranchAutoName: { status: "pending", @@ -575,7 +575,7 @@ test("renames an eligible unnamed branch-off worktree once on first agent contex branchName: "renamed-from-agent-context", }); expect(branchAfterFirst).toBe("renamed-from-agent-context"); - expect(readPaseoWorktreeMetadata(created.worktree.worktreePath)).toMatchObject({ + expect(await readPaseoWorktreeMetadata(created.worktree.worktreePath)).toMatchObject({ version: 2, firstAgentBranchAutoName: { status: "attempted", @@ -762,7 +762,7 @@ test("leaves the branch alone when generated branch text is invalid", async () = .toString() .trim(), ).toBe("dazzling-yak"); - expect(readPaseoWorktreeMetadata(created.worktree.worktreePath)).toMatchObject({ + expect(await readPaseoWorktreeMetadata(created.worktree.worktreePath)).toMatchObject({ version: 2, firstAgentBranchAutoName: { status: "attempted", @@ -794,7 +794,7 @@ test("does not mark checkout branch worktrees as eligible for first-agent rename // baseRefName must be the repo's default branch, not the checked-out branch // itself — otherwise the diff panel compares the branch against itself and // always shows no changes. - expect(readPaseoWorktreeMetadata(created.worktree.worktreePath)).toMatchObject({ + expect(await readPaseoWorktreeMetadata(created.worktree.worktreePath)).toMatchObject({ version: 1, baseRefName: "main", }); @@ -831,7 +831,7 @@ test("does not mark GitHub PR checkout worktrees as eligible for first-agent ren createDeps(), ); - expect(readPaseoWorktreeMetadata(created.worktree.worktreePath)).toMatchObject({ + expect(await readPaseoWorktreeMetadata(created.worktree.worktreePath)).toMatchObject({ version: 1, baseRefName: "main", }); diff --git a/packages/server/src/server/paseo-worktree-service.ts b/packages/server/src/server/paseo-worktree-service.ts index 61e00723d0..4080efd580 100644 --- a/packages/server/src/server/paseo-worktree-service.ts +++ b/packages/server/src/server/paseo-worktree-service.ts @@ -77,7 +77,7 @@ async function createPaseoWorktreeWithPriority( const workspaceCwdPlan = await planWorkspaceCwdForWorktree(input.cwd, deps.workspaceGitService); const createdWorktree = await createWorktreeCore(input, deps); try { - maybeMarkFirstAgentBranchAutoNameEligible({ createdWorktree }); + await maybeMarkFirstAgentBranchAutoNameEligible({ createdWorktree }); const workspaceCwd = mapWorkspaceRelativeCwdToWorktree({ relativeWorkspaceCwd: workspaceCwdPlan.relativeWorkspaceCwd, targetWorktreePath: createdWorktree.worktree.worktreePath, @@ -182,9 +182,9 @@ export async function attemptFirstAgentBranchAutoName(options: { return { attempted: false, renamed: false, branchName: null }; } - let metadata: ReturnType; + let metadata: Awaited>; try { - metadata = readPaseoWorktreeMetadata(options.cwd); + metadata = await readPaseoWorktreeMetadata(options.cwd); } catch { return { attempted: false, renamed: false, branchName: null }; } @@ -199,11 +199,11 @@ export async function attemptFirstAgentBranchAutoName(options: { const getCurrentBranchImpl = options.getCurrentBranch ?? getCurrentBranch; const placeholderBranchName = metadata.firstAgentBranchAutoName.placeholderBranchName; if ((await getCurrentBranchImpl(options.cwd)) !== placeholderBranchName) { - markPaseoWorktreeFirstAgentBranchAutoNameAttempted(options.cwd); + await markPaseoWorktreeFirstAgentBranchAutoNameAttempted(options.cwd); return { attempted: true, renamed: false, branchName: null }; } - markPaseoWorktreeFirstAgentBranchAutoNameAttempted(options.cwd); + await markPaseoWorktreeFirstAgentBranchAutoNameAttempted(options.cwd); const branchName = await options.generateBranchNameFromContext({ cwd: options.cwd, @@ -264,15 +264,15 @@ async function findAvailableBranchName(options: { return null; } -function maybeMarkFirstAgentBranchAutoNameEligible(options: { +async function maybeMarkFirstAgentBranchAutoNameEligible(options: { createdWorktree: Awaited>; -}): void { +}): Promise { const { createdWorktree } = options; if (!createdWorktree.created || createdWorktree.intent.kind !== "branch-off") { return; } - writePaseoWorktreeFirstAgentBranchAutoNameMetadata(createdWorktree.worktree.worktreePath, { + await writePaseoWorktreeFirstAgentBranchAutoNameMetadata(createdWorktree.worktree.worktreePath, { placeholderBranchName: createdWorktree.worktree.branchName, }); } diff --git a/packages/server/src/server/session.workspaces.test.ts b/packages/server/src/server/session.workspaces.test.ts index e4a0ca7668..3755ff56d8 100644 --- a/packages/server/src/server/session.workspaces.test.ts +++ b/packages/server/src/server/session.workspaces.test.ts @@ -9228,8 +9228,8 @@ test("workspace auto-name uses the backing root for a nested worktree", async () execFileSync("git", ["add", "README.md"], { cwd: repoDir, stdio: "pipe" }); execFileSync("git", ["commit", "-m", "initial"], { cwd: repoDir, stdio: "pipe" }); execFileSync("git", ["branch", "-M", "placeholder-branch"], { cwd: repoDir, stdio: "pipe" }); - writePaseoWorktreeMetadata(repoDir, { baseRefName: "main" }); - writePaseoWorktreeFirstAgentBranchAutoNameMetadata(repoDir, { + await writePaseoWorktreeMetadata(repoDir, { baseRefName: "main" }); + await writePaseoWorktreeFirstAgentBranchAutoNameMetadata(repoDir, { placeholderBranchName: "placeholder-branch", }); const workspaceCwd = path.join(repoDir, "packages", "app"); @@ -9288,6 +9288,7 @@ test("workspace auto-name uses the backing root for a nested worktree", async () firstAgentContext: { prompt: "Fix checkout title" }, }); await vi.runAllTimersAsync(); + await vi.waitFor(() => expect(emittedCwds).toEqual([workspaceCwd])); expect(generateCalls).toBe(1); expect(stored.get(workspace.workspaceId)).toMatchObject({ @@ -9299,7 +9300,7 @@ test("workspace auto-name uses the backing root for a nested worktree", async () .toString() .trim(), ).toBe("placeholder-branch"); - expect(readPaseoWorktreeMetadata(repoDir)).toMatchObject({ + expect(await readPaseoWorktreeMetadata(repoDir)).toMatchObject({ version: 2, firstAgentBranchAutoName: { status: "attempted", diff --git a/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.test.ts b/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.test.ts index f738a0b0d6..22e903b5f1 100644 --- a/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.test.ts +++ b/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.test.ts @@ -347,7 +347,7 @@ async function createBaseRecoveryFixture(baseBranch: string | null) { test("preserves ordinary checkout behavior when no separate base was recorded", async () => { const fixture = await createBaseRecoveryFixture(null); - writePaseoWorktreeMetadata(fixture.workspace.cwd, { baseRefName: "feature" }); + await writePaseoWorktreeMetadata(fixture.workspace.cwd, { baseRefName: "feature" }); await fixture.archiveAndRemove(); await fixture.service.restore(fixture.workspace.workspaceId); expect((await fixture.registry.get(fixture.workspace.workspaceId))?.baseBranch).toBeNull(); @@ -430,7 +430,7 @@ test("restores the branch HEAD with a base name when the exact base is missing", }); expect(existsSync(fixture.workspace.cwd)).toBe(true); expect((await fixture.registry.get(fixture.workspace.workspaceId))?.archivedAt).toBeNull(); - const metadata = readPaseoWorktreeMetadata(fixture.workspace.cwd); + const metadata = await readPaseoWorktreeMetadata(fixture.workspace.cwd); expect(metadata).toMatchObject({ baseRefName: "main" }); expect(metadata?.baseRef).toBeUndefined(); expect( @@ -450,7 +450,7 @@ test("restore fetches a deleted local branch from origin and retains its base", await fixture.archiveAndRemove(); execFileSync("git", ["branch", "-D", "feature"], { cwd: fixture.repoDir }); await fixture.service.restore(fixture.workspace.workspaceId); - expect(readPaseoWorktreeMetadata(fixture.workspace.cwd)?.baseRef).toBe("refs/heads/main"); + expect((await readPaseoWorktreeMetadata(fixture.workspace.cwd))?.baseRef).toBe("refs/heads/main"); expect( await getCheckoutStatus(fixture.workspace.cwd, { paseoHome: fixture.paseoHome }), ).toMatchObject({ diff --git a/packages/server/src/server/workspace-create-worktree-source.e2e.test.ts b/packages/server/src/server/workspace-create-worktree-source.e2e.test.ts index fc9efe1684..cd9ec71d83 100644 --- a/packages/server/src/server/workspace-create-worktree-source.e2e.test.ts +++ b/packages/server/src/server/workspace-create-worktree-source.e2e.test.ts @@ -493,6 +493,7 @@ async function createRestorableWorkspace(baseRef: string) { commitFile(cwd, "feature.txt", "feature change\n"); const head = runGit(cwd, "rev-parse", "HEAD"); await client.checkoutRefresh(cwd); + expect(await client.getCheckoutStatus(cwd)).toMatchObject({ isPaseoOwnedWorktree: true }); const before = await client.getCheckoutDiff(cwd, { mode: "base", baseRef: "main" }); expect(before.error).toBeNull(); expect(before.files.map((file) => file.path)).toEqual(["feature.txt"]); diff --git a/packages/server/src/server/workspace-git-service.observation.integration.test.ts b/packages/server/src/server/workspace-git-service.observation.integration.test.ts index a8a1f11dfb..55265416dc 100644 --- a/packages/server/src/server/workspace-git-service.observation.integration.test.ts +++ b/packages/server/src/server/workspace-git-service.observation.integration.test.ts @@ -526,3 +526,183 @@ test("a late Git-ignored tree is pruned while tracked changes still notify consu rmSync(tempDir, { recursive: true, force: true }); } }, 15_000); + +test("Git refresh, command tracing and 10,000 ignored alias events do no synchronous IO", async () => { + const { execFile } = await import("node:child_process"); + const { promisify } = await import("node:util"); + const { fileURLToPath } = await import("node:url"); + const repositoryRoot = fileURLToPath(new URL("../../../../", import.meta.url)); + const source = ` + import assert from 'node:assert/strict'; + import { write } from 'node:fs'; + import { mkdtemp, mkdir, writeFile, symlink, rm } from 'node:fs/promises'; + import { tmpdir } from 'node:os'; + import { join } from 'node:path'; + import { setImmediate as tick } from 'node:timers/promises'; + import { createHook } from 'node:async_hooks'; + import pino from 'pino'; + import { WorkspaceGitServiceImpl } from './packages/server/src/server/workspace-git-service.ts'; + import { runGitCommand } from './packages/server/src/utils/run-git-command.ts'; + import { writePaseoWorktreeMetadata } from './packages/server/src/utils/worktree-metadata.ts'; + const root = await mkdtemp(join(tmpdir(), 'git-async-contract-')); + const home = join(root, 'home'); + const repo = join(root, 'repo'); + const worktree = join(home, 'worktrees', 'project', 'topic'); + const alias = join(root, 'alias'); + const logger = pino({ level: 'trace' }, { write() {} }); + // Async descriptor writes avoid Windows stderr's synchronous stream API. + const marker = (label) => new Promise((resolve, reject) => { + write(2, label + '\\n', (error) => error ? reject(error) : resolve()); + }); + let callback; + let notifications = 0; + const service = new WorkspaceGitServiceImpl({ logger, paseoHome: home, deps: { + subscribe: async (_root, onChange) => { + callback = onChange; + return { updateIgnore: async () => {}, unsubscribe: async () => {} }; + } + } }); + try { + await mkdir(repo); + await runGitCommand(['init', '-b', 'main'], { cwd: repo }); + await runGitCommand(['-c', 'user.name=Test', '-c', 'user.email=test@example.com', 'commit', '--allow-empty', '-m', 'base'], { cwd: repo }); + await mkdir(join(home, 'worktrees', 'project'), { recursive: true }); + await runGitCommand(['worktree', 'add', '-b', 'topic', worktree], { cwd: repo }); + await writePaseoWorktreeMetadata(worktree, { baseRefName: 'main' }); + await writeFile(join(worktree, '.gitignore'), 'ignored/\\n'); + await mkdir(join(worktree, 'ignored')); + await writeFile(join(worktree, 'ignored', 'noise'), 'noise'); + await symlink(worktree, alias, process.platform === 'win32' ? 'junction' : 'dir'); + const subscription = await service.requestWorkingTreeWatch(alias, () => { notifications++; }); + const events = Array.from({ length: process.env.GIT_IO_TRACE ? 2 : 10000 }, (_, i) => ({ type: 'update', path: join(i % 2 ? alias : worktree, 'ignored', 'noise') })); + // A shared CI runner can deschedule the child during a wall-clock sample. + // Keep the 20ms gate, but take three independent batches and require one + // responsive callback/timer pair. All batches must remain filesystem-free. + const samples = []; + for (let trial = 0; trial < (process.env.GIT_IO_TRACE ? 1 : 3); trial++) { + await tick(); + let fsCalls = 0; + const hook = createHook({ init(_id, type) { if (type.startsWith('FSREQ')) fsCalls++; } }); + await marker('FILTER_START'); + hook.enable(); + const started = performance.now(); + const pulse = new Promise((resolve) => setTimeout(() => resolve(performance.now() - started), 0)); + callback(null, events); + const filterMs = performance.now() - started; + hook.disable(); + const loopGapMs = await pulse; + await marker('FILTER_END'); + assert.equal(fsCalls, 0, "filesystem calls"); + assert.equal(notifications, 0, "ignored event notification"); + samples.push({ filterMs, loopGapMs, fsCalls }); + } + console.log(JSON.stringify({ ...samples[0], samples })); + assert.ok(process.env.GIT_IO_TRACE || samples.some(({ filterMs, loopGapMs }) => filterMs < 20 && loopGapMs < 20), 'no responsive filter sample: ' + JSON.stringify(samples)); + // Alias identity remains useful after deletion: no per-event realpath can recover this file. + callback(null, [{ type: 'delete', path: join(worktree, 'tracked.txt') }]); + assert.equal(notifications, 1); + await marker('REFRESH_START'); + const snapshot = await service.getSnapshot(worktree); + assert.equal(snapshot.git.isGit, true); + assert.equal(snapshot.git.isPaseoOwnedWorktree, true); + await runGitCommand(['status', '--porcelain'], { cwd: alias, logger }); + await marker('REFRESH_END'); + subscription.unsubscribe(); + } finally { + await service.dispose(); + await rm(root, { recursive: true, force: true }); + } + `; + for (const tracing of [false, true]) { + const { stdout, stderr } = await promisify(execFile)( + process.execPath, + [ + "--import", + "tsx", + ...(tracing ? ["--trace-sync-io"] : []), + "--input-type=module", + "--eval", + source, + ], + { + cwd: repositoryRoot, + env: { ...process.env, GIT_IO_TRACE: tracing ? "1" : "" }, + timeout: 30_000, + maxBuffer: 4 * 1024 * 1024, + }, + ).catch((error) => { + throw new Error(String(error.stderr).replaceAll(/at .*/g, "[child stack omitted]")); + }); + for (const phase of ["FILTER", "REFRESH"]) { + const output = stderr.split(`${phase}_START\n`)[1]?.split(`${phase}_END\n`)[0]; + expect(output, `${phase}: synchronous filesystem IO`).toBe(""); + } + expect(JSON.parse(stdout.trim().split("\n")[0])).toMatchObject({ fsCalls: 0 }); + } +}, 60_000); + +test("Git event identity preserves Windows namespace, case and subtree boundaries", async () => { + const { GitObservationPaths } = await import("./git-observation-paths.js"); + const paths = await GitObservationPaths.create("C:\\paseo-observation-contract"); + const accept = paths.createEventFilter(["C:\\paseo-observation-contract\\Build"]); + expect(paths.relative("\\\\?\\C:\\PASEO-OBSERVATION-CONTRACT\\refs\\heads\\MixedCase")).toBe( + "refs/heads/MixedCase", + ); + expect(accept("\\\\?\\C:\\paseo-observation-contract\\build\\noise")).toBe(false); + expect(accept("C:\\paseo-observation-contract\\BuildSibling\\file")).toBe(true); +}); + +test("concurrent alias requests establish one working-tree subscription", async () => { + const { symlink } = await import("node:fs/promises"); + const root = realpathSync(mkdtempSync(path.join(tmpdir(), "git-observation-concurrent-"))); + const repo = path.join(root, "repo"); + const alias = path.join(root, "alias"); + execFileSync("git", ["init", "-b", "main", repo], { stdio: "pipe" }); + await symlink(repo, alias, process.platform === "win32" ? "junction" : "dir"); + let subscriptions = 0; + const service = new WorkspaceGitServiceImpl({ + logger: pino({ enabled: false }), + paseoHome: path.join(root, "home"), + deps: { + subscribe: async () => { + subscriptions++; + return { updateIgnore: async () => {}, unsubscribe: async () => {} }; + }, + }, + }); + try { + const watches = await Promise.all([ + service.requestWorkingTreeWatch(repo, () => {}), + service.requestWorkingTreeWatch(alias, () => {}), + ]); + expect(subscriptions).toBe(1); + for (const watch of watches) watch.unsubscribe(); + } finally { + await service.dispose(); + rmSync(root, { recursive: true, force: true }); + } +}); + +test("Git event identity retains a symlink's literal target before canonicalizing its parent", async () => { + const { mkdir, symlink } = await import("node:fs/promises"); + const { GitObservationPaths } = await import("./git-observation-paths.js"); + const root = realpathSync(mkdtempSync(path.join(tmpdir(), "git-observation-literal-target-"))); + const repository = path.join(root, "repository"); + const parentAlias = path.join(root, "parent-alias"); + const workspaceAlias = path.join(root, "workspace-alias"); + const literalTarget = path.join(parentAlias, "repository"); + const linkType = process.platform === "win32" ? "junction" : "dir"; + try { + await mkdir(repository); + await symlink(root, parentAlias, linkType); + await symlink(literalTarget, workspaceAlias, linkType); + const paths = await GitObservationPaths.create(workspaceAlias); + const accept = paths.createEventFilter([path.join(workspaceAlias, "ignored")]); + for (const spelling of [workspaceAlias, literalTarget, repository]) { + expect(paths.relative(path.join(spelling, "deleted.txt"))).toBe("deleted.txt"); + expect(accept(path.join(spelling, "ignored", "deleted.txt"))).toBe(false); + } + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/packages/server/src/server/workspace-git-service.observation.test.ts b/packages/server/src/server/workspace-git-service.observation.test.ts index f91a96e464..ab93558793 100644 --- a/packages/server/src/server/workspace-git-service.observation.test.ts +++ b/packages/server/src/server/workspace-git-service.observation.test.ts @@ -1189,7 +1189,7 @@ describe("WorkspaceGitService checkout observation", () => { ]); await vi.advanceTimersByTimeAsync(1_000); await vi.waitFor(() => { - expect(getCalledCwds(getCheckoutStatus)).toEqual([WORKTREE_A, WORKTREE_B]); + expect(getCalledCwds(getCheckoutStatus).sort()).toEqual([WORKTREE_A, WORKTREE_B].sort()); }); first.unsubscribe(); @@ -1624,6 +1624,12 @@ describe("WorkspaceGitService checkout observation", () => { const subscription = service.registerWorkspace({ cwd: REPO_CWD }, vi.fn()); await vi.waitFor(() => { + expect(watcher.subscribe).toHaveBeenCalledWith( + GIT_DIR, + expect.any(Function), + expect.any(Object), + ); + expect(getCheckoutStatus).toHaveBeenCalledTimes(1); expect(service.getMetrics().workspaceObservationSetupInFlightCount).toBe(0); expect(service.getMetrics().workspaceRefreshInFlightCount).toBe(0); }); @@ -1642,14 +1648,17 @@ describe("WorkspaceGitService checkout observation", () => { [60_000, 6], ] as const) { await vi.advanceTimersByTimeAsync(elapsedMs); - expect(pollCount()).toBe(expectedPolls); + await vi.waitFor(() => { + expect(pollCount()).toBe(expectedPolls); + expect(service.getMetrics().workspaceRefreshInFlightCount).toBe(0); + }); } isDirty = true; await vi.advanceTimersByTimeAsync(60_000); - expect(pollCount()).toBe(7); + await vi.waitFor(() => expect(pollCount()).toBe(7)); await vi.advanceTimersByTimeAsync(5_000); - expect(pollCount()).toBe(8); + await vi.waitFor(() => expect(pollCount()).toBe(8)); subscription.unsubscribe(); service.dispose(); @@ -1860,8 +1869,10 @@ describe("WorkspaceGitService checkout observation", () => { expect(watcher.subscribe).toHaveBeenCalledTimes(1); }); await vi.advanceTimersByTimeAsync(35_000); - expect(service.getMetrics().workingTreeWatchSetupInFlightCount).toBe(0); - expect(service.getMetrics().workspaceObservationSetupAdmissionActiveCount).toBe(0); + await vi.waitFor(() => { + expect(service.getMetrics().workingTreeWatchSetupInFlightCount).toBe(0); + expect(service.getMetrics().workspaceObservationSetupAdmissionActiveCount).toBe(0); + }); expect(getWatcherSubscribeCallCount(watcher, REPO_CWD)).toBe(1); openedSubscription.resolve({ diff --git a/packages/server/src/server/workspace-git-service.primitive.test.ts b/packages/server/src/server/workspace-git-service.primitive.test.ts index 9a3599740c..1b43026c7d 100644 --- a/packages/server/src/server/workspace-git-service.primitive.test.ts +++ b/packages/server/src/server/workspace-git-service.primitive.test.ts @@ -991,7 +991,7 @@ describe("WorkspaceGitServiceImpl primitive refresh entrypoint", () => { await vi.advanceTimersByTimeAsync(60_000); await flushPromises(); - expect(subscribe).toHaveBeenCalledTimes(2); + await vi.waitFor(() => expect(subscribe).toHaveBeenCalledTimes(2)); expect(getCheckoutStatus).toHaveBeenCalledTimes(1); subscription.unsubscribe(); @@ -2221,7 +2221,7 @@ describe("WorkspaceGitServiceImpl D2 read methods", () => { expect(getCheckoutStatus).toHaveBeenCalledTimes(2); expect(getPullRequestStatus).toHaveBeenCalledTimes(2); - service.dispose(); + await service.dispose(); }); test("onWorkspaceStateMayHaveChanged preserves includeForge when a file watcher fires within the debounce window", async () => { diff --git a/packages/server/src/server/workspace-git-service.ts b/packages/server/src/server/workspace-git-service.ts index 493daa1ddd..b5672846bd 100644 --- a/packages/server/src/server/workspace-git-service.ts +++ b/packages/server/src/server/workspace-git-service.ts @@ -42,18 +42,13 @@ import { type ForgeResolver, } from "../services/forge-resolver.js"; import { parseGitRevParsePath } from "../utils/git-rev-parse-path.js"; -import { - createRealpathAwarePathMatcher, - getRealpathAwareRelativePath, - isPathInsideRoot, - isRealpathInsideRoot, - looksLikeDefiniteWindowsPath, -} from "../utils/path.js"; +import { isPathInsideRoot, looksLikeDefiniteWindowsPath } from "../utils/path.js"; import { createRunGitCommand, runGitCommand, type RunGitCommand, } from "../utils/run-git-command.js"; +import { GitObservationPaths } from "./git-observation-paths.js"; import { branchNameFromRef } from "../utils/worktree-metadata.js"; import { listPaseoWorktrees, type PaseoWorktreeInfo } from "../utils/worktree.js"; import { READ_ONLY_GIT_ENV } from "./checkout-git-utils.js"; @@ -417,6 +412,7 @@ class WorkspaceGitWatcherSubscriptionTimeoutError extends Error { } interface WorkspaceGitTarget { + gitDirPaths: GitObservationPaths | null; cwd: string; listeners: Set; workingTreeWatchTarget: WorkingTreeWatchTarget | null; @@ -443,6 +439,7 @@ interface WorkspaceGitTarget { } interface RepoGitTarget { + paths: GitObservationPaths; repoGitRoot: string; cwd: string; workspaceKeys: Set; @@ -470,6 +467,8 @@ interface RepoMetadataWorkspaceRefresh { } interface WorkingTreeWatchTarget { + paths: GitObservationPaths; + acceptsEvent: (candidate: string) => boolean; cwd: string; watchPath: string; repoRoot: string | null; @@ -1170,6 +1169,8 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { private async resolveWorkingTreeWatchTarget(cwd: string): Promise { const repoRoot = await this.resolveCheckoutWatchRoot(cwd); + const cwdPaths = repoRoot ? await GitObservationPaths.create(cwd) : null; + this.assertNotDisposed(); const targetCwd = repoRoot ?? cwd; const existingTarget = this.workingTreeWatchTargets.get(targetCwd); if (existingTarget) { @@ -1184,7 +1185,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { return target; } - const watchPath = repoRoot && createRealpathAwarePathMatcher(repoRoot)(cwd) ? cwd : targetCwd; + const watchPath = repoRoot && cwdPaths?.matches(repoRoot) ? cwd : targetCwd; const setup = this.createWorkingTreeWatchTarget(targetCwd, watchPath, repoRoot).finally(() => { if (this.workingTreeWatchSetups.get(targetCwd) === setup) { this.workingTreeWatchSetups.delete(targetCwd); @@ -1203,6 +1204,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { private createWorkspaceTarget(cwd: string): WorkspaceGitTarget { const target: WorkspaceGitTarget = { + gitDirPaths: null, cwd, listeners: new Set(), workingTreeWatchTarget: null, @@ -1304,6 +1306,11 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { } await this.promoteWorkingTreeWatchTarget(workingTreeTarget, facts.worktreeRoot); const gitDir = facts.absoluteGitDir; + const gitDirPaths = target.gitDirPaths?.matches(gitDir) + ? target.gitDirPaths + : await GitObservationPaths.create(gitDir); + if (!this.isActiveObservedWorkspaceTarget(target)) return; + target.gitDirPaths = gitDirPaths; const repoGitRoot = facts.gitCommonDir ?? (await this.resolveWorkspaceGitRefsRoot(gitDir)); if (!this.isActiveObservedWorkspaceTarget(target)) { return; @@ -1336,7 +1343,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { const promise = this.deps .getCheckoutSnapshotFacts(target.cwd, context) .then((facts) => { - target.latestFacts = facts; + if (!target.closed) target.latestFacts = facts; return facts; }) .finally(() => { @@ -1364,7 +1371,11 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { const ignoredDirectories = repoRoot ? (await this.loadIgnoredDirs(watchPath)).ignored : new Set(); + const paths = await GitObservationPaths.create(watchPath); + this.assertNotDisposed(); const target: WorkingTreeWatchTarget = { + paths, + acceptsEvent: paths.createEventFilter([join(watchPath, ".git"), ...ignoredDirectories]), cwd, watchPath, repoRoot, @@ -1528,15 +1539,14 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { if (watcherErrored) { return; } + events = this.relevantWorkingTreeEvents(target, events); + if (events.length === 0) return; const discovered = this.noteWorkingTreeDirectories(target, events); if (events.some((event) => basename(event.path) === ".gitignore")) { void this.refreshWorkingTreeIgnoredDirectories(target); } else if (discovered) { this.scheduleWorkingTreeIgnoreRefresh(target); } - if (!this.hasRelevantWorkingTreeEvent(target, events)) { - return; - } this.notifyWorkingTreeChanged(target, "working-tree-watch"); }, { ignore }, @@ -1768,20 +1778,15 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { } this.removeDeletedKnownDirectories(target, events); const gitDir = join(target.watchPath, ".git"); - // `matchesWatchPath` is realpath-aware because it compares an event-reported - // directory against `target.watchPath` itself — a config-time root that can - // legitimately differ from the watcher's reported form (e.g. a symlinked - // temp dir). It is now gated behind the plain Set lookup below, so it only - // runs for a directory this target has never seen before, not on every - // event. - const matchesWatchPath = createRealpathAwarePathMatcher(target.watchPath); + // Event paths have already been mapped into this subscription's established namespace. + const matchesWatchPath = target.paths.matches; // One new directory is enough: the scheduled Git query inventories every // ignored directory that exists by then. Stop before a large event batch // multiplies containment checks across all its new directories. for (const event of events) { const directory = dirname(event.path); // Cheap Set lookup first — the steady-state case where the directory is - // already known must never reach the realpath-aware matcher below. + // already known do not need another root comparison. if (target.knownDirectories.has(directory) || matchesWatchPath(directory)) { continue; } @@ -1960,28 +1965,22 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { target.pendingKnownDirectories.clear(); } - private hasRelevantWorkingTreeEvent( + private relevantWorkingTreeEvents( target: WorkingTreeWatchTarget, events: FileChange[], - ): boolean { - const gitDir = join(target.watchPath, ".git"); - const matchesWatchPath = createRealpathAwarePathMatcher(target.watchPath); - return events.some((event) => { - // Directory metadata changes at the watch root do not change Git state. - // FSEvents may emit these when every changed descendant was ignored. - if (matchesWatchPath(event.path)) { - return false; + ): FileChange[] { + const relevant: FileChange[] = []; + // Watch backends may report the same path more than once in a batch. + const acceptedPaths = new Map(); + for (const event of events) { + let accepted = acceptedPaths.get(event.path); + if (accepted === undefined) { + accepted = target.acceptsEvent(event.path); + acceptedPaths.set(event.path, accepted); } - if (isRealpathInsideRoot(gitDir, event.path)) { - return false; - } - for (const ignoredDirectory of target.ignoredDirectories) { - if (isRealpathInsideRoot(ignoredDirectory, event.path)) { - return false; - } - } - return true; - }); + if (accepted) relevant.push({ ...event, path: target.paths.toWatchPath(event.path) }); + } + return relevant; } private refreshWorkingTreeIgnoredDirectories(target: WorkingTreeWatchTarget): Promise { @@ -2036,6 +2035,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { } if (!this.haveSamePaths(target.ignoredDirectories, ignoredDirectories)) { target.ignoredDirectories = ignoredDirectories; + target.acceptsEvent = target.paths.createEventFilter(this.workingTreeIgnoreList(target)); this.pruneKnownDirectories(target); } if (target.fallbackPolling) { @@ -2157,7 +2157,15 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { return; } + const paths = await GitObservationPaths.create(repoGitRoot); + if (!this.isActiveObservedWorkspaceTarget(workspaceTarget)) return; + const establishedTarget = this.repoTargets.get(repoGitRoot); + if (establishedTarget) { + establishedTarget.workspaceKeys.add(workspaceTarget.cwd); + return; + } const repoTarget: RepoGitTarget = { + paths, repoGitRoot, cwd: workspaceTarget.cwd, workspaceKeys: new Set([workspaceTarget.cwd]), @@ -2210,10 +2218,11 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { target: RepoGitTarget, options?: { replaceFallback?: boolean }, ): Promise { + const paths = target.paths; const ignore = getPrunedGitMetadataPaths("common").map((path) => join(target.repoGitRoot, path), ); - const matchesRepoGitRoot = createRealpathAwarePathMatcher(target.repoGitRoot); + const matchesRepoGitRoot = paths.matches; const canary = this.deps.createWatcherLivenessCanary(target.repoGitRoot); let openedSubscription: FileObserverSubscription | null = null; let watcherErrored = false; @@ -2228,7 +2237,9 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { const subscription = await this.subscribeWithDeadline( target.repoGitRoot, (error, events) => { - const liveEvents = canary.filterEvents(events); + const liveEvents = canary.filterEvents( + events.map((event) => ({ ...event, path: paths.toWatchPath(event.path) })), + ); if (error) { if (watcherErrored) { return; @@ -2254,7 +2265,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { const relevantEvents = liveEvents.filter( (event) => !matchesRepoGitRoot(event.path) && - ignore.every((ignoredPath) => !isRealpathInsideRoot(ignoredPath, event.path)), + ignore.every((ignoredPath) => !isPathInsideRoot(ignoredPath, event.path)), ); if (relevantEvents.length > 0) { const immediateEvents = target.fetchInFlight @@ -2367,7 +2378,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { events: FileChange[], ): Map | null { const refreshes = new Map(); - const matchesRepoGitRoot = createRealpathAwarePathMatcher(target.repoGitRoot); + const matchesRepoGitRoot = target.paths.matches; for (const event of events) { if (!this.routeRepoMetadataEvent(target, event, matchesRepoGitRoot, refreshes)) return null; @@ -2382,10 +2393,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { ): void { const workspaceKeys = new Set(); for (const event of events) { - const commonRelativePath = getRealpathAwareRelativePath( - target.repoGitRoot, - event.path, - )?.replaceAll("\\", "/"); + const commonRelativePath = target.paths.relative(event.path)?.replaceAll("\\", "/"); if (commonRelativePath === "config" || commonRelativePath === "info/exclude") { for (const workspaceKey of target.workspaceKeys) workspaceKeys.add(workspaceKey); continue; @@ -2395,8 +2403,10 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { if ( facts?.isGit && facts.absoluteGitDir && - getRealpathAwareRelativePath(facts.absoluteGitDir, event.path)?.replaceAll("\\", "/") === - "config.worktree" + this.workspaceTargets + .get(workspaceKey) + ?.gitDirPaths?.relative(event.path) + ?.replaceAll("\\", "/") === "config.worktree" ) { workspaceKeys.add(workspaceKey); } @@ -2412,7 +2422,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { } private isFetchRemoteMetadataEvent(target: RepoGitTarget, event: FileChange): boolean { - const relativePath = getRealpathAwareRelativePath(target.repoGitRoot, event.path); + const relativePath = target.paths.relative(event.path); const effect = classifyGitMetadataPath("common", relativePath ?? ""); return ( (effect.kind === "ref" && effect.namespace === "remote") || @@ -2424,12 +2434,12 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { private routeRepoMetadataEvent( target: RepoGitTarget, event: FileChange, - matchesRepoGitRoot: ReturnType, + matchesRepoGitRoot: (candidate: string) => boolean, refreshes: Map, ): boolean { if (this.routePrivateGitDirEvent(target, event, matchesRepoGitRoot, refreshes)) return true; - const commonRelativePath = getRealpathAwareRelativePath(target.repoGitRoot, event.path); + const commonRelativePath = target.paths.relative(event.path); const effect = classifyGitMetadataPath("common", commonRelativePath ?? ""); switch (effect.kind) { case "ignore": @@ -2481,7 +2491,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { private routePrivateGitDirEvent( target: RepoGitTarget, event: FileChange, - matchesRepoGitRoot: ReturnType, + matchesRepoGitRoot: (candidate: string) => boolean, refreshes: Map, ): boolean { let matched = false; @@ -2490,8 +2500,10 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { if (!facts?.isGit || !facts.absoluteGitDir || matchesRepoGitRoot(facts.absoluteGitDir)) { continue; } - const relativePath = getRealpathAwareRelativePath(facts.absoluteGitDir, event.path); - if (relativePath === null) continue; + const relativePath = this.workspaceTargets + .get(workspaceKey) + ?.gitDirPaths?.relative(event.path); + if (relativePath == null) continue; matched = true; const effect = classifyGitMetadataPath("worktree", relativePath); if (effect.kind === "owner") { @@ -2505,7 +2517,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { private routeMainCheckoutMetadata( target: RepoGitTarget, - matchesRepoGitRoot: ReturnType, + matchesRepoGitRoot: (candidate: string) => boolean, refreshBase: boolean, refreshes: Map, ): void { diff --git a/packages/server/src/server/workspace-registry-bootstrap.ts b/packages/server/src/server/workspace-registry-bootstrap.ts index cf192a44b6..817853dad9 100644 --- a/packages/server/src/server/workspace-registry-bootstrap.ts +++ b/packages/server/src/server/workspace-registry-bootstrap.ts @@ -74,7 +74,7 @@ export async function bootstrapWorkspaceRegistries(options: { continue; } try { - pinPaseoWorktreeBranchIdentityIfMissing(workspace.worktreeRoot, workspace.branch); + await pinPaseoWorktreeBranchIdentityIfMissing(workspace.worktreeRoot, workspace.branch); } catch (error) { options.logger.warn( { err: error, workspaceId: workspace.workspaceId }, diff --git a/packages/server/src/server/worktree-branch-name-generator.test.ts b/packages/server/src/server/worktree-branch-name-generator.test.ts index 8eb1625265..186dcbc0b1 100644 --- a/packages/server/src/server/worktree-branch-name-generator.test.ts +++ b/packages/server/src/server/worktree-branch-name-generator.test.ts @@ -343,8 +343,8 @@ describe("generateBranchNameFromFirstAgentContext", () => { const repoRoot = createTempDir("paseo-branch-config-"); const worktreeRoot = createTempDir("paseo-branch-worktree-"); mkdirSync(path.join(worktreeRoot, ".git")); - writePaseoWorktreeMetadata(worktreeRoot, { baseRefName: "main" }); - writePaseoWorktreeFirstAgentBranchAutoNameMetadata(worktreeRoot, { + await writePaseoWorktreeMetadata(worktreeRoot, { baseRefName: "main" }); + await writePaseoWorktreeFirstAgentBranchAutoNameMetadata(worktreeRoot, { placeholderBranchName: "dazzling-yak", }); writeConfig(repoRoot, { diff --git a/packages/server/src/server/worktree-core.posix.test.ts b/packages/server/src/server/worktree-core.posix.test.ts index 9d02d0a2ec..4ec533d0c3 100644 --- a/packages/server/src/server/worktree-core.posix.test.ts +++ b/packages/server/src/server/worktree-core.posix.test.ts @@ -854,7 +854,7 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => { second.worktree.worktreePath, "remote.paseo-pr-14.url", ); - const metadata = readPaseoWorktreeMetadata(second.worktree.worktreePath); + const metadata = await readPaseoWorktreeMetadata(second.worktree.worktreePath); const facts = await getCheckoutSnapshotFacts(second.worktree.worktreePath, { paseoHome }); expect(second.worktree.branchName).toBe("feature/gitlab-mr-1"); @@ -1113,7 +1113,7 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => { createCoreDeps({ github }), ); writeFileSync( - getPaseoWorktreeMetadataPath(second.worktree.worktreePath), + await getPaseoWorktreeMetadataPath(second.worktree.worktreePath), `${JSON.stringify({ version: 1, baseRefName: "main" }, null, 2)}\n`, "utf8", ); diff --git a/packages/server/src/utils/checkout-git.commits.test.ts b/packages/server/src/utils/checkout-git.commits.test.ts index d614e32f9b..ee29579f55 100644 --- a/packages/server/src/utils/checkout-git.commits.test.ts +++ b/packages/server/src/utils/checkout-git.commits.test.ts @@ -172,7 +172,7 @@ describe("listCheckoutCommits", () => { mkdirSync(join(worktreesRoot, "repo-hash"), { recursive: true }); git(["worktree", "add", "-b", "feature", worktreeDir], repoDir); commitFile(worktreeDir, "feature.txt", "feature\n", "Feature work"); - writePaseoWorktreeMetadata(worktreeDir, { baseRefName: "deleted-base" }); + await writePaseoWorktreeMetadata(worktreeDir, { baseRefName: "deleted-base" }); const { baseRef, commits } = await listCheckoutCommits({ cwd: worktreeDir, diff --git a/packages/server/src/utils/checkout-git.test.ts b/packages/server/src/utils/checkout-git.test.ts index 3cc5c3dace..bd52b0e49f 100644 --- a/packages/server/src/utils/checkout-git.test.ts +++ b/packages/server/src/utils/checkout-git.test.ts @@ -2859,7 +2859,7 @@ const x = 1; execFileSync("git", ["worktree", "add", workspaceDir, "contributor/old-change"], { cwd: repoDir, }); - writePaseoWorktreeMetadata(workspaceDir, { + await writePaseoWorktreeMetadata(workspaceDir, { baseRefName: "main", changeRequestLookupTarget: { headRef: "old-change", @@ -2899,7 +2899,7 @@ const x = 1; const workspaceDir = join(paseoHome, "worktrees", "repo", "renamed-by-agent"); mkdirSync(join(paseoHome, "worktrees", "repo"), { recursive: true }); execFileSync("git", ["worktree", "add", workspaceDir, "placeholder"], { cwd: repoDir }); - writePaseoWorktreeMetadata(workspaceDir, { + await writePaseoWorktreeMetadata(workspaceDir, { baseRefName: "main", changeRequestLookupTarget: { headRef: "placeholder", @@ -2936,7 +2936,7 @@ const x = 1; const workspaceDir = join(paseoHome, "worktrees", "repo", "pinned-worktree"); mkdirSync(join(paseoHome, "worktrees", "repo"), { recursive: true }); execFileSync("git", ["worktree", "add", workspaceDir, "feature/pinned"], { cwd: repoDir }); - writePaseoWorktreeMetadata(workspaceDir, { + await writePaseoWorktreeMetadata(workspaceDir, { baseRefName: "main", changeRequestLookupTarget: { headRef: "feature/pinned", @@ -2975,7 +2975,7 @@ const x = 1; execFileSync("git", ["worktree", "add", workspaceDir, "contributor/old-change-1"], { cwd: repoDir, }); - writePaseoWorktreeMetadata(workspaceDir, { + await writePaseoWorktreeMetadata(workspaceDir, { baseRefName: "main", changeRequestLookupTarget: { headRef: "old-change", @@ -2997,7 +2997,7 @@ const x = 1; execFileSync("git", ["worktree", "add", workspaceDir, "contributor/old-change"], { cwd: repoDir, }); - writePaseoWorktreeMetadata(workspaceDir, { + await writePaseoWorktreeMetadata(workspaceDir, { baseRefName: "main", changeRequestLookupTarget: { headRef: "old-change", @@ -3062,7 +3062,7 @@ const x = 1; execFileSync("git", ["worktree", "add", workspaceDir, "mixedowner/old-change"], { cwd: repoDir, }); - writePaseoWorktreeMetadata(workspaceDir, { + await writePaseoWorktreeMetadata(workspaceDir, { baseRefName: "main", changeRequestLookupTarget: { headRef: "old-change", @@ -3114,7 +3114,7 @@ const x = 1; execFileSync("git", ["worktree", "add", workspaceDir, "feature/gitlab-mr"], { cwd: repoDir, }); - writePaseoWorktreeMetadata(workspaceDir, { + await writePaseoWorktreeMetadata(workspaceDir, { baseRefName: "main", changeRequestLookupTarget: { headRef: "feature/gitlab-mr", @@ -3128,7 +3128,9 @@ const x = 1; const forge = createGitHubServiceRecordingPullRequestTargets({ requestedTargets }); await renameCurrentBranch(workspaceCwd, "feature/renamed"); - expect(readPaseoWorktreeMetadata(workspaceDir)?.changeRequestLookupTarget).toMatchObject({ + expect( + (await readPaseoWorktreeMetadata(workspaceDir))?.changeRequestLookupTarget, + ).toMatchObject({ localBranchName: "feature/renamed", }); const renamedFacts = await getCheckoutSnapshotFacts(workspaceDir, { paseoHome }); @@ -3164,7 +3166,7 @@ const x = 1; execFileSync("git", ["worktree", "add", workspaceDir, "feature/placeholder"], { cwd: repoDir, }); - writePaseoWorktreeMetadata(workspaceDir, { + await writePaseoWorktreeMetadata(workspaceDir, { baseRefName: "main", changeRequestLookupTarget: { headRef: "feature/placeholder", @@ -3174,7 +3176,7 @@ const x = 1; await renameCurrentBranch(workspaceDir, "feature/generated"); - expect(readPaseoWorktreeMetadata(workspaceDir)?.changeRequestLookupTarget).toEqual({ + expect((await readPaseoWorktreeMetadata(workspaceDir))?.changeRequestLookupTarget).toEqual({ headRef: "feature/generated", localBranchName: "feature/generated", }); @@ -3951,7 +3953,7 @@ const x = 1; cwd: worktree.worktreePath, }); - const metadataPath = getPaseoWorktreeMetadataPath(worktree.worktreePath); + const metadataPath = await getPaseoWorktreeMetadataPath(worktree.worktreePath); rmSync(metadataPath, { force: true }); const baseDiff = await getCheckoutDiff(worktree.worktreePath, { mode: "base" }, { paseoHome }); @@ -3970,7 +3972,7 @@ const x = 1; paseoHome, }); - const metadataPath = getPaseoWorktreeMetadataPath(worktree.worktreePath); + const metadataPath = await getPaseoWorktreeMetadataPath(worktree.worktreePath); rmSync(metadataPath, { force: true }); const status = await getCheckoutStatus(worktree.worktreePath, { paseoHome }); diff --git a/packages/server/src/utils/checkout-git.ts b/packages/server/src/utils/checkout-git.ts index a39b6445e2..eed39f63e5 100644 --- a/packages/server/src/utils/checkout-git.ts +++ b/packages/server/src/utils/checkout-git.ts @@ -1,7 +1,15 @@ import { MAX_RELAY_WEBSOCKET_MESSAGE_BYTES } from "@getpaseo/protocol/websocket-message-limit"; import { resolve, dirname, basename } from "path"; -import { existsSync, realpathSync } from "fs"; -import { open as openFile, readFile, stat as statFile, mkdtemp, copyFile, rm } from "fs/promises"; +import { + open as openFile, + readFile, + stat as statFile, + mkdtemp, + copyFile, + realpath, + access, + rm, +} from "fs/promises"; import { tmpdir } from "node:os"; import { setImmediate } from "node:timers/promises"; import { TTLCache } from "@isaacs/ttlcache"; @@ -1104,7 +1112,7 @@ async function getMainRepoRootFromCommonDir( if (!commonDir) { throw new Error("Not in a git repository"); } - const normalized = realpathSync(commonDir); + const normalized = await realpath(commonDir); if (basename(normalized) === ".git") { return dirname(normalized); @@ -1229,7 +1237,7 @@ export async function renameCurrentBranch( const currentBranch = await getCurrentBranch(cwd); if (currentBranch) { - rebindPaseoWorktreeChangeRequestHint(worktreeRoot, previousBranch, currentBranch); + await rebindPaseoWorktreeChangeRequestHint(worktreeRoot, previousBranch, currentBranch); } return { previousBranch, currentBranch }; } @@ -1274,8 +1282,8 @@ function storedBaseRefFromMetadata(metadata: PaseoWorktreeMetadata | null): stri return metadata?.baseRef ?? metadata?.baseRefName ?? null; } -function readPaseoWorktreeBaseRef(worktreeRoot: string): string | null { - return storedBaseRefFromMetadata(readPaseoWorktreeMetadata(worktreeRoot)); +async function readPaseoWorktreeBaseRef(worktreeRoot: string): Promise { + return storedBaseRefFromMetadata(await readPaseoWorktreeMetadata(worktreeRoot)); } async function getStoredBaseRefForCwd( @@ -1549,7 +1557,12 @@ async function abortGitPullConflictState(cwd: string): Promise { const rebaseMergePath = resolve(gitDir, "rebase-merge"); const rebaseApplyPath = resolve(gitDir, "rebase-apply"); - if (existsSync(mergeHeadPath)) { + if ( + await access(mergeHeadPath).then( + () => true, + () => false, + ) + ) { try { await runGitCommand(["merge", "--abort"], { cwd, timeout: 120_000 }); } catch { @@ -1557,7 +1570,16 @@ async function abortGitPullConflictState(cwd: string): Promise { } } - if (existsSync(rebaseMergePath) || existsSync(rebaseApplyPath)) { + if ( + (await access(rebaseMergePath).then( + () => true, + () => false, + )) || + (await access(rebaseApplyPath).then( + () => true, + () => false, + )) + ) { try { await runGitCommand(["rebase", "--abort"], { cwd, timeout: 120_000 }); } catch { @@ -2078,7 +2100,7 @@ export async function getCheckoutSnapshotFacts( } const paseoWorktreeMetadata = inspected.paseoWorktree.isPaseoOwnedWorktree - ? readPaseoWorktreeMetadata(inspected.paseoWorktree.worktreeRoot) + ? await readPaseoWorktreeMetadata(inspected.paseoWorktree.worktreeRoot) : null; const storedBaseRef = storedBaseRefFromMetadata(paseoWorktreeMetadata); const resolvedBaseRef = storedBaseRef ?? (await resolveBaseRef(cwd, context)); diff --git a/packages/server/src/utils/path.ts b/packages/server/src/utils/path.ts index a0ec908fbb..45cb8b01b5 100644 --- a/packages/server/src/utils/path.ts +++ b/packages/server/src/utils/path.ts @@ -107,7 +107,7 @@ export function isRealpathInsideRoot(root: string, candidate: string): boolean { return getRealpathAwareRelativePath(root, candidate) !== null; } -function getRelativePathInsideRoot(root: string, candidate: string): string | null { +export function getRelativePathInsideRoot(root: string, candidate: string): string | null { const compareAsWindows = shouldCompareAsWindows(root, candidate); const platformPath = compareAsWindows ? nodePath.win32 : nodePath.posix; const normalizedRoot = normalizePathForComparison(root, compareAsWindows); @@ -175,7 +175,7 @@ function normalizePathForComparison(value: string, compareAsWindows: boolean): s return compareAsWindows ? normalized.toLowerCase() : normalized; } -function normalizePathPreservingCase(value: string, compareAsWindows: boolean): string { +export function normalizePathPreservingCase(value: string, compareAsWindows: boolean): string { const platformPath = compareAsWindows ? nodePath.win32 : nodePath.posix; const comparableValue = compareAsWindows ? stripWindowsNamespacePrefix(value) : value; const platformNormalized = platformPath.normalize(comparableValue); diff --git a/packages/server/src/utils/run-git-command.test.ts b/packages/server/src/utils/run-git-command.test.ts index 32844d0de8..5153b606dc 100644 --- a/packages/server/src/utils/run-git-command.test.ts +++ b/packages/server/src/utils/run-git-command.test.ts @@ -507,7 +507,6 @@ describe("runGitCommand", () => { command: "git", args: ["status", "--short"], cwd: process.cwd(), - cwdExists: true, timeout: 30_000, maxOutputBytes: 20 * 1024 * 1024, acceptExitCodes: [0, 1], @@ -520,7 +519,6 @@ describe("runGitCommand", () => { command: "git", args: ["status", "--short"], cwd: process.cwd(), - cwdExists: true, durationMs: expect.any(Number), exitCode: 0, signal: null, @@ -530,6 +528,9 @@ describe("runGitCommand", () => { }), "Git command closed", ); + for (const [record] of trace.mock.calls) { + expect(record).not.toHaveProperty("cwdExists"); + } }); it("rejects non-zero exit codes that are not accepted and frees the slot", async () => { diff --git a/packages/server/src/utils/run-git-command.ts b/packages/server/src/utils/run-git-command.ts index bdf7bc1f32..3a3cbf5b4c 100644 --- a/packages/server/src/utils/run-git-command.ts +++ b/packages/server/src/utils/run-git-command.ts @@ -1,5 +1,4 @@ import { AsyncLocalStorage } from "node:async_hooks"; -import { existsSync } from "node:fs"; import type { Logger } from "pino"; import type { ProcessEnvRecord } from "../server/paseo-env.js"; import { @@ -311,7 +310,6 @@ function executeGitCommand( command: "git", args, cwd: options.cwd, - cwdExists: existsSync(options.cwd), timeout, maxOutputBytes, acceptExitCodes, diff --git a/packages/server/src/utils/worktree-metadata.ts b/packages/server/src/utils/worktree-metadata.ts index b977f7952b..13c95567db 100644 --- a/packages/server/src/utils/worktree-metadata.ts +++ b/packages/server/src/utils/worktree-metadata.ts @@ -1,7 +1,12 @@ -import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs"; +import { mkdir, open, realpath, rename, stat, writeFile } from "node:fs/promises"; +import { randomUUID } from "node:crypto"; +import { constants } from "node:fs"; +import pLimit from "p-limit"; import { isAbsolute, join, resolve } from "path"; import { z } from "zod"; +const MAX_WORKTREE_METADATA_BYTES = 64 * 1024; + const ChangeRequestLookupTargetSchema = z.object({ headRef: z.string().min(1), headRepositoryOwner: z.string().min(1).optional(), @@ -90,75 +95,78 @@ function normalizeLegacyGitHubOwnerForBranch(owner: string): string | null { return /^[a-z0-9-]+$/.test(normalized) ? normalized : null; } -export function rebindPaseoWorktreeChangeRequestHint( +export async function rebindPaseoWorktreeChangeRequestHint( worktreeRoot: string, previousBranch: string, currentBranch: string, -): boolean { - const metadata = readPaseoWorktreeMetadata(worktreeRoot); - const target = getPaseoWorktreeChangeRequestHintForBranch(metadata, previousBranch); - if (!metadata || !target) { - return false; - } +): Promise { + return mutateMetadata(worktreeRoot, async (root) => { + const metadata = await readMetadataFile(root); + const target = getPaseoWorktreeChangeRequestHintForBranch(metadata, previousBranch); + if (!metadata || !target) { + return false; + } - writePaseoWorktreeMetadataFile(worktreeRoot, { - ...metadata, - changeRequestLookupTarget: { - ...target, - ...(target.headRef === previousBranch && - !target.headRepositoryOwner && - target.changeRequestNumber === undefined - ? { headRef: currentBranch } - : {}), - localBranchName: currentBranch, - }, + await writePaseoWorktreeMetadataFile(root, { + ...metadata, + changeRequestLookupTarget: { + ...target, + ...(target.headRef === previousBranch && + !target.headRepositoryOwner && + target.changeRequestNumber === undefined + ? { headRef: currentBranch } + : {}), + localBranchName: currentBranch, + }, + }); + return true; }); - return true; } -export function pinPaseoWorktreeBranchIdentityIfMissing( +export async function pinPaseoWorktreeBranchIdentityIfMissing( worktreeRoot: string, branch: string, -): boolean { - const metadata = readPaseoWorktreeMetadata(worktreeRoot); - if (!metadata || metadata.changeRequestLookupTarget) { - return false; - } - const target = createPaseoWorktreeChangeRequestHint({ - headRef: branch, - localBranchName: branch, +): Promise { + return mutateMetadata(worktreeRoot, async (root) => { + const metadata = await readMetadataFile(root); + if (!metadata || metadata.changeRequestLookupTarget) { + return false; + } + const target = createPaseoWorktreeChangeRequestHint({ + headRef: branch, + localBranchName: branch, + }); + await writePaseoWorktreeMetadataFile(root, { + ...metadata, + changeRequestLookupTarget: target, + }); + return true; }); - writePaseoWorktreeMetadataFile(worktreeRoot, { - ...metadata, - changeRequestLookupTarget: target, - }); - return true; } -function getGitDirForWorktreeRoot(worktreeRoot: string): string { +async function getGitDirForWorktreeRoot(worktreeRoot: string): Promise { const gitPath = join(worktreeRoot, ".git"); - if (!existsSync(gitPath)) { - throw new Error(`Not a git repository: ${worktreeRoot}`); - } - - // In a worktree checkout, `.git` is a file containing `gitdir: `. - // In a normal checkout, `.git` is a directory. + let info; try { - const gitFileContent = readFileSync(gitPath, "utf8"); - const match = gitFileContent.match(/gitdir:\s*(.+)/); - if (match?.[1]) { - const raw = match[1].trim(); - return isAbsolute(raw) ? raw : resolve(worktreeRoot, raw); - } - } catch { - // If `.git` is a directory, readFileSync will throw; fall through. + info = await stat(gitPath); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") + throw new Error(`Not a git repository: ${worktreeRoot}`, { cause: error }); + throw error; + } + if (info.isDirectory()) return gitPath; + const gitFileContent = await readBoundedFile(gitPath); + const match = gitFileContent.match(/gitdir:\s*(.+)/); + if (match?.[1]) { + const raw = match[1].trim(); + return isAbsolute(raw) ? raw : resolve(worktreeRoot, raw); } return gitPath; } -export function getPaseoWorktreeMetadataPath(worktreeRoot: string): string { - const gitDir = getGitDirForWorktreeRoot(worktreeRoot); +export async function getPaseoWorktreeMetadataPath(worktreeRoot: string): Promise { + const gitDir = await getGitDirForWorktreeRoot(worktreeRoot); return join(gitDir, "paseo", "worktree.json"); } @@ -213,120 +221,166 @@ function assertValidBaseRef(value: string): void { } } -export function writePaseoWorktreeMetadata( +export async function writePaseoWorktreeMetadata( worktreeRoot: string, options: { baseRefName: string; baseRef?: string; changeRequestLookupTarget?: PaseoWorktreeChangeRequestHint; }, -): void { - const baseRefName = normalizeBaseRefName(options.baseRefName); - assertValidBaseRef(baseRefName); - const baseRef = options.baseRef?.trim(); - if (baseRef) { - assertValidBaseRef(baseRef); - } +): Promise { + return mutateMetadata(worktreeRoot, async (root) => { + const baseRefName = normalizeBaseRefName(options.baseRefName); + assertValidBaseRef(baseRefName); + const baseRef = options.baseRef?.trim(); + if (baseRef) { + assertValidBaseRef(baseRef); + } - const metadata: PaseoWorktreeMetadata = { - version: 1, - baseRefName, - ...(baseRef ? { baseRef } : {}), - ...(options.changeRequestLookupTarget - ? { changeRequestLookupTarget: options.changeRequestLookupTarget } - : {}), - }; - writePaseoWorktreeMetadataFile(worktreeRoot, metadata); -} - -export function writePaseoWorktreeRuntimeMetadata( - worktreeRoot: string, - options: { worktreePort: number }, -): void { - if (!Number.isInteger(options.worktreePort) || options.worktreePort <= 0) { - throw new Error(`Invalid worktree runtime port: ${options.worktreePort}`); - } - - const current = readPaseoWorktreeMetadata(worktreeRoot); - if (!current) { - throw new Error("Cannot persist worktree runtime metadata: missing base metadata"); - } - - const next: PaseoWorktreeMetadata = { - ...current, - version: 2, - runtime: { - worktreePort: options.worktreePort, - }, - }; - writePaseoWorktreeMetadataFile(worktreeRoot, next); -} - -export function writePaseoWorktreeFirstAgentBranchAutoNameMetadata( - worktreeRoot: string, - options: { placeholderBranchName: string }, -): void { - const placeholderBranchName = options.placeholderBranchName.trim(); - if (!placeholderBranchName) { - throw new Error("Placeholder branch name is required"); - } - - const current = readPaseoWorktreeMetadata(worktreeRoot); - if (!current) { - throw new Error("Cannot persist first-agent branch auto-name metadata: missing base metadata"); - } - - writePaseoWorktreeMetadataFile(worktreeRoot, { - ...current, - version: 2, - firstAgentBranchAutoName: { - status: "pending", - placeholderBranchName, - }, + const metadata: PaseoWorktreeMetadata = { + version: 1, + baseRefName, + ...(baseRef ? { baseRef } : {}), + ...(options.changeRequestLookupTarget + ? { changeRequestLookupTarget: options.changeRequestLookupTarget } + : {}), + }; + await writePaseoWorktreeMetadataFile(root, metadata); }); } -export function markPaseoWorktreeFirstAgentBranchAutoNameAttempted( +export async function writePaseoWorktreeRuntimeMetadata( + worktreeRoot: string, + options: { worktreePort: number }, +): Promise { + return mutateMetadata(worktreeRoot, async (root) => { + if (!Number.isInteger(options.worktreePort) || options.worktreePort <= 0) { + throw new Error(`Invalid worktree runtime port: ${options.worktreePort}`); + } + + const current = await readMetadataFile(root); + if (!current) { + throw new Error("Cannot persist worktree runtime metadata: missing base metadata"); + } + + const next: PaseoWorktreeMetadata = { + ...current, + version: 2, + runtime: { + worktreePort: options.worktreePort, + }, + }; + await writePaseoWorktreeMetadataFile(root, next); + }); +} + +export async function writePaseoWorktreeFirstAgentBranchAutoNameMetadata( + worktreeRoot: string, + options: { placeholderBranchName: string }, +): Promise { + return mutateMetadata(worktreeRoot, async (root) => { + const placeholderBranchName = options.placeholderBranchName.trim(); + if (!placeholderBranchName) { + throw new Error("Placeholder branch name is required"); + } + + const current = await readMetadataFile(root); + if (!current) { + throw new Error( + "Cannot persist first-agent branch auto-name metadata: missing base metadata", + ); + } + + await writePaseoWorktreeMetadataFile(root, { + ...current, + version: 2, + firstAgentBranchAutoName: { + status: "pending", + placeholderBranchName, + }, + }); + }); +} + +export async function markPaseoWorktreeFirstAgentBranchAutoNameAttempted( worktreeRoot: string, options: { attemptedAt?: string } = {}, -): PaseoWorktreeMetadata | null { - const current = readPaseoWorktreeMetadata(worktreeRoot); - if (!current || current.version !== 2 || current.firstAgentBranchAutoName?.status !== "pending") { - return current; - } +): Promise { + return mutateMetadata(worktreeRoot, async (root) => { + const current = await readMetadataFile(root); + if ( + !current || + current.version !== 2 || + current.firstAgentBranchAutoName?.status !== "pending" + ) { + return current; + } - const next: PaseoWorktreeMetadata = { - ...current, - firstAgentBranchAutoName: { - status: "attempted", - placeholderBranchName: current.firstAgentBranchAutoName.placeholderBranchName, - attemptedAt: options.attemptedAt ?? new Date().toISOString(), - }, - }; - writePaseoWorktreeMetadataFile(worktreeRoot, next); - return next; + const next: PaseoWorktreeMetadata = { + ...current, + firstAgentBranchAutoName: { + status: "attempted", + placeholderBranchName: current.firstAgentBranchAutoName.placeholderBranchName, + attemptedAt: options.attemptedAt ?? new Date().toISOString(), + }, + }; + await writePaseoWorktreeMetadataFile(root, next); + return next; + }); } -export function readPaseoWorktreeMetadata(worktreeRoot: string): PaseoWorktreeMetadata | null { - const metadataPath = getPaseoWorktreeMetadataPath(worktreeRoot); - if (!existsSync(metadataPath)) { - return null; - } - const parsed = JSON.parse(readFileSync(metadataPath, "utf8")); - return PaseoWorktreeMetadataSchema.parse(parsed); +export async function readPaseoWorktreeMetadata( + worktreeRoot: string, +): Promise { + const key = await resolveMetadataIdentity(worktreeRoot); + await metadataMutations.get(key)?.catch(() => {}); + return metadataIo(() => readMetadataFile(key)); } -export function requirePaseoWorktreeBaseRefName(worktreeRoot: string): string { - const metadataPath = getPaseoWorktreeMetadataPath(worktreeRoot); - const metadata = readPaseoWorktreeMetadata(worktreeRoot); +async function readMetadataFile(worktreeRoot: string): Promise { + const metadataPath = await getPaseoWorktreeMetadataPath(worktreeRoot); + try { + return PaseoWorktreeMetadataSchema.parse(JSON.parse(await readBoundedFile(metadataPath))); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; + throw error; + } +} + +// O_NONBLOCK lets us reject FIFOs by kind without hanging in open(). A fixed read also +// caps a regular file that grows between stat and read; readFile's whole-file loop does not. +async function readBoundedFile(path: string): Promise { + const file = await open(path, constants.O_RDONLY | constants.O_NONBLOCK); + try { + const info = await file.stat(); + const limit = MAX_WORKTREE_METADATA_BYTES; + if (!info.isFile() || info.size > limit) + throw new Error(`Invalid Paseo worktree metadata file: ${path}`); + const buffer = Buffer.alloc(limit + 1); + let length = 0; + while (length < buffer.length) { + const { bytesRead } = await file.read(buffer, length, buffer.length - length); + if (bytesRead === 0) break; + length += bytesRead; + } + if (length > limit) throw new Error(`Invalid Paseo worktree metadata file: ${path}`); + return buffer.toString("utf8", 0, length); + } finally { + await file.close(); + } +} + +export async function requirePaseoWorktreeBaseRefName(worktreeRoot: string): Promise { + const metadataPath = await getPaseoWorktreeMetadataPath(worktreeRoot); + const metadata = await readPaseoWorktreeMetadata(worktreeRoot); if (!metadata) { throw new Error(`Missing Paseo worktree base metadata: ${metadataPath}`); } return metadata.baseRefName; } -export function readPaseoWorktreeRuntimePort(worktreeRoot: string): number | null { - const metadata = readPaseoWorktreeMetadata(worktreeRoot); +export async function readPaseoWorktreeRuntimePort(worktreeRoot: string): Promise { + const metadata = await readPaseoWorktreeMetadata(worktreeRoot); if (!metadata) { return null; } @@ -336,13 +390,61 @@ export function readPaseoWorktreeRuntimePort(worktreeRoot: string): number | nul return null; } -function writePaseoWorktreeMetadataFile( +async function writePaseoWorktreeMetadataFile( worktreeRoot: string, metadata: PaseoWorktreeMetadata, -): void { - const metadataPath = getPaseoWorktreeMetadataPath(worktreeRoot); - mkdirSync(join(getGitDirForWorktreeRoot(worktreeRoot), "paseo"), { recursive: true }); - const tempPath = `${metadataPath}.${process.pid}.${Date.now()}.tmp`; - writeFileSync(tempPath, `${JSON.stringify(metadata, null, 2)}\n`, "utf8"); - renameSync(tempPath, metadataPath); +): Promise { + const metadataPath = await getPaseoWorktreeMetadataPath(worktreeRoot); + const contents = `${JSON.stringify(metadata, null, 2)}\n`; + if (Buffer.byteLength(contents) > MAX_WORKTREE_METADATA_BYTES) { + throw new Error(`Invalid Paseo worktree metadata file: ${metadataPath}`); + } + // Never recreate an archived Git directory while a queued mutation is pending. + try { + await mkdir(join(await getGitDirForWorktreeRoot(worktreeRoot), "paseo")); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + } + const tempPath = `${metadataPath}.${randomUUID()}.tmp`; + await writeFile(tempPath, contents, "utf8"); + await rename(tempPath, metadataPath); +} + +const metadataIo = pLimit(2); +const metadataMutations = new Map>(); + +// Only share in-flight identity resolution: a replaced symlink must not retain an old owner. +const metadataIdentities = new Map>(); + +function resolveMetadataIdentity(worktreeRoot: string): Promise { + const path = resolve(worktreeRoot); + const existing = metadataIdentities.get(path); + if (existing) return existing; + const identity = metadataIo(async () => { + try { + return await realpath(path); + } catch { + return path; + } + }).finally(() => { + if (metadataIdentities.get(path) === identity) metadataIdentities.delete(path); + }); + metadataIdentities.set(path, identity); + return identity; +} + +async function mutateMetadata( + worktreeRoot: string, + mutation: (root: string) => Promise, +): Promise { + const key = await resolveMetadataIdentity(worktreeRoot); + const previous = metadataMutations.get(key) ?? Promise.resolve(); + const pending = previous.catch(() => {}).then(() => metadataIo(() => mutation(key))); + metadataMutations.set(key, pending); + void pending + .finally(() => { + if (metadataMutations.get(key) === pending) metadataMutations.delete(key); + }) + .catch(() => {}); + return pending; } diff --git a/packages/server/src/utils/worktree.posix.test.ts b/packages/server/src/utils/worktree.posix.test.ts index 7819e2275c..aede7cf8e3 100644 --- a/packages/server/src/utils/worktree.posix.test.ts +++ b/packages/server/src/utils/worktree.posix.test.ts @@ -21,7 +21,13 @@ import { type WorktreeConfig, } from "./worktree"; import type { PaseoConfig } from "@getpaseo/protocol/paseo-config-schema"; -import { getPaseoWorktreeMetadataPath, readPaseoWorktreeMetadata } from "./worktree-metadata.js"; +import { + getPaseoWorktreeMetadataPath, + readPaseoWorktreeMetadata, + writePaseoWorktreeMetadata, + writePaseoWorktreeRuntimeMetadata, + writePaseoWorktreeFirstAgentBranchAutoNameMetadata, +} from "./worktree-metadata.js"; import { getCheckoutDiff, getCheckoutStatus, @@ -125,7 +131,7 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { expect(result.worktreePath).toBe(join(paseoHome, "worktrees", projectHash, "hello-world")); expect(existsSync(result.worktreePath)).toBe(true); expect(existsSync(join(result.worktreePath, "file.txt"))).toBe(true); - const metadataPath = getPaseoWorktreeMetadataPath(result.worktreePath); + const metadataPath = await getPaseoWorktreeMetadataPath(result.worktreePath); expect(existsSync(metadataPath)).toBe(true); const metadata = JSON.parse(readFileSync(metadataPath, "utf8")); expect(metadata).toMatchObject({ @@ -256,7 +262,7 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { cwd: result.worktreePath, }); - const metadataPath = getPaseoWorktreeMetadataPath(result.worktreePath); + const metadataPath = await getPaseoWorktreeMetadataPath(result.worktreePath); const metadata = JSON.parse(readFileSync(metadataPath, "utf8")); expect(metadata).toMatchObject({ version: 1, @@ -319,7 +325,7 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { // baseRefName must be the repo's default branch, not the checked-out branch // itself — otherwise the diff panel compares the branch against itself and // always shows no changes. - const metadataPath = getPaseoWorktreeMetadataPath(result.worktreePath); + const metadataPath = await getPaseoWorktreeMetadataPath(result.worktreePath); const metadata = JSON.parse(readFileSync(metadataPath, "utf8")); expect(metadata).toMatchObject({ version: 1, @@ -370,7 +376,7 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { }); expect(existsSync(result.worktreePath)).toBe(true); - const metadataPath = getPaseoWorktreeMetadataPath(result.worktreePath); + const metadataPath = await getPaseoWorktreeMetadataPath(result.worktreePath); const metadata = JSON.parse(readFileSync(metadataPath, "utf8")); expect(metadata).toMatchObject({ version: 1, baseRefName: "develop" }); }); @@ -406,7 +412,9 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { expect(result.branchName).toBe("main-1"); expect(existsSync(result.worktreePath)).toBe(true); - expect(readPaseoWorktreeMetadata(result.worktreePath)?.changeRequestLookupTarget).toEqual({ + expect( + (await readPaseoWorktreeMetadata(result.worktreePath))?.changeRequestLookupTarget, + ).toEqual({ headRef: "main-1", localBranchName: "main-1", }); @@ -459,7 +467,7 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { .trim(); expect(currentBranch).toBe("user/feature"); - const metadataPath = getPaseoWorktreeMetadataPath(result.worktreePath); + const metadataPath = await getPaseoWorktreeMetadataPath(result.worktreePath); const metadata = JSON.parse(readFileSync(metadataPath, "utf8")); expect(metadata).toMatchObject({ baseRefName: "main" }); }); @@ -566,7 +574,9 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { "from-origin\n", ); expect( - JSON.parse(readFileSync(getPaseoWorktreeMetadataPath(originResult.worktreePath), "utf8")), + JSON.parse( + readFileSync(await getPaseoWorktreeMetadataPath(originResult.worktreePath), "utf8"), + ), ).toMatchObject({ baseRefName: "main" }); }); @@ -607,7 +617,7 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { // to the commit the worktree was cut from: "main" resolves local-first, which here is // a different commit than the fork's upstream. expect( - JSON.parse(readFileSync(getPaseoWorktreeMetadataPath(result.worktreePath), "utf8")), + JSON.parse(readFileSync(await getPaseoWorktreeMetadataPath(result.worktreePath), "utf8")), ).toMatchObject({ baseRefName: "main", baseRef: "refs/remotes/upstream/main" }); // An untouched child must report no work of its own. Comparing against the wrong base @@ -694,7 +704,7 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { }); expect( - JSON.parse(readFileSync(getPaseoWorktreeMetadataPath(result.worktreePath), "utf8")), + JSON.parse(readFileSync(await getPaseoWorktreeMetadataPath(result.worktreePath), "utf8")), ).toMatchObject({ baseRefName: "release+hotfix", baseRef: "refs/remotes/upstream/release+hotfix", @@ -1617,3 +1627,104 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { }); }); }); + +describe.skipIf(isPlatform("win32"))("async worktree metadata", () => { + it("serializes metadata mutations per worktree while another worktree progresses", async () => { + const root = mkdtempSync(join(tmpdir(), "worktree-metadata-order-")); + const first = join(root, "first"); + const second = join(root, "second"); + mkdirSync(join(first, ".git"), { recursive: true }); + mkdirSync(join(second, ".git"), { recursive: true }); + try { + await writePaseoWorktreeMetadata(first, { baseRefName: "main" }); + await writePaseoWorktreeMetadata(second, { baseRefName: "release" }); + const order: string[] = []; + const runtime = writePaseoWorktreeRuntimeMetadata(first, { worktreePort: 4101 }).then(() => + order.push("first-runtime"), + ); + const unrelated = writePaseoWorktreeRuntimeMetadata(second, { worktreePort: 4102 }).then(() => + order.push("second-runtime"), + ); + const naming = writePaseoWorktreeFirstAgentBranchAutoNameMetadata(first, { + placeholderBranchName: "topic", + }).then(() => order.push("first-naming")); + // A read issued while writes are pending observes their completed snapshot. + const snapshot = readPaseoWorktreeMetadata(first); + await Promise.all([runtime, unrelated, naming]); + expect(order.indexOf("first-runtime")).toBeLessThan(order.indexOf("first-naming")); + expect(await snapshot).toMatchObject({ + baseRefName: "main", + runtime: { worktreePort: 4101 }, + firstAgentBranchAutoName: { status: "pending", placeholderBranchName: "topic" }, + }); + expect(await readPaseoWorktreeMetadata(second)).toMatchObject({ + baseRefName: "release", + runtime: { worktreePort: 4102 }, + }); + const alias = join(root, "first-alias"); + symlinkSync(first, alias, "dir"); + await Promise.all([ + writePaseoWorktreeRuntimeMetadata(first, { worktreePort: 4103 }), + writePaseoWorktreeFirstAgentBranchAutoNameMetadata(alias, { + placeholderBranchName: "renamed", + }), + ]); + expect(await readPaseoWorktreeMetadata(first)).toMatchObject({ + runtime: { worktreePort: 4103 }, + firstAgentBranchAutoName: { placeholderBranchName: "renamed" }, + }); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it("a queued metadata mutation cannot recreate an archived Git directory", async () => { + const root = mkdtempSync(join(tmpdir(), "worktree-metadata-archive-")); + mkdirSync(join(root, ".git")); + try { + await writePaseoWorktreeMetadata(root, { baseRefName: "main" }); + const pending = writePaseoWorktreeRuntimeMetadata(root, { worktreePort: 4101 }); + // The mutation is queued in a microtask, so archive wins this ordering. + rmSync(join(root, ".git"), { recursive: true }); + await expect(pending).rejects.toThrow("Not a git repository"); + expect(existsSync(join(root, ".git"))).toBe(false); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it("recognizes a removed worktree under a symlinked ownership root", async () => { + const root = mkdtempSync(join(tmpdir(), "worktree-ownership-alias-")); + const actual = join(root, "actual"); + const alias = join(root, "worktrees"); + mkdirSync(actual); + symlinkSync(actual, alias, "dir"); + try { + const cwd = join(alias, "project", "removed"); + expect( + await isPaseoOwnedWorktreeCwd(cwd, { worktreesRoot: alias, knownGitCommonDir: null }), + ).toMatchObject({ allowed: true, worktreePath: cwd }); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it("rejects oversized metadata and named pipes without reading them whole", async () => { + const root = mkdtempSync(join(tmpdir(), "worktree-metadata-admission-")); + mkdirSync(join(root, ".git", "paseo"), { recursive: true }); + try { + const path = await getPaseoWorktreeMetadataPath(root); + writeFileSync(path, JSON.stringify({ version: 1, baseRefName: "x".repeat(64 * 1024) })); + await expect(readPaseoWorktreeMetadata(root)).rejects.toThrow( + "Invalid Paseo worktree metadata file", + ); + rmSync(path); + execFileSync("mkfifo", [path]); + await expect(readPaseoWorktreeMetadata(root)).rejects.toThrow( + "Invalid Paseo worktree metadata file", + ); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/server/src/utils/worktree.test.ts b/packages/server/src/utils/worktree.test.ts index 4d6f50bba6..605e2b8c20 100644 --- a/packages/server/src/utils/worktree.test.ts +++ b/packages/server/src/utils/worktree.test.ts @@ -5,6 +5,7 @@ import { deletePaseoWorktree, isPaseoOwnedWorktreeCwd, mapWorkspaceCwdToWorktree, + runWorktreeTeardownCommands, slugify, type CreateWorktreeOptions, type WorktreeConfig, @@ -171,7 +172,15 @@ describe("paseo worktree manager", () => { expect(existsSync(created.worktreePath)).toBe(true); const ownership = await isPaseoOwnedWorktreeCwd(created.worktreePath, { paseoHome }); - expect(ownership.allowed).toBe(true); + expect(ownership).toMatchObject({ allowed: true, worktreePath: created.worktreePath }); + // Windows may report the same root through native 8.3 and JS long spellings. + const nativeWorktreePath = realpathSync.native(created.worktreePath); + await expect( + runWorktreeTeardownCommands({ + worktreePath: created.worktreePath, + teardownCwd: nativeWorktreePath, + }), + ).resolves.toEqual([]); await expect( isPaseoOwnedWorktreeCwd(join(created.worktreePath, "packages", "app"), { paseoHome }), ).resolves.toMatchObject({ diff --git a/packages/server/src/utils/worktree.ts b/packages/server/src/utils/worktree.ts index dd6dfe7a44..3ddc71b472 100644 --- a/packages/server/src/utils/worktree.ts +++ b/packages/server/src/utils/worktree.ts @@ -1,11 +1,12 @@ import { execFile } from "child_process"; import { promisify } from "util"; -import { constants as fsConstants, existsSync, mkdirSync, realpathSync, statSync } from "fs"; -import { copyFile, rm, stat } from "fs/promises"; +import { constants as fsConstants, realpath } from "fs"; +import { copyFile, mkdir, rm, stat } from "fs/promises"; import { join, basename, dirname, isAbsolute, resolve, sep } from "path"; import net from "node:net"; import { createHash } from "node:crypto"; import stripAnsi from "strip-ansi"; +import pLimit from "p-limit"; import { buildStringCommandShellInvocation, createStringCommandShellEnv, @@ -37,7 +38,12 @@ import { spawnProcess } from "./spawn.js"; import { resolvePaseoHome } from "../server/paseo-home.js"; import { createExternalProcessEnv } from "../server/paseo-env.js"; import { parseGitRevParsePath, resolveGitRevParsePath } from "./git-rev-parse-path.js"; -import { expandTilde, getRealpathAwareRelativePath, isPathInsideRoot } from "./path.js"; +import { + expandTilde, + getRealpathAwareRelativePath, + getRelativePathInsideRoot, + isPathInsideRoot, +} from "./path.js"; import { terminateWithTreeKill } from "./tree-kill.js"; export { slugify, validateBranchSlug } from "@getpaseo/protocol/branch-slug"; @@ -595,7 +601,7 @@ async function assertPortAvailable(port: number): Promise { async function inferRepoRootPathFromWorktreePath(worktreePath: string): Promise { try { const commonDir = await getGitCommonDir(worktreePath); - const normalizedCommonDir = normalizePathForOwnership(commonDir); + const normalizedCommonDir = await normalizePathForOwnership(commonDir); // Normal repo/worktree: common dir is /.git if (basename(normalizedCommonDir) === ".git") { return dirname(normalizedCommonDir); @@ -611,12 +617,12 @@ async function inferRepoRootPathFromWorktreePath(worktreePath: string): Promise< }); const topLevel = parseGitRevParsePath(stdout); if (topLevel) { - return normalizePathForOwnership(topLevel); + return await normalizePathForOwnership(topLevel); } } catch { // ignore } - return normalizePathForOwnership(worktreePath); + return await normalizePathForOwnership(worktreePath); } } @@ -699,12 +705,12 @@ export async function resolveWorktreeRuntimeEnv(options: { const branchName = options.branchName ?? (await resolveBranchNameForWorktreePath(options.worktreePath)); - let worktreePort = readPaseoWorktreeRuntimePort(options.worktreePath); + let worktreePort = await readPaseoWorktreeRuntimePort(options.worktreePath); if (worktreePort === null) { worktreePort = await getAvailablePort(); - const metadata = readPaseoWorktreeMetadata(options.worktreePath); + const metadata = await readPaseoWorktreeMetadata(options.worktreePath); if (metadata) { - writePaseoWorktreeRuntimeMetadata(options.worktreePath, { worktreePort }); + await writePaseoWorktreeRuntimeMetadata(options.worktreePath, { worktreePort }); } } else { await assertPortAvailable(worktreePort); @@ -730,7 +736,7 @@ export async function runWorktreeTeardownCommands(options: { repoRootPath?: string; }): Promise { const teardownCwd = options.teardownCwd ?? options.worktreePath; - if (getRealpathAwareRelativePath(options.worktreePath, teardownCwd) === null) { + if ((await getOwnershipRelativePath(options.worktreePath, teardownCwd)) === null) { throw new Error(`Worktree teardown cwd is outside the worktree: ${teardownCwd}`); } const teardownCommands = await getWorktreeTeardownCommands(teardownCwd); @@ -742,7 +748,7 @@ export async function runWorktreeTeardownCommands(options: { options.repoRootPath ?? (await inferRepoRootPathFromWorktreePath(options.worktreePath)); const branchName = options.branchName ?? (await resolveBranchNameForWorktreePath(options.worktreePath)); - const worktreePort = readPaseoWorktreeRuntimePort(options.worktreePath); + const worktreePort = await readPaseoWorktreeRuntimePort(options.worktreePath); const teardownEnv: NodeJS.ProcessEnv = createStringCommandShellEnv( createExternalProcessEnv(process.env, { @@ -819,12 +825,12 @@ function deriveShortAlphanumericHash(value: string): string { export async function deriveWorktreeProjectHash(cwd: string): Promise { try { const commonDir = await getGitCommonDir(cwd); - const normalizedCommonDir = normalizePathForOwnership(commonDir); + const normalizedCommonDir = await normalizePathForOwnership(commonDir); const repoRoot = basename(normalizedCommonDir) === ".git" ? dirname(normalizedCommonDir) : normalizedCommonDir; return deriveShortAlphanumericHash(repoRoot); } catch { - return deriveShortAlphanumericHash(normalizePathForOwnership(cwd)); + return deriveShortAlphanumericHash(await normalizePathForOwnership(cwd)); } } @@ -892,16 +898,46 @@ export function mapWorkspaceRelativeCwdToWorktree(input: { return mappedCwd; } -function normalizePathForOwnership(input: string): string { +// Keep the former realpathSync spelling on Windows: promises.realpath uses the +// native resolver and can return an 8.3 alias instead of the long path. +const resolveOwnershipPath = promisify(realpath); +const resolveNativeOwnershipPath = promisify(realpath.native); +const ownershipIdentityIo = pLimit(2); + +async function normalizePathForOwnership(input: string): Promise { try { - return realpathSync(input); + return await ownershipIdentityIo(() => resolveOwnershipPath(input)); } catch { return resolve(input); } } -function resolveRepoRootFromGitCommonDir(commonDir: string): string { - const normalizedCommonDir = normalizePathForOwnership(commonDir); +async function ownershipPathVariants(input: string): Promise { + const variants = new Set([input, await normalizePathForOwnership(input)]); + try { + variants.add(await ownershipIdentityIo(() => resolveNativeOwnershipPath(input))); + } catch { + // Missing descendants still match a lexical or established root spelling. + } + return [...variants]; +} + +// Keep lexical variants for missing paths: archive must still recognize a removed +// worktree below a symlinked worktrees root, whose full realpath no longer exists. +async function getOwnershipRelativePath(root: string, candidate: string): Promise { + const roots = await ownershipPathVariants(root); + const candidates = await ownershipPathVariants(candidate); + for (const rootPath of roots) { + for (const candidatePath of candidates) { + const relative = getRelativePathInsideRoot(rootPath, candidatePath); + if (relative !== null) return relative; + } + } + return null; +} + +async function resolveRepoRootFromGitCommonDir(commonDir: string): Promise { + const normalizedCommonDir = await normalizePathForOwnership(commonDir); return basename(normalizedCommonDir) === ".git" ? dirname(normalizedCommonDir) : normalizedCommonDir; @@ -911,25 +947,25 @@ export async function isPaseoOwnedWorktreeCwd( cwd: string, options?: PaseoWorktreeOwnershipOptions, ): Promise { - const resolvedCwd = normalizePathForOwnership(cwd); + const resolvedCwd = await normalizePathForOwnership(cwd); // repoRoot is best-effort: git may be unreachable from the worktree (e.g. a // previous archive attempt removed the admin dir before the working tree // could be fully cleaned up). We still want to allow archiving in that case. let repoRoot: string | undefined; if (options?.knownGitCommonDir) { - repoRoot = resolveRepoRootFromGitCommonDir(options.knownGitCommonDir); + repoRoot = await resolveRepoRootFromGitCommonDir(options.knownGitCommonDir); } else if (options?.knownGitCommonDir === undefined) { try { const gitCommonDir = await getGitCommonDir(cwd); - repoRoot = resolveRepoRootFromGitCommonDir(gitCommonDir); + repoRoot = await resolveRepoRootFromGitCommonDir(gitCommonDir); } catch { // ignore } } const worktreesBaseRoot = resolvePaseoWorktreesBaseRoot(options); - const relativePath = getRealpathAwareRelativePath(worktreesBaseRoot, resolvedCwd); + const relativePath = await getOwnershipRelativePath(worktreesBaseRoot, resolvedCwd); // Ownership is defined by the path living under //[/...]. // The / prefix is Paseo-private — nothing else writes there — so the @@ -1000,9 +1036,9 @@ function parseWorktreeList(output: string): ParsedPaseoWorktreeInfo[] { return entries; } -function resolveWorktreeCreatedAtIso(worktreePath: string): string { +async function resolveWorktreeCreatedAtIso(worktreePath: string): Promise { try { - const stats = statSync(worktreePath); + const stats = await stat(worktreePath); const birthtimeMs = stats.birthtimeMs; const createdAtMs = Number.isFinite(birthtimeMs) && birthtimeMs > 0 ? birthtimeMs : stats.ctimeMs; @@ -1027,12 +1063,15 @@ export async function listPaseoWorktrees({ envOverlay: READ_ONLY_GIT_ENV, }); - return parseWorktreeList(stdout) - .map((entry) => Object.assign({}, entry, { path: normalizePathForOwnership(entry.path) })) - .filter((entry) => getRealpathAwareRelativePath(projectWorktreesRoot, entry.path) !== null) - .map((entry) => - Object.assign({}, entry, { createdAt: resolveWorktreeCreatedAtIso(entry.path) }), - ); + const roots = await ownershipPathVariants(projectWorktreesRoot); + const worktrees: PaseoWorktreeInfo[] = []; + // Inspect foreign paths sequentially; a large worktree list must not consume the FS pool. + for (const entry of parseWorktreeList(stdout)) { + const path = await normalizePathForOwnership(entry.path); + if (!roots.some((root) => getRelativePathInsideRoot(root, path) !== null)) continue; + worktrees.push({ ...entry, path, createdAt: await resolveWorktreeCreatedAtIso(path) }); + } + return worktrees; } export interface DeletePaseoWorktreeOptions { @@ -1071,7 +1110,7 @@ export async function deletePaseoWorktree({ } const requestedPath = worktreePath ?? join(resolvedWorktreesRoot, worktreeSlug!); - const resolvedRequested = normalizePathForOwnership(requestedPath); + const resolvedRequested = await normalizePathForOwnership(requestedPath); const ownership = await isPaseoOwnedWorktreeCwd(requestedPath, { paseoHome, worktreesRoot: worktreesBaseRoot, @@ -1079,7 +1118,7 @@ export async function deletePaseoWorktree({ const resolvedWorktree = ownership.allowed && ownership.worktreePath ? ownership.worktreePath : resolvedRequested; - const relativeWorktreePath = getRealpathAwareRelativePath( + const relativeWorktreePath = await getOwnershipRelativePath( resolvedWorktreesRoot, resolvedWorktree, ); @@ -1195,12 +1234,12 @@ export const createWorktree = async ({ }: CreateWorktreeOptions): Promise => { const sourcePlan = await resolveWorktreeSourcePlan({ cwd, source, desiredSlug: worktreeSlug }); let worktreePath = join(await getPaseoWorktreesRoot(cwd, paseoHome, worktreesRoot), worktreeSlug); - mkdirSync(dirname(worktreePath), { recursive: true }); + await mkdir(dirname(worktreePath), { recursive: true }); // Also handle worktree path collision let finalWorktreePath = worktreePath; let pathSuffix = 1; - while (existsSync(finalWorktreePath)) { + while (await pathExists(finalWorktreePath)) { finalWorktreePath = `${worktreePath}-${pathSuffix}`; pathSuffix++; } @@ -1210,7 +1249,7 @@ export const createWorktree = async ({ cwd, timeout: 120_000, }); - worktreePath = normalizePathForOwnership(finalWorktreePath); + worktreePath = await normalizePathForOwnership(finalWorktreePath); if (sourcePlan.pushRemote) { await configureWorktreePushRemote({ @@ -1227,7 +1266,7 @@ export const createWorktree = async ({ }); } - writePaseoWorktreeMetadata(worktreePath, { + await writePaseoWorktreeMetadata(worktreePath, { baseRefName: sourcePlan.metadataBaseRefName, ...(sourcePlan.metadataBaseRef ? { baseRef: sourcePlan.metadataBaseRef } : {}), ...(sourcePlan.changeRequestLookupTarget From 7f6a805e0e011c44b0596054bc9bbf600a1ca30c Mon Sep 17 00:00:00 2001 From: Luke LaBonte Date: Mon, 26 Oct 2026 22:05:16 -0500 Subject: [PATCH 044/173] feat(app): choose the composer send shortcut (#5503) Add a client-local Send shortcut selector with Enter and Command/Ctrl+Enter choices. Preserve Enter as the default and route the selected shortcut through the existing send behavior. Cover selection, persistence, editing, and running-agent send behavior with browser tests. Co-authored-by: Luke LaBonte --- .../settings-toggle-tab-regression.spec.ts | 121 ++++++++++ packages/app/src/composer/index.tsx | 1 + packages/app/src/composer/input/input.tsx | 38 +++- packages/app/src/composer/input/state.test.ts | 208 ++++++++++++++++++ packages/app/src/composer/input/state.ts | 24 ++ packages/app/src/hooks/use-settings/index.ts | 2 + .../src/hooks/use-settings/storage.test.ts | 33 +++ .../app/src/hooks/use-settings/storage.ts | 5 + packages/app/src/i18n/resources/ar.ts | 13 ++ packages/app/src/i18n/resources/en.ts | 14 ++ packages/app/src/i18n/resources/es.ts | 15 ++ packages/app/src/i18n/resources/fr.ts | 15 ++ packages/app/src/i18n/resources/ja.ts | 13 ++ packages/app/src/i18n/resources/ko.ts | 15 ++ packages/app/src/i18n/resources/pt-BR.ts | 15 ++ packages/app/src/i18n/resources/ru.ts | 15 ++ packages/app/src/i18n/resources/zh-CN.ts | 12 + .../settings/general/sending-section.tsx | 33 ++- 18 files changed, 586 insertions(+), 6 deletions(-) diff --git a/packages/app/e2e/browser/settings-toggle-tab-regression.spec.ts b/packages/app/e2e/browser/settings-toggle-tab-regression.spec.ts index 41da8ac3fa..35ec6f78bb 100644 --- a/packages/app/e2e/browser/settings-toggle-tab-regression.spec.ts +++ b/packages/app/e2e/browser/settings-toggle-tab-regression.spec.ts @@ -1,3 +1,4 @@ +import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent"; import { buildHostAgentDetailRoute, buildHostWorkspaceRoute } from "@/utils/host-routes"; import { expect, test } from "../support/fixtures"; import { createMockIdleAgent, openWorkspaceWithAgents } from "../support/helpers/archive-tab"; @@ -274,3 +275,123 @@ test.describe("Settings toggle tab regression", () => { } }); }); + +async function selectSendingOption( + page: import("@playwright/test").Page, + setting: string, + option: string, +) { + await page.getByRole("button", { name: new RegExp(`^${setting}:`) }).click(); + await page.getByRole("menuitem", { name: option, exact: true }).click(); + await expect( + page.getByRole("button", { name: `${setting}: ${option}`, exact: true }), + ).toBeVisible(); +} + +async function sendDraftWithShortcut( + page: import("@playwright/test").Page, + draft: string, + shortcut: string, +) { + const composer = page.getByRole("textbox", { name: "Message agent..." }); + await composer.fill(draft); + await composer.press(shortcut); + await expect(composer).toHaveValue(""); + await expect(page.getByText(draft, { exact: true })).toBeVisible(); +} + +test("send shortcut selection persists and controls the composer", async ({ page }, testInfo) => { + test.setTimeout(180_000); + const workspace = await seedWorkspace({ repoPrefix: "send-shortcut-" }); + const modifierLabel = process.platform === "darwin" ? "⌘" : "Ctrl"; + try { + const agent = await createMockIdleAgent(workspace.client, { + cwd: workspace.repoPath, + workspaceId: workspace.workspaceId, + title: "Send shortcut", + }); + await openAgentRouteAndExpectFocused({ + page, + serverId: getServerId(), + workspaceId: workspace.workspaceId, + agentId: agent.id, + }); + await openComposerTab(page, agent.id); + const composer = page.getByRole("textbox", { name: "Message agent..." }); + + await test.step("Enter sends by default", async () => { + await sendDraftWithShortcut(page, "Default Enter submission", "Enter"); + }); + await test.step("choose the explicit modifier shortcut and retain it after reload", async () => { + await pressSettingsToggleShortcut(page); + await expect( + page.getByRole("button", { name: "Send shortcut: Enter", exact: true }), + ).toBeVisible(); + await page.getByRole("button", { name: "Send shortcut: Enter", exact: true }).click(); + await expect(page.getByRole("menuitem")).toHaveText(["Enter", `${modifierLabel}+Enter`]); + // Let the menu opening animation settle for visual QA. + await page.waitForTimeout(300); + await page.screenshot({ path: testInfo.outputPath("send-shortcut-selector.png") }); + await page.getByRole("menuitem", { name: `${modifierLabel}+Enter`, exact: true }).click(); + await page.reload(); + await expect( + page.getByRole("button", { name: `Send shortcut: ${modifierLabel}+Enter`, exact: true }), + ).toBeVisible(); + await pressSettingsToggleShortcut(page); + await expect(composer).toBeVisible(); + }); + await test.step("Enter and Shift+Enter keep editing; modifier Enter sends", async () => { + await composer.fill("First line"); + await composer.press("Enter"); + await expect(composer).toHaveValue("First line\n"); + await composer.press("Shift+Enter"); + await expect(composer).toHaveValue("First line\n\n"); + await sendDraftWithShortcut(page, "Sent with Control", "Control+Enter"); + await sendDraftWithShortcut(page, "Sent with Command", "Meta+Enter"); + }); + await test.step("switch back to Enter without changing the default send behavior", async () => { + await pressSettingsToggleShortcut(page); + await selectSendingOption(page, "Send shortcut", "Enter"); + await pressSettingsToggleShortcut(page); + await composer.fill("Shift still edits"); + await composer.press("Shift+Enter"); + await expect(composer).toHaveValue("Shift still edits\n"); + await sendDraftWithShortcut(page, "Restored Enter submission", "Enter"); + }); + } finally { + await workspace.cleanup(); + } +}); + +for (const behavior of ["Steer", "Interrupt", "Queue"] as const) { + test(`modifier send shortcut follows ${behavior} while an agent runs`, async ({ page }) => { + const agent = await seedMockAgentWorkspace({ + repoPrefix: "running-send-shortcut-", + title: "Running send shortcut", + model: "one-minute-stream", + }); + const modifierLabel = process.platform === "darwin" ? "⌘" : "Ctrl"; + try { + await openAgentRoute(page, agent); + await expect(page.getByRole("textbox", { name: "Message agent..." })).toBeVisible(); + await pressSettingsToggleShortcut(page); + await selectSendingOption(page, "Send shortcut", `${modifierLabel}+Enter`); + await selectSendingOption(page, "Default send", behavior); + await pressSettingsToggleShortcut(page); + await sendDraftWithShortcut(page, "Stay running while I write a follow-up", "Control+Enter"); + await expect(page.getByRole("button", { name: "Stop agent", exact: true })).toBeVisible(); + const composer = page.getByRole("textbox", { name: "Message agent..." }); + await composer.fill("Follow-up"); + await composer.press("Enter"); + await expect(composer).toHaveValue("Follow-up\n"); + await composer.press("Control+Enter"); + await expect(composer).toHaveValue(""); + await expect(page.getByText("Follow-up", { exact: true })).toBeVisible(); + await expect(page.getByRole("button", { name: "Send queued message" })).toHaveCount( + behavior === "Queue" ? 1 : 0, + ); + } finally { + await agent.cleanup(); + } + }); +} diff --git a/packages/app/src/composer/index.tsx b/packages/app/src/composer/index.tsx index d000c269af..b7088ddeef 100644 --- a/packages/app/src/composer/index.tsx +++ b/packages/app/src/composer/index.tsx @@ -2495,6 +2495,7 @@ function ComposerContentImpl({ voiceAgentId={agentId} isAgentRunning={isAgentRunning} defaultSendBehavior={activeSendBehavior} + sendShortcut={appSettings.sendShortcut} onQueue={handleQueue} onSubmitLoadingPress={submitLoadingPressHandler} onKeyPress={handleCommandKeyPress} diff --git a/packages/app/src/composer/input/input.tsx b/packages/app/src/composer/input/input.tsx index 73c54331d1..16acede7e5 100644 --- a/packages/app/src/composer/input/input.tsx +++ b/packages/app/src/composer/input/input.tsx @@ -1,3 +1,4 @@ +import type { SendShortcut } from "@/hooks/use-settings"; import { useComposerEditingSession, useComposerFullscreen, @@ -88,6 +89,7 @@ import { resolveAlternateSendAction, resolveComposerSurfacePresentation, resolveComposerSurfaceText, + resolveMessageInputEnterAction, resolveRetainedSelection, runAlternateSendAction, runDefaultSendAction, @@ -96,6 +98,11 @@ import { } from "./state"; const DEFAULT_SEND_KEYS: ShortcutKey[][] = [["Enter"]]; +const MOD_ENTER_SEND_KEYS: ShortcutKey[][] = [["mod", "Enter"]]; + +function resolveSendKeys(sendShortcut: SendShortcut): ShortcutKey[][] { + return sendShortcut === "mod-enter" ? MOD_ENTER_SEND_KEYS : DEFAULT_SEND_KEYS; +} const COMPOSER_INPUT_DATASET = { composerInput: "" } as const; export interface AttachmentMenuItem { @@ -167,6 +174,7 @@ export interface MessageInputProps { * running. "interrupt" and "steer" send immediately, "queue" queues. Required so the default * lives only in DEFAULT_CLIENT_SETTINGS. */ defaultSendBehavior: "interrupt" | "steer" | "queue"; + sendShortcut: SendShortcut; /** Callback for queue button when agent is running */ onQueue?: (payload: MessagePayload) => void; /** Optional handler used when submit button is in loading state. */ @@ -402,6 +410,9 @@ interface DesktopKeyPressContext { onKeyPressCallback: ((event: ComposerKeyPressEvent) => boolean) | undefined; input: ComposerKeyPressEvent["input"]; submitOnEnter: boolean; + sendShortcut: SendShortcut; + isAgentRunning: boolean; + onQueue: ((payload: MessagePayload) => void) | undefined; isSubmitDisabled: boolean; isSubmitLoading: boolean; disabled: boolean; @@ -428,12 +439,21 @@ function handleDesktopKeyPressImpl( } if (event.nativeEvent.key !== "Enter") return; - if (!ctx.submitOnEnter) return; - if (shiftKey) return; + + const action = resolveMessageInputEnterAction({ + submitOnEnter: ctx.submitOnEnter, + sendShortcut: ctx.sendShortcut, + shiftKey: shiftKey ?? false, + metaKey: metaKey ?? false, + ctrlKey: ctrlKey ?? false, + isAgentRunning: ctx.isAgentRunning, + onQueue: ctx.onQueue, + }); + if (action === null) return; if (ctx.isSubmitDisabled || ctx.isSubmitLoading || ctx.disabled) return; event.preventDefault(); - if (metaKey || ctrlKey) { + if (action === "alternate-send") { ctx.handleAlternateSendAction(); return; } @@ -1112,6 +1132,7 @@ interface ResolvedMessageInputProps { voiceAgentId: string | undefined; isAgentRunning: boolean; defaultSendBehavior: "interrupt" | "steer" | "queue"; + sendShortcut: SendShortcut; onQueue: ((payload: MessagePayload) => void) | undefined; onSubmitLoadingPress: (() => void) | undefined; onKeyPressCallback: ((event: ComposerKeyPressEvent) => boolean) | undefined; @@ -1159,6 +1180,7 @@ function resolveMessageInputProps(props: MessageInputProps): ResolvedMessageInpu voiceAgentId: props.voiceAgentId, isAgentRunning: props.isAgentRunning ?? false, defaultSendBehavior: props.defaultSendBehavior, + sendShortcut: props.sendShortcut, onQueue: props.onQueue, onSubmitLoadingPress: props.onSubmitLoadingPress, onKeyPressCallback: props.onKeyPress, @@ -1236,6 +1258,7 @@ export const MessageInput = forwardRef( voiceAgentId, isAgentRunning, defaultSendBehavior, + sendShortcut, onQueue, onSubmitLoadingPress, onKeyPressCallback, @@ -1755,6 +1778,9 @@ export const MessageInput = forwardRef( selectionRef.current, ), submitOnEnter: shouldSubmitOnEnter, + sendShortcut, + isAgentRunning, + onQueue, isSubmitDisabled, isSubmitLoading, disabled, @@ -1766,6 +1792,9 @@ export const MessageInput = forwardRef( shouldHandleWebKeyPress, onKeyPressCallback, shouldSubmitOnEnter, + sendShortcut, + isAgentRunning, + onQueue, isSubmitDisabled, isSubmitLoading, disabled, @@ -1980,7 +2009,7 @@ export const MessageInput = forwardRef( submitLabel={submitLabel} submitButtonTestID={submitButtonTestID} buttonIconSize={buttonIconSize} - sendKeys={DEFAULT_SEND_KEYS} + sendKeys={resolveSendKeys(sendShortcut)} sendTooltipLabel={sendTooltipLabel} /> ), @@ -2001,6 +2030,7 @@ export const MessageInput = forwardRef( submitLabel, submitButtonTestID, buttonIconSize, + sendShortcut, sendTooltipLabel, ], ); diff --git a/packages/app/src/composer/input/state.test.ts b/packages/app/src/composer/input/state.test.ts index 82f30da364..ad492976b3 100644 --- a/packages/app/src/composer/input/state.test.ts +++ b/packages/app/src/composer/input/state.test.ts @@ -2,10 +2,12 @@ import { describe, expect, it, vi } from "vitest"; import { applyDictationTranscript, computeCanStartDictation, + type MessageInputEnterContext, resolveActiveSendBehavior, resolveComposerSurfacePresentation, resolveComposerSurfaceText, resolveGlyphRailOffset, + resolveMessageInputEnterAction, resolveRetainedSelection, resolveAlternateSendAction, runAlternateSendAction, @@ -320,6 +322,212 @@ describe("composer send behavior", () => { }); }); +describe("resolveMessageInputEnterAction", () => { + function enterContext( + overrides: Partial = {}, + ): MessageInputEnterContext { + return { + submitOnEnter: true, + sendShortcut: "enter", + shiftKey: false, + metaKey: false, + ctrlKey: false, + isAgentRunning: false, + onQueue: () => undefined, + ...overrides, + }; + } + + it("returns null for plain, Shift, and modifier Enter when submit on enter is disabled", () => { + expect(resolveMessageInputEnterAction(enterContext({ submitOnEnter: false }))).toBeNull(); + expect( + resolveMessageInputEnterAction(enterContext({ submitOnEnter: false, shiftKey: true })), + ).toBeNull(); + expect( + resolveMessageInputEnterAction(enterContext({ submitOnEnter: false, metaKey: true })), + ).toBeNull(); + expect( + resolveMessageInputEnterAction(enterContext({ submitOnEnter: false, ctrlKey: true })), + ).toBeNull(); + }); + + it("still returns null when modifier Enter sends and submit on enter is disabled", () => { + expect( + resolveMessageInputEnterAction( + enterContext({ sendShortcut: "mod-enter", submitOnEnter: false, metaKey: true }), + ), + ).toBeNull(); + expect( + resolveMessageInputEnterAction( + enterContext({ sendShortcut: "mod-enter", submitOnEnter: false }), + ), + ).toBeNull(); + }); + + it("sends on plain Enter when Enter sends", () => { + expect(resolveMessageInputEnterAction(enterContext())).toBe("default-send"); + }); + + it("returns null for Shift+Enter when Enter sends", () => { + expect(resolveMessageInputEnterAction(enterContext({ shiftKey: true }))).toBeNull(); + }); + + it("returns null for Shift+Cmd+Enter and Shift+Ctrl+Enter so Shift keeps its newline", () => { + expect( + resolveMessageInputEnterAction( + enterContext({ shiftKey: true, metaKey: true, isAgentRunning: true }), + ), + ).toBeNull(); + expect( + resolveMessageInputEnterAction( + enterContext({ shiftKey: true, ctrlKey: true, isAgentRunning: true }), + ), + ).toBeNull(); + }); + + it("sends on Cmd+Enter and Ctrl+Enter while idle even with a queue handler", () => { + expect(resolveMessageInputEnterAction(enterContext({ metaKey: true }))).toBe("default-send"); + expect(resolveMessageInputEnterAction(enterContext({ ctrlKey: true }))).toBe("default-send"); + }); + + it("queues on Cmd+Enter and Ctrl+Enter while the agent is running with a queue handler", () => { + expect( + resolveMessageInputEnterAction(enterContext({ metaKey: true, isAgentRunning: true })), + ).toBe("alternate-send"); + expect( + resolveMessageInputEnterAction(enterContext({ ctrlKey: true, isAgentRunning: true })), + ).toBe("alternate-send"); + }); + + it("sends on Cmd+Enter and Ctrl+Enter while running when no queue handler exists", () => { + expect( + resolveMessageInputEnterAction( + enterContext({ metaKey: true, isAgentRunning: true, onQueue: undefined }), + ), + ).toBe("default-send"); + expect( + resolveMessageInputEnterAction( + enterContext({ ctrlKey: true, isAgentRunning: true, onQueue: undefined }), + ), + ).toBe("default-send"); + }); + + it("returns null for plain and Shift+Enter when modifier Enter sends", () => { + expect(resolveMessageInputEnterAction(enterContext({ sendShortcut: "mod-enter" }))).toBeNull(); + expect( + resolveMessageInputEnterAction(enterContext({ sendShortcut: "mod-enter", shiftKey: true })), + ).toBeNull(); + }); + + it("returns null for Shift+Cmd+Enter and Shift+Ctrl+Enter when modifier Enter sends", () => { + expect( + resolveMessageInputEnterAction( + enterContext({ sendShortcut: "mod-enter", shiftKey: true, metaKey: true }), + ), + ).toBeNull(); + expect( + resolveMessageInputEnterAction( + enterContext({ sendShortcut: "mod-enter", shiftKey: true, ctrlKey: true }), + ), + ).toBeNull(); + }); + + it("sends on Cmd+Enter and Ctrl+Enter while idle when modifier Enter sends", () => { + expect( + resolveMessageInputEnterAction(enterContext({ sendShortcut: "mod-enter", metaKey: true })), + ).toBe("default-send"); + expect( + resolveMessageInputEnterAction(enterContext({ sendShortcut: "mod-enter", ctrlKey: true })), + ).toBe("default-send"); + }); + + it("uses the default action on modifier Enter while running when modifier Enter sends", () => { + expect( + resolveMessageInputEnterAction( + enterContext({ sendShortcut: "mod-enter", metaKey: true, isAgentRunning: true }), + ), + ).toBe("default-send"); + expect( + resolveMessageInputEnterAction( + enterContext({ sendShortcut: "mod-enter", ctrlKey: true, isAgentRunning: true }), + ), + ).toBe("default-send"); + }); + + describe("composed with the send actions", () => { + function actions() { + const calls: string[] = []; + return { + calls, + handleSendMessage: () => calls.push("send"), + handleQueueMessage: () => calls.push("queue"), + onQueue: () => undefined, + }; + } + + function resolveCommandEnterToSendModifierEnter() { + return resolveMessageInputEnterAction( + enterContext({ sendShortcut: "mod-enter", metaKey: true, isAgentRunning: true }), + ); + } + + it("queues through the default send action when queue behavior is selected and the agent is running", () => { + const sendAction = actions(); + + expect(resolveCommandEnterToSendModifierEnter()).toBe("default-send"); + + runDefaultSendAction({ + defaultSendBehavior: "queue", + isAgentRunning: true, + onQueue: sendAction.onQueue, + handleSendMessage: sendAction.handleSendMessage, + handleQueueMessage: sendAction.handleQueueMessage, + }); + + expect(sendAction.calls).toEqual(["queue"]); + }); + + it("sends through the default send action when queue behavior is selected and the agent is idle", () => { + const sendAction = actions(); + + expect( + resolveMessageInputEnterAction( + enterContext({ sendShortcut: "mod-enter", metaKey: true, isAgentRunning: false }), + ), + ).toBe("default-send"); + + runDefaultSendAction({ + defaultSendBehavior: "queue", + isAgentRunning: false, + onQueue: sendAction.onQueue, + handleSendMessage: sendAction.handleSendMessage, + handleQueueMessage: sendAction.handleQueueMessage, + }); + + expect(sendAction.calls).toEqual(["send"]); + }); + + it.each([{ defaultSendBehavior: "steer" }, { defaultSendBehavior: "interrupt" }] as const)( + "sends through the default send action when $defaultSendBehavior behavior is selected and the agent is running", + ({ defaultSendBehavior }) => { + const sendAction = actions(); + + expect(resolveCommandEnterToSendModifierEnter()).toBe("default-send"); + + runDefaultSendAction({ + defaultSendBehavior, + isAgentRunning: true, + onQueue: sendAction.onQueue, + handleSendMessage: sendAction.handleSendMessage, + handleQueueMessage: sendAction.handleQueueMessage, + }); + + expect(sendAction.calls).toEqual(["send"]); + }, + ); + }); +}); + describe("stopRealtimeVoice", () => { it("keeps voice mode active when the running agent refuses cancellation", async () => { const cancellationError = new Error("active run cancellation was not acknowledged"); diff --git a/packages/app/src/composer/input/state.ts b/packages/app/src/composer/input/state.ts index 9cf6279482..67c8030745 100644 --- a/packages/app/src/composer/input/state.ts +++ b/packages/app/src/composer/input/state.ts @@ -1,3 +1,4 @@ +import type { SendShortcut } from "@/hooks/use-settings"; import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages"; import type { MessagePayload, TextReplacement } from "@/composer/types"; @@ -151,6 +152,29 @@ export function runAlternateSendAction(ctx: SendActionContext): void { runDefaultSendAction(ctx); } +export type MessageInputEnterAction = "alternate-send" | "default-send"; + +export interface MessageInputEnterContext { + submitOnEnter: boolean; + sendShortcut: SendShortcut; + shiftKey: boolean; + metaKey: boolean; + ctrlKey: boolean; + isAgentRunning: boolean; + onQueue: ((payload: MessagePayload) => void) | undefined; +} + +export function resolveMessageInputEnterAction( + ctx: MessageInputEnterContext, +): MessageInputEnterAction | null { + if (!ctx.submitOnEnter) return null; + if (ctx.shiftKey) return null; + const hasModifier = ctx.metaKey || ctx.ctrlKey; + if (ctx.sendShortcut === "mod-enter") return hasModifier ? "default-send" : null; + if (hasModifier && ctx.isAgentRunning && ctx.onQueue) return "alternate-send"; + return "default-send"; +} + export function runMessageInputKeyboardAction( action: MessageInputKeyboardActionKind, actions: MessageInputKeyboardActions, diff --git a/packages/app/src/hooks/use-settings/index.ts b/packages/app/src/hooks/use-settings/index.ts index 9f6f22fb23..382ab350fc 100644 --- a/packages/app/src/hooks/use-settings/index.ts +++ b/packages/app/src/hooks/use-settings/index.ts @@ -49,6 +49,7 @@ import { type KeyValueStorage, type ReleaseChannel, type SendBehavior, + type SendShortcut, type ServiceUrlBehavior, type Settings, type SidebarWorkspaceTrailing, @@ -93,6 +94,7 @@ export type { KeyValueStorage, ReleaseChannel, SendBehavior, + SendShortcut, ServiceUrlBehavior, Settings, SettingsDeps, diff --git a/packages/app/src/hooks/use-settings/storage.test.ts b/packages/app/src/hooks/use-settings/storage.test.ts index fe2ffdd2a0..0b169b5214 100644 --- a/packages/app/src/hooks/use-settings/storage.test.ts +++ b/packages/app/src/hooks/use-settings/storage.test.ts @@ -227,6 +227,39 @@ describe("loadAppSettingsFromStorage", () => { expect(result.chatOutlineEnabled).toBe(false); }); + it("uses Enter to send by default", async () => { + const deps = makeDeps(); + + const result = await loadAppSettingsFromStorage(deps); + + expect(result.sendShortcut).toBe("enter"); + expect(DEFAULT_CLIENT_SETTINGS.sendShortcut).toBe("enter"); + }); + + it("loads the modifier Enter send preference", async () => { + const deps = makeDeps({ + storage: createInMemoryKeyValueStorage({ + [APP_SETTINGS_KEY]: JSON.stringify({ sendShortcut: "mod-enter" }), + }), + }); + + const result = await loadAppSettingsFromStorage(deps); + + expect(result.sendShortcut).toBe("mod-enter"); + }); + + it("falls back to Enter when the stored send shortcut is invalid", async () => { + const deps = makeDeps({ + storage: createInMemoryKeyValueStorage({ + [APP_SETTINGS_KEY]: JSON.stringify({ sendShortcut: "yes" }), + }), + }); + + const result = await loadAppSettingsFromStorage(deps); + + expect(result.sendShortcut).toBe("enter"); + }); + it("defaults sidebar navigation items to an empty preference list", async () => { const deps = makeDeps(); diff --git a/packages/app/src/hooks/use-settings/storage.ts b/packages/app/src/hooks/use-settings/storage.ts index 3a5be63441..424536ac69 100644 --- a/packages/app/src/hooks/use-settings/storage.ts +++ b/packages/app/src/hooks/use-settings/storage.ts @@ -33,6 +33,8 @@ import { migrateAppSettings } from "./migrations"; export { APP_SETTINGS_KEY } from "./keys"; export const APP_SETTINGS_QUERY_KEY = ["app-settings"]; +export type SendShortcut = "enter" | "mod-enter"; + export type SendBehavior = ActiveTurnBehavior | "queue"; export type ReleaseChannel = "stable" | "beta"; export type ServiceUrlBehavior = "ask" | "in-app" | "external"; @@ -104,6 +106,7 @@ export interface AppSettings { chatDisplay: ChatDisplay; chatOutlineEnabled: boolean; vimKeybindings: boolean; + sendShortcut: SendShortcut; filePanelAssociations: Record; /** Desktop-only preferences for implicit opens into the ordinary side pane. */ openInSidePane: OpenInSidePanePreferences; @@ -160,6 +163,7 @@ export const DEFAULT_CLIENT_SETTINGS: AppSettings = { chatDisplay: "collapseTurns", chatOutlineEnabled: true, vimKeybindings: false, + sendShortcut: "enter", filePanelAssociations: {}, openInSidePane: DEFAULT_OPEN_IN_SIDE_PANE_PREFERENCES, pullRequestOpenLocation: "explorer", @@ -264,6 +268,7 @@ const StoredAppSettingsSchema = z compactToolCalls: z.boolean().optional().catch(undefined), chatOutlineEnabled: z.boolean().catch(true), vimKeybindings: z.boolean().catch(false), + sendShortcut: z.enum(["enter", "mod-enter"]).catch("enter"), filePanelAssociations: z.record(z.string(), z.string()).catch({}), openInSidePane: z .object({ diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index 108fad41d4..6bfc30095c 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -2369,12 +2369,25 @@ export const ar: TranslationResources = { "عند تشغيل الوكيل، يوجّه Enter الجولة النشطة. يضيف Command/Ctrl+Enter إلى قائمة الانتظار.", queue: "عند تشغيل الوكيل، يضيف Enter إلى قائمة الانتظار. Command/Ctrl+Enter يرسل.", }, + commandEnterDescriptions: { + interrupt: "عند تشغيل الوكيل، يوقف {{modifier}}+Enter التشغيل. يُدرج Enter سطرًا جديدًا.", + steer: "عند تشغيل الوكيل، يوجّه {{modifier}}+Enter الجولة النشطة. يُدرج Enter سطرًا جديدًا.", + queue: + "عند تشغيل الوكيل، يضيف {{modifier}}+Enter إلى قائمة الانتظار. يُدرج Enter سطرًا جديدًا.", + }, options: { interrupt: "مقاطعة", steer: "توجيه", queue: "طابور", }, }, + sendShortcut: { + label: "اختصار الإرسال", + options: { + enter: "Enter", + "mod-enter": "{{modifier}}+Enter", + }, + }, serviceUrls: { options: { ask: "بسأل", diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index 16bddd9cf9..ff1e80d88b 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -2457,12 +2457,26 @@ export const en = { "When the agent is running, Enter steers the active turn. Command/Ctrl+Enter queues.", queue: "When the agent is running, Enter queues. Command/Ctrl+Enter submits.", }, + commandEnterDescriptions: { + interrupt: + "When the agent is running, {{modifier}}+Enter interrupts. Enter inserts a new line.", + steer: + "When the agent is running, {{modifier}}+Enter steers the active turn. Enter inserts a new line.", + queue: "When the agent is running, {{modifier}}+Enter queues. Enter inserts a new line.", + }, options: { interrupt: "Interrupt", steer: "Steer", queue: "Queue", }, }, + sendShortcut: { + label: "Send shortcut", + options: { + enter: "Enter", + "mod-enter": "{{modifier}}+Enter", + }, + }, serviceUrls: { options: { ask: "Ask", diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index 2226583781..8784adefb5 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -2384,12 +2384,27 @@ export const es: TranslationResources = { queue: "Cuando el agente se está ejecutando, Enter pone en cola. Command/Ctrl+Enter envía.", }, + commandEnterDescriptions: { + interrupt: + "Cuando el agente se está ejecutando, {{modifier}}+Enter interrumpe. Enter inserta una línea nueva.", + steer: + "Cuando el agente se está ejecutando, {{modifier}}+Enter dirige el turno activo. Enter inserta una línea nueva.", + queue: + "Cuando el agente se está ejecutando, {{modifier}}+Enter pone en cola. Enter inserta una línea nueva.", + }, options: { interrupt: "Interrumpir", steer: "Dirigir", queue: "Cola", }, }, + sendShortcut: { + label: "Atajo de envío", + options: { + enter: "Enter", + "mod-enter": "{{modifier}}+Enter", + }, + }, serviceUrls: { options: { ask: "Preguntar", diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index 65d72d405b..bbafc03dda 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -2383,12 +2383,27 @@ export const fr: TranslationResources = { queue: "Quand l’agent est en cours d’exécution, Entrée met en file d’attente. Cmd/Ctrl+Entrée envoie.", }, + commandEnterDescriptions: { + interrupt: + "Lorsque l'agent est en cours d'exécution, {{modifier}}+Entrée interrompt. Entrée insère une nouvelle ligne.", + steer: + "Lorsque l'agent est en cours d'exécution, {{modifier}}+Entrée oriente le tour actif. Entrée insère une nouvelle ligne.", + queue: + "Lorsque l'agent est en cours d'exécution, {{modifier}}+Entrée met en file d'attente. Entrée insère une nouvelle ligne.", + }, options: { interrupt: "Interrompre", steer: "Réorienter", queue: "File d’attente", }, }, + sendShortcut: { + label: "Raccourci d’envoi", + options: { + enter: "Enter", + "mod-enter": "{{modifier}}+Enter", + }, + }, serviceUrls: { options: { ask: "Demander", diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index 5829bf4fa3..e7dcc5b5e7 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -2353,12 +2353,25 @@ export const ja: TranslationResources = { "エージェント実行中、Enterで現在のターンに指示を送ります。Command/Ctrl+Enterでキューに追加。", queue: "エージェント実行中、Enterでキューに追加します。Command/Ctrl+Enterで送信。", }, + commandEnterDescriptions: { + interrupt: "エージェント実行中、{{modifier}}+Enterで中断します。Enterで改行します。", + steer: + "エージェント実行中、{{modifier}}+Enterで現在のターンに指示を送ります。Enterで改行します。", + queue: "エージェント実行中、{{modifier}}+Enterでキューに追加します。Enterで改行します。", + }, options: { interrupt: "中断", steer: "指示", queue: "キュー", }, }, + sendShortcut: { + label: "送信ショートカット", + options: { + enter: "Enter", + "mod-enter": "{{modifier}}+Enter", + }, + }, serviceUrls: { options: { ask: "確認する", diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index 36a27fc84e..d8d1fbc787 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -2344,12 +2344,27 @@ export const ko: TranslationResources = { queue: "에이전트가 실행 중일 때 Enter는 대기열에 추가합니다. Command/Ctrl+Enter는 제출합니다.", }, + commandEnterDescriptions: { + interrupt: + "에이전트가 실행 중일 때 {{modifier}}+Enter는 중단합니다. Enter는 줄바꿈합니다.", + steer: + "에이전트가 실행 중일 때 {{modifier}}+Enter는 현재 턴에 지시합니다. Enter는 줄바꿈합니다.", + queue: + "에이전트가 실행 중일 때 {{modifier}}+Enter는 대기열에 추가합니다. Enter는 줄바꿈합니다.", + }, options: { interrupt: "중단", steer: "지시", queue: "대기열", }, }, + sendShortcut: { + label: "전송 단축키", + options: { + enter: "Enter", + "mod-enter": "{{modifier}}+Enter", + }, + }, serviceUrls: { options: { ask: "물어보기", diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index 5a83b4345c..1c024dc64a 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -2367,12 +2367,27 @@ export const ptBR: TranslationResources = { "Quando o agente está em execução, Enter orienta o turno ativo. Command/Ctrl+Enter enfileira.", queue: "Quando o agente está em execução, Enter enfileira. Command/Ctrl+Enter envia.", }, + commandEnterDescriptions: { + interrupt: + "Quando o agente está em execução, {{modifier}}+Enter interrompe. Enter insere uma nova linha.", + steer: + "Quando o agente está em execução, {{modifier}}+Enter orienta o turno ativo. Enter insere uma nova linha.", + queue: + "Quando o agente está em execução, {{modifier}}+Enter enfileira. Enter insere uma nova linha.", + }, options: { interrupt: "Interromper", steer: "Orientar", queue: "Fila", }, }, + sendShortcut: { + label: "Atalho de envio", + options: { + enter: "Enter", + "mod-enter": "{{modifier}}+Enter", + }, + }, serviceUrls: { options: { ask: "Perguntar", diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index 135d5fe2f9..093ac68c36 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -2370,12 +2370,27 @@ export const ru: TranslationResources = { queue: "Когда агент работает, Enter ставит сообщение в очередь, а Command/Ctrl+Enter отправляет его.", }, + commandEnterDescriptions: { + interrupt: + "Когда агент работает, {{modifier}}+Enter прерывает его работу, а Enter вставляет новую строку.", + steer: + "Когда агент работает, {{modifier}}+Enter дополняет текущий ответ новым указанием, а Enter вставляет новую строку.", + queue: + "Когда агент работает, {{modifier}}+Enter ставит сообщение в очередь, а Enter вставляет новую строку.", + }, options: { interrupt: "Прерывать", steer: "Направить", queue: "Поставить в очередь", }, }, + sendShortcut: { + label: "Сочетание клавиш для отправки", + options: { + enter: "Enter", + "mod-enter": "{{modifier}}+Enter", + }, + }, serviceUrls: { options: { ask: "Спрашивать", diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index 78b0f06442..8ca178f206 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -2308,12 +2308,24 @@ export const zhCN: TranslationResources = { steer: "Agent 运行时,Enter 会引导当前回合。Command/Ctrl+Enter 会排队。", queue: "Agent 运行时,Enter 会排队。Command/Ctrl+Enter 会提交。", }, + commandEnterDescriptions: { + interrupt: "Agent 运行时,{{modifier}}+Enter 会中断。Enter 会插入换行。", + steer: "Agent 运行时,{{modifier}}+Enter 会引导当前回合。Enter 会插入换行。", + queue: "Agent 运行时,{{modifier}}+Enter 会排队。Enter 会插入换行。", + }, options: { interrupt: "中断", steer: "引导", queue: "排队", }, }, + sendShortcut: { + label: "发送快捷键", + options: { + enter: "Enter", + "mod-enter": "{{modifier}}+Enter", + }, + }, serviceUrls: { options: { ask: "询问", diff --git a/packages/app/src/screens/settings/general/sending-section.tsx b/packages/app/src/screens/settings/general/sending-section.tsx index 85da0fdf4e..c5d5f01760 100644 --- a/packages/app/src/screens/settings/general/sending-section.tsx +++ b/packages/app/src/screens/settings/general/sending-section.tsx @@ -1,13 +1,17 @@ import { useCallback, useMemo } from "react"; import { useTranslation } from "react-i18next"; import { SettingsCard, SettingsSection, SettingsSelect } from "@/components/settings"; -import { useAppSettings, type SendBehavior } from "@/hooks/use-settings"; +import { useAppSettings, type SendShortcut, type SendBehavior } from "@/hooks/use-settings"; +import { useKeyboardShortcutsAvailable } from "@/keyboard/availability"; +import { getShortcutOs } from "@/utils/shortcut-platform"; const SEND_BEHAVIORS: readonly SendBehavior[] = ["interrupt", "steer", "queue"]; export function SendingSection() { const { t } = useTranslation(); const { settings, updateSettings } = useAppSettings(); + const shortcutsAvailable = useKeyboardShortcutsAvailable(); + const modifier = getShortcutOs() === "mac" ? "⌘" : "Ctrl"; const options = useMemo( () => SEND_BEHAVIORS.map((value) => ({ @@ -20,12 +24,37 @@ export function SendingSection() { (sendBehavior: SendBehavior) => void updateSettings({ sendBehavior }), [updateSettings], ); + const shortcutOptions = useMemo( + () => + (["enter", "mod-enter"] as const).map((value) => ({ + value, + label: t(`settings.general.sendShortcut.options.${value}`, { modifier }), + })), + [t, modifier], + ); + const changeSendShortcut = useCallback( + (sendShortcut: SendShortcut) => void updateSettings({ sendShortcut }), + [updateSettings], + ); return ( + {shortcutsAvailable ? ( + + ) : null} Date: Tue, 27 Oct 2026 10:23:59 +0700 Subject: [PATCH 045/173] Keep the daemon responsive during Claude history replay (#7940) * fix(server): keep Claude history replay responsive Load persisted history through session readiness rather than the constructor. Async descriptor-owned replay preserves ordering while serving other requests, and rebind retires the old query before rebuilding history and rewind state. * fix(server): recover Claude history readiness after rebind errors * test(server): calibrate Claude replay fixture for CI * fix(server): report Claude rewind rebind failures to callers --- .../claude/agent.history-load.test.ts | 335 ++++++++++- .../server/agent/providers/claude/agent.ts | 258 +++++--- .../agent/providers/claude/project-dir.ts | 26 +- .../server/agent/providers/claude/rewind.ts | 6 +- .../claude/subagents/replay-source.test.ts | 568 ++++++++++-------- .../claude/subagents/replay-source.ts | 14 +- .../subagents/workflow-replay-source.test.ts | 26 +- .../subagents/workflow-replay-source.ts | 31 +- .../claude/task-notification-tool-call.ts | 6 +- .../providers/claude/transcript-history.ts | 107 ++-- 10 files changed, 920 insertions(+), 457 deletions(-) diff --git a/packages/server/src/server/agent/providers/claude/agent.history-load.test.ts b/packages/server/src/server/agent/providers/claude/agent.history-load.test.ts index b355f367b3..921b4018be 100644 --- a/packages/server/src/server/agent/providers/claude/agent.history-load.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.history-load.test.ts @@ -1,9 +1,13 @@ import fs, { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { open } from "node:fs/promises"; +import { performance } from "node:perf_hooks"; import * as os from "node:os"; import * as path from "node:path"; import pino from "pino"; import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +import { createTestPaseoDaemon } from "../../../test-utils/paseo-daemon.js"; +import type { ClaudeRewindSdk } from "./rewind.js"; import { ClaudeAgentClient } from "./agent.js"; import { claudeProjectDirSync } from "./project-dir.js"; import { withClaudeReplayHistory } from "./transcript-history.js"; @@ -32,7 +36,10 @@ describe("ClaudeAgentSession persisted history load", () => { let configDir: string; let records: LogRecord[]; - async function resume(queryFactory?: ClaudeQueryFactory): Promise { + async function resume( + queryFactory?: ClaudeQueryFactory, + rewindSdk?: ClaudeRewindSdk, + ): Promise { const client = new ClaudeAgentClient({ logger: pino({ level: "info" }, { write: (line: string) => records.push(JSON.parse(line)) }), queryFactory: @@ -42,10 +49,36 @@ describe("ClaudeAgentSession persisted history load", () => { }), resolveBinary: async () => process.execPath, resolveVersion: async () => "2.1.220", + rewindSdk, }); return client.resumeSession({ provider: "claude", sessionId: SESSION_ID }, { cwd }); } + function replyFactory(text: string, messageId = "live-reply"): ClaudeQueryFactory { + return (() => { + const messages = [ + { type: "assistant", uuid: messageId, message: { content: text } }, + { type: "result", subtype: "success", total_cost_usd: 0 }, + ]; + return { + async next() { + const value = messages.shift(); + return value ? { done: false, value } : { done: true, value: undefined }; + }, + close() {}, + async return() { + return { done: true, value: undefined }; + }, + async supportedCommands() { + return []; + }, + [Symbol.asyncIterator]() { + return this; + }, + }; + }) as ClaudeQueryFactory; + } + function transcriptPath(): string { return path.join(claudeProjectDirSync(cwd, { configDir }), `${SESSION_ID}.jsonl`); } @@ -65,6 +98,288 @@ describe("ClaudeAgentSession persisted history load", () => { rmSync(tempRoot, { recursive: true, force: true }); }); + test("serves unrelated health requests while resuming 32 MiB of ordered history", async () => { + const startedAt = performance.now(); + mkdirSync(path.dirname(transcriptPath()), { recursive: true }); + const file = await open(transcriptPath(), "w"); + const text = "x".repeat(16 * 1024); + let bytes = 0; + let count = 0; + try { + while (bytes < 32 * 1024 * 1024) { + const line = + JSON.stringify({ type: "assistant", message: { content: `${count}:${text}` } }) + "\n"; + bytes += Buffer.byteLength(line); + await file.write(line); + count++; + } + } finally { + await file.close(); + } + const daemon = await createTestPaseoDaemon(); + let lastTick = performance.now(); + let longestGap = 0; + const probe = setInterval(() => { + const now = performance.now(); + longestGap = Math.max(longestGap, now - lastTick); + lastTick = now; + }, 2); + let loading = true; + let answeredDuringLoad = false; + const health = fetch(`http://127.0.0.1:${daemon.port}/api/health`).then(async (response) => { + expect(response.status).toBe(200); + await response.text(); + answeredDuringLoad = loading; + return undefined; + }); + let session: AgentSession | undefined; + try { + session = await resume(replyFactory("live after large resume")); + let index = 0; + for await (const event of session.streamHistory()) { + expect(event).toEqual({ + type: "timeline", + provider: "claude", + timestamp: undefined, + item: { type: "assistant_message", text: `${index}:${text}` }, + }); + index++; + } + loading = false; + await health; + await new Promise((resolve) => setTimeout(resolve, 5)); + console.info( + JSON.stringify({ + bytes, + count, + longestGap, + answeredDuringLoad, + elapsedMs: performance.now() - startedAt, + }), + ); + expect(index).toBe(count); + expect(longestGap).toBeLessThan(50); + expect(answeredDuringLoad).toBe(true); + const live = await collectSessionTurnEvents(session, "follow up"); + expect( + live + .filter((event) => event.type === "timeline" && event.item.type === "assistant_message") + .map((event) => (event.type === "timeline" ? event.item : null)), + ).toEqual([ + { type: "assistant_message", messageId: "live-reply", text: "live after large resume" }, + ]); + } finally { + clearInterval(probe); + await session?.close(); + await daemon.close(); + } + }, 60_000); + + test("rebinds ordered history before returning from rewind and accepts a live turn", async () => { + const entries = [ + { type: "user", uuid: "u1", message: { content: "first" } }, + { type: "assistant", uuid: "a1", message: { content: "first reply" } }, + { type: "user", uuid: "u2", message: { content: "second" } }, + { type: "assistant", uuid: "a2", message: { content: "second reply" } }, + ]; + mkdirSync(path.dirname(transcriptPath()), { recursive: true }); + writeFileSync(transcriptPath(), entries.map((entry) => JSON.stringify(entry)).join("\n")); + const forkId = "rebound-history"; + const forkFile = path.join(path.dirname(transcriptPath()), `${forkId}.jsonl`); + writeFileSync( + forkFile, + entries + .slice(0, 2) + .map((entry) => JSON.stringify(entry)) + .join("\n"), + ); + const forks: unknown[] = []; + const late = { + type: "assistant", + uuid: "retired-reply", + message: { content: "retired query" }, + }; + let pendingRead: ((value: unknown) => void) | undefined; + let releaseRetirement!: () => void; + const retirementGate = new Promise((resolve) => { + releaseRetirement = resolve; + }); + let retirementStarted!: () => void; + const retiring = new Promise((resolve) => { + retirementStarted = resolve; + }); + let firstQuery = true; + let retired = false; + const queryFactory = (() => { + if (!firstQuery) return replyFactory("live after rebind")({} as never); + firstQuery = false; + const messages = [ + { type: "assistant", uuid: "before-rebind", message: { content: "before rebind" } }, + { type: "result", subtype: "success", total_cost_usd: 0 }, + ]; + return { + async next() { + const value = messages.shift(); + if (value) return { done: false, value }; + if (retired) return { done: true, value: undefined }; + return new Promise((resolve) => { + pendingRead = resolve; + }); + }, + close() { + retired = true; + pendingRead?.({ done: false, value: late }); + }, + async return() { + retirementStarted(); + await retirementGate; + return { done: true, value: undefined }; + }, + async supportedCommands() { + return []; + }, + [Symbol.asyncIterator]() { + return this; + }, + }; + }) as ClaudeQueryFactory; + const session = await resume(queryFactory, { + async forkSession(sessionId, options) { + forks.push({ sessionId, ...options }); + return { sessionId: forkId }; + }, + }); + try { + const original = await Array.fromAsync(session.streamHistory()); + expect(original).toHaveLength(4); + await collectSessionTurnEvents(session, "before rewind"); + const emitted: AgentStreamEvent[] = []; + const subscription = session.subscribe((event) => emitted.push(event)); + let rewindDone = false; + const rewind = (async () => { + await session.revertConversation!({ messageId: "u2" }); + rewindDone = true; + })(); + await retiring; + let historyDone = false; + const reading = (async () => { + const history = await Array.fromAsync(session.streamHistory()); + historyDone = true; + return history; + })(); + const readingAgain = Array.fromAsync(session.streamHistory()); + await Promise.resolve(); + expect(rewindDone).toBe(false); + expect(historyDone).toBe(false); + releaseRetirement(); + await rewind; + subscription(); + expect(retired).toBe(true); + expect( + emitted.filter( + (event) => event.type === "timeline" && event.item.type === "assistant_message", + ), + ).toEqual([ + { + type: "timeline", + provider: "claude", + item: { + type: "assistant_message", + text: `Claude switched to a new session: ${SESSION_ID} -> ${forkId}`, + }, + }, + ]); + expect(forks).toEqual([ + { sessionId: SESSION_ID, upToMessageId: "a1", transcriptPath: transcriptPath() }, + ]); + expect(session.id).toBe(forkId); + const [history, secondRead] = await Promise.all([reading, readingAgain]); + expect(history).toEqual(original.slice(0, 2)); + expect(secondRead).toEqual([]); + const live = await collectSessionTurnEvents(session, "continue the fork"); + expect( + live + .filter((event) => event.type === "timeline" && event.item.type === "assistant_message") + .map((event) => (event.type === "timeline" ? event.item : null)), + ).toEqual([ + { type: "assistant_message", messageId: "live-reply", text: "live after rebind" }, + ]); + } finally { + releaseRetirement(); + await session.close(); + } + }); + + test("reports a failed rewind without poisoning readiness when query retirement throws", async () => { + mkdirSync(path.dirname(transcriptPath()), { recursive: true }); + writeFileSync( + transcriptPath(), + [ + { type: "user", uuid: "u1", message: { content: "first" } }, + { type: "assistant", uuid: "a1", message: { content: "reply" } }, + { type: "user", uuid: "u2", message: { content: "second" } }, + ] + .map((entry) => JSON.stringify(entry)) + .join("\n"), + ); + let firstQuery = true; + let finishRead: ((value: unknown) => void) | undefined; + const queryFactory = ((input) => { + const query = replyFactory( + firstQuery ? "before retirement" : "still available", + firstQuery ? "before-retirement" : "live-reply", + )(input); + if (!firstQuery) return query; + firstQuery = false; + let reads = 0; + return { + ...query, + async next() { + if (++reads <= 2) return query.next(); + return new Promise((resolve) => { + finishRead = resolve; + }); + }, + close() { + finishRead?.({ done: true, value: undefined }); + throw new Error("retirement failed"); + }, + [Symbol.asyncIterator]() { + return this; + }, + }; + }) as ClaudeQueryFactory; + const session = await resume(queryFactory, { + async forkSession() { + return { sessionId: "failed-rebind" }; + }, + }); + try { + await Array.fromAsync(session.streamHistory()); + await collectSessionTurnEvents(session, "before rewind"); + await expect(session.revertConversation!({ messageId: "u2" })).rejects.toThrow( + "retirement failed", + ); + expect(records).toContainEqual( + expect.objectContaining({ + level: pino.levels.values.warn, + msg: "Failed to rebind Claude session", + sessionId: "failed-rebind", + err: expect.objectContaining({ message: "retirement failed" }), + }), + ); + expect(session.id).toBe(SESSION_ID); + const live = await collectSessionTurnEvents(session, "after failed rebind"); + expect( + live + .filter((event) => event.type === "timeline" && event.item.type === "assistant_message") + .map((event) => (event.type === "timeline" ? event.item : null)), + ).toEqual([{ type: "assistant_message", messageId: "live-reply", text: "still available" }]); + } finally { + await session.close(); + } + }); + test.each(["file_path", "files"])( "replays %s without probing targets and preserves live existence checks", async (field) => { @@ -300,21 +615,21 @@ describe("ClaudeAgentSession persisted history load", () => { ); }); - test("loads readable history when the temporary directory is unavailable", () => { + test("loads readable history when the temporary directory is unavailable", async () => { const file = transcriptPath(); const entry = { type: "assistant", message: { content: [{ type: "text", text: "saved" }] } }; mkdirSync(path.dirname(file), { recursive: true }); writeFileSync(file, JSON.stringify(entry)); const unavailable = path.join(tempRoot, "unavailable-tmp"); for (const variable of ["TMPDIR", "TEMP", "TMP"]) vi.stubEnv(variable, unavailable); - withClaudeReplayHistory(file, (history) => { - expect([...history.parentEntries]).toEqual([entry]); + await withClaudeReplayHistory(file, async (history) => { + expect(await Array.fromAsync(history.parentEntries)).toEqual([entry]); }); }); test.each(["parent", "child", "workflow"])( "preserves indexed %s history when its transcript disappears between passes", - (target) => { + async (target) => { const parent = transcriptPath(); const sessionDirectory = parent.slice(0, -".jsonl".length); const child = path.join(sessionDirectory, "subagents", "agent-child.jsonl"); @@ -334,14 +649,16 @@ describe("ClaudeAgentSession persisted history load", () => { writeFileSync(parent, JSON.stringify(parentEntry)); writeFileSync(child, JSON.stringify(childEntry)); writeFileSync(workflow, JSON.stringify(childEntry)); - withClaudeReplayHistory(parent, (history) => { + await withClaudeReplayHistory(parent, async (history) => { rmSync({ parent, child, workflow }[target]); // Ownership facts and visible payloads are separate passes over the same source. for (let pass = 0; pass < 2; pass++) { - expect([...history.parentEntries]).toEqual([parentEntry]); + expect(await Array.fromAsync(history.parentEntries)).toEqual([parentEntry]); expect(history.subagents).toHaveLength(1); - expect([...history.subagents[0]!.entries]).toEqual([childEntry]); - expect([...history.workflowEntriesByRunId.get("wf_test")!]).toEqual([childEntry]); + expect(await Array.fromAsync(history.subagents[0]!.entries)).toEqual([childEntry]); + expect(await Array.fromAsync(history.workflowEntriesByRunId.get("wf_test")!)).toEqual([ + childEntry, + ]); } }); }, diff --git a/packages/server/src/server/agent/providers/claude/agent.ts b/packages/server/src/server/agent/providers/claude/agent.ts index 201fa349eb..734272dd02 100644 --- a/packages/server/src/server/agent/providers/claude/agent.ts +++ b/packages/server/src/server/agent/providers/claude/agent.ts @@ -1,3 +1,4 @@ +import { setImmediate } from "node:timers/promises"; import { ClaudeRuntimeSafety } from "./runtime-safety.js"; import { validateProviderOptions } from "../../provider-options.js"; import type { ChildProcess } from "node:child_process"; @@ -82,7 +83,7 @@ import { type ClaudeRewindSdk, } from "./rewind.js"; import { normalizeProviderReplayTimestamp } from "../../provider-history-timestamps.js"; -import { claudeConfigDir, claudeProjectDirSync, claudeTranscriptPathSync } from "./project-dir.js"; +import { claudeConfigDir, claudeProjectDirSync, claudeTranscriptPath } from "./project-dir.js"; import { THINKING_APPLIES_NEXT_TURN_NOTICE } from "../../provider-notices.js"; import { isProviderImageMarkdown, @@ -1634,7 +1635,7 @@ export class ClaudeAgentClient implements AgentClient { cwd: merged.cwd, }; const claudeConfig = this.assertConfig(mergedConfig); - return new ClaudeAgentSession(claudeConfig, { + const session = new ClaudeAgentSession(claudeConfig, { defaults: this.defaults, runtimeSettings: this.runtimeSettings, handle, @@ -1645,6 +1646,8 @@ export class ClaudeAgentClient implements AgentClient { resolveBinary: this.resolveBinary, rewindSdk: this.rewindSdk, }); + await session.ensureHistoryReady(); + return session; } async getCatalogCacheKey(_options: FetchCatalogOptions): Promise { @@ -2329,6 +2332,9 @@ class ClaudeAgentSession implements AgentSession { { type: "provider_subagent" } >[] = []; private historyPending = false; + // Readiness never rejects; history/rebind failures are logged at their owning boundary. + private historyReady: Promise | null = null; + private historySessionId: string | null = null; private replayingHistory = false; private turnState: TurnState = "idle"; private nextTurnOrdinal = 1; @@ -2382,7 +2388,7 @@ class ClaudeAgentSession implements AgentSession { } this.claudeSessionId = handle.sessionId; this.persistence = handle; - this.loadPersistedHistory(handle.sessionId); + this.historySessionId = handle.sessionId; } else { this.claudeSessionId = null; this.persistence = null; @@ -2462,6 +2468,7 @@ class ClaudeAgentSession implements AgentSession { prompt: AgentPromptInput, options?: AgentRunOptions, ): Promise<{ turnId: string }> { + await this.ensureHistoryReady(); if (this.closed) { throw new Error("Claude session is closed"); } @@ -2632,6 +2639,7 @@ class ClaudeAgentSession implements AgentSession { } async *streamHistory(): AsyncGenerator { + await this.ensureHistoryReady(); if ( !this.historyPending || (this.persistedHistory.length === 0 && this.persistedProviderSubagentEvents.length === 0) @@ -2643,7 +2651,9 @@ class ClaudeAgentSession implements AgentSession { this.persistedHistory = []; this.persistedProviderSubagentEvents = []; this.historyPending = false; + let replayed = 0; for (const entry of history) { + if (++replayed % 32 === 0) await setImmediate(); yield { type: "timeline", item: entry.item, @@ -2961,6 +2971,7 @@ class ClaudeAgentSession implements AgentSession { "provider.claude.session_close.start", ); this.closed = true; + await this.ensureHistoryReady(); this.rejectAllPendingPermissions(new Error("Claude session closed")); this.cancelCurrentTurn?.(); this.subscribers.clear(); @@ -3001,7 +3012,7 @@ class ClaudeAgentSession implements AgentSession { // (see `claude --help`), so the SDK's persistSession=false is silently dropped // in stream-json mode. Sweep the transcript ourselves so ephemeral runs // (metadata generator, branch-name generator) don't show up as resumable. - const historyPath = this.resolveHistoryPath(this.claudeSessionId); + const historyPath = await this.resolveHistoryPath(this.claudeSessionId); if (historyPath) { try { await promises.rm(historyPath, { force: true }); @@ -3045,6 +3056,7 @@ class ClaudeAgentSession implements AgentSession { } async revertConversation(input: { messageId: string }): Promise { + await this.ensureHistoryReady(); const target = this.resolveConversationRewindTarget(input.messageId); if (target.kind === "fresh-session") { this.startFreshConversationSession(); @@ -3054,16 +3066,15 @@ class ClaudeAgentSession implements AgentSession { await revertClaudeConversation({ sdk: this.rewindSdk, sessionId: currentSessionId, - transcriptPath: currentSessionId ? this.resolveHistoryPath(currentSessionId) : null, + transcriptPath: currentSessionId ? await this.resolveHistoryPath(currentSessionId) : null, messageId: target.messageId, resolveMessageId: (messageId) => this.resolveClaudeMessageId(messageId), - setSessionId: (sessionId) => { - this.rebindConversationSession(sessionId); - }, + setSessionId: (sessionId) => this.rebindConversationSession(sessionId), }); } async revertFiles(input: { messageId: string }): Promise { + await this.ensureHistoryReady(); const messageId = await this.resolveClaudeMessageId(input.messageId); await revertClaudeFiles({ query: await this.ensureQuery(), @@ -3238,38 +3249,52 @@ class ClaudeAgentSession implements AgentSession { return candidates; } - private rebindConversationSession(sessionId: string): void { - const oldSessionId = this.claudeSessionId; - this.claudeSessionId = sessionId; - this.pendingFreshSessionId = null; - this.persistence = null; - this.cachedRuntimeInfo = null; - this.queryRestartNeeded = true; - this.persistedHistory = []; - this.persistedProviderSubagentEvents = []; - this.historyPending = false; - this.userMessageIds = []; - this.emittedUserMessageIds.clear(); - this.rewindTurnAnchors.length = 0; - this.taskState.reset(); - this.loadPersistedHistory(sessionId); - if (oldSessionId && oldSessionId !== sessionId) { - this.dispatchEvents([ - { - type: "timeline", - provider: "claude", - item: this.createClaudeSessionChangedNotice(oldSessionId, sessionId), - }, - { - type: "thread_started", - provider: "claude", - sessionId, - }, - ]); - } + private rebindConversationSession(sessionId: string): Promise { + const previousReady = this.ensureHistoryReady(); + const rebind = (async () => { + await previousReady; + await this.retireQuery(); + if (this.closed) return; + const oldSessionId = this.claudeSessionId; + this.claudeSessionId = sessionId; + this.pendingFreshSessionId = null; + this.persistence = null; + this.cachedRuntimeInfo = null; + this.queryRestartNeeded = true; + this.persistedHistory = []; + this.persistedProviderSubagentEvents = []; + this.historyPending = false; + this.userMessageIds = []; + this.emittedUserMessageIds.clear(); + this.rewindTurnAnchors.length = 0; + this.taskState.reset(); + this.historySessionId = sessionId; + await this.loadPersistedHistory(sessionId); + if (this.closed) return; + if (oldSessionId && oldSessionId !== sessionId) { + this.dispatchEvents([ + { + type: "timeline", + provider: "claude", + item: this.createClaudeSessionChangedNotice(oldSessionId, sessionId), + }, + { + type: "thread_started", + provider: "claude", + sessionId, + }, + ]); + } + })(); + this.historyReady = rebind.catch((error) => { + this.logger.warn({ err: error, sessionId }, "Failed to rebind Claude session"); + }); + return rebind; } private startFreshConversationSession(): void { + this.historySessionId = null; + this.historyReady = Promise.resolve(); const sessionId = randomUUID(); this.claudeSessionId = sessionId; this.pendingFreshSessionId = sessionId; @@ -3390,7 +3415,43 @@ class ClaudeAgentSession implements AgentSession { return { kind: "fresh-session" }; } + private async retireQuery(): Promise { + const oldQuery = this.query; + if (!oldQuery) return; + const oldInput = this.input; + // Null out query/input BEFORE awaiting the old iterator's return so the + // old pump sees this.query !== activeQuery and skips failActiveTurns. + this.query = null; + this.input = null; + this.queryPumpPromise = null; + this.queryRestartNeeded = false; + // Ending the input retires the process on purpose. Detach first so its + // exit is not reported as a crash. + const retiredChild = this.childProcess; + this.childProcess = null; + if (retiredChild) this.failRunningRuntimeTasks(); + oldInput?.end(); + oldQuery.close?.(); + try { + await oldQuery.return?.(); + } catch { + /* ignore */ + } + // Tree-kill the old process tree now that the SDK has cleaned up. + // If we skip this, MCP children of the previous claude process can + // survive as orphans when the session spawns a replacement query. + if (retiredChild) { + await terminateWithTreeKill(retiredChild, { + gracefulTimeoutMs: 2_000, + forceTimeoutMs: 2_000, + }).catch(() => { + /* process may already be dead */ + }); + } + } + private async ensureQuery(launchMode: PermissionMode = this.currentMode): Promise { + await this.ensureHistoryReady(); // Controls use the running turn's query. Pending launch settings take effect // after that turn finishes, when its active query handle has been cleared. if (this.query && (!this.queryRestartNeeded || this.activeForegroundQuery === this.query)) { @@ -3398,37 +3459,7 @@ class ClaudeAgentSession implements AgentSession { } if (this.queryRestartNeeded && this.query) { - const oldQuery = this.query; - const oldInput = this.input; - // Null out query/input BEFORE awaiting the old iterator's return so the - // old pump sees this.query !== activeQuery and skips failActiveTurns. - this.query = null; - this.input = null; - this.queryPumpPromise = null; - this.queryRestartNeeded = false; - // Ending the input retires the process on purpose. Detach first so its - // exit is not reported as a crash. - const retiredChild = this.childProcess; - this.childProcess = null; - if (retiredChild) this.failRunningRuntimeTasks(); - oldInput?.end(); - oldQuery.close?.(); - try { - await oldQuery.return?.(); - } catch { - /* ignore */ - } - // Tree-kill the old process tree now that the SDK has cleaned up. - // If we skip this, MCP children of the previous claude process can - // survive as orphans when the session spawns a replacement query. - if (retiredChild) { - await terminateWithTreeKill(retiredChild, { - gracefulTimeoutMs: 2_000, - forceTimeoutMs: 2_000, - }).catch(() => { - /* process may already be dead */ - }); - } + await this.retireQuery(); } // Preserve claudeSessionId across query recreation so buildOptions() passes @@ -4095,13 +4126,15 @@ class ClaudeAgentSession implements AgentSession { ); }; const handlePumpedMessage = async (message: SDKMessage): Promise => { + if (!this.ownsQuery(activeQuery)) return true; this.processingSdkMessages++; try { this.runtimeSafety.observe(message); logRawMessage(message); consecutiveInterruptAbortRecoveries = 0; if (await this.handleMissingResumedConversation(message, activeQuery)) return true; - await this.routeSdkMessageFromPump(message); + if (!this.ownsQuery(activeQuery)) return true; + this.routeSdkMessageFromPump(message); return false; } finally { this.processingSdkMessages--; @@ -4221,7 +4254,11 @@ class ClaudeAgentSession implements AgentSession { return isClaudeTurnInit(message) && !this.activeForegroundTurnId; } - private async routeSdkMessageFromPump(message: SDKMessage): Promise { + private ownsQuery(query: Query): boolean { + return !this.closed && this.query === query; + } + + private routeSdkMessageFromPump(message: SDKMessage): void { if (this.consumeSessionStateChange(message)) { return; } @@ -4255,7 +4292,7 @@ class ClaudeAgentSession implements AgentSession { "provider.claude.parsed_event", ); - const events = await this.buildPumpedMessageEvents(message, identifiers.messageId, turnId); + const events = this.buildPumpedMessageEvents(message, identifiers.messageId, turnId); if (events.length === 0) { return; @@ -4290,11 +4327,11 @@ class ClaudeAgentSession implements AgentSession { this.dispatchEvents(events); } - private async buildPumpedMessageEvents( + private buildPumpedMessageEvents( message: SDKMessage, messageIdHint: string | null, turnId: string | null, - ): Promise { + ): AgentStreamEvent[] { const messageEvents = this.translateMessageToEvents(message, { suppressAssistantText: true, suppressReasoning: true, @@ -5272,22 +5309,31 @@ class ClaudeAgentSession implements AgentSession { } } - private loadPersistedHistory(sessionId: string): void { + ensureHistoryReady(): Promise { + if (!this.historyReady) { + this.historyReady = this.historySessionId + ? this.loadPersistedHistory(this.historySessionId) + : Promise.resolve(); + } + return this.historyReady; + } + + private async loadPersistedHistory(sessionId: string): Promise { let historyPath: string | null = null; this.replayingHistory = true; try { this.taskState.reset(); - historyPath = this.resolveHistoryPath(sessionId); - if (!historyPath || !fs.existsSync(historyPath)) { + historyPath = await this.resolveHistoryPath(sessionId); + if (!historyPath || !(await transcriptExists(historyPath))) { this.logger.info( { sessionId, cwd: this.config.cwd, historyPath }, "No Claude transcript to load history from", ); return; } - withClaudeReplayHistory(historyPath, (history) => { - const replay = this.ingestPersistedSidechains(history); - this.ingestPersistedHistory(history.parentEntries, replay); + await withClaudeReplayHistory(historyPath, async (history) => { + const replay = await this.ingestPersistedSidechains(history); + await this.ingestPersistedHistory(history.parentEntries, replay); }); } catch (error) { this.logger.warn( @@ -5299,12 +5345,12 @@ class ClaudeAgentSession implements AgentSession { } } - private ingestPersistedHistory( - entries: Iterable, + private async ingestPersistedHistory( + entries: Iterable | AsyncIterable, replay: ClaudeReplayOwnership, - ): void { + ): Promise { const timeline: PersistedTimelineEntry[] = []; - for (const entry of entries) { + for await (const entry of entries) { this.ingestPersistedHistoryEntry(entry, timeline, replay); } @@ -5314,27 +5360,33 @@ class ClaudeAgentSession implements AgentSession { } } - private ingestPersistedSidechains(history: ClaudeReplayHistory): ClaudeReplayOwnership { - const parentFacts = readClaudeReplayParentFacts(history.parentEntries); + private async ingestPersistedSidechains( + history: ClaudeReplayHistory, + ): Promise { + const parentFacts = await readClaudeReplayParentFacts(history.parentEntries); // Replay produces the same observations the live task protocol produces, then folds them // with the same function, so identity and status are derived once for both paths. - const subagentReplay = observeReplaySubagents({ - subagents: history.subagents.map((subagent) => ({ + const subagents = []; + for (const subagent of history.subagents) { + subagents.push({ ...subagent, - parentFacts: readClaudeReplayParentFacts(subagent.entries), - })), + parentFacts: await readClaudeReplayParentFacts(subagent.entries), + }); + } + const subagentReplay = await observeReplaySubagents({ + subagents, parent: parentFacts, convertEntry: (entry) => this.convertHistoryEntry(entry), }); const observations = [ ...subagentReplay.observations, - ...observeReplayWorkflows({ + ...(await observeReplayWorkflows({ workflows: history.workflows, parentEntries: history.parentEntries, entriesByRunId: history.workflowEntriesByRunId, convertEntry: (entry) => this.convertHistoryEntry(entry), - }), + })), ]; const restoredProviderSubagentIds = new Set( observations @@ -5421,10 +5473,10 @@ class ClaudeAgentSession implements AgentSession { } } - private resolveHistoryPath(sessionId: string): string | null { + private async resolveHistoryPath(sessionId: string): Promise { const cwd = this.config.cwd; if (!cwd) return null; - return claudeTranscriptPathSync({ + return claudeTranscriptPath({ cwd, sessionId, configDir: claudeConfigDir(this.harnessEnvironment), @@ -6191,13 +6243,13 @@ function labelReplayedSubagentCard( * source consumes. The agentId scrape is kept only as a fallback for sessions recorded before * Claude Code wrote the meta sidecar. */ -function readClaudeReplayParentFacts( - entries: Iterable, -): ClaudeReplayParentFacts { +async function readClaudeReplayParentFacts( + entries: Iterable | AsyncIterable, +): Promise { const toolCalls = new Map(); const linksByAgentId = new Map(); const outcomes = new Map(); - for (const entry of entries) { + for await (const entry of entries) { const content = toObjectRecord(entry.message)?.content; if (!Array.isArray(content)) continue; for (const value of content) { @@ -6729,7 +6781,7 @@ async function readClaudeRenamedSessionTitle(input: { }): Promise { let content: string; try { - content = await fsPromises.readFile(claudeTranscriptPathSync(input), "utf8"); + content = await fsPromises.readFile(await claudeTranscriptPath(input), "utf8"); } catch (error) { // A session with no transcript on disk has no rename to carry over. Every // other read failure is a real fault and stays explicit. @@ -6829,3 +6881,13 @@ function readClaudeCommandLifecycle(message: unknown): ClaudeCommandLifecycle | state: record.state as ClaudeCommandLifecycle["state"], }; } + +async function transcriptExists(file: string): Promise { + try { + await fs.promises.access(file); + return true; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; + throw error; + } +} diff --git a/packages/server/src/server/agent/providers/claude/project-dir.ts b/packages/server/src/server/agent/providers/claude/project-dir.ts index 030a54c813..c9fa690101 100644 --- a/packages/server/src/server/agent/providers/claude/project-dir.ts +++ b/packages/server/src/server/agent/providers/claude/project-dir.ts @@ -1,5 +1,5 @@ -import { existsSync, readdirSync, realpathSync } from "node:fs"; -import { realpath } from "node:fs/promises"; +import { realpathSync } from "node:fs"; +import { realpath, access, readdir } from "node:fs/promises"; import { homedir } from "node:os"; import { join } from "node:path"; @@ -35,21 +35,21 @@ export function claudeProjectDirSync(cwd: string, options?: ClaudeProjectDirOpti // one `cwd` encodes to when the project moved, the daemon migrated, or Claude Code sees the // cwd under another name (a Windows binary under WSL). Returns the expected path when no // transcript exists anywhere. -export function claudeTranscriptPathSync(input: { +export async function claudeTranscriptPath(input: { cwd: string; sessionId: string; configDir?: string; -}): string { +}): Promise { const options = { configDir: input.configDir }; const fileName = `${input.sessionId}.jsonl`; - const expected = join(claudeProjectDirSync(input.cwd, options), fileName); - if (existsSync(expected)) { + const expected = join(await claudeProjectDir(input.cwd, options), fileName); + if (await exists(expected)) { return expected; } const projectsRoot = join(resolveConfigDir(options), "projects"); let projectDirs: string[]; try { - projectDirs = readdirSync(projectsRoot); + projectDirs = await readdir(projectsRoot); } catch (error) { if (isMissingDirectoryError(error)) { return expected; @@ -58,13 +58,23 @@ export function claudeTranscriptPathSync(input: { } for (const projectDir of projectDirs) { const candidate = join(projectsRoot, projectDir, fileName); - if (existsSync(candidate)) { + if (await exists(candidate)) { return candidate; } } return expected; } +async function exists(file: string): Promise { + try { + await access(file); + return true; + } catch (error) { + if (isMissingDirectoryError(error)) return false; + throw error; + } +} + function isMissingDirectoryError(error: unknown): boolean { const code = (error as NodeJS.ErrnoException | null)?.code; return code === "ENOENT" || code === "ENOTDIR"; diff --git a/packages/server/src/server/agent/providers/claude/rewind.ts b/packages/server/src/server/agent/providers/claude/rewind.ts index 3b228aacc6..91183687e0 100644 --- a/packages/server/src/server/agent/providers/claude/rewind.ts +++ b/packages/server/src/server/agent/providers/claude/rewind.ts @@ -76,7 +76,7 @@ export async function revertClaudeConversation(input: { transcriptPath: string | null; messageId: string; resolveMessageId?: (messageId: string) => string | Promise; - setSessionId: (sessionId: string) => void; + setSessionId: (sessionId: string) => void | Promise; }): Promise { if (!input.sessionId || !input.transcriptPath) { throw new Error("Claude session is not ready for rewind"); @@ -86,7 +86,7 @@ export async function revertClaudeConversation(input: { upToMessageId: messageId, transcriptPath: input.transcriptPath, }); - input.setSessionId(fork.sessionId); + await input.setSessionId(fork.sessionId); } export async function revertClaudeFiles(input: { @@ -108,7 +108,7 @@ export async function revertClaudeConversationAndFiles(input: { transcriptPath: string | null; messageId: string; resolveMessageId?: (messageId: string) => string | Promise; - setSessionId: (sessionId: string) => void; + setSessionId: (sessionId: string) => void | Promise; }): Promise { await revertClaudeFiles({ query: input.query, diff --git a/packages/server/src/server/agent/providers/claude/subagents/replay-source.test.ts b/packages/server/src/server/agent/providers/claude/subagents/replay-source.test.ts index e28d15b8c1..413f39d427 100644 --- a/packages/server/src/server/agent/providers/claude/subagents/replay-source.test.ts +++ b/packages/server/src/server/agent/providers/claude/subagents/replay-source.test.ts @@ -45,7 +45,7 @@ function applyToStore(observations: SubagentObservation[]): ProviderSubagentDesc } describe("parseClaudeSubagentMeta", () => { - it("reads the real sidecar shape", () => { + it("reads the real sidecar shape", async () => { expect( parseClaudeSubagentMeta( '{"agentType":"general-purpose","description":"Reply banana","toolUseId":"toolu_013i","spawnDepth":1}', @@ -68,7 +68,7 @@ describe("parseClaudeSubagentMeta", () => { expect(parseClaudeSubagentMeta(contents)).toBeNull(); }); - it("keeps the good fields when one field has the wrong type", () => { + it("keeps the good fields when one field has the wrong type", async () => { expect(parseClaudeSubagentMeta('{"agentType":"Explore","toolUseId":42}')).toEqual({ agentType: "Explore", description: undefined, @@ -79,12 +79,14 @@ describe("parseClaudeSubagentMeta", () => { }); describe("observeReplaySubagents", () => { - it("links a subagent to its Task call through meta.toolUseId", () => { - const observations = observeReplaySubagents({ - subagents: [{ agentId: AGENT_ID, meta: { toolUseId: TOOL_USE_ID }, entries: [] }], - parent: parentWithTaskCall(), - convertEntry: () => [], - }).observations; + it("links a subagent to its Task call through meta.toolUseId", async () => { + const observations = ( + await observeReplaySubagents({ + subagents: [{ agentId: AGENT_ID, meta: { toolUseId: TOOL_USE_ID }, entries: [] }], + parent: parentWithTaskCall(), + convertEntry: () => [], + }) + ).observations; expect(observations[0]).toMatchObject({ kind: "declared", @@ -95,31 +97,33 @@ describe("observeReplaySubagents", () => { }); }); - it("replays descendants beneath the sidechain that declared their Task", () => { + it("replays descendants beneath the sidechain that declared their Task", async () => { const nestedToolUseId = "toolu_012rzYnFZA"; - const observations = observeReplaySubagents({ - subagents: [ - { - agentId: AGENT_ID, - meta: { toolUseId: TOOL_USE_ID, spawnDepth: 1 }, - entries: [], - parentFacts: { - toolCalls: new Map([ - [nestedToolUseId, { title: "Explore", description: "Nested audit" }], - ]), - linksByAgentId: new Map(), - outcomesByToolCallId: new Map([[nestedToolUseId, { failed: false }]]), + const observations = ( + await observeReplaySubagents({ + subagents: [ + { + agentId: AGENT_ID, + meta: { toolUseId: TOOL_USE_ID, spawnDepth: 1 }, + entries: [], + parentFacts: { + toolCalls: new Map([ + [nestedToolUseId, { title: "Explore", description: "Nested audit" }], + ]), + linksByAgentId: new Map(), + outcomesByToolCallId: new Map([[nestedToolUseId, { failed: false }]]), + }, }, - }, - { - agentId: "a6acb4b898", - meta: { toolUseId: nestedToolUseId, agentType: "Explore", spawnDepth: 2 }, - entries: [], - }, - ], - parent: parentWithTaskCall(), - convertEntry: () => [], - }).observations; + { + agentId: "a6acb4b898", + meta: { toolUseId: nestedToolUseId, agentType: "Explore", spawnDepth: 2 }, + entries: [], + }, + ], + parent: parentWithTaskCall(), + convertEntry: () => [], + }) + ).observations; expect(observations).toContainEqual( expect.objectContaining({ @@ -130,89 +134,143 @@ describe("observeReplaySubagents", () => { ); }); - it("keeps a subagent recorded before spawnDepth existed", () => { - const observations = observeReplaySubagents({ - subagents: [{ agentId: AGENT_ID, meta: { toolUseId: TOOL_USE_ID }, entries: [] }], - parent: parentWithTaskCall(), - convertEntry: () => [], - }).observations; + it("keeps a subagent recorded before spawnDepth existed", async () => { + const observations = ( + await observeReplaySubagents({ + subagents: [{ agentId: AGENT_ID, meta: { toolUseId: TOOL_USE_ID }, entries: [] }], + parent: parentWithTaskCall(), + convertEntry: () => [], + }) + ).observations; expect(observations[0]).toMatchObject({ kind: "declared", id: TOOL_USE_ID }); }); - it("drops a meta-linked subagent when the parent never declared its Task", () => { - const observations = observeReplaySubagents({ - subagents: [ - { - agentId: AGENT_ID, - meta: { toolUseId: TOOL_USE_ID, agentType: "Explore", description: "Find the code" }, - entries: [], - }, - ], - parent: emptyParent(), - convertEntry: () => [], - }).observations; + it("drops a meta-linked subagent when the parent never declared its Task", async () => { + const observations = ( + await observeReplaySubagents({ + subagents: [ + { + agentId: AGENT_ID, + meta: { toolUseId: TOOL_USE_ID, agentType: "Explore", description: "Find the code" }, + entries: [], + }, + ], + parent: emptyParent(), + convertEntry: () => [], + }) + ).observations; expect(observations).toEqual([]); }); - it("falls back to the scraped link when there is no meta file", () => { + it("falls back to the scraped link when there is no meta file", async () => { const parent: ClaudeReplayParentFacts = { toolCalls: new Map([[TOOL_USE_ID, { title: "Explore" }]]), linksByAgentId: new Map([[AGENT_ID, { toolCallId: TOOL_USE_ID, failed: false }]]), outcomesByToolCallId: new Map(), }; - const [declared, ...rest] = observeReplaySubagents({ - subagents: [{ agentId: AGENT_ID, meta: null, entries: [] }], - parent, - convertEntry: () => [], - }).observations; + const [declared, ...rest] = ( + await observeReplaySubagents({ + subagents: [{ agentId: AGENT_ID, meta: null, entries: [] }], + parent, + convertEntry: () => [], + }) + ).observations; expect(declared).toMatchObject({ id: TOOL_USE_ID, toolCallId: TOOL_USE_ID, title: "Explore" }); expect(rest.at(-1)).toMatchObject({ kind: "status", status: "completed" }); }); - it("drops an unlinkable subagent", () => { - const observations = observeReplaySubagents({ - subagents: [{ agentId: AGENT_ID, meta: null, entries: [] }], - parent: emptyParent(), - convertEntry: () => [], - }).observations; + it("drops an unlinkable subagent", async () => { + const observations = ( + await observeReplaySubagents({ + subagents: [{ agentId: AGENT_ID, meta: null, entries: [] }], + parent: emptyParent(), + convertEntry: () => [], + }) + ).observations; expect(observations).toEqual([]); }); - it("drops a terminal subagent the parent has no Task call for", () => { + it("drops a terminal subagent the parent has no Task call for", async () => { // A legacy grandchild: its toolUseId names a Task call made inside a sibling's transcript, so // no tool_result for it can ever reach the parent. Left running, it never stops. const descriptor = applyToStore( - observeReplaySubagents({ - subagents: [ - { - agentId: AGENT_ID, - meta: { toolUseId: TOOL_USE_ID }, - entries: [ - { - type: "assistant", - timestamp: "2026-07-31T03:41:00.000Z", - message: { stop_reason: "end_turn" }, - }, - ], - }, - ], - parent: emptyParent(), - convertEntry: () => [], - }).observations, + ( + await observeReplaySubagents({ + subagents: [ + { + agentId: AGENT_ID, + meta: { toolUseId: TOOL_USE_ID }, + entries: [ + { + type: "assistant", + timestamp: "2026-07-31T03:41:00.000Z", + message: { stop_reason: "end_turn" }, + }, + ], + }, + ], + parent: emptyParent(), + convertEntry: () => [], + }) + ).observations, ); expect(descriptor).toBeNull(); }); - it("drops a terminal skill-spawned subagent that has no link at all", () => { + it("drops a terminal skill-spawned subagent that has no link at all", async () => { // A /code-review run: no Task tool_use exists to name it, so its sidecar carries only // agentType and its id appears nowhere in the parent transcript. const descriptor = applyToStore( - observeReplaySubagents({ + ( + await observeReplaySubagents({ + subagents: [ + { + agentId: AGENT_ID, + meta: { agentType: "general-purpose" }, + entries: [ + { + type: "assistant", + timestamp: "2026-07-31T03:41:00.000Z", + message: { stop_reason: "end_turn" }, + }, + ], + }, + ], + parent: emptyParent(), + convertEntry: () => [], + }) + ).observations, + ); + + expect(descriptor).toBeNull(); + }); + + it("reports a scraped link's failure as failed", async () => { + const descriptor = applyToStore( + ( + await observeReplaySubagents({ + subagents: [{ agentId: AGENT_ID, meta: null, entries: [] }], + parent: { + toolCalls: new Map([[TOOL_USE_ID, { title: "Explore" }]]), + linksByAgentId: new Map([[AGENT_ID, { toolCallId: TOOL_USE_ID, failed: true }]]), + outcomesByToolCallId: new Map(), + }, + convertEntry: () => [], + }) + ).observations, + ); + + expect(descriptor).toMatchObject({ id: TOOL_USE_ID, status: "failed" }); + }); + + it("drops a non-terminal linkless subagent", async () => { + const observations = ( + await observeReplaySubagents({ subagents: [ { agentId: AGENT_ID, @@ -221,111 +279,81 @@ describe("observeReplaySubagents", () => { { type: "assistant", timestamp: "2026-07-31T03:41:00.000Z", - message: { stop_reason: "end_turn" }, + message: { stop_reason: null }, }, ], }, ], parent: emptyParent(), convertEntry: () => [], - }).observations, - ); - - expect(descriptor).toBeNull(); - }); - - it("reports a scraped link's failure as failed", () => { - const descriptor = applyToStore( - observeReplaySubagents({ - subagents: [{ agentId: AGENT_ID, meta: null, entries: [] }], - parent: { - toolCalls: new Map([[TOOL_USE_ID, { title: "Explore" }]]), - linksByAgentId: new Map([[AGENT_ID, { toolCallId: TOOL_USE_ID, failed: true }]]), - outcomesByToolCallId: new Map(), - }, - convertEntry: () => [], - }).observations, - ); - - expect(descriptor).toMatchObject({ id: TOOL_USE_ID, status: "failed" }); - }); - - it("drops a non-terminal linkless subagent", () => { - const observations = observeReplaySubagents({ - subagents: [ - { - agentId: AGENT_ID, - meta: { agentType: "general-purpose" }, - entries: [ - { - type: "assistant", - timestamp: "2026-07-31T03:41:00.000Z", - message: { stop_reason: null }, - }, - ], - }, - ], - parent: emptyParent(), - convertEntry: () => [], - }).observations; + }) + ).observations; expect(observations).toEqual([]); }); - it("finishes a terminal Task child when the parent has not recorded its outcome", () => { + it("finishes a terminal Task child when the parent has not recorded its outcome", async () => { const descriptor = applyToStore( - observeReplaySubagents({ - subagents: [ - { - agentId: AGENT_ID, - meta: { toolUseId: TOOL_USE_ID }, - entries: [ - { - type: "assistant", - timestamp: "2026-07-31T03:41:00.000Z", - message: { stop_reason: "end_turn" }, - }, - ], - }, - ], - parent: { ...parentWithTaskCall(), outcomesByToolCallId: new Map() }, - convertEntry: () => [], - }).observations, + ( + await observeReplaySubagents({ + subagents: [ + { + agentId: AGENT_ID, + meta: { toolUseId: TOOL_USE_ID }, + entries: [ + { + type: "assistant", + timestamp: "2026-07-31T03:41:00.000Z", + message: { stop_reason: "end_turn" }, + }, + ], + }, + ], + parent: { ...parentWithTaskCall(), outcomesByToolCallId: new Map() }, + convertEntry: () => [], + }) + ).observations, ); expect(descriptor).toMatchObject({ status: "completed" }); }); - it("leaves a subagent with no recorded outcome running", () => { - const observations = observeReplaySubagents({ - subagents: [{ agentId: AGENT_ID, meta: { toolUseId: TOOL_USE_ID }, entries: [] }], - parent: { ...parentWithTaskCall(), outcomesByToolCallId: new Map() }, - convertEntry: () => [], - }).observations; + it("leaves a subagent with no recorded outcome running", async () => { + const observations = ( + await observeReplaySubagents({ + subagents: [{ agentId: AGENT_ID, meta: { toolUseId: TOOL_USE_ID }, entries: [] }], + parent: { ...parentWithTaskCall(), outcomesByToolCallId: new Map() }, + convertEntry: () => [], + }) + ).observations; expect(observations.some((o) => o.kind === "status")).toBe(false); }); - it("reports a failed outcome as failed", () => { - const observations = observeReplaySubagents({ - subagents: [{ agentId: AGENT_ID, meta: { toolUseId: TOOL_USE_ID }, entries: [] }], - parent: parentWithTaskCall(true), - convertEntry: () => [], - }).observations; + it("reports a failed outcome as failed", async () => { + const observations = ( + await observeReplaySubagents({ + subagents: [{ agentId: AGENT_ID, meta: { toolUseId: TOOL_USE_ID }, entries: [] }], + parent: parentWithTaskCall(true), + convertEntry: () => [], + }) + ).observations; expect(observations.at(-1)).toMatchObject({ kind: "status", status: "failed" }); }); - it("carries entry timestamps onto timeline observations", () => { - const observations = observeReplaySubagents({ - subagents: [ - { - agentId: AGENT_ID, - meta: { toolUseId: TOOL_USE_ID }, - entries: [{ type: "assistant", timestamp: "2026-07-26T06:27:47.034Z" }], - }, - ], - parent: parentWithTaskCall(), - convertEntry: () => [{ type: "reasoning", text: "thinking" }], - }).observations; + it("carries entry timestamps onto timeline observations", async () => { + const observations = ( + await observeReplaySubagents({ + subagents: [ + { + agentId: AGENT_ID, + meta: { toolUseId: TOOL_USE_ID }, + entries: [{ type: "assistant", timestamp: "2026-07-26T06:27:47.034Z" }], + }, + ], + parent: parentWithTaskCall(), + convertEntry: () => [{ type: "reasoning", text: "thinking" }], + }) + ).observations; expect(observations.find((observation) => observation.kind === "timeline")).toMatchObject({ kind: "timeline", @@ -336,18 +364,20 @@ describe("observeReplaySubagents", () => { }); describe("replay runtime", () => { - it("reads the model and effort off the subagent's own transcript", () => { - const observations = observeReplaySubagents({ - subagents: [ - { - agentId: AGENT_ID, - meta: { toolUseId: TOOL_USE_ID }, - entries: [{ type: "assistant", effort: "high", message: { model: "claude-opus-5" } }], - }, - ], - parent: parentWithTaskCall(), - convertEntry: () => [], - }).observations; + it("reads the model and effort off the subagent's own transcript", async () => { + const observations = ( + await observeReplaySubagents({ + subagents: [ + { + agentId: AGENT_ID, + meta: { toolUseId: TOOL_USE_ID }, + entries: [{ type: "assistant", effort: "high", message: { model: "claude-opus-5" } }], + }, + ], + parent: parentWithTaskCall(), + convertEntry: () => [], + }) + ).observations; expect(observations.find((o) => o.kind === "subtitle")).toEqual({ kind: "subtitle", @@ -356,49 +386,55 @@ describe("replay runtime", () => { }); }); - it("takes the last observed values when the model changes mid-transcript", () => { - const observations = observeReplaySubagents({ - subagents: [ - { - agentId: AGENT_ID, - meta: { toolUseId: TOOL_USE_ID }, - entries: [ - { type: "assistant", effort: "high", message: { model: "claude-opus-5" } }, - { type: "assistant", effort: "low", message: { model: "claude-sonnet-5" } }, - ], - }, - ], - parent: parentWithTaskCall(), - convertEntry: () => [], - }).observations; + it("takes the last observed values when the model changes mid-transcript", async () => { + const observations = ( + await observeReplaySubagents({ + subagents: [ + { + agentId: AGENT_ID, + meta: { toolUseId: TOOL_USE_ID }, + entries: [ + { type: "assistant", effort: "high", message: { model: "claude-opus-5" } }, + { type: "assistant", effort: "low", message: { model: "claude-sonnet-5" } }, + ], + }, + ], + parent: parentWithTaskCall(), + convertEntry: () => [], + }) + ).observations; expect(observations.find((o) => o.kind === "subtitle")).toMatchObject({ subtitle: "general-purpose · Sonnet 5 · Low", }); }); - it("reports nothing when the transcript never names a model or effort", () => { - const observations = observeReplaySubagents({ - subagents: [{ agentId: AGENT_ID, meta: { toolUseId: TOOL_USE_ID }, entries: [] }], - parent: parentWithTaskCall(), - convertEntry: () => [], - }).observations; + it("reports nothing when the transcript never names a model or effort", async () => { + const observations = ( + await observeReplaySubagents({ + subagents: [{ agentId: AGENT_ID, meta: { toolUseId: TOOL_USE_ID }, entries: [] }], + parent: parentWithTaskCall(), + convertEntry: () => [], + }) + ).observations; expect(observations.some((o) => o.kind === "subtitle")).toBe(false); }); - it("passes through a model the manifest does not know", () => { + it("passes through a model the manifest does not know", async () => { // Claude Code is an Anthropic-compatible client; subagents legitimately report other models. - const observations = observeReplaySubagents({ - subagents: [ - { - agentId: AGENT_ID, - meta: { toolUseId: TOOL_USE_ID }, - entries: [{ type: "assistant", message: { model: "glm-5.1" } }], - }, - ], - parent: parentWithTaskCall(), - convertEntry: () => [], - }).observations; + const observations = ( + await observeReplaySubagents({ + subagents: [ + { + agentId: AGENT_ID, + meta: { toolUseId: TOOL_USE_ID }, + entries: [{ type: "assistant", message: { model: "glm-5.1" } }], + }, + ], + parent: parentWithTaskCall(), + convertEntry: () => [], + }) + ).observations; expect(observations.find((o) => o.kind === "subtitle")).toMatchObject({ subtitle: "general-purpose · glm-5.1", }); @@ -406,20 +442,24 @@ describe("replay runtime", () => { }); describe("replay usage", () => { - function subtitleOf(entries: ClaudeReplayEntry[]): SubagentObservation | undefined { - return observeReplaySubagents({ - subagents: [{ agentId: AGENT_ID, meta: { toolUseId: TOOL_USE_ID }, entries }], - parent: parentWithTaskCall(), - convertEntry: () => [], - }).observations.find((observation) => observation.kind === "subtitle"); + async function subtitleOf( + entries: ClaudeReplayEntry[], + ): Promise { + return ( + await observeReplaySubagents({ + subagents: [{ agentId: AGENT_ID, meta: { toolUseId: TOOL_USE_ID }, entries }], + parent: parentWithTaskCall(), + convertEntry: () => [], + }) + ).observations.find((observation) => observation.kind === "subtitle"); } - it("derives the counters Claude Code itself reports, from a real transcript's shape", () => { + it("derives the counters Claude Code itself reports, from a real transcript's shape", async () => { // Shape and numbers taken from an on-disk subagent transcript. Claude Code finalizes a // subagent from the LAST assistant entry's usage, so the earlier, smaller turn must not win // and must not be added in. expect( - subtitleOf([ + await subtitleOf([ { type: "assistant", timestamp: "2026-07-23T23:18:43.023Z", @@ -462,9 +502,9 @@ describe("replay usage", () => { }); }); - it("formats tokens for a child that only answered", () => { + it("formats tokens for a child that only answered", async () => { expect( - subtitleOf([ + await subtitleOf([ { type: "assistant", timestamp: "2026-07-27T16:42:14.698Z", @@ -479,12 +519,12 @@ describe("replay usage", () => { ).toMatchObject({ subtitle: "general-purpose · 16.4k tokens" }); }); - it("emits nothing for a transcript with no entries", () => { - expect(subtitleOf([])).toBeUndefined(); + it("emits nothing for a transcript with no entries", async () => { + expect(await subtitleOf([])).toBeUndefined(); }); - it("keeps duration out of the compact subtitle", () => { - const observation = subtitleOf([ + it("keeps duration out of the compact subtitle", async () => { + const observation = await subtitleOf([ { type: "assistant", timestamp: "2026-07-27T16:42:14.698Z", @@ -494,8 +534,8 @@ describe("replay usage", () => { expect(observation).toMatchObject({ subtitle: "general-purpose · 10 tokens" }); }); - it("omits totalTokens when no entry carries a usage block", () => { - const observation = subtitleOf([ + it("omits totalTokens when no entry carries a usage block", async () => { + const observation = await subtitleOf([ { type: "assistant", timestamp: "2026-07-27T16:42:14.698Z", message: { content: [] } }, { type: "assistant", @@ -506,9 +546,9 @@ describe("replay usage", () => { expect(observation).toBeUndefined(); }); - it("keeps the last usage-bearing entry when the final assistant entry has none", () => { + it("keeps the last usage-bearing entry when the final assistant entry has none", async () => { expect( - subtitleOf([ + await subtitleOf([ { type: "assistant", timestamp: "2026-07-27T16:42:14.698Z", @@ -519,34 +559,36 @@ describe("replay usage", () => { ).toMatchObject({ subtitle: "general-purpose · 1k tokens" }); }); - it("only reports counters the transcript actually shows", () => { + it("only reports counters the transcript actually shows", async () => { // A user-only transcript says nothing about cost: no assistant turn, so no tool count either. - const observation = subtitleOf([ + const observation = await subtitleOf([ { type: "user", timestamp: "2026-07-27T16:42:14.698Z", message: { content: "prompt" } }, { type: "user", timestamp: "2026-07-27T16:42:20.000Z", message: { content: "more" } }, ]); expect(observation).toBeUndefined(); }); - it("lands the complete provider-owned subtitle on the descriptor", () => { + it("lands the complete provider-owned subtitle on the descriptor", async () => { const store = new ProviderSubagentStore(); - const observations = observeReplaySubagents({ - subagents: [ - { - agentId: AGENT_ID, - meta: { toolUseId: TOOL_USE_ID }, - entries: [ - { - type: "assistant", - timestamp: "2026-07-27T16:42:14.698Z", - message: { content: [], usage: { input_tokens: 7 } }, - }, - ], - }, - ], - parent: parentWithTaskCall(), - convertEntry: () => [], - }).observations; + const observations = ( + await observeReplaySubagents({ + subagents: [ + { + agentId: AGENT_ID, + meta: { toolUseId: TOOL_USE_ID }, + entries: [ + { + type: "assistant", + timestamp: "2026-07-27T16:42:14.698Z", + message: { content: [], usage: { input_tokens: 7 } }, + }, + ], + }, + ], + parent: parentWithTaskCall(), + convertEntry: () => [], + }) + ).observations; for (const event of foldSubagentObservations(observations)) { store.apply("parent", "claude", event); } @@ -559,7 +601,7 @@ describe("live and replay agree", () => { // The property the design exists to guarantee: one session, two sources, one descriptor. // This is inexpressible against the inference implementation, where the paths share no // vocabulary and each derives identity and status its own way. - it("produces identical descriptor state from the wire and from disk", () => { + it("produces identical descriptor state from the wire and from disk", async () => { const live = new ClaudeTaskProtocolSource(); const liveObservations = [ ...live.observe({ @@ -579,21 +621,23 @@ describe("live and replay agree", () => { } as unknown as SDKMessage), ]; - const replayObservations = observeReplaySubagents({ - subagents: [ - { - agentId: AGENT_ID, - meta: { - toolUseId: TOOL_USE_ID, - agentType: "general-purpose", - description: "Summarize hover and unistyles docs", + const replayObservations = ( + await observeReplaySubagents({ + subagents: [ + { + agentId: AGENT_ID, + meta: { + toolUseId: TOOL_USE_ID, + agentType: "general-purpose", + description: "Summarize hover and unistyles docs", + }, + entries: [], }, - entries: [], - }, - ], - parent: parentWithTaskCall(), - convertEntry: () => [], - }).observations; + ], + parent: parentWithTaskCall(), + convertEntry: () => [], + }) + ).observations; const fromWire = applyToStore(liveObservations); const fromDisk = applyToStore(replayObservations); diff --git a/packages/server/src/server/agent/providers/claude/subagents/replay-source.ts b/packages/server/src/server/agent/providers/claude/subagents/replay-source.ts index 23ba35c0fe..567a98dfe5 100644 --- a/packages/server/src/server/agent/providers/claude/subagents/replay-source.ts +++ b/packages/server/src/server/agent/providers/claude/subagents/replay-source.ts @@ -130,7 +130,7 @@ function readUsage(entry: ClaudeReplayEntry): ClaudeSubagentUsage | null { export interface ClaudeReplaySubagentInput { agentId: string; meta: ClaudeSubagentMeta | null; - entries: Iterable; + entries: Iterable | AsyncIterable; /** Task declarations made by this subagent, used to attach its direct children. */ parentFacts?: ClaudeReplayParentFacts; } @@ -250,13 +250,13 @@ function observeSubtitle( }; } -function observeSubagent( +async function observeSubagent( subagent: ClaudeReplaySubagentInput, parent: ClaudeReplayParentFacts, convertEntry: (entry: ClaudeReplayEntry) => AgentTimelineItem[], toolOwners: Map, parentSubagentId?: string, -): SubagentObservation[] { +): Promise { const link = resolveParentLink(subagent, parent); if (!link) return []; const toolCall = parent.toolCalls.get(link.toolCallId); @@ -269,7 +269,7 @@ function observeSubagent( let childTerminalStatus: ProviderSubagentStatus | null = null; // Consume each source once for presentation and timeline; keep no raw transcript records. - for (const entry of subagent.entries) { + for await (const entry of subagent.entries) { const timestamp = normalizeProviderReplayTimestamp(entry.timestamp); if (!seenEntry) firstTimestamp = timestamp; seenEntry = true; @@ -320,11 +320,11 @@ function recordReplayToolOwners( } } -export function observeReplaySubagents(input: { +export async function observeReplaySubagents(input: { subagents: readonly ClaudeReplaySubagentInput[]; parent: ClaudeReplayParentFacts; convertEntry: (entry: ClaudeReplayEntry) => AgentTimelineItem[]; -}): { observations: SubagentObservation[]; toolOwners: ReadonlyMap } { +}): Promise<{ observations: SubagentObservation[]; toolOwners: ReadonlyMap }> { const observations: SubagentObservation[] = []; const toolOwners = new Map(); const unresolved = [...input.subagents].sort( @@ -346,7 +346,7 @@ export function observeReplaySubagents(input: { const { ownerId, parent, link } = resolved; // Only proven descendants may own notifications; ambient sidecars cannot claim them. - for (const observation of observeSubagent( + for (const observation of await observeSubagent( subagent, parent, input.convertEntry, diff --git a/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.test.ts b/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.test.ts index 59e1f23557..af03a515b7 100644 --- a/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.test.ts +++ b/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.test.ts @@ -35,7 +35,7 @@ function parentEntries( } describe("Claude workflow replay", () => { - it("parses the persisted run summary observed from Claude Code 2.1.220", () => { + it("parses the persisted run summary observed from Claude Code 2.1.220", async () => { expect( parseClaudeWorkflowRun( JSON.stringify({ @@ -62,8 +62,8 @@ describe("Claude workflow replay", () => { }); }); - it("rebuilds the same generic completed descriptor through the parent Workflow call", () => { - const observations = observeReplayWorkflows({ + it("rebuilds the same generic completed descriptor through the parent Workflow call", async () => { + const observations = await observeReplayWorkflows({ workflows: [ { runId: RUN_ID, @@ -91,8 +91,8 @@ describe("Claude workflow replay", () => { }); }); - it("rebuilds a workflow when Claude persists its result as structured text blocks", () => { - const observations = observeReplayWorkflows({ + it("rebuilds a workflow when Claude persists its result as structured text blocks", async () => { + const observations = await observeReplayWorkflows({ workflows: [{ runId: RUN_ID, summary: "Structured result workflow", status: "completed" }], parentEntries: parentEntries([ { @@ -114,7 +114,7 @@ describe("Claude workflow replay", () => { }); }); - it("replays the workflow result without exposing its script or child prompt", () => { + it("replays the workflow result without exposing its script or child prompt", async () => { const workflow = parseClaudeWorkflowRun( JSON.stringify({ runId: RUN_ID, @@ -128,7 +128,7 @@ describe("Claude workflow replay", () => { expect(workflow).not.toBeNull(); if (!workflow) throw new Error("expected workflow"); - const observations = observeReplayWorkflows({ + const observations = await observeReplayWorkflows({ workflows: [workflow], parentEntries: parentEntries(), }); @@ -145,9 +145,9 @@ describe("Claude workflow replay", () => { expect(JSON.stringify(observations)).not.toContain("SECRET CHILD PROMPT"); }); - it("does not duplicate a result already present in the child transcript", () => { + it("does not duplicate a result already present in the child transcript", async () => { const report = "What Paseo is\nA local-first coding-agent environment."; - const observations = observeReplayWorkflows({ + const observations = await observeReplayWorkflows({ workflows: [ { runId: RUN_ID, summary: "Inspect Paseo", status: "completed", result: { report } }, ], @@ -166,8 +166,8 @@ describe("Claude workflow replay", () => { ).toHaveLength(1); }); - it("fails a nonterminal persisted run because its former runtime cannot update it", () => { - const observations = observeReplayWorkflows({ + it("fails a nonterminal persisted run because its former runtime cannot update it", async () => { + const observations = await observeReplayWorkflows({ workflows: [{ runId: RUN_ID, summary: "Interrupted workflow", status: "running" }], parentEntries: parentEntries(), }); @@ -179,9 +179,9 @@ describe("Claude workflow replay", () => { }); }); - it("drops a run that no parent Workflow tool call declared", () => { + it("drops a run that no parent Workflow tool call declared", async () => { expect( - observeReplayWorkflows({ + await observeReplayWorkflows({ workflows: [{ runId: RUN_ID, status: "completed" }], parentEntries: [], }), diff --git a/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.ts b/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.ts index 1d7ff2b1a8..7496ce7c8d 100644 --- a/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.ts +++ b/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.ts @@ -45,14 +45,17 @@ export function parseClaudeWorkflowRun(contents: string): ClaudeWorkflowRun | nu * provider runtime was recreated, so replay terminalizes it as failed instead of resurrecting a * row that can never receive another update. */ -export function observeReplayWorkflows(input: { +export async function observeReplayWorkflows(input: { workflows: readonly ClaudeWorkflowRun[]; - parentEntries: Iterable; + parentEntries: Iterable | AsyncIterable; /** Repeatable entries in chronological order, supplied by the transcript reader. */ - entriesByRunId?: ReadonlyMap>; + entriesByRunId?: ReadonlyMap< + string, + Iterable | AsyncIterable + >; convertEntry?: (entry: ClaudeReplayEntry) => AgentTimelineItem[]; -}): SubagentObservation[] { - const toolCallIdByRunId = readWorkflowLinks(input.parentEntries); +}): Promise { + const toolCallIdByRunId = await readWorkflowLinks(input.parentEntries); const observations: SubagentObservation[] = []; for (const workflow of input.workflows) { @@ -79,7 +82,7 @@ export function observeReplayWorkflows(input: { }); } - for (const observation of observeWorkflowTimeline({ + for (const observation of await observeWorkflowTimeline({ id, result: workflow.result, entries: input.entriesByRunId?.get(workflow.runId) ?? [], @@ -115,17 +118,17 @@ export function observeReplayWorkflows(input: { return observations; } -function observeWorkflowTimeline(input: { +async function observeWorkflowTimeline(input: { id: string; result: unknown; - entries: Iterable; + entries: Iterable | AsyncIterable; convertEntry?: (entry: ClaudeReplayEntry) => AgentTimelineItem[]; finishedAt?: string; -}): SubagentObservation[] { +}): Promise { const observations: SubagentObservation[] = []; const replayedAssistantText = new Set(); - for (const entry of input.entries) { + for await (const entry of input.entries) { const timestamp = normalizeProviderReplayTimestamp(entry.timestamp); const items = input.convertEntry?.(entry) ?? []; for (const item of items) { @@ -150,11 +153,13 @@ function observeWorkflowTimeline(input: { return observations; } -function readWorkflowLinks(entries: Iterable): Map { +async function readWorkflowLinks( + entries: Iterable | AsyncIterable, +): Promise> { const workflowToolCallIds = new Set(); const toolCallIdByRunId = new Map(); - for (const entry of entries) { + for await (const entry of entries) { const content = entry.message?.content; if (!Array.isArray(content)) continue; for (const value of content) { @@ -165,7 +170,7 @@ function readWorkflowLinks(entries: Iterable): Map(entries: Iterable): Generator { +export async function* assignTaskNotificationReplayIds( + entries: AsyncIterable, +): AsyncGenerator { const occurrences = new Map>(); - for (const entry of entries) { + for await (const entry of entries) { const record = TaskNotificationHistoryRecordSchema.safeParse(entry); if (!record.success) { yield entry; diff --git a/packages/server/src/server/agent/providers/claude/transcript-history.ts b/packages/server/src/server/agent/providers/claude/transcript-history.ts index f8663f83d0..09882b76dd 100644 --- a/packages/server/src/server/agent/providers/claude/transcript-history.ts +++ b/packages/server/src/server/agent/providers/claude/transcript-history.ts @@ -1,5 +1,6 @@ import { assignTaskNotificationReplayIds } from "./task-notification-tool-call.js"; -import fs from "node:fs"; +import fs, { type FileHandle } from "node:fs/promises"; +import { setImmediate } from "node:timers/promises"; import path from "node:path"; import { normalizeProviderReplayTimestamp } from "../../provider-history-timestamps.js"; import { @@ -24,11 +25,11 @@ interface RecordLocation { } /** Chunk in bytes so UTF-8 and multi-chunk records are decoded once, at a line boundary. */ -function* locatedRecords( +async function* locatedRecords( file: string, - fd: number, -): Generator<{ entry: TranscriptEntry; location: RecordLocation }> { - const stat = fs.fstatSync(fd); + fd: FileHandle, +): AsyncGenerator<{ entry: TranscriptEntry; location: RecordLocation }> { + const stat = await fd.stat(); // Opening a directory succeeds on some platforms; it must never look like empty history. if (stat.isDirectory()) { throw Object.assign(new Error(`EISDIR: illegal operation on a directory, read '${file}'`), { @@ -43,7 +44,7 @@ function* locatedRecords( let length = 0; while (remaining > 0) { const buffer = Buffer.allocUnsafe(Math.min(64 * 1024, remaining)); - const count = fs.readSync(fd, buffer, 0, buffer.length, null); + const { bytesRead: count } = await fd.read(buffer, 0, buffer.length, null); if (count === 0) break; remaining -= count; let start = 0; @@ -64,6 +65,8 @@ function* locatedRecords( if (entry) yield { entry, location }; start = end + 1; } + // Bound parsing work as well as IO; microtasks alone do not service timers or sockets. + await setImmediate(); if (start < count) { pieces.push(buffer.subarray(start, count)); length += count - start; @@ -85,20 +88,25 @@ function* locatedRecords( /** Indexed sources parse only their own records using descriptors owned by this replay. */ function indexedRecords( locations: readonly RecordLocation[], - descriptors: ReadonlyMap, -): Iterable { + descriptors: ReadonlyMap, +): AsyncIterable { return { - *[Symbol.iterator]() { + async *[Symbol.asyncIterator]() { yield* assignTaskNotificationReplayIds(readEntries()); }, }; - function* readEntries(): Generator { + async function* readEntries(): AsyncGenerator { for (const location of locations) { const fd = descriptors.get(location.file)!; const buffer = Buffer.allocUnsafe(location.length); let read = 0; while (read < buffer.length) { - const count = fs.readSync(fd, buffer, read, buffer.length - read, location.offset + read); + const { bytesRead: count } = await fd.read( + buffer, + read, + buffer.length - read, + location.offset + read, + ); if (count === 0) throw new Error(`Claude transcript was truncated during replay: ${location.file}`); read += count; @@ -127,9 +135,9 @@ function parseRecord(line: string): TranscriptEntry | null { } } -function readOptionalFile(file: string): string | null { +async function readOptionalFile(file: string): Promise { try { - return fs.readFileSync(file, "utf8"); + return await fs.readFile(file, "utf8"); } catch { return null; } @@ -138,31 +146,40 @@ function readOptionalFile(file: string): string | null { /** Discover sources without retaining transcript contents. Unrelated sidechains stay excluded * by the replay ownership resolver; workflow children retain their separate run ownership. */ export interface ClaudeReplayHistory { - parentEntries: Iterable; + parentEntries: AsyncIterable; subagents: { agentId: string; meta: ClaudeSubagentMeta | null; - entries: Iterable; + entries: AsyncIterable; }[]; workflows: ClaudeWorkflowRun[]; - workflowEntriesByRunId: Map>; + workflowEntriesByRunId: Map>; } /** Own descriptors through every pass so unlink or rename cannot invalidate discovered history. * Sources must be consumed before the callback returns. No transcript copies are needed. */ -export function withClaudeReplayHistory( +export async function withClaudeReplayHistory( historyPath: string, - consume: (history: ClaudeReplayHistory) => T, -): T { - const descriptors = new Map(); + consume: (history: ClaudeReplayHistory) => Promise, +): Promise { + const descriptors = new Map(); try { - return consume(indexHistory(historyPath, descriptors)); + return await consume(await indexHistory(historyPath, descriptors)); } finally { - for (const fd of descriptors.values()) fs.closeSync(fd); + await closeReplaySources(descriptors.values()); } } -function indexHistory(historyPath: string, descriptors: Map): ClaudeReplayHistory { +async function closeReplaySources(descriptors: Iterable): Promise { + const results = await Promise.allSettled([...descriptors].map((fd) => fd.close())); + const failure = results.find((result) => result.status === "rejected"); + if (failure) throw failure.reason; +} + +async function indexHistory( + historyPath: string, + descriptors: Map, +): Promise { const sessionDirectory = path.join( path.dirname(historyPath), path.basename(historyPath, ".jsonl"), @@ -174,8 +191,7 @@ function indexHistory(historyPath: string, descriptors: Map): Cl const directories = [sidechainDirectory]; while (directories.length) { const directory = directories.pop()!; - if (!fs.existsSync(directory)) continue; - for (const entry of fs.readdirSync(directory, { withFileTypes: true })) { + for (const entry of await optionalDirectory(directory)) { const file = path.join(directory, entry.name); if (entry.isDirectory()) { directories.push(file); @@ -194,23 +210,23 @@ function indexHistory(historyPath: string, descriptors: Map): Cl } const agentId = /^agent-(.+)\.meta\.json$/.exec(entry.name)?.[1]; if (!agentId) continue; - const contents = readOptionalFile(file); + const contents = await readOptionalFile(file); const meta = contents === null ? null : parseClaudeSubagentMeta(contents); if (meta) metaByAgentId.set(agentId, meta); } } const parentLocations: RecordLocation[] = []; const locationsByAgentId = new Map(); - function scan( + async function scan( file: string, visit: (entry: TranscriptEntry, location: RecordLocation) => void, - ): void { - const fd = fs.openSync(file, "r"); + ): Promise { + const fd = await fs.open(file, "r"); descriptors.set(file, fd); - for (const { entry, location } of locatedRecords(file, fd)) visit(entry, location); + for await (const { entry, location } of locatedRecords(file, fd)) visit(entry, location); } for (const file of sidechainFiles) { - scan(file, (entry, location) => { + await scan(file, (entry, location) => { if (file === historyPath && entry.isSidechain !== true) parentLocations.push(location); if (entry.isSidechain !== true || typeof entry.agentId !== "string") return; const locations = locationsByAgentId.get(entry.agentId) ?? []; @@ -218,11 +234,11 @@ function indexHistory(historyPath: string, descriptors: Map): Cl locationsByAgentId.set(entry.agentId, locations); }); } - const workflowEntriesByRunId = new Map>(); + const workflowEntriesByRunId = new Map>(); for (const [runId, files] of workflowFiles) { const locations: RecordLocation[] = []; for (const file of files) - scan(file, (entry, location) => { + await scan(file, (entry, location) => { if (entry.type !== "user" || isToolResult(entry)) locations.push(location); }); locations.sort((a, b) => { @@ -240,21 +256,28 @@ function indexHistory(historyPath: string, descriptors: Map): Cl meta: metaByAgentId.get(agentId) ?? null, entries: indexedRecords(locations, descriptors), })), - workflows: readWorkflows(sessionDirectory), + workflows: await readWorkflows(sessionDirectory), workflowEntriesByRunId, }; } -function readWorkflows(sessionDirectory: string): ClaudeWorkflowRun[] { +async function readWorkflows(sessionDirectory: string): Promise { const workflows: ClaudeWorkflowRun[] = []; const workflowDirectory = path.join(sessionDirectory, "workflows"); - if (fs.existsSync(workflowDirectory)) { - for (const entry of fs.readdirSync(workflowDirectory, { withFileTypes: true })) { - if (!entry.isFile() || !entry.name.endsWith(".json")) continue; - const contents = readOptionalFile(path.join(workflowDirectory, entry.name)); - const workflow = contents === null ? null : parseClaudeWorkflowRun(contents); - if (workflow) workflows.push(workflow); - } + for (const entry of await optionalDirectory(workflowDirectory)) { + if (!entry.isFile() || !entry.name.endsWith(".json")) continue; + const contents = await readOptionalFile(path.join(workflowDirectory, entry.name)); + const workflow = contents === null ? null : parseClaudeWorkflowRun(contents); + if (workflow) workflows.push(workflow); } return workflows; } + +async function optionalDirectory(directory: string) { + try { + return await fs.readdir(directory, { withFileTypes: true }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; + throw error; + } +} From 9e4aab16cc74f945f9bb676fcab3d8a9a8b686ca Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Tue, 27 Oct 2026 10:30:41 +0700 Subject: [PATCH 046/173] fix(server): keep the daemon responsive during plugin builds (#7967) * fix(server): keep plugin compilation off the daemon event loop TypeScript import validation runs in esbuild callbacks on the daemon thread. Isolate preparation and compilation behind one bounded compiler queue, returning bundles and metadata only after runtime-boundary validation. Recheck lifecycle intent before executing a compiled plugin. * fix(server): reuse the compiler worker during plugin build batches Amortize TypeScript startup across built-ins and queued builds, then retire the worker after one idle second. Carry preparation environments explicitly across worker reuse. Keep dependency-backed example coverage with its existing app fixture. * fix(server): retire the compiler worker after build errors A failed parallel target can leave the other target compiling. Await worker termination before the next queued request instead of reusing an isolate with unfinished build work. * fix(server): preserve compiler error metadata across workers * test(server): isolate plugin validation in the loop-gap fixture Exercise erased TypeScript syntax with a small runtime bundle so parser validation, not multi-MiB result transfer, determines the CI fixture. Keep the 20 ms gate and report event-loop active/idle time for scheduler diagnostics. Resolve the development loader at module initialization. * test(server): probe event-loop turns during plugin compilation Windows timer wake-up lateness measured 22 ms while the loop was idle for 21.96 ms. Use check-phase callbacks to measure loop availability, retaining the raw 20 ms limit and the failing base-branch reproduction. * test: run plugin responsiveness probe in serial integration suite * test: diagnose compiler probe gaps with per-thread CPU readings * test: distinguish compiler CPU blocking from runner scheduling * test: classify the largest compiler CPU accounting window * test: isolate compiler responsiveness from harness GC and idle accounting * test: measure callback blocking with a high-resolution clock --- .../src/server/plugins/compiler-build.ts | 431 +++++++++++++ .../src/server/plugins/compiler-esbuild.ts | 64 ++ .../src/server/plugins/compiler-worker.ts | 62 ++ .../src/server/plugins/compiler.test.ts | 51 ++ .../server/src/server/plugins/compiler.ts | 564 +++++------------- .../plugins/plugin-paseo-api.e2e.test.ts | 24 + .../src/server/plugins/preparation-build.ts | 76 +++ .../src/server/plugins/preparation.test.ts | 48 ++ .../server/src/server/plugins/preparation.ts | 68 +-- .../src/server/plugins/runtime.posix.test.ts | 55 +- packages/server/src/server/plugins/runtime.ts | 72 +-- .../compile-responsiveness.e2e.ts | 187 ++++++ 12 files changed, 1155 insertions(+), 547 deletions(-) create mode 100644 packages/server/src/server/plugins/compiler-build.ts create mode 100644 packages/server/src/server/plugins/compiler-esbuild.ts create mode 100644 packages/server/src/server/plugins/compiler-worker.ts create mode 100644 packages/server/src/server/plugins/preparation-build.ts create mode 100644 packages/server/src/server/plugins/test-fixtures/compile-responsiveness.e2e.ts diff --git a/packages/server/src/server/plugins/compiler-build.ts b/packages/server/src/server/plugins/compiler-build.ts new file mode 100644 index 0000000000..5abd0df6ef --- /dev/null +++ b/packages/server/src/server/plugins/compiler-build.ts @@ -0,0 +1,431 @@ +import { stat } from "node:fs/promises"; +import { readPluginManifest } from "./manifest.js"; +import { assertPluginCompatibility } from "@getpaseo/protocol/plugin-requirements"; +import { existsSync, readFileSync, realpathSync } from "node:fs"; +import { isBuiltin } from "node:module"; +import path from "node:path"; +import { createPluginImportReader, type PluginImportKind } from "./compiler-imports.js"; +import type { Metafile, OnResolveResult, Plugin } from "esbuild"; +import { + isPluginClientOnlySdkSpecifier, + isPluginServerOnlySdkSpecifier, + PLUGIN_SDK_SPECIFIERS, +} from "./plugin-sdk-specifiers.js"; + +import { loadEsbuild, SERVER_HOST_MODULES } from "./compiler-esbuild.js"; + +type PluginBuildTarget = "client" | "server"; + +type PluginModuleLocation = PluginBuildTarget | "shared" | "invalid"; + +function directoryTarget(filePath: string, pluginDirectory: string): PluginModuleLocation | null { + const relative = path.relative(pluginDirectory, filePath); + if (relative.startsWith("..") || path.isAbsolute(relative)) return "invalid"; + const segments = relative.split(path.sep); + if (segments.includes("node_modules")) return null; + if (segments[0] === "client") return "client"; + if (segments[0] === "server") return "server"; + if (segments[0] === "shared") return "shared"; + if (/^index\.client\.tsx?$/.test(relative)) return "client"; + if (/^index\.server\.tsx?$/.test(relative)) return "server"; + return "invalid"; +} + +function containsPath(directory: string, filePath: string): boolean { + const relative = path.relative(directory, filePath); + return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative)); +} + +function dependencyName(specifier: string): string { + const segments = specifier.split("/"); + return specifier.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0]; +} + +function findDependencyRoot( + resolvedPath: string, + specifier: string, + pluginDirectory: string, +): string | null { + const expectedName = dependencyName(specifier); + const ambientName = `@types/${expectedName.replace(/^@/, "").replace("/", "__")}`; + let directory = path.dirname(resolvedPath); + for (;;) { + const manifestPath = path.join(directory, "package.json"); + if (existsSync(manifestPath)) { + const manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as { name?: unknown }; + if (manifest.name === expectedName || manifest.name === ambientName) { + if (containsPath(pluginDirectory, directory) || containsPath(directory, pluginDirectory)) { + return null; + } + return directory; + } + } + const parent = path.dirname(directory); + if (parent === directory) return null; + directory = parent; + } +} + +function moduleBoundaryError( + moduleLocation: PluginModuleLocation | null, + target: PluginBuildTarget | "shared", + filePath: string, +): OnResolveResult | null { + if (moduleLocation === "invalid") { + return { + errors: [{ text: `Plugin modules belong in client/, server/, or shared/: ${filePath}` }], + }; + } + if (moduleLocation === null || moduleLocation === "shared" || moduleLocation === target) { + return null; + } + return { + errors: [ + { + text: `${moduleLocation}-only module cannot be imported into the plugin ${target} bundle: ${filePath}`, + }, + ], + }; +} + +function lexicalBoundaryError( + specifier: string, + resolveDirectory: string, + pluginDirectory: string, + target: PluginBuildTarget | "shared", +): OnResolveResult | null { + if (!specifier.startsWith(".") && !path.isAbsolute(specifier)) return null; + const lexicalPath = path.resolve(resolveDirectory, specifier); + if (containsPath(pluginDirectory, lexicalPath)) { + return moduleBoundaryError(directoryTarget(lexicalPath, pluginDirectory), target, lexicalPath); + } + // Normalize only a containing root alias. Resolving the whole import would erase + // an authored server/ or client/ location when the final file is a symlink. + for (let ancestor = path.dirname(lexicalPath); ; ancestor = path.dirname(ancestor)) { + if (existsSync(ancestor) && realpathSync.native(ancestor) === pluginDirectory) { + const ownedPath = path.join(pluginDirectory, path.relative(ancestor, lexicalPath)); + return moduleBoundaryError(directoryTarget(ownedPath, pluginDirectory), target, lexicalPath); + } + if (path.dirname(ancestor) === ancestor) return null; + } +} + +function createRuntimeBoundaryPlugin(target: PluginBuildTarget, pluginDirectory: string): Plugin { + const boundaryResolution = {}; + const linkedDependencyRoots = new Set(); + return { + name: `paseo-plugin-${target}-runtime-boundary`, + setup(buildContext) { + const checked = new Set(); + const imports = createPluginImportReader(pluginDirectory); + function resolvedBoundaryError( + resolvedFile: string, + specifier: string, + importer: string, + owner: PluginBuildTarget | "shared", + ) { + const file = realpathSync.native(resolvedFile); + const location = directoryTarget(file, pluginDirectory); + if (location === "invalid") { + if ( + [...linkedDependencyRoots].some( + (root) => containsPath(root, importer) && containsPath(root, file), + ) + ) + return null; + if (!specifier.startsWith(".") && !path.isAbsolute(specifier)) { + const root = findDependencyRoot(file, specifier, pluginDirectory); + if (root) { + linkedDependencyRoots.add(root); + return null; + } + } + } + return moduleBoundaryError(location, owner, file); + } + async function resolveImportFiles( + file: string, + specifier: string, + kind: PluginImportKind, + typeOnly: boolean, + ): Promise> { + const declaration = imports.resolve(specifier, file, kind); + const dependencyFiles = new Set(); + if (declaration && (typeOnly || /\.d\.[cm]?ts$/.test(declaration))) + dependencyFiles.add(declaration); + if (typeOnly && !declaration) { + throw new Error(`Could not resolve type dependency "${specifier}" imported by ${file}`); + } + if (!typeOnly && kind !== "type-reference") { + const resolution = await buildContext.resolve(specifier, { + importer: file, + resolveDir: path.dirname(file), + kind, + }); + // esbuild owns missing-runtime errors: erased imports and guarded optional + // requires are legal. Inspect every dependency that actually resolves. + if (!resolution.errors.length && !resolution.external && resolution.namespace === "file") + dependencyFiles.add(realpathSync.native(resolution.path)); + } + return dependencyFiles; + } + async function checkSourceImports( + sourcePath: string, + inheritedOwner: PluginBuildTarget | "shared", + ): Promise { + const file = realpathSync.native(sourcePath); + const owner = + directoryTarget(file, pluginDirectory) === "shared" ? "shared" : inheritedOwner; + const key = `${owner}:${file}`; + if (checked.has(key) || !/\.[cm]?[jt]sx?$/.test(file)) return null; + checked.add(key); + for (const { specifier, kind, typeOnly } of imports.read(file)) { + const packageSpecifier = + kind === "type-reference" + ? `@types/${specifier.replace(/^@/, "").replace("/", "__")}` + : specifier; + const error = + runtimeSpecifierError(specifier, owner, file) ?? + runtimeSpecifierError(packageSpecifier, owner, file) ?? + lexicalBoundaryError(specifier, path.dirname(file), pluginDirectory, owner); + if (error) return error; + // Protocol types are shared host contracts, also exposed by the SDK's peer + // dependency during development. Erased imports need no plugin-local install; + // runtime imports still go through normal dependency resolution below. + if (typeOnly && specifier.startsWith("@getpaseo/protocol/")) continue; + // Host modules have separately enforced SDK boundaries and need no local installation. + if ( + (PLUGIN_SDK_SPECIFIERS as readonly string[]).includes(specifier) || + /^(zod|react|react-native|@tanstack\/react-query)(\/|$)/.test(specifier) || + isBuiltin(specifier) || + packageSpecifier === "@types/node" + ) + continue; + const dependencyFiles = await resolveImportFiles(file, specifier, kind, typeOnly); + for (const dependencyFile of dependencyFiles) { + const boundaryError = resolvedBoundaryError(dependencyFile, specifier, file, owner); + if (boundaryError) return boundaryError; + const dependencyError = await checkSourceImports(dependencyFile, owner); + if (dependencyError) return dependencyError; + } + } + return null; + } + buildContext.onLoad({ filter: /\.[cm]?[jt]sx?$/ }, (args) => + checkSourceImports(args.path, target), + ); + buildContext.onResolve({ filter: /.*/ }, async (args) => { + if (args.kind === "entry-point") return null; + if (args.pluginData === boundaryResolution) return null; + const importer = + args.namespace === "file" ? realpathSync.native(args.importer) : args.importer; + const resolveDir = args.namespace === "file" ? path.dirname(importer) : args.resolveDir; + const owner = directoryTarget(importer, pluginDirectory) === "shared" ? "shared" : target; + const specifierError = runtimeSpecifierError(args.path, owner, importer); + if (specifierError) return specifierError; + const lexicalError = lexicalBoundaryError(args.path, resolveDir, pluginDirectory, owner); + if (lexicalError) return lexicalError; + const resolution = await buildContext.resolve(args.path, { + importer, + namespace: args.namespace, + resolveDir, + kind: args.kind, + pluginData: boundaryResolution, + with: args.with, + }); + if ( + resolution.errors.length > 0 || + resolution.external || + resolution.namespace !== "file" + ) { + return null; + } + return resolvedBoundaryError(resolution.path, args.path, importer, owner); + }); + }, + }; +} + +function wrapCommonJsBundle(code: string): string { + return `(function(require) {\nconst module = { exports: {} };\nconst exports = module.exports;\n${code}\nreturn module.exports;\n})`; +} + +function makeHermesInteropEager(code: string): string { + // Hermes evaluates esbuild's lazy CommonJS interop getters from a string with + // the final loop binding, so every named import can resolve to the last export. + // Plugin bundles execute once and do not need live bindings from host modules. + return code.replaceAll("get: () => from[key]", "value: from[key]"); +} + +function runtimeSpecifierError( + specifier: string, + target: PluginBuildTarget | "shared", + importer: string, +): OnResolveResult | null { + let kind: string | null = null; + if (specifier === "@getpaseo/plugin/client/host") kind = "host-private"; + else if ( + (specifier === "@getpaseo/plugin" || + specifier.startsWith("@getpaseo/plugin/") || + specifier === "@paseo/plugin" || + specifier.startsWith("@paseo/plugin/")) && + !(PLUGIN_SDK_SPECIFIERS as readonly string[]).includes(specifier) + ) + kind = "Unknown SDK"; + else if (target !== "server" && (isBuiltin(specifier) || specifier === "@types/node")) + kind = "Node"; + else if (target !== "server" && isPluginServerOnlySdkSpecifier(specifier)) kind = "server-only"; + else if ( + target !== "client" && + (isPluginClientOnlySdkSpecifier(specifier) || + /^((?:@types\/)?react(?:-dom|-native)?|use-sync-external-store|@tanstack\/react-query)(\/|$)/.test( + specifier, + )) + ) + kind = "client-only"; + return kind + ? { + errors: [ + { + text: `${kind} module cannot be imported into the plugin ${target} bundle: ${specifier} imported by ${importer}`, + }, + ], + } + : null; +} + +function checkSharedDependencies(inputs: Metafile["inputs"], pluginDirectory: string): void { + function inputLocation(file: string): PluginModuleLocation | null { + const absolutePath = path.resolve(file); + // Metafile keys must stay unchanged for graph traversal. Only filesystem + // inputs have canonical paths; data URLs and external specifiers do not. + return directoryTarget( + existsSync(absolutePath) ? realpathSync.native(absolutePath) : absolutePath, + pluginDirectory, + ); + } + const pending = Object.keys(inputs).filter((file) => inputLocation(file) === "shared"); + const visited = new Set(); + while (pending.length) { + const file = pending.pop()!; + if (visited.has(file)) continue; + visited.add(file); + for (const dependency of inputs[file]?.imports ?? []) { + const location = dependency.external ? null : inputLocation(dependency.path); + const error = + runtimeSpecifierError(dependency.original ?? dependency.path, "shared", file) ?? + (dependency.external + ? null + : moduleBoundaryError( + location === "invalid" ? null : location, + "shared", + dependency.path, + )); + if (error?.errors?.length) throw new Error(error.errors[0].text); + if (!dependency.external) pending.push(dependency.path); + } + } +} + +async function compileTarget(entryPath: string, target: PluginBuildTarget): Promise { + const { build } = loadEsbuild(); + // Use native canonical paths throughout: TypeScript expands Windows short names + // when resolving type references, while the JS realpath implementation retains them. + const pluginDirectory = realpathSync.native(path.dirname(entryPath)); + const result = await build({ + entryPoints: [realpathSync.native(entryPath)], + bundle: true, + format: "cjs", + jsx: "automatic", + // `import icon from "./icon.svg"` yields the markup for an inline `{ svg }` icon. + loader: { ".svg": "text" }, + platform: target === "server" ? "node" : "neutral", + target: target === "server" ? "node20" : "es2020", + // The neutral platform reads no package.json entry fields, so packages without + // `exports` would not resolve. Read the same fields as esbuild's browser platform + // minus `browser`, since the bundle also runs in React Native. + mainFields: target === "client" ? ["module", "main"] : undefined, + // Metro lowers async syntax before Hermes sees app code. Plugin client bundles bypass Metro, + // so apply the same compatibility transform before the app evaluates them from source. + supported: target === "client" ? { "async-await": false } : undefined, + external: + target === "client" + ? [ + ...PLUGIN_SDK_SPECIFIERS, + "@tanstack/react-query", + "react", + "react/jsx-runtime", + "react-native", + "zod", + ] + : SERVER_HOST_MODULES, + plugins: [createRuntimeBoundaryPlugin(target, pluginDirectory)], + metafile: true, + logLevel: "silent", + treeShaking: true, + write: false, + }); + checkSharedDependencies(result.metafile.inputs, pluginDirectory); + const output = result.outputFiles[0]?.text; + if (!output) throw new Error(`Plugin ${target} compilation produced no output`); + return wrapCommonJsBundle(makeHermesInteropEager(output)); +} + +export async function compilePlugin(entryPaths: { + client: string | null; + server: string | null; +}): Promise<{ + clientBundle: string | null; + serverBundle: string | null; +}> { + const [clientBundle, serverBundle] = await Promise.all([ + entryPaths.client ? compileTarget(entryPaths.client, "client") : null, + entryPaths.server ? compileTarget(entryPaths.server, "server") : null, + ]); + return { clientBundle, serverBundle }; +} + +const CLIENT_ENTRY_FILENAMES = ["index.client.ts", "index.client.tsx"] as const; +const SERVER_ENTRY_FILENAMES = ["index.server.ts", "index.server.tsx"] as const; +async function findEntry(directory: string, filenames: readonly string[]): Promise { + for (const filename of filenames) { + const filePath = path.join(directory, filename); + const info = await stat(filePath).catch(() => null); + if (info?.isFile()) return filePath; + } + return null; +} + +async function resolveEntryPaths(directory: string): Promise<{ + client: string | null; + server: string | null; +}> { + const [client, server] = await Promise.all([ + findEntry(directory, CLIENT_ENTRY_FILENAMES), + findEntry(directory, SERVER_ENTRY_FILENAMES), + ]); + if (client || server) return { client, server }; + const legacyEntry = await findEntry(directory, ["index.ts", "index.tsx"]); + if (legacyEntry) { + throw new Error( + "This plugin was made for an older version of Paseo and cannot run on Paseo v0.8. Ask its author to update it. Plugin authors can follow the migration guide: https://paseo.sh/docs/plugins/migration", + ); + } + throw new Error( + `Plugin entry points are missing: expected ${CLIENT_ENTRY_FILENAMES.join(" or ")} and/or ${SERVER_ENTRY_FILENAMES.join(" or ")} in ${directory}`, + ); +} + +export async function compileDirectoryPlugin( + directory: string, + version: string, + builtinId?: string, +) { + const manifest = await readPluginManifest(directory); + if (builtinId !== undefined && manifest.id !== builtinId) { + throw new Error(`Built-in plugin ${builtinId} has manifest ID ${manifest.id}`); + } + assertPluginCompatibility({ ...manifest, version, runtime: "daemon" }); + const bundles = await compilePlugin(await resolveEntryPaths(directory)); + return { ...bundles, manifest }; +} diff --git a/packages/server/src/server/plugins/compiler-esbuild.ts b/packages/server/src/server/plugins/compiler-esbuild.ts new file mode 100644 index 0000000000..c36c9c22f9 --- /dev/null +++ b/packages/server/src/server/plugins/compiler-esbuild.ts @@ -0,0 +1,64 @@ +import { existsSync } from "node:fs"; +import { createRequire } from "node:module"; +import path from "node:path"; +import { PLUGIN_SDK_SPECIFIERS } from "./plugin-sdk-specifiers.js"; +const nodeRequire = createRequire(import.meta.url); +export const SERVER_HOST_MODULES = [...PLUGIN_SDK_SPECIFIERS, "zod"]; +const ESBUILD_BINARY_PATH = "ESBUILD_BINARY_PATH"; + +// esbuild resolves its own platform binary via require.resolve() the first time its +// module is evaluated. Inside the packaged desktop app that resolves to a path under +// app.asar even though electron-builder unpacks the real binary to app.asar.unpacked. +// child_process.spawn bypasses Electron's asar fs shim, so the OS rejects that path +// with ENOTDIR. Point esbuild at the real unpacked binary before its module loads. +export function unpackedEsbuildBinaryFromPackageDir( + esbuildPackageDir: string, + platform: NodeJS.Platform, + arch: string, +): string | null { + const asarSegment = `${path.sep}app.asar${path.sep}`; + const asarIndex = esbuildPackageDir.indexOf(asarSegment); + if (asarIndex === -1) return null; + return path.join( + esbuildPackageDir.slice(0, asarIndex), + "app.asar.unpacked", + "node_modules", + `@esbuild/${platform}-${arch}`, + ...(platform === "win32" ? ["esbuild.exe"] : ["bin", "esbuild"]), + ); +} + +export function resolveExistingAsarUnpackedEsbuildBinary( + esbuildPackageDir: string, + platform: NodeJS.Platform = process.platform, + arch: string = process.arch, + exists: (file: string) => boolean = existsSync, +): string | null { + const binaryPath = unpackedEsbuildBinaryFromPackageDir(esbuildPackageDir, platform, arch); + return binaryPath && exists(binaryPath) ? binaryPath : null; +} + +function resolveAsarUnpackedEsbuildBinary(): string | null { + let esbuildDir: string; + try { + esbuildDir = path.dirname(nodeRequire.resolve("esbuild/package.json")); + } catch { + return null; + } + return resolveExistingAsarUnpackedEsbuildBinary(esbuildDir); +} + +export function loadEsbuild(): typeof import("esbuild") { + const previousBinaryPath = process.env[ESBUILD_BINARY_PATH]; + const unpackedBinary = resolveAsarUnpackedEsbuildBinary(); + if (unpackedBinary) process.env[ESBUILD_BINARY_PATH] = unpackedBinary; + + try { + // esbuild reads this variable while its CommonJS module is evaluated. Keep + // the compatibility bridge local so it cannot become an agent's environment. + return nodeRequire("esbuild") as typeof import("esbuild"); + } finally { + if (previousBinaryPath === undefined) delete process.env[ESBUILD_BINARY_PATH]; + else process.env[ESBUILD_BINARY_PATH] = previousBinaryPath; + } +} diff --git a/packages/server/src/server/plugins/compiler-worker.ts b/packages/server/src/server/plugins/compiler-worker.ts new file mode 100644 index 0000000000..ddf2544b8b --- /dev/null +++ b/packages/server/src/server/plugins/compiler-worker.ts @@ -0,0 +1,62 @@ +import { parentPort } from "node:worker_threads"; +import type { ZodIssue } from "zod"; +import { compilePlugin, compileDirectoryPlugin } from "./compiler-build.js"; +import { runPluginBuild } from "./preparation-build.js"; +import type { CompilerTask } from "./compiler.js"; + +export type CompilerReply = + | { kind: "log"; data: Record; message: string } + | { kind: "result"; value: unknown } + | { + kind: "error"; + error: Error; + properties: Record; + issues?: ZodIssue[]; + errors?: unknown[]; + warnings?: unknown[]; + }; + +const port = parentPort!; +// The compiler owner serializes requests; the port queues the first request +// until this entrypoint has loaded, including in source/tsx development. +port.on("message", (task: CompilerTask) => { + void run(task); +}); + +async function run(task: CompilerTask): Promise { + try { + let value: unknown; + switch (task.kind) { + case "entries": + value = await compilePlugin(task.entries); + break; + case "directory": + value = await compileDirectoryPlugin(task.directory, task.version, task.builtinId); + break; + case "prepare": + await runPluginBuild( + task.directory, + task.commands, + { + info: (data, message) => + port.postMessage({ kind: "log", data, message } satisfies CompilerReply), + }, + task.environment, + ); + break; + } + port.postMessage({ kind: "result", value } satisfies CompilerReply); + } catch (cause) { + const error = cause instanceof Error ? cause : new Error(String(cause)); + port.postMessage({ + kind: "error", + error, + // Error cloning drops own metadata such as filesystem code/path. Zod's + // readonly issues are reconstructed separately by the compiler owner. + properties: Object.fromEntries(Object.entries(error).filter(([key]) => key !== "issues")), + ...("issues" in error ? { issues: error.issues as ZodIssue[] } : {}), + ...("errors" in error ? { errors: error.errors as unknown[] } : {}), + ...("warnings" in error ? { warnings: error.warnings as unknown[] } : {}), + } satisfies CompilerReply); + } +} diff --git a/packages/server/src/server/plugins/compiler.test.ts b/packages/server/src/server/plugins/compiler.test.ts index 6f694fbaa3..67ca96e596 100644 --- a/packages/server/src/server/plugins/compiler.test.ts +++ b/packages/server/src/server/plugins/compiler.test.ts @@ -3,8 +3,10 @@ import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; +import { ZodError } from "zod"; import { compilePlugin, + compileDirectoryPlugin, resolveExistingAsarUnpackedEsbuildBinary, unpackedEsbuildBinaryFromPackageDir, } from "./compiler.js"; @@ -975,3 +977,52 @@ export default function contribute() { void value; void secret; return () => und expect(serverBundle).toBeNull(); }); }); + +it("preserves esbuild diagnostics across the compiler boundary", async () => { + const { server } = await createSplitPlugin(); + await writeFile(server, "export default function contribute( {"); + const error = await compilePlugin({ client: null, server }).catch((cause: unknown) => cause); + expect(error).toBeInstanceOf(Error); + expect(error).toMatchObject({ + name: "Error", + message: expect.stringContaining("Expected identifier but found end of file"), + errors: [ + expect.objectContaining({ + text: "Expected identifier but found end of file", + location: expect.objectContaining({ + line: 1, + lineText: "export default function contribute( {", + }), + }), + ], + warnings: [], + }); + // A failed task does not poison the next build. + await writeFile(server, 'export default () => "recovered";'); + const bundles = await compilePlugin({ client: null, server }); + expect(bundles.serverBundle).toContain("recovered"); +}); + +it("preserves manifest validation errors across the compiler boundary", async () => { + const { directory } = await createSplitPlugin(); + await writeFile(path.join(directory, "paseo-plugin.json"), JSON.stringify({ id: 42 })); + const error = await compileDirectoryPlugin(directory, "0.13.2").catch((cause: unknown) => cause); + expect(error).toBeInstanceOf(ZodError); + expect(error).toMatchObject({ + name: "ZodError", + issues: [expect.objectContaining({ path: ["id"], code: "invalid_type" })], + }); + await writeFile(path.join(directory, "paseo-plugin.json"), "{"); + await expect(compileDirectoryPlugin(directory, "0.13.2")).rejects.toBeInstanceOf(SyntaxError); +}); + +it("preserves filesystem error metadata for a missing entry", async () => { + const { server } = await createSplitPlugin(); + await rm(server); + await expect(compilePlugin({ client: null, server })).rejects.toMatchObject({ + code: "ENOENT", + errno: expect.any(Number), + syscall: "realpath", + path: server, + }); +}); diff --git a/packages/server/src/server/plugins/compiler.ts b/packages/server/src/server/plugins/compiler.ts index 4cf89a902c..b96c8ecd4e 100644 --- a/packages/server/src/server/plugins/compiler.ts +++ b/packages/server/src/server/plugins/compiler.ts @@ -1,442 +1,152 @@ -import { existsSync, readFileSync, realpathSync } from "node:fs"; -import { createRequire, isBuiltin } from "node:module"; -import path from "node:path"; -import { createPluginImportReader, type PluginImportKind } from "./compiler-imports.js"; -import type { Metafile, OnResolveResult, Plugin } from "esbuild"; -import { - isPluginClientOnlySdkSpecifier, - isPluginServerOnlySdkSpecifier, - PLUGIN_SDK_SPECIFIERS, -} from "./plugin-sdk-specifiers.js"; +import { createRequire } from "node:module"; +import { pathToFileURL } from "node:url"; +import { Worker } from "node:worker_threads"; +import pLimit from "p-limit"; +import { ZodError } from "zod"; +import type * as build from "./compiler-build.js"; +import type { PluginManifest } from "./manifest.js"; +import type { CompilerReply } from "./compiler-worker.js"; -const nodeRequire = createRequire(import.meta.url); -export const SERVER_HOST_MODULES = [...PLUGIN_SDK_SPECIFIERS, "zod"]; -const ESBUILD_BINARY_PATH = "ESBUILD_BINARY_PATH"; +export { + SERVER_HOST_MODULES, + resolveExistingAsarUnpackedEsbuildBinary, + unpackedEsbuildBinaryFromPackageDir, +} from "./compiler-esbuild.js"; -// esbuild resolves its own platform binary via require.resolve() the first time its -// module is evaluated. Inside the packaged desktop app that resolves to a path under -// app.asar even though electron-builder unpacks the real binary to app.asar.unpacked. -// child_process.spawn bypasses Electron's asar fs shim, so the OS rejects that path -// with ENOTDIR. Point esbuild at the real unpacked binary before its module loads. -export function unpackedEsbuildBinaryFromPackageDir( - esbuildPackageDir: string, - platform: NodeJS.Platform, - arch: string, -): string | null { - const asarSegment = `${path.sep}app.asar${path.sep}`; - const asarIndex = esbuildPackageDir.indexOf(asarSegment); - if (asarIndex === -1) return null; - return path.join( - esbuildPackageDir.slice(0, asarIndex), - "app.asar.unpacked", - "node_modules", - `@esbuild/${platform}-${arch}`, - ...(platform === "win32" ? ["esbuild.exe"] : ["bin", "esbuild"]), - ); -} - -export function resolveExistingAsarUnpackedEsbuildBinary( - esbuildPackageDir: string, - platform: NodeJS.Platform = process.platform, - arch: string = process.arch, - exists: (file: string) => boolean = existsSync, -): string | null { - const binaryPath = unpackedEsbuildBinaryFromPackageDir(esbuildPackageDir, platform, arch); - return binaryPath && exists(binaryPath) ? binaryPath : null; -} - -function resolveAsarUnpackedEsbuildBinary(): string | null { - let esbuildDir: string; - try { - esbuildDir = path.dirname(nodeRequire.resolve("esbuild/package.json")); - } catch { - return null; - } - return resolveExistingAsarUnpackedEsbuildBinary(esbuildDir); -} - -function loadEsbuild(): typeof import("esbuild") { - const previousBinaryPath = process.env[ESBUILD_BINARY_PATH]; - const unpackedBinary = resolveAsarUnpackedEsbuildBinary(); - if (unpackedBinary) process.env[ESBUILD_BINARY_PATH] = unpackedBinary; - - try { - // esbuild reads this variable while its CommonJS module is evaluated. Keep - // the compatibility bridge local so it cannot become an agent's environment. - return nodeRequire("esbuild") as typeof import("esbuild"); - } finally { - if (previousBinaryPath === undefined) delete process.env[ESBUILD_BINARY_PATH]; - else process.env[ESBUILD_BINARY_PATH] = previousBinaryPath; - } -} - -type PluginBuildTarget = "client" | "server"; - -type PluginModuleLocation = PluginBuildTarget | "shared" | "invalid"; - -function directoryTarget(filePath: string, pluginDirectory: string): PluginModuleLocation | null { - const relative = path.relative(pluginDirectory, filePath); - if (relative.startsWith("..") || path.isAbsolute(relative)) return "invalid"; - const segments = relative.split(path.sep); - if (segments.includes("node_modules")) return null; - if (segments[0] === "client") return "client"; - if (segments[0] === "server") return "server"; - if (segments[0] === "shared") return "shared"; - if (/^index\.client\.tsx?$/.test(relative)) return "client"; - if (/^index\.server\.tsx?$/.test(relative)) return "server"; - return "invalid"; -} - -function containsPath(directory: string, filePath: string): boolean { - const relative = path.relative(directory, filePath); - return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative)); -} - -function dependencyName(specifier: string): string { - const segments = specifier.split("/"); - return specifier.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0]; -} - -function findDependencyRoot( - resolvedPath: string, - specifier: string, - pluginDirectory: string, -): string | null { - const expectedName = dependencyName(specifier); - const ambientName = `@types/${expectedName.replace(/^@/, "").replace("/", "__")}`; - let directory = path.dirname(resolvedPath); - for (;;) { - const manifestPath = path.join(directory, "package.json"); - if (existsSync(manifestPath)) { - const manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as { name?: unknown }; - if (manifest.name === expectedName || manifest.name === ambientName) { - if (containsPath(pluginDirectory, directory) || containsPath(directory, pluginDirectory)) { - return null; - } - return directory; - } - } - const parent = path.dirname(directory); - if (parent === directory) return null; - directory = parent; - } -} - -function moduleBoundaryError( - moduleLocation: PluginModuleLocation | null, - target: PluginBuildTarget | "shared", - filePath: string, -): OnResolveResult | null { - if (moduleLocation === "invalid") { - return { - errors: [{ text: `Plugin modules belong in client/, server/, or shared/: ${filePath}` }], +export type CompilerTask = + | { kind: "entries"; entries: Parameters[0] } + | { kind: "directory"; directory: string; version: string; builtinId?: string } + | { + kind: "prepare"; + directory: string; + commands: PluginManifest["build"]; + environment: NodeJS.ProcessEnv; }; - } - if (moduleLocation === null || moduleLocation === "shared" || moduleLocation === target) { - return null; - } - return { - errors: [ - { - text: `${moduleLocation}-only module cannot be imported into the plugin ${target} bundle: ${filePath}`, - }, - ], - }; + +interface TaskResult { + entries: Awaited>; + directory: Awaited>; + prepare: void; } -function lexicalBoundaryError( - specifier: string, - resolveDirectory: string, - pluginDirectory: string, - target: PluginBuildTarget | "shared", -): OnResolveResult | null { - if (!specifier.startsWith(".") && !path.isAbsolute(specifier)) return null; - const lexicalPath = path.resolve(resolveDirectory, specifier); - if (containsPath(pluginDirectory, lexicalPath)) { - return moduleBoundaryError(directoryTarget(lexicalPath, pluginDirectory), target, lexicalPath); - } - // Normalize only a containing root alias. Resolving the whole import would erase - // an authored server/ or client/ location when the final file is a symlink. - for (let ancestor = path.dirname(lexicalPath); ; ancestor = path.dirname(ancestor)) { - if (existsSync(ancestor) && realpathSync.native(ancestor) === pluginDirectory) { - const ownedPath = path.join(pluginDirectory, path.relative(ancestor, lexicalPath)); - return moduleBoundaryError(directoryTarget(ownedPath, pluginDirectory), target, lexicalPath); - } - if (path.dirname(ancestor) === ancestor) return null; - } -} +const IDLE_TIMEOUT_MS = 1_000; +const source = import.meta.url.endsWith(".ts"); +const workerUrl = new URL( + source ? "./compiler-worker.ts" : "./compiler-worker.js", + import.meta.url, +); +// Resolve the development loader once at module initialization, never during a +// compile request. Packaged workers execute ordinary JavaScript without tsx. +const workerEntrypoint = source + ? `import(${JSON.stringify(pathToFileURL(createRequire(import.meta.url).resolve("tsx/esm/api")).href)}).then(({ register }) => { register(); return import(${JSON.stringify(workerUrl.href)}); });` + : workerUrl; -function createRuntimeBoundaryPlugin(target: PluginBuildTarget, pluginDirectory: string): Plugin { - const boundaryResolution = {}; - const linkedDependencyRoots = new Set(); - return { - name: `paseo-plugin-${target}-runtime-boundary`, - setup(buildContext) { - const checked = new Set(); - const imports = createPluginImportReader(pluginDirectory); - function resolvedBoundaryError( - resolvedFile: string, - specifier: string, - importer: string, - owner: PluginBuildTarget | "shared", - ) { - const file = realpathSync.native(resolvedFile); - const location = directoryTarget(file, pluginDirectory); - if (location === "invalid") { - if ( - [...linkedDependencyRoots].some( - (root) => containsPath(root, importer) && containsPath(root, file), - ) - ) - return null; - if (!specifier.startsWith(".") && !path.isAbsolute(specifier)) { - const root = findDependencyRoot(file, specifier, pluginDirectory); - if (root) { - linkedDependencyRoots.add(root); - return null; - } +// Reuse the isolate during a build batch (notably daemon bootstrap), then release +// TypeScript's heap when idle. Only this owner admits work or stops the worker. +class PluginCompiler { + private readonly queue = pLimit(1); + private worker: Worker | null = null; + private idleTimer: ReturnType | null = null; + private stopping: Promise = Promise.resolve(); + + run( + task: T, + onLog?: (data: Record, message: string) => void, + ): Promise { + return this.queue(async () => { + if (this.idleTimer) clearTimeout(this.idleTimer); + this.idleTimer = null; + await this.stopping; + const worker = this.worker ?? this.startWorker(); + worker.ref(); + try { + return await this.request(worker, task, onLog); + } finally { + if (this.worker === worker) { + worker.unref(); + this.idleTimer = setTimeout(() => this.stopWorker(worker), IDLE_TIMEOUT_MS); + this.idleTimer.unref(); + } else { + await this.stopping; + } + } + }); + } + + private startWorker(): Worker { + const worker = new Worker(workerEntrypoint, { eval: source, execArgv: [] }); + this.worker = worker; + // Keep error/exit ownership while idle too. The next caller gets a fresh + // isolate after a crash; author build commands are never retried. + worker.on("error", () => this.stopWorker(worker)); + worker.on("exit", () => { + if (this.worker === worker) this.stopWorker(worker); + }); + return worker; + } + + private stopWorker(worker: Worker): void { + if (this.worker !== worker) return; + this.worker = null; + if (this.idleTimer) clearTimeout(this.idleTimer); + this.idleTimer = null; + this.stopping = worker.terminate(); + } + + private async request( + worker: Worker, + task: T, + onLog?: (data: Record, message: string) => void, + ): Promise { + let onMessage: (reply: CompilerReply) => void; + let onError: (error: Error) => void; + let onExit: (code: number) => void; + try { + return await new Promise((resolve, reject) => { + onError = reject; + onExit = (code) => reject(new Error(`Plugin compiler worker exited (code ${code})`)); + onMessage = (reply) => { + if (reply.kind === "log") { + onLog?.(reply.data, reply.message); + } else if (reply.kind === "result") { + resolve(reply.value as TaskResult[T["kind"]]); + } else { + const error = reply.issues ? new ZodError(reply.issues) : reply.error; + Object.assign(error, reply.properties); + if (reply.errors) Object.assign(error, { errors: reply.errors }); + if (reply.warnings) Object.assign(error, { warnings: reply.warnings }); + // Promise.all can reject while the other target is still compiling. + // Retire the isolate before another request can enter it. + this.stopWorker(worker); + reject(error); } - } - return moduleBoundaryError(location, owner, file); - } - async function resolveImportFiles( - file: string, - specifier: string, - kind: PluginImportKind, - typeOnly: boolean, - ): Promise> { - const declaration = imports.resolve(specifier, file, kind); - const dependencyFiles = new Set(); - if (declaration && (typeOnly || /\.d\.[cm]?ts$/.test(declaration))) - dependencyFiles.add(declaration); - if (typeOnly && !declaration) { - throw new Error(`Could not resolve type dependency "${specifier}" imported by ${file}`); - } - if (!typeOnly && kind !== "type-reference") { - const resolution = await buildContext.resolve(specifier, { - importer: file, - resolveDir: path.dirname(file), - kind, - }); - // esbuild owns missing-runtime errors: erased imports and guarded optional - // requires are legal. Inspect every dependency that actually resolves. - if (!resolution.errors.length && !resolution.external && resolution.namespace === "file") - dependencyFiles.add(realpathSync.native(resolution.path)); - } - return dependencyFiles; - } - async function checkSourceImports( - sourcePath: string, - inheritedOwner: PluginBuildTarget | "shared", - ): Promise { - const file = realpathSync.native(sourcePath); - const owner = - directoryTarget(file, pluginDirectory) === "shared" ? "shared" : inheritedOwner; - const key = `${owner}:${file}`; - if (checked.has(key) || !/\.[cm]?[jt]sx?$/.test(file)) return null; - checked.add(key); - for (const { specifier, kind, typeOnly } of imports.read(file)) { - const packageSpecifier = - kind === "type-reference" - ? `@types/${specifier.replace(/^@/, "").replace("/", "__")}` - : specifier; - const error = - runtimeSpecifierError(specifier, owner, file) ?? - runtimeSpecifierError(packageSpecifier, owner, file) ?? - lexicalBoundaryError(specifier, path.dirname(file), pluginDirectory, owner); - if (error) return error; - // Protocol types are shared host contracts, also exposed by the SDK's peer - // dependency during development. Erased imports need no plugin-local install; - // runtime imports still go through normal dependency resolution below. - if (typeOnly && specifier.startsWith("@getpaseo/protocol/")) continue; - // Host modules have separately enforced SDK boundaries and need no local installation. - if ( - (PLUGIN_SDK_SPECIFIERS as readonly string[]).includes(specifier) || - /^(zod|react|react-native|@tanstack\/react-query)(\/|$)/.test(specifier) || - isBuiltin(specifier) || - packageSpecifier === "@types/node" - ) - continue; - const dependencyFiles = await resolveImportFiles(file, specifier, kind, typeOnly); - for (const dependencyFile of dependencyFiles) { - const boundaryError = resolvedBoundaryError(dependencyFile, specifier, file, owner); - if (boundaryError) return boundaryError; - const dependencyError = await checkSourceImports(dependencyFile, owner); - if (dependencyError) return dependencyError; - } - } - return null; - } - buildContext.onLoad({ filter: /\.[cm]?[jt]sx?$/ }, (args) => - checkSourceImports(args.path, target), - ); - buildContext.onResolve({ filter: /.*/ }, async (args) => { - if (args.kind === "entry-point") return null; - if (args.pluginData === boundaryResolution) return null; - const importer = - args.namespace === "file" ? realpathSync.native(args.importer) : args.importer; - const resolveDir = args.namespace === "file" ? path.dirname(importer) : args.resolveDir; - const owner = directoryTarget(importer, pluginDirectory) === "shared" ? "shared" : target; - const specifierError = runtimeSpecifierError(args.path, owner, importer); - if (specifierError) return specifierError; - const lexicalError = lexicalBoundaryError(args.path, resolveDir, pluginDirectory, owner); - if (lexicalError) return lexicalError; - const resolution = await buildContext.resolve(args.path, { - importer, - namespace: args.namespace, - resolveDir, - kind: args.kind, - pluginData: boundaryResolution, - with: args.with, - }); - if ( - resolution.errors.length > 0 || - resolution.external || - resolution.namespace !== "file" - ) { - return null; - } - return resolvedBoundaryError(resolution.path, args.path, importer, owner); + }; + worker.on("error", onError); + worker.on("exit", onExit); + worker.on("message", onMessage); + worker.postMessage(task, []); }); - }, - }; -} - -function wrapCommonJsBundle(code: string): string { - return `(function(require) {\nconst module = { exports: {} };\nconst exports = module.exports;\n${code}\nreturn module.exports;\n})`; -} - -function makeHermesInteropEager(code: string): string { - // Hermes evaluates esbuild's lazy CommonJS interop getters from a string with - // the final loop binding, so every named import can resolve to the last export. - // Plugin bundles execute once and do not need live bindings from host modules. - return code.replaceAll("get: () => from[key]", "value: from[key]"); -} - -function runtimeSpecifierError( - specifier: string, - target: PluginBuildTarget | "shared", - importer: string, -): OnResolveResult | null { - let kind: string | null = null; - if (specifier === "@getpaseo/plugin/client/host") kind = "host-private"; - else if ( - (specifier === "@getpaseo/plugin" || - specifier.startsWith("@getpaseo/plugin/") || - specifier === "@paseo/plugin" || - specifier.startsWith("@paseo/plugin/")) && - !(PLUGIN_SDK_SPECIFIERS as readonly string[]).includes(specifier) - ) - kind = "Unknown SDK"; - else if (target !== "server" && (isBuiltin(specifier) || specifier === "@types/node")) - kind = "Node"; - else if (target !== "server" && isPluginServerOnlySdkSpecifier(specifier)) kind = "server-only"; - else if ( - target !== "client" && - (isPluginClientOnlySdkSpecifier(specifier) || - /^((?:@types\/)?react(?:-dom|-native)?|use-sync-external-store|@tanstack\/react-query)(\/|$)/.test( - specifier, - )) - ) - kind = "client-only"; - return kind - ? { - errors: [ - { - text: `${kind} module cannot be imported into the plugin ${target} bundle: ${specifier} imported by ${importer}`, - }, - ], - } - : null; -} - -function checkSharedDependencies(inputs: Metafile["inputs"], pluginDirectory: string): void { - function inputLocation(file: string): PluginModuleLocation | null { - const absolutePath = path.resolve(file); - // Metafile keys must stay unchanged for graph traversal. Only filesystem - // inputs have canonical paths; data URLs and external specifiers do not. - return directoryTarget( - existsSync(absolutePath) ? realpathSync.native(absolutePath) : absolutePath, - pluginDirectory, - ); - } - const pending = Object.keys(inputs).filter((file) => inputLocation(file) === "shared"); - const visited = new Set(); - while (pending.length) { - const file = pending.pop()!; - if (visited.has(file)) continue; - visited.add(file); - for (const dependency of inputs[file]?.imports ?? []) { - const location = dependency.external ? null : inputLocation(dependency.path); - const error = - runtimeSpecifierError(dependency.original ?? dependency.path, "shared", file) ?? - (dependency.external - ? null - : moduleBoundaryError( - location === "invalid" ? null : location, - "shared", - dependency.path, - )); - if (error?.errors?.length) throw new Error(error.errors[0].text); - if (!dependency.external) pending.push(dependency.path); + } finally { + worker.off("message", onMessage!); + worker.off("error", onError!); + worker.off("exit", onExit!); } } } -async function compileTarget(entryPath: string, target: PluginBuildTarget): Promise { - const { build } = loadEsbuild(); - // Use native canonical paths throughout: TypeScript expands Windows short names - // when resolving type references, while the JS realpath implementation retains them. - const pluginDirectory = realpathSync.native(path.dirname(entryPath)); - const result = await build({ - entryPoints: [realpathSync.native(entryPath)], - bundle: true, - format: "cjs", - jsx: "automatic", - // `import icon from "./icon.svg"` yields the markup for an inline `{ svg }` icon. - loader: { ".svg": "text" }, - platform: target === "server" ? "node" : "neutral", - target: target === "server" ? "node20" : "es2020", - // The neutral platform reads no package.json entry fields, so packages without - // `exports` would not resolve. Read the same fields as esbuild's browser platform - // minus `browser`, since the bundle also runs in React Native. - mainFields: target === "client" ? ["module", "main"] : undefined, - // Metro lowers async syntax before Hermes sees app code. Plugin client bundles bypass Metro, - // so apply the same compatibility transform before the app evaluates them from source. - supported: target === "client" ? { "async-await": false } : undefined, - external: - target === "client" - ? [ - ...PLUGIN_SDK_SPECIFIERS, - "@tanstack/react-query", - "react", - "react/jsx-runtime", - "react-native", - "zod", - ] - : SERVER_HOST_MODULES, - plugins: [createRuntimeBoundaryPlugin(target, pluginDirectory)], - metafile: true, - logLevel: "silent", - treeShaking: true, - write: false, - }); - checkSharedDependencies(result.metafile.inputs, pluginDirectory); - const output = result.outputFiles[0]?.text; - if (!output) throw new Error(`Plugin ${target} compilation produced no output`); - return wrapCommonJsBundle(makeHermesInteropEager(output)); +const compiler = new PluginCompiler(); + +export function runCompilerTask( + task: T, + onLog?: (data: Record, message: string) => void, +): Promise { + return compiler.run(task, onLog); } -export async function compilePlugin(entryPaths: { - client: string | null; - server: string | null; -}): Promise<{ - clientBundle: string | null; - serverBundle: string | null; -}> { - const [clientBundle, serverBundle] = await Promise.all([ - entryPaths.client ? compileTarget(entryPaths.client, "client") : null, - entryPaths.server ? compileTarget(entryPaths.server, "server") : null, - ]); - return { clientBundle, serverBundle }; +export function compilePlugin(entries: Parameters[0]) { + return runCompilerTask({ kind: "entries", entries }); +} + +export function compileDirectoryPlugin(directory: string, version: string, builtinId?: string) { + return runCompilerTask({ kind: "directory", directory, version, builtinId }); } diff --git a/packages/server/src/server/plugins/plugin-paseo-api.e2e.test.ts b/packages/server/src/server/plugins/plugin-paseo-api.e2e.test.ts index 729b36fa1c..cad97ce743 100644 --- a/packages/server/src/server/plugins/plugin-paseo-api.e2e.test.ts +++ b/packages/server/src/server/plugins/plugin-paseo-api.e2e.test.ts @@ -1,3 +1,6 @@ +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { performance } from "node:perf_hooks"; import pino from "pino"; import { createPaseoDaemon } from "../bootstrap.js"; import { loadConfig } from "../config.js"; @@ -522,3 +525,24 @@ export default function contribute(server: PluginServerContext) { await daemon.close(); } }, 60_000); + +test("keeps reload and enable responsive while compiling a real plugin", async () => { + const directory = await mkdtemp(path.join(tmpdir(), "paseo-responsive-plugin-")); + roots.push(directory); + const { stdout, stderr } = await promisify(execFile)( + process.execPath, + [ + "--import", + "tsx", + fileURLToPath(new URL("./test-fixtures/compile-responsiveness.e2e.ts", import.meta.url)), + directory, + ], + { timeout: 20_000 }, + ); + process.stderr.write(stderr); + const results = z + .array(z.object({ blockingMs: z.number() })) + .length(2) + .parse(JSON.parse(stdout)); + for (const result of results) expect(result.blockingMs).toBeLessThan(20); +}); diff --git a/packages/server/src/server/plugins/preparation-build.ts b/packages/server/src/server/plugins/preparation-build.ts new file mode 100644 index 0000000000..cd42772617 --- /dev/null +++ b/packages/server/src/server/plugins/preparation-build.ts @@ -0,0 +1,76 @@ +import { spawnProcess } from "../../utils/spawn.js"; + +import type { PluginManifest } from "./manifest.js"; + +const OUTPUT_LIMIT = 64 * 1024; + +export async function runPluginBuild( + directory: string, + commands: PluginManifest["build"], + logger: { info(data: Record, message: string): void }, + environment: NodeJS.ProcessEnv, +): Promise { + for (const command of commands ?? []) { + logger.info({ directory, command }, "Running plugin build command"); + const result = await run(command, directory, environment); + if (result.stdout) + logger.info({ directory, command, output: result.stdout }, "Plugin build stdout"); + if (result.stderr) + logger.info({ directory, command, output: result.stderr }, "Plugin build stderr"); + if (result.error) { + throw new Error( + `Plugin build command failed to start: ${formatCommand(command)}\n${result.error.message}`, + ); + } + if (result.exitCode !== 0) { + throw new Error( + `Plugin build command failed (exit ${result.exitCode}): ${formatCommand(command)}${formatOutput(result)}`, + ); + } + } +} + +function run( + command: string[], + directory: string, + environment: NodeJS.ProcessEnv, +): Promise { + return new Promise((resolve) => { + const executable = command[0]!; + const arguments_ = command.slice(1); + const child = spawnProcess(executable, arguments_, { cwd: directory, env: environment }); + let stdout = ""; + let stderr = ""; + let error: Error | undefined; + child.stdout?.on("data", (chunk: Buffer | string) => { + stdout = appendOutput(stdout, chunk.toString()); + }); + child.stderr?.on("data", (chunk: Buffer | string) => { + stderr = appendOutput(stderr, chunk.toString()); + }); + child.once("error", (spawnError) => { + error = spawnError; + }); + child.once("close", (exitCode) => resolve({ exitCode, stdout, stderr, error })); + }); +} + +function appendOutput(current: string, next: string): string { + return `${current}${next}`.slice(-OUTPUT_LIMIT); +} + +function formatCommand(command: string[]): string { + return command.map((argument) => JSON.stringify(argument)).join(" "); +} + +function formatOutput(result: CommandResult): string { + const output = [result.stdout, result.stderr].filter(Boolean).join("\n").trim(); + return output ? `\n${output}` : ""; +} + +interface CommandResult { + exitCode: number | null; + stdout: string; + stderr: string; + error?: Error; +} diff --git a/packages/server/src/server/plugins/preparation.test.ts b/packages/server/src/server/plugins/preparation.test.ts index 0fdb0e34fc..d83fa012e3 100644 --- a/packages/server/src/server/plugins/preparation.test.ts +++ b/packages/server/src/server/plugins/preparation.test.ts @@ -1,6 +1,8 @@ import { chmod, mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; +import { Writable } from "node:stream"; +import pino from "pino"; import { afterEach, describe, expect, it } from "vitest"; import { createTestLogger } from "../../test-utils/test-logger.js"; import { runPluginBuild } from "./preparation.js"; @@ -117,6 +119,52 @@ describe("runPluginBuild", () => { ).rejects.toThrow(/Plugin build command failed \(exit 2\)/); }); + it("forwards build progress and output from the worker to the caller's logger", async () => { + const directory = await mkdtemp(path.join(tmpdir(), "paseo-plugin-build-")); + directories.push(directory); + const records: Array<{ msg: string; output?: string }> = []; + const logger = pino( + new Writable({ + write(chunk, _encoding, callback) { + records.push(JSON.parse(chunk.toString())); + callback(); + }, + }), + ); + await runPluginBuild( + directory, + [[process.execPath, "-e", 'console.log("prepared"); console.error("diagnostic");']], + logger, + ); + expect(records).toMatchObject([ + { msg: "Running plugin build command" }, + { msg: "Plugin build stdout", output: "prepared\n" }, + { msg: "Plugin build stderr", output: expect.stringContaining("diagnostic\n") }, + ]); + }); + + it("uses the caller's current environment across consecutive builds", async () => { + const directory = await mkdtemp(path.join(tmpdir(), "paseo-plugin-build-")); + directories.push(directory); + const previous = process.env.PASEO_PLUGIN_TEST_BUILD_VALUE; + const command = [ + process.execPath, + "-e", + 'require("node:fs").writeFileSync(process.argv[1], process.env.PASEO_PLUGIN_TEST_BUILD_VALUE);', + ]; + try { + process.env.PASEO_PLUGIN_TEST_BUILD_VALUE = "first"; + await runPluginBuild(directory, [[...command, "first.txt"]], createTestLogger()); + process.env.PASEO_PLUGIN_TEST_BUILD_VALUE = "second"; + await runPluginBuild(directory, [[...command, "second.txt"]], createTestLogger()); + expect(await readFile(path.join(directory, "first.txt"), "utf8")).toBe("first"); + expect(await readFile(path.join(directory, "second.txt"), "utf8")).toBe("second"); + } finally { + if (previous === undefined) delete process.env.PASEO_PLUGIN_TEST_BUILD_VALUE; + else process.env.PASEO_PLUGIN_TEST_BUILD_VALUE = previous; + } + }); + it("handles empty or undefined build commands gracefully", async () => { const directory = await mkdtemp(path.join(tmpdir(), "paseo-plugin-build-")); directories.push(directory); diff --git a/packages/server/src/server/plugins/preparation.ts b/packages/server/src/server/plugins/preparation.ts index 267f9697e9..79aec65cdc 100644 --- a/packages/server/src/server/plugins/preparation.ts +++ b/packages/server/src/server/plugins/preparation.ts @@ -1,71 +1,15 @@ -import { spawnProcess } from "../../utils/spawn.js"; import type pino from "pino"; import type { PluginManifest } from "./manifest.js"; - -const OUTPUT_LIMIT = 64 * 1024; +import { runCompilerTask } from "./compiler.js"; export async function runPluginBuild( directory: string, commands: PluginManifest["build"], logger: pino.Logger, ): Promise { - for (const command of commands ?? []) { - logger.info({ directory, command }, "Running plugin build command"); - const result = await run(command, directory); - if (result.stdout) - logger.info({ directory, command, output: result.stdout }, "Plugin build stdout"); - if (result.stderr) - logger.info({ directory, command, output: result.stderr }, "Plugin build stderr"); - if (result.error) { - throw new Error( - `Plugin build command failed to start: ${formatCommand(command)}\n${result.error.message}`, - ); - } - if (result.exitCode !== 0) { - throw new Error( - `Plugin build command failed (exit ${result.exitCode}): ${formatCommand(command)}${formatOutput(result)}`, - ); - } - } -} - -function run(command: string[], directory: string): Promise { - return new Promise((resolve) => { - const executable = command[0]!; - const arguments_ = command.slice(1); - const child = spawnProcess(executable, arguments_, { cwd: directory }); - let stdout = ""; - let stderr = ""; - let error: Error | undefined; - child.stdout?.on("data", (chunk: Buffer | string) => { - stdout = appendOutput(stdout, chunk.toString()); - }); - child.stderr?.on("data", (chunk: Buffer | string) => { - stderr = appendOutput(stderr, chunk.toString()); - }); - child.once("error", (spawnError) => { - error = spawnError; - }); - child.once("close", (exitCode) => resolve({ exitCode, stdout, stderr, error })); - }); -} - -function appendOutput(current: string, next: string): string { - return `${current}${next}`.slice(-OUTPUT_LIMIT); -} - -function formatCommand(command: string[]): string { - return command.map((argument) => JSON.stringify(argument)).join(" "); -} - -function formatOutput(result: CommandResult): string { - const output = [result.stdout, result.stderr].filter(Boolean).join("\n").trim(); - return output ? `\n${output}` : ""; -} - -interface CommandResult { - exitCode: number | null; - stdout: string; - stderr: string; - error?: Error; + if (!commands?.length) return; + await runCompilerTask( + { kind: "prepare", directory, commands, environment: { ...process.env } }, + (data, message) => logger.info(data, message), + ); } diff --git a/packages/server/src/server/plugins/runtime.posix.test.ts b/packages/server/src/server/plugins/runtime.posix.test.ts index 8dd80ce499..30ada955a6 100644 --- a/packages/server/src/server/plugins/runtime.posix.test.ts +++ b/packages/server/src/server/plugins/runtime.posix.test.ts @@ -1,4 +1,4 @@ -import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises"; import { fork } from "node:child_process"; import { tmpdir } from "node:os"; import { PassThrough } from "node:stream"; @@ -1849,9 +1849,9 @@ export default function contribute(plugin: any) { const child = createReloadChild("blocked", events); const runtime = createTestRuntime({ spawnChild: () => child }); - await expect(runtime.startPlugin("blocked", directory, () => false)).rejects.toThrow( - "Plugin start cancelled: blocked", - ); + await expect( + runtime.startPlugin("blocked", directory, () => events.length === 0), + ).rejects.toThrow("Plugin start cancelled: blocked"); expect(runtime.catalog()).toEqual([]); expect(events).toEqual(["start:blocked", "shutdown:blocked", "exit:blocked"]); @@ -2055,3 +2055,50 @@ export default function contribute(server) { await runtime.stopAll(); } }); + +const examplesDirectory = fileURLToPath( + new URL("../../../../../plugin-examples/", import.meta.url), +); +// The Markdown example owns npm preparation in the real app fixture: +// packages/app/e2e/browser/plugin-file-panel-examples.spec.ts. +const examples = (await readdir(examplesDirectory, { withFileTypes: true })) + .filter((entry) => entry.isDirectory() && entry.name !== "markdown-panel") + .map((entry) => entry.name); + +it.each(examples)("builds and loads the %s plugin example", async (example) => { + const settingsDirectory = await mkdtemp(path.join(tmpdir(), "paseo-example-settings-")); + temporaryDirectories.push(settingsDirectory); + const runtime = createTestRuntime({ settingsDirectory }, undefined, "0.13.2"); + try { + await runtime.startPlugin(example, path.join(examplesDirectory, example)); + expect(runtime.catalog()).toMatchObject([{ id: example }]); + expect(pluginMessages(runtime, example)).toContain("[paseo] Plugin ready"); + } finally { + await runtime.stopAll(); + } +}); + +it("does not initialize a plugin cancelled during compilation", async () => { + const directory = await createPlugin("cancelled-build", "export default () => {};"); + const marker = path.join(directory, "initialized.txt"); + await writeFile( + path.join(directory, "index.server.ts"), + ` +import { writeFileSync } from "node:fs"; +export default function contribute() { + writeFileSync(${JSON.stringify(marker)}, "initialized"); + return () => {}; +}`, + ); + const runtime = createTestRuntime(); + let allowed = true; + try { + const loading = runtime.startPlugin("cancelled-build", directory, () => allowed); + allowed = false; + await expect(loading).rejects.toThrow("Plugin start cancelled: cancelled-build"); + expect(await readTextIfPresent(marker)).toBeNull(); + expect(runtime.catalog()).toEqual([]); + } finally { + await runtime.stopAll(); + } +}); diff --git a/packages/server/src/server/plugins/runtime.ts b/packages/server/src/server/plugins/runtime.ts index f5a644ef9d..bc06d5d991 100644 --- a/packages/server/src/server/plugins/runtime.ts +++ b/packages/server/src/server/plugins/runtime.ts @@ -13,7 +13,6 @@ import type { } from "@getpaseo/plugin/server"; import { validateBeforeRequest, validateBeforeResult } from "./lifecycle/index.js"; import { fork } from "node:child_process"; -import { stat } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { randomUUID } from "node:crypto"; @@ -28,10 +27,8 @@ import { type ProviderInput, } from "@getpaseo/plugin/server/provider"; import type { PluginLogEntry } from "@getpaseo/protocol/messages"; -import { compilePlugin } from "./compiler.js"; -import { readPluginManifest } from "./manifest.js"; +import { compileDirectoryPlugin } from "./compiler.js"; import type { PluginRequirements } from "@getpaseo/protocol/messages"; -import { assertPluginCompatibility } from "@getpaseo/protocol/plugin-requirements"; import type { PluginProcessMessage, PluginProcessRequest, @@ -43,8 +40,6 @@ import { PluginSessionSocket } from "./session-socket.js"; import { InternalPluginChild } from "./internal-child.js"; import { evaluateBundle } from "./bundle-evaluator.js"; -const CLIENT_ENTRY_FILENAMES = ["index.client.ts", "index.client.tsx"] as const; -const SERVER_ENTRY_FILENAMES = ["index.server.ts", "index.server.tsx"] as const; const REQUEST_TIMEOUT_MS = 30_000; const TOOL_CALL_TIMEOUT_MS = 10 * 60_000; const MAX_LOG_ENTRIES = 500; @@ -273,35 +268,6 @@ function send(child: PluginChild, message: PluginProcessRequest): Promise }); } -async function findEntry(directory: string, filenames: readonly string[]): Promise { - for (const filename of filenames) { - const filePath = path.join(directory, filename); - const info = await stat(filePath).catch(() => null); - if (info?.isFile()) return filePath; - } - return null; -} - -async function resolveEntryPaths(directory: string): Promise<{ - client: string | null; - server: string | null; -}> { - const [client, server] = await Promise.all([ - findEntry(directory, CLIENT_ENTRY_FILENAMES), - findEntry(directory, SERVER_ENTRY_FILENAMES), - ]); - if (client || server) return { client, server }; - const legacyEntry = await findEntry(directory, ["index.ts", "index.tsx"]); - if (legacyEntry) { - throw new Error( - "This plugin was made for an older version of Paseo and cannot run on Paseo v0.8. Ask its author to update it. Plugin authors can follow the migration guide: https://paseo.sh/docs/plugins/migration", - ); - } - throw new Error( - `Plugin entry points are missing: expected ${CLIENT_ENTRY_FILENAMES.join(" or ")} and/or ${SERVER_ENTRY_FILENAMES.join(" or ")} in ${directory}`, - ); -} - export class PluginRuntime { private readonly plugins = new Map(); private readonly pendingEvents = new Set>(); @@ -350,10 +316,16 @@ export class PluginRuntime { ): Promise { if (this.plugins.has(pluginId)) throw new Error(`Plugin is already running: ${pluginId}`); this.appendLog(pluginId, "stdout", "[paseo] Loading plugin"); - const loaded = await this.loadDirectoryPlugin(pluginId, configuredPath).catch((error) => { - this.appendLog(pluginId, "stderr", `[paseo] Plugin failed to load: ${describeError(error)}`); - throw error; - }); + const loaded = await this.loadDirectoryPlugin(pluginId, configuredPath, canPublish).catch( + (error) => { + this.appendLog( + pluginId, + "stderr", + `[paseo] Plugin failed to load: ${describeError(error)}`, + ); + throw error; + }, + ); if (!canPublish()) { await this.stopPlugin(loaded); throw new Error(`Plugin start cancelled: ${pluginId}`); @@ -367,12 +339,8 @@ export class PluginRuntime { if (this.plugins.has(input.id)) throw new Error(`Plugin is already running: ${input.id}`); this.appendLog(input.id, "stdout", "[paseo] Loading plugin"); const directory = path.resolve(input.directory); - const manifest = await readPluginManifest(directory); - if (manifest.id !== input.id) { - throw new Error(`Built-in plugin ${input.id} has manifest ID ${manifest.id}`); - } - assertPluginCompatibility({ ...manifest, version: this.daemonVersion, runtime: "daemon" }); - const bundles = await compilePlugin(await resolveEntryPaths(directory)); + const bundles = await compileDirectoryPlugin(directory, this.daemonVersion, input.id); + const { manifest } = bundles; if (!bundles.serverBundle) throw new Error(`Built-in plugin ${input.id} needs a server entry`); const loaded = await this.launchPlugin({ pluginId: input.id, @@ -388,11 +356,7 @@ export class PluginRuntime { } async validatePlugin(configuredPath: string): Promise { - const directory = path.resolve(configuredPath); - const manifest = await readPluginManifest(directory); - assertPluginCompatibility({ ...manifest, version: this.daemonVersion, runtime: "daemon" }); - const entryPaths = await resolveEntryPaths(directory); - await compilePlugin(entryPaths); + await compileDirectoryPlugin(path.resolve(configuredPath), this.daemonVersion); } async stopPluginById(pluginId: string): Promise { @@ -738,12 +702,12 @@ export class PluginRuntime { private async loadDirectoryPlugin( pluginId: string, configuredPath: string, + canPublish: () => boolean, ): Promise { const directory = path.resolve(configuredPath); - const manifest = await readPluginManifest(directory); - assertPluginCompatibility({ ...manifest, version: this.daemonVersion, runtime: "daemon" }); - const entryPaths = await resolveEntryPaths(directory); - const bundles = await compilePlugin(entryPaths); + const bundles = await compileDirectoryPlugin(directory, this.daemonVersion); + const { manifest } = bundles; + if (!canPublish()) throw new Error(`Plugin start cancelled: ${pluginId}`); const serverBundle = bundles.serverBundle; if (!serverBundle) { return { diff --git a/packages/server/src/server/plugins/test-fixtures/compile-responsiveness.e2e.ts b/packages/server/src/server/plugins/test-fixtures/compile-responsiveness.e2e.ts new file mode 100644 index 0000000000..229e388b34 --- /dev/null +++ b/packages/server/src/server/plugins/test-fixtures/compile-responsiveness.e2e.ts @@ -0,0 +1,187 @@ +import assert from "node:assert/strict"; +import { createHook, executionAsyncResource } from "node:async_hooks"; +import { open as openFile, writeFile } from "node:fs/promises"; +import { performance, PerformanceObserver } from "node:perf_hooks"; +import path from "node:path"; +import { MessagePort } from "node:worker_threads"; +import pino from "pino"; +import { DaemonConfigStore } from "../../daemon-config-store.js"; +import { PluginService } from "../index.js"; + +// A fresh process excludes the E2E harness's transform/bootstrap garbage from +// the compiler measurement. All work and dependencies below are real. +const directory = process.argv[2]; +assert.ok(directory, "Fixture directory is required"); +const results: { blockingMs: number }[] = []; +await writeFile( + path.join(directory, "paseo-plugin.json"), + JSON.stringify({ id: "responsive-build" }), +); +// Erased types stress TypeScript's AST walk without a multi-MiB runtime bundle. +// Payload transfer is a different cost from import validation. +const entryFile = await openFile(path.join(directory, "index.client.ts"), "w"); +try { + await entryFile.write("type FixtureValues = ["); + for (let offset = 0; offset < 350_000; offset += 10_000) { + await entryFile.write( + Array.from({ length: 10_000 }, (_, index) => offset + index).join(",") + ",", + ); + } + await entryFile.write( + ']; export default function contribute() { return () => "compiled fixture"; }', + ); +} finally { + await entryFile.close(); +} +const store = new DaemonConfigStore(directory, { + mcp: { injectIntoAgents: true }, + browserTools: { enabled: false }, + providers: {}, + metadataGeneration: { providers: [] }, + autoArchiveAfterMerge: false, + enableTerminalAgentHooks: false, + appendSystemPrompt: "", + pluginsEnabled: true, + plugins: { + "responsive-build": { source: "directory", path: directory, enabled: false }, + }, +}); +const service = new PluginService(pino({ level: "silent" }), store, "0.4.0"); +await service.start(); +try { + for (const action of [ + () => service.enablePlugin("responsive-build"), + () => service.reloadPlugin("responsive-build"), + ]) { + // Node 22.19+ exposes per-thread CPU accounting; the repository's older + // Node declarations do not include it yet. .tool-versions pins Node 22.20. + const threadCpuUsage: (previous?: NodeJS.CpuUsage) => NodeJS.CpuUsage = Reflect.get( + process, + "threadCpuUsage", + ); + const startedAt = performance.now(); + let previous = startedAt; + let cpu = threadCpuUsage(); + let longestWall = 0; + let longestBlocking = 0; + let longestWallCpu = 0; + let workerStarts = 0; + let portCallbacks = 0; + let longestWallEvents = { workerStarts: 0, portCallbacks: 0 }; + let longestBlockingWindow = { wallMs: 0, cpuMs: 0, resource: "" }; + let probe: ReturnType; + const callbacks = new Map(); + const recordBlocking = ( + blockingMs: number, + window: { wallMs: number; cpuMs: number; resource: string }, + ) => { + if (blockingMs > longestBlocking) { + longestBlocking = blockingMs; + longestBlockingWindow = window; + } + }; + let longestGc = 0; + const observeGc = (entries: readonly import("node:perf_hooks").PerformanceEntry[]) => { + for (const entry of entries) { + if (entry.startTime >= startedAt) longestGc = Math.max(longestGc, entry.duration); + } + }; + const gc = new PerformanceObserver((list) => observeGc(list.getEntries())); + gc.observe({ entryTypes: ["gc"] }); + // Measure work within callbacks, not CPU-counter increments attributed to + // the idle interval between them. Exclude this probe's own timer callback. + const activity = createHook({ + init(_id, type) { + if (type === "WORKER") workerStarts++; + }, + before(id) { + const resource = executionAsyncResource(); + if (resource instanceof MessagePort) portCallbacks++; + if (resource === probe) return; + callbacks.set(id, { + wall: performance.now(), + cpu: threadCpuUsage(), + resource: Object.prototype.toString.call(resource), + }); + }, + after(id) { + const start = callbacks.get(id); + if (!start) return; + callbacks.delete(id); + const wallMs = performance.now() - start.wall; + const { user, system } = threadCpuUsage(start.cpu); + const cpuMs = (user + system) / 1_000; + // A callback prevents the loop from serving IO for its entire span. + // Use the high-resolution clock, not Windows' coarse CPU increments. + recordBlocking(wallMs, { wallMs, cpuMs, resource: start.resource }); + }, + }).enable(); + const sample = () => { + const now = performance.now(); + const currentCpu = threadCpuUsage(); + const wallMs = now - previous; + const cpuMs = (currentCpu.user - cpu.user + currentCpu.system - cpu.system) / 1_000; + // Native worker construction and message deserialization can precede + // async_hooks.before. Include their interval when those events occurred. + if (workerStarts || portCallbacks) { + recordBlocking(Math.min(wallMs, cpuMs), { + wallMs, + cpuMs, + resource: "worker/port interval", + }); + } + if (wallMs > longestWall) { + longestWall = wallMs; + longestWallCpu = cpuMs; + longestWallEvents = { workerStarts, portCallbacks }; + } + workerStarts = 0; + portCallbacks = 0; + previous = now; + cpu = currentCpu; + }; + // Sleep between probes: a continuously runnable setImmediate loop consumes + // a core while the worker compiles. Raw gaps remain diagnostics; the + // assertion measures elapsed daemon-thread callback spans and GC pauses. + probe = setInterval(sample, 1); + try { + // The caller's current callback began before the hook was enabled. + // Include synchronous work before the action's first await explicitly. + const actionStartedAt = performance.now(); + const actionCpu = threadCpuUsage(); + const pending = action(); + const actionWallMs = performance.now() - actionStartedAt; + const actionCost = threadCpuUsage(actionCpu); + recordBlocking(actionWallMs, { + wallMs: actionWallMs, + cpuMs: (actionCost.user + actionCost.system) / 1_000, + resource: "action()", + }); + await pending; + await new Promise((resolve) => setImmediate(resolve)); + sample(); + observeGc(gc.takeRecords()); + } finally { + clearInterval(probe); + activity.disable(); + gc.disconnect(); + } + longestBlocking = Math.max(longestBlocking, longestGc); + process.stderr.write( + `plugin compile main-thread blocking: ${longestBlocking.toFixed(2)} ms ${JSON.stringify({ longestWall, longestWallCpu, ...longestWallEvents, longestBlockingWindow, longestGc })}\n`, + ); + assert.ok(service.catalog()[0]?.clientBundle.includes("compiled fixture")); + results.push({ blockingMs: longestBlocking }); + } + // Evaluate after both probes so parsing the returned code is not charged to compilation. + const factory = globalThis.eval(service.catalog()[0]!.clientBundle) as ( + require: (specifier: string) => never, + ) => { default: () => () => string }; + const result = factory((specifier) => { + throw new Error(`Unexpected fixture dependency: ${specifier}`); + }).default()(); + assert.equal(result, "compiled fixture"); +} finally { + await service.stopAllPlugins(); +} +process.stdout.write(JSON.stringify(results)); From 63ed15e9333aee63629228f0771f312a4ce60b52 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Tue, 27 Oct 2026 12:51:49 +0700 Subject: [PATCH 047/173] test(server): make the reconciliation responsiveness probe independent of idle waits (#7988) * test(server): measure reconciliation callback work instead of idle gaps Timer gaps include Windows runner scheduling waits. Keep the 20 ms gate on actual main-thread callback spans and GC, retaining raw gaps and thread CPU as diagnostics. * test(server): exclude preemption within reconciliation callbacks Zero-CPU scheduling waits also occur inside callbacks. Budget charged thread CPU and independently require async filesystem admission so synchronous inspection waits remain a deterministic regression. --- .../workspace-reconciliation-service.test.ts | 87 +++++++++++++++++-- 1 file changed, 81 insertions(+), 6 deletions(-) diff --git a/packages/server/src/server/workspace-reconciliation-service.test.ts b/packages/server/src/server/workspace-reconciliation-service.test.ts index e1a8860e3b..5a1b3ae990 100644 --- a/packages/server/src/server/workspace-reconciliation-service.test.ts +++ b/packages/server/src/server/workspace-reconciliation-service.test.ts @@ -1,3 +1,5 @@ +import { createHook, executionAsyncResource } from "node:async_hooks"; +import { performance, PerformanceObserver } from "node:perf_hooks"; import { execFileSync } from "node:child_process"; import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -658,22 +660,95 @@ describe("WorkspaceReconciliationService", () => { workspaceRegistry, logger: createTestLogger(), }); - let last = performance.now(); + // Windows can deschedule Node inside a callback too. Budget charged thread + // CPU within callback spans, capped by wall time because Windows CPU counters + // advance in coarse increments. Also require real asynchronous inspections: + // synchronous filesystem waits can block the loop without consuming CPU. + // Node 22.20 provides this API; our older Node declarations omit it. + const threadCpuUsage: (previous?: NodeJS.CpuUsage) => NodeJS.CpuUsage = Reflect.get( + process, + "threadCpuUsage", + ); + const startedAt = performance.now(); + let last = startedAt; let longestGap = 0; - const probe = setInterval(() => { + let longestCallback = 0; + let longestCallbackCpu = 0; + let longestBlocking = 0; + let asyncInspections = 0; + let longestGc = 0; + const callbacks = new Map(); + const observeGc = (entries: readonly import("node:perf_hooks").PerformanceEntry[]) => { + for (const entry of entries) { + if (entry.startTime >= startedAt) longestGc = Math.max(longestGc, entry.duration); + } + }; + const gc = new PerformanceObserver((list) => observeGc(list.getEntries())); + gc.observe({ entryTypes: ["gc"] }); + let probe: ReturnType; + const activity = createHook({ + init(_id, type) { + if (type === "FSREQPROMISE") asyncInspections++; + }, + before(id) { + if (executionAsyncResource() === probe) return; + callbacks.set(id, { wall: performance.now(), cpu: threadCpuUsage() }); + }, + after(id) { + const start = callbacks.get(id); + if (!start) return; + callbacks.delete(id); + const duration = performance.now() - start.wall; + const { user, system } = threadCpuUsage(start.cpu); + const cpuMs = (user + system) / 1_000; + longestBlocking = Math.max(longestBlocking, Math.min(duration, cpuMs)); + if (duration > longestCallback) { + longestCallback = duration; + longestCallbackCpu = cpuMs; + } + }, + }).enable(); + const sample = () => { const now = performance.now(); longestGap = Math.max(longestGap, now - last); last = now; - }, 1); + }; + probe = setInterval(sample, 1); let result; try { - result = await service.runOnce(); - await new Promise((resolve) => setTimeout(resolve, 1)); + // Include the initial synchronous span: its callback predates the hook. + const actionStartedAt = performance.now(); + const actionCpu = threadCpuUsage(); + const pending = service.runOnce(); + const actionWallMs = performance.now() - actionStartedAt; + const { user, system } = threadCpuUsage(actionCpu); + longestCallback = Math.max(longestCallback, actionWallMs); + longestBlocking = Math.max(longestBlocking, Math.min(actionWallMs, (user + system) / 1_000)); + result = await pending; + await new Promise((resolve) => setImmediate(resolve)); + sample(); + observeGc(gc.takeRecords()); } finally { clearInterval(probe); + activity.disable(); + gc.disconnect(); service.dispose(); } - expect(longestGap).toBeLessThan(20); + // GC CPU during callbacks is included above. GC elapsed durations, like + // callback elapsed durations, include runner preemption: log them separately. + const blockingMs = longestBlocking; + process.stderr.write( + `workspace reconciliation main-thread blocking: ${JSON.stringify({ + blockingMs, + asyncInspections, + longestCallback, + longestCallbackCpu, + longestGc, + longestGap, + })}\n`, + ); + expect(blockingMs).toBeLessThan(20); + expect(asyncInspections).toBe(20001); expect(result.changesApplied).toHaveLength(20000); expect([...workspaces.values()].every((workspace) => workspace.archivedAt !== null)).toBe(true); }, 30000); From 2ce6681d6e4de6d6400ba095741014f1bbfa4221 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Tue, 27 Oct 2026 13:15:38 +0700 Subject: [PATCH 048/173] Keep image attachments responsive during prompts and replay (#7954) * fix(server): keep image materialization responsive Decode and hash attachments in bounded yielding units, deduplicate before writing, and publish complete private files before provider timeline events. Await mapping through existing replay boundaries and serialize notification dispatch so turn completion cannot overtake an image. * fix(server): reject attachment starts closed during conversion Keep interruption terminal for prompts still being materialized, and reject a start if its session closes before provider submission. Cover both providers with real large-image conversions and make history reconciliation tests await the async timeline capability. * fix(server): publish OpenCode snapshots before live suffixes Commit snapshot cursors and publish each event together. Holding those events until attachment IO completed let live deltas overtake text that had already advanced the cursor. Require snapshot publishers and exercise text and reasoning interleaving against real image materialization. --- .../claude/agent.image-rendering.test.ts | 12 +- .../agent/providers/claude/agent.test.ts | 78 +-- .../server/agent/providers/claude/agent.ts | 127 +++-- .../claude/subagents/replay-source.test.ts | 37 ++ .../claude/subagents/replay-source.ts | 6 +- .../subagents/workflow-replay-source.test.ts | 32 ++ .../subagents/workflow-replay-source.ts | 6 +- .../providers/codex-app-server-agent.test.ts | 469 ++++++++++++------ .../agent/providers/codex-app-server-agent.ts | 133 +++-- .../server/agent/providers/omp/agent.test.ts | 95 +++- .../src/server/agent/providers/omp/agent.ts | 20 +- .../opencode/event-translator.test.ts | 37 +- .../test-utils/v2-streamed-text-memory.ts | 23 +- .../opencode/test-utils/v2-timeline.ts | 15 + .../agent/providers/opencode/v2/children.ts | 4 +- .../agent/providers/opencode/v2/session.ts | 10 +- .../providers/opencode/v2/streaming.test.ts | 82 ++- .../providers/opencode/v2/timeline.test.ts | 11 +- .../agent/providers/opencode/v2/timeline.ts | 42 +- .../server/agent/providers/pi/agent.test.ts | 60 +++ .../src/server/agent/providers/pi/agent.ts | 18 +- .../provider-image-output.posix.test.ts | 4 +- .../providers/provider-image-output.test.ts | 118 ++++- .../agent/providers/provider-image-output.ts | 154 ++++-- 24 files changed, 1134 insertions(+), 459 deletions(-) create mode 100644 packages/server/src/server/agent/providers/opencode/test-utils/v2-timeline.ts diff --git a/packages/server/src/server/agent/providers/claude/agent.image-rendering.test.ts b/packages/server/src/server/agent/providers/claude/agent.image-rendering.test.ts index 5a06fea7fd..a772e544d1 100644 --- a/packages/server/src/server/agent/providers/claude/agent.image-rendering.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.image-rendering.test.ts @@ -13,8 +13,8 @@ const MATERIALIZED_PNG_PATH_PATTERN = /paseo-attachments(?:-[^\\/]+)?[\\/](?:[^\\/]+[\\/])?[0-9a-f]{64}\.png$/; interface ClaudeImageTestSession { - translateMessageToEvents(message: SDKMessage): AgentStreamEvent[]; - convertHistoryEntry(entry: unknown): AgentTimelineItem[]; + translateMessageToEvents(message: SDKMessage): Promise; + convertHistoryEntry(entry: unknown): Promise; } async function createSession(): Promise { @@ -157,7 +157,7 @@ describe("Claude tool_result image rendering", () => { test("emits the image as assistant markdown and keeps base64 out of the live tool output", async () => { const session = await createSession(); - const events = session.translateMessageToEvents(imageToolResultUserMessage()); + const events = await session.translateMessageToEvents(imageToolResultUserMessage()); const timelineItems = events .filter((event) => event.type === "timeline") @@ -181,7 +181,7 @@ describe("Claude tool_result image rendering", () => { test("replays the image as assistant markdown through history conversion", async () => { const session = await createSession(); - const items = session.convertHistoryEntry(imageToolResultHistoryEntry()); + const items = await session.convertHistoryEntry(imageToolResultHistoryEntry()); const [imageMessage, ...extraImages] = imageMessages(items); expect(extraImages).toEqual([]); @@ -202,7 +202,7 @@ describe("Claude tool_result image rendering", () => { test("keeps base64 out of an errored tool_result that carries an image", async () => { const session = await createSession(); - const events = session.translateMessageToEvents(erroredImageToolResultUserMessage()); + const events = await session.translateMessageToEvents(erroredImageToolResultUserMessage()); const timelineItems = events .filter((event) => event.type === "timeline") @@ -226,7 +226,7 @@ describe("Claude tool_result image rendering", () => { test("emits one image message per image block in a multi-image tool_result", async () => { const session = await createSession(); - const events = session.translateMessageToEvents(multiImageToolResultUserMessage()); + const events = await session.translateMessageToEvents(multiImageToolResultUserMessage()); const timelineItems = events .filter((event) => event.type === "timeline") diff --git a/packages/server/src/server/agent/providers/claude/agent.test.ts b/packages/server/src/server/agent/providers/claude/agent.test.ts index 2b2c725269..52b70c25bc 100644 --- a/packages/server/src/server/agent/providers/claude/agent.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.test.ts @@ -32,7 +32,7 @@ import type { AgentAttachment } from "@getpaseo/protocol/messages"; import { buildAgentPrompt, renderPromptAttachmentAsText } from "../../prompt-attachments.js"; interface TestClaudeSession { - translateMessageToEvents(message: SDKMessage): AgentStreamEvent[]; + translateMessageToEvents(message: SDKMessage): Promise; close(): Promise; } @@ -53,7 +53,7 @@ afterEach(() => { }); describe("convertClaudeHistoryEntry", () => { - test("maps user tool results to timeline items", () => { + test("maps user tool results to timeline items", async () => { const toolUseId = "toolu_test"; const entry = { type: "user", @@ -79,14 +79,14 @@ describe("convertClaudeHistoryEntry", () => { ]; const mapBlocks = vi.fn().mockReturnValue(stubTimeline); - const result = convertClaudeHistoryEntry(entry, mapBlocks); + const result = await convertClaudeHistoryEntry(entry, mapBlocks); expect(result).toEqual(stubTimeline); expect(mapBlocks).toHaveBeenCalledTimes(1); expect(Array.isArray(mapBlocks.mock.calls[0][0])).toBe(true); }); - test("replays persisted Claude tool results as completed tool calls", () => { + test("replays persisted Claude tool results as completed tool calls", async () => { const entry = { type: "user", message: { @@ -124,12 +124,12 @@ describe("convertClaudeHistoryEntry", () => { const mapPersistedToolResultBlocks = (): AgentTimelineItem[] => completedToolCall; - expect(convertClaudeHistoryEntry(entry, mapPersistedToolResultBlocks)).toEqual( + expect(await convertClaudeHistoryEntry(entry, mapPersistedToolResultBlocks)).toEqual( completedToolCall, ); }); - test("returns user messages when no tool blocks exist", () => { + test("returns user messages when no tool blocks exist", async () => { const entry = { type: "user", message: { @@ -138,7 +138,7 @@ describe("convertClaudeHistoryEntry", () => { }, }; - expect(convertClaudeHistoryEntry(entry, () => [])).toEqual([ + expect(await convertClaudeHistoryEntry(entry, () => [])).toEqual([ { type: "user_message", text: "Run npm test", @@ -146,7 +146,7 @@ describe("convertClaudeHistoryEntry", () => { ]); }); - test("converts compact boundary metadata variants", () => { + test("converts compact boundary metadata variants", async () => { const fixtures = [ { entry: { @@ -175,7 +175,7 @@ describe("convertClaudeHistoryEntry", () => { ] as const; for (const fixture of fixtures) { - expect(convertClaudeHistoryEntry(fixture.entry, () => [])).toEqual([ + expect(await convertClaudeHistoryEntry(fixture.entry, () => [])).toEqual([ { type: "compaction", status: "completed", @@ -186,7 +186,7 @@ describe("convertClaudeHistoryEntry", () => { } }); - test("skips synthetic user entries", () => { + test("skips synthetic user entries", async () => { const entry = { type: "user", isSynthetic: true, @@ -197,13 +197,13 @@ describe("convertClaudeHistoryEntry", () => { }; const mapBlocks = vi.fn().mockReturnValue([]); - const result = convertClaudeHistoryEntry(entry, mapBlocks); + const result = await convertClaudeHistoryEntry(entry, mapBlocks); expect(result).toEqual([]); expect(mapBlocks).not.toHaveBeenCalled(); }); - test("skips meta user entries from Claude skill loading", () => { + test("skips meta user entries from Claude skill loading", async () => { const entry = { type: "user", isMeta: true, @@ -219,13 +219,13 @@ describe("convertClaudeHistoryEntry", () => { }; const mapBlocks = vi.fn().mockReturnValue([]); - const result = convertClaudeHistoryEntry(entry, mapBlocks); + const result = await convertClaudeHistoryEntry(entry, mapBlocks); expect(result).toEqual([]); expect(mapBlocks).not.toHaveBeenCalled(); }); - test("skips interrupt placeholder transcript noise", () => { + test("skips interrupt placeholder transcript noise", async () => { const interruptEntry = { type: "user", message: { @@ -246,11 +246,11 @@ describe("convertClaudeHistoryEntry", () => { .fn() .mockReturnValue([{ type: "assistant_message", text: "No response requested." }]); - expect(convertClaudeHistoryEntry(interruptEntry, mapBlocks)).toEqual([]); - expect(convertClaudeHistoryEntry(assistantNoiseEntry, mapBlocks)).toEqual([]); + expect(await convertClaudeHistoryEntry(interruptEntry, mapBlocks)).toEqual([]); + expect(await convertClaudeHistoryEntry(assistantNoiseEntry, mapBlocks)).toEqual([]); }); - test("skips messages (model switch, /context, etc.)", () => { + test("skips messages (model switch, /context, etc.)", async () => { // Real entries from Claude Code JSONL history files const modelSwitch = { type: "user", @@ -305,24 +305,24 @@ describe("convertClaudeHistoryEntry", () => { const mapBlocks = vi.fn().mockReturnValue([]); - expect(convertClaudeHistoryEntry(modelSwitch, mapBlocks)).toEqual([]); - expect(convertClaudeHistoryEntry(modelSwitchWithAnsi, mapBlocks)).toEqual([]); - expect(convertClaudeHistoryEntry(contextDump, mapBlocks)).toEqual([]); - expect(convertClaudeHistoryEntry(planMode, mapBlocks)).toEqual([]); - expect(convertClaudeHistoryEntry(goodbye, mapBlocks)).toEqual([]); - expect(convertClaudeHistoryEntry(empty, mapBlocks)).toEqual([]); + expect(await convertClaudeHistoryEntry(modelSwitch, mapBlocks)).toEqual([]); + expect(await convertClaudeHistoryEntry(modelSwitchWithAnsi, mapBlocks)).toEqual([]); + expect(await convertClaudeHistoryEntry(contextDump, mapBlocks)).toEqual([]); + expect(await convertClaudeHistoryEntry(planMode, mapBlocks)).toEqual([]); + expect(await convertClaudeHistoryEntry(goodbye, mapBlocks)).toEqual([]); + expect(await convertClaudeHistoryEntry(empty, mapBlocks)).toEqual([]); // Real user messages must NOT be filtered const realMessage = { type: "user", message: { role: "user", content: "fix the bug in auth.ts" }, }; - expect(convertClaudeHistoryEntry(realMessage, mapBlocks)).toEqual([ + expect(await convertClaudeHistoryEntry(realMessage, mapBlocks)).toEqual([ { type: "user_message", text: "fix the bug in auth.ts" }, ]); }); - test("maps task notifications to synthetic tool calls", () => { + test("maps task notifications to synthetic tool calls", async () => { const entry = { type: "system", subtype: "task_notification", @@ -333,7 +333,7 @@ describe("convertClaudeHistoryEntry", () => { output_file: "/tmp/bg-fail-1.txt", }; - expect(convertClaudeHistoryEntry(entry, () => [])).toEqual([ + expect(await convertClaudeHistoryEntry(entry, () => [])).toEqual([ { type: "tool_call", callId: "task_notification_task-note-system-1", @@ -357,7 +357,7 @@ describe("convertClaudeHistoryEntry", () => { ]); }); - test("maps queue-operation task notifications to synthetic tool calls", () => { + test("maps queue-operation task notifications to synthetic tool calls", async () => { const entry = { type: "queue-operation", operation: "enqueue", @@ -372,7 +372,7 @@ describe("convertClaudeHistoryEntry", () => { ].join("\n"), }; - expect(convertClaudeHistoryEntry(entry, () => [])).toEqual([ + expect(await convertClaudeHistoryEntry(entry, () => [])).toEqual([ { type: "tool_call", callId: "task_notification_task-note-queue-1", @@ -396,7 +396,7 @@ describe("convertClaudeHistoryEntry", () => { ]); }); - test("passes assistant content blocks through to the mapper", () => { + test("passes assistant content blocks through to the mapper", async () => { const entry = { type: "assistant", message: { @@ -414,7 +414,7 @@ describe("convertClaudeHistoryEntry", () => { ]; const mapBlocks = vi.fn().mockReturnValue(mappedTimeline); - expect(convertClaudeHistoryEntry(entry, mapBlocks)).toEqual(mappedTimeline); + expect(await convertClaudeHistoryEntry(entry, mapBlocks)).toEqual(mappedTimeline); expect(mapBlocks).toHaveBeenCalledWith(entry.message.content); }); }); @@ -1208,7 +1208,7 @@ describe("ClaudeAgentSession features", () => { input: Record, options: Record, ): Promise; - translateMessageToEvents(message: SDKMessage): AgentStreamEvent[]; + translateMessageToEvents(message: SDKMessage): Promise; }; try { @@ -1248,7 +1248,7 @@ describe("ClaudeAgentSession features", () => { ), ).resolves.toMatchObject({ behavior: "deny", interrupt: undefined }); - internal.translateMessageToEvents({ + await internal.translateMessageToEvents({ type: "command_lifecycle", command_uuid: steerUuid, state: "started", @@ -2395,7 +2395,7 @@ describe("ClaudeAgentSession context window usage", () => { test("emits canonical task snapshots from Claude TaskCreate results", async () => { const session = await createSessionForTest(); try { - session.translateMessageToEvents({ + await session.translateMessageToEvents({ type: "assistant", message: { content: [ @@ -2409,7 +2409,7 @@ describe("ClaudeAgentSession context window usage", () => { }, } as unknown as SDKMessage); - const events = session.translateMessageToEvents({ + const events = await session.translateMessageToEvents({ type: "user", message: { content: [{ type: "tool_result", tool_use_id: "task-create-1", content: "created" }], @@ -3611,9 +3611,9 @@ describe("ClaudeAgentSession context window usage", () => { ]); try { - const compactEvents = (session as unknown as TestClaudeSession).translateMessageToEvents( - createCompactBoundary(), - ); + const compactEvents = await ( + session as unknown as TestClaudeSession + ).translateMessageToEvents(createCompactBoundary()); expect(compactEvents).toContainEqual( expect.objectContaining({ type: "usage_updated", @@ -3799,7 +3799,7 @@ describe("ClaudeAgentSession context window usage", () => { test("result.result is surfaced as an assistant message when no model output was produced", async () => { const session = await createSessionForTest(); - const events = session.translateMessageToEvents({ + const events = await session.translateMessageToEvents({ type: "result", subtype: "success", result: "Unknown command: /foo-doesnt-exist", @@ -3834,7 +3834,7 @@ describe("ClaudeAgentSession context window usage", () => { test("result.result is not duplicated when the model produced output during the turn", async () => { const session = await createSessionForTest(); - const events = session.translateMessageToEvents({ + const events = await session.translateMessageToEvents({ type: "result", subtype: "success", result: "Here is the answer.", diff --git a/packages/server/src/server/agent/providers/claude/agent.ts b/packages/server/src/server/agent/providers/claude/agent.ts index 734272dd02..6516ff81b7 100644 --- a/packages/server/src/server/agent/providers/claude/agent.ts +++ b/packages/server/src/server/agent/providers/claude/agent.ts @@ -2546,7 +2546,11 @@ class ClaudeAgentSession implements AgentSession { this.input.push(sdkMessage); setTimeout(() => { if (this.activeForegroundTurnId === turnId) { - this.emitSubmittedUserMessage(sdkMessage, turnId, options?.clientMessageId); + void this.emitSubmittedUserMessage(sdkMessage, turnId, options?.clientMessageId).catch( + (error: unknown) => { + this.logger.warn({ err: error }, "Failed to emit submitted Claude message"); + }, + ); } }, 0); } catch (error) { @@ -4134,7 +4138,7 @@ class ClaudeAgentSession implements AgentSession { consecutiveInterruptAbortRecoveries = 0; if (await this.handleMissingResumedConversation(message, activeQuery)) return true; if (!this.ownsQuery(activeQuery)) return true; - this.routeSdkMessageFromPump(message); + await this.routeSdkMessageFromPump(message); return false; } finally { this.processingSdkMessages--; @@ -4258,7 +4262,7 @@ class ClaudeAgentSession implements AgentSession { return !this.closed && this.query === query; } - private routeSdkMessageFromPump(message: SDKMessage): void { + private async routeSdkMessageFromPump(message: SDKMessage): Promise { if (this.consumeSessionStateChange(message)) { return; } @@ -4292,7 +4296,7 @@ class ClaudeAgentSession implements AgentSession { "provider.claude.parsed_event", ); - const events = this.buildPumpedMessageEvents(message, identifiers.messageId, turnId); + const events = await this.buildPumpedMessageEvents(message, identifiers.messageId, turnId); if (events.length === 0) { return; @@ -4327,15 +4331,22 @@ class ClaudeAgentSession implements AgentSession { this.dispatchEvents(events); } - private buildPumpedMessageEvents( + private async buildPumpedMessageEvents( message: SDKMessage, messageIdHint: string | null, turnId: string | null, - ): AgentStreamEvent[] { - const messageEvents = this.translateMessageToEvents(message, { + ): Promise { + const query = this.query; + const messageEvents = await this.translateMessageToEvents(message, { suppressAssistantText: true, suppressReasoning: true, }); + if ( + this.closed || + this.query !== query || + (this.activeForegroundTurnId ?? this.autonomousTurn?.id ?? null) !== turnId + ) + return []; const assistantTimelineEvents = readClaudeParentToolUseId(message) ? [] : this.timelineAssembler @@ -4480,13 +4491,13 @@ class ClaudeAgentSession implements AgentSession { return withdrewAll; } - private translateMessageToEvents( + private async translateMessageToEvents( message: SDKMessage, options?: { suppressAssistantText?: boolean; suppressReasoning?: boolean; }, - ): AgentStreamEvent[] { + ): Promise { const parentToolUseId = readClaudeParentToolUseId(message); if (parentToolUseId) { return this.translateSidechainFrameToEvents(message, parentToolUseId); @@ -4534,11 +4545,11 @@ class ClaudeAgentSession implements AgentSession { this.appendSystemMessageEvents(message, events); break; case "user": - this.appendUserMessageEvents(message, events); + await this.appendUserMessageEvents(message, events); this.appendSidechainResultEvents(message, events); break; case "assistant": { - const timelineItems = this.mapBlocksToTimeline(message.message.content, { + const timelineItems = await this.mapBlocksToTimeline(message.message.content, { suppressAssistantText: options?.suppressAssistantText ?? false, suppressReasoning: options?.suppressReasoning ?? false, }); @@ -4549,7 +4560,7 @@ class ClaudeAgentSession implements AgentSession { break; } case "stream_event": - this.appendStreamEventEvents(message, events, options); + await this.appendStreamEventEvents(message, events, options); break; case "result": this.appendResultEvents(message, events); @@ -4651,13 +4662,14 @@ class ClaudeAgentSession implements AgentSession { } } - private emitSubmittedUserMessage( + private async emitSubmittedUserMessage( message: Extract, turnId: string, clientMessageId?: string, - ): void { + ): Promise { const events: AgentStreamEvent[] = []; - this.appendUserMessageEvents(message, events); + await this.appendUserMessageEvents(message, events); + if (this.activeForegroundTurnId !== turnId) return; if (events.length === 0) { return; } @@ -4787,10 +4799,10 @@ class ClaudeAgentSession implements AgentSession { } } - private appendUserMessageEvents( + private async appendUserMessageEvents( message: Extract, events: AgentStreamEvent[], - ): void { + ): Promise { if (isSyntheticUserEntry(message)) { return; } @@ -4829,7 +4841,7 @@ class ClaudeAgentSession implements AgentSession { return; } if (Array.isArray(content)) { - this.appendUserContentArrayEvents(content, messageId, events); + await this.appendUserContentArrayEvents(content, messageId, events); } } @@ -4855,12 +4867,12 @@ class ClaudeAgentSession implements AgentSession { events.push({ type: "timeline", item, provider: "claude" }); } - private appendUserContentArrayEvents( + private async appendUserContentArrayEvents( content: ReadonlyArray, messageId: string | undefined, events: AgentStreamEvent[], - ): void { - const timelineItems = this.mapBlocksToTimeline(content, { + ): Promise { + const timelineItems = await this.mapBlocksToTimeline(content, { textMessageType: "user_message", }); for (const item of timelineItems) { @@ -4876,16 +4888,16 @@ class ClaudeAgentSession implements AgentSession { } } - private appendStreamEventEvents( + private async appendStreamEventEvents( message: Extract, events: AgentStreamEvent[], options: { suppressAssistantText?: boolean; suppressReasoning?: boolean } | undefined, - ): void { + ): Promise { const usageUpdatedEvent = this.contextUsage.buildStreamUsageEvent(message.event); if (usageUpdatedEvent) { events.push(usageUpdatedEvent); } - const timelineItems = this.mapPartialEvent(message.event, { + const timelineItems = await this.mapPartialEvent(message.event, { suppressAssistantText: options?.suppressAssistantText ?? false, suppressReasoning: options?.suppressReasoning ?? false, }); @@ -5351,7 +5363,7 @@ class ClaudeAgentSession implements AgentSession { ): Promise { const timeline: PersistedTimelineEntry[] = []; for await (const entry of entries) { - this.ingestPersistedHistoryEntry(entry, timeline, replay); + await this.ingestPersistedHistoryEntry(entry, timeline, replay); } if (timeline.length > 0) { @@ -5411,11 +5423,11 @@ class ClaudeAgentSession implements AgentSession { return replay; } - private ingestPersistedHistoryEntry( + private async ingestPersistedHistoryEntry( entry: ClaudeHistoryEntry, timeline: PersistedTimelineEntry[], replay: ClaudeReplayOwnership, - ): void { + ): Promise { if (entry.isSidechain) { return; } @@ -5429,7 +5441,7 @@ class ClaudeAgentSession implements AgentSession { ? replay.toolOwners.get(notificationToolUseId) : undefined; if (notificationOwner) { - for (const item of this.convertHistoryEntry(entry)) { + for (const item of await this.convertHistoryEntry(entry)) { this.persistedProviderSubagentEvents.push({ type: "provider_subagent", provider: "claude", @@ -5446,7 +5458,7 @@ class ClaudeAgentSession implements AgentSession { const taskSnapshot = this.taskState.observe(entry); const items = [ ...(taskSnapshot ? [taskSnapshot] : []), - ...this.convertHistoryEntry(entry).map((item) => + ...(await this.convertHistoryEntry(entry)).map((item) => labelReplayedSubagentCard(item, replay.subagentToolCalls), ), ]; @@ -5483,10 +5495,10 @@ class ClaudeAgentSession implements AgentSession { }); } - private convertHistoryEntry(entry: ClaudeHistoryEntry): AgentTimelineItem[] { - return convertClaudeHistoryEntry(entry, (content) => this.mapBlocksToTimeline(content)).map( - limitAgentTimelineItemContent, - ); + private async convertHistoryEntry(entry: ClaudeHistoryEntry): Promise { + return ( + await convertClaudeHistoryEntry(entry, (content) => this.mapBlocksToTimeline(content)) + ).map(limitAgentTimelineItemContent); } // Maps Claude content blocks into AgentTimelineItems. @@ -5501,14 +5513,14 @@ class ClaudeAgentSession implements AgentSession { // // NOTE: convertClaudeHistoryEntry uses extractUserMessageText directly instead of this function // for user entries. Both paths must produce equivalent user_message items. - private mapBlocksToTimeline( + private async mapBlocksToTimeline( content: string | ReadonlyArray, options?: { textMessageType?: "assistant_message" | "user_message"; suppressAssistantText?: boolean; suppressReasoning?: boolean; }, - ): AgentTimelineItem[] { + ): Promise { const textMessageType = options?.textMessageType ?? "assistant_message"; const suppressText = textMessageType === "assistant_message" && (options?.suppressAssistantText ?? false); @@ -5535,7 +5547,7 @@ class ClaudeAgentSession implements AgentSession { if (!isClaudeContentChunk(block) || this.mapSubagentHandbackBlock(block, items)) { continue; } - this.mapBlockToTimeline(block, { + await this.mapBlockToTimeline(block, { items, userTextParts, textMessageType, @@ -5580,7 +5592,7 @@ class ClaudeAgentSession implements AgentSession { } } - private mapBlockToTimeline( + private async mapBlockToTimeline( block: ClaudeContentChunk, context: { items: AgentTimelineItem[]; @@ -5589,7 +5601,7 @@ class ClaudeAgentSession implements AgentSession { suppressText: boolean; suppressReasoning: boolean; }, - ): void { + ): Promise { switch (block.type) { case "text": case "text_delta": @@ -5613,7 +5625,7 @@ class ClaudeAgentSession implements AgentSession { case "code_execution_tool_result": case "bash_code_execution_tool_result": case "text_editor_code_execution_tool_result": - this.handleToolResult(block, context.items); + await this.handleToolResult(block, context.items); break; default: break; @@ -5659,7 +5671,10 @@ class ClaudeAgentSession implements AgentSession { ); } - private handleToolResult(block: ClaudeContentChunk, items: AgentTimelineItem[]): void { + private async handleToolResult( + block: ClaudeContentChunk, + items: AgentTimelineItem[], + ): Promise { const entry = typeof block.tool_use_id === "string" ? this.toolUseCache.get(block.tool_use_id) : undefined; const blockToolName = typeof block.tool_name === "string" ? block.tool_name : undefined; @@ -5692,7 +5707,7 @@ class ClaudeAgentSession implements AgentSession { this.rememberSettledSubagentToolCall(settledToolCall, entry); for (const image of images) { - const imageItem = renderProviderImageOutputAsAssistantMarkdown(image, { + const imageItem = await renderProviderImageOutputAsAssistantMarkdown(image, { materialize: materializeProviderImage, }); if (imageItem) { @@ -5916,13 +5931,13 @@ class ClaudeAgentSession implements AgentSession { return false; } - private mapPartialEvent( + private async mapPartialEvent( event: SDKPartialAssistantMessage["event"], options?: { suppressAssistantText?: boolean; suppressReasoning?: boolean; }, - ): AgentTimelineItem[] { + ): Promise { if (this.updatePartialEventToolState(event)) { return []; } @@ -5930,14 +5945,14 @@ class ClaudeAgentSession implements AgentSession { switch (event.type) { case "content_block_start": return isClaudeContentChunk(event.content_block) - ? this.mapBlocksToTimeline([event.content_block], { + ? await this.mapBlocksToTimeline([event.content_block], { suppressAssistantText: options?.suppressAssistantText, suppressReasoning: options?.suppressReasoning, }) : []; case "content_block_delta": return isClaudeContentChunk(event.delta) - ? this.mapBlocksToTimeline([event.delta], { + ? await this.mapBlocksToTimeline([event.delta], { suppressAssistantText: options?.suppressAssistantText, suppressReasoning: options?.suppressReasoning, }) @@ -6300,12 +6315,14 @@ interface ClaudeHistoryEntry { [key: string]: unknown; } -function mapAssistantHistoryBlocksWithMessageId( +async function mapAssistantHistoryBlocksWithMessageId( entry: ClaudeHistoryEntry, content: string | ClaudeContentChunk[], - mapBlocks: (content: string | ClaudeContentChunk[]) => AgentTimelineItem[], -): AgentTimelineItem[] { - const items = mapBlocks(content); + mapBlocks: ( + content: string | ClaudeContentChunk[], + ) => AgentTimelineItem[] | Promise, +): Promise { + const items = await mapBlocks(content); const assistantMessageId = typeof entry.uuid === "string" && entry.uuid.length > 0 ? entry.uuid : null; if (!assistantMessageId) { @@ -6373,10 +6390,12 @@ function isProviderImageMessage(item: AgentTimelineItem): boolean { return item.type === "assistant_message" && isProviderImageMarkdown(item.text); } -export function convertClaudeHistoryEntry( +export async function convertClaudeHistoryEntry( entry: ClaudeHistoryEntry, - mapBlocks: (content: string | ClaudeContentChunk[]) => AgentTimelineItem[], -): AgentTimelineItem[] { + mapBlocks: ( + content: string | ClaudeContentChunk[], + ) => AgentTimelineItem[] | Promise, +): Promise { const preamble = convertClaudeHistoryEntryPreamble(entry); if ("shortCircuit" in preamble) { return preamble.shortCircuit; @@ -6415,7 +6434,7 @@ export function convertClaudeHistoryEntry( } if (hasToolBlock && normalizedBlocks) { - const mapped = mapBlocks(normalizedBlocks); + const mapped = await mapBlocks(normalizedBlocks); if (entry.type === "user") { // tool_result handling (handleToolResult) emits image markdown as an assistant_message // alongside the tool_call. User-entry text blocks also map to assistant_message in this path @@ -6429,7 +6448,7 @@ export function convertClaudeHistoryEntry( } if (entry.type === "assistant" && contentValue) { - return mapAssistantHistoryBlocksWithMessageId(entry, contentValue, mapBlocks); + return await mapAssistantHistoryBlocksWithMessageId(entry, contentValue, mapBlocks); } return timeline; diff --git a/packages/server/src/server/agent/providers/claude/subagents/replay-source.test.ts b/packages/server/src/server/agent/providers/claude/subagents/replay-source.test.ts index 413f39d427..f5bbf52422 100644 --- a/packages/server/src/server/agent/providers/claude/subagents/replay-source.test.ts +++ b/packages/server/src/server/agent/providers/claude/subagents/replay-source.test.ts @@ -1,3 +1,9 @@ +import { readFile } from "node:fs/promises"; +import { fileURLToPath } from "node:url"; +import { + materializeProviderImage, + renderProviderImageOutputAsAssistantMarkdown, +} from "../../provider-image-output.js"; import type { SDKMessage } from "@anthropic-ai/claude-agent-sdk"; import { describe, expect, it } from "vitest"; @@ -660,3 +666,34 @@ describe("live and replay agree", () => { }); }); }); + +it("awaits image materialization before publishing replay observations", async () => { + const bytes = Buffer.from("async replay image fixture"); + const convertEntry = async () => { + const item = await renderProviderImageOutputAsAssistantMarkdown( + { data: bytes.toString("base64"), mimeType: "image/png" }, + { materialize: materializeProviderImage }, + ); + return item ? [item] : []; + }; + const { observations } = await observeReplaySubagents({ + parent: parentWithTaskCall(), + subagents: [ + { + agentId: AGENT_ID, + meta: { toolUseId: TOOL_USE_ID }, + entries: [{ type: "assistant", message: { content: [] } }], + }, + ], + convertEntry, + }); + const image = observations.find( + (observation) => + observation.kind === "timeline" && observation.item.type === "assistant_message", + ); + if (!image || image.kind !== "timeline" || image.item.type !== "assistant_message") + throw new Error("Expected replay image"); + const source = image.item.text.match(/!\[Image\]\(([^)]+)\)/)?.[1]; + expect(source).toBeTruthy(); + expect(await readFile(fileURLToPath(source!))).toEqual(bytes); +}); diff --git a/packages/server/src/server/agent/providers/claude/subagents/replay-source.ts b/packages/server/src/server/agent/providers/claude/subagents/replay-source.ts index 567a98dfe5..2a3ca74846 100644 --- a/packages/server/src/server/agent/providers/claude/subagents/replay-source.ts +++ b/packages/server/src/server/agent/providers/claude/subagents/replay-source.ts @@ -253,7 +253,7 @@ function observeSubtitle( async function observeSubagent( subagent: ClaudeReplaySubagentInput, parent: ClaudeReplayParentFacts, - convertEntry: (entry: ClaudeReplayEntry) => AgentTimelineItem[], + convertEntry: (entry: ClaudeReplayEntry) => AgentTimelineItem[] | Promise, toolOwners: Map, parentSubagentId?: string, ): Promise { @@ -280,7 +280,7 @@ async function observeSubagent( childTerminalStatus = entry.message?.stop_reason === "end_turn" ? "completed" : null; } recordReplayToolOwners(toolOwners, entry, link.id); - for (const item of convertEntry(entry)) { + for (const item of await convertEntry(entry)) { timeline.push({ kind: "timeline", id: link.id, item, ...(timestamp ? { timestamp } : {}) }); } } @@ -323,7 +323,7 @@ function recordReplayToolOwners( export async function observeReplaySubagents(input: { subagents: readonly ClaudeReplaySubagentInput[]; parent: ClaudeReplayParentFacts; - convertEntry: (entry: ClaudeReplayEntry) => AgentTimelineItem[]; + convertEntry: (entry: ClaudeReplayEntry) => AgentTimelineItem[] | Promise; }): Promise<{ observations: SubagentObservation[]; toolOwners: ReadonlyMap }> { const observations: SubagentObservation[] = []; const toolOwners = new Map(); diff --git a/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.test.ts b/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.test.ts index af03a515b7..edb673c664 100644 --- a/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.test.ts +++ b/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.test.ts @@ -1,3 +1,9 @@ +import { readFile } from "node:fs/promises"; +import { fileURLToPath } from "node:url"; +import { + materializeProviderImage, + renderProviderImageOutputAsAssistantMarkdown, +} from "../../provider-image-output.js"; import { describe, expect, it } from "vitest"; import { ProviderSubagentStore } from "../../../provider-subagents/store.js"; @@ -195,3 +201,29 @@ describe("Claude workflow replay", () => { }, ); }); + +it("awaits image materialization before publishing replay observations", async () => { + const bytes = Buffer.from("async replay image fixture"); + const convertEntry = async () => { + const item = await renderProviderImageOutputAsAssistantMarkdown( + { data: bytes.toString("base64"), mimeType: "image/png" }, + { materialize: materializeProviderImage }, + ); + return item ? [item] : []; + }; + const observations = await observeReplayWorkflows({ + workflows: [{ runId: RUN_ID, status: "completed" }], + parentEntries: parentEntries(), + entriesByRunId: new Map([[RUN_ID, [{ type: "assistant", message: { content: [] } }]]]), + convertEntry, + }); + const image = observations.find( + (observation) => + observation.kind === "timeline" && observation.item.type === "assistant_message", + ); + if (!image || image.kind !== "timeline" || image.item.type !== "assistant_message") + throw new Error("Expected replay image"); + const source = image.item.text.match(/!\[Image\]\(([^)]+)\)/)?.[1]; + expect(source).toBeTruthy(); + expect(await readFile(fileURLToPath(source!))).toEqual(bytes); +}); diff --git a/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.ts b/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.ts index 7496ce7c8d..17a278d00f 100644 --- a/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.ts +++ b/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.ts @@ -53,7 +53,7 @@ export async function observeReplayWorkflows(input: { string, Iterable | AsyncIterable >; - convertEntry?: (entry: ClaudeReplayEntry) => AgentTimelineItem[]; + convertEntry?: (entry: ClaudeReplayEntry) => AgentTimelineItem[] | Promise; }): Promise { const toolCallIdByRunId = await readWorkflowLinks(input.parentEntries); const observations: SubagentObservation[] = []; @@ -122,7 +122,7 @@ async function observeWorkflowTimeline(input: { id: string; result: unknown; entries: Iterable | AsyncIterable; - convertEntry?: (entry: ClaudeReplayEntry) => AgentTimelineItem[]; + convertEntry?: (entry: ClaudeReplayEntry) => AgentTimelineItem[] | Promise; finishedAt?: string; }): Promise { const observations: SubagentObservation[] = []; @@ -130,7 +130,7 @@ async function observeWorkflowTimeline(input: { for await (const entry of input.entries) { const timestamp = normalizeProviderReplayTimestamp(entry.timestamp); - const items = input.convertEntry?.(entry) ?? []; + const items = (await input.convertEntry?.(entry)) ?? []; for (const item of items) { if (item.type === "assistant_message") replayedAssistantText.add(item.text.trim()); observations.push({ diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts index 8c61635d6f..1d113fb27a 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts @@ -113,7 +113,7 @@ interface CodexSessionTestAccess { }; ensureThreadLoaded(): Promise; handleToolApprovalRequest(params: unknown): Promise; - handleNotification(method: string, params: unknown): void; + handleNotification(method: string, params: unknown): Promise; loadPersistedHistory(client: CodexClientLike | null): Promise; refreshResolvedCollaborationMode(): void; serviceTier: "fast" | null; @@ -212,6 +212,7 @@ async function startPublicSteeringSession( const started = await session.startTurn("first"); await appServer.waitForTurnStart(); appServer.startsTurn({ threadId: "thread-1", turnId: "native-A" }); + await new Promise((resolve) => setImmediate(resolve)); await new Promise((resolve) => setTimeout(resolve, 0)); return { session, paseoTurnId: started.turnId }; } @@ -354,9 +355,11 @@ describe("Codex active-turn steering admission", () => { }); await resolverEntered.promise; appServer.completeTurn({ threadId: "thread-1" }); + await new Promise((resolve) => setImmediate(resolve)); await new Promise((resolve) => setTimeout(resolve, 0)); const startedB = await session.startTurn("second"); appServer.startsTurn({ threadId: "thread-1", turnId: "native-B" }); + await new Promise((resolve) => setImmediate(resolve)); await new Promise((resolve) => setTimeout(resolve, 0)); commandResolution.resolve(null); @@ -478,6 +481,7 @@ async function startCompactionTurnTest(): Promise<{ await session.startTurn("exercise compaction lifecycle"); appServer.startsTurn({ threadId: "thread-1", turnId: "codex-turn-1" }); + await new Promise((resolve) => setImmediate(resolve)); return { appServer, session, events, terminalEvent }; } @@ -1460,7 +1464,9 @@ describe("Codex app-server provider", () => { command: "gh pr merge 2030 --squash", cwd: "/workspace/project", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.says({ threadId: "thread-1", text: "Merged." }); + await new Promise((resolve) => setImmediate(resolve)); await expect(nextTimelineItem).resolves.toEqual({ type: "timeline", @@ -1504,6 +1510,7 @@ describe("Codex app-server provider", () => { command: "gh pr merge 2030 --squash", cwd: "/workspace/project", }); + await new Promise((resolve) => setImmediate(resolve)); await expect(nextTimelineItem).resolves.toEqual({ type: "timeline", @@ -1548,6 +1555,7 @@ describe("Codex app-server provider", () => { processId: "4242", text: "gh pr merge 2030 --squash\n", }); + await new Promise((resolve) => setImmediate(resolve)); await expect(nextTimelineItem).resolves.toEqual({ type: "timeline", @@ -1576,6 +1584,7 @@ describe("Codex app-server provider", () => { command: "sleep 30", output: "Process running with session id 4242", }); + await new Promise((resolve) => setImmediate(resolve)); await expect(relabeledTerminal).resolves.toEqual({ type: "timeline", @@ -1623,6 +1632,7 @@ describe("Codex app-server provider", () => { processId: "73", command, }); + await new Promise((resolve) => setImmediate(resolve)); const terminalWrite = waitForTimelineToolCall(session, "terminal-session-73-1"); appServer.typesIntoTerminal({ @@ -1632,6 +1642,7 @@ describe("Codex app-server provider", () => { processId: "73", text: "print(1)\n", }); + await new Promise((resolve) => setImmediate(resolve)); await expect(terminalWrite).resolves.toMatchObject({ item: { @@ -1668,7 +1679,9 @@ describe("Codex app-server provider", () => { processId: "4242", text: "git status\n", }); + await new Promise((resolve) => setImmediate(resolve)); + await firstTimelineItem; const secondTimelineItem = waitForNextTimelineItem(session); appServer.typesIntoTerminal({ threadId: "thread-1", @@ -1677,6 +1690,7 @@ describe("Codex app-server provider", () => { processId: "4242", text: "git push\n", }); + await new Promise((resolve) => setImmediate(resolve)); const [first, second] = await Promise.all([firstTimelineItem, secondTimelineItem]); expect(first.item).toMatchObject({ @@ -2075,9 +2089,13 @@ describe("Codex app-server provider", () => { await session.startTurn("remember first"); emitCodexUserMessage(appServer, { id: "codex-first", text: "remember first" }); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); + await new Promise((resolve) => setImmediate(resolve)); await session.startTurn("remember second"); emitCodexUserMessage(appServer, { id: "codex-second", text: "remember second" }); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); + await new Promise((resolve) => setImmediate(resolve)); await session.revertConversation({ messageId: "codex-first" }); @@ -2116,6 +2134,8 @@ describe("Codex app-server provider", () => { turnId: "turn-first", }); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); + await new Promise((resolve) => setImmediate(resolve)); await session.startTurn("remember second"); emitCodexUserMessage(appServer, { id: "codex-second", @@ -2123,6 +2143,8 @@ describe("Codex app-server provider", () => { turnId: "turn-second", }); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); + await new Promise((resolve) => setImmediate(resolve)); await session.revertConversation({ messageId: "codex-second" }); @@ -2172,6 +2194,8 @@ describe("Codex app-server provider", () => { turnId: "turn-first", }); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); + await new Promise((resolve) => setImmediate(resolve)); await session.startTurn("remember second"); emitCodexUserMessage(appServer, { id: "codex-second", @@ -2179,6 +2203,8 @@ describe("Codex app-server provider", () => { turnId: "turn-second", }); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); + await new Promise((resolve) => setImmediate(resolve)); await session.revertConversation({ messageId: "codex-first" }); @@ -2249,6 +2275,8 @@ describe("Codex app-server provider", () => { turnId: "turn-first", }); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); + await new Promise((resolve) => setImmediate(resolve)); await session.startTurn("remember second"); emitCodexUserMessage(appServer, { id: "codex-second", @@ -2256,6 +2284,8 @@ describe("Codex app-server provider", () => { turnId: "turn-second", }); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); + await new Promise((resolve) => setImmediate(resolve)); await session.revertConversation({ messageId: "codex-first" }); @@ -2290,7 +2320,7 @@ describe("Codex app-server provider", () => { const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); await session.startTurn("remember this", { clientMessageId: "client-message" }); - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { threadId: "thread-1", turn: { id: "turn-1" }, }); @@ -2306,6 +2336,8 @@ describe("Codex app-server provider", () => { }); expect(events.slice(0, 2).map((event) => event.type)).toEqual(["turn_started", "timeline"]); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); + await new Promise((resolve) => setImmediate(resolve)); await session.close(); }); @@ -3181,12 +3213,12 @@ describe("Codex app-server provider", () => { ]); }); - test("converts Codex collab agent notifications through the normal timeline path", () => { + test("converts Codex collab agent notifications through the normal timeline path", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/started", { + await asInternals(session).handleNotification("item/started", { threadId: "test-thread", item: { type: "collabAgentToolCall", @@ -3222,12 +3254,12 @@ describe("Codex app-server provider", () => { ]); }); - test("folds child-thread Codex activity into the parent sub-agent tool call", () => { + test("folds child-thread Codex activity into the parent sub-agent tool call", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "collabAgentToolCall", @@ -3241,12 +3273,12 @@ describe("Codex app-server provider", () => { }, }, }); - asInternals(session).handleNotification("item/agentMessage/delta", { + await asInternals(session).handleNotification("item/agentMessage/delta", { threadId: "child-thread-1", itemId: "child-message-1", delta: "Found", }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "child-thread-1", item: { type: "agentMessage", @@ -3254,7 +3286,7 @@ describe("Codex app-server provider", () => { text: "Found the path.", }, }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { threadId: "child-thread-1", turn: { status: "completed" }, }); @@ -3332,12 +3364,15 @@ describe("Codex app-server provider", () => { threadId: "settled-child-thread", agentPath: "/root/settled-child", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn({ threadId: "settled-child-thread" }); + await new Promise((resolve) => setImmediate(resolve)); appServer.says({ threadId: "settled-child-thread", itemId: "late-child-message", text: "Late trailing output.", }); + await new Promise((resolve) => setImmediate(resolve)); const providerUpserts = events.flatMap((event) => event.type === "provider_subagent" && event.event.type === "upsert" ? [event.event] : [], @@ -3361,6 +3396,7 @@ describe("Codex app-server provider", () => { agentPath: "/root/settled-child", kind: "interacted", }); + await new Promise((resolve) => setImmediate(resolve)); expect( events.findLast( (event) => event.type === "provider_subagent" && event.event.type === "upsert", @@ -3371,6 +3407,7 @@ describe("Codex app-server provider", () => { threadId: "settled-child-thread", turnId: "next-child-turn", }); + await new Promise((resolve) => setImmediate(resolve)); expect( events.findLast( (event) => event.type === "provider_subagent" && event.event.type === "upsert", @@ -3378,7 +3415,9 @@ describe("Codex app-server provider", () => { ).toMatchObject({ event: { id: "settled-child-thread", status: "running" } }); appServer.completeTurn({ threadId: "settled-child-thread" }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); await resultPromise; appServer.assertNoErrors(); } finally { @@ -3386,12 +3425,12 @@ describe("Codex app-server provider", () => { } }); - test("updates a registered child with its later native activity name", () => { + test("updates a registered child with its later native activity name", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "collabAgentToolCall", @@ -3405,7 +3444,7 @@ describe("Codex app-server provider", () => { }, }, }); - asInternals(session).handleNotification("item/started", { + await asInternals(session).handleNotification("item/started", { threadId: "test-thread", item: { type: "subAgentActivity", @@ -3440,11 +3479,11 @@ describe("Codex app-server provider", () => { }); }); - test("renders child MCP image results in the provider subagent timeline", () => { + test("renders child MCP image results in the provider subagent timeline", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "subAgentActivity", @@ -3455,7 +3494,7 @@ describe("Codex app-server provider", () => { }, }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "image-child-thread", item: { id: "child-mcp-image", @@ -3488,11 +3527,11 @@ describe("Codex app-server provider", () => { rmSync(source, { force: true }); }); - test("renders a child user message once across lifecycle notifications", () => { + test("renders a child user message once across lifecycle notifications", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "subAgentActivity", @@ -3508,11 +3547,11 @@ describe("Codex app-server provider", () => { content: [{ type: "text", text: "Inspect this path." }], }; - asInternals(session).handleNotification("item/started", { + await asInternals(session).handleNotification("item/started", { threadId: "user-child-thread", item: childUserMessage, }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "user-child-thread", item: childUserMessage, }); @@ -3546,19 +3585,24 @@ describe("Codex app-server provider", () => { threadId: "child-thread-1", agentPath: "/root/child", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.says({ threadId: "child-thread-1", itemId: "child-message-1", text: "Child findings.", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn({ threadId: "child-thread-1" }); + await new Promise((resolve) => setImmediate(resolve)); appServer.says({ threadId: "thread-1", itemId: "parent-message-1", text: "Parent report.", chunks: ["Parent ", "report."], }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); const result = await resultPromise; expect(result.finalText).toBe("Parent report."); @@ -3592,13 +3636,16 @@ describe("Codex app-server provider", () => { itemId: "first-parent-message", text: "First report.", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.says({ threadId: "thread-1", itemId: "second-parent-message", text: "Second report.", chunks: ["", "Second report."], }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); const result = await resultPromise; expect(result.finalText).toBe("Second report."); @@ -3623,8 +3670,11 @@ describe("Codex app-server provider", () => { await appServer.waitForTurnStart(); appServer.says({ threadId: "thread-1", text: "First report." }); + await new Promise((resolve) => setImmediate(resolve)); appServer.says({ threadId: "thread-1", text: "Second report." }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); const result = await resultPromise; expect(result.finalText).toBe("Second report."); @@ -3648,23 +3698,29 @@ describe("Codex app-server provider", () => { await appServer.waitForTurnStart(); appServer.startsTurn({ threadId: "child-thread-early" }); + await new Promise((resolve) => setImmediate(resolve)); appServer.says({ threadId: "child-thread-early", itemId: "child-message-early", text: "Early child findings.", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn({ threadId: "child-thread-early" }); + await new Promise((resolve) => setImmediate(resolve)); appServer.startsSubAgent({ callId: "spawn-child-early", threadId: "child-thread-early", agentPath: "/root/early-child", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.says({ threadId: "thread-1", itemId: "parent-message-after-early-child", text: "Parent report after replay.", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); const result = await resultPromise; expect(result.finalText).toBe("Parent report after replay."); @@ -3708,36 +3764,43 @@ describe("Codex app-server provider", () => { threadId: "child-thread-stable", agentPath: "/root/stable-child", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.beginsSubAgentActivity({ callId: "message-child-stable", threadId: "child-thread-stable", agentPath: "/root/stable-child", kind: "interacted", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completesSubAgentActivity({ callId: "message-child-stable", threadId: "child-thread-stable", agentPath: "/root/stable-child", kind: "interacted", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.says({ threadId: "child-thread-stable", itemId: "stable-child-message", text: "Still on the same card.", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.beginsSubAgentActivity({ callId: "interrupt-child-stable", threadId: "child-thread-stable", agentPath: "/root/stable-child", kind: "interrupted", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completesSubAgentActivity({ callId: "interrupt-child-stable", threadId: "child-thread-stable", agentPath: "/root/stable-child", kind: "interrupted", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); const result = await resultPromise; const toolCalls = result.timeline.filter((item) => item.type === "tool_call"); @@ -3772,6 +3835,7 @@ describe("Codex app-server provider", () => { await appServer.waitForTurnStart(); appServer.completeTurn({ threadId: "child-thread-fast" }); + await new Promise((resolve) => setImmediate(resolve)); const activity = { callId: "spawn-child-fast", threadId: "child-thread-fast", @@ -3779,8 +3843,11 @@ describe("Codex app-server provider", () => { kind: "started" as const, }; appServer.beginsSubAgentActivity(activity); + await new Promise((resolve) => setImmediate(resolve)); appServer.completesSubAgentActivity(activity); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); const result = await resultPromise; const toolCalls = result.timeline.filter((item) => item.type === "tool_call"); @@ -3809,16 +3876,20 @@ describe("Codex app-server provider", () => { await appServer.waitForTurnStart(); appServer.completeTurn({ threadId: "child-late-compaction" }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completesCompaction({ threadId: "child-late-compaction", itemId: "late-child-compaction", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.startsSubAgent({ callId: "spawn-child-late-compaction", threadId: "child-late-compaction", agentPath: "/root/late-compaction", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); const result = await resultPromise; const toolCalls = result.timeline.filter((item) => item.type === "tool_call"); @@ -3852,6 +3923,7 @@ describe("Codex app-server provider", () => { threadId: "legacy-tool-child", agentPath: "/root/legacy-tool-child", }); + await new Promise((resolve) => setImmediate(resolve)); const command = { threadId: "legacy-tool-child", callId: "legacy-child-command", @@ -3859,15 +3931,20 @@ describe("Codex app-server provider", () => { output: "child output", }; appServer.runsLegacyCommand(command); + await new Promise((resolve) => setImmediate(resolve)); appServer.completesCommand(command); + await new Promise((resolve) => setImmediate(resolve)); appServer.appliesLegacyPatch({ threadId: "legacy-tool-child", callId: "legacy-child-patch", path: "/workspace/project/src/child.ts", diff: "@@\n-old\n+new\n", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn({ threadId: "legacy-tool-child" }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); const result = await resultPromise; const toolCalls = result.timeline.filter((item) => item.type === "tool_call"); @@ -3890,12 +3967,12 @@ describe("Codex app-server provider", () => { } }); - test("keeps nested MultiAgentV2 output inside the root sub-agent card", () => { + test("keeps nested MultiAgentV2 output inside the root sub-agent card", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "subAgentActivity", @@ -3905,7 +3982,7 @@ describe("Codex app-server provider", () => { agentPath: "/root/child", }, }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "child-thread-root", item: { type: "subAgentActivity", @@ -3915,12 +3992,12 @@ describe("Codex app-server provider", () => { agentPath: "/root/child/grandchild", }, }); - asInternals(session).handleNotification("item/agentMessage/delta", { + await asInternals(session).handleNotification("item/agentMessage/delta", { threadId: "grandchild-thread", itemId: "grandchild-message", delta: "Grandchild findings.", }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { threadId: "grandchild-thread", turn: { status: "completed" }, }); @@ -3953,7 +4030,7 @@ describe("Codex app-server provider", () => { detail: { type: "sub_agent", log: expect.stringContaining("Grandchild findings.") }, }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { threadId: "child-thread-root", turn: { status: "completed" }, }); @@ -3963,12 +4040,12 @@ describe("Codex app-server provider", () => { }); }); - test("keeps a nested child under its spawning parent after a root interaction", () => { + test("keeps a nested child under its spawning parent after a root interaction", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "subAgentActivity", @@ -3978,7 +4055,7 @@ describe("Codex app-server provider", () => { agentPath: "/root/child", }, }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "child-thread-root", item: { type: "subAgentActivity", @@ -3988,7 +4065,7 @@ describe("Codex app-server provider", () => { agentPath: "/root/child/grandchild", }, }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "collabAgentToolCall", @@ -4001,7 +4078,7 @@ describe("Codex app-server provider", () => { }, }, }); - asInternals(session).handleNotification("item/agentMessage/delta", { + await asInternals(session).handleNotification("item/agentMessage/delta", { threadId: "grandchild-thread", itemId: "grandchild-after-wait", delta: "Still nested.", @@ -4027,28 +4104,28 @@ describe("Codex app-server provider", () => { }); }); - test("never treats an unmapped foreign terminal as the root terminal", () => { + test("never treats an unmapped foreign terminal as the root terminal", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { threadId: "unmapped-child-thread", turn: { status: "completed" }, }); expect(events).toEqual([]); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { threadId: "test-thread", turn: { status: "completed" }, }); expect(events.filter((event) => event.type === "turn_completed")).toHaveLength(1); - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { threadId: "test-thread", turn: { id: "next-root-turn" }, }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "subAgentActivity", @@ -4064,12 +4141,12 @@ describe("Codex app-server provider", () => { }); }); - test("routes msg-scoped legacy Codex events to their child thread", () => { + test("routes msg-scoped legacy Codex events to their child thread", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "subAgentActivity", @@ -4079,7 +4156,7 @@ describe("Codex app-server provider", () => { agentPath: "/root/legacy-envelope-child", }, }); - asInternals(session).handleNotification("codex/event/exec_command_begin", { + await asInternals(session).handleNotification("codex/event/exec_command_begin", { msg: { type: "exec_command_begin", threadId: "legacy-envelope-child", @@ -4087,7 +4164,7 @@ describe("Codex app-server provider", () => { command: "pwd", }, }); - asInternals(session).handleNotification("codex/event/task_complete", { + await asInternals(session).handleNotification("codex/event/task_complete", { msg: { type: "task_complete", thread_id: "legacy-envelope-child", @@ -4125,7 +4202,7 @@ describe("Codex app-server provider", () => { }, }); - asInternals(session).handleNotification("codex/event/task_complete", { + await asInternals(session).handleNotification("codex/event/task_complete", { msg: { type: "task_complete" }, }); expect(events.filter((event) => event.type === "turn_completed")).toHaveLength(1); @@ -4147,11 +4224,13 @@ describe("Codex app-server provider", () => { const spawn = waitForTimelineToolCall(session, "spawn-legacy-only-child"); appServer.startsTurn({ threadId: "thread-1", turnId: "turn-with-legacy-only-child" }); + await new Promise((resolve) => setImmediate(resolve)); appServer.startsLegacyOnlySubAgent({ callId: "spawn-legacy-only-child", threadId: "legacy-only-child-thread", agentPath: "/root/legacy-only-child", }); + await new Promise((resolve) => setImmediate(resolve)); await expect(child).resolves.toMatchObject({ type: "provider_subagent", @@ -4179,6 +4258,7 @@ describe("Codex app-server provider", () => { }); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); await resultPromise; appServer.assertNoErrors(); } finally { @@ -4203,10 +4283,12 @@ describe("Codex app-server provider", () => { const resultPromise = session.run("Wait for the child."); await appServer.waitForTurnStart(); appServer.startsTurn({ threadId: "thread-1", turnId: "turn-waiting-for-child" }); + await new Promise((resolve) => setImmediate(resolve)); await expect(session.interrupt()).rejects.toThrow("A foreground turn is already active"); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); await resultPromise; appServer.assertNoErrors(); } finally { @@ -4231,10 +4313,12 @@ describe("Codex app-server provider", () => { const resultPromise = session.run("Wait for the child."); await appServer.waitForTurnStart(); appServer.startsTurn({ threadId: "thread-1", turnId: "turn-already-idle" }); + await new Promise((resolve) => setImmediate(resolve)); await expect(session.interrupt()).resolves.toBeUndefined(); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); await resultPromise; appServer.assertNoErrors(); } finally { @@ -4263,10 +4347,12 @@ describe("Codex app-server provider", () => { const interruptPromise = session.interrupt(); appServer.startsTurn({ threadId: "thread-1", turnId: "turn-identified-late" }); + await new Promise((resolve) => setImmediate(resolve)); await interruptPromise; expect(interruptedTurns).toEqual([{ threadId: "thread-1", turnId: "turn-identified-late" }]); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); await resultPromise; appServer.assertNoErrors(); } finally { @@ -4294,6 +4380,7 @@ describe("Codex app-server provider", () => { await appServer.waitForTurnStart(); const interruptPromise = session.interrupt(); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); await expect(interruptPromise).resolves.toBeUndefined(); await resultPromise; @@ -4353,7 +4440,9 @@ describe("Codex app-server provider", () => { const nativeStart = await appServer.waitForTurnStart().catch(() => null); if (nativeStart) { appServer.startsTurn({ threadId: "thread-1", turnId: "cleanup-turn" }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); } await resultPromise.catch(() => undefined); await session.close(); @@ -4371,7 +4460,7 @@ describe("Codex app-server provider", () => { }, }; - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { threadId: "test-thread", turn: { id: "autonomous-turn" }, }); @@ -4387,13 +4476,13 @@ describe("Codex app-server provider", () => { }); }); - test("never replaces the root identity with an early child thread start", () => { + test("never replaces the root identity with an early child thread start", async () => { const session = createSession(); - asInternals(session).handleNotification("thread/started", { + await asInternals(session).handleNotification("thread/started", { thread: { id: "child-thread-started-early" }, }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "subAgentActivity", @@ -4407,12 +4496,12 @@ describe("Codex app-server provider", () => { expect(session.currentThreadId).toBe("test-thread"); }); - test("does not leak aggregate child telemetry into the root timeline", () => { + test("does not leak aggregate child telemetry into the root timeline", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "subAgentActivity", @@ -4424,7 +4513,7 @@ describe("Codex app-server provider", () => { }); const eventCountAfterSpawn = events.length; - asInternals(session).handleNotification("turn/plan/updated", { + await asInternals(session).handleNotification("turn/plan/updated", { threadId: "child-thread-telemetry", plan: [{ step: "Child-only plan", status: "inProgress" }], }); @@ -4432,12 +4521,12 @@ describe("Codex app-server provider", () => { expect(events).toHaveLength(eventCountAfterSpawn); }); - test("keeps child context compaction inside the child card", () => { + test("keeps child context compaction inside the child card", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "subAgentActivity", @@ -4447,11 +4536,11 @@ describe("Codex app-server provider", () => { agentPath: "/root/compacting-child", }, }); - asInternals(session).handleNotification("item/started", { + await asInternals(session).handleNotification("item/started", { threadId: "child-thread-compaction", item: { type: "contextCompaction", id: "child-compaction" }, }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "child-thread-compaction", item: { type: "contextCompaction", id: "child-compaction" }, }); @@ -4471,12 +4560,12 @@ describe("Codex app-server provider", () => { }); }); - test("keeps the parent sub-agent running when a child command fails during the child turn", () => { + test("keeps the parent sub-agent running when a child command fails during the child turn", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "collabAgentToolCall", @@ -4490,7 +4579,7 @@ describe("Codex app-server provider", () => { }, }, }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "child-thread-1", item: { type: "commandExecution", @@ -4517,12 +4606,12 @@ describe("Codex app-server provider", () => { }); }); - test("does not synthesize a parent sub-agent failure from child error state alone", () => { + test("does not synthesize a parent sub-agent failure from child error state alone", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "collabAgentToolCall", @@ -4773,11 +4862,11 @@ describe("Codex app-server provider", () => { const liveEvents: AgentStreamEvent[] = []; session.subscribe((event) => liveEvents.push(event)); - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { threadId: "v2-child-thread", turn: { id: "v2-child-turn-after-resume" }, }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "subAgentActivity", @@ -4787,7 +4876,7 @@ describe("Codex app-server provider", () => { agentPath: "/root/v2-child", }, }); - asInternals(session).handleNotification("item/agentMessage/delta", { + await asInternals(session).handleNotification("item/agentMessage/delta", { threadId: "v2-child-thread", itemId: "v2-child-message-after-resume", delta: "More findings after resume.", @@ -4805,11 +4894,11 @@ describe("Codex app-server provider", () => { }); liveEvents.length = 0; - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { threadId: "legacy-child-thread", turn: { id: "legacy-child-turn-after-resume" }, }); - asInternals(session).handleNotification("item/agentMessage/delta", { + await asInternals(session).handleNotification("item/agentMessage/delta", { threadId: "legacy-child-thread", itemId: "legacy-child-message-after-resume", delta: "Legacy findings after resume.", @@ -5058,6 +5147,7 @@ describe("Codex app-server provider", () => { threadId: "child-thread", agentPath: "/root/child", }); + await new Promise((resolve) => setImmediate(resolve)); await child; appServer.beginsSubAgentActivity({ callId: "parent-interacted", @@ -5066,7 +5156,9 @@ describe("Codex app-server provider", () => { kind: "interacted", agentPath: "/root", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); await resultPromise; expect(providerSubagentIds).toEqual(new Set(["child-thread"])); @@ -5198,7 +5290,7 @@ describe("Codex app-server provider", () => { ]); }); - test("captures live Codex user message ids from item events", () => { + test("captures live Codex user message ids from item events", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); @@ -5209,11 +5301,11 @@ describe("Codex app-server provider", () => { content: [{ type: "text", text: "Use the native Codex id." }], }; - asInternals(session).handleNotification("item/started", { + await asInternals(session).handleNotification("item/started", { threadId: "test-thread", item: userMessageItem, }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: userMessageItem, }); @@ -5232,19 +5324,19 @@ describe("Codex app-server provider", () => { ]); }); - test("emits Codex context compaction markers from live thread items", () => { + test("emits Codex context compaction markers from live thread items", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/started", { + await asInternals(session).handleNotification("item/started", { threadId: "test-thread", item: { type: "contextCompaction", id: "compact-live", }, }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "contextCompaction", @@ -5282,7 +5374,9 @@ describe("Codex app-server provider", () => { threadId: "thread-1", itemId: "compact-without-completion", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); await terminalEvent; expect( @@ -5304,11 +5398,14 @@ describe("Codex app-server provider", () => { threadId: "thread-1", itemId: "compact-completed-normally", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completesCompaction({ threadId: "thread-1", itemId: "compact-completed-normally", }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); await terminalEvent; expect( @@ -5327,8 +5424,11 @@ describe("Codex app-server provider", () => { try { appServer.startsCompaction({ threadId: "thread-1", itemId: "current-compaction" }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completesCompaction({ threadId: "thread-1", itemId: "older-compaction" }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn(); + await new Promise((resolve) => setImmediate(resolve)); await terminalEvent; expect( @@ -5350,10 +5450,12 @@ describe("Codex app-server provider", () => { try { appServer.startsCompaction({ threadId: "thread-1", itemId: `compact-${status}` }); + await new Promise((resolve) => setImmediate(resolve)); appServer.completeTurn({ status, error: status === "failed" ? { message: "Compaction failed" } : null, }); + await new Promise((resolve) => setImmediate(resolve)); await terminalEvent; expect( @@ -5367,17 +5469,17 @@ describe("Codex app-server provider", () => { } }); - test("emits and dedupes Codex thread/compacted notifications", () => { + test("emits and dedupes Codex thread/compacted notifications", async () => { const session = createSession(); session.activeForegroundTurnId = null; const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("thread/compacted", { + await asInternals(session).handleNotification("thread/compacted", { threadId: "test-thread", turnId: "legacy-compact-turn", }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "contextCompaction", @@ -5398,17 +5500,17 @@ describe("Codex app-server provider", () => { ]); }); - test("emits consecutive Codex thread/compacted notifications", () => { + test("emits consecutive Codex thread/compacted notifications", async () => { const session = createSession(); session.activeForegroundTurnId = null; const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("thread/compacted", { + await asInternals(session).handleNotification("thread/compacted", { threadId: "test-thread", turnId: "legacy-compact-turn-1", }); - asInternals(session).handleNotification("thread/compacted", { + await asInternals(session).handleNotification("thread/compacted", { threadId: "test-thread", turnId: "legacy-compact-turn-2", }); @@ -5534,14 +5636,14 @@ describe("Codex app-server provider", () => { const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); await handler?.run({ emit: (event) => events.push(event) }); - asInternals(session).handleNotification("item/started", { + await asInternals(session).handleNotification("item/started", { threadId: "test-thread", item: { type: "contextCompaction", id: "manual-compact", }, }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { threadId: "test-thread", item: { type: "contextCompaction", @@ -5656,23 +5758,23 @@ describe("Codex app-server provider", () => { }); }); - test("emits a synthetic plan approval permission after a successful Codex plan turn", () => { + test("emits a synthetic plan approval permission after a successful Codex plan turn", async () => { const session = createSession({ featureValues: { plan_mode: true, fast_mode: true }, }); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { turn: { id: "turn-plan-1" }, }); - asInternals(session).handleNotification("turn/plan/updated", { + await asInternals(session).handleNotification("turn/plan/updated", { plan: [ { step: "Inspect the existing auth flow", status: "completed" }, { step: "Implement the button behavior", status: "pending" }, ], }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { turn: { status: "completed", error: null }, }); @@ -5726,24 +5828,24 @@ describe("Codex app-server provider", () => { }); }); - test("does not complete Codex plan timeline cards while plan approval is pending", () => { + test("does not complete Codex plan timeline cards while plan approval is pending", async () => { const session = createSession({ featureValues: { plan_mode: true, fast_mode: true }, }); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { turn: { id: "turn-plan-thread-item" }, }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { item: { id: "plan-item-1", type: "plan", text: "- Inspect README\n- Add a short note", }, }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { turn: { status: "completed", error: null }, }); @@ -5772,28 +5874,28 @@ describe("Codex app-server provider", () => { }); }); - test("replaces a pending synthetic plan approval when a later plan completes", () => { + test("replaces a pending synthetic plan approval when a later plan completes", async () => { const session = createSession({ featureValues: { plan_mode: true }, }); - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { turn: { id: "turn-plan-first" }, }); - asInternals(session).handleNotification("turn/plan/updated", { + await asInternals(session).handleNotification("turn/plan/updated", { plan: [{ step: "Implement the first plan", status: "pending" }], }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { turn: { status: "completed", error: null }, }); - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { turn: { id: "turn-plan-second" }, }); - asInternals(session).handleNotification("turn/plan/updated", { + await asInternals(session).handleNotification("turn/plan/updated", { plan: [{ step: "Implement the revised plan", status: "pending" }], }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { turn: { status: "completed", error: null }, }); @@ -5812,13 +5914,13 @@ describe("Codex app-server provider", () => { const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { turn: { id: "turn-plan-pending" }, }); - asInternals(session).handleNotification("turn/plan/updated", { + await asInternals(session).handleNotification("turn/plan/updated", { plan: [{ step: "Implement the original plan", status: "pending" }], }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { turn: { status: "completed", error: null }, }); const pendingPlan = session.getPendingPermissions()[0]; @@ -5852,13 +5954,13 @@ describe("Codex app-server provider", () => { featureValues: { plan_mode: true }, }); - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { turn: { id: "turn-plan-pending" }, }); - asInternals(session).handleNotification("turn/plan/updated", { + await asInternals(session).handleNotification("turn/plan/updated", { plan: [{ step: "Implement the original plan", status: "pending" }], }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { turn: { status: "completed", error: null }, }); const pendingPlan = session.getPendingPermissions()[0]; @@ -5906,13 +6008,13 @@ describe("Codex app-server provider", () => { featureValues: { plan_mode: true }, }); - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { turn: { id: "turn-plan-pending" }, }); - asInternals(session).handleNotification("turn/plan/updated", { + await asInternals(session).handleNotification("turn/plan/updated", { plan: [{ step: "Implement the original plan", status: "pending" }], }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { turn: { status: "completed", error: null }, }); @@ -5937,10 +6039,10 @@ describe("Codex app-server provider", () => { const startTurn = session.startTurn("Revise the plan"); await promptRequested; - asInternals(session).handleNotification("turn/plan/updated", { + await asInternals(session).handleNotification("turn/plan/updated", { plan: [{ step: "Implement the newer plan", status: "pending" }], }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { turn: { status: "completed", error: null }, }); acceptPrompt?.(); @@ -5956,13 +6058,13 @@ describe("Codex app-server provider", () => { featureValues: { plan_mode: true }, }); - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { turn: { id: "turn-plan-pending" }, }); - asInternals(session).handleNotification("turn/plan/updated", { + await asInternals(session).handleNotification("turn/plan/updated", { plan: [{ step: "Implement the original plan", status: "pending" }], }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { turn: { status: "completed", error: null }, }); const pendingPlan = session.getPendingPermissions()[0]; @@ -5982,12 +6084,12 @@ describe("Codex app-server provider", () => { expect(session.getPendingPermissions()).toEqual([]); }); - test("emits imageView paths with spaces as valid assistant markdown images", () => { + test("emits imageView paths with spaces as valid assistant markdown images", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { item: { id: "image-view-1", type: "imageView", @@ -6013,12 +6115,12 @@ describe("Codex app-server provider", () => { ["saved_path", { saved_path: "/tmp/generated-snake.png" }, "file:///tmp/generated-snake.png"], ])( "emits imageGeneration thread items with %s as assistant markdown images", - (_fieldName, imageFields, expectedPath) => { + async (_fieldName, imageFields, expectedPath) => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { item: { id: `image-generation-${_fieldName}`, type: "imageGeneration", @@ -6041,12 +6143,12 @@ describe("Codex app-server provider", () => { }, ); - test("materializes imageGeneration base64 results before rendering markdown", () => { + test("materializes imageGeneration base64 results before rendering markdown", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { item: { id: "image-generation-base64", type: "imageGeneration", @@ -6194,21 +6296,22 @@ describe("Codex app-server provider", () => { } }); - test("ignores incomplete imageGeneration thread items without failing the turn", () => { + test("ignores incomplete imageGeneration thread items without failing the turn", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - expect(() => - asInternals(session).handleNotification("item/completed", { - item: { - id: "image-generation-incomplete", - type: "imageGeneration", - status: "in_progress", - }, - }), + expect( + async () => + await asInternals(session).handleNotification("item/completed", { + item: { + id: "image-generation-incomplete", + type: "imageGeneration", + status: "in_progress", + }, + }), ).not.toThrow(); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { turn: { status: "completed", error: null }, }); @@ -6231,12 +6334,12 @@ describe("Codex app-server provider", () => { ["no failure details", null, { message: "Image generation failed" }], ])( "emits failed imageGeneration items with %s as failed tool calls", - (_label, failure, expectedError) => { + async (_label, failure, expectedError) => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { item: { id: "image-generation-failed", type: "imageGeneration", @@ -6323,12 +6426,12 @@ describe("Codex app-server provider", () => { ]); }); - test("emits usage_updated on token usage updates and keeps usage on turn completion", () => { + test("emits usage_updated on token usage updates and keeps usage on turn completion", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("thread/tokenUsage/updated", { + await asInternals(session).handleNotification("thread/tokenUsage/updated", { tokenUsage: { model_context_window: 200000, last: { @@ -6339,7 +6442,7 @@ describe("Codex app-server provider", () => { }, }, }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { turn: { status: "completed", error: null }, }); @@ -6369,20 +6472,20 @@ describe("Codex app-server provider", () => { }); }); - test("streams Codex assistant message deltas and does not replay completed text", () => { + test("streams Codex assistant message deltas and does not replay completed text", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/agentMessage/delta", { + await asInternals(session).handleNotification("item/agentMessage/delta", { itemId: "assistant-item-1", delta: "Hel", }); - asInternals(session).handleNotification("item/agentMessage/delta", { + await asInternals(session).handleNotification("item/agentMessage/delta", { itemId: "assistant-item-1", delta: "lo", }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { item: { id: "assistant-item-1", type: "agentMessage", @@ -6406,20 +6509,20 @@ describe("Codex app-server provider", () => { ]); }); - test("emits only the missing assistant suffix when completed text extends streamed deltas", () => { + test("emits only the missing assistant suffix when completed text extends streamed deltas", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/agentMessage/delta", { + await asInternals(session).handleNotification("item/agentMessage/delta", { itemId: "assistant-item-2", delta: "Hel", }); - asInternals(session).handleNotification("item/agentMessage/delta", { + await asInternals(session).handleNotification("item/agentMessage/delta", { itemId: "assistant-item-2", delta: "lo", }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { item: { id: "assistant-item-2", type: "agentMessage", @@ -6449,24 +6552,24 @@ describe("Codex app-server provider", () => { ]); }); - test("emits a markdown divider when a new Codex assistant item starts after the previous one completed", () => { + test("emits a markdown divider when a new Codex assistant item starts after the previous one completed", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/agentMessage/delta", { + await asInternals(session).handleNotification("item/agentMessage/delta", { itemId: "assistant-item-3", delta: "I’m in the waiting phase now. The next read is intentionally delayed so we get meaningful CI state instead of churn.", }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { item: { id: "assistant-item-3", type: "agentMessage", text: "I’m in the waiting phase now. The next read is intentionally delayed so we get meaningful CI state instead of churn.", }, }); - asInternals(session).handleNotification("item/agentMessage/delta", { + await asInternals(session).handleNotification("item/agentMessage/delta", { itemId: "assistant-item-4", delta: "CI is still cooking. I’m staying on the current run rather than jumping around, because the first red job will tell us exactly whether anything else needs work.", @@ -6496,20 +6599,20 @@ describe("Codex app-server provider", () => { ]); }); - test("streams Codex reasoning deltas and does not replay completed reasoning", () => { + test("streams Codex reasoning deltas and does not replay completed reasoning", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/reasoning/summaryTextDelta", { + await asInternals(session).handleNotification("item/reasoning/summaryTextDelta", { itemId: "reasoning-item-1", delta: "Think", }); - asInternals(session).handleNotification("item/reasoning/summaryTextDelta", { + await asInternals(session).handleNotification("item/reasoning/summaryTextDelta", { itemId: "reasoning-item-1", delta: "ing", }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { item: { id: "reasoning-item-1", type: "reasoning", @@ -6533,20 +6636,20 @@ describe("Codex app-server provider", () => { ]); }); - test("emits only the missing reasoning suffix when completed reasoning extends streamed deltas", () => { + test("emits only the missing reasoning suffix when completed reasoning extends streamed deltas", async () => { const session = createSession(); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("item/reasoning/summaryTextDelta", { + await asInternals(session).handleNotification("item/reasoning/summaryTextDelta", { itemId: "reasoning-item-2", delta: "Think", }); - asInternals(session).handleNotification("item/reasoning/summaryTextDelta", { + await asInternals(session).handleNotification("item/reasoning/summaryTextDelta", { itemId: "reasoning-item-2", delta: "ing", }); - asInternals(session).handleNotification("item/completed", { + await asInternals(session).handleNotification("item/completed", { item: { id: "reasoning-item-2", type: "reasoning", @@ -6583,13 +6686,13 @@ describe("Codex app-server provider", () => { const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { turn: { id: "turn-plan-2" }, }); - asInternals(session).handleNotification("turn/plan/updated", { + await asInternals(session).handleNotification("turn/plan/updated", { plan: [{ step: "Implement the new flow", status: "pending" }], }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { turn: { status: "completed", error: null }, }); @@ -6637,13 +6740,13 @@ describe("Codex app-server provider", () => { const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { turn: { id: "turn-plan-3" }, }); - asInternals(session).handleNotification("turn/plan/updated", { + await asInternals(session).handleNotification("turn/plan/updated", { plan: [{ step: "Implement the safe flow", status: "pending" }], }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { turn: { status: "completed", error: null }, }); @@ -6705,13 +6808,13 @@ describe("Codex app-server provider", () => { const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); - asInternals(session).handleNotification("turn/started", { + await asInternals(session).handleNotification("turn/started", { turn: { id: "turn-plan-4" }, }); - asInternals(session).handleNotification("turn/plan/updated", { + await asInternals(session).handleNotification("turn/plan/updated", { plan: [{ step: "Implement the fast flow", status: "pending" }], }); - asInternals(session).handleNotification("turn/completed", { + await asInternals(session).handleNotification("turn/completed", { turn: { status: "completed", error: null }, }); @@ -7182,6 +7285,7 @@ test("Codex runtime safety queries live terminals and retains unsupported app se await appServer.waitForTurnStart(); expect(await session.canStopRuntime()).toBe(false); appServer.completeTurn({ threadId: "thread-1" }); + await new Promise((resolve) => setImmediate(resolve)); await expect.poll(() => session.canStopRuntime()).toBe(true); response = { data: [{ processId: "shell-1" }], nextCursor: null }; expect(await session.canStopRuntime()).toBe(false); @@ -7199,3 +7303,60 @@ test("Codex runtime safety queries live terminals and retains unsupported app se await session.close(); } }); + +test("publishes a materialized image before dispatching the following turn completion", async () => { + const appServer = createFakeCodexAppServer(); + const session = new CodexAppServerAgentSession( + createConfig(), + null, + createTestLogger(), + async () => appServer.child, + ); + const events: AgentStreamEvent[] = []; + session.subscribe((event) => events.push(event)); + try { + await session.startTurn("generate an image"); + const data = Buffer.alloc(1024 * 1024, 47).toString("base64"); + const imageFrame = + JSON.stringify({ + method: "item/completed", + params: { + item: { + id: "ordered-image", + type: "imageGeneration", + status: "completed", + result: { data, mimeType: "image/png" }, + }, + }, + }) + "\n"; + const completed = new Promise((resolve) => + session.subscribe((event) => { + if (event.type === "turn_completed") resolve(); + }), + ); + appServer.child.stdout.write(imageFrame); + appServer.child.stdout.write( + JSON.stringify({ + method: "turn/completed", + params: { turn: { status: "completed", error: null } }, + }) + "\n", + ); + await completed; + await new Promise((resolve) => setTimeout(resolve, 5)); + const imageIndex = events.findIndex( + (event) => + event.type === "timeline" && + event.item.type === "assistant_message" && + event.item.text.includes("![Image]"), + ); + const completedIndex = events.findIndex((event) => event.type === "turn_completed"); + expect(imageIndex).toBeGreaterThanOrEqual(0); + expect(imageIndex).toBeLessThan(completedIndex); + const imageEvent = events[imageIndex]; + if (imageEvent.type !== "timeline" || imageEvent.item.type !== "assistant_message") + throw new Error("Expected image"); + expect(existsSync(markdownImageSource(imageEvent.item.text))).toBe(true); + } finally { + await session.close(); + } +}); diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.ts index f438c98ec4..291841c730 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.ts @@ -1939,12 +1939,12 @@ function codexImageOutputFromResult(result: unknown): ProviderImageOutput | null }; } -function mapCodexThreadImageItem( +async function mapCodexThreadImageItem( normalizedType: string, normalizedItem: Record, -): AgentTimelineItem | null { +): Promise { if (normalizedType === "imageView") { - return renderProviderImageOutputAsAssistantMarkdown({ + return await renderProviderImageOutputAsAssistantMarkdown({ path: firstStringField(normalizedItem, ["path"]), }); } @@ -1960,7 +1960,7 @@ function mapCodexThreadImageItem( const savedPath = firstStringField(normalizedItem, ["savedPath", "saved_path"]); const result = codexImageOutputFromResult(normalizedItem.result); - return renderProviderImageOutputAsAssistantMarkdown( + return await renderProviderImageOutputAsAssistantMarkdown( { path: savedPath ?? result?.path ?? null, url: result?.url ?? null, @@ -1982,10 +1982,10 @@ function mapCodexAgentMessage(item: Record): AgentTimelineItem }; } -export function threadItemToTimeline( +export async function threadItemToTimeline( item: unknown, options?: { includeUserMessage?: boolean; cwd?: string | null }, -): AgentTimelineItem | null { +): Promise { const itemRecord = toObjectRecord(item); if (!itemRecord) return null; const includeUserMessage = options?.includeUserMessage ?? true; @@ -1999,7 +1999,7 @@ export function threadItemToTimeline( : itemRecord; if (normalizedType === "imageView" || normalizedType === "imageGeneration") { - return mapCodexThreadImageItem(normalizedType, normalizedItem); + return await mapCodexThreadImageItem(normalizedType, normalizedItem); } if (normalizedType && CODEX_TOOL_THREAD_ITEM_TYPES.has(normalizedType)) { return mapCodexToolCallFromThreadItem(normalizedItem, { cwd }); @@ -2024,7 +2024,7 @@ export function threadItemToTimeline( } } -function mcpToolResultImagesToTimeline(item: unknown): AgentTimelineItem[] { +async function mcpToolResultImagesToTimeline(item: unknown): Promise { const itemRecord = toObjectRecord(item); if (!itemRecord) { return []; @@ -2037,24 +2037,25 @@ function mcpToolResultImagesToTimeline(item: unknown): AgentTimelineItem[] { } const { images } = splitCodexMcpToolResultImages(itemRecord.result); - return images - .map((image) => - renderProviderImageOutputAsAssistantMarkdown(image, { - materialize: materializeProviderImage, - }), - ) - .filter((timelineItem): timelineItem is AgentTimelineItem => timelineItem !== null); + const items: AgentTimelineItem[] = []; + for (const image of images) { + const imageItem = await renderProviderImageOutputAsAssistantMarkdown(image, { + materialize: materializeProviderImage, + }); + if (imageItem) items.push(imageItem); + } + return items; } -function threadItemToTimelineEntries( +async function threadItemToTimelineEntries( item: unknown, options?: { includeUserMessage?: boolean; cwd?: string | null }, -): AgentTimelineItem[] { - const timelineItem = threadItemToTimeline(item, options); +): Promise { + const timelineItem = await threadItemToTimeline(item, options); if (!timelineItem) { return []; } - return [timelineItem, ...mcpToolResultImagesToTimeline(item)]; + return [timelineItem, ...(await mcpToolResultImagesToTimeline(item))]; } const CodexThreadReadResponseSchema = z @@ -2103,7 +2104,7 @@ async function loadCodexThreadHistoryTimeline(params: { historicalSubAgentActivity.agentThreadId, ); if (existingIndex !== undefined) { - const activityTimelineItem = threadItemToTimeline(item, { cwd: params.cwd }); + const activityTimelineItem = await threadItemToTimeline(item, { cwd: params.cwd }); updateHistoricalSubAgentActivity( timeline, existingIndex, @@ -2116,7 +2117,7 @@ async function loadCodexThreadHistoryTimeline(params: { continue; } } - for (const timelineItem of threadItemToTimelineEntries(item, { cwd: params.cwd })) { + for (const timelineItem of await threadItemToTimelineEntries(item, { cwd: params.cwd })) { const timestamp = readCodexHistoryTimestamp(item) ?? readCodexTurnHistoryTimestamp(turn, timelineItem); const settledTimelineItem = @@ -3290,10 +3291,12 @@ export async function codexAppServerTurnInputFromPrompt( } if (block.type === "image") { try { - const filePath = materializeProviderImage({ - data: block.data, - mimeType: block.mimeType, - }).path; + const filePath = ( + await materializeProviderImage({ + data: block.data, + mimeType: block.mimeType, + }) + ).path; output.push({ type: "localImage", path: filePath }); } catch (error) { const message = error instanceof Error ? error.message : String(error); @@ -4370,6 +4373,7 @@ export class CodexAppServerAgentSession implements AgentSession { this.dismissPendingPlanApprovals("Dismissed by a new prompt"); try { + await this.pendingNotifications; await this.connect(); if (!this.client) { throw new Error("Codex client not initialized"); @@ -5437,7 +5441,21 @@ export class CodexAppServerAgentSession implements AgentSession { return `codex-turn-${this.nextTurnOrdinal++}`; } - private handleNotification(method: string, params: unknown): void { + private pendingNotifications: Promise = Promise.resolve(); + + private handleNotification(method: string, params: unknown): Promise { + // An image must exist before its event, and completion must follow that event. + // Transport callbacks cannot await: the session owns their ordered drain. + const next = this.pendingNotifications.then(() => { + return this.closed ? undefined : this.processNotification(method, params); + }); + this.pendingNotifications = next.catch((error: unknown) => { + this.handleUnexpectedTermination(error instanceof Error ? error : new Error(String(error))); + }); + return this.pendingNotifications; + } + + private async processNotification(method: string, params: unknown): Promise { const notificationParams = toObjectRecord(params); if (method === "serverRequest/resolved" && typeof notificationParams?.requestId === "number") { const requestId = this.mcpElicitationPermissionIds.get(notificationParams.requestId); @@ -5467,13 +5485,16 @@ export class CodexAppServerAgentSession implements AgentSession { return; } if (route.kind === "sub_agent") { - this.dispatchSubAgentNotification(parsed, route.callId); + await this.dispatchSubAgentNotification(parsed, route.callId); return; } - this.dispatchParsedNotification(parsed); + await this.dispatchParsedNotification(parsed); } - private dispatchSubAgentNotification(parsed: ParsedCodexNotification, callId: string): void { + private async dispatchSubAgentNotification( + parsed: ParsedCodexNotification, + callId: string, + ): Promise { switch (parsed.kind) { case "thread_started": this.emitSubAgentActivityUpdate(callId, "running", { reopen: true }); @@ -5484,7 +5505,7 @@ export class CodexAppServerAgentSession implements AgentSession { case "reasoning_delta": case "item_started": case "item_completed": - this.dispatchParsedNotification(parsed); + await this.dispatchParsedNotification(parsed); return; case "exec_command_output_delta": case "file_change_output_delta": @@ -5510,7 +5531,7 @@ export class CodexAppServerAgentSession implements AgentSession { } } - private dispatchParsedNotification(parsed: ParsedCodexNotification): void { + private async dispatchParsedNotification(parsed: ParsedCodexNotification): Promise { if (isCodexDeltaNotification(parsed)) { this.handleCodexDeltaNotification(parsed); return; @@ -5555,10 +5576,10 @@ export class CodexAppServerAgentSession implements AgentSession { this.handlePatchApplyCompletedNotification(parsed); return; case "item_completed": - this.handleItemCompletedNotification(parsed); + await this.handleItemCompletedNotification(parsed); return; case "item_started": - this.handleItemStartedNotification(parsed); + await this.handleItemStartedNotification(parsed); return; case "invalid_payload": this.warnInvalidNotificationPayload(parsed.method, parsed.params); @@ -5600,7 +5621,7 @@ export class CodexAppServerAgentSession implements AgentSession { pending.push(parsed); } - private replayPendingSubAgentNotifications(threadIds: readonly string[]): void { + private async replayPendingSubAgentNotifications(threadIds: readonly string[]): Promise { for (const threadId of threadIds) { const pending = this.pendingSubAgentNotificationsByThreadId.get(threadId); if (!pending) { @@ -5612,7 +5633,7 @@ export class CodexAppServerAgentSession implements AgentSession { continue; } for (const parsed of pending) { - this.dispatchSubAgentNotification(parsed, callId); + await this.dispatchSubAgentNotification(parsed, callId); } } } @@ -6578,9 +6599,13 @@ export class CodexAppServerAgentSession implements AgentSession { } } - private handleItemCompletedNotification( + private ownsNotificationTurn(turnId: string | null): boolean { + return !this.closed && this.activeForegroundTurnId === turnId; + } + + private async handleItemCompletedNotification( parsed: Extract, - ): void { + ): Promise { // Codex emits mirrored lifecycle notifications via both `codex/event/item_*` // and canonical `item/*`. Render ordinary items only from the canonical // channel, but accept a legacy-only child announcement so it can establish @@ -6590,20 +6615,23 @@ export class CodexAppServerAgentSession implements AgentSession { } this.receiveAsyncQuestion(parsed.threadId, parsed.item); if (this.isUserMessageItem(parsed.item)) { - this.handleUserMessageItem(parsed); + await this.handleUserMessageItem(parsed); return; } const childSubAgentCallId = this.getSubAgentCallIdForThread(parsed.threadId); if (this.handleCompletedSpecialItem(parsed, childSubAgentCallId)) { return; } - const timelineItem = threadItemToTimeline(parsed.item, { + const foregroundTurnId = this.activeForegroundTurnId; + const timelineItem = await threadItemToTimeline(parsed.item, { includeUserMessage: false, cwd: this.config.cwd ?? null, }); if (!timelineItem) { return; } + const imageItems = await mcpToolResultImagesToTimeline(parsed.item); + if (!this.ownsNotificationTurn(foregroundTurnId)) return; const registeredChildThreadIds = timelineItem.type === "tool_call" ? this.registerSubAgentToolCall({ @@ -6613,12 +6641,11 @@ export class CodexAppServerAgentSession implements AgentSession { parentSubagentId: resolveCodexParentSubagentId(childSubAgentCallId, parsed.threadId), }) : []; - const imageItems = mcpToolResultImagesToTimeline(parsed.item); if (childSubAgentCallId) { this.emitCompletedProviderSubagentItem(parsed, timelineItem); this.handleSubAgentChildItemCompleted(childSubAgentCallId, parsed.item.id, timelineItem); this.emitProviderSubagentTimelineItems(parsed.threadId, imageItems); - this.replayPendingSubAgentNotifications(registeredChildThreadIds); + await this.replayPendingSubAgentNotifications(registeredChildThreadIds); return; } const normalizedItemType = normalizeCodexThreadItemType( @@ -6626,7 +6653,7 @@ export class CodexAppServerAgentSession implements AgentSession { ); const itemId = parsed.item.id; if (this.shouldSkipCompletedThreadItem(timelineItem, normalizedItemType, itemId)) { - this.replayPendingSubAgentNotifications(registeredChildThreadIds); + await this.replayPendingSubAgentNotifications(registeredChildThreadIds); return; } if (this.consumeStreamedTextCompletion(timelineItem, itemId)) { @@ -6637,7 +6664,7 @@ export class CodexAppServerAgentSession implements AgentSession { this.emittedItemCompletedIds.add(itemId); this.emittedItemStartedIds.delete(itemId); } - this.replayPendingSubAgentNotifications(registeredChildThreadIds); + await this.replayPendingSubAgentNotifications(registeredChildThreadIds); return; } this.applyBufferedDeltaTextToTimelineItem(timelineItem, itemId); @@ -6666,7 +6693,7 @@ export class CodexAppServerAgentSession implements AgentSession { this.pendingCommandOutputDeltas.delete(itemId); this.pendingFileChangeOutputDeltas.delete(itemId); } - this.replayPendingSubAgentNotifications(registeredChildThreadIds); + await this.replayPendingSubAgentNotifications(registeredChildThreadIds); } private consumeStreamedTextCompletion( @@ -6738,14 +6765,14 @@ export class CodexAppServerAgentSession implements AgentSession { } } - private handleItemStartedNotification( + private async handleItemStartedNotification( parsed: Extract, - ): void { + ): Promise { if (shouldIgnoreMirroredLifecycleItem(parsed.source, parsed.item)) { return; } if (this.isUserMessageItem(parsed.item)) { - this.handleUserMessageItem(parsed); + await this.handleUserMessageItem(parsed); return; } const childSubAgentCallId = this.getSubAgentCallIdForThread(parsed.threadId); @@ -6767,7 +6794,7 @@ export class CodexAppServerAgentSession implements AgentSession { if (this.handleRegisteredSubAgentActivity(parsed.item)) { return; } - const timelineItem = threadItemToTimeline(parsed.item, { + const timelineItem = await threadItemToTimeline(parsed.item, { includeUserMessage: false, cwd: this.config.cwd ?? null, }); @@ -6786,7 +6813,7 @@ export class CodexAppServerAgentSession implements AgentSession { this.upsertSubAgentChildItem(childSubAgentCallId, parsed.item.id, timelineItem); } this.emitSubAgentActivityUpdate(childSubAgentCallId, "running"); - this.replayPendingSubAgentNotifications(registeredChildThreadIds); + await this.replayPendingSubAgentNotifications(registeredChildThreadIds); return; } const normalizedItemType = normalizeCodexThreadItemType( @@ -6810,14 +6837,14 @@ export class CodexAppServerAgentSession implements AgentSession { this.pendingCommandOutputDeltas.delete(itemId); this.pendingFileChangeOutputDeltas.delete(itemId); } - this.replayPendingSubAgentNotifications(registeredChildThreadIds); + await this.replayPendingSubAgentNotifications(registeredChildThreadIds); } - private handleUserMessageItem( + private async handleUserMessageItem( parsed: Extract, - ): void { + ): Promise { const itemId = parsed.item.id; - const timelineItem = threadItemToTimeline(parsed.item, { + const timelineItem = await threadItemToTimeline(parsed.item, { includeUserMessage: true, cwd: this.config.cwd ?? null, }); diff --git a/packages/server/src/server/agent/providers/omp/agent.test.ts b/packages/server/src/server/agent/providers/omp/agent.test.ts index 7b56c9bdec..15392fc07c 100644 --- a/packages/server/src/server/agent/providers/omp/agent.test.ts +++ b/packages/server/src/server/agent/providers/omp/agent.test.ts @@ -1343,13 +1343,14 @@ describe("OMP agent client and session", () => { expect(omp.runtimeLaunches()).toHaveLength(1); }); - test("closes a replacement process if the session closes during relaunch", async () => { + test("rejects a pending recovery start and closes its processes when the session closes", async () => { const omp = new OmpHarness(); await omp.start(); omp.processExit("OMP RPC process exited with code 1 and signal null"); const turn = omp.startTurnDetached("continue"); + const rejected = expect(turn).rejects.toThrow("closed"); await omp.close(); - await turn; + await rejected; await waitForImmediate(); expect(omp.runtimeSessions().every((session) => session.closed)).toBe(true); }); @@ -1638,3 +1639,93 @@ test.each([ expect(await session.canStopRuntime!()).toBe(expected); }, ); + +test.each([false, true])( + "image prompt keeps OMP's vision capability contract (vision: %s)", + async (vision) => { + const runtime = new FakeOmp(); + runtime.queueSessionSetup((session) => { + session.state = { + ...session.state, + model: { + provider: "test", + id: "image-model", + input: vision ? ["text", "image"] : ["text"], + }, + }; + }); + const client = new OmpAgentClient({ logger: createTestLogger(), runtime }); + const session = await client.createSession({ provider: "omp", cwd: process.cwd() }); + onTestFinished(() => session.close()); + const bytes = Buffer.from("OMP attachment fixture"); + const first = session.startTurn([ + { type: "text", text: "Describe this image." }, + { type: "image", data: bytes.toString("base64"), mimeType: "image/png" }, + ]); + await expect(session.startTurn("overlapping prompt")).rejects.toThrow("already active"); + await first; + const [prompt] = runtime.latestSession().prompts; + expect(prompt.imageCount).toBe(vision ? 1 : 0); + if (vision) expect(prompt.message).toBe("Describe this image."); + else { + const imagePath = prompt.message.match(/\[Image available at: (.+)\]/)?.[1]; + expect(imagePath).toBeTruthy(); + const { readFile, rm } = await import("node:fs/promises"); + expect(await readFile(imagePath!)).toEqual(bytes); + await rm(imagePath!); + } + }, +); + +test("interrupting OMP during image conversion cancels the admitted turn and permits a follow-up", async () => { + const runtime = new FakeOmp(); + const client = new OmpAgentClient({ logger: createTestLogger(), runtime }); + const session = await client.createSession({ provider: "omp", cwd: process.cwd() }); + onTestFinished(() => session.close()); + const events: AgentStreamEvent[] = []; + session.subscribe((event) => events.push(event)); + let admitted = false; + const first = session + .startTurn([ + { + type: "image", + data: Buffer.alloc(16 * 1024 * 1024, 53).toString("base64"), + mimeType: "image/png", + }, + ]) + .then((result) => { + admitted = true; + return result; + }); + await waitForImmediate(); + expect(admitted).toBe(false); + expect(runtime.latestSession().prompts).toHaveLength(0); + await session.interrupt(); + const followup = await session.startTurn("follow-up after image interrupt"); + const original = await first; + expect(events).toContainEqual( + expect.objectContaining({ type: "turn_canceled", turnId: original.turnId }), + ); + expect(followup.turnId).not.toBe(original.turnId); + expect(runtime.latestSession().prompts).toEqual([ + { message: "follow-up after image interrupt", imageCount: 0 }, + ]); +}); + +test("closing OMP during image conversion rejects its pending start", async () => { + const runtime = new FakeOmp(); + const client = new OmpAgentClient({ logger: createTestLogger(), runtime }); + const session = await client.createSession({ provider: "omp", cwd: process.cwd() }); + const first = session.startTurn([ + { + type: "image", + data: Buffer.alloc(16 * 1024 * 1024, 54).toString("base64"), + mimeType: "image/png", + }, + ]); + const rejected = expect(first).rejects.toThrow("closed"); + await waitForImmediate(); + expect(runtime.latestSession().prompts).toHaveLength(0); + await session.close(); + await rejected; +}); diff --git a/packages/server/src/server/agent/providers/omp/agent.ts b/packages/server/src/server/agent/providers/omp/agent.ts index 434a49d89e..f2f405540b 100644 --- a/packages/server/src/server/agent/providers/omp/agent.ts +++ b/packages/server/src/server/agent/providers/omp/agent.ts @@ -317,9 +317,9 @@ function ompModelSupportsImageInput(model: OmpModel | null | undefined): boolean return model?.input?.includes("image") === true; } -function renderTextOnlyImageHint(image: { data: string; mimeType: string }): string { +async function renderTextOnlyImageHint(image: { data: string; mimeType: string }): Promise { try { - const materialized = materializeProviderImage({ + const materialized = await materializeProviderImage({ data: image.data, mimeType: image.mimeType, }); @@ -329,10 +329,10 @@ function renderTextOnlyImageHint(image: { data: string; mimeType: string }): str } } -function convertPromptInput( +async function convertPromptInput( prompt: AgentPromptInput, options: { model: OmpModel | null | undefined }, -): OmpPromptPayload { +): Promise { if (typeof prompt === "string") { return { text: prompt }; } @@ -355,7 +355,7 @@ function convertPromptInput( mimeType: block.mimeType, }); } else { - textParts.push(renderTextOnlyImageHint(block)); + textParts.push(await renderTextOnlyImageHint(block)); } continue; } @@ -868,11 +868,9 @@ export class OmpAgentSession implements AgentSession { throw new Error("An OMP turn is already active"); } - const payload = convertPromptInput(prompt, { model: this.state.model }); const turnId = randomUUID(); this.live = true; this.activeTurnId = turnId; - this.rememberClientMessage(options?.clientMessageId ?? null, payload.text); this.activeAssistantMessageId = null; this.activeTurnTerminalAssistantMessage = null; this.activeTurnStarted = false; @@ -880,6 +878,10 @@ export class OmpAgentSession implements AgentSession { this.activeTurnHasUserMessage = false; this.activePromptRequestId = null; this.clearNoTurnBuffers(); + const payload = await convertPromptInput(prompt, { model: this.state.model }); + if (this.closed) throw new Error("OMP session is closed"); + if (this.activeTurnId !== turnId) return { turnId }; + this.rememberClientMessage(options?.clientMessageId ?? null, payload.text); this.activeNoTurnPromptText = payload.text; this.usagePoller.startTurn(); if (announceTurn) { @@ -946,7 +948,9 @@ export class OmpAgentSession implements AgentSession { ): Promise { if (this.closed || this.activeTurnId !== options.expectedTurnId) return { status: "unavailable" }; - const payload = convertPromptInput(prompt, { model: this.state.model }); + const payload = await convertPromptInput(prompt, { model: this.state.model }); + if (this.closed || this.activeTurnId !== options.expectedTurnId) + return { status: "unavailable" }; if (this.parseSlashCommandInput(payload.text)) return { status: "unavailable" }; const submission = this.rememberClientMessage(options.clientMessageId ?? null, payload.text); try { diff --git a/packages/server/src/server/agent/providers/opencode/event-translator.test.ts b/packages/server/src/server/agent/providers/opencode/event-translator.test.ts index 9ed61fef67..6dc5bd5a2e 100644 --- a/packages/server/src/server/agent/providers/opencode/event-translator.test.ts +++ b/packages/server/src/server/agent/providers/opencode/event-translator.test.ts @@ -1,3 +1,4 @@ +import { collectTimelineSnapshot } from "./test-utils/v2-timeline.js"; import type { SessionMessageAssistant, SessionMessageUser } from "@opencode/client"; import { V2Timeline } from "./v2/timeline.js"; import { describe, expect, it } from "vitest"; @@ -1560,7 +1561,7 @@ describe("translateOpenCodeEvent", () => { }); describe("OpenCode v2 history reconciliation", () => { - it("keeps client message identity on live echoes but omits it from history", () => { + it("keeps client message identity on live echoes but omits it from history", async () => { const user: SessionMessageUser = { id: "native-message", type: "user", @@ -1568,13 +1569,13 @@ describe("OpenCode v2 history reconciliation", () => { time: { created: 1 }, metadata: { paseoClientMessageId: "client-message" }, }; - expect(new V2Timeline().messages([user])).toMatchObject([ + expect(await collectTimelineSnapshot(new V2Timeline(), [user])).toMatchObject([ { item: { clientMessageId: "client-message", messageId: "native-message" } }, ]); - expect(new V2Timeline(false).messages([user])).toMatchObject([ + expect(await collectTimelineSnapshot(new V2Timeline(false), [user])).toMatchObject([ { item: { type: "user_message", messageId: "native-message" } }, ]); - const [event] = new V2Timeline(false).messages([user]); + const [event] = await collectTimelineSnapshot(new V2Timeline(false), [user]); expect(event && "item" in event && event.item).not.toHaveProperty("clientMessageId"); }); function assistant(text: string): SessionMessageAssistant { @@ -1587,31 +1588,35 @@ describe("OpenCode v2 history reconciliation", () => { content: [{ type: "text", text }], }; } - it("emits only the missing suffix after reconnect, even if an intermediate snapshot lags", () => { + it("emits only the missing suffix after reconnect, even if an intermediate snapshot lags", async () => { const timeline = new V2Timeline(); - const text = (messages: ReturnType) => + const text = (messages: Awaited>) => messages.flatMap((event) => event.type === "timeline" && event.item.type === "assistant_message" ? [event.item.text] : [], ); - expect(text(timeline.messages([assistant("hello")]))).toEqual(["hello"]); - expect(timeline.messages([assistant("hel")])).toEqual([]); - expect(text(timeline.messages([assistant("hello world")]))).toEqual([" world"]); - expect(timeline.messages([assistant("hello world")])).toEqual([]); + expect(text(await collectTimelineSnapshot(timeline, [assistant("hello")]))).toEqual(["hello"]); + expect(await collectTimelineSnapshot(timeline, [assistant("hel")])).toEqual([]); + expect(text(await collectTimelineSnapshot(timeline, [assistant("hello world")]))).toEqual([ + " world", + ]); + expect(await collectTimelineSnapshot(timeline, [assistant("hello world")])).toEqual([]); }); - it("keeps reasoning separate from assistant output", () => { + it("keeps reasoning separate from assistant output", async () => { const timeline = new V2Timeline(); const message = assistant("answer"); message.content.unshift({ type: "reasoning", text: "thinking" }); expect( - timeline.messages([message]).map((event) => (event.type === "timeline" ? event.item : null)), + (await collectTimelineSnapshot(timeline, [message])).map((event) => + event.type === "timeline" ? event.item : null, + ), ).toEqual([ { type: "reasoning", text: "thinking" }, { type: "assistant_message", text: "answer", messageId: "message" }, ]); }); - it("emits tool state transitions once and keeps their call identity", () => { + it("emits tool state transitions once and keeps their call identity", async () => { const timeline = new V2Timeline(); const message = assistant(""); message.content = [ @@ -1623,7 +1628,7 @@ describe("OpenCode v2 history reconciliation", () => { state: { status: "running", input: { command: "pwd" }, metadata: {} }, }, ]; - expect(timeline.messages([message])).toMatchObject([ + expect(await collectTimelineSnapshot(timeline, [message])).toMatchObject([ { item: { type: "tool_call", callId: "call", status: "running" } }, ]); message.content = [ @@ -1639,9 +1644,9 @@ describe("OpenCode v2 history reconciliation", () => { }, }, ]; - expect(timeline.messages([message])).toMatchObject([ + expect(await collectTimelineSnapshot(timeline, [message])).toMatchObject([ { item: { type: "tool_call", callId: "call", status: "completed" } }, ]); - expect(timeline.messages([message])).toEqual([]); + expect(await collectTimelineSnapshot(timeline, [message])).toEqual([]); }); }); diff --git a/packages/server/src/server/agent/providers/opencode/test-utils/v2-streamed-text-memory.ts b/packages/server/src/server/agent/providers/opencode/test-utils/v2-streamed-text-memory.ts index d9d254d9de..98cd79526a 100644 --- a/packages/server/src/server/agent/providers/opencode/test-utils/v2-streamed-text-memory.ts +++ b/packages/server/src/server/agent/providers/opencode/test-utils/v2-streamed-text-memory.ts @@ -1,3 +1,4 @@ +import { collectTimelineSnapshot } from "./v2-timeline.js"; import { TimelineProjection } from "../../../timeline-projection.js"; import { V2Timeline } from "../v2/timeline.js"; @@ -21,16 +22,18 @@ for (let index = 0; index < chunks; index++) { const event = mode === "delta" ? timeline.delta({ ...part, delta }) - : timeline.messages([ - { - id: "answer", - type: "assistant", - agent: "build", - model: { providerID: "test", id: "model" }, - time: { created: 2 }, - content: [{ type: "reasoning", text }], - }, - ])[0]; + : ( + await collectTimelineSnapshot(timeline, [ + { + id: "answer", + type: "assistant", + agent: "build", + model: { providerID: "test", id: "model" }, + time: { created: 2 }, + content: [{ type: "reasoning", text }], + }, + ]) + )[0]; if (event?.type !== "timeline") throw new Error("Expected a timeline event"); projection.append({ seq: index + 1, diff --git a/packages/server/src/server/agent/providers/opencode/test-utils/v2-timeline.ts b/packages/server/src/server/agent/providers/opencode/test-utils/v2-timeline.ts new file mode 100644 index 0000000000..e7aa552479 --- /dev/null +++ b/packages/server/src/server/agent/providers/opencode/test-utils/v2-timeline.ts @@ -0,0 +1,15 @@ +import type { SessionMessageInfo } from "@opencode/client"; +import type { AgentStreamEvent } from "../../../agent-sdk-types.js"; +import type { V2Timeline } from "../v2/timeline.js"; + +// Snapshot assertions without a live stream can collect the publisher's events. +export async function collectTimelineSnapshot( + timeline: V2Timeline, + messages: SessionMessageInfo[], +): Promise { + const events: AgentStreamEvent[] = []; + await timeline.messages(messages, (event) => { + events.push(event); + }); + return events; +} diff --git a/packages/server/src/server/agent/providers/opencode/v2/children.ts b/packages/server/src/server/agent/providers/opencode/v2/children.ts index 8c2e0ec312..08af88dcb0 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/children.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/children.ts @@ -92,13 +92,13 @@ export class SessionChildren { this.childStates.set(info.id, signature); this.options.emit({ type: "provider_subagent", provider: "opencode", event: presentation }); } - for (const event of timeline.messages(await messages(this.options.client(), info.id))) { + await timeline.messages(await messages(this.options.client(), info.id), (event) => { if (event.type === "timeline") this.options.emit({ type: "provider_subagent", provider: "opencode", event: { type: "timeline", id: info.id, item: event.item, timestamp: event.timestamp }, }); - } + }); } } diff --git a/packages/server/src/server/agent/providers/opencode/v2/session.ts b/packages/server/src/server/agent/providers/opencode/v2/session.ts index 9358a14040..f173ccb301 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/session.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/session.ts @@ -131,7 +131,7 @@ export class OpenCodeV2Session implements AgentSession { await this.configureConnection(); const location = { directory: this.config.cwd }; this.modes = modesFromV2((await this.client.agent.list({ location })).data); - this.timeline.messages(await messages(this.client, this.id)); + await this.timeline.messages(await messages(this.client, this.id), () => {}); await this.startStream(); await this.children.reconcile(this.id); } @@ -261,7 +261,11 @@ export class OpenCodeV2Session implements AgentSession { async *streamHistory() { await this.reconnectIfExited(); const history = new V2Timeline(false); - yield* history.messages(await messages(this.client, this.id)); + const events: AgentStreamEvent[] = []; + await history.messages(await messages(this.client, this.id), (event) => { + events.push(event); + }); + yield* events; } async getRuntimeInfo() { await this.reconnectIfExited(); @@ -417,7 +421,7 @@ export class OpenCodeV2Session implements AgentSession { ]); this.info = info; this.history = history; - for (const event of this.timeline.messages(history)) this.emitTimeline(event); + await this.timeline.messages(history, (event) => this.emitTimeline(event)); await this.permissions.reconcile(this.id); } private async reconcile() { diff --git a/packages/server/src/server/agent/providers/opencode/v2/streaming.test.ts b/packages/server/src/server/agent/providers/opencode/v2/streaming.test.ts index aa74faa6cf..b8c118f037 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/streaming.test.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/streaming.test.ts @@ -1,3 +1,4 @@ +import { collectTimelineSnapshot } from "../test-utils/v2-timeline.js"; import { V2Timeline } from "./timeline.js"; import type { SessionMessageAssistant } from "@opencode/client"; import { describe, expect, test } from "vitest"; @@ -80,7 +81,7 @@ describe("OpenCode v2 token streaming", () => { } }); - test("deduplicates snapshots before and after deltas using per-type ordinals", () => { + test("deduplicates snapshots before and after deltas using per-type ordinals", async () => { const timeline = new V2Timeline(); const text = { assistantMessageID: "answer", type: "text", ordinal: 0 } as const; const reasoning = { ...text, type: "reasoning" } as const; @@ -99,24 +100,28 @@ describe("OpenCode v2 token streaming", () => { }, { type: "text", text: "Hello" }, ]); - expect(timeline.messages([snapshot])).toMatchObject([{ item: { text: "lo" } }]); + expect(await collectTimelineSnapshot(timeline, [snapshot])).toMatchObject([ + { item: { text: "lo" } }, + ]); expect(timeline.delta({ ...text, delta: "lo" })).toBeNull(); - expect(timeline.messages([snapshot])).toEqual([]); + expect(await collectTimelineSnapshot(timeline, [snapshot])).toEqual([]); expect(timeline.delta({ ...text, delta: "!" })).toMatchObject({ item: { text: "!" } }); - expect(timeline.messages([snapshot])).toEqual([]); + expect(await collectTimelineSnapshot(timeline, [snapshot])).toEqual([]); }); - test("recovers missed fragments from snapshots after reconnect", () => { + test("recovers missed fragments from snapshots after reconnect", async () => { const timeline = new V2Timeline(); const part = { assistantMessageID: "answer", type: "text", ordinal: 0 } as const; timeline.startPart(part); expect(timeline.delta({ ...part, delta: "Hel" })).toMatchObject({ item: { text: "Hel" } }); timeline.resetStreams(); expect(timeline.delta({ ...part, delta: "!" })).toBeNull(); - expect(timeline.messages([assistant([{ type: "text", text: "Hello!" }])])).toMatchObject([ - { item: { text: "lo!" } }, - ]); - expect(timeline.messages([assistant([{ type: "text", text: "Hello!" }])])).toEqual([]); + expect( + await collectTimelineSnapshot(timeline, [assistant([{ type: "text", text: "Hello!" }])]), + ).toMatchObject([{ item: { text: "lo!" } }]); + expect( + await collectTimelineSnapshot(timeline, [assistant([{ type: "text", text: "Hello!" }])]), + ).toEqual([]); }); test("withholds streamed prose during a structured-output turn", async () => { @@ -203,3 +208,62 @@ describe("OpenCode v2 token streaming", () => { } }); }); + +test.each(["text", "reasoning"] as const)( + "publishes snapshot %s before a live suffix during image materialization", + async (type) => { + const timeline = new V2Timeline(); + const part = { assistantMessageID: "answer", type, ordinal: 0 }; + timeline.startPart(part); + const emitted: AgentStreamEvent[] = []; + let settled = false; + const snapshot = timeline + .messages( + [ + assistant([ + { type, text: "Hello" }, + { + type: "tool", + id: "screenshot", + name: "paseo_browser_screenshot", + executed: false, + state: { + status: "completed", + input: {}, + content: [ + { type: "file", uri: "data:image/png;base64,aGVsbG8=", mime: "image/png" }, + ], + metadata: {}, + }, + time: { created: 2, ran: 2, completed: 2 }, + }, + ]), + ], + (event) => { + emitted.push(event); + }, + ) + .then(() => { + settled = true; + return undefined; + }); + await new Promise((resolve) => setImmediate(resolve)); + expect(settled).toBe(false); + const delta = timeline.delta({ ...part, delta: "Hello world" }); + if (delta) emitted.push(delta); + await snapshot; + const text = emitted.flatMap((event) => { + if (event.type !== "timeline") return []; + if ( + type === "text" && + event.item.type === "assistant_message" && + !event.item.text.includes("![Image]") + ) + return [event.item.text]; + if (type === "reasoning" && event.item.type === "reasoning") return [event.item.text]; + return []; + }); + expect(text).toEqual(["Hello", " world"]); + expect(text.join("")).toBe("Hello world"); + }, +); diff --git a/packages/server/src/server/agent/providers/opencode/v2/timeline.test.ts b/packages/server/src/server/agent/providers/opencode/v2/timeline.test.ts index d86b9a7dcb..6e9b886c09 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/timeline.test.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/timeline.test.ts @@ -1,3 +1,4 @@ +import { collectTimelineSnapshot } from "../test-utils/v2-timeline.js"; import type { SessionMessageAssistant } from "@opencode/client"; import { execFileSync } from "node:child_process"; import { fileURLToPath } from "node:url"; @@ -15,7 +16,7 @@ function assistant(content: SessionMessageAssistant["content"]): SessionMessageA }; } -test("a completed edit carries the replaced and replacement text", () => { +test("a completed edit carries the replaced and replacement text", async () => { // Captured from OpenCode 2.0.18, whose edit tool takes `path` instead of `filePath`. const edit = assistant([ { @@ -45,7 +46,7 @@ test("a completed edit carries the replaced and replacement text", () => { }, ]); - expect(new V2Timeline().messages([edit])).toMatchObject([ + expect(await collectTimelineSnapshot(new V2Timeline(), [edit])).toMatchObject([ { item: { type: "tool_call", @@ -57,7 +58,7 @@ test("a completed edit carries the replaced and replacement text", () => { ]); }); -test("a tool's image output is shown as an image, not as base64 in the tool output", () => { +test("a tool's image output is shown as an image, not as base64 in the tool output", async () => { const png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg=="; const screenshot = assistant([ @@ -80,7 +81,7 @@ test("a tool's image output is shown as an image, not as base64 in the tool outp ]); const timeline = new V2Timeline(); - const events = timeline.messages([screenshot]); + const events = await collectTimelineSnapshot(timeline, [screenshot]); expect(JSON.stringify(events)).not.toContain(png); expect(events.map((event) => event.type === "timeline" && event.item)).toMatchObject([ @@ -95,7 +96,7 @@ test("a tool's image output is shown as an image, not as base64 in the tool outp text: expect.stringMatching(/^\n\n!\[Image\]\(file:\/\/.*paseo-attachments.*\.png\)\n\n$/), }, ]); - expect(timeline.messages([screenshot])).toEqual([]); + expect(await collectTimelineSnapshot(timeline, [screenshot])).toEqual([]); }); test("a surrogate pair split across deltas streams back intact", () => { diff --git a/packages/server/src/server/agent/providers/opencode/v2/timeline.ts b/packages/server/src/server/agent/providers/opencode/v2/timeline.ts index 0fdd6f9f40..5596443bbb 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/timeline.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/timeline.ts @@ -55,18 +55,32 @@ export class V2Timeline { return { type: "timeline", provider: "opencode", item, timestamp: new Date().toISOString() }; } - messages(messages: SessionMessageInfo[]): AgentStreamEvent[] { - const events: AgentStreamEvent[] = []; + private pendingMessages: Promise = Promise.resolve(); + + // Publish each cursor advance in the same synchronous step. Buffering snapshot + // events until image IO finishes lets live deltas overtake already committed text. + messages( + messages: SessionMessageInfo[], + publish: (event: AgentStreamEvent) => void, + ): Promise { + const result = this.pendingMessages.then(() => this.publishMessages(messages, publish)); + this.pendingMessages = result.catch(() => {}); + return result; + } + + private async publishMessages( + messages: SessionMessageInfo[], + publish: (event: AgentStreamEvent) => void, + ): Promise { const state: TimelineState = { structured: false, accepted: false }; for (const message of messages) { const timestamp = new Date(message.time.created).toISOString(); const push = (item: AgentTimelineItem) => - events.push({ type: "timeline", provider: "opencode", item, timestamp }); + publish({ type: "timeline", provider: "opencode", item, timestamp }); if (message.type === "user") this.userMessage(message, state, push); - else if (message.type === "assistant") this.assistantMessage(message, state, push); + else if (message.type === "assistant") await this.assistantMessage(message, state, push); else if (message.type === "compaction") this.compactionMessage(message, push); } - return events; } private userMessage( @@ -89,7 +103,7 @@ export class V2Timeline { }); } - private assistantMessage( + private async assistantMessage( message: Extract, state: TimelineState, push: (item: AgentTimelineItem) => void, @@ -99,16 +113,16 @@ export class V2Timeline { // paths address the same cursor entry. let textOrdinal = 0; let reasoningOrdinal = 0; - message.content.forEach((part, partIndex) => { + for (const [partIndex, part] of message.content.entries()) { if (part.type === "tool" && part.name === STRUCTURED_OUTPUT_TOOL) { this.structuredOutputPart(message.id, partIndex, part, state, push); } else if (part.type === "text" || part.type === "reasoning") { const ordinal = part.type === "text" ? textOrdinal++ : reasoningOrdinal++; this.textPart(message.id, part, ordinal, state, push); } else { - this.toolPart(message.id, partIndex, part, push); + await this.toolPart(message.id, partIndex, part, push); } - }); + } } private structuredOutputPart( @@ -156,7 +170,7 @@ export class V2Timeline { else push({ type: "reasoning", text: suffix }); } - private toolPart( + private async toolPart( messageID: string, partIndex: number, part: Extract< @@ -174,16 +188,16 @@ export class V2Timeline { if (item) push(item); // Images follow their tool call as markdown, as Claude and Codex emit them, // so base64 never reaches the tool output. - images.forEach((image, index) => { + for (const [index, image] of images.entries()) { const imageKey = `${key}:image:${index}`; - if (this.content.has(imageKey)) return; + if (this.content.has(imageKey)) continue; this.content.set(imageKey, ""); - const imageItem = renderProviderImageOutputAsAssistantMarkdown( + const imageItem = await renderProviderImageOutputAsAssistantMarkdown( { url: image.uri, mimeType: image.mime }, { materialize: materializeProviderImage }, ); if (imageItem) push(imageItem); - }); + } } private compactionMessage( diff --git a/packages/server/src/server/agent/providers/pi/agent.test.ts b/packages/server/src/server/agent/providers/pi/agent.test.ts index b9f31b61b2..82887bf199 100644 --- a/packages/server/src/server/agent/providers/pi/agent.test.ts +++ b/packages/server/src/server/agent/providers/pi/agent.test.ts @@ -3583,3 +3583,63 @@ test("pi runtime safety protects queued replies and runtime-owned activity", asy native.getStateError = new Error("Unable to prove idle"); await expect(session.canStopRuntime!()).rejects.toThrow("Unable to prove idle"); }); + +test("reserves the Pi turn while an image prompt is materialized", async () => { + const { pi, session } = await createSession(); + onTestFinished(() => session.close()); + const first = session.startTurn([ + { type: "image", data: ONE_BY_ONE_PNG_BASE64, mimeType: "image/png" }, + ]); + await expect(session.startTurn("overlapping prompt")).rejects.toThrow("already active"); + await first; + expect(pi.latestSession().prompts).toHaveLength(1); +}); + +test("interrupting Pi during image conversion cancels the admitted turn and permits a follow-up", async () => { + const { pi, session } = await createSession(); + onTestFinished(() => session.close()); + const events: AgentStreamEvent[] = []; + session.subscribe((event) => events.push(event)); + let admitted = false; + const first = session + .startTurn([ + { + type: "image", + data: Buffer.alloc(16 * 1024 * 1024, 51).toString("base64"), + mimeType: "image/png", + }, + ]) + .then((result) => { + admitted = true; + return result; + }); + await waitForImmediate(); + expect(admitted).toBe(false); + expect(pi.latestSession().prompts).toHaveLength(0); + await session.interrupt(); + const followup = await session.startTurn("follow-up after image interrupt"); + const original = await first; + expect(events).toContainEqual( + expect.objectContaining({ type: "turn_canceled", turnId: original.turnId }), + ); + expect(followup.turnId).not.toBe(original.turnId); + expect(pi.latestSession().prompts).toEqual([ + { message: "follow-up after image interrupt", imageCount: 0 }, + ]); +}); + +test("closing Pi during image conversion rejects its pending start", async () => { + const { pi, session } = await createSession(); + const first = session.startTurn([ + { + type: "image", + data: Buffer.alloc(16 * 1024 * 1024, 52).toString("base64"), + mimeType: "image/png", + }, + ]); + const rejected = expect(first).rejects.toThrow("closed"); + await waitForImmediate(); + expect(pi.latestSession().prompts).toHaveLength(0); + await session.close(); + await rejected; +}); diff --git a/packages/server/src/server/agent/providers/pi/agent.ts b/packages/server/src/server/agent/providers/pi/agent.ts index 881f8cbb29..5fbffde84b 100644 --- a/packages/server/src/server/agent/providers/pi/agent.ts +++ b/packages/server/src/server/agent/providers/pi/agent.ts @@ -367,9 +367,9 @@ function piModelSupportsImageInput(model: PiModel | null | undefined): boolean { return model?.input?.includes("image") === true; } -function renderTextOnlyImageHint(image: { data: string; mimeType: string }): string { +async function renderTextOnlyImageHint(image: { data: string; mimeType: string }): Promise { try { - const materialized = materializeProviderImage({ + const materialized = await materializeProviderImage({ data: image.data, mimeType: image.mimeType, }); @@ -379,10 +379,10 @@ function renderTextOnlyImageHint(image: { data: string; mimeType: string }): str } } -function convertPromptInput( +async function convertPromptInput( prompt: AgentPromptInput, options: { model: PiModel | null | undefined }, -): PiPromptPayload { +): Promise { if (typeof prompt === "string") { return { text: prompt }; } @@ -405,7 +405,7 @@ function convertPromptInput( mimeType: block.mimeType, }); } else { - textParts.push(renderTextOnlyImageHint(block)); + textParts.push(await renderTextOnlyImageHint(block)); } continue; } @@ -1280,7 +1280,6 @@ export class PiRpcAgentSession implements AgentSession { throw new Error("A Pi turn is already active"); } - const payload = convertPromptInput(prompt, { model: this.state.model }); const turnId = randomUUID(); this.activeTurnId = turnId; this.usagePoller.startTurn(); @@ -1292,6 +1291,9 @@ export class PiRpcAgentSession implements AgentSession { this.activePromptRequestId = null; this.pendingSteerSubmissions.length = 0; this.clearNoTurnBuffers(); + const payload = await convertPromptInput(prompt, { model: this.state.model }); + if (this.closed) throw new Error("Pi session is closed"); + if (this.activeTurnId !== turnId) return { turnId }; this.activeNoTurnPromptText = payload.text; const shouldProbeForNoTurnPrompt = this.parseSlashCommandInput(payload.text) !== null; @@ -1363,7 +1365,9 @@ export class PiRpcAgentSession implements AgentSession { if (this.closed || this.activeTurnId !== options.expectedTurnId) { return { status: "unavailable" }; } - const payload = convertPromptInput(prompt, { model: this.state.model }); + const payload = await convertPromptInput(prompt, { model: this.state.model }); + if (this.closed || this.activeTurnId !== options.expectedTurnId) + return { status: "unavailable" }; // Pi rejects steer RPCs that are extension commands, so slash inputs keep the // interrupt-and-replace fallback where they can run directly. if (this.parseSlashCommandInput(payload.text)) { diff --git a/packages/server/src/server/agent/providers/provider-image-output.posix.test.ts b/packages/server/src/server/agent/providers/provider-image-output.posix.test.ts index 1f4da6e04a..5e71bad0bd 100644 --- a/packages/server/src/server/agent/providers/provider-image-output.posix.test.ts +++ b/packages/server/src/server/agent/providers/provider-image-output.posix.test.ts @@ -5,8 +5,8 @@ import { describe, expect, test } from "vitest"; import { materializeProviderImage } from "./provider-image-output.js"; describe.skipIf(process.platform === "win32")("materializeProviderImage", () => { - test("writes image attachments under a private temp directory", () => { - const materialized = materializeProviderImage({ + test("writes image attachments under a private temp directory", async () => { + const materialized = await materializeProviderImage({ data: "YWJjMTIz", mimeType: "image/png", }); diff --git a/packages/server/src/server/agent/providers/provider-image-output.test.ts b/packages/server/src/server/agent/providers/provider-image-output.test.ts index b4f4784a66..0606c59de3 100644 --- a/packages/server/src/server/agent/providers/provider-image-output.test.ts +++ b/packages/server/src/server/agent/providers/provider-image-output.test.ts @@ -1,10 +1,11 @@ -import { existsSync, rmSync } from "node:fs"; +import { existsSync, rmSync, statSync, readFileSync } from "node:fs"; import path from "node:path"; import MarkdownIt from "markdown-it"; import { projectTimelineRows } from "../timeline-projection.js"; import { describe, expect, test } from "vitest"; import { + MAX_PROVIDER_IMAGE_BYTES, isProviderImageMarkdown, materializeProviderImage, renderProviderImageOutputAsAssistantMarkdown, @@ -12,8 +13,8 @@ import { const HASH = "a".repeat(64); -function renderImageMarkdown(imagePath: string): string { - const item = renderProviderImageOutputAsAssistantMarkdown({ path: imagePath }); +async function renderImageMarkdown(imagePath: string): Promise { + const item = await renderProviderImageOutputAsAssistantMarkdown({ path: imagePath }); if (!item || item.type !== "assistant_message") { throw new Error("Expected provider image output to render as assistant markdown."); } @@ -40,8 +41,8 @@ describe("isProviderImageMarkdown", () => { ).toBe(true); }); - test("emits Windows file paths as file URIs", () => { - const markdown = renderImageMarkdown( + test("emits Windows file paths as file URIs", async () => { + const markdown = await renderImageMarkdown( `C:\\Users\\me\\AppData\\Local\\Temp\\paseo-attachments\\${HASH}.png`, ); @@ -51,22 +52,24 @@ describe("isProviderImageMarkdown", () => { expect(isProviderImageMarkdown(markdown)).toBe(true); }); - test("emits POSIX file paths with spaces as valid file URI markdown", () => { - const markdown = renderImageMarkdown("/home/user/Projects/Project With Spaces/screenshot.png"); + test("emits POSIX file paths with spaces as valid file URI markdown", async () => { + const markdown = await renderImageMarkdown( + "/home/user/Projects/Project With Spaces/screenshot.png", + ); expect(markdown).toBe( "\n\n![Image](file:///home/user/Projects/Project%20With%20Spaces/screenshot.png)\n\n", ); }); - test("encodes URI-significant characters in POSIX file paths", () => { - const markdown = renderImageMarkdown("/tmp/screenshot#1?draft.png"); + test("encodes URI-significant characters in POSIX file paths", async () => { + const markdown = await renderImageMarkdown("/tmp/screenshot#1?draft.png"); expect(markdown).toBe("\n\n![Image](file:///tmp/screenshot%231%3Fdraft.png)\n\n"); }); - test("preserves double-leading slashes in POSIX file paths", () => { - const markdown = renderImageMarkdown("//tmp/screenshot#1.png"); + test("preserves double-leading slashes in POSIX file paths", async () => { + const markdown = await renderImageMarkdown("//tmp/screenshot#1.png"); expect(markdown).toBe("\n\n![Image](file:////tmp/screenshot%231.png)\n\n"); }); @@ -78,8 +81,8 @@ describe("isProviderImageMarkdown", () => { "\\\\?\\UNC\\server\\share\\shot?draft.png", "file://server/share/shot%3Fdraft.png", ], - ])("encodes %s image paths as file URIs", (_label, imagePath, expectedSource) => { - expect(renderImageMarkdown(imagePath)).toBe(`\n\n![Image](${expectedSource})\n\n`); + ])("encodes %s image paths as file URIs", async (_label, imagePath, expectedSource) => { + expect(await renderImageMarkdown(imagePath)).toBe(`\n\n![Image](${expectedSource})\n\n`); }); test("rejects user-authored markdown that is not a materialized attachment", () => { @@ -92,8 +95,8 @@ describe("isProviderImageMarkdown", () => { }); describe("materializeProviderImage", () => { - test("recreates the private temp directory if the cached directory is removed", () => { - const first = materializeProviderImage({ + test("recreates the private temp directory if the cached directory is removed", async () => { + const first = await materializeProviderImage({ data: "YWJjMTIz", mimeType: "image/png", }); @@ -102,7 +105,7 @@ describe("materializeProviderImage", () => { rmSync(firstDir, { recursive: true, force: true }); - const second = materializeProviderImage({ + const second = await materializeProviderImage({ data: "ZGVmNDU2", mimeType: "image/png", }); @@ -117,8 +120,8 @@ describe("materializeProviderImage", () => { }); describe("provider image paragraph boundaries", () => { - test.each(["", "\n"])("keeps image outputs separate from prose ending in %j", (ending) => { - const image = renderProviderImageOutputAsAssistantMarkdown({ + test.each(["", "\n"])("keeps image outputs separate from prose ending in %j", async (ending) => { + const image = await renderProviderImageOutputAsAssistantMarkdown({ url: "https://example.com/chart.png", }); if (!image) throw new Error("Expected image output"); @@ -152,10 +155,10 @@ describe("provider image paragraph boundaries", () => { }); }); -test("materialized image output retains paragraph boundaries and attachment recognition", () => { - const item = renderProviderImageOutputAsAssistantMarkdown( +test("materialized image output retains paragraph boundaries and attachment recognition", async () => { + const item = await renderProviderImageOutputAsAssistantMarkdown( { data: "YWJjMTIz", mimeType: "image/png" }, - { materialize: () => ({ path: `/tmp/paseo-attachments/${HASH}.png` }) }, + { materialize: async () => ({ path: `/tmp/paseo-attachments/${HASH}.png` }) }, ); expect(item).toEqual({ type: "assistant_message", @@ -164,3 +167,76 @@ test("materialized image output retains paragraph boundaries and attachment reco if (!item || item.type !== "assistant_message") throw new Error("Expected image output"); expect(isProviderImageMarkdown(item.text)).toBe(true); }); + +test("repeated content is reused without rewriting the attachment", async () => { + const image = { + data: Buffer.from("dedupe regression").toString("base64"), + mimeType: "image/png", + }; + const first = await materializeProviderImage(image); + const before = statSync(first.path, { bigint: true }); + await new Promise((resolve) => setTimeout(resolve, 20)); + const second = await materializeProviderImage(image); + expect(second.path).toBe(first.path); + expect(statSync(second.path, { bigint: true }).mtimeNs).toBe(before.mtimeNs); +}); + +test("64 MiB materialization leaves the event loop responsive and preserves bytes", async () => { + const bytes = Buffer.alloc(64 * 1024 * 1024, 37); + const data = bytes.toString("base64"); + let previous = performance.now(); + let longest = 0; + const probe = setInterval(() => { + const now = performance.now(); + longest = Math.max(longest, now - previous); + previous = now; + }, 1); + try { + const result = await materializeProviderImage({ data, mimeType: "image/png" }); + await new Promise((resolve) => setTimeout(resolve, 5)); + console.log(`64 MiB attachment longest loop gap: ${longest.toFixed(2)} ms`); + expect(longest).toBeLessThan(50); + expect(readFileSync(result.path).equals(bytes)).toBe(true); + rmSync(result.path, { force: true }); + } finally { + clearInterval(probe); + } +}); + +test("preserves base64 decoding across whitespace and chunk boundaries", async () => { + const bytes = Buffer.alloc(512 * 1024, 123); + const base64 = bytes.toString("base64"); + const data = base64.match(/.{1,77}/g)!.join("\n"); + const result = await materializeProviderImage({ data, mimeType: "image/png" }); + expect(readFileSync(result.path).equals(bytes)).toBe(true); +}); + +test("rejects oversized materialization before work and leaves the queue usable", async () => { + const data = "A".repeat(Math.ceil(MAX_PROVIDER_IMAGE_BYTES / 3) * 4 + 260); + await expect(materializeProviderImage({ data, mimeType: "image/png" })).rejects.toThrow( + "exceeds", + ); + const omitted = await renderProviderImageOutputAsAssistantMarkdown( + { data, mimeType: "image/png" }, + { materialize: materializeProviderImage }, + ); + expect(omitted).toEqual({ + type: "assistant_message", + text: "Image output was omitted because it was not available as a file path or URL.", + }); + const image = await materializeProviderImage({ data: "YWJjMTIz", mimeType: "image/png" }); + expect(readFileSync(image.path).toString()).toBe("abc123"); +}); + +test("simultaneous requests for the same content share the published file", async () => { + const image = { + data: Buffer.from("concurrent dedupe fixture").toString("base64"), + mimeType: "image/png", + }; + const results = await Promise.all([ + materializeProviderImage(image), + materializeProviderImage(image), + ]); + expect(results[0]).toEqual(results[1]); + expect(readFileSync(results[0].path).toString()).toBe("concurrent dedupe fixture"); +}); diff --git a/packages/server/src/server/agent/providers/provider-image-output.ts b/packages/server/src/server/agent/providers/provider-image-output.ts index ba8843918b..0cd0787c1e 100644 --- a/packages/server/src/server/agent/providers/provider-image-output.ts +++ b/packages/server/src/server/agent/providers/provider-image-output.ts @@ -1,5 +1,6 @@ import { createHash } from "node:crypto"; -import * as fsSync from "node:fs"; +import * as fs from "node:fs/promises"; +import { setImmediate } from "node:timers/promises"; import os from "node:os"; import path from "node:path"; @@ -23,32 +24,26 @@ const PRIVATE_ATTACHMENT_DIR_MODE = 0o700; const MATERIALIZED_IMAGE_FILE_MODE = 0o600; let materializedImageAttachmentDir: string | null = null; +// Serialize materializations: one decoder and one file operation at a time, including +// concurrent history replay and live turns. A rejected operation must not poison the queue. +let pendingMaterialization: Promise = Promise.resolve(); -function canReuseMaterializedImageAttachmentDir(dir: string): boolean { - try { - const stats = fsSync.lstatSync(dir); - if (!stats.isDirectory()) { - return false; +async function getMaterializedImageAttachmentDir(): Promise { + if (materializedImageAttachmentDir) { + try { + const stats = await fs.lstat(materializedImageAttachmentDir); + if (stats.isDirectory()) { + await fs.chmod(materializedImageAttachmentDir, PRIVATE_ATTACHMENT_DIR_MODE); + return materializedImageAttachmentDir; + } + } catch { + /* Temp storage may have been removed between turns. */ } - fsSync.chmodSync(dir, PRIVATE_ATTACHMENT_DIR_MODE); - return true; - } catch { - return false; } -} - -function getMaterializedImageAttachmentDir(): string { - if ( - materializedImageAttachmentDir && - canReuseMaterializedImageAttachmentDir(materializedImageAttachmentDir) - ) { - return materializedImageAttachmentDir; - } - - materializedImageAttachmentDir = fsSync.mkdtempSync( + materializedImageAttachmentDir = await fs.mkdtemp( path.join(os.tmpdir(), PROVIDER_IMAGE_ATTACHMENT_DIR_PREFIX), ); - fsSync.chmodSync(materializedImageAttachmentDir, PRIVATE_ATTACHMENT_DIR_MODE); + await fs.chmod(materializedImageAttachmentDir, PRIVATE_ATTACHMENT_DIR_MODE); return materializedImageAttachmentDir; } @@ -71,32 +66,92 @@ function getImageExtension(mimeType: string): string { } } -function normalizeImageData(mimeType: string, data: string): { mimeType: string; data: string } { - if (data.startsWith("data:")) { - const match = data.match(/^data:([^;]+);base64,(.*)$/); - if (match) { - return { mimeType: match[1], data: match[2] }; - } - } - return { mimeType, data }; -} +// 128 MiB admits the measured 64 MiB fixture with headroom while bounding disk +// and decoding per image. This is materialization admission, not a wire schema limit. +export const MAX_PROVIDER_IMAGE_BYTES = 128 * 1024 * 1024; +const BASE64_CHUNK_CHARACTERS = 256 * 1024; // Multiple of four; decode units stay aligned. -// Filenames are a content hash of the bytes so re-materializing the same image -// within a process reuses the existing temp file instead of leaking a fresh one -// for repeated image blocks or history replay. export function materializeProviderImage(image: { data: string; mimeType: string | null; -}): MaterializedProviderImage { - const attachmentsDir = getMaterializedImageAttachmentDir(); - const normalized = normalizeImageData(image.mimeType ?? "image/png", image.data); - const bytes = Buffer.from(normalized.data, "base64"); - const extension = getImageExtension(normalized.mimeType); - const hash = createHash("sha256").update(bytes).digest("hex"); - const filePath = path.join(attachmentsDir, `${hash}.${extension}`); - fsSync.writeFileSync(filePath, bytes, { mode: MATERIALIZED_IMAGE_FILE_MODE }); - fsSync.chmodSync(filePath, MATERIALIZED_IMAGE_FILE_MODE); - return { path: filePath }; +}): Promise { + const result = pendingMaterialization.then(() => materializeImage(image)); + pendingMaterialization = result.catch(() => {}); + return result; +} + +async function materializeImage(image: { + data: string; + mimeType: string | null; +}): Promise { + const maxEncodedCharacters = Math.ceil(MAX_PROVIDER_IMAGE_BYTES / 3) * 4; + // Check length before inspecting/copying the payload, including a bounded data URI header. + if (image.data.length > maxEncodedCharacters + 256) { + throw new Error(`Image attachment exceeds ${MAX_PROVIDER_IMAGE_BYTES} bytes`); + } + let data = image.data; + let mimeType = image.mimeType ?? "image/png"; + if (data.startsWith("data:")) { + const separator = data.indexOf(";base64,"); + if (separator >= 0 && separator < 256) { + mimeType = data.slice(5, separator); + data = data.slice(separator + 8); + } + } + if (data.length > maxEncodedCharacters) { + throw new Error(`Image attachment exceeds ${MAX_PROVIDER_IMAGE_BYTES} bytes`); + } + const hash = createHash("sha256"); + for await (const bytes of decodeImage(data)) hash.update(bytes); + const dir = await getMaterializedImageAttachmentDir(); + const filePath = path.join(dir, `${hash.digest("hex")}.${getImageExtension(mimeType)}`); + try { + await fs.stat(filePath); + return { path: filePath }; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + } + + const staging = await fs.mkdtemp(path.join(dir, ".pending-")); + const stagingPath = path.join(staging, "image"); + try { + await fs.chmod(staging, PRIVATE_ATTACHMENT_DIR_MODE); + const file = await fs.open(stagingPath, "wx", MATERIALIZED_IMAGE_FILE_MODE); + try { + await file.chmod(MATERIALIZED_IMAGE_FILE_MODE); + // Decode again only for a new hash. This bounds retained memory to one chunk + // and performs no writes at all for repeated content, including history replay. + for await (const bytes of decodeImage(data)) await file.writeFile(bytes); + } finally { + await file.close(); + } + await fs.rename(stagingPath, filePath); + return { path: filePath }; + } finally { + await fs.rm(staging, { recursive: true, force: true }); + } +} + +async function* decodeImage(data: string): AsyncGenerator { + let carry = ""; + let decodedBytes = 0; + for (let offset = 0; offset < data.length; offset += BASE64_CHUNK_CHARACTERS) { + // Buffer.from ignores non-base64 characters. Carry incomplete quartets so + // line-wrapped payloads decode identically across chunk boundaries. + const chunk = + carry + + data.slice(offset, offset + BASE64_CHUNK_CHARACTERS).replace(/[^A-Za-z0-9+/_=-]/g, ""); + const finalChunk = offset + BASE64_CHUNK_CHARACTERS >= data.length || chunk.includes("="); + const end = finalChunk ? chunk.length : chunk.length - (chunk.length % 4); + const bytes = Buffer.from(chunk.slice(0, end), "base64"); + carry = chunk.slice(end); + decodedBytes += bytes.length; + if (decodedBytes > MAX_PROVIDER_IMAGE_BYTES) + throw new Error("Image attachment exceeds size limit"); + yield bytes; + await setImmediate(); + if (finalChunk) break; + } } // Recognizes markdown rendered for a materialized provider image: its source is a content-hashed @@ -112,7 +167,10 @@ export function isProviderImageMarkdown(text: string): boolean { } interface RenderProviderImageOutputOptions { - materialize?: (image: { data: string; mimeType: string | null }) => MaterializedProviderImage; + materialize?: (image: { + data: string; + mimeType: string | null; + }) => Promise; } function nonEmptyString(value: string | null | undefined): string | null { @@ -169,10 +227,10 @@ function escapeMarkdownImageSource(value: string): string { return markdownImageSource(value).replace(/\\/g, "\\\\").replace(/\)/g, "\\)"); } -export function renderProviderImageOutputAsAssistantMarkdown( +export async function renderProviderImageOutputAsAssistantMarkdown( image: ProviderImageOutput, options: RenderProviderImageOutputOptions = {}, -): AgentTimelineItem | null { +): Promise { const source = nonEmptyString(image.path) ?? nonEmptyString(image.url); if (source && !isDataImageSource(source)) { const altText = escapeMarkdownImageAlt(nonEmptyString(image.altText) ?? "Image"); @@ -191,7 +249,7 @@ export function renderProviderImageOutputAsAssistantMarkdown( let materialized: MaterializedProviderImage | null = null; try { materialized = options.materialize - ? options.materialize({ + ? await options.materialize({ data, mimeType: nonEmptyString(image.mimeType), }) From 3a1b1466904a42d286f99641d1242d42e85f4f32 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Tue, 27 Oct 2026 13:41:54 +0700 Subject: [PATCH 049/173] Guard daemon modules against synchronous Node IO (#7991) * chore(server): guard against synchronous Node IO in daemon modules * chore(server): retire unused sync IO exceptions automatically * chore(server): remove the attachment IO exception after async materialization --- .oxlintrc.json | 145 +++++++++++++++++++++++++++ scripts/oxlint/paseo-plugin.mjs | 121 ++++++++++++++++++++++ scripts/oxlint/paseo-plugin.test.mjs | 114 +++++++++++++++++++-- 3 files changed, 372 insertions(+), 8 deletions(-) diff --git a/.oxlintrc.json b/.oxlintrc.json index f5078649c9..7a6192215e 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -85,6 +85,151 @@ "max-nested-callbacks": ["error", { "max": 3 }] }, "overrides": [ + // Exceptions name individual APIs in individual modules; new APIs still fail in these files. + // TODO entries are runtime debt, not startup exemptions. Do not add directory-wide exceptions. + { + "files": ["packages/server/src/**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}"], + "rules": { + "paseo/no-sync-io": [ + "error", + { + "allow": { + // TODO: literal executableExists is a synchronous public capability; move its callers and Windows existence predicates to async together. + "executable-resolution/executable-resolution.ts": ["existsSync"], + // TODO: winget enumeration shares synchronous existence predicates with literal lookup; convert the executable-resolution boundary together. + "executable-resolution/windows.ts": ["readdirSync"], + // TODO: live file-change classification is a synchronous event mapper; move the probe to async event ingestion. + "server/agent/providers/claude/agent.ts": ["existsSync"], + // TODO: new-session construction still resolves its project directory synchronously; move preparation before construction. + "server/agent/providers/claude/project-dir.ts": ["realpathSync"], + // TODO: live subagent output is read by a synchronous event mapper; add bounded async loading at ingestion. + "server/agent/providers/claude/subagents/workflow-output.ts": [ + "closeSync", + "openSync", + "readSync" + ], + // TODO: diagnostics probes provider-owned auth/session storage; convert alongside provider discovery and readiness. + "server/agent/providers/omp/agent.ts": ["existsSync"], + // TODO: synchronous provider configuration discovery; move discovery into async launch preparation. + "server/agent/providers/omp/provider-config.ts": ["existsSync"], + // TODO: synchronous session-root selection is shared by descriptor builders; migrate callers with explicit readiness. + "server/agent/providers/omp/session-descriptor.ts": ["existsSync"], + // TODO: launch directory creation shares the server generation/start state machine; audit concurrent rotation before adding an await. + "server/agent/providers/opencode/server-manager.ts": ["mkdirSync"], + // TODO: launch preparation owns MCP config merge, extension generation and synchronous cleanup; migrate lifecycle and diagnostics together. + "server/agent/providers/pi/agent.ts": [ + "existsSync", + "mkdtempSync", + "readFileSync", + "rmSync", + "writeFileSync" + ], + // Provider child process: Pi loads this extension outside the daemon; it reads child-agent status there. + "server/agent/providers/pi/extensions/pi-subagents/index.ts": ["readFileSync"], + // Startup/shutdown only: remove stale Unix listening sockets before bind and during disposal. + "server/bootstrap.ts": ["existsSync", "unlinkSync"], + // Startup configuration resolution: detect the bundled app distribution before the daemon listens. + "server/config.ts": ["existsSync"], + // Startup identity: load or create the daemon keypair before accepting connections. + "server/daemon-keypair.ts": ["existsSync", "readFileSync"], + // Fatal exit diagnostics: synchronously flush the exit reason when the worker is about to terminate. + "server/daemon-worker.ts": ["appendFileSync", "mkdirSync"], + // Startup host identity: memoized scutil lookup is warmed before listening; later callers use the cache. + "server/host-name.ts": ["execFileSync"], + // TODO: relationship persistence is atomic with enrollment/revocation state transitions; serialize those transitions before async writes. + "server/hub/relationship-controller.ts": [ + "existsSync", + "readFileSync", + "renameSync", + "rmSync" + ], + // Local client bootstrap: reads the local credential and pid lock to select/authenticate a daemon connection. + "server/local-credential.ts": ["readFileSync"], + // Startup logger construction: create the log directory before opening the logging destination. + "server/logger.ts": ["mkdirSync"], + // TODO: runtime skill commands resolve their bundled source through a synchronous targets capability; migrate the capability and controller together. + "server/orchestration-skills/internal/paths.ts": ["existsSync"], + // Module initialization: the package version is resolved once and cached at import. + "server/package-version.ts": ["existsSync", "readFileSync"], + // Startup config and exported synchronous configuration API; runtime DaemonConfigStore uses the async load/save capabilities. + "server/persisted-config.ts": ["existsSync", "readFileSync"], + // Startup pid identity: read and memoize the Linux boot id for the daemon lock. + "server/pid-lock.ts": ["readFileSync"], + // Startup builtin loader construction: select the bundled plugin root before loading plugins. + "server/plugins/builtin/index.ts": ["existsSync"], + // Build child process: plugin graph traversal and esbuild preparation run in the isolated compiler process. + "server/plugins/compiler-build.ts": ["existsSync", "readFileSync", "realpathSync"], + // Build child process: select the esbuild binary for the isolated plugin compiler. + "server/plugins/compiler-esbuild.ts": ["existsSync"], + // Build child process: TypeScript resolution and source reads run in the isolated plugin compiler. + "server/plugins/compiler-imports.ts": ["readFileSync", "realpathSync"], + // TODO: plugin install/update/remove commits sources.json synchronously; preserve record/write ordering with an async mutation queue. + "server/plugins/managed-source.ts": ["existsSync", "readFileSync"], + // TODO: shared synchronous persistence supports startup identity plus Hub/plugin/push runtime writers; migrate those owners before removing these exports. + "server/private-files.ts": [ + "chmodSync", + "mkdirSync", + "realpathSync", + "renameSync", + "rmSync", + "writeFileSync" + ], + // TODO: constructor load plus runtime renew/revoke/prune use synchronous persistence; introduce ordered async mutations and readiness. + "server/push/token-store.ts": ["existsSync", "readFileSync"], + // Startup identity: load or create the server id before accepting connections. + "server/server-id.ts": ["existsSync", "readFileSync"], + // Listener lifecycle only: unlink the Unix socket before binding or after stopping the proxy. + "server/service-proxy.ts": ["existsSync", "unlinkSync"], + // TODO: self-update origin validation exposes synchronous package-root and realpath checks; migrate validation and its runtime interface together. + "server/session/daemon/install-origin.ts": ["existsSync", "readFileSync"], + // TODO: npm self-update inspection probes the reported install path; move the probe into bounded async installation inspection. + "server/session/daemon/npm-global-cli.ts": ["lstatSync"], + // Speech child process: model-file validation runs in the worker-backed local speech provider. + "server/speech/providers/local/sherpa/sherpa-offline-recognizer.ts": ["existsSync"], + // Speech child process: native addon discovery and patchelf run outside the daemon. + "server/speech/providers/local/sherpa/sherpa-onnx-node-loader.ts": [ + "existsSync", + "spawnSync" + ], + // Speech child process: model-file validation runs in the worker-backed local speech provider. + "server/speech/providers/local/sherpa/sherpa-tts.ts": ["existsSync"], + // TODO: static request selection and index injection need bounded async serving with response/error ownership; keep this as a separate request-path conversion. + "server/web-ui.ts": ["readFileSync", "statSync"], + // Startup registry hydration: check persisted workspace directories before the runtime reconciliation service starts. + "server/workspace-registry-bootstrap.ts": ["statSync"], + // Terminal child process: hook config installation/removal is owned by terminal creation and teardown in the worker. + "terminal/agent-hooks/agent-hook-installer.ts": [ + "existsSync", + "readFileSync", + "rmSync" + ], + // Node loader thread: TypeScript terminal-worker resolution runs in the loader, outside the daemon event loop. + "terminal/terminal-ts-loader.mjs": ["existsSync"], + // Terminal child process: executable preparation and shell integration run in the worker-backed terminal manager. + "terminal/terminal.ts": [ + "accessSync", + "chmodSync", + "existsSync", + "mkdirSync", + "readFileSync", + "statSync" + ], + // TODO: legacy realpath helpers still serve install-origin validation and other synchronous consumers; migrate remaining callers before removing them. + "utils/path.ts": ["realpathSync"] + } + } + ] + } + }, + { + "files": [ + "packages/server/src/**/*.{test,spec,fixture}.{ts,tsx,mts,cts,js,jsx,mjs,cjs}", + "packages/server/src/**/test-utils/**", + "packages/server/src/server/daemon-e2e/**", + "packages/server/src/server/agent/providers/pi/extensions/*-test.ts" + ], + "rules": { "paseo/no-sync-io": "off" } + }, { "files": [ "plugins/*-provider/server/**/*.ts", diff --git a/scripts/oxlint/paseo-plugin.mjs b/scripts/oxlint/paseo-plugin.mjs index d6f8d0365e..af58021991 100644 --- a/scripts/oxlint/paseo-plugin.mjs +++ b/scripts/oxlint/paseo-plugin.mjs @@ -34,9 +34,130 @@ const noRawPressable = { }, }; +const SYNC_IO_MODULES = new Set(["fs", "node:fs", "child_process", "node:child_process"]); + +function propertyName(node) { + return node.type === "Identifier" ? node.name : node.value; +} + +function findDefinition(node, sourceCode) { + let scope = sourceCode.getScope(node); + while (scope && !scope.set.has(node.name)) scope = scope.upper; + return scope?.set.get(node.name)?.defs[0]; +} + +function isIoNamespaceImport(definition) { + if (definition?.node.type === "TSImportEqualsDeclaration") { + return SYNC_IO_MODULES.has(definition.node.moduleReference.expression?.value); + } + if (definition?.type !== "ImportBinding") return false; + return ( + (definition.node.type !== "ImportSpecifier" || + propertyName(definition.node.imported) === "default") && + SYNC_IO_MODULES.has(definition.parent.source.value) + ); +} + +// Follow only immutable namespace aliases. Resolve bindings rather than spelling so a parameter +// named `fs` is not mistaken for the imported namespace. +function isIoNamespace(node, sourceCode, seen = new Set()) { + if (!node || seen.has(node)) return false; + seen.add(node); + if (node.type === "AwaitExpression") return isIoNamespace(node.argument, sourceCode, seen); + if (node.type === "ImportExpression") return SYNC_IO_MODULES.has(node.source.value); + if (node.type === "CallExpression") { + return ( + node.callee.type === "Identifier" && + node.callee.name === "require" && + SYNC_IO_MODULES.has(node.arguments[0]?.value) + ); + } + if (node.type !== "Identifier") return false; + const definition = findDefinition(node, sourceCode); + if (isIoNamespaceImport(definition)) return true; + return ( + definition?.type === "Variable" && + definition.parent.kind === "const" && + definition.node.id.type === "Identifier" && + isIoNamespace(definition.node.init, sourceCode, seen) + ); +} + +const noSyncIo = { + meta: { + schema: [ + { + type: "object", + properties: { + allow: { + type: "object", + additionalProperties: { type: "array", items: { type: "string" } }, + }, + }, + additionalProperties: false, + }, + ], + }, + create(context) { + const filename = context.filename.replaceAll("\\", "/"); + const relativeFile = filename.split("/packages/server/src/")[1]; + const allowed = new Set(context.options[0]?.allow?.[relativeFile] ?? []); + const unused = new Set(allowed); + function check(node, name) { + if (typeof name !== "string" || !name.endsWith("Sync")) return; + if (allowed.has(name)) { + unused.delete(name); + return; + } + context.report({ + node, + message: `Synchronous Node IO (${name}) blocks the daemon event loop. Use an asynchronous capability at the owning module boundary.`, + }); + } + return { + "Program:exit"(node) { + for (const name of unused) { + context.report({ node, message: `Remove the unused sync IO exception for ${name}.` }); + } + }, + ImportDeclaration(node) { + if (node.importKind === "type" || !SYNC_IO_MODULES.has(node.source.value)) return; + for (const specifier of node.specifiers) { + if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type") { + check(specifier, propertyName(specifier.imported)); + } + } + }, + ExportNamedDeclaration(node) { + if (node.exportKind === "type" || !SYNC_IO_MODULES.has(node.source?.value)) return; + for (const specifier of node.specifiers) { + if (specifier.exportKind !== "type") check(specifier, propertyName(specifier.local)); + } + }, + MemberExpression(node) { + if (node.computed && node.property.type !== "Literal") return; + const name = propertyName(node.property); + if (typeof name !== "string" || !name.endsWith("Sync")) return; + if (isIoNamespace(node.object, context.sourceCode)) { + check(node.property, name); + } + }, + VariableDeclarator(node) { + if (node.id.type !== "ObjectPattern" || !isIoNamespace(node.init, context.sourceCode)) { + return; + } + for (const property of node.id.properties) { + if (property.type === "Property") check(property, propertyName(property.key)); + } + }, + }; + }, +}; + export default { meta: { name: "paseo" }, rules: { "no-raw-pressable": noRawPressable, + "no-sync-io": noSyncIo, }, }; diff --git a/scripts/oxlint/paseo-plugin.test.mjs b/scripts/oxlint/paseo-plugin.test.mjs index c30a429026..4312f5e337 100644 --- a/scripts/oxlint/paseo-plugin.test.mjs +++ b/scripts/oxlint/paseo-plugin.test.mjs @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { test } from "node:test"; @@ -10,15 +10,21 @@ const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../ const oxlintBin = path.join(repoRoot, "node_modules/.bin/oxlint"); const pluginPath = path.join(repoRoot, "scripts/oxlint/paseo-plugin.mjs"); -function lint(source) { +function lint(source, rule = "paseo/no-raw-pressable", options, filename = "probe.tsx") { + const config = JSON.stringify({ + jsPlugins: [pluginPath], + rules: { [rule]: options ? ["error", options] : "error" }, + }); + return lintWithConfig(source, config, filename); +} + +function lintWithConfig(source, config, filename) { const dir = mkdtempSync(path.join(tmpdir(), "paseo-oxlint-")); try { - writeFileSync( - path.join(dir, ".oxlintrc.json"), - JSON.stringify({ jsPlugins: [pluginPath], rules: { "paseo/no-raw-pressable": "error" } }), - ); - writeFileSync(path.join(dir, "probe.tsx"), source); - const result = spawnSync(oxlintBin, ["-c", ".oxlintrc.json", "probe.tsx"], { + writeFileSync(path.join(dir, ".oxlintrc.json"), config); + mkdirSync(path.dirname(path.join(dir, filename)), { recursive: true }); + writeFileSync(path.join(dir, filename), source); + const result = spawnSync(oxlintBin, ["-c", ".oxlintrc.json", filename], { cwd: dir, encoding: "utf8", }); @@ -52,3 +58,95 @@ test("press primitives and pressable types are allowed", () => { ); assert.equal(result.failed, false, result.output); }); + +for (const source of [ + 'import { readFileSync as read } from "node:fs"; export { read };', + 'import { execSync } from "child_process"; export { execSync };', + 'import fs from "node:fs"; export const read = fs.readFileSync;', + 'import { default as fs } from "node:fs"; export const read = fs.readFileSync;', + 'import fs = require("node:fs"); export const read = fs.readFileSync;', + 'import * as fs from "fs"; export const read = fs["readFileSync"];', + 'import cp from "node:child_process"; export const run = cp.spawnSync;', + 'const { readFileSync: read } = require("node:fs"); export { read };', + 'const fs = require("fs"); export const read = fs.readFileSync;', + 'export const run = require("node:child_process").execFileSync;', + 'import fs from "node:fs"; const other = fs; export const read = other.statSync;', + 'export { readFileSync as read } from "node:fs";', + 'export const read = (await import("node:fs")).readFileSync;', +]) { + test(`sync IO is reported: ${source}`, () => { + const result = lint(source, "paseo/no-sync-io"); + assert.equal(result.failed, true, result.output); + assert.match(result.output, /Synchronous Node IO/); + }); +} + +test("async IO, types, unrelated methods and shadowed namespaces are allowed", () => { + const result = lint( + 'import fs from "node:fs"; import { readFile } from "node:fs/promises";\n' + + 'import type { readFileSync } from "node:fs";\n' + + "export const read = readFile; export const asyncRead = fs.promises.readFile;\n" + + "export function unrelated(fs: { readFileSync(): void }) { fs.readFileSync(); }\n" + + "export type Reader = typeof readFileSync;\n", + "paseo/no-sync-io", + ); + assert.equal(result.failed, false, result.output); +}); + +test("sync IO exceptions allow only named APIs in the named server module", () => { + const options = { allow: { "server/startup.ts": ["readFileSync"] } }; + const source = 'import { readFileSync } from "node:fs"; export { readFileSync };'; + const allowed = lint( + source, + "paseo/no-sync-io", + options, + "packages/server/src/server/startup.ts", + ); + assert.equal(allowed.failed, false, allowed.output); + const otherFile = lint( + source, + "paseo/no-sync-io", + options, + "packages/server/src/server/session.ts", + ); + assert.equal(otherFile.failed, true, otherFile.output); + assert.match(otherFile.output, /Synchronous Node IO/); + const otherApi = lint( + 'import fs from "node:fs"; export const read = fs.statSync;', + "paseo/no-sync-io", + options, + "packages/server/src/server/startup.ts", + ); + assert.equal(otherApi.failed, true, otherApi.output); + assert.match(otherApi.output, /Synchronous Node IO/); +}); + +test("repository config guards request paths while allowing startup APIs and test fixtures", () => { + const config = readFileSync(path.join(repoRoot, ".oxlintrc.json"), "utf8").replace( + '"./scripts/oxlint/paseo-plugin.mjs"', + JSON.stringify(pluginPath), + ); + const source = 'import { existsSync } from "node:fs"; export const probe = existsSync;'; + const request = lintWithConfig(source, config, "packages/server/src/server/probe.ts"); + assert.equal(request.failed, true, request.output); + assert.match(request.output, /Synchronous Node IO/); + for (const filename of [ + "packages/server/src/server/config.ts", + "packages/server/src/server/probe.test.ts", + "packages/app/src/probe.ts", + ]) { + const result = lintWithConfig(source, config, filename); + assert.equal(result.failed, false, result.output); + } +}); + +test("sync IO exceptions must be removed when a module stops using the API", () => { + const result = lint( + 'import { readFile } from "node:fs/promises"; export const read = readFile;', + "paseo/no-sync-io", + { allow: { "server/startup.ts": ["readFileSync"] } }, + "packages/server/src/server/startup.ts", + ); + assert.equal(result.failed, true, result.output); + assert.match(result.output, /Remove the unused sync IO exception for readFileSync/); +}); From b12eefb28ff99fd8a26eb826fced87f5d62dd808 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Tue, 27 Oct 2026 13:57:17 +0700 Subject: [PATCH 050/173] Keep conversation turns distinct and history stable (#7990) * fix(app): keep autonomous turns distinct and readable Hidden system prompts merged autonomous work into the previous response and reopened completed turns. Preserve canonical turn boundaries and expose their triggers, while making received messages attributable and expanded turn details readable in one step. * fix(timeline): mount history at actual run boundaries * fix(timeline): load and retain complete available turns * fix(app): summarize actions and preserve conversation events * test(timeline): verify whole-turn paging stays responsive * fix(app): group reasoning according to thinking preference * test(app): align history journeys with whole-turn loading --- docs/timeline-sync.md | 34 ++- .../browser/agent-message-submission.spec.ts | 9 +- .../owned-subscriptions-old-daemon.spec.ts | 57 +---- .../app/e2e/browser/turn-collapse.spec.ts | 235 +++++++++++++++++- .../app/e2e/support/helpers/custom-models.ts | 3 + .../app/e2e/support/helpers/seed-client.ts | 6 +- .../src/agent-stream/footer-spacing.test.ts | 2 +- .../app/src/agent-stream/history-window.ts | 3 +- packages/app/src/agent-stream/layout.test.ts | 12 +- packages/app/src/agent-stream/layout.ts | 55 ++-- packages/app/src/agent-stream/model.test.ts | 18 +- .../app/src/agent-stream/presentation.test.ts | 126 ++++++++++ packages/app/src/agent-stream/presentation.ts | 54 +++- .../src/agent-stream/render-strategy.test.ts | 4 +- .../app/src/agent-stream/stream-tick.bench.ts | 2 +- .../agent-stream/turn-collapse/model.test.ts | 64 ++++- .../src/agent-stream/turn-collapse/model.ts | 72 ++++-- .../turn-collapse/summary-line.tsx | 16 +- packages/app/src/agent-stream/turn-footer.tsx | 2 +- .../src/agent-stream/turn-membership.test.ts | 30 ++- .../app/src/agent-stream/turn-membership.ts | 22 +- packages/app/src/agent-stream/view.tsx | 73 ++++-- .../agent-stream/web-virtualization.test.ts | 11 + packages/app/src/components/indent-rail.tsx | 7 +- packages/app/src/components/message.tsx | 88 ++++--- .../rewind/use-rewind-agent-mutation.ts | 4 +- packages/app/src/components/ui/edge-fade.tsx | 3 +- .../app/src/components/user-message/index.tsx | 79 ++++++ .../hooks/use-agent-initialization.test.ts | 5 + .../use-load-older-agent-history.test.ts | 1 + packages/app/src/i18n/resources/ar.ts | 9 +- packages/app/src/i18n/resources/en.ts | 9 +- packages/app/src/i18n/resources/es.ts | 9 +- packages/app/src/i18n/resources/fr.ts | 9 +- packages/app/src/i18n/resources/ja.ts | 9 +- packages/app/src/i18n/resources/ko.ts | 9 +- packages/app/src/i18n/resources/pt-BR.ts | 9 +- packages/app/src/i18n/resources/ru.ts | 9 +- packages/app/src/i18n/resources/zh-CN.ts | 9 +- .../src/runtime/replica-cache/index.test.ts | 15 ++ .../app/src/runtime/replica-cache/index.ts | 12 +- .../screens/workspace/workspace-screen.tsx | 4 +- .../src/timeline/timeline-replacement.test.ts | 2 +- .../src/timeline/timeline-sync-plan.test.ts | 4 + .../app/src/timeline/timeline-sync-plan.ts | 7 + packages/app/src/timeline/turn-time.test.ts | 60 +++-- packages/app/src/timeline/turn-time.ts | 30 ++- .../src/timeline/viewed-timeline-sync.test.ts | 21 +- .../src/tool-calls/detail-level/grouping.ts | 43 ++-- .../tool-calls/detail-level/overview/label.ts | 7 +- .../tool-calls/detail-level/overview/model.ts | 34 +-- .../detail-level/projection.test.ts | 64 ++++- .../src/tool-calls/detail-level/projection.ts | 5 + packages/app/src/types/stream.ts | 2 + packages/client/src/daemon-client.test.ts | 5 + packages/client/src/daemon-client.ts | 5 + packages/protocol/src/messages.ts | 3 + .../src/paseo-tool-presentation/catalog.ts | 126 +++++++--- .../src/paseo-tool-presentation/index.ts | 15 +- packages/protocol/src/timeline-turn.ts | 24 ++ .../src/server/agent/agent-manager.test.ts | 70 +++++- .../server/agent/agent-messages/envelope.ts | 17 +- .../src/server/agent/agent-prompt.test.ts | 18 ++ .../agent/agent-timeline-store-types.ts | 1 + .../server/agent/agent-timeline-store.test.ts | 87 +++++-- .../src/server/agent/agent-timeline-store.ts | 1 + .../agent/providers/mock-load-test-agent.ts | 48 ++-- .../test-utils/timeline-page-reference.ts | 2 +- .../server/agent/timeline-projection.test.ts | 148 +++++++++++ .../src/server/agent/timeline-projection.ts | 39 ++- packages/server/src/server/session.ts | 1 + .../server/src/server/websocket-server.ts | 1 + 72 files changed, 1690 insertions(+), 409 deletions(-) create mode 100644 packages/app/src/components/user-message/index.tsx create mode 100644 packages/protocol/src/timeline-turn.ts diff --git a/docs/timeline-sync.md b/docs/timeline-sync.md index 118ad628ce..0dd2c2093f 100644 --- a/docs/timeline-sync.md +++ b/docs/timeline-sync.md @@ -13,7 +13,7 @@ and rebuilds the projection when an agent resumes. The invariants are: > A continuously subscribed client applies every committed row in order. Opening or resuming an -> agent establishes the daemon's current tail in one bounded request, with older history reachable +> agent establishes the daemon's current tail in one complete-turn request, with older history reachable > through backward pagination. Tool output is bounded before it enters either delivery path. Canonical shell tool output is sliced @@ -44,7 +44,20 @@ recovery is complete only when `hasNewer: false`. Initialization timeouts guard lack of catch-up progress, not the full multi-page sync. A successful page that queues the next `after` page refreshes the watchdog. -Opening or resuming an agent fetches one bounded latest tail page. Older history remains +Opening or resuming an agent fetches the latest available turns with a soft target of 40 +projected items. Backward pages and prompt-jump windows also include whole turns, including +all currently available rows of an active run. There is no per-turn cap: a large run can +exceed the target. Local history mounting uses the same boundaries so revealing older rows +does not change the collapse state of a turn already displayed. + +`wholeTurns` is optional for existing SDK callers. The app requires +`features.wholeTurnTimeline` once at the client fetch boundary; unsupported hosts receive an +update-host error. Forward catch-up stays incremental, but its reset snapshot honors the +whole-turn request. Source coverage still includes interleaved tool updates. + +Canonical IDs define runs. With missing IDs, human prompts, heartbeats and typed received +agent messages each start a fallback turn. This deterministic fallback is shared by paging +and presentation; it cannot recover historical batching or steering. Older history remains user-driven by scrolling upward. A failed catch-up or subscription reconcile retries on its own, doubling from 1s to a 30s ceiling. @@ -149,12 +162,13 @@ range describes those exact items: `startSeq` drives older pagination and `endSe catch-up. The owner requests `after endSeq`, and requests `before startSeq` when the user loads older history. Code outside the owner does not distinguish cached and network timelines. -The first resume request is bounded. If it reports more newer history, fetch one latest bounded tail +The first resume request is bounded. If it reports more newer history, fetch one latest complete-turn tail instead of replaying every missed page. Live gap recovery still pages forward until current. -If the canonical window exceeds the cache item limit, contains a discontiguous retained range, has a +If the canonical window exceeds the cache item target, contains a discontiguous retained range, has a live head, or includes presentation data the cache cannot encode losslessly, persistence drops the -range and keeps a display-only tail. Never slice items while retaining the pre-slice range; that +range and keeps a display-only tail of complete available turns. The item target is soft; +the byte budget still evicts entire cache rows. Never slice items while retaining the pre-slice range; that falsely certifies discarded source rows. A display-only row paints without granting synchronization authority, so the owner uses the ordinary bounded `tail` bootstrap. @@ -238,11 +252,11 @@ foreground control ownership remains a separate daemon concern. Cancellation req with that record rather than in a React component, so an old request cannot clear a newer one. Submissions remain a separate pre-turn registry and retire on canonical acknowledgement. -Canonical turns and visible responses are different boundaries. Agent-originated prompts and lifecycle -notifications project into tool rows, so they do not create a human-message boundary. Legacy system -prompts, including schedule injections, remain hidden. One visible response can span several canonical -turns; layout and copy group that response together while lifecycle, timing, tool sequences, and exact -fork positions retain the canonical `turnId` boundaries. +Every canonical run owns a visible turn, including heartbeats and agent notifications. +Notifications delivered during a run stay inside it; batched notifications share the run +that starts or accepts them. Received messages retain sender attribution, while lifecycle +notifications remain visible events. Collapse, timing and locally mounted history share +these boundaries. Agent-message XML belongs to the daemon's `agent/agent-messages` boundary. Prompt delivery encodes provenance; acceptance, provider echoes, import, and replay share its projection. The delivery ID is diff --git a/packages/app/e2e/browser/agent-message-submission.spec.ts b/packages/app/e2e/browser/agent-message-submission.spec.ts index 0009188b34..dcf872f8be 100644 --- a/packages/app/e2e/browser/agent-message-submission.spec.ts +++ b/packages/app/e2e/browser/agent-message-submission.spec.ts @@ -53,6 +53,7 @@ import { import { expectInFlightForkAvailable } from "../support/helpers/assistant-fork"; import { scrollTimelineToNewestLoadedEdge, + userScrollsTimelineToHistoryStart, scrollTimelineUntilOlderHistoryIsReachable, } from "../support/helpers/timeline-pagination"; import { @@ -986,7 +987,7 @@ test.describe("Agent message submission", () => { } }); - test("keeps one prompt when its provider echo crosses the bounded tail", async ({ + test("keeps one prompt when a delayed provider echo belongs to a large whole turn", async ({ page, }, testInfo) => { const workspace = await seedWorkspace({ @@ -1003,8 +1004,10 @@ test.describe("Agent message submission", () => { await expectVisibleAgentSurfacesIdle(page); await page.reload(); - await expect(submittedPrompt).toHaveCount(0); - await scrollTimelineUntilOlderHistoryIsReachable(page, prompt); + // The complete turn arrives on reload; scrolling mounts its oldest rows + // without requiring another page or an increase in total content height. + await userScrollsTimelineToHistoryStart(page); + await expect(submittedPrompt).toBeVisible(); await expect(submittedPrompt).toHaveCount(1); await expect(submittedPrompt).toHaveAttribute("aria-busy", "false"); } finally { diff --git a/packages/app/e2e/browser/owned-subscriptions-old-daemon.spec.ts b/packages/app/e2e/browser/owned-subscriptions-old-daemon.spec.ts index 17f4db2e85..4b49d8105e 100644 --- a/packages/app/e2e/browser/owned-subscriptions-old-daemon.spec.ts +++ b/packages/app/e2e/browser/owned-subscriptions-old-daemon.spec.ts @@ -1,5 +1,4 @@ import { randomUUID } from "node:crypto"; -import { submitMessage, expectComposerEditable } from "../support/helpers/composer"; import { focusTerminalSurface, typeInTerminal, @@ -11,14 +10,9 @@ import { buildCreateAgentPreferences, buildSeededHost } from "../support/helpers import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon"; import type { MockAgentWorkspace } from "../support/helpers/mock-agent"; import { seedWorkspace } from "../support/helpers/seed-client"; -import { - expectTimelinePromptVisible, - holdOlderHistoryPages, - openAgentTimeline, - scrollThroughOlderHistoryPages, -} from "../support/helpers/timeline-pagination"; +import { openAgentTimeline } from "../support/helpers/timeline-pagination"; -test("does not repeat an assistant block when the current app paginates a published 0.2.5 daemon", async ({ +test("requires a host update for whole-turn history while retaining old-daemon connections and terminals", async ({ page, }) => { test.setTimeout(120_000); @@ -58,22 +52,8 @@ test("does not repeat an assistant block when the current app paginates a publis }; try { - for (let index = 0; index < 40; index += 1) { - await agent.client.sendAgentMessage( - agent.agentId, - `timeline-pagination-older-turn-${index}: emit 1 coalesced agent stream updates`, - ); - await agent.client.waitForFinish(agent.agentId, 15_000); - } - await agent.client.sendAgentMessage(agent.agentId, "build a realistic long mock timeline"); - await agent.client.waitForFinish(agent.agentId, 20_000); - for (let index = 0; index < 20; index += 1) { - await agent.client.sendAgentMessage( - agent.agentId, - `timeline-pagination-turn-${index}: emit 1 coalesced agent stream updates`, - ); - await agent.client.waitForFinish(agent.agentId, 15_000); - } + await agent.client.sendAgentMessage(agent.agentId, "emit 1 coalesced agent stream updates"); + await agent.client.waitForFinish(agent.agentId, 15_000); const host = buildSeededHost({ serverId, @@ -89,34 +69,18 @@ test("does not repeat an assistant block when the current app paginates a publis { seededHost: host, preferences: buildCreateAgentPreferences() }, ); - const history = await holdOlderHistoryPages(page, agent, daemon.port); await openAgentTimeline(page, agent, serverId); - await expectTimelinePromptVisible( - page, - "timeline-pagination-turn-19: emit 1 coalesced agent stream updates", - ); - await scrollThroughOlderHistoryPages(page, 3, history); - - history.expectRepeatedEntries(); - await history.expectOwnedTextRendered("Now I have a clearer picture."); + const updateMessage = page.getByText("Update the host to load complete conversation turns.", { + exact: true, + }); + await expect(updateMessage).toBeVisible(); expect(observationSockets.size).toBe(1); - await test.step("send a live turn after reconnecting the old daemon", async () => { + await test.step("retain one directory observation after reconnecting the old daemon", async () => { await daemon.restart(); await expect.poll(() => observationSockets.size, { timeout: 30_000 }).toBe(2); - await expectComposerEditable(page); - await submitMessage( - page, - "compatibility-after-reconnect: emit 1 coalesced agent stream updates", - ); - await expectTimelinePromptVisible( - page, - "compatibility-after-reconnect: emit 1 coalesced agent stream updates", - ); - // The browser and the seed client reconnect independently after the restart. + await expect(updateMessage).toBeVisible(); await agent.client.connect(); - await agent.client.waitForFinish(agent.agentId, 20_000); - await page.screenshot({ path: test.info().outputPath("old-daemon-live-reconnect.png") }); }); await test.step("open a terminal and receive its output", async () => { @@ -130,7 +94,6 @@ test("does not repeat an assistant block when the current app paginates a publis await expect .poll(() => getTerminalBufferText(page), { timeout: 15_000 }) .toContain("compatibility-terminal-output"); - await page.screenshot({ path: test.info().outputPath("old-daemon-terminal.png") }); await agent.client.killTerminal(terminalId); }); } finally { diff --git a/packages/app/e2e/browser/turn-collapse.spec.ts b/packages/app/e2e/browser/turn-collapse.spec.ts index 1deb050fa8..bef85080cf 100644 --- a/packages/app/e2e/browser/turn-collapse.spec.ts +++ b/packages/app/e2e/browser/turn-collapse.spec.ts @@ -1,3 +1,8 @@ +import { + holdOlderHistoryPages, + userScrollsTimelineToHistoryStart, +} from "../support/helpers/timeline-pagination"; +import { getActiveTabTestId } from "../support/helpers/launcher"; import type { Page } from "@playwright/test"; import { test, expect } from "../support/fixtures"; import { expectComposerVisible } from "../support/helpers/composer"; @@ -19,7 +24,10 @@ async function seedAnsweredAgent(title: string) { initialPrompt: "Why does the chat stop following new output?", }); await agent.client.waitForFinish(agent.agentId, 30_000); - await agent.client.sendAgentMessage(agent.agentId, "Make the fix and run the burst script."); + await agent.client.sendAgentMessage( + agent.agentId, + "Make the fix and run the burst script.\n" + "Keep the previous response visible.\n".repeat(40), + ); await agent.client.waitForFinish(agent.agentId, 30_000); return agent; } @@ -36,17 +44,67 @@ async function rowsBetweenLatestSummaryAndReply(page: Page): Promise { }); } +async function groupedToolsInsideLatestTurn(page: Page): Promise { + return page.evaluate(() => { + const rows = [...document.querySelectorAll("[data-message-id]")]; + const start = rows.findLastIndex((row) => row.querySelector("[data-testid=turn-summary]")); + const end = rows.findLastIndex((row) => row.querySelector("[data-testid=assistant-message]")); + return rows + .slice(start + 1, end) + .flatMap((row) => + [...row.querySelectorAll("[data-testid=tool-call-group]")].map( + (group) => group.textContent ?? "", + ), + ); + }); +} + +async function expandAndCollapseLongPrompt(page: Page) { + const prompt = page.getByTestId("user-message").last(); + const before = await prompt.boundingBox(); + const text = prompt.locator('[data-message-text="true"]'); + const messageLeft = (await text.boundingBox())!.x; + await expect + .poll(async () => (await prompt.getByText("Show more", { exact: true }).boundingBox())!.x) + .toBe(messageLeft); + await prompt.getByRole("button", { name: "Show more", exact: true }).click(); + await expect(prompt.getByRole("button", { name: "Show less", exact: true })).toBeVisible(); + await expect + .poll(async () => (await prompt.getByText("Show less", { exact: true }).boundingBox())!.x) + .toBe(messageLeft); + await expect + .poll(async () => (await prompt.boundingBox())?.height ?? 0) + .toBeGreaterThan(before!.height); + await prompt.getByRole("button", { name: "Show less", exact: true }).click(); + await expect.poll(async () => (await prompt.boundingBox())?.height ?? 0).toBe(before!.height); + await prompt.scrollIntoViewIfNeeded(); + const bounds = (await prompt.boundingBox())!; + const body = (await text.boundingBox())!; + await page.screenshot({ + path: "/tmp/message-toggle-aligned.png", + clip: { + x: body.x - 16, + y: bounds.y, + width: bounds.x + bounds.width - body.x + 16, + height: bounds.height, + }, + }); +} + test.describe("Turn collapse", () => { test("folds each answered turn behind a summary line that opens it", async ({ page }) => { test.setTimeout(120_000); + await page.setViewportSize({ width: 1280, height: 1000 }); await useChatDisplay(page, "collapseTurns"); const agent = await seedAnsweredAgent("Turn collapse"); try { await openAgentRoute(page, agent); await expectComposerVisible(page); + await expandAndCollapseLongPrompt(page); + const summary = page.getByTestId("turn-summary").last().getByRole("button"); - await expect(summary).toHaveText(/^Wrote \d+ messages?, edited 1 file/); + await expect(summary).toHaveText(/^Edited 1 file/); // Text chunks that stream back to back merge into one message, so the reply holds // at least the stream's last chunk. await expect(page.getByTestId("assistant-message").last()).toHaveText( @@ -57,6 +115,9 @@ test.describe("Turn collapse", () => { await summary.click(); await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBeGreaterThan(0); await expect(summary).toBeInViewport(); + await summary.evaluate((element) => element.scrollIntoView({ block: "start" })); + await page.screenshot({ path: "/tmp/turn-rail-aligned.png" }); + await expect.poll(() => groupedToolsInsideLatestTurn(page)).toEqual([]); await summary.click(); await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(0); @@ -65,3 +126,173 @@ test.describe("Turn collapse", () => { } }); }); + +test("received messages show their sender and open that agent", async ({ page }) => { + const recipient = await seedMockAgentWorkspace({ + repoPrefix: "sender-attribution-", + title: "Implementation", + }); + try { + const sender = await recipient.client.createAgent({ + provider: "mock", + cwd: recipient.cwd, + workspaceId: recipient.workspaceId, + title: "Reviewer", + model: "e2e-fast-stream", + modeId: "load-test", + }); + await recipient.client.sendAgentMessage( + recipient.agentId, + "I reviewed the turn-grouping changes. Heartbeats now keep their own timing footer, and the previous response stays visible.", + { sourceAgentId: sender.id }, + ); + await openAgentRoute(page, recipient); + await expectComposerVisible(page); + const attribution = page.getByRole("button", { name: "Sent by Reviewer", exact: true }); + await expect(attribution).toBeVisible(); + await expect(page.getByTestId("user-message").filter({ has: attribution })).toContainText( + "I reviewed the turn-grouping changes.", + ); + await attribution.scrollIntoViewIfNeeded(); + await page.screenshot({ path: "/tmp/sender-attribution.png" }); + await attribution.click(); + await expect.poll(() => getActiveTabTestId(page)).toContain(sender.id); + } finally { + await recipient.cleanup(); + } +}); + +async function seedWholeTurnHistory() { + const agent = await seedMockAgentWorkspace({ + repoPrefix: "whole-turn-history-", + title: "Whole turns", + model: "e2e-fast-stream", + }); + for (const prompt of [ + ...Array.from( + { length: 25 }, + (_, index) => `Short ${index}: emit 1 coalesced agent stream updates`, + ), + "Older long turn: emit 60 tool agent stream updates", + "Latest long turn: emit 120 tool agent stream updates", + ]) { + await agent.client.sendAgentMessage(agent.agentId, prompt); + await agent.client.waitForFinish(agent.agentId, 15_000); + } + return agent; +} + +test("loads complete long turns and preserves expansion while revealing older history", async ({ + page, +}) => { + test.setTimeout(120_000); + await useChatDisplay(page, "collapseTurns"); + const agent = await seedWholeTurnHistory(); + try { + const history = await holdOlderHistoryPages(page, agent); + await openAgentRoute(page, agent); + await expectComposerVisible(page); + const latest = page + .getByTestId("turn-summary") + .getByRole("button", { name: "Ran 120 commands", exact: true }); + await expect(latest).toBeVisible(); + await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(0); + await latest.click(); + await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(120); + await userScrollsTimelineToHistoryStart(page); + await history.expectRequestedPages(1); + history.releasePage(1); + await expect( + page + .getByTestId("turn-summary") + .getByRole("button", { name: "Ran 60 commands", exact: true }), + ).toBeVisible(); + await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(120); + history.expectNoRepeatedEntries(); + await latest.scrollIntoViewIfNeeded(); + await latest.click(); + await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(0); + } finally { + await agent.cleanup(); + } +}); + +async function useThinkingDisplay( + page: Page, + autoExpandReasoning: boolean, + chatDisplay: ChatDisplay, +) { + await page.addInitScript( + (settings) => { + localStorage.setItem( + "@paseo:app-settings", + JSON.stringify({ + ...settings, + chatDisplay: sessionStorage.getItem("e2e-chat-display") ?? settings.chatDisplay, + }), + ); + }, + { autoExpandReasoning, chatDisplay }, + ); +} + +for (const autoExpandReasoning of [false, true]) { + test(`reasoning follows Expand thinking (${autoExpandReasoning}) and opens fully with its turn`, async ({ + page, + }) => { + await page.setViewportSize({ width: 1280, height: 1000 }); + await useThinkingDisplay(page, autoExpandReasoning, "collapseToolCalls"); + const agent = await seedMockAgentWorkspace({ + repoPrefix: "thinking-group-", + title: "Thinking with tools", + model: "ten-second-stream", + initialPrompt: "Inspect the scroll container", + }); + try { + await agent.client.waitForFinish(agent.agentId, 30_000); + await openAgentRoute(page, agent); + await expectComposerVisible(page); + const reasoning = page + .getByText(/Need to find the scroll container, the layout effect/) + .filter({ visible: true }) + .first(); + await expectThinkingPresentation(page, autoExpandReasoning); + await switchToCollapsedTurns(page); + await expectComposerVisible(page); + const summary = page.getByTestId("turn-summary").last().getByRole("button"); + await expect(summary).toBeVisible(); + await summary.click(); + await expect(reasoning).toBeVisible(); + await expect.poll(() => groupedToolsInsideLatestTurn(page)).toEqual([]); + } finally { + await agent.cleanup(); + } + }); +} + +async function expectThinkingPresentation(page: Page, autoExpandReasoning: boolean) { + const reasoning = page + .getByText(/Need to find the scroll container, the layout effect/) + .filter({ visible: true }) + .first(); + if (autoExpandReasoning) { + await expect(reasoning).toBeVisible(); + await expect(page.getByTestId("tool-call-group").filter({ hasText: /thought/ })).toHaveCount(0); + } else { + await expect(reasoning).toHaveCount(0); + const group = page + .getByTestId("tool-call-group") + .filter({ hasText: /thought/, visible: true }) + .last(); + await expect(group).toContainText(/read 1 file/i); + await group.getByRole("button").first().click(); + await expect(reasoning).toBeVisible(); + } +} + +async function switchToCollapsedTurns(page: Page) { + await page.evaluate(() => { + sessionStorage.setItem("e2e-chat-display", "collapseTurns"); + }); + await page.reload(); +} diff --git a/packages/app/e2e/support/helpers/custom-models.ts b/packages/app/e2e/support/helpers/custom-models.ts index 11933a0dfa..aff79965ea 100644 --- a/packages/app/e2e/support/helpers/custom-models.ts +++ b/packages/app/e2e/support/helpers/custom-models.ts @@ -19,6 +19,9 @@ export async function addCustomModel(page: Page, id: string): Promise { .getByRole("button", { name: "Add", exact: true }) .click(); await expect(page.getByRole("button", { name: `Remove ${id}`, exact: true })).toHaveCount(1); + // Config updates before provider refresh finishes and dismisses the add sheet. + // Resizing or interacting with the model list must wait for that save to finish. + await expect(page.getByTestId("add-custom-model-sheet")).toBeHidden(); } export async function removeCustomModel(page: Page, id: string): Promise { diff --git a/packages/app/e2e/support/helpers/seed-client.ts b/packages/app/e2e/support/helpers/seed-client.ts index 4419e5193f..f57beb5783 100644 --- a/packages/app/e2e/support/helpers/seed-client.ts +++ b/packages/app/e2e/support/helpers/seed-client.ts @@ -149,7 +149,11 @@ export interface SeedDaemonClient { timeout?: number, ): Promise<{ status: string }>; cancelAgent(agentId: string): Promise; - sendAgentMessage(agentId: string, text: string): Promise; + sendAgentMessage( + agentId: string, + text: string, + options?: { sourceAgentId?: string }, + ): Promise; waitForFinish( agentId: string, timeout?: number, diff --git a/packages/app/src/agent-stream/footer-spacing.test.ts b/packages/app/src/agent-stream/footer-spacing.test.ts index 5fa3535bce..341ce75583 100644 --- a/packages/app/src/agent-stream/footer-spacing.test.ts +++ b/packages/app/src/agent-stream/footer-spacing.test.ts @@ -71,7 +71,7 @@ function layoutFor(input: { platform: "web" | "native"; isTurnActive: boolean }) isTurnActive: input.isTurnActive, history: strategy.orderTail([userMessage("user"), assistant]), liveHead: [], - timingByAssistantId: timingFor(assistant.id), + timingByItemId: timingFor(assistant.id), }), }; } diff --git a/packages/app/src/agent-stream/history-window.ts b/packages/app/src/agent-stream/history-window.ts index 347f780023..43cca2bbbf 100644 --- a/packages/app/src/agent-stream/history-window.ts +++ b/packages/app/src/agent-stream/history-window.ts @@ -1,4 +1,5 @@ import type { StreamItem } from "@/types/stream"; +import { continuesTurn } from "./turn-membership"; export const DEFAULT_MOUNTED_RECENT_STREAM_ITEMS = 20; @@ -32,7 +33,7 @@ export function findMountedWindowStart(input: { } let startIndex = Math.max(items.length - minMountedCount, 0); - while (startIndex > 0 && items[startIndex]?.kind !== "user_message") { + while (startIndex > 0 && continuesTurn(items[startIndex - 1], items[startIndex])) { startIndex -= 1; } return startIndex; diff --git a/packages/app/src/agent-stream/layout.test.ts b/packages/app/src/agent-stream/layout.test.ts index f10fde2cb1..a86817b6a7 100644 --- a/packages/app/src/agent-stream/layout.test.ts +++ b/packages/app/src/agent-stream/layout.test.ts @@ -104,7 +104,7 @@ function layoutFor(input: { strategy, streamHead: input.head ?? [], }), - timingByAssistantId: timingFor(...(input.timingIds ?? [])), + timingByItemId: timingFor(...(input.timingIds ?? [])), }); } @@ -148,7 +148,7 @@ function findLayoutItem(layout: StreamLayout, id: string): StreamLayoutItem { } describe("layoutStream", () => { - it("places one response footer after an adjacent tagged tool-only turn", () => { + it("keeps separate footers for an assistant turn and an adjacent tool-only turn", () => { const priorAssistant = assistantMessage("prior", 1, undefined, "turn-1"); const nextTool = toolCall("next-tool", 2, "turn-2"); const layout = layoutFor({ @@ -157,8 +157,8 @@ describe("layoutStream", () => { timingIds: [priorAssistant.id], }); - expect(layout.auxiliaryTurnFooter?.itemId).toBe(priorAssistant.id); - expect(footerOwners(layout)).toEqual([priorAssistant.id]); + expect(layout.auxiliaryTurnFooter?.itemId).toBe(nextTool.id); + expect(footerOwners(layout)).toEqual([priorAssistant.id, nextTool.id]); }); it("recomputes cached history layout when only the live boundary turn changes", () => { @@ -171,7 +171,7 @@ describe("layoutStream", () => { isTurnActive: true, history, liveHead, - timingByAssistantId: timingFor(priorAssistant.id), + timingByItemId: timingFor(priorAssistant.id), }); liveHead[0] = { ...liveHead[0]!, turnId: "turn-2" }; @@ -180,7 +180,7 @@ describe("layoutStream", () => { isTurnActive: true, history, liveHead, - timingByAssistantId: timingFor(priorAssistant.id), + timingByItemId: timingFor(priorAssistant.id), }); expect(footerOwners(first)).toEqual([]); diff --git a/packages/app/src/agent-stream/layout.ts b/packages/app/src/agent-stream/layout.ts index 82ef98db54..924d9d75ec 100644 --- a/packages/app/src/agent-stream/layout.ts +++ b/packages/app/src/agent-stream/layout.ts @@ -39,13 +39,13 @@ export interface StreamLayoutInput { isTurnActive: boolean; history: StreamItem[]; liveHead: StreamItem[]; - timingByAssistantId: Map; + timingByItemId: Map; } interface LayoutSegmentInput { strategy: StreamStrategy; items: StreamItem[]; - timingByAssistantId: Map; + timingByItemId: Map; auxiliaryTurnFooter: TurnFooterHost | null; hasAuxiliaryFooter: boolean; frameOrder: StreamFrameChildOrder; @@ -57,8 +57,8 @@ interface LayoutSegmentInput { phase: "streaming" | "complete"; } -interface AssistantFooterSource { - item: Extract; +interface TurnFooterSource { + item: StreamItem; items: StreamItem[]; index: number; } @@ -67,23 +67,26 @@ function createTurnFooterHost(input: { item: StreamItem; items: StreamItem[]; index: number; - timingByAssistantId: Map; + timingByItemId: Map; }): TurnFooterHost { return { itemId: input.item.id, items: input.items, - timing: input.timingByAssistantId.get(input.item.id), + timing: input.timingByItemId.get(input.item.id), startIndex: input.index, }; } -function findLatestAssistantInResponse(input: { +function findTurnFooterSource(input: { strategy: StreamStrategy; items: StreamItem[]; startIndex: number; boundaryAboveItems?: StreamItem[] | null; boundaryAboveIndex?: number | null; -}): AssistantFooterSource | null { +}): TurnFooterSource | null { + const last = input.items[input.startIndex]; + const toolFallback: TurnFooterSource | null = + last?.kind === "tool_call" ? { item: last, items: input.items, index: input.startIndex } : null; let items = input.items; let index = input.startIndex; let canCrossBoundary = true; @@ -97,7 +100,7 @@ function findLatestAssistantInResponse(input: { ) { const item = items[index]; if (!item || (laterItem && !continuesResponse(item, laterItem))) { - return null; + return toolFallback; } if (item.kind === "assistant_message") { return { item, items, index }; @@ -111,7 +114,7 @@ function findLatestAssistantInResponse(input: { input.boundaryAboveIndex === null || input.boundaryAboveIndex === undefined ) { - return null; + return toolFallback; } items = input.boundaryAboveItems; @@ -131,20 +134,20 @@ function resolveAuxiliaryTurnFooter(input: StreamLayoutInput): TurnFooterHost | return null; } - const assistant = findLatestAssistantInResponse({ + const source = findTurnFooterSource({ strategy: input.strategy, items: footerItems, startIndex: latestIndex, }); - if (!assistant) { + if (!source) { return null; } return createTurnFooterHost({ - item: assistant.item, - items: assistant.items, - index: assistant.index, - timingByAssistantId: input.timingByAssistantId, + item: source.item, + items: source.items, + index: source.index, + timingByItemId: input.timingByItemId, }); } @@ -154,7 +157,7 @@ function resolveCompletedFooter(input: { index: number; item: StreamItem; belowItem: StreamItem | null; - timingByAssistantId: Map; + timingByItemId: Map; auxiliaryTurnFooter: TurnFooterHost | null; boundaryAboveItems: StreamItem[] | null; boundaryAboveIndex: number | null; @@ -163,21 +166,21 @@ function resolveCompletedFooter(input: { return null; } - const assistant = findLatestAssistantInResponse({ + const source = findTurnFooterSource({ strategy: input.strategy, items: input.items, startIndex: input.index, boundaryAboveItems: input.boundaryAboveItems, boundaryAboveIndex: input.boundaryAboveIndex, }); - if (!assistant || input.auxiliaryTurnFooter?.itemId === assistant.item.id) { + if (!source || input.auxiliaryTurnFooter?.itemId === source.item.id) { return null; } return createTurnFooterHost({ - item: assistant.item, - items: assistant.items, - index: assistant.index, - timingByAssistantId: input.timingByAssistantId, + item: source.item, + items: source.items, + index: source.index, + timingByItemId: input.timingByItemId, }); } @@ -306,7 +309,7 @@ function layoutSegmentItem( index, item, belowItem, - timingByAssistantId: input.timingByAssistantId, + timingByItemId: input.timingByItemId, auxiliaryTurnFooter: input.auxiliaryTurnFooter, boundaryAboveItems: input.boundaryAboveItems, boundaryAboveIndex: input.boundaryAboveIndex, @@ -375,7 +378,7 @@ export function layoutStream(input: StreamLayoutInput): StreamLayout { history = layoutSegment({ strategy: input.strategy, items: input.history, - timingByAssistantId: input.timingByAssistantId, + timingByItemId: input.timingByItemId, auxiliaryTurnFooter, hasAuxiliaryFooter, frameOrder, @@ -395,7 +398,7 @@ export function layoutStream(input: StreamLayoutInput): StreamLayout { const liveHead = layoutSegment({ strategy: input.strategy, items: input.liveHead, - timingByAssistantId: input.timingByAssistantId, + timingByItemId: input.timingByItemId, auxiliaryTurnFooter, hasAuxiliaryFooter, frameOrder, diff --git a/packages/app/src/agent-stream/model.test.ts b/packages/app/src/agent-stream/model.test.ts index dec4c489b9..9c6ef3384d 100644 --- a/packages/app/src/agent-stream/model.test.ts +++ b/packages/app/src/agent-stream/model.test.ts @@ -69,8 +69,8 @@ describe("buildAgentStreamRenderModel", () => { historyStart: 2, }); - expect(model.turnTiming.byAssistantId.has("hidden-a")).toBe(false); - expect(model.turnTiming.byAssistantId.get("visible-a")).toEqual({ + expect(model.turnTiming.byItemId.has("hidden-a")).toBe(false); + expect(model.turnTiming.byItemId.get("visible-a")).toEqual({ completedAt: tail[3]?.timestamp, durationMs: 1000, }); @@ -184,7 +184,7 @@ describe("buildAgentStreamRenderModel", () => { }); expect(model.turnTiming.runningStartedAt).toBe(tail[0]?.timestamp); - expect(model.turnTiming.byAssistantId.has("live-a")).toBe(false); + expect(model.turnTiming.byItemId.has("live-a")).toBe(false); }); it("maps completed turn timing to assistant ids across committed history and live head", () => { @@ -201,7 +201,7 @@ describe("buildAgentStreamRenderModel", () => { }); expect(model.turnTiming.runningStartedAt).toBe(null); - expect(model.turnTiming.byAssistantId.get("live-a")).toEqual({ + expect(model.turnTiming.byItemId.get("live-a")).toEqual({ completedAt: head[0]?.timestamp, durationMs: 3000, }); @@ -220,7 +220,7 @@ describe("buildAgentStreamRenderModel", () => { }); expect(model.segments.historyMounted.map((item) => item.id)).toEqual(["a1", "u1"]); - expect(model.turnTiming.byAssistantId.get("a1")).toEqual({ + expect(model.turnTiming.byItemId.get("a1")).toEqual({ completedAt: tail[1]?.timestamp, durationMs: 3000, }); @@ -238,7 +238,7 @@ describe("buildAgentStreamRenderModel", () => { isMobileBreakpoint: false, }); - expect(model.turnTiming.byAssistantId.size).toBe(0); + expect(model.turnTiming.byItemId.size).toBe(0); }); it.each(["web", "native"] as const)( @@ -274,10 +274,10 @@ describe("buildAgentStreamRenderModel", () => { expect(second.history).toBe(first.history); expect(second.segments.historyMounted).toBe(first.segments.historyMounted); - expect(second.turnTiming.byAssistantId).toBe(first.turnTiming.byAssistantId); + expect(second.turnTiming.byItemId).toBe(first.turnTiming.byItemId); expect(first.history).toHaveLength(20); - expect(first.turnTiming.byAssistantId.has("a29")).toBe(false); - expect(first.turnTiming.byAssistantId.get("a38")).toEqual({ + expect(first.turnTiming.byItemId.has("a29")).toBe(false); + expect(first.turnTiming.byItemId.get("a38")).toEqual({ completedAt: tail[77]?.timestamp, durationMs: 1000, }); diff --git a/packages/app/src/agent-stream/presentation.test.ts b/packages/app/src/agent-stream/presentation.test.ts index 357b6c079b..bba7267a5d 100644 --- a/packages/app/src/agent-stream/presentation.test.ts +++ b/packages/app/src/agent-stream/presentation.test.ts @@ -588,3 +588,129 @@ describe("timeline presentation", () => { expect(projectTimelineItems([source], () => [])).toEqual([]); }); }); + +it("opening a turn reveals individual calls rather than another tool group", () => { + const present = createStreamPresentation(); + const timestamp = new Date(); + const tail: StreamItem[] = [ + { kind: "user_message", id: "prompt", text: "Work", timestamp }, + toolCall("one", "Bash"), + toolCall("two", "Bash"), + { kind: "assistant_message", id: "reply", text: "Done", timestamp }, + ]; + const result = present({ + ...presentationOptions, + transform: undefined, + tail, + head: [], + display: "collapseTurns", + isTurnActive: false, + expandedTurnHostIds: new Set(["prompt"]), + }); + expect(result.tail.map((item) => item.id)).toEqual(tail.map((item) => item.id)); + expect(result.groupsByHostId.size).toBe(0); +}); + +it("presents received agent messages as attributed bubbles with the original turn identity", () => { + const call = toolCall("received", "agent_message"); + if (call.payload.source !== "agent") throw new Error("Expected agent tool"); + call.turnId = "turn"; + call.payload.data.agentMessage = { + event: "message", + sender: { id: "sender", title: "Reviewer" }, + text: "Ready", + }; + const result = createStreamPresentation()({ + ...presentationOptions, + transform: undefined, + tail: [call], + head: [], + }); + expect(result.tail[0]).toMatchObject({ + kind: "user_message", + id: call.id, + turnId: "turn", + text: "Ready", + sender: { id: "sender", title: "Reviewer" }, + }); +}); + +it("does not reopen the previous turn while a new run waits for its first row", () => { + const timestamp = new Date(); + const tail: StreamItem[] = [ + { kind: "user_message", id: "prompt", text: "Work", timestamp }, + toolCall("one", "Bash"), + { kind: "assistant_message", id: "reply", text: "Done", timestamp }, + ]; + for (const item of tail) item.turnId = "completed"; + const result = createStreamPresentation()({ + ...presentationOptions, + transform: undefined, + tail, + head: [], + display: "collapseTurns", + isTurnActive: true, + activeTurnId: "new", + }); + expect(result.tail.map((item) => item.id)).toEqual(["prompt", "reply"]); +}); + +it("groups reasoning with tools unless Expand thinking is enabled, including setting changes", () => { + const present = createStreamPresentation(); + const timestamp = new Date(); + const thought: StreamItem = { + kind: "thought", + id: "thought", + text: "Consider this", + status: "ready", + timestamp, + }; + const tail: StreamItem[] = [toolCall("one", "Bash"), thought, toolCall("two", "Bash")]; + for (const item of tail) item.turnId = "run"; + const input = { + ...presentationOptions, + transform: undefined, + tail, + head: [], + display: "collapseToolCalls" as const, + isTurnActive: false, + }; + const grouped = present({ ...input, autoExpandReasoning: false }); + expect(grouped.tail).toHaveLength(1); + expect(grouped.groupsByHostId.get("tool-one")?.run.calls).toEqual(tail); + const separate = present({ ...input, autoExpandReasoning: true }); + expect(separate.tail.map((item) => item.id)).toEqual(["tool-one", "thought", "tool-two"]); + expect(separate.groupsByHostId.has("thought")).toBe(false); + const next = { ...thought, id: "next", turnId: "next-run" }; + const bounded = present({ ...input, tail: [...tail, next], autoExpandReasoning: false }); + expect(bounded.tail.map((item) => item.id)).toEqual(["tool-one", "next"]); +}); + +it.each([false, true])( + "reveals raw reasoning when opening a turn (Expand thinking %s)", + (autoExpandReasoning) => { + const timestamp = new Date(); + const tail: StreamItem[] = [ + { kind: "user_message", id: "prompt", text: "Work", timestamp }, + { kind: "thought", id: "thought", text: "Consider this", status: "ready", timestamp }, + toolCall("one", "Bash"), + { kind: "assistant_message", id: "reply", text: "Done", timestamp }, + ]; + const input = { + ...presentationOptions, + transform: undefined, + tail, + head: [], + display: "collapseTurns" as const, + isTurnActive: false, + autoExpandReasoning, + }; + const present = createStreamPresentation(); + const closed = present(input); + expect(closed.tail.some((item) => item.id === "thought")).toBe(autoExpandReasoning); + const opened = present({ ...input, expandedTurnHostIds: new Set(["prompt"]) }); + expect(opened.tail).toEqual(tail); + expect(opened.turns.nestedItemIds.has("thought")).toBe(true); + expect(opened.groupsByHostId.size).toBe(0); + }, +); diff --git a/packages/app/src/agent-stream/presentation.ts b/packages/app/src/agent-stream/presentation.ts index 9e8e5b430e..ad5d362d38 100644 --- a/packages/app/src/agent-stream/presentation.ts +++ b/packages/app/src/agent-stream/presentation.ts @@ -1,3 +1,4 @@ +import { isTurnBoundary } from "./turn-membership"; import type { ChatDisplay } from "@/hooks/use-settings"; import type { TimelineItemTransform } from "@/plugins/timeline/model"; import { projectPluginTimelineItems } from "@/plugins/timeline/projection"; @@ -16,9 +17,11 @@ interface PresentationInput { head: StreamItem[]; transform: TimelineItemTransform | undefined; display: ChatDisplay; + autoExpandReasoning?: boolean; /** User messages whose collapsed turn the reader opened. */ expandedTurnHostIds: ReadonlySet; isTurnActive: boolean; + activeTurnId?: string | null; } export interface StreamPresentation extends ToolCallDetailProjection { @@ -55,6 +58,7 @@ export function createStreamPresentation() { let historyTransform: TimelineItemTransform | undefined; let historyRows: StreamItem[] = []; let preparedTail: StreamItem[] | undefined; + let preparedAutoExpandReasoning: boolean | undefined; let preparedLevel: ToolCallDetailLevel | undefined; let preparedHistory: PreparedToolCallHistory | null = null; let collapsedSource: StreamItem[] | undefined; @@ -63,6 +67,22 @@ export function createStreamPresentation() { let collapsed: TurnCollapse | undefined; function presentRows(item: StreamItem): StreamItem[] { + if (item.kind === "tool_call" && item.payload.source === "agent") { + const message = item.payload.data.agentMessage; + if (message?.event === "message") { + return [ + { + kind: "user_message", + id: item.id, + turnId: item.turnId, + timelineCursor: item.timelineCursor, + timestamp: item.timestamp, + text: message.text, + sender: message.sender, + }, + ]; + } + } return [item.kind === "user_message" ? presentUserMessage(item) : item]; } @@ -75,7 +95,14 @@ export function createStreamPresentation() { } // Live text updates reach the head only, so the folded history is reused until the // retained rows, the latest turn's liveness, or the reader's expanded turns change. - const isLatestTurnOpen = input.isTurnActive || projection.head.length > 0; + const isLatestTurnOpen = + (input.isTurnActive || projection.head.length > 0) && + !isTurnBoundary(projection.tail.at(-1) ?? null, projection.head[0] ?? null) && + !( + input.activeTurnId && + projection.tail.at(-1)?.turnId && + input.activeTurnId !== projection.tail.at(-1)?.turnId + ); if ( !collapsed || collapsedSource !== projection.tail || @@ -84,6 +111,7 @@ export function createStreamPresentation() { ) { collapsed = collapseTurns({ tail: projection.tail, + autoExpandReasoning: input.autoExpandReasoning, isLatestTurnOpen, expandedHostIds: input.expandedTurnHostIds, getGroupedCalls: (itemId) => projection.groupsByHostId.get(itemId)?.run.calls, @@ -93,7 +121,20 @@ export function createStreamPresentation() { collapsedExpandedHostIds = input.expandedTurnHostIds; } const { tail, ...turns } = collapsed; - return { ...projection, tail, turns }; + if (turns.nestedItemIds.size === 0) return { ...projection, tail, turns }; + // Opening a turn reveals its raw calls; those rows must not become group hosts again. + const withoutExpandedRows = (groups: StreamPresentation["groupsByHostId"]) => ({ + size: groups.size - [...turns.nestedItemIds].filter((id) => groups.has(id)).length, + get: (id: string) => (turns.nestedItemIds.has(id) ? undefined : groups.get(id)), + has: (id: string) => !turns.nestedItemIds.has(id) && groups.has(id), + }); + return { + ...projection, + tail, + turns, + groupsByHostId: withoutExpandedRows(projection.groupsByHostId), + historyGroupUpdatesByHostId: withoutExpandedRows(projection.historyGroupUpdatesByHostId), + }; } return (input: PresentationInput): StreamPresentation => { @@ -111,10 +152,15 @@ export function createStreamPresentation() { const blocks = presentRows(item); head.push(...blocks); } - if (preparedTail !== historyRows || preparedLevel !== level) { - preparedHistory = prepareToolCallHistory(level, historyRows); + if ( + preparedTail !== historyRows || + preparedLevel !== level || + preparedAutoExpandReasoning !== input.autoExpandReasoning + ) { + preparedHistory = prepareToolCallHistory(level, historyRows, input.autoExpandReasoning); preparedTail = historyRows; preparedLevel = level; + preparedAutoExpandReasoning = input.autoExpandReasoning; } return collapse( projectToolCallDetailLevel({ diff --git a/packages/app/src/agent-stream/render-strategy.test.ts b/packages/app/src/agent-stream/render-strategy.test.ts index 22d7c5f2f1..59a2f7aed3 100644 --- a/packages/app/src/agent-stream/render-strategy.test.ts +++ b/packages/app/src/agent-stream/render-strategy.test.ts @@ -214,7 +214,7 @@ describe("neighbor and traversal semantics", () => { ).toBe("assistant-1\n\nassistant-2"); }); - it("collects copy content across adjacent turns without a visible prompt", () => { + it("keeps copied content within the canonical turn without a visible prompt", () => { const chronological: StreamItem[] = [ { ...assistantMessage("a1", "first turn", 1), turnId: "turn-1" }, { ...toolCall("tool", 2), turnId: "turn-2" }, @@ -228,7 +228,7 @@ describe("neighbor and traversal semantics", () => { items: chronological, startIndex: 2, }), - ).toBe("first turn\n\nsecond turn"); + ).toBe("second turn"); }); it("returns undefined neighbor when index would be out of bounds", () => { diff --git a/packages/app/src/agent-stream/stream-tick.bench.ts b/packages/app/src/agent-stream/stream-tick.bench.ts index dc1fecb881..b765c441e8 100644 --- a/packages/app/src/agent-stream/stream-tick.bench.ts +++ b/packages/app/src/agent-stream/stream-tick.bench.ts @@ -110,7 +110,7 @@ function runTicks(input: { tail: StreamItem[]; historyStart: number; heads: Stre isTurnActive: true, history: model.history, liveHead: model.segments.liveHead, - timingByAssistantId: model.turnTiming.byAssistantId, + timingByItemId: model.turnTiming.byItemId, }); } } diff --git a/packages/app/src/agent-stream/turn-collapse/model.test.ts b/packages/app/src/agent-stream/turn-collapse/model.test.ts index 4535b14d9e..6cefaf3651 100644 --- a/packages/app/src/agent-stream/turn-collapse/model.test.ts +++ b/packages/app/src/agent-stream/turn-collapse/model.test.ts @@ -48,6 +48,41 @@ function collapse(tail: StreamItem[], options: Partial = {}) const ids = (items: StreamItem[]) => items.map((item) => item.id); describe("collapseTurns", () => { + it("keeps lifecycle events and compaction recognizable beside a semantic action summary", () => { + const create = shell("create"); + if (create.payload.source !== "agent") throw new Error("Expected agent tool"); + create.payload.data.name = "mcp__paseo__create_agent"; + create.payload.data.detail = { type: "unknown", input: { title: "Side fix" }, output: null }; + const finished = shell("finished"); + if (finished.payload.source !== "agent") throw new Error("Expected agent tool"); + finished.payload.data.name = "agent_notification"; + finished.payload.data.agentMessage = { + event: "finished", + sender: { id: "worker", title: "PR helper" }, + text: "Finished", + }; + const items: StreamItem[] = [ + user("u1"), + create, + finished, + { + kind: "compaction", + id: "compaction", + timestamp: at, + status: "completed", + } satisfies StreamItem, + shell("bash"), + reply("done"), + ].map((item) => Object.assign(item, { turnId: "same-run" })); + const result = collapse(items); + expect(ids(result.tail)).toEqual(["u1", "finished", "compaction", "done"]); + expect(result.turnsByHostId.get("u1")?.summary.tools).toMatchObject({ + commandCount: 1, + otherToolCount: 0, + paseoActions: { "Created agent": 1 }, + }); + }); + it("folds a finished turn's work into its user message and keeps the reply", () => { const result = collapse([ user("u1"), @@ -63,7 +98,6 @@ describe("collapseTurns", () => { hostId: "u1", expanded: false, summary: { - messageCount: 1, tools: expect.objectContaining({ commandCount: 2 }), }, }); @@ -121,6 +155,34 @@ describe("collapseTurns", () => { expect(result.turnsByHostId.size).toBe(0); }); + it("keeps a completed response folded when a promptless canonical turn starts", () => { + const first = [user("u1"), shell("c1"), reply("r1")].map((item) => + Object.assign(item, { turnId: "first" }), + ); + const next = { ...shell("heartbeat"), turnId: "second" }; + const result = collapse([...first, next], { isLatestTurnOpen: true }); + expect(ids(result.tail)).toEqual(["u1", "r1", "heartbeat"]); + expect(result.turnsByHostId.has("u1")).toBe(true); + }); + + it("keeps mid-turn messages visible when work is folded", () => { + const tail = [user("prompt"), shell("work"), user("steer"), shell("more"), reply("done")]; + for (const item of tail) item.turnId = "same-turn"; + const result = collapse(tail); + expect(ids(result.tail)).toEqual(["prompt", "steer", "done"]); + expect(result.hostIdByFoldedMessageId.has("steer")).toBe(false); + }); + + it("reveals every raw call inside an expanded turn", () => { + const calls = [shell("one"), shell("two")]; + const result = collapse([user("prompt"), calls[0]!, reply("done")], { + expandedHostIds: new Set(["prompt"]), + getGroupedCalls: (id) => (id === "one" ? calls : undefined), + }); + expect(ids(result.tail)).toEqual(["prompt", "one", "two", "done"]); + expect([...result.nestedItemIds]).toEqual(["one", "two"]); + }); + it("counts every call a tool-call group row stands for", () => { const group = [shell("c1"), shell("c2"), shell("c3")]; const result = collapse([user("u1"), group[0]!, reply("final")], { diff --git a/packages/app/src/agent-stream/turn-collapse/model.ts b/packages/app/src/agent-stream/turn-collapse/model.ts index d9f532ad73..c8c1617e24 100644 --- a/packages/app/src/agent-stream/turn-collapse/model.ts +++ b/packages/app/src/agent-stream/turn-collapse/model.ts @@ -1,13 +1,18 @@ -import { getStreamItemMessageId, type StreamItem, type ToolCallItem } from "@/types/stream"; +import { isTurnBoundary, isTurnTrigger } from "../turn-membership"; +import { + getStreamItemMessageId, + type StreamItem, + type ThoughtItem, + type ToolCallItem, +} from "@/types/stream"; import { summarizeToolCalls, type OverviewSummary } from "@/tool-calls/detail-level/overview/model"; export interface TurnSummary { - messageCount: number; tools: OverviewSummary; } export interface CollapsedTurn { - /** The user message the turn answers. Its row carries the turn's summary line. */ + /** The input or first loaded row that carries the turn's summary line. */ hostId: string; expanded: boolean; summary: TurnSummary; @@ -24,11 +29,12 @@ export interface TurnCollapse { export interface CollapseTurnsInput { tail: StreamItem[]; + autoExpandReasoning?: boolean; /** The latest turn is still producing output, so it stays unfolded. */ isLatestTurnOpen: boolean; expandedHostIds: ReadonlySet; /** The calls a tool-call group row stands for; undefined for a single call. */ - getGroupedCalls: (itemId: string) => readonly ToolCallItem[] | undefined; + getGroupedCalls: (itemId: string) => readonly (ToolCallItem | ThoughtItem)[] | undefined; } const EMPTY_TURNS: ReadonlyMap = new Map(); @@ -39,17 +45,25 @@ function summarizeTurn( items: readonly StreamItem[], getGroupedCalls: CollapseTurnsInput["getGroupedCalls"], ): TurnSummary { - const calls: ToolCallItem[] = []; - let messageCount = 0; + const calls: (ToolCallItem | ThoughtItem)[] = []; for (const item of items) { - if (item.kind === "assistant_message") messageCount += 1; - else if (item.kind === "tool_call") calls.push(...(getGroupedCalls(item.id) ?? [item])); + if ((item.kind === "tool_call" || item.kind === "thought") && !isTurnTrigger(item)) + calls.push(...(getGroupedCalls(item.id) ?? [item])); } - return { messageCount, tools: summarizeToolCalls(calls) }; + return { tools: summarizeToolCalls(calls) }; } function hasWork(summary: TurnSummary): boolean { - return summary.messageCount > 0 || Object.values(summary.tools).some((count) => count > 0); + const { paseoActions, thoughtCount: _thoughtCount, ...counts } = summary.tools; + return Object.keys(paseoActions).length > 0 || Object.values(counts).some((count) => count > 0); +} + +function staysVisibleWhenCollapsed(item: StreamItem, autoExpandReasoning = false): boolean { + return ( + isTurnTrigger(item) || + item.kind === "compaction" || + (autoExpandReasoning && item.kind === "thought") + ); } function findLastAssistantIndex(tail: StreamItem[], start: number, end: number): number { @@ -63,7 +77,7 @@ function findLastAssistantIndex(tail: StreamItem[], start: number, end: number): * Folds each answered turn into its user message: everything the agent did before its last * message collapses into one summary line, and that message stays in the chat. A turn folds * only once it is complete, its user message is loaded, and it sent messages or called tools - * before its reply. Thoughts fold with the turn but are not counted. + * before its reply. Reasoning stays visible when Expand thinking is enabled. */ export function collapseTurns(input: CollapseTurnsInput): TurnCollapse { const { tail } = input; @@ -77,28 +91,49 @@ export function collapseTurns(input: CollapseTurnsInput): TurnCollapse { const host = tail[runStart - 1]; const isClosed = runEnd < tail.length || !input.isLatestTurnOpen; const replyIndex = findLastAssistantIndex(tail, runStart, runEnd); - if (host?.kind !== "user_message" || !isClosed || replyIndex <= runStart) { + if ( + !host || + (host.kind !== "user_message" && host.kind !== "tool_call") || + !isClosed || + replyIndex <= runStart + ) { output.push(...tail.slice(runStart, runEnd)); return; } const folded = tail.slice(runStart, replyIndex); const summary = summarizeTurn(folded, input.getGroupedCalls); - if (!hasWork(summary)) { + if (!hasWork(summary) && !folded.some((item) => item.kind === "assistant_message")) { output.push(...tail.slice(runStart, runEnd)); return; } const expanded = input.expandedHostIds.has(host.id); turnsByHostId.set(host.id, { hostId: host.id, expanded, summary }); - for (const item of folded) { + const revealed = expanded + ? folded.flatMap((item) => + item.kind === "tool_call" || item.kind === "thought" + ? [...(input.getGroupedCalls(item.id) ?? [item])] + : [item], + ) + : folded; + for (const item of revealed) { + if (staysVisibleWhenCollapsed(item)) continue; hostIdByFoldedMessageId.set(getStreamItemMessageId(item), host.id); if (expanded) nestedItemIds.add(item.id); } - if (expanded) output.push(...folded); + output.push( + ...(expanded + ? revealed + : folded.filter((item) => staysVisibleWhenCollapsed(item, input.autoExpandReasoning))), + ); output.push(...tail.slice(replyIndex, runEnd)); }; for (let index = 0; index < tail.length; index += 1) { - if (tail[index]?.kind !== "user_message") continue; + if ( + !(index === 0 && isTurnTrigger(tail[index]!)) && + !isTurnBoundary(tail[index - 1] ?? null, tail[index] ?? null) + ) + continue; flushRun(index); output.push(tail[index]!); runStart = index + 1; @@ -114,7 +149,10 @@ export function collapseTurns(input: CollapseTurnsInput): TurnCollapse { }; } return { - tail: output.length === tail.length ? tail : output, + tail: + output.length === tail.length && output.every((item, index) => item === tail[index]) + ? tail + : output, turnsByHostId, nestedItemIds, hostIdByFoldedMessageId, diff --git a/packages/app/src/agent-stream/turn-collapse/summary-line.tsx b/packages/app/src/agent-stream/turn-collapse/summary-line.tsx index 9f73f1ac22..191ac706d5 100644 --- a/packages/app/src/agent-stream/turn-collapse/summary-line.tsx +++ b/packages/app/src/agent-stream/turn-collapse/summary-line.tsx @@ -1,4 +1,4 @@ -import { memo, useCallback, useMemo } from "react"; +import { memo, useCallback } from "react"; import { useTranslation } from "react-i18next"; import { Summary } from "lucide-react-native"; import { ExpandableBadge } from "@/components/message"; @@ -17,19 +17,7 @@ export const TurnSummaryLine = memo(function TurnSummaryLine({ onExpandedChange: (hostId: string, expanded: boolean) => void; }) { const { t } = useTranslation(); - const { messageCount, tools } = turn.summary; - const messageParts = useMemo( - () => - messageCount > 0 - ? [ - t(`turnSummary.messages.${messageCount === 1 ? "one" : "other"}`, { - count: messageCount, - }), - ] - : [], - [messageCount, t], - ); - const label = useOverviewSummaryLabel(tools, messageParts); + const label = useOverviewSummaryLabel(turn.summary.tools) || t("turnSummary.details"); const toggle = useCallback( () => onExpandedChange(turn.hostId, !turn.expanded), [onExpandedChange, turn.expanded, turn.hostId], diff --git a/packages/app/src/agent-stream/turn-footer.tsx b/packages/app/src/agent-stream/turn-footer.tsx index acbd920b81..5d04f9eca9 100644 --- a/packages/app/src/agent-stream/turn-footer.tsx +++ b/packages/app/src/agent-stream/turn-footer.tsx @@ -197,7 +197,7 @@ function CompletedTurnFooter({ return ( ["layout"]): str } describe("canonical turn membership", () => { + it("uses trigger fallback for missing IDs without pretending to recover batching", () => { + const previous = assistant("reply", 1, "first"); + const trigger = runningTool("heartbeat", 2, "first"); + if (trigger.kind !== "tool_call" || trigger.payload.source !== "agent") + throw new Error("Expected agent tool"); + trigger.payload.data.name = "heartbeat"; + expect(continuesTurn(previous, trigger)).toBe(true); + delete trigger.turnId; + expect(continuesTurn(previous, trigger)).toBe(false); + trigger.payload.data.name = "agent_message"; + trigger.payload.data.agentMessage = { + event: "finished", + sender: { id: "worker" }, + text: "Done", + }; + expect(continuesTurn(previous, trigger)).toBe(false); + }); + it("stops tagged traversal at every mismatching turn ID", () => { expect(continuesTurn(assistant("first", 1, "turn-1"), runningTool("next", 2, "turn-2"))).toBe( false, @@ -76,7 +94,7 @@ describe("canonical turn membership", () => { ); }); - it("renders adjacent turns without visible prompts as one response", () => { + it("renders a separate footer for each canonical turn without visible prompts", () => { const items = [ user("prompt", 1, "turn-1"), assistant("first reply", 2, "turn-1"), @@ -88,7 +106,11 @@ describe("canonical turn membership", () => { const completed = layoutFor(items, false); - expect(completedFooterIds(completed.layout)).toEqual(["heartbeat-2-reply"]); + expect(completedFooterIds(completed.layout)).toEqual([ + "first reply", + "heartbeat-1-reply", + "heartbeat-2-reply", + ]); expect(completed.layout.auxiliaryTurnFooter?.timing).toEqual({ completedAt: at(6), durationMs: null, @@ -123,7 +145,7 @@ describe("canonical turn membership", () => { const completedItems = [...build(turnId), assistant("done", 9, turnId)]; const completed = layoutFor(completedItems, false); expect(completedFooterIds(completed.layout)).toEqual(["done"]); - expect(completed.model.turnTiming.byAssistantId.get("done")).toMatchObject({ + expect(completed.model.turnTiming.byItemId.get("done")).toMatchObject({ completedAt: at(9), durationMs: 8000, }); diff --git a/packages/app/src/agent-stream/turn-membership.ts b/packages/app/src/agent-stream/turn-membership.ts index 414d583305..9650c12ff1 100644 --- a/packages/app/src/agent-stream/turn-membership.ts +++ b/packages/app/src/agent-stream/turn-membership.ts @@ -1,24 +1,21 @@ +import { continuesTimelineTurn, isTimelineTurnTrigger } from "@getpaseo/protocol/timeline-turn"; import type { StreamItem } from "@/types/stream"; /** * Canonical turn IDs take precedence. Timelines without them retain the legacy - * user-message boundary rule so old daemons and persisted rows need no rewrite. + * trigger boundary rule; missing IDs cannot reconstruct historical batching. */ export function continuesTurn(previous: StreamItem | null, next: StreamItem | null): boolean { if (!previous || !next) return false; - if (previous.turnId !== undefined && next.turnId !== undefined) { - return previous.turnId === next.turnId; - } - return next.kind !== "user_message"; + return continuesTimelineTurn(previous.turnId, next.turnId, isTurnTrigger(next)); } /** - * A visible response can span multiple canonical turns when their prompts are - * system-injected and therefore absent from the Paseo timeline. + * Every canonical turn owns its response, including system-triggered runs. */ export function continuesResponse(previous: StreamItem | null, next: StreamItem | null): boolean { if (!previous || !next) return false; - return continuesTurn(previous, next) || next.kind !== "user_message"; + return continuesTurn(previous, next); } export function isTurnBoundary(previous: StreamItem | null, next: StreamItem | null): boolean { @@ -37,3 +34,12 @@ export function startsNewTurn(item: StreamItem, previous: StreamItem | null): bo export function belongsToTurn(item: StreamItem, turnId: string | null): boolean { return turnId !== null && item.turnId === turnId; } + +/** Inputs that start a turn when older history has no canonical turn IDs. */ +export function isTurnTrigger(item: StreamItem): boolean { + return isTimelineTurnTrigger( + item.kind === "tool_call" && item.payload.source === "agent" + ? { type: item.kind, ...item.payload.data } + : { type: item.kind }, + ); +} diff --git a/packages/app/src/agent-stream/view.tsx b/packages/app/src/agent-stream/view.tsx index 67e08a6f82..1cfddc8ecc 100644 --- a/packages/app/src/agent-stream/view.tsx +++ b/packages/app/src/agent-stream/view.tsx @@ -524,8 +524,10 @@ const AgentStreamViewComponent = forwardRef + presentation.turns.nestedItemIds.has(id), + ); const renderThoughtItem = useCallback( (layoutItem: StreamLayoutItem, item: Extract) => { return ( @@ -796,11 +804,11 @@ const AgentStreamViewComponent = forwardRef ); }, - [autoExpandReasoning, setInlineDetailsExpanded], + [autoExpandReasoning, setInlineDetailsExpanded, isExpandedTurnItem], ); const renderSingleToolCallItem = useCallback( @@ -830,6 +838,8 @@ const AgentStreamViewComponent = forwardRef ); }, - [context.cwd, resolvedServerId, setInlineDetailsExpanded, handleToolCallOpenFile], + [ + context.cwd, + resolvedServerId, + setInlineDetailsExpanded, + handleToolCallOpenFile, + isExpandedTurnItem, + ], ); // Read through a stable event so live group updates do not change the renderer identity @@ -868,10 +884,15 @@ const AgentStreamViewComponent = forwardRef) => { + ( + layoutItem: StreamLayoutItem, + item: Extract, + ) => { const group = getToolCallGroup(item.id); if (!group) { - return renderSingleToolCallItem(item, layoutItem.isLastInToolSequence); + return item.kind === "thought" + ? renderThoughtItem(layoutItem, item) + : renderSingleToolCallItem(item, layoutItem.isLastInToolSequence); } const expanded = expandedToolCallGroupIds.has(group.run.id); return ( @@ -884,10 +905,21 @@ const AgentStreamViewComponent = forwardRef ( - {renderSingleToolCallItem( - call, - index === group.run.calls.length - 1, - GROUPED_TOOL_CALL_DETAIL_MAX_HEIGHT, + {call.kind === "thought" ? ( + + ) : ( + renderSingleToolCallItem( + call, + index === group.run.calls.length - 1, + GROUPED_TOOL_CALL_DETAIL_MAX_HEIGHT, + ) )} )) @@ -897,6 +929,8 @@ const AgentStreamViewComponent = forwardRef + {renderToolCallItem(layoutItem, item)} + {getCollapsedTurn(item.id) ? ( + + ) : null} + + ); case "notification": return ; @@ -947,8 +991,9 @@ const AgentStreamViewComponent = forwardRef { + it("mounts complete autonomous runs and keeps same-run steers together", () => { + const items = [ + { ...userMessage("human", 1), turnId: "first" }, + { ...assistantMessage("reply", 2), turnId: "first" }, + { ...toolCall("wake", 3), turnId: "autonomous" }, + { ...userMessage("steer", 4), turnId: "autonomous" }, + { ...assistantMessage("done", 5), turnId: "autonomous" }, + ]; + expect(findMountedWindowStart({ items, minMountedCount: 1 })).toBe(2); + }); + it("keeps all items mounted when the chat is below the threshold", () => { const items = [userMessage("u1", 1), assistantMessage("a1", 2)]; diff --git a/packages/app/src/components/indent-rail.tsx b/packages/app/src/components/indent-rail.tsx index b54ac1ca9b..36fd84a0a9 100644 --- a/packages/app/src/components/indent-rail.tsx +++ b/packages/app/src/components/indent-rail.tsx @@ -3,11 +3,10 @@ import { View, type StyleProp, type ViewStyle } from "react-native"; import { StyleSheet } from "react-native-unistyles"; /** - * Collapsed chat rows badge their summary with an icon whose center sits 7px into the content - * column (`ExpandableBadge` bleeds 13px left, then 1px border, 8px padding, 22px icon). The rail - * hangs from that center so opened rows read as children of the line that opened them. + * Align the rail with the expanded caret's left edge. Keep the content offset fixed so + * expanded tool cards stay in place, with a gap between their border and the rail. */ -const RAIL_LEFT = 7; +const RAIL_LEFT = 1; const RAIL_WIDTH = 1; export const INDENT_RAIL_CONTENT_OFFSET = 21; diff --git a/packages/app/src/components/message.tsx b/packages/app/src/components/message.tsx index 9430aa3a12..a075b97c92 100644 --- a/packages/app/src/components/message.tsx +++ b/packages/app/src/components/message.tsx @@ -1,3 +1,4 @@ +import { MessagePreview, MessageSender } from "@/components/user-message"; import { useStableEvent } from "@/hooks/use-stable-event"; import { getAgentAttachmentPillContent } from "@/attachments/attachment-pill-content"; import { AssistantForkMenu, type AssistantForkTarget } from "@/components/assistant-fork-menu"; @@ -89,6 +90,7 @@ export type { InlinePathTarget } from "@/assistant-file-links"; export type { AssistantForkTarget }; interface UserMessageProps { + sender?: AgentMessage["sender"]; serverId?: string; agentId?: string; messageId?: string; @@ -387,6 +389,7 @@ function UserMessageImagePill({ image, onOpen, accessibilityLabel }: UserMessage const MESSAGE_TEXT_DATASET = { messageText: "true" }; export const UserMessage = memo(function UserMessage({ + sender, serverId, agentId, messageId, @@ -473,42 +476,45 @@ export const UserMessage = memo(function UserMessage({ onPointerEnter={handlePointerEnter} onPointerLeave={handlePointerLeave} > + {sender ? : null} - {hasImages ? ( - - {images.map((image) => ( - - ))} - - ) : null} - {hasAttachments ? ( - - {attachments.map((attachment, index) => { - const content = getAgentAttachmentPillContent(attachment, t); - return ( - - - - ); - })} - - ) : null} - {hasText ? ( - - {message} - - ) : null} + + {hasImages ? ( + + {images.map((image) => ( + + ))} + + ) : null} + {hasAttachments ? ( + + {attachments.map((attachment, index) => { + const content = getAgentAttachmentPillContent(attachment, t); + return ( + + + + ); + })} + + ) : null} + {hasText ? ( + + {message} + + ) : null} + {hasText ? ( string; + getContent?: () => string; completedAt?: Date; durationMs?: number | null; onFork?: (target: AssistantForkTarget) => Promise | void; @@ -641,10 +647,12 @@ export const AssistantTurnFooter = memo(function AssistantTurnFooter({ return ( - + {getContent ? ( + + ) : null} {canFork ? : null} {primaryLabel ? ( { color: string }> = { + surface3: (theme) => ({ color: theme.colors.surface3 }), surface0: (theme) => ({ color: theme.colors.surface0 }), surfaceWorkspace: (theme) => ({ color: theme.colors.surfaceWorkspace }), }; diff --git a/packages/app/src/components/user-message/index.tsx b/packages/app/src/components/user-message/index.tsx new file mode 100644 index 0000000000..18a48798fb --- /dev/null +++ b/packages/app/src/components/user-message/index.tsx @@ -0,0 +1,79 @@ +import { useState, useCallback, useMemo, type ReactNode } from "react"; +import { View, type LayoutChangeEvent } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import { useTranslation } from "react-i18next"; +import type { AgentMessage } from "@getpaseo/protocol/agent-message"; +import { Button } from "@/components/ui/button"; +import { EdgeFade } from "@/components/ui/edge-fade"; +import { useProviderIcon } from "@/components/provider-icons"; +import { useSessionStore } from "@/stores/session-store"; +import { navigateToAgent } from "@/utils/navigate-to-agent"; + +const PREVIEW_HEIGHT = 240; + +export function MessagePreview({ children }: { children: ReactNode }) { + const { t } = useTranslation(); + const [expanded, setExpanded] = useState(false); + const [height, setHeight] = useState(0); + const overflowing = height > PREVIEW_HEIGHT; + const measure = useCallback( + (event: LayoutChangeEvent) => setHeight(event.nativeEvent.layout.height), + [], + ); + const toggle = useCallback(() => setExpanded((value) => !value), []); + const accessibilityState = useMemo(() => ({ expanded }), [expanded]); + return ( + <> + + + {children} + + {overflowing && !expanded ? ( + + ) : null} + + {overflowing ? ( + + ) : null} + + ); +} + +export function MessageSender({ + sender, + serverId, +}: { + sender: AgentMessage["sender"]; + serverId?: string; +}) { + const { t } = useTranslation(); + const host = sender.serverId ?? serverId; + const agent = useSessionStore((state) => { + const session = host ? state.sessions[host] : undefined; + return session?.agents.get(sender.id) ?? session?.agentDetails.get(sender.id); + }); + const ProviderIcon = useProviderIcon(agent?.provider ?? "", host); + const openSender = useCallback(() => { + if (host) navigateToAgent({ serverId: host, agentId: sender.id }); + }, [host, sender.id]); + return ( + + ); +} + +const styles = StyleSheet.create((theme) => ({ + preview: { maxHeight: PREVIEW_HEIGHT, overflow: "hidden" }, + body: { flexShrink: 0 }, + toggle: { alignSelf: "flex-start", paddingHorizontal: 0, borderWidth: 0 }, + fade: { position: "absolute", bottom: 0, left: 0, right: 0, height: theme.spacing[12] }, +})); diff --git a/packages/app/src/hooks/use-agent-initialization.test.ts b/packages/app/src/hooks/use-agent-initialization.test.ts index f2726fba02..e517021b6b 100644 --- a/packages/app/src/hooks/use-agent-initialization.test.ts +++ b/packages/app/src/hooks/use-agent-initialization.test.ts @@ -78,6 +78,7 @@ describe("ensureAgentIsInitialized", () => { cursor: { epoch: "epoch-1", seq: 42 }, limit: TIMELINE_FETCH_PAGE_SIZE, projection: "projected", + wholeTurns: true, }, }, ]); @@ -105,6 +106,7 @@ describe("ensureAgentIsInitialized", () => { direction: "tail", limit: TIMELINE_FETCH_PAGE_SIZE, projection: "projected", + wholeTurns: true, }, }, ]); @@ -148,6 +150,7 @@ describe("ensureAgentIsInitialized", () => { direction: "tail", limit: TIMELINE_FETCH_PAGE_SIZE, projection: "projected", + wholeTurns: true, }, }, ]); @@ -192,6 +195,7 @@ describe("ensureAgentIsInitialized", () => { cursor: { epoch: "epoch-1", seq: 12 }, limit: TIMELINE_FETCH_PAGE_SIZE, projection: "projected", + wholeTurns: true, }, }, ]); @@ -283,6 +287,7 @@ describe("refreshAgent", () => { direction: "tail", limit: TIMELINE_FETCH_PAGE_SIZE, projection: "projected", + wholeTurns: true, }, }, ]); diff --git a/packages/app/src/hooks/use-load-older-agent-history.test.ts b/packages/app/src/hooks/use-load-older-agent-history.test.ts index 1da68b4edf..3259631992 100644 --- a/packages/app/src/hooks/use-load-older-agent-history.test.ts +++ b/packages/app/src/hooks/use-load-older-agent-history.test.ts @@ -152,6 +152,7 @@ describe("loadOlderAgentHistory", () => { cursor: { epoch: "epoch-1", seq: 10 }, limit: TIMELINE_FETCH_PAGE_SIZE, projection: "projected", + wholeTurns: true, }, }, ]); diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index 6bfc30095c..49e8a1669a 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -2018,12 +2018,13 @@ export const ar: TranslationResources = { output: "الإخراج", }, turnSummary: { - messages: { - one: "كتب {{count}} رسالة", - other: "كتب {{count}} رسائل", - }, + details: "عرض تفاصيل الجولة", + sentBy: "أرسلها {{name}}", + showMore: "عرض المزيد", + showLess: "عرض أقل", }, toolCallGroup: { + thought: "فكّر", editedFiles: { one: "حرّر {{count}} ملفًا", other: "حرّر {{count}} ملفات", diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index ff1e80d88b..1ae0e3a363 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -2043,12 +2043,13 @@ export const en = { output: "Output", }, turnSummary: { - messages: { - one: "wrote {{count}} message", - other: "wrote {{count}} messages", - }, + details: "View turn details", + sentBy: "Sent by {{name}}", + showMore: "Show more", + showLess: "Show less", }, toolCallGroup: { + thought: "Thought", editedFiles: { one: "edited {{count}} file", other: "edited {{count}} files", diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index 8784adefb5..6b99c229fe 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -2066,12 +2066,13 @@ export const es: TranslationResources = { output: "Producción", }, turnSummary: { - messages: { - one: "escribió {{count}} mensaje", - other: "escribió {{count}} mensajes", - }, + details: "Ver detalles del turno", + sentBy: "Enviado por {{name}}", + showMore: "Mostrar más", + showLess: "Mostrar menos", }, toolCallGroup: { + thought: "Razonó", editedFiles: { one: "editó {{count}} archivo", other: "editó {{count}} archivos", diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index bbafc03dda..927237900c 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -2065,12 +2065,13 @@ export const fr: TranslationResources = { output: "Sortie", }, turnSummary: { - messages: { - one: "{{count}} message écrit", - other: "{{count}} messages écrits", - }, + details: "Voir les détails du tour", + sentBy: "Envoyé par {{name}}", + showMore: "Afficher plus", + showLess: "Afficher moins", }, toolCallGroup: { + thought: "Réfléchi", editedFiles: { one: "{{count}} fichier modifié", other: "{{count}} fichiers modifiés", diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index e7dcc5b5e7..494714ebca 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -2038,12 +2038,13 @@ export const ja: TranslationResources = { output: "出力", }, turnSummary: { - messages: { - one: "{{count}}件のメッセージを送信", - other: "{{count}}件のメッセージを送信", - }, + details: "ターンの詳細を表示", + sentBy: "{{name}} から送信", + showMore: "もっと見る", + showLess: "折りたたむ", }, toolCallGroup: { + thought: "思考", editedFiles: { one: "{{count}}個のファイルを編集", other: "{{count}}個のファイルを編集", diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index d8d1fbc787..d6777add4a 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -2028,12 +2028,13 @@ export const ko: TranslationResources = { output: "출력", }, turnSummary: { - messages: { - one: "{{count}} 메시지를 작성했습니다.", - other: "{{count}} 메시지를 작성했습니다.", - }, + details: "턴 세부 정보 보기", + sentBy: "{{name}}이(가) 보냄", + showMore: "더 보기", + showLess: "접기", }, toolCallGroup: { + thought: "생각함", editedFiles: { one: "{{count}} 파일을 편집했습니다.", other: "{{count}} 파일을 편집했습니다.", diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index 1c024dc64a..ce1a3b01c8 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -2051,12 +2051,13 @@ export const ptBR: TranslationResources = { output: "Saída", }, turnSummary: { - messages: { - one: "escreveu {{count}} mensagem", - other: "escreveu {{count}} mensagens", - }, + details: "Ver detalhes do turno", + sentBy: "Enviado por {{name}}", + showMore: "Mostrar mais", + showLess: "Mostrar menos", }, toolCallGroup: { + thought: "Pensou", editedFiles: { one: "editou {{count}} arquivo", other: "editou {{count}} arquivos", diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index 093ac68c36..cfc7954abf 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -2051,12 +2051,13 @@ export const ru: TranslationResources = { output: "Выходные данные", }, turnSummary: { - messages: { - one: "написано {{count}} сообщение", - other: "написаны сообщения ({{count}})", - }, + details: "Показать подробности хода", + sentBy: "Отправлено агентом {{name}}", + showMore: "Показать больше", + showLess: "Свернуть", }, toolCallGroup: { + thought: "Обдумал", editedFiles: { one: "изменён {{count}} файл", other: "изменены файлы ({{count}})", diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index 8ca178f206..5a08f1ea40 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -1996,12 +1996,13 @@ export const zhCN: TranslationResources = { output: "输出", }, turnSummary: { - messages: { - one: "写了 {{count}} 条消息", - other: "写了 {{count}} 条消息", - }, + details: "查看轮次详情", + sentBy: "由 {{name}} 发送", + showMore: "展开", + showLess: "收起", }, toolCallGroup: { + thought: "已思考", editedFiles: { one: "编辑了 {{count}} 个文件", other: "编辑了 {{count}} 个文件", diff --git a/packages/app/src/runtime/replica-cache/index.test.ts b/packages/app/src/runtime/replica-cache/index.test.ts index eaad715a52..d91d8e7ba4 100644 --- a/packages/app/src/runtime/replica-cache/index.test.ts +++ b/packages/app/src/runtime/replica-cache/index.test.ts @@ -306,6 +306,21 @@ async function expectLegacyWorkspaceRefresh({ } describe("ReplicaCache", () => { + it("persists the complete newest turn beyond the cache item target", async () => { + const storage = new MemoryStorage(); + const writer = createCache(storage); + const items = Array.from({ length: 60 }, (_, index) => ({ + ...timelineItem(`item-${index}`), + id: `item-${index}`, + turnId: "long-run", + })); + writer.commitTimeline(SERVER_ID, "agent-1", { ...timeline(), items }); + await writer.flush(); + const restored = await createCache(storage).readTimeline(SERVER_ID, "agent-1"); + expect(restored?.items.map((item) => item.id)).toEqual(items.map((item) => item.id)); + expect(restored?.range).toBeNull(); + }); + it("preserves workspace sorting timestamps across cache reopen", async () => { const storage = new MemoryStorage(); const writer = createCache(storage); diff --git a/packages/app/src/runtime/replica-cache/index.ts b/packages/app/src/runtime/replica-cache/index.ts index 59578e65d7..9ad604c8eb 100644 --- a/packages/app/src/runtime/replica-cache/index.ts +++ b/packages/app/src/runtime/replica-cache/index.ts @@ -1,3 +1,4 @@ +import { findMountedWindowStart } from "@/agent-stream/history-window"; import { z } from "zod"; import { AgentStatusSchema, @@ -766,7 +767,14 @@ function serializeTimeline(timeline: CachedTimeline): StoredTimeline | null { const canonicalItems = timeline.items.filter( (item) => item.kind !== "user_message" || !isUnreconciledLocalUserMessage(item), ); - const items = canonicalItems.map(serializeTimelineItem).filter((item) => item !== null); + const start = findMountedWindowStart({ + items: canonicalItems, + minMountedCount: MAX_TIMELINE_ITEMS, + }); + const items = canonicalItems + .slice(start) + .map(serializeTimelineItem) + .filter((item) => item !== null); const range = timeline.range; const canPersistCoverage = range !== null && @@ -783,7 +791,7 @@ function serializeTimeline(timeline: CachedTimeline): StoredTimeline | null { canonicalItems.some((item) => item.timelineCursor?.seq === range.endSeq); return { agentId: timeline.agentId, - items: items.slice(-MAX_TIMELINE_ITEMS), + items, range: canPersistCoverage ? { epoch: range.epoch, startSeq: range.startSeq, endSeq: range.endSeq } : null, diff --git a/packages/app/src/screens/workspace/workspace-screen.tsx b/packages/app/src/screens/workspace/workspace-screen.tsx index 3617c074e2..1746c50653 100644 --- a/packages/app/src/screens/workspace/workspace-screen.tsx +++ b/packages/app/src/screens/workspace/workspace-screen.tsx @@ -1,3 +1,4 @@ +import { planTimelineTailFetch } from "@/timeline/timeline-sync-plan"; import { useHostFeature } from "@/runtime/host-features"; import { AssistantFileLinkResolverProvider, @@ -2179,8 +2180,7 @@ function WorkspaceScreenContent({ const sessionState = useSessionStore.getState().sessions[normalizedServerId]; const currentCursor = sessionState?.agentTimelineCursor.get(agentId); await getHostRuntimeStore().fetchAgentTimeline(normalizedServerId, agentId, { - direction: "tail", - projection: "projected", + ...planTimelineTailFetch(), ...(currentCursor ? { cursor: { epoch: currentCursor.epoch, seq: currentCursor.endSeq } } : {}), diff --git a/packages/app/src/timeline/timeline-replacement.test.ts b/packages/app/src/timeline/timeline-replacement.test.ts index f457ea7daa..cea2dc909d 100644 --- a/packages/app/src/timeline/timeline-replacement.test.ts +++ b/packages/app/src/timeline/timeline-replacement.test.ts @@ -15,7 +15,7 @@ describe("requestTimelineReplacement", () => { await expect(requestTimelineReplacement(client, "agent-1")).rejects.toThrow("fetch complete"); expect(requests).toEqual([ - ["agent-1", { direction: "tail", projection: "projected", limit: 40 }], + ["agent-1", { direction: "tail", projection: "projected", wholeTurns: true, limit: 40 }], ]); }); }); diff --git a/packages/app/src/timeline/timeline-sync-plan.test.ts b/packages/app/src/timeline/timeline-sync-plan.test.ts index 9135b5fb85..093941fb77 100644 --- a/packages/app/src/timeline/timeline-sync-plan.test.ts +++ b/packages/app/src/timeline/timeline-sync-plan.test.ts @@ -17,6 +17,7 @@ describe("timeline sync planning", () => { direction: "tail", limit: TIMELINE_FETCH_PAGE_SIZE, projection: "projected", + wholeTurns: true, }); }); @@ -26,6 +27,7 @@ describe("timeline sync planning", () => { cursor: { epoch: "epoch-1", seq: 49 }, limit: TIMELINE_FETCH_PAGE_SIZE, projection: "projected", + wholeTurns: true, }); }); @@ -37,6 +39,7 @@ describe("timeline sync planning", () => { cursor: { epoch: "epoch-1", seq: 25 }, limit: TIMELINE_FETCH_PAGE_SIZE, projection: "projected", + wholeTurns: true, }); }); @@ -49,6 +52,7 @@ describe("timeline sync planning", () => { }, limit: TIMELINE_FETCH_PAGE_SIZE, projection: "projected", + wholeTurns: true, mergeWindow: true, }); }); diff --git a/packages/app/src/timeline/timeline-sync-plan.ts b/packages/app/src/timeline/timeline-sync-plan.ts index e5e8b2fb95..b66de16941 100644 --- a/packages/app/src/timeline/timeline-sync-plan.ts +++ b/packages/app/src/timeline/timeline-sync-plan.ts @@ -9,6 +9,7 @@ export interface ProjectedTimelineTailFetchPlan { direction: "tail"; limit: number; projection: "projected"; + wholeTurns: true; } export interface ProjectedTimelineAfterFetchPlan { @@ -16,6 +17,7 @@ export interface ProjectedTimelineAfterFetchPlan { cursor: TimelineSyncCursor; limit: number; projection: "projected"; + wholeTurns: true; } export interface ProjectedTimelineBeforeFetchPlan { @@ -23,6 +25,7 @@ export interface ProjectedTimelineBeforeFetchPlan { cursor: TimelineSyncCursor; limit: number; projection: "projected"; + wholeTurns: true; } export type ProjectedTimelineFetchPlan = @@ -40,6 +43,7 @@ export function planTimelineCatchUpAfter(cursor: TimelineSyncCursor) { cursor, limit: TIMELINE_FETCH_PAGE_SIZE, projection: "projected", + wholeTurns: true, } as const; } @@ -48,6 +52,7 @@ export function planTimelineTailFetch() { direction: "tail", limit: TIMELINE_FETCH_PAGE_SIZE, projection: "projected", + wholeTurns: true, } as const; } @@ -65,6 +70,7 @@ export function planTimelineOlderFetch(cursor: TimelineSyncCursor) { cursor, limit: TIMELINE_FETCH_PAGE_SIZE, projection: "projected", + wholeTurns: true, } as const; } @@ -75,6 +81,7 @@ export function planTimelinePromptJump(target: TimelineSyncCursor) { cursor: { epoch: target.epoch, seq: target.seq + newerRows + 1 }, limit: TIMELINE_FETCH_PAGE_SIZE, projection: "projected", + wholeTurns: true, mergeWindow: true, } as const; } diff --git a/packages/app/src/timeline/turn-time.test.ts b/packages/app/src/timeline/turn-time.test.ts index 3ce6942301..f3e97b2e49 100644 --- a/packages/app/src/timeline/turn-time.test.ts +++ b/packages/app/src/timeline/turn-time.test.ts @@ -51,7 +51,7 @@ describe("deriveStreamTurnTiming", () => { }); assert.equal(timing.runningStartedAt, secondUserAt); - assert.equal(timing.byAssistantId.has("a2"), false); + assert.equal(timing.byItemId.has("a2"), false); }); it("derives completed turn timing from user and assistant item timestamps", () => { @@ -69,7 +69,7 @@ describe("deriveStreamTurnTiming", () => { head: [], }); - assert.deepEqual(timing.byAssistantId.get("a1"), { + assert.deepEqual(timing.byItemId.get("a1"), { completedAt: assistantAt, durationMs: 7000, }); @@ -95,8 +95,8 @@ describe("deriveStreamTurnTiming", () => { completedAt: lastAssistantAt, durationMs: 7000, }; - assert.deepEqual(timing.byAssistantId.get("a1"), expected); - assert.deepEqual(timing.byAssistantId.get("a2"), expected); + assert.deepEqual(timing.byItemId.get("a1"), expected); + assert.deepEqual(timing.byItemId.get("a2"), expected); }); it("preserves the completion timestamp when a canonical turn has no visible prompt", () => { @@ -120,7 +120,7 @@ describe("deriveStreamTurnTiming", () => { head: [], }); - assert.deepEqual(timing.byAssistantId.get("hidden-prompt-a2"), { + assert.deepEqual(timing.byItemId.get("hidden-prompt-a2"), { completedAt: hiddenPromptTurnAt, durationMs: null, }); @@ -143,12 +143,12 @@ describe("deriveStreamTurnTiming", () => { const first = derive("one", "2026-05-15T00:01:04.000Z"); const second = derive("one two", "2026-05-15T00:01:05.000Z"); - assert.equal(second.byAssistantId, first.byAssistantId); - assert.deepEqual(first.byAssistantId.get("a1"), { + assert.equal(second.byItemId, first.byItemId); + assert.deepEqual(first.byItemId.get("a1"), { completedAt: tail[1]?.timestamp, durationMs: 7000, }); - assert.equal(first.byAssistantId.has("a2"), false); + assert.equal(first.byItemId.has("a2"), false); }); it("keeps the timing map identity when the head closed the tail's open turn", () => { @@ -168,8 +168,8 @@ describe("deriveStreamTurnTiming", () => { const first = derive("one", "2026-05-15T00:01:04.000Z"); const second = derive("one two", "2026-05-15T00:01:05.000Z"); - assert.equal(second.byAssistantId, first.byAssistantId); - assert.deepEqual(first.byAssistantId.get("a1"), { + assert.equal(second.byItemId, first.byItemId); + assert.deepEqual(first.byItemId.get("a1"), { completedAt: lastTailAt, durationMs: 7000, }); @@ -193,9 +193,9 @@ describe("deriveStreamTurnTiming", () => { head, }); - assert.notEqual(completed.byAssistantId, active.byAssistantId); - assert.equal(active.byAssistantId.has("a1"), false); - assert.deepEqual(completed.byAssistantId.get("a1"), { completedAt, durationMs: 9000 }); + assert.notEqual(completed.byItemId, active.byItemId); + assert.equal(active.byItemId.has("a1"), false); + assert.deepEqual(completed.byItemId.get("a1"), { completedAt, durationMs: 9000 }); }); it("derives fresh timing when the tail itself changes", () => { @@ -211,11 +211,39 @@ describe("deriveStreamTurnTiming", () => { const first = derive(firstTail); const second = derive(secondTail); - assert.notEqual(second.byAssistantId, first.byAssistantId); - assert.equal(first.byAssistantId.has("a2"), false); - assert.deepEqual(second.byAssistantId.get("a2"), { + assert.notEqual(second.byItemId, first.byItemId); + assert.equal(first.byItemId.has("a2"), false); + assert.deepEqual(second.byItemId.get("a2"), { completedAt: secondTail[3]?.timestamp, durationMs: 3000, }); }); }); + +it("times a heartbeat that ends with tools and no assistant text", () => { + const trigger: StreamItem = { + kind: "tool_call", + id: "trigger", + timestamp: new Date("2026-05-15T00:00:00Z"), + turnId: "heartbeat", + payload: { + source: "agent", + data: { + provider: "claude", + callId: "trigger", + name: "heartbeat", + status: "completed", + error: null, + detail: { type: "plain_text", text: "Check progress" }, + }, + }, + }; + const tool: StreamItem = { ...trigger, id: "last", timestamp: new Date("2026-05-15T00:00:05Z") }; + const timing = deriveStreamTurnTiming({ + tail: [trigger, tool], + head: [], + isTurnActive: false, + activeTurnStartedAt: null, + }); + assert.equal(timing.byItemId.get("last")?.durationMs, 5000); +}); diff --git a/packages/app/src/timeline/turn-time.ts b/packages/app/src/timeline/turn-time.ts index c47a6983cd..8d1aa00648 100644 --- a/packages/app/src/timeline/turn-time.ts +++ b/packages/app/src/timeline/turn-time.ts @@ -1,5 +1,5 @@ import type { StreamItem } from "@/types/stream"; -import { startsNewTurn } from "@/agent-stream/turn-membership"; +import { startsNewTurn, isTurnTrigger } from "@/agent-stream/turn-membership"; export interface TurnTiming { completedAt: Date; @@ -7,7 +7,7 @@ export interface TurnTiming { } export interface StreamTurnTiming { - byAssistantId: Map; + byItemId: Map; runningStartedAt: Date | null; } @@ -20,7 +20,7 @@ interface OpenTurn { interface HeadTurnTiming { additions: Map; - byAssistantId: Map; + byItemId: Map; } interface TailTurnTiming { @@ -37,14 +37,18 @@ const EMPTY_OPEN_TURN: OpenTurn = { }; function closeTurn(turn: OpenTurn, into: Map): void { - if (!turn.lastItemAt || turn.assistantIds.length === 0) { + if (!turn.lastItemAt) { return; } const timing: TurnTiming = { completedAt: turn.lastItemAt, durationMs: turn.userAt ? Math.max(0, turn.lastItemAt.getTime() - turn.userAt.getTime()) : null, }; - for (const id of turn.assistantIds) { + let footerIds = turn.assistantIds; + if (footerIds.length === 0 && turn.previousItem?.kind === "tool_call") { + footerIds = [turn.previousItem.id]; + } + for (const id of footerIds) { into.set(id, timing); } } @@ -61,7 +65,7 @@ function walkTurns( for (const item of items) { if (startsNewTurn(item, previousItem)) { closeTurn({ userAt, lastItemAt, assistantIds, previousItem }, into); - userAt = item.kind === "user_message" ? item.timestamp : null; + userAt = isTurnTrigger(item) ? item.timestamp : null; lastItemAt = null; assistantIds = []; } @@ -108,7 +112,7 @@ function getTailTurnTiming(tail: StreamItem[]): TailTurnTiming { return timing; } -function resolveByAssistantId( +function resolveByItemId( tail: TailTurnTiming, additions: Map, ): Map { @@ -116,14 +120,14 @@ function resolveByAssistantId( return tail.completed; } if (tail.lastHead && areTimingsEqual(tail.lastHead.additions, additions)) { - return tail.lastHead.byAssistantId; + return tail.lastHead.byItemId; } - const byAssistantId = new Map(tail.completed); + const byItemId = new Map(tail.completed); for (const [id, timing] of additions) { - byAssistantId.set(id, timing); + byItemId.set(id, timing); } - tail.lastHead = { additions, byAssistantId }; - return byAssistantId; + tail.lastHead = { additions, byItemId }; + return byItemId; } export function deriveStreamTurnTiming(params: { @@ -139,7 +143,7 @@ export function deriveStreamTurnTiming(params: { closeTurn(openTurn, additions); } return { - byAssistantId: resolveByAssistantId(tail, additions), + byItemId: resolveByItemId(tail, additions), runningStartedAt: params.isTurnActive ? params.activeTurnStartedAt : null, }; } diff --git a/packages/app/src/timeline/viewed-timeline-sync.test.ts b/packages/app/src/timeline/viewed-timeline-sync.test.ts index 9bf6897bd9..a6e7cbeb33 100644 --- a/packages/app/src/timeline/viewed-timeline-sync.test.ts +++ b/packages/app/src/timeline/viewed-timeline-sync.test.ts @@ -189,6 +189,7 @@ class TimelineWorld { direction: "tail", limit: 40, projection: "projected", + wholeTurns: true, }); } finally { this.forcedTimelineTailReplacements.delete(agentId); @@ -341,7 +342,12 @@ test("uses a tail fetch when an agent becomes visible", async () => { membership.succeed(); const fetch = await world.nextFetch("agent-a"); - expect(fetch.request).toEqual({ direction: "tail", limit: 40, projection: "projected" }); + expect(fetch.request).toEqual({ + direction: "tail", + limit: 40, + projection: "projected", + wholeTurns: true, + }); fetch.respond({ hasNewer: false }); }); @@ -366,6 +372,7 @@ test("loads the cache before choosing the authoritative network request", async cursor: { epoch: "cached-epoch", seq: 17 }, limit: 40, projection: "projected", + wholeTurns: true, }); fetch.respond({ hasNewer: false }); }); @@ -384,6 +391,7 @@ test("catches up after the restored cursor when an agent becomes visible", async cursor: { epoch: "epoch-agent-a", seq: 42 }, limit: 40, projection: "projected", + wholeTurns: true, }); fetch.respond({ hasNewer: false }); }); @@ -401,7 +409,12 @@ test("falls back to the latest tail when a restored cursor has more than one cat probe.respond({ hasNewer: true, seq: 82 }); const fallback = await world.nextFetch("agent-a"); - expect(fallback.request).toEqual({ direction: "tail", limit: 40, projection: "projected" }); + expect(fallback.request).toEqual({ + direction: "tail", + limit: 40, + projection: "projected", + wholeTurns: true, + }); expect( world.applyTimelineResponse({ requestId: "fallback-tail", @@ -444,6 +457,7 @@ test("a gap absorbed by a running tail is recovered after the tail completes", a cursor: { epoch: "epoch-agent-a", seq: 9 }, limit: 40, projection: "projected", + wholeTurns: true, }); recovery.respond({ hasNewer: false }); await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready")); @@ -527,6 +541,7 @@ test("unchanged visible-set publication does not cancel paged catch-up", async ( cursor: { epoch: "epoch-agent-a", seq: 5 }, limit: 40, projection: "projected", + wholeTurns: true, }); world.expectNoPendingMembership(); }); @@ -897,12 +912,14 @@ test("gap recovery supersedes completed catch-up and pages through the current t cursor: { epoch: "epoch-agent-a", seq: 10 }, limit: 40, projection: "projected", + wholeTurns: true, }, { direction: "after", cursor: { epoch: "epoch-agent-a", seq: 15 }, limit: 40, projection: "projected", + wholeTurns: true, }, ]); }); diff --git a/packages/app/src/tool-calls/detail-level/grouping.ts b/packages/app/src/tool-calls/detail-level/grouping.ts index 079158b2d9..5713a06de3 100644 --- a/packages/app/src/tool-calls/detail-level/grouping.ts +++ b/packages/app/src/tool-calls/detail-level/grouping.ts @@ -1,5 +1,6 @@ +import { isTurnTrigger, isTurnBoundary } from "@/agent-stream/turn-membership"; import type { ToolCallDetail } from "@getpaseo/protocol/agent-types"; -import type { StreamItem, ToolCallItem } from "@/types/stream"; +import type { StreamItem, ToolCallItem, ThoughtItem } from "@/types/stream"; export interface ToolCallDescriptor { detail: ToolCallDetail; @@ -9,17 +10,19 @@ export interface ToolCallDescriptor { metadata?: Record; } +export type GroupableItem = ToolCallItem | ThoughtItem; + export interface ToolCallRun { id: string; - calls: readonly ToolCallItem[]; - latest: ToolCallItem; + calls: readonly GroupableItem[]; + latest: GroupableItem; isSealed: boolean; } export interface GroupedHistory { tail: StreamItem[]; groupsByHostId: Map; - pendingCalls: readonly ToolCallItem[]; + pendingCalls: readonly GroupableItem[]; } export interface GroupedToolCalls { @@ -62,15 +65,19 @@ export function describeToolCall(item: ToolCallItem): ToolCallDescriptor { }; } -export function isGroupableToolCall(item: StreamItem): item is ToolCallItem { - if (item.kind !== "tool_call") { +export function isGroupableToolCall( + item: StreamItem, + autoExpandReasoning = false, +): item is GroupableItem { + if (item.kind === "thought") return !autoExpandReasoning; + if (item.kind !== "tool_call" || isTurnTrigger(item)) { return false; } const descriptor = describeToolCall(item); return descriptor.detail.type !== "plan" && descriptor.name.trim().toLowerCase() !== "speak"; } -function createRun(calls: readonly ToolCallItem[], isSealed: boolean): ToolCallRun { +function createRun(calls: readonly GroupableItem[], isSealed: boolean): ToolCallRun { const first = calls[0]; const latest = calls.at(-1); if (!first || !latest) { @@ -79,20 +86,21 @@ function createRun(calls: readonly ToolCallItem[], isSealed: boolean): ToolCallR return { id: first.id, calls, latest, isSealed }; } -function createHost(run: ToolCallRun): ToolCallItem { +function createHost(run: ToolCallRun): GroupableItem { if (run.calls.length === 1) { return run.latest; } return { ...run.latest, id: run.id }; } -function isRunning(call: ToolCallItem): boolean { +function isRunning(call: GroupableItem): boolean { + if (call.kind === "thought") return call.status !== "ready"; const status = describeToolCall(call).status; return status === "running" || status === "executing"; } function appendRun(input: { - calls: readonly ToolCallItem[]; + calls: readonly GroupableItem[]; isSealed: boolean; output: StreamItem[]; groups: Map; @@ -110,13 +118,17 @@ function appendRun(input: { export function prepareGroupedHistory(input: { tail: StreamItem[]; buildGroup: (run: ToolCallRun) => TGroup; + autoExpandReasoning?: boolean; }): GroupedHistory { const output: StreamItem[] = []; const groups = new Map(); - let pending: ToolCallItem[] = []; + let pending: GroupableItem[] = []; for (const item of input.tail) { - if (isGroupableToolCall(item)) { + if ( + isGroupableToolCall(item, input.autoExpandReasoning) && + !isTurnBoundary(pending.at(-1) ?? null, item) + ) { pending.push(item); continue; } @@ -128,7 +140,8 @@ export function prepareGroupedHistory(input: { buildGroup: input.buildGroup, }); pending = []; - output.push(item); + if (isGroupableToolCall(item, input.autoExpandReasoning)) pending.push(item); + else output.push(item); } appendRun({ @@ -151,6 +164,7 @@ export function groupLiveToolCalls(input: { head: StreamItem[]; isTurnActive: boolean; buildGroup: (run: ToolCallRun) => TGroup; + autoExpandReasoning?: boolean; }): GroupedToolCalls { const head: StreamItem[] = []; const liveGroups = new Map(); @@ -175,7 +189,8 @@ export function groupLiveToolCalls(input: { }; for (const item of input.head) { - if (isGroupableToolCall(item)) { + if (isTurnBoundary(pending.at(-1) ?? null, item)) flush(true); + if (isGroupableToolCall(item, input.autoExpandReasoning)) { if (pending.length === 0) { hostPlacement = "head"; } diff --git a/packages/app/src/tool-calls/detail-level/overview/label.ts b/packages/app/src/tool-calls/detail-level/overview/label.ts index 762e530172..7a34685d62 100644 --- a/packages/app/src/tool-calls/detail-level/overview/label.ts +++ b/packages/app/src/tool-calls/detail-level/overview/label.ts @@ -33,13 +33,18 @@ export function useOverviewSummaryLabel( [summary.readFileCount, "toolCallGroup.readFiles"], [summary.searchCount, "toolCallGroup.searches"], [summary.otherToolCount, "toolCallGroup.otherTools"], - [summary.paseoCallCount, "toolCallGroup.paseoCalls"], ] as const; for (const [count, key] of entries) { if (count > 0) { parts.push(t(`${key}.${count === 1 ? "one" : "other"}`, { count })); } } + for (const [action, count] of Object.entries(summary.paseoActions)) { + parts.push( + count === 1 ? action.toLocaleLowerCase() : `${action.toLocaleLowerCase()} ×${count}`, + ); + } + if (summary.thoughtCount > 0) parts.push(t("toolCallGroup.thought").toLocaleLowerCase()); return joinSummaryParts(parts, t("toolCallGroup.and")); }, [leadingParts, summary, t]); } diff --git a/packages/app/src/tool-calls/detail-level/overview/model.ts b/packages/app/src/tool-calls/detail-level/overview/model.ts index 0fb638c012..e4717c43bf 100644 --- a/packages/app/src/tool-calls/detail-level/overview/model.ts +++ b/packages/app/src/tool-calls/detail-level/overview/model.ts @@ -1,17 +1,18 @@ -import { isPaseoToolName } from "@getpaseo/protocol/tool-name-normalization"; -import type { ToolCallItem } from "@/types/stream"; -import { describeToolCall, type ToolCallRun } from "../grouping"; +import { getPaseoToolActionLabel } from "@getpaseo/protocol/paseo-tool-presentation/index"; +import { isTurnTrigger } from "@/agent-stream/turn-membership"; + +import { describeToolCall, type GroupableItem, type ToolCallRun } from "../grouping"; -const DIRECT_PASEO_TOOL_PREFIX = "paseo_"; const DIRECT_SEARCH_TOOL_SUFFIX_PATTERN = /(?:^|[_.:/])(?:web_search|llm_context)$/; export interface OverviewSummary { + thoughtCount: number; editedFileCount: number; commandCount: number; readFileCount: number; searchCount: number; otherToolCount: number; - paseoCallCount: number; + paseoActions: Record; } export interface OverviewToolCallGroup { @@ -21,28 +22,31 @@ export interface OverviewToolCallGroup { isLoading: boolean; } -function isPaseoCall(name: string, normalizedName: string): boolean { - return isPaseoToolName(name) || normalizedName.startsWith(DIRECT_PASEO_TOOL_PREFIX); -} - function isSearchCall(name: string): boolean { return DIRECT_SEARCH_TOOL_SUFFIX_PATTERN.test(name); } /** Counts tool calls by what they did, for any summary of a stretch of agent work. */ -export function summarizeToolCalls(calls: readonly ToolCallItem[]): OverviewSummary { +export function summarizeToolCalls(calls: readonly GroupableItem[]): OverviewSummary { const editedFiles = new Set(); const readFiles = new Set(); + let thoughtCount = 0; let commandCount = 0; let searchCount = 0; let otherToolCount = 0; - let paseoCallCount = 0; + const paseoActions: Record = {}; for (const call of calls) { + if (call.kind === "thought") { + thoughtCount += 1; + continue; + } + if (isTurnTrigger(call)) continue; const descriptor = describeToolCall(call); const normalizedName = descriptor.name.trim().toLowerCase(); - if (isPaseoCall(descriptor.name, normalizedName)) { - paseoCallCount += 1; + const action = getPaseoToolActionLabel(descriptor.name); + if (action) { + paseoActions[action] = (paseoActions[action] ?? 0) + 1; } else if (descriptor.detail.type === "edit" || descriptor.detail.type === "write") { editedFiles.add(descriptor.detail.filePath); } else if (descriptor.detail.type === "shell") { @@ -57,17 +61,19 @@ export function summarizeToolCalls(calls: readonly ToolCallItem[]): OverviewSumm } return { + thoughtCount, editedFileCount: editedFiles.size, commandCount, readFileCount: readFiles.size, searchCount, otherToolCount, - paseoCallCount, + paseoActions, }; } export function buildOverviewGroup(run: ToolCallRun): OverviewToolCallGroup { const isLoading = run.calls.some((call) => { + if (call.kind === "thought") return call.status !== "ready"; const status = describeToolCall(call).status; return status === "running" || status === "executing"; }); diff --git a/packages/app/src/tool-calls/detail-level/projection.test.ts b/packages/app/src/tool-calls/detail-level/projection.test.ts index dabf87b73d..d6233854a2 100644 --- a/packages/app/src/tool-calls/detail-level/projection.test.ts +++ b/packages/app/src/tool-calls/detail-level/projection.test.ts @@ -255,12 +255,13 @@ describe("tool call detail-level projection", () => { run: expect.any(Object), isLoading: false, summary: { + thoughtCount: 0, editedFileCount: 1, commandCount: 1, readFileCount: 2, searchCount: 0, otherToolCount: 0, - paseoCallCount: 0, + paseoActions: {}, }, }); }); @@ -328,7 +329,7 @@ describe("tool call detail-level projection", () => { const result = project({ level: "overview", head: calls }); expect(result.groupsByHostId.get("1")).toMatchObject({ - summary: { otherToolCount: 2, paseoCallCount: 2 }, + summary: { otherToolCount: 2, paseoActions: { "Listed agents": 1, "List worktrees": 1 } }, }); }); @@ -346,7 +347,11 @@ describe("tool call detail-level projection", () => { const result = project({ level: "overview", head: calls }); expect(result.groupsByHostId.get("1")).toMatchObject({ - summary: { searchCount: 3, otherToolCount: 0, paseoCallCount: 3 }, + summary: { + searchCount: 3, + otherToolCount: 0, + paseoActions: { "Listed providers": 1, "List worktrees": 2 }, + }, }); }); @@ -480,3 +485,56 @@ describe("tool call detail-level projection", () => { expect(result.groupsByHostId.size).toBe(1); }); }); + +it("keeps a heartbeat trigger visible outside grouped work", () => { + const trigger = toolCall( + "1", + { type: "plain_text", text: "Check progress" }, + { name: "heartbeat" }, + ); + const work = toolCall("2", { type: "shell", command: "pwd" }); + const result = project({ level: "overview", tail: [trigger, work] }); + expect(result.tail.map((item) => item.id)).toEqual(["1", "2"]); + expect(result.groupsByHostId.has("1")).toBe(false); +}); + +it("does not merge tools from different canonical turns", () => { + const first = toolCall("1", { type: "shell", command: "pwd" }); + first.turnId = "first"; + const second = toolCall("2", { type: "shell", command: "ls" }); + second.turnId = "second"; + const result = project({ level: "overview", tail: [first, second] }); + expect(result.tail.map((item) => item.id)).toEqual(["1", "2"]); +}); + +it.each([false, true])( + "handles streaming reasoning across retained history (Expand thinking %s)", + (autoExpandReasoning) => { + const call = { ...toolCall("1", { type: "shell", command: "echo ok" }), turnId: "run" }; + const thought: StreamItem = { + kind: "thought", + id: "reasoning", + text: "Checking", + status: "loading", + timestamp: new Date(), + turnId: "run", + }; + const tail = [call]; + const result = project({ + level: "overview", + tail, + head: [thought], + isTurnActive: true, + preparedHistory: prepareToolCallHistory("overview", tail, autoExpandReasoning), + }); + expect(result.head).toEqual(autoExpandReasoning ? [thought] : []); + expect(result.groupsByHostId.get(call.id)?.run.calls).toEqual( + autoExpandReasoning ? [call] : [call, thought], + ); + expect(result.groupsByHostId.get(call.id)?.summary).toMatchObject({ + commandCount: 1, + otherToolCount: 0, + thoughtCount: autoExpandReasoning ? 0 : 1, + }); + }, +); diff --git a/packages/app/src/tool-calls/detail-level/projection.ts b/packages/app/src/tool-calls/detail-level/projection.ts index 9d57391b2e..3f10855ce5 100644 --- a/packages/app/src/tool-calls/detail-level/projection.ts +++ b/packages/app/src/tool-calls/detail-level/projection.ts @@ -13,6 +13,7 @@ export type ToolCallDetailGroup = OverviewToolCallGroup; export interface PreparedToolCallHistory { mode: "overview"; + autoExpandReasoning: boolean; grouped: GroupedHistory; } @@ -41,15 +42,18 @@ function visibleToolCallItems(items: StreamItem[]): StreamItem[] { export function prepareToolCallHistory( level: ToolCallDetailLevel, tail: StreamItem[], + autoExpandReasoning = false, ): PreparedToolCallHistory | null { if (level === "detailed") { return null; } return { mode: "overview", + autoExpandReasoning, grouped: prepareGroupedHistory({ tail: visibleToolCallItems(tail), buildGroup: buildOverviewGroup, + autoExpandReasoning, }), }; } @@ -74,6 +78,7 @@ export function projectToolCallDetailLevel(input: { } return groupLiveToolCalls({ history: input.preparedHistory.grouped, + autoExpandReasoning: input.preparedHistory.autoExpandReasoning, head: visibleToolCallItems(input.head), isTurnActive: input.isTurnActive, buildGroup: buildOverviewGroup, diff --git a/packages/app/src/types/stream.ts b/packages/app/src/types/stream.ts index 657d218b35..b1d0903a92 100644 --- a/packages/app/src/types/stream.ts +++ b/packages/app/src/types/stream.ts @@ -91,6 +91,8 @@ export type StreamItem = export type UserMessageImageAttachment = AttachmentMetadata; export interface UserMessageItem { + /** Attribution added by presentation for received agent messages. */ + sender?: AgentMessage["sender"]; kind: "user_message"; id: string; clientMessageId?: string; diff --git a/packages/client/src/daemon-client.test.ts b/packages/client/src/daemon-client.test.ts index f663aeb8be..f3b483193c 100644 --- a/packages/client/src/daemon-client.test.ts +++ b/packages/client/src/daemon-client.test.ts @@ -1658,6 +1658,11 @@ test("honors explicit fetchAgentTimeline timeout below the session RPC default", mock.triggerOpen(); await connectPromise; + await expect(client.fetchAgentTimeline("agent-1", { wholeTurns: true })).rejects.toThrow( + "Update the host to load complete conversation turns.", + ); + expect(mock.sent).toHaveLength(0); + const responsePromise = client.fetchAgentTimeline("agent-1", { requestId: "req-timeline-1", direction: "tail", diff --git a/packages/client/src/daemon-client.ts b/packages/client/src/daemon-client.ts index 59d928283f..8840aa1eb4 100644 --- a/packages/client/src/daemon-client.ts +++ b/packages/client/src/daemon-client.ts @@ -686,6 +686,7 @@ export interface FetchAgentOptions { } type LegacyFetchAgentOptions = Omit; export interface FetchAgentTimelineOptions { + wholeTurns?: boolean; direction?: FetchAgentTimelineDirection; cursor?: FetchAgentTimelineCursor; limit?: number; @@ -3548,9 +3549,13 @@ export class DaemonClient { agentId: string, options: FetchAgentTimelineOptions = {}, ): Promise { + if (options.wholeTurns && this.lastServerInfoMessage?.features?.wholeTurnTimeline !== true) { + throw new Error("Update the host to load complete conversation turns."); + } const resolvedRequestId = this.createRequestId(options.requestId); const message = SessionInboundMessageSchema.parse({ type: "fetch_agent_timeline_request", + ...(options.wholeTurns !== undefined ? { wholeTurns: options.wholeTurns } : {}), agentId, requestId: resolvedRequestId, ...(options.direction ? { direction: options.direction } : {}), diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index 3034598f1e..704c7ad277 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -1910,6 +1910,8 @@ export const AgentTimelineCursorSchema = z.object({ }); export const FetchAgentTimelineRequestMessageSchema = z.object({ + // Keep available turns whole for tail/before pages; after catch-up stays incremental. + wholeTurns: z.boolean().optional(), type: z.literal("fetch_agent_timeline_request"), agentId: z.string(), requestId: z.string(), @@ -3765,6 +3767,7 @@ export const ServerInfoStatusPayloadSchema = z providerSubagents: z.boolean().optional(), // COMPAT(projectedSubagentTimeline): added after v0.8.0, remove gates after 2027-03-14; retain wire field. projectedSubagentTimeline: z.boolean().optional(), + wholeTurnTimeline: z.boolean().optional(), // COMPAT(providerSubagentNesting): added in v0.7, remove gate after 2027-03-04. providerSubagentNesting: z.boolean().optional(), // COMPAT(workspacePinning): added in v0.1.107, remove gate after 2027-01-12. diff --git a/packages/protocol/src/paseo-tool-presentation/catalog.ts b/packages/protocol/src/paseo-tool-presentation/catalog.ts index 0c35b128b7..4844b7ceb7 100644 --- a/packages/protocol/src/paseo-tool-presentation/catalog.ts +++ b/packages/protocol/src/paseo-tool-presentation/catalog.ts @@ -19,6 +19,7 @@ export interface PaseoToolDetailSpec { export interface PaseoToolEntry { label: string; + completedLabel: string; context?: PaseoToolContext; detail?: PaseoToolDetailSpec; } @@ -123,14 +124,24 @@ function baseName(value: unknown): string | undefined { return value.split(/[\\/]/).findLast((segment) => segment.length > 0); } -function browser(label: string, context?: PaseoToolContext): PaseoToolEntry { - return { label, ...(context ? { context } : {}), detail: { inputOrder: BROWSER_FIELDS } }; +function browser( + label: string, + completedLabel: string, + context?: PaseoToolContext, +): PaseoToolEntry { + return { + label, + completedLabel, + ...(context ? { context } : {}), + detail: { inputOrder: BROWSER_FIELDS }, + }; } export const PASEO_TOOL_CATALOG = { // Agents create_agent: { label: "Create agent", + completedLabel: "Created agent", context: field("title", "initialPrompt"), detail: { promptField: "initialPrompt", @@ -140,6 +151,7 @@ export const PASEO_TOOL_CATALOG = { }, send_agent_prompt: { label: "Send message", + completedLabel: "Sent message", context: field("prompt"), detail: { promptField: "prompt", @@ -149,42 +161,55 @@ export const PASEO_TOOL_CATALOG = { }, get_agent_status: { label: "Check agent", + completedLabel: "Checked agent", context: targetAgent(), detail: { inputOrder: ["agentId"] }, }, get_agent_activity: { label: "Read agent activity", + completedLabel: "Read agent activity", context: targetAgent(), detail: { inputOrder: ["agentId", "limit"] }, }, list_agents: { label: "List agents", + completedLabel: "Listed agents", detail: { inputOrder: ["cwd", "statuses", "sinceHours", "limit", "includeArchived"] }, }, update_agent: { label: "Update agent", + completedLabel: "Updated agent", context: fieldOrTargetAgent("name"), detail: { inputOrder: AGENT_FIELDS }, }, set_agent_mode: { label: "Set agent mode", + completedLabel: "Set agent mode", context: field("modeId"), detail: { inputOrder: ["agentId", "modeId"] }, }, cancel_agent: { label: "Cancel agent", + completedLabel: "Canceled agent", context: targetAgent(), detail: { inputOrder: ["agentId"] }, }, archive_agent: { label: "Archive agent", + completedLabel: "Archived agent", context: targetAgent(), detail: { inputOrder: ["agentId"] }, }, - kill_agent: { label: "Kill agent", context: targetAgent(), detail: { inputOrder: ["agentId"] } }, - list_pending_permissions: { label: "List permissions" }, + kill_agent: { + label: "Kill agent", + completedLabel: "Killed agent", + context: targetAgent(), + detail: { inputOrder: ["agentId"] }, + }, + list_pending_permissions: { label: "List permissions", completedLabel: "Listed permissions" }, respond_to_permission: { label: "Respond to permission", + completedLabel: "Responded to permission", context: targetAgent(), detail: { inputOrder: ["agentId", "requestId", "response"] }, }, @@ -192,32 +217,41 @@ export const PASEO_TOOL_CATALOG = { // Workspaces and scripts create_workspace: { label: "Create workspace", + completedLabel: "Created workspace", context: workspaceContext(), detail: { inputOrder: WORKSPACE_FIELDS, outputFields: ["workspaceId", "projectId"] }, }, - list_hosts: { label: "List hosts" }, - list_workspaces: { label: "List workspaces" }, + list_hosts: { label: "List hosts", completedLabel: "Listed hosts" }, + list_workspaces: { label: "List workspaces", completedLabel: "Listed workspaces" }, rename_workspace: { label: "Rename workspace", + completedLabel: "Renamed workspace", context: field("title"), detail: { inputOrder: ["title", "workspaceId"] }, }, archive_workspace: { label: "Archive workspace", + completedLabel: "Archived workspace", context: field("workspaceId"), detail: { inputOrder: ["workspaceId"], outputFields: ["workspaceId", "archivedAgentIds", "removedDirectory"], }, }, - list_workspace_scripts: { label: "List scripts", detail: { inputOrder: ["workspaceId"] } }, + list_workspace_scripts: { + label: "List scripts", + completedLabel: "Listed scripts", + detail: { inputOrder: ["workspaceId"] }, + }, start_workspace_script: { label: "Start script", + completedLabel: "Started script", context: field("scriptName"), detail: { inputOrder: ["workspaceId", "scriptName"] }, }, stop_workspace_script: { label: "Stop script", + completedLabel: "Stopped script", context: field("scriptName"), detail: { inputOrder: ["workspaceId", "scriptName"] }, }, @@ -225,22 +259,30 @@ export const PASEO_TOOL_CATALOG = { // Terminals create_terminal: { label: "Create terminal", + completedLabel: "Created terminal", context: field("name", "command"), detail: { inputOrder: ["cwd", "workspaceId", "name", "command"] }, }, - list_terminals: { label: "List terminals", detail: { inputOrder: ["cwd", "all"] } }, + list_terminals: { + label: "List terminals", + completedLabel: "Listed terminals", + detail: { inputOrder: ["cwd", "all"] }, + }, capture_terminal: { label: "Read terminal", + completedLabel: "Read terminal", context: field("terminalId"), detail: { inputOrder: ["terminalId", "lines"] }, }, send_terminal_keys: { label: "Send keys", + completedLabel: "Sent keys", context: field("keys"), detail: { inputOrder: ["terminalId", "keys", "literal"] }, }, kill_terminal: { label: "Kill terminal", + completedLabel: "Killed terminal", context: field("terminalId"), detail: { inputOrder: ["terminalId"] }, }, @@ -248,6 +290,7 @@ export const PASEO_TOOL_CATALOG = { // Schedules and heartbeats create_schedule: { label: "Create schedule", + completedLabel: "Created schedule", context: field("name", "cron"), detail: { promptField: "prompt", @@ -257,6 +300,7 @@ export const PASEO_TOOL_CATALOG = { }, create_heartbeat: { label: "Create heartbeat", + completedLabel: "Created heartbeat", context: field("name", "cron"), detail: { promptField: "prompt", @@ -266,79 +310,93 @@ export const PASEO_TOOL_CATALOG = { }, update_schedule: { label: "Update schedule", + completedLabel: "Updated schedule", context: field("name", "id"), detail: { promptField: "prompt", inputOrder: AUTOMATION_FIELDS }, }, - list_schedules: { label: "List schedules" }, + list_schedules: { label: "List schedules", completedLabel: "Listed schedules" }, inspect_schedule: { label: "Inspect schedule", + completedLabel: "Inspected schedule", context: field("id"), detail: { inputOrder: ["id"] }, }, schedule_logs: { label: "Read schedule logs", + completedLabel: "Read schedule logs", context: field("id"), detail: { inputOrder: ["id"] }, }, run_schedule_once: { label: "Run schedule", + completedLabel: "Ran schedule", + context: field("id"), + detail: { inputOrder: ["id"] }, + }, + pause_schedule: { + label: "Pause schedule", + completedLabel: "Paused schedule", context: field("id"), detail: { inputOrder: ["id"] }, }, - pause_schedule: { label: "Pause schedule", context: field("id"), detail: { inputOrder: ["id"] } }, resume_schedule: { label: "Resume schedule", + completedLabel: "Resumed schedule", context: field("id"), detail: { inputOrder: ["id"] }, }, delete_schedule: { label: "Delete schedule", + completedLabel: "Deleted schedule", context: field("id"), detail: { inputOrder: ["id"] }, }, delete_heartbeat: { label: "Delete heartbeat", + completedLabel: "Deleted heartbeat", context: field("id"), detail: { inputOrder: ["id"] }, }, // Providers - list_providers: { label: "List providers" }, + list_providers: { label: "List providers", completedLabel: "Listed providers" }, list_models: { label: "List models", + completedLabel: "Listed models", context: field("provider"), detail: { inputOrder: ["provider"] }, }, - list_profiles: { label: "List profiles" }, + list_profiles: { label: "List profiles", completedLabel: "Listed profiles" }, inspect_provider: { label: "Inspect provider", + completedLabel: "Inspected provider", context: field("provider"), detail: { inputOrder: ["provider", "cwd", "settings"] }, }, // Browser - browser_list_tabs: browser("List browser tabs"), - browser_new_tab: browser("Open browser tab", field("url")), - browser_close_tab: browser("Close browser tab", field("browserId")), - browser_navigate: browser("Navigate", field("url")), - browser_back: browser("Go back"), - browser_forward: browser("Go forward"), - browser_reload: browser("Reload page"), - browser_snapshot: browser("Snapshot page"), - browser_screenshot: browser("Take screenshot"), - browser_click: browser("Click element", field("ref")), - browser_hover: browser("Hover element", field("ref")), - browser_drag: browser("Drag element", field("sourceRef")), - browser_fill: browser("Fill field", field("ref")), - browser_select: browser("Select option", field("value", "ref")), - browser_type: browser("Type text", field("text")), - browser_keypress: browser("Press key", field("key")), - browser_upload: browser("Upload files", field("filePaths")), - browser_wait: browser("Wait for page", field("text", "url")), - browser_scroll: browser("Scroll page"), - browser_resize: browser("Resize browser", viewportContext()), - browser_logs: browser("Read browser logs"), - browser_evaluate: browser("Run JavaScript", field("function")), + browser_list_tabs: browser("List browser tabs", "Listed browser tabs"), + browser_new_tab: browser("Open browser tab", "Opened browser tab", field("url")), + browser_close_tab: browser("Close browser tab", "Closed browser tab", field("browserId")), + browser_navigate: browser("Navigate", "Navigated", field("url")), + browser_back: browser("Go back", "Went back"), + browser_forward: browser("Go forward", "Went forward"), + browser_reload: browser("Reload page", "Reloaded page"), + browser_snapshot: browser("Snapshot page", "Snapshotted page"), + browser_screenshot: browser("Take screenshot", "Took screenshot"), + browser_click: browser("Click element", "Clicked element", field("ref")), + browser_hover: browser("Hover element", "Hovered element", field("ref")), + browser_drag: browser("Drag element", "Dragged element", field("sourceRef")), + browser_fill: browser("Fill field", "Filled field", field("ref")), + browser_select: browser("Select option", "Selected option", field("value", "ref")), + browser_type: browser("Type text", "Typed text", field("text")), + browser_keypress: browser("Press key", "Pressed key", field("key")), + browser_upload: browser("Upload files", "Uploaded files", field("filePaths")), + browser_wait: browser("Wait for page", "Waited for page", field("text", "url")), + browser_scroll: browser("Scroll page", "Scrolled page"), + browser_resize: browser("Resize browser", "Resized browser", viewportContext()), + browser_logs: browser("Read browser logs", "Read browser logs"), + browser_evaluate: browser("Run JavaScript", "Ran JavaScript", field("function")), } satisfies Record; export type PaseoToolName = keyof typeof PASEO_TOOL_CATALOG; diff --git a/packages/protocol/src/paseo-tool-presentation/index.ts b/packages/protocol/src/paseo-tool-presentation/index.ts index c04606a231..e5395a9e62 100644 --- a/packages/protocol/src/paseo-tool-presentation/index.ts +++ b/packages/protocol/src/paseo-tool-presentation/index.ts @@ -28,6 +28,8 @@ export const PASEO_TOOL_NAMES = Object.keys(PASEO_TOOL_CATALOG) as readonly Pase /** Returns null for tools outside the Paseo namespace. */ export function buildPaseoToolDisplay(input: PaseoToolDisplayInput): PaseoToolDisplay | null { + // Canonical details own internal lifecycle rows such as worktree setup. + if (input.detail.type !== "unknown") return null; const leafName = paseoLeafName(input.toolName); if (!leafName) return null; const entry = getPaseoToolEntry(leafName); @@ -39,6 +41,13 @@ export function buildPaseoToolDisplay(input: PaseoToolDisplayInput): PaseoToolDi return { displayName: entry.label, ...(summary ? { summary } : {}) }; } +/** A semantic action label for summaries, sharing the tool presentation catalog. */ +export function getPaseoToolActionLabel(toolName: string): string | null { + const leafName = paseoLeafName(toolName); + if (!leafName) return null; + return getPaseoToolEntry(leafName)?.completedLabel ?? humanizeLeafName(leafName); +} + /** The agent a Paseo call acts on, so callers can resolve its title. */ export function getPaseoToolTargetAgentId( toolName: string, @@ -49,7 +58,11 @@ export function getPaseoToolTargetAgentId( } function paseoLeafName(toolName: string): string | null { - return isPaseoToolName(toolName) ? getPaseoToolLeafName(toolName) : null; + if (isPaseoToolName(toolName)) return getPaseoToolLeafName(toolName); + const normalized = toolName.trim().toLowerCase(); + return normalized.startsWith("paseo_") && !normalized.startsWith("paseo__") + ? normalized.slice("paseo_".length) + : null; } function readToolInput(detail: ToolCallDetail): Readonly> { diff --git a/packages/protocol/src/timeline-turn.ts b/packages/protocol/src/timeline-turn.ts new file mode 100644 index 0000000000..f509787317 --- /dev/null +++ b/packages/protocol/src/timeline-turn.ts @@ -0,0 +1,24 @@ +/** Canonical run identity wins over trigger-shaped rows steered into that run. */ +export function continuesTimelineTurn( + previousTurnId: string | undefined, + nextTurnId: string | undefined, + nextIsTrigger: boolean, +): boolean { + if (previousTurnId !== undefined && nextTurnId !== undefined) { + return previousTurnId === nextTurnId; + } + // Missing IDs cannot recover historical batching or steering. Each visible + // trigger deterministically starts a turn in both paging and presentation. + return !nextIsTrigger; +} + +export function isTimelineTurnTrigger(item: { + type: string; + name?: string; + agentMessage?: unknown; +}): boolean { + return ( + item.type === "user_message" || + (item.type === "tool_call" && (item.agentMessage !== undefined || item.name === "heartbeat")) + ); +} diff --git a/packages/server/src/server/agent/agent-manager.test.ts b/packages/server/src/server/agent/agent-manager.test.ts index ae8989c003..2d21bdc63c 100644 --- a/packages/server/src/server/agent/agent-manager.test.ts +++ b/packages/server/src/server/agent/agent-manager.test.ts @@ -880,6 +880,66 @@ test("retries provider history hydration after a stream failure", async () => { } }); +test("notification batches share the run they start or join", async () => { + const session = new SteeringTestSession({ provider: "codex", cwd: process.cwd() }); + const workdir = mkdtempSync(join(tmpdir(), "agent-notification-turns-")); + const manager = new AgentManager({ + clients: { + codex: new (class extends TestAgentClient { + override async createSession(): Promise { + return session; + } + })(), + }, + logger, + }); + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + const batch = (prefix: string) => + ["one", "two"] + .map((id) => + formatAgentMessage({ + id: `${prefix}-${id}`, + source: { kind: "agent-notification", agentId: "worker", event: "finished" }, + text: "Worker finished", + }), + ) + .join("\n\n"); + const consume = async (prompt: string, clientMessageId: string) => { + for await (const _event of manager.streamAgent(agent.id, prompt, { clientMessageId })) { + } + }; + try { + const first = consume("human", "human"); + await manager.waitForAgentRunStart(agent.id); + await expect( + manager.steerAgentRun(agent.id, batch("joined"), { clientMessageId: "joined-one" }), + ).resolves.toEqual({ status: "accepted" }); + session.pushEvent({ type: "turn_completed", provider: "codex", turnId: "active-turn-1" }); + await first; + const second = consume(batch("idle"), "idle-one"); + await manager.waitForAgentRunStart(agent.id); + session.pushEvent({ type: "turn_completed", provider: "codex", turnId: "active-turn-2" }); + await second; + expect( + manager.fetchTimeline(agent.id, { limit: 0 }).rows.map((row) => ({ + turnId: row.turnId, + id: row.item.type === "tool_call" ? row.item.callId : row.item.type, + })), + ).toEqual([ + { turnId: "active-turn-1", id: "user_message" }, + { turnId: "active-turn-1", id: "paseo-agent-message:joined-one" }, + { turnId: "active-turn-1", id: "paseo-agent-message:joined-two" }, + { turnId: "active-turn-2", id: "paseo-agent-message:idle-one" }, + { turnId: "active-turn-2", id: "paseo-agent-message:idle-two" }, + ]); + } finally { + await manager.closeAgent(agent.id); + rmSync(workdir, { recursive: true, force: true }); + } +}); + test("unavailable steer interrupts once and starts one replacement turn", async () => { const session = new SteeringTestSession({ provider: "codex", cwd: process.cwd() }); session.steerResult = "unavailable"; @@ -11341,7 +11401,7 @@ test("listImportableSessions searches every provider result before global rankin ]); }); -test("user_message events wrapping a paseo-system envelope are not added to the timeline", async () => { +test("system-injected prompts appear as trigger tools in the live timeline", async () => { const workdir = mkdtempSync(join(tmpdir(), "agent-manager-envelope-live-")); const storagePath = join(workdir, "agents"); const storage = new AgentStorage(storagePath, logger); @@ -11370,13 +11430,16 @@ test("user_message events wrapping a paseo-system envelope are not added to the await manager.runAgent(snapshot.id, { text: "do something" }); const timeline = manager.getTimeline(snapshot.id); + expect(timeline).toContainEqual( + expect.objectContaining({ type: "tool_call", name: "heartbeat", status: "completed" }), + ); const userMessages = timeline.filter((item) => item.type === "user_message"); expect(userMessages).toHaveLength(1); expect(userMessages[0].text).toBe("plain user message"); }); -test("user_message events wrapping a paseo-system envelope are not restored during history replay", async () => { +test("system-injected prompts appear as trigger tools during history replay", async () => { const workdir = mkdtempSync(join(tmpdir(), "agent-manager-envelope-history-")); const storagePath = join(workdir, "agents"); const storage = new AgentStorage(storagePath, logger); @@ -11411,6 +11474,9 @@ test("user_message events wrapping a paseo-system envelope are not restored duri await manager.hydrateTimelineFromProvider(snapshot.id, { force: true }); const timeline = manager.getTimeline(snapshot.id); + expect(timeline).toContainEqual( + expect.objectContaining({ type: "tool_call", name: "heartbeat", status: "completed" }), + ); const userMessages = timeline.filter((item) => item.type === "user_message"); expect(userMessages).toHaveLength(1); diff --git a/packages/server/src/server/agent/agent-messages/envelope.ts b/packages/server/src/server/agent/agent-messages/envelope.ts index 2144d6ae02..a0aa880fce 100644 --- a/packages/server/src/server/agent/agent-messages/envelope.ts +++ b/packages/server/src/server/agent/agent-messages/envelope.ts @@ -1,5 +1,5 @@ import { renderPromptAttachmentAsText } from "../prompt-attachments.js"; -import { randomUUID } from "node:crypto"; +import { createHash, randomUUID } from "node:crypto"; import { z } from "zod"; import type { AgentPromptContentBlock, @@ -175,9 +175,18 @@ function projectAgentMessage(item: AgentTimelineItem): AgentTimelineItem | null if (item.type !== "user_message") return item; const message = parseAgentMessage(item.text); if (!message) { - // COMPAT(legacySystemEnvelope): added in v0.11.1; remove after 2027-04-08 once - // legacy notification history is retired. Schedules still use this envelope. - return isSystemInjectedEnvelope(item.text) ? null : item; + // Schedule bodies include their run ID, keeping identity stable across acceptance + // and provider replay even when the provider assigns its own message ID. + if (!isSystemInjectedEnvelope(item.text)) return item; + const text = item.text.slice("\n".length, -"\n".length); + return { + type: "tool_call", + callId: `paseo-system:${createHash("sha256").update(item.text).digest("hex")}`, + name: "heartbeat", + status: "completed", + error: null, + detail: { type: "plain_text", text, icon: "sparkles" }, + }; } const { source } = message; if (!source) { diff --git a/packages/server/src/server/agent/agent-prompt.test.ts b/packages/server/src/server/agent/agent-prompt.test.ts index 00e70756de..2c150bd2e1 100644 --- a/packages/server/src/server/agent/agent-prompt.test.ts +++ b/packages/server/src/server/agent/agent-prompt.test.ts @@ -357,3 +357,21 @@ test("a human pasting an agent envelope stays a human message through provider r clientMessageId: "human-submission", }); }); + +test("schedule prompts remain visible as completed tool calls on replay", () => { + const text = formatSystemNotificationPrompt("Heartbeat: check progress"); + expect(projectAgentMessages({ type: "user_message", messageId: "fire-1", text })).toEqual([ + expect.objectContaining({ + type: "tool_call", + status: "completed", + detail: { type: "plain_text", text: "Heartbeat: check progress", icon: "sparkles" }, + }), + ]); +}); + +test("schedule trigger identity survives the provider assigning a message ID", () => { + const text = formatSystemNotificationPrompt("Schedule fired (id=heartbeat, run=run-1)."); + expect(projectAgentMessages({ type: "user_message", text })).toEqual( + projectAgentMessages({ type: "user_message", text, messageId: "provider-message" }), + ); +}); diff --git a/packages/server/src/server/agent/agent-timeline-store-types.ts b/packages/server/src/server/agent/agent-timeline-store-types.ts index 639b24a904..9ca1ab37b9 100644 --- a/packages/server/src/server/agent/agent-timeline-store-types.ts +++ b/packages/server/src/server/agent/agent-timeline-store-types.ts @@ -17,6 +17,7 @@ export interface AgentTimelineCursor { export type AgentTimelineFetchDirection = "tail" | "before" | "after"; export interface AgentTimelineFetchOptions { + wholeTurns?: boolean; direction?: AgentTimelineFetchDirection; cursor?: AgentTimelineCursor; /** diff --git a/packages/server/src/server/agent/agent-timeline-store.test.ts b/packages/server/src/server/agent/agent-timeline-store.test.ts index eb46916fe3..99e392f188 100644 --- a/packages/server/src/server/agent/agent-timeline-store.test.ts +++ b/packages/server/src/server/agent/agent-timeline-store.test.ts @@ -4,6 +4,39 @@ import type { AgentTimelineItem } from "./agent-sdk-types.js"; import { InMemoryAgentTimelineStore } from "./agent-timeline-store.js"; describe("InMemoryAgentTimelineStore", () => { + it("resets stale forward cursors to complete available turns", () => { + const store = new InMemoryAgentTimelineStore(); + store.initialize("agent", { epoch: "current" }); + for (let index = 0; index < 60; index++) + store.append( + "agent", + { + type: "tool_call", + callId: `call-${index}`, + name: "shell", + status: "completed", + error: null, + detail: { type: "unknown", input: null, output: null }, + }, + { turnId: "run" }, + ); + const page = store.fetch("agent", { + direction: "after", + cursor: { epoch: "old", seq: 10 }, + limit: 40, + wholeTurns: true, + }); + expect(page.rows).toHaveLength(60); + expect(page).toMatchObject({ + reset: true, + staleCursor: true, + startSeq: 1, + endSeq: 60, + hasOlder: false, + hasNewer: false, + }); + }); + it("clamps an overshooting before cursor into the bounded tail window", () => { const store = new InMemoryAgentTimelineStore(); store.initialize("agent-1", { @@ -217,31 +250,35 @@ it("includes transitive tool updates in a contiguous projected tail", () => { expect(tail).toMatchObject({ startSeq: 1, endSeq: 6, hasOlder: false }); }); -it("serves tail 200 from 100,000 retained rows without stalling the loop", async () => { - const store = new InMemoryAgentTimelineStore(); - store.initialize("large"); - for (let index = 0; index < 100_000; index++) { - store.append("large", { type: "user_message", text: String(index) }); - } - // Generation and its GC are outside the measured request window. - await new Promise((resolve) => setImmediate(resolve)); - const started = performance.now(); - const probe = new Promise((resolve) => - setImmediate(() => resolve(performance.now() - started)), - ); - let page = store.fetch("large", { limit: 200 }); - for (let repeat = 1; repeat < 8; repeat++) page = store.fetch("large", { limit: 200 }); - const duration = performance.now() - started; - const loopGap = await probe; - console.info({ duration, loopGap }); - expect(page.rows).toHaveLength(200); - expect(page.startSeq).toBe(99_801); - expect(page.endSeq).toBe(100_000); - // CI runners can pause for scheduling/GC; the local per-request 2 ms gate - // is measured separately. Eight requests amplify the old full-history work. - expect(duration).toBeLessThan(50); - expect(loopGap).toBeLessThan(50); -}); +it.each([false, true])( + "serves tail 200 from 100,000 retained rows without stalling the loop (wholeTurns=%s)", + async (wholeTurns) => { + const store = new InMemoryAgentTimelineStore(); + store.initialize("large"); + for (let index = 0; index < 100_000; index++) { + store.append("large", { type: "user_message", text: String(index) }); + } + // Generation and its GC are outside the measured request window. + await new Promise((resolve) => setImmediate(resolve)); + const started = performance.now(); + const probe = new Promise((resolve) => + setImmediate(() => resolve(performance.now() - started)), + ); + let page = store.fetch("large", { limit: 200, wholeTurns }); + for (let repeat = 1; repeat < 8; repeat++) + page = store.fetch("large", { limit: 200, wholeTurns }); + const duration = performance.now() - started; + const loopGap = await probe; + console.info({ duration, loopGap }); + expect(page.rows).toHaveLength(200); + expect(page.startSeq).toBe(99_801); + expect(page.endSeq).toBe(100_000); + // CI runners can pause for scheduling/GC; the local per-request 2 ms gate + // is measured separately. Eight requests amplify the old full-history work. + expect(duration).toBeLessThan(50); + expect(loopGap).toBeLessThan(50); + }, +); it("matches the previous reprojecting selector on seeded randomized timelines", () => { let seed = 0x76aabbcc; diff --git a/packages/server/src/server/agent/agent-timeline-store.ts b/packages/server/src/server/agent/agent-timeline-store.ts index b9727e33e9..49b5013fd4 100644 --- a/packages/server/src/server/agent/agent-timeline-store.ts +++ b/packages/server/src/server/agent/agent-timeline-store.ts @@ -107,6 +107,7 @@ export class InMemoryAgentTimelineStore { direction: reset ? "tail" : direction, cursorSeq: cursor?.seq, limit: options?.limit ?? DEFAULT_TIMELINE_FETCH_LIMIT, + wholeTurns: options?.wholeTurns, }); return { epoch: state.epoch, diff --git a/packages/server/src/server/agent/providers/mock-load-test-agent.ts b/packages/server/src/server/agent/providers/mock-load-test-agent.ts index 7055030dc0..14322c6ccf 100644 --- a/packages/server/src/server/agent/providers/mock-load-test-agent.ts +++ b/packages/server/src/server/agent/providers/mock-load-test-agent.ts @@ -230,6 +230,7 @@ interface LargeAgentStreamPayloadRequest { } interface AgentStreamStressRequest { + tools: boolean; count: number; coalesced: boolean; } @@ -461,7 +462,7 @@ function parseLargeAgentStreamPayloadPrompt( function parseAgentStreamStressPrompt(prompt: AgentPromptInput): AgentStreamStressRequest | null { const text = promptToText(prompt); - const match = /emit\s+(\d+)\s+(coalesced\s+)?agent stream updates/i.exec(text); + const match = /emit\s+(\d+)\s+(coalesced\s+|tool\s+)?agent stream updates/i.exec(text); if (!match) { return null; } @@ -471,7 +472,8 @@ function parseAgentStreamStressPrompt(prompt: AgentPromptInput): AgentStreamStre } return { count: Math.min(count, 5_000), - coalesced: Boolean(match[2]), + coalesced: match[2]?.trim() === "coalesced", + tools: match[2]?.trim() === "tool", }; } @@ -1452,21 +1454,37 @@ export class MockLoadTestAgentSession implements AgentSession { this.emitTurnStarted(turn); for (let index = 0; index < stress.count; index += 1) { - this.emitTimeline( - turn.turnId, - stress.coalesced - ? { - type: "assistant_message", - text: `stress-update-${index}`, - messageId: turn.assistantMessageId, - } - : { - type: "todo", - items: [{ text: `stress-update-${index}`, completed: index % 2 === 0 }], - }, - ); + let item: AgentTimelineItem; + if (stress.tools) { + item = { + type: "tool_call", + callId: `${turn.turnId}:stress:${index}`, + name: "Bash", + status: "completed", + error: null, + detail: { type: "shell", command: `echo stress-${index}`, output: `stress-${index}` }, + }; + } else if (stress.coalesced) { + item = { + type: "assistant_message", + text: `stress-update-${index}`, + messageId: turn.assistantMessageId, + }; + } else { + item = { + type: "todo", + items: [{ text: `stress-update-${index}`, completed: index % 2 === 0 }], + }; + } + this.emitTimeline(turn.turnId, item); } + if (stress.tools) + this.emitTimeline(turn.turnId, { + type: "assistant_message", + text: `Completed ${stress.count} commands`, + messageId: turn.assistantMessageId, + }); this.activeTurn = null; const usage = { inputTokens: 1, diff --git a/packages/server/src/server/agent/test-utils/timeline-page-reference.ts b/packages/server/src/server/agent/test-utils/timeline-page-reference.ts index 8e9ab228a6..b3a51f22e5 100644 --- a/packages/server/src/server/agent/test-utils/timeline-page-reference.ts +++ b/packages/server/src/server/agent/test-utils/timeline-page-reference.ts @@ -234,7 +234,7 @@ export function selectReferenceProjectedTimelinePage(input: { // Existing selection fixtures exercise the retained owner through its public API. export function selectProjectedTimelinePage( - input: Parameters[0], + input: Parameters[0] & { wholeTurns?: boolean }, ) { const projection = new TimelineProjection(input.rows); const bounds = input.bounds ?? getTimelineBounds(input.rows) ?? { minSeq: 0, maxSeq: 0 }; diff --git a/packages/server/src/server/agent/timeline-projection.test.ts b/packages/server/src/server/agent/timeline-projection.test.ts index f2f832ffcf..d5e4c5b637 100644 --- a/packages/server/src/server/agent/timeline-projection.test.ts +++ b/packages/server/src/server/agent/timeline-projection.test.ts @@ -534,6 +534,154 @@ describe("selectProjectedTimelinePage", () => { }; } + test("whole-turn pages extend past the soft target and keep prompt jumps whole", () => { + const rows: AgentTimelineRow[] = Array.from({ length: 125 }, (_, index) => ({ + seq: index + 1, + timestamp: new Date(1000 + index).toISOString(), + turnId: ["short", "long", "latest"][Number(index >= 3) + Number(index >= 123)], + item: { + type: "tool_call", + callId: `tool-${index}`, + name: "shell", + status: "completed", + error: null, + detail: { type: "unknown", input: null, output: null }, + }, + })); + const tail = selectProjectedTimelinePage({ + rows, + direction: "tail", + limit: 40, + wholeTurns: true, + }); + expect(tail.entries.map((entry) => entry.seqStart)).toEqual( + rows.slice(3).map((row) => row.seq), + ); + expect(tail).toMatchObject({ startSeq: 4, endSeq: 125, hasOlder: true, hasNewer: false }); + const before = selectProjectedTimelinePage({ + rows, + direction: "before", + cursorSeq: 124, + limit: 40, + wholeTurns: true, + }); + expect(before.entries.map((entry) => entry.seqStart)).toEqual( + rows.slice(3, 123).map((row) => row.seq), + ); + expect(before.endSeq).toBe(123); + const older = selectProjectedTimelinePage({ + rows, + direction: "before", + cursorSeq: 4, + limit: 40, + wholeTurns: true, + }); + expect(older.entries.map((entry) => entry.seqStart)).toEqual([1, 2, 3]); + expect(older.hasOlder).toBe(false); + const jump = selectProjectedTimelinePage({ + rows, + direction: "before", + cursorSeq: 70, + limit: 40, + wholeTurns: true, + }); + expect(jump.entries.map((entry) => entry.seqStart)).toEqual( + rows.slice(3, 123).map((row) => row.seq), + ); + expect(jump).toMatchObject({ startSeq: 4, endSeq: 123, hasOlder: true, hasNewer: true }); + const nearPreviousPrompt = selectProjectedTimelinePage({ + rows, + direction: "before", + cursorSeq: 10, + limit: 40, + wholeTurns: true, + }); + expect(nearPreviousPrompt).toMatchObject({ startSeq: 1, endSeq: 123 }); + expect( + selectProjectedTimelinePage({ rows, direction: "tail", limit: 40 }).entries, + ).toHaveLength(40); + }); + + test("whole-turn pages share short runs and use the same deterministic legacy triggers", () => { + const rows: AgentTimelineRow[] = Array.from({ length: 24 }, (_, index) => ({ + seq: index + 1, + timestamp: new Date(1000 + index).toISOString(), + item: + index % 2 === 0 + ? { type: "user_message", text: `prompt-${index}` } + : { type: "assistant_message", text: `reply-${index}` }, + })); + const page = selectProjectedTimelinePage({ + rows, + direction: "tail", + limit: 7, + wholeTurns: true, + }); + expect(page.entries.map((entry) => entry.seqStart)).toEqual([17, 18, 19, 20, 21, 22, 23, 24]); + expect( + selectProjectedTimelinePage({ rows, direction: "tail", limit: 0, wholeTurns: true }).entries, + ).toHaveLength(24); + rows.push({ + ...toolRow(25, "completed"), + item: { ...toolRow(25, "completed").item, name: "heartbeat" } as AgentTimelineRow["item"], + }); + rows.push({ + seq: 26, + timestamp: new Date().toISOString(), + item: { type: "assistant_message", text: "awake" }, + }); + expect( + selectProjectedTimelinePage({ + rows, + direction: "tail", + limit: 1, + wholeTurns: true, + }).entries.map((entry) => entry.seqStart), + ).toEqual([25, 26]); + }); + + test("whole-turn tails close interleaved source coverage without changing forward catch-up", () => { + const rows: AgentTimelineRow[] = [ + { + seq: 1, + timestamp: new Date(1).toISOString(), + turnId: "first", + item: { type: "user_message", text: "go" }, + }, + { ...toolRow(2, "running"), turnId: "first" }, + { + seq: 3, + timestamp: new Date(3).toISOString(), + turnId: "second", + item: { type: "user_message", text: "next" }, + }, + { + seq: 4, + timestamp: new Date(4).toISOString(), + turnId: "second", + item: { type: "assistant_message", text: "done" }, + }, + { ...toolRow(5, "completed"), turnId: "first" }, + ]; + expect( + selectProjectedTimelinePage({ rows, direction: "tail", limit: 1, wholeTurns: true }), + ).toMatchObject({ + startSeq: 1, + endSeq: 5, + hasOlder: false, + hasNewer: false, + }); + expect( + selectProjectedTimelinePage({ + rows, + direction: "after", + cursorSeq: 2, + limit: 1, + wholeTurns: true, + }), + ).toEqual(selectProjectedTimelinePage({ rows, direction: "after", cursorSeq: 2, limit: 1 })); + }); + test("tail page returns full projected items instead of tool lifecycle deltas", () => { const rows: AgentTimelineRow[] = [ { seq: 1, timestamp: "2026-02-13T00:00:00.000Z", item: { type: "user_message", text: "go" } }, diff --git a/packages/server/src/server/agent/timeline-projection.ts b/packages/server/src/server/agent/timeline-projection.ts index 3a65f28531..8b05432545 100644 --- a/packages/server/src/server/agent/timeline-projection.ts +++ b/packages/server/src/server/agent/timeline-projection.ts @@ -1,3 +1,4 @@ +import { continuesTimelineTurn, isTimelineTurnTrigger } from "@getpaseo/protocol/timeline-turn"; import type { AgentTimelineItem, ToolCallDetail } from "./agent-sdk-types.js"; import { timelineItemIdentity } from "@getpaseo/protocol/timeline-identity"; @@ -296,6 +297,7 @@ function mergeAssistantChunks(entries: readonly WorkingEntry[]): WorkingEntry[] export type ProjectedTimelineRow = AgentTimelineRow & TimelineProjectionEntry; interface ProjectedTimelinePageOptions { + wholeTurns?: boolean; bounds: { minSeq: number; maxSeq: number }; direction: TimelineLimitDirection; cursorSeq?: number; @@ -423,7 +425,8 @@ export class TimelineProjection { private selectTail(input: ProjectedTimelinePageOptions): ProjectedTimelinePageSelection { const limit = Math.max(0, Math.floor(input.limit ?? 0)); const requestedStart = limit === 0 ? 0 : Math.max(0, this.rows.length - limit); - const start = this.spans[this.spanIndex(requestedStart)].start; + const coveredStart = this.spans[this.spanIndex(requestedStart)].start; + const start = input.wholeTurns ? this.wholeTurnWindowStart(coveredStart) : coveredStart; return { entries: this.rows.slice(start), startSeq: this.rows[start].seqStart, @@ -433,6 +436,17 @@ export class TimelineProjection { }; } + private wholeTurnWindowStart(requestedStart: number): number { + let start = requestedStart; + for (;;) { + while (start > 0 && continuesProjectedTurn(this.rows[start - 1], this.rows[start])) start--; + // Source coverage can pull in an earlier tool and therefore its entire run. + const coveredStart = this.spans[this.spanIndex(start)].start; + if (coveredStart === start) return start; + start = coveredStart; + } + } + private selectAfter(input: ProjectedTimelinePageOptions): ProjectedTimelinePageSelection { const startSeq = Math.max( input.bounds.minSeq, @@ -480,13 +494,23 @@ export class TimelineProjection { else high = middle; } const limit = Math.max(0, Math.floor(input.limit ?? 0)); - const start = limit === 0 ? 0 : Math.max(0, low - limit); + const requestedStart = limit === 0 ? 0 : Math.max(0, low - limit); + const start = input.wholeTurns ? this.wholeTurnWindowStart(requestedStart) : requestedStart; + // Choose the window before extending the right edge, so a prompt jump + // cannot lose its target when the next turn is arbitrarily large. + if (input.wholeTurns) { + while (low < this.rows.length && continuesProjectedTurn(this.rows[low - 1], this.rows[low])) + low++; + } + let selectedEnd = endSeq; + if (input.wholeTurns) + selectedEnd = low === this.rows.length ? input.bounds.maxSeq : this.rows[low].seqStart - 1; return { entries: this.rows.slice(start, low), startSeq: this.rows[start]?.seqStart ?? null, - endSeq, + endSeq: selectedEnd, hasOlder: start > 0, - hasNewer: endSeq < input.bounds.maxSeq, + hasNewer: selectedEnd < input.bounds.maxSeq, }; } return { entries: [], startSeq: null, endSeq: null, hasOlder: false, hasNewer: true }; @@ -675,6 +699,13 @@ function selectProjectedEntriesAfter(input: { }; } +function continuesProjectedTurn( + previous: TimelineProjectionEntry, + next: TimelineProjectionEntry, +): boolean { + return continuesTimelineTurn(previous.turnId, next.turnId, isTimelineTurnTrigger(next.item)); +} + /** * Apply a projected-count limit to a flat AgentTimelineItem[] without seq metadata. * Used by callers that only have items in hand (e.g. MCP tools reading diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index 9d25328079..3e78982793 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -7805,6 +7805,7 @@ export class Session { direction, cursor, limit: msg.limit, + wholeTurns: msg.wholeTurns, }); const selectedTimeline = { timeline: fetchedControlTimeline, diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index 4473a4004d..dfa324315c 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -2062,6 +2062,7 @@ export class VoiceAssistantWebSocketServer { providerSubagents: true, // COMPAT(projectedSubagentTimeline): added after v0.8.0, remove gates after 2027-03-14; retain advertisement. projectedSubagentTimeline: true, + wholeTurnTimeline: true, // COMPAT(providerSubagentNesting): added in v0.7, remove gate after 2027-03-04. providerSubagentNesting: true, // COMPAT(workspacePinning): added in v0.1.107, remove gate after 2027-01-12. From 26ee20b371d9e360f03fd9ca2cce8d1a3f9e2635 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Tue, 27 Oct 2026 14:10:54 +0700 Subject: [PATCH 051/173] fix(ci): hoist expo-module-scripts so root overrides reach its Expo peers (#7998) `npm audit signatures` in the quality job fails on some runners with EMISSINGSIGNATUREKEY for @react-native/babel-preset@0.88.0. Nothing in the repo uses React Native 0.88: the package came from a second Expo SDK that npm placed under packages/expo-two-way-audio/node_modules because expo-module-scripts was declared there. Root `overrides` are not applied to packages nested under a workspace, so jest-expo's `expo@*` peer resolved to the latest SDK and pulled 200+ duplicate packages into the lockfile. The failure itself is a CDN cache problem: one Cloudflare edge (ORD, which serves GitHub runners in Azure northcentralus) cached the attestations document for that version seconds after publish, before the publish attestation existed, and keeps serving the provenance-only document for a year. Every quality job that lands in that region fails; every other region passes. The audit code path checks the registry signature before attestations, so the key list is fine and reruns only succeed by landing elsewhere. Declaring expo-module-scripts in the root devDependencies puts it under the overrides, which removes the nested SDK and the poisoned URL from the lockfile. The module's tsconfig points its typeRoots at the hoisted copy; its scripts resolve `expo-module` from the root `.bin`. Closes #7730 --- docs/development.md | 33 + package-lock.json | 6381 ++++++++------------- package.json | 1 + packages/expo-two-way-audio/package.json | 1 - packages/expo-two-way-audio/tsconfig.json | 2 +- 5 files changed, 2355 insertions(+), 4063 deletions(-) diff --git a/docs/development.md b/docs/development.md index 7eb92375ab..d45ec589fc 100644 --- a/docs/development.md +++ b/docs/development.md @@ -542,6 +542,39 @@ patch every build the consumers use: Metro resolves the `react-native` field of (`src/*.ts` for `react-native-svg`), while Node and Vitest resolve `main`/`module` (`lib/commonjs`, `lib/module`). Patching only `lib/` leaves the app bundle unfixed. +## Dependency overrides and workspace tooling + +Root `package.json` `overrides` pin one Expo SDK across the tree (`expo`, `expo-router`, +`react-native`, …). npm does not apply those overrides to packages it places under a +workspace's own `node_modules`. When `expo-module-scripts` was declared in +`packages/expo-two-way-audio`, npm nested it there and its `jest-expo` peer `expo@*` resolved to +a second, newer Expo SDK and React Native: 200+ duplicate packages nothing imported (#7730). +Declare tooling that peer-depends on `expo` or `react-native` in the root `devDependencies`, +where the overrides apply; workspace scripts still find the binary through the root +`node_modules/.bin`. + +## Dependency signature audit + +The `quality` CI job runs `npm audit signatures`. It verifies every lockfile package's registry +signature and, for packages published with provenance, fetches +`/-/npm/v1/attestations/@` from the registry. Cloudflare caches that document +for a year. An edge that cached it in the seconds before the registry attached the publish +attestation keeps serving a document with only the provenance bundle, and npm fails with: + +``` +npm error code EMISSINGSIGNATUREKEY +npm error @ has attestations but no corresponding public key(s) can be found +``` + +The same package's registry signature verified a moment earlier with the same keys, so the +key list is intact. The failure names one package, repeats only for that package, and depends +on the Azure region the runner landed in, because each region maps to one Cloudflare colo. A +rerun passes only by landing elsewhere. + +To confirm, fetch the URL from several runners and compare `content-length`, the `cf-ray` colo +suffix, and the number of `attestations` entries (#7730 has the probe). To fix, remove or +replace that version in the lockfile and report the URL to npm so they purge it. + ## ACP provider catalog versions The in-app ACP provider catalog pins package-runner entries (`npx`, `npm exec`, diff --git a/package-lock.json b/package-lock.json index 847bd24eb7..ce261ea94d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -30,6 +30,7 @@ "concurrently": "^9.2.1", "cross-env": "^10.1.0", "electron": "44.2.0", + "expo-module-scripts": "^5.0.8", "get-port-cli": "^3.0.0", "js-yaml": "^4.1.1", "knip": "^5.82.1", @@ -980,7 +981,7 @@ "version": "7.8.4", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.8.0" @@ -993,7 +994,7 @@ "version": "7.8.3", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz", "integrity": "sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.8.0" @@ -1006,7 +1007,7 @@ "version": "7.12.13", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz", "integrity": "sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.12.13" @@ -1019,7 +1020,7 @@ "version": "7.14.5", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-static-block/-/plugin-syntax-class-static-block-7.14.5.tgz", "integrity": "sha512-b+YyPmr6ldyNnM6sqYeMWE+bgJcJpO6yS4QD7ymxgH34GBPNDM/THBh8iunyvKIZztiwLH4CJZ0RxTk9emgpjw==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.14.5" @@ -1108,7 +1109,7 @@ "version": "7.28.6", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-attributes/-/plugin-syntax-import-attributes-7.28.6.tgz", "integrity": "sha512-jiLC0ma9XkQT3TKJ9uYvlakm66Pamywo+qwL+oL8HJOvc6TWdZXVfhqJr8CCzbSGUAbDOzlGHJC1U+vRfLQDvw==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.28.6" @@ -1124,7 +1125,7 @@ "version": "7.10.4", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz", "integrity": "sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.10.4" @@ -1137,7 +1138,7 @@ "version": "7.8.3", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz", "integrity": "sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.8.0" @@ -1165,7 +1166,7 @@ "version": "7.10.4", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz", "integrity": "sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.10.4" @@ -1190,7 +1191,7 @@ "version": "7.10.4", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz", "integrity": "sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.10.4" @@ -1203,7 +1204,7 @@ "version": "7.8.3", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz", "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.8.0" @@ -1216,7 +1217,7 @@ "version": "7.8.3", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz", "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.8.0" @@ -1241,7 +1242,7 @@ "version": "7.14.5", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-private-property-in-object/-/plugin-syntax-private-property-in-object-7.14.5.tgz", "integrity": "sha512-0wVnp9dxJ72ZUJDV27ZfbSj6iHLoytYZmh3rFcxNnvsJF3ktkzLDZPy/mA17HGsaQT3/DQsWYX1f1QGWkCoVUg==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.14.5" @@ -1257,7 +1258,7 @@ "version": "7.14.5", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.14.5.tgz", "integrity": "sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.14.5" @@ -2510,6 +2511,14 @@ "node": ">=6.9.0" } }, + "node_modules/@bcoe/v8-coverage": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz", + "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", + "devOptional": true, + "license": "MIT", + "peer": true + }, "node_modules/@blazediff/core": { "version": "1.9.1", "resolved": "https://registry.npmjs.org/@blazediff/core/-/core-1.9.1.tgz", @@ -2884,6 +2893,17 @@ "react": ">=16.8.0" } }, + "node_modules/@dual-bundle/import-meta-resolve": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@dual-bundle/import-meta-resolve/-/import-meta-resolve-4.2.1.tgz", + "integrity": "sha512-id+7YRUgoUX6CgV0DtuhirQWodeeA7Lf4i2x71JS/vtA5pRb/hIGWlw+G6MeXvsM+MXrz0VAydTGElX1rAfgPg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/JounQin" + } + }, "node_modules/@egjs/hammerjs": { "version": "2.0.17", "resolved": "https://registry.npmjs.org/@egjs/hammerjs/-/hammerjs-2.0.17.tgz", @@ -5537,14 +5557,6 @@ "react-native": "*" } }, - "node_modules/@expo/log-box-utils": { - "version": "58.0.2", - "resolved": "https://registry.npmjs.org/@expo/log-box-utils/-/log-box-utils-58.0.2.tgz", - "integrity": "sha512-My8Lwe9FU/yDwwzqwi5LN2rzzDcJqIAZKrD9f0XHZEKz/FQnWJYdt1rsV7+RwqMGeGq2XsxTCVT1ggTCOvumxw==", - "dev": true, - "license": "MIT", - "peer": true - }, "node_modules/@expo/logger": { "version": "1.0.221", "resolved": "https://registry.npmjs.org/@expo/logger/-/logger-1.0.221.tgz", @@ -5899,36 +5911,6 @@ "node": "^20.19.4 || ^22.13.0 || ^24.3.0 || >= 25.0.0" } }, - "node_modules/@expo/modules-macros-win32-arm64": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@expo/modules-macros-win32-arm64/-/modules-macros-win32-arm64-0.20.0.tgz", - "integrity": "sha512-7B57gc7+TeygPcK8fLYlEhJbbvaPh+JBzex11YIYZrSzbFhz7Q+Z37fSdAfp4EsfCswJNcX0S6wpkgSlVNefVw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "peer": true - }, - "node_modules/@expo/modules-macros-win32-x64": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@expo/modules-macros-win32-x64/-/modules-macros-win32-x64-0.20.0.tgz", - "integrity": "sha512-BM5a2U2tCyHzmtiSEY70KPsts82Mfy1bHSZ7AUbg6z9LcnxuThxJlcH85/SV5eFbhrPfgDBAG/WAncyZCvKvyA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "peer": true - }, "node_modules/@expo/multipart-body-parser": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/@expo/multipart-body-parser/-/multipart-body-parser-2.0.0.tgz", @@ -6216,14 +6198,6 @@ "node-forge": "^1.2.1" } }, - "node_modules/@expo/platforms": { - "version": "58.0.1", - "resolved": "https://registry.npmjs.org/@expo/platforms/-/platforms-58.0.1.tgz", - "integrity": "sha512-KtLrtAvpShq16l9lTxd2fZSjULxcGxXrJTHA31iUVqrc+Af7aTAJW4ZB3yQBgi/w+kSb6BB/CG9RXI0ohbMm6g==", - "dev": true, - "license": "MIT", - "peer": true - }, "node_modules/@expo/plist": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/@expo/plist/-/plist-0.2.0.tgz", @@ -7569,7 +7543,7 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", - "dev": true, + "devOptional": true, "license": "ISC", "dependencies": { "camelcase": "^5.3.1", @@ -7586,7 +7560,7 @@ "version": "5.3.1", "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=6" @@ -7596,7 +7570,7 @@ "version": "4.1.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "locate-path": "^5.0.0", @@ -7610,7 +7584,7 @@ "version": "3.14.2", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.2.tgz", "integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "argparse": "^1.0.7", @@ -7624,7 +7598,7 @@ "version": "5.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "p-locate": "^4.1.0" @@ -7637,7 +7611,7 @@ "version": "2.3.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "p-try": "^2.0.0" @@ -7653,7 +7627,7 @@ "version": "4.1.0", "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "p-limit": "^2.2.0" @@ -7666,7 +7640,7 @@ "version": "0.1.3", "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz", "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=8" @@ -7676,7 +7650,7 @@ "version": "29.7.0", "resolved": "https://registry.npmjs.org/@jest/console/-/console-29.7.0.tgz", "integrity": "sha512-5Ni4CU7XHQi32IJ398EEP4RrB8eV09sXP2ROqD4bksHrnTree52PsxvX8tpL8LvTZ3pFzXyPbNQReSN41CAhOg==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@jest/types": "^29.6.3", @@ -7694,12 +7668,72 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=8" } }, + "node_modules/@jest/core": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/core/-/core-29.7.0.tgz", + "integrity": "sha512-n7aeXWKMnGtDA48y8TLWJPJmLmmZ642Ceo78cYWEpiD7FzDgmNDV/GCVRorPABdXLJZ/9wzzgZAlHjXjxDHGsg==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@jest/console": "^29.7.0", + "@jest/reporters": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "ansi-escapes": "^4.2.1", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "exit": "^0.1.2", + "graceful-fs": "^4.2.9", + "jest-changed-files": "^29.7.0", + "jest-config": "^29.7.0", + "jest-haste-map": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-regex-util": "^29.6.3", + "jest-resolve": "^29.7.0", + "jest-resolve-dependencies": "^29.7.0", + "jest-runner": "^29.7.0", + "jest-runtime": "^29.7.0", + "jest-snapshot": "^29.7.0", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "jest-watcher": "^29.7.0", + "micromatch": "^4.0.4", + "pretty-format": "^29.7.0", + "slash": "^3.0.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/@jest/core/node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, "node_modules/@jest/create-cache-key-function": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/@jest/create-cache-key-function/-/create-cache-key-function-29.7.0.tgz", @@ -7714,10 +7748,10 @@ } }, "node_modules/@jest/diff-sequences": { - "version": "30.4.0", - "resolved": "https://registry.npmjs.org/@jest/diff-sequences/-/diff-sequences-30.4.0.tgz", - "integrity": "sha512-zOpzlfUs45l6u7jm39qr87JCHUDsaeCtvL+kQe/Vn9jSnRB4/5IPXISm0h9I1vZW/o00Kn4UTJ2MOlhnUGwv3g==", - "dev": true, + "version": "30.5.0", + "resolved": "https://registry.npmjs.org/@jest/diff-sequences/-/diff-sequences-30.5.0.tgz", + "integrity": "sha512-OsqBjHXCn8cadasoAZBP6nWYvMsRhpMzGXTpxJ5aO04NlbdhIz+FVe3q49l0AwVhsz/cEmIpBes6gAFl1/dWQg==", + "devOptional": true, "license": "MIT", "engines": { "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" @@ -7727,7 +7761,7 @@ "version": "29.7.0", "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-29.7.0.tgz", "integrity": "sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@jest/fake-timers": "^29.7.0", @@ -7743,7 +7777,7 @@ "version": "29.7.0", "resolved": "https://registry.npmjs.org/@jest/expect/-/expect-29.7.0.tgz", "integrity": "sha512-8uMeAMycttpva3P1lBHB8VciS9V0XAr3GymPpipdyQXbBcuhkLQOSe8E/p92RyAdToS6ZD1tFkX+CkhoECE0dQ==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "expect": "^29.7.0", @@ -7757,7 +7791,7 @@ "version": "29.7.0", "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.7.0.tgz", "integrity": "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "jest-get-type": "^29.6.3" @@ -7770,7 +7804,7 @@ "version": "29.7.0", "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-29.7.0.tgz", "integrity": "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@jest/types": "^29.6.3", @@ -7785,10 +7819,10 @@ } }, "node_modules/@jest/get-type": { - "version": "30.1.0", - "resolved": "https://registry.npmjs.org/@jest/get-type/-/get-type-30.1.0.tgz", - "integrity": "sha512-eMbZE2hUnx1WV0pmURZY9XoXPkUYjpc55mb0CrhtdWLtzMQPFvu/rZkTLZFTsdaVQa+Tr4eWAteqcUzoawq/uA==", - "dev": true, + "version": "30.5.0", + "resolved": "https://registry.npmjs.org/@jest/get-type/-/get-type-30.5.0.tgz", + "integrity": "sha512-9/2VUPitAjmBzbvDvqrxmvB7BzWsBW0WmkkojX1ODuxX1NLGxx9gfaZpHB0z8DtJ9uhGNmZG/VXBhf8uO0OV8Q==", + "devOptional": true, "license": "MIT", "engines": { "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" @@ -7798,7 +7832,7 @@ "version": "29.7.0", "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-29.7.0.tgz", "integrity": "sha512-mpiz3dutLbkW2MNFubUGUEVLkTGiqW6yLVTA+JbP6fI6J5iL9Y0Nlg8k95pcF8ctKwCS7WVxteBs29hhfAotzQ==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@jest/environment": "^29.7.0", @@ -7810,6 +7844,171 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/@jest/react-is-18": { + "name": "react-is", + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", + "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/@jest/react-is-19": { + "name": "react-is", + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.3.1.tgz", + "integrity": "sha512-RRieF6IyxQBkcK6pP8xOHprLTPW6QjRkbGdImtqNme+/hYVwCZkLQLdlZGOhUqXwkS9IEynaGvPJtv6XB/cz0Q==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/@jest/reporters": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-29.7.0.tgz", + "integrity": "sha512-DApq0KJbJOEzAFYjHADNNxAE3KbhxQB1y5Kplb5Waqw6zVbuWatSnMjE5gs8FUgEPmNsnZA3NCWl9NG0ia04Pg==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@bcoe/v8-coverage": "^0.2.3", + "@jest/console": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@jridgewell/trace-mapping": "^0.3.18", + "@types/node": "*", + "chalk": "^4.0.0", + "collect-v8-coverage": "^1.0.0", + "exit": "^0.1.2", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "istanbul-lib-coverage": "^3.0.0", + "istanbul-lib-instrument": "^6.0.0", + "istanbul-lib-report": "^3.0.0", + "istanbul-lib-source-maps": "^4.0.0", + "istanbul-reports": "^3.1.3", + "jest-message-util": "^29.7.0", + "jest-util": "^29.7.0", + "jest-worker": "^29.7.0", + "slash": "^3.0.0", + "string-length": "^4.0.1", + "strip-ansi": "^6.0.0", + "v8-to-istanbul": "^9.0.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/@jest/reporters/node_modules/brace-expansion": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/@jest/reporters/node_modules/char-regex": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz", + "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=10" + } + }, + "node_modules/@jest/reporters/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "devOptional": true, + "license": "ISC", + "peer": true, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@jest/reporters/node_modules/istanbul-lib-instrument": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-6.0.3.tgz", + "integrity": "sha512-Vtgk7L/R2JHyyGW07spoFlB8/lpjiOLTjMdms6AFMraYt3BaJauod/NGrfnVG/y4Ix1JEuMRPDPEj2ua+zz1/Q==", + "devOptional": true, + "license": "BSD-3-Clause", + "peer": true, + "dependencies": { + "@babel/core": "^7.23.9", + "@babel/parser": "^7.23.9", + "@istanbuljs/schema": "^0.1.3", + "istanbul-lib-coverage": "^3.2.0", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@jest/reporters/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "devOptional": true, + "license": "ISC", + "peer": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/@jest/reporters/node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/reporters/node_modules/string-length": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz", + "integrity": "sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "char-regex": "^1.0.2", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/@jest/schemas": { "version": "29.6.3", "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz", @@ -7822,11 +8021,27 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/@jest/source-map": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-29.6.3.tgz", + "integrity": "sha512-MHjT95QuipcPrpLM+8JMSzFx6eHp5Bm+4XeFDJlwsvVBjmKNiIAvasGK2fxz2WbGRlnvqehFbh07MMa7n3YJnw==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.18", + "callsites": "^3.0.0", + "graceful-fs": "^4.2.9" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, "node_modules/@jest/test-result": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-29.7.0.tgz", "integrity": "sha512-Fdx+tv6x1zlkJPcWXmMDAG2HBnaR9XPSd5aDWQVsfrZmLVT3lU1cwyxLgRmXR9yrq4NBoEm9BMsfgFzTQAbJYA==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@jest/console": "^29.7.0", @@ -7838,11 +8053,39 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/@jest/test-sequencer": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-29.7.0.tgz", + "integrity": "sha512-GQwJ5WZVrKnOJuiYiAF52UNUJXgTZx1NHjFSEB0qEMmSZKAkdMoIzw/Cj6x6NF4AvV23AUqDpFzQkN/eYCYTxw==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@jest/test-result": "^29.7.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.7.0", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/test-sequencer/node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, "node_modules/@jest/transform": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-29.7.0.tgz", "integrity": "sha512-ok/BTPFzFKVMwO5eOHRrvnBVHdRy9IrsrW1GpMaQ9MCnilNLXQKmAX8s1YXDFaai9xJpac2ySzV0YeRRECr2Vw==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/core": "^7.11.6", @@ -7869,14 +8112,14 @@ "version": "3.0.7", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", - "dev": true, + "devOptional": true, "license": "ISC" }, "node_modules/@jest/transform/node_modules/slash": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=8" @@ -7886,7 +8129,7 @@ "version": "4.0.2", "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-4.0.2.tgz", "integrity": "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg==", - "dev": true, + "devOptional": true, "license": "ISC", "dependencies": { "imurmurhash": "^0.1.4", @@ -8892,150 +9135,6 @@ "node": ">=12.4.0" } }, - "node_modules/@noxcturnal/noxcturnal-darwin-arm64": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/@noxcturnal/noxcturnal-darwin-arm64/-/noxcturnal-darwin-arm64-0.1.5.tgz", - "integrity": "sha512-hQgDaWxKYln83Uk1Hh4Liju9AvGoYh4aLd4A1ou3lGn5hxzhW2uO+z3mERtWk6BMGVazvi/yUXtp9x3IlaWyhA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "peer": true, - "engines": { - "node": ">=18" - } - }, - "node_modules/@noxcturnal/noxcturnal-darwin-x64": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/@noxcturnal/noxcturnal-darwin-x64/-/noxcturnal-darwin-x64-0.1.5.tgz", - "integrity": "sha512-I57zR8QF7Xam+4nGD5UoIODsw0VjkVyn51iDBL3CMaDR5Lh1OxXwKZMYKtv3CtQl+RSDsMfmXBEqGYLE8lIPHg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "peer": true, - "engines": { - "node": ">=18" - } - }, - "node_modules/@noxcturnal/noxcturnal-linux-arm64-gnu": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/@noxcturnal/noxcturnal-linux-arm64-gnu/-/noxcturnal-linux-arm64-gnu-0.1.5.tgz", - "integrity": "sha512-gVH4XJPh8RdrdjjlU0dKeielQt/FXfvqhr8IEWEf3VeNtQs8l2rPzFPdqS0uwLWQYHLBGgB0LkuOil1KKYx1gQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "peer": true, - "engines": { - "node": ">=18" - } - }, - "node_modules/@noxcturnal/noxcturnal-linux-arm64-musl": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/@noxcturnal/noxcturnal-linux-arm64-musl/-/noxcturnal-linux-arm64-musl-0.1.5.tgz", - "integrity": "sha512-rzQ075fcHZ+ebsELussRjnW8WBMy1RuLdS8wSqBGhdVlPR7/NaSyoWkNxnVDT8sEO26xjqGoW/o/08ghBzr/zA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "peer": true, - "engines": { - "node": ">=18" - } - }, - "node_modules/@noxcturnal/noxcturnal-linux-x64-gnu": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/@noxcturnal/noxcturnal-linux-x64-gnu/-/noxcturnal-linux-x64-gnu-0.1.5.tgz", - "integrity": "sha512-X5O0lXMrv8HGOGoXDB1PG0Hjt7Rl+MJA+seR2NecQvUAAw2gzDvF/unCV5sqTAVeHfXhBHEFGkLenHZSD44efg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "peer": true, - "engines": { - "node": ">=18" - } - }, - "node_modules/@noxcturnal/noxcturnal-linux-x64-musl": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/@noxcturnal/noxcturnal-linux-x64-musl/-/noxcturnal-linux-x64-musl-0.1.5.tgz", - "integrity": "sha512-fkQIQHRxqldNXVmjxfeCvGOiLhLU9SLBw1As02pMA2xjyiZfiXcUn4SUrZ92ciGnyCS8/XMbx+nZSxgEc3qDPw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "peer": true, - "engines": { - "node": ">=18" - } - }, - "node_modules/@noxcturnal/noxcturnal-win32-arm64-msvc": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/@noxcturnal/noxcturnal-win32-arm64-msvc/-/noxcturnal-win32-arm64-msvc-0.1.5.tgz", - "integrity": "sha512-baeH5m/vM1nf0J2UkW8cfgiVogpM0gRO9b4PZWknXQPbv5+k+0N5sGOYl/UAO2q72qYb3Xbiu7eD8c4A2kR2SA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "peer": true, - "engines": { - "node": ">=18" - } - }, - "node_modules/@noxcturnal/noxcturnal-win32-x64-msvc": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/@noxcturnal/noxcturnal-win32-x64-msvc/-/noxcturnal-win32-x64-msvc-0.1.5.tgz", - "integrity": "sha512-2faDMzom8pCG/s/uR4Czh1atz4KohI85AaSmA2vtAuVnCq+nLL4Viys3A5vUlNz9MNBmTNFxzXyF2Z5HtfxXLg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "peer": true, - "engines": { - "node": ">=18" - } - }, "node_modules/@npmcli/agent": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/@npmcli/agent/-/agent-3.0.0.tgz", @@ -9387,17 +9486,6 @@ "node": ">=8.0.0" } }, - "node_modules/@oxc-project/types": { - "version": "0.154.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.154.0.tgz", - "integrity": "sha512-KYOUGQFlLWR+s4QMV2Q9ko38TZm7EdO87Qm7rvZLqk/webse/cDjtyxKhg/47l0byCbs/k46LT8qc4PKjAikzA==", - "dev": true, - "license": "MIT", - "peer": true, - "funding": { - "url": "https://github.com/sponsors/oxc-project" - } - }, "node_modules/@oxc-resolver/binding-android-arm-eabi": { "version": "11.19.1", "resolved": "https://registry.npmjs.org/@oxc-resolver/binding-android-arm-eabi/-/binding-android-arm-eabi-11.19.1.tgz", @@ -10429,13 +10517,13 @@ } }, "node_modules/@pkgr/core": { - "version": "0.2.9", - "resolved": "https://registry.npmjs.org/@pkgr/core/-/core-0.2.9.tgz", - "integrity": "sha512-QNqXyfVS2wm9hweSYD2O7F0G06uurj9kZ96TRQE5Y9hU7+tgdZwIkbAKc5Ocy1HxEY2kuDQa6cQ1WRs/O5LFKA==", + "version": "0.3.6", + "resolved": "https://registry.npmjs.org/@pkgr/core/-/core-0.3.6.tgz", + "integrity": "sha512-SEeaJLb3qBNF/OaXnaR1NmmBbFYk1zC0ZH/52fATcRPLFg/p791YrcyFFy44Bo9sLaGuSuLp5Q6axbb/O+v/RA==", "dev": true, "license": "MIT", "engines": { - "node": "^12.20.0 || ^14.18.0 || >=16.0.0" + "node": "^14.18.0 || >=16.0.0" }, "funding": { "url": "https://opencollective.com/pkgr" @@ -11020,17 +11108,6 @@ "react-native": ">=0.57" } }, - "node_modules/@react-native/asset-utils": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/@react-native/asset-utils/-/asset-utils-0.88.0.tgz", - "integrity": "sha512-Bj1DxQt5f4OrjdlgSVkZT37Z3hx5hUIN5AUDSqL/e99vgtTcqj5vnm067epZL1EF/QiqsniZO8Q1GSkItOakDg==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, "node_modules/@react-native/assets-registry": { "version": "0.86.3", "resolved": "https://registry.npmjs.org/@react-native/assets-registry/-/assets-registry-0.86.3.tgz", @@ -12073,7 +12150,7 @@ "version": "3.0.1", "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-3.0.1.tgz", "integrity": "sha512-K3mCHKQ9sVh8o1C9cxkwxaOmXoAMlDxC1mYyHrjqOWEcBjYr76t96zL2zlj5dUGZ3HSw240X1qgH3Mjf1yJWpQ==", - "dev": true, + "devOptional": true, "license": "BSD-3-Clause", "dependencies": { "type-detect": "4.0.8" @@ -12083,7 +12160,7 @@ "version": "10.3.0", "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-10.3.0.tgz", "integrity": "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA==", - "dev": true, + "devOptional": true, "license": "BSD-3-Clause", "dependencies": { "@sinonjs/commons": "^3.0.0" @@ -12556,6 +12633,151 @@ } } }, + "node_modules/@testing-library/react-native": { + "version": "13.3.3", + "resolved": "https://registry.npmjs.org/@testing-library/react-native/-/react-native-13.3.3.tgz", + "integrity": "sha512-k6Mjsd9dbZgvY4Bl7P1NIpePQNi+dfYtlJ5voi9KQlynxSyQkfOgJmYGCYmw/aSgH/rUcFvG8u5gd4npzgRDyg==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "jest-matcher-utils": "^30.0.5", + "picocolors": "^1.1.1", + "pretty-format": "^30.0.5", + "redent": "^3.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "jest": ">=29.0.0", + "react": ">=18.2.0", + "react-native": ">=0.71", + "react-test-renderer": ">=18.2.0" + }, + "peerDependenciesMeta": { + "jest": { + "optional": true + } + } + }, + "node_modules/@testing-library/react-native/node_modules/@jest/schemas": { + "version": "30.5.0", + "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-30.5.0.tgz", + "integrity": "sha512-/hunigyNpc4RCjC0VaW3f5RCUZVM2+WQ65qP7z083Gmvac7or2LI50XVNOtE4YPgBpV0yxYiAgorAPGniCoJmg==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@sinclair/typebox": "^0.34.0" + }, + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/@testing-library/react-native/node_modules/@sinclair/typebox": { + "version": "0.34.52", + "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.34.52.tgz", + "integrity": "sha512-XiMQh7qqVlxZzcVD+kkGMNGMzcTrDMLWI7S4x7z1MkCkbDPrekpZXEUK0eZqZFMuHQg2a2DZOcDIh9o5v3Gonw==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/@testing-library/react-native/node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "devOptional": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/@testing-library/react-native/node_modules/indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", + "devOptional": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@testing-library/react-native/node_modules/jest-diff": { + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-30.5.2.tgz", + "integrity": "sha512-rBtHnI6BWTiWj3lM7fOLVfChx7R9B0u9VV3PRHawKs79x6ZjW1QoSrKenaigNGWlvhtoi2BqvDbABDie+Os3xQ==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@jest/diff-sequences": "30.5.0", + "@jest/get-type": "30.5.0", + "chalk": "^4.1.2", + "pretty-format": "30.5.1" + }, + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/@testing-library/react-native/node_modules/jest-matcher-utils": { + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-30.5.2.tgz", + "integrity": "sha512-lFkB365PTIHOhPzwrb9T6gvlDnPpOZ7/c3ewOKKB7bzztqjVrtlyRL2MkyfJXpyY2u2SKw001JKrTx14fBUFcQ==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@jest/get-type": "30.5.0", + "chalk": "^4.1.2", + "jest-diff": "30.5.2", + "pretty-format": "30.5.1" + }, + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/@testing-library/react-native/node_modules/pretty-format": { + "version": "30.5.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-30.5.1.tgz", + "integrity": "sha512-byhRAPguVKMQIj4kjJwJ5lAskVhfuiSdiYl/aLTWpgkGEmic2jYhJh1yE9ih8Ox44Xg9ccCT11/S6QrzSJuNrg==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@jest/react-is-18": "npm:react-is@^18.3.1", + "@jest/react-is-19": "npm:react-is@^19.2.5", + "@jest/schemas": "30.5.0", + "ansi-styles": "^5.2.0" + }, + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/@testing-library/react-native/node_modules/redent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/redent/-/redent-3.0.0.tgz", + "integrity": "sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "indent-string": "^4.0.0", + "strip-indent": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@testing-library/react-native/node_modules/strip-indent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-3.0.0.tgz", + "integrity": "sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "min-indent": "^1.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/@tootallnate/once": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz", @@ -12623,7 +12845,7 @@ "version": "7.20.5", "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/parser": "^7.20.7", @@ -12637,7 +12859,7 @@ "version": "7.27.0", "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz", "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/types": "^7.0.0" @@ -12647,7 +12869,7 @@ "version": "7.4.4", "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/parser": "^7.1.0", @@ -12658,7 +12880,7 @@ "version": "7.28.0", "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz", "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/types": "^7.28.2" @@ -13065,7 +13287,7 @@ "version": "4.1.9", "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.9.tgz", "integrity": "sha512-olP3sd1qOEe5dXTSaFvQG+02VdRXcdytWLAZsAq1PecU8uqQAhkrnbli7DagjtXKW/Bl7YJbUsa8MPcuc8LHEQ==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@types/node": "*" @@ -13373,7 +13595,7 @@ "version": "2.0.3", "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.3.tgz", "integrity": "sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw==", - "dev": true, + "devOptional": true, "license": "MIT" }, "node_modules/@types/tough-cookie": { @@ -13443,6 +13665,288 @@ "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==", "license": "MIT" }, + "node_modules/@typescript-eslint/eslint-plugin": { + "version": "8.72.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.72.1.tgz", + "integrity": "sha512-5CokTWXpmbylfFabsbvHC0CAw3XLaGnoa+nFJX5FR592h/LoZsENUE6p/rg5xvkKrFEXz6pYmgI29AgXc2N3BQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/regexpp": "^4.12.2", + "@typescript-eslint/scope-manager": "8.72.1", + "@typescript-eslint/type-utils": "8.72.1", + "@typescript-eslint/utils": "8.72.1", + "@typescript-eslint/visitor-keys": "8.72.1", + "ignore": "^7.0.5", + "natural-compare": "^1.4.0", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript-eslint/parser": "^8.72.1", + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": { + "version": "7.0.14", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.14.tgz", + "integrity": "sha512-wCBiZ77u1tuWde6G/nfOtLaCTYcFDU5yCzARzK10y+rLhzYoL7a7yEemcopcc2Mzow7gZOIjnV2ym1NYmdiJOQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/@typescript-eslint/parser": { + "version": "8.72.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.72.1.tgz", + "integrity": "sha512-ZGwZP4OCfyA0AQTpEAMWz+rtX01DRhQWW5hB0ucKDEIX5U7jdmPSaMx94rQfaPAQzIYz2BimOgKOJtjfpRFQ9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/scope-manager": "8.72.1", + "@typescript-eslint/types": "8.72.1", + "@typescript-eslint/typescript-estree": "8.72.1", + "@typescript-eslint/visitor-keys": "8.72.1", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/project-service": { + "version": "8.72.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.72.1.tgz", + "integrity": "sha512-fAuVMkwdO/huI8nyo/WKnNKf6Gag93S56Rh3Ts5mGcavwSdaN8tRg1gCeIGX8PF+nzp1BjGfO4gHhGzW1J6jTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/tsconfig-utils": "^8.72.1", + "@typescript-eslint/types": "^8.72.1", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/scope-manager": { + "version": "8.72.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.72.1.tgz", + "integrity": "sha512-lC/t6eMCZZQAAKZEYGL6RDVSuFehpdmMT6h+nJIjIa6oylN/PwDgDVtEIbB7O9xFfZYtZAYLoLlDNWKJhtF+uQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.72.1", + "@typescript-eslint/visitor-keys": "8.72.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/tsconfig-utils": { + "version": "8.72.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.72.1.tgz", + "integrity": "sha512-e4D5R5vpeAEPBxT2BAzsFQL3sbwyeeeo5+aczgNSRK1V734jE7pTqaGFU+fXapWEQwnZbpFaTn32+Z8DwS6OTg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/type-utils": { + "version": "8.72.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.72.1.tgz", + "integrity": "sha512-iY2wlmyrXJmx4yxUGP3aYCFF3cA/6ShddOKmLU2dx7LnEykbAM8WThlxZEfd1NddqceF6eJmZUayxx9oKIYNlg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.72.1", + "@typescript-eslint/typescript-estree": "8.72.1", + "@typescript-eslint/utils": "8.72.1", + "debug": "^4.4.3", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/types": { + "version": "8.72.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.72.1.tgz", + "integrity": "sha512-LmE5IhQet1BWOWEXqBrVtBPsMAOQ6Nzk35d+WLh3mk4EUF33sqlfxjio1MdYeSvKSG5skactKKuixBIKXhL4Rw==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/typescript-estree": { + "version": "8.72.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.72.1.tgz", + "integrity": "sha512-DAlUoUV93hIvrtIQLwCbmZQYVZwOMhiHJrOVUUIWicFZaIYjTRqlY3I/NZevfkLmSqkNHRu2qYDcq9lrn16oOQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/project-service": "8.72.1", + "@typescript-eslint/tsconfig-utils": "8.72.1", + "@typescript-eslint/types": "8.72.1", + "@typescript-eslint/visitor-keys": "8.72.1", + "debug": "^4.4.3", + "minimatch": "^10.2.2", + "semver": "^7.7.3", + "tinyglobby": "^0.2.15", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": { + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@typescript-eslint/utils": { + "version": "8.72.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.72.1.tgz", + "integrity": "sha512-5v5liypurJBFHCBNqh/RjsymAD+VWcE0djuGY/BUqp5fC3Qn+luWDEksjuTtWjPn6i5zQlUtkZCRG/CYG0yCkA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.9.1", + "@typescript-eslint/scope-manager": "8.72.1", + "@typescript-eslint/types": "8.72.1", + "@typescript-eslint/typescript-estree": "8.72.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/visitor-keys": { + "version": "8.72.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.72.1.tgz", + "integrity": "sha512-SB8xqipSzZHUePCCLNeYxqnxq83X61/qzNhjQGbTfjxGZIeOEP7tBgWYX05Tcd6CgE02WdTJnh5b8kMZJ/+bnQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.72.1", + "eslint-visitor-keys": "^5.0.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", + "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, "node_modules/@typescript/native-preview": { "version": "7.0.0-dev.20260423.1", "resolved": "https://registry.npmjs.org/@typescript/native-preview/-/native-preview-7.0.0-dev.20260423.1.tgz", @@ -14520,7 +15024,7 @@ "version": "3.1.3", "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", - "dev": true, + "devOptional": true, "license": "ISC", "dependencies": { "normalize-path": "^3.0.0", @@ -14534,7 +15038,7 @@ "version": "2.3.1", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=8.6" @@ -15208,7 +15712,7 @@ "version": "29.7.0", "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-29.7.0.tgz", "integrity": "sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@jest/transform": "^29.7.0", @@ -15230,7 +15734,7 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=8" @@ -15250,7 +15754,7 @@ "version": "6.1.1", "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-6.1.1.tgz", "integrity": "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA==", - "dev": true, + "devOptional": true, "license": "BSD-3-Clause", "dependencies": { "@babel/helper-plugin-utils": "^7.0.0", @@ -15267,7 +15771,7 @@ "version": "29.6.3", "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-29.6.3.tgz", "integrity": "sha512-ESAc/RJvGTFEzRwOTT4+lNDk/GNHMkKbNzsvT0qKRfDyyYTskxB5rnU2njIDYVxXCBHHEI1c0YwHob3WaYujOg==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/template": "^7.3.3", @@ -15365,7 +15869,7 @@ "version": "1.2.0", "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.2.0.tgz", "integrity": "sha512-E/VlAEzRrsLEb2+dv8yp3bo4scof3l9nR4lrld+Iy5NyVqgVYUJnDAmunkhPMisRI32Qc4iRiz425d8vM++2fg==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/plugin-syntax-async-generators": "^7.8.4", @@ -15436,7 +15940,7 @@ "version": "29.6.3", "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-29.6.3.tgz", "integrity": "sha512-0B3bhxR6snWXJZtR/RliHTDPRgn1sNHOR0yVtq/IiQFyuOVjFS+wuio/R4gSNkyYmKmJB4wGZv2NZanmKmTnNA==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "babel-plugin-jest-hoist": "^29.6.3", @@ -15469,7 +15973,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "dev": true, + "devOptional": true, "license": "MIT" }, "node_modules/barcode-detector": { @@ -16103,7 +16607,7 @@ "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=6" @@ -16378,6 +16882,14 @@ "node": ">=8" } }, + "node_modules/cjs-module-lexer": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.4.3.tgz", + "integrity": "sha512-9z8TZaGM1pfswYeXrUpzPrkx8UnWYdhJclsiYMm6x/w5+nN+8Tf/LnAgfLGQCm59qAOxU8WwHEq2vNwF6i4j+Q==", + "devOptional": true, + "license": "MIT", + "peer": true + }, "node_modules/clean-stack": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-3.0.1.tgz", @@ -16508,11 +17020,23 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/co": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", + "integrity": "sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "iojs": ">= 1.0.0", + "node": ">= 0.12.0" + } + }, "node_modules/collect-v8-coverage": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.3.tgz", "integrity": "sha512-1L5aqIkwPfiodaMgQunkF1zRhNqifHBmtbbbxcr6yVxxBnliw4TDOW6NxpO8DJLgJ16OT+Y4ztZqP6p/FtXnAw==", - "dev": true, + "devOptional": true, "license": "MIT" }, "node_modules/color": { @@ -16677,7 +17201,7 @@ "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", - "dev": true, + "devOptional": true, "license": "MIT" }, "node_modules/concurrently": { @@ -16876,6 +17400,29 @@ "ieee754": "^1.1.13" } }, + "node_modules/create-jest": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/create-jest/-/create-jest-29.7.0.tgz", + "integrity": "sha512-Adz2bdH0Vq3F53KEMJOoftQFutWCukm6J24wbPWRO4k1kMY7gS7ds/uoJkNuV8wDCtWWnuwGcJwpWcih+zEW1Q==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@jest/types": "^29.6.3", + "chalk": "^4.0.0", + "exit": "^0.1.2", + "graceful-fs": "^4.2.9", + "jest-config": "^29.7.0", + "jest-util": "^29.7.0", + "prompts": "^2.0.1" + }, + "bin": { + "create-jest": "bin/create-jest.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, "node_modules/create-require": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", @@ -17797,6 +18344,22 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/dedent": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.7.2.tgz", + "integrity": "sha512-WzMx3mW98SN+zn3hgemf4OzdmyNhhhKz5Ay0pUfQiMQ3e1g+xmTJWp/pKdwKVXhdSkAEGIIzqeuWrL3mV/AXbA==", + "devOptional": true, + "license": "MIT", + "peer": true, + "peerDependencies": { + "babel-plugin-macros": "^3.1.0" + }, + "peerDependenciesMeta": { + "babel-plugin-macros": { + "optional": true + } + } + }, "node_modules/deep-is": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", @@ -17964,6 +18527,17 @@ "node": ">=8" } }, + "node_modules/detect-newline": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", + "integrity": "sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, "node_modules/detect-node": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.1.0.tgz", @@ -18004,7 +18578,7 @@ "version": "29.6.3", "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz", "integrity": "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": "^14.15.0 || ^16.10.0 || >=18.0.0" @@ -18769,7 +19343,7 @@ "version": "0.13.1", "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.13.1.tgz", "integrity": "sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=12" @@ -18869,7 +19443,7 @@ "version": "1.3.4", "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.4.tgz", "integrity": "sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "is-arrayish": "^0.2.1" @@ -19189,7 +19763,6 @@ "dev": true, "license": "BSD-3-Clause", "optional": true, - "peer": true, "engines": { "node": ">=0.10.0" } @@ -19270,6 +19843,60 @@ "eslint": ">=6.0.0" } }, + "node_modules/eslint-config-prettier": { + "version": "9.1.2", + "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-9.1.2.tgz", + "integrity": "sha512-iI1f+D2ViGn+uvv5HuHVUamg8ll4tN+JRHGc6IJi4TP9Kl976C57fzPXgseXNs8v0iA8aSJpHsTWjDb9QJamGQ==", + "dev": true, + "license": "MIT", + "bin": { + "eslint-config-prettier": "bin/cli.js" + }, + "peerDependencies": { + "eslint": ">=7.0.0" + } + }, + "node_modules/eslint-config-universe": { + "version": "15.2.0", + "resolved": "https://registry.npmjs.org/eslint-config-universe/-/eslint-config-universe-15.2.0.tgz", + "integrity": "sha512-n2662q/mM+2pTFVz7ELosqhN+/nbR75Ut/4vLme40kKSHHe0oPbPMxgPqyYrASlANuSDP4aAJ71rRviDMCZTxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/eslint-plugin": "^8.59.0", + "@typescript-eslint/parser": "^8.59.0", + "eslint-config-prettier": "^9.1.0", + "eslint-plugin-import": "^2.31.0", + "eslint-plugin-n": "^17.17.0", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-prettier": "^5.2.6", + "eslint-plugin-react": "^7.37.5", + "eslint-plugin-react-hooks": "^7.0.0", + "globals": "^16.0.0" + }, + "peerDependencies": { + "eslint": ">=8.10", + "prettier": ">=3" + }, + "peerDependenciesMeta": { + "prettier": { + "optional": true + } + } + }, + "node_modules/eslint-config-universe/node_modules/globals": { + "version": "16.5.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-16.5.0.tgz", + "integrity": "sha512-c/c15i26VrJ4IRt5Z89DnIzCGDn9EcebibhAOjw5ibqEHsE1wLUgkPn9RDmNcUKyU87GeaL633nyJ+pplFR2ZQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/eslint-import-resolver-node": { "version": "0.3.9", "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.9.tgz", @@ -19547,9 +20174,9 @@ } }, "node_modules/eslint-plugin-node/node_modules/brace-expansion": { - "version": "1.1.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", - "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", "dev": true, "license": "MIT", "dependencies": { @@ -19581,14 +20208,14 @@ } }, "node_modules/eslint-plugin-prettier": { - "version": "5.5.5", - "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-5.5.5.tgz", - "integrity": "sha512-hscXkbqUZ2sPithAuLm5MXL+Wph+U7wHngPBv9OMWwlP8iaflyxpjTYZkmdgB4/vPIhemRlBEoLrH7UC1n7aUw==", + "version": "5.5.7", + "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-5.5.7.tgz", + "integrity": "sha512-WjHyn3GrFd+ZR0rzsLiM4zJZ35PZMOE0SUIxzGmnWNG0126yNfJKJzObmmkYDwHJfGlkz3PSlzyG9ez/LJntwg==", "dev": true, "license": "MIT", "dependencies": { "prettier-linter-helpers": "^1.0.1", - "synckit": "^0.11.12" + "synckit": "^0.12.3" }, "engines": { "node": "^14.18.0 || >=16.0.0" @@ -19644,6 +20271,43 @@ "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9.7" } }, + "node_modules/eslint-plugin-react-hooks": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-7.1.1.tgz", + "integrity": "sha512-f2I7Gw6JbvCexzIInuSbZpfdQ44D7iqdWX01FKLvrPgqxoE7oMj8clOfto8U6vYiz4yd5oKu39rRSVOe1zRu0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.24.4", + "@babel/parser": "^7.24.4", + "hermes-parser": "^0.25.1", + "zod": "^3.25.0 || ^4.0.0", + "zod-validation-error": "^3.5.0 || ^4.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0 || ^10.0.0" + } + }, + "node_modules/eslint-plugin-react-hooks/node_modules/hermes-estree": { + "version": "0.25.1", + "resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.25.1.tgz", + "integrity": "sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw==", + "dev": true, + "license": "MIT" + }, + "node_modules/eslint-plugin-react-hooks/node_modules/hermes-parser": { + "version": "0.25.1", + "resolved": "https://registry.npmjs.org/hermes-parser/-/hermes-parser-0.25.1.tgz", + "integrity": "sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "hermes-estree": "0.25.1" + } + }, "node_modules/eslint-plugin-react/node_modules/brace-expansion": { "version": "1.1.12", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", @@ -19841,7 +20505,7 @@ "version": "4.0.1", "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", - "dev": true, + "devOptional": true, "license": "BSD-2-Clause", "bin": { "esparse": "bin/esparse.js", @@ -19990,11 +20654,54 @@ "dev": true, "license": "MIT" }, + "node_modules/execa": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", + "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "cross-spawn": "^7.0.3", + "get-stream": "^6.0.0", + "human-signals": "^2.1.0", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.1", + "onetime": "^5.1.2", + "signal-exit": "^3.0.3", + "strip-final-newline": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/execa/node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "devOptional": true, + "license": "ISC", + "peer": true + }, + "node_modules/exit": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", + "integrity": "sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ==", + "devOptional": true, + "peer": true, + "engines": { + "node": ">= 0.8.0" + } + }, "node_modules/expect": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/expect/-/expect-29.7.0.tgz", "integrity": "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@jest/expect-utils": "^29.7.0", @@ -20246,6 +20953,131 @@ "react-native": "*" } }, + "node_modules/expo-module-scripts": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/expo-module-scripts/-/expo-module-scripts-5.0.8.tgz", + "integrity": "sha512-3YkAic3E6QGQuNEIchq6/0GGSBwR2C70AhDUF7VI7/N3THwUpeqZrX20FxHKN95/wclHs1ljrGvRX+2YTgXxiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/cli": "^7.23.4", + "@babel/plugin-transform-export-namespace-from": "^7.23.4", + "@babel/preset-env": "^7.23.8", + "@babel/preset-typescript": "^7.23.3", + "@expo/npm-proofread": "^1.0.1", + "@testing-library/react-native": "^13.2.0", + "@tsconfig/node18": "^18.2.2", + "@types/jest": "^29.2.1", + "babel-plugin-dynamic-import-node": "^2.3.3", + "babel-preset-expo": "~54.0.7", + "commander": "^12.1.0", + "eslint-config-universe": "^15.0.3", + "glob": "^13.0.0", + "jest-expo": "~54.0.13", + "jest-snapshot-prettier": "npm:prettier@^2", + "jest-watch-typeahead": "2.2.1", + "resolve-workspace-root": "^2.0.0", + "ts-jest": "~29.0.4", + "typescript": "^5.9.2" + }, + "bin": { + "expo-module": "bin/expo-module.js" + } + }, + "node_modules/expo-module-scripts/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/expo-module-scripts/node_modules/brace-expansion": { + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/expo-module-scripts/node_modules/commander": { + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", + "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/expo-module-scripts/node_modules/glob": { + "version": "13.0.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", + "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "minimatch": "^10.2.2", + "minipass": "^7.1.3", + "path-scurry": "^2.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/expo-module-scripts/node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/expo-module-scripts/node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/expo-module-scripts/node_modules/path-scurry": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", + "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/expo-modules-autolinking": { "version": "57.0.16", "resolved": "https://registry.npmjs.org/expo-modules-autolinking/-/expo-modules-autolinking-57.0.16.tgz", @@ -20303,18 +21135,6 @@ "react-native": "*" } }, - "node_modules/expo-modules-macros": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/expo-modules-macros/-/expo-modules-macros-0.20.0.tgz", - "integrity": "sha512-Ekgb5c9LQPM9CPnmDZdeWcOa1eBbCDUGrgdN5lIFNH2GWDUf9doeAOK7IqQOOVviamy37eIp5FW+N1zyrIwzoA==", - "dev": true, - "license": "MIT", - "peer": true, - "optionalDependencies": { - "@expo/modules-macros-win32-arm64": "0.20.0", - "@expo/modules-macros-win32-x64": "0.20.0" - } - }, "node_modules/expo-router": { "version": "57.0.28", "resolved": "https://registry.npmjs.org/expo-router/-/expo-router-57.0.28.tgz", @@ -20947,7 +21767,7 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", - "dev": true, + "devOptional": true, "license": "MIT" }, "node_modules/fast-levenshtein": { @@ -21293,31 +22113,6 @@ "integrity": "sha512-3PYnM29RFXwvAN6Pc/scUfkI7RwhQ/xqyLUyPNlXUp9S40zI8nup9tUSrTLSVnWGBN38FNiGWbwZOB6uR4OGdw==", "license": "MIT" }, - "node_modules/flow-estree": { - "version": "0.331.0", - "resolved": "https://registry.npmjs.org/flow-estree/-/flow-estree-0.331.0.tgz", - "integrity": "sha512-FVLYkSL/ITb/QXBEQvNWPjPooRGswuUtGOwrH+puSlMDneNkxy640+FZsk/TfKL+b7Wbw/Fg9FTUv2bMQDpj2w==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=18" - } - }, - "node_modules/flow-parser": { - "version": "0.331.0", - "resolved": "https://registry.npmjs.org/flow-parser/-/flow-parser-0.331.0.tgz", - "integrity": "sha512-vEZcHIlnKeN8JSVtYFczj8sWJfHIJOkz+YG00O/oul/Bete+t1ZhTi+O6JRRLFYvGW+yJkZ0YgL16iStnbkUqQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "flow-estree": "0.331.0" - }, - "engines": { - "node": ">=0.4.0" - } - }, "node_modules/follow-redirects": { "version": "1.15.11", "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz", @@ -21507,7 +22302,7 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", - "dev": true, + "devOptional": true, "license": "ISC" }, "node_modules/fsevents": { @@ -21629,7 +22424,7 @@ "version": "0.1.0", "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=8.0.0" @@ -21681,6 +22476,20 @@ "node": ">= 0.4" } }, + "node_modules/get-stream": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", + "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/get-symbol-description": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.1.0.tgz", @@ -22394,6 +23203,14 @@ "node": ">=12" } }, + "node_modules/html-escaper": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", + "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", + "devOptional": true, + "license": "MIT", + "peer": true + }, "node_modules/html-parse-stringify": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/html-parse-stringify/-/html-parse-stringify-3.0.1.tgz", @@ -22525,6 +23342,17 @@ "node": ">= 6" } }, + "node_modules/human-signals": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", + "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", + "devOptional": true, + "license": "Apache-2.0", + "peer": true, + "engines": { + "node": ">=10.17.0" + } + }, "node_modules/hyperlinker": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/hyperlinker/-/hyperlinker-1.0.0.tgz", @@ -22671,6 +23499,27 @@ "node": ">=4" } }, + "node_modules/import-local": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.2.0.tgz", + "integrity": "sha512-2SPlun1JUPWoM6t3F0dw0FkCF/jWY8kttcY4f599GLTSjh2OCuuhdTkJQsEcZzBqbXZGKMK2OqW1oZsjtf/gQA==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "pkg-dir": "^4.2.0", + "resolve-cwd": "^3.0.0" + }, + "bin": { + "import-local-fixture": "fixtures/cli.js" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/import-meta-resolve": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/import-meta-resolve/-/import-meta-resolve-4.2.0.tgz", @@ -22685,7 +23534,7 @@ "version": "0.1.4", "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=0.8.19" @@ -22709,7 +23558,7 @@ "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", - "dev": true, + "devOptional": true, "license": "ISC", "dependencies": { "once": "^1.3.0", @@ -22847,7 +23696,7 @@ "version": "0.2.1", "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", - "dev": true, + "devOptional": true, "license": "MIT" }, "node_modules/is-async-function": { @@ -23057,6 +23906,17 @@ "node": ">=8" } }, + "node_modules/is-generator-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz", + "integrity": "sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=6" + } + }, "node_modules/is-generator-function": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.1.2.tgz", @@ -23247,7 +24107,7 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=8" @@ -23417,7 +24277,7 @@ "version": "3.2.2", "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz", "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==", - "dev": true, + "devOptional": true, "license": "BSD-3-Clause", "engines": { "node": ">=8" @@ -23427,7 +24287,7 @@ "version": "5.2.1", "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-5.2.1.tgz", "integrity": "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg==", - "dev": true, + "devOptional": true, "license": "BSD-3-Clause", "dependencies": { "@babel/core": "^7.12.3", @@ -23444,12 +24304,101 @@ "version": "6.3.1", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "dev": true, + "devOptional": true, "license": "ISC", "bin": { "semver": "bin/semver.js" } }, + "node_modules/istanbul-lib-report": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", + "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", + "devOptional": true, + "license": "BSD-3-Clause", + "peer": true, + "dependencies": { + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^4.0.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-lib-report/node_modules/make-dir": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", + "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/istanbul-lib-report/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-source-maps": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz", + "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==", + "devOptional": true, + "license": "BSD-3-Clause", + "peer": true, + "dependencies": { + "debug": "^4.1.1", + "istanbul-lib-coverage": "^3.0.0", + "source-map": "^0.6.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-lib-source-maps/node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "devOptional": true, + "license": "BSD-3-Clause", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/istanbul-reports": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz", + "integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==", + "devOptional": true, + "license": "BSD-3-Clause", + "peer": true, + "dependencies": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/iterator.prototype": { "version": "1.1.5", "resolved": "https://registry.npmjs.org/iterator.prototype/-/iterator.prototype-1.1.5.tgz", @@ -23502,11 +24451,273 @@ "node": ">=10" } }, + "node_modules/jest": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest/-/jest-29.7.0.tgz", + "integrity": "sha512-NIy3oAFp9shda19hy4HK0HRTWKtPJmGdnvywu01nOqNC2vZg+Z+fvJDxpMQA88eb2I9EcafcdjYgsDthnYTvGw==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@jest/core": "^29.7.0", + "@jest/types": "^29.6.3", + "import-local": "^3.0.2", + "jest-cli": "^29.7.0" + }, + "bin": { + "jest": "bin/jest.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/jest-changed-files": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-29.7.0.tgz", + "integrity": "sha512-fEArFiwf1BpQ+4bXSprcDc3/x4HSzL4al2tozwVpDFpsxALjLYdyiIK4e5Vz66GQJIbXJ82+35PtysofptNX2w==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "execa": "^5.0.0", + "jest-util": "^29.7.0", + "p-limit": "^3.1.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-circus": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-29.7.0.tgz", + "integrity": "sha512-3E1nCMgipcTkCocFwM90XXQab9bS+GMsjdpmPrlelaxwD93Ad8iVEjX/vvHPdLPnFf+L40u+5+iutRdA1N9myw==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@jest/environment": "^29.7.0", + "@jest/expect": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "co": "^4.6.0", + "dedent": "^1.0.0", + "is-generator-fn": "^2.0.0", + "jest-each": "^29.7.0", + "jest-matcher-utils": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-runtime": "^29.7.0", + "jest-snapshot": "^29.7.0", + "jest-util": "^29.7.0", + "p-limit": "^3.1.0", + "pretty-format": "^29.7.0", + "pure-rand": "^6.0.0", + "slash": "^3.0.0", + "stack-utils": "^2.0.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-circus/node_modules/pure-rand": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.1.0.tgz", + "integrity": "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA==", + "devOptional": true, + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/dubzzz" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fast-check" + } + ], + "license": "MIT", + "peer": true + }, + "node_modules/jest-circus/node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-cli": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-29.7.0.tgz", + "integrity": "sha512-OVVobw2IubN/GSYsxETi+gOe7Ka59EFMR/twOU3Jb2GnKKeMGJB5SGUUrEz3SFVmJASUdZUzy83sLNNQ2gZslg==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@jest/core": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/types": "^29.6.3", + "chalk": "^4.0.0", + "create-jest": "^29.7.0", + "exit": "^0.1.2", + "import-local": "^3.0.2", + "jest-config": "^29.7.0", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "yargs": "^17.3.1" + }, + "bin": { + "jest": "bin/jest.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/jest-config": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-29.7.0.tgz", + "integrity": "sha512-uXbpfeQ7R6TZBqI3/TxCU4q4ttk3u0PJeC+E0zbfSoSjq6bJ7buBPxzQPL0ifrkY4DNu4JUdk0ImlBUYi840eQ==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@babel/core": "^7.11.6", + "@jest/test-sequencer": "^29.7.0", + "@jest/types": "^29.6.3", + "babel-jest": "^29.7.0", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "deepmerge": "^4.2.2", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "jest-circus": "^29.7.0", + "jest-environment-node": "^29.7.0", + "jest-get-type": "^29.6.3", + "jest-regex-util": "^29.6.3", + "jest-resolve": "^29.7.0", + "jest-runner": "^29.7.0", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "micromatch": "^4.0.4", + "parse-json": "^5.2.0", + "pretty-format": "^29.7.0", + "slash": "^3.0.0", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "@types/node": "*", + "ts-node": ">=9.0.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "ts-node": { + "optional": true + } + } + }, + "node_modules/jest-config/node_modules/brace-expansion": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/jest-config/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "devOptional": true, + "license": "ISC", + "peer": true, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/jest-config/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "devOptional": true, + "license": "ISC", + "peer": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/jest-config/node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-config/node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/jest-diff": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.7.0.tgz", "integrity": "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "chalk": "^4.0.0", @@ -23518,6 +24729,38 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/jest-docblock": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-29.7.0.tgz", + "integrity": "sha512-q617Auw3A612guyaFgsbFeYpNP5t2aoUNLwBUbc/0kD1R4t9ixDbyFTHd1nok4epoVFpr7PmeWHrhvuV3XaJ4g==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "detect-newline": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-each": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-29.7.0.tgz", + "integrity": "sha512-gns+Er14+ZrEoC5fhOfYCY1LOHHr0TI+rQUHZS8Ttw2l7gl+80eHc/gFf2Ktkw0+SIACDTeWvpFcv3B04VembQ==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@jest/types": "^29.6.3", + "chalk": "^4.0.0", + "jest-get-type": "^29.6.3", + "jest-util": "^29.7.0", + "pretty-format": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, "node_modules/jest-environment-jsdom": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest-environment-jsdom/-/jest-environment-jsdom-29.7.0.tgz", @@ -23546,6 +24789,358 @@ } } }, + "node_modules/jest-environment-node": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-29.7.0.tgz", + "integrity": "sha512-DOSwCRqXirTOyheM+4d5YZOrWcdu0LNZ87ewUoywbcb2XR4wKgqiG8vNeYwhjFMbEkfju7wx2GYH0P2gevGvFw==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@jest/environment": "^29.7.0", + "@jest/fake-timers": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "jest-mock": "^29.7.0", + "jest-util": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-expo": { + "version": "54.0.18", + "resolved": "https://registry.npmjs.org/jest-expo/-/jest-expo-54.0.18.tgz", + "integrity": "sha512-couPPatkifK3v0WZW7zu1HZW5HyxY+1cY69LKHPawwbZTuIvf5wk4SYHtoUrGa/nAM2jW/YiXDLWfociEHJPvw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@expo/config": "~12.0.14", + "@expo/json-file": "^10.0.16", + "@jest/create-cache-key-function": "^29.2.1", + "@jest/globals": "^29.2.1", + "babel-jest": "^29.2.1", + "jest-environment-jsdom": "^29.2.1", + "jest-snapshot": "^29.2.1", + "jest-watch-select-projects": "^2.0.0", + "jest-watch-typeahead": "2.2.1", + "json5": "^2.2.3", + "lodash": "^4.17.19", + "react-test-renderer": "19.1.0", + "server-only": "^0.0.1", + "stacktrace-js": "^2.0.2" + }, + "bin": { + "jest": "bin/jest.js" + }, + "peerDependencies": { + "expo": "*", + "react-native": "*", + "react-server-dom-webpack": "~19.0.4 || ~19.1.5 || ~19.2.4" + }, + "peerDependenciesMeta": { + "react-server-dom-webpack": { + "optional": true + } + } + }, + "node_modules/jest-expo/node_modules/@expo/config": { + "version": "12.0.14", + "resolved": "https://registry.npmjs.org/@expo/config/-/config-12.0.14.tgz", + "integrity": "sha512-3dfbBd9LnPDgyylhCgkOsaG8Adg52uOVOTQYH5lf23a/t8M5eQpXKCvzUarrf62B78057n2NnkiofK9TfPgvzw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "~7.10.4", + "@expo/config-plugins": "~54.0.5", + "@expo/config-types": "^54.0.10", + "@expo/json-file": "^10.0.16", + "deepmerge": "^4.3.1", + "getenv": "^2.0.0", + "glob": "^13.0.0", + "require-from-string": "^2.0.2", + "resolve-from": "^5.0.0", + "resolve-workspace-root": "^2.0.0", + "semver": "^7.6.0", + "slugify": "^1.3.4", + "sucrase": "~3.35.1" + } + }, + "node_modules/jest-expo/node_modules/@expo/config-plugins": { + "version": "54.0.6", + "resolved": "https://registry.npmjs.org/@expo/config-plugins/-/config-plugins-54.0.6.tgz", + "integrity": "sha512-RKKhe3HSCTEmU2PBl4lu0BtV68TOz7qjPRXQBkBOUeYe83vIno1N63viDOiHIf7wxZ1ALxvsyEu3QWlCICnfWw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@expo/config-types": "^54.0.10", + "@expo/json-file": "~10.0.16", + "@expo/plist": "^0.4.9", + "@expo/sdk-runtime-versions": "^1.0.0", + "chalk": "^4.1.2", + "debug": "^4.3.5", + "getenv": "^2.0.0", + "glob": "^13.0.0", + "resolve-from": "^5.0.0", + "semver": "^7.5.4", + "slash": "^3.0.0", + "slugify": "^1.6.6", + "xcode": "^4.0.0", + "xml2js": "0.6.0" + } + }, + "node_modules/jest-expo/node_modules/@expo/config-plugins/node_modules/@babel/code-frame": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.10.4.tgz", + "integrity": "sha512-vG6SvB6oYEhvgisZNFRmRCUkLz11c7rp+tbNTynGqc6mS1d5ATd/sGyV6W0KZZnXRKMTzZDRgQT3Ou9jhpAfUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/highlight": "^7.10.4" + } + }, + "node_modules/jest-expo/node_modules/@expo/config-plugins/node_modules/@expo/json-file": { + "version": "10.0.16", + "resolved": "https://registry.npmjs.org/@expo/json-file/-/json-file-10.0.16.tgz", + "integrity": "sha512-fcVkWEj+hLuP2yt5W0aw6LmDRqSPWDLUSxOMcmFeV+algmIF59sQVKCwB9btjQLd4V6x9N0pISkQEkBubUHrCw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "~7.10.4", + "json5": "^2.2.3" + } + }, + "node_modules/jest-expo/node_modules/@expo/config-types": { + "version": "54.0.10", + "resolved": "https://registry.npmjs.org/@expo/config-types/-/config-types-54.0.10.tgz", + "integrity": "sha512-/J16SC2an1LdtCZ67xhSkGXpALYUVUNyZws7v+PVsFZxClYehDSoKLqyRaGkpHlYrCc08bS0RF5E0JV6g50psA==", + "dev": true, + "license": "MIT" + }, + "node_modules/jest-expo/node_modules/@expo/config/node_modules/@babel/code-frame": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.10.4.tgz", + "integrity": "sha512-vG6SvB6oYEhvgisZNFRmRCUkLz11c7rp+tbNTynGqc6mS1d5ATd/sGyV6W0KZZnXRKMTzZDRgQT3Ou9jhpAfUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/highlight": "^7.10.4" + } + }, + "node_modules/jest-expo/node_modules/@expo/json-file": { + "version": "10.2.0", + "resolved": "https://registry.npmjs.org/@expo/json-file/-/json-file-10.2.0.tgz", + "integrity": "sha512-S6XzKe3R9GQeHiUPXc3xJjOv2VJhOEwFYf7xdC2z2cUqt3kZJ9mSO877sNQloVdnW/SUCtPY3bexlM7nwq+CAQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.20.0", + "json5": "^2.2.3" + } + }, + "node_modules/jest-expo/node_modules/@expo/plist": { + "version": "0.4.9", + "resolved": "https://registry.npmjs.org/@expo/plist/-/plist-0.4.9.tgz", + "integrity": "sha512-MPVpmKGfnQEnrCzgxuXcmPP/y/t6AVm+DcSb2Myp21LKWv1N3l8uFxMggesfF4ixAxkRlGmMMx9GyDC9M+XklQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@xmldom/xmldom": "^0.8.8", + "base64-js": "^1.2.3", + "xmlbuilder": "^15.1.1" + } + }, + "node_modules/jest-expo/node_modules/@xmldom/xmldom": { + "version": "0.8.15", + "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.15.tgz", + "integrity": "sha512-/5NV/vDALVFDXgLmfsy9TRCBlKwO2LNBFzpzvb9iIj+jR+eSc6DLYYvVOdivT/jm7MtU6TebYuRmzEOI7w40UA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/jest-expo/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/jest-expo/node_modules/brace-expansion": { + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/jest-expo/node_modules/commander": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", + "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/jest-expo/node_modules/getenv": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/getenv/-/getenv-2.0.0.tgz", + "integrity": "sha512-VilgtJj/ALgGY77fiLam5iD336eSWi96Q15JSAG1zi8NRBysm3LXKdGnHb4m5cuyxvOLQQKWpBZAT6ni4FI2iQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/jest-expo/node_modules/glob": { + "version": "13.0.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", + "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "minimatch": "^10.2.2", + "minipass": "^7.1.3", + "path-scurry": "^2.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/jest-expo/node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/jest-expo/node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/jest-expo/node_modules/path-scurry": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", + "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/jest-expo/node_modules/react-test-renderer": { + "version": "19.1.0", + "resolved": "https://registry.npmjs.org/react-test-renderer/-/react-test-renderer-19.1.0.tgz", + "integrity": "sha512-jXkSl3CpvPYEF+p/eGDLB4sPoDX8pKkYvRl9+rR8HxLY0X04vW7hCm1/0zHoUSjPZ3bDa+wXWNTDVIw/R8aDVw==", + "dev": true, + "license": "MIT", + "dependencies": { + "react-is": "^19.1.0", + "scheduler": "^0.26.0" + }, + "peerDependencies": { + "react": "^19.1.0" + } + }, + "node_modules/jest-expo/node_modules/scheduler": { + "version": "0.26.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.26.0.tgz", + "integrity": "sha512-NlHwttCI/l5gCPR3D1nNXtWABUmBwvZpEQiD4IXSbIDq8BzLIK/7Ir5gTFSGZDUu37K5cMNp0hFtzO38sC7gWA==", + "dev": true, + "license": "MIT" + }, + "node_modules/jest-expo/node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-expo/node_modules/sucrase": { + "version": "3.35.1", + "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.1.tgz", + "integrity": "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.2", + "commander": "^4.0.0", + "lines-and-columns": "^1.1.6", + "mz": "^2.7.0", + "pirates": "^4.0.1", + "tinyglobby": "^0.2.11", + "ts-interface-checker": "^0.1.9" + }, + "bin": { + "sucrase": "bin/sucrase", + "sucrase-node": "bin/sucrase-node" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/jest-expo/node_modules/xcode": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/xcode/-/xcode-4.0.0.tgz", + "integrity": "sha512-dDaoWzc9EP2fp9FS9PVZUkyvFxY4y1TOV9pcKaKLk++Ei/qb97XDFEVP7GnW7Osii/TzVABJ0jq2F+9/lq0TVA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "simple-plist": "^1.3.1" + }, + "engines": { + "node": ">=14.17.0" + } + }, + "node_modules/jest-expo/node_modules/xmlbuilder": { + "version": "15.1.1", + "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz", + "integrity": "sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.0" + } + }, "node_modules/jest-get-type": { "version": "29.6.3", "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.6.3.tgz", @@ -23559,7 +25154,7 @@ "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-29.7.0.tgz", "integrity": "sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@jest/types": "^29.6.3", @@ -23581,11 +25176,26 @@ "fsevents": "^2.3.2" } }, + "node_modules/jest-leak-detector": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-29.7.0.tgz", + "integrity": "sha512-kYA8IJcSYtST2BY9I+SMC32nDpBT3J2NvWJx8+JCuCdl/CR1I4EKUJROiP8XtCcxqgTTBGJNdbB1A8XRKbTetw==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "jest-get-type": "^29.6.3", + "pretty-format": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, "node_modules/jest-matcher-utils": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.7.0.tgz", "integrity": "sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "chalk": "^4.0.0", @@ -23601,7 +25211,7 @@ "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.7.0.tgz", "integrity": "sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/code-frame": "^7.12.13", @@ -23622,7 +25232,7 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=8" @@ -23632,7 +25242,7 @@ "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-29.7.0.tgz", "integrity": "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@jest/types": "^29.6.3", @@ -23643,21 +25253,251 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/jest-pnp-resolver": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/jest-pnp-resolver/-/jest-pnp-resolver-1.2.3.tgz", + "integrity": "sha512-+3NpwQEnRoIBtx4fyhblQDPgJI0H1IEIkX7ShLUjPGA7TtUTvI1oiKi3SR4oBR0hQhQR80l4WAe5RrXBwWMA8w==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=6" + }, + "peerDependencies": { + "jest-resolve": "*" + }, + "peerDependenciesMeta": { + "jest-resolve": { + "optional": true + } + } + }, "node_modules/jest-regex-util": { "version": "29.6.3", "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-29.6.3.tgz", "integrity": "sha512-KJJBsRCyyLNWCNBOvZyRDnAIfUiRJ8v+hOBQYGn8gDyF3UegwiP4gwRR3/SDa42g1YbVycTidUF3rKjyLFDWbg==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/jest-resolve": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-29.7.0.tgz", + "integrity": "sha512-IOVhZSrg+UvVAshDSDtHyFCCBUl/Q3AAJv8iZ6ZjnZ74xzvwuzLXid9IIIPgTnY62SJjfuupMKZsZQRsCvxEgA==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.7.0", + "jest-pnp-resolver": "^1.2.2", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "resolve": "^1.20.0", + "resolve.exports": "^2.0.0", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-resolve-dependencies": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-29.7.0.tgz", + "integrity": "sha512-un0zD/6qxJ+S0et7WxeI3H5XSe9lTBBR7bOHCHXkKR6luG5mwDDlIzVQ0V5cZCuoTgEdcdwzTghYkTWfubi+nA==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "jest-regex-util": "^29.6.3", + "jest-snapshot": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-resolve/node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-runner": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-29.7.0.tgz", + "integrity": "sha512-fsc4N6cPCAahybGBfTRcq5wFR6fpLznMg47sY5aDpsoejOcVYFb07AHuSnR0liMcPTgBsA3ZJL6kFOjPdoNipQ==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@jest/console": "^29.7.0", + "@jest/environment": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "emittery": "^0.13.1", + "graceful-fs": "^4.2.9", + "jest-docblock": "^29.7.0", + "jest-environment-node": "^29.7.0", + "jest-haste-map": "^29.7.0", + "jest-leak-detector": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-resolve": "^29.7.0", + "jest-runtime": "^29.7.0", + "jest-util": "^29.7.0", + "jest-watcher": "^29.7.0", + "jest-worker": "^29.7.0", + "p-limit": "^3.1.0", + "source-map-support": "0.5.13" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-runner/node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "devOptional": true, + "license": "BSD-3-Clause", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/jest-runner/node_modules/source-map-support": { + "version": "0.5.13", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.13.tgz", + "integrity": "sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/jest-runtime": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-29.7.0.tgz", + "integrity": "sha512-gUnLjgwdGqW7B4LvOIkbKs9WGbn+QLqRQQ9juC6HndeDiezIwhDP+mhMwHWCEcfQ5RUXa6OPnFF8BJh5xegwwQ==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@jest/environment": "^29.7.0", + "@jest/fake-timers": "^29.7.0", + "@jest/globals": "^29.7.0", + "@jest/source-map": "^29.6.3", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "cjs-module-lexer": "^1.0.0", + "collect-v8-coverage": "^1.0.0", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-mock": "^29.7.0", + "jest-regex-util": "^29.6.3", + "jest-resolve": "^29.7.0", + "jest-snapshot": "^29.7.0", + "jest-util": "^29.7.0", + "slash": "^3.0.0", + "strip-bom": "^4.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-runtime/node_modules/brace-expansion": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/jest-runtime/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "devOptional": true, + "license": "ISC", + "peer": true, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/jest-runtime/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "devOptional": true, + "license": "ISC", + "peer": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/jest-runtime/node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-runtime/node_modules/strip-bom": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", + "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, "node_modules/jest-snapshot": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-29.7.0.tgz", "integrity": "sha512-Rm0BMWtxBcioHr1/OX5YCP8Uov4riHvKPknOGs804Zg9JGZgmIBkbtlxJC/7Z4msKYVbIJtfU+tKb8xlYNfdkw==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/core": "^7.11.6", @@ -23868,7 +25708,7 @@ "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-29.7.0.tgz", "integrity": "sha512-49Fg7WXkU3Vl2h6LbLtMQ/HyB6rXSIX7SqvBLQmssRBGN9I0PNvPmAmCWSOY6SOvrjhI/F7/bGAv9RtnsPA03g==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@jest/test-result": "^29.7.0", @@ -23888,7 +25728,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz", "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=10" @@ -23898,7 +25738,7 @@ "version": "4.0.2", "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz", "integrity": "sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "char-regex": "^1.0.2", @@ -24172,7 +26012,7 @@ "version": "2.3.1", "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", - "dev": true, + "devOptional": true, "license": "MIT" }, "node_modules/json-schema": { @@ -24967,7 +26807,7 @@ "version": "1.2.4", "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", - "dev": true, + "devOptional": true, "license": "MIT" }, "node_modules/linkify-it": { @@ -27300,7 +29140,7 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=6" @@ -27332,7 +29172,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz", "integrity": "sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=4" @@ -27823,7 +29663,7 @@ "version": "1.4.0", "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", - "dev": true, + "devOptional": true, "license": "MIT" }, "node_modules/natural-orderby": { @@ -28154,7 +29994,7 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=0.10.0" @@ -28173,31 +30013,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/noxcturnal": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/noxcturnal/-/noxcturnal-0.1.5.tgz", - "integrity": "sha512-X/HQXJP/xn7LVQ4z1E4La0NHSl5UHdtJPG6ky4r2/Xgb7k79nGDJgBXk7I5f1V2vInWjlSCM14oSB0cUxwZS/Q==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "@oxc-project/types": "0.154.0" - }, - "engines": { - "node": ">=18" - }, - "optionalDependencies": { - "@noxcturnal/noxcturnal-darwin-arm64": "0.1.5", - "@noxcturnal/noxcturnal-darwin-x64": "0.1.5", - "@noxcturnal/noxcturnal-linux-arm64-gnu": "0.1.5", - "@noxcturnal/noxcturnal-linux-arm64-musl": "0.1.5", - "@noxcturnal/noxcturnal-linux-x64-gnu": "0.1.5", - "@noxcturnal/noxcturnal-linux-x64-musl": "0.1.5", - "@noxcturnal/noxcturnal-win32-arm64-msvc": "0.1.5", - "@noxcturnal/noxcturnal-win32-x64-msvc": "0.1.5" - } - }, "node_modules/npm-package-arg": { "version": "11.0.3", "resolved": "https://registry.npmjs.org/npm-package-arg/-/npm-package-arg-11.0.3.tgz", @@ -28231,6 +30046,20 @@ "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", "license": "ISC" }, + "node_modules/npm-run-path": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", + "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "path-key": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/nth-check": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz", @@ -28453,7 +30282,7 @@ "version": "5.1.2", "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "mimic-fn": "^2.1.0" @@ -28728,7 +30557,7 @@ "version": "3.1.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "yocto-queue": "^0.1.0" @@ -28880,7 +30709,7 @@ "version": "5.2.0", "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/code-frame": "^7.0.0", @@ -29015,7 +30844,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=0.10.0" @@ -29190,7 +31019,7 @@ "version": "4.0.7", "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz", "integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">= 6" @@ -29209,7 +31038,7 @@ "version": "4.2.0", "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "find-up": "^4.0.0" @@ -29222,7 +31051,7 @@ "version": "4.1.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "locate-path": "^5.0.0", @@ -29236,7 +31065,7 @@ "version": "5.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "p-locate": "^4.1.0" @@ -29249,7 +31078,7 @@ "version": "2.3.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "p-try": "^2.0.0" @@ -29265,7 +31094,7 @@ "version": "4.1.0", "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "p-limit": "^2.2.0" @@ -30085,25 +31914,9 @@ } }, "node_modules/react-is": { - "version": "19.2.4", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.4.tgz", - "integrity": "sha512-W+EWGn2v0ApPKgKKCy/7s7WHXkboGcsrXE+2joLyVxkbyVQfO3MUEaUQDHoSmb8TFFrSKYa9mw64WZHNHSDzYA==", - "license": "MIT" - }, - "node_modules/react-is-18": { - "name": "react-is", - "version": "18.3.1", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", - "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", - "dev": true, - "license": "MIT" - }, - "node_modules/react-is-19": { - "name": "react-is", - "version": "19.2.7", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.7.tgz", - "integrity": "sha512-kZFnouyVv7eP/Phmrlo9FK+zcAdriZJvzxXHF1Sl1P377WSGe2G/JxVolhTrB/jeV47lKImhNUsijjHAAbcl/A==", - "dev": true, + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.3.1.tgz", + "integrity": "sha512-RRieF6IyxQBkcK6pP8xOHprLTPW6QjRkbGdImtqNme+/hYVwCZkLQLdlZGOhUqXwkS9IEynaGvPJtv6XB/cz0Q==", "license": "MIT" }, "node_modules/react-markdown": { @@ -30651,6 +32464,21 @@ } } }, + "node_modules/react-test-renderer": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-test-renderer/-/react-test-renderer-19.3.1.tgz", + "integrity": "sha512-YcNewwmnZMd0wTb2nkb4hQ58NmX/u1hW2OJsNpen8CnV+jNkmEjYd1R6wJrOMSgb8bIF5HAJv4iL+S3PwNptOA==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "react-is": "^19.3.1", + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.1" + } + }, "node_modules/read-binary-file-arch": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/read-binary-file-arch/-/read-binary-file-arch-1.0.6.tgz", @@ -31181,6 +33009,20 @@ "dev": true, "license": "MIT" }, + "node_modules/resolve-cwd": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", + "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", + "devOptional": true, + "license": "MIT", + "peer": true, + "dependencies": { + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/resolve-from": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", @@ -31206,6 +33048,17 @@ "integrity": "sha512-nR23LHAvaI6aHtMg6RWoaHpdR4D881Nydkzi2CixINyg9T00KgaJdJI6Vwty+Ps8WLxZHuxsS0BseWjxSA4C+w==", "license": "MIT" }, + "node_modules/resolve.exports": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/resolve.exports/-/resolve.exports-2.0.4.tgz", + "integrity": "sha512-zepuGL0ulf+nt+XaFrlKeaiTJeyPFPLLY62+ncq1/VTHBdt3HsfXOH60priZ6tnXQozdGcDeIF5JVTanvIcYWQ==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=10" + } + }, "node_modules/responselike": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/responselike/-/responselike-2.0.1.tgz", @@ -31583,11 +33436,12 @@ } }, "node_modules/scheduler": { - "version": "0.26.0", - "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.26.0.tgz", - "integrity": "sha512-NlHwttCI/l5gCPR3D1nNXtWABUmBwvZpEQiD4IXSbIDq8BzLIK/7Ir5gTFSGZDUu37K5cMNp0hFtzO38sC7gWA==", - "dev": true, - "license": "MIT" + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", + "devOptional": true, + "license": "MIT", + "peer": true }, "node_modules/secure-json-parse": { "version": "4.1.0", @@ -32450,7 +34304,7 @@ "version": "2.0.6", "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "escape-string-regexp": "^2.0.0" @@ -32463,7 +34317,7 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=8" @@ -32863,6 +34717,17 @@ "node": ">=4" } }, + "node_modules/strip-final-newline": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", + "devOptional": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=6" + } + }, "node_modules/strip-indent": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-4.1.1.tgz", @@ -33047,13 +34912,14 @@ "license": "MIT" }, "node_modules/synckit": { - "version": "0.11.12", - "resolved": "https://registry.npmjs.org/synckit/-/synckit-0.11.12.tgz", - "integrity": "sha512-Bh7QjT8/SuKUIfObSXNHNSK6WHo6J1tHCqJsuaFDP7gP0fkzSfTxI8y85JrppZ0h8l0maIgc2tfuZQ6/t3GtnQ==", + "version": "0.12.3", + "resolved": "https://registry.npmjs.org/synckit/-/synckit-0.12.3.tgz", + "integrity": "sha512-U+/AXT6LWsxnj2vz9HeUuPWBNgdWxjyIEjEPdbJARC9txmgPzo2VEdqnFo4hHaNyMPtycyVJrSaQYeQv/PoyyA==", "dev": true, "license": "MIT", "dependencies": { - "@pkgr/core": "^0.2.9" + "@dual-bundle/import-meta-resolve": "^4.2.1", + "@pkgr/core": "^0.3.6" }, "engines": { "node": "^14.18.0 || >=16.0.0" @@ -33228,7 +35094,7 @@ "version": "6.0.0", "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", - "dev": true, + "devOptional": true, "license": "ISC", "dependencies": { "@istanbuljs/schema": "^0.1.2", @@ -33243,7 +35109,7 @@ "version": "1.1.12", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "balanced-match": "^1.0.0", @@ -33255,7 +35121,7 @@ "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", - "dev": true, + "devOptional": true, "license": "ISC", "dependencies": { "fs.realpath": "^1.0.0", @@ -33276,7 +35142,7 @@ "version": "3.1.5", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", - "dev": true, + "devOptional": true, "license": "ISC", "dependencies": { "brace-expansion": "^1.1.7" @@ -33579,6 +35445,19 @@ "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==", "license": "MIT" }, + "node_modules/ts-api-utils": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", + "integrity": "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.12" + }, + "peerDependencies": { + "typescript": ">=4.8.4" + } + }, "node_modules/ts-declaration-location": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/ts-declaration-location/-/ts-declaration-location-1.0.7.tgz", @@ -33868,7 +35747,7 @@ "version": "4.0.8", "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=4" @@ -34517,6 +36396,22 @@ "dev": true, "license": "MIT" }, + "node_modules/v8-to-istanbul": { + "version": "9.3.0", + "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.3.0.tgz", + "integrity": "sha512-kiGUalWN+rgBJ/1OHZsBtU4rXZOfj/7rKQxULKlIzwzQSvMJUUNgPwJEEh7gU6xEVxC0ahoOBvN2YI8GH6FNgA==", + "devOptional": true, + "license": "ISC", + "peer": true, + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.12", + "@types/istanbul-lib-coverage": "^2.0.1", + "convert-source-map": "^2.0.0" + }, + "engines": { + "node": ">=10.12.0" + } + }, "node_modules/validate-npm-package-license": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", @@ -35517,7 +37412,7 @@ "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=10" @@ -37103,43 +38998,6 @@ "typescript": ">=4.8.4 <6.1.0" } }, - "packages/app/node_modules/eslint-config-expo/node_modules/eslint-plugin-react-hooks": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-7.1.1.tgz", - "integrity": "sha512-f2I7Gw6JbvCexzIInuSbZpfdQ44D7iqdWX01FKLvrPgqxoE7oMj8clOfto8U6vYiz4yd5oKu39rRSVOe1zRu0g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/core": "^7.24.4", - "@babel/parser": "^7.24.4", - "hermes-parser": "^0.25.1", - "zod": "^3.25.0 || ^4.0.0", - "zod-validation-error": "^3.5.0 || ^4.0.0" - }, - "engines": { - "node": ">=18" - }, - "peerDependencies": { - "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0 || ^10.0.0" - } - }, - "packages/app/node_modules/eslint-config-expo/node_modules/hermes-estree": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.25.1.tgz", - "integrity": "sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw==", - "dev": true, - "license": "MIT" - }, - "packages/app/node_modules/eslint-config-expo/node_modules/hermes-parser": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/hermes-parser/-/hermes-parser-0.25.1.tgz", - "integrity": "sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==", - "dev": true, - "license": "MIT", - "dependencies": { - "hermes-estree": "0.25.1" - } - }, "packages/app/node_modules/eslint-config-expo/node_modules/ignore": { "version": "7.0.12", "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.12.tgz", @@ -37150,19 +39008,6 @@ "node": ">= 4" } }, - "packages/app/node_modules/eslint-config-expo/node_modules/ts-api-utils": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", - "integrity": "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18.12" - }, - "peerDependencies": { - "typescript": ">=4.8.4" - } - }, "packages/app/node_modules/eslint-plugin-expo": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/eslint-plugin-expo/-/eslint-plugin-expo-1.2.1.tgz", @@ -37272,19 +39117,6 @@ "typescript": ">=4.8.4 <6.1.0" } }, - "packages/app/node_modules/eslint-plugin-expo/node_modules/ts-api-utils": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", - "integrity": "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18.12" - }, - "peerDependencies": { - "typescript": ">=4.8.4" - } - }, "packages/app/node_modules/eslint-visitor-keys": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", @@ -38477,7 +40309,6 @@ "devDependencies": { "@types/jest": "^29.5.14", "@types/react": "^18.0.25", - "expo-module-scripts": "^5.0.8", "expo-modules-core": "^2.0.4" }, "peerDependencies": { @@ -38486,1234 +40317,6 @@ "react-native": "*" } }, - "packages/expo-two-way-audio/node_modules/@expo/code-signing-certificates": { - "version": "0.0.7", - "resolved": "https://registry.npmjs.org/@expo/code-signing-certificates/-/code-signing-certificates-0.0.7.tgz", - "integrity": "sha512-zP0tnfqrFFRL8INtOaQ6XwEYfdIpIH9vrEo7y0bHQGQa50z4/QWXE5CI4nRUHxqFW4MVWOwXFg1hom1aAZHNkQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "node-forge": "^1.4.0" - }, - "engines": { - "node": ">=22.13.0" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/config": { - "version": "12.0.13", - "resolved": "https://registry.npmjs.org/@expo/config/-/config-12.0.13.tgz", - "integrity": "sha512-Cu52arBa4vSaupIWsF0h7F/Cg//N374nYb7HAxV0I4KceKA7x2UXpYaHOL7EEYYvp7tZdThBjvGpVmr8ScIvaQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "~7.10.4", - "@expo/config-plugins": "~54.0.4", - "@expo/config-types": "^54.0.10", - "@expo/json-file": "^10.0.8", - "deepmerge": "^4.3.1", - "getenv": "^2.0.0", - "glob": "^13.0.0", - "require-from-string": "^2.0.2", - "resolve-from": "^5.0.0", - "resolve-workspace-root": "^2.0.0", - "semver": "^7.6.0", - "slugify": "^1.3.4", - "sucrase": "~3.35.1" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/config-plugins": { - "version": "54.0.4", - "resolved": "https://registry.npmjs.org/@expo/config-plugins/-/config-plugins-54.0.4.tgz", - "integrity": "sha512-g2yXGICdoOw5i3LkQSDxl2Q5AlQCrG7oniu0pCPPO+UxGb7He4AFqSvPSy8HpRUj55io17hT62FTjYRD+d6j3Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@expo/config-types": "^54.0.10", - "@expo/json-file": "~10.0.8", - "@expo/plist": "^0.4.8", - "@expo/sdk-runtime-versions": "^1.0.0", - "chalk": "^4.1.2", - "debug": "^4.3.5", - "getenv": "^2.0.0", - "glob": "^13.0.0", - "resolve-from": "^5.0.0", - "semver": "^7.5.4", - "slash": "^3.0.0", - "slugify": "^1.6.6", - "xcode": "^3.0.1", - "xml2js": "0.6.0" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/config-plugins/node_modules/@babel/code-frame": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.10.4.tgz", - "integrity": "sha512-vG6SvB6oYEhvgisZNFRmRCUkLz11c7rp+tbNTynGqc6mS1d5ATd/sGyV6W0KZZnXRKMTzZDRgQT3Ou9jhpAfUg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/highlight": "^7.10.4" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/config-plugins/node_modules/@expo/json-file": { - "version": "10.0.16", - "resolved": "https://registry.npmjs.org/@expo/json-file/-/json-file-10.0.16.tgz", - "integrity": "sha512-fcVkWEj+hLuP2yt5W0aw6LmDRqSPWDLUSxOMcmFeV+algmIF59sQVKCwB9btjQLd4V6x9N0pISkQEkBubUHrCw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "~7.10.4", - "json5": "^2.2.3" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/config-types": { - "version": "54.0.10", - "resolved": "https://registry.npmjs.org/@expo/config-types/-/config-types-54.0.10.tgz", - "integrity": "sha512-/J16SC2an1LdtCZ67xhSkGXpALYUVUNyZws7v+PVsFZxClYehDSoKLqyRaGkpHlYrCc08bS0RF5E0JV6g50psA==", - "dev": true, - "license": "MIT" - }, - "packages/expo-two-way-audio/node_modules/@expo/config/node_modules/@babel/code-frame": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.10.4.tgz", - "integrity": "sha512-vG6SvB6oYEhvgisZNFRmRCUkLz11c7rp+tbNTynGqc6mS1d5ATd/sGyV6W0KZZnXRKMTzZDRgQT3Ou9jhpAfUg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/highlight": "^7.10.4" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/devtools": { - "version": "58.0.2", - "resolved": "https://registry.npmjs.org/@expo/devtools/-/devtools-58.0.2.tgz", - "integrity": "sha512-WBj/K+vv8JPSmY70ennL04YYOHkpEsGGkfuVY9lfv4XO7Qhbt5qz4q6W7maME194I5oGcimRMigUFfWNkBe90w==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "chalk": "^4.1.2" - }, - "peerDependencies": { - "expo": "*", - "react": "*", - "react-native": "*" - }, - "peerDependenciesMeta": { - "expo": { - "optional": true - }, - "react": { - "optional": true - }, - "react-native": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/@expo/dom-webview": { - "version": "58.0.2", - "resolved": "https://registry.npmjs.org/@expo/dom-webview/-/dom-webview-58.0.2.tgz", - "integrity": "sha512-bLkREoP7qL3rEuzxP60xG+TjdPoGjbnZfxkvYo5imJxGWfKMOf7x962W06Pu+WWAr4gcDRk16iA+Clg8D0zjCg==", - "dev": true, - "license": "MIT", - "peer": true, - "peerDependencies": { - "expo": "*", - "react": "*", - "react-native": "*" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/env": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/@expo/env/-/env-2.5.2.tgz", - "integrity": "sha512-z8kCvBVJpd2S20a+Ab1otQgz8sJLeR7CXDTsuAMcNbYFsK10Fdhfb7rx9Ys1vvlbijnY55eZhQvJACajc1IjBQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "chalk": "^4.0.0", - "debug": "^4.3.4", - "getenv": "^2.0.0" - }, - "engines": { - "node": ">=20.12.0" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/fingerprint": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@expo/fingerprint/-/fingerprint-0.21.5.tgz", - "integrity": "sha512-4ngc+aPgMK56sYc47tfabmoaNdP7OvPBOH7QPgN3riSYM0Ev+KwsGRDius5jBBwjCI9ADp7IpjJEK9xlRYjjvA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/env": "^2.5.2", - "@expo/spawn-async": "^1.8.0", - "arg": "^5.0.2", - "chalk": "^4.1.2", - "debug": "^4.3.4", - "getenv": "^2.0.0", - "glob": "^13.0.0", - "ignore": "^5.3.1", - "minimatch": "^10.2.2", - "resolve-from": "^5.0.0", - "semver": "^7.7.4" - }, - "bin": { - "fingerprint": "bin/cli.js" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/fingerprint/node_modules/ignore": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", - "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 4" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/image-utils": { - "version": "0.12.5", - "resolved": "https://registry.npmjs.org/@expo/image-utils/-/image-utils-0.12.5.tgz", - "integrity": "sha512-nsFYd7GfDdwZa+S+p+EkVCkh7UKKNf0kfUXDQ53HbyMmNFD3psb5JYwU/2N+uZG5wOEfKGfQ5u7pk/wn2gMlBA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/require-utils": "^58.0.4", - "@expo/spawn-async": "^1.8.0", - "chalk": "^4.0.0", - "getenv": "^2.0.0", - "jimp-compact": "0.16.1", - "parse-png": "^2.1.0", - "semver": "^7.7.4" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/image-utils/node_modules/@expo/require-utils": { - "version": "58.0.4", - "resolved": "https://registry.npmjs.org/@expo/require-utils/-/require-utils-58.0.4.tgz", - "integrity": "sha512-DvjS5NCitXYcad2Woe1EMHJKcbhTbE77HX0BgOQGL2LFHE3q2H0n8kCWDPBOCVJ63Drap3c35nwoJwF5TQL7Tw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "@babel/core": "^7.25.2", - "@babel/plugin-transform-modules-commonjs": "^7.24.8" - }, - "peerDependencies": { - "typescript": "^5.0.0 || ^5.0.0-0 || ^6.0.0 || ^7.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/@expo/inline-modules": { - "version": "0.2.6", - "resolved": "https://registry.npmjs.org/@expo/inline-modules/-/inline-modules-0.2.6.tgz", - "integrity": "sha512-S8PK3wx6ogwunoQ7pqdPbklQGtXloeWTAOzWJ9yIL7xHFxvnI/Ryj0phA3KEGCMlaKZjaCP1h/3s7n/ueErRgQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/config-plugins": "~58.0.9" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/inline-modules/node_modules/@expo/config-plugins": { - "version": "58.0.9", - "resolved": "https://registry.npmjs.org/@expo/config-plugins/-/config-plugins-58.0.9.tgz", - "integrity": "sha512-HyP7V1QgDxeHcOEh4qQH7cfK7cI7wNp0y9lszAu98SRYCshhDbwB9gWpFfnpX1GQUtgiqG4Hvgh1z3ntcGwAjw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/config-types": "^58.0.3", - "@expo/json-file": "~11.2.1", - "@expo/plist": "^0.10.1", - "@expo/require-utils": "^58.0.4", - "@expo/sdk-runtime-versions": "^1.0.1", - "chalk": "^4.1.2", - "debug": "^4.3.5", - "getenv": "^2.0.0", - "glob": "^13.0.0", - "semver": "^7.7.4", - "slugify": "^1.6.6", - "xcode": "^3.0.1", - "xml2js": "0.6.0" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/inline-modules/node_modules/@expo/config-types": { - "version": "58.0.3", - "resolved": "https://registry.npmjs.org/@expo/config-types/-/config-types-58.0.3.tgz", - "integrity": "sha512-wyfrwkTT/hQHzwyqkXkngKxoOa8L6ovsTP4h/UukS1mTmssee5et6HOPoN5RtawdJPnm5JO28f//C/wXlpka8Q==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/@expo/inline-modules/node_modules/@expo/json-file": { - "version": "11.2.1", - "resolved": "https://registry.npmjs.org/@expo/json-file/-/json-file-11.2.1.tgz", - "integrity": "sha512-UPhKoFCj8BcwgLB1rKQ1CuR/REITnZLiqxHEHOeH1tPsdXcHGtUDh0P5bLbr7oU0nKVdtJ5rzyKx8jniMQdESQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "json5": "^2.2.3" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/inline-modules/node_modules/@expo/plist": { - "version": "0.10.1", - "resolved": "https://registry.npmjs.org/@expo/plist/-/plist-0.10.1.tgz", - "integrity": "sha512-nuNOqj+r/hGJbZ1Ax3jUpZaOB8UAMHUrISALJEUKaCieTflYj7224EqFWmMpriCGk9wXS1gH+9GGVnSj0tWzuQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@xmldom/xmldom": "^0.8.8", - "base64-js": "^1.5.1", - "xmlbuilder": "^15.1.1" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/inline-modules/node_modules/@expo/require-utils": { - "version": "58.0.4", - "resolved": "https://registry.npmjs.org/@expo/require-utils/-/require-utils-58.0.4.tgz", - "integrity": "sha512-DvjS5NCitXYcad2Woe1EMHJKcbhTbE77HX0BgOQGL2LFHE3q2H0n8kCWDPBOCVJ63Drap3c35nwoJwF5TQL7Tw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "@babel/core": "^7.25.2", - "@babel/plugin-transform-modules-commonjs": "^7.24.8" - }, - "peerDependencies": { - "typescript": "^5.0.0 || ^5.0.0-0 || ^6.0.0 || ^7.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/@expo/json-file": { - "version": "10.2.0", - "resolved": "https://registry.npmjs.org/@expo/json-file/-/json-file-10.2.0.tgz", - "integrity": "sha512-S6XzKe3R9GQeHiUPXc3xJjOv2VJhOEwFYf7xdC2z2cUqt3kZJ9mSO877sNQloVdnW/SUCtPY3bexlM7nwq+CAQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.20.0", - "json5": "^2.2.3" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/local-build-cache-provider": { - "version": "58.0.6", - "resolved": "https://registry.npmjs.org/@expo/local-build-cache-provider/-/local-build-cache-provider-58.0.6.tgz", - "integrity": "sha512-AJk3pslFNlwRMbUbfvxhu6CPA9U7A+JPb88VS/uWkG/S/QMJL90Iw4sPVfG4BOKfRUNkB8ipl432Dr4txjSMKw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/config": "~58.0.6", - "chalk": "^4.1.2" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/local-build-cache-provider/node_modules/@expo/config": { - "version": "58.0.6", - "resolved": "https://registry.npmjs.org/@expo/config/-/config-58.0.6.tgz", - "integrity": "sha512-PT1qv4s/R5A/NxXb4efGlFsYF5Consi7F8xSsJBAN090EGDr6U1EDQGOijFqzDc3JA2epD8zjKLJLOVB9YOewg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/config-plugins": "~58.0.9", - "@expo/config-types": "^58.0.3", - "@expo/json-file": "^11.2.1", - "@expo/platforms": "^58.0.1", - "@expo/require-utils": "^58.0.4", - "deepmerge": "^4.3.1", - "getenv": "^2.0.0", - "glob": "^13.0.0", - "resolve-workspace-root": "^2.0.0", - "semver": "^7.7.4", - "slugify": "^1.3.4" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/local-build-cache-provider/node_modules/@expo/config-plugins": { - "version": "58.0.9", - "resolved": "https://registry.npmjs.org/@expo/config-plugins/-/config-plugins-58.0.9.tgz", - "integrity": "sha512-HyP7V1QgDxeHcOEh4qQH7cfK7cI7wNp0y9lszAu98SRYCshhDbwB9gWpFfnpX1GQUtgiqG4Hvgh1z3ntcGwAjw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/config-types": "^58.0.3", - "@expo/json-file": "~11.2.1", - "@expo/plist": "^0.10.1", - "@expo/require-utils": "^58.0.4", - "@expo/sdk-runtime-versions": "^1.0.1", - "chalk": "^4.1.2", - "debug": "^4.3.5", - "getenv": "^2.0.0", - "glob": "^13.0.0", - "semver": "^7.7.4", - "slugify": "^1.6.6", - "xcode": "^3.0.1", - "xml2js": "0.6.0" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/local-build-cache-provider/node_modules/@expo/config-types": { - "version": "58.0.3", - "resolved": "https://registry.npmjs.org/@expo/config-types/-/config-types-58.0.3.tgz", - "integrity": "sha512-wyfrwkTT/hQHzwyqkXkngKxoOa8L6ovsTP4h/UukS1mTmssee5et6HOPoN5RtawdJPnm5JO28f//C/wXlpka8Q==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/@expo/local-build-cache-provider/node_modules/@expo/json-file": { - "version": "11.2.1", - "resolved": "https://registry.npmjs.org/@expo/json-file/-/json-file-11.2.1.tgz", - "integrity": "sha512-UPhKoFCj8BcwgLB1rKQ1CuR/REITnZLiqxHEHOeH1tPsdXcHGtUDh0P5bLbr7oU0nKVdtJ5rzyKx8jniMQdESQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "json5": "^2.2.3" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/local-build-cache-provider/node_modules/@expo/plist": { - "version": "0.10.1", - "resolved": "https://registry.npmjs.org/@expo/plist/-/plist-0.10.1.tgz", - "integrity": "sha512-nuNOqj+r/hGJbZ1Ax3jUpZaOB8UAMHUrISALJEUKaCieTflYj7224EqFWmMpriCGk9wXS1gH+9GGVnSj0tWzuQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@xmldom/xmldom": "^0.8.8", - "base64-js": "^1.5.1", - "xmlbuilder": "^15.1.1" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/local-build-cache-provider/node_modules/@expo/require-utils": { - "version": "58.0.4", - "resolved": "https://registry.npmjs.org/@expo/require-utils/-/require-utils-58.0.4.tgz", - "integrity": "sha512-DvjS5NCitXYcad2Woe1EMHJKcbhTbE77HX0BgOQGL2LFHE3q2H0n8kCWDPBOCVJ63Drap3c35nwoJwF5TQL7Tw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "@babel/core": "^7.25.2", - "@babel/plugin-transform-modules-commonjs": "^7.24.8" - }, - "peerDependencies": { - "typescript": "^5.0.0 || ^5.0.0-0 || ^6.0.0 || ^7.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/@expo/log-box": { - "version": "58.0.12", - "resolved": "https://registry.npmjs.org/@expo/log-box/-/log-box-58.0.12.tgz", - "integrity": "sha512-IzDYoFY2iUsmSDvl1V7YUM7UkCPDyMVS4e4a38c2LnFc1A3WGMUiQh+vsHLYTPKjIelu4r7/u4V7Gxtfa0oJgA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/dom-webview": "^58.0.2", - "@expo/log-box-utils": "^58.0.2", - "anser": "^1.4.9", - "stacktrace-parser": "^0.1.10" - }, - "peerDependencies": { - "@expo/dom-webview": "^58.0.2", - "expo": "*", - "react": "*", - "react-native": "*" - }, - "peerDependenciesMeta": { - "expo": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/@expo/metro": { - "version": "58.0.0", - "resolved": "https://registry.npmjs.org/@expo/metro/-/metro-58.0.0.tgz", - "integrity": "sha512-PMD640ihB0C3Oqm0AnDVJ/8qF2cKbRUEqGuSOr4tM/OTb9ktxsQqsiSSSeaOEgdCZBq20AxRS0d6WHNhhH2P+g==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "metro": "0.87.1", - "metro-babel-transformer": "0.87.1", - "metro-cache": "0.87.1", - "metro-cache-key": "0.87.1", - "metro-config": "0.87.1", - "metro-core": "0.87.1", - "metro-file-map": "0.87.1", - "metro-minify-terser": "0.87.1", - "metro-resolver": "0.87.1", - "metro-runtime": "0.87.1", - "metro-source-map": "0.87.1", - "metro-symbolicate": "0.87.1", - "metro-transform-plugins": "0.87.1", - "metro-transform-worker": "0.87.1" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/metro-config": { - "version": "58.0.14", - "resolved": "https://registry.npmjs.org/@expo/metro-config/-/metro-config-58.0.14.tgz", - "integrity": "sha512-UDUMAJwYGEzaB26ejMLG/IOVzwKDbHzoODBf3FZeRS94kk9jDf1dWE1VMX6bLBLoiflxXwqrMWiH0Fvz3gZ9YQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "@babel/core": "^7.20.0", - "@babel/generator": "^7.20.5", - "@expo/config": "~58.0.6", - "@expo/env": "~2.5.2", - "@expo/json-file": "~11.2.1", - "@expo/metro": "~58.0.0", - "@expo/platforms": "^58.0.1", - "@expo/require-utils": "^58.0.4", - "@expo/spawn-async": "^1.8.0", - "@jridgewell/gen-mapping": "^0.3.13", - "@jridgewell/remapping": "^2.3.5", - "@jridgewell/sourcemap-codec": "^1.5.5", - "@jridgewell/trace-mapping": "^0.3.31", - "@react-native/js-polyfills": "0.88.0", - "2g": "^1.0.1", - "browserslist": "^4.25.0", - "chalk": "^4.1.0", - "debug": "^4.3.2", - "getenv": "^2.0.0", - "glob": "^13.0.0", - "hermes-parser": "^0.36.0", - "jsc-safe-url": "^0.2.4", - "lightningcss": "^1.30.1", - "noxcturnal": "^0.1.0", - "picomatch": "^4.0.4", - "postcss": "^8.5.23", - "resolve-from": "^5.0.0" - }, - "peerDependencies": { - "expo": "*" - }, - "peerDependenciesMeta": { - "expo": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/@expo/metro-config/node_modules/@expo/config": { - "version": "58.0.6", - "resolved": "https://registry.npmjs.org/@expo/config/-/config-58.0.6.tgz", - "integrity": "sha512-PT1qv4s/R5A/NxXb4efGlFsYF5Consi7F8xSsJBAN090EGDr6U1EDQGOijFqzDc3JA2epD8zjKLJLOVB9YOewg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/config-plugins": "~58.0.9", - "@expo/config-types": "^58.0.3", - "@expo/json-file": "^11.2.1", - "@expo/platforms": "^58.0.1", - "@expo/require-utils": "^58.0.4", - "deepmerge": "^4.3.1", - "getenv": "^2.0.0", - "glob": "^13.0.0", - "resolve-workspace-root": "^2.0.0", - "semver": "^7.7.4", - "slugify": "^1.3.4" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/metro-config/node_modules/@expo/config-plugins": { - "version": "58.0.9", - "resolved": "https://registry.npmjs.org/@expo/config-plugins/-/config-plugins-58.0.9.tgz", - "integrity": "sha512-HyP7V1QgDxeHcOEh4qQH7cfK7cI7wNp0y9lszAu98SRYCshhDbwB9gWpFfnpX1GQUtgiqG4Hvgh1z3ntcGwAjw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/config-types": "^58.0.3", - "@expo/json-file": "~11.2.1", - "@expo/plist": "^0.10.1", - "@expo/require-utils": "^58.0.4", - "@expo/sdk-runtime-versions": "^1.0.1", - "chalk": "^4.1.2", - "debug": "^4.3.5", - "getenv": "^2.0.0", - "glob": "^13.0.0", - "semver": "^7.7.4", - "slugify": "^1.6.6", - "xcode": "^3.0.1", - "xml2js": "0.6.0" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/metro-config/node_modules/@expo/config-types": { - "version": "58.0.3", - "resolved": "https://registry.npmjs.org/@expo/config-types/-/config-types-58.0.3.tgz", - "integrity": "sha512-wyfrwkTT/hQHzwyqkXkngKxoOa8L6ovsTP4h/UukS1mTmssee5et6HOPoN5RtawdJPnm5JO28f//C/wXlpka8Q==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/@expo/metro-config/node_modules/@expo/json-file": { - "version": "11.2.1", - "resolved": "https://registry.npmjs.org/@expo/json-file/-/json-file-11.2.1.tgz", - "integrity": "sha512-UPhKoFCj8BcwgLB1rKQ1CuR/REITnZLiqxHEHOeH1tPsdXcHGtUDh0P5bLbr7oU0nKVdtJ5rzyKx8jniMQdESQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "json5": "^2.2.3" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/metro-config/node_modules/@expo/plist": { - "version": "0.10.1", - "resolved": "https://registry.npmjs.org/@expo/plist/-/plist-0.10.1.tgz", - "integrity": "sha512-nuNOqj+r/hGJbZ1Ax3jUpZaOB8UAMHUrISALJEUKaCieTflYj7224EqFWmMpriCGk9wXS1gH+9GGVnSj0tWzuQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@xmldom/xmldom": "^0.8.8", - "base64-js": "^1.5.1", - "xmlbuilder": "^15.1.1" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/metro-config/node_modules/@expo/require-utils": { - "version": "58.0.4", - "resolved": "https://registry.npmjs.org/@expo/require-utils/-/require-utils-58.0.4.tgz", - "integrity": "sha512-DvjS5NCitXYcad2Woe1EMHJKcbhTbE77HX0BgOQGL2LFHE3q2H0n8kCWDPBOCVJ63Drap3c35nwoJwF5TQL7Tw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "@babel/core": "^7.25.2", - "@babel/plugin-transform-modules-commonjs": "^7.24.8" - }, - "peerDependencies": { - "typescript": "^5.0.0 || ^5.0.0-0 || ^6.0.0 || ^7.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/@expo/metro-config/node_modules/2g": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/2g/-/2g-1.0.1.tgz", - "integrity": "sha512-+uViadKOS/wwR4pFu5g8TPn3QHpKqoX19JHCnp8k/3cLpImdcXozwvZA6Q/5PeW3AcU8neL8faaMidBcv7o8CA==", - "dev": true, - "license": "MIT", - "peer": true, - "bin": { - "2g": "bin/cli.js" - }, - "peerDependencies": { - "typescript": ">=5.8.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/@expo/metro-config/node_modules/hermes-estree": { - "version": "0.36.1", - "resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.36.1.tgz", - "integrity": "sha512-guv1nQ6IJ7S83NRFPWc3SA7IBZrdNC9kapwOq6uXvF4wP+sDCgjzQbKPCoyYmoyZRzztF/n/c36l/rccCZSiCw==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/@expo/metro-config/node_modules/hermes-parser": { - "version": "0.36.1", - "resolved": "https://registry.npmjs.org/hermes-parser/-/hermes-parser-0.36.1.tgz", - "integrity": "sha512-GApNk4zLHi2UWoWZZkx7LNCOSzLSc5lB55pZ/PhK7ycFeg7u5LcF88p/WbpIi1XUDtE0MpHE3uRR3u3KB7TjSQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "hermes-estree": "0.36.1" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/metro-file-map": { - "version": "58.0.5", - "resolved": "https://registry.npmjs.org/@expo/metro-file-map/-/metro-file-map-58.0.5.tgz", - "integrity": "sha512-Y2w8qKklLffZie28In4WF6f6e8nIJOhU0mZ5UaQdCiITVQm2a5teNdIDudEPkBsh8ItlvyHZt9n42PN2onRbkQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "2g": "^1.0.1", - "debug": "^4.3.4", - "fb-watchman": "^2.0.2", - "invariant": "^2.2.4", - "jest-worker": "^29.7.0", - "walker": "^1.0.8" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/metro-file-map/node_modules/2g": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/2g/-/2g-1.0.1.tgz", - "integrity": "sha512-+uViadKOS/wwR4pFu5g8TPn3QHpKqoX19JHCnp8k/3cLpImdcXozwvZA6Q/5PeW3AcU8neL8faaMidBcv7o8CA==", - "dev": true, - "license": "MIT", - "peer": true, - "bin": { - "2g": "bin/cli.js" - }, - "peerDependencies": { - "typescript": ">=5.8.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/@expo/osascript": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/@expo/osascript/-/osascript-2.8.1.tgz", - "integrity": "sha512-SCi+6q6uOkGhiAn6AIP/OPFgaIq/iKD2oYpnAOg2rShHStJ8ey7wyT127RbOaZXmlcY/62rHOX1WiiMnD8u/BA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/spawn-async": "^1.8.0" - }, - "engines": { - "node": ">=12" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/package-manager": { - "version": "1.14.2", - "resolved": "https://registry.npmjs.org/@expo/package-manager/-/package-manager-1.14.2.tgz", - "integrity": "sha512-sftl0eRVVCarI6grMdjAB3jX2pX1Mt3cdSnajlXS4QyeDkaKRM/ntBy6dcagj1VL0+cEfEqctlyvinmlZdNubg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/json-file": "^11.2.1", - "@expo/spawn-async": "^1.8.0", - "chalk": "^4.0.0", - "npm-package-arg": "^11.0.0", - "ora": "^3.4.0", - "resolve-workspace-root": "^2.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/package-manager/node_modules/@expo/json-file": { - "version": "11.2.1", - "resolved": "https://registry.npmjs.org/@expo/json-file/-/json-file-11.2.1.tgz", - "integrity": "sha512-UPhKoFCj8BcwgLB1rKQ1CuR/REITnZLiqxHEHOeH1tPsdXcHGtUDh0P5bLbr7oU0nKVdtJ5rzyKx8jniMQdESQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "json5": "^2.2.3" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/plist": { - "version": "0.4.9", - "resolved": "https://registry.npmjs.org/@expo/plist/-/plist-0.4.9.tgz", - "integrity": "sha512-MPVpmKGfnQEnrCzgxuXcmPP/y/t6AVm+DcSb2Myp21LKWv1N3l8uFxMggesfF4ixAxkRlGmMMx9GyDC9M+XklQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@xmldom/xmldom": "^0.8.8", - "base64-js": "^1.2.3", - "xmlbuilder": "^15.1.1" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/prebuild-config": { - "version": "58.0.14", - "resolved": "https://registry.npmjs.org/@expo/prebuild-config/-/prebuild-config-58.0.14.tgz", - "integrity": "sha512-2wVzVDfXjRB3LzUbW5shOM/A+6eUUCfR+2bpZiWRBBZBtZP2HA5Zq1YgCio1tDqMGAHf2NQQDhvy/Rz1U6aC3A==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/config": "~58.0.6", - "@expo/config-plugins": "~58.0.9", - "@expo/config-types": "^58.0.3", - "@expo/image-utils": "^0.12.5", - "@expo/json-file": "^11.2.1", - "@react-native/normalize-colors": "0.88.0", - "debug": "^4.3.1", - "expo-modules-autolinking": "~58.0.13", - "resolve-from": "^5.0.0", - "semver": "^7.7.4" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/prebuild-config/node_modules/@expo/config": { - "version": "58.0.6", - "resolved": "https://registry.npmjs.org/@expo/config/-/config-58.0.6.tgz", - "integrity": "sha512-PT1qv4s/R5A/NxXb4efGlFsYF5Consi7F8xSsJBAN090EGDr6U1EDQGOijFqzDc3JA2epD8zjKLJLOVB9YOewg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/config-plugins": "~58.0.9", - "@expo/config-types": "^58.0.3", - "@expo/json-file": "^11.2.1", - "@expo/platforms": "^58.0.1", - "@expo/require-utils": "^58.0.4", - "deepmerge": "^4.3.1", - "getenv": "^2.0.0", - "glob": "^13.0.0", - "resolve-workspace-root": "^2.0.0", - "semver": "^7.7.4", - "slugify": "^1.3.4" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/prebuild-config/node_modules/@expo/config-plugins": { - "version": "58.0.9", - "resolved": "https://registry.npmjs.org/@expo/config-plugins/-/config-plugins-58.0.9.tgz", - "integrity": "sha512-HyP7V1QgDxeHcOEh4qQH7cfK7cI7wNp0y9lszAu98SRYCshhDbwB9gWpFfnpX1GQUtgiqG4Hvgh1z3ntcGwAjw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/config-types": "^58.0.3", - "@expo/json-file": "~11.2.1", - "@expo/plist": "^0.10.1", - "@expo/require-utils": "^58.0.4", - "@expo/sdk-runtime-versions": "^1.0.1", - "chalk": "^4.1.2", - "debug": "^4.3.5", - "getenv": "^2.0.0", - "glob": "^13.0.0", - "semver": "^7.7.4", - "slugify": "^1.6.6", - "xcode": "^3.0.1", - "xml2js": "0.6.0" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/prebuild-config/node_modules/@expo/config-types": { - "version": "58.0.3", - "resolved": "https://registry.npmjs.org/@expo/config-types/-/config-types-58.0.3.tgz", - "integrity": "sha512-wyfrwkTT/hQHzwyqkXkngKxoOa8L6ovsTP4h/UukS1mTmssee5et6HOPoN5RtawdJPnm5JO28f//C/wXlpka8Q==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/@expo/prebuild-config/node_modules/@expo/json-file": { - "version": "11.2.1", - "resolved": "https://registry.npmjs.org/@expo/json-file/-/json-file-11.2.1.tgz", - "integrity": "sha512-UPhKoFCj8BcwgLB1rKQ1CuR/REITnZLiqxHEHOeH1tPsdXcHGtUDh0P5bLbr7oU0nKVdtJ5rzyKx8jniMQdESQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "json5": "^2.2.3" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/prebuild-config/node_modules/@expo/plist": { - "version": "0.10.1", - "resolved": "https://registry.npmjs.org/@expo/plist/-/plist-0.10.1.tgz", - "integrity": "sha512-nuNOqj+r/hGJbZ1Ax3jUpZaOB8UAMHUrISALJEUKaCieTflYj7224EqFWmMpriCGk9wXS1gH+9GGVnSj0tWzuQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@xmldom/xmldom": "^0.8.8", - "base64-js": "^1.5.1", - "xmlbuilder": "^15.1.1" - } - }, - "packages/expo-two-way-audio/node_modules/@expo/prebuild-config/node_modules/@expo/require-utils": { - "version": "58.0.4", - "resolved": "https://registry.npmjs.org/@expo/require-utils/-/require-utils-58.0.4.tgz", - "integrity": "sha512-DvjS5NCitXYcad2Woe1EMHJKcbhTbE77HX0BgOQGL2LFHE3q2H0n8kCWDPBOCVJ63Drap3c35nwoJwF5TQL7Tw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "@babel/core": "^7.25.2", - "@babel/plugin-transform-modules-commonjs": "^7.24.8" - }, - "peerDependencies": { - "typescript": "^5.0.0 || ^5.0.0-0 || ^6.0.0 || ^7.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/@expo/schema-utils": { - "version": "58.0.2", - "resolved": "https://registry.npmjs.org/@expo/schema-utils/-/schema-utils-58.0.2.tgz", - "integrity": "sha512-w28y8SG+5ZTdDdmH2ZnCQk9wHVwGzI9NqX5V4urJUFEnxbm7I129fJRkb8RIAJmMA1WKU5h3ONmranV473uaXQ==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/@expo/sdk-runtime-versions": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@expo/sdk-runtime-versions/-/sdk-runtime-versions-1.0.1.tgz", - "integrity": "sha512-kvisefkhxu8Fm/4M8G6DEqUaigrXfrSOm2lFw7hsk/nq0zchcp6B4wSk8rlheHY8FRi5iHxKtoVMGY/3M6h04A==", - "dev": true, - "license": "MIT" - }, - "packages/expo-two-way-audio/node_modules/@expo/spawn-async": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/@expo/spawn-async/-/spawn-async-1.8.0.tgz", - "integrity": "sha512-eb9xxd/LbuEGSdua4NumCu/McVB9EM+F/JxB9pWgnERw4HQ9XyTNH1KapG6oqLWR8TuRK2LQfzJlmNi94CVobw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "cross-spawn": "^7.0.6" - }, - "engines": { - "node": ">=12" - } - }, - "packages/expo-two-way-audio/node_modules/@jest/schemas": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-30.4.1.tgz", - "integrity": "sha512-i6b4qw5qnP8c5FEeBJg/uZQ4ddrkN6Ca8qISJh0pr7a5hfn3h3v5x60BEbOC7OYAGZNMs1LfFLwnW2CuK8F57Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@sinclair/typebox": "^0.34.0" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/babel-plugin-codegen": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/@react-native/babel-plugin-codegen/-/babel-plugin-codegen-0.88.0.tgz", - "integrity": "sha512-leGEnCcS7Q0hTxvzvhNtr8zGQpI1gfWqXjzC4UedsFmNMv6kIo4s70o0XbtM30ZXbpfWe4BcSC8NKWuak5sI4A==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/traverse": "^7.29.0", - "@react-native/codegen": "0.88.0" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/babel-preset": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/@react-native/babel-preset/-/babel-preset-0.88.0.tgz", - "integrity": "sha512-iMfAHhFGNegnReSY6CYaWHncvyDwHq8olRs0zp9nRRApMAoCiLyfo1dwL/f39qt/MreD6xIqUs9SrTPYWobY6g==", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "@babel/core": "^7.25.2", - "@babel/plugin-proposal-export-default-from": "^7.24.7", - "@babel/plugin-syntax-dynamic-import": "^7.8.3", - "@babel/plugin-syntax-export-default-from": "^7.24.7", - "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", - "@babel/plugin-syntax-optional-chaining": "^7.8.3", - "@babel/plugin-transform-async-generator-functions": "^7.25.4", - "@babel/plugin-transform-async-to-generator": "^7.24.7", - "@babel/plugin-transform-block-scoping": "^7.25.0", - "@babel/plugin-transform-class-properties": "^7.25.4", - "@babel/plugin-transform-classes": "^7.25.4", - "@babel/plugin-transform-destructuring": "^7.24.8", - "@babel/plugin-transform-flow-strip-types": "^7.25.2", - "@babel/plugin-transform-for-of": "^7.24.7", - "@babel/plugin-transform-modules-commonjs": "^7.24.8", - "@babel/plugin-transform-named-capturing-groups-regex": "^7.24.7", - "@babel/plugin-transform-nullish-coalescing-operator": "^7.24.7", - "@babel/plugin-transform-optional-catch-binding": "^7.24.7", - "@babel/plugin-transform-optional-chaining": "^7.24.8", - "@babel/plugin-transform-private-methods": "^7.24.7", - "@babel/plugin-transform-private-property-in-object": "^7.24.7", - "@babel/plugin-transform-react-display-name": "^7.24.7", - "@babel/plugin-transform-react-jsx": "^7.25.2", - "@babel/plugin-transform-react-jsx-self": "^7.24.7", - "@babel/plugin-transform-react-jsx-source": "^7.24.7", - "@babel/plugin-transform-regenerator": "^7.24.7", - "@babel/plugin-transform-runtime": "^7.24.7", - "@babel/plugin-transform-typescript": "^7.25.2", - "@babel/plugin-transform-unicode-regex": "^7.24.7", - "@react-native/babel-plugin-codegen": "0.88.0", - "babel-plugin-transform-flow-enums": "^0.0.2", - "flow-parser": "0.327.0", - "react-refresh": "^0.14.0" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - }, - "peerDependencies": { - "@babel/core": "*" - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/babel-preset/node_modules/flow-parser": { - "version": "0.327.0", - "resolved": "https://registry.npmjs.org/flow-parser/-/flow-parser-0.327.0.tgz", - "integrity": "sha512-/MYZ5hXWf5ozpbdfUDmazMgQXviLxWEiRLH3MppEGDdW0itRVqmB5UaU7QX+SBCDNiq+gEesSVn8nlxmPDyDkw==", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "flow-estree": "0.327.0" - }, - "engines": { - "node": ">=0.4.0" - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/codegen": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/@react-native/codegen/-/codegen-0.88.0.tgz", - "integrity": "sha512-SAGg+XfzsrPiYTscbKa9bo2/H2ei2TjyxW8RTMq2Ps661kRK3AnmpMGVfrEFshEMr3FGEbuQIvj86X98kaXlRA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/core": "^7.25.2", - "@babel/parser": "^7.29.0", - "flow-parser": "0.327.0", - "invariant": "^2.2.4", - "nullthrows": "^1.1.1", - "tinyglobby": "^0.2.15", - "yargs": "^17.6.2" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - }, - "peerDependencies": { - "@babel/core": "*" - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/codegen/node_modules/flow-parser": { - "version": "0.327.0", - "resolved": "https://registry.npmjs.org/flow-parser/-/flow-parser-0.327.0.tgz", - "integrity": "sha512-/MYZ5hXWf5ozpbdfUDmazMgQXviLxWEiRLH3MppEGDdW0itRVqmB5UaU7QX+SBCDNiq+gEesSVn8nlxmPDyDkw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "flow-estree": "0.327.0" - }, - "engines": { - "node": ">=0.4.0" - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/community-cli-plugin": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/@react-native/community-cli-plugin/-/community-cli-plugin-0.88.0.tgz", - "integrity": "sha512-WrQdXbjVt1gwAay8ZzYtpOi9ly99ksJ0VMYFdVcMe6nq3vtiRgqKRpHgCdN6ySIbtr5o+aJ+Vr7OTDY98ec/Ow==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@react-native/asset-utils": "0.88.0", - "@react-native/dev-middleware": "0.88.0", - "commander": "^12.0.0", - "debug": "^4.4.0", - "invariant": "^2.2.4", - "metro": "^0.87.1", - "semver": "^7.1.3" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - }, - "peerDependencies": { - "@react-native-community/cli": "*", - "@react-native/metro-config": "0.88.0" - }, - "peerDependenciesMeta": { - "@react-native-community/cli": { - "optional": true - }, - "@react-native/metro-config": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/debugger-frontend": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/@react-native/debugger-frontend/-/debugger-frontend-0.88.0.tgz", - "integrity": "sha512-v5cnBaaWhDRPcQv8EC20zj53jOAKH7u2wnzzXS4JTNu+diPC+cA2+kC7rq3eKI5vGhlAcG2kDPoViRuC0AY0oA==", - "dev": true, - "license": "BSD-3-Clause", - "peer": true, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/debugger-shell": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/@react-native/debugger-shell/-/debugger-shell-0.88.0.tgz", - "integrity": "sha512-p82zT8ZKNx7nIm/8zf8pi55sxm5KQBm8td47kzoJysTdqHLyPsRMUvDXtvCJIWadHSv7RJ6t/yiCc+IoImLBtw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "cross-spawn": "^7.0.6", - "debug": "^4.4.0", - "fb-dotslash": "0.5.8" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/dev-middleware": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/@react-native/dev-middleware/-/dev-middleware-0.88.0.tgz", - "integrity": "sha512-sHLxVHOwfkF672ZzMepNh4d3IKbrZy3qXDKWSwN5LC5VJkzzZ5FdmSPP4N/CCn2pcKJ4oSqvojXwN4De3Xk92A==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@isaacs/ttlcache": "^1.4.1", - "@react-native/debugger-frontend": "0.88.0", - "@react-native/debugger-shell": "0.88.0", - "connect": "^3.6.5", - "debug": "^4.4.0", - "invariant": "^2.2.4", - "nullthrows": "^1.1.1", - "open": "^8.4.2", - "serve-static": "^1.16.2", - "ws": "^7.5.10" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/dev-middleware/node_modules/ws": { - "version": "7.5.13", - "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.13.tgz", - "integrity": "sha512-rsKI6xDBFVf4r/x8XyChGK04QR/XHroxs/jUcoWvtEZM8TPU/X/uIY9B1CsSzYws9ZJb/6bbBu7dPhFW00CAoA==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=8.3.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": "^5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/gradle-plugin": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/@react-native/gradle-plugin/-/gradle-plugin-0.88.0.tgz", - "integrity": "sha512-4jPSKslOfJj8NKY/jv9qmWkxZYmqPyamoS3Vs0JOFxw9t4PM6L/ea0fUsjNV0LxC9zJlvWilPJOCTOf7h8wlyw==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/js-polyfills": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/@react-native/js-polyfills/-/js-polyfills-0.88.0.tgz", - "integrity": "sha512-Iq6v4+EWdOLv0M1+BpADQJBVfInl6FkABXCIBSi0FbvHahEYT+Y4UJ7Cm96p18gbEN1VKzqz3nbBbwLA6bx0rQ==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/metro-babel-transformer": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/@react-native/metro-babel-transformer/-/metro-babel-transformer-0.88.0.tgz", - "integrity": "sha512-xsUfzXrqKXeD7sBja7hkyBG32AGIwWJ3IEZ+UcNMRTR/sucnXXZ6Do40qXoeY52YC8b9//J+p51JIp2CC0DZKA==", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "@babel/core": "^7.25.2", - "@react-native/babel-preset": "0.88.0", - "flow-parser": "0.327.0", - "nullthrows": "^1.1.1" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - }, - "peerDependencies": { - "@babel/core": "*" - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/metro-babel-transformer/node_modules/flow-parser": { - "version": "0.327.0", - "resolved": "https://registry.npmjs.org/flow-parser/-/flow-parser-0.327.0.tgz", - "integrity": "sha512-/MYZ5hXWf5ozpbdfUDmazMgQXviLxWEiRLH3MppEGDdW0itRVqmB5UaU7QX+SBCDNiq+gEesSVn8nlxmPDyDkw==", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "flow-estree": "0.327.0" - }, - "engines": { - "node": ">=0.4.0" - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/metro-config": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/@react-native/metro-config/-/metro-config-0.88.0.tgz", - "integrity": "sha512-iPV2HNXlPs7xQDBJJGIjkH0x2psZwJeRIEpfSqxgqLaO5eEfE2Ccicfz2OBHBcIC5jKGGa4IoI/e26zMNDuTMQ==", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "@react-native/js-polyfills": "0.88.0", - "@react-native/metro-babel-transformer": "0.88.0", - "metro-config": "^0.87.1", - "metro-runtime": "^0.87.1" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/@react-native/normalize-colors": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/@react-native/normalize-colors/-/normalize-colors-0.88.0.tgz", - "integrity": "sha512-eZCu3tGAQCfvMCPQJVY4dmoMX8ZZYBvqIGHX7lwOYyzNK+Dl8e5ky7ZoXub1Rq75oSrQXNNmSP2CDjNNXXZpFQ==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/@sinclair/typebox": { - "version": "0.34.49", - "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.34.49.tgz", - "integrity": "sha512-brySQQs7Jtn0joV8Xh9ZV/hZb9Ozb0pmazDIASBkYKCjXrXU3mpcFahmK/z4YDhGkQvP9mWJbVyahdtU5wQA+A==", - "dev": true, - "license": "MIT" - }, "packages/expo-two-way-audio/node_modules/@types/react": { "version": "18.3.28", "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.28.tgz", @@ -39725,1390 +40328,6 @@ "csstype": "^3.2.2" } }, - "packages/expo-two-way-audio/node_modules/@typescript-eslint/scope-manager": { - "version": "8.61.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.61.1.tgz", - "integrity": "sha512-L2bdIeoQS8FlKAvONAr20w6OcLXeB+qiDKbAooS9A0Ben+iSIkBef0FxqwKWYqt5sa0i4KJtxVyVmhMylKzF5w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/types": "8.61.1", - "@typescript-eslint/visitor-keys": "8.61.1" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "packages/expo-two-way-audio/node_modules/@typescript-eslint/types": { - "version": "8.61.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.61.1.tgz", - "integrity": "sha512-G+CRlPqLv7Bz1IZVs03x5K59F1veqL0EJUROAdGhKsEq8qOiRiZbI+HUojPq5l0fEGOKModD9br6lObhB8zkoA==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "packages/expo-two-way-audio/node_modules/@typescript-eslint/visitor-keys": { - "version": "8.61.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.61.1.tgz", - "integrity": "sha512-6fJ9MHWtK14C1DSkiMlHUSOmrVebL7150xZJBlJiL62jjhIA4JmOq6flwBgDxIdBKKdoiZRel+dfPD5MLfny3w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/types": "8.61.1", - "eslint-visitor-keys": "^5.0.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "packages/expo-two-way-audio/node_modules/@xmldom/xmldom": { - "version": "0.8.13", - "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.13.tgz", - "integrity": "sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/agent-base": { - "version": "7.1.4", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", - "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 14" - } - }, - "packages/expo-two-way-audio/node_modules/ansi-styles": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", - "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "packages/expo-two-way-audio/node_modules/babel-plugin-react-native-web": { - "version": "0.21.4", - "resolved": "https://registry.npmjs.org/babel-plugin-react-native-web/-/babel-plugin-react-native-web-0.21.4.tgz", - "integrity": "sha512-FSclsDTGi5EcvpbW3TM7s8GLWwQqo5wI9zQqJr2m0IoJRenSkp1+bVvdeZXTNznI5Ms9Bry7DLBR+C5Shb9gtw==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/babel-plugin-syntax-hermes-parser": { - "version": "0.36.1", - "resolved": "https://registry.npmjs.org/babel-plugin-syntax-hermes-parser/-/babel-plugin-syntax-hermes-parser-0.36.1.tgz", - "integrity": "sha512-ycduwJbvdvIMmVvlAZqGggS+pm5Eu4Bk9pcV9Sm2Z4PJNRVsKkv0g7vHj+LeuC1gHTeF67sJXFOq61IlqCa2hA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "hermes-parser": "0.36.1" - } - }, - "packages/expo-two-way-audio/node_modules/babel-plugin-syntax-hermes-parser/node_modules/hermes-estree": { - "version": "0.36.1", - "resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.36.1.tgz", - "integrity": "sha512-guv1nQ6IJ7S83NRFPWc3SA7IBZrdNC9kapwOq6uXvF4wP+sDCgjzQbKPCoyYmoyZRzztF/n/c36l/rccCZSiCw==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/babel-plugin-syntax-hermes-parser/node_modules/hermes-parser": { - "version": "0.36.1", - "resolved": "https://registry.npmjs.org/hermes-parser/-/hermes-parser-0.36.1.tgz", - "integrity": "sha512-GApNk4zLHi2UWoWZZkx7LNCOSzLSc5lB55pZ/PhK7ycFeg7u5LcF88p/WbpIi1XUDtE0MpHE3uRR3u3KB7TjSQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "hermes-estree": "0.36.1" - } - }, - "packages/expo-two-way-audio/node_modules/balanced-match": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", - "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", - "dev": true, - "license": "MIT", - "engines": { - "node": "18 || 20 || >=22" - } - }, - "packages/expo-two-way-audio/node_modules/brace-expansion": { - "version": "5.0.6", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.6.tgz", - "integrity": "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^4.0.2" - }, - "engines": { - "node": "18 || 20 || >=22" - } - }, - "packages/expo-two-way-audio/node_modules/cli-cursor": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-2.1.0.tgz", - "integrity": "sha512-8lgKz8LmCRYZZQDpRyT2m5rKJ08TnU4tR9FFFW2rxpxR1FzWi4PQ/NfyODchAatHaUgnSPVcx/R5w6NuTBzFiw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "restore-cursor": "^2.0.0" - }, - "engines": { - "node": ">=4" - } - }, - "packages/expo-two-way-audio/node_modules/color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "color-name": "1.1.3" - } - }, - "packages/expo-two-way-audio/node_modules/color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/commander": { - "version": "12.1.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", - "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - } - }, - "packages/expo-two-way-audio/node_modules/content-type": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", - "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "packages/expo-two-way-audio/node_modules/escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=0.8.0" - } - }, - "packages/expo-two-way-audio/node_modules/eslint-config-prettier": { - "version": "9.1.2", - "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-9.1.2.tgz", - "integrity": "sha512-iI1f+D2ViGn+uvv5HuHVUamg8ll4tN+JRHGc6IJi4TP9Kl976C57fzPXgseXNs8v0iA8aSJpHsTWjDb9QJamGQ==", - "dev": true, - "license": "MIT", - "bin": { - "eslint-config-prettier": "bin/cli.js" - }, - "peerDependencies": { - "eslint": ">=7.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/eslint-config-universe": { - "version": "15.2.0", - "resolved": "https://registry.npmjs.org/eslint-config-universe/-/eslint-config-universe-15.2.0.tgz", - "integrity": "sha512-n2662q/mM+2pTFVz7ELosqhN+/nbR75Ut/4vLme40kKSHHe0oPbPMxgPqyYrASlANuSDP4aAJ71rRviDMCZTxg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/eslint-plugin": "^8.59.0", - "@typescript-eslint/parser": "^8.59.0", - "eslint-config-prettier": "^9.1.0", - "eslint-plugin-import": "^2.31.0", - "eslint-plugin-n": "^17.17.0", - "eslint-plugin-node": "^11.1.0", - "eslint-plugin-prettier": "^5.2.6", - "eslint-plugin-react": "^7.37.5", - "eslint-plugin-react-hooks": "^7.0.0", - "globals": "^16.0.0" - }, - "peerDependencies": { - "eslint": ">=8.10", - "prettier": ">=3" - }, - "peerDependenciesMeta": { - "prettier": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/eslint-config-universe/node_modules/@typescript-eslint/eslint-plugin": { - "version": "8.61.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.61.1.tgz", - "integrity": "sha512-ZPlVl3PB3et/59Ne0fv/sci6ZXz4T4Hp4nTJ56i/Y0gR89ARb+KphojTq6j+56E5PIezmOIOOWyY+aWQFd+IkQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@eslint-community/regexpp": "^4.12.2", - "@typescript-eslint/scope-manager": "8.61.1", - "@typescript-eslint/type-utils": "8.61.1", - "@typescript-eslint/utils": "8.61.1", - "@typescript-eslint/visitor-keys": "8.61.1", - "ignore": "^7.0.5", - "natural-compare": "^1.4.0", - "ts-api-utils": "^2.5.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "@typescript-eslint/parser": "^8.61.1", - "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", - "typescript": ">=4.8.4 <6.1.0" - } - }, - "packages/expo-two-way-audio/node_modules/eslint-config-universe/node_modules/@typescript-eslint/parser": { - "version": "8.61.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.61.1.tgz", - "integrity": "sha512-PJ5vePq5/ognBbrIcoC5+SHO5dfpeLPzP9FpLkzWrguoYQEeeSjlJpVwOpo1JRSTEi7dRcwNy4h4dzV70PqHcg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/scope-manager": "8.61.1", - "@typescript-eslint/types": "8.61.1", - "@typescript-eslint/typescript-estree": "8.61.1", - "@typescript-eslint/visitor-keys": "8.61.1", - "debug": "^4.4.3" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", - "typescript": ">=4.8.4 <6.1.0" - } - }, - "packages/expo-two-way-audio/node_modules/eslint-config-universe/node_modules/@typescript-eslint/project-service": { - "version": "8.61.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.61.1.tgz", - "integrity": "sha512-PrC4JYGmR241lYnfhmKGTXkFqv8+ymbTFgSAY0fVXpY82/QkMw5TZPl+vGzuDDU2QYJk9fIDOBTntF+yDv9LEA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/tsconfig-utils": "^8.61.1", - "@typescript-eslint/types": "^8.61.1", - "debug": "^4.4.3" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "typescript": ">=4.8.4 <6.1.0" - } - }, - "packages/expo-two-way-audio/node_modules/eslint-config-universe/node_modules/@typescript-eslint/tsconfig-utils": { - "version": "8.61.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.61.1.tgz", - "integrity": "sha512-UN/H4di+OO7EWx2ovME+8t31YO+KVnK0RRKEHR3kOt21/Ay8BOq3M1OMvWs5vNiqcFCYGYoxK3MXPZzmMUE+yg==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "typescript": ">=4.8.4 <6.1.0" - } - }, - "packages/expo-two-way-audio/node_modules/eslint-config-universe/node_modules/@typescript-eslint/type-utils": { - "version": "8.61.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.61.1.tgz", - "integrity": "sha512-GYRicKmVK0C4fsKgaACaknOUAq9Oa2kwsjnpFhFcS/5p4Ht5IP9OVLbgIgcK4SRk92nVHFluurg1lumD9dBcLw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/types": "8.61.1", - "@typescript-eslint/typescript-estree": "8.61.1", - "@typescript-eslint/utils": "8.61.1", - "debug": "^4.4.3", - "ts-api-utils": "^2.5.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", - "typescript": ">=4.8.4 <6.1.0" - } - }, - "packages/expo-two-way-audio/node_modules/eslint-config-universe/node_modules/@typescript-eslint/typescript-estree": { - "version": "8.61.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.61.1.tgz", - "integrity": "sha512-u+oQD3BqYWPc8YV9Zab4vaJElJuwOLPRc10Jm1o/qS+6Qwen14HCWwx0Seo4LnSn2wxea2Ik8DxPt2/FHmuhrg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/project-service": "8.61.1", - "@typescript-eslint/tsconfig-utils": "8.61.1", - "@typescript-eslint/types": "8.61.1", - "@typescript-eslint/visitor-keys": "8.61.1", - "debug": "^4.4.3", - "minimatch": "^10.2.2", - "semver": "^7.7.3", - "tinyglobby": "^0.2.15", - "ts-api-utils": "^2.5.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "typescript": ">=4.8.4 <6.1.0" - } - }, - "packages/expo-two-way-audio/node_modules/eslint-config-universe/node_modules/@typescript-eslint/utils": { - "version": "8.61.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.61.1.tgz", - "integrity": "sha512-1+P/3Dj6jvtybE1q0HQ6yBt/gq+oKJyLdEv4HdnqasaEXRSYCAsD59mXEVQnM/ULNdQxbX77tdG4jPRjIS6knA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@eslint-community/eslint-utils": "^4.9.1", - "@typescript-eslint/scope-manager": "8.61.1", - "@typescript-eslint/types": "8.61.1", - "@typescript-eslint/typescript-estree": "8.61.1" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", - "typescript": ">=4.8.4 <6.1.0" - } - }, - "packages/expo-two-way-audio/node_modules/eslint-config-universe/node_modules/ts-api-utils": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", - "integrity": "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18.12" - }, - "peerDependencies": { - "typescript": ">=4.8.4" - } - }, - "packages/expo-two-way-audio/node_modules/eslint-plugin-react-hooks": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-7.1.1.tgz", - "integrity": "sha512-f2I7Gw6JbvCexzIInuSbZpfdQ44D7iqdWX01FKLvrPgqxoE7oMj8clOfto8U6vYiz4yd5oKu39rRSVOe1zRu0g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/core": "^7.24.4", - "@babel/parser": "^7.24.4", - "hermes-parser": "^0.25.1", - "zod": "^3.25.0 || ^4.0.0", - "zod-validation-error": "^3.5.0 || ^4.0.0" - }, - "engines": { - "node": ">=18" - }, - "peerDependencies": { - "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0 || ^10.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/eslint-visitor-keys": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", - "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "packages/expo-two-way-audio/node_modules/expo-asset": { - "version": "58.0.16", - "resolved": "https://registry.npmjs.org/expo-asset/-/expo-asset-58.0.16.tgz", - "integrity": "sha512-beR3uusLA+rFo+6Ug0L7FPR4b6y/37VwtYW2Jig/i+3Co+oyYCTnvVuFPWhb05W9TOZRxdHUEI569fVKIgtYAA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/image-utils": "^0.12.5", - "expo-constants": "~58.0.12" - }, - "peerDependencies": { - "expo": "*", - "react": "*", - "react-native": "*" - } - }, - "packages/expo-two-way-audio/node_modules/expo-constants": { - "version": "58.0.12", - "resolved": "https://registry.npmjs.org/expo-constants/-/expo-constants-58.0.12.tgz", - "integrity": "sha512-d3/dsps32nU4m6YJQbXQ1dIfn58GxfmJjTnZ0WtnhdSHTdG/oVsOakLqYRlX/FaLUKkQOSHXMf7hyCx+2a/HSQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/env": "~2.5.2", - "@expo/require-utils": "^58.0.4" - }, - "peerDependencies": { - "expo": "*", - "react-native": "*" - } - }, - "packages/expo-two-way-audio/node_modules/expo-constants/node_modules/@expo/require-utils": { - "version": "58.0.4", - "resolved": "https://registry.npmjs.org/@expo/require-utils/-/require-utils-58.0.4.tgz", - "integrity": "sha512-DvjS5NCitXYcad2Woe1EMHJKcbhTbE77HX0BgOQGL2LFHE3q2H0n8kCWDPBOCVJ63Drap3c35nwoJwF5TQL7Tw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "@babel/core": "^7.25.2", - "@babel/plugin-transform-modules-commonjs": "^7.24.8" - }, - "peerDependencies": { - "typescript": "^5.0.0 || ^5.0.0-0 || ^6.0.0 || ^7.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-file-system": { - "version": "58.0.9", - "resolved": "https://registry.npmjs.org/expo-file-system/-/expo-file-system-58.0.9.tgz", - "integrity": "sha512-JT0km3Wa+wDz/7Rli8ifreoMnmk68ulf/uaWzRA26xm/4K+jGTY+cDhnboRmpmXUCBkED6uqxWmNoXjaVU9VUw==", - "dev": true, - "license": "MIT", - "peer": true, - "peerDependencies": { - "expo": "*", - "react-native": "*" - } - }, - "packages/expo-two-way-audio/node_modules/expo-font": { - "version": "58.0.8", - "resolved": "https://registry.npmjs.org/expo-font/-/expo-font-58.0.8.tgz", - "integrity": "sha512-i9HKj/ljdmmjLamYQEkI4wXJB9+ap7AG5CpCqK/bgwwy45y5T8+1lpNbYgRXE7aQgmDjPpzd09wX6dOZkHfrxg==", - "dev": true, - "license": "MIT", - "peer": true, - "peerDependencies": { - "expo": "*", - "react": "*", - "react-native": "*" - } - }, - "packages/expo-two-way-audio/node_modules/expo-keep-awake": { - "version": "58.0.3", - "resolved": "https://registry.npmjs.org/expo-keep-awake/-/expo-keep-awake-58.0.3.tgz", - "integrity": "sha512-wLRF+XeVsD/Rt/ZyX+A0mk1brdf8vefWizNAPzqV5eOCgkj23LCRZdN8gUi5X8UwyR8UJ7Y7Dzdz4YDGB/4c9Q==", - "dev": true, - "license": "MIT", - "peer": true, - "peerDependencies": { - "expo": "*", - "react": "*" - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/expo-module-scripts/-/expo-module-scripts-5.0.8.tgz", - "integrity": "sha512-3YkAic3E6QGQuNEIchq6/0GGSBwR2C70AhDUF7VI7/N3THwUpeqZrX20FxHKN95/wclHs1ljrGvRX+2YTgXxiw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/cli": "^7.23.4", - "@babel/plugin-transform-export-namespace-from": "^7.23.4", - "@babel/preset-env": "^7.23.8", - "@babel/preset-typescript": "^7.23.3", - "@expo/npm-proofread": "^1.0.1", - "@testing-library/react-native": "^13.2.0", - "@tsconfig/node18": "^18.2.2", - "@types/jest": "^29.2.1", - "babel-plugin-dynamic-import-node": "^2.3.3", - "babel-preset-expo": "~54.0.7", - "commander": "^12.1.0", - "eslint-config-universe": "^15.0.3", - "glob": "^13.0.0", - "jest-expo": "~54.0.13", - "jest-snapshot-prettier": "npm:prettier@^2", - "jest-watch-typeahead": "2.2.1", - "resolve-workspace-root": "^2.0.0", - "ts-jest": "~29.0.4", - "typescript": "^5.9.2" - }, - "bin": { - "expo-module": "bin/expo-module.js" - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/@expo/config-plugins": { - "version": "58.0.9", - "resolved": "https://registry.npmjs.org/@expo/config-plugins/-/config-plugins-58.0.9.tgz", - "integrity": "sha512-HyP7V1QgDxeHcOEh4qQH7cfK7cI7wNp0y9lszAu98SRYCshhDbwB9gWpFfnpX1GQUtgiqG4Hvgh1z3ntcGwAjw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/config-types": "^58.0.3", - "@expo/json-file": "~11.2.1", - "@expo/plist": "^0.10.1", - "@expo/require-utils": "^58.0.4", - "@expo/sdk-runtime-versions": "^1.0.1", - "chalk": "^4.1.2", - "debug": "^4.3.5", - "getenv": "^2.0.0", - "glob": "^13.0.0", - "semver": "^7.7.4", - "slugify": "^1.6.6", - "xcode": "^3.0.1", - "xml2js": "0.6.0" - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/@expo/config-plugins/node_modules/@expo/json-file": { - "version": "11.2.1", - "resolved": "https://registry.npmjs.org/@expo/json-file/-/json-file-11.2.1.tgz", - "integrity": "sha512-UPhKoFCj8BcwgLB1rKQ1CuR/REITnZLiqxHEHOeH1tPsdXcHGtUDh0P5bLbr7oU0nKVdtJ5rzyKx8jniMQdESQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "json5": "^2.2.3" - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/@expo/config-plugins/node_modules/@expo/require-utils": { - "version": "58.0.4", - "resolved": "https://registry.npmjs.org/@expo/require-utils/-/require-utils-58.0.4.tgz", - "integrity": "sha512-DvjS5NCitXYcad2Woe1EMHJKcbhTbE77HX0BgOQGL2LFHE3q2H0n8kCWDPBOCVJ63Drap3c35nwoJwF5TQL7Tw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "@babel/core": "^7.25.2", - "@babel/plugin-transform-modules-commonjs": "^7.24.8" - }, - "peerDependencies": { - "typescript": "^5.0.0 || ^5.0.0-0 || ^6.0.0 || ^7.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/@expo/config-types": { - "version": "58.0.3", - "resolved": "https://registry.npmjs.org/@expo/config-types/-/config-types-58.0.3.tgz", - "integrity": "sha512-wyfrwkTT/hQHzwyqkXkngKxoOa8L6ovsTP4h/UukS1mTmssee5et6HOPoN5RtawdJPnm5JO28f//C/wXlpka8Q==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/@expo/metro-runtime": { - "version": "58.0.14", - "resolved": "https://registry.npmjs.org/@expo/metro-runtime/-/metro-runtime-58.0.14.tgz", - "integrity": "sha512-IIvTo+RpN5jZVuYspQdECsxQ03VGWjZnGS6wtr9U7DERBpykUe+ZSHDZ1hsrvQ7HAucsVoKr9np0xAscGEuXtg==", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "@expo/log-box": "^58.0.12", - "anser": "^1.4.9", - "pretty-format": "^29.7.0", - "stacktrace-parser": "^0.1.10", - "whatwg-fetch": "^3.0.0" - }, - "peerDependencies": { - "@expo/log-box": "^58.0.12", - "expo": "*", - "react": "*", - "react-dom": "*", - "react-native": "*" - }, - "peerDependenciesMeta": { - "react-dom": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/@expo/metro-runtime/node_modules/pretty-format": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", - "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "@jest/schemas": "^29.6.3", - "ansi-styles": "^5.0.0", - "react-is": "^18.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/@expo/plist": { - "version": "0.10.1", - "resolved": "https://registry.npmjs.org/@expo/plist/-/plist-0.10.1.tgz", - "integrity": "sha512-nuNOqj+r/hGJbZ1Ax3jUpZaOB8UAMHUrISALJEUKaCieTflYj7224EqFWmMpriCGk9wXS1gH+9GGVnSj0tWzuQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@xmldom/xmldom": "^0.8.8", - "base64-js": "^1.5.1", - "xmlbuilder": "^15.1.1" - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/@jest/schemas": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz", - "integrity": "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@sinclair/typebox": "^0.27.8" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/@react-native/virtualized-lists": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/@react-native/virtualized-lists/-/virtualized-lists-0.88.0.tgz", - "integrity": "sha512-zpZIOAbobdS93edwHkNUdGDzvElNeQJqukRERRPns3/ucPvuMd2G4fYpmVJSVjhxtGCcLLB1PFndLYYfwaYoBQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "invariant": "^2.2.4", - "nullthrows": "^1.1.1" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - }, - "peerDependencies": { - "@types/react": "^19.2.0", - "react": "*", - "react-native": "0.88.0" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/@sinclair/typebox": { - "version": "0.27.12", - "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.12.tgz", - "integrity": "sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/@testing-library/react-native": { - "version": "13.3.3", - "resolved": "https://registry.npmjs.org/@testing-library/react-native/-/react-native-13.3.3.tgz", - "integrity": "sha512-k6Mjsd9dbZgvY4Bl7P1NIpePQNi+dfYtlJ5voi9KQlynxSyQkfOgJmYGCYmw/aSgH/rUcFvG8u5gd4npzgRDyg==", - "dev": true, - "license": "MIT", - "dependencies": { - "jest-matcher-utils": "^30.0.5", - "picocolors": "^1.1.1", - "pretty-format": "^30.0.5", - "redent": "^3.0.0" - }, - "engines": { - "node": ">=18" - }, - "peerDependencies": { - "jest": ">=29.0.0", - "react": ">=18.2.0", - "react-native": ">=0.71", - "react-test-renderer": ">=18.2.0" - }, - "peerDependenciesMeta": { - "jest": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/@types/react": { - "version": "19.3.0", - "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", - "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "csstype": "^3.2.2" - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/expo": { - "version": "58.0.14", - "resolved": "https://registry.npmjs.org/expo/-/expo-58.0.14.tgz", - "integrity": "sha512-M05O++KRgG4NA6kQ9AP60kbN8xqHJ6S8uTXdtkeiwcGVIYzdu2kaUXJyraVturvePO/Mf4PWa0C9+JggrHITwA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/runtime": "^7.20.0", - "@expo/cli": "^58.1.11", - "@expo/config": "~58.0.6", - "@expo/config-plugins": "~58.0.9", - "@expo/devtools": "~58.0.2", - "@expo/dom-webview": "~58.0.2", - "@expo/fingerprint": "^0.21.5", - "@expo/local-build-cache-provider": "^58.0.6", - "@expo/log-box": "^58.0.12", - "@expo/log-box-utils": "^58.0.2", - "@expo/metro": "~58.0.0", - "@expo/metro-config": "~58.0.14", - "@ungap/structured-clone": "^1.3.0", - "babel-preset-expo": "~58.0.17", - "expo-asset": "~58.0.16", - "expo-constants": "~58.0.12", - "expo-file-system": "~58.0.9", - "expo-font": "~58.0.8", - "expo-keep-awake": "~58.0.3", - "expo-modules-autolinking": "~58.0.13", - "expo-modules-core": "~58.0.22", - "pretty-format": "^29.7.0", - "react-refresh": "^0.14.2", - "whatwg-url-minimum": "^0.2.0" - }, - "bin": { - "expo": "bin/cli", - "expo-modules-autolinking": "bin/autolinking", - "fingerprint": "bin/fingerprint" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || ^26.0.0 || >=27.0.0" - }, - "peerDependencies": { - "@expo/dom-webview": "*", - "@expo/metro-runtime": "*", - "react": "*", - "react-dom": "*", - "react-native": "*", - "react-native-web": "*", - "react-native-webview": "*" - }, - "peerDependenciesMeta": { - "@expo/dom-webview": { - "optional": true - }, - "@expo/metro-runtime": { - "optional": true - }, - "react-dom": { - "optional": true - }, - "react-native-web": { - "optional": true - }, - "react-native-webview": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/expo-modules-core": { - "version": "58.0.22", - "resolved": "https://registry.npmjs.org/expo-modules-core/-/expo-modules-core-58.0.22.tgz", - "integrity": "sha512-T3YJYziFkF4JlGDpX4zCl91oIxz1Skq5sp1LFVO+GL/BARSIXk013QWGdRZrvt+wMxoVaql5dpOdPdP5q2+0jQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "expo-modules-jsi": "~58.0.15", - "expo-modules-macros": "0.20.0", - "invariant": "^2.2.4" - }, - "peerDependencies": { - "react": "*", - "react-native": "*", - "react-native-worklets": ">=0.13.0" - }, - "peerDependenciesMeta": { - "react-native-worklets": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/expo/node_modules/@expo/cli": { - "version": "58.1.11", - "resolved": "https://registry.npmjs.org/@expo/cli/-/cli-58.1.11.tgz", - "integrity": "sha512-wkFTSLXXYqLkRT5oy4DnLuTOtbFIu3qTiXHSHkFSqUBTHiE92y3bOIwM3UN7Y1ys18qVJge8lXjezaEfsHmijQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/code-signing-certificates": "^0.0.7", - "@expo/config": "~58.0.6", - "@expo/config-plugins": "~58.0.9", - "@expo/devcert": "^1.2.2", - "@expo/env": "~2.5.2", - "@expo/image-utils": "^0.12.5", - "@expo/inline-modules": "^0.2.6", - "@expo/json-file": "^11.2.1", - "@expo/log-box": "^58.0.12", - "@expo/log-box-utils": "^58.0.2", - "@expo/metro": "~58.0.0", - "@expo/metro-config": "58.0.14", - "@expo/metro-file-map": "^58.0.5", - "@expo/osascript": "^2.8.1", - "@expo/package-manager": "^1.14.2", - "@expo/platforms": "^58.0.1", - "@expo/plist": "^0.10.1", - "@expo/prebuild-config": "^58.0.14", - "@expo/require-utils": "^58.0.4", - "@expo/router-server": "^58.0.14", - "@expo/schema-utils": "^58.0.2", - "@expo/spawn-async": "^1.8.0", - "@expo/ws-tunnel": "^2.0.1", - "@expo/xcpretty": "^4.4.6", - "@react-native/asset-utils": "0.88.0", - "@react-native/dev-middleware": "0.88.0", - "@react-native/js-polyfills": "0.88.0", - "2g": "^1.0.1", - "accepts": "^1.3.8", - "agent-cli-detector": "0.1.7", - "arg": "^5.0.2", - "bplist-creator": "0.1.0", - "bplist-parser": "^0.3.1", - "chalk": "^4.0.0", - "ci-info": "^3.3.0", - "compression": "^1.7.4", - "connect": "^3.7.0", - "dnssd-advertise": "^1.1.6", - "expo-server": "^58.0.5", - "fetch-nodeshim": "^0.4.10", - "getenv": "^2.0.0", - "glob": "^13.0.0", - "lan-network": "^0.2.1", - "multitars": "^1.0.2", - "node-forge": "^1.4.0", - "npm-package-arg": "^11.0.0", - "ora": "^3.4.0", - "picomatch": "^4.0.4", - "pretty-format": "^29.7.0", - "progress": "^2.0.3", - "prompts": "^2.3.2", - "resolve-from": "^5.0.0", - "sandbox-cli-detector": "^0.2.0", - "semver": "^7.7.4", - "send": "^0.19.0", - "slugify": "^1.3.4", - "stacktrace-parser": "^0.1.10", - "structured-headers": "^0.4.1", - "terminal-link": "^2.1.1", - "toqr": "^0.1.1", - "wrap-ansi": "^7.0.0", - "ws": "^8.12.1", - "zod": "^3.25.76" - }, - "bin": { - "expo-internal": "bin/cli.js" - }, - "peerDependencies": { - "expo": "*", - "expo-router": "*", - "react-native": "*" - }, - "peerDependenciesMeta": { - "expo-router": { - "optional": true - }, - "react-native": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/expo/node_modules/@expo/cli/node_modules/@expo/router-server": { - "version": "58.0.14", - "resolved": "https://registry.npmjs.org/@expo/router-server/-/router-server-58.0.14.tgz", - "integrity": "sha512-RSzQYMA+Tv2eTemhjhzpx8+hL+pMC30JTVqAWrk5AZwht+OgaKZar/gHmj4iJf7n3rq+GG6KujrkKF9xAXLz2w==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "debug": "^4.3.4" - }, - "peerDependencies": { - "@expo/metro-runtime": "^58.0.14", - "expo": "*", - "expo-constants": "^58.0.12", - "expo-font": "^58.0.8", - "expo-router": "*", - "expo-server": "^58.0.5", - "react": "*", - "react-dom": "*", - "react-server-dom-webpack": "~19.0.1 || ~19.1.2 || ~19.2.1 || ~19.3.0" - }, - "peerDependenciesMeta": { - "@expo/metro-runtime": { - "optional": true - }, - "expo-router": { - "optional": true - }, - "react-dom": { - "optional": true - }, - "react-server-dom-webpack": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/expo/node_modules/@expo/config": { - "version": "58.0.6", - "resolved": "https://registry.npmjs.org/@expo/config/-/config-58.0.6.tgz", - "integrity": "sha512-PT1qv4s/R5A/NxXb4efGlFsYF5Consi7F8xSsJBAN090EGDr6U1EDQGOijFqzDc3JA2epD8zjKLJLOVB9YOewg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/config-plugins": "~58.0.9", - "@expo/config-types": "^58.0.3", - "@expo/json-file": "^11.2.1", - "@expo/platforms": "^58.0.1", - "@expo/require-utils": "^58.0.4", - "deepmerge": "^4.3.1", - "getenv": "^2.0.0", - "glob": "^13.0.0", - "resolve-workspace-root": "^2.0.0", - "semver": "^7.7.4", - "slugify": "^1.3.4" - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/expo/node_modules/@expo/json-file": { - "version": "11.2.1", - "resolved": "https://registry.npmjs.org/@expo/json-file/-/json-file-11.2.1.tgz", - "integrity": "sha512-UPhKoFCj8BcwgLB1rKQ1CuR/REITnZLiqxHEHOeH1tPsdXcHGtUDh0P5bLbr7oU0nKVdtJ5rzyKx8jniMQdESQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "json5": "^2.2.3" - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/expo/node_modules/@expo/require-utils": { - "version": "58.0.4", - "resolved": "https://registry.npmjs.org/@expo/require-utils/-/require-utils-58.0.4.tgz", - "integrity": "sha512-DvjS5NCitXYcad2Woe1EMHJKcbhTbE77HX0BgOQGL2LFHE3q2H0n8kCWDPBOCVJ63Drap3c35nwoJwF5TQL7Tw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "@babel/core": "^7.25.2", - "@babel/plugin-transform-modules-commonjs": "^7.24.8" - }, - "peerDependencies": { - "typescript": "^5.0.0 || ^5.0.0-0 || ^6.0.0 || ^7.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/expo/node_modules/2g": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/2g/-/2g-1.0.1.tgz", - "integrity": "sha512-+uViadKOS/wwR4pFu5g8TPn3QHpKqoX19JHCnp8k/3cLpImdcXozwvZA6Q/5PeW3AcU8neL8faaMidBcv7o8CA==", - "dev": true, - "license": "MIT", - "peer": true, - "bin": { - "2g": "bin/cli.js" - }, - "peerDependencies": { - "typescript": ">=5.8.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/expo/node_modules/babel-preset-expo": { - "version": "58.0.17", - "resolved": "https://registry.npmjs.org/babel-preset-expo/-/babel-preset-expo-58.0.17.tgz", - "integrity": "sha512-Rrqc/Z5Idc4bG2/PrEh725t3kvuAc7jUKCJ+wZVU9KXk2bKSdqAniXxQa8aph9aHdv4h5sGKLpMXMaMNz/4+Og==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/generator": "^7.20.5", - "@babel/helper-module-imports": "^7.25.9", - "@babel/plugin-proposal-decorators": "^7.12.9", - "@babel/plugin-proposal-export-default-from": "^7.24.7", - "@babel/plugin-syntax-dynamic-import": "^7.8.3", - "@babel/plugin-syntax-export-default-from": "^7.24.7", - "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", - "@babel/plugin-syntax-optional-chaining": "^7.8.3", - "@babel/plugin-transform-async-generator-functions": "^7.25.4", - "@babel/plugin-transform-async-to-generator": "^7.24.7", - "@babel/plugin-transform-block-scoping": "^7.25.0", - "@babel/plugin-transform-class-properties": "^7.25.4", - "@babel/plugin-transform-class-static-block": "^7.27.1", - "@babel/plugin-transform-classes": "^7.25.4", - "@babel/plugin-transform-destructuring": "^7.24.8", - "@babel/plugin-transform-export-namespace-from": "^7.25.9", - "@babel/plugin-transform-flow-strip-types": "^7.25.2", - "@babel/plugin-transform-for-of": "^7.24.7", - "@babel/plugin-transform-logical-assignment-operators": "^7.24.7", - "@babel/plugin-transform-modules-commonjs": "^7.24.8", - "@babel/plugin-transform-named-capturing-groups-regex": "^7.24.7", - "@babel/plugin-transform-nullish-coalescing-operator": "^7.24.7", - "@babel/plugin-transform-object-rest-spread": "^7.24.7", - "@babel/plugin-transform-optional-catch-binding": "^7.24.7", - "@babel/plugin-transform-optional-chaining": "^7.24.8", - "@babel/plugin-transform-parameters": "^7.24.7", - "@babel/plugin-transform-private-methods": "^7.24.7", - "@babel/plugin-transform-private-property-in-object": "^7.24.7", - "@babel/plugin-transform-react-display-name": "^7.24.7", - "@babel/plugin-transform-react-jsx": "^7.28.6", - "@babel/plugin-transform-react-jsx-development": "^7.27.1", - "@babel/plugin-transform-react-pure-annotations": "^7.27.1", - "@babel/plugin-transform-runtime": "^7.24.7", - "@babel/plugin-transform-typescript": "^7.25.2", - "@babel/plugin-transform-unicode-regex": "^7.24.7", - "@babel/preset-typescript": "^7.23.0", - "@react-native/babel-plugin-codegen": "0.88.0", - "babel-plugin-react-compiler": "^1.0.0", - "babel-plugin-react-native-web": "~0.21.4", - "babel-plugin-syntax-hermes-parser": "^0.36.0", - "babel-plugin-transform-flow-enums": "^0.0.2", - "debug": "^4.3.4" - }, - "peerDependencies": { - "@babel/runtime": "^7.20.0", - "expo": "*", - "expo-widgets": "^58.0.20", - "react-refresh": ">=0.14.0 <1.0.0" - }, - "peerDependenciesMeta": { - "@babel/runtime": { - "optional": true - }, - "expo": { - "optional": true - }, - "expo-widgets": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/expo/node_modules/pretty-format": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", - "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@jest/schemas": "^29.6.3", - "ansi-styles": "^5.0.0", - "react-is": "^18.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/flow-parser": { - "version": "0.327.0", - "resolved": "https://registry.npmjs.org/flow-parser/-/flow-parser-0.327.0.tgz", - "integrity": "sha512-/MYZ5hXWf5ozpbdfUDmazMgQXviLxWEiRLH3MppEGDdW0itRVqmB5UaU7QX+SBCDNiq+gEesSVn8nlxmPDyDkw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "flow-estree": "0.327.0" - }, - "engines": { - "node": ">=0.4.0" - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/jest-expo": { - "version": "54.0.17", - "resolved": "https://registry.npmjs.org/jest-expo/-/jest-expo-54.0.17.tgz", - "integrity": "sha512-LyIhrsP4xvHEEcR1R024u/LBj3uPpAgB+UljgV+YXWkEHjprnr0KpE4tROsMNYCVTM1pPlAnPuoBmn5gnAN9KA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@expo/config": "~12.0.13", - "@expo/json-file": "^10.0.8", - "@jest/create-cache-key-function": "^29.2.1", - "@jest/globals": "^29.2.1", - "babel-jest": "^29.2.1", - "jest-environment-jsdom": "^29.2.1", - "jest-snapshot": "^29.2.1", - "jest-watch-select-projects": "^2.0.0", - "jest-watch-typeahead": "2.2.1", - "json5": "^2.2.3", - "lodash": "^4.17.19", - "react-test-renderer": "19.1.0", - "server-only": "^0.0.1", - "stacktrace-js": "^2.0.2" - }, - "bin": { - "jest": "bin/jest.js" - }, - "peerDependencies": { - "expo": "*", - "react-native": "*", - "react-server-dom-webpack": "~19.0.4 || ~19.1.5 || ~19.2.4" - }, - "peerDependenciesMeta": { - "react-server-dom-webpack": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/react-is": { - "version": "18.3.1", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", - "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/react-native": { - "version": "0.88.0", - "resolved": "https://registry.npmjs.org/react-native/-/react-native-0.88.0.tgz", - "integrity": "sha512-v/wee0nYWcammMYBnSat/e3WY/5iaf9YQOMcBrfKT/wPApPPlHp94hgZovBtwhMuthR01yc/8cGn0FpFTE/C4A==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@react-native/asset-utils": "0.88.0", - "@react-native/codegen": "0.88.0", - "@react-native/community-cli-plugin": "0.88.0", - "@react-native/gradle-plugin": "0.88.0", - "@react-native/normalize-colors": "0.88.0", - "@react-native/virtualized-lists": "0.88.0", - "anser": "^1.4.9", - "ansi-regex": "^5.0.0", - "base64-js": "^1.5.1", - "flow-enums-runtime": "^0.0.6", - "flow-parser": "0.327.0", - "hermes-compiler": "260318099.0.4", - "invariant": "^2.2.4", - "memoize-one": "^5.0.0", - "metro-runtime": "^0.87.1", - "metro-source-map": "^0.87.1", - "nullthrows": "^1.1.1", - "pretty-format": "^29.7.0", - "promise": "^8.3.0", - "react-devtools-core": "^6.1.5", - "react-refresh": "^0.14.0", - "regenerator-runtime": "^0.13.2", - "scheduler": "0.28.0", - "semver": "^7.1.3", - "stacktrace-parser": "^0.1.10", - "tinyglobby": "^0.2.15", - "whatwg-fetch": "^3.0.0", - "ws": "^7.5.10", - "yargs": "^17.6.2" - }, - "bin": { - "react-native": "cli.js" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - }, - "peerDependencies": { - "@types/react": "^19.1.1", - "react": "^19.3.0" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/react-native/node_modules/pretty-format": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", - "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@jest/schemas": "^29.6.3", - "ansi-styles": "^5.0.0", - "react-is": "^18.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/react-native/node_modules/ws": { - "version": "7.5.13", - "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.13.tgz", - "integrity": "sha512-rsKI6xDBFVf4r/x8XyChGK04QR/XHroxs/jUcoWvtEZM8TPU/X/uIY9B1CsSzYws9ZJb/6bbBu7dPhFW00CAoA==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=8.3.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": "^5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-module-scripts/node_modules/scheduler": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", - "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/expo-modules-autolinking": { - "version": "58.0.13", - "resolved": "https://registry.npmjs.org/expo-modules-autolinking/-/expo-modules-autolinking-58.0.13.tgz", - "integrity": "sha512-uzLFoTnAKabUdITvzRqWTvFkZsOdRPEXj7AEMAuBEhA2kGhqaBDa2EOWqPXVay0QJVoZuIQaEEgPGAXN1dPuYg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@expo/platforms": "^58.0.1", - "@expo/require-utils": "^58.0.4", - "@expo/spawn-async": "^1.8.0", - "chalk": "^4.1.0", - "commander": "^7.2.0" - }, - "bin": { - "expo-modules-autolinking": "bin/expo-modules-autolinking.js" - } - }, - "packages/expo-two-way-audio/node_modules/expo-modules-autolinking/node_modules/@expo/require-utils": { - "version": "58.0.4", - "resolved": "https://registry.npmjs.org/@expo/require-utils/-/require-utils-58.0.4.tgz", - "integrity": "sha512-DvjS5NCitXYcad2Woe1EMHJKcbhTbE77HX0BgOQGL2LFHE3q2H0n8kCWDPBOCVJ63Drap3c35nwoJwF5TQL7Tw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.20.0", - "@babel/core": "^7.25.2", - "@babel/plugin-transform-modules-commonjs": "^7.24.8" - }, - "peerDependencies": { - "typescript": "^5.0.0 || ^5.0.0-0 || ^6.0.0 || ^7.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/expo-modules-autolinking/node_modules/commander": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz", - "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 10" - } - }, "packages/expo-two-way-audio/node_modules/expo-modules-core": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/expo-modules-core/-/expo-modules-core-2.5.0.tgz", @@ -41119,770 +40338,6 @@ "invariant": "^2.2.4" } }, - "packages/expo-two-way-audio/node_modules/expo-modules-jsi": { - "version": "58.0.15", - "resolved": "https://registry.npmjs.org/expo-modules-jsi/-/expo-modules-jsi-58.0.15.tgz", - "integrity": "sha512-PsjYgL4KWtvBqWH242r0wbP99VjgHkHCpkPCekO7nzb+ulkDNyrNnhysxa0TcNpfRTNLetmCUaLs9t4CcoquZQ==", - "dev": true, - "license": "MIT", - "peer": true, - "peerDependencies": { - "react-native": "*" - } - }, - "packages/expo-two-way-audio/node_modules/expo-server": { - "version": "58.0.5", - "resolved": "https://registry.npmjs.org/expo-server/-/expo-server-58.0.5.tgz", - "integrity": "sha512-FHYecxfGOuAhacHcanR6qCN8Cln9S+FFulcYetLu3ddDg55ohuCsMZ9U4Egzwdm+A2o6N+MdSoJKquBC5F9NIg==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": "^22.13.0 || ^24.3.0 || ^26.0.0 || >=27.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/flow-estree": { - "version": "0.327.0", - "resolved": "https://registry.npmjs.org/flow-estree/-/flow-estree-0.327.0.tgz", - "integrity": "sha512-f9vK751YUzD0qaHSpKc5/qQM6gqOlgGS+4ZRqTNcZOpVqn3mC55yEQ6dUG2K1eaVm5FbKkz9CFWe6XNvrkQFQg==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=18" - } - }, - "packages/expo-two-way-audio/node_modules/getenv": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/getenv/-/getenv-2.0.0.tgz", - "integrity": "sha512-VilgtJj/ALgGY77fiLam5iD336eSWi96Q15JSAG1zi8NRBysm3LXKdGnHb4m5cuyxvOLQQKWpBZAT6ni4FI2iQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "packages/expo-two-way-audio/node_modules/glob": { - "version": "13.0.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", - "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "minimatch": "^10.2.2", - "minipass": "^7.1.3", - "path-scurry": "^2.0.2" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "packages/expo-two-way-audio/node_modules/globals": { - "version": "16.5.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-16.5.0.tgz", - "integrity": "sha512-c/c15i26VrJ4IRt5Z89DnIzCGDn9EcebibhAOjw5ibqEHsE1wLUgkPn9RDmNcUKyU87GeaL633nyJ+pplFR2ZQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "packages/expo-two-way-audio/node_modules/has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=4" - } - }, - "packages/expo-two-way-audio/node_modules/hermes-compiler": { - "version": "260318099.0.4", - "resolved": "https://registry.npmjs.org/hermes-compiler/-/hermes-compiler-260318099.0.4.tgz", - "integrity": "sha512-8odcPFkPC82HlqCl0C5QI9mBN4rEAT+IAo55sJhzwKw//K3qZloiv3ex6J2O8CuBbhdmkJozfidNsset2KH25w==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/hermes-estree": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.25.1.tgz", - "integrity": "sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw==", - "dev": true, - "license": "MIT" - }, - "packages/expo-two-way-audio/node_modules/hermes-parser": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/hermes-parser/-/hermes-parser-0.25.1.tgz", - "integrity": "sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==", - "dev": true, - "license": "MIT", - "dependencies": { - "hermes-estree": "0.25.1" - } - }, - "packages/expo-two-way-audio/node_modules/https-proxy-agent": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", - "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "agent-base": "^7.1.2", - "debug": "4" - }, - "engines": { - "node": ">= 14" - } - }, - "packages/expo-two-way-audio/node_modules/ignore": { - "version": "7.0.5", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz", - "integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 4" - } - }, - "packages/expo-two-way-audio/node_modules/indent-string": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", - "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "packages/expo-two-way-audio/node_modules/jest-diff": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-30.4.1.tgz", - "integrity": "sha512-CRpFK0RtLriVDGcPPAnR6HMVI8bSR2jnUIgralhauzYQZIb4RH9AtEInTuQr65LmmGggGcRT6HIASxwqsVsmlA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/diff-sequences": "30.4.0", - "@jest/get-type": "30.1.0", - "chalk": "^4.1.2", - "pretty-format": "30.4.1" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/jest-matcher-utils": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-30.4.1.tgz", - "integrity": "sha512-zvYfX5CaeEkFrrLS9suWe9rvJrm9J1Iv3ua8kIBv9GEPzcnsfBf0bob37la7s67fs0nlBC3EuvkOLnXQKxtx4A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/get-type": "30.1.0", - "chalk": "^4.1.2", - "jest-diff": "30.4.1", - "pretty-format": "30.4.1" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/log-symbols": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-2.2.0.tgz", - "integrity": "sha512-VeIAFslyIerEJLXHziedo2basKbMKtTw3vfn5IzG0XTjhAVEJyNHnL2p7vc+wBDSdQuUpNw3M2u6xb9QsAY5Eg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "chalk": "^2.0.1" - }, - "engines": { - "node": ">=4" - } - }, - "packages/expo-two-way-audio/node_modules/log-symbols/node_modules/ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "color-convert": "^1.9.0" - }, - "engines": { - "node": ">=4" - } - }, - "packages/expo-two-way-audio/node_modules/log-symbols/node_modules/chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - }, - "engines": { - "node": ">=4" - } - }, - "packages/expo-two-way-audio/node_modules/lru-cache": { - "version": "11.5.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.1.tgz", - "integrity": "sha512-RPimw/7aMdv2oqRrxKwvZXcPfwBrn/JZ2xYcY9Hus/6LaS3VOAKVWKWgNLCFSiOm1ESXinjsDlidVU7JlnCN2A==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": "20 || >=22" - } - }, - "packages/expo-two-way-audio/node_modules/metro": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/metro/-/metro-0.87.1.tgz", - "integrity": "sha512-1oyLU9elM7hPAsKIqKooEekwxiuWr27+MZBhUROPhzcbXhMDxK64GPF/hCXwBZVp1F89ODavCrBmJtLx9WtBoQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.29.0", - "@babel/core": "^7.25.2", - "@babel/generator": "^7.29.1", - "@babel/parser": "^7.29.0", - "@babel/template": "^7.28.6", - "@babel/traverse": "^7.29.0", - "@babel/types": "^7.29.0", - "accepts": "^2.0.0", - "connect": "^3.6.5", - "debug": "^4.4.0", - "error-stack-parser": "^2.0.6", - "flow-enums-runtime": "^0.0.6", - "flow-parser": "0.331.0", - "graceful-fs": "^4.2.4", - "invariant": "^2.2.4", - "jest-worker": "^29.7.0", - "jsc-safe-url": "^0.2.2", - "lodash.throttle": "^4.1.1", - "metro-babel-transformer": "0.87.1", - "metro-cache": "0.87.1", - "metro-cache-key": "0.87.1", - "metro-config": "0.87.1", - "metro-core": "0.87.1", - "metro-file-map": "0.87.1", - "metro-resolver": "0.87.1", - "metro-runtime": "0.87.1", - "metro-source-map": "0.87.1", - "metro-symbolicate": "0.87.1", - "metro-transform-plugins": "0.87.1", - "metro-transform-worker": "0.87.1", - "mime-types": "^3.0.1", - "nullthrows": "^1.1.1", - "serialize-error": "^2.1.0", - "source-map": "^0.5.6", - "throat": "^5.0.0", - "ws": "^7.5.10", - "yargs": "^17.6.2" - }, - "bin": { - "metro": "src/cli.js" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/metro-babel-transformer": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/metro-babel-transformer/-/metro-babel-transformer-0.87.1.tgz", - "integrity": "sha512-orvRIGpb0yK1yMbk5YP3dhVKjmoxUkRB9fdltGJxNppEqus/1tFpNuf9KnGFR3Qjg0izoUrJ4z6WgoBvdkXPrA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/core": "^7.25.2", - "flow-enums-runtime": "^0.0.6", - "flow-parser": "0.331.0", - "metro-cache-key": "0.87.1", - "nullthrows": "^1.1.1" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/metro-cache": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/metro-cache/-/metro-cache-0.87.1.tgz", - "integrity": "sha512-juNPaj0Xi5tkLp8imXqvbSnEIijwKG36m7OiFFVJMqEkiURwAjkMFVek3/xpix1+LVQqO7kjVp3PvuvIM61mKQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "exponential-backoff": "^3.1.1", - "flow-enums-runtime": "^0.0.6", - "https-proxy-agent": "^7.0.5", - "metro-core": "0.87.1" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/metro-cache-key": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/metro-cache-key/-/metro-cache-key-0.87.1.tgz", - "integrity": "sha512-scqVVPMA2c+RVO12I3wyMDp5xCkRPLsyrcG4Qc3xfU5JR0EW/0sz2tjty+5UjMUtG09uiM1KYQ8HjWg7OQXHtw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "flow-enums-runtime": "^0.0.6" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/metro-config": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/metro-config/-/metro-config-0.87.1.tgz", - "integrity": "sha512-NmkDlc/qZAdo5gTkVTuO2AKE/khemRKRH5IA+SKfqUBJigI5GqZ5TOXhmEokhlkAqzjt8dyzKhzI6FHvXoXaTQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "connect": "^3.6.5", - "flow-enums-runtime": "^0.0.6", - "jest-validate": "^29.7.0", - "metro": "0.87.1", - "metro-cache": "0.87.1", - "metro-core": "0.87.1", - "metro-runtime": "0.87.1" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/metro-core": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/metro-core/-/metro-core-0.87.1.tgz", - "integrity": "sha512-xizzky/4+c/Mkznege8OW05j7bSdM39VPoEps61Se4+hf32UQujmbvLvIE9+UnP6kNEPVomk0Fw8NsBK9iRQmw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "flow-enums-runtime": "^0.0.6", - "lodash.throttle": "^4.1.1", - "metro-resolver": "0.87.1" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/metro-file-map": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/metro-file-map/-/metro-file-map-0.87.1.tgz", - "integrity": "sha512-9sPuNCojC3pS4vj+ZPY7FXmHGpdJeckXuKXQrDAfJvZc60AF8owRFTkI8XdwlwrmPIB2w++KraK9FMEXvC4wJw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "debug": "^4.4.0", - "fb-watchman": "^2.0.0", - "flow-enums-runtime": "^0.0.6", - "graceful-fs": "^4.2.4", - "invariant": "^2.2.4", - "jest-worker": "^29.7.0", - "micromatch": "^4.0.4", - "nullthrows": "^1.1.1" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/metro-minify-terser": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/metro-minify-terser/-/metro-minify-terser-0.87.1.tgz", - "integrity": "sha512-YK4k1oO1wV48hfE+Nbw2rJCnAgeabzrgT/xH5ha5n9gbK4p3HYFC898cERUiyTl9vRh58CNTiXRc88f7y6PfKg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "flow-enums-runtime": "^0.0.6", - "terser": "^5.15.0" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/metro-resolver": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/metro-resolver/-/metro-resolver-0.87.1.tgz", - "integrity": "sha512-FXH/brY69wT6sPxaSW8BhMmDGD/6irmBr/cL4rUi+VWwqR3pbvdcfUOfyjcHucgQ7pe5IW3xJY21eHKLVKNumQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "flow-enums-runtime": "^0.0.6" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/metro-runtime": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/metro-runtime/-/metro-runtime-0.87.1.tgz", - "integrity": "sha512-kjeuSvInsM6OzBjkCQsWxnkrKZFMKtnkCl38oXWRI9lDGs2L9hGs9Tak9sQYJ9h3gtDujneB7wZio+irgqJKDw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/runtime": "^7.25.0", - "flow-enums-runtime": "^0.0.6" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/metro-source-map": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/metro-source-map/-/metro-source-map-0.87.1.tgz", - "integrity": "sha512-Bqpm0PBGdy53pigIJb4HRF7QxD2pUOdgSmVh/4AWbP635kSCv+Y6ltVxUZgSnzS/QbSmzyCGijmRPlXMj2/qHw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/traverse": "^7.29.0", - "@babel/types": "^7.29.0", - "flow-enums-runtime": "^0.0.6", - "invariant": "^2.2.4", - "metro-symbolicate": "0.87.1", - "nullthrows": "^1.1.1", - "ob1": "0.87.1", - "source-map": "^0.5.6", - "vlq": "^1.0.0" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/metro-symbolicate": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/metro-symbolicate/-/metro-symbolicate-0.87.1.tgz", - "integrity": "sha512-rcGvwabrg0lbXGRGRKl14PY3My3+dkno2jZYhdJEuH2DmjTtTkV5bYwgto4JtV/Lbe+sXE6GO1UGg654430uow==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "flow-enums-runtime": "^0.0.6", - "invariant": "^2.2.4", - "metro-source-map": "0.87.1", - "nullthrows": "^1.1.1", - "source-map": "^0.5.6", - "vlq": "^1.0.0" - }, - "bin": { - "metro-symbolicate": "src/index.js" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/metro-transform-plugins": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/metro-transform-plugins/-/metro-transform-plugins-0.87.1.tgz", - "integrity": "sha512-qMiJ/x+VfqumFJJSefKS6nj8uojzC29b2/aK8vlMuFABIqGjDucICEOXd2Yt6k/XMFAgAcaJvShUOT0HLyYaPw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/core": "^7.25.2", - "@babel/generator": "^7.29.1", - "@babel/template": "^7.28.6", - "@babel/traverse": "^7.29.0", - "flow-enums-runtime": "^0.0.6", - "nullthrows": "^1.1.1" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/metro-transform-worker": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/metro-transform-worker/-/metro-transform-worker-0.87.1.tgz", - "integrity": "sha512-VOzs3OV405FuOLYdAhqA2wsn1F9lvueDVxMDLvCKaQ44U+yknIqphJ9eMjjsGwLDZiJq9sW3DMLhjD27JxQgqQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/core": "^7.25.2", - "@babel/generator": "^7.29.1", - "@babel/parser": "^7.29.0", - "@babel/types": "^7.29.0", - "flow-enums-runtime": "^0.0.6", - "metro": "0.87.1", - "metro-babel-transformer": "0.87.1", - "metro-cache": "0.87.1", - "metro-cache-key": "0.87.1", - "metro-minify-terser": "0.87.1", - "metro-source-map": "0.87.1", - "metro-transform-plugins": "0.87.1", - "nullthrows": "^1.1.1" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/metro/node_modules/accepts": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", - "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "mime-types": "^3.0.0", - "negotiator": "^1.0.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "packages/expo-two-way-audio/node_modules/metro/node_modules/ws": { - "version": "7.5.13", - "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.13.tgz", - "integrity": "sha512-rsKI6xDBFVf4r/x8XyChGK04QR/XHroxs/jUcoWvtEZM8TPU/X/uIY9B1CsSzYws9ZJb/6bbBu7dPhFW00CAoA==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=8.3.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": "^5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - }, - "packages/expo-two-way-audio/node_modules/mime-types": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", - "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "mime-db": "^1.54.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "packages/expo-two-way-audio/node_modules/mimic-fn": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-1.2.0.tgz", - "integrity": "sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=4" - } - }, - "packages/expo-two-way-audio/node_modules/minimatch": { - "version": "10.2.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", - "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "brace-expansion": "^5.0.5" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "packages/expo-two-way-audio/node_modules/negotiator": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz", - "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "content-type": "^2.1.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "packages/expo-two-way-audio/node_modules/node-forge": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.4.0.tgz", - "integrity": "sha512-LarFH0+6VfriEhqMMcLX2F7SwSXeWwnEAJEsYm5QKWchiVYVvJyV9v7UDvUv+w5HO23ZpQTXDv/GxdDdMyOuoQ==", - "dev": true, - "license": "(BSD-3-Clause OR GPL-2.0)", - "peer": true, - "engines": { - "node": ">= 6.13.0" - } - }, - "packages/expo-two-way-audio/node_modules/ob1": { - "version": "0.87.1", - "resolved": "https://registry.npmjs.org/ob1/-/ob1-0.87.1.tgz", - "integrity": "sha512-i8iA8uij0g1YQzS8uOJPSRCgwDjO9warIHUAu1Fqj877Wc3wlfxDYBioYWgKTBF2+URVJttyDWSEpmd99nlvtQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "flow-enums-runtime": "^0.0.6" - }, - "engines": { - "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" - } - }, - "packages/expo-two-way-audio/node_modules/onetime": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-2.0.1.tgz", - "integrity": "sha512-oyyPpiMaKARvvcgip+JV+7zci5L8D1W9RZIz2l1o08AM3pfspitVWnPt3mzHcBPp12oYMTy0pqrFs/C+m3EwsQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "mimic-fn": "^1.0.0" - }, - "engines": { - "node": ">=4" - } - }, - "packages/expo-two-way-audio/node_modules/open": { - "version": "8.4.2", - "resolved": "https://registry.npmjs.org/open/-/open-8.4.2.tgz", - "integrity": "sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "define-lazy-prop": "^2.0.0", - "is-docker": "^2.1.1", - "is-wsl": "^2.2.0" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "packages/expo-two-way-audio/node_modules/ora": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/ora/-/ora-3.4.0.tgz", - "integrity": "sha512-eNwHudNbO1folBP3JsZ19v9azXWtQZjICdr3Q0TDPIaeBQ3mXLrh54wM+er0+hSp+dWKf+Z8KM58CYzEyIYxYg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "chalk": "^2.4.2", - "cli-cursor": "^2.1.0", - "cli-spinners": "^2.0.0", - "log-symbols": "^2.2.0", - "strip-ansi": "^5.2.0", - "wcwidth": "^1.0.1" - }, - "engines": { - "node": ">=6" - } - }, - "packages/expo-two-way-audio/node_modules/ora/node_modules/ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "color-convert": "^1.9.0" - }, - "engines": { - "node": ">=4" - } - }, - "packages/expo-two-way-audio/node_modules/ora/node_modules/chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - }, - "engines": { - "node": ">=4" - } - }, - "packages/expo-two-way-audio/node_modules/path-scurry": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", - "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "lru-cache": "^11.0.0", - "minipass": "^7.1.2" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "packages/expo-two-way-audio/node_modules/pretty-format": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-30.4.1.tgz", - "integrity": "sha512-K6KiKMHTL4jjX4u3Kir2EW07nRfcqVTXIImx50wbjHQTcZPgg+gjVeNTIT3l3L1Rd4UefxfogquC9J37SoFyyw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/schemas": "30.4.1", - "ansi-styles": "^5.2.0", - "react-is-18": "npm:react-is@^18.3.1", - "react-is-19": "npm:react-is@^19.2.5" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, "packages/expo-two-way-audio/node_modules/react": { "version": "19.3.1", "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", @@ -41893,202 +40348,6 @@ "node": ">=0.10.0" } }, - "packages/expo-two-way-audio/node_modules/react-refresh": { - "version": "0.14.2", - "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.14.2.tgz", - "integrity": "sha512-jCvmsr+1IUSMUyzOkRcvnVbX3ZYC6g9TDrDbFuFmRDq7PD4yaGbLKNQL6k2jnArV8hjYxh7hVhAZB6s9HDGpZA==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=0.10.0" - } - }, - "packages/expo-two-way-audio/node_modules/react-test-renderer": { - "version": "19.1.0", - "resolved": "https://registry.npmjs.org/react-test-renderer/-/react-test-renderer-19.1.0.tgz", - "integrity": "sha512-jXkSl3CpvPYEF+p/eGDLB4sPoDX8pKkYvRl9+rR8HxLY0X04vW7hCm1/0zHoUSjPZ3bDa+wXWNTDVIw/R8aDVw==", - "dev": true, - "license": "MIT", - "dependencies": { - "react-is": "^19.1.0", - "scheduler": "^0.26.0" - }, - "peerDependencies": { - "react": "^19.1.0" - } - }, - "packages/expo-two-way-audio/node_modules/redent": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/redent/-/redent-3.0.0.tgz", - "integrity": "sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==", - "dev": true, - "license": "MIT", - "dependencies": { - "indent-string": "^4.0.0", - "strip-indent": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "packages/expo-two-way-audio/node_modules/restore-cursor": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-2.0.0.tgz", - "integrity": "sha512-6IzJLuGi4+R14vwagDHX+JrXmPVtPpn4mffDJ1UdR7/Edm87fl6yi8mMBIVvFtJaNTUvjughmW4hwLhRG7gC1Q==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "onetime": "^2.0.0", - "signal-exit": "^3.0.2" - }, - "engines": { - "node": ">=4" - } - }, - "packages/expo-two-way-audio/node_modules/signal-exit": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", - "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", - "dev": true, - "license": "ISC", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/slash": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", - "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "packages/expo-two-way-audio/node_modules/source-map": { - "version": "0.5.7", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", - "integrity": "sha512-LbrmJOMUSdEVxIKvdcJzQC+nQhe8FUZQTXQy6+I75skNgn3OoQ0DZA8YnFa7gp8tqtL3KPf1kmo0R5DoApeSGQ==", - "dev": true, - "license": "BSD-3-Clause", - "peer": true, - "engines": { - "node": ">=0.10.0" - } - }, - "packages/expo-two-way-audio/node_modules/strip-ansi": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", - "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "ansi-regex": "^4.1.0" - }, - "engines": { - "node": ">=6" - } - }, - "packages/expo-two-way-audio/node_modules/strip-ansi/node_modules/ansi-regex": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.1.tgz", - "integrity": "sha512-ILlv4k/3f6vfQ4OoP2AGvirOktlQ98ZEL1k9FaQjxa3L1abBgbuTDAdPOpvbGncC0BTVQrl+OM8xZGK6tWXt7g==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=6" - } - }, - "packages/expo-two-way-audio/node_modules/strip-indent": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-3.0.0.tgz", - "integrity": "sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "min-indent": "^1.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "packages/expo-two-way-audio/node_modules/sucrase": { - "version": "3.35.1", - "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.1.tgz", - "integrity": "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/gen-mapping": "^0.3.2", - "commander": "^4.0.0", - "lines-and-columns": "^1.1.6", - "mz": "^2.7.0", - "pirates": "^4.0.1", - "tinyglobby": "^0.2.11", - "ts-interface-checker": "^0.1.9" - }, - "bin": { - "sucrase": "bin/sucrase", - "sucrase-node": "bin/sucrase-node" - }, - "engines": { - "node": ">=16 || 14 >=14.17" - } - }, - "packages/expo-two-way-audio/node_modules/sucrase/node_modules/commander": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", - "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 6" - } - }, - "packages/expo-two-way-audio/node_modules/supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "has-flag": "^3.0.0" - }, - "engines": { - "node": ">=4" - } - }, - "packages/expo-two-way-audio/node_modules/whatwg-url-minimum": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/whatwg-url-minimum/-/whatwg-url-minimum-0.2.0.tgz", - "integrity": "sha512-BtjXU1caNcCFfETP2DhqSeVPfRDl2MTUitI107RE34rJXjR/izfUtR5IoTFOK1WqjNLXbbeqaCH/mQAOLjpc8g==", - "dev": true, - "license": "MIT", - "peer": true - }, - "packages/expo-two-way-audio/node_modules/xmlbuilder": { - "version": "15.1.1", - "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz", - "integrity": "sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8.0" - } - }, - "packages/expo-two-way-audio/node_modules/zod": { - "version": "3.25.76", - "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", - "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/colinhacks" - } - }, "packages/highlight": { "name": "@getpaseo/highlight", "version": "0.13.2", diff --git a/package.json b/package.json index beeff7c613..d7d17fe83b 100644 --- a/package.json +++ b/package.json @@ -131,6 +131,7 @@ "concurrently": "^9.2.1", "cross-env": "^10.1.0", "electron": "44.2.0", + "expo-module-scripts": "^5.0.8", "get-port-cli": "^3.0.0", "js-yaml": "^4.1.1", "knip": "^5.82.1", diff --git a/packages/expo-two-way-audio/package.json b/packages/expo-two-way-audio/package.json index 1a38528c25..391ed1cfd7 100644 --- a/packages/expo-two-way-audio/package.json +++ b/packages/expo-two-way-audio/package.json @@ -33,7 +33,6 @@ "devDependencies": { "@types/jest": "^29.5.14", "@types/react": "^18.0.25", - "expo-module-scripts": "^5.0.8", "expo-modules-core": "^2.0.4" }, "peerDependencies": { diff --git a/packages/expo-two-way-audio/tsconfig.json b/packages/expo-two-way-audio/tsconfig.json index 102525ffa9..24e443895c 100644 --- a/packages/expo-two-way-audio/tsconfig.json +++ b/packages/expo-two-way-audio/tsconfig.json @@ -6,7 +6,7 @@ "module": "esnext", "moduleResolution": "bundler", "typeRoots": [ - "./node_modules/expo-module-scripts/ts-declarations", + "../../node_modules/expo-module-scripts/ts-declarations", "./node_modules/@types", "../../node_modules/@types" ] From 07007a485def915c496d109e602c5de9b2fe1fd2 Mon Sep 17 00:00:00 2001 From: "paseo-ai[bot]" <266920839+paseo-ai[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 07:20:13 +0000 Subject: [PATCH 052/173] fix: update lockfile signatures and Nix hash [skip ci] --- nix/npm-deps.hash | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nix/npm-deps.hash b/nix/npm-deps.hash index 3e19f893c2..bdacb9b93b 100644 --- a/nix/npm-deps.hash +++ b/nix/npm-deps.hash @@ -1 +1 @@ -sha256-eNiKmiZ3XXZMRZRSoGxUbMn2RtY6AX079vUatBYM+qE= +sha256-dk7kJUdmQBF8L8Vkj6Ryza3n4/S+YqgxWY3R59Dc3mY= From 6b7d49f0d8d21d01565f9517a8c2a30e2a587e2a Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Tue, 27 Oct 2026 14:35:44 +0700 Subject: [PATCH 053/173] test(server): keep responsiveness gates independent of runner scheduling (#8002) Raw timer gaps and elapsed callback or GC spans include Windows runner preemption. Share callback CPU accounting across the daemon hot-path probes and retain deterministic async admission, real yields, and sync-IO tracing at filesystem boundaries. --- .../server/agent/agent-timeline-store.test.ts | 31 ++--- .../claude/agent.history-load.test.ts | 51 ++++--- .../providers/jsonl-frame-decoder.test.ts | 26 +--- .../agent/providers/omp/history.e2e.test.ts | 85 ++++++------ packages/server/src/server/config.test.ts | 21 ++- .../plugins/plugin-paseo-api.e2e.test.ts | 23 +--- .../compile-responsiveness.e2e.ts | 124 +----------------- .../src/server/utils/diff-highlighter.test.ts | 43 +++--- ...it-service.observation.integration.test.ts | 37 +++--- .../workspace-reconciliation-service.test.ts | 100 ++------------ .../server/src/test-utils/main-thread-work.ts | 108 +++++++++++++++ .../src/utils/paseo-config-file.test.ts | 53 +++----- 12 files changed, 270 insertions(+), 432 deletions(-) create mode 100644 packages/server/src/test-utils/main-thread-work.ts diff --git a/packages/server/src/server/agent/agent-timeline-store.test.ts b/packages/server/src/server/agent/agent-timeline-store.test.ts index 99e392f188..4baaf89edb 100644 --- a/packages/server/src/server/agent/agent-timeline-store.test.ts +++ b/packages/server/src/server/agent/agent-timeline-store.test.ts @@ -1,3 +1,4 @@ +import { measureMainThreadWork } from "../../test-utils/main-thread-work.js"; import { describe, expect, it } from "vitest"; import { selectReferenceProjectedTimelinePage } from "./test-utils/timeline-page-reference.js"; import type { AgentTimelineItem } from "./agent-sdk-types.js"; @@ -258,25 +259,19 @@ it.each([false, true])( for (let index = 0; index < 100_000; index++) { store.append("large", { type: "user_message", text: String(index) }); } - // Generation and its GC are outside the measured request window. - await new Promise((resolve) => setImmediate(resolve)); - const started = performance.now(); - const probe = new Promise((resolve) => - setImmediate(() => resolve(performance.now() - started)), + const { result: tail, blockingMs } = await measureMainThreadWork( + `timeline tail main-thread work (wholeTurns=${wholeTurns})`, + () => { + let page = store.fetch("large", { limit: 200, wholeTurns }); + for (let repeat = 1; repeat < 8; repeat++) + page = store.fetch("large", { limit: 200, wholeTurns }); + return page; + }, ); - let page = store.fetch("large", { limit: 200, wholeTurns }); - for (let repeat = 1; repeat < 8; repeat++) - page = store.fetch("large", { limit: 200, wholeTurns }); - const duration = performance.now() - started; - const loopGap = await probe; - console.info({ duration, loopGap }); - expect(page.rows).toHaveLength(200); - expect(page.startSeq).toBe(99_801); - expect(page.endSeq).toBe(100_000); - // CI runners can pause for scheduling/GC; the local per-request 2 ms gate - // is measured separately. Eight requests amplify the old full-history work. - expect(duration).toBeLessThan(50); - expect(loopGap).toBeLessThan(50); + expect(tail.rows).toHaveLength(200); + expect(tail.startSeq).toBe(99_801); + expect(tail.endSeq).toBe(100_000); + expect(blockingMs).toBeLessThan(50); }, ); diff --git a/packages/server/src/server/agent/providers/claude/agent.history-load.test.ts b/packages/server/src/server/agent/providers/claude/agent.history-load.test.ts index 921b4018be..393fda60de 100644 --- a/packages/server/src/server/agent/providers/claude/agent.history-load.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.history-load.test.ts @@ -1,3 +1,4 @@ +import { measureMainThreadWork } from "../../../../test-utils/main-thread-work.js"; import fs, { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { open } from "node:fs/promises"; import { performance } from "node:perf_hooks"; @@ -117,13 +118,6 @@ describe("ClaudeAgentSession persisted history load", () => { await file.close(); } const daemon = await createTestPaseoDaemon(); - let lastTick = performance.now(); - let longestGap = 0; - const probe = setInterval(() => { - const now = performance.now(); - longestGap = Math.max(longestGap, now - lastTick); - lastTick = now; - }, 2); let loading = true; let answeredDuringLoad = false; const health = fetch(`http://127.0.0.1:${daemon.port}/api/health`).then(async (response) => { @@ -134,33 +128,39 @@ describe("ClaudeAgentSession persisted history load", () => { }); let session: AgentSession | undefined; try { - session = await resume(replyFactory("live after large resume")); - let index = 0; - for await (const event of session.streamHistory()) { - expect(event).toEqual({ - type: "timeline", - provider: "claude", - timestamp: undefined, - item: { type: "assistant_message", text: `${index}:${text}` }, - }); - index++; - } - loading = false; - await health; - await new Promise((resolve) => setTimeout(resolve, 5)); + const { + result: { resumed: loadedSession, historyCount }, + blockingMs, + } = await measureMainThreadWork("Claude history main-thread work", async () => { + const resumed = await resume(replyFactory("live after large resume")); + session = resumed; + let index = 0; + for await (const event of resumed.streamHistory()) { + expect(event).toEqual({ + type: "timeline", + provider: "claude", + timestamp: undefined, + item: { type: "assistant_message", text: `${index}:${text}` }, + }); + index++; + } + loading = false; + await health; + return { resumed, historyCount: index }; + }); console.info( JSON.stringify({ bytes, count, - longestGap, + blockingMs, answeredDuringLoad, elapsedMs: performance.now() - startedAt, }), ); - expect(index).toBe(count); - expect(longestGap).toBeLessThan(50); + expect(historyCount).toBe(count); + expect(blockingMs).toBeLessThan(50); expect(answeredDuringLoad).toBe(true); - const live = await collectSessionTurnEvents(session, "follow up"); + const live = await collectSessionTurnEvents(loadedSession, "follow up"); expect( live .filter((event) => event.type === "timeline" && event.item.type === "assistant_message") @@ -169,7 +169,6 @@ describe("ClaudeAgentSession persisted history load", () => { { type: "assistant_message", messageId: "live-reply", text: "live after large resume" }, ]); } finally { - clearInterval(probe); await session?.close(); await daemon.close(); } diff --git a/packages/server/src/server/agent/providers/jsonl-frame-decoder.test.ts b/packages/server/src/server/agent/providers/jsonl-frame-decoder.test.ts index c1c81bdae8..4844415324 100644 --- a/packages/server/src/server/agent/providers/jsonl-frame-decoder.test.ts +++ b/packages/server/src/server/agent/providers/jsonl-frame-decoder.test.ts @@ -1,5 +1,4 @@ -import { performance } from "node:perf_hooks"; -import { setTimeout as delay } from "node:timers/promises"; +import { measureMainThreadWork } from "../../../test-utils/main-thread-work.js"; import { describe, expect, it } from "vitest"; import { JsonlFrameDecoder, type JsonlFrameProblem } from "./jsonl-frame-decoder.js"; @@ -72,26 +71,15 @@ describe("provider line admission", () => { it("keeps the loop responsive while accumulating a fragmented provider response", async () => { const { decoder, frames, problems } = decoderHarness(); const part = "x".repeat(512); - let last = performance.now(); - let longestGap = 0; - const probe = setInterval(() => { - const now = performance.now(); - longestGap = Math.max(longestGap, now - last); - last = now; - }, 1); - try { - await delay(5); + const { blockingMs } = await measureMainThreadWork("fragmented JSONL main-thread work", () => { decoder.write('{"type":"notice","text":"'); - // 1 MiB is enough to expose the former rescan of every accumulated prefix. + // 1 MiB exposes the former rescan of every accumulated prefix. for (let index = 0; index < 2048; index++) decoder.write(part); decoder.write('"}\n'); - await delay(5); - expect(frames).toEqual([{ type: "notice", text: part.repeat(2048) }]); - expect(problems).toEqual([]); - expect(longestGap).toBeLessThan(50); - } finally { - clearInterval(probe); - } + }); + expect(frames).toEqual([{ type: "notice", text: part.repeat(2048) }]); + expect(problems).toEqual([]); + expect(blockingMs).toBeLessThan(50); }); it("rejects an unterminated over-cap UTF-8 line and stops accepting frames", () => { diff --git a/packages/server/src/server/agent/providers/omp/history.e2e.test.ts b/packages/server/src/server/agent/providers/omp/history.e2e.test.ts index 77521a9687..f0a00d5a0d 100644 --- a/packages/server/src/server/agent/providers/omp/history.e2e.test.ts +++ b/packages/server/src/server/agent/providers/omp/history.e2e.test.ts @@ -1,3 +1,4 @@ +import { measureMainThreadWork } from "../../../../test-utils/main-thread-work.js"; import { BUILTIN_PROVIDER_IDS } from "@getpaseo/protocol/provider-manifest"; import { mkdtemp, open, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; @@ -50,51 +51,45 @@ test("replays selected OMP history without blocking the event loop", async () => } finally { await file.close(); } - let last = performance.now(); - let longestGap = 0; - const probe = setInterval(() => { - const now = performance.now(); - longestGap = Math.max(longestGap, now - last); - last = now; - }, 5); - try { - const replayState = { finished: false }; - let repliesDuringReplay = 0; - const replay = readActiveOmpEntryChain(sessionFile, "row-0").finally(() => { - replayState.finished = true; - }); - // A real WebSocket RPC served by the isolated daemon on the same event loop. - const requests = (async () => { - while (!replayState.finished) { - await client.getDaemonStatus(); - if (!replayState.finished) repliesDuringReplay++; - await delay(10); - } - })(); - const [entries] = await Promise.all([replay, requests]); - await delay(10); - console.log( - JSON.stringify({ - bytes, - count, - longestGap, - repliesDuringReplay, - generationAndLoadMs: performance.now() - started, - }), - ); - expect(entries).toEqual([ - { - type: "message", - id: "row-0", - parentId: null, - message: { role: "user", content: text }, - }, - ]); - expect(longestGap).toBeLessThan(50); - expect(repliesDuringReplay).toBeGreaterThan(0); - } finally { - clearInterval(probe); - } + let repliesDuringReplay = 0; + const { result: replayedEntries, blockingMs } = await measureMainThreadWork( + "OMP history main-thread work", + async () => { + const replayState = { finished: false }; + const replay = readActiveOmpEntryChain(sessionFile, "row-0").finally(() => { + replayState.finished = true; + }); + // A real WebSocket RPC served by the isolated daemon on the same event loop. + const requests = (async () => { + while (!replayState.finished) { + await client.getDaemonStatus(); + if (!replayState.finished) repliesDuringReplay++; + await delay(10); + } + })(); + const [entries] = await Promise.all([replay, requests]); + return entries; + }, + ); + console.log( + JSON.stringify({ + bytes, + count, + blockingMs, + repliesDuringReplay, + generationAndLoadMs: performance.now() - started, + }), + ); + expect(replayedEntries).toEqual([ + { + type: "message", + id: "row-0", + parentId: null, + message: { role: "user", content: text }, + }, + ]); + expect(blockingMs).toBeLessThan(50); + expect(repliesDuringReplay).toBeGreaterThan(0); } finally { await client.close().finally(() => daemon.close()); } diff --git a/packages/server/src/server/config.test.ts b/packages/server/src/server/config.test.ts index 72d1c30f7d..53a77338b6 100644 --- a/packages/server/src/server/config.test.ts +++ b/packages/server/src/server/config.test.ts @@ -1,3 +1,4 @@ +import { measureMainThreadWork } from "../test-utils/main-thread-work.js"; import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; @@ -25,22 +26,18 @@ describe("server config", () => { const env = { PASEO_PASSWORD: "synthetic-audit-password" }; const persisted = loadPersistedConfig(paseoHome); const startup = resolveConfigFromPersisted(paseoHome, persisted, { env }); - const started = performance.now(); - const timer = new Promise((resolve) => - setTimeout(() => resolve(performance.now() - started), 0), + const { result: reloaded, blockingMs } = await measureMainThreadWork( + "config resolve main-thread work", + () => + resolveReloadableConfig( + { ...persisted, daemon: { ...persisted.daemon, browserTools: { enabled: true } } }, + { env }, + ), ); - const reloaded = resolveReloadableConfig( - { - ...persisted, - daemon: { ...persisted.daemon, browserTools: { enabled: true } }, - }, - { env }, - ); - const gap = await timer; expect(reloaded).not.toHaveProperty("auth"); expect(reloaded.browserToolsEnabled).toBe(true); expect(startup.auth?.password).toBeTypeOf("string"); - expect(gap).toBeLessThan(50); + expect(blockingMs).toBeLessThan(50); }); test("records when the daemon is managed by Paseo Desktop", async () => { diff --git a/packages/server/src/server/plugins/plugin-paseo-api.e2e.test.ts b/packages/server/src/server/plugins/plugin-paseo-api.e2e.test.ts index cad97ce743..042388447b 100644 --- a/packages/server/src/server/plugins/plugin-paseo-api.e2e.test.ts +++ b/packages/server/src/server/plugins/plugin-paseo-api.e2e.test.ts @@ -1,6 +1,6 @@ +import { measureMainThreadWork } from "../../test-utils/main-thread-work.js"; import { execFile } from "node:child_process"; import { promisify } from "node:util"; -import { performance } from "node:perf_hooks"; import pino from "pino"; import { createPaseoDaemon } from "../bootstrap.js"; import { loadConfig } from "../config.js"; @@ -231,21 +231,12 @@ test("password-protected config reload preserves startup auth and session constr await client.fetchAgents({ subscribe: {} }); const configPath = path.join(home, "config.json"); await writeFile(configPath, JSON.stringify({ daemon: { browserTools: { enabled: true } } })); - let longestGap = 0; - let previous = performance.now(); - const probe = setInterval(() => { - const now = performance.now(); - longestGap = Math.max(longestGap, now - previous); - previous = now; - }, 1); - try { - const reloaded = await client.reloadDaemonConfig(); - longestGap = Math.max(longestGap, performance.now() - previous); - expect(reloaded.appliedPaths).toContain("daemon.browserTools.enabled"); - expect(longestGap).toBeLessThan(50); - } finally { - clearInterval(probe); - } + const { result: reloaded, blockingMs } = await measureMainThreadWork( + "daemon config reload main-thread work", + () => client.reloadDaemonConfig(), + ); + expect(reloaded.appliedPaths).toContain("daemon.browserTools.enabled"); + expect(blockingMs).toBeLessThan(50); expect((await client.getDaemonConfig()).config.browserTools.enabled).toBe(true); // A new physical session uses ready daemon state; corrupt config is reported only by an explicit read. await writeFile(configPath, "invalid JSON"); diff --git a/packages/server/src/server/plugins/test-fixtures/compile-responsiveness.e2e.ts b/packages/server/src/server/plugins/test-fixtures/compile-responsiveness.e2e.ts index 229e388b34..95aaec0d6a 100644 --- a/packages/server/src/server/plugins/test-fixtures/compile-responsiveness.e2e.ts +++ b/packages/server/src/server/plugins/test-fixtures/compile-responsiveness.e2e.ts @@ -1,9 +1,7 @@ +import { measureMainThreadWork } from "../../../test-utils/main-thread-work.js"; import assert from "node:assert/strict"; -import { createHook, executionAsyncResource } from "node:async_hooks"; import { open as openFile, writeFile } from "node:fs/promises"; -import { performance, PerformanceObserver } from "node:perf_hooks"; import path from "node:path"; -import { MessagePort } from "node:worker_threads"; import pino from "pino"; import { DaemonConfigStore } from "../../daemon-config-store.js"; import { PluginService } from "../index.js"; @@ -53,125 +51,9 @@ try { () => service.enablePlugin("responsive-build"), () => service.reloadPlugin("responsive-build"), ]) { - // Node 22.19+ exposes per-thread CPU accounting; the repository's older - // Node declarations do not include it yet. .tool-versions pins Node 22.20. - const threadCpuUsage: (previous?: NodeJS.CpuUsage) => NodeJS.CpuUsage = Reflect.get( - process, - "threadCpuUsage", - ); - const startedAt = performance.now(); - let previous = startedAt; - let cpu = threadCpuUsage(); - let longestWall = 0; - let longestBlocking = 0; - let longestWallCpu = 0; - let workerStarts = 0; - let portCallbacks = 0; - let longestWallEvents = { workerStarts: 0, portCallbacks: 0 }; - let longestBlockingWindow = { wallMs: 0, cpuMs: 0, resource: "" }; - let probe: ReturnType; - const callbacks = new Map(); - const recordBlocking = ( - blockingMs: number, - window: { wallMs: number; cpuMs: number; resource: string }, - ) => { - if (blockingMs > longestBlocking) { - longestBlocking = blockingMs; - longestBlockingWindow = window; - } - }; - let longestGc = 0; - const observeGc = (entries: readonly import("node:perf_hooks").PerformanceEntry[]) => { - for (const entry of entries) { - if (entry.startTime >= startedAt) longestGc = Math.max(longestGc, entry.duration); - } - }; - const gc = new PerformanceObserver((list) => observeGc(list.getEntries())); - gc.observe({ entryTypes: ["gc"] }); - // Measure work within callbacks, not CPU-counter increments attributed to - // the idle interval between them. Exclude this probe's own timer callback. - const activity = createHook({ - init(_id, type) { - if (type === "WORKER") workerStarts++; - }, - before(id) { - const resource = executionAsyncResource(); - if (resource instanceof MessagePort) portCallbacks++; - if (resource === probe) return; - callbacks.set(id, { - wall: performance.now(), - cpu: threadCpuUsage(), - resource: Object.prototype.toString.call(resource), - }); - }, - after(id) { - const start = callbacks.get(id); - if (!start) return; - callbacks.delete(id); - const wallMs = performance.now() - start.wall; - const { user, system } = threadCpuUsage(start.cpu); - const cpuMs = (user + system) / 1_000; - // A callback prevents the loop from serving IO for its entire span. - // Use the high-resolution clock, not Windows' coarse CPU increments. - recordBlocking(wallMs, { wallMs, cpuMs, resource: start.resource }); - }, - }).enable(); - const sample = () => { - const now = performance.now(); - const currentCpu = threadCpuUsage(); - const wallMs = now - previous; - const cpuMs = (currentCpu.user - cpu.user + currentCpu.system - cpu.system) / 1_000; - // Native worker construction and message deserialization can precede - // async_hooks.before. Include their interval when those events occurred. - if (workerStarts || portCallbacks) { - recordBlocking(Math.min(wallMs, cpuMs), { - wallMs, - cpuMs, - resource: "worker/port interval", - }); - } - if (wallMs > longestWall) { - longestWall = wallMs; - longestWallCpu = cpuMs; - longestWallEvents = { workerStarts, portCallbacks }; - } - workerStarts = 0; - portCallbacks = 0; - previous = now; - cpu = currentCpu; - }; - // Sleep between probes: a continuously runnable setImmediate loop consumes - // a core while the worker compiles. Raw gaps remain diagnostics; the - // assertion measures elapsed daemon-thread callback spans and GC pauses. - probe = setInterval(sample, 1); - try { - // The caller's current callback began before the hook was enabled. - // Include synchronous work before the action's first await explicitly. - const actionStartedAt = performance.now(); - const actionCpu = threadCpuUsage(); - const pending = action(); - const actionWallMs = performance.now() - actionStartedAt; - const actionCost = threadCpuUsage(actionCpu); - recordBlocking(actionWallMs, { - wallMs: actionWallMs, - cpuMs: (actionCost.user + actionCost.system) / 1_000, - resource: "action()", - }); - await pending; - await new Promise((resolve) => setImmediate(resolve)); - sample(); - observeGc(gc.takeRecords()); - } finally { - clearInterval(probe); - activity.disable(); - gc.disconnect(); - } - longestBlocking = Math.max(longestBlocking, longestGc); - process.stderr.write( - `plugin compile main-thread blocking: ${longestBlocking.toFixed(2)} ms ${JSON.stringify({ longestWall, longestWallCpu, ...longestWallEvents, longestBlockingWindow, longestGc })}\n`, - ); + const { blockingMs } = await measureMainThreadWork("plugin compile main-thread work", action); assert.ok(service.catalog()[0]?.clientBundle.includes("compiled fixture")); - results.push({ blockingMs: longestBlocking }); + results.push({ blockingMs }); } // Evaluate after both probes so parsing the returned code is not charged to compilation. const factory = globalThis.eval(service.catalog()[0]!.clientBundle) as ( diff --git a/packages/server/src/server/utils/diff-highlighter.test.ts b/packages/server/src/server/utils/diff-highlighter.test.ts index 3ecb0372ad..794cd00856 100644 --- a/packages/server/src/server/utils/diff-highlighter.test.ts +++ b/packages/server/src/server/utils/diff-highlighter.test.ts @@ -3,7 +3,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; import { setImmediate } from "node:timers/promises"; -import { performance } from "node:perf_hooks"; +import { measureMainThreadWork } from "../../test-utils/main-thread-work.js"; import { SessionDelivery } from "../session/owned-subscriptions/index.js"; import { highlightCode, highlightCodeWithBudget } from "@getpaseo/highlight"; import { @@ -840,26 +840,19 @@ describe("diff highlighting budget", () => { @@ -1 +1 @@ -const value = Math.max(42, 7); +const value = Math.max(43, 7);`)[0]; - let lastTick = performance.now(); - let longestGap = 0; - const timer = setInterval(() => { - const now = performance.now(); - longestGap = Math.max(longestGap, now - lastTick); - lastTick = now; - }, 1); try { - await setImmediate(); - const highlighted = await highlightDiffWithFileContent( - file, - cwd, - source === "supplied" ? { oldFileContent } : {}, + const { result: highlighted, blockingMs } = await measureMainThreadWork( + `diff highlight 5MiB ${source} main-thread work`, + () => + highlightDiffWithFileContent( + file, + cwd, + source === "supplied" ? { oldFileContent } : {}, + ), ); - await new Promise((resolve) => setTimeout(resolve, 5)); - console.info({ sourceBytes: Buffer.byteLength(oldFileContent), longestGap }); - expect(longestGap).toBeLessThan(50); + expect(blockingMs).toBeLessThan(50); expect(highlighted).toEqual(highlightDiffFromHunks(file)); } finally { - clearInterval(timer); rmSync(cwd, { recursive: true, force: true }); } }, @@ -952,23 +945,17 @@ it("highlights a one-line hunk from an over-budget JSON source without blocking @@ -2 +2 @@ - "value": 42, + "value": 43,`); - let last = performance.now(), - longestGap = 0; - const timer = setInterval(() => { - const now = performance.now(); - longestGap = Math.max(longestGap, now - last); - last = now; - }, 1); try { - const result = await highlightDiffWithFileContent(file, cwd, { oldFileContent }); - await new Promise((resolve) => setTimeout(resolve, 5)); - expect(longestGap).toBeLessThan(50); + const { result, blockingMs } = await measureMainThreadWork( + "diff highlight large JSON main-thread work", + () => highlightDiffWithFileContent(file, cwd, { oldFileContent }), + ); + expect(blockingMs).toBeLessThan(50); expect(result.hunks[0].lines.find((line) => line.type === "add")?.tokens).toContainEqual({ text: "43", style: "number", }); } finally { - clearInterval(timer); rmSync(cwd, { recursive: true, force: true }); } }); diff --git a/packages/server/src/server/workspace-git-service.observation.integration.test.ts b/packages/server/src/server/workspace-git-service.observation.integration.test.ts index 55265416dc..9f53dec33a 100644 --- a/packages/server/src/server/workspace-git-service.observation.integration.test.ts +++ b/packages/server/src/server/workspace-git-service.observation.integration.test.ts @@ -534,6 +534,7 @@ test("Git refresh, command tracing and 10,000 ignored alias events do no synchro const repositoryRoot = fileURLToPath(new URL("../../../../", import.meta.url)); const source = ` import assert from 'node:assert/strict'; + import { measureMainThreadWork } from './packages/server/src/test-utils/main-thread-work.ts'; import { write } from 'node:fs'; import { mkdtemp, mkdir, writeFile, symlink, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; @@ -575,29 +576,23 @@ test("Git refresh, command tracing and 10,000 ignored alias events do no synchro await symlink(worktree, alias, process.platform === 'win32' ? 'junction' : 'dir'); const subscription = await service.requestWorkingTreeWatch(alias, () => { notifications++; }); const events = Array.from({ length: process.env.GIT_IO_TRACE ? 2 : 10000 }, (_, i) => ({ type: 'update', path: join(i % 2 ? alias : worktree, 'ignored', 'noise') })); - // A shared CI runner can deschedule the child during a wall-clock sample. - // Keep the 20ms gate, but take three independent batches and require one - // responsive callback/timer pair. All batches must remain filesystem-free. - const samples = []; - for (let trial = 0; trial < (process.env.GIT_IO_TRACE ? 1 : 3); trial++) { - await tick(); - let fsCalls = 0; - const hook = createHook({ init(_id, type) { if (type.startsWith('FSREQ')) fsCalls++; } }); + let fsCalls = 0; + const hook = createHook({ init(_id, type) { if (type.startsWith('FSREQ')) fsCalls++; } }); + await tick(); + const { blockingMs } = await measureMainThreadWork('Git filter main-thread work', async () => { await marker('FILTER_START'); hook.enable(); - const started = performance.now(); - const pulse = new Promise((resolve) => setTimeout(() => resolve(performance.now() - started), 0)); - callback(null, events); - const filterMs = performance.now() - started; - hook.disable(); - const loopGapMs = await pulse; - await marker('FILTER_END'); - assert.equal(fsCalls, 0, "filesystem calls"); - assert.equal(notifications, 0, "ignored event notification"); - samples.push({ filterMs, loopGapMs, fsCalls }); - } - console.log(JSON.stringify({ ...samples[0], samples })); - assert.ok(process.env.GIT_IO_TRACE || samples.some(({ filterMs, loopGapMs }) => filterMs < 20 && loopGapMs < 20), 'no responsive filter sample: ' + JSON.stringify(samples)); + try { + callback(null, events); + } finally { + hook.disable(); + await marker('FILTER_END'); + } + }); + assert.equal(fsCalls, 0, "filesystem calls"); + assert.equal(notifications, 0, "ignored event notification"); + assert.ok(blockingMs < 20, 'blocking filter work: ' + blockingMs); + console.log(JSON.stringify({ blockingMs, fsCalls })); // Alias identity remains useful after deletion: no per-event realpath can recover this file. callback(null, [{ type: 'delete', path: join(worktree, 'tracked.txt') }]); assert.equal(notifications, 1); diff --git a/packages/server/src/server/workspace-reconciliation-service.test.ts b/packages/server/src/server/workspace-reconciliation-service.test.ts index 5a1b3ae990..0e9f5a2c2d 100644 --- a/packages/server/src/server/workspace-reconciliation-service.test.ts +++ b/packages/server/src/server/workspace-reconciliation-service.test.ts @@ -1,5 +1,4 @@ -import { createHook, executionAsyncResource } from "node:async_hooks"; -import { performance, PerformanceObserver } from "node:perf_hooks"; +import { measureMainThreadWork } from "../test-utils/main-thread-work.js"; import { execFileSync } from "node:child_process"; import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -660,97 +659,20 @@ describe("WorkspaceReconciliationService", () => { workspaceRegistry, logger: createTestLogger(), }); - // Windows can deschedule Node inside a callback too. Budget charged thread - // CPU within callback spans, capped by wall time because Windows CPU counters - // advance in coarse increments. Also require real asynchronous inspections: - // synchronous filesystem waits can block the loop without consuming CPU. - // Node 22.20 provides this API; our older Node declarations omit it. - const threadCpuUsage: (previous?: NodeJS.CpuUsage) => NodeJS.CpuUsage = Reflect.get( - process, - "threadCpuUsage", - ); - const startedAt = performance.now(); - let last = startedAt; - let longestGap = 0; - let longestCallback = 0; - let longestCallbackCpu = 0; - let longestBlocking = 0; - let asyncInspections = 0; - let longestGc = 0; - const callbacks = new Map(); - const observeGc = (entries: readonly import("node:perf_hooks").PerformanceEntry[]) => { - for (const entry of entries) { - if (entry.startTime >= startedAt) longestGc = Math.max(longestGc, entry.duration); - } - }; - const gc = new PerformanceObserver((list) => observeGc(list.getEntries())); - gc.observe({ entryTypes: ["gc"] }); - let probe: ReturnType; - const activity = createHook({ - init(_id, type) { - if (type === "FSREQPROMISE") asyncInspections++; - }, - before(id) { - if (executionAsyncResource() === probe) return; - callbacks.set(id, { wall: performance.now(), cpu: threadCpuUsage() }); - }, - after(id) { - const start = callbacks.get(id); - if (!start) return; - callbacks.delete(id); - const duration = performance.now() - start.wall; - const { user, system } = threadCpuUsage(start.cpu); - const cpuMs = (user + system) / 1_000; - longestBlocking = Math.max(longestBlocking, Math.min(duration, cpuMs)); - if (duration > longestCallback) { - longestCallback = duration; - longestCallbackCpu = cpuMs; - } - }, - }).enable(); - const sample = () => { - const now = performance.now(); - longestGap = Math.max(longestGap, now - last); - last = now; - }; - probe = setInterval(sample, 1); - let result; try { - // Include the initial synchronous span: its callback predates the hook. - const actionStartedAt = performance.now(); - const actionCpu = threadCpuUsage(); - const pending = service.runOnce(); - const actionWallMs = performance.now() - actionStartedAt; - const { user, system } = threadCpuUsage(actionCpu); - longestCallback = Math.max(longestCallback, actionWallMs); - longestBlocking = Math.max(longestBlocking, Math.min(actionWallMs, (user + system) / 1_000)); - result = await pending; - await new Promise((resolve) => setImmediate(resolve)); - sample(); - observeGc(gc.takeRecords()); + const { result, blockingMs, filesystemRequests } = await measureMainThreadWork( + "workspace reconciliation main-thread work", + () => service.runOnce(), + ); + expect(blockingMs).toBeLessThan(20); + expect(filesystemRequests).toBe(20001); + expect(result.changesApplied).toHaveLength(20000); + expect([...workspaces.values()].every((workspace) => workspace.archivedAt !== null)).toBe( + true, + ); } finally { - clearInterval(probe); - activity.disable(); - gc.disconnect(); service.dispose(); } - // GC CPU during callbacks is included above. GC elapsed durations, like - // callback elapsed durations, include runner preemption: log them separately. - const blockingMs = longestBlocking; - process.stderr.write( - `workspace reconciliation main-thread blocking: ${JSON.stringify({ - blockingMs, - asyncInspections, - longestCallback, - longestCallbackCpu, - longestGc, - longestGap, - })}\n`, - ); - expect(blockingMs).toBeLessThan(20); - expect(asyncInspections).toBe(20001); - expect(result.changesApplied).toHaveLength(20000); - expect([...workspaces.values()].every((workspace) => workspace.archivedAt !== null)).toBe(true); }, 30000); test("preserves workspace archival that lands during boot reconciliation", async () => { diff --git a/packages/server/src/test-utils/main-thread-work.ts b/packages/server/src/test-utils/main-thread-work.ts new file mode 100644 index 0000000000..66bb55e491 --- /dev/null +++ b/packages/server/src/test-utils/main-thread-work.ts @@ -0,0 +1,108 @@ +import { createHook, executionAsyncResource } from "node:async_hooks"; +import { performance, PerformanceObserver, type PerformanceEntry } from "node:perf_hooks"; +import { MessagePort } from "node:worker_threads"; + +/** Measure main-thread work without charging idle IO or runner descheduling. */ +export async function measureMainThreadWork(label: string, action: () => T | Promise) { + // Node 22.20 supplies this API; the repository's older declarations omit it. + const threadCpuUsage: (previous?: NodeJS.CpuUsage) => NodeJS.CpuUsage = Reflect.get( + process, + "threadCpuUsage", + ); + let blockingMs = 0; + let filesystemRequests = 0; + let yields = 0; + let longestCallbackMs = 0; + let longestCallbackCpuMs = 0; + let longestGapMs = 0; + let longestGcMs = 0; + let gcCount = 0; + let workerEvents = 0; + let draining = false; + const startedAt = performance.now(); + let previous = startedAt; + let previousCpu = threadCpuUsage(); + let probe: ReturnType; + let drain: ReturnType; + const callbacks = new Map(); + const record = (wallMs: number, cpu: NodeJS.CpuUsage) => { + const cpuMs = (cpu.user + cpu.system) / 1_000; + // Windows CPU accounting is coarse. Cap charged CPU by the real span so a + // counter increment cannot inflate a short callback. Zero-CPU waits drop out. + blockingMs = Math.max(blockingMs, Math.min(wallMs, cpuMs)); + if (wallMs > longestCallbackMs) { + longestCallbackMs = wallMs; + longestCallbackCpuMs = cpuMs; + } + }; + const observeGc = (entries: readonly PerformanceEntry[]) => { + for (const entry of entries) { + if (entry.startTime < startedAt) continue; + gcCount++; + longestGcMs = Math.max(longestGcMs, entry.duration); + } + }; + const gc = new PerformanceObserver((list) => observeGc(list.getEntries())); + gc.observe({ entryTypes: ["gc"] }); + const activity = createHook({ + init(_id, type) { + if (type.startsWith("FSREQ")) filesystemRequests++; + if (!draining && type === "Immediate") yields++; + if (type === "WORKER") workerEvents++; + }, + before(id) { + const resource = executionAsyncResource(); + if (resource === probe || resource === drain) return; + if (resource instanceof MessagePort) workerEvents++; + callbacks.set(id, { wall: performance.now(), cpu: threadCpuUsage() }); + }, + after(id) { + const start = callbacks.get(id); + if (!start) return; + callbacks.delete(id); + record(performance.now() - start.wall, threadCpuUsage(start.cpu)); + }, + }).enable(); + const sample = () => { + const now = performance.now(); + const cpu = threadCpuUsage(); + const wallMs = now - previous; + longestGapMs = Math.max(longestGapMs, wallMs); + // Worker construction/message cloning can precede async_hooks.before. + if (workerEvents) { + blockingMs = Math.max( + blockingMs, + Math.min(wallMs, (cpu.user - previousCpu.user + cpu.system - previousCpu.system) / 1_000), + ); + } + workerEvents = 0; + previous = now; + previousCpu = cpu; + }; + probe = setInterval(sample, 1); + let result: T; + try { + // The caller's current callback began before the hook was installed. + const wall = performance.now(); + const cpu = threadCpuUsage(); + const pending = action(); + record(performance.now() - wall, threadCpuUsage(cpu)); + result = await pending; + draining = true; + await new Promise((resolve) => { + drain = setImmediate(resolve); + }); + sample(); + observeGc(gc.takeRecords()); + } finally { + clearInterval(probe); + activity.disable(); + gc.disconnect(); + } + // GC CPU inside callbacks is charged above. Elapsed GC spans, like elapsed + // callback spans, include preemption and remain diagnostics rather than gates. + process.stderr.write( + `${label}: ${JSON.stringify({ blockingMs, filesystemRequests, yields, longestCallbackMs, longestCallbackCpuMs, longestGcMs, gcCount, longestGapMs })}\n`, + ); + return { result, blockingMs, filesystemRequests, yields }; +} diff --git a/packages/server/src/utils/paseo-config-file.test.ts b/packages/server/src/utils/paseo-config-file.test.ts index 075ddd9720..1eed6ec054 100644 --- a/packages/server/src/utils/paseo-config-file.test.ts +++ b/packages/server/src/utils/paseo-config-file.test.ts @@ -3,7 +3,7 @@ import { execFile } from "node:child_process"; import { promisify } from "node:util"; import { fileURLToPath } from "node:url"; import { writeFile, truncate, rm } from "node:fs/promises"; -import { setImmediate as nextTurn } from "node:timers/promises"; +import { measureMainThreadWork } from "../test-utils/main-thread-work.js"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; @@ -67,7 +67,7 @@ describe("paseo config file substrate", () => { ); }); - it("keeps the longest loop stall below 20ms while admitting large configs", async () => { + it("keeps main-thread work below 20ms while admitting large configs", async () => { const config = { scripts: Object.fromEntries( Array.from({ length: 7_000 }, (_, i) => [`script${i}`, { command: "echo hi" }]), @@ -75,48 +75,27 @@ describe("paseo config file substrate", () => { worktree: { setup: "npm ci" }, }; await writeFile(join(tempDir, "paseo.json"), JSON.stringify(config)); - let previous = performance.now(); - let longestGap = 0; - const probe = setInterval(() => { - const now = performance.now(); - longestGap = Math.max(longestGap, now - previous); - previous = now; - }, 1); - let result: Awaited>; - try { - result = await readPaseoConfigForEdit(tempDir); - await nextTurn(); - longestGap = Math.max(longestGap, performance.now() - previous); - } finally { - clearInterval(probe); - } + const { result, blockingMs, filesystemRequests, yields } = await measureMainThreadWork( + "project config 7000 scripts main-thread work", + () => readPaseoConfigForEdit(tempDir), + ); expect(result).toEqual({ ok: true, config, revision: await statPaseoConfigPath(tempDir) }); - process.stdout.write(`project config 7,000 scripts max loop gap: ${longestGap.toFixed(2)}ms\n`); - expect(longestGap).toBeLessThan(20); + expect(blockingMs).toBeLessThan(20); + expect(filesystemRequests).toBeGreaterThan(0); + expect(yields).toBeGreaterThan(0); }); - it("rejects a 32MiB config with a loop stall below 20ms", async () => { + it("rejects a 32MiB config with main-thread work below 20ms", async () => { await writeFile( join(tempDir, "paseo.json"), JSON.stringify({ extra: "x".repeat(32 * 1024 * 1024) }), ); - let previous = performance.now(); - let longestGap = 0; - const probe = setInterval(() => { - const now = performance.now(); - longestGap = Math.max(longestGap, now - previous); - previous = now; - }, 1); - let result: Awaited>; - try { - result = await readPaseoConfigForEdit(tempDir); - await nextTurn(); - longestGap = Math.max(longestGap, performance.now() - previous); - } finally { - clearInterval(probe); - } - process.stdout.write(`project config 32MiB max loop gap: ${longestGap.toFixed(2)}ms\n`); - expect(longestGap).toBeLessThan(20); + const { result, blockingMs, filesystemRequests } = await measureMainThreadWork( + "project config 32MiB main-thread work", + () => readPaseoConfigForEdit(tempDir), + ); + expect(blockingMs).toBeLessThan(20); + expect(filesystemRequests).toBeGreaterThan(0); expect(result).toEqual({ ok: false, error: { code: "invalid_project_config" } }); }); From 8a542048b653f946288cd9b01d6a6e91838648fc Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Tue, 27 Oct 2026 15:20:06 +0700 Subject: [PATCH 054/173] Let plugins contribute MCP servers on every agent session open (#7983) * feat(plugins): contribute launch-only MCP servers at session open * docs(plugins): explain saved configuration and launch-only MCP servers --- docs/plugins.md | 6 +- packages/plugin/src/boundaries.test.ts | 6 +- packages/plugin/src/server/lifecycle.ts | 1 + .../server/src/server/agent/agent-manager.ts | 90 ++++-- .../src/server/agent/agent-sdk-types.ts | 3 + .../src/server/agent/plugin-provider.test.ts | 25 ++ .../src/server/agent/plugin-provider.ts | 2 +- .../src/server/agent/runtime-mcp-config.ts | 2 +- .../plugins/agent-configuration.e2e.test.ts | 28 +- .../server/plugins/agent-tools.e2e.test.ts | 294 +++++++++++++++++- .../server/plugins/lifecycle/handlers.test.ts | 4 +- .../src/server/plugins/lifecycle/index.ts | 16 +- packages/server/src/server/plugins/runtime.ts | 39 ++- plugin-examples/agent-configuration/README.md | 29 +- .../agent-configuration/index.server.ts | 22 +- .../agent-configuration/paseo-plugin.json | 2 +- public-docs/plugins/reference.md | 85 +++-- public-docs/plugins/reference.zh-CN.md | 68 ++-- skills/paseo-plugin/SKILL.md | 72 +++-- 19 files changed, 663 insertions(+), 131 deletions(-) diff --git a/docs/plugins.md b/docs/plugins.md index 9cab47214e..951738c902 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -430,7 +430,11 @@ The [public reference](../public-docs/plugins/reference.md#icons) owns the autho Server entries register lifecycle observers with `server.on()` and request transforms with `server.before()`. The [public reference](../public-docs/plugins/reference.md#lifecycle-hooks) -owns callback shapes, ordering, and failure behavior. `plugin-examples/lifecycle-logger` registers all +owns callback shapes, ordering, and failure behavior. `agent.create` edits the agent's saved +configuration; `agent.session_open` contributes launch-only `env`, `tools`, and `mcpServers`, +re-derived on each open and following the plugin's lifecycle. See +[Inject MCP servers](../public-docs/plugins/reference.md#inject-mcp-servers) for choosing the hook. +`plugin-examples/lifecycle-logger` registers all eleven hooks; `plugin-examples/lifecycle-actions` demonstrates common automation callbacks. Session-open hooks also [attach tools to individual agents](../public-docs/plugins/reference.md#attach-tools-to-agents), as shown in `plugin-examples/agent-tools`. The agent manager stamps their metadata per session; diff --git a/packages/plugin/src/boundaries.test.ts b/packages/plugin/src/boundaries.test.ts index 017b69bda5..56f0d0d78c 100644 --- a/packages/plugin/src/boundaries.test.ts +++ b/packages/plugin/src/boundaries.test.ts @@ -238,7 +238,11 @@ describe("plugin agent tools SDK boundary", () => { // @ts-expect-error labels are read-only request.labels.x = "changed"; if (request.labels.x !== "y") return; - return { ...request, tools: [...request.tools, tool] }; + // @ts-expect-error MCP servers use the same typed transport config as saved servers + request.mcpServers.invalid = { type: "http", url: 42 }; + return { ...request, tools: [...request.tools, tool], mcpServers: { + ...request.mcpServers, company: { type: "http", url: "https://tools.example.com/mcp" }, + } }; }); return () => {}; } diff --git a/packages/plugin/src/server/lifecycle.ts b/packages/plugin/src/server/lifecycle.ts index f3f2643a04..9486383072 100644 --- a/packages/plugin/src/server/lifecycle.ts +++ b/packages/plugin/src/server/lifecycle.ts @@ -41,6 +41,7 @@ export interface PluginSessionOpenRequest { readonly labels: Readonly>; tools: AgentToolDefinition[]; env: Record; + mcpServers: NonNullable; } export type PluginTurnOutcome = diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index 1342576f7f..8cbdfc068e 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -85,7 +85,11 @@ import { import { invokeRewindCapability, type RewindMode } from "./rewind/rewind.js"; import { parseAgentMessage, projectAgentMessages } from "./agent-messages/index.js"; import { isStaleProviderSessionError } from "./stale-provider-session-error.js"; -import { stripInternalPaseoMcpServer, withRuntimePaseoMcpServer } from "./runtime-mcp-config.js"; +import { + PASEO_MCP_SERVER_NAME, + stripInternalPaseoMcpServer, + withRuntimePaseoMcpServer, +} from "./runtime-mcp-config.js"; import { resolveCreateAgentTitles } from "./create-agent-title.js"; import type { PaseoToolCatalogFactory } from "./tools/types.js"; import { isPaseoToolPolicyEnabled } from "./paseo-tool-policy.js"; @@ -559,18 +563,20 @@ interface AgentMetadataPatch { const SYSTEM_ERROR_PREFIX = "[System Error]"; -function attachPersistenceCwd( +function normalizePersistenceForConfig( handle: AgentPersistenceHandle | null, - cwd: string, + config: AgentSessionConfig, ): AgentPersistenceHandle | null { if (!handle) { return null; } + const { mcpServers: _launchMcpServers, ...metadata } = handle.metadata ?? {}; return { ...handle, metadata: { - ...handle.metadata, - cwd, + ...metadata, + cwd: config.cwd, + ...(config.mcpServers ? { mcpServers: config.mcpServers } : {}), }, }; } @@ -1387,7 +1393,7 @@ export class AgentManager { const providerLaunchConfig = this.resolveProviderLaunchConfig(launchConfig, launchContext); const createOptions = this.buildCreateSessionOptions(options); const session = await client.createSession(providerLaunchConfig, launchContext, createOptions); - await this.requireExternalMcpSupport(session, storedConfig); + await this.requireExternalMcpSupport(session, providerLaunchConfig, launchContext); const agent = await this.registerSession(session, storedConfig, resolvedAgentId, { labels: options.labels, initialTitle: options.initialTitle, @@ -1515,7 +1521,7 @@ export class AgentManager { launchContext, currentResumeOptions, ); - await this.requireExternalMcpSupport(session, storedConfig); + await this.requireExternalMcpSupport(session, providerLaunchConfig, launchContext); return this.registerSession(session, storedConfig, resolvedAgentId, { ...options, persistence: handle, @@ -1578,6 +1584,7 @@ export class AgentManager { }, { config: providerLaunchConfig, storedConfig, launchContext }, ); + await this.requireExternalMcpSupport(imported.session, providerLaunchConfig, launchContext); let handedToRegistration = false; try { const importedConfig = await this.normalizeConfig( @@ -1673,10 +1680,10 @@ export class AgentManager { ); const providerLaunchConfig = this.resolveProviderLaunchConfig(launchConfig, launchContext); if ( - Object.keys(storedConfig.mcpServers ?? {}).length > 0 && + Object.keys(stripInternalPaseoMcpServer(providerLaunchConfig).mcpServers ?? {}).length > 0 && existing.session.capabilities.supportsMcpServers !== true ) { - throw new Error(`Provider '${provider}' does not support MCP servers`); + throw this.unsupportedMcpError(providerLaunchConfig, launchContext); } let session: AgentSession | undefined; @@ -1695,7 +1702,7 @@ export class AgentManager { session = handle ? await client.resumeSession(handle, providerLaunchConfig, launchContext) : await client.createSession(providerLaunchConfig, launchContext); - await this.requireExternalMcpSupport(session, storedConfig); + await this.requireExternalMcpSupport(session, providerLaunchConfig, launchContext); this.assertAcceptingAgentRegistrations(); if (rehydrateFromDisk) { @@ -2921,7 +2928,10 @@ export class AgentManager { ? { provider: mutableAgent.provider, sessionId: mutableAgent.runtimeInfo.sessionId } : null); if (persistenceHandle) { - mutableAgent.persistence = attachPersistenceCwd(persistenceHandle, mutableAgent.cwd); + mutableAgent.persistence = normalizePersistenceForConfig( + persistenceHandle, + mutableAgent.config, + ); } this.logger.trace( { @@ -3865,16 +3875,23 @@ export class AgentManager { private async requireExternalMcpSupport( session: AgentSession, - storedConfig: AgentSessionConfig, + launchConfig: AgentSessionConfig, + launchContext: AgentLaunchContext, ): Promise { if ( - Object.keys(storedConfig.mcpServers ?? {}).length === 0 || + Object.keys(stripInternalPaseoMcpServer(launchConfig).mcpServers ?? {}).length === 0 || session.capabilities.supportsMcpServers === true ) { return; } await this.closeUnregisteredSession(session); - throw new Error(`Provider '${storedConfig.provider}' does not support MCP servers`); + throw this.unsupportedMcpError(launchConfig, launchContext); + } + + private unsupportedMcpError(config: AgentSessionConfig, context: AgentLaunchContext): Error { + const owners = [...new Set(Object.values(context.mcpServerOwners ?? {}))]; + const source = owners.length ? ` (plugin ${owners.join(", ")})` : ""; + return new Error(`Provider '${config.provider}' does not support MCP servers${source}`); } private async initializeAgentTimelineForRegister(params: { @@ -3960,9 +3977,9 @@ export class AgentManager { foregroundTurnWaiters: new Set(), finalizedForegroundTurnIds: new Set(), unsubscribeSession: null, - persistence: attachPersistenceCwd( + persistence: normalizePersistenceForConfig( options?.persistence ?? session.describePersistence(), - config.cwd, + config, ), historyPrimed: options?.historyPrimed ?? durableTimelineHasRows, lastUserMessageAt: options?.lastUserMessageAt ?? null, @@ -4266,9 +4283,9 @@ export class AgentManager { newInfo.modeId !== agent.runtimeInfo?.modeId; agent.runtimeInfo = newInfo; if (!agent.persistence && newInfo.sessionId) { - agent.persistence = attachPersistenceCwd( + agent.persistence = normalizePersistenceForConfig( { provider: agent.provider, sessionId: newInfo.sessionId }, - agent.cwd, + agent.config, ); } // Emit state if runtimeInfo changed so clients get the updated model @@ -4626,9 +4643,9 @@ export class AgentManager { case "model_changed": agent.runtimeInfo = event.runtimeInfo; if (!agent.persistence && event.runtimeInfo.sessionId) { - agent.persistence = attachPersistenceCwd( + agent.persistence = normalizePersistenceForConfig( { provider: agent.provider, sessionId: event.runtimeInfo.sessionId }, - agent.cwd, + agent.config, ); } this.applyObservedMode(agent, event.runtimeInfo.modeId ?? agent.currentModeId); @@ -4702,7 +4719,7 @@ export class AgentManager { private refreshSessionPersistence(agent: ActiveManagedAgent): void { const handle = agent.session.describePersistence(); if (handle) { - agent.persistence = attachPersistenceCwd(handle, agent.cwd); + agent.persistence = normalizePersistenceForConfig(handle, agent.config); } } @@ -5519,6 +5536,8 @@ export class AgentManager { // A plugin changing during this open must still make the resulting session stale. const generation = this.sessionOpenGeneration; this.detachPluginTools(agentId); + let mcpServers: AgentSessionConfig["mcpServers"]; + let mcpServerOwners: Record | undefined; if (this.pluginLifecycle) { const request = { agentId, @@ -5531,14 +5550,20 @@ export class AgentManager { title: opening?.title ?? null, labels: opening?.labels ?? {}, tools: [], + mcpServers: {}, }; const transformed = await this.pluginLifecycle.before("agent.session_open", request); env = transformed.env; - if (request.purpose === "interactive") + if (request.purpose === "interactive") { this.attachedPluginTools.set(agentId, transformed.tools as AttachedAgentTool[]); + mcpServers = transformed.mcpServers; + mcpServerOwners = transformed.mcpServerOwners; + } } const context: AgentLaunchContext = { agentId, + mcpServers, + mcpServerOwners, env: { ...env, PASEO_AGENT_ID: agentId, @@ -5572,7 +5597,26 @@ export class AgentManager { launchConfig: AgentSessionConfig, launchContext: AgentLaunchContext, ): AgentSessionConfig { - return launchContext.paseoTools ? stripInternalPaseoMcpServer(launchConfig) : launchConfig; + const savedServerNames = new Set( + Object.keys(stripInternalPaseoMcpServer(launchConfig).mcpServers ?? {}), + ); + for (const name of Object.keys(launchContext.mcpServers ?? {})) { + const owner = launchContext.mcpServerOwners?.[name]; + if (name === PASEO_MCP_SERVER_NAME || savedServerNames.has(name)) { + const existingOwner = savedServerNames.has(name) + ? "agent saved configuration" + : "Paseo internal MCP server"; + throw new Error(`MCP server '${name}' from plugin ${owner} collides with ${existingOwner}`); + } + } + const merged = + Object.keys(launchContext.mcpServers ?? {}).length > 0 + ? { + ...launchConfig, + mcpServers: { ...launchConfig.mcpServers, ...launchContext.mcpServers }, + } + : launchConfig; + return launchContext.paseoTools ? stripInternalPaseoMcpServer(merged) : merged; } private async requireAvailableClient(options: { provider: AgentProvider }): Promise { diff --git a/packages/server/src/server/agent/agent-sdk-types.ts b/packages/server/src/server/agent/agent-sdk-types.ts index 6818e65445..507cfbceb8 100644 --- a/packages/server/src/server/agent/agent-sdk-types.ts +++ b/packages/server/src/server/agent/agent-sdk-types.ts @@ -616,6 +616,9 @@ export interface AgentSessionConfig { } export interface AgentLaunchContext { + /** Launch-only plugin MCP servers and their owners; never persisted. */ + mcpServers?: Record; + mcpServerOwners?: Record; agentId?: string; env?: Record; /** diff --git a/packages/server/src/server/agent/plugin-provider.test.ts b/packages/server/src/server/agent/plugin-provider.test.ts index 72bc0f475b..8ae271c08a 100644 --- a/packages/server/src/server/agent/plugin-provider.test.ts +++ b/packages/server/src/server/agent/plugin-provider.test.ts @@ -1321,3 +1321,28 @@ test("plugin without a runtime safety capability uses baseline collection withou await rm(home, { recursive: true, force: true }); } }); + +test("plugin provider import launches with runtime MCP servers and returns only saved configuration", async () => { + const harness = createProviderHarness(); + const registry = new PluginAgentClientRegistry(createTestLogger()); + registry.replace([harness.registration]); + const client = registry.clients()[harness.registration.id]!; + const storedConfig = { provider: harness.registration.id, cwd: "/project" }; + const company = { type: "http", url: "https://tools.example.com/mcp" } as const; + try { + const imported = await client.importSession!( + { providerHandleId: 'plugin:{"version":1,"data":{"token":"root"}}', cwd: "/project" }, + { config: { ...storedConfig, mcpServers: { company } }, storedConfig }, + ); + expect(harness.inputs).toContainEqual( + expect.objectContaining({ + type: "session.open", + config: expect.objectContaining({ mcpServers: { company } }), + }), + ); + expect(imported.config).toEqual(storedConfig); + await imported.session.close(); + } finally { + await registry.shutdown(); + } +}); diff --git a/packages/server/src/server/agent/plugin-provider.ts b/packages/server/src/server/agent/plugin-provider.ts index 68e9778e43..570e339203 100644 --- a/packages/server/src/server/agent/plugin-provider.ts +++ b/packages/server/src/server/agent/plugin-provider.ts @@ -1052,7 +1052,7 @@ class PluginAgentClient implements AgentClient { if (!persistence) throw new Error(`Plugin provider '${this.provider}' did not persist import`); return { session, - config: { ...context.config, provider: this.provider, cwd: input.cwd }, + config: { ...context.storedConfig, provider: this.provider, cwd: input.cwd }, persistence, timeline: session.timelineHistory(), providerSubagentEvents: session.subagentHistory(), diff --git a/packages/server/src/server/agent/runtime-mcp-config.ts b/packages/server/src/server/agent/runtime-mcp-config.ts index af04e8021c..711638ce2f 100644 --- a/packages/server/src/server/agent/runtime-mcp-config.ts +++ b/packages/server/src/server/agent/runtime-mcp-config.ts @@ -1,6 +1,6 @@ import type { AgentSessionConfig, McpServerConfig } from "./agent-sdk-types.js"; -const PASEO_MCP_SERVER_NAME = "paseo"; +export const PASEO_MCP_SERVER_NAME = "paseo"; const PASEO_MCP_PATHNAME = "/mcp/agents"; export function stripInternalPaseoMcpServer(config: AgentSessionConfig): AgentSessionConfig { diff --git a/packages/server/src/server/plugins/agent-configuration.e2e.test.ts b/packages/server/src/server/plugins/agent-configuration.e2e.test.ts index 3228306297..1cfad77e05 100644 --- a/packages/server/src/server/plugins/agent-configuration.e2e.test.ts +++ b/packages/server/src/server/plugins/agent-configuration.e2e.test.ts @@ -4,17 +4,29 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; import { expect, test } from "vitest"; import { DaemonClient } from "../test-utils/daemon-client.js"; +import type { AgentSessionConfig } from "../agent/agent-sdk-types.js"; import { createTestAgentClient } from "../test-utils/fake-agent-client.js"; import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js"; -test("the configuration example adds MCP servers and overrides Codex options while preserving other configuration", async () => { +test("the configuration example saves Codex options and injects launch-only MCP servers while preserving other configuration", async () => { const directory = await mkdtemp(path.join(tmpdir(), "paseo-config-example-")); + const launches: AgentSessionConfig[] = []; const daemon = await createTestPaseoDaemon({ - daemonVersion: "0.8.0", - agentClients: { codex: createTestAgentClient("codex", { supportsMcpServers: true }) }, + daemonVersion: "0.13.2", + agentClients: { + codex: createTestAgentClient("codex", { + supportsMcpServers: true, + beforeCreateSession: async (config) => { + launches.push(config); + }, + }), + }, mcpEnabled: false, }); - const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws`, appVersion: "0.8.0" }); + const client = new DaemonClient({ + url: `ws://127.0.0.1:${daemon.port}/ws`, + appVersion: "0.13.2", + }); try { await client.connect(); await client.fetchAgents({ subscribe: {} }); @@ -44,9 +56,15 @@ test("the configuration example adds MCP servers and overrides Codex options whi }, mcpServers: { existing: { type: "http", url: "https://existing.example.com/mcp" }, - company: { type: "http", url: "https://tools.example.com/mcp" }, }, }); + expect(daemon.daemon.agentManager.getAgent(agent.id)!.config.mcpServers).toEqual({ + existing: { type: "http", url: "https://existing.example.com/mcp" }, + }); + expect(launches[0].mcpServers).toEqual({ + existing: { type: "http", url: "https://existing.example.com/mcp" }, + company: { type: "http", url: "https://tools.example.com/mcp" }, + }); await client.archiveAgent(agent.id); } finally { await client.close(); diff --git a/packages/server/src/server/plugins/agent-tools.e2e.test.ts b/packages/server/src/server/plugins/agent-tools.e2e.test.ts index 14629aa15e..5b03bae09b 100644 --- a/packages/server/src/server/plugins/agent-tools.e2e.test.ts +++ b/packages/server/src/server/plugins/agent-tools.e2e.test.ts @@ -1,5 +1,5 @@ import { fileURLToPath } from "node:url"; -import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { mkdtemp, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { expect, test } from "vitest"; @@ -11,6 +11,7 @@ import { type TestAgentClientOptions, } from "../test-utils/fake-agent-client.js"; import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js"; +import { importSessionFromPersistence } from "../agent/provider-session-import.js"; import { BuiltinPluginLoader } from "./builtin/index.js"; import { serializePaseoToolInputParameters } from "../agent/tools/paseo-tool-serialization.js"; import type { @@ -27,7 +28,7 @@ function recordingProvider(native: boolean, callbacks: TestAgentClientOptions = const events = { interrupts: 0 }; const inner = createTestAgentClient("codex", { ...callbacks, - supportsMcpServers: true, + supportsMcpServers: callbacks.supportsMcpServers ?? true, onStartTurn: (prompt, config) => { turns.push({ prompt, launchCount: launches.length }); callbacks.onStartTurn?.(prompt, config); @@ -52,6 +53,13 @@ function recordingProvider(native: boolean, callbacks: TestAgentClientOptions = launches.push({ config: config as AgentSessionConfig, context }); return inner.resumeSession(handle, config, context, options); }, + importSession: (input, context) => + importSessionFromPersistence({ + provider: "codex", + request: input, + context, + resumeSession: provider.resumeSession.bind(provider), + }), isAvailable: () => inner.isAvailable(), fetchCatalog: (options) => inner.fetchCatalog(options), }; @@ -750,3 +758,285 @@ test("the agent-tools example appends notes only for labeled agents", async () = await h.close(); } }, 60_000); + +const companyServer = { type: "http", url: "https://tools.example.com/mcp" } as const; +const mcpSource = ` +export default function contribute(server) { + server.before("agent.session_open", ({ request }) => { + if (request.provider !== "codex") return; + return { ...request, mcpServers: { ...request.mcpServers, company: ${JSON.stringify(companyServer)} }, + env: { ...request.env, OPEN_REASON: request.reason } }; + }); + return () => {}; +} +`; + +test.each([ + { native: false, serverNames: ["paseo", "company"] }, + { native: true, serverNames: ["company"] }, +])( + "session-open MCP servers reach launch but never saved configuration (native=$native)", + async ({ native, serverNames }) => { + const h = await setup(native, mcpSource); + try { + const a = await h.create(); + expect(h.launches.at(-1)!.config.mcpServers?.company).toEqual(companyServer); + expect(a.config.mcpServers?.company).toBeUndefined(); + const snapshot = (await h.client.fetchAgent(a.id))!.agent; + expect(snapshot.id).toBe(a.id); + expect(JSON.stringify(snapshot)).not.toContain("tools.example.com"); + expect(h.launches.at(-1)!.context!.env!.OPEN_REASON).toBe("create"); + expect(Object.keys(h.launches.at(-1)!.config.mcpServers!)).toEqual(serverNames); + await h.daemon.daemon.agentManager.closeAgent(a.id); + const agentFiles = await readdir(path.join(h.daemon.paseoHome, "agents"), { + recursive: true, + }); + const recordFile = agentFiles.find((file) => file.endsWith(a.id + ".json"))!; + const record = await readFile(path.join(h.daemon.paseoHome, "agents", recordFile), "utf8"); + expect(record).not.toContain("tools.example.com"); + } finally { + await h.close(); + } + }, + 60_000, +); + +test("session-open MCP servers are rederived on resume, SDK reload, and provider import", async () => { + const source = reloadRpcSource + .replace(' if (request.labels.x !== "y") return;', "") + .replace( + "return { ...request, env:", + `return { ...request, mcpServers: { ...request.mcpServers, company: ${JSON.stringify(companyServer)} }, env:`, + ); + const h = await setup(true, source); + try { + const a = await h.create({ x: "y" }); + const manager = h.daemon.daemon.agentManager; + await manager.closeAgent(a.id); + await manager.resumeAgentFromPersistence(a.persistence!, a.config, a.id); + expect(h.launches.at(-1)!.config.mcpServers?.company).toEqual(companyServer); + expect(JSON.parse(h.launches.at(-1)!.context!.env!.OPEN_INFO).reason).toBe("resume"); + await h.client.invokePluginRpc("tools-test", "reload_agent", { id: a.id }); + expect(h.launches.at(-1)!.config.mcpServers?.company).toEqual(companyServer); + expect(JSON.parse(h.launches.at(-1)!.context!.env!.OPEN_INFO).reason).toBe("refresh"); + const imported = await manager.importProviderSession({ + provider: "codex", + providerHandleId: "imported-session", + cwd: h.directory, + workspaceId: "import-workspace", + labels: { x: "y" }, + }); + expect(h.launches.at(-1)!.config.mcpServers?.company).toEqual(companyServer); + expect(JSON.parse(h.launches.at(-1)!.context!.env!.OPEN_INFO).reason).toBe("import"); + expect(imported.config.mcpServers?.company).toBeUndefined(); + expect(JSON.stringify(imported.persistence)).not.toContain("tools.example.com"); + expect(manager.getAgent(a.id)!.config.mcpServers?.company).toBeUndefined(); + expect(JSON.stringify(manager.getAgent(a.id)!.persistence)).not.toContain("tools.example.com"); + } finally { + await h.close(); + } +}, 60_000); + +test("installing and disabling an MCP plugin reopens idle sessions before their next prompt", async () => { + const h = await setup(true, "export default function contribute() { return () => {}; }"); + try { + const a = await h.create(); + expect(h.launches.at(-1)!.config.mcpServers?.company).toBeUndefined(); + await h.install("company-mcp", mcpSource); + await sendAndFinish(h, a.id, "after install"); + expect(h.launches).toHaveLength(2); + expect(h.launches.at(-1)!.config.mcpServers?.company).toEqual(companyServer); + await h.client.disablePlugin("company-mcp"); + await sendAndFinish(h, a.id, "after disable"); + expect(h.launches).toHaveLength(3); + expect(h.launches.at(-1)!.config.mcpServers?.company).toBeUndefined(); + await sendAndFinish(h, a.id, "stable"); + expect(h.launches).toHaveLength(3); + expect(h.events.interrupts).toBe(0); + } finally { + await h.close(); + } +}, 60_000); + +test("installing and disabling an MCP plugin never interrupts a running turn", async () => { + let release!: () => void; + const blocked = new Promise((resolve) => { + release = resolve; + }); + const h = await setup( + true, + "export default function contribute() { return () => {}; }", + undefined, + { beforeTurnComplete: async () => blocked }, + ); + try { + const a = await h.create(); + await h.client.sendMessage(a.id, "busy", { activeTurnBehavior: "steer" }); + const manager = h.daemon.daemon.agentManager; + await expect.poll(() => manager.getAgent(a.id)!.activeTurnId).not.toBeNull(); + const turn = manager.getAgent(a.id)!.activeTurnId; + await h.install("company-mcp", mcpSource); + expect(h.launches).toHaveLength(1); + expect(manager.getAgent(a.id)!.activeTurnId).toBe(turn); + await h.client.disablePlugin("company-mcp"); + expect(h.launches).toHaveLength(1); + expect(manager.getAgent(a.id)!.activeTurnId).toBe(turn); + expect(h.events.interrupts).toBe(0); + release(); + await expect.poll(() => manager.hasInFlightRun(a.id)).toBe(false); + await sendAndFinish(h, a.id, "idle"); + expect(h.launches).toHaveLength(2); + expect(h.launches.at(-1)!.config.mcpServers?.company).toBeUndefined(); + } finally { + release(); + await h.close(); + } +}, 60_000); + +test.each([ + { + target: "saved configuration", + saved: true, + name: "company", + other: false, + error: /company.*plugin tools-test.*agent saved configuration/, + }, + { + target: "saved Paseo name", + saved: true, + name: "paseo", + other: false, + error: /paseo.*plugin tools-test.*agent saved configuration/, + }, + { + target: "Paseo internal server", + saved: false, + name: "paseo", + other: false, + error: /paseo.*plugin tools-test.*Paseo internal MCP server/, + }, + { + target: "another plugin with identical config", + saved: false, + name: "company", + other: true, + error: /Plugin tools-test.*company.*plugin other-mcp/, + }, +])( + "session-open MCP collisions with $target name both owners", + async ({ saved, name, other, error }) => { + const h = await setup(true, mcpSource.replace("company:", name + ":")); + try { + if (other) await h.install("other-mcp", mcpSource); + await expect( + h.daemon.daemon.agentManager.createAgent( + { + provider: "codex", + cwd: h.directory, + ...(saved + ? { mcpServers: { [name]: { type: "http", url: "https://saved.example.com" } } } + : {}), + }, + undefined, + {}, + ), + ).rejects.toThrow(error); + expect(h.launches).toHaveLength(0); + } finally { + await h.close(); + } + }, + 60_000, +); + +test("session-open MCP servers fail on unsupported providers and leave saved config untouched", async () => { + const h = await setup(false, mcpSource, undefined, { supportsMcpServers: false }); + try { + await h.client.disablePlugin("tools-test"); + const a = await h.create(); + await h.client.enablePlugin("tools-test"); + await expect(h.daemon.daemon.agentManager.reloadAgentSession(a.id)).rejects.toThrow( + /does not support MCP servers.*plugin tools-test/, + ); + expect(a.config.mcpServers?.company).toBeUndefined(); + await expect(h.create()).rejects.toThrow(/does not support MCP servers.*plugin tools-test/); + const imported = h.daemon.daemon.agentManager.importProviderSession({ + provider: "codex", + providerHandleId: "unsupported-import", + cwd: h.directory, + workspaceId: "import-workspace", + }); + await expect(imported).rejects.toThrow(/does not support MCP servers.*plugin tools-test/); + } finally { + await h.close(); + } +}, 60_000); + +test("history opens ignore session-open MCP servers", async () => { + const h = await setup(true, mcpSource); + try { + const a = await h.create(); + await h.client.archiveAgent(a.id); + await h.install("other-mcp", mcpSource); + await h.daemon.daemon.agentManager.resumeAgentFromPersistence(a.persistence!, a.config, a.id); + expect(h.launches.at(-1)!.config.mcpServers?.company).toBeUndefined(); + expect(h.launches.at(-1)!.context!.mcpServers).toBeUndefined(); + } finally { + await h.close(); + } +}, 60_000); + +test("session-open MCP maps are plugin-local and accumulate only across their own callbacks", async () => { + const h = await setup(true, mcpSource); + try { + await h.install( + "z-extend", + ` +export default function contribute(server) { + server.before("agent.session_open", ({ request }) => { + if ("mcpServerOwners" in request) throw new Error("Daemon provenance leaked"); + if (Object.keys(request.mcpServers).length !== 0) throw new Error("Saw another plugin servers"); + return { ...request, mcpServers: { ...request.mcpServers, extra: { type: "stdio", command: "company-tools", args: ["--mcp"], env: { MODE: "agent" } } } }; + }); + server.before("agent.session_open", ({ request }) => { + if (request.mcpServers.extra.command !== "company-tools") throw new Error("Lost own earlier server"); + return { ...request, mcpServers: { ...request.mcpServers, additional: { type: "http", url: "https://additional.example.com/mcp" } } }; + }); + server.before("agent.session_open", () => undefined); + return () => {}; +}`, + ); + const a = await h.create(); + expect(h.launches.at(-1)!.config.mcpServers).toEqual({ + company: companyServer, + extra: { type: "stdio", command: "company-tools", args: ["--mcp"], env: { MODE: "agent" } }, + additional: { type: "http", url: "https://additional.example.com/mcp" }, + }); + const contributedServers = h.launches.at(-1)!.config.mcpServers; + await h.install( + "zz-remove", + `export default function contribute(server) { + server.before("agent.session_open", ({ request }) => ({ ...request, mcpServers: {} })); + return () => {}; +}`, + ); + await sendAndFinish(h, a.id, "after removal"); + expect(h.launches.at(-1)!.config.mcpServers).toEqual(contributedServers); + expect(a.config.mcpServers).toBeUndefined(); + } finally { + await h.close(); + } +}, 60_000); + +test("session-open MCP configs are validated before a provider launches", async () => { + const h = await setup( + true, + mcpSource.replace(JSON.stringify(companyServer), '{ type: "http", url: 42 }'), + ); + try { + await expect(h.create()).rejects.toThrow(/Plugin tools-test.*before agent.session_open/s); + expect(h.launches).toHaveLength(0); + } finally { + await h.close(); + } +}, 60_000); diff --git a/packages/server/src/server/plugins/lifecycle/handlers.test.ts b/packages/server/src/server/plugins/lifecycle/handlers.test.ts index bafd1f9b94..fe86f6a754 100644 --- a/packages/server/src/server/plugins/lifecycle/handlers.test.ts +++ b/packages/server/src/server/plugins/lifecycle/handlers.test.ts @@ -96,6 +96,7 @@ test("session-open hooks reject changes to session identity instead of silently title: null, labels: {}, tools: [], + mcpServers: {}, }, paseo, ), @@ -120,12 +121,13 @@ test.each([{ title: "Changed" }, { labels: { changed: "true" } }])( title: "Original", labels: {}, tools: [], + mcpServers: {}, env: {}, reason: "create", purpose: "interactive", }, paseo, ), - ).rejects.toThrow("agent.session_open hooks can only change env and tools"); + ).rejects.toThrow("agent.session_open hooks can only change env, tools, and mcpServers"); }, ); diff --git a/packages/server/src/server/plugins/lifecycle/index.ts b/packages/server/src/server/plugins/lifecycle/index.ts index 2b379eb7f8..c43e113e38 100644 --- a/packages/server/src/server/plugins/lifecycle/index.ts +++ b/packages/server/src/server/plugins/lifecycle/index.ts @@ -27,6 +27,11 @@ export type PluginWireBeforeRequests = Omit }; +}; + export const lifecycleEventNames = [ "agent.created", "agent.closed", @@ -54,6 +59,7 @@ const beforeSchemas = { labels: z.record(z.string(), z.string()), tools: z.array(agentToolMetadataSchema), env: z.record(z.string(), z.string()), + mcpServers: CreateAgentRequestMessageSchema.shape.config.shape.mcpServers.unwrap(), }) .strict(), "workspace.create": WorkspaceCreateRequestSchema.omit({ type: true, requestId: true }).strict(), @@ -80,7 +86,7 @@ export interface PluginLifecycle { before( name: Name, request: PluginWireBeforeRequests[Name], - ): Promise; + ): Promise; } export function validateBeforeRequest( @@ -176,7 +182,7 @@ export function validateBeforeResult( name: Name, input: PluginWireBeforeRequests[Name], - ): Promise { + ): Promise { let request = validateBeforeRequest(name, input); const plugins = [...this.plugins.values()].sort((left, right) => { return left.id.localeCompare(right.id); }); const attached: AttachedAgentTool[] = []; + const mcpServers: SessionOpenWireRequest["mcpServers"] = {}; + const mcpServerOwners: Record = {}; for (const loaded of plugins) { if (!loaded.hooks.before.includes(name)) { continue; @@ -551,11 +553,14 @@ export class PluginRuntime { requestId: randomUUID(), kind: "before", name, - input: name === "agent.session_open" ? { ...request, tools: [] } : request, + input: + name === "agent.session_open" ? { ...request, tools: [], mcpServers: {} } : request, }); request = validateBeforeResult(name, request, output); if (name === "agent.session_open") { - this.collectAgentTools(attached, loaded, (request as SessionOpenWireRequest).tools); + const opened = request as SessionOpenWireRequest; + this.collectMcpServers(mcpServers, mcpServerOwners, loaded, opened.mcpServers); + this.collectAgentTools(attached, loaded, opened.tools); } } catch (error) { if (name === "agent.session_open") @@ -565,7 +570,14 @@ export class PluginRuntime { }); } } - if (name === "agent.session_open") (request as SessionOpenWireRequest).tools = attached; + if (name === "agent.session_open") { + return { + ...request, + tools: attached, + mcpServers, + mcpServerOwners, + } as PluginBeforeResults[Name]; + } return request; } @@ -587,6 +599,23 @@ export class PluginRuntime { return output; } + private collectMcpServers( + servers: SessionOpenWireRequest["mcpServers"], + owners: Record, + loaded: LoadedPlugin, + contributions: SessionOpenWireRequest["mcpServers"], + ): void { + for (const [name, server] of Object.entries(contributions)) { + if (Object.hasOwn(servers, name)) { + throw new Error( + `MCP server ${name} from plugin ${loaded.id} collides with plugin ${owners[name]}`, + ); + } + servers[name] = server; + owners[name] = loaded.id; + } + } + private collectAgentTools( attached: AttachedAgentTool[], loaded: LoadedPlugin, diff --git a/plugin-examples/agent-configuration/README.md b/plugin-examples/agent-configuration/README.md index 189afe6cfd..2a34c1222d 100644 --- a/plugin-examples/agent-configuration/README.md +++ b/plugin-examples/agent-configuration/README.md @@ -1,14 +1,19 @@ # Agent configuration -Changes new Codex agents through `server.before("agent.create", ...)`: +Sets saved Codex options through `server.before("agent.create", ...)`: - Sets `config.providerOptions.sandbox_mode` to `workspace-write`. - Sets `config.providerOptions.approval_policy` to `on-request`. -- Adds the `company` server to `config.mcpServers`. -- Preserves other configuration, provider options, MCP servers, and environment overrides. +- Preserves other configuration and provider options. + +Adds the `company` MCP server to Codex launches through +`server.before("agent.session_open", ...)`. The server is never saved in the agent's configuration; +existing saved MCP servers are preserved. Existing agents receive the server through the +[session reopen behavior](../../public-docs/plugins/reference.md#attach-tools-to-agents). Replace `https://tools.example.com/mcp` in `index.server.ts` with your MCP server URL before using -this example. The URL is a placeholder. The `company` entry replaces an existing server with that name. +this example. A `company` name collision with a saved server or another +plugin fails the session open and names both sources. Install on a daemon with plugins enabled: @@ -16,11 +21,13 @@ Install on a daemon with plugins enabled: paseo plugin install /absolute/path/to/plugin-examples/agent-configuration ``` -The callback receives the request after earlier plugins have transformed it. The nested spreads -preserve their settings; the explicit values replace only the named fields. Paseo validates and saves -the resulting configuration before starting the agent. Existing agents are unchanged. +Each session-open callback receives only this plugin's MCP servers. The nested spreads preserve +entries added by this plugin's earlier callbacks. The create callback receives configuration after +earlier plugins have transformed it; its explicit Codex options replace the named fields in the +saved configuration of new agents and remain after this plugin is disabled. -See the [lifecycle reference](../../public-docs/plugins/reference.md#lifecycle-hooks) for ordering -and callback shapes. [Lifecycle actions](../lifecycle-actions) demonstrates provider switching and -environment injection. Its provider-switch callback clears provider options when changing Codex to -Claude, so use these examples separately when trying the Codex-specific settings. +See [Inject MCP servers](../../public-docs/plugins/reference.md#inject-mcp-servers) for choosing +between saved configuration and plugin-owned servers. [Lifecycle actions](../lifecycle-actions) +demonstrates provider switching and environment injection. Its provider-switch callback clears +provider options when changing Codex to Claude, so use these examples separately when trying the +Codex-specific settings. diff --git a/plugin-examples/agent-configuration/index.server.ts b/plugin-examples/agent-configuration/index.server.ts index 1f86e63a67..bc5abc9e3d 100644 --- a/plugin-examples/agent-configuration/index.server.ts +++ b/plugin-examples/agent-configuration/index.server.ts @@ -15,12 +15,22 @@ export default function contribute(server: PluginServerContext) { sandbox_mode: "workspace-write", approval_policy: "on-request", }, - mcpServers: { - ...request.config.mcpServers, - company: { - type: "http", - url: "https://tools.example.com/mcp", - }, + }, + }; + }); + + server.before("agent.session_open", ({ request }) => { + if (request.provider !== "codex") { + return; + } + + return { + ...request, + mcpServers: { + ...request.mcpServers, + company: { + type: "http", + url: "https://tools.example.com/mcp", }, }, }; diff --git a/plugin-examples/agent-configuration/paseo-plugin.json b/plugin-examples/agent-configuration/paseo-plugin.json index 1a049eda62..019394b8f7 100644 --- a/plugin-examples/agent-configuration/paseo-plugin.json +++ b/plugin-examples/agent-configuration/paseo-plugin.json @@ -1,6 +1,6 @@ { "id": "agent-configuration", "requirements": { - "paseo": ">=0.8.0" + "paseo": ">=0.13.2" } } diff --git a/public-docs/plugins/reference.md b/public-docs/plugins/reference.md index 69608a83a7..439892edb8 100644 --- a/public-docs/plugins/reference.md +++ b/public-docs/plugins/reference.md @@ -653,9 +653,14 @@ export default function contribute(server: PluginServerContext) { Hooks run on the daemon while the plugin is enabled, even with no app connected. -### Change configuration and inject an MCP server +`agent.create` edits the agent's saved configuration. Changes to `config` are persisted and remain +after the plugin is disabled or removed. `agent.session_open` contributes launch-only `env`, `tools`, +and `mcpServers`, re-derived on every create, resume, refresh, and import, following the plugin's +lifecycle without being saved in the agent record. -Add this callback inside `contribute(server)`. Replace the placeholder URL with your MCP endpoint. +### Change saved configuration + +Add this callback inside `contribute(server)` to set the saved options for new Codex agents: ```ts server.before("agent.create", ({ request }) => { @@ -672,27 +677,50 @@ server.before("agent.create", ({ request }) => { sandbox_mode: "workspace-write", approval_policy: "on-request", }, - mcpServers: { - ...request.config.mcpServers, - company: { - type: "http", - url: "https://tools.example.com/mcp", - }, - }, }, }; }); ``` -| Input | Result | -| ------------------------------------------- | ----------------------------- | -| `providerOptions.sandbox_mode: "read-only"` | `"workspace-write"` | -| `providerOptions.web_search: "disabled"` | Preserved by the spread | -| Existing `mcpServers.search` | Preserved by the spread | -| Existing `mcpServers.company` | Replaced with the entry above | +| Input | Result | +| ------------------------------------------- | ----------------------- | +| `providerOptions.sandbox_mode: "read-only"` | `"workspace-write"` | +| `providerOptions.web_search: "disabled"` | Preserved by the spread | -The selected provider validates `providerOptions` and must support the configured MCP servers. -Explicit Codex sandbox and approval options override its mode presets. +The selected provider validates `providerOptions`. Explicit Codex sandbox and approval options +override its mode presets. + +### Inject MCP servers + +Use `agent.create.config.mcpServers` when the server should become part of the agent's saved +configuration. For a plugin-owned server, add this callback inside `contribute(server)`, replacing +the placeholder URL with your MCP endpoint: + +```ts +server.before("agent.session_open", ({ request }) => { + if (request.provider !== "codex") return; + + return { + ...request, + mcpServers: { + ...request.mcpServers, + company: { type: "http", url: "https://tools.example.com/mcp" }, + }, + }; +}); +``` + +`request.mcpServers` uses the same server configurations as `AgentSessionConfig.mcpServers`. +The map starts empty for each plugin and accumulates across that plugin's own callbacks. It never +contains the agent's saved servers or another plugin's servers. Replace the map to add, replace, +or remove this plugin's entries; returning `undefined` preserves it. Paseo merges the plugins' +final maps in plugin-ID order. + +A name colliding with a saved server, Paseo's internal `paseo` server, or another plugin's server +fails the session open and names the server and both sources. A provider without MCP support fails +with `does not support MCP servers`, naming the plugin. Opens with `purpose: "history"` ignore +these servers. Install, disable, and reload changes reach existing agents through the +[session reopen behavior](#attach-tools-to-agents). ### Inject environment variables on every session opening @@ -708,8 +736,8 @@ server.before("agent.session_open", ({ request }) => { }); ``` -This runs on create, resume, refresh, and import. To inject only on creation, set `env` in an -`agent.create` callback instead. +Session-open overrides are re-derived on every open. `agent.create.env` applies only to the +initial launch and is not saved in the agent's configuration. ### Attach tools to agents @@ -992,11 +1020,11 @@ type PluginTurnOutcome = ### Before hooks -| Name | Request fields | Editable | -| -------------------- | ---------------------------------------------------------------------------------------------------------------- | --------------------------------------- | -| `agent.create` | `config`, optional `env` | Public agent config except `cwd`; `env` | -| `agent.session_open` | `agentId`, `workspaceId`, `provider`, `cwd`, read-only `title` and `labels`, `reason`, `purpose`, `env`, `tools` | `env` and `tools` | -| `workspace.create` | `source`, optional `title`, `firstAgentContext` | Entire explicit creation request | +| Name | Request fields | Editable | +| -------------------- | ------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------- | +| `agent.create` | `config`, optional `env` | Public agent config except `cwd`; `env` | +| `agent.session_open` | `agentId`, `workspaceId`, `provider`, `cwd`, read-only `title` and `labels`, `reason`, `purpose`, `env`, `tools`, `mcpServers` | Launch-only `env`, `tools`, `mcpServers` | +| `workspace.create` | `source`, optional `title`, `firstAgentContext` | Entire explicit creation request | **`agent.create.config`** uses `AgentSessionConfig`: @@ -1020,6 +1048,7 @@ type PluginTurnOutcome = "title": "Workspace notes", "labels": { "notes/enabled": "true" }, "tools": [], + "mcpServers": {}, "reason": "resume", "purpose": "interactive", "env": { "COMPANY_ENV": "development" } @@ -1032,6 +1061,7 @@ type PluginTurnOutcome = | `title` | Read-only string or `null`; creation title on create, stored title on resume. | | `labels` | Read-only string map; creation labels on create, stored labels on resume. | | `tools` | Editable `AgentToolDefinition[]`, local to this plugin. See [Attach tools to agents](#attach-tools-to-agents). | +| `mcpServers` | Editable launch-only server map, local to this plugin. See [Inject MCP servers](#inject-mcp-servers). | | `reason` | `create`, `resume`, `refresh`, `import` | | `purpose` | `interactive`, `history` | | `env` | Launch override map; excludes the daemon's inherited environment. Replace the map to add, replace, or remove overrides. | @@ -1043,7 +1073,7 @@ Creation request → agent.create hooks (plugin-ID order; registration order within each plugin) → resolve defaults and validate provider configuration → derive launch configuration with Paseo runtime tools and daemon prompt - → agent.session_open hooks (same ordering; env and plugin-local tools) + → agent.session_open hooks (same ordering; env and plugin-local tools and MCP servers) → set PASEO_AGENT_ID and PASEO_AGENT_CWD → open provider session and save agent configuration ``` @@ -1055,8 +1085,9 @@ Creation request | `undefined` | Unchanged request | | Throws or returns invalid data | Operation fails; later callbacks do not run | -No automatic deep merge. Later callbacks can overwrite earlier values. Agent configuration is -saved; environment overrides are not persisted with it. +There is no automatic deep merge. `env` accumulates across plugins; `tools` and `mcpServers` +accumulate only across callbacks within the same plugin. Returning a replacement map or array +replaces that scope's prior value. ### Context and cleanup diff --git a/public-docs/plugins/reference.zh-CN.md b/public-docs/plugins/reference.zh-CN.md index 3c84f8cc0c..4fc7380ee3 100644 --- a/public-docs/plugins/reference.zh-CN.md +++ b/public-docs/plugins/reference.zh-CN.md @@ -529,9 +529,12 @@ export default function contribute(server: PluginServerContext) { 只要插件处于启用状态,钩子就会在 daemon 上运行,即使没有应用连接。 -### 修改配置并注入 MCP 服务器 {#change-configuration-and-inject-an-mcp-server} +`agent.create` 修改 Agent 的已保存配置。对 `config` 的修改会被持久化,在插件停用或移除后仍然保留。 +`agent.session_open` 提供仅用于启动的 `env`、`tools` 和 `mcpServers`;每次创建、恢复、刷新和导入时都会重新计算,随插件的生命周期变化,不会写入 Agent 记录。 -在 `contribute(server)` 中添加这个回调。把占位 URL 替换为你的 MCP 端点。 +### 修改已保存的配置 {#change-saved-configuration} + +在 `contribute(server)` 中添加这个回调,为新的 Codex Agent 设置已保存的选项: ```ts server.before("agent.create", ({ request }) => { @@ -548,13 +551,6 @@ server.before("agent.create", ({ request }) => { sandbox_mode: "workspace-write", approval_policy: "on-request", }, - mcpServers: { - ...request.config.mcpServers, - company: { - type: "http", - url: "https://tools.example.com/mcp", - }, - }, }, }; }); @@ -564,10 +560,37 @@ server.before("agent.create", ({ request }) => { | ------------------------------------------- | ------------------- | | `providerOptions.sandbox_mode: "read-only"` | `"workspace-write"` | | `providerOptions.web_search: "disabled"` | 由展开运算保留 | -| 已有的 `mcpServers.search` | 由展开运算保留 | -| 已有的 `mcpServers.company` | 被替换为上面的条目 | -所选的 Provider 会校验 `providerOptions`,并且必须支持配置的 MCP 服务器。显式的 Codex 沙盒和批准选项会覆盖它的模式预设。 +所选的 Provider 会校验 `providerOptions`。显式的 Codex 沙盒和批准选项会覆盖它的模式预设。 + +### 注入 MCP 服务器 {#inject-mcp-servers} + +需要将服务器保存为 Agent 配置的一部分时,使用 `agent.create.config.mcpServers`。 +插件拥有的服务器使用下面的回调,在 `contribute(server)` 中添加,并把占位 URL 替换为你的 MCP 端点: + +```ts +server.before("agent.session_open", ({ request }) => { + if (request.provider !== "codex") return; + + return { + ...request, + mcpServers: { + ...request.mcpServers, + company: { type: "http", url: "https://tools.example.com/mcp" }, + }, + }; +}); +``` + +`request.mcpServers` 使用与 `AgentSessionConfig.mcpServers` 相同的服务器配置。 +每个插件的映射从空开始,只在该插件自己的回调之间累积,不包含 Agent 已保存的服务器或其他插件的服务器。 +替换映射即可添加、替换或移除本插件的条目;返回 `undefined` 会保持不变。 +Paseo 按插件 ID 顺序合并各插件的最终映射。 + +名称与已保存的服务器、Paseo 内部的 `paseo` 服务器或其他插件的服务器冲突时,会话打开失败,错误会指出服务器名称及双方来源。 +不支持 MCP 的 Provider 会报 `does not support MCP servers` 错误,并指出插件名称。 +`purpose: "history"` 的会话打开会忽略这些服务器。安装、停用和重新加载插件后,现有 Agent +通过[会话重新打开行为](#attach-tools-to-agents)获取变化。 ### 在每次打开会话时注入环境变量 {#inject-environment-variables-on-every-session-opening} @@ -583,7 +606,7 @@ server.before("agent.session_open", ({ request }) => { }); ``` -它会在创建、恢复、刷新和导入时运行。如果只想在创建时注入,请改为在 `agent.create` 回调中设置 `env`。 +会话打开时的环境变量覆盖项会在每次打开时重新计算。`agent.create.env` 只作用于首次启动,不会写入 Agent 的已保存配置。 ### 为 Agent 附加工具 {#attach-tools-to-agents} @@ -852,11 +875,11 @@ type PluginTurnOutcome = ### before 钩子 {#before-hooks} -| 名称 | 请求字段 | 可编辑 | -| -------------------- | ------------------------------------------------------------------------------------------------------------ | ----------------------------------- | -| `agent.create` | `config`,可选的 `env` | 除 `cwd` 外的公开 Agent 配置;`env` | -| `agent.session_open` | `agentId`, `workspaceId`, `provider`, `cwd`,只读的 `title` 和 `labels`,`reason`, `purpose`, `env`, `tools` | `env` 和 `tools` | -| `workspace.create` | `source`,可选的 `title`,`firstAgentContext` | 整个显式创建请求 | +| 名称 | 请求字段 | 可编辑 | +| -------------------- | -------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- | +| `agent.create` | `config`,可选的 `env` | 除 `cwd` 外的公开 Agent 配置;`env` | +| `agent.session_open` | `agentId`, `workspaceId`, `provider`, `cwd`,只读的 `title` 和 `labels`,`reason`, `purpose`, `env`, `tools`, `mcpServers` | 仅用于启动的 `env`、`tools`、`mcpServers` | +| `workspace.create` | `source`,可选的 `title`,`firstAgentContext` | 整个显式创建请求 | **`agent.create.config`** 使用 `AgentSessionConfig`: @@ -880,6 +903,7 @@ type PluginTurnOutcome = "title": "Workspace notes", "labels": { "notes/enabled": "true" }, "tools": [], + "mcpServers": {}, "reason": "resume", "purpose": "interactive", "env": { "COMPANY_ENV": "development" } @@ -892,6 +916,7 @@ type PluginTurnOutcome = | `title` | 只读字符串或 `null`;创建时使用创建请求的标题,恢复时使用已保存的标题。 | | `labels` | 只读的字符串映射;创建时使用创建请求的标签,恢复时使用已保存的标签。 | | `tools` | 可编辑的 `AgentToolDefinition[]`,仅包含此插件的工具。参阅[为 Agent 附加工具](#attach-tools-to-agents)。 | +| `mcpServers` | 可编辑的服务器映射,仅用于启动且仅包含本插件的条目。参阅[注入 MCP 服务器](#inject-mcp-servers)。 | | `reason` | `create`、`resume`、`refresh`、`import` | | `purpose` | `interactive`、`history` | | `env` | 启动覆盖映射;不包括 daemon 继承的环境变量。替换整个映射即可添加、替换或移除覆盖项。 | @@ -903,7 +928,7 @@ Creation request → agent.create hooks (plugin-ID order; registration order within each plugin) → resolve defaults and validate provider configuration → derive launch configuration with Paseo runtime tools and daemon prompt - → agent.session_open hooks (same ordering; env and plugin-local tools) + → agent.session_open hooks (same ordering; env and plugin-local tools and MCP servers) → set PASEO_AGENT_ID and PASEO_AGENT_CWD → open provider session and save agent configuration ``` @@ -915,7 +940,8 @@ Creation request | `undefined` | 未改变的请求 | | 抛出错误或返回无效数据 | 操作失败;后面的回调不会运行 | -没有自动的深度合并。后面的回调可以覆盖前面的值。Agent 配置会被保存;环境变量覆盖项不会随之持久化。 +没有自动的深度合并。`env` 在插件之间累积;`tools` 和 `mcpServers` 只在同一插件的回调之间累积。 +返回替换的映射或数组会替换该范围内之前的值。 ### context 与清理 {#context-and-cleanup} @@ -1187,7 +1213,7 @@ export function IssueActions({ theme }: PluginSurfaceProps) { ```tsx import { Markdown } from "@getpaseo/plugin/client/ui"; -{"## 审查\n\n检查**通过**。"}; +{"## Review\n\nThe checks **passed**."}; ``` `children` 是唯一的属性,必须为字符串。更新它会立即渲染新内容;空字符串不渲染任何内容。 diff --git a/skills/paseo-plugin/SKILL.md b/skills/paseo-plugin/SKILL.md index 028d869085..0a36b5b3eb 100644 --- a/skills/paseo-plugin/SKILL.md +++ b/skills/paseo-plugin/SKILL.md @@ -27,28 +27,29 @@ public docs; this skill indexes the references and examples. Pick the contribution that matches the request. Each row names the registration, when it fits, and where the full contract lives. Most plugins combine several: a slash command that calls an RPC, which appends a timeline row, which a renderer draws. -| Contribution | Registration | Use it when | Reference | -| ------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -| Screen and sidebar item | `addScreen` + `addSidebarHeaderItem`/`addSidebarFooterItem` | A full screen of plugin UI, or sidebar header or footer rows that open a screen or popover | reference.md → Screens and sidebar items | -| Workspace panel | `addWorkspacePanel` | UI that lives as a tab beside agents, terminals, files, and diffs; `locations: ["explorer"]` for the Explorer | reference.md → Workspace panels | -| File panel | `addFilePanel` | View or edit a matching file inside the file tab through its file handle | reference.md → File panels; `plugin-examples/pdf-panel`, `plugin-examples/markdown-panel` | -| Command Center item | `addCommandCenterItem` | A global, workspace, or agent action reachable from ⌘K | reference.md → Command Center items | -| Client slash command | `addSlashCommand` | A `/command args` in the composer that runs plugin code instead of prompting the agent | reference.md → Slash commands | -| Composer pill | `addComposerPill` | A per-agent button in the composer track bar next to Tasks and Subagents | reference.md → Composer pills | -| Timeline transformer | `addTimelineTransformer` + `addTimelineRenderer` | Replace, explode, or hide a built-in timeline item, including while it streams | reference.md → Timeline items; `plugin-examples/timeline-items`, `plugin-examples/inline-thinking` | -| Timeline row | `paseo.agents.ref(id).timeline.append(...)` | Push a plugin-owned row into an agent timeline from a server handler and update it later | reference.md → Append a timeline row from the daemon | -| Attachment source | `client.addAttachmentSource` + `server.handle` | Let the user attach a searchable external resource, such as an issue, to a prompt | reference.md → Add a composer attachment source; `plugin-examples/linear` | -| Theme | `addTheme` | A light or dark palette under Settings → Appearance | reference.md → Contribute a theme; `plugin-examples/catppuccin` | -| Plugin RPC | `defineRpc` + `server.handle` + `useRpc` | Daemon-side work that is not a normal Paseo operation: vendor APIs, credentials, local files | reference.md → Add plugin-specific backend behavior | -| Lifecycle events | `server.on` | Observe agent/workspace lifecycle, inspect ended turns, and answer permission requests | [Lifecycle hooks](https://paseo.sh/docs/plugins/reference.md#lifecycle-hooks) | -| Creation and launch hooks | `server.before` | Change agent config, provider options, MCP servers, environment, or workspace isolation before the operation | [Before hooks](https://paseo.sh/docs/plugins/reference.md#before-hooks) | -| Paseo SDK | `usePaseo()` / handler `{ paseo }` | Normal Paseo operations: workspaces, agents, providers, config | reference.md → Use the Paseo SDK | +| Contribution | Registration | Use it when | Reference | +| ------------------------- | ----------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| Screen and sidebar item | `addScreen` + `addSidebarHeaderItem`/`addSidebarFooterItem` | A full screen of plugin UI, or sidebar header or footer rows that open a screen or popover | reference.md → Screens and sidebar items | +| Workspace panel | `addWorkspacePanel` | UI that lives as a tab beside agents, terminals, files, and diffs; `locations: ["explorer"]` for the Explorer | reference.md → Workspace panels | +| File panel | `addFilePanel` | View or edit a matching file inside the file tab through its file handle | reference.md → File panels; `plugin-examples/pdf-panel`, `plugin-examples/markdown-panel` | +| Command Center item | `addCommandCenterItem` | A global, workspace, or agent action reachable from ⌘K | reference.md → Command Center items | +| Client slash command | `addSlashCommand` | A `/command args` in the composer that runs plugin code instead of prompting the agent | reference.md → Slash commands | +| Composer pill | `addComposerPill` | A per-agent button in the composer track bar next to Tasks and Subagents | reference.md → Composer pills | +| Timeline transformer | `addTimelineTransformer` + `addTimelineRenderer` | Replace, explode, or hide a built-in timeline item, including while it streams | reference.md → Timeline items; `plugin-examples/timeline-items`, `plugin-examples/inline-thinking` | +| Timeline row | `paseo.agents.ref(id).timeline.append(...)` | Push a plugin-owned row into an agent timeline from a server handler and update it later | reference.md → Append a timeline row from the daemon | +| Attachment source | `client.addAttachmentSource` + `server.handle` | Let the user attach a searchable external resource, such as an issue, to a prompt | reference.md → Add a composer attachment source; `plugin-examples/linear` | +| Theme | `addTheme` | A light or dark palette under Settings → Appearance | reference.md → Contribute a theme; `plugin-examples/catppuccin` | +| Plugin RPC | `defineRpc` + `server.handle` + `useRpc` | Daemon-side work that is not a normal Paseo operation: vendor APIs, credentials, local files | reference.md → Add plugin-specific backend behavior | +| Lifecycle events | `server.on` | Observe agent/workspace lifecycle, inspect ended turns, and answer permission requests | [Lifecycle hooks](https://paseo.sh/docs/plugins/reference.md#lifecycle-hooks) | +| Creation and launch hooks | `server.before` | `agent.create` edits saved config; `agent.session_open` contributes launch-only `env`, `tools`, `mcpServers` on every open; `workspace.create` chooses isolation | [Before hooks](https://paseo.sh/docs/plugins/reference.md#before-hooks) | +| Paseo SDK | `usePaseo()` / handler `{ paseo }` | Normal Paseo operations: workspaces, agents, providers, config | reference.md → Use the Paseo SDK | -| Lifecycle task | Example | -| ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | -| Log all eleven hooks | [lifecycle-logger](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-logger) | -| Follow-ups, permissions, environment, provider switching, worktrees | [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | -| Inject MCP servers and change Codex sandbox/approval options | [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | +| Lifecycle task | Example | +| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | +| Log all eleven hooks | [lifecycle-logger](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-logger) | +| Follow-ups, permissions, environment, provider switching, worktrees | [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | +| Inject launch-only MCP servers and save Codex sandbox/approval options | [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | +| Attach a tool to selected agents | [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | ## Create the project @@ -377,6 +378,35 @@ Inputs and outputs are validated on both sides. Backend handlers receive the sam Use TanStack Query for async request state, caching, and mutations. +### Contribute tools and MCP servers at session open + +Use `before("agent.session_open")` for per-agent tools and plugin-owned MCP servers. Add this +callback inside `contribute(server)`: + +```ts +server.before("agent.session_open", ({ request }) => { + if (request.provider !== "codex") return; + return { + ...request, + mcpServers: { + ...request.mcpServers, + company: { type: "http", url: "https://tools.example.com/mcp" }, + }, + }; +}); +``` + +`tools` and `mcpServers` start empty for each plugin and accumulate across its own callbacks. +They are launch-only. Use `agent.create` to edit configuration that should be saved with the agent. +See [Attach tools to agents](https://paseo.sh/docs/plugins/reference.md#attach-tools-to-agents) +for `defineAgentTool` and targeting, and +[Inject MCP servers](https://paseo.sh/docs/plugins/reference.md#inject-mcp-servers) for server configuration and collisions. + +Starting, stopping, or reloading a plugin with a session-open hook marks open agent sessions stale. +Each reopens before its next idle prompt without interrupting a running turn. +`await paseo.agents.ref(id).reload()` applies changes immediately and interrupts a running turn; +`refresh()` only reads the current snapshot. + ### Debug daemon-side behavior Backend contributions can use normal Node logging. `console.log()` writes to the plugin's stdout; From ef58ace424089c220b6d42bd618234a2159e3db3 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Tue, 27 Oct 2026 15:49:42 +0700 Subject: [PATCH 055/173] Fix history compatibility and turn presentation regressions (#8010) * fix(client): preserve history loading on older hosts Whole-turn paging is optional, but requiring its capability blocked existing history reads before any request was sent. Negotiate the paging enhancement at the client boundary while preserving item-based requests for older daemons. * fix(app): preserve row ownership during late turn updates Late lifecycle events retagged the newest row even when they updated an earlier call, causing the next update to append a duplicate tool ID. Assign turn membership only to rows written by the event before finalizing unrelated reasoning. Co-authored-by: luke * fix(app): preserve reasoning continuity and turn expansion controls * fix(app): hide reasoning inside collapsed turns --------- Co-authored-by: luke --- docs/protocol-compatibility.md | 4 +- docs/timeline-sync.md | 9 +- .../owned-subscriptions-old-daemon.spec.ts | 22 +-- .../app/e2e/browser/turn-collapse.spec.ts | 127 +++++++++++++++++- .../app/src/agent-stream/presentation.test.ts | 2 +- packages/app/src/agent-stream/presentation.ts | 1 - .../src/agent-stream/strategy-web.test.tsx | 75 ++++++++++- .../src/agent-stream/turn-collapse/model.ts | 15 +-- packages/app/src/agent-stream/view.tsx | 17 +-- .../app/src/components/user-message/index.tsx | 14 +- .../timeline/session-stream-reducers.test.ts | 60 +++++++++ .../src/timeline/session-stream-reducers.ts | 12 +- packages/app/src/types/stream.test.ts | 76 +++++++++++ packages/app/src/types/stream.ts | 88 ++++++------ packages/client/src/daemon-client.test.ts | 76 ++++++++++- packages/client/src/daemon-client.ts | 11 +- 16 files changed, 492 insertions(+), 117 deletions(-) diff --git a/docs/protocol-compatibility.md b/docs/protocol-compatibility.md index e5ba1db2a3..f7244e67ba 100644 --- a/docs/protocol-compatibility.md +++ b/docs/protocol-compatibility.md @@ -2,7 +2,7 @@ The app and the daemon are separate products that ship separately. A user updates the app from an app store or a desktop auto-update; they update the daemon when they feel like it. Every combination happens in the wild: new app against an old daemon, old app against a new daemon, and both sides months apart. -In development both sides are always the same version, which is why this is the constraint contributors miss most often. +Development can have the same version drift: an app reload picks up new code while a long-running daemon keeps its loaded version. Check the connected daemon version when diagnosing behavior that crosses this boundary. Two contracts follow from it. @@ -38,7 +38,7 @@ The app checks for the capability and either runs the feature or tells the user - **No defensive branches spread through the feature.** Detection happens in one place, and everything downstream reads a clean shape. - Capability flags live in `features` on the `server_info` message (`packages/protocol/src/messages.ts`, the `server_info` schema). -Existing functionality keeps working across versions because of the protocol contract. Gating a new feature never substitutes for that. +Existing functionality keeps working across versions. Never gate an established request on a new enhancement: negotiate the optional enhancement at the client boundary and preserve the existing request for older hosts. Whole-turn pagination can require a capability; reading conversation history cannot. ## Client capability ownership diff --git a/docs/timeline-sync.md b/docs/timeline-sync.md index 0dd2c2093f..812718be58 100644 --- a/docs/timeline-sync.md +++ b/docs/timeline-sync.md @@ -50,10 +50,11 @@ all currently available rows of an active run. There is no per-turn cap: a large exceed the target. Local history mounting uses the same boundaries so revealing older rows does not change the collapse state of a turn already displayed. -`wholeTurns` is optional for existing SDK callers. The app requires -`features.wholeTurnTimeline` once at the client fetch boundary; unsupported hosts receive an -update-host error. Forward catch-up stays incremental, but its reset snapshot honors the -whole-turn request. Source coverage still includes interleaved tool updates. +`wholeTurns` is a preference negotiated once at the client fetch boundary. Hosts advertising +`features.wholeTurnTimeline` receive it; other hosts receive the existing item-based request. +Reading history remains available on older hosts, whose pages can still split turns. Forward +catch-up stays incremental, but its reset snapshot honors a supported whole-turn request. +Source coverage still includes interleaved tool updates. Canonical IDs define runs. With missing IDs, human prompts, heartbeats and typed received agent messages each start a fallback turn. This deterministic fallback is shared by paging diff --git a/packages/app/e2e/browser/owned-subscriptions-old-daemon.spec.ts b/packages/app/e2e/browser/owned-subscriptions-old-daemon.spec.ts index 4b49d8105e..1fdef794a0 100644 --- a/packages/app/e2e/browser/owned-subscriptions-old-daemon.spec.ts +++ b/packages/app/e2e/browser/owned-subscriptions-old-daemon.spec.ts @@ -10,9 +10,12 @@ import { buildCreateAgentPreferences, buildSeededHost } from "../support/helpers import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon"; import type { MockAgentWorkspace } from "../support/helpers/mock-agent"; import { seedWorkspace } from "../support/helpers/seed-client"; -import { openAgentTimeline } from "../support/helpers/timeline-pagination"; +import { + openAgentTimeline, + expectTimelinePromptVisible, +} from "../support/helpers/timeline-pagination"; -test("requires a host update for whole-turn history while retaining old-daemon connections and terminals", async ({ +test("loads history across browser reconnection while retaining old-daemon connections and terminals", async ({ page, }) => { test.setTimeout(120_000); @@ -70,17 +73,14 @@ test("requires a host update for whole-turn history while retaining old-daemon c ); await openAgentTimeline(page, agent, serverId); - const updateMessage = page.getByText("Update the host to load complete conversation turns.", { - exact: true, - }); - await expect(updateMessage).toBeVisible(); + await expectTimelinePromptVisible(page, "emit 1 coalesced agent stream updates"); expect(observationSockets.size).toBe(1); - await test.step("retain one directory observation after reconnecting the old daemon", async () => { - await daemon.restart(); - await expect.poll(() => observationSockets.size, { timeout: 30_000 }).toBe(2); - await expect(updateMessage).toBeVisible(); - await agent.client.connect(); + await test.step("reconnect the browser and reload the old daemon history", async () => { + observationSockets.clear(); + await page.reload(); + await expectTimelinePromptVisible(page, "emit 1 coalesced agent stream updates"); + await expect.poll(() => observationSockets.size).toBe(1); }); await test.step("open a terminal and receive its output", async () => { diff --git a/packages/app/e2e/browser/turn-collapse.spec.ts b/packages/app/e2e/browser/turn-collapse.spec.ts index bef85080cf..c170386266 100644 --- a/packages/app/e2e/browser/turn-collapse.spec.ts +++ b/packages/app/e2e/browser/turn-collapse.spec.ts @@ -1,13 +1,29 @@ +import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; +import path from "node:path"; import { holdOlderHistoryPages, userScrollsTimelineToHistoryStart, } from "../support/helpers/timeline-pagination"; import { getActiveTabTestId } from "../support/helpers/launcher"; -import type { Page } from "@playwright/test"; +import type { Page, Locator } from "@playwright/test"; import { test, expect } from "../support/fixtures"; import { expectComposerVisible } from "../support/helpers/composer"; import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent"; +test.use({ + e2eDaemonConfig: { + version: 1, + agents: { + providers: { + codex: { + enabled: true, + command: [process.execPath, path.resolve("e2e/fixtures/catalog-codex.mjs")], + }, + }, + }, + }, +}); + type ChatDisplay = "full" | "collapseToolCalls" | "collapseTurns"; async function useChatDisplay(page: Page, chatDisplay: ChatDisplay): Promise { @@ -59,6 +75,21 @@ async function groupedToolsInsideLatestTurn(page: Page): Promise { }); } +async function expectCompactMessageToggle(prompt: Locator, label: string) { + const button = prompt.getByRole("button", { name: label, exact: true }); + const text = prompt.getByText(label, { exact: true }); + await expect + .poll( + async () => { + const control = (await button.boundingBox())!; + const glyphs = (await text.boundingBox())!; + return control.height - glyphs.height; + }, + { message: "The inline toggle adds no vertical space beyond its text" }, + ) + .toBe(0); +} + async function expandAndCollapseLongPrompt(page: Page) { const prompt = page.getByTestId("user-message").last(); const before = await prompt.boundingBox(); @@ -67,6 +98,7 @@ async function expandAndCollapseLongPrompt(page: Page) { await expect .poll(async () => (await prompt.getByText("Show more", { exact: true }).boundingBox())!.x) .toBe(messageLeft); + await expectCompactMessageToggle(prompt, "Show more"); await prompt.getByRole("button", { name: "Show more", exact: true }).click(); await expect(prompt.getByRole("button", { name: "Show less", exact: true })).toBeVisible(); await expect @@ -75,6 +107,7 @@ async function expandAndCollapseLongPrompt(page: Page) { await expect .poll(async () => (await prompt.boundingBox())?.height ?? 0) .toBeGreaterThan(before!.height); + await expectCompactMessageToggle(prompt, "Show less"); await prompt.getByRole("button", { name: "Show less", exact: true }).click(); await expect.poll(async () => (await prompt.boundingBox())?.height ?? 0).toBe(before!.height); await prompt.scrollIntoViewIfNeeded(); @@ -128,18 +161,21 @@ test.describe("Turn collapse", () => { }); test("received messages show their sender and open that agent", async ({ page }) => { + await page.addInitScript(() => + localStorage.setItem("@paseo:app-settings", JSON.stringify({ theme: "dark" })), + ); const recipient = await seedMockAgentWorkspace({ repoPrefix: "sender-attribution-", title: "Implementation", }); try { const sender = await recipient.client.createAgent({ - provider: "mock", + provider: "codex", cwd: recipient.cwd, workspaceId: recipient.workspaceId, title: "Reviewer", - model: "e2e-fast-stream", - modeId: "load-test", + model: "gpt-6.1-sol", + modeId: "full-access", }); await recipient.client.sendAgentMessage( recipient.agentId, @@ -153,6 +189,10 @@ test("received messages show their sender and open that agent", async ({ page }) await expect(page.getByTestId("user-message").filter({ has: attribution })).toContainText( "I reviewed the turn-grouping changes.", ); + const labelColor = await attribution + .getByText("Sent by Reviewer", { exact: true }) + .evaluate((element) => getComputedStyle(element).color); + await expect(attribution.locator("svg")).toHaveCSS("fill", labelColor); await attribution.scrollIntoViewIfNeeded(); await page.screenshot({ path: "/tmp/sender-attribution.png" }); await attribution.click(); @@ -237,7 +277,7 @@ async function useThinkingDisplay( } for (const autoExpandReasoning of [false, true]) { - test(`reasoning follows Expand thinking (${autoExpandReasoning}) and opens fully with its turn`, async ({ + test(`reasoning follows Expand thinking (${autoExpandReasoning}) when opening its turn`, async ({ page, }) => { await page.setViewportSize({ width: 1280, height: 1000 }); @@ -261,15 +301,32 @@ for (const autoExpandReasoning of [false, true]) { await expectComposerVisible(page); const summary = page.getByTestId("turn-summary").last().getByRole("button"); await expect(summary).toBeVisible(); + await expect(reasoning).toHaveCount(0); await summary.click(); - await expect(reasoning).toBeVisible(); + await expect(reasoning).toHaveCount(autoExpandReasoning ? 1 : 0); await expect.poll(() => groupedToolsInsideLatestTurn(page)).toEqual([]); + await openOneToolOutput(page); + await summary.click(); + await expect(reasoning).toHaveCount(0); } finally { await agent.cleanup(); } }); } +async function openOneToolOutput(page: Page) { + const output = page.getByText(/\[burst\] tick 1 userIsAtBottom=true/).filter({ visible: true }); + await expect(output).toHaveCount(0); + const command = page + .getByTestId("tool-call-badge") + .filter({ hasText: "node scripts/simulate-stream-burst.mjs" }) + .first(); + await command.getByRole("button").first().click(); + await expect(output.first()).toBeVisible(); + await command.getByRole("button").first().click(); + await expect(output).toHaveCount(0); +} + async function expectThinkingPresentation(page: Page, autoExpandReasoning: boolean) { const reasoning = page .getByText(/Need to find the scroll container, the layout effect/) @@ -296,3 +353,61 @@ async function switchToCollapsedTurns(page: Page) { }); await page.reload(); } + +test("a scheduled heartbeat opens a separate turn without reopening the previous response", async ({ + page, +}) => { + test.setTimeout(90_000); + await useChatDisplay(page, "collapseTurns"); + const agent = await seedMockAgentWorkspace({ + repoPrefix: "heartbeat-turn-", + title: "Heartbeat turns", + model: "ten-second-stream", + initialPrompt: "Inspect the scroll container", + }); + const schedules = agent.client as unknown as Pick< + DaemonClient, + "scheduleCreate" | "scheduleRunOnce" | "scheduleDelete" + >; + let scheduleId: string | undefined; + try { + await agent.client.waitForFinish(agent.agentId, 30_000); + await openAgentRoute(page, agent); + await expectComposerVisible(page); + const summaries = page.getByTestId("turn-summary"); + await expect(summaries).toHaveCount(1); + const previousSummary = await summaries.first().innerText(); + const previousReplyId = await page + .getByTestId("assistant-message") + .last() + .evaluate((element) => element.closest("[data-message-id]")!.getAttribute("data-message-id")); + const created = await schedules.scheduleCreate({ + name: "Check the completed work", + prompt: "Inspect the scroll container again", + cadence: { type: "cron", expression: "0 0 1 1 *" }, + target: { type: "self", agentId: agent.agentId }, + runOnCreate: false, + }); + expect(created.error).toBeNull(); + scheduleId = created.schedule!.id; + const fired = await schedules.scheduleRunOnce({ id: scheduleId }); + expect(fired.error).toBeNull(); + await expect( + page.getByTestId("tool-call-badge").filter({ hasText: /^Heartbeat/ }), + ).toBeVisible(); + await expect(summaries.first()).toHaveText(previousSummary); + const previousReply = page + .locator(`[data-message-id="${previousReplyId}"]`) + .getByTestId("assistant-message"); + await expect(previousReply).toBeVisible(); + await expect(previousReply).toContainText("(end of synthetic stream)"); + await agent.client.waitForFinish(agent.agentId, 30_000); + await expect(summaries).toHaveCount(2); + await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(0); + await expect(page.getByRole("button", { name: /^Worked for/ })).toHaveCount(2); + await page.screenshot({ path: "/tmp/heartbeat-turn-footer.png" }); + } finally { + if (scheduleId) await schedules.scheduleDelete({ id: scheduleId }); + await agent.cleanup(); + } +}); diff --git a/packages/app/src/agent-stream/presentation.test.ts b/packages/app/src/agent-stream/presentation.test.ts index bba7267a5d..0cfc793228 100644 --- a/packages/app/src/agent-stream/presentation.test.ts +++ b/packages/app/src/agent-stream/presentation.test.ts @@ -707,7 +707,7 @@ it.each([false, true])( }; const present = createStreamPresentation(); const closed = present(input); - expect(closed.tail.some((item) => item.id === "thought")).toBe(autoExpandReasoning); + expect(closed.tail.some((item) => item.id === "thought")).toBe(false); const opened = present({ ...input, expandedTurnHostIds: new Set(["prompt"]) }); expect(opened.tail).toEqual(tail); expect(opened.turns.nestedItemIds.has("thought")).toBe(true); diff --git a/packages/app/src/agent-stream/presentation.ts b/packages/app/src/agent-stream/presentation.ts index ad5d362d38..5138cc1647 100644 --- a/packages/app/src/agent-stream/presentation.ts +++ b/packages/app/src/agent-stream/presentation.ts @@ -111,7 +111,6 @@ export function createStreamPresentation() { ) { collapsed = collapseTurns({ tail: projection.tail, - autoExpandReasoning: input.autoExpandReasoning, isLatestTurnOpen, expandedHostIds: input.expandedTurnHostIds, getGroupedCalls: (itemId) => projection.groupsByHostId.get(itemId)?.run.calls, diff --git a/packages/app/src/agent-stream/strategy-web.test.tsx b/packages/app/src/agent-stream/strategy-web.test.tsx index 1f61d0a14c..5ad0be03c2 100644 --- a/packages/app/src/agent-stream/strategy-web.test.tsx +++ b/packages/app/src/agent-stream/strategy-web.test.tsx @@ -7,7 +7,7 @@ import { act } from "react"; import { createRoot, type Root } from "react-dom/client"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { RetainedPanelActivity } from "@/components/retained-panel"; -import type { StreamItem } from "@/types/stream"; +import { reduceStreamUpdate, type StreamItem } from "@/types/stream"; import type { StreamRenderInput, StreamSegmentRenderers, StreamViewportHandle } from "./strategy"; import { createWebStreamStrategy } from "./strategy-web"; @@ -131,6 +131,79 @@ describe("createWebStreamStrategy", () => { vi.restoreAllMocks(); }); + it.each(["liveHead", "historyMounted"] as const)( + "keeps one rendered tool row after late prior-turn updates in %s", + (lane) => { + const strategy = createWebStreamStrategy({ isMobileBreakpoint: true }); + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + const input: StreamRenderInput = { + agentId: "agent", + segments: { historyVirtualized: [], historyMounted: [], liveHead: [] }, + boundary: { + hasVirtualizedHistory: false, + hasMountedHistory: lane === "historyMounted", + hasLiveHead: lane === "liveHead", + }, + renderers: createRenderers(() => {}), + listEmptyComponent: null, + viewportRef: React.createRef(), + routeBottomAnchorRequest: null, + isAuthoritativeHistoryReady: true, + onNearBottomChange: () => {}, + onNearHistoryStart: () => true, + isLoadingOlderHistory: false, + hasOlderHistory: false, + olderHistoryProgressKey: null, + scrollEnabled: true, + listStyle: null, + baseListContentContainerStyle: null, + forwardListContentContainerStyle: null, + contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH, + }; + let items: StreamItem[] = []; + const updates = [ + { callId: "background", turnId: "old", status: "running" }, + { callId: "exec", turnId: "current", status: "running" }, + { callId: "background", turnId: "old", status: "completed" }, + { callId: "exec", turnId: "current", status: "completed" }, + ] as const; + for (const [index, update] of updates.entries()) { + items = reduceStreamUpdate( + items, + { + type: "timeline", + provider: "codex", + turnId: update.turnId, + item: { + type: "tool_call", + callId: update.callId, + name: "exec_command", + status: update.status, + error: null, + detail: { type: "shell", command: update.callId }, + }, + }, + new Date(index), + ); + act(() => + root?.render( + strategy.render({ + ...input, + segments: { ...input.segments, [lane]: items }, + }), + ), + ); + } + const rows = [...container.querySelectorAll("[data-history-row-id]")]; + expect(rows.map((row) => row.getAttribute("data-history-row-id"))).toEqual([ + "agent_tool_turn:old/background", + "agent_tool_turn:current/exec", + ]); + }, + ); + it("mounts virtualized history without recursive row measurement updates", () => { const rowRenderCount = vi.fn(); const strategy = createWebStreamStrategy({ isMobileBreakpoint: true }); diff --git a/packages/app/src/agent-stream/turn-collapse/model.ts b/packages/app/src/agent-stream/turn-collapse/model.ts index c8c1617e24..20ab84a817 100644 --- a/packages/app/src/agent-stream/turn-collapse/model.ts +++ b/packages/app/src/agent-stream/turn-collapse/model.ts @@ -29,7 +29,6 @@ export interface TurnCollapse { export interface CollapseTurnsInput { tail: StreamItem[]; - autoExpandReasoning?: boolean; /** The latest turn is still producing output, so it stays unfolded. */ isLatestTurnOpen: boolean; expandedHostIds: ReadonlySet; @@ -58,12 +57,8 @@ function hasWork(summary: TurnSummary): boolean { return Object.keys(paseoActions).length > 0 || Object.values(counts).some((count) => count > 0); } -function staysVisibleWhenCollapsed(item: StreamItem, autoExpandReasoning = false): boolean { - return ( - isTurnTrigger(item) || - item.kind === "compaction" || - (autoExpandReasoning && item.kind === "thought") - ); +function staysVisibleWhenCollapsed(item: StreamItem): boolean { + return isTurnTrigger(item) || item.kind === "compaction"; } function findLastAssistantIndex(tail: StreamItem[], start: number, end: number): number { @@ -77,7 +72,7 @@ function findLastAssistantIndex(tail: StreamItem[], start: number, end: number): * Folds each answered turn into its user message: everything the agent did before its last * message collapses into one summary line, and that message stays in the chat. A turn folds * only once it is complete, its user message is loaded, and it sent messages or called tools - * before its reply. Reasoning stays visible when Expand thinking is enabled. + * before its reply. Reasoning is revealed only when the turn opens. */ export function collapseTurns(input: CollapseTurnsInput): TurnCollapse { const { tail } = input; @@ -121,9 +116,7 @@ export function collapseTurns(input: CollapseTurnsInput): TurnCollapse { if (expanded) nestedItemIds.add(item.id); } output.push( - ...(expanded - ? revealed - : folded.filter((item) => staysVisibleWhenCollapsed(item, input.autoExpandReasoning))), + ...(expanded ? revealed : folded.filter((item) => staysVisibleWhenCollapsed(item))), ); output.push(...tail.slice(replyIndex, runEnd)); }; diff --git a/packages/app/src/agent-stream/view.tsx b/packages/app/src/agent-stream/view.tsx index 1cfddc8ecc..049f0d704b 100644 --- a/packages/app/src/agent-stream/view.tsx +++ b/packages/app/src/agent-stream/view.tsx @@ -792,9 +792,6 @@ const AgentStreamViewComponent = forwardRef - presentation.turns.nestedItemIds.has(id), - ); const renderThoughtItem = useCallback( (layoutItem: StreamLayoutItem, item: Extract) => { return ( @@ -804,11 +801,11 @@ const AgentStreamViewComponent = forwardRef ); }, - [autoExpandReasoning, setInlineDetailsExpanded, isExpandedTurnItem], + [autoExpandReasoning, setInlineDetailsExpanded], ); const renderSingleToolCallItem = useCallback( @@ -838,8 +835,6 @@ const AgentStreamViewComponent = forwardRef ); }, - [ - context.cwd, - resolvedServerId, - setInlineDetailsExpanded, - handleToolCallOpenFile, - isExpandedTurnItem, - ], + [context.cwd, resolvedServerId, setInlineDetailsExpanded, handleToolCallOpenFile], ); // Read through a stable event so live group updates do not change the renderer identity diff --git a/packages/app/src/components/user-message/index.tsx b/packages/app/src/components/user-message/index.tsx index 18a48798fb..d420ffdde5 100644 --- a/packages/app/src/components/user-message/index.tsx +++ b/packages/app/src/components/user-message/index.tsx @@ -61,11 +61,21 @@ export function MessageSender({ return session?.agents.get(sender.id) ?? session?.agentDetails.get(sender.id); }); const ProviderIcon = useProviderIcon(agent?.provider ?? "", host); + const renderProviderIcon = useCallback( + (color: string) => , + [ProviderIcon], + ); const openSender = useCallback(() => { if (host) navigateToAgent({ serverId: host, agentId: sender.id }); }, [host, sender.id]); return ( - ); @@ -74,6 +84,6 @@ export function MessageSender({ const styles = StyleSheet.create((theme) => ({ preview: { maxHeight: PREVIEW_HEIGHT, overflow: "hidden" }, body: { flexShrink: 0 }, - toggle: { alignSelf: "flex-start", paddingHorizontal: 0, borderWidth: 0 }, + toggle: { alignSelf: "flex-start", paddingHorizontal: 0, minHeight: 0, borderWidth: 0 }, fade: { position: "absolute", bottom: 0, left: 0, right: 0, height: theme.spacing[12] }, })); diff --git a/packages/app/src/timeline/session-stream-reducers.test.ts b/packages/app/src/timeline/session-stream-reducers.test.ts index 9e57142846..0e401ad7a0 100644 --- a/packages/app/src/timeline/session-stream-reducers.test.ts +++ b/packages/app/src/timeline/session-stream-reducers.test.ts @@ -19,6 +19,66 @@ import { type TimelineCursor, } from "./session-stream-reducers"; +it("keeps streamed reasoning together while the initial history is loading", () => { + let head: StreamItem[] = []; + const chunks = ["Checking a long oper", "ation before", " the re", "sult arrives."]; + for (const [index, text] of chunks.entries()) { + const result = processAgentStreamEvent({ + event: { + type: "timeline", + provider: "codex", + turnId: "turn-18", + item: { type: "reasoning", text }, + }, + seq: index + 1, + epoch: "epoch-1", + currentTail: [], + currentHead: head, + currentCursor: undefined, + timestamp: new Date(1000 + index), + hasAuthoritativeBaseline: false, + }); + head = result.head; + expect(head).toHaveLength(1); + expect(head[0]).toMatchObject({ + kind: "thought", + text: chunks.slice(0, index + 1).join(""), + turnId: "turn-18", + }); + } +}); + +it.each([false, true])( + "keeps adjacent reasoning from different turns separate (history loaded: %s)", + (hasAuthoritativeBaseline) => { + let head: StreamItem[] = []; + let tail: StreamItem[] = []; + for (const [index, turnId] of ["turn-1", "turn-2"].entries()) { + const result = processAgentStreamEvent({ + event: { + type: "timeline", + provider: "codex", + turnId, + item: { type: "reasoning", text: turnId }, + }, + seq: index + 1, + epoch: "epoch-1", + currentTail: tail, + currentHead: head, + currentCursor: undefined, + timestamp: new Date(1000), + hasAuthoritativeBaseline, + }); + head = result.head; + tail = result.tail; + } + expect([...tail, ...head]).toMatchObject([ + { kind: "thought", text: "turn-1", turnId: "turn-1" }, + { kind: "thought", text: "turn-2", turnId: "turn-2" }, + ]); + }, +); + // --------------------------------------------------------------------------- // Test helpers // --------------------------------------------------------------------------- diff --git a/packages/app/src/timeline/session-stream-reducers.ts b/packages/app/src/timeline/session-stream-reducers.ts index 34a461d893..a46ec8188f 100644 --- a/packages/app/src/timeline/session-stream-reducers.ts +++ b/packages/app/src/timeline/session-stream-reducers.ts @@ -1615,19 +1615,17 @@ export function processAgentStreamEvent( unmatchedUserMessageInsert: "head", }); } else { - const overlay = applyStreamEvent({ - tail: currentHead, - head: [], - event, - timestamp, + // Before history arrives, the overlay is one ordered stream. Reducing it + // directly keeps consecutive reasoning chunks in the same row. + const overlay = reduceStreamUpdate(currentHead, event, timestamp, { source: "live", timelineCursor, }); streamResult = { tail: currentTail, - head: [...overlay.tail, ...overlay.head], + head: overlay, changedTail: false, - changedHead: overlay.changedTail || overlay.changedHead, + changedHead: overlay !== currentHead, }; } } else { diff --git a/packages/app/src/types/stream.test.ts b/packages/app/src/types/stream.test.ts index 62e26698db..376d04ea67 100644 --- a/packages/app/src/types/stream.test.ts +++ b/packages/app/src/types/stream.test.ts @@ -661,6 +661,82 @@ describe("stream reducer canonical tool calls", () => { expect(new Set(tools.map((tool) => tool.id)).size).toBe(2); }); + it.each(["live", "canonical"] as const)( + "keeps current tool identity during %s updates when an older turn reports late", + (source) => { + let state: StreamItem[] = []; + const events = [ + { callId: "background", turnId: "codex-turn-17", status: "running" as const }, + { callId: "exec-current", turnId: "codex-turn-18", status: "running" as const }, + { callId: "background", turnId: "codex-turn-17", status: "completed" as const }, + { callId: "exec-current", turnId: "codex-turn-18", status: "completed" as const }, + ]; + for (const [index, item] of events.entries()) { + state = reduceStreamUpdate( + state, + canonicalToolTimeline({ + provider: "codex", + name: "exec_command", + ...item, + }), + new Date(index * 1000), + { source }, + ); + } + expect( + state.filter(isAgentToolCallItem).map((item) => ({ + id: item.id, + turnId: item.turnId, + status: item.payload.data.status, + })), + ).toEqual([ + { + id: "agent_tool_turn:codex-turn-17/background", + turnId: "codex-turn-17", + status: "completed", + }, + { + id: "agent_tool_turn:codex-turn-18/exec-current", + turnId: "codex-turn-18", + status: "completed", + }, + ]); + }, + ); + + it("does not move reasoning into an older turn when a late tool update finalizes it", () => { + const background = canonicalToolTimeline({ + provider: "codex", + name: "exec_command", + callId: "background", + turnId: "old", + status: "running", + }); + let state = reduceStreamUpdate([], background, new Date(0)); + state = reduceStreamUpdate( + state, + { + type: "timeline", + provider: "codex", + turnId: "current", + item: { type: "reasoning", text: "Working on the current request" }, + }, + new Date(1), + ); + state = reduceStreamUpdate( + state, + canonicalToolTimeline({ + provider: "codex", + name: "exec_command", + callId: "background", + turnId: "old", + status: "completed", + }), + new Date(2), + ); + expect(state.at(-1)).toMatchObject({ kind: "thought", turnId: "current", status: "ready" }); + }); + it("merges lifecycle updates for the same call occurrence", () => { const callId = "tool-updated-within-turn"; const turnId = "autonomous-turn-1"; diff --git a/packages/app/src/types/stream.ts b/packages/app/src/types/stream.ts index b1d0903a92..0226993a8c 100644 --- a/packages/app/src/types/stream.ts +++ b/packages/app/src/types/stream.ts @@ -988,6 +988,7 @@ function appendThought( text: string, timestamp: Date, timelineCursor?: TimelinePosition, + turnId?: string, ): StreamItem[] { const { chunk, hasContent } = normalizeChunk(text); if (!chunk) { @@ -995,7 +996,7 @@ function appendThought( } const last = state[state.length - 1]; - if (last && last.kind === "thought") { + if (last && last.kind === "thought" && last.turnId === turnId) { const updated: ThoughtItem = { ...last, ...(timelineCursor ? { timelineCursor } : {}), @@ -1513,36 +1514,30 @@ function reduceTimelineEvent( const item = event.item; switch (item.type) { case "user_message": - return finalizeActiveThoughts( - appendUserMessage( - state, - item.text, - timestamp, - source, - item.messageId, - item.clientMessageId, - timelineCursor, - event.turnId, - ), + return appendUserMessage( + state, + item.text, + timestamp, + source, + item.messageId, + item.clientMessageId, + timelineCursor, + event.turnId, ); case "assistant_message": - return finalizeActiveThoughts( - appendAssistantMessage( - state, - item.text, - timestamp, - source, - item.messageId, - reservedItemIds, - timelineCursor, - ), + return appendAssistantMessage( + state, + item.text, + timestamp, + source, + item.messageId, + reservedItemIds, + timelineCursor, ); case "reasoning": - return appendThought(state, item.text, timestamp, timelineCursor); + return appendThought(state, item.text, timestamp, timelineCursor, event.turnId); case "tool_call": - return finalizeActiveThoughts( - reduceTimelineToolCall(state, event, item, timestamp, timelineCursor), - ); + return reduceTimelineToolCall(state, event, item, timestamp, timelineCursor); case "todo": { const items: TodoEntry[] = (item.items ?? []).map((todo) => ({ text: todo.text, @@ -1551,9 +1546,7 @@ function reduceTimelineEvent( status: todo.status, activeForm: todo.activeForm, })); - return finalizeActiveThoughts( - appendTodoList(state, event.provider, items, timestamp, timelineCursor), - ); + return appendTodoList(state, event.provider, items, timestamp, timelineCursor); } case "error": { const notification: NotificationItem = { @@ -1565,7 +1558,7 @@ function reduceTimelineEvent( level: "error", message: item.message ?? "Unknown error", }; - return finalizeActiveThoughts(appendNotification(state, notification)); + return appendNotification(state, notification); } case "notification": { const notification: NotificationItem = { @@ -1577,16 +1570,12 @@ function reduceTimelineEvent( level: item.level, message: item.message, }; - return finalizeActiveThoughts(appendNotification(state, notification)); + return appendNotification(state, notification); } case "compaction": - return finalizeActiveThoughts( - reduceTimelineCompaction(state, item, timestamp, timelineCursor), - ); + return reduceTimelineCompaction(state, item, timestamp, timelineCursor); case "plugin": - return finalizeActiveThoughts( - appendPluginTimelineItem(state, item, timestamp, timelineCursor), - ); + return appendPluginTimelineItem(state, item, timestamp, timelineCursor); default: return state; } @@ -1603,8 +1592,9 @@ export function reduceStreamUpdate( ): StreamItem[] { const source = options?.source ?? "live"; switch (event.type) { - case "timeline": - return applyTimelineTurnId( + case "timeline": { + const updated = applyTimelineTurnId( + state, reduceTimelineEvent( state, event, @@ -1615,6 +1605,8 @@ export function reduceStreamUpdate( ), event, ); + return event.item.type === "reasoning" ? updated : finalizeActiveThoughts(updated); + } case "thread_started": case "turn_started": case "turn_completed": @@ -1630,6 +1622,7 @@ export function reduceStreamUpdate( } function applyTimelineTurnId( + previous: StreamItem[], items: StreamItem[], event: Extract, ): StreamItem[] { @@ -1639,15 +1632,14 @@ function applyTimelineTurnId( return reconcileCanonicalUserTurnMembership(items, clientMessageId, event.turnId); } - if (!event.turnId || items.length === 0) return items; - const index = items.length - 1; - const last = items[index]; - if (!last || last.turnId === event.turnId) return items; - return [ - ...items.slice(0, index), - { ...last, turnId: event.turnId } as StreamItem, - ...items.slice(index + 1), - ]; + if (!event.turnId || items === previous) return items; + // Assign membership only to rows written by this event, before finalizing + // unrelated reasoning rows. Late lifecycle updates can replace an earlier row. + return items.map((item, index) => + item === previous[index] || item.turnId === event.turnId + ? item + : ({ ...item, turnId: event.turnId } as StreamItem), + ); } function reconcileCanonicalUserTurnMembership( diff --git a/packages/client/src/daemon-client.test.ts b/packages/client/src/daemon-client.test.ts index f3b483193c..2a3b409cee 100644 --- a/packages/client/src/daemon-client.test.ts +++ b/packages/client/src/daemon-client.test.ts @@ -1640,6 +1640,77 @@ test("preserves legacy fetchAgent id overload", async () => { await expect(responsePromise).rejects.toThrow("legacy fetch sentinel"); }); +test.each([undefined, false, true])( + "loads history with whole-turn support advertised as %s", + async (wholeTurnTimeline) => { + const transport = createMockTransport(); + const client = new DaemonClient({ + url: "ws://test", + clientId: "history-compatibility", + reconnect: { enabled: false }, + transportFactory: () => transport.transport, + }); + clients.push(client); + const connected = client.connect(); + transport.triggerOpen({ + features: wholeTurnTimeline === undefined ? {} : { wholeTurnTimeline }, + }); + await connected; + + const requests = [ + { direction: "tail" as const }, + { direction: "before" as const, cursor: { epoch: "epoch-1", seq: 50 } }, + { direction: "after" as const, cursor: { epoch: "epoch-1", seq: 50 } }, + { direction: "before" as const, cursor: { epoch: "epoch-1", seq: 80 }, mergeWindow: true }, + ]; + for (const [index, request] of requests.entries()) { + const requestId = `history-${index}`; + const result = client.fetchAgentTimeline("agent-1", { + ...request, + requestId, + wholeTurns: true, + limit: 40, + projection: "projected", + }); + // Attach immediately so the old rejection is captured by the regression. + const completed = expect(result).resolves.toMatchObject({ requestId, entries: [] }); + expect(parseSentFrame(transport.sent.at(-1))).toEqual({ + type: "fetch_agent_timeline_request", + agentId: "agent-1", + requestId, + ...request, + limit: 40, + projection: "projected", + ...(wholeTurnTimeline === true ? { wholeTurns: true } : {}), + }); + transport.triggerMessage( + wrapSessionMessage({ + type: "fetch_agent_timeline_response", + payload: { + requestId, + agentId: "agent-1", + agent: null, + direction: request.direction, + projection: "projected", + epoch: "epoch-1", + reset: false, + staleCursor: false, + gap: false, + window: { minSeq: 0, maxSeq: 0, nextSeq: 1 }, + startCursor: null, + endCursor: null, + hasOlder: false, + hasNewer: false, + entries: [], + error: null, + }, + }), + ); + await completed; + } + }, +); + test("honors explicit fetchAgentTimeline timeout below the session RPC default", async () => { useHeartbeatClock(); const logger = createMockLogger(); @@ -1658,11 +1729,6 @@ test("honors explicit fetchAgentTimeline timeout below the session RPC default", mock.triggerOpen(); await connectPromise; - await expect(client.fetchAgentTimeline("agent-1", { wholeTurns: true })).rejects.toThrow( - "Update the host to load complete conversation turns.", - ); - expect(mock.sent).toHaveLength(0); - const responsePromise = client.fetchAgentTimeline("agent-1", { requestId: "req-timeline-1", direction: "tail", diff --git a/packages/client/src/daemon-client.ts b/packages/client/src/daemon-client.ts index 8840aa1eb4..524c3e264a 100644 --- a/packages/client/src/daemon-client.ts +++ b/packages/client/src/daemon-client.ts @@ -686,6 +686,7 @@ export interface FetchAgentOptions { } type LegacyFetchAgentOptions = Omit; export interface FetchAgentTimelineOptions { + /** Prefer whole-turn pages when supported; older hosts retain item-based paging. */ wholeTurns?: boolean; direction?: FetchAgentTimelineDirection; cursor?: FetchAgentTimelineCursor; @@ -3549,13 +3550,15 @@ export class DaemonClient { agentId: string, options: FetchAgentTimelineOptions = {}, ): Promise { - if (options.wholeTurns && this.lastServerInfoMessage?.features?.wholeTurnTimeline !== true) { - throw new Error("Update the host to load complete conversation turns."); - } + // COMPAT(wholeTurnTimeline): added after v0.13.2 (#8010); remove after 2027-04-27 once the daemon floor supports whole-turn pages. + // Reading history predates this capability and must keep working on older hosts. + const supportsWholeTurns = this.lastServerInfoMessage?.features?.wholeTurnTimeline === true; const resolvedRequestId = this.createRequestId(options.requestId); const message = SessionInboundMessageSchema.parse({ type: "fetch_agent_timeline_request", - ...(options.wholeTurns !== undefined ? { wholeTurns: options.wholeTurns } : {}), + ...(supportsWholeTurns && options.wholeTurns !== undefined + ? { wholeTurns: options.wholeTurns } + : {}), agentId, requestId: resolvedRequestId, ...(options.direction ? { direction: options.direction } : {}), From 50623965b4bb689dfe5dc47aaf36843a754c2a11 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Tue, 27 Oct 2026 16:09:53 +0700 Subject: [PATCH 056/173] Make line wrapping responsive in large diffs (#8006) * perf(app): make diff line wrapping responsive on large changes Wrapping eagerly shaped every expanded line before the viewport could paint. Estimate off-screen heights and measure rows as they enter the window, preserving the scroll anchor as geometry becomes exact. Add shared layout and browser benchmarks to track toggle latency and shaping cost. * fix(app): preserve wrapped diff anchors across bounded relayouts Resizing can move the viewed row outside the old materialization window. Keep its estimated wrap geometry available to anchor resolution, and measure the anchored row in the same layout pass so inaccurate estimates cannot discard the exact fragment or pixel offset. --- docs/development.md | 20 ++ .../app/e2e/browser/diff-performance.spec.ts | 180 ++++++++++ .../src/git/diff-document/benchmark-corpus.ts | 65 ++++ .../app/src/git/diff-document/model.bench.ts | 317 ++++++++++++++++++ .../app/src/git/diff-document/model.test.ts | 114 ++++++- packages/app/src/git/diff-document/model.ts | 134 ++++++-- .../src/git/diff-document/surface.native.tsx | 5 + .../app/src/git/diff-document/surface.web.tsx | 27 +- packages/app/src/git/diff-document/types.ts | 4 + .../git/diff-document/workspace-cache.test.ts | 31 ++ .../src/git/diff-document/workspace-cache.tsx | 4 +- 11 files changed, 872 insertions(+), 29 deletions(-) create mode 100644 packages/app/src/git/diff-document/benchmark-corpus.ts create mode 100644 packages/app/src/git/diff-document/model.bench.ts diff --git a/docs/development.md b/docs/development.md index d45ec589fc..873f9cabb9 100644 --- a/docs/development.md +++ b/docs/development.md @@ -273,6 +273,26 @@ Playwright dispatch lateness. Set `PASEO_PROFILE_TYPING_KEYS`, `PASEO_PROFILE_TY `PASEO_PROFILE_CPU_PATH` and `PASEO_PROFILE_TRACE_PATH` captures run separately after the latency measurements so profiling overhead does not contaminate them. +For diff layout, two benchmarks share one corpus +(`packages/app/src/git/diff-document/benchmark-corpus.ts`: a real source file, a changelog with +600-character lines, generated code with ligature punctuation, and JSON). The node bench runs the +shared document model with the web and native measurers replaced by counters, so it reports how +many strings each backend would have to shape, which is the cost that survives the move to canvas +or Skia: + +```bash +cd packages/app && npx vitest bench --project unit src/git/diff-document/model.bench.ts +``` + +The browser benchmark opens the same corpus as a working diff, toggles line wrap from the toolbar, +and reports pointer-down to painted latency, the longest main-thread task, and the `DiffDocument` +React commit time for cold and warm toggles, then scroll frame times in both modes: + +```bash +cd packages/app && PASEO_DIFF_PERF_E2E=1 npx playwright test --project=browser \ + e2e/browser/diff-performance.spec.ts -g "toggling line wrap" +``` + Set `PASEO_PROFILE_TYPING_SCENARIO=height-growth` to alternate `Shift+Enter` and printable input. That report includes input and composer height changes plus React work grouped into composer, stream, and ancestor/root scopes. Ancestor/root timings include descendant work because the Profiler diff --git a/packages/app/e2e/browser/diff-performance.spec.ts b/packages/app/e2e/browser/diff-performance.spec.ts index c11c82f279..0358b6359e 100644 --- a/packages/app/e2e/browser/diff-performance.spec.ts +++ b/packages/app/e2e/browser/diff-performance.spec.ts @@ -1,6 +1,7 @@ import { writeFile } from "node:fs/promises"; import path from "node:path"; import type { CDPSession, Locator, Page, TestInfo } from "@playwright/test"; +import { pullRequestCorpus } from "../../src/git/diff-document/benchmark-corpus"; import { buildHostWorkspaceRoute } from "../../src/utils/host-routes"; import { test, expect } from "../support/fixtures"; import { getServerId } from "../support/helpers/server-id"; @@ -296,8 +297,187 @@ diffPerfDescribe("Diff canvas performance", () => { await repo.cleanup().catch(() => undefined); } }); + test("toggling line wrap on a pull-request-sized diff", async ({ page }, testInfo) => { + test.setTimeout(300_000); + const corpus = await createPullRequestCorpusRepository(); + const client = await connectSeedClient(); + + try { + const created = await client.createWorkspace({ + source: { kind: "directory", path: corpus.repo.path }, + }); + if (!created.workspace) { + throw new Error(created.error ?? "Failed to create wrap performance workspace"); + } + + await configureUnwrappedUnifiedDiff(page); + await instrumentDiffLatency(page); + await page.setViewportSize({ width: 1400, height: 900 }); + await page.goto(buildHostWorkspaceRoute(getServerId(), created.workspace.id)); + await waitForWorkspaceTabsVisible(page); + const openStartedAt = performance.now(); + await openChangesPanel(page, 90_000); + await expect(page.getByTestId("git-diff-canvas")).toBeVisible({ timeout: 30_000 }); + const open = { + readyMs: Math.round(performance.now() - openStartedAt), + ...(await readDiffDocumentRenders(page)), + }; + + const toggles: WrapToggleMeasurement[] = []; + for (const name of [ + "wrap on (cold)", + "wrap off (cold)", + "wrap on (warm)", + "wrap off (warm)", + ]) { + toggles.push(await measureWrapToggle(page, name)); + } + const unwrappedScroll = await continuouslyScrollCanvas(page); + toggles.push(await measureWrapToggle(page, "wrap on (warm, scrolled)")); + const wrappedScroll = await continuouslyScrollCanvas(page); + + const report = { + scenario: "wrap-toggle", + sourceFiles: corpus.fileCount, + sourceLines: corpus.lineCount, + open, + toggles, + scroll: { + unwrapped: summarizeScroll(unwrappedScroll), + wrapped: summarizeScroll(wrappedScroll), + }, + }; + await attachPerformanceReport(testInfo, report); + console.log(`[perf] Wrap toggle: ${JSON.stringify(report)}`); + + const [wrapOn, wrapOff] = toggles; + expect(wrapOn!.scrollHeightAfter).toBeGreaterThan(wrapOn!.scrollHeightBefore); + expect(wrapOff!.scrollHeightAfter).toBe(wrapOn!.scrollHeightBefore); + } finally { + await client.close().catch(() => undefined); + await corpus.repo.cleanup().catch(() => undefined); + } + }); }); +interface WrapToggleMeasurement { + name: string; + /** Pointer down on the toolbar button to two painted frames after the document resized. */ + latencyMs: number; + scrollHeightBefore: number; + scrollHeightAfter: number; + longestTaskMs: number; + longTaskTotalMs: number; + diffDocumentCommits: number; + diffDocumentRenderMs: number; +} + +interface LongTask { + startTime: number; + duration: number; +} + +interface DiffLatencyScope { + __PASEO_RENDER_PROFILE_ENABLED__?: boolean; + __PASEO_RENDER_PROFILE__?: Array<{ id: string; actualDuration: number }>; + __PASEO_RESET_RENDER_PROFILE__?: () => void; + __PASEO_LONG_TASKS__?: LongTask[]; + __PASEO_WRAP_TOGGLE_AT__?: number; +} + +async function createPullRequestCorpusRepository() { + const files = pullRequestCorpus(); + const repo = await createTempGitRepo("diff-wrap-perf-", { + files: files.map((file) => ({ path: file.path, content: "baseline\n" })), + }); + for (const file of files) { + await writeFile(path.join(repo.path, file.path), `${file.lines.join("\n")}\n`); + } + return { + repo, + fileCount: files.length, + lineCount: files.reduce((count, file) => count + file.lines.length, 0), + }; +} + +async function instrumentDiffLatency(page: Page): Promise { + await page.addInitScript(() => { + const scope = globalThis as typeof globalThis & DiffLatencyScope; + scope.__PASEO_RENDER_PROFILE_ENABLED__ = true; + scope.__PASEO_LONG_TASKS__ = []; + new PerformanceObserver((list) => { + for (const entry of list.getEntries()) { + scope.__PASEO_LONG_TASKS__?.push({ startTime: entry.startTime, duration: entry.duration }); + } + }).observe({ type: "longtask", buffered: true }); + }); +} + +async function readDiffDocumentRenders( + page: Page, +): Promise<{ diffDocumentCommits: number; diffDocumentRenderMs: number }> { + return page.evaluate(() => { + const scope = globalThis as typeof globalThis & DiffLatencyScope; + const samples = (scope.__PASEO_RENDER_PROFILE__ ?? []).filter( + (sample) => sample.id === "DiffDocument", + ); + return { + diffDocumentCommits: samples.length, + diffDocumentRenderMs: Math.round( + samples.reduce((total, sample) => total + sample.actualDuration, 0), + ), + }; + }); +} + +async function measureWrapToggle(page: Page, name: string): Promise { + const scroll = page.getByTestId("git-diff-scroll"); + const scrollHeightBefore = await scroll.evaluate((element) => element.scrollHeight); + await page.evaluate(() => { + const scope = globalThis as typeof globalThis & DiffLatencyScope; + scope.__PASEO_RESET_RENDER_PROFILE__?.(); + scope.__PASEO_LONG_TASKS__ = []; + scope.__PASEO_WRAP_TOGGLE_AT__ = undefined; + document.addEventListener( + "pointerdown", + () => { + scope.__PASEO_WRAP_TOGGLE_AT__ = performance.now(); + }, + { capture: true, once: true }, + ); + }); + await page.getByTestId("changes-toggle-wrap-lines").click(); + const measured = await scroll.evaluate(async (element, before) => { + const scope = globalThis as typeof globalThis & DiffLatencyScope; + const deadline = performance.now() + 240_000; + while (element.scrollHeight === before && performance.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 5)); + } + await new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())), + ); + const doneAt = performance.now(); + // Long task entries are delivered after the task ends; give the observer a turn. + await new Promise((resolve) => setTimeout(resolve, 50)); + const startedAt = scope.__PASEO_WRAP_TOGGLE_AT__ ?? doneAt; + const longTasks = (scope.__PASEO_LONG_TASKS__ ?? []).filter( + (task) => task.startTime + task.duration >= startedAt && task.startTime <= doneAt, + ); + return { + latencyMs: Math.round(doneAt - startedAt), + scrollHeightAfter: element.scrollHeight, + longestTaskMs: Math.round(Math.max(0, ...longTasks.map((task) => task.duration))), + longTaskTotalMs: Math.round(longTasks.reduce((total, task) => total + task.duration, 0)), + }; + }, scrollHeightBefore); + return { name, scrollHeightBefore, ...measured, ...(await readDiffDocumentRenders(page)) }; +} + +function summarizeScroll(report: Awaited>) { + const { frameSignatures: _frameSignatures, ...summary } = report; + return summary; +} + async function measureAdditionalPerformanceScenario( page: Page, cdp: CDPSession, diff --git a/packages/app/src/git/diff-document/benchmark-corpus.ts b/packages/app/src/git/diff-document/benchmark-corpus.ts new file mode 100644 index 0000000000..469d437e8d --- /dev/null +++ b/packages/app/src/git/diff-document/benchmark-corpus.ts @@ -0,0 +1,65 @@ +import { readFileSync } from "node:fs"; +import path from "node:path"; + +/** + * The diff shapes the layout benchmarks measure, shared by the node bench + * (`model.bench.ts`) and the browser benchmark (`e2e/browser/diff-performance.spec.ts`) + * so both report against the same text. + */ +export interface BenchmarkCorpusFile { + path: string; + lines: string[]; +} + +function repeatToLength(unit: string, length: number): string { + return unit.repeat(Math.ceil(length / unit.length)).slice(0, length); +} + +/** A real source file: short lines, a few with ligature punctuation. */ +export function realCodeCorpusFile(): BenchmarkCorpusFile { + const source = readFileSync(path.resolve(__dirname, "../diff-pane.tsx"), "utf8"); + return { path: "packages/app/src/git/diff-pane.tsx", lines: source.split("\n") }; +} + +/** The CHANGELOG shape that once froze the renderer: 42 lines, longest ~600 characters. */ +export function changelogCorpusFile(): BenchmarkCorpusFile { + const sentence = + "- Fixed an issue where the diff viewer re-measured every line -> on toggle, which made wrapping painfully slow. "; + return { + path: "CHANGELOG.md", + lines: Array.from({ length: 42 }, (_, index) => + repeatToLength(sentence, 200 + ((index * 97) % 398)), + ), + }; +} + +/** Generated TypeScript: ligature punctuation on every line, every tenth line long. */ +export function generatedCodeCorpusFile(lineCount: number): BenchmarkCorpusFile { + return { + path: "src/generated.ts", + lines: Array.from({ length: lineCount }, (_, index) => { + const base = `const handler${index} = async (event) => items.filter((item) => item.id !== ${index} && item.kind === "selected");`; + return index % 10 === 9 ? repeatToLength(`${base} // `, 320) : base; + }), + }; +} + +/** Serialized data: no ligatures, every line wraps several times. */ +export function jsonCorpusFile(lineCount: number): BenchmarkCorpusFile { + return { + path: "fixtures/data.json", + lines: Array.from({ length: lineCount }, (_, index) => + repeatToLength(`{"id": ${index}, "label": "row ${index}", "tags": ["alpha", "beta"]}, `, 300), + ), + }; +} + +/** A pull-request-sized working diff: one of each shape above. */ +export function pullRequestCorpus(): BenchmarkCorpusFile[] { + return [ + realCodeCorpusFile(), + changelogCorpusFile(), + generatedCodeCorpusFile(1200), + jsonCorpusFile(300), + ]; +} diff --git a/packages/app/src/git/diff-document/model.bench.ts b/packages/app/src/git/diff-document/model.bench.ts new file mode 100644 index 0000000000..2fb25d502a --- /dev/null +++ b/packages/app/src/git/diff-document/model.bench.ts @@ -0,0 +1,317 @@ +import type { ParsedDiffFile } from "@getpaseo/protocol/messages"; +import { bench, describe } from "vitest"; +import { + changelogCorpusFile, + generatedCodeCorpusFile, + jsonCorpusFile, + pullRequestCorpus, + realCodeCorpusFile, + type BenchmarkCorpusFile, +} from "./benchmark-corpus"; +import { buildDiffDocumentModel } from "./model"; +import { + createAdditiveAdvances, + createChunkedAdvanceMeasurer, + createChunkedWidthMeasurer, + createMeasuredAdvances, + requiresShaping, +} from "./text-measurement"; +import type { BuildDiffDocumentModelInput, TextMeasurer } from "./types"; + +// The pure layout work the diff surface does when a diff opens or line wrap is +// toggled, without a browser or Skia. Counts are the backend-independent cost +// owners (how many strings a shaper has to see), timings are the JS overhead +// around them: +// npx vitest bench --project unit src/git/diff-document/model.bench.ts + +const DESKTOP_VIEWPORT = { width: 1400, height: 900 }; +const PHONE_VIEWPORT = { width: 390, height: 800 }; +const CELL_WIDTH = 7.8; + +interface MeasurementStats { + /** Whole strings handed to the backend. */ + calls: number; + /** Characters inside those strings; canvas and Skia cost scales with this. */ + characters: number; +} + +interface Backend { + measurer: TextMeasurer; + stats: MeasurementStats; +} + +function monospaceWidth(text: string): number { + let width = 0; + for (const character of text) width += character.charCodeAt(0) > 0x2e7f ? 2 : 1; + return width * CELL_WIDTH; +} + +function countingMeasure(stats: MeasurementStats): (text: string) => number { + return (text) => { + stats.calls += 1; + stats.characters += text.length; + return monospaceWidth(text); + }; +} + +/** Previous web backend, retained to isolate the cost of width-only probes. */ +function webBackendWithoutWidthProbe(): Backend { + const stats: MeasurementStats = { calls: 0, characters: 0 }; + const measure = countingMeasure(stats); + return { stats, measurer: { measure, measureAdvances: createMeasuredAdvances(measure) } }; +} + +/** + * `createWebTextMeasurer` in surface.web.tsx, with canvas replaced by a counter. + * Width-only probes shape one string per chunk, like the native measurer; the + * widths are the same sums, in the same order, as the last cumulative advance. + */ +function webBackend(): Backend { + const stats: MeasurementStats = { calls: 0, characters: 0 }; + const measure = countingMeasure(stats); + const additive = createAdditiveAdvances(measure); + return { + stats, + measurer: { + measure, + measureAdvances: createMeasuredAdvances(measure), + measureWidth: createChunkedWidthMeasurer((graphemes) => { + const text = graphemes.join(""); + return requiresShaping(text) ? measure(text) : (additive(graphemes).at(-1) ?? 0); + }), + }, + }; +} + +/** `createNativeTextMeasurer` in text.native.ts, with Skia replaced by a counter. */ +function nativeBackend(): Backend { + const stats: MeasurementStats = { calls: 0, characters: 0 }; + const widths = new Map(); + const additive = (graphemes: readonly string[]) => { + let advance = 0; + return graphemes.map((grapheme) => { + let width = widths.get(grapheme); + if (width === undefined) { + stats.calls += 1; + stats.characters += grapheme.length; + width = monospaceWidth(grapheme); + widths.set(grapheme, width); + } + return (advance += width); + }); + }; + const shape = countingMeasure(stats); + return { + stats, + measurer: { + measure(text) { + return requiresShaping(text) ? shape(text) : (additive([...text]).at(-1) ?? 0); + }, + measureWidth: createChunkedWidthMeasurer((graphemes) => { + const text = graphemes.join(""); + return requiresShaping(text) ? shape(text) : (additive(graphemes).at(-1) ?? 0); + }), + measureAdvances: createChunkedAdvanceMeasurer({ + requiresShaping, + measureAdditive: additive, + measureShaped(graphemes) { + shape(graphemes.join("")); + let advance = 0; + return graphemes.map((grapheme) => (advance += monospaceWidth(grapheme))); + }, + }), + }, + }; +} + +function addedFile(file: BenchmarkCorpusFile): ParsedDiffFile { + return { + path: file.path, + isNew: true, + isDeleted: false, + additions: file.lines.length, + deletions: 0, + hunks: [ + { + oldStart: 0, + oldCount: 0, + newStart: 1, + newCount: file.lines.length, + lines: file.lines.map((content) => ({ + type: "add" as const, + content, + tokens: [{ text: content, style: null }], + })), + }, + ], + }; +} + +interface Scenario { + name: string; + files: ParsedDiffFile[]; +} + +const SCENARIOS: Scenario[] = [ + { name: "real code (diff-pane.tsx)", files: [addedFile(realCodeCorpusFile())] }, + { name: "changelog (42 long prose lines)", files: [addedFile(changelogCorpusFile())] }, + { name: "generated code (1200 lines)", files: [addedFile(generatedCodeCorpusFile(1200))] }, + { name: "json (300 lines x 300 chars)", files: [addedFile(jsonCorpusFile(300))] }, + { name: "pull request (all of the above)", files: pullRequestCorpus().map(addedFile) }, +]; + +function input( + scenario: Scenario, + options: { + wrapLines: boolean; + viewport: { width: number; height: number }; + measureText: TextMeasurer; + }, +): BuildDiffDocumentModelInput { + return { + files: scenario.files, + collapsedFilePaths: new Set(), + layout: "unified", + wrapLines: options.wrapLines, + viewportWidth: options.viewport.width, + typography: { family: "monospace", size: 13, lineHeight: 20 }, + measureText: options.measureText, + palette: { + surface: "#000", + headerSurface: "#111", + border: "#222", + foreground: "#fff", + foregroundMuted: "#aaa", + addition: "green", + deletion: "red", + additionBackground: "#010", + deletionBackground: "#100", + emptyBackground: "#111", + selection: "blue", + headerActiveSurface: "#222", + headerBorder: "#333", + statusSuccess: "green", + statusDanger: "red", + statusWarning: "orange", + syntax: {}, + }, + labels: { binary: "Binary", tooLarge: "Too large" }, + // What the surfaces pass at scrollTop 0: five viewports tall. + materializationWindow: { top: 0, height: options.viewport.height * 5 }, + }; +} + +interface Variant { + name: string; + wrapLines: boolean; + viewport: { width: number; height: number }; + backend: () => Backend; +} + +const VARIANTS: Variant[] = [ + { + name: "unwrapped desktop | web", + wrapLines: false, + viewport: DESKTOP_VIEWPORT, + backend: webBackend, + }, + { + name: "wrapped desktop | web", + wrapLines: true, + viewport: DESKTOP_VIEWPORT, + backend: webBackend, + }, + { + name: "wrapped desktop | web without width probe", + wrapLines: true, + viewport: DESKTOP_VIEWPORT, + backend: webBackendWithoutWidthProbe, + }, + { + name: "wrapped phone | web", + wrapLines: true, + viewport: PHONE_VIEWPORT, + backend: webBackend, + }, + { + name: "unwrapped desktop | native", + wrapLines: false, + viewport: DESKTOP_VIEWPORT, + backend: nativeBackend, + }, + { + name: "wrapped desktop | native", + wrapLines: true, + viewport: DESKTOP_VIEWPORT, + backend: nativeBackend, + }, + { + name: "wrapped phone | native", + wrapLines: true, + viewport: PHONE_VIEWPORT, + backend: nativeBackend, + }, +]; + +function countModel(scenario: Scenario, variant: Variant) { + const { measurer, stats } = variant.backend(); + const started = performance.now(); + const model = buildDiffDocumentModel( + input(scenario, { + wrapLines: variant.wrapLines, + viewport: variant.viewport, + measureText: measurer, + }), + ); + const elapsedMs = performance.now() - started; + let materializedCells = 0; + let fragments = 0; + let graphemes = 0; + for (const row of model.rows) { + if (row.kind !== "line") continue; + for (const cell of row.cells) { + if (!cell || cell.fragments.length === 0) continue; + materializedCells += 1; + fragments += cell.fragments.length; + for (const fragment of cell.fragments) graphemes += fragment.graphemes.length; + } + } + const sourceLines = scenario.files.reduce( + (count, file) => count + file.hunks.reduce((total, hunk) => total + hunk.lines.length, 0), + 0, + ); + return { + sourceLines, + materializedCells, + fragments, + graphemeObjects: graphemes, + measureCalls: stats.calls, + measuredCharacters: stats.characters, + coldMs: Number(elapsedMs.toFixed(1)), + }; +} + +const report: Record> = {}; +for (const scenario of SCENARIOS) { + for (const variant of VARIANTS) { + report[`${scenario.name} | ${variant.name}`] = countModel(scenario, variant); + } +} +console.table(report); + +for (const scenario of SCENARIOS) { + describe(scenario.name, () => { + for (const variant of VARIANTS) { + if (variant.backend === nativeBackend) continue; + bench(variant.name, () => { + buildDiffDocumentModel( + input(scenario, { + wrapLines: variant.wrapLines, + viewport: variant.viewport, + measureText: variant.backend().measurer, + }), + ); + }); + } + }); +} diff --git a/packages/app/src/git/diff-document/model.test.ts b/packages/app/src/git/diff-document/model.test.ts index ace965c1ce..9b55a242db 100644 --- a/packages/app/src/git/diff-document/model.test.ts +++ b/packages/app/src/git/diff-document/model.test.ts @@ -10,7 +10,7 @@ import { resolveRelayoutScrollTop, shouldApplyRelayoutScroll, } from "./model"; -import type { BuildDiffDocumentModelInput, TextMeasurer } from "./types"; +import type { BuildDiffDocumentModelInput, DiffCell, TextMeasurer } from "./types"; const measurer: TextMeasurer = { measure: (text) => Array.from(text).length * 10 }; @@ -639,17 +639,119 @@ describe("diff document model", () => { expect(firstLineCells(last, "b.ts")).toBe(firstLineCells(first, "b.ts")); }); - it("keeps wrapped geometry fully measured", () => { + it("replaces estimated wrapped heights through reuse and preserves the scroll anchor", () => { + const changed = fileWithChangedLine("x".repeat(100)); + const files = [changed, file("later.ts")]; + // Deliberately inaccurate M width makes the estimate differ from exact layout. + const measureText = { + measure: (text: string) => (text === "M" ? 5 : Array.from(text).length * 10), + }; + const options = input({ files, measureText }); + const first = buildDiffDocumentModel({ + ...options, + materializationWindow: { top: 30, height: 1 }, + }); + const eager = buildDiffDocumentModel(options); + const exact = buildDiffDocumentModel({ ...options, reuseFrom: [first] }); + expect(first.height).not.toBe(eager.height); + expect(exact.rows).toEqual(eager.rows); + expect(exact.height).toBe(eager.height); + expect(firstLineCells(exact, changed.path)).toBe(firstLineCells(first, changed.path)); + const scrollTop = first.files[1]!.bodyTop + 3; + const nextScrollTop = resolveRelayoutScrollTop(first, exact, scrollTop); + expect(nextScrollTop).toBe(exact.files[1]!.bodyTop + 3); + expect(captureScrollAnchor(exact, nextScrollTop)).toEqual( + captureScrollAnchor(first, scrollTop), + ); + }); + + it("preserves the wrapped source offset when resize leaves the anchor outside the window", () => { + const source = file(); + source.hunks[0]!.lines = Array.from({ length: 200 }, () => ({ + type: "add" as const, + content: "x".repeat(200), + })); + const options = input({ files: [source], viewportWidth: 500 }); + const before = buildDiffDocumentModel(options); + const scrollTop = before.rows[100]!.top + 36; + const anchor = captureScrollAnchor(before, scrollTop)!; + expect(anchor).toMatchObject({ kind: "text", cellOffset: 90 }); + const resizedOptions = { ...options, viewportWidth: 180 }; + const estimated = buildDiffDocumentModel({ + ...resizedOptions, + materializationWindow: { + top: Math.floor(scrollTop / 800) * 800 - 800, + height: 2000, + }, + }); + const estimatedRow = estimated.rows[100]!; + expect(estimatedRow.kind === "line" && estimatedRow.cells[0]?.fragments).toEqual([]); + const restored = resolveRelayoutScrollTop(before, estimated, scrollTop); + const recaptured = captureScrollAnchor(estimated, restored)!; + expect(recaptured).toMatchObject({ kind: "text", cellOffset: 78 }); + + const materialized = buildDiffDocumentModel({ + ...resizedOptions, + materializationWindow: { top: restored - 800, height: 2000 }, + reuseFrom: [estimated], + }); + const eager = buildDiffDocumentModel(resizedOptions); + const expected = resolveRelayoutScrollTop(before, eager, scrollTop); + expect(expected).toBe(28_938); + expect(Math.abs(restored - expected)).toBeLessThan(before.lineHeight); + expect(resolveRelayoutScrollTop(estimated, materialized, restored)).toBe(expected); + }); + + it("materializes the relayout anchor even when off-screen height estimates are inaccurate", () => { + const source = file(); + source.hunks[0]!.lines = Array.from({ length: 200 }, () => ({ + type: "add" as const, + content: "x".repeat(200), + })); + const options = input({ files: [source], viewportWidth: 500 }); + const before = buildDiffDocumentModel(options); + const scrollTop = before.rows[100]!.top + 38; + const anchor = captureScrollAnchor(before, scrollTop)!; + const resizedOptions = { + ...options, + viewportWidth: 180, + measureText: { measure: (text: string) => (text === "M" ? 5 : text.length * 10) }, + }; + const resized = buildDiffDocumentModel({ + ...resizedOptions, + materializationWindow: { top: scrollTop - 800, height: 2000 }, + materializationAnchor: anchor, + }); + const row = resized.rows[100]!; + expect(row.kind === "line" && row.cells[0]!.fragments.length).toBeGreaterThan(0); + const restored = resolveRelayoutScrollTop(before, resized, scrollTop); + const materialized = buildDiffDocumentModel({ + ...resizedOptions, + materializationWindow: { top: restored - 800, height: 2000 }, + materializationAnchor: captureScrollAnchor(resized, restored), + reuseFrom: [resized], + }); + const nextScrollTop = resolveRelayoutScrollTop(resized, materialized, restored); + const nextAnchor = captureScrollAnchor(materialized, nextScrollTop); + // Offset 90 belongs to the fragment beginning at 78 after narrowing. + expect(nextAnchor).toMatchObject({ kind: "text", cellOffset: 78, viewportDelta: -2 }); + expect(nextScrollTop).toBe(resolveScrollAnchor(materialized, anchor)); + }); + + it("materializes wrapped text only inside the window", () => { const model = buildDiffDocumentModel( input({ files: [file("a.ts"), file("b.ts")], wrapLines: true, - materializationWindow: { top: 0, height: FILE_HEADER_HEIGHT }, + materializationWindow: { top: FILE_HEADER_HEIGHT, height: 1 }, }), ); expect(measuredFragments(model, "a.ts")).toBeGreaterThan(0); - expect(measuredFragments(model, "b.ts")).toBeGreaterThan(0); + expect(measuredFragments(model, "b.ts")).toBe(0); + expect( + model.rows.filter((row) => row.kind === "line" && row.cells.some(hasFragments)), + ).toHaveLength(1); }); }); @@ -798,3 +900,7 @@ function reviewActionsWithEditor( onDeleteComment() {}, }; } + +function hasFragments(cell: DiffCell | null): boolean { + return cell !== null && cell.fragments.length > 0; +} diff --git a/packages/app/src/git/diff-document/model.ts b/packages/app/src/git/diff-document/model.ts index fb2b9a04f0..67efe06c2b 100644 --- a/packages/app/src/git/diff-document/model.ts +++ b/packages/app/src/git/diff-document/model.ts @@ -154,27 +154,38 @@ function appendReusableFileRows(candidate: { }): FileRowsResult { const reusedRows = candidate.model.rows.slice(candidate.file.rowStart, candidate.file.rowEnd); const retainsRowGeometry = - !candidate.input.wrapLines && candidate.model.reviewGeometryKey === candidate.reviewGeometryKey && candidate.file.top === candidate.fileTop && candidate.file.fileIndex === candidate.fileIndex && candidate.file.rowStart === candidate.rows.length; let top = candidate.bodyTop; for (const reusedRow of reusedRows) { - let nextRow = retainsRowGeometry ? reusedRow : repositionReusedRow(reusedRow, candidate, top); + let nextRow = + retainsRowGeometry && reusedRow.top === top + ? reusedRow + : repositionReusedRow(reusedRow, candidate, top); if ( nextRow.kind === "line" && - intersectsMaterializationWindow(candidate.input, top, top + nextRow.height) && + (intersectsMaterializationWindow(candidate.input, top, top + nextRow.height) || + containsMaterializationAnchor(candidate.input, candidate.file.path, nextRow.cells)) && nextRow.cells.some((cell) => cell && cell.fragments.length === 0) ) { + const cells = materializeCells( + nextRow.cells, + candidate.file.file, + candidate.file.gutterWidth, + candidate.input, + ); nextRow = { ...nextRow, - cells: materializeCells( - nextRow.cells, - candidate.file.file, - candidate.file.gutterWidth, - candidate.input, - ), + cells, + height: + Math.max( + candidate.input.typography.lineHeight, + ...cells.map( + (cell) => (cell?.fragments.length ?? 1) * candidate.input.typography.lineHeight, + ), + ) + nextRow.reviewHeight, }; } candidate.rows.push(nextRow); @@ -240,6 +251,7 @@ function appendNewFileRows(candidate: { const lines = geometryLines( lineSources(candidate.file, candidate.input.layout, false), candidate.input, + candidate.gutterWidth, ); const fileBottom = candidate.bodyTop + @@ -252,8 +264,8 @@ function appendNewFileRows(candidate: { let maximumHorizontalOverflow = 0; for (const line of lines) { const shouldMaterialize = - candidate.input.wrapLines || - intersectsMaterializationWindow(candidate.input, top, top + line.height); + intersectsMaterializationWindow(candidate.input, top, top + line.height) || + containsMaterializationAnchor(candidate.input, candidate.file.path, line.cells); const cells = shouldMaterialize ? materializeCells(line.cells, candidate.file, candidate.gutterWidth, candidate.input) : line.cells; @@ -275,7 +287,7 @@ function appendNewFileRows(candidate: { candidate.input.typography.lineHeight, ...cells.map((cell) => (cell?.fragments.length ?? 1) * candidate.input.typography.lineHeight), ); - const height = textHeight + line.reviewHeight; + const height = shouldMaterialize ? textHeight + line.reviewHeight : line.height; candidate.rows.push({ kind: "line", index: candidate.rows.length, @@ -412,13 +424,14 @@ function cellSource(line: SplitDiffDisplayLine | null, includeTokens: boolean): }; } -function geometryCell(source: CellSource): DiffCell { +function geometryCell(source: CellSource, estimatedWrapColumns: number): DiffCell { return { type: source.type, content: source.content, lineNumber: source.lineNumber, tokens: [], fragments: [], + estimatedWrapColumns, reviewTarget: source.reviewTarget, sourceIdentity: source.sourceIdentity, }; @@ -427,20 +440,87 @@ function geometryCell(source: CellSource): DiffCell { function geometryLines( sources: Array<[CellSource] | [CellSource | null, CellSource | null]>, input: BuildDiffDocumentModelInput, + gutterWidth: number, ): GeometryLine[] { + const characterWidth = input.wrapLines ? input.measureText.measure("M") : 0; return sources.map((sourceCells) => { + const columns = input.wrapLines + ? Math.max( + 1, + Math.floor( + (input.viewportWidth / sourceCells.length - gutterWidth - CODE_HORIZONTAL_PADDING) / + characterWidth, + ), + ) + : Infinity; const cells = sourceCells.map((source) => - source ? geometryCell(source) : null, + source ? geometryCell(source, columns) : null, ) as DiffLineRow["cells"]; const reviewHeight = reviewHeightForCells(cells, input); return { cells, reviewHeight, - height: input.typography.lineHeight + reviewHeight, + // Unseen wrapped rows use a monospace estimate; materialization replaces + // it with the exact fragment count without changing source identity. + height: + input.typography.lineHeight * + Math.max( + 1, + ...cells.map((cell) => { + return cell && input.wrapLines + ? Math.ceil(estimatedDisplayOffset(cell.content) / columns) + : 1; + }), + ) + + reviewHeight, }; }); } +// Use the same tab expansion and column count for estimated heights and anchors. +function estimatedDisplayOffset(text: string): number { + return text.length + (text.match(/\t/g)?.length ?? 0) * 3; +} + +function estimatedVisualLine(cell: DiffCell, sourceOffset: number): number { + return Math.floor( + estimatedDisplayOffset(cell.content.slice(0, sourceOffset)) / + (cell.estimatedWrapColumns ?? Infinity), + ); +} + +function estimatedFragment(cell: DiffCell, visualIndex: number, lineHeight: number) { + const columns = cell.estimatedWrapColumns ?? Infinity; + const lastIndex = Math.max(0, Math.ceil(estimatedDisplayOffset(cell.content) / columns) - 1); + const index = Math.min(visualIndex, lastIndex); + const displayOffset = index === 0 ? 0 : index * columns; + let start = Math.min(displayOffset, cell.content.length); + if (cell.content.includes("\t")) { + let offset = 0; + start = 0; + while (start < cell.content.length && offset < displayOffset) { + offset += cell.content[start] === "\t" ? 4 : 1; + start += 1; + } + } + return { start, top: index * lineHeight }; +} + +// A resize can move the anchor outside the old window. Measure that row in the +// same pass: estimated columns cannot identify exact shaped-text fragments. +function containsMaterializationAnchor( + input: BuildDiffDocumentModelInput, + path: string, + cells: DiffLineRow["cells"], +): boolean { + const anchor = input.materializationAnchor; + return ( + anchor?.kind === "text" && + anchor.path === path && + cells.some((cell) => cell && sameSourceIdentity(cell.sourceIdentity, anchor.sourceIdentity)) + ); +} + function intersectsMaterializationWindow( input: BuildDiffDocumentModelInput, fileTop: number, @@ -795,17 +875,27 @@ export function captureScrollAnchor( } const textY = Math.max(0, Math.min(scrollTop - row.top, row.height - row.reviewHeight)); const visualIndex = Math.max(0, Math.floor(textY / model.lineHeight)); - let cellIndex = row.cells.findIndex((cell) => Boolean(cell?.fragments[visualIndex])); + let cellIndex = row.cells.findIndex( + (cell) => + cell && + (cell.fragments.length > 0 + ? Boolean(cell.fragments[visualIndex]) + : estimatedFragment(cell, visualIndex, model.lineHeight).top === + visualIndex * model.lineHeight), + ); if (cellIndex < 0) cellIndex = row.cells.findIndex((cell) => cell !== null); const cell = row.cells[cellIndex]; if (!cell) return { kind: "header", path: file.path, viewportDelta: row.top - scrollTop }; - const fragment = cell.fragments[Math.min(cell.fragments.length - 1, visualIndex)]; - const anchorY = row.top + (fragment?.top ?? 0); + const fragment = + cell.fragments.length > 0 + ? cell.fragments[Math.min(cell.fragments.length - 1, visualIndex)]! + : estimatedFragment(cell, visualIndex, model.lineHeight); + const anchorY = row.top + fragment.top; return { kind: "text", path: file.path, sourceIdentity: cell.sourceIdentity, - cellOffset: fragment?.start ?? 0, + cellOffset: fragment.start, viewportDelta: anchorY - scrollTop, }; } @@ -831,8 +921,10 @@ export function resolveScrollAnchor(model: DiffDocumentModel, anchor: DiffScroll const fragment = cell.fragments.find( (candidate) => candidate.start <= anchor.cellOffset && anchor.cellOffset < candidate.end, - ) ?? cell.fragments.at(-1); - return Math.max(0, row.top + (fragment?.top ?? 0) - anchor.viewportDelta); + ) ?? + cell.fragments.at(-1) ?? + estimatedFragment(cell, estimatedVisualLine(cell, anchor.cellOffset), model.lineHeight); + return Math.max(0, row.top + fragment.top - anchor.viewportDelta); } export function resolveRelayoutScrollTop( diff --git a/packages/app/src/git/diff-document/surface.native.tsx b/packages/app/src/git/diff-document/surface.native.tsx index 2063198712..00a47437cd 100644 --- a/packages/app/src/git/diff-document/surface.native.tsx +++ b/packages/app/src/git/diff-document/surface.native.tsx @@ -38,6 +38,7 @@ import { } from "./horizontal-offsets"; import { buildDiffDocumentModel, + captureScrollAnchor, resolveRelayoutScrollTop, retainReusableModels, shouldApplyRelayoutScroll, @@ -138,6 +139,9 @@ export function DiffSurface(props: DiffSurfaceProps) { tooLarge: t("workspace.git.diff.tooLarge"), }, materializationWindow: diffMaterializationWindow(fileWindowTop, viewport.height), + materializationAnchor: previousModelRef.current + ? captureScrollAnchor(previousModelRef.current, scrollTop.get()) + : null, reuseFrom, }); reusableModelRef.current = { @@ -148,6 +152,7 @@ export function DiffSurface(props: DiffSurfaceProps) { }, [ measurement, fileWindowTop, + scrollTop, props.collapsedFilePaths, props.displayPreferences.layout, props.displayPreferences.wrapLines, diff --git a/packages/app/src/git/diff-document/surface.web.tsx b/packages/app/src/git/diff-document/surface.web.tsx index 97801b708f..393f6dfcd7 100644 --- a/packages/app/src/git/diff-document/surface.web.tsx +++ b/packages/app/src/git/diff-document/surface.web.tsx @@ -28,10 +28,20 @@ import { } from "./hit-testing"; import { retainHorizontalOffsetMapForPaths } from "./horizontal-offsets"; import { HorizontalScroll } from "./horizontal-scroll.web"; -import { buildDiffDocumentModel, FILE_HEADER_HEIGHT, resolveRelayoutScrollTop } from "./model"; +import { + buildDiffDocumentModel, + captureScrollAnchor, + FILE_HEADER_HEIGHT, + resolveRelayoutScrollTop, +} from "./model"; import { paintWebFileHeader, paintWebViewport } from "./paint.web"; import { hasPointerDragStarted } from "./pointer-gesture"; -import { createMeasuredAdvances } from "./text-measurement"; +import { + createMeasuredAdvances, + createAdditiveAdvances, + createChunkedWidthMeasurer, + requiresShaping, +} from "./text-measurement"; import { retainDiffViewport } from "./viewport"; import type { DiffHit, @@ -183,6 +193,9 @@ export function DiffSurface(props: DiffSurfaceProps) { tooLarge: t("workspace.git.diff.tooLarge"), }, materializationWindow: diffMaterializationWindow(fileWindowTop, viewport.height), + materializationAnchor: previousModelRef.current + ? captureScrollAnchor(previousModelRef.current, scrollTopRef.current) + : null, }); return next; }, [ @@ -1166,5 +1179,13 @@ function createWebTextMeasurer(typography: DiffTypography): TextMeasurer { }; // Canvas exposes no glyph coverage, so `requiresShaping` alone decides which // runs a shaper has to see -- there is no `glyphIds` to fall back on. - return { measure, measureAdvances: createMeasuredAdvances((text) => measure(text)) }; + const additive = createAdditiveAdvances(measure); + return { + measure, + measureAdvances: createMeasuredAdvances(measure), + measureWidth: createChunkedWidthMeasurer((graphemes) => { + const text = graphemes.join(""); + return requiresShaping(text) ? measure(text) : (additive(graphemes).at(-1) ?? 0); + }), + }; } diff --git a/packages/app/src/git/diff-document/types.ts b/packages/app/src/git/diff-document/types.ts index 4ac8125445..d98880eb8c 100644 --- a/packages/app/src/git/diff-document/types.ts +++ b/packages/app/src/git/diff-document/types.ts @@ -112,6 +112,8 @@ export interface DiffCell { lineNumber: number | null; tokens: DiffTokenRun[]; fragments: DiffFragment[]; + /** Monospace columns per visual line until this cell is measured. */ + estimatedWrapColumns?: number; reviewTarget: ReviewableDiffTarget | null; sourceIdentity: DiffSourceIdentity; } @@ -185,6 +187,8 @@ export interface BuildDiffDocumentModelInput { reviewActions?: InlineReviewActions; labels: { binary: string; tooLarge: string }; materializationWindow?: { top: number; height: number }; + /** Also measure the anchored row so relayout can restore its exact fragment. */ + materializationAnchor?: DiffScrollAnchor | null; /** A geometry-compatible model whose unchanged file measurements may be reused. */ reuseFrom?: readonly DiffDocumentModel[]; } diff --git a/packages/app/src/git/diff-document/workspace-cache.test.ts b/packages/app/src/git/diff-document/workspace-cache.test.ts index ddf9972a46..a264d417ca 100644 --- a/packages/app/src/git/diff-document/workspace-cache.test.ts +++ b/packages/app/src/git/diff-document/workspace-cache.test.ts @@ -95,6 +95,37 @@ describe("diff document workspace cache", () => { expect(stats.calls).toBe(0); }); + it("materializes a new anchor when the viewport window is unchanged", () => { + const cache = createDiffDocumentWorkspaceCache(); + const source = diffFile(); + source.hunks[0]!.lines = Array.from({ length: 100 }, () => ({ + type: "add" as const, + content: "x".repeat(200), + })); + const { measureText } = countingMeasurer(); + const input = modelInput([source], measureText, { + wrapLines: true, + materializationWindow: { top: 30, height: 54 }, + }); + const first = cache.buildModel(input); + const anchored = cache.buildModel({ + ...input, + materializationAnchor: { + kind: "text", + path: source.path, + sourceIdentity: { hunkIndex: 0, lineIndex: 50, side: "new" }, + cellOffset: 90, + viewportDelta: -2, + }, + }); + const firstRow = first.rows[50]!; + const anchoredRow = anchored.rows[50]!; + expect(firstRow.kind === "line" && firstRow.cells[0]!.fragments.length).toBe(0); + expect(anchoredRow.kind === "line" && anchoredRow.cells[0]!.fragments.length).toBeGreaterThan( + 0, + ); + }); + it("retains text cells for unchanged files when another file changes", () => { const cache = createDiffDocumentWorkspaceCache(); const { measureText } = countingMeasurer(); diff --git a/packages/app/src/git/diff-document/workspace-cache.tsx b/packages/app/src/git/diff-document/workspace-cache.tsx index 5b9921e31d..dac4d96c2e 100644 --- a/packages/app/src/git/diff-document/workspace-cache.tsx +++ b/packages/app/src/git/diff-document/workspace-cache.tsx @@ -128,7 +128,9 @@ function exactModelKey(input: Omit): s const materializationWindow = input.materializationWindow ? [input.materializationWindow.top, input.materializationWindow.height] : null; - return JSON.stringify([collapsedFilePaths, reviewGeometry, materializationWindow]); + const anchor = input.materializationAnchor; + const anchoredRow = anchor?.kind === "text" ? [anchor.path, anchor.sourceIdentity] : null; + return JSON.stringify([collapsedFilePaths, reviewGeometry, materializationWindow, anchoredRow]); } function typographyKey(typography: DiffTypography): string { From b9f624f72e601b050de54bb5e8544e74883d2c0c Mon Sep 17 00:00:00 2001 From: Dong Hyeon An <71166472+donghyeonan@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:22:15 +0900 Subject: [PATCH 057/173] fix(app): update xterm to prevent shared-atlas glyph corruption (#8013) Use upstream atlas invalidation fixes and cover ordinary output and shared-atlas clearing with real-WebGL pixel regressions.\n\nRelated to #6506; does not close the broader rendering issue. --- package-lock.json | 18 +- packages/app/package.json | 4 +- .../terminal-glyph-rendering.browser.test.ts | 203 ++++++++++++++++++ packages/app/vitest.config.ts | 5 +- 4 files changed, 218 insertions(+), 12 deletions(-) create mode 100644 packages/app/src/terminal/runtime/terminal-glyph-rendering.browser.test.ts diff --git a/package-lock.json b/package-lock.json index ce261ea94d..916df12cc5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -37625,8 +37625,8 @@ "@xterm/addon-search": "^0.17.0-beta.213", "@xterm/addon-unicode11": "^0.10.0-beta.213", "@xterm/addon-web-links": "^0.13.0-beta.213", - "@xterm/addon-webgl": "^0.20.0-beta.212", - "@xterm/xterm": "^6.1.0-beta.213", + "@xterm/addon-webgl": "0.20.0-beta.291", + "@xterm/xterm": "6.1.0-beta.292", "buffer": "^6.0.3", "expo": "~57.0.30", "expo-asset": "~57.0.20", @@ -38535,12 +38535,12 @@ } }, "packages/app/node_modules/@xterm/addon-webgl": { - "version": "0.20.0-beta.212", - "resolved": "https://registry.npmjs.org/@xterm/addon-webgl/-/addon-webgl-0.20.0-beta.212.tgz", - "integrity": "sha512-RzaTYeukTXTJth+Sl7FzCmb8AqiyDrNWNnqG+/300qJbfHYfCMmBlBVZ0yCTSZIWMdgFbgkhmnmBN7Yzs6xoBA==", + "version": "0.20.0-beta.291", + "resolved": "https://registry.npmjs.org/@xterm/addon-webgl/-/addon-webgl-0.20.0-beta.291.tgz", + "integrity": "sha512-gH7r5g8f2NWMhBtaeApuwLQTJmX4uq7zT0okjeNWkFAD0nxzbUPB+kt6sogZZ5K90XYPt2OLu/bhuvF6DmKqOQ==", "license": "MIT", "peerDependencies": { - "@xterm/xterm": "^6.1.0-beta.213" + "@xterm/xterm": "^6.1.0-beta.292" } }, "packages/app/node_modules/@xterm/headless": { @@ -38554,9 +38554,9 @@ ] }, "packages/app/node_modules/@xterm/xterm": { - "version": "6.1.0-beta.213", - "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.1.0-beta.213.tgz", - "integrity": "sha512-bq5nJkgoZDSg6Ma4zgiQ7jlooGNo7U+HDa6vnhx43yXsVEK2laIF7R08bMYAuU0B+C9xX0gwSrcsW18GxjUoJQ==", + "version": "6.1.0-beta.292", + "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.1.0-beta.292.tgz", + "integrity": "sha512-17zqK5tM/l6qeD7McF42OrEJ6w3XqJ2vFVKdWqu0cYLzdFqMWAHp2oFNc8Fj5DmqDSl1E1FZEg6IFflDllTvLA==", "license": "MIT", "workspaces": [ "addons/*" diff --git a/packages/app/package.json b/packages/app/package.json index 3eddd9b53f..6dd914a94f 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -76,8 +76,8 @@ "@xterm/addon-search": "^0.17.0-beta.213", "@xterm/addon-unicode11": "^0.10.0-beta.213", "@xterm/addon-web-links": "^0.13.0-beta.213", - "@xterm/addon-webgl": "^0.20.0-beta.212", - "@xterm/xterm": "^6.1.0-beta.213", + "@xterm/addon-webgl": "0.20.0-beta.291", + "@xterm/xterm": "6.1.0-beta.292", "buffer": "^6.0.3", "expo": "~57.0.30", "expo-asset": "~57.0.20", diff --git a/packages/app/src/terminal/runtime/terminal-glyph-rendering.browser.test.ts b/packages/app/src/terminal/runtime/terminal-glyph-rendering.browser.test.ts new file mode 100644 index 0000000000..35629f01f8 --- /dev/null +++ b/packages/app/src/terminal/runtime/terminal-glyph-rendering.browser.test.ts @@ -0,0 +1,203 @@ +import "@xterm/xterm/css/xterm.css"; +import { page } from "vitest/browser"; +import { afterEach, expect, it } from "vitest"; +import type { Terminal } from "@xterm/xterm"; +import { encodeTerminalOutput, TerminalEmulatorRuntime } from "./terminal-emulator-runtime"; + +interface TerminalView { + root: HTMLDivElement; + host: HTMLDivElement; + runtime: TerminalEmulatorRuntime; + terminal: Terminal; +} + +interface RowImage { + width: number; + height: number; + pixels: Uint8ClampedArray; +} + +const views: TerminalView[] = []; +const header = "HEADER_0123456789 한글 日本語"; + +function mountTerminal(left: number): TerminalView { + const root = document.createElement("div"); + Object.assign(root.style, { + position: "fixed", + left: `${left}px`, + top: "0", + width: "440px", + height: "360px", + overflow: "hidden", + }); + const host = document.createElement("div"); + Object.assign(host.style, { width: "100%", height: "100%" }); + root.appendChild(host); + document.body.appendChild(root); + const runtime = new TerminalEmulatorRuntime(); + runtime.mount({ + root, + host, + initialSnapshot: null, + scrollback: 1000, + fontFamily: "monospace", + fontSize: 16, + theme: { background: "#101010", foreground: "#eeeeee", cursor: "#eeeeee" }, + }); + const terminal = window.__paseoTerminal; + if (!terminal) throw new Error("Terminal did not mount"); + const view = { root, host, runtime, terminal }; + views.push(view); + return view; +} + +function write(view: TerminalView, text: string): Promise { + return new Promise((resolve) => { + view.runtime.write({ data: encodeTerminalOutput(text), onCommitted: resolve }); + }); +} + +function webglCanvas(view: TerminalView): HTMLCanvasElement { + for (const canvas of view.host.querySelectorAll(".xterm-screen canvas")) { + if (canvas instanceof HTMLCanvasElement && canvas.getContext("webgl2")) return canvas; + } + throw new Error("Real WebGL is required; DOM fallback cannot test glyph corruption"); +} + +async function mountPair() { + await page.viewport(1000, 600); + const active = mountTerminal(0); + const sibling = mountTerminal(460); + await document.fonts.ready; + await expect + .poll(() => active.host.querySelectorAll(".xterm-screen canvas").length) + .toBeGreaterThan(0); + await expect + .poll(() => sibling.host.querySelectorAll(".xterm-screen canvas").length) + .toBeGreaterThan(0); + webglCanvas(active); + webglCanvas(sibling); + await write(active, "\x1b[?25l"); + await write(sibling, "\x1b[?25l"); + return { active, sibling }; +} + +function captureHeader(input: { view: TerminalView; output?: string }): Promise { + const { view, output } = input; + return new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + rendered.dispose(); + reject(new Error("Terminal did not render within 2 seconds")); + }, 2000); + const rendered = view.terminal.onRender(() => { + rendered.dispose(); + clearTimeout(timeout); + try { + // Copy during onRender, before WebGL discards its default drawing buffer. + const source = webglCanvas(view); + const canvas = document.createElement("canvas"); + canvas.width = source.width; + canvas.height = Math.round(source.height / view.terminal.rows); + const context = canvas.getContext("2d"); + if (!context) throw new Error("Canvas 2D pixel capture is unavailable"); + context.drawImage(source, 0, 0); + const pixels = context.getImageData(0, 0, canvas.width, canvas.height).data; + resolve({ width: canvas.width, height: canvas.height, pixels }); + } catch (error) { + reject(error); + } + }); + if (output === undefined) view.terminal.refresh(0, view.terminal.rows - 1); + else view.runtime.write({ data: encodeTerminalOutput(output) }); + }); +} + +function expectSamePixels(input: { expected: RowImage; actual: RowImage; label: string }): void { + const { expected, actual, label } = input; + expect(actual.width, label).toBe(expected.width); + expect(actual.height, label).toBe(expected.height); + let changed = 0; + for (let index = 0; index < expected.pixels.length; index += 1) { + if (expected.pixels[index] !== actual.pixels[index]) changed += 1; + } + expect(changed, label).toBe(0); +} + +function coloredOutput(input: { cells: number; offset: number }): string { + const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + let output = ""; + for (let index = 0; index < input.cells; index += 1) { + const value = index + input.offset; + const foreground = `${value % 256};${(value >> 8) % 256};${(value * 13) % 256}`; + const background = (value * 7) % 256; + output += `\x1b[38;2;${foreground}m\x1b[48;5;${background}m${alphabet[value % alphabet.length]}`; + } + return `${output}\x1b[0m`; +} + +afterEach(() => { + for (const view of views.splice(0)) { + view.runtime.unmount(); + view.root.remove(); + } +}); + +it("preserves another terminal's glyph pixels when a shared atlas is cleared", async () => { + const { active, sibling } = await mountPair(); + await write(sibling, header); + const before = await captureHeader({ view: sibling }); + const visibleChannels = before.pixels.filter( + (channel, index) => index % 4 !== 3 && channel > 100, + ); + expect(visibleChannels.length).toBeGreaterThan(100); + + active.terminal.clearTextureAtlas(); + await captureHeader({ view: active, output: coloredOutput({ cells: 2000, offset: 0 }) }); + const after = await captureHeader({ + view: sibling, + output: `\x1b[${sibling.terminal.rows};1Hx`, + }); + expect(sibling.terminal.buffer.active.getLine(0)?.translateToString(true)).toBe(header); + expectSamePixels({ expected: before, actual: after, label: "sibling after atlas clear" }); +}); + +it("preserves both headers while ordinary output grows the shared glyph atlas", async () => { + const { active, sibling } = await mountPair(); + const cells = active.terminal.cols * (active.terminal.rows - 2); + // Startup glyphs can stay on an unmerged page and hide this bug. Allocate the + // reference after some output, as a real long-running TUI does. + for (let batch = 0; batch < 16; batch += 1) { + await captureHeader({ + view: active, + output: `\x1b[H${coloredOutput({ cells, offset: batch * cells })}`, + }); + } + const lateHeader = `\x1b[H\x1b[0m\x1b[2K\x1b[38;2;253;251;247m${header}\x1b[0m`; + await write(active, lateHeader); + await write(sibling, lateHeader); + const activeBefore = await captureHeader({ view: active }); + const siblingBefore = await captureHeader({ view: sibling }); + + for (let batch = 0; batch < 256; batch += 1) { + const activeFrame = await captureHeader({ + view: active, + output: `\x1b[2;1H${coloredOutput({ cells, offset: (batch + 16) * cells })}`, + }); + const siblingFrame = await captureHeader({ + view: sibling, + output: `\x1b[${sibling.terminal.rows};1H${batch % 10}`, + }); + expect(active.terminal.buffer.active.getLine(0)?.translateToString(true)).toBe(header); + expect(sibling.terminal.buffer.active.getLine(0)?.translateToString(true)).toBe(header); + expectSamePixels({ + expected: activeBefore, + actual: activeFrame, + label: `active frame ${batch}`, + }); + expectSamePixels({ + expected: siblingBefore, + actual: siblingFrame, + label: `sibling frame ${batch}`, + }); + } +}, 30000); diff --git a/packages/app/vitest.config.ts b/packages/app/vitest.config.ts index 3254fc5e0c..ae7f935823 100644 --- a/packages/app/vitest.config.ts +++ b/packages/app/vitest.config.ts @@ -96,7 +96,10 @@ export default defineConfig({ include: ["src/**/*.browser.{test,spec}.{ts,tsx}"], browser: { enabled: true, - provider: playwright(), + provider: playwright({ + // Exercise real WebGL glyph rendering on GPU-less CI runners. + launchOptions: { args: ["--enable-unsafe-swiftshader"] }, + }), headless: true, connectTimeout: 180_000, instances: [{ browser: "chromium" }], From 36892d5be772c8364a52a0756e3d450cb83db3dd Mon Sep 17 00:00:00 2001 From: "paseo-ai[bot]" <266920839+paseo-ai[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 09:31:18 +0000 Subject: [PATCH 058/173] fix: update lockfile signatures and Nix hash [skip ci] --- nix/npm-deps.hash | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nix/npm-deps.hash b/nix/npm-deps.hash index bdacb9b93b..baf3a04c95 100644 --- a/nix/npm-deps.hash +++ b/nix/npm-deps.hash @@ -1 +1 @@ -sha256-dk7kJUdmQBF8L8Vkj6Ryza3n4/S+YqgxWY3R59Dc3mY= +sha256-zgyG4roTTTOnNkqOu10gnwwG8GXcjrKH6XlqOvvqKQo= From dc07efe937c3160e8fe83d02dc972c8a0b014957 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 09:53:42 +0000 Subject: [PATCH 059/173] Keep plugin ACP reasoning separate from assistant replies (#7272) * fix(plugin): keep ACP reasoning separate from replies Scope explicit timeline identities by chunk kind so a provider sharing a native message ID cannot merge reasoning into the assistant reply. Preserve the native assistant messageId for consumers. Co-authored-by: Yanlin <127009+cncolder@users.noreply.github.com> * test(plugin): cover kind-qualified ACP history identities --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Yanlin <127009+cncolder@users.noreply.github.com> --- .../src/server/acp-internal/connection.ts | 4 +- packages/plugin/src/server/acp.test.ts | 81 ++++++++++++++++++- 2 files changed, 80 insertions(+), 5 deletions(-) diff --git a/packages/plugin/src/server/acp-internal/connection.ts b/packages/plugin/src/server/acp-internal/connection.ts index b2fbee8e2c..86e22b2afe 100644 --- a/packages/plugin/src/server/acp-internal/connection.ts +++ b/packages/plugin/src/server/acp-internal/connection.ts @@ -997,7 +997,9 @@ class AcpRuntime { ): string { if (messageId) { this.fallbackChunkIds.delete(kind); - return messageId; + // Native IDs identify a message within its chunk kind. Timeline IDs must + // also distinguish reasoning from replies and from generated fallback IDs. + return JSON.stringify([kind, messageId]); } let id = this.fallbackChunkIds.get(kind); if (!id) { diff --git a/packages/plugin/src/server/acp.test.ts b/packages/plugin/src/server/acp.test.ts index f4b429578f..1d99c73a75 100644 --- a/packages/plugin/src/server/acp.test.ts +++ b/packages/plugin/src/server/acp.test.ts @@ -1307,7 +1307,15 @@ describe("runAcpProvider streamed chunks without messageId (#4699)", () => { const items = events.flatMap((event) => event.type === "timeline.item" && (event.item.type === "assistant_message" || event.item.type === "reasoning") - ? [{ id: event.item.id, text: event.item.text }] + ? [ + { + id: event.item.id, + text: event.item.text, + ...(event.item.type === "assistant_message" && event.item.messageId + ? { messageId: event.item.messageId } + : {}), + }, + ] : [], ); expect(items).toEqual([ @@ -1315,7 +1323,11 @@ describe("runAcpProvider streamed chunks without messageId (#4699)", () => { { id: "agent_message_chunk:1", text: "- **Current temperature**: 25°C" }, { id: "agent_message_chunk:2", text: "next turn" }, { id: "agent_thought_chunk:3", text: "think A" }, - { id: "m-explicit", text: "say" }, + { + id: JSON.stringify(["agent_message_chunk", "m-explicit"]), + messageId: "m-explicit", + text: "say", + }, { id: "agent_thought_chunk:4", text: "think B" }, ]); await connection.close(); @@ -1402,6 +1414,21 @@ async function streamChunkTurns( } describe("ACP streamed message boundaries", () => { + it("keeps reasoning separate from a reply sharing its native message ID", async () => { + expect( + await streamChunkTurns([ + textChunk("private ", "agent_thought_chunk", "shared-id"), + textChunk("reasoning", "agent_thought_chunk", "shared-id"), + textChunk("public ", "agent_message_chunk", "shared-id"), + textChunk("reply", "agent_message_chunk", "shared-id"), + ]), + ).toEqual([ + { type: "reasoning", text: "private reasoning" }, + { type: "assistant_message", text: "public reply" }, + { type: "assistant_message", text: "Next turn" }, + ]); + }); + it.each([ { name: "tool call", @@ -1584,8 +1611,12 @@ describe("ACP session history replay", () => { ); try { expect(timelineProjection(events)).toEqual([ - { type: "user_message", id: "user-1", text: "What is the " }, - { type: "user_message", id: "user-1", text: "What is the temperature?" }, + { type: "user_message", id: '["user_message_chunk","user-1"]', text: "What is the " }, + { + type: "user_message", + id: '["user_message_chunk","user-1"]', + text: "What is the temperature?", + }, { type: "reasoning", id: "agent_thought_chunk:1", text: "Checking the sensor" }, { type: "tool_call", id: "tool-1", status: "running" }, { type: "tool_call", id: "tool-1", status: "completed" }, @@ -1599,6 +1630,48 @@ describe("ACP session history replay", () => { } }); + it("keeps replayed user, reasoning and reply chunks separate when their native IDs match", async () => { + const { connection, events } = await openReplaySession( + [ + userChunk("What is the ", "shared-id"), + userChunk("temperature?", "shared-id"), + textChunk("Checking ", "agent_thought_chunk", "shared-id"), + textChunk("the sensor", "agent_thought_chunk", "shared-id"), + textChunk("It is ", "agent_message_chunk", "shared-id"), + textChunk("25°C", "agent_message_chunk", "shared-id"), + ], + "replay", + ); + try { + const items = new Map( + events.flatMap((event) => + event.type === "timeline.item" ? [[event.item.id, event.item] as const] : [], + ), + ); + expect([...items.values()]).toEqual([ + { + type: "user_message", + id: '["user_message_chunk","shared-id"]', + messageId: "shared-id", + text: "What is the temperature?", + }, + { + type: "reasoning", + id: '["agent_thought_chunk","shared-id"]', + text: "Checking the sensor", + }, + { + type: "assistant_message", + id: '["agent_message_chunk","shared-id"]', + messageId: "shared-id", + text: "It is 25°C", + }, + ]); + } finally { + await connection.close(); + } + }); + it("continues anonymous user chunks into one message and starts a new one after an agent reply", async () => { const { connection, events } = await openReplaySession( [ From a8032a1502897c0495610082cabb7718b4bb9ec5 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 10:57:58 +0000 Subject: [PATCH 060/173] fix(app): open outside folder links without breaking Files (#7726) Outside folder links were routed to the workspace-scoped Files explorer, which kept an access error until Retry. Route explicit outside folders to the local file manager or show an outside-workspace message, while preserving existing file and inside-folder behavior. Refs #7513 Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Jacek Tomaszewski --- packages/app/src/agent-stream/view.tsx | 5 ++- .../assistant-file-links/path-open.test.ts | 28 +++++++++++++++ .../app/src/assistant-file-links/path-open.ts | 18 ++++++++-- packages/app/src/i18n/resources/ar.ts | 1 + packages/app/src/i18n/resources/en.ts | 1 + packages/app/src/i18n/resources/es.ts | 1 + packages/app/src/i18n/resources/fr.ts | 1 + packages/app/src/i18n/resources/ja.ts | 1 + packages/app/src/i18n/resources/ko.ts | 1 + packages/app/src/i18n/resources/pt-BR.ts | 1 + packages/app/src/i18n/resources/ru.ts | 1 + packages/app/src/i18n/resources/zh-CN.ts | 1 + .../screens/workspace/workspace-screen.tsx | 11 +++++- .../open-in-file-manager/outside-folder.ts | 36 +++++++++++++++++++ .../features/editor-targets/registry.test.ts | 17 +++++++++ .../src/features/editor-targets/registry.ts | 8 ++++- .../src/features/editor-targets/runtime.ts | 9 +++++ .../src/features/editor-targets/target.ts | 2 ++ 18 files changed, 138 insertions(+), 5 deletions(-) create mode 100644 packages/app/src/workspace/open-in-file-manager/outside-folder.ts diff --git a/packages/app/src/agent-stream/view.tsx b/packages/app/src/agent-stream/view.tsx index 049f0d704b..5d8fe3d913 100644 --- a/packages/app/src/agent-stream/view.tsx +++ b/packages/app/src/agent-stream/view.tsx @@ -90,6 +90,7 @@ import { import { createAssistantImageOccurrenceKey } from "@/assistant-image/acquisition-cache"; import { AssistantSelectionCopySurface } from "@/assistant-selection-copy/surface"; import { AssistantFileLinkResolverProvider, createInlinePathOpener } from "@/assistant-file-links"; +import { useOpenOutsideWorkspaceFolder } from "@/workspace/open-in-file-manager/outside-folder"; import { createWorkspaceFileTabTarget, type WorkspaceFileLocation, @@ -459,6 +460,7 @@ const AgentStreamViewComponent = forwardRef createInlinePathOpener({ @@ -466,8 +468,9 @@ const AgentStreamViewComponent = forwardRef { if (!isActive) inlinePathOpener.cancel(); diff --git a/packages/app/src/assistant-file-links/path-open.test.ts b/packages/app/src/assistant-file-links/path-open.test.ts index a046a598f6..a85d4c8ec0 100644 --- a/packages/app/src/assistant-file-links/path-open.test.ts +++ b/packages/app/src/assistant-file-links/path-open.test.ts @@ -71,6 +71,9 @@ it("ignores an older probe after a newer file link opens", async () => { openDirectory: (directory) => { opened.push(directory); }, + openOutsideDirectory: (directory) => { + opened.push(directory); + }, }); const first = opener.open({ raw: "./first.md", path: "/repo/first.md" }, "preferred"); await opener.open({ raw: "./second.md:2", path: "/repo/second.md", lineStart: 2 }, "preferred"); @@ -95,6 +98,9 @@ it("ignores a pending probe when its view is left", async () => { openDirectory: (directory) => { opened.push(directory); }, + openOutsideDirectory: (directory) => { + opened.push(directory); + }, }); const pending = opener.open({ raw: "./docs", path: "/repo/docs" }, "preferred"); opener.cancel(); @@ -102,3 +108,25 @@ it("ignores a pending probe when its view is left", async () => { await pending; expect(opened).toEqual([]); }); + +it("sends folders outside the workspace away from the workspace Files panel", async () => { + const { createInlinePathOpener } = await import("./path-open"); + const workspaceFolders: string[] = []; + const outsideFolders: string[] = []; + const opener = createInlinePathOpener({ + workspaceRoot: "/Users/me/repo", + client: null, + openFile: () => {}, + openDirectory: (directory) => { + workspaceFolders.push(directory); + }, + openOutsideDirectory: (directory) => { + outsideFolders.push(directory); + }, + }); + for (const raw of ["~/Downloads/contracts/", "/tmp/reports/", "/Users/me/repo/docs/"]) { + await opener.open({ raw, path: raw }, "preferred"); + } + expect(outsideFolders).toEqual(["~/Downloads/contracts", "/tmp/reports"]); + expect(workspaceFolders).toEqual(["docs"]); +}); diff --git a/packages/app/src/assistant-file-links/path-open.ts b/packages/app/src/assistant-file-links/path-open.ts index b3d2178165..7c9cf228f4 100644 --- a/packages/app/src/assistant-file-links/path-open.ts +++ b/packages/app/src/assistant-file-links/path-open.ts @@ -14,12 +14,23 @@ interface PathOpenInput { client: { listDirectory(root: string, path: string): Promise } | null; } -type PathOpenTarget = { kind: "file" } | { kind: "directory"; directoryPath: string }; +type PathOpenTarget = + | { kind: "file" } + | { kind: "directory"; directoryPath: string } + | { kind: "outsideDirectory"; directoryPath: string }; + +// Workspace paths arrive relative to the root; anything still absolute or +// home-relative lives outside it, where the Files panel cannot list it. +function isOutsideWorkspacePath(pathValue: string): boolean { + return isAbsolutePath(pathValue) || pathValue === "~" || pathValue.startsWith("~/"); +} /** Resolve workspace folders from filesystem facts, including names that contain dots. */ export async function resolveInlinePathOpen(input: PathOpenInput): Promise { if (!input.file) { - return { kind: "directory", directoryPath: input.directory }; + return isOutsideWorkspacePath(input.directory) + ? { kind: "outsideDirectory", directoryPath: input.directory } + : { kind: "directory", directoryPath: input.directory }; } if ( input.lineStart !== undefined || @@ -42,6 +53,7 @@ export function createInlinePathOpener(input: { client: PathOpenInput["client"]; openFile: (location: WorkspaceFileLocation, disposition: OpenFileDisposition) => void; openDirectory: (path: string) => void; + openOutsideDirectory: (path: string) => void; }) { let generation = 0; return { @@ -58,6 +70,8 @@ export function createInlinePathOpener(input: { if (ownGeneration !== generation) return; if (destination.kind === "directory") { input.openDirectory(destination.directoryPath); + } else if (destination.kind === "outsideDirectory") { + input.openOutsideDirectory(destination.directoryPath); } else if (normalized.file) { const location = normalizeWorkspaceFileLocation({ path: normalized.file, diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index 49e8a1669a..3928da7e68 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -67,6 +67,7 @@ export const ar: TranslationResources = { daemonClientUnavailable: "عميل Daemon غير متوفر", daemonClientDisconnected: "تم قطع اتصال عميل Daemon", noFileFound: "لم يتم العثور على ملف لـ{{token}}", + folderOutsideWorkspace: "{{path}} خارج مساحة العمل هذه", unexpectedDictationError: "حدث خطأ غير متوقع أثناء معالجة الإملاء.", }, connectionStatus: { diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index 1ae0e3a363..e7ed75e509 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -63,6 +63,7 @@ export const en = { daemonClientUnavailable: "Daemon client unavailable", daemonClientDisconnected: "Daemon client is disconnected", noFileFound: "No file found for {{token}}", + folderOutsideWorkspace: "{{path}} is outside this workspace", unexpectedDictationError: "An unexpected error occurred while handling dictation.", }, connectionStatus: { diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index 6b99c229fe..7cf68c69ba 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -68,6 +68,7 @@ export const es: TranslationResources = { daemonClientUnavailable: "ClienteDaemonno disponible", daemonClientDisconnected: "El clienteDaemonestá desconectado", noFileFound: "No se encontró ningún archivo para{{token}}", + folderOutsideWorkspace: "{{path}} está fuera de este espacio de trabajo", unexpectedDictationError: "Se produjo un error inesperado al manejar el dictado.", }, connectionStatus: { diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index 927237900c..da58636a70 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -68,6 +68,7 @@ export const fr: TranslationResources = { daemonClientUnavailable: "Client du daemon indisponible", daemonClientDisconnected: "Le client du daemon est déconnecté", noFileFound: "Aucun fichier trouvé pour {{token}}", + folderOutsideWorkspace: "{{path}} se trouve en dehors de cet espace de travail", unexpectedDictationError: "Une erreur inattendue s’est produite pendant la dictée.", }, connectionStatus: { diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index 494714ebca..cd327a6bb5 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -68,6 +68,7 @@ export const ja: TranslationResources = { daemonClientUnavailable: "デーモンクライアントが利用できません", daemonClientDisconnected: "デーモンクライアントが切断されています", noFileFound: "{{token}}のファイルが見つかりません", + folderOutsideWorkspace: "{{path}} はこのワークスペースの外にあります", unexpectedDictationError: "音声入力処理中に予期しないエラーが発生しました。", }, connectionStatus: { diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index d6777add4a..aad8d5e0cb 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -67,6 +67,7 @@ export const ko: TranslationResources = { daemonClientUnavailable: "데몬 클라이언트를 사용할 수 없습니다", daemonClientDisconnected: "데몬 클라이언트 연결이 끊어졌습니다", noFileFound: "{{token}}에 해당하는 파일을 찾을 수 없습니다", + folderOutsideWorkspace: "{{path}}은(는) 이 워크스페이스 밖에 있습니다", unexpectedDictationError: "받아쓰기를 처리하는 중 예기치 않은 오류가 발생했습니다.", }, connectionStatus: { diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index ce1a3b01c8..696cb86b17 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -68,6 +68,7 @@ export const ptBR: TranslationResources = { daemonClientUnavailable: "Cliente do daemon indisponível", daemonClientDisconnected: "O cliente do daemon está desconectado", noFileFound: "Nenhum arquivo encontrado para {{token}}", + folderOutsideWorkspace: "{{path}} está fora deste workspace", unexpectedDictationError: "Ocorreu um erro inesperado ao processar o ditado.", }, connectionStatus: { diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index cfc7954abf..ab1405852a 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -68,6 +68,7 @@ export const ru: TranslationResources = { daemonClientUnavailable: "Daemon клиента недоступен", daemonClientDisconnected: "Daemon клиента отключен", noFileFound: "Файл для {{token}} не найден", + folderOutsideWorkspace: "{{path}} находится вне этого рабочего пространства", unexpectedDictationError: "При обработке диктовки произошла непредвиденная ошибка.", }, connectionStatus: { diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index 5a08f1ea40..da97288cf4 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -67,6 +67,7 @@ export const zhCN: TranslationResources = { daemonClientUnavailable: "Daemon client 不可用", daemonClientDisconnected: "Daemon client 已断开连接", noFileFound: "未找到 {{token}} 对应的文件", + folderOutsideWorkspace: "{{path}} 不在此工作区内", unexpectedDictationError: "处理听写时发生意外错误。", }, connectionStatus: { diff --git a/packages/app/src/screens/workspace/workspace-screen.tsx b/packages/app/src/screens/workspace/workspace-screen.tsx index 1746c50653..d1b3fd3e9a 100644 --- a/packages/app/src/screens/workspace/workspace-screen.tsx +++ b/packages/app/src/screens/workspace/workspace-screen.tsx @@ -64,6 +64,7 @@ import { WorkspaceScriptsButton } from "@/screens/workspace/scripts"; import { ImportSessionSheet } from "@/components/import-session-sheet"; import { useNavigateToImportedAgent } from "@/hooks/use-import-session"; import { useToast } from "@/contexts/toast-context"; +import { useOpenOutsideWorkspaceFolder } from "@/workspace/open-in-file-manager/outside-folder"; import { getOrCreateClientId } from "@/utils/client-id"; import { selectIsAgentListOpen, usePanelStore } from "@/stores/panel-store"; import { toggleDesktopSidebarsWithCheckoutIntent } from "@/utils/desktop-sidebar-toggle"; @@ -3682,6 +3683,7 @@ function WorkspaceScreenContent({ view: "files", }); }); + const openMarkdownOutsideDirectory = useOpenOutsideWorkspaceFolder(normalizedServerId); const markdownPathOpener = useMemo( () => createInlinePathOpener({ @@ -3689,8 +3691,15 @@ function WorkspaceScreenContent({ client, openFile: openMarkdownFile, openDirectory: openMarkdownDirectory, + openOutsideDirectory: openMarkdownOutsideDirectory, }), - [workspaceDirectory, client, openMarkdownFile, openMarkdownDirectory], + [ + workspaceDirectory, + client, + openMarkdownFile, + openMarkdownDirectory, + openMarkdownOutsideDirectory, + ], ); useEffect(() => { if (!isRouteFocused) markdownPathOpener.cancel(); diff --git a/packages/app/src/workspace/open-in-file-manager/outside-folder.ts b/packages/app/src/workspace/open-in-file-manager/outside-folder.ts new file mode 100644 index 0000000000..e7d41d72d9 --- /dev/null +++ b/packages/app/src/workspace/open-in-file-manager/outside-folder.ts @@ -0,0 +1,36 @@ +import { useCallback } from "react"; +import { useTranslation } from "react-i18next"; +import { useToast } from "@/contexts/toast-context"; +import { useIsLocalDaemon } from "@/hooks/use-is-local-daemon"; +import { openDesktopTarget, useDesktopOpenTargets } from "@/workspace/desktop-open-targets"; + +/** + * Opens a folder outside the workspace in the system file manager. The Files + * panel only lists the workspace, so hosts without a local file manager get a + * toast instead. + */ +export function useOpenOutsideWorkspaceFolder(serverId: string): (folderPath: string) => void { + const { t } = useTranslation(); + const toast = useToast(); + const isLocalExecution = useIsLocalDaemon(serverId); + const { targets } = useDesktopOpenTargets({ isLocalExecution }); + const fileManagerTarget = targets.find((target) => target.kind === "file-manager"); + + return useCallback( + (folderPath: string) => { + const showOutsideWorkspace = () => + toast.show(t("common.errors.folderOutsideWorkspace", { path: folderPath })); + if (!fileManagerTarget) { + showOutsideWorkspace(); + return; + } + void openDesktopTarget({ editorId: fileManagerTarget.id, workspacePath: folderPath }).catch( + (error: unknown) => { + console.warn("[open-outside-workspace-folder] open failed", error); + showOutsideWorkspace(); + }, + ); + }, + [fileManagerTarget, t, toast], + ); +} diff --git a/packages/desktop/src/features/editor-targets/registry.test.ts b/packages/desktop/src/features/editor-targets/registry.test.ts index 4d8c4d80c7..0a6ae12328 100644 --- a/packages/desktop/src/features/editor-targets/registry.test.ts +++ b/packages/desktop/src/features/editor-targets/registry.test.ts @@ -86,6 +86,10 @@ class FakeEditorTargets implements EditorTargetRuntime { return this.paths.has(targetPath); } + expandHomePath(targetPath: string): string { + return targetPath.startsWith("~/") ? `/home/me/${targetPath.slice(2)}` : targetPath; + } + isAbsolutePath(targetPath: string): boolean { return targetPath.startsWith("/") || /^[A-Z]:\//u.test(targetPath); } @@ -513,6 +517,19 @@ describe("editor target registry", () => { expect(runtime.revealedPaths).toEqual(["C:/repo/src/app.ts"]); }); + it("opens a home-relative folder in the file manager", async () => { + const runtime = new FakeEditorTargets(); + runtime.addPath("/home/me/Downloads/contracts"); + + await openEditorTarget( + { editorId: "file-manager", workspacePath: "~/Downloads/contracts" }, + runtime, + [fileManagerTarget], + ); + + expect(runtime.openedPaths).toEqual(["/home/me/Downloads/contracts"]); + }); + it("keeps the platform file-manager ids used by stored preferences", async () => { const macTargets = await listAvailableEditorTargets(new FakeEditorTargets("darwin"), [ finderTarget, diff --git a/packages/desktop/src/features/editor-targets/registry.ts b/packages/desktop/src/features/editor-targets/registry.ts index 1e589f7a64..99a8e8d461 100644 --- a/packages/desktop/src/features/editor-targets/registry.ts +++ b/packages/desktop/src/features/editor-targets/registry.ts @@ -97,10 +97,16 @@ export function getEditorTarget( } export async function openEditorTarget( - input: EditorTargetLaunchInput & { editorId: string }, + request: EditorTargetLaunchInput & { editorId: string }, runtime: EditorTargetRuntime, targets: readonly EditorTarget[] = EDITOR_TARGETS, ): Promise { + // Assistant replies name folders like `~/Downloads/x`; expand them before the absolute-path guard. + const input = { + ...request, + workspacePath: runtime.expandHomePath(request.workspacePath), + filePath: request.filePath === undefined ? undefined : runtime.expandHomePath(request.filePath), + }; if (!runtime.isAbsolutePath(input.workspacePath)) { throw new Error("Editor target workspace path must be an absolute local path"); } diff --git a/packages/desktop/src/features/editor-targets/runtime.ts b/packages/desktop/src/features/editor-targets/runtime.ts index 9562b27977..36bfac0e65 100644 --- a/packages/desktop/src/features/editor-targets/runtime.ts +++ b/packages/desktop/src/features/editor-targets/runtime.ts @@ -61,6 +61,14 @@ function isAbsolutePath(value: string, platform: NodeJS.Platform): boolean { return platform === "win32" ? win32.isAbsolute(value) : posix.isAbsolute(value); } +function expandHomePath(value: string, homeDirectory: string): string { + if (value === "~") return homeDirectory; + if (value.startsWith("~/") || value.startsWith("~\\")) { + return path.join(homeDirectory, value.slice(2)); + } + return value; +} + function resolveExecutable( commands: readonly string[], input: { @@ -166,6 +174,7 @@ export function createEditorTargetRuntime( pathExists, isAbsolutePath: (targetPath) => isAbsolutePath(targetPath, platform), listDirectory, + expandHomePath: (targetPath) => expandHomePath(targetPath, homeDirectory), resolveCommand: (commands) => resolveExecutable(commands, { env, pathExists, platform }), async spawnDetached({ command, args }) { const commandScript = isWindowsCommandScript(command, platform); diff --git a/packages/desktop/src/features/editor-targets/target.ts b/packages/desktop/src/features/editor-targets/target.ts index f7111662c5..b6a9f93668 100644 --- a/packages/desktop/src/features/editor-targets/target.ts +++ b/packages/desktop/src/features/editor-targets/target.ts @@ -30,6 +30,8 @@ export interface EditorTargetRuntime { pathExists(path: string): boolean; isAbsolutePath(path: string): boolean; listDirectory(path: string): EditorTargetDirectoryEntry[]; + /** Resolves a leading `~` to the user's home directory. */ + expandHomePath(path: string): string; resolveCommand(commands: readonly string[]): string | null; spawnDetached(input: { command: string; args: readonly string[] }): Promise; openPath(path: string): Promise; From 694696e82c35f57c21f4d5116f836673d0edeed3 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:00:55 +0000 Subject: [PATCH 061/173] fix(server): keep background Git fetches from opening login prompts (#8019) * fix(server): keep background Git fetches from opening login prompts Git tries graphical askpass before consulting GIT_TERMINAL_PROMPT, so passive fetches repeatedly opened a login despite terminal prompting being disabled. Disable askpass and credential-manager interaction for this fetch while preserving stored credential lookup. * test(server): make fetch and ACP expectations match supported Git and timeline behavior Newer Git also creates origin/HEAD on the first fetch, so assert the authenticated branch result without excluding that valid additional ref. Main now qualifies ACP timeline identities by chunk kind while preserving the native messageId; update the plugin round-trip test to check that contract. --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../src/server/plugins/runtime.posix.test.ts | 3 +- .../src/server/workspace-git-fetch.test.ts | 144 +++++++++++++++++- .../server/src/server/workspace-git-fetch.ts | 4 +- 3 files changed, 146 insertions(+), 5 deletions(-) diff --git a/packages/server/src/server/plugins/runtime.posix.test.ts b/packages/server/src/server/plugins/runtime.posix.test.ts index 30ada955a6..a777ff188e 100644 --- a/packages/server/src/server/plugins/runtime.posix.test.ts +++ b/packages/server/src/server/plugins/runtime.posix.test.ts @@ -651,7 +651,8 @@ lines.on("line", (line) => { type: "timeline.item", item: expect.objectContaining({ type: "assistant_message", - id: "assistant-1", + id: JSON.stringify(["agent_message_chunk", "assistant-1"]), + messageId: "assistant-1", text: "ACP says hi", }), }), diff --git a/packages/server/src/server/workspace-git-fetch.test.ts b/packages/server/src/server/workspace-git-fetch.test.ts index 29a95b64d8..de9e69959e 100644 --- a/packages/server/src/server/workspace-git-fetch.test.ts +++ b/packages/server/src/server/workspace-git-fetch.test.ts @@ -1,4 +1,8 @@ import { describe, expect, test } from "vitest"; +import { createServer } from "node:http"; +import { mkdtemp, readFile, writeFile, rm, chmod } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { diffWorkspaceGitRefs, @@ -6,14 +10,21 @@ import { fetchWorkspaceGitRemote, parseWorkspaceGitRefs, } from "./workspace-git-fetch.js"; -import type { RunGitCommand } from "../utils/run-git-command.js"; +import { runGitCommand, type RunGitCommand } from "../utils/run-git-command.js"; describe("workspace Git remote refs", () => { test("runs the complete fetch through the supplied Git runner", async () => { const commands: string[][] = []; let refRead = 0; - const runGitCommand: RunGitCommand = async (args) => { + const run: RunGitCommand = async (args, options) => { commands.push(args); + if (args[0] === "fetch") { + expect(options.envOverlay).toEqual({ + GIT_TERMINAL_PROMPT: "0", + GIT_ASKPASS: "", + GCM_INTERACTIVE: "0", + }); + } const stdout = args[0] === "for-each-ref" ? `refs/remotes/origin/main\0${refRead++ === 0 ? "aaaaaaaa" : "bbbbbbbb"}` @@ -22,7 +33,7 @@ describe("workspace Git remote refs", () => { }; await expect( - fetchWorkspaceGitRemote("/repo", { onRefSnapshot() {} }, runGitCommand), + fetchWorkspaceGitRemote("/repo", { onRefSnapshot() {} }, run), ).resolves.toMatchObject({ changes: [ { @@ -109,3 +120,130 @@ describe("workspace Git remote refs", () => { ]); }); }); + +// Serve a real bare repository over Git's dumb HTTP transport, behind Basic authentication. +// Both the authentication challenge and successful fetch exercise Git itself. +async function withAuthenticatedRemote( + verify: (fixture: { + cwd: string; + run: RunGitCommand; + root: string; + origin: string; + expectedOid: string; + }) => Promise, +): Promise { + const root = await mkdtemp(join(tmpdir(), "paseo-fetch-auth-")); + const cwd = join(root, "checkout"); + const remote = join(root, "remote.git"); + const emptyConfig = join(root, "gitconfig"); + const askpass = join(root, "askpass.sh"); + const marker = join(root, "prompts"); + await writeFile(emptyConfig, ""); + await writeFile( + askpass, + `#!/bin/sh\nprintf 'prompt\\n' >> '${marker.replaceAll("'", "'\\''")}'\nexit 1\n`, + ); + await chmod(askpass, 0o755); + const askpassCommand = askpass; + const run: RunGitCommand = (args, options) => + runGitCommand(args, { + ...options, + env: { + ...options.env, + GIT_CONFIG_GLOBAL: emptyConfig, + GIT_CONFIG_NOSYSTEM: "1", + GIT_ASKPASS: askpassCommand, + SSH_ASKPASS: askpassCommand, + }, + }); + const server = createServer(async (request, response) => { + if ( + request.headers.authorization !== `Basic ${Buffer.from("fixture:secret").toString("base64")}` + ) { + response.writeHead(401, { "WWW-Authenticate": 'Basic realm="git-test"' }); + response.end(); + return; + } + const pathname = new URL(request.url!, "http://localhost").pathname; + try { + const contents = await readFile(join(root, pathname)); + response.writeHead(200, { "Content-Type": "application/octet-stream" }); + response.end(contents); + } catch { + response.writeHead(404); + response.end(); + } + }); + try { + await run(["init", "--initial-branch=main", cwd], { cwd: root }); + await run( + [ + "-c", + "user.name=Fixture", + "-c", + "user.email=fixture@example.invalid", + "commit", + "--allow-empty", + "-m", + "initial", + ], + { cwd }, + ); + await run(["clone", "--bare", cwd, remote], { cwd: root }); + await run(["update-server-info"], { cwd: remote }); + await run(["config", "credential.helper", ""], { cwd }); + await run(["config", "core.askPass", askpassCommand], { cwd }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Expected TCP server"); + const origin = `http://127.0.0.1:${address.port}/remote.git`; + await run(["remote", "add", "origin", origin], { cwd }); + const expectedOid = (await run(["rev-parse", "HEAD"], { cwd })).stdout.trim(); + await verify({ cwd, run, root, origin, expectedOid }); + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); + } +} + +test.skipIf(process.platform === "win32")( + "background fetches never invoke askpass when credentials are missing", + async () => { + await withAuthenticatedRemote(async ({ cwd, run, root }) => { + for (let attempt = 0; attempt < 2; attempt++) { + const result = await fetchWorkspaceGitRemote(cwd, { onRefSnapshot() {} }, run); + expect(String(result.error)).toContain("terminal prompts disabled"); + } + await expect(readFile(join(root, "prompts"), "utf8")).rejects.toMatchObject({ + code: "ENOENT", + }); + }); + }, +); + +test.skipIf(process.platform === "win32")( + "background fetches still use stored credentials", + async () => { + await withAuthenticatedRemote(async ({ cwd, run, root, origin, expectedOid }) => { + const credentials = join(root, "credentials"); + await writeFile(credentials, origin.replace("http://", "http://fixture:secret@") + "\n"); + await run(["config", "credential.helper", `store --file="${credentials}"`], { cwd }); + + const result = await fetchWorkspaceGitRemote(cwd, { onRefSnapshot() {} }, run); + + expect(result.error).toBeNull(); + expect(result.changes).toContainEqual({ + kind: "added", + ref: "origin/main", + afterOid: expectedOid, + }); + expect((await run(["rev-parse", "refs/remotes/origin/main"], { cwd })).stdout.trim()).toBe( + expectedOid, + ); + await expect(readFile(join(root, "prompts"), "utf8")).rejects.toMatchObject({ + code: "ENOENT", + }); + }); + }, +); diff --git a/packages/server/src/server/workspace-git-fetch.ts b/packages/server/src/server/workspace-git-fetch.ts index 72f5d407da..5673600d23 100644 --- a/packages/server/src/server/workspace-git-fetch.ts +++ b/packages/server/src/server/workspace-git-fetch.ts @@ -33,7 +33,9 @@ export async function fetchWorkspaceGitRemote( try { await run(["fetch", "origin", "--prune"], { cwd, - envOverlay: { GIT_TERMINAL_PROMPT: "0" }, + // Terminal prompting and graphical credential prompting have separate controls. + // Keep cached credentials available, but never start a login from a passive fetch. + envOverlay: { GIT_TERMINAL_PROMPT: "0", GIT_ASKPASS: "", GCM_INTERACTIVE: "0" }, timeout: 120_000, }); } catch (caught) { From 1b8dbc38ab8a53b72663b337fcdbd3724313ac57 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Tue, 27 Oct 2026 19:25:13 +0700 Subject: [PATCH 062/173] fix(app): preserve chat reading position across older pages (#8026) * fix(app): preserve reading position when older turns fold Item-based history pages can complete and collapse the row at the reading position. Transfer its anchor to the folded turn host so reaching history start does not drain older pages. Also omit reasoning from action summaries and align sender attribution with its message bubble. * fix(app): preserve the reader when older pages extend tool groups Resolve grouped calls and folded turns through one presentation-owned row lookup. Keep retained group indexing off the streaming path and verify item-page group replacement against its failing baseline. * fix(app): preserve message previews when opening turns Keep the wrapper child structure stable so React does not remount the message fragment when the indent rail appears. Remounting reset preview measurements and briefly removed the fade and Show more control. * fix(app): separate show less from expanded message text --- .../browser/agent-timeline-pagination.spec.ts | 30 ++++ .../owned-subscriptions-old-daemon.spec.ts | 150 ++++++++++++---- .../app/e2e/browser/turn-collapse.spec.ts | 134 +++++++++++++- .../support/helpers/agent-timeline-gate.ts | 26 ++- .../support/helpers/timeline-pagination.ts | 167 +++++++++++++++++- .../app/src/agent-stream/presentation.test.ts | 47 +++++ packages/app/src/agent-stream/presentation.ts | 61 +++++-- .../src/agent-stream/reading-anchor.test.ts | 18 ++ .../app/src/agent-stream/reading-anchor.ts | 26 ++- .../app/src/agent-stream/strategy-web.tsx | 23 ++- packages/app/src/agent-stream/strategy.ts | 3 + .../agent-stream/turn-collapse/model.test.ts | 8 + .../src/agent-stream/turn-collapse/model.ts | 6 + packages/app/src/agent-stream/view.tsx | 4 +- .../app/src/components/user-message/index.tsx | 5 +- .../tool-calls/detail-level/overview/label.ts | 4 +- 16 files changed, 642 insertions(+), 70 deletions(-) diff --git a/packages/app/e2e/browser/agent-timeline-pagination.spec.ts b/packages/app/e2e/browser/agent-timeline-pagination.spec.ts index f2772b0b1b..57ee050fa4 100644 --- a/packages/app/e2e/browser/agent-timeline-pagination.spec.ts +++ b/packages/app/e2e/browser/agent-timeline-pagination.spec.ts @@ -27,6 +27,10 @@ import { seedRealisticOlderTimeline, sendLiveTurnBeforeHydration, expectTimelineViewportAnchoredAfterPrepend, + expectToolCallGroupPositionPreserved, + rememberToolCallGroupPosition, + seedItemPagedToolGroupTimeline, + useChatDisplay, userNavigatesTimelineToHistoryStartWithKeyboard, userScrollsTimelineToHistoryStart, } from "../support/helpers/timeline-pagination"; @@ -100,6 +104,32 @@ test.describe("Agent timeline pagination", () => { } }); + // Hosts paged by items can end a page inside a tool run. The older page extends the group + // the reader is on, which changes the row hosting it; the reader must stay with that group + // rather than land at history start and drain every older page. + test("keeps the reading position when an older item page extends the tool-call group being read", async ({ + page, + }) => { + test.setTimeout(120_000); + await useChatDisplay(page, "collapseToolCalls"); + const agent = await seedItemPagedToolGroupTimeline(); + try { + const history = await holdOlderHistoryPages(page, agent, { itemPagedHost: true }); + await openAgentTimeline(page, agent); + await expectTimelinePromptVisible(page, agent.newestPrompt); + + await userScrollsTimelineToHistoryStart(page); + await history.expectRequestedPages(1); + const reading = await rememberToolCallGroupPosition(page, agent.loadedCommands); + + history.releasePage(1); + await expectToolCallGroupPositionPreserved(page, agent.totalCommands, reading); + await history.expectSettledWithRequestedPages(1); + } finally { + await agent.cleanup(); + } + }); + test("loads older history when the user navigates to history start with the keyboard", async ({ page, }) => { diff --git a/packages/app/e2e/browser/owned-subscriptions-old-daemon.spec.ts b/packages/app/e2e/browser/owned-subscriptions-old-daemon.spec.ts index 1fdef794a0..5f1f36e409 100644 --- a/packages/app/e2e/browser/owned-subscriptions-old-daemon.spec.ts +++ b/packages/app/e2e/browser/owned-subscriptions-old-daemon.spec.ts @@ -5,22 +5,86 @@ import { getTerminalBufferText, } from "../support/helpers/terminal-perf"; import { buildHostWorkspaceRoute } from "../../src/utils/host-routes"; -import { metroTest as test, expect } from "../support/fixtures"; +import { metroTest as test, expect, type Page } from "../support/fixtures"; import { buildCreateAgentPreferences, buildSeededHost } from "../support/helpers/daemon-registry"; import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon"; import type { MockAgentWorkspace } from "../support/helpers/mock-agent"; import { seedWorkspace } from "../support/helpers/seed-client"; import { + expectFoldedTurnAtReadingPosition, + expectOldestLoadedTurnPartial, + holdOlderHistoryPages, openAgentTimeline, expectTimelinePromptVisible, + userScrollsTimelineToHistoryStart, } from "../support/helpers/timeline-pagination"; +interface PublishedDaemonAgent { + serverId: string; + daemon: Awaited>; + agent: MockAgentWorkspace; + /** Register the host in the browser and apply app settings before the first load. */ + seedBrowser(page: Page, appSettings?: Record): Promise; + close(): Promise; +} + +async function startPublishedDaemonAgent(options: { + publishedVersion: string; + serverIdPrefix: string; + repoPrefix: string; + title: string; +}): Promise { + const serverId = `${options.serverIdPrefix}${randomUUID().replaceAll("-", "").slice(0, 12)}`; + const daemon = await startIsolatedHostDaemon(serverId, { + publishedVersion: options.publishedVersion, + }); + const workspace = await seedWorkspace({ repoPrefix: options.repoPrefix, port: daemon.port }); + const createdAgent = await workspace.client.createAgent({ + provider: "mock", + cwd: workspace.repoPath, + workspaceId: workspace.workspaceId, + title: options.title, + modeId: "load-test", + model: "ten-second-stream", + }); + const agent: MockAgentWorkspace = { + agentId: createdAgent.id, + workspaceId: workspace.workspaceId, + cwd: workspace.repoPath, + client: workspace.client, + cleanup: workspace.cleanup, + }; + return { + serverId, + daemon, + agent, + async seedBrowser(page, appSettings) { + const host = buildSeededHost({ + serverId, + endpoint: `127.0.0.1:${daemon.port}`, + nowIso: new Date().toISOString(), + }); + await page.addInitScript( + ({ seededHost, preferences, settings }) => { + localStorage.setItem("@paseo:e2e", "1"); + localStorage.setItem("@paseo:daemon-registry", JSON.stringify([seededHost])); + localStorage.setItem("@paseo:create-agent-preferences", JSON.stringify(preferences)); + if (settings) localStorage.setItem("@paseo:app-settings", JSON.stringify(settings)); + }, + { seededHost: host, preferences: buildCreateAgentPreferences(), settings: appSettings }, + ); + }, + async close() { + await agent.cleanup(); + await daemon.close(); + }, + }; +} + test("loads history across browser reconnection while retaining old-daemon connections and terminals", async ({ page, }) => { test.setTimeout(120_000); - const serverId = `srv_old_pagination_${randomUUID().replaceAll("-", "").slice(0, 12)}`; - const daemon = await startIsolatedHostDaemon(serverId, { publishedVersion: "0.2.5" }); const observationSockets = new Set(); page.on("websocket", (socket) => { socket.on("framesent", ({ payload }) => { @@ -34,43 +98,18 @@ test("loads history across browser reconnection while retaining old-daemon conne observationSockets.add(socket); }); }); - const workspace = await seedWorkspace({ + const published = await startPublishedDaemonAgent({ + publishedVersion: "0.2.5", + serverIdPrefix: "srv_old_pagination_", repoPrefix: "timeline-old-daemon-pagination-", - port: daemon.port, - }); - const createdAgent = await workspace.client.createAgent({ - provider: "mock", - cwd: workspace.repoPath, - workspaceId: workspace.workspaceId, title: "Published daemon pagination regression", - modeId: "load-test", - model: "ten-second-stream", }); - const agent: MockAgentWorkspace = { - agentId: createdAgent.id, - workspaceId: workspace.workspaceId, - cwd: workspace.repoPath, - client: workspace.client, - cleanup: workspace.cleanup, - }; + const { agent, serverId } = published; try { await agent.client.sendAgentMessage(agent.agentId, "emit 1 coalesced agent stream updates"); await agent.client.waitForFinish(agent.agentId, 15_000); - - const host = buildSeededHost({ - serverId, - endpoint: `127.0.0.1:${daemon.port}`, - nowIso: new Date().toISOString(), - }); - await page.addInitScript( - ({ seededHost, preferences }) => { - localStorage.setItem("@paseo:e2e", "1"); - localStorage.setItem("@paseo:daemon-registry", JSON.stringify([seededHost])); - localStorage.setItem("@paseo:create-agent-preferences", JSON.stringify(preferences)); - }, - { seededHost: host, preferences: buildCreateAgentPreferences() }, - ); + await published.seedBrowser(page); await openAgentTimeline(page, agent, serverId); await expectTimelinePromptVisible(page, "emit 1 coalesced agent stream updates"); @@ -87,7 +126,7 @@ test("loads history across browser reconnection while retaining old-daemon conne const terminal = await agent.client.createTerminal(agent.cwd, "Compatibility terminal"); expect(terminal.error).toBeNull(); const terminalId = terminal.terminal!.id; - const route = buildHostWorkspaceRoute(serverId, workspace.workspaceId); + const route = buildHostWorkspaceRoute(serverId, agent.workspaceId); await page.goto(`${route}?open=${encodeURIComponent(`terminal:${terminalId}`)}`); await focusTerminalSurface(page); await typeInTerminal(page, "printf 'compatibility-%s\\n' terminal-output\n"); @@ -97,7 +136,46 @@ test("loads history across browser reconnection while retaining old-daemon conne await agent.client.killTerminal(terminalId); }); } finally { - await agent.cleanup(); - await daemon.close(); + await published.close(); + } +}); + +// Hosts without whole-turn pages split turns across item pages. The oldest loaded turn +// starts mid-turn and only folds once the next page completes it; the reader must stay +// with that turn instead of landing at history start and draining every older page. +test("keeps the reader on the turn that folds when an older item page completes it", async ({ + page, +}) => { + test.setTimeout(240_000); + const published = await startPublishedDaemonAgent({ + publishedVersion: "0.13.0-beta.2", + serverIdPrefix: "srv_old_fold_", + repoPrefix: "timeline-old-daemon-fold-", + title: "Published daemon folded turn pagination", + }); + const { agent, serverId } = published; + const prompts = Array.from({ length: 5 }, (_, index) => `Realistic turn ${index}: inspect it`); + + try { + for (const prompt of prompts) { + await agent.client.sendAgentMessage(agent.agentId, prompt); + await agent.client.waitForFinish(agent.agentId, 30_000); + } + await published.seedBrowser(page, { chatDisplay: "collapseTurns" }); + const history = await holdOlderHistoryPages(page, agent, { + daemonPort: published.daemon.port, + }); + await openAgentTimeline(page, agent, serverId); + await expectTimelinePromptVisible(page, prompts.at(-1)!); + + await userScrollsTimelineToHistoryStart(page); + await history.expectRequestedPages(1); + const partialTurnPrompt = await expectOldestLoadedTurnPartial(page, prompts); + + history.releasePage(1); + await expectFoldedTurnAtReadingPosition(page, partialTurnPrompt); + await history.expectSettledWithRequestedPages(1); + } finally { + await published.close(); } }); diff --git a/packages/app/e2e/browser/turn-collapse.spec.ts b/packages/app/e2e/browser/turn-collapse.spec.ts index c170386266..4d98dea506 100644 --- a/packages/app/e2e/browser/turn-collapse.spec.ts +++ b/packages/app/e2e/browser/turn-collapse.spec.ts @@ -193,6 +193,7 @@ test("received messages show their sender and open that agent", async ({ page }) .getByText("Sent by Reviewer", { exact: true }) .evaluate((element) => getComputedStyle(element).color); await expect(attribution.locator("svg")).toHaveCSS("fill", labelColor); + await expectSenderAlignedWithBubble(attribution); await attribution.scrollIntoViewIfNeeded(); await page.screenshot({ path: "/tmp/sender-attribution.png" }); await attribution.click(); @@ -202,6 +203,135 @@ test("received messages show their sender and open that agent", async ({ page }) } }); +interface MessagePreviewWatch { + /** Frames after the watch started on which the fade or "Show more" control was missing. */ + framesWithoutClip: number[]; + /** Frames on which the fade was a different DOM node than when the watch started. */ + framesRemounted: number[]; +} + +declare global { + interface Window { + __paseoMessagePreviewWatch?: { stop(): MessagePreviewWatch }; + } +} + +async function seedReceivedReviewWithToolTurn() { + const recipient = await seedMockAgentWorkspace({ + repoPrefix: "preview-clip-", + title: "Implementation", + }); + const sender = await recipient.client.createAgent({ + provider: "mock", + cwd: recipient.cwd, + workspaceId: recipient.workspaceId, + title: "Reviewer", + modeId: "load-test", + model: "e2e-fast-stream", + }); + // Long enough to clip behind the preview fade; the instruction makes the recipient run tools. + await recipient.client.sendAgentMessage( + recipient.agentId, + "Review complete: the regression is red on the baseline and green with the fix.\n" + + "Keep the previous response visible while the reader scrolls.\n".repeat(30) + + "Now emit 7 tool agent stream updates", + { sourceAgentId: sender.id }, + ); + return recipient; +} + +/** Samples the received message's bubble on every animation frame until stopped. */ +async function watchReceivedMessagePreview(page: Page, senderLabel: string): Promise { + await page.evaluate((label) => { + const findBubble = () => + [...document.querySelectorAll("[data-testid=user-message]")].find((row) => + row.textContent?.includes(label), + ) ?? null; + const initialFade = findBubble()?.querySelector("svg") ?? null; + if (!initialFade) throw new Error(`No faded bubble for ${label}`); + const framesWithoutClip: number[] = []; + const framesRemounted: number[] = []; + let frame = 0; + let running = true; + const sample = () => { + if (!running) return; + const bubble = findBubble(); + const fade = bubble?.querySelector("svg") ?? null; + if (!fade || !bubble?.textContent?.includes("Show more")) framesWithoutClip.push(frame); + else if (fade !== initialFade) framesRemounted.push(frame); + frame += 1; + requestAnimationFrame(sample); + }; + requestAnimationFrame(sample); + window.__paseoMessagePreviewWatch = { + stop() { + running = false; + return { framesWithoutClip, framesRemounted }; + }, + }; + }, senderLabel); +} + +async function expectReceivedMessagePreviewUndisturbed(page: Page): Promise { + // Give the opened turn's layout a few frames to settle before judging. + await page.evaluate( + () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))), + ); + const watch = await page.evaluate(() => window.__paseoMessagePreviewWatch!.stop()); + expect( + watch.framesWithoutClip, + "the preview fade and Show more control stay on every frame", + ).toEqual([]); + expect(watch.framesRemounted, "the preview keeps its DOM node (no remount)").toEqual([]); +} + +// Opening a turn must not rebuild its host row: the preview above the summary loses its +// measured height when remounted, which drops the fade and "Show more" for a frame. +test("opening a turn keeps the received message above it clipped on every frame", async ({ + page, +}) => { + await useChatDisplay(page, "collapseTurns"); + const recipient = await seedReceivedReviewWithToolTurn(); + try { + await openAgentRoute(page, recipient); + await expectComposerVisible(page); + await expect(page.getByText("Completed 7 commands", { exact: true })).toBeVisible({ + timeout: 30_000, + }); + const bubble = page + .getByTestId("user-message") + .filter({ has: page.getByRole("button", { name: "Sent by Reviewer", exact: true }) }); + await expect(bubble.getByRole("button", { name: "Show more", exact: true })).toBeVisible(); + await bubble.scrollIntoViewIfNeeded(); + + await watchReceivedMessagePreview(page, "Sent by Reviewer"); + await page + .getByTestId("turn-summary") + .getByRole("button", { name: "Ran 7 commands", exact: true }) + .click(); + await expect(page.getByText("echo stress-6", { exact: true })).toBeVisible(); + await expectReceivedMessagePreviewUndisturbed(page); + } finally { + await recipient.cleanup(); + } +}); + +async function expectSenderAlignedWithBubble(attribution: Locator) { + const edges = await attribution.evaluate((button) => { + const bubble = button.nextElementSibling; + const label = button.querySelector('[dir="auto"]'); + if (!bubble || !label) throw new Error("Sender label or message bubble missing"); + return { + labelRight: label.getBoundingClientRect().right, + bubbleRight: bubble.getBoundingClientRect().right, + }; + }); + expect( + Math.abs(edges.labelRight - edges.bubbleRight), + "sender and bubble share the right edge", + ).toBeLessThanOrEqual(1); +} + async function seedWholeTurnHistory() { const agent = await seedMockAgentWorkspace({ repoPrefix: "whole-turn-history-", @@ -301,6 +431,7 @@ for (const autoExpandReasoning of [false, true]) { await expectComposerVisible(page); const summary = page.getByTestId("turn-summary").last().getByRole("button"); await expect(summary).toBeVisible(); + await expect(summary).not.toContainText(/thought/i); await expect(reasoning).toHaveCount(0); await summary.click(); await expect(reasoning).toHaveCount(autoExpandReasoning ? 1 : 0); @@ -339,9 +470,10 @@ async function expectThinkingPresentation(page: Page, autoExpandReasoning: boole await expect(reasoning).toHaveCount(0); const group = page .getByTestId("tool-call-group") - .filter({ hasText: /thought/, visible: true }) + .filter({ hasText: /read 1 file/i, visible: true }) .last(); await expect(group).toContainText(/read 1 file/i); + await expect(group.getByRole("button").first()).not.toContainText(/thought/i); await group.getByRole("button").first().click(); await expect(reasoning).toBeVisible(); } diff --git a/packages/app/e2e/support/helpers/agent-timeline-gate.ts b/packages/app/e2e/support/helpers/agent-timeline-gate.ts index 408bd8af24..89a1d8c364 100644 --- a/packages/app/e2e/support/helpers/agent-timeline-gate.ts +++ b/packages/app/e2e/support/helpers/agent-timeline-gate.ts @@ -338,11 +338,32 @@ export async function delayAgentOlderTimelineResponse( return delayAgentTimelineResponse(page, agentId, "before"); } +export interface OlderTimelinePagesOptions { + daemonPort?: number; + /** + * Hide whole-turn paging from the app so it reads this host with item pages, as it reads + * daemons released before whole-turn pages. An item page can end inside a turn or a tool run. + */ + itemPagedHost?: boolean; +} + +function withoutWholeTurnPages(message: WebSocketMessage): WebSocketMessage { + const sessionMessage = getSessionMessage(message); + const payload = sessionMessage ? getPayload(sessionMessage) : null; + if (sessionMessage?.type !== "status" || payload?.status !== "server_info") return message; + const envelope = parseWebSocketJson(message) as { + message: { payload: { features?: Record } }; + }; + delete envelope.message.payload.features?.wholeTurnTimeline; + return JSON.stringify(envelope); +} + export async function holdAgentOlderTimelinePages( page: Page, agentId: string, - daemonPort?: number, + options: OlderTimelinePagesOptions = {}, ): Promise { + const { daemonPort } = options; let requestCount = 0; let responseCount = 0; let repeatedEntryCount = 0; @@ -376,7 +397,8 @@ export async function holdAgentOlderTimelinePages( } server.send(message); }); - server.onMessage((message) => { + server.onMessage((received) => { + const message = options.itemPagedHost ? withoutWholeTurnPages(received) : received; const sessionMessage = getSessionMessage(message); const payload = sessionMessage ? getPayload(sessionMessage) : null; if ( diff --git a/packages/app/e2e/support/helpers/timeline-pagination.ts b/packages/app/e2e/support/helpers/timeline-pagination.ts index 52027df956..e575f4f0d9 100644 --- a/packages/app/e2e/support/helpers/timeline-pagination.ts +++ b/packages/app/e2e/support/helpers/timeline-pagination.ts @@ -1,4 +1,4 @@ -import { expect, type TestInfo, type Page } from "@playwright/test"; +import { expect, type Locator, type TestInfo, type Page } from "@playwright/test"; import { buildAgentRoute, seedMockAgentWorkspace, type MockAgentWorkspace } from "./mock-agent"; import { readReplicaCache } from "./replica-cache-storage"; import { @@ -9,6 +9,7 @@ import { type AgentTimelineResponseGate, type BootstrapTimelineGate, type OlderTimelinePagesGate, + type OlderTimelinePagesOptions, } from "./agent-timeline-gate"; export { holdDaemonHydration }; @@ -35,6 +36,19 @@ interface RealisticOlderTimelineAgent extends MockAgentWorkspace { newestPrompt: string; } +export interface ItemPagedToolGroupAgent extends MockAgentWorkspace { + newestPrompt: string; + /** Commands in one run, more than an item page holds. */ + totalCommands: number; + /** Commands of that run the initial tail loads, so the size of the group as first shown. */ + loadedCommands: number; +} + +interface ToolCallGroupPositionSnapshot { + top: number; +} + +const ITEM_PAGE_SIZE = 40; const PROMPT_PREFIX = "timeline-pagination-turn"; const LIVE_BEFORE_HYDRATION_PROMPT = "timeline live before authoritative hydration"; const HISTORY_START_THRESHOLD_PX = 96; @@ -126,6 +140,93 @@ export async function seedRealisticOlderTimeline(): Promise { + const agent = await seedMockAgentWorkspace({ + repoPrefix: "timeline-item-page-tool-group-", + title: "Item page tool group regression", + }); + const olderTurns = 10; + const newerTurns = 12; + const totalCommands = 50; + // A short turn is its prompt and one reply; the run's turn ends with one reply. + const loadedCommands = ITEM_PAGE_SIZE - newerTurns * 2 - 1; + const shortTurnPrompt = (label: string, index: number) => + `item-page-${label}-turn-${index}: emit 1 coalesced agent stream updates`; + const sendTurn = async (prompt: string) => { + await agent.client.sendAgentMessage(agent.agentId, prompt); + await agent.client.waitForFinish(agent.agentId, 15_000); + }; + + for (let index = 0; index < olderTurns; index += 1) { + await sendTurn(shortTurnPrompt("older", index)); + } + await sendTurn(`emit ${totalCommands} tool agent stream updates`); + for (let index = 0; index < newerTurns; index += 1) { + await sendTurn(shortTurnPrompt("newer", index)); + } + + return { + ...agent, + newestPrompt: shortTurnPrompt("newer", newerTurns - 1), + totalCommands, + loadedCommands, + }; +} + +export async function useChatDisplay( + page: Page, + chatDisplay: "full" | "collapseToolCalls" | "collapseTurns", +): Promise { + await page.addInitScript((value) => { + localStorage.setItem("@paseo:app-settings", JSON.stringify({ chatDisplay: value })); + }, chatDisplay); +} + +function toolCallGroup(page: Page, commandCount: number): Locator { + const timeline = page.locator('[data-testid="agent-chat-scroll"]:visible').first(); + return timeline + .getByTestId("tool-call-group") + .getByRole("button", { name: `Ran ${commandCount} commands`, exact: true }); +} + +export async function rememberToolCallGroupPosition( + page: Page, + commandCount: number, +): Promise { + const group = toolCallGroup(page, commandCount); + await expect(group).toBeVisible(); + const box = await group.boundingBox(); + if (!box) { + throw new Error(`Expected a rendered tool-call group of ${commandCount} commands`); + } + return { top: box.y }; +} + +/** The group the reader was on keeps its place on screen, now counting the older page's calls. */ +export async function expectToolCallGroupPositionPreserved( + page: Page, + commandCount: number, + before: ToolCallGroupPositionSnapshot, +): Promise { + const group = toolCallGroup(page, commandCount); + await expect(group).toBeVisible(); + await expect + .poll( + async () => { + const box = await group.boundingBox(); + return box ? Math.abs(box.y - before.top) : Number.POSITIVE_INFINITY; + }, + { message: `the group of ${commandCount} commands keeps its viewport position` }, + ) + .toBeLessThanOrEqual(2); +} + export async function scrollThroughOlderHistoryPages( page: Page, pageCount: number, @@ -316,13 +417,14 @@ export async function holdNextOlderTimelinePage( export async function holdOlderHistoryPages( page: Page, agent: MockAgentWorkspace, - daemonPort?: number, + options?: OlderTimelinePagesOptions, ): Promise { const gate: OlderTimelinePagesGate = await holdAgentOlderTimelinePages( page, agent.agentId, - daemonPort, + options, ); + const loader = page.getByTestId("load-older-history-spinner"); return { async expectRequestedPages(count) { await gate.waitForRequestCount(count); @@ -330,7 +432,17 @@ export async function holdOlderHistoryPages( }, async expectSettledWithRequestedPages(count) { await waitForTimelineGeometryToSettle(page); - expect(gate.getRequestCount()).toBe(count); + // The loader stays until the prepend settles and the viewport decides whether to + // keep loading. Once it hides, no further page loads without new user intent. + await expect + .poll( + async () => ({ + requestedPages: gate.getRequestCount(), + loading: await loader.isVisible(), + }), + { message: `older history settles after ${count} requested page(s)` }, + ) + .toEqual({ requestedPages: count, loading: false }); }, expectNoRepeatedEntries() { expect(gate.getRepeatedEntryCount()).toBe(0); @@ -423,6 +535,53 @@ export async function expectTimelineViewportAnchoredAfterPrepend( expect(Math.abs(contentGrowth - scrollAdjustment)).toBeLessThanOrEqual(2); } +/** + * Item-based pages from older hosts split turns, so the oldest loaded turn starts + * mid-turn: its prompt is above loaded history. Returns that prompt. + */ +export async function expectOldestLoadedTurnPartial( + page: Page, + prompts: readonly string[], +): Promise { + const timeline = page.locator('[data-testid="agent-chat-scroll"]:visible').first(); + const oldestLoadedPrompt = await timeline + .getByTestId("user-message") + .first() + .evaluate((element) => element.textContent ?? ""); + const loadedIndex = prompts.findIndex((prompt) => oldestLoadedPrompt.includes(prompt)); + expect(loadedIndex, "oldest loaded prompt is a seeded turn").toBeGreaterThan(0); + const oldestRow = timeline.locator("[data-history-row-id]").first(); + await expect(oldestRow.getByTestId("user-message"), "rows above the oldest prompt").toHaveCount( + 0, + ); + const partialPrompt = prompts[loadedIndex - 1]!; + await expectTimelinePromptNotMounted(page, partialPrompt); + return partialPrompt; +} + +/** The reader stays with the turn they were reading once it folds behind its summary. */ +export async function expectFoldedTurnAtReadingPosition(page: Page, prompt: string): Promise { + const timeline = page.locator('[data-testid="agent-chat-scroll"]:visible').first(); + const promptRow = timeline.locator("[data-history-row-id]").filter({ hasText: prompt }); + await expect(promptRow).toBeVisible({ timeout: 15_000 }); + // The host row carries the folded turn's summary line. + await expect(promptRow.getByTestId("turn-summary")).toBeVisible(); + await expect + .poll( + async () => { + const [timelineBox, promptBox] = await Promise.all([ + timeline.boundingBox(), + promptRow.boundingBox(), + ]); + if (!timelineBox || !promptBox) return false; + const offset = promptBox.y - timelineBox.y; + return offset >= 0 && offset <= timelineBox.height / 2; + }, + { message: "folded turn sits in the upper half of the viewport" }, + ) + .toBe(true); +} + export async function expectTimelineAtHistoryStart(page: Page): Promise { await expect .poll(async () => (await readTimelineViewport(page)).scrollTop) diff --git a/packages/app/src/agent-stream/presentation.test.ts b/packages/app/src/agent-stream/presentation.test.ts index 0cfc793228..f7d146d92a 100644 --- a/packages/app/src/agent-stream/presentation.test.ts +++ b/packages/app/src/agent-stream/presentation.test.ts @@ -15,6 +15,7 @@ import { QueryClient } from "@tanstack/react-query"; import { describe, expect, it } from "vitest"; import { buildAgentStreamRenderModel } from "./model"; import { createStreamPresentation } from "./presentation"; +import { createReadingAnchor } from "./reading-anchor"; const runtime = { paseo: {}, @@ -609,8 +610,54 @@ it("opening a turn reveals individual calls rather than another tool group", () }); expect(result.tail.map((item) => item.id)).toEqual(tail.map((item) => item.id)); expect(result.groupsByHostId.size).toBe(0); + expect(result.readingRowReplacements.get("tool-two")).toBeUndefined(); }); +it.each(["collapseToolCalls", "collapseTurns"] as const)( + "preserves the reader when a prepend extends a group in %s", + (display) => { + const present = createStreamPresentation(); + const anchor = createReadingAnchor(); + const calls = [toolCall("one", "Bash"), toolCall("two", "Bash")]; + const input = { + ...presentationOptions, + transform: undefined, + display, + head: [], + isTurnActive: false, + }; + const partial = present({ ...input, tail: calls.slice(1) }); + anchor.reconcile(0, [{ id: partial.tail[0]!.id, top: 48, height: 200 }]); + const completed = present({ ...input, tail: calls }); + const groupId = completed.tail[0]!.id; + expect(anchor.getRowId(completed.readingRowReplacements)).toBe(groupId); + expect( + anchor.reconcile( + 0, + [{ id: groupId, top: 448, height: 200 }], + false, + completed.readingRowReplacements, + ), + ).toBe(400); + expect(anchor.getRowId()).toBe(groupId); + const timestamp = new Date(); + const folded = present({ + ...input, + display: "collapseTurns", + tail: [ + { kind: "user_message", id: "prompt", text: "Work", timestamp }, + ...calls, + { kind: "assistant_message", id: "reply", text: "Done", timestamp }, + ], + }); + // Both the original partial group and its replacement resolve directly to the turn. + expect(folded.readingRowReplacements.get(calls[1]!.id)).toBe("prompt"); + expect(anchor.getRowId(folded.readingRowReplacements)).toBe("prompt"); + const opened = present({ ...input, tail: calls, display: "full" }); + expect(opened.readingRowReplacements.get(calls[1]!.id)).toBeUndefined(); + }, +); + it("presents received agent messages as attributed bubbles with the original turn identity", () => { const call = toolCall("received", "agent_message"); if (call.payload.source !== "agent") throw new Error("Expected agent tool"); diff --git a/packages/app/src/agent-stream/presentation.ts b/packages/app/src/agent-stream/presentation.ts index 5138cc1647..b449cb63cc 100644 --- a/packages/app/src/agent-stream/presentation.ts +++ b/packages/app/src/agent-stream/presentation.ts @@ -11,6 +11,7 @@ import { } from "@/tool-calls/detail-level/projection"; import type { StreamItem, UserMessageItem } from "@/types/stream"; import { collapseTurns, type TurnCollapse } from "./turn-collapse/model"; +import type { ReadingRowReplacements } from "./reading-anchor"; interface PresentationInput { tail: StreamItem[]; @@ -26,6 +27,22 @@ interface PresentationInput { export interface StreamPresentation extends ToolCallDetailProjection { turns: Omit; + readingRowReplacements: ReadingRowReplacements; +} + +function groupedRowHosts( + rows: readonly StreamItem[], + groups: ToolCallDetailProjection["groupsByHostId"], +): ReadonlyMap { + const hosts = new Map(); + for (const row of rows) { + const group = groups.get(row.id); + if (!group) continue; + for (const call of group.run.calls) { + if (call.id !== row.id) hosts.set(call.id, row.id); + } + } + return hosts; } const NO_COLLAPSED_TURNS: StreamPresentation["turns"] = collapseTurns({ @@ -61,6 +78,7 @@ export function createStreamPresentation() { let preparedAutoExpandReasoning: boolean | undefined; let preparedLevel: ToolCallDetailLevel | undefined; let preparedHistory: PreparedToolCallHistory | null = null; + let historyGroupHosts: ReadonlyMap = new Map(); let collapsedSource: StreamItem[] | undefined; let collapsedIsLatestTurnOpen = false; let collapsedExpandedHostIds: ReadonlySet | undefined; @@ -89,7 +107,7 @@ export function createStreamPresentation() { function collapse( projection: ToolCallDetailProjection, input: PresentationInput, - ): StreamPresentation { + ): Omit { if (input.display !== "collapseTurns") { return { ...projection, turns: NO_COLLAPSED_TURNS }; } @@ -157,19 +175,42 @@ export function createStreamPresentation() { preparedAutoExpandReasoning !== input.autoExpandReasoning ) { preparedHistory = prepareToolCallHistory(level, historyRows, input.autoExpandReasoning); + historyGroupHosts = preparedHistory + ? groupedRowHosts(preparedHistory.grouped.tail, preparedHistory.grouped.groupsByHostId) + : new Map(); preparedTail = historyRows; preparedLevel = level; preparedAutoExpandReasoning = input.autoExpandReasoning; } - return collapse( - projectToolCallDetailLevel({ - level, - tail: historyRows, - head, - preparedHistory, - isTurnActive: input.isTurnActive, - }), - input, + const projection = projectToolCallDetailLevel({ + level, + tail: historyRows, + head, + preparedHistory, + isTurnActive: input.isTurnActive, + }); + const result = collapse(projection, input); + // Only the trailing retained group can absorb head rows. Reuse the retained + // index across streaming updates rather than walking the full history again. + const last = projection.tail.at(-1); + const liveGroupHosts = groupedRowHosts( + last ? [last, ...projection.head] : projection.head, + projection.groupsByHostId, ); + const retainedGroupHosts = historyGroupHosts; + return { + ...result, + readingRowReplacements: { + get(id) { + if (result.turns.nestedItemIds.has(id)) return undefined; + const groupHost = liveGroupHosts.get(id) ?? retainedGroupHosts.get(id) ?? id; + return ( + result.turns.hostIdByHiddenRowId.get(id) ?? + result.turns.hostIdByHiddenRowId.get(groupHost) ?? + (groupHost === id ? undefined : groupHost) + ); + }, + }, + }; }; } diff --git a/packages/app/src/agent-stream/reading-anchor.test.ts b/packages/app/src/agent-stream/reading-anchor.test.ts index 74b2bd5bcd..d7d1b2beb4 100644 --- a/packages/app/src/agent-stream/reading-anchor.test.ts +++ b/packages/app/src/agent-stream/reading-anchor.test.ts @@ -2,6 +2,24 @@ import { describe, expect, it } from "vitest"; import { createReadingAnchor } from "./reading-anchor"; describe("reading anchor", () => { + it("pins the folded turn host when a prepend replaces the row being read", () => { + const anchor = createReadingAnchor(); + anchor.reconcile(0, [{ id: "tool", top: 48, height: 200 }]); + const replacements = new Map([["tool", "prompt"]]); + expect(anchor.getRowId(replacements)).toBe("prompt"); + expect(anchor.project(0, { id: "prompt", top: 1048 }, replacements)).toBe(1000); + // Projection does not consume the correction; an unmounted host keeps the pin. + expect(anchor.reconcile(0, [], false, replacements)).toBe(0); + expect(anchor.getRowId()).toBe("tool"); + expect( + anchor.reconcile(0, [{ id: "prompt", top: 1048, height: 100 }], false, replacements), + ).toBe(1000); + expect(anchor.getRowId()).toBe("prompt"); + expect( + anchor.reconcile(1000, [{ id: "prompt", top: 1048, height: 100 }], false, replacements), + ).toBe(1000); + }); + const rows = [ { id: "above", top: 0, height: 500 }, { id: "reading", top: 500, height: 500 }, diff --git a/packages/app/src/agent-stream/reading-anchor.ts b/packages/app/src/agent-stream/reading-anchor.ts index 4299f1d9c8..aa915c6ae7 100644 --- a/packages/app/src/agent-stream/reading-anchor.ts +++ b/packages/app/src/agent-stream/reading-anchor.ts @@ -6,6 +6,10 @@ interface RowGeometry { // A row must clear the reading line before the next row takes ownership. const READING_POSITION_OFFSET_PX = 8; +export interface ReadingRowReplacements { + get(id: string): string | undefined; +} +const NO_REPLACEMENTS: ReadingRowReplacements = new Map(); // Content coordinates survive user scrolling. Layout commits replace the geometry; // scroll events reuse it, without another DOM measurement pass. @@ -14,10 +18,15 @@ export function createReadingAnchor() { let geometry: readonly RowGeometry[] = []; const readingRow = (scrollTop: number) => geometry.find((row) => row.top + row.height > scrollTop + READING_POSITION_OFFSET_PX); - const project = (scrollTop: number, row: Pick | undefined) => - scrollTop + (anchor && row?.id === anchor.id ? row.top - anchor.top : 0); + const getRowId = (replacements = NO_REPLACEMENTS) => + anchor ? (replacements.get(anchor.id) ?? anchor.id) : null; + const project = ( + scrollTop: number, + row: Pick | undefined, + replacements = NO_REPLACEMENTS, + ) => scrollTop + (anchor && row && row.id === getRowId(replacements) ? row.top - anchor.top : 0); return { - getRowId: () => anchor?.id ?? null, + getRowId, getReadingRowId: (scrollTop: number) => readingRow(scrollTop)?.id ?? geometry.at(-1)?.id ?? null, project, @@ -28,13 +37,18 @@ export function createReadingAnchor() { const next = readingRow(scrollTop); anchor = next ? { id: next.id, top: next.top } : null; }, - reconcile(scrollTop: number, rows: readonly RowGeometry[], userScrolled = false): number { + reconcile( + scrollTop: number, + rows: readonly RowGeometry[], + userScrolled = false, + replacements = NO_REPLACEMENTS, + ): number { geometry = rows; - const previous = anchor && rows.find((row) => row.id === anchor?.id); + const previous = anchor && rows.find((row) => row.id === getRowId(replacements)); // The first virtualized commit can precede its mounted range. Keep the // pinned reader until it mounts, rather than adopting an unrelated row. if (anchor && !previous && !userScrolled) return scrollTop; - const correctedTop = project(scrollTop, previous ?? undefined); + const correctedTop = project(scrollTop, previous ?? undefined, replacements); // A prepend can expose the bottom of an estimated row above the reader. // Do not transfer ownership to it until the user moves the reading position. const next = previous && !userScrolled ? previous : readingRow(correctedTop); diff --git a/packages/app/src/agent-stream/strategy-web.tsx b/packages/app/src/agent-stream/strategy-web.tsx index 8e8bdf7680..9dae42bcc0 100644 --- a/packages/app/src/agent-stream/strategy-web.tsx +++ b/packages/app/src/agent-stream/strategy-web.tsx @@ -394,7 +394,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool const rangeExtractor = useCallback( (range: VirtualRange): number[] => { const anchorIndex = segments.historyVirtualized.findIndex( - (row) => row.id === readingAnchor.getRowId(), + (row) => row.id === readingAnchor.getRowId(props.readingRowReplacements), ); const container = scrollContainerRef.current; // TanStack has computed the new measurements before calling the extractor. @@ -404,10 +404,14 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool const measurement = virtualizer.measurementsCache[anchorIndex]; const correctedOffset = container && measurement - ? readingAnchor.project(container.scrollTop, { - id: String(measurement.key), - top: measurement.start, - }) + ? readingAnchor.project( + container.scrollTop, + { + id: String(measurement.key), + top: measurement.start, + }, + props.readingRowReplacements, + ) : container?.scrollTop; let visibleRange = range; if ( @@ -428,7 +432,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool ]), ].sort((left, right) => left - right); }, - [chatFindRowIndexes, readingAnchor, segments.historyVirtualized], + [chatFindRowIndexes, readingAnchor, segments.historyVirtualized, props.readingRowReplacements], ); const virtualOffsetListener = useRef<((offset: number, scrolling: boolean) => void) | null>(null); const observeVirtualOffset = useCallback((instance, onOffset) => { @@ -742,7 +746,12 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool ); const shouldAnchor = !followOutputRef.current && !isJumpSettling(); if (!shouldAnchor) readingAnchor.reset(); - const correctedTop = readingAnchor.reconcile(container.scrollTop, rows); + const correctedTop = readingAnchor.reconcile( + container.scrollTop, + rows, + false, + props.readingRowReplacements, + ); if (!shouldAnchor) { readingAnchor.reset(); return; diff --git a/packages/app/src/agent-stream/strategy.ts b/packages/app/src/agent-stream/strategy.ts index 3d9df4d201..364eba1043 100644 --- a/packages/app/src/agent-stream/strategy.ts +++ b/packages/app/src/agent-stream/strategy.ts @@ -1,6 +1,7 @@ import type { ComponentType, ReactElement, ReactNode, RefObject } from "react"; import type { StyleProp, ViewStyle } from "react-native"; import type { StreamItem } from "@/types/stream"; +import type { ReadingRowReplacements } from "./reading-anchor"; import { continuesResponse } from "./turn-membership"; import type { StreamHistoryBoundary, StreamRenderSegments } from "./model"; import type { @@ -78,6 +79,8 @@ export interface StreamRenderInput { segments: StreamRenderSegments; historyRowRevision?: StreamHistoryRowRevision; liveHeadRowRevision?: unknown; + /** Presentation rows replaced by another row after history is folded. */ + readingRowReplacements?: ReadingRowReplacements; boundary: StreamHistoryBoundary; renderers: StreamSegmentRenderers; listEmptyComponent: ReactNode; diff --git a/packages/app/src/agent-stream/turn-collapse/model.test.ts b/packages/app/src/agent-stream/turn-collapse/model.test.ts index 6cefaf3651..eca6d8757c 100644 --- a/packages/app/src/agent-stream/turn-collapse/model.test.ts +++ b/packages/app/src/agent-stream/turn-collapse/model.test.ts @@ -48,6 +48,14 @@ function collapse(tail: StreamItem[], options: Partial = {}) const ids = (items: StreamItem[]) => items.map((item) => item.id); describe("collapseTurns", () => { + it("maps hidden rows only while their turn is closed", () => { + const result = collapse([user("u1"), shell("c1"), reply("final")]); + expect(result.hostIdByHiddenRowId.get("c1")).toBe("u1"); + const expanded = collapse([user("u1"), shell("c1"), reply("final")], { + expandedHostIds: new Set(["u1"]), + }); + expect(expanded.hostIdByHiddenRowId.size).toBe(0); + }); it("keeps lifecycle events and compaction recognizable beside a semantic action summary", () => { const create = shell("create"); if (create.payload.source !== "agent") throw new Error("Expected agent tool"); diff --git a/packages/app/src/agent-stream/turn-collapse/model.ts b/packages/app/src/agent-stream/turn-collapse/model.ts index 20ab84a817..a5985e600f 100644 --- a/packages/app/src/agent-stream/turn-collapse/model.ts +++ b/packages/app/src/agent-stream/turn-collapse/model.ts @@ -25,6 +25,8 @@ export interface TurnCollapse { nestedItemIds: ReadonlySet; /** The turn a folded message belongs to, for surfaces that must reveal it. */ hostIdByFoldedMessageId: ReadonlyMap; + /** Mounted rows replaced by a closed turn's host, for preserving the reading position. */ + hostIdByHiddenRowId: ReadonlyMap; } export interface CollapseTurnsInput { @@ -80,6 +82,7 @@ export function collapseTurns(input: CollapseTurnsInput): TurnCollapse { const turnsByHostId = new Map(); const nestedItemIds = new Set(); const hostIdByFoldedMessageId = new Map(); + const hostIdByHiddenRowId = new Map(); let runStart = 0; const flushRun = (runEnd: number) => { @@ -114,6 +117,7 @@ export function collapseTurns(input: CollapseTurnsInput): TurnCollapse { if (staysVisibleWhenCollapsed(item)) continue; hostIdByFoldedMessageId.set(getStreamItemMessageId(item), host.id); if (expanded) nestedItemIds.add(item.id); + else hostIdByHiddenRowId.set(item.id, host.id); } output.push( ...(expanded ? revealed : folded.filter((item) => staysVisibleWhenCollapsed(item))), @@ -139,6 +143,7 @@ export function collapseTurns(input: CollapseTurnsInput): TurnCollapse { turnsByHostId: EMPTY_TURNS, nestedItemIds: EMPTY_IDS, hostIdByFoldedMessageId: EMPTY_HOSTS, + hostIdByHiddenRowId: EMPTY_HOSTS, }; } return { @@ -149,5 +154,6 @@ export function collapseTurns(input: CollapseTurnsInput): TurnCollapse { turnsByHostId, nestedItemIds, hostIdByFoldedMessageId, + hostIdByHiddenRowId, }; } diff --git a/packages/app/src/agent-stream/view.tsx b/packages/app/src/agent-stream/view.tsx index 5d8fe3d913..f35af10498 100644 --- a/packages/app/src/agent-stream/view.tsx +++ b/packages/app/src/agent-stream/view.tsx @@ -1206,6 +1206,7 @@ const AgentStreamViewComponent = forwardRef {streamRenderStrategy.render({ + readingRowReplacements: presentation.readingRowReplacements, agentId, segments: renderModel.segments, historyRowRevision, @@ -1898,12 +1899,11 @@ function StreamItemWrapper({ gapBelow, turnIndent, children }: StreamItemWrapper const gapStyle = useMemo(() => ({ paddingBottom: gapBelow }), [gapBelow]); switch (turnIndent) { case "none": - return {children}; case "openedHost": return ( {children} - + {turnIndent === "openedHost" ? : null} ); case "nested": diff --git a/packages/app/src/components/user-message/index.tsx b/packages/app/src/components/user-message/index.tsx index d420ffdde5..ba383eb0d3 100644 --- a/packages/app/src/components/user-message/index.tsx +++ b/packages/app/src/components/user-message/index.tsx @@ -36,7 +36,7 @@ export function MessagePreview({ children }: { children: ReactNode }) { + {terminalsSurviveRestart ? ( + + + + {t("settings.host.daemon.restart.closeTerminalsHint")} + + + + + ) : null} + {restartError ? ( + + + + ) : null} ); } @@ -848,7 +894,7 @@ function UpdateDaemonCard({ host }: { host: HostProfile }) { /> ) : null} {updateState.status === "failed" ? ( - + ({ })); const styles = StyleSheet.create((theme) => ({ - updateFailure: { + cardAlert: { marginHorizontal: theme.spacing[4], marginBottom: theme.spacing[4], }, diff --git a/packages/cli/src/commands/daemon/restart.ts b/packages/cli/src/commands/daemon/restart.ts index ef88e39a23..97e2fbf604 100644 --- a/packages/cli/src/commands/daemon/restart.ts +++ b/packages/cli/src/commands/daemon/restart.ts @@ -3,8 +3,11 @@ import { readDaemonInstance, isSameDaemonInstance, DaemonInstanceError, + retryUnconfirmedTerminalCleanup, + TerminalCleanupNotConfirmedError, } from "@getpaseo/server/daemon-control"; import { setTimeout as delay } from "node:timers/promises"; +import type { DaemonGetStatusResponse } from "@getpaseo/protocol/messages"; import { connectToDaemon } from "../../utils/client.js"; import { withOutput, type CommandOptions } from "../../output/index.js"; import { addJsonAndDaemonHostOptions } from "../../utils/command-options.js"; @@ -20,13 +23,30 @@ export function daemonRestartCommand(): Command { ), ) .option("--timeout ", "Replacement readiness deadline (default: 600)") + .option("--kill-terminals", "Close every terminal instead of keeping them across the restart") .action(withOutput(runRestartCommand)); } +type DaemonStatus = DaemonGetStatusResponse["payload"]; + export async function runRestartCommand(options: CommandOptions, _command: Command) { const target = options.daemonTarget; const deadline = Date.now() + parseTimeoutMs(options.timeout); const remaining = () => Math.max(1, deadline - Date.now()); + const killTerminals = options.killTerminals === true; + // The supervisor reaps before the respawn and the replacement retries what that left; + // anything still named by a closing record survived both. A local caller retries once more + // itself; a remote one has only what the replacement reports. + const confirmTerminalsClosed = async (status: DaemonStatus) => { + if (!killTerminals) return; + if (target.kind === "instance") { + await retryUnconfirmedTerminalCleanup(target.home); + return; + } + // Absent on daemons without terminalsSurviveRestart, which have no terminal cleanup. + const unconfirmed = status.terminalCleanupUnconfirmed ?? []; + if (unconfirmed.length > 0) throw new TerminalCleanupNotConfirmedError(unconfirmed); + }; const instance = target.kind === "instance" ? await readDaemonInstance(target.home) : null; async function checkSupervisor() { if (target.kind !== "instance") return; @@ -54,7 +74,10 @@ export async function runRestartCommand(options: CommandOptions, _command: Comma workerPid = (await client.getDaemonStatus({ timeout: remaining() })).pid; await checkSupervisor(); try { - await client.restartServer("cli_restart", undefined, { timeout: remaining() }); + await client.restartServer("cli_restart", undefined, { + timeout: remaining(), + killTerminals, + }); acknowledged = true; } catch (error) { if (!isReconnectFailure(error)) throw error; @@ -77,6 +100,7 @@ export async function runRestartCommand(options: CommandOptions, _command: Comma const status = await replacement.getDaemonStatus({ timeout: remaining() }); if (status.pid !== workerPid) { await checkSupervisor(); + await confirmTerminalsClosed(status); return { type: "single" as const, data: { diff --git a/packages/cli/src/commands/daemon/status.ts b/packages/cli/src/commands/daemon/status.ts index 14c20534e6..cd499ea6cb 100644 --- a/packages/cli/src/commands/daemon/status.ts +++ b/packages/cli/src/commands/daemon/status.ts @@ -103,6 +103,7 @@ async function probeDaemonStatus( daemonNode: status.nodePath, providers: status.providers, relay: status.relay, + ...(status.terminalsUnavailable ? { terminals: status.terminalsUnavailable } : {}), }; } } finally { diff --git a/packages/cli/src/commands/daemon/stop.test.ts b/packages/cli/src/commands/daemon/stop.test.ts new file mode 100644 index 0000000000..7ee5f930f9 --- /dev/null +++ b/packages/cli/src/commands/daemon/stop.test.ts @@ -0,0 +1,110 @@ +import { spawn, type ChildProcess } from "node:child_process"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { hostname, tmpdir } from "node:os"; +import path from "node:path"; +import { Command } from "commander"; +import { afterEach, describe, expect, test } from "vitest"; +import { createStopCommandRunner, type StopCommandDeps } from "./stop.js"; + +// The daemon the gate is checked against: a connection whose server_info may or may not +// advertise terminalsSurviveRestart, and that records any shutdown it is asked for. +function createFakeDaemon(features: { terminalsSurviveRestart?: boolean } = {}) { + const shutdownRequests: Array<{ keepTerminals?: boolean }> = []; + const deps: StopCommandDeps = { + connectToDaemon: async () => ({ + getLastServerInfoMessage: () => ({ + status: "server_info", + serverId: "fake-daemon", + version: "0.11.0", + features, + }), + shutdownServer: async (options) => { + shutdownRequests.push({ keepTerminals: options?.keepTerminals }); + return { status: "shutdown_requested", clientId: "fake-client", requestId: "fake-request" }; + }, + close: async () => undefined, + }), + }; + return { deps, shutdownRequests }; +} + +const cleanups: Array<() => void> = []; + +afterEach(() => { + for (const cleanup of cleanups.splice(0)) cleanup(); +}); + +function stop(options: Record, deps: StopCommandDeps) { + return createStopCommandRunner(deps)(options as never, new Command("stop")); +} + +// A home whose lock names a live stand-in supervisor, so the local stop path runs for real. +function homeWithRunningSupervisor(): { home: string; supervisor: ChildProcess } { + const home = mkdtempSync(path.join(tmpdir(), "paseo-stop-keep-")); + const supervisor = spawn(process.execPath, ["-e", "setInterval(() => {}, 1e9)"], { + stdio: "ignore", + }); + writeFileSync( + path.join(home, "paseo.pid"), + JSON.stringify({ + pid: supervisor.pid, + startedAt: new Date().toISOString(), + hostname: hostname(), + uid: process.getuid?.() ?? 0, + listen: "127.0.0.1:1", + }), + ); + cleanups.push(() => { + supervisor.kill("SIGKILL"); + rmSync(home, { recursive: true, force: true }); + }); + return { home, supervisor }; +} + +describe("daemon stop --keep-terminals", () => { + test("refuses an endpoint daemon that does not advertise terminalsSurviveRestart", async () => { + const daemon = createFakeDaemon(); + await expect( + stop( + { daemonTarget: { kind: "endpoint", host: "127.0.0.1:7777" }, keepTerminals: true }, + daemon.deps, + ), + ).rejects.toMatchObject({ code: "TERMINALS_KEEP_UNSUPPORTED" }); + expect(daemon.shutdownRequests).toEqual([]); + }); + + test.skipIf(process.platform === "win32")( + "refuses a local daemon without the capability and never signals its supervisor", + async () => { + const daemon = createFakeDaemon(); + const { home, supervisor } = homeWithRunningSupervisor(); + await expect( + stop({ daemonTarget: { kind: "instance", home }, keepTerminals: true }, daemon.deps), + ).rejects.toMatchObject({ code: "TERMINALS_KEEP_UNSUPPORTED" }); + expect(daemon.shutdownRequests).toEqual([]); + expect(supervisor.exitCode).toBeNull(); + expect(supervisor.signalCode).toBeNull(); + }, + ); + + test("asks a capable daemon to keep its terminals", async () => { + const daemon = createFakeDaemon({ terminalsSurviveRestart: true }); + await stop( + { daemonTarget: { kind: "endpoint", host: "127.0.0.1:7777" }, keepTerminals: true }, + daemon.deps, + ); + expect(daemon.shutdownRequests).toEqual([{ keepTerminals: true }]); + }); + + test("rejects --force with --keep-terminals before contacting the daemon", async () => { + const daemon = createFakeDaemon({ terminalsSurviveRestart: true }); + const { home } = homeWithRunningSupervisor(); + await expect( + stop( + { daemonTarget: { kind: "instance", home }, keepTerminals: true, force: true }, + daemon.deps, + ), + ).rejects.toMatchObject({ code: "INVALID_OPTIONS" }); + expect(daemon.shutdownRequests).toEqual([]); + }); +}); diff --git a/packages/cli/src/commands/daemon/stop.ts b/packages/cli/src/commands/daemon/stop.ts index f2bf8b1255..141d50965e 100644 --- a/packages/cli/src/commands/daemon/stop.ts +++ b/packages/cli/src/commands/daemon/stop.ts @@ -1,6 +1,10 @@ import { Command } from "commander"; +import { + requireTerminalKeepCapability, + type DaemonClient, +} from "@getpaseo/client/internal/daemon-client"; import { stopDaemonInstance, type DaemonInstance } from "@getpaseo/server/daemon-control"; -import { connectToDaemon } from "../../utils/client.js"; +import { connectToDaemon, type ConnectOptions } from "../../utils/client.js"; import { withOutput, type CommandOptions } from "../../output/index.js"; import { addJsonAndDaemonHostOptions } from "../../utils/command-options.js"; import { describeDaemonTarget } from "../../utils/daemon-target.js"; @@ -10,19 +14,43 @@ export function daemonStopCommand(): Command { return addJsonAndDaemonHostOptions(new Command("stop").description("Stop the selected daemon")) .option("--timeout ", "Graceful exit deadline (default: 15)") .option("--force", "Permit forced local process cleanup") + .option( + "--keep-terminals", + "Leave terminals running; the next daemon started for this home takes them back", + ) .option("--kill-timeout ", "Forced exit deadline (default: 3)") .action(withOutput(runStopCommand)); } -export async function runStopCommand(options: CommandOptions, _command: Command) { +// The daemon connection stop needs; stop.test.ts passes an in-memory adapter. +export type StopDaemonConnection = Pick< + DaemonClient, + "getLastServerInfoMessage" | "shutdownServer" | "close" +>; + +export interface StopCommandDeps { + connectToDaemon(options: ConnectOptions): Promise; +} + +export const runStopCommand = createStopCommandRunner({ connectToDaemon }); + +export function createStopCommandRunner(deps: StopCommandDeps) { + return (options: CommandOptions, _command: Command) => runStop(options, deps); +} + +async function runStop(options: CommandOptions, deps: StopCommandDeps) { const target = options.daemonTarget; const timeoutMs = parseTimeoutMs(options.timeout, 15_000); const deadline = Date.now() + timeoutMs; const remaining = () => Math.max(1, deadline - Date.now()); + const keepTerminals = options.keepTerminals === true; const requestShutdown = async (instance?: DaemonInstance) => { - const client = await connectToDaemon({ target, timeout: remaining(), instance }); + const client = await deps.connectToDaemon({ target, timeout: remaining(), instance }); try { - await client.shutdownServer({ timeout: remaining() }); + // Checked on the connection that carries the shutdown: a daemon without the capability + // would close the terminals it was asked to keep. + if (keepTerminals) requireTerminalKeepCapability(client, describeDaemonTarget(target)); + await client.shutdownServer({ timeout: remaining(), keepTerminals }); } finally { await client.close(); } @@ -32,6 +60,11 @@ export async function runStopCommand(options: CommandOptions, _command: Command) code: "INVALID_OPTIONS", message: "--force requires a local --home; an endpoint gives no remote process authority.", }; + if (options.force && keepTerminals) + throw { + code: "INVALID_OPTIONS", + message: "--force kills terminals; it cannot be combined with --keep-terminals.", + }; const result: { action: string; home?: string; @@ -44,6 +77,7 @@ export async function runStopCommand(options: CommandOptions, _command: Command) ? { ...(await stopDaemonInstance(target.home, { force: options.force === true, + keepTerminals, timeoutMs, killTimeoutMs: parseTimeoutMs(options.killTimeout, 3_000), requestShutdown, diff --git a/packages/cli/tests/45-daemon-terminals-survive.test.ts b/packages/cli/tests/45-daemon-terminals-survive.test.ts new file mode 100644 index 0000000000..7804ea6917 --- /dev/null +++ b/packages/cli/tests/45-daemon-terminals-survive.test.ts @@ -0,0 +1,324 @@ +#!/usr/bin/env npx tsx + +/** + * Terminals survive `paseo daemon restart` and `stop --keep-terminals`; `restart + * --kill-terminals`, `stop` and `stop --force` close them. Runs the built CLI and daemon in a + * throwaway home; every process it starts is stopped in `finally`. + */ + +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { existsSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { mkdtemp, mkdir, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { readDaemonInstance } from "@getpaseo/server/daemon-control"; +import { runLocalPaseo } from "./helpers/local-cli.ts"; +import { getAvailablePort } from "./helpers/network.ts"; + +if (process.platform === "win32") { + console.log("Skipping terminal survival CLI test on Windows (POSIX shell terminals)."); + process.exit(0); +} + +console.log("=== Daemon terminals survive restart ===\n"); + +const paseoHome = await mkdtemp(join(tmpdir(), "paseo-terminals-survive-")); +const workDir = join(paseoHome, "work"); +await mkdir(workDir, { recursive: true }); +const port = await getAvailablePort(); +const env = { + PASEO_HOME: paseoHome, + PASEO_LOCAL_SPEECH_AUTO_DOWNLOAD: "0", + PASEO_DICTATION_ENABLED: "0", + PASEO_VOICE_MODE_ENABLED: "0", + // The daemon inherits this; terminals then run a plain POSIX shell with no startup files. + SHELL: "/bin/sh", +}; + +function isAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +async function waitFor( + probe: () => Promise | T | null | false, + message: string, + timeoutMs = 30_000, +): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const value = await probe(); + if (value) return value; + await new Promise((resolve) => setTimeout(resolve, 100)); + } + throw new Error(message); +} + +async function paseo(args: string[], expectSuccess = true) { + const result = await runLocalPaseo(args, env); + if (expectSuccess) { + assert.equal( + result.exitCode, + 0, + `paseo ${args.join(" ")} failed:\nstdout:\n${result.stdout}\nstderr:\n${result.stderr}`, + ); + } + return result; +} + +async function json(args: string[]): Promise { + return JSON.parse((await paseo([...args, "--json"])).stdout) as T; +} + +async function capture(terminalId: string): Promise { + const { lines } = await json<{ lines: string[] }>(["terminal", "capture", terminalId]); + return lines.join("\n"); +} + +async function waitForScreen(terminalId: string, text: string): Promise { + await waitFor( + async () => (await capture(terminalId)).includes(text), + `terminal ${terminalId} never showed ${text}:\n${await capture(terminalId)}`, + ); +} + +async function terminalIds(): Promise { + return (await json>(["terminal", "ls", "--all"])).map((t) => t.id); +} + +// Worker records and the cleanup records a kill that could not finish leaves beside them. +function workerRecordCount(): number { + const dir = join(paseoHome, "terminal-worker"); + return existsSync(dir) + ? readdirSync(dir).filter((name) => /^(\d+|closing-.+)\.json$/.test(name)).length + : 0; +} + +// A shell terminal that reports its pid and prints a marker. +async function openTerminal(name: string): Promise<{ id: string; pid: number }> { + const terminal = await json<{ id: string }>([ + "terminal", + "create", + "--cwd", + workDir, + "--name", + name, + ]); + const pidFile = join(workDir, `${name}.pid`); + await paseo([ + "terminal", + "send-keys", + terminal.id, + "-l", + `echo $$ > '${pidFile}'; echo MARKER-${name}`, + ]); + await paseo(["terminal", "send-keys", terminal.id, "Enter"]); + const pid = await waitFor( + () => + existsSync(pidFile) && readFileSync(pidFile, "utf8").trim() + ? Number(readFileSync(pidFile, "utf8")) + : null, + `terminal ${name} never wrote its pid`, + ); + await waitForScreen(terminal.id, `MARKER-${name}`); + return { id: terminal.id, pid }; +} + +async function expectKept(terminal: { id: string; pid: number }, name: string, trigger: string) { + assert((await terminalIds()).includes(terminal.id), `${trigger}: terminal is still listed`); + assert(isAlive(terminal.pid), `${trigger}: terminal program is still alive`); + assert((await capture(terminal.id)).includes(`MARKER-${name}`), `${trigger}: marker is kept`); + await paseo(["terminal", "send-keys", terminal.id, "-l", `echo after-${trigger}`]); + await paseo(["terminal", "send-keys", terminal.id, "Enter"]); + await waitForScreen(terminal.id, `\nafter-${trigger}`); +} + +async function expectClosed(pid: number, trigger: string) { + await waitFor(() => !isAlive(pid), `${trigger}: terminal program ${pid} is still alive`, 15_000); +} + +// A zombie: a real process with a birth time that SIGKILL cannot remove while its parent (an +// exec'd `sleep` that never waits) lives. Cleanup can only report it as still alive. +async function startZombie(): Promise<{ zombiePid: number; parentPid: number }> { + const parent = spawn("/bin/sh", ["-c", "sleep 0 & echo $!; exec sleep 600"], { + stdio: ["ignore", "pipe", "ignore"], + }); + const zombiePid = await new Promise((resolve) => { + parent.stdout!.once("data", (chunk: Buffer) => resolve(Number(chunk.toString().trim()))); + }); + parent.unref(); + await waitFor( + async () => (await psField(zombiePid, "stat")).startsWith("Z"), + `process ${zombiePid} never became a zombie`, + ); + return { zombiePid, parentPid: parent.pid! }; +} + +async function psField(pid: number, field: "stat" | "lstart"): Promise { + const child = spawn("ps", ["-o", `${field}=`, "-p", String(pid)], { + env: { ...process.env, LC_ALL: "C" }, + stdio: ["ignore", "pipe", "ignore"], + }); + let out = ""; + child.stdout.on("data", (chunk: Buffer) => (out += chunk.toString())); + await new Promise((resolve) => child.once("close", resolve)); + return out.trim(); +} + +async function goneProcessPid(): Promise { + const child = spawn(process.execPath, ["-e", ""], { stdio: "ignore" }); + await new Promise((resolve) => child.once("exit", resolve)); + return child.pid!; +} + +// A record as a dead terminal worker leaves it, naming one terminal program that is a zombie. +async function plantRecordNaming(programPid: number): Promise { + const workerPid = await goneProcessPid(); + const record = { + recordId: "planted-record", + pid: workerPid, + bootId: null, + createdAt: new Date().toISOString(), + identity: { startedAt: "Thu Jan 1 00:00:00 1970", commandLine: "planted-worker" }, + protocolVersion: 1, + paseoVersion: "0.0.0-test", + socketPath: join(paseoHome, "planted-worker.sock"), + secret: "planted-secret", + terminals: [ + { id: "planted-terminal", pid: programPid, startedAt: await psField(programPid, "lstart") }, + ], + }; + writeFileSync( + join(paseoHome, "terminal-worker", `${workerPid}.json`), + `${JSON.stringify(record, null, 2)}\n`, + { mode: 0o600 }, + ); +} + +const trackedPids: number[] = []; + +try { + for (const [field, value] of [ + ["daemon.listen", `127.0.0.1:${port}`], + ["daemon.relay.enabled", "false"], + ["features.dictation.enabled", "false"], + ["features.voiceMode.enabled", "false"], + ] as const) { + await paseo(["daemon", "config", "set", field, value]); + } + await paseo(["daemon", "start"]); + + console.log("Test 1: daemon restart keeps the terminal"); + const kept = await openTerminal("kept"); + trackedPids.push(kept.pid); + await paseo(["daemon", "restart", "--home", paseoHome]); + await expectKept(kept, "kept", "restart"); + console.log("✓ same id, same program, marker and input after restart\n"); + + console.log("Test 2: stop --keep-terminals, then start, gives the terminal back"); + const forceAndKeep = await paseo( + ["daemon", "stop", "--home", paseoHome, "--force", "--keep-terminals"], + false, + ); + assert.notEqual(forceAndKeep.exitCode, 0, "--force with --keep-terminals is refused"); + await paseo(["daemon", "stop", "--home", paseoHome, "--keep-terminals"]); + assert.equal(await readDaemonInstance(paseoHome), null, "the supervisor stopped"); + assert(isAlive(kept.pid), "the program outlives the stopped daemon"); + await paseo(["daemon", "start"]); + await expectKept(kept, "kept", "keep-stop"); + console.log("✓ adopted with the same id and still usable\n"); + + console.log("Test 3: a plain stop with no daemon running closes kept terminals"); + await paseo(["daemon", "stop", "--home", paseoHome, "--keep-terminals"]); + assert(isAlive(kept.pid), "kept again"); + await paseo(["daemon", "stop", "--home", paseoHome]); + await expectClosed(kept.pid, "stop without a supervisor"); + assert.equal(workerRecordCount(), 0, "no worker record is left"); + console.log("✓ closed\n"); + + console.log("Test 4: restart --kill-terminals closes the terminal"); + await paseo(["daemon", "start"]); + const killedByRestart = await openTerminal("restart-kill"); + trackedPids.push(killedByRestart.pid); + await paseo(["daemon", "restart", "--home", paseoHome, "--kill-terminals"]); + await expectClosed(killedByRestart.pid, "restart --kill-terminals"); + assert.deepEqual(await terminalIds(), [], "no terminal is listed after the kill restart"); + console.log("✓ closed\n"); + + console.log("Test 5: daemon stop closes the terminal and its worker"); + const killedByStop = await openTerminal("stop-kill"); + trackedPids.push(killedByStop.pid); + await paseo(["daemon", "stop", "--home", paseoHome]); + await expectClosed(killedByStop.pid, "stop"); + assert.equal(workerRecordCount(), 0, "no worker record is left"); + console.log("✓ closed\n"); + + console.log("Test 6: daemon stop --force closes the terminal"); + await paseo(["daemon", "start"]); + const killedByForce = await openTerminal("force-kill"); + trackedPids.push(killedByForce.pid); + await paseo(["daemon", "stop", "--home", paseoHome, "--force"]); + await expectClosed(killedByForce.pid, "stop --force"); + assert.equal(workerRecordCount(), 0, "no worker record is left"); + console.log("✓ closed\n"); + + const endpoint = `127.0.0.1:${port}`; + console.log("Test 7: restart --host --kill-terminals closes the terminal"); + await paseo(["daemon", "start"]); + const killedByEndpointRestart = await openTerminal("endpoint-restart-kill"); + trackedPids.push(killedByEndpointRestart.pid); + await paseo(["daemon", "restart", "--host", endpoint, "--kill-terminals"]); + await expectClosed(killedByEndpointRestart.pid, "restart --host --kill-terminals"); + assert.deepEqual(await terminalIds(), [], "no terminal is listed after the kill restart"); + console.log("✓ closed and confirmed by the replacement\n"); + + console.log("Test 8: restart --host --kill-terminals reports a process cleanup could not end"); + const zombie = await startZombie(); + trackedPids.push(zombie.parentPid); + await plantRecordNaming(zombie.zombiePid); + const unconfirmed = await paseo( + ["daemon", "restart", "--host", endpoint, "--kill-terminals"], + false, + ); + assert.notEqual(unconfirmed.exitCode, 0, "the kill restart fails"); + const output = unconfirmed.stdout + unconfirmed.stderr; + assert(output.includes("Terminal cleanup was not confirmed"), `names the failure:\n${output}`); + assert(output.includes(`pid ${zombie.zombiePid}`), `names the surviving pid:\n${output}`); + process.kill(zombie.parentPid, "SIGKILL"); + await expectClosed(zombie.zombiePid, "zombie reaped once its parent exits"); + await paseo(["daemon", "stop", "--home", paseoHome]); + assert.equal(workerRecordCount(), 0, "the next stop retries the cleanup and retires the record"); + console.log("✓ reported, then retried by stop\n"); + + console.log("Test 9: restart --host --kill-terminals reports a worker record it cannot read"); + await paseo(["daemon", "start"]); + // A kill cleanup cannot check what an unreadable record names, and leaves nothing else + // behind, so the replacement daemon must still report it. + const unreadablePath = join(paseoHome, "terminal-worker", `${await goneProcessPid()}.json`); + writeFileSync(unreadablePath, "{ not json", { mode: 0o600 }); + const unreadable = await paseo( + ["daemon", "restart", "--host", endpoint, "--kill-terminals"], + false, + ); + assert.notEqual(unreadable.exitCode, 0, "the kill restart fails"); + const unreadableOutput = unreadable.stdout + unreadable.stderr; + assert(unreadableOutput.includes(unreadablePath), `names the record:\n${unreadableOutput}`); + assert(existsSync(unreadablePath), "the unreadable record is kept"); + rmSync(unreadablePath); + await paseo(["daemon", "stop", "--home", paseoHome]); + assert.equal(workerRecordCount(), 0, "no worker record is left"); + console.log("✓ reported with the record's path\n"); +} finally { + await runLocalPaseo(["daemon", "stop", "--home", paseoHome, "--force"], env); + for (const pid of trackedPids) { + if (isAlive(pid)) process.kill(pid, "SIGKILL"); + } + await rm(paseoHome, { recursive: true, force: true }); +} + +console.log("=== Daemon terminals survive restart passed ==="); diff --git a/packages/cli/tests/46-daemon-terminal-worker-upgrade.test.ts b/packages/cli/tests/46-daemon-terminal-worker-upgrade.test.ts new file mode 100644 index 0000000000..ff8ef6bc6f --- /dev/null +++ b/packages/cli/tests/46-daemon-terminal-worker-upgrade.test.ts @@ -0,0 +1,527 @@ +#!/usr/bin/env npx tsx + +/** + * A terminal worker survives an upgrade of the installation that started it. Two disposable + * installations A and B (built dist, real copies of @getpaseo/server, @getpaseo/cli and + * node-pty, every other dependency a symlink into this repo) each get their own CLI shim, so + * each daemon's PASEO_CLI is a distinct path: + * + * 1. A daemon from A runs its worker from a copy in $PASEO_HOME/terminal-worker/. After + * `stop --keep-terminals` and moving A's node-pty, worker bundle and shell integration away, + * a daemon from B adopts the same worker and opens a new, working terminal in it with B's + * environment and CLI, while the first terminal keeps A's. + * 2. Worker protocol versions (PASEO_TERMINAL_WORKER_PROTOCOL_OVERRIDE): a worker one version + * old drains (keeps its terminal, new ones open in a second worker, it exits after its last + * terminal and its copy is deleted); one two versions old is shut down; one from a newer + * Paseo is left running, reported as terminal_worker_incompatible, and closed by + * `daemon stop`. + * + * Every process it starts is stopped in `finally`. + */ + +import assert from "node:assert/strict"; +import { execFile } from "node:child_process"; +import { + chmodSync, + cpSync, + existsSync, + mkdirSync, + readdirSync, + readFileSync, + renameSync, + symlinkSync, + writeFileSync, +} from "node:fs"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { getAvailablePort } from "./helpers/network.ts"; + +if (process.platform === "win32") { + console.log("Skipping terminal worker upgrade CLI test on Windows (POSIX shell terminals)."); + process.exit(0); +} + +console.log("=== Terminal worker survives an upgrade ===\n"); + +const repoRoot = join(import.meta.dirname, "..", "..", ".."); +const root = await mkdtemp(join(tmpdir(), "paseo-worker-upgrade-")); +const paseoHome = join(root, "home"); +const cliHome = join(root, "os-home"); +const workDir = join(root, "work"); +for (const dir of [paseoHome, cliHome, workDir]) mkdirSync(dir, { recursive: true }); +const port = await getAvailablePort(); +const zsh = ["/bin/zsh", "/usr/bin/zsh"].find((candidate) => existsSync(candidate)) ?? null; + +interface Installation { + name: string; + dir: string; + version: string; + shim: string; + serverDir: string; +} + +// --------------------------------------------------------------------------------------------- +// Installation fixtures +// --------------------------------------------------------------------------------------------- + +function linkEntries(source: string, target: string, taken: Set): void { + if (!existsSync(source)) return; + for (const name of readdirSync(source)) { + if (name.startsWith(".")) continue; + if (name.startsWith("@")) { + mkdirSync(join(target, name), { recursive: true }); + for (const scoped of readdirSync(join(source, name))) { + const key = `${name}/${scoped}`; + if (taken.has(key)) continue; + taken.add(key); + symlinkSync(join(source, name, scoped), join(target, name, scoped)); + } + continue; + } + if (taken.has(name)) continue; + taken.add(name); + symlinkSync(join(source, name), join(target, name)); + } +} + +function createInstallation(name: string, version: string): Installation { + const dir = join(root, `install-${name}`); + const modules = join(dir, "node_modules"); + mkdirSync(join(modules, "@getpaseo"), { recursive: true }); + + // Real copies: the server (its version marks the installation), the CLI (so it resolves this + // installation's server), and node-pty (so moving it away breaks only this installation). + const serverDir = join(modules, "@getpaseo", "server"); + const serverPackage = JSON.parse( + readFileSync(join(repoRoot, "packages/server/package.json"), "utf8"), + ) as Record; + mkdirSync(join(serverDir, "dist"), { recursive: true }); + writeFileSync( + join(serverDir, "package.json"), + `${JSON.stringify({ ...serverPackage, version }, null, 2)}\n`, + ); + for (const part of ["server", "src", "scripts"]) { + cpSync(join(repoRoot, "packages/server/dist", part), join(serverDir, "dist", part), { + recursive: true, + }); + } + const cliDir = join(modules, "@getpaseo", "cli"); + mkdirSync(cliDir, { recursive: true }); + cpSync(join(repoRoot, "packages/cli/package.json"), join(cliDir, "package.json")); + cpSync(join(repoRoot, "packages/cli/dist"), join(cliDir, "dist"), { recursive: true }); + cpSync(join(repoRoot, "packages/server/node_modules/node-pty"), join(modules, "node-pty"), { + recursive: true, + }); + + const taken = new Set(["@getpaseo/server", "@getpaseo/cli", "node-pty"]); + for (const source of [ + "packages/server/node_modules", + "packages/cli/node_modules", + "node_modules", + ]) { + linkEntries(join(repoRoot, source), modules, taken); + } + + const shim = join(dir, "bin", "paseo"); + mkdirSync(join(dir, "bin")); + writeFileSync( + shim, + `#!/bin/sh\nexec "${process.execPath}" "${join(cliDir, "dist", "index.js")}" "$@"\n`, + ); + chmodSync(shim, 0o755); + return { name, dir, version, shim, serverDir }; +} + +// The runtime files an upgrade replaces: node-pty, the worker bundle, the shell integration. +function moveRuntimeAway(installation: Installation): () => void { + const away = join(installation.dir, "moved-away"); + const moves = [ + join(installation.dir, "node_modules", "node-pty"), + join(installation.serverDir, "dist", "server", "terminal-worker"), + join(installation.serverDir, "dist", "server", "terminal", "shell-integration"), + ].map((from, index) => ({ from, to: join(away, String(index)) })); + mkdirSync(away, { recursive: true }); + for (const move of moves) renameSync(move.from, move.to); + return () => { + for (const move of moves) renameSync(move.to, move.from); + }; +} + +// --------------------------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------------------------- + +function isAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +async function waitFor( + probe: () => Promise | T | null | false, + message: () => string | Promise, + timeoutMs = 30_000, +): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const value = await probe(); + if (value) return value; + await new Promise((resolve) => setTimeout(resolve, 100)); + } + throw new Error(await message()); +} + +interface RunResult { + exitCode: number; + stdout: string; + stderr: string; +} + +function run( + installation: Installation, + args: string[], + extraEnv: Record = {}, +): Promise { + const env = { + ...Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("PASEO_"))), + HOME: cliHome, + USERPROFILE: cliHome, + PASEO_HOME: paseoHome, + PASEO_LOCAL_SPEECH_AUTO_DOWNLOAD: "0", + PASEO_DICTATION_ENABLED: "0", + PASEO_VOICE_MODE_ENABLED: "0", + // Each daemon hands its terminals its own installation's CLI. + PASEO_CLI: installation.shim, + PASEO_TEST_INSTALL: installation.name, + SHELL: "/bin/sh", + ...extraEnv, + }; + return new Promise((resolve) => { + execFile(installation.shim, args, { env, timeout: 120_000 }, (error, stdout, stderr) => { + let exitCode = 0; + if (error) exitCode = typeof error.code === "number" ? error.code : 1; + resolve({ exitCode, stdout, stderr }); + }); + }); +} + +async function paseo( + installation: Installation, + args: string[], + extraEnv: Record = {}, +): Promise { + const result = await run(installation, args, extraEnv); + assert.equal( + result.exitCode, + 0, + `paseo ${args.join(" ")} (${installation.name}) failed:\nstdout:\n${result.stdout}\nstderr:\n${result.stderr}`, + ); + return result; +} + +async function json(installation: Installation, args: string[]): Promise { + return JSON.parse((await paseo(installation, [...args, "--json"])).stdout) as T; +} + +async function capture(installation: Installation, terminalId: string): Promise { + const { lines } = await json<{ lines: string[] }>(installation, [ + "terminal", + "capture", + terminalId, + ]); + return lines.join("\n"); +} + +async function type(installation: Installation, terminalId: string, line: string) { + await paseo(installation, ["terminal", "send-keys", terminalId, "-l", line]); + await paseo(installation, ["terminal", "send-keys", terminalId, "Enter"]); +} + +async function waitForScreen(installation: Installation, terminalId: string, text: string) { + await waitFor( + async () => (await capture(installation, terminalId)).includes(text), + async () => + `terminal ${terminalId} never showed ${text}:\n${await capture(installation, terminalId)}`, + ); +} + +// Opens a terminal, records its shell's pid, and prints a marker. +async function openTerminal( + installation: Installation, + name: string, +): Promise<{ id: string; pid: number }> { + const terminal = await json<{ id: string }>(installation, [ + "terminal", + "create", + "--cwd", + workDir, + "--name", + name, + ]); + const pidFile = join(workDir, `${name}.pid`); + await type(installation, terminal.id, `echo $$ > '${pidFile}'; echo MARKER-${name}`); + const pid = await waitFor( + () => + existsSync(pidFile) && readFileSync(pidFile, "utf8").trim() + ? Number(readFileSync(pidFile, "utf8")) + : null, + () => `terminal ${name} never wrote its pid`, + ); + await waitForScreen(installation, terminal.id, `MARKER-${name}`); + trackedPids.push(pid); + return { id: terminal.id, pid }; +} + +// The value of `$variable` in the terminal's shell, written to a file (a long path would wrap +// on screen). +async function echoVariable( + installation: Installation, + terminalId: string, + label: string, + variable: string, +): Promise { + const valueFile = join(workDir, `${label}.value`); + await type( + installation, + terminalId, + `printf '%s' "$${variable}" > '${valueFile}.tmp' && mv '${valueFile}.tmp' '${valueFile}'`, + ); + await waitFor( + () => existsSync(valueFile), + async () => + `terminal ${terminalId} never wrote ${label}:\n${await capture(installation, terminalId)}`, + ); + return readFileSync(valueFile, "utf8"); +} + +interface WorkerRecordFile { + pid: number; + protocolVersion: unknown; + runtime?: string | null; + terminals: Array<{ id: string; pid: number }>; +} + +function workerRecords(): WorkerRecordFile[] { + const dir = join(paseoHome, "terminal-worker"); + if (!existsSync(dir)) return []; + return readdirSync(dir) + .filter((name) => /^\d+\.json$/.test(name)) + .map((name) => JSON.parse(readFileSync(join(dir, name), "utf8")) as WorkerRecordFile); +} + +function runtimeCopies(): string[] { + const dir = join(paseoHome, "terminal-worker"); + if (!existsSync(dir)) return []; + return readdirSync(dir).filter((name) => + existsSync(join(dir, name, "paseo-terminal-worker-runtime.json")), + ); +} + +function commandLineOf(pid: number): Promise { + return new Promise((resolve) => { + execFile("ps", ["-ww", "-o", "command=", "-p", String(pid)], (_error, stdout) => + resolve(stdout.trim()), + ); + }); +} + +async function terminalIds(installation: Installation): Promise { + return (await json>(installation, ["terminal", "ls", "--all"])).map( + (terminal) => terminal.id, + ); +} + +async function startDaemon(installation: Installation, extraEnv: Record = {}) { + await paseo(installation, ["daemon", "start"], extraEnv); +} + +async function stopDaemon(installation: Installation, keepTerminals = false) { + await paseo(installation, [ + "daemon", + "stop", + "--home", + paseoHome, + ...(keepTerminals ? ["--keep-terminals"] : []), + ]); +} + +// A terminal in a worker reporting `protocolVersion`, left running by `stop --keep-terminals`. +async function leaveWorkerWithProtocol( + installation: Installation, + protocolVersion: number, + name: string, +): Promise<{ terminal: { id: string; pid: number }; workerPid: number; runtime: string }> { + await startDaemon(installation, { + PASEO_TERMINAL_WORKER_PROTOCOL_OVERRIDE: String(protocolVersion), + }); + const terminal = await openTerminal(installation, name); + const [worker] = workerRecords(); + assert(worker, "the daemon started a worker"); + assert.equal(worker.protocolVersion, protocolVersion, "the worker reports the override"); + await stopDaemon(installation, true); + return { terminal, workerPid: worker.pid, runtime: worker.runtime! }; +} + +const trackedPids: number[] = []; +const a = createInstallation("A", "0.98.0"); +const b = createInstallation("B", "0.99.0"); +let restoreA: (() => void) | null = null; +let passed = false; + +try { + for (const [field, value] of [ + ["daemon.listen", `127.0.0.1:${port}`], + ["daemon.relay.enabled", "false"], + ["features.dictation.enabled", "false"], + ["features.voiceMode.enabled", "false"], + ] as const) { + await paseo(a, ["daemon", "config", "set", field, value]); + } + + console.log("Test 1: a daemon from A runs its worker from a copy in the home"); + await startDaemon(a); + const t1 = await openTerminal(a, "t1"); + const [firstWorker] = workerRecords(); + assert(firstWorker, "one worker runs"); + assert.match(firstWorker.runtime ?? "", /^0\.98\.0-[0-9a-f]{12}$/); + const copyA = join(paseoHome, "terminal-worker", firstWorker.runtime!); + assert( + (await commandLineOf(firstWorker.pid)).includes(join(copyA, "terminal-worker.mjs")), + "the worker runs the copy's bundle", + ); + assert.equal(await echoVariable(a, t1.id, "CLI1", "PASEO_CLI"), a.shim, "T1 has A's CLI"); + console.log("✓ worker runs from", copyA, "\n"); + + console.log("Test 2: B adopts the worker after A's runtime files are gone"); + await stopDaemon(a, true); + restoreA = moveRuntimeAway(a); + await startDaemon(b, zsh ? { SHELL: zsh } : {}); + assert.deepEqual( + workerRecords().map((record) => record.pid), + [firstWorker.pid], + "B adopted the same worker instead of starting one", + ); + assert((await terminalIds(b)).includes(t1.id), "T1 is listed by B"); + const t2 = await openTerminal(b, "t2"); + assert.equal(await echoVariable(b, t2.id, "INSTALL2", "PASEO_TEST_INSTALL"), "B"); + assert.equal(await echoVariable(b, t2.id, "CLI2", "PASEO_CLI"), b.shim, "T2 has B's CLI"); + if (zsh) { + // Creating a zsh terminal reads Paseo's integration from the worker's copy (A's is gone); + // a missing file would have failed the create. + const zshVersion = await echoVariable(b, t2.id, "ZSH", "ZSH_VERSION"); + assert(zshVersion.length > 0, "T2 runs zsh with Paseo's shell integration"); + } else { + console.log(" (zsh is not installed: the shell-integration check is skipped)"); + } + assert.equal(await echoVariable(b, t1.id, "CLI1AGAIN", "PASEO_CLI"), a.shim, "T1 keeps A's CLI"); + console.log("✓ same worker, T2 uses B's environment, T1 still works\n"); + + console.log("Test 3: daemon stop closes both terminals and deletes the copy"); + await stopDaemon(b); + await waitFor( + () => !isAlive(t1.pid) && !isAlive(t2.pid) && !isAlive(firstWorker.pid), + () => "terminals or worker outlived daemon stop", + ); + assert.deepEqual(workerRecords(), [], "no worker record is left"); + assert.deepEqual(runtimeCopies(), [], "no copy is left"); + restoreA(); + restoreA = null; + console.log("✓ closed and cleaned up\n"); + + console.log("Test 4: a worker one protocol version old drains"); + const old = await leaveWorkerWithProtocol(a, 0, "t3"); + await startDaemon(b); + const workers = workerRecords(); + assert.equal(workers.length, 2, "the old worker drains beside a new one"); + const current = workers.find((record) => record.pid !== old.workerPid)!; + assert.equal(current.protocolVersion, 1); + assert.match(current.runtime ?? "", /^0\.99\.0-/); + assert((await terminalIds(b)).includes(old.terminal.id), "the old worker's terminal is listed"); + await type(b, old.terminal.id, "echo still-served"); + await waitForScreen(b, old.terminal.id, "\nstill-served"); + const t4 = await openTerminal(b, "t4"); + assert.deepEqual( + workerRecords() + .find((record) => record.pid === current.pid)! + .terminals.map((terminal) => terminal.id), + [t4.id], + "new terminals open in the current worker", + ); + await paseo(b, ["terminal", "kill", old.terminal.id]); + await waitFor( + () => !isAlive(old.workerPid), + () => `the drained worker ${old.workerPid} did not exit`, + ); + await waitFor( + () => !runtimeCopies().includes(old.runtime), + () => `the drained worker's copy ${old.runtime} was not deleted: ${runtimeCopies().join(", ")}`, + ); + assert.deepEqual(runtimeCopies(), [current.runtime], "the current worker's copy stays"); + await type(b, t4.id, "echo after-drain"); + await waitForScreen(b, t4.id, "\nafter-drain"); + await stopDaemon(b); + console.log("✓ drained, exited, copy deleted\n"); + + console.log("Test 5: a worker two protocol versions old is shut down"); + const obsolete = await leaveWorkerWithProtocol(a, -1, "t5"); + await startDaemon(b); + await waitFor( + () => !isAlive(obsolete.workerPid) && !isAlive(obsolete.terminal.pid), + () => "the obsolete worker or its terminal survived", + ); + assert(!(await terminalIds(b)).includes(obsolete.terminal.id), "its terminal is gone"); + assert.equal(workerRecords().length, 1, "one current worker runs"); + await stopDaemon(b); + console.log("✓ shut down\n"); + + console.log("Test 6: a worker from a newer Paseo is left running and reported"); + const newer = await leaveWorkerWithProtocol(a, 2, "t6"); + await startDaemon(b); + const listed = await run(b, ["terminal", "ls", "--all", "--json"]); + assert.notEqual(listed.exitCode, 0, "terminal ls fails"); + assert.match(listed.stdout + listed.stderr, /held by a newer Paseo \(v0\.98\.0/); + const created = await run(b, ["terminal", "create", "--cwd", workDir, "--json"]); + assert.notEqual(created.exitCode, 0, "terminal create fails"); + assert.match(created.stdout + created.stderr, /held by a newer Paseo/); + const status = await paseo(b, ["daemon", "status", "--home", paseoHome]); + assert.match(status.stdout, /terminals: Terminals are held by a newer Paseo/); + assert(isAlive(newer.terminal.pid), "its program keeps running"); + assert.deepEqual( + workerRecords().map((record) => record.pid), + [newer.workerPid], + "no second worker starts", + ); + await stopDaemon(b); + await waitFor( + () => !isAlive(newer.workerPid) && !isAlive(newer.terminal.pid), + () => "daemon stop left the newer worker or its terminal running", + ); + assert.deepEqual(workerRecords(), [], "no worker record is left"); + assert.deepEqual(runtimeCopies(), [], "no copy is left"); + console.log("✓ reported, untouched, closed by stop\n"); + passed = true; +} finally { + if (!passed) { + for (const log of ["daemon.log", "terminal-worker.log"]) { + const logPath = join(paseoHome, log); + if (existsSync(logPath)) { + console.error(`--- ${log} (last 60 lines) ---`); + console.error(readFileSync(logPath, "utf8").split("\n").slice(-60).join("\n")); + } + } + } + restoreA?.(); + for (const installation of [b, a]) { + await run(installation, ["daemon", "stop", "--home", paseoHome, "--force"]); + } + for (const pid of trackedPids) { + if (isAlive(pid)) process.kill(pid, "SIGKILL"); + } + await rm(root, { recursive: true, force: true }); +} + +console.log("=== Terminal worker survives an upgrade passed ==="); diff --git a/packages/client/src/daemon-client.ts b/packages/client/src/daemon-client.ts index bca3d00301..d4b0f28a39 100644 --- a/packages/client/src/daemon-client.ts +++ b/packages/client/src/daemon-client.ts @@ -781,6 +781,9 @@ type ShutdownRequestedStatusPayload = z.infer, + target: string, +): void { + const serverInfo = client.getLastServerInfoMessage(); + if (serverInfo?.features?.terminalsSurviveRestart !== true) { + throw new TerminalKeepUnsupportedError(target, serverInfo?.version ?? null); + } +} + function buildFetchAgentsRequest( options: FetchAgentsOptions | undefined, requestId: string, @@ -4071,13 +4104,14 @@ export class DaemonClient { async restartServer( reason?: string, requestId?: string, - options?: { timeout?: number }, + options?: { timeout?: number; killTerminals?: boolean }, ): Promise { const resolvedRequestId = this.createRequestId(requestId); const message = SessionInboundMessageSchema.parse({ type: "restart_server_request", ...(reason && reason.trim().length > 0 ? { reason } : {}), requestId: resolvedRequestId, + ...(options?.killTerminals ? { killTerminals: true } : {}), }); return this.sendRequest({ requestId: resolvedRequestId, @@ -4105,6 +4139,7 @@ export class DaemonClient { const message = SessionInboundMessageSchema.parse({ type: "shutdown_server_request", requestId: resolvedRequestId, + ...(options?.keepTerminals ? { keepTerminals: true } : {}), }); return this.sendRequest({ requestId: resolvedRequestId, diff --git a/packages/desktop/src/daemon/cli/external.ts b/packages/desktop/src/daemon/cli/external.ts index 6c9deeccb1..4a55adff1c 100644 --- a/packages/desktop/src/daemon/cli/external.ts +++ b/packages/desktop/src/daemon/cli/external.ts @@ -4,6 +4,31 @@ import type { NodeEntrypointInvocation } from "../node-entrypoint-launcher.js"; import { createNodeEntrypointInvocation } from "../runtime-paths.js"; import { resolveExternalCliEntrypoint } from "./entrypoints.js"; +/** A CLI command that exited non-zero, with the `--json` error it printed when there was one. */ +export class ExternalCliCommandError extends Error { + readonly code: string | null; + readonly error: Record | null; + + constructor(message: string, error: Record | null) { + super(message); + this.name = "ExternalCliCommandError"; + this.error = error; + this.code = typeof error?.code === "string" ? error.code : null; + } +} + +// `--json` commands print `{ "error": { code, message, ... } }` on stderr when they fail. +function parseJsonCliError(stderr: string): Record | null { + try { + const parsed = JSON.parse(stderr) as { error?: unknown }; + return typeof parsed.error === "object" && parsed.error !== null + ? (parsed.error as Record) + : null; + } catch { + return null; + } +} + function createExternalCliInvocation(args: string[]): NodeEntrypointInvocation { return createNodeEntrypointInvocation({ entrypoint: resolveExternalCliEntrypoint(), @@ -85,7 +110,10 @@ export async function runExternalCliJsonCommand(args: string[]): Promise ({ paseoHome: "", @@ -73,7 +79,8 @@ vi.mock("./runtime-paths.js", () => ({ })), })); -vi.mock("./cli/external.js", () => ({ +vi.mock("./cli/external.js", async (importOriginal) => ({ + ...(await importOriginal>()), runExternalCliJsonCommand: mocks.runExternalCliJsonCommand, runExternalCliTextCommand: mocks.runExternalCliTextCommand, })); @@ -176,3 +183,107 @@ describe("daemon-manager commands", () => { expect(await handler({ listen: "localhost:6799" })).toBeNull(); }); }); + +describe("desktop stops and terminals", () => { + const reasons: DesktopDaemonStopReason[] = [ + "manual_ipc", + "settings", + "host_remove", + "quit", + "app_update", + "version_mismatch", + "restart", + ]; + + it("keeps terminals only for an app update or version-mismatch restart, never on Windows", () => { + for (const platform of ["darwin", "linux"] as const) { + expect(reasons.filter((reason) => keepsTerminalsOnStop(reason, platform))).toEqual([ + "app_update", + "version_mismatch", + ]); + } + expect(reasons.filter((reason) => keepsTerminalsOnStop(reason, "win32"))).toEqual([]); + }); + + function stopHarness(runCliJson: (args: string[]) => Promise) { + const stops: Array<{ keepTerminals: boolean | undefined }> = []; + const logged: string[] = []; + const instance = { + pid: 4242, + startedAt: "2026-10-21T00:00:00.000Z", + hostname: "host", + uid: 501, + listen: "127.0.0.1:6799", + }; + const stopInstance = (async ( + _home: string, + options: { + keepTerminals?: boolean; + requestShutdown?: (ready: { listen: string }) => Promise; + }, + ) => { + stops.push({ keepTerminals: options.keepTerminals }); + await options.requestShutdown?.({ listen: instance.listen }); + return { action: "stopped", pid: instance.pid, forced: false, usedLifecycleRpc: true }; + }) as unknown as NonNullable[0]["stopInstance"]>; + return { + stops, + logged, + input: { + home: "/tmp/paseo-home", + instance, + stopInstance, + runCliJson, + log: (message: string) => logged.push(message), + } as Omit[0], "reason" | "keepTerminals">, + }; + } + + it("asks the daemon to keep its terminals on an app update", async () => { + const calls: string[][] = []; + const harness = stopHarness(async (args) => { + calls.push(args); + return { action: "shutdown_requested" }; + }); + + await stopCapturedDaemon({ ...harness.input, reason: "app_update", keepTerminals: true }); + + expect(harness.stops).toEqual([{ keepTerminals: true }]); + expect(calls).toEqual([ + ["daemon", "stop", "--host", "127.0.0.1:6799", "--keep-terminals", "--json"], + ]); + }); + + it("stops a daemon without the capability with its terminals closed, and says so", async () => { + const calls: string[][] = []; + const harness = stopHarness(async (args) => { + calls.push(args); + if (args.includes("--keep-terminals")) { + throw new ExternalCliCommandError("refused", { + code: "TERMINALS_KEEP_UNSUPPORTED", + version: "0.11.0", + }); + } + return { action: "shutdown_requested" }; + }); + + await stopCapturedDaemon({ ...harness.input, reason: "app_update", keepTerminals: true }); + + expect(harness.stops).toEqual([{ keepTerminals: true }, { keepTerminals: false }]); + expect(calls[1]).toEqual(["daemon", "stop", "--host", "127.0.0.1:6799", "--json"]); + expect(harness.logged).toContain( + "daemon v0.11.0 cannot keep terminals; stopping it and closing them", + ); + }); + + it("does not retry a keep stop that failed for another reason", async () => { + const harness = stopHarness(async () => { + throw new ExternalCliCommandError("unreachable", { code: "DAEMON_UNREACHABLE" }); + }); + + await expect( + stopCapturedDaemon({ ...harness.input, reason: "app_update", keepTerminals: true }), + ).rejects.toThrow("unreachable"); + expect(harness.stops).toEqual([{ keepTerminals: true }]); + }); +}); diff --git a/packages/desktop/src/daemon/daemon-manager.ts b/packages/desktop/src/daemon/daemon-manager.ts index 5f3f5394c6..769b5513f5 100644 --- a/packages/desktop/src/daemon/daemon-manager.ts +++ b/packages/desktop/src/daemon/daemon-manager.ts @@ -37,7 +37,11 @@ import { closeLocalTransportSession, } from "./local-transport.js"; import { createNodeEntrypointInvocation, resolveDaemonRunnerEntrypoint } from "./runtime-paths.js"; -import { runExternalCliJsonCommand, runExternalCliTextCommand } from "./cli/external.js"; +import { + ExternalCliCommandError, + runExternalCliJsonCommand, + runExternalCliTextCommand, +} from "./cli/external.js"; import { createDesktopSettingsCommandHandlers, type DesktopCommandHandler, @@ -348,18 +352,84 @@ export async function stopDesktopDaemon( "Daemon changed since confirmation; inspect its current home and PID before stopping it.", ); if (!instance || (!owned && !explicit)) return resolveDesktopDaemonStatus(); - logDesktopDaemonLifecycle("stopping captured supervisor", { reason, pid: instance.pid, owned }); - await stopDaemonInstance(home, { - instance, - timeoutMs: 15_000, - requestShutdown: async (ready) => { - await runExternalCliJsonCommand(["daemon", "stop", "--host", ready.listen, "--json"]); - }, + const keepTerminals = keepsTerminalsOnStop(reason, process.platform); + logDesktopDaemonLifecycle("stopping captured supervisor", { + reason, + pid: instance.pid, + owned, + keepTerminals, }); + await stopCapturedDaemon({ home, instance, reason, keepTerminals }); if (owned) ownedLaunch = null; return resolveDesktopDaemonStatus(); } +export interface StopCapturedDaemonInput { + home: string; + instance: DaemonInstance; + reason: DesktopDaemonStopReason; + keepTerminals: boolean; + stopInstance?: typeof stopDaemonInstance; + runCliJson?: typeof runExternalCliJsonCommand; + log?: typeof logDesktopDaemonLifecycle; +} + +/** Stops the supervisor desktop captured, keeping its terminals when asked and supported. */ +export async function stopCapturedDaemon(input: StopCapturedDaemonInput): Promise { + const stopInstance = input.stopInstance ?? stopDaemonInstance; + const runCliJson = input.runCliJson ?? runExternalCliJsonCommand; + const logLifecycle = input.log ?? logDesktopDaemonLifecycle; + const stop = (keep: boolean) => + stopInstance(input.home, { + instance: input.instance, + timeoutMs: 15_000, + keepTerminals: keep, + requestShutdown: async (ready) => { + await runCliJson([ + "daemon", + "stop", + "--host", + ready.listen, + ...(keep ? ["--keep-terminals"] : []), + "--json", + ]); + }, + }); + try { + await stop(input.keepTerminals); + } catch (error) { + // The CLI refuses a keep stop before sending anything when the daemon predates the feature; + // that daemon closes terminals on every stop, as every upgrade did before. + if ( + !input.keepTerminals || + !(error instanceof ExternalCliCommandError) || + error.code !== "TERMINALS_KEEP_UNSUPPORTED" + ) { + throw error; + } + const version = typeof error.error?.version === "string" ? error.error.version : "unknown"; + logLifecycle(`daemon v${version} cannot keep terminals; stopping it and closing them`, { + reason: input.reason, + pid: input.instance.pid, + }); + await stop(false); + } +} + +/** + * Whether a desktop stop keeps the daemon's terminals running for the daemon that replaces it. + * Only when one comes straight back (an app update, a version-mismatch restart), and never on + * Windows: a surviving terminal worker runs Paseo.exe and would lock the install folder the + * update replaces. Quit, Settings, host removal and manual stops close terminals. + */ +export function keepsTerminalsOnStop( + reason: DesktopDaemonStopReason, + platform: NodeJS.Platform, +): boolean { + if (platform === "win32") return false; + return reason === "app_update" || reason === "version_mismatch"; +} + async function restartDaemon(): Promise { await runExternalCliJsonCommand(["daemon", "restart", "--home", getPaseoHome(), "--json"]); return resolveDesktopDaemonStatus(); diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index 92d6ec71e1..26a90016a7 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -1896,11 +1896,17 @@ export const RestartServerRequestMessageSchema = z.object({ type: z.literal("restart_server_request"), reason: z.string().optional(), requestId: z.string(), + // Restart keeps terminals unless this is true. Daemons that predate + // `features.terminalsSurviveRestart` ignore it and close terminals anyway. + killTerminals: z.boolean().optional(), }); export const ShutdownServerRequestMessageSchema = z.object({ type: z.literal("shutdown_server_request"), requestId: z.string(), + // Shutdown closes terminals unless this is true. Gate on + // `features.terminalsSurviveRestart`: older daemons drop the field. + keepTerminals: z.boolean().optional(), }); export const DaemonUpdateRequestMessageSchema = z.object({ @@ -3763,6 +3769,8 @@ export const ServerInfoStatusPayloadSchema = z daemonDiagnostics: z.boolean().optional(), // COMPAT(daemonSelfUpdate): added in v0.1.93, remove gate after 2026-12-13. daemonSelfUpdate: z.boolean().optional(), + // COMPAT(terminalsSurviveRestart): added in v0.12.0, remove gate after 2027-04-21. + terminalsSurviveRestart: z.boolean().optional(), // COMPAT(agentForkContext): added in v0.1.102, remove gate after 2026-12-28. agentForkContext: z.boolean().optional(), // COMPAT(agentForkContextCursor): added in v0.1.108, remove gate after 2027-01-14. @@ -5125,6 +5133,22 @@ export const DaemonGetStatusResponseSchema = z.object({ error: z.string().nullable().optional(), }), ), + // Processes a terminal cleanup on this host (a kill restart or stop) could not confirm + // gone; empty when every cleanup finished. Daemons without terminalsSurviveRestart have + // no such cleanup and omit it. + terminalCleanupUnconfirmed: z + .array( + z.object({ + pid: z.number(), + role: z.string(), + reason: z.string(), + detail: z.string(), + }), + ) + .optional(), + // Set when this host's terminals are held by a terminal worker from a newer Paseo, which + // this daemon leaves running but cannot drive: why, and what the user can do. + terminalsUnavailable: z.string().optional(), }) .passthrough(), }); diff --git a/packages/server/package.json b/packages/server/package.json index a6eb8eaa32..5572271cbb 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -73,7 +73,7 @@ "clean": "node ../../scripts/clean-package-dist.mjs", "build": "npm run build:lib && npm run build:scripts", "build:clean": "npm run clean && npm run build", - "build:lib": "tsc -p tsconfig.server.json --incremental false && node scripts/build-opencode-bridge-plugin.mjs && node -e \"const fs=require('node:fs'); fs.mkdirSync('dist/server/server/speech/providers/local/sherpa/assets',{recursive:true}); fs.copyFileSync('src/server/speech/providers/local/sherpa/assets/silero_vad.onnx','dist/server/server/speech/providers/local/sherpa/assets/silero_vad.onnx'); fs.cpSync('src/terminal/shell-integration','dist/server/terminal/shell-integration',{recursive:true}); fs.cpSync('src/terminal/shell-integration','dist/src/terminal/shell-integration',{recursive:true}); fs.copyFileSync('src/terminal/terminal-ts-loader.mjs','dist/server/terminal/terminal-ts-loader.mjs'); fs.rmSync('dist/server/skills',{recursive:true,force:true}); fs.cpSync('../../skills','dist/server/skills',{recursive:true}); fs.rmSync('dist/server/builtin-plugins',{recursive:true,force:true}); fs.cpSync('../../plugins','dist/server/builtin-plugins',{recursive:true,filter:(source)=>!source.split(require('node:path').sep).some((segment)=>segment==='node_modules'||segment==='test')&&!/\\.(test|spec)\\.[cm]?[jt]sx?$/.test(source)&&!source.endsWith('.tsbuildinfo')});\"", + "build:lib": "tsc -p tsconfig.server.json --incremental false && node scripts/build-opencode-bridge-plugin.mjs && node scripts/build-terminal-worker.mjs && node -e \"const fs=require('node:fs'); fs.mkdirSync('dist/server/server/speech/providers/local/sherpa/assets',{recursive:true}); fs.copyFileSync('src/server/speech/providers/local/sherpa/assets/silero_vad.onnx','dist/server/server/speech/providers/local/sherpa/assets/silero_vad.onnx'); fs.cpSync('src/terminal/shell-integration','dist/server/terminal/shell-integration',{recursive:true}); fs.cpSync('src/terminal/shell-integration','dist/src/terminal/shell-integration',{recursive:true}); fs.copyFileSync('src/terminal/terminal-ts-loader.mjs','dist/server/terminal/terminal-ts-loader.mjs'); fs.rmSync('dist/server/skills',{recursive:true,force:true}); fs.cpSync('../../skills','dist/server/skills',{recursive:true}); fs.rmSync('dist/server/builtin-plugins',{recursive:true,force:true}); fs.cpSync('../../plugins','dist/server/builtin-plugins',{recursive:true,filter:(source)=>!source.split(require('node:path').sep).some((segment)=>segment==='node_modules'||segment==='test')&&!/\\.(test|spec)\\.[cm]?[jt]sx?$/.test(source)&&!source.endsWith('.tsbuildinfo')});\"", "build:scripts": "tsc -p tsconfig.scripts.json --incremental false && node -e \"const fs=require('node:fs'); fs.mkdirSync('dist/scripts',{recursive:true}); fs.copyFileSync('scripts/mcp-stdio-socket-bridge-cli.mjs','dist/scripts/mcp-stdio-socket-bridge-cli.mjs');\"", "prepack": "npm run build:clean && npm --prefix ../.. run build:daemon-web-ui", "start": "node dist/scripts/supervisor-entrypoint.js", @@ -89,7 +89,7 @@ "speech:transcribe:local": "tsx scripts/transcribe-local-wav.ts", "test": "npm run test:unit && npm run test:integration", "test:unit": "vitest run --fileParallelism --exclude \"**/*.e2e.test.ts\"", - "test:integration": "vitest run --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts && vitest run --maxWorkers=1 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history\"", + "test:integration": "vitest run --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts && vitest run --maxWorkers=1 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history\"", "test:hub-cli-contract": "vitest run --maxWorkers=1 src/server/hub/hub-cli-contract.test.ts", "test:integration:all": "npm run test:e2e", "test:integration:real": "vitest run real.e2e.test.ts", diff --git a/packages/server/scripts/build-terminal-worker.mjs b/packages/server/scripts/build-terminal-worker.mjs new file mode 100644 index 0000000000..3a5b290fc3 --- /dev/null +++ b/packages/server/scripts/build-terminal-worker.mjs @@ -0,0 +1,55 @@ +// Bundles the terminal worker into one file with its shell integration beside it. The daemon +// copies this directory (plus node-pty) into $PASEO_HOME/terminal-worker/ and launches the worker +// from the copy, so a worker that outlives an upgrade never loads files from the installation +// that replaced the one it came from. See docs/terminal-worker.md. +// +// Usage: node scripts/build-terminal-worker.mjs [--outdir