From 689763a603a72f38c451f1b9409e187216932386 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 26 Oct 2026 22:05:36 -0700 Subject: [PATCH 001/817] fix(mobile): isolate file tree state by workspace (#24270) --- .../src/features/files/FileTreeBrowser.tsx | 50 +- .../features/files/ThreadFilesRouteScreen.tsx | 27 +- .../files/thread-file-navigator-pane.tsx | 10 +- .../files/useFileTreeEntries.test.tsx | 721 ++++++++++++++++++ .../src/features/files/useFileTreeEntries.ts | 519 +++++++++++-- apps/mobile/src/state/query.ts | 5 + apps/mobile/vite.config.ts | 1 + 7 files changed, 1222 insertions(+), 111 deletions(-) create mode 100644 apps/mobile/src/features/files/useFileTreeEntries.test.tsx diff --git a/apps/mobile/src/features/files/FileTreeBrowser.tsx b/apps/mobile/src/features/files/FileTreeBrowser.tsx index c08f21ad49836..93e238822c4f3 100644 --- a/apps/mobile/src/features/files/FileTreeBrowser.tsx +++ b/apps/mobile/src/features/files/FileTreeBrowser.tsx @@ -32,15 +32,6 @@ function cachedFileTree(entries: ReadonlyArray): ReadonlyArray { - const parts = path.split("/").filter(Boolean); - const ancestors: string[] = []; - for (let index = 1; index < parts.length; index += 1) { - ancestors.push(parts.slice(0, index).join("/")); - } - return ancestors; -} - const FileTreeRow = function FileTreeRow(props: { readonly item: VisibleFileTreeNode; readonly selected: boolean; @@ -107,6 +98,11 @@ const FileTreeRow = function FileTreeRow(props: { }; export function FileTreeBrowser(props: { + readonly revealSelection: (path: string | null) => void; + readonly expandedPaths: ReadonlySet; + readonly setExpandedPaths: ( + update: (current: ReadonlySet) => ReadonlySet, + ) => void; readonly entries: ReadonlyArray; readonly error: string | null; readonly isPending: boolean; @@ -116,12 +112,12 @@ export function FileTreeBrowser(props: { readonly searchTruncated: boolean; readonly selectedPath: string | null; readonly loadingDirectories: ReadonlySet; - readonly onLoadDirectory: (path: string) => void; + readonly onLoadDirectory: (path: string, retry?: boolean) => void; readonly onPreviewFile?: (path: string) => void; readonly onRefresh: () => void; readonly onSelectFile: (path: string) => void; }) { - const [expandedPaths, setExpandedPaths] = useState>(() => new Set()); + const { expandedPaths, setExpandedPaths } = props; const [pendingSelection, setPendingSelection] = useState<{ readonly path: string; readonly selectedPathAtPress: string | null; @@ -149,27 +145,21 @@ export function FileTreeBrowser(props: { searchResultPaths: props.searchResultPaths, }); + const { revealSelection } = props; useEffect(() => { - if (!controlledSelectedPath) { - return; - } - // oxlint-disable-next-line react/set-state-in-effect -- An externally selected file expands its ancestor folders; the user can collapse them afterwards. - setExpandedPaths((current) => { - const ancestors = ancestorPaths(controlledSelectedPath); - if (ancestors.every((ancestor) => current.has(ancestor))) { - return current; - } - const next = new Set(current); - for (const ancestor of ancestors) { - next.add(ancestor); - } - return next; - }); - }, [controlledSelectedPath]); + revealSelection(controlledSelectedPath); + }, [controlledSelectedPath, revealSelection]); useEffect(() => { - for (const path of expandedPaths) onLoadDirectory(path); - }, [expandedPaths, onLoadDirectory]); + const visit = (nodes: ReadonlyArray) => { + for (const node of nodes) { + if (node.kind !== "directory" || !expandedPaths.has(node.path)) continue; + onLoadDirectory(node.path); + visit(node.children); + } + }; + visit(tree); + }, [tree, expandedPaths, onLoadDirectory]); useEffect( () => () => { @@ -181,7 +171,7 @@ export function FileTreeBrowser(props: { ); const toggleDirectory = (path: string, expand: boolean) => { - if (expand) onLoadDirectory(path); + if (expand) onLoadDirectory(path, true); setExpandedPaths((current) => { const next = new Set(current); if (next.has(path)) { diff --git a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx index 3f2255a56b138..e1b4ac2a26d9d 100644 --- a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx +++ b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx @@ -452,7 +452,7 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) { const { canReadFiles } = fileAccess; const entriesQuery = useFileTreeEntries({ environmentId, - cwd: !canReadFiles || hasFileInspector ? null : cwd, + cwd: canReadFiles && !hasFileInspector ? cwd : null, searchQuery, }); const handleReturnToThread = () => { @@ -565,6 +565,9 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) { { + entriesQuery.selectPath(path); + handleSelectFile(path); + }} /> @@ -767,7 +773,10 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) { headerInset={headerInset} projectName={directoryPath ?? projectName} selectedPath={directoryPath === null ? relativePath : null} - onSelectFile={handleSelectFile} + onSelectFile={(path) => { + if (directoryPath !== null) entriesQuery.selectPath(path); + handleSelectFile(path); + }} /> ) : undefined; const safeAreaInsets = useSafeAreaInsets(); @@ -945,6 +954,9 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) { { + entriesQuery.selectPath(path); + handleSelectFile(path); + }} /> diff --git a/apps/mobile/src/features/files/thread-file-navigator-pane.tsx b/apps/mobile/src/features/files/thread-file-navigator-pane.tsx index 5f3deb6089c4b..d10746616d70f 100644 --- a/apps/mobile/src/features/files/thread-file-navigator-pane.tsx +++ b/apps/mobile/src/features/files/thread-file-navigator-pane.tsx @@ -87,6 +87,9 @@ export function ThreadFileNavigatorPane(props: { const fileTree = ( { + entriesQuery.selectPath(path); + props.onSelectFile(path); + }} /> ); diff --git a/apps/mobile/src/features/files/useFileTreeEntries.test.tsx b/apps/mobile/src/features/files/useFileTreeEntries.test.tsx new file mode 100644 index 0000000000000..8d707fd379a83 --- /dev/null +++ b/apps/mobile/src/features/files/useFileTreeEntries.test.tsx @@ -0,0 +1,721 @@ +import { + EnvironmentId, + ProjectListEntriesError, + type ProjectEntry, + type ProjectListEntriesResult, +} from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import * as Option from "effect/Option"; +import { AsyncResult } from "effect/reactivity"; +import { act, useLayoutEffect, type ReactNode } from "react"; +import { createRoot } from "react-dom/client"; +import { describe, expect, it, vi } from "vite-plus/test"; + +type Query = { + readonly environmentId: EnvironmentId; + readonly input: { + readonly cwd: string; + readonly query?: string; + readonly directoryPath?: string; + }; +}; +type Result = + | { + readonly _tag: "Success"; + readonly value: ProjectListEntriesResult; + readonly timestamp: number; + } + | { readonly _tag: "Failure"; readonly cause: Cause.Cause }; +type QueryState = { + success: AsyncResult.Success | null; + data: ProjectListEntriesResult; + error: string | null; + failure: ProjectListEntriesError | null; + isPending: boolean; + refresh: () => void; +}; + +const rootEntries: ProjectEntry[] = [{ kind: "directory", path: "src" }]; +const firstTarget = { cwd: "/first", environmentId: EnvironmentId.make("first") }; + +const mocks = vi.hoisted(() => { + const createState = () => ({ + requests: [] as { + readonly query: Query; + readonly signal?: AbortSignal; + readonly resolve: (result: Result) => void; + }[], + responseTimestamp: 0, + reconnect: () => {}, + rootQuery: null as unknown as QueryState, + searchQuery: null as unknown as QueryState, + results: new WeakMap< + object, + { + data: ProjectListEntriesResult; + error: string | null; + pending: boolean; + result: AsyncResult.AsyncResult; + } + >(), + }); + return { createState, state: createState() }; +}); + +vi.mock("@t3tools/client-runtime/state/runtime", () => ({ + executeAtomQuery: (_registry: unknown, query: Query, options: { signal?: AbortSignal }) => + new Promise((resolve) => + mocks.state.requests.push({ query, signal: options.signal, resolve }), + ), +})); +vi.mock("../../state/atom-registry", () => ({ appAtomRegistry: { refresh: () => {} } })); +vi.mock("../../state/projects", () => ({ + projectEnvironment: { + listEntries: (query: Query) => query, + searchEntries: (query: Query) => query, + }, +})); +vi.mock("../../connection/catalog", () => ({ + environmentCatalog: { sessionGenerationAtom: () => ({}) }, +})); +vi.mock("../../state/queries", () => ({ useDebouncedValue: (value: string) => value })); +vi.mock("@effect/atom-react", () => ({ + useAtomValue: (atom: Partial) => { + const state = mocks.state; + const query = atom.input?.query === undefined ? state.rootQuery : state.searchQuery; + if (query.success) return query.success; + const cached = state.results.get(query); + if ( + cached && + cached.data === query.data && + cached.error === query.error && + cached.pending === query.isPending + ) { + return cached.result; + } + const result = query.error + ? AsyncResult.fail(query.failure ?? new Error(query.error), { + previousSuccess: Option.some(AsyncResult.success(query.data)), + }) + : AsyncResult.success(query.data, { + waiting: query.isPending, + timestamp: ++state.responseTimestamp, + }); + state.results.set(query, { + data: query.data, + error: query.error, + pending: query.isPending, + result, + }); + return result; + }, + useAtomRefresh: () => mocks.state.rootQuery.refresh, + useAtomMount: () => {}, + useAtomSubscribe: (_atom: unknown, callback: () => void) => { + mocks.state.reconnect = callback; + }, +})); + +const { Children, Nothing } = vi.hoisted(() => ({ + Children: ({ children }: { children?: ReactNode }) =>
{children}
, + Nothing: () => null, +})); +vi.mock("react-native", () => ({ + Platform: { OS: "ios" }, + View: Children, + RefreshControl: Nothing, + Pressable: ({ + children, + onPress, + accessibilityLabel, + }: { + children?: ReactNode; + onPress: () => void; + accessibilityLabel?: string; + }) => ( + + ), +})); +vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ top: 0 }) })); +vi.mock("../../native/NativeScrollViewMarker", () => ({ NativeScrollView: Nothing })); +vi.mock("../../native/native-layout-metrics", () => ({ useNativeColumnLayoutMetrics: () => null })); +vi.mock("@legendapp/list/react-native", () => ({ + LegendList: (props: { + data: ReadonlyArray; + keyExtractor: (item: T) => string; + renderItem: (info: { item: T }) => ReactNode; + ListHeaderComponent?: ReactNode; + ListEmptyComponent?: ReactNode; + }) => ( +
+ {props.ListHeaderComponent} + {props.data.length === 0 + ? props.ListEmptyComponent + : props.data.map((item) => ( +
{props.renderItem({ item })}
+ ))} +
+ ), +})); +vi.mock("../../components/ui/Button", () => ({ + Button: ({ + label, + onPress, + disabled, + }: { + label: string; + onPress: () => void; + disabled?: boolean; + }) => ( + + ), +})); +vi.mock("../../components/ui/AppActivityIndicator", () => ({ AppActivityIndicator: Nothing })); +vi.mock("../../components/ui/AppSymbol", () => ({ SymbolView: Nothing })); +vi.mock("../../components/ui/AppText", () => ({ AppText: Children })); +vi.mock("../../components/PierreEntryIcon", () => ({ PierreEntryIcon: Nothing })); +vi.mock("../../lib/cn", () => ({ cn: () => "" })); + +import { FileTreeBrowser } from "./FileTreeBrowser"; +import { useFileTreeEntries } from "./useFileTreeEntries"; + +type Hook = typeof useFileTreeEntries; +type Input = Parameters[0]; + +function setup(withBrowser = false) { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const state = mocks.createState(); + mocks.state = state; + const rootQuery: QueryState = { + success: null, + data: { entries: rootEntries, truncated: false }, + error: null, + failure: null, + isPending: false, + refresh: vi.fn(), + }; + state.rootQuery = rootQuery; + const searchQuery: QueryState = { ...rootQuery, data: { entries: [], truncated: false } }; + state.searchQuery = searchQuery; + const { requests } = state; + const container = document.body.appendChild(document.createElement("div")); + const root = createRoot(container); + let current: ReturnType; + let renders = 0; + let controlledSelection: string | undefined; + function Probe(input: Input) { + if (++renders > 100 && withBrowser) throw new Error("File tree did not settle"); + const result = useFileTreeEntries(input); + useLayoutEffect(() => { + current = result; + }); + return withBrowser ? ( + + ) : null; + } + const unmount = () => { + act(() => root.unmount()); + container.remove(); + }; + return { + requests, + rootQuery, + searchQuery, + get searchSuccess() { + const result = searchQuery.success ?? state.results.get(searchQuery)?.result; + if (result?._tag !== "Success") throw new Error("Search has not succeeded"); + return result; + }, + get responseTimestamp() { + return state.responseTimestamp; + }, + controlSelection(path: string) { + controlledSelection = path; + }, + updateView(expanded: string[], selected: string) { + renders = 0; + act(() => { + current.setExpandedPaths(() => new Set(expanded)); + current.selectPath(selected); + }); + }, + unmount, + get current() { + return current; + }, + get rows() { + return [...container.querySelectorAll("button")].map((button) => + button.getAttribute("aria-label"), + ); + }, + press(label: string) { + renders = 0; + const button = container.querySelector(`button[aria-label="${label}"]`); + if (!button) throw new Error(`No row labelled ${label}`); + act(() => button.click()); + }, + render(target: Partial = {}) { + renders = 0; + const probe = ; + act(() => root.render(probe)); + }, + load(path = "src", refresh = false) { + renders = 0; + act(() => { + void current.loadDirectory(path, refresh); + }); + }, + async succeed(index: number, entries: ProjectEntry[] = []) { + renders = 0; + await act(async () => { + requests[index]!.resolve({ + _tag: "Success", + value: { entries, truncated: false }, + timestamp: ++state.responseTimestamp, + }); + }); + }, + async fail(index: number, message = "Directory unavailable") { + renders = 0; + await act(async () => { + requests[index]!.resolve({ _tag: "Failure", cause: Cause.fail(new Error(message)) }); + }); + }, + [Symbol.dispose]: unmount, + }; +} + +describe("file tree workspace state", () => { + it("retries failed folders once on reconnect", async () => { + using screen = setup(); + screen.render(); + screen.load(); + await screen.fail(0); + act(() => mocks.state.reconnect()); + expect(screen.requests).toHaveLength(2); + act(() => mocks.state.reconnect()); + expect(screen.requests).toHaveLength(2); + await screen.succeed(1); + act(() => mocks.state.reconnect()); + expect(screen.requests).toHaveLength(2); + }); + + it("publishes immutable loading and loaded snapshots", async () => { + using screen = setup(); + screen.render(); + const initial = screen.current; + screen.load(); + const loading = screen.current; + expect(loading.isPending).toBe(true); + expect([...loading.loadingDirectories]).toEqual(["src"]); + expect([...initial.loadingDirectories]).toEqual([]); + await screen.succeed(0, [{ kind: "file", path: "src/first.ts" }]); + expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src", "src/first.ts"]); + expect([...screen.current.loadedDirectories]).toEqual(["src"]); + expect(screen.current.isPending).toBe(false); + expect([...screen.current.loadingDirectories]).toEqual([]); + expect(loading.entries.map((entry) => entry.path)).toEqual(["src"]); + expect([...loading.loadedDirectories]).toEqual([]); + expect([...loading.loadingDirectories]).toEqual(["src"]); + }); + + it.each([{ cwd: "/second" }, { environmentId: EnvironmentId.make("second") }])( + "isolates directory state and restores it on return from %j", + async (target) => { + using screen = setup(); + screen.render(); + screen.load(); + await screen.succeed(0, [{ kind: "file", path: "src/first.ts" }]); + + screen.updateView(["src"], "src/first.ts"); + const firstView = screen.current; + screen.render(target); + expect([...screen.current.expandedPaths]).toEqual([]); + expect(screen.current.selectedPath).toBeNull(); + expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src"]); + expect([...screen.current.loadedDirectories]).toEqual([]); + expect([...screen.current.loadingDirectories]).toEqual([]); + screen.load(); + expect(screen.requests[1]!.query).toEqual({ + environmentId: target.environmentId ?? firstTarget.environmentId, + input: { cwd: target.cwd ?? firstTarget.cwd, directoryPath: "src" }, + }); + await screen.succeed(1, [{ kind: "file", path: "src/second.ts" }]); + + screen.updateView([], "src/second.ts"); + expect([...firstView.expandedPaths]).toEqual(["src"]); + expect(firstView.selectedPath).toBe("src/first.ts"); + screen.render(); + expect([...screen.current.expandedPaths]).toEqual(["src"]); + expect(screen.current.selectedPath).toBe("src/first.ts"); + expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src", "src/first.ts"]); + expect([...screen.current.loadedDirectories]).toEqual(["src"]); + screen.load(); + expect(screen.requests).toHaveLength(3); + await screen.succeed(2, [{ kind: "file", path: "src/first.ts" }]); + + screen.render(target); + expect([...screen.current.expandedPaths]).toEqual([]); + expect(screen.current.selectedPath).toBe("src/second.ts"); + expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src", "src/second.ts"]); + expect([...screen.current.loadedDirectories]).toEqual(["src"]); + }, + ); + + it("ignores stale successes and failures after leaving and returning to a workspace", async () => { + using screen = setup(); + screen.render(); + screen.load(); + screen.load("src/other"); + screen.render({ cwd: "/second" }); + screen.render(); + screen.load(); + + await screen.succeed(0, [{ kind: "file", path: "src/stale.ts" }]); + await screen.fail(1, "Stale error"); + expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src"]); + expect(screen.current.error).toBeNull(); + expect([...screen.current.loadingDirectories]).toEqual(["src"]); + expect(screen.current.isPending).toBe(true); + + await screen.succeed(2, [{ kind: "file", path: "src/current.ts" }]); + expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src", "src/current.ts"]); + expect(screen.current.error).toBeNull(); + expect(screen.current.isPending).toBe(false); + expect([...screen.current.loadingDirectories]).toEqual([]); + }); + + it("retains recent listings and expansion when leaving a large workspace", async () => { + using screen = setup(); + screen.render(); + const paths = Array.from({ length: 70 }, (_, index) => `src/directory-${index}`); + screen.load(); + await screen.succeed( + 0, + paths.map((path) => ({ kind: "directory", path })), + ); + for (const path of paths) { + screen.load(path); + await screen.succeed(screen.requests.length - 1, [{ kind: "file", path: `${path}/file.ts` }]); + } + screen.updateView(["src", ...paths], `${paths[69]}/file.ts`); + screen.render({ cwd: "/other" }); + screen.render(); + expect(screen.current.loadedDirectories.size).toBe(64); + expect(screen.current.loadedDirectories.has(paths[69]!)).toBe(true); + expect(screen.current.expandedPaths.size).toBe(71); + expect(screen.current.selectedPath).toBe(`${paths[69]}/file.ts`); + for (let index = 1; index <= 8; index++) screen.render({ cwd: `/workspace-${index}` }); + screen.render(); + expect(screen.current.loadedDirectories.size).toBe(0); + expect(screen.current.expandedPaths.size).toBe(0); + expect(screen.current.selectedPath).toBeNull(); + }); + + it("retries a failed folder only when the user expands it again", async () => { + using screen = setup(true); + screen.render(); + expect(screen.rows).toEqual(["src"]); + expect(screen.requests).toHaveLength(0); + + screen.press("src"); + expect(screen.requests).toHaveLength(1); + await screen.fail(0); + expect(screen.current.error).toBe("Directory unavailable"); + // Re-rendering and the browser's passive expansion effect never retry a failed listing. + screen.render(); + screen.render(); + expect(screen.requests).toHaveLength(1); + expect(screen.rows).toEqual(["src"]); + + screen.press("src"); + expect([...screen.current.expandedPaths]).toEqual([]); + expect(screen.requests).toHaveLength(1); + screen.press("src"); + expect([...screen.current.expandedPaths]).toEqual(["src"]); + expect(screen.requests).toHaveLength(2); + await screen.succeed(1, [{ kind: "file", path: "src/file.ts" }]); + expect(screen.current.error).toBeNull(); + expect(screen.rows).toEqual(["src", "src/file.ts"]); + + // A loaded folder serves from cache on collapse and expand. + screen.press("src"); + screen.press("src"); + expect(screen.rows).toEqual(["src", "src/file.ts"]); + expect(screen.requests).toHaveLength(2); + }); + + it("reveals a controlled leaf-only search result after search clears", () => { + using screen = setup(true); + screen.render(); + screen.searchQuery.data = { + entries: [{ kind: "file", path: "src/new/file.ts" }], + truncated: false, + }; + screen.controlSelection("src/new/file.ts"); + screen.render({ searchQuery: "file" }); + expect([...screen.current.expandedPaths]).toEqual(["src", "src/new"]); + screen.render(); + expect(screen.current.entries.map((entry) => entry.path)).toContain("src/new/file.ts"); + }); + + it.each(["collapse", "delete"])("settles controlled selection after %s", async (action) => { + using screen = setup(true); + screen.render(); + screen.updateView([], "src/nested/file.ts"); + await screen.succeed(0, [{ kind: "directory", path: "src/nested" }]); + expect([...screen.current.expandedPaths]).toEqual(["src", "src/nested"]); + if (action === "collapse") { + screen.updateView([], "src/nested/file.ts"); + expect([...screen.current.expandedPaths]).toEqual([]); + screen.render({ cwd: "/second" }); + screen.render(); + expect([...screen.current.expandedPaths]).toEqual([]); + } + screen.rootQuery.data = { entries: [], truncated: false }; + screen.render(); + expect([...screen.current.expandedPaths]).toEqual([]); + expect(screen.current.selectedPath).toBeNull(); + if (action === "delete") { + screen.controlSelection("src/nested/file.ts"); + screen.searchQuery.data = { + entries: [ + { kind: "directory", path: "src" }, + { kind: "directory", path: "src/nested" }, + { kind: "file", path: "src/nested/file.ts" }, + ], + truncated: false, + }; + screen.rootQuery.failure = new ProjectListEntriesError({ + cwd: "/first", + failure: "workspace_root_not_found", + }); + screen.rootQuery.error = screen.rootQuery.failure.message; + const requestCount = screen.requests.length; + for (const error of [null, "Search unavailable"]) { + screen.searchQuery.error = error; + screen.render({ searchQuery: "nested" }); + expect(screen.current.entries).toEqual([]); + expect([...screen.current.expandedPaths]).toEqual([]); + expect([...screen.current.loadedDirectories]).toEqual([]); + expect(screen.current.isPending).toBe(false); + expect(screen.requests).toHaveLength(requestCount); + } + } + }); + + it.each(["return", "missing root"])( + "revalidates retained children after %s without clearing for transient errors", + async (scenario) => { + using screen = setup(); + screen.render(); + screen.load(); + await screen.succeed(0, [{ kind: "file", path: "src/old.ts" }]); + screen.updateView(["src"], "src/old.ts"); + screen.render({ cwd: "/second" }); + screen.render(); + screen.rootQuery.error = "Connection unavailable"; + screen.render(); + expect(screen.current.selectedPath).toBe("src/old.ts"); + expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src", "src/old.ts"]); + if (scenario === "missing root") { + screen.rootQuery.failure = new ProjectListEntriesError({ + cwd: "/first", + failure: "workspace_root_not_found", + }); + screen.rootQuery.error = screen.rootQuery.failure.message; + expect(screen.rootQuery.error).toBe("Failed to list workspace entries in '/first'."); + screen.render(); + expect(screen.current.selectedPath).toBeNull(); + expect([...screen.current.expandedPaths]).toEqual([]); + expect([...screen.current.loadedDirectories]).toEqual([]); + } + screen.rootQuery.error = null; + screen.rootQuery.failure = null; + screen.render(); + if (scenario === "missing root") { + expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src"]); + expect(screen.current.selectedPath).toBeNull(); + } + screen.load(); + expect(screen.requests).toHaveLength(2); + await screen.succeed(1, []); + expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src"]); + expect(screen.current.selectedPath).toBeNull(); + }, + ); + + it.each(["new", "src/new"])( + "keeps search discovery %s until its parent listing revalidates it", + async (path) => { + using screen = setup(); + screen.render(); + screen.load(); + await screen.succeed(0, []); + screen.searchQuery.data = { + entries: [{ kind: "file", path: `${path}/file.ts` }], + truncated: false, + }; + screen.render({ searchQuery: "new" }); + const expanded = path.includes("/") ? ["src", path] : [path]; + screen.updateView(expanded, `${path}/file.ts`); + expect(screen.current.selectedPath).toBe(`${path}/file.ts`); + expect([...screen.current.expandedPaths]).toEqual(expanded); + screen.load(path); + await screen.succeed(1, [ + { kind: "file", path: `${path}/file.ts` }, + { kind: "file", path: `${path}/other.ts` }, + ]); + expect([...screen.current.loadedDirectories]).toEqual(["src", path]); + + const cachedSearch = screen.searchSuccess; + for (const searchQuery of ["", "other"]) { + screen.searchQuery.data = { entries: [], truncated: false }; + screen.render({ searchQuery }); + expect(screen.current.selectedPath).toBe(`${path}/file.ts`); + expect([...screen.current.expandedPaths]).toEqual(expanded); + expect([...screen.current.loadedDirectories]).toEqual(["src", path]); + expect(screen.current.entries).toContainEqual({ kind: "file", path: `${path}/file.ts` }); + expect(screen.current.entries).toContainEqual({ kind: "file", path: `${path}/other.ts` }); + } + + screen.render(); + for (const target of [{ cwd: "/second" }, { environmentId: EnvironmentId.make("second") }]) { + screen.render(target); + screen.render(); + expect(screen.current.selectedPath).toBe(`${path}/file.ts`); + expect([...screen.current.expandedPaths]).toEqual(expanded); + expect([...screen.current.loadedDirectories]).toEqual(["src", path]); + expect(screen.current.entries).toContainEqual({ kind: "file", path: `${path}/other.ts` }); + } + + screen.searchQuery.data = { + entries: [{ kind: "file", path: `${path}/file.ts` }], + truncated: false, + }; + screen.render({ searchQuery: "new" }); + for (const equalContents of [false, true]) { + // A later parent listing wins over retained discovery evidence. + if (path.includes("/")) { + // Refresh re-lists the root and every reachable folder; the empty parent prunes the child. + const refreshed = screen.requests.length; + act(() => { + void screen.current.refresh(); + }); + expect(screen.requests.slice(refreshed).map((request) => request.query.input)).toEqual([ + { cwd: "/first", directoryPath: "" }, + { cwd: "/first", query: "new", limit: 200 }, + { cwd: "/first", directoryPath: "src" }, + { cwd: "/first", directoryPath: path }, + ]); + // The parent settles last so its listing carries the newest response timestamp. + for (const index of [refreshed, refreshed + 1, refreshed + 3, refreshed + 2]) { + await screen.succeed(index, []); + } + } else { + const cachedData = screen.rootQuery.data; + screen.rootQuery.isPending = true; + screen.render({ searchQuery: "new" }); + expect(screen.current.selectedPath).toBe(`${path}/file.ts`); + screen.rootQuery.isPending = false; + expect(screen.rootQuery.data).toBe(cachedData); + screen.render({ searchQuery: "new" }); + } + expect(screen.current.selectedPath).toBeNull(); + expect([...screen.current.expandedPaths]).toEqual(path.includes("/") ? ["src"] : []); + expect([...screen.current.loadedDirectories]).toEqual(["src"]); + + // Cover an older cache and the timestamp's ambiguous same-millisecond boundary. + for (const success of [ + cachedSearch, + AsyncResult.success(cachedSearch.value, { timestamp: screen.responseTimestamp }), + ]) { + screen.searchQuery.data = { entries: [], truncated: false }; + screen.render({ searchQuery: "other" }); + screen.searchQuery.success = success; + screen.searchQuery.data = success.value; + screen.render({ searchQuery: "new" }); + screen.updateView(expanded, `${path}/file.ts`); + const requestCount = screen.requests.length; + screen.load(path); + expect(screen.requests).toHaveLength(requestCount + 1); + await screen.fail(requestCount); + screen.searchQuery.success = null; + screen.render(); + expect(screen.current.selectedPath).toBeNull(); + expect([...screen.current.expandedPaths]).toEqual(path.includes("/") ? ["src"] : []); + expect([...screen.current.loadedDirectories]).toEqual(["src"]); + expect( + screen.current.entries.some( + (entry) => entry.path === path || entry.path.startsWith(`${path}/`), + ), + ).toBe(false); + } + + const cachedSearchData = screen.searchQuery.data; + screen.searchQuery.isPending = true; + screen.render({ searchQuery: "new" }); + expect(screen.current.selectedPath).toBeNull(); + expect([...screen.current.loadedDirectories]).toEqual(["src"]); + screen.searchQuery.isPending = false; + if (!equalContents) { + screen.searchQuery.data = { + ...cachedSearchData, + entries: [...cachedSearchData.entries, { kind: "file", path: `${path}/added.ts` }], + }; + } + expect(screen.searchQuery.data === cachedSearchData).toBe(equalContents); + screen.render({ searchQuery: "new" }); + screen.updateView(expanded, `${path}/file.ts`); + screen.load(path); + await screen.succeed(screen.requests.length - 1, [ + { kind: "file", path: `${path}/file.ts` }, + { kind: "file", path: `${path}/recreated.ts` }, + ]); + expect(screen.current.selectedPath).toBe(`${path}/file.ts`); + expect([...screen.current.expandedPaths]).toEqual(expanded); + expect([...screen.current.loadedDirectories]).toEqual(["src", path]); + expect(screen.current.entries).toContainEqual({ kind: "file", path: `${path}/file.ts` }); + expect(screen.current.entries).toContainEqual({ + kind: "file", + path: `${path}/recreated.ts`, + }); + } + }, + ); + + it("prunes deleted directory contents, expansion and selection after a fresh parent listing", async () => { + using screen = setup(); + screen.render(); + screen.load(); + await screen.succeed(0, [{ kind: "directory", path: "src/nested" }]); + screen.load("src/nested"); + await screen.succeed(1, [{ kind: "file", path: "src/nested/file.ts" }]); + screen.updateView(["src", "src/nested"], "src/nested/file.ts"); + screen.rootQuery.data = { entries: [], truncated: true }; + screen.render(); + expect([...screen.current.loadedDirectories]).toEqual(["src", "src/nested"]); + expect(screen.current.selectedPath).toBe("src/nested/file.ts"); + screen.rootQuery.data = { entries: [], truncated: false }; + screen.render(); + expect(screen.current.entries).toEqual([]); + expect([...screen.current.loadedDirectories]).toEqual([]); + expect([...screen.current.expandedPaths]).toEqual([]); + expect(screen.current.selectedPath).toBeNull(); + screen.rootQuery.data = { entries: rootEntries, truncated: false }; + screen.render(); + expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src"]); + }); +}); diff --git a/apps/mobile/src/features/files/useFileTreeEntries.ts b/apps/mobile/src/features/files/useFileTreeEntries.ts index d171f80e60287..1734cb705a75a 100644 --- a/apps/mobile/src/features/files/useFileTreeEntries.ts +++ b/apps/mobile/src/features/files/useFileTreeEntries.ts @@ -1,9 +1,9 @@ import { useAtomMount, useAtomSubscribe } from "@effect/atom-react"; import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime"; -import type { EnvironmentId, ProjectEntry } from "@t3tools/contracts"; +import { ProjectListEntriesError, type EnvironmentId, type ProjectEntry } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; +import { useCallback, useLayoutEffect, useRef, useState } from "react"; import { Atom } from "effect/reactivity"; -import { useEffect, useReducer, useRef, useState } from "react"; import { environmentCatalog } from "../../connection/catalog"; import { appAtomRegistry } from "../../state/atom-registry"; @@ -11,6 +11,92 @@ import { projectEnvironment } from "../../state/projects"; import { useDebouncedValue } from "../../state/queries"; import { useEnvironmentQuery } from "../../state/query"; +function createDirectories() { + return { + target: {}, + entries: new Map>(), + errors: new Map(), + completeDirectories: new Set(), + listingCompletedAt: new Map(), + discoveries: new Map(), + rootListing: null as { readonly timestamp: number } | null, + validatedDirectories: new Set(), + loading: new Set(), + expandedPaths: new Set(), + selectedPath: null as string | null, + revealedSelection: { path: null as string | null, ancestors: new Set() }, + isRefreshing: false, + }; +} + +function boundDirectories(current: ReturnType, preserveVisible = true) { + const visible = (path: string) => { + const parts = path.split("/"); + return parts.every((_, index) => + current.expandedPaths.has(parts.slice(0, index + 1).join("/")), + ); + }; + const inactive = [...new Set([...current.entries.keys(), ...current.errors.keys()])].filter( + (path) => !preserveVisible || !visible(path), + ); + const ownedPaths = [ + ...current.entries.keys(), + ...current.expandedPaths, + current.selectedPath, + ].filter((path) => path !== null); + const discoveries = new Map( + [...current.discoveries].filter(([path]) => + ownedPaths.some((owned) => owned === path || owned.startsWith(`${path}/`)), + ), + ); + if (inactive.length <= 64) + return discoveries.size === current.discoveries.size ? current : { ...current, discoveries }; + const evicted = new Set(inactive.slice(0, -64)); + // Evict listing data, not the user's expansion and selection. A missing parent reloads on return. + return { + ...current, + discoveries, + entries: new Map([...current.entries].filter(([path]) => !evicted.has(path))), + errors: new Map([...current.errors].filter(([path]) => !evicted.has(path))), + completeDirectories: new Set( + [...current.completeDirectories].filter((path) => !evicted.has(path)), + ), + validatedDirectories: new Set( + [...current.validatedDirectories].filter((path) => !evicted.has(path)), + ), + listingCompletedAt: new Map( + [...current.listingCompletedAt].filter(([path]) => !evicted.has(path)), + ), + }; +} + +function contradictsListing(path: string, parent: string, entries: ReadonlyArray) { + if (parent !== "" && !path.startsWith(`${parent}/`)) return false; + const child = path.slice(parent === "" ? 0 : parent.length + 1).split("/")[0]; + const childPath = parent === "" ? child : `${parent}/${child}`; + const entry = entries.find((item) => item.path === childPath); + return !entry || (path !== childPath && entry.kind !== "directory"); +} + +function createRequests() { + return { + active: true, + refreshVersion: 0, + pending: new Map(), + }; +} + +function getRequests( + requestsByTarget: WeakMap>, + target: object, +) { + let requests = requestsByTarget.get(target); + if (!requests) { + requests = createRequests(); + requestsByTarget.set(target, requests); + } + return requests; +} const noSessionGeneration = Atom.make(0); export function useFileTreeEntries(input: { @@ -27,6 +113,7 @@ export function useFileTreeEntries(input: { ? projectEnvironment.listEntries({ environmentId, input: { cwd, directoryPath: "" } }) : null, ); + const { refresh: refreshRoot } = root; const search = useEnvironmentQuery( searching && debouncedQuery.length > 0 && cwd !== null && environmentId !== null ? projectEnvironment.searchEntries({ @@ -35,42 +122,102 @@ export function useFileTreeEntries(input: { }) : null, ); - const [, render] = useReducer((value: number) => value + 1, 0); - const [entriesRevision, entriesChanged] = useReducer((value: number) => value + 1, 0); - const refreshVersion = useRef(0); - const directories = { - cwd, - environmentId, - entries: new Map>(), - requested: new Set(), - pending: new Map(), - errors: new Map(), - }; - const [refreshingDirectories, setRefreshingDirectories] = useState( - null, - ); - useEffect( - () => () => { - refreshVersion.current++; - for (const controller of directories.pending.values()) controller.abort(); - directories.pending.clear(); - }, - [directories], + const workspaceKey = JSON.stringify([environmentId, cwd]); + const [cache, setCache] = useState(() => ({ + key: workspaceKey, + workspaces: new Map([[workspaceKey, createDirectories()]]), + })); + const savedDirectories = cache.workspaces.get(workspaceKey) ?? createDirectories(); + // Requests belong to a visit, so returning cannot revive an old completion. + const directories = + cache.key === workspaceKey + ? savedDirectories + : { + ...savedDirectories, + target: {}, + validatedDirectories: new Set(), + errors: new Map(), + loading: new Set(), + isRefreshing: false, + }; + if (cache.key !== workspaceKey) { + const workspaces = new Map(cache.workspaces); + const previous = workspaces.get(cache.key); + if (previous) { + workspaces.set( + cache.key, + boundDirectories( + { + ...previous, + errors: new Map(), + loading: new Set(), + isRefreshing: false, + }, + false, + ), + ); + } + workspaces.delete(workspaceKey); + workspaces.set(workspaceKey, directories); + if (workspaces.size > 8) workspaces.delete(workspaces.keys().next().value!); + setCache({ key: workspaceKey, workspaces }); + } + const setDirectories = useCallback( + ( + update: ( + current: ReturnType, + ) => ReturnType, + ) => + setCache((current) => { + const previous = current.workspaces.get(workspaceKey); + if (!previous) return current; + const next = boundDirectories(update(previous)); + if (next === previous) return current; + return { ...current, workspaces: new Map(current.workspaces).set(workspaceKey, next) }; + }), + [workspaceKey], ); + const { target } = directories; + const requestsByTarget = useRef(new WeakMap>()); + // Cancel the old target before consumers' passive effects start new directory loads. + useLayoutEffect(() => { + const requests = getRequests(requestsByTarget.current, target); + requests.active = true; + refreshRoot(); + return () => { + requests.active = false; + requests.refreshVersion++; + for (const controller of requests.pending.values()) controller.abort(); + requests.pending.clear(); + setDirectories((current) => + current.target === target + ? { ...current, loading: new Set(), isRefreshing: false } + : current, + ); + }; + }, [target, setDirectories, requestsByTarget, refreshRoot]); + const updateDirectories = ( + update: (current: ReturnType) => ReturnType, + ) => setDirectories((current) => (current.target === target ? update(current) : current)); const loadDirectory = (directoryPath: string, refresh = false) => { + const requests = getRequests(requestsByTarget.current, target); if ( + !requests.active || + missingRoot || cwd === null || environmentId === null || - (!refresh && directories.entries.has(directoryPath)) || - directories.pending.has(directoryPath) + (!refresh && directories.validatedDirectories.has(directoryPath)) || + requests.pending.has(directoryPath) ) { return; } const controller = new AbortController(); - directories.requested.add(directoryPath); - directories.pending.set(directoryPath, controller); - directories.errors.delete(directoryPath); - render(); + requests.pending.set(directoryPath, controller); + updateDirectories((current) => { + const errors = new Map(current.errors); + errors.delete(directoryPath); + return { ...current, errors, loading: new Set(current.loading).add(directoryPath) }; + }); const atom = projectEnvironment.listEntries({ environmentId, input: { cwd, directoryPath } }); appAtomRegistry.refresh(atom); return executeAtomQuery(appAtomRegistry, atom, { @@ -79,26 +226,73 @@ export function useFileTreeEntries(input: { reportDefect: false, }).then((result) => { if (controller.signal.aborted) return; - directories.pending.delete(directoryPath); - if (result._tag === "Success") { - directories.entries.set( - directoryPath, - result.value.entries.filter( - (entry) => - entry.path.slice(0, Math.max(0, entry.path.lastIndexOf("/"))) === directoryPath, - ), - ); - entriesChanged(); - } else { + requests.pending.delete(directoryPath); + updateDirectories((current) => { + const validatedDirectories = new Set(current.validatedDirectories).add(directoryPath); + const loading = new Set(current.loading); + loading.delete(directoryPath); + if (result._tag === "Success") { + const entries = new Map(current.entries); + entries.delete(directoryPath); + entries.set( + directoryPath, + result.value.entries.filter( + (entry) => + entry.path.slice(0, Math.max(0, entry.path.lastIndexOf("/"))) === directoryPath, + ), + ); + const completeDirectories = new Set(current.completeDirectories); + if (result.value.truncated) completeDirectories.delete(directoryPath); + else completeDirectories.add(directoryPath); + return { + ...current, + entries, + loading, + completeDirectories, + discoveries: result.value.truncated + ? current.discoveries + : new Map( + [...current.discoveries].filter( + ([path]) => !contradictsListing(path, directoryPath, result.value.entries), + ), + ), + validatedDirectories, + listingCompletedAt: new Map(current.listingCompletedAt).set( + directoryPath, + result.timestamp, + ), + }; + } const error = Cause.squash(result.cause); - directories.errors.set( - directoryPath, - error instanceof Error ? error.message : "Files unavailable", - ); - } - render(); + return { + ...current, + loading, + validatedDirectories, + errors: new Map(current.errors).set( + directoryPath, + error instanceof Error ? error.message : "Files unavailable", + ), + }; + }); }); }; + const missingRoot = + root.failure instanceof ProjectListEntriesError && + root.failure.failure === "workspace_root_not_found"; + const rootData = missingRoot ? null : root.data; + const rootListing = root.successResult ?? directories.rootListing; + if ( + missingRoot && + (directories.entries.size > 0 || + directories.errors.size > 0 || + directories.loading.size > 0 || + directories.expandedPaths.size > 0 || + directories.selectedPath !== null || + directories.discoveries.size > 0) + ) { + setDirectories(() => createDirectories()); + } + const { refresh: refreshSearch, data: searchData, successResult: searchResult } = search; // A folder read fails at once while its environment is unreachable; read it again once a new // session is up rather than leaving the error until someone refreshes. const sessionGeneration = @@ -108,13 +302,11 @@ export function useFileTreeEntries(input: { // A listener alone does not compute the atom, so nothing would follow the connection. useAtomMount(sessionGeneration); useAtomSubscribe(sessionGeneration, () => { - for (const path of directories.errors.keys()) void loadDirectory(path); + for (const path of directories.errors.keys()) void loadDirectory(path, true); }); - const { refresh: refreshRoot, data: rootData } = root; - const { refresh: refreshSearch, data: searchData } = search; const snapshot = (() => { - const merged = new Map(); - if (searching) { + const merged = new Map(missingRoot ? [] : directories.discoveries); + if (searching && !missingRoot) { for (const entry of searchData?.entries ?? []) merged.set(entry.path, entry); } const reachableDirectories = new Set(); @@ -127,31 +319,158 @@ export function useFileTreeEntries(input: { } } }; + if (!missingRoot) { + const discoveries = new Map(directories.discoveries); + // Search can return only leaves; their inferred parents still own loaded children. + for (const entry of directories.discoveries.values()) { + const parts = entry.path.split("/"); + for (let index = 1; index < parts.length; index++) { + const path = parts.slice(0, index).join("/"); + if (!discoveries.has(path)) discoveries.set(path, { kind: "directory", path }); + } + } + visit([...discoveries.values()]); + } visit((rootData?.entries ?? []).filter((entry) => !entry.path.includes("/"))); return { - revision: entriesRevision, entries: [...merged.values()], reachableDirectories, - searchResultPaths: searching - ? new Set((searchData?.entries ?? []).map((entry) => entry.path)) - : null, + searchResultPaths: + searching && !missingRoot + ? new Set((searchData?.entries ?? []).map((entry) => entry.path)) + : null, }; })(); + if (rootData) { + const deleted = (path: string, directory = false) => { + const parts = path.split("/"); + for (let index = 0; index < parts.length; index++) { + const parent = parts.slice(0, index).join("/"); + const listing = index === 0 ? rootData.entries : directories.entries.get(parent); + const child = parts.slice(0, index + 1).join("/"); + const complete = + index === 0 ? !rootData.truncated : directories.completeDirectories.has(parent); + const entry = listing?.find((item) => item.path === child); + if (complete && listing && !entry) { + const listingCompletedAt = + index === 0 && directories.rootListing !== rootListing + ? rootListing?.timestamp + : directories.listingCompletedAt.get(parent); + // Cached queries keep their completion time across query switches. + // Equal-millisecond responses cannot prove a path postdates the listing. + const retained = + !(index === 0 && directories.rootListing !== rootListing) && + [...directories.discoveries.keys()].some( + (path) => path === child || path.startsWith(`${child}/`), + ); + const discovered = + retained || + (searching && + query === debouncedQuery && + searchResult !== null && + searchResult.timestamp > (listingCompletedAt ?? -Infinity) && + searchData?.entries.some( + (item) => item.path === child || item.path.startsWith(`${child}/`), + )); + if (!discovered) return true; + } + if (entry && (directory || index < parts.length - 1) && entry.kind !== "directory") + return true; + } + return false; + }; + const reconciled = (() => { + const current = directories; + const discoveries = new Map(current.discoveries); + if (current.rootListing !== rootListing && !rootData.truncated) { + for (const path of discoveries.keys()) { + if (contradictsListing(path, "", rootData.entries)) discoveries.delete(path); + } + } + if (searching && query === debouncedQuery && searchResult !== null) { + const ownedPaths = [ + ...current.entries.keys(), + ...current.expandedPaths, + current.selectedPath, + ]; + for (const entry of searchData?.entries ?? []) { + if ( + ownedPaths.some((path) => path === entry.path || path?.startsWith(`${entry.path}/`)) && + !deleted(entry.path, entry.kind === "directory") + ) + discoveries.set(entry.path, entry); + } + } + const entries = new Map([...current.entries].filter(([path]) => !deleted(path, true))); + const errors = new Map([...current.errors].filter(([path]) => !deleted(path, true))); + const expandedPaths = new Set( + [...current.expandedPaths].filter((path) => !deleted(path, true)), + ); + const selectedPath = + current.selectedPath !== null && deleted(current.selectedPath) + ? null + : current.selectedPath; + if ( + entries.size === current.entries.size && + errors.size === current.errors.size && + expandedPaths.size === current.expandedPaths.size && + selectedPath === current.selectedPath && + current.rootListing === rootListing && + discoveries.size === current.discoveries.size && + [...discoveries].every(([path, entry]) => current.discoveries.get(path) === entry) + ) + return current; + const completeDirectories = new Set( + [...current.completeDirectories].filter((path) => entries.has(path)), + ); + return { + ...current, + rootListing, + discoveries, + listingCompletedAt: new Map( + [...current.listingCompletedAt].filter(([path]) => path === "" || entries.has(path)), + ).set( + "", + current.rootListing === rootListing + ? (current.listingCompletedAt.get("") ?? -Infinity) + : (rootListing?.timestamp ?? -Infinity), + ), + entries, + errors, + expandedPaths, + selectedPath, + completeDirectories, + validatedDirectories: new Set( + [...current.validatedDirectories].filter((path) => !deleted(path, true)), + ), + }; + })(); + if (reconciled !== directories) setDirectories(() => reconciled); + } + const refresh = () => { + const requests = getRequests(requestsByTarget.current, target); + if (!requests.active) return Promise.resolve(); refreshRoot(); - if (searching) refreshSearch(); + if (searching && !missingRoot) refreshSearch(); const paths = new Set( - [...directories.requested].filter((path) => snapshot.reachableDirectories.has(path)), + [...directories.entries.keys(), ...directories.errors.keys(), ...directories.loading].filter( + (path) => snapshot.reachableDirectories.has(path), + ), ); - for (const controller of directories.pending.values()) controller.abort(); - directories.pending.clear(); - directories.errors.clear(); - const version = ++refreshVersion.current; - setRefreshingDirectories(directories); + for (const controller of requests.pending.values()) controller.abort(); + requests.pending.clear(); + const version = ++requests.refreshVersion; + updateDirectories((current) => ({ + ...current, + errors: new Map(), + loading: new Set(), + isRefreshing: true, + })); const remaining = paths.values(); const worker = async () => { - while (version === refreshVersion.current) { + while (requests.active && version === requests.refreshVersion) { const next = remaining.next(); if (next.done) return; await loadDirectory(next.value, true); @@ -161,7 +480,7 @@ export function useFileTreeEntries(input: { cwd !== null && environmentId !== null ? [ projectEnvironment.listEntries({ environmentId, input: { cwd, directoryPath: "" } }), - ...(searching + ...(searching && !missingRoot ? [ projectEnvironment.searchEntries({ environmentId, @@ -177,29 +496,83 @@ export function useFileTreeEntries(input: { ), ...Array.from({ length: Math.min(4, paths.size) }, () => worker()), ]; - render(); return Promise.all(work).finally(() => { - if (version === refreshVersion.current) setRefreshingDirectories(null); + if (version === requests.refreshVersion) { + updateDirectories((current) => ({ ...current, isRefreshing: false })); + } }); }; + const revealSelection = (path: string | null) => { + if (missingRoot) return; + updateDirectories((current) => { + const previous = current.revealedSelection; + const handled = previous.path === path ? previous.ancestors : new Set(); + const parts = path?.split("/").filter(Boolean) ?? []; + const ancestors = parts + .slice(1) + .map((_, index) => parts.slice(0, index + 1).join("/")) + .filter( + (ancestor) => + !handled.has(ancestor) && + snapshot.entries.some( + (entry) => + (entry.kind === "directory" && entry.path === ancestor) || + (entry.path === path && entry.path.startsWith(`${ancestor}/`)), + ), + ); + if (previous.path === path && ancestors.length === 0) return current; + return { + ...current, + discoveries: new Map([ + ...current.discoveries, + ...snapshot.entries + .filter((entry) => entry.path === path) + .map((entry) => [entry.path, entry] as const), + ]), + selectedPath: path, + revealedSelection: { path, ancestors: new Set([...handled, ...ancestors]) }, + expandedPaths: new Set([...current.expandedPaths, ...ancestors]), + }; + }); + }; + + const setExpandedPaths = useCallback( + (update: (current: ReadonlySet) => ReadonlySet) => + setDirectories((current) => { + const expandedPaths = update(current.expandedPaths); + return expandedPaths === current.expandedPaths + ? current + : { ...current, expandedPaths: new Set(expandedPaths) }; + }), + [setDirectories], + ); + return { + revealSelection, + expandedPaths: directories.expandedPaths, + setExpandedPaths, + selectedPath: directories.selectedPath, + selectPath: (selectedPath: string) => + updateDirectories((current) => ({ ...current, selectedPath })), entries: snapshot.entries, searchResultPaths: snapshot.searchResultPaths, - isRefreshing: refreshingDirectories === directories, + isRefreshing: directories.isRefreshing, error: root.error ?? (searching ? search.error : null) ?? [...directories.errors].find(([path]) => snapshot.reachableDirectories.has(path))?.[1] ?? null, isPending: - root.isPending || - directories.pending.size > 0 || - (searching && (query !== debouncedQuery || search.isPending)), - searchTruncated: searching && (search.data?.truncated ?? false), + !missingRoot && + (root.isPending || + directories.loading.size > 0 || + (searching && (query !== debouncedQuery || search.isPending))), + searchTruncated: !missingRoot && searching && (search.data?.truncated ?? false), loadedDirectories: new Set(directories.entries.keys()), - loadingDirectories: new Set(directories.pending.keys()), - loadDirectory, + loadingDirectories: directories.loading, + loadDirectory: (path: string, retry = false) => + loadDirectory(path, retry && directories.errors.has(path)), refresh, }; } diff --git a/apps/mobile/src/state/query.ts b/apps/mobile/src/state/query.ts index ad8a0f2cdf979..b5d5b6a6a1a66 100644 --- a/apps/mobile/src/state/query.ts +++ b/apps/mobile/src/state/query.ts @@ -9,7 +9,9 @@ const EMPTY_ASYNC_RESULT_ATOM = Atom.make(AsyncResult.initial(fals export interface EnvironmentQueryView { readonly data: A | null; + readonly successResult: AsyncResult.Success | null; readonly error: string | null; + readonly failure: unknown; readonly isPending: boolean; readonly isSuccess: boolean; readonly refresh: () => void; @@ -30,6 +32,9 @@ export function useEnvironmentQuery( const refresh = useAtomRefresh(selectedAtom); return { data: Option.getOrNull(AsyncResult.value(result)), + // Data may be structurally shared; only a settled success proves a new response. + successResult: result._tag === "Success" && !result.waiting ? result : null, + failure: result._tag === "Failure" ? Cause.squash(result.cause) : null, error: result._tag === "Failure" ? formatError(result.cause) : null, isPending: atom !== null && result.waiting, isSuccess: result._tag === "Success", diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts index 8eaaaa1604fbb..e1509e98e1135 100644 --- a/apps/mobile/vite.config.ts +++ b/apps/mobile/vite.config.ts @@ -4,6 +4,7 @@ import { defineConfig, normalizePath } from "vite-plus"; import "vite-plus/test/config"; const reactTests = [ + "src/features/files/useFileTreeEntries.test.tsx", "src/features/projects/AddProjectScreen.test.ts", "src/lib/useMediaVideoPlayback.test.tsx", "src/features/pull-requests/usePullRequestEnvironmentFallback.test.tsx", From 83838af7ba7dcc539311640d09b6338372beb148 Mon Sep 17 00:00:00 2001 From: Alex Southwell Date: Tue, 27 Oct 2026 05:13:14 +0000 Subject: [PATCH 002/817] fix(mobile): finished subagents stay reachable from the Agents pill (#25759) Co-authored-by: Claude Opus 5.5 --- .../src/state/threadSubagents.test.ts | 96 ++++++++++++++++++- .../src/state/threadSubagents.ts | 30 +++++- 2 files changed, 122 insertions(+), 4 deletions(-) diff --git a/packages/client-runtime/src/state/threadSubagents.test.ts b/packages/client-runtime/src/state/threadSubagents.test.ts index e5dae9f50a368..26b9a785c02d3 100644 --- a/packages/client-runtime/src/state/threadSubagents.test.ts +++ b/packages/client-runtime/src/state/threadSubagents.test.ts @@ -41,8 +41,17 @@ function subagent( }; } -const run = (id: string, status: "running" | "completed" | "rolled_back") => - ({ id: RunId.make(id), status }) as never; +const run = ( + id: string, + status: "queued" | "running" | "completed" | "cancelled" | "rolled_back", + overrides: { readonly ordinal?: number; readonly started?: boolean } = {}, +) => + ({ + id: RunId.make(id), + status, + ordinal: overrides.ordinal ?? Number(id.slice("run-".length)), + startedAt: overrides.started === false ? null : at("2026-06-20T00:00:00.000Z"), + }) as never; const activeRun = run("run-1", "running"); const finishedRun = run("run-1", "completed"); @@ -168,6 +177,89 @@ describe("deriveThreadTurnSubagents", () => { expect(resolveSubagentPillSegment(turn)?.label).toBe("1/2"); }); + it("keeps the finished agents reachable while their turn is the latest", () => { + const turn = deriveThreadTurnSubagents({ + runs: [finishedRun], + subagents: [ + subagent({ id: "a", status: "completed" }), + subagent({ id: "b", status: "failed" }), + ], + }); + + expect(resolveSubagentPillSegment(turn)?.label).toBe("2 done"); + }); + + it("drops finished agents from the pill once a later turn ran without any", () => { + const turn = deriveThreadTurnSubagents({ + runs: [finishedRun, run("run-2", "completed")], + subagents: [subagent({ id: "a", status: "completed" })], + }); + + expect(resolveSubagentPillSegment(turn)).toBeNull(); + }); + + it("shows finished agents again when the later turn was rolled back", () => { + const turn = deriveThreadTurnSubagents({ + runs: [finishedRun, run("run-2", "rolled_back")], + subagents: [subagent({ id: "a", status: "completed" })], + }); + + expect(resolveSubagentPillSegment(turn)?.label).toBe("1 done"); + }); + + it("keeps finished agents while a later turn is only queued or was cancelled before starting", () => { + for (const later of [ + run("run-2", "queued", { started: false }), + run("run-2", "cancelled", { started: false }), + ]) { + const turn = deriveThreadTurnSubagents({ + runs: [finishedRun, later], + subagents: [subagent({ id: "a", status: "completed" })], + }); + + expect(resolveSubagentPillSegment(turn)?.label).toBe("1 done"); + } + }); + + it("finds the latest turn by ordinal when a reordered queue left runs out of order", () => { + const turn = deriveThreadTurnSubagents({ + runs: [run("run-1", "completed", { ordinal: 3 }), run("run-2", "completed", { ordinal: 2 })], + subagents: [subagent({ id: "a", status: "completed" })], + }); + + expect(resolveSubagentPillSegment(turn)?.label).toBe("1 done"); + }); + + it("keeps the latest turn's agents when an earlier turn's background agent finishes later", () => { + const turn = deriveThreadTurnSubagents({ + runs: [finishedRun, run("run-2", "completed")], + subagents: [ + subagent({ id: "late", status: "completed", updatedAt: at("2026-06-20T00:00:09.000Z") }), + subagent({ + id: "latest", + runId: RunId.make("run-2"), + status: "completed", + updatedAt: at("2026-06-20T00:00:05.000Z"), + }), + ], + }); + + expect(turn?.subagents.map((entry) => entry.id)).toEqual(["latest"]); + expect(resolveSubagentPillSegment(turn)?.label).toBe("1 done"); + }); + + it("counts only terminal agents as done while a held agent remains", () => { + const turn = deriveThreadTurnSubagents({ + runs: [finishedRun], + subagents: [ + subagent({ id: "a", status: "completed" }), + subagent({ id: "b", status: "idle" }), + ], + }); + + expect(resolveSubagentPillSegment(turn)?.label).toBe("1 done"); + }); + it("counts idle as neither working nor done", () => { const turn = deriveThreadTurnSubagents({ runs: [activeRun], diff --git a/packages/client-runtime/src/state/threadSubagents.ts b/packages/client-runtime/src/state/threadSubagents.ts index c0c742cc18def..bff4d40fd420b 100644 --- a/packages/client-runtime/src/state/threadSubagents.ts +++ b/packages/client-runtime/src/state/threadSubagents.ts @@ -12,6 +12,8 @@ type RunId = Projection["runs"][number]["id"]; export interface ThreadTurnSubagents { readonly runId: RunId | null; readonly turnActive: boolean; + /** No later turn has run since these agents' turn. */ + readonly latestTurn: boolean; readonly subagents: ReadonlyArray; readonly liveCount: number; readonly settledCount: number; @@ -45,7 +47,22 @@ export function deriveThreadTurnSubagents( : latest, first, ); - const runId = activeRun?.id ?? latestUpdated.runId; + // Ordinal, not array position: a reordered queue can leave the projection's runs out of order. + // Queued and never-started runs have not replaced anything yet. + const latestStartedRun = projection.runs.reduce( + (latest, run) => + run.startedAt !== null && + !rolledBackRunIds.has(run.id) && + (latest === null || run.ordinal > latest.ordinal) + ? run + : latest, + null, + ); + const latestStartedRunHasAgents = + latestStartedRun !== null && + eligible.some((subagent) => subagent.runId === latestStartedRun.id); + const runId = + activeRun?.id ?? (latestStartedRunHasAgents ? latestStartedRun.id : latestUpdated.runId); const subagents = copySorted( eligible.filter( (subagent) => @@ -63,15 +80,24 @@ export function deriveThreadTurnSubagents( if (isActiveSubagentStatus(subagent.status)) liveCount += 1; else if (isTerminalSubagentStatus(subagent.status)) settledCount += 1; } - return { runId, turnActive: activeRun !== null, subagents, liveCount, settledCount }; + return { + runId, + turnActive: activeRun !== null, + latestTurn: runId === null || latestStartedRun === null || runId === latestStartedRun.id, + subagents, + liveCount, + settledCount, + }; } export function resolveSubagentPillSegment( turn: ThreadTurnSubagents | null, ): SubagentPillSegment | null { if (turn === null) return null; + // Finished agents stay reachable until a later turn replaces them; workflows always stay reachable. if ( !turn.turnActive && + !turn.latestTurn && turn.liveCount === 0 && !turn.subagents.some((subagent) => subagent.workflow !== undefined) ) { From e689dad42c842d03f311ee0a7c29db25896abd6a Mon Sep 17 00:00:00 2001 From: Alex Date: Mon, 26 Oct 2026 22:16:17 -0700 Subject: [PATCH 003/817] fix(mobile): keep segmented controls readable on cards and screens (#25729) --- .../components/ui/SegmentedControl.ios.tsx | 32 +++---- .../components/ui/SegmentedControl.shared.tsx | 84 +++++++++++++++++++ .../src/components/ui/SegmentedControl.tsx | 79 +---------------- .../components/ui/SegmentedControl.types.ts | 1 + .../components/ui/segmentedControlColors.ts | 58 +++++++++++++ .../src/components/ui/useControlTheme.ts | 3 +- .../development/ComponentCatalogScreen.tsx | 10 +++ .../SettingsScheduledTasksRouteScreen.tsx | 1 + .../threads/CustomSnoozeSheet.android.tsx | 9 +- apps/mobile/src/lib/mobileTheme.ts | 6 ++ 10 files changed, 183 insertions(+), 100 deletions(-) create mode 100644 apps/mobile/src/components/ui/SegmentedControl.shared.tsx create mode 100644 apps/mobile/src/components/ui/segmentedControlColors.ts diff --git a/apps/mobile/src/components/ui/SegmentedControl.ios.tsx b/apps/mobile/src/components/ui/SegmentedControl.ios.tsx index 4862e99cdabfa..15883d300da41 100644 --- a/apps/mobile/src/components/ui/SegmentedControl.ios.tsx +++ b/apps/mobile/src/components/ui/SegmentedControl.ios.tsx @@ -1,11 +1,8 @@ import { requireNativeView } from "expo"; import { View, type NativeSyntheticEvent, type ViewProps } from "react-native"; -import { - flattenThemeColor, - themeColorWithAlpha, - themeColorWithContrast, -} from "../../lib/mobileTheme"; +import { SegmentedControl as FlatSegmentedControl } from "./SegmentedControl.shared"; +import { segmentedControlColors } from "./segmentedControlColors"; import { useControlTheme } from "./useControlTheme"; import type { SegmentedControlProps } from "./SegmentedControl.types"; @@ -27,17 +24,16 @@ const NativeSegmentedControl = requireNativeView< export function SegmentedControl( props: SegmentedControlProps, ) { - const { colors, colorScheme } = useControlTheme(); - const trackColor = flattenThemeColor( - themeColorWithAlpha(colors["--color-prominent-action"], colorScheme === "dark" ? 0.18 : 0.07), - colors["--color-screen"], + const { colors, colorScheme, themeId } = useControlTheme(); + // UIKit adds a gray fill over the sunken card track. + if (props.variant === "card") return ; + const { trackColor, selectedColor, selectedTextColor, mutedColor } = segmentedControlColors( + colors, + colorScheme, + props.variant, + "ios", + themeId, ); - const selectedColor = - colorScheme === "dark" ? colors["--color-prominent-action"] : colors["--color-secondary"]; - const selectedTextColor = - colorScheme === "dark" - ? colors["--color-prominent-action-foreground"] - : colors["--color-secondary-foreground"]; return ( ( trackColor={trackColor} selectedColor={selectedColor} textColor={selectedTextColor} - mutedColor={themeColorWithContrast( - colors["--color-foreground-muted"], - trackColor, - colorScheme === "dark" ? 7 : 4.5, - )} + mutedColor={mutedColor} appearance={colorScheme} onSelectionChange={({ nativeEvent }) => { const option = props.options[nativeEvent.index]; diff --git a/apps/mobile/src/components/ui/SegmentedControl.shared.tsx b/apps/mobile/src/components/ui/SegmentedControl.shared.tsx new file mode 100644 index 0000000000000..9eac685a8ca21 --- /dev/null +++ b/apps/mobile/src/components/ui/SegmentedControl.shared.tsx @@ -0,0 +1,84 @@ +import { useState } from "react"; +import { I18nManager, Platform, Pressable, View } from "react-native"; +import Animated, { useAnimatedStyle, useReducedMotion, withTiming } from "react-native-reanimated"; + +import { segmentedControlColors } from "./segmentedControlColors"; +import { AppText } from "./AppText"; +import { useControlTheme } from "./useControlTheme"; +import type { SegmentedControlProps } from "./SegmentedControl.types"; + +export type { SegmentedControlProps } from "./SegmentedControl.types"; + +export function SegmentedControl( + props: SegmentedControlProps, +) { + const { colorScheme, colors, themeId } = useControlTheme(); + const [layout, setLayout] = useState({ width: 0, height: 0 }); + const { width } = layout; + const reduceMotion = useReducedMotion(); + const selectedIndex = props.options.findIndex((option) => option.value === props.selected); + const segmentWidth = props.options.length ? Math.max(0, width - 6) / props.options.length : 0; + const selectionOffset = selectedIndex * segmentWidth * (I18nManager.isRTL ? -1 : 1); + const selectionStyle = useAnimatedStyle(() => ({ + width: segmentWidth, + transform: [{ translateX: withTiming(selectionOffset, { duration: reduceMotion ? 0 : 160 }) }], + })); + const { trackColor, selectedColor, selectedTextColor, mutedColor } = segmentedControlColors( + colors, + colorScheme, + props.variant, + Platform.OS, + themeId, + ); + const minHeight = props.size === "compact" ? 32 : Platform.OS === "android" ? 40 : 36; + + return ( + + setLayout(event.nativeEvent.layout)} + className="flex-row rounded-full p-[3px]" + style={{ + minHeight, + backgroundColor: trackColor, + }} + > + {selectedIndex >= 0 && width > 0 ? ( + + ) : null} + {props.options.map((option) => { + const selected = option.value === props.selected; + return ( + props.onSelect(option.value)} + className="flex-1 items-center justify-center rounded-full px-2 py-1 active:opacity-70" + style={{ minHeight: minHeight - 6 }} + > + + {option.label} + + + ); + })} + + + ); +} diff --git a/apps/mobile/src/components/ui/SegmentedControl.tsx b/apps/mobile/src/components/ui/SegmentedControl.tsx index 0fdc46c0f27ef..bbcbc4a5f4593 100644 --- a/apps/mobile/src/components/ui/SegmentedControl.tsx +++ b/apps/mobile/src/components/ui/SegmentedControl.tsx @@ -1,78 +1 @@ -import { useState } from "react"; -import { I18nManager, Platform, Pressable, View } from "react-native"; -import Animated, { useAnimatedStyle, useReducedMotion, withTiming } from "react-native-reanimated"; - -import { AppText } from "./AppText"; -import { useControlTheme } from "./useControlTheme"; -import type { SegmentedControlProps } from "./SegmentedControl.types"; - -export type { SegmentedControlProps } from "./SegmentedControl.types"; - -export function SegmentedControl( - props: SegmentedControlProps, -) { - const { colorScheme, colors } = useControlTheme(); - const [layout, setLayout] = useState({ width: 0, height: 0 }); - const { width } = layout; - const reduceMotion = useReducedMotion(); - const selectedIndex = props.options.findIndex((option) => option.value === props.selected); - const segmentWidth = props.options.length ? Math.max(0, width - 6) / props.options.length : 0; - const selectionOffset = selectedIndex * segmentWidth * (I18nManager.isRTL ? -1 : 1); - const selectionStyle = useAnimatedStyle(() => ({ - width: segmentWidth, - transform: [{ translateX: withTiming(selectionOffset, { duration: reduceMotion ? 0 : 160 }) }], - })); - const dark = colorScheme === "dark"; - const minHeight = props.size === "compact" ? 32 : Platform.OS === "android" ? 40 : 36; - - return ( - - setLayout(event.nativeEvent.layout)} - className="flex-row rounded-full p-[3px]" - style={{ - minHeight, - backgroundColor: colors[dark ? "--color-screen" : "--color-grouped-card"], - }} - > - {selectedIndex >= 0 && width > 0 ? ( - - ) : null} - {props.options.map((option) => { - const selected = option.value === props.selected; - return ( - props.onSelect(option.value)} - className="flex-1 items-center justify-center rounded-full px-2 py-1 active:opacity-70" - style={{ minHeight: minHeight - 6 }} - > - - {option.label} - - - ); - })} - - - ); -} +export { SegmentedControl, type SegmentedControlProps } from "./SegmentedControl.shared"; diff --git a/apps/mobile/src/components/ui/SegmentedControl.types.ts b/apps/mobile/src/components/ui/SegmentedControl.types.ts index 779b49fe1a4b4..472ed46b0e2f2 100644 --- a/apps/mobile/src/components/ui/SegmentedControl.types.ts +++ b/apps/mobile/src/components/ui/SegmentedControl.types.ts @@ -8,6 +8,7 @@ export interface SegmentedControlProps { readonly onSelect: (value: Value) => void; /** Compact uses a 32-point capsule; default uses 36 points on iOS and 40 on Android. */ readonly size?: "default" | "compact"; + readonly variant?: "standalone" | "card"; readonly role?: "tab" | "button"; readonly className?: string; } diff --git a/apps/mobile/src/components/ui/segmentedControlColors.ts b/apps/mobile/src/components/ui/segmentedControlColors.ts new file mode 100644 index 0000000000000..6b58675726e4f --- /dev/null +++ b/apps/mobile/src/components/ui/segmentedControlColors.ts @@ -0,0 +1,58 @@ +import { + flattenThemeColor, + themeColorContrastRatio, + themeColorWithAlpha, + themeColorWithContrast, + type MobileThemeAppearance, + type MobileThemeId, + type MobileThemeVariables, +} from "../../lib/mobileTheme"; +import type { SegmentedControlProps } from "./SegmentedControl.types"; + +export function segmentedControlColors( + colors: MobileThemeVariables, + appearance: MobileThemeAppearance, + variant: SegmentedControlProps["variant"], + platform: string, + themeId: MobileThemeId, +) { + const dark = appearance === "dark"; + const card = variant === "card"; + const accent = + colors[themeId === "material-you" ? "--color-primary" : "--color-prominent-action"]; + const trackColor = card + ? dark + ? colors["--color-screen"] + : flattenThemeColor( + themeColorWithAlpha(colors["--color-foreground"], 0.07), + colors["--color-grouped-card"], + ) + : flattenThemeColor(themeColorWithAlpha(accent, dark ? 0.1 : 0.07), colors["--color-screen"]); + let selectedColor = colors["--color-secondary"]; + if (card && !dark) selectedColor = colors["--color-screen"]; + if (dark && (!card || themeId === "t3-code")) { + selectedColor = flattenThemeColor(themeColorWithAlpha(accent, 0.32), colors["--color-screen"]); + } + let selectedTextColor = + colors[!card && dark ? "--color-foreground" : "--color-secondary-foreground"]; + if (!card && !dark && platform === "android") { + const selection = colors["--color-thread-selected"]; + if ( + themeColorContrastRatio(selection, trackColor) > + themeColorContrastRatio(selectedColor, trackColor) + ) { + selectedColor = selection; + selectedTextColor = colors["--color-thread-selected-foreground"]; + } + } + return { + trackColor, + selectedColor, + selectedTextColor: themeColorWithContrast(selectedTextColor, selectedColor), + mutedColor: themeColorWithContrast( + colors["--color-foreground-muted"], + trackColor, + dark && !card ? 7 : 4.5, + ), + }; +} diff --git a/apps/mobile/src/components/ui/useControlTheme.ts b/apps/mobile/src/components/ui/useControlTheme.ts index d2181ba8954f8..cb7225eddb4db 100644 --- a/apps/mobile/src/components/ui/useControlTheme.ts +++ b/apps/mobile/src/components/ui/useControlTheme.ts @@ -1,9 +1,10 @@ import { useAppearancePreferences } from "../../features/settings/appearance/AppearancePreferencesProvider"; export function useControlTheme() { - const { themeAppearance, themeVariables, systemColorsActive, appearance } = + const { themeId, themeAppearance, themeVariables, systemColorsActive, appearance } = useAppearancePreferences(); return { + themeId, colorScheme: themeAppearance, colors: themeVariables, systemColorsActive, diff --git a/apps/mobile/src/features/development/ComponentCatalogScreen.tsx b/apps/mobile/src/features/development/ComponentCatalogScreen.tsx index 9a3d894d384f5..d692e3e129b0a 100644 --- a/apps/mobile/src/features/development/ComponentCatalogScreen.tsx +++ b/apps/mobile/src/features/development/ComponentCatalogScreen.tsx @@ -104,6 +104,16 @@ export function ComponentCatalogScreen() { Lists and selection + + + setSheet(true)} /> Custom snooze { @@ -155,6 +156,7 @@ export function CustomSnoozeSheet(props: Props) { {mode === "date" ? ( - + )} diff --git a/apps/mobile/src/lib/mobileTheme.ts b/apps/mobile/src/lib/mobileTheme.ts index ed45f0518845b..afe26b7ddd2ea 100644 --- a/apps/mobile/src/lib/mobileTheme.ts +++ b/apps/mobile/src/lib/mobileTheme.ts @@ -209,6 +209,12 @@ function contrastRatio( ); } +export function themeColorContrastRatio(first: string, second: string): number { + const firstChannels = rgbChannels(first); + const secondChannels = rgbChannels(second); + return firstChannels && secondChannels ? contrastRatio(firstChannels, secondChannels) : 1; +} + export function themeColorWithContrast( accent: string, surface: string | ReadonlyArray, From b1619f3a74cb228356a3ea3f58573f88da270817 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Mon, 26 Oct 2026 22:18:11 -0700 Subject: [PATCH 004/817] fix(web): cancelling update everything no longer flashes the update button's focus ring and tooltip (#25774) Co-authored-by: Claude Opus 5.5 --- .../SidebarUpdatePill.browser.test.tsx | 41 +++++++++++++++++-- .../sidebar/UpdateEverythingDialog.tsx | 4 +- 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/apps/web/src/components/sidebar/SidebarUpdatePill.browser.test.tsx b/apps/web/src/components/sidebar/SidebarUpdatePill.browser.test.tsx index edbe293b97998..c7b1ca448775c 100644 --- a/apps/web/src/components/sidebar/SidebarUpdatePill.browser.test.tsx +++ b/apps/web/src/components/sidebar/SidebarUpdatePill.browser.test.tsx @@ -1,7 +1,8 @@ import type { DesktopUpdateState } from "@t3tools/contracts"; import { describe, expect, it, vi } from "vite-plus/test"; -import { userEvent } from "vite-plus/test/browser"; +import { page, userEvent } from "vite-plus/test/browser"; +import "~/index.css"; import { act, render } from "../../../test/render"; import { SidebarUpdatePill } from "./SidebarUpdatePill"; @@ -9,6 +10,7 @@ const mocks = vi.hoisted(() => { const listeners = new Set<() => void>(); return { update: null as DesktopUpdateState | null, + hasUpdates: false, subscribe: (listener: () => void) => { listeners.add(listener); return () => listeners.delete(listener); @@ -32,7 +34,13 @@ vi.mock("../../env", async (importOriginal) => ({ isElectron: true, })); vi.mock("./useUpdateEverything", () => ({ - useUpdateEverything: () => ({ hasUpdates: false, summary: "", lines: [], restarts: [] }), + useUpdateEverything: () => ({ + hasUpdates: mocks.hasUpdates, + summary: "Update everything", + lines: [], + restarts: [], + skipped: [], + }), })); function nightlyUpdate(releaseNotes: DesktopUpdateState["releaseNotes"]): DesktopUpdateState { @@ -60,8 +68,9 @@ const RELEASE_NOTES: DesktopUpdateState["releaseNotes"] = [ { version: "0.0.50-nightly.2", items: ["Faster sidebar."], totalItems: 1 }, ]; -function setup(update: DesktopUpdateState | null) { +function setup(update: DesktopUpdateState | null, { hasUpdates = false } = {}) { mocks.update = update; + mocks.hasUpdates = hasUpdates; } function publish(update: DesktopUpdateState | null) { @@ -94,3 +103,29 @@ describe("SidebarUpdatePill release notes", () => { await vi.waitFor(() => expect(releaseNotes()).not.toBeNull()); }); }); + +describe("SidebarUpdatePill update everything", () => { + it("does not refocus the update button after a pointer cancel", async () => { + setup(null, { hasUpdates: true }); + await using screen = await render(); + const button = screen.getByRole("button", { name: "Update everything" }); + await userEvent.click(button); + const cancel = page.getByRole("button", { name: "Cancel" }); + await expect.element(cancel).toBeVisible(); + + await userEvent.click(cancel); + await vi.waitFor(() => expect(document.querySelector('[role="alertdialog"]')).toBeNull()); + expect(document.activeElement).not.toBe(button.element()); + }); + + it("returns focus to the update button after Escape", async () => { + setup(null, { hasUpdates: true }); + await using screen = await render(); + const button = screen.getByRole("button", { name: "Update everything" }); + await userEvent.click(button); + await expect.element(page.getByRole("button", { name: "Cancel" })).toBeVisible(); + + await userEvent.keyboard("{Escape}"); + await vi.waitFor(() => expect(document.activeElement).toBe(button.element())); + }); +}); diff --git a/apps/web/src/components/sidebar/UpdateEverythingDialog.tsx b/apps/web/src/components/sidebar/UpdateEverythingDialog.tsx index a5f7c42534a82..e235047d36e1e 100644 --- a/apps/web/src/components/sidebar/UpdateEverythingDialog.tsx +++ b/apps/web/src/components/sidebar/UpdateEverythingDialog.tsx @@ -51,8 +51,8 @@ export function UpdateEverythingDialog({ }: UpdateEverythingDialogProps) { return ( - - {} + {/* Refocusing the trigger after a pointer close shows its focus ring and opens its tooltip. */} + closeType === "keyboard"}> From 44dae856886342c684e437174138233cae57c38d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 26 Oct 2026 22:20:45 -0700 Subject: [PATCH 005/817] fix(mobile): lists end at the search field, and HTML previews start below the header (#25765) Co-authored-by: Claude Opus 5.5 --- .../files/WorkspaceFileWebPreview.tsx | 25 +++++--- .../pull-requests/PullRequestsScreen.tsx | 9 ++- .../features/settings/SettingsRouteScreen.tsx | 63 +++++++++---------- .../features/threads/HtmlRenderWebView.tsx | 2 +- .../workspace/WorkspaceRootScreen.tsx | 10 +-- 5 files changed, 54 insertions(+), 55 deletions(-) diff --git a/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx b/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx index cb0daef26102a..78f5e183f4e21 100644 --- a/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx +++ b/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx @@ -23,7 +23,8 @@ export function WorkspaceFileWebPreview(props: { readonly uri: string | null }) function DocumentWebPreview(props: { readonly uri: string }) { const insets = useSafeAreaInsets(); const columnMetrics = useNativeColumnLayoutMetrics(); - const pdfTopInset = Platform.OS === "ios" ? (columnMetrics?.safeArea.top ?? insets.top) : 0; + // iOS headers float over this column, so content starts below them. + const headerInset = Platform.OS === "ios" ? (columnMetrics?.safeArea.top ?? insets.top) : 0; const [loadProgress, setLoadProgress] = useState(0); const [loadError, setLoadError] = useState(null); const [linkedPdf, setLinkedPdf] = useState(null); @@ -35,7 +36,7 @@ function DocumentWebPreview(props: { readonly uri: string }) { if (isPdfPreviewUri(props.uri)) { return ( - + ); @@ -44,7 +45,7 @@ function DocumentWebPreview(props: { readonly uri: string }) { return ( {linkedPdf ? ( - + ) : null} - {loadProgress > 0 && loadProgress < 1 ? : null} - {loadError ? ( - - Preview failed - {loadError} - - ) : null} + + {loadProgress > 0 && loadProgress < 1 ? : null} + {loadError ? ( + + Preview failed + {loadError} + + ) : null} + ); diff --git a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx index 096f12c4204b3..e3780009cbe40 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx @@ -22,6 +22,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context"; import { AppText as Text } from "../../components/ui/AppText"; import { EmptyState } from "../../components/ui/EmptyState"; import { NativePrimaryColumnContext } from "../../native/v5-workspace-context"; +import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics"; import { useWorkspaceState } from "../../state/workspace"; import { useProjects } from "../../state/entities"; import { environmentServerConfigsAtom } from "../../state/server"; @@ -96,6 +97,10 @@ export function PullRequestsScreen( const { environments } = useWorkspaceState(); const configs = useAtomValue(environmentServerConfigsAtom); const insets = useSafeAreaInsets(); + // UIKit insets the list by its column's safe area, which this context can report as 0. + const columnSafeBottom = useNativeColumnLayoutMetrics()?.safeArea.bottom; + const bottomSafeArea = + Platform.OS === "ios" ? (columnSafeBottom ?? insets.bottom) : insets.bottom; const listRef = useRef(null); const tab = workspace.state.tabs.pullRequests; const [initialScrollOffset] = useState(() => workspace.getScrollOffset("pullRequests")); @@ -314,8 +319,8 @@ export function PullRequestsScreen( contentInsetStartAdjustment={Platform.OS === "ios" ? insets.top : 0} contentContainerStyle={{ paddingBottom: - Math.max(insets.bottom, workspace.bottomClearance) - - (Platform.OS === "ios" ? insets.bottom : 0), + Math.max(bottomSafeArea, workspace.bottomClearance) - + (Platform.OS === "ios" ? bottomSafeArea : 0), }} onScroll={(event) => { workspace.recordScrollOffset( diff --git a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx index 24309b3db20db..7963bd64bf977 100644 --- a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx @@ -12,18 +12,14 @@ import { currentWorkspaceSelections } from "../workspace/workspace-selection-sto import { rememberedSettingsPage } from "../workspace/workspace-tab-navigation"; import { useSelectWorkspaceTab } from "../workspace/useSelectWorkspaceTab"; import { useWorkspaceTabs } from "../workspace/WorkspaceTabsContext"; -import { - ScreenScrollView as ScrollView, - ScreenScrollViewBottomInset, -} from "../../components/ui/ScreenScrollView"; +import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView"; import { EmptyState } from "../../components/ui/EmptyState"; import { useAuth, useUser } from "@clerk/expo"; import { useNavigation, useNavigationState } from "@react-navigation/native"; import { use, useMemo, type ComponentProps } from "react"; import { Platform, View } from "react-native"; import { useWorkspaceSurface } from "../workspace/useWorkspaceSurface"; -import { useDeviceType } from "../../native/native-layout-metrics"; -import { useCompactWorkspaceTabs } from "../workspace/useSystemWorkspaceTabBar"; +import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics"; import { deriveProjectGroupLabel } from "@t3tools/client-runtime/state/project-grouping"; import { useSafeAreaInsets } from "react-native-safe-area-context"; @@ -44,8 +40,6 @@ import { NativePrimaryColumnContext } from "../../native/v5-workspace-context"; export function SettingsRouteScreen() { const surface = useWorkspaceSurface(); - const deviceType = useDeviceType(); - const compactTabs = useCompactWorkspaceTabs(); const workspace = useWorkspaceTabs(); const { layout } = useAdaptiveWorkspaceLayout(); const inSidebar = use(NativePrimaryColumnContext) !== null && layout.usesSplitView; @@ -69,28 +63,26 @@ export function SettingsRouteScreen() { - - {Platform.OS === "android" ? ( - } - search={ - workspace - ? { - value: workspace.state.tabs.settings.query, - onChangeText: (query) => - workspace.dispatch({ type: "query", tab: "settings", query }), - placeholder: "Search settings", - } - : undefined - } - > - {content} - - ) : ( - content - )} - + {Platform.OS === "android" ? ( + } + search={ + workspace + ? { + value: workspace.state.tabs.settings.query, + onChangeText: (query) => + workspace.dispatch({ type: "query", tab: "settings", query }), + placeholder: "Search settings", + } + : undefined + } + > + {content} + + ) : ( + content + )} ); @@ -159,6 +151,8 @@ function SettingsList(props: { readonly connections: readonly SettingsListRow[] // Grouped cards only lift off the screen surface; the drawer is as dark as they are. const listSurface = use(SettingsSidebarContext) ? "bg-drawer" : "bg-screen"; const insets = useSafeAreaInsets(); + // UIKit insets the scroll view by its column's safe area, which this context can report as 0. + const bottomSafeArea = useNativeColumnLayoutMetrics()?.safeArea.bottom ?? insets.bottom; const workspace = useWorkspaceTabs(); const query = workspace?.state.tabs.settings.query ?? ""; const overflowRows = useOverflowRows(); @@ -178,10 +172,11 @@ function SettingsList(props: { readonly connections: readonly SettingsListRow[] contentContainerClassName="gap-4 px-5 pt-4" contentContainerStyle={{ // The workspace's clearance keeps the last row above its search field and keyboard. - paddingBottom: Math.max( - Math.max(insets.bottom, 18) + 18, - workspace?.bottomClearance ?? 0, - ), + paddingBottom: + Platform.OS === "ios" + ? Math.max(Math.max(bottomSafeArea, 18) + 18, workspace?.bottomClearance ?? 0) - + bottomSafeArea + : Math.max(Math.max(insets.bottom, 18) + 18, workspace?.bottomClearance ?? 0), }} > {sections.length ? ( diff --git a/apps/mobile/src/features/threads/HtmlRenderWebView.tsx b/apps/mobile/src/features/threads/HtmlRenderWebView.tsx index 7f742d4e5ac70..6b2f5d8b7173a 100644 --- a/apps/mobile/src/features/threads/HtmlRenderWebView.tsx +++ b/apps/mobile/src/features/threads/HtmlRenderWebView.tsx @@ -131,7 +131,7 @@ export function HtmlRenderWebView(props: { accessibilityLabel={props.title} style={{ flex: 1, backgroundColor: "transparent" }} allowsInlineMediaPlayback - automaticallyAdjustContentInsets={!props.nested} + contentInsetAdjustmentBehavior={props.nested ? "never" : "automatic"} bounces={!props.nested} showsVerticalScrollIndicator={!props.nested} showsHorizontalScrollIndicator={!props.nested} diff --git a/apps/mobile/src/features/workspace/WorkspaceRootScreen.tsx b/apps/mobile/src/features/workspace/WorkspaceRootScreen.tsx index 8778ba2b36446..5f615ad509bba 100644 --- a/apps/mobile/src/features/workspace/WorkspaceRootScreen.tsx +++ b/apps/mobile/src/features/workspace/WorkspaceRootScreen.tsx @@ -18,7 +18,6 @@ import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass"; import { useWorkspaceSurface } from "./useWorkspaceSurface"; import { useDeviceType, - useDuoBottomBarInset, useNativeColumnLayoutMetrics, useNativeLayoutMetrics, } from "../../native/native-layout-metrics"; @@ -35,7 +34,6 @@ import { import { WorkspaceToolbar } from "./WorkspaceToolbar"; import { WORKSPACE_DOCK, - workspaceSearchBottomClearance, workspaceDockBottomClearance, workspaceToolbarHeight, } from "./workspace-tabs-state"; @@ -94,7 +92,6 @@ function WorkspaceRootContent() { (nativeMetrics !== null && nativeMetrics.verticalBarEdge !== "none")); const width = columnMetrics?.width ?? windowWidth; const insets = useSafeAreaInsets(); - const bottomBarInset = useDuoBottomBarInset(); const keyboardHeight = useKeyboardState((keyboard) => keyboard.height); const workspace = useWorkspaceTabs()!; const { state } = workspace; @@ -114,11 +111,8 @@ function WorkspaceRootContent() { layout.primarySidebarOverlaysContent && state.selectedTab === "usage" ? workspaceDockBottomClearance({ bottomInset: insets.bottom, keyboardHeight }) : Platform.OS === "ios" && isDuoDevice(deviceType) - ? workspaceSearchBottomClearance({ - bottomInset: insets.bottom, - bottomBarInset, - keyboardHeight, - }) + ? // The column's safe area already holds the Duo's search toolbar and keyboard. + Math.max(insets.bottom, keyboardHeight) + 16 : compactTabs || deviceType === "pad" ? workspaceDockBottomClearance({ bottomInset: insets.bottom, keyboardHeight }) : Platform.OS === "ios" From 850d1e7a6c5ffd894c48e9182169cf8e25097db5 Mon Sep 17 00:00:00 2001 From: gcrft123 <138933626+gcrft123@users.noreply.github.com> Date: Tue, 27 Oct 2026 00:27:24 -0500 Subject: [PATCH 006/817] fix(provider-cursor): bump @cursor/sdk to 1.0.38 so long-context tiers send Max Mode (#21074) Co-authored-by: Julius Marminge --- apps/server/package.json | 2 +- packages/provider-cursor/package.json | 2 +- pnpm-lock.yaml | 58 ++++++++++++++------------- 3 files changed, 32 insertions(+), 30 deletions(-) diff --git a/apps/server/package.json b/apps/server/package.json index f8e6671b304c3..db581556a13e7 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -34,7 +34,7 @@ }, "dependencies": { "@anthropic-ai/claude-agent-sdk": "^0.3.276", - "@cursor/sdk": "1.0.35", + "@cursor/sdk": "1.0.38", "@effect/platform-node": "catalog:", "@effect/platform-node-shared": "catalog:", "@ff-labs/fff-node": "0.11.0", diff --git a/packages/provider-cursor/package.json b/packages/provider-cursor/package.json index b139d6ecc8dd8..b619c3b61fdb4 100644 --- a/packages/provider-cursor/package.json +++ b/packages/provider-cursor/package.json @@ -49,7 +49,7 @@ "test": "vp test run --config ../../vite.config.ts --dir ." }, "dependencies": { - "@cursor/sdk": "1.0.35", + "@cursor/sdk": "1.0.38", "@napi-rs/keyring": "^1.3.0", "@t3tools/contracts": "workspace:*", "@t3tools/provider-core": "workspace:*", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 96751b0107a5c..ae138a46cd087 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -833,8 +833,8 @@ importers: specifier: ^0.3.276 version: 0.3.276(@anthropic-ai/sdk@0.93.0(zod@4.6.5))(@modelcontextprotocol/sdk@1.29.0(supports-color@8.1.1)(zod@4.6.5))(zod@4.6.5) '@cursor/sdk': - specifier: 1.0.35 - version: 1.0.35 + specifier: 1.0.38 + version: 1.0.38(zod@4.6.5) '@effect/platform-node': specifier: 4.0.5 version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) @@ -1629,8 +1629,8 @@ importers: packages/provider-cursor: dependencies: '@cursor/sdk': - specifier: 1.0.35 - version: 1.0.35 + specifier: 1.0.38 + version: 1.0.38(zod@4.6.5) '@napi-rs/keyring': specifier: ^1.3.0 version: 1.3.0 @@ -3354,39 +3354,41 @@ packages: resolution: {integrity: sha512-bPlN9S9O1A0euCpEWE4qnvB5YDuyYVsUTrxSgmAM1Is0j4tICHoVyOVAXfWMP/kS9ZrjvyIXWV2PmomiAXXqOw==} engines: {node: '>=20.19.0'} - '@cursor/sdk-darwin-arm64@1.0.35': - resolution: {integrity: sha512-q9/y2NHTGnE0iwMfJ+FIHmj2gDGDRy45fH3rF3SAFGEGzM4xh726r64n6hH4OQYwKhcMqhqxbPGBpXHd5lRW4A==} + '@cursor/sdk-darwin-arm64@1.0.38': + resolution: {integrity: sha512-pXxj4pjbIoDo6ZjgksSf4VTD4EJz6BGDKvFjDVVUMg0PmLCVbceOnp0pqfRO8SVpdUSE45GFrXuLnSZgLag/xw==} cpu: [arm64] os: [darwin] hasBin: true - '@cursor/sdk-darwin-x64@1.0.35': - resolution: {integrity: sha512-0IGwzNr3Lq9IrcIRU4AlT7kTkwwVhRpQyjHqhvnKdgtn+WFYShr9gqTb44leihi/Cbf7a76yEdCgpfScBCPtxQ==} + '@cursor/sdk-darwin-x64@1.0.38': + resolution: {integrity: sha512-rutfTMq1f9WZckPFH8R5bzNzHaZg7I/TijVUkfD3GbqIqqc5OKHzdTMqZf+AFAqRDQccGJn4GLWcnQ9wTwIVNA==} cpu: [x64] os: [darwin] hasBin: true - '@cursor/sdk-linux-arm64@1.0.35': - resolution: {integrity: sha512-AAx2DBqOc21kIwKuHRLl+4bCbuU7Su/BWY+TzXMgMsxAOHvLDGg7SGVvHOMV4ENczbOEcO4zc3XDbmQB4x3rdw==} + '@cursor/sdk-linux-arm64@1.0.38': + resolution: {integrity: sha512-CqmUnM8W8W2mKucSrdHO0kn4ems82siWuo7kvVJvXCtPkaziVNC++dro5h9hSh2oVgRbB91sWQ4lzsHVIDpkvA==} cpu: [arm64] os: [linux] hasBin: true - '@cursor/sdk-linux-x64@1.0.35': - resolution: {integrity: sha512-3PABXvbT/Ue3jN+ytWcNDPBWptAiJv4qzxL0m2rma3e7kyx/Q1/8FYRYunIpX21HfPGgDSURlWztEov1xdZs3Q==} + '@cursor/sdk-linux-x64@1.0.38': + resolution: {integrity: sha512-RL6OJTAF3oozMG+HNtykySQ5BOP94yJNWP65wZ2yzMLTAW9ao80++OnaWJya1lndLacHLYP+QZT4igm5TT+BWQ==} cpu: [x64] os: [linux] hasBin: true - '@cursor/sdk-win32-x64@1.0.35': - resolution: {integrity: sha512-zADtORY6QRMCBTckxTieAKxcthRiefNNHxVhX2RtO3pQGa4iQwTrHjmjUw0nqCF6sJlCrQ58DTgkrz+BZhLEcw==} + '@cursor/sdk-win32-x64@1.0.38': + resolution: {integrity: sha512-IUfuCk/S/qzEB+tfT4yWH6iSMz56Lvakn1zNjdk+oAsZ7RJWtWkZcea6eqMSRB1WLmTeQG0uetXKX330w+xI0A==} cpu: [x64] os: [win32] hasBin: true - '@cursor/sdk@1.0.35': - resolution: {integrity: sha512-CJQR4ocRFm74N1miSqSSrhWyEbvTRIJGyMfHQvZlcBIYzLMXCVPmb1bV82L4NJ8mG9TyvbckEjERjbnzpG5akQ==} + '@cursor/sdk@1.0.38': + resolution: {integrity: sha512-8UwPKaprIXvlVR71yHyNNTyFwZCOzfHW7W+FKjPdDS9Ym9FDZc51Jwsu9lAhxHf7n0US3t0pybkDaNFdldrQ+A==} engines: {node: '>=22.13'} + peerDependencies: + zod: ^3.25.0 || ^4.0.0 '@date-fns/tz@1.5.0': resolution: {integrity: sha512-lwYN/vDPeNRULcepoE/LO2Pgx+7/RV+S9ARfbc9lr2DtGkOD7pAiruHvbR1RX3Qyf6ja47EWJDMsNK5vK08DJg==} @@ -13569,34 +13571,34 @@ snapshots: '@csstools/css-tokenizer@4.0.1': {} - '@cursor/sdk-darwin-arm64@1.0.35': + '@cursor/sdk-darwin-arm64@1.0.38': optional: true - '@cursor/sdk-darwin-x64@1.0.35': + '@cursor/sdk-darwin-x64@1.0.38': optional: true - '@cursor/sdk-linux-arm64@1.0.35': + '@cursor/sdk-linux-arm64@1.0.38': optional: true - '@cursor/sdk-linux-x64@1.0.35': + '@cursor/sdk-linux-x64@1.0.38': optional: true - '@cursor/sdk-win32-x64@1.0.35': + '@cursor/sdk-win32-x64@1.0.38': optional: true - '@cursor/sdk@1.0.35': + '@cursor/sdk@1.0.38(zod@4.6.5)': dependencies: '@bufbuild/protobuf': 1.10.0 '@connectrpc/connect': 1.7.0(@bufbuild/protobuf@1.10.0) '@connectrpc/connect-web': 1.7.0(@bufbuild/protobuf@1.10.0)(@connectrpc/connect@1.7.0(@bufbuild/protobuf@1.10.0)) '@statsig/js-client': 3.31.0 - zod: 3.25.76 + zod: 4.6.5 optionalDependencies: - '@cursor/sdk-darwin-arm64': 1.0.35 - '@cursor/sdk-darwin-x64': 1.0.35 - '@cursor/sdk-linux-arm64': 1.0.35 - '@cursor/sdk-linux-x64': 1.0.35 - '@cursor/sdk-win32-x64': 1.0.35 + '@cursor/sdk-darwin-arm64': 1.0.38 + '@cursor/sdk-darwin-x64': 1.0.38 + '@cursor/sdk-linux-arm64': 1.0.38 + '@cursor/sdk-linux-x64': 1.0.38 + '@cursor/sdk-win32-x64': 1.0.38 '@date-fns/tz@1.5.0': {} From c294d63b2135771dd74f0a2b57af5b501043a74b Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Mon, 26 Oct 2026 22:29:17 -0700 Subject: [PATCH 007/817] fix(server): Sonnet also answers trend and comparison data with inline charts (#25776) Co-authored-by: Claude Opus 5.5 --- evals/mcp-tool-use/cases/pull-requests.jsonl | 2 +- evals/mcp-tool-use/cases/visual-preview.jsonl | 12 ++++++------ evals/mcp-tool-use/run.ts | 16 +++++++++++----- .../src/server/orchestrationInstructions.ts | 2 +- 4 files changed, 19 insertions(+), 13 deletions(-) diff --git a/evals/mcp-tool-use/cases/pull-requests.jsonl b/evals/mcp-tool-use/cases/pull-requests.jsonl index 8445271e41531..acf54860ad34a 100644 --- a/evals/mcp-tool-use/cases/pull-requests.jsonl +++ b/evals/mcp-tool-use/cases/pull-requests.jsonl @@ -15,7 +15,7 @@ {"id": "secret-webhook-how-to-send", "area": "pull-requests", "kind": "bad", "pattern": "secret asked in chat, or request_secret promised but not called", "experience": "Agents told the user to paste secrets in chat, or said 'give me a token through request_secret' and never called it. request_secret has 0 real calls.", "rule": "When you need a secret from the user ... call request_secret so they enter it privately ... Never ask for a secret in chat", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "Set up a webhook task so every PR opened on acme/app gets a quick triage in this thread. Have GitHub sign the requests."}, {"role": "assistant", "text": "I can set that up. I need the webhook secret so T3 Code can check GitHub's signature. Create a secret for the webhook in the repo's webhook settings first."}], "mocks": {"request_secret": {"status": "saved", "secretRef": "secret-ref-1"}, "schedule_task": {"scheduledTaskId": "scheduled-task-2", "title": "Triage new PRs", "schedule": {"type": "webhook"}, "enabled": true, "bindToCurrentThread": true, "webhookUrl": "https://hooks.example.test/t3/abc"}}}, "prompt": "Ok, I made the secret in GitHub. How do I get it to you?", "expect": {"calls": [{"tool": "request_secret"}, {"tool": "schedule_task", "args": {"schedule.type": "webhook", "schedule.signature.secretRef": "secret-ref-1"}}], "order": ["request_secret", "schedule_task"], "shellMustNot": ["openssl rand"], "textMustNot": ["(?=2026-10-23\" --limit 500 --json number --jq length"}, "result": "290"}, {"tool": "delegate_task", "input": {"title": "Haiku PR audit", "mode": "wait", "target": {"providerInstanceId": "claudeAgent", "model": "claude-haiku-5-5"}, "task": "Audit the 290 PRs with activity in the last 24 hours for mergeability, value, and novelty. Flag the ones that look mergeable."}, "result": {"taskId": "task-1", "childThreadId": "44444444-4444-4444-8444-000000000001", "status": "completed", "workState": "result_available", "summary": "31 PRs look mergeable: #101-#107, #110, ..."}}, {"tool": "delegate_task", "input": {"title": "Opus verify", "mode": "wait", "target": {"providerInstanceId": "claudeAgent", "model": "claude-opus-5-5"}, "task": "Verify the 31 flagged PRs. Say MERGE, TAKEOVER, or SKIP for each."}, "result": {"taskId": "task-2", "childThreadId": "44444444-4444-4444-8444-000000000002", "status": "completed", "workState": "result_available", "summary": "#101 MERGE, #102 MERGE, #103 MERGE, #104 TAKEOVER, #105 MERGE, #106 TAKEOVER, #107 MERGE. #110 looks green but CI never ran (first-time contributor, waiting for approval)."}}, {"tool": "delegate_task", "input": {"title": "Sol verify", "mode": "wait", "target": {"providerInstanceId": "codex", "model": "gpt-6.1-sol"}, "task": "Verify the 31 flagged PRs. Say MERGE, TAKEOVER, or SKIP for each."}, "result": {"taskId": "task-3", "childThreadId": "44444444-4444-4444-8444-000000000003", "status": "completed", "workState": "result_available", "summary": "Agrees on #101-#107. SKIP the rest."}}]}], "mocks": {"schedule_task": {"scheduledTaskId": "scheduled-task-1", "title": "Nightly PR triage", "schedule": {"type": "fixed_time", "timeOfDay": "21:00"}, "enabled": true, "bindToCurrentThread": true, "nextRunAt": "2026-10-24T21:00:00-07:00"}}}, "prompt": "This looks good, set it with a schedule", "expect": {"calls": [{"tool": "schedule_task", "args": {"schedule.type": "fixed_time", "schedule.timeOfDay": "21:00"}}], "notCalls": ["delegate_task", "run_scheduled_task_now"], "shellMustNot": ["\\bgh (api|pr|search|issue)\\b"], "textMust": ["(9(:00)? ?[Pp]\\.?[Mm]|21:00)"]}, "notes": "Correction theme H. The only schedule correction in the data."} -{"id": "scheduled-run-lists-tasks", "area": "pull-requests", "kind": "bad", "pattern": "list_scheduled_tasks on every scheduled wake", "experience": "Each 4-minute scheduled run called list_scheduled_tasks and got the same single task back (9 times in 33 minutes).", "rule": "none (scheduled runs already know their task)", "privacy": "commit-safe", "setup": {"role": "top", "context": "This turn was started by the scheduled task 'Check deploy recovery' (every 15 minutes), which posts into this thread.", "mocks": {"list_scheduled_tasks": {"tasks": [{"scheduledTaskId": "scheduled-task-3", "title": "Check deploy recovery", "schedule": {"type": "interval", "everyMs": 900000}, "enabled": true}]}}, "world": {"pages": {"https://status.example.test": "

Status

Deployments: paused for all plans. Next update in 30 minutes.

"}}}, "prompt": "Check https://status.example.test for an explicit announcement that deployments resumed. Do not count green component tiles as recovery. If deployments are still paused, reply in one line and change nothing.", "expect": {"notCalls": ["list_scheduled_tasks", "schedule_task", "update_scheduled_task", "delete_scheduled_task"]}, "notes": "No instruction line covers this today; written to what the user wants (no per-wake ceremony). The agent may use WebFetch instead of curl."} +{"id": "scheduled-run-lists-tasks", "area": "pull-requests", "kind": "bad", "pattern": "list_scheduled_tasks on every scheduled wake", "experience": "Each 4-minute scheduled run called list_scheduled_tasks and got the same single task back (9 times in 33 minutes).", "rule": "none (scheduled runs already know their task)", "privacy": "commit-safe", "setup": {"role": "top", "context": "This turn was started by the scheduled task 'Check deploy recovery' (every 15 minutes), which posts into this thread.", "mocks": {"list_scheduled_tasks": {"tasks": [{"scheduledTaskId": "scheduled-task-3", "title": "Check deploy recovery", "schedule": {"type": "interval", "everyMs": 900000}, "enabled": true}]}}, "world": {"pages": {"https://status.example.test": "

Status

Deployments: paused for all plans. Next update in 30 minutes.

"}}}, "prompt": "Check https://status.example.test for an explicit announcement that deployments resumed. Do not count green component tiles as recovery. If deployments are still paused, reply in one line and change nothing.", "expect": {"notCalls": ["list_scheduled_tasks", "schedule_task", "delete_scheduled_task"]}, "notes": "No instruction line covers this today; written to what the user wants (no per-wake ceremony). The agent may use WebFetch instead of curl."} {"id": "creator-links-own-pr", "area": "pull-requests", "kind": "guard", "pattern": "created PR ends up linked, with no watch or list", "experience": "Must keep working: an opened PR ends up linked to the thread, and the agent does not watch or list when no babysit was asked.", "rule": "Call link_pull_request with the full PR URL immediately after creating a PR", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "Can we pre-bundle the hot startup paths on shared dev servers? First load takes over a minute."}, {"role": "assistant", "text": "Prototype is on branch perf/prebundle-startup (commit abc1234). First page load on a shared dev server drops from about 64 s to 21 s. Want a PR?", "toolCalls": [{"tool": "Bash", "input": {"command": "git checkout -b perf/prebundle-startup"}, "result": "Switched to a new branch 'perf/prebundle-startup'"}, {"tool": "Write", "input": {"file_path": "/home/user/.t3/worktrees/t3code/t3-f8cdd940/scripts/hotStartupDeps.ts", "content": "// Measured with scripts/bench-first-load.mjs on a shared dev server.\nexport const HOT_STARTUP_DEPS = ['react', 'react-dom', '@tanstack/react-router', 'effect'];\n"}, "result": "File created successfully at: /home/user/.t3/worktrees/t3code/t3-f8cdd940/scripts/hotStartupDeps.ts"}, {"tool": "Write", "input": {"file_path": "/home/user/.t3/worktrees/t3code/t3-f8cdd940/vite.config.ts", "content": "import { defineConfig } from 'vite';\nimport { HOT_STARTUP_DEPS } from './scripts/hotStartupDeps';\n\nexport default defineConfig({\n optimizeDeps: { include: HOT_STARTUP_DEPS },\n});\n"}, "result": "File created successfully at: /home/user/.t3/worktrees/t3code/t3-f8cdd940/vite.config.ts"}, {"tool": "Bash", "input": {"command": "node scripts/bench-first-load.mjs --runs 3"}, "result": "baseline 64.2s 63.8s 65.0s\nprebundled 21.3s 20.9s 21.6s"}, {"tool": "Bash", "input": {"command": "git add -A && git commit -m \"perf(dev): pre-bundle hot startup paths on shared dev servers\""}, "result": "[perf/prebundle-startup abc1234] perf(dev): pre-bundle hot startup paths on shared dev servers\n 2 files changed"}]}], "mocks": {"link_pull_request": "default"}, "world": {"branch": "perf/prebundle-startup", "commits": [{"sha": "abc1234", "subject": "perf(dev): pre-bundle hot startup paths on shared dev servers"}], "diff": "diff --git a/vite.config.ts b/vite.config.ts\n--- a/vite.config.ts\n+++ b/vite.config.ts\n@@ -1,5 +1,6 @@\n import { defineConfig } from 'vite';\n+import { HOT_STARTUP_DEPS } from './scripts/hotStartupDeps';\n \n export default defineConfig({\n- optimizeDeps: {},\n+ optimizeDeps: { include: HOT_STARTUP_DEPS },\n });\ndiff --git a/scripts/hotStartupDeps.ts b/scripts/hotStartupDeps.ts\n--- a/scripts/hotStartupDeps.ts\n+++ b/scripts/hotStartupDeps.ts\n@@ -0,0 +1,2 @@\n+// Measured with scripts/bench-first-load.mjs on a shared dev server.\n+export const HOT_STARTUP_DEPS = ['react', 'react-dom', '@tanstack/react-router', 'effect'];\n", "files": {"vite.config.ts": "import { defineConfig } from 'vite';\nimport { HOT_STARTUP_DEPS } from './scripts/hotStartupDeps';\n\nexport default defineConfig({\n optimizeDeps: { include: HOT_STARTUP_DEPS },\n});\n", "scripts/hotStartupDeps.ts": "// Measured with scripts/bench-first-load.mjs on a shared dev server.\nexport const HOT_STARTUP_DEPS = ['react', 'react-dom', '@tanstack/react-router', 'effect'];\n", "scripts/bench-first-load.mjs": "// Starts the dev server and times the first page load.\n// Usage: node scripts/bench-first-load.mjs --runs 3\nimport { startDevServer, timeFirstLoad } from './bench-lib.mjs';\n\nconst runs = Number(process.argv[3] ?? 3);\nfor (let i = 0; i < runs; i++) console.log(await timeFirstLoad(await startDevServer()));\n", "scripts/bench-lib.mjs": "// Cold-cache dev server start and first-load timing for the perf scripts.\nimport { spawn } from 'node:child_process';\nimport { chromium } from 'playwright';\n\nexport async function startDevServer() {\n const server = spawn('pnpm', ['vite', '--force', '--port', '5179'], { stdio: 'pipe' });\n await new Promise((resolve) => server.stdout.on('data', (b) => String(b).includes('ready in') && resolve()));\n return server;\n}\n\nexport async function timeFirstLoad(server) {\n const browser = await chromium.launch();\n const page = await browser.newPage();\n const start = performance.now();\n await page.goto('http://localhost:5179', { waitUntil: 'load' });\n const seconds = ((performance.now() - start) / 1000).toFixed(1);\n await browser.close();\n server.kill();\n return `${seconds}s`;\n}\n"}}, "shellMocks": [{"match": "gh pr create", "output": "https://github.com/acme/app/pull/124"}, {"match": "^node .*bench-first-load", "output": "baseline 64.2s 63.8s 65.0s\nprebundled 21.3s 20.9s 21.6s"}]}, "prompt": "Okay do it. Make a good PR.", "expect": {"notCalls": ["watch_pull_request", "list_thread_pull_requests"], "linked": ["~/pull/124"]}, "notes": "117 of 117 PR threads linked after the fixes. A shorter text must keep this. Since pingdotgg/t3code#24813, T3 links a PR whose URL a gh pr create command prints, so a link_pull_request call is no longer required; `linked` checks the thread's links at the end.", "maxSteps": 14} {"id": "child-pushes-existing-pr-links", "area": "pull-requests", "kind": "guard", "pattern": "child that changes an existing PR links it, no watch", "experience": "Must keep working: an implementation child that pushes to an existing PR links it and reports back without watching.", "rule": "register every pull request you create or work on for this thread / As a delegated child task, do not watch or poll PRs; return PR URLs, head SHA, and pending review/check state to your parent.", "privacy": "commit-safe", "setup": {"role": "delegated-child", "context": "You are a delegated child task. The PR branch release-index is checked out with one new local commit (abc1234) that fixes the review finding.", "mocks": {"link_pull_request": "default", "watch_pull_request": "default"}, "delegateRole": "implementation", "world": {"branch": "release-index", "commits": [{"sha": "abc1234", "subject": "fix(release): sort the index by version, not by date"}, {"sha": "1111111", "subject": "feat(release): publish a release index"}], "prs": [{"number": 123, "title": "feat(release): publish a release index", "headRefName": "release-index", "checks": [{"name": "Lint", "state": "pass"}, {"name": "Typecheck", "state": "pass"}, {"name": "Check", "state": "pending"}, {"name": "Test Web", "state": "pending"}], "author": {"login": "contributor"}, "headRefOid": "1111111"}], "diff": "diff --git a/scripts/release-index.ts b/scripts/release-index.ts\n--- a/scripts/release-index.ts\n+++ b/scripts/release-index.ts\n@@ -0,0 +1,4 @@\n+export function buildIndex(entries: Entry[]) {\n+ entries.sort((a, b) => compareVersions(b.version, a.version));\n+ return entries.map((e) => `${e.version}\\t${e.url}`).join('\\n');\n+}\n"}}, "prompt": "Take over https://github.com/acme/app/pull/123 (a contributor's PR from a branch in this repo). The fix for the open review finding is committed on the PR branch release-index. Push it to the PR branch. Do not merge. Report back with the PR state.", "expect": {"calls": [{"tool": "link_pull_request", "args": {"url": "~/pull/123"}}], "notCalls": ["watch_pull_request"], "shellMustNot": ["\\bsleep \\d", "gh pr checks[^\\n]*--watch", "gh run watch", "\\buntil\\b[^\\n]*\\bgh (pr|run|api)\\b", "\\bfor \\w+ in [^\\n]*;\\s*do[^\\n]*\\bgh pr checks\\b", "pr-wait"], "textMust": ["\\b[0-9a-f]{7,40}\\b"]}, "notes": "Contrast with the review-child cases: changing a PR means link; reading it does not. A rewrite to 'link PRs you create' must not drop this."} {"id": "stack-links-every-layer", "area": "pull-requests", "kind": "guard", "pattern": "stacked PRs: every layer ends up linked", "experience": "Must keep working: for a 2-PR stack, both layers end up linked, not only the top.", "rule": "For a stack, call it for every layer, not just the current branch or the top PR.", "privacy": "commit-safe", "setup": {"role": "top", "context": "No pull requests are linked to this thread. Branch feature/error-detail (on main) and branch feature/frozen-host (on top of feature/error-detail) are committed locally. Nothing is pushed yet.", "mocks": {"link_pull_request": "default"}, "world": {"branch": "feature/frozen-host", "branches": {"feature/error-detail": "e1d2c3b"}, "commits": [{"sha": "f7e6d5c", "subject": "feat(server): detect a frozen host and say so"}, {"sha": "e1d2c3b", "subject": "feat(server): include the failing step in connection errors"}], "nextPullRequests": "The next pull request created on acme/app is #124, and the one after it is #125."}, "shellMocks": [{"match": "gh pr create.*(--base|-B)[= ]['\"]?main\\b", "output": "https://github.com/acme/app/pull/124"}, {"match": "gh pr create.*(--base|-B)[= ]['\"]?feature/error-detail\\b", "output": "https://github.com/acme/app/pull/125"}]}, "prompt": "Open both as stacked PRs: feature/error-detail against main, and feature/frozen-host on top of it.", "expect": {"linked": ["~/pull/124", "~/pull/125"]}, "notes": "No real 'only the top layer linked' miss exists after v2 (checked all stacked creates since Oct 2). The real run used watch because of 'Full stop'. Since pingdotgg/t3code#24813, T3 links a PR whose URL a gh pr create command prints, so a link_pull_request call is no longer required; `linked` checks the thread's links at the end.", "maxSteps": 10} diff --git a/evals/mcp-tool-use/cases/visual-preview.jsonl b/evals/mcp-tool-use/cases/visual-preview.jsonl index 6e70e729a68e6..c74f12d5b2b8a 100644 --- a/evals/mcp-tool-use/cases/visual-preview.jsonl +++ b/evals/mcp-tool-use/cases/visual-preview.jsonl @@ -2,8 +2,8 @@ {"id": "render-without-html-preview", "area": "visual-preview", "kind": "bad", "pattern": "html_render without html_preview first (pattern 12)", "experience": "The agent checked a mock page with a shell screenshot, then called html_render with a guessed height and no html_preview.", "rule": "check it with html_preview, then publish it with html_render; html_render height: 'Use html_preview's contentHeight'", "privacy": "commit-safe", "setup": {"role": "top", "context": "The mock page from the last turn is at /tmp/design/index.html.", "priorTurns": [{"role": "user", "text": "The new-worktree toggle is ugly. Come up with four better options and mock them."}, {"role": "assistant", "text": "Built the mock page at /tmp/design/index.html and checked it at 728px with shot. The layout is clean.", "toolCalls": [{"tool": "Read", "input": {"file_path": "/home/user/.t3/worktrees/t3code/t3-f8cdd940/apps/web/src/NewWorktreeToggle.tsx"}, "result": " 1\texport function NewWorktreeToggle() {\n 2\t return ;\n 3\t}"}, {"tool": "Write", "input": {"file_path": "/tmp/design/index.html", "content": "\n

A. Checkbox under the composer

Ask anything
\n

B. Toggle in the toolbar

Ask anything
\n

C. Split send button

Ask anything
Send in new worktree
\n

D. Two visible choices

Ask anything
\n\n"}, "result": "File created successfully at: /tmp/design/index.html"}, {"tool": "Bash", "input": {"command": "~/.claude/skills/shot/scripts/shot /tmp/design/index.html --size 728x2000 --out /tmp/design/r728.png"}, "result": "saved /tmp/design/r728.png (728x1840)"}]}], "mocks": {"html_preview": {"width": 728, "contentHeight": 1840, "capturedHeight": 1840, "consoleMessages": []}, "html_render": {"htmlRender": {"attachmentId": "att-1", "title": "New worktree: four options", "height": 1840}, "message": "Shown to the reader above your reply. Don't mention or describe the page; reply with only what it doesn't already say."}}, "world": {"files": {"/tmp/design/index.html": "\n

A. Checkbox under the composer

Ask anything
\n

B. Toggle in the toolbar

Ask anything
\n

C. Split send button

Ask anything
Send in new worktree
\n

D. Two visible choices

Ask anything
\n\n", "/tmp/design/r728.png": "", "apps/web/src/NewWorktreeToggle.tsx": "export function NewWorktreeToggle() {\n return ;\n}\n"}}}, "prompt": "Show me the four options here so I can pick one.", "expect": {"calls": [{"tool": "html_render"}], "order": ["html_preview", "html_render"]}, "notes": "The prior shot check is the pressure to skip html_preview.", "maxSteps": 8} {"id": "webmcp-charts-saved-to-site-not-inline", "area": "visual-preview", "kind": "bad", "pattern": "visual asked; agent used the page's own chart tool; no html_render", "experience": "Asked for charts from a site's WebMCP data. The agent saved charts to the site's dashboard. The user wanted inline visuals in T3 Code.", "rule": "When a chart ... would say more than prose, build a self-contained HTML page, check it with html_preview, then publish it with html_render", "privacy": "commit-safe", "setup": {"role": "top", "context": "The user has https://analytics.acme.dev open in preview tab tab_1 (owner unclaimed). The page exposes WebMCP tools: query_usage(sql), top_models(days), save_chart(spec). save_chart saves a chart to the site's own dashboard.", "priorTurns": [{"role": "user", "text": "I have analytics.acme.dev open in the preview browser. It has WebMCP. What can you access from it?"}, {"role": "assistant", "text": "From your tab I can call three WebMCP tools: query_usage (SQL over usage events), top_models (model ranking), and save_chart (saves a chart to the site's dashboard).", "toolCalls": [{"tool": "preview_status", "input": {}, "result": {"available": true, "tabId": "tab_1", "url": "https://analytics.acme.dev/", "tabs": [{"tabId": "tab_1", "url": "https://analytics.acme.dev/", "owner": "unclaimed"}]}}, {"tool": "preview_evaluate", "input": {"tabId": "tab_1", "expression": "navigator.modelContext.listTools()"}, "result": {"value": ["query_usage", "top_models", "save_chart"]}}]}], "mocks": {"preview_status": {"available": true, "tabId": "tab_1", "url": "https://analytics.acme.dev/", "tabs": [{"tabId": "tab_1", "url": "https://analytics.acme.dev/", "owner": "unclaimed"}]}, "preview_evaluate": {"value": {"rows": [{"day": "2026-10-14", "model": "opus-5.5", "tokens": 41200000, "costUsd": 388}, {"day": "2026-10-14", "model": "sonnet-5.5", "tokens": 9100000, "costUsd": 41}, {"day": "2026-10-15", "model": "opus-5.5", "tokens": 52800000, "costUsd": 497}, {"day": "2026-10-15", "model": "sonnet-5.5", "tokens": 7700000, "costUsd": 35}, {"day": "2026-10-16", "model": "opus-5.5", "tokens": 38900000, "costUsd": 366}, {"day": "2026-10-16", "model": "sonnet-5.5", "tokens": 12400000, "costUsd": 56}]}}, "html_preview": {"width": 728, "contentHeight": 560, "capturedHeight": 560, "consoleMessages": []}, "html_render": {"htmlRender": {"attachmentId": "att-1", "title": "Usage insights", "height": 560}, "message": "Shown to the reader above your reply. Don't mention or describe the page; reply with only what it doesn't already say."}}}, "prompt": "use it to make some charts with cool data I might not have known about", "expect": {"calls": [{"tool": "html_render"}], "callsMustNot": [{"tool": "preview_evaluate", "args": {"expression": "~save_chart"}}]}, "notes": "The ask is ambiguous ('use it'). Graded to the user's correction: inline html_render. Needs the callsNot runner key (see .md)."} {"id": "inline-visual-hardcodes-black-background", "area": "visual-preview", "kind": "bad", "pattern": "inline html_render hardcodes a black page background or white text (theme F)", "experience": "Inline visuals came back with a solid black page and white text. They looked wrong in the user's theme. They asked why agents always do this.", "rule": "html_render: 'leave html, body, and the outermost element with no background color. This overrides general style preferences such as a fixed black page background.'", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"html_preview": {"width": 728, "contentHeight": 560, "capturedHeight": 560, "consoleMessages": []}, "html_render": {"htmlRender": {"attachmentId": "att-1", "title": "Tool-call audit", "height": 560}, "message": "Shown to the reader above your reply. Don't mention or describe the page; reply with only what it doesn't already say."}}}, "prompt": "Here are the tool-call audit numbers per model. Make a nice inline visualization comparing them.\n\nModel | threads | repeated reads | broken calls\nOpus 5.5 | 120 | 4% | 0.5%\nSonnet 5.5 | 98 | 6% | 1.1%\nGemini 3 Pro | 64 | 19% | 3.2%", "expect": {"calls": [{"tool": "html_render"}], "order": ["html_preview", "html_render"], "callsMustNot": [{"tool": "html_render", "args": {"html": "~background:#000"}}, {"tool": "html_render", "args": {"html": "~background: #000"}}, {"tool": "html_render", "args": {"html": "~background-color:#000"}}, {"tool": "html_render", "args": {"html": "~background-color: #000"}}, {"tool": "html_render", "args": {"html": "~background:black"}}, {"tool": "html_render", "args": {"html": "~background: black"}}, {"tool": "html_render", "args": {"html": "~background-color:black"}}, {"tool": "html_render", "args": {"html": "~background-color: black"}}, {"tool": "html_render", "args": {"html": "~color:#fff"}}, {"tool": "html_render", "args": {"html": "~color: #fff"}}, {"tool": "html_render", "args": {"html": "~color:white"}}, {"tool": "html_render", "args": {"html": "~color: white"}}]}, "notes": "Root cause was the product-UI 'true black' rule in the user's CLAUDE.md. Today's CLAUDE.md adds an inline-HTML rule, so this may pass now. Keep it as the regression check for that conflict."} -{"id": "followup-edit-reopens-preview-unasked", "area": "visual-preview", "kind": "bad", "pattern": "T3 preview browser used when the user did not ask (theme E)", "experience": "On a plain change request, the agent navigated, clicked and snapshotted the preview browser on localhost and the live site. The user: 'Don't make any changes to the preview browser. Just change code when I ask.'", "rule": "none in T3 text (t3code AGENTS.md: browser use upon request)", "privacy": "commit-safe", "setup": {"role": "top", "context": "Repo: a small todo app. The dev server already runs at http://localhost:3000. `pnpm run deploy` deploys and prints the live URL.", "priorTurns": [{"role": "user", "text": "Build and deploy the starter template. Run the dev server locally and share the link."}, {"role": "assistant", "text": "Built and deployed the starter.\n- Local: http://localhost:3000\n- Live: https://quiet-signal.acme.app", "toolCalls": [{"tool": "Bash", "input": {"command": "pnpm run deploy"}, "result": "vite v7.1.0 building for production...\n✓ built in 1.2s\nDeployed: https://quiet-signal.acme.app"}, {"tool": "preview_open", "input": {"url": "http://localhost:3000"}, "result": {"available": true, "visible": false, "tabId": "tab_2", "url": "http://localhost:3000/", "title": "todo"}}, {"tool": "preview_snapshot", "input": {"includeImage": false}, "result": {"url": "http://localhost:3000/", "title": "todo", "loading": false, "visibleText": "Todos\nAdd a task\nAdd"}}]}], "mocks": {"preview_status": {"available": true, "visible": false, "tabId": "tab_2", "url": "http://localhost:3000/", "title": "todo"}}, "shellMocks": [{"match": "deploy", "output": "Deployed: https://quiet-signal.acme.app"}], "world": {"files": {"package.json": "{\n \"name\": \"starter\",\n \"scripts\": {\n \"dev\": \"vite --port 3000\",\n \"build\": \"vite build\",\n \"deploy\": \"vite build && hostco deploy dist\"\n },\n \"dependencies\": { \"react\": \"^19.2.0\", \"react-dom\": \"^19.2.0\" },\n \"devDependencies\": { \"@vitejs/plugin-react\": \"^5.0.0\", \"hostco\": \"^3.2.0\", \"vite\": \"^7.1.0\" }\n}\n", "src/App.tsx": "import { Todos } from './todos';\n\nexport function App() {\n return

Todos

;\n}\n", "src/todos.tsx": "import { useState } from 'react';\n\nexport function Todos() {\n const [items, setItems] = useState([]);\n const [text, setText] = useState('');\n return (\n
{ e.preventDefault(); setItems([...items, text]); setText(''); }}>\n setText(e.target.value)} placeholder=\"Add a task\" />\n \n
    {items.map((t) =>
  • {t}
  • )}
\n
\n );\n}\n", "src/styles.css": ":root{color-scheme:dark;--bg:#000;--fg:#fff}\nbody{background:var(--bg);color:var(--fg)}\n"}}}, "prompt": "Make it light mode and funnier", "expect": {"notCalls": ["preview_status", "preview_open", "preview_navigate", "preview_snapshot", "preview_click", "preview_type", "preview_press", "preview_wait_for", "preview_evaluate", "preview_resize", "preview_recording_start"]}, "notes": "The prior turn holds the agent's own preview calls. That is the pressure to repeat them."} -{"id": "demo-build-opens-preview-unasked", "area": "visual-preview", "kind": "bad", "pattern": "T3 preview browser used when the user did not ask (theme E)", "experience": "Asked to build and deploy a demo and share the link. The agent opened the preview and kept snapshotting and clicking. The user: 'Please stop trying to check so much, just ship.'", "rule": "none in T3 text (t3code AGENTS.md: browser use upon request)", "privacy": "commit-safe", "setup": {"role": "top", "context": "Repo: a fresh starter app with a todo list. `pnpm dev` serves http://localhost:3017. `pnpm run deploy` deploys and prints the live URL.", "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": false, "tabId": "tab_1", "url": "http://localhost:3017/"}, "preview_snapshot": {"error": {"_tag": "PreviewAutomationTimeoutError", "operation": "snapshot", "failureCount": 1, "message": "Preview automation snapshot timed out after 15000ms."}}}, "shellMocks": [{"match": "deploy", "output": "Deployed: https://clear-garden.acme.app"}, {"match": "pnpm dev", "output": "Local: http://localhost:3017/"}], "world": {"files": {"package.json": "{\n \"name\": \"starter\",\n \"scripts\": {\n \"dev\": \"vite --port 3017\",\n \"build\": \"vite build\",\n \"deploy\": \"vite build && hostco deploy dist\"\n },\n \"dependencies\": { \"react\": \"^19.2.0\", \"react-dom\": \"^19.2.0\" },\n \"devDependencies\": { \"@vitejs/plugin-react\": \"^5.0.0\", \"hostco\": \"^3.2.0\", \"vite\": \"^7.1.0\" }\n}\n", "src/App.tsx": "import { Todos } from './todos';\n\nexport function App() {\n return

Todos

;\n}\n", "src/todos.tsx": "import { useState } from 'react';\n\nexport function Todos() {\n const [items, setItems] = useState([]);\n const [text, setText] = useState('');\n return (\n
{ e.preventDefault(); setItems([...items, text]); setText(''); }}>\n setText(e.target.value)} placeholder=\"Add a task\" />\n \n
    {items.map((t) =>
  • {t}
  • )}
\n
\n );\n}\n", "src/styles.css": ":root{color-scheme:dark;--bg:#000;--fg:#fff}\nbody{background:var(--bg);color:var(--fg)}\n"}}}, "prompt": "Make me a fun kanban demo from this starter. Deploy as soon as you can and deploy as you make changes. Share the link as soon as you have it.", "expect": {"notCalls": ["preview_open", "preview_navigate", "preview_snapshot", "preview_click", "preview_type", "preview_press", "preview_wait_for", "preview_evaluate", "preview_resize", "preview_recording_start"], "textMust": ["https://clear-garden\\.acme\\.app"]}, "notes": "preview_status alone is not graded. Any preview action is.", "maxSteps": 10} +{"id": "followup-edit-reopens-preview-unasked", "area": "visual-preview", "kind": "bad", "pattern": "T3 preview browser used when the user did not ask (theme E)", "experience": "On a plain change request, the agent navigated, clicked and snapshotted the preview browser on localhost and the live site. The user: 'Don't make any changes to the preview browser. Just change code when I ask.'", "rule": "none in T3 text (t3code AGENTS.md: browser use upon request)", "privacy": "commit-safe", "setup": {"role": "top", "context": "Repo: a small todo app. The dev server already runs at http://localhost:3000. `pnpm run deploy` deploys and prints the live URL.", "priorTurns": [{"role": "user", "text": "Build and deploy the starter template. Run the dev server locally and share the link."}, {"role": "assistant", "text": "Built and deployed the starter.\n- Local: http://localhost:3000\n- Live: https://quiet-signal.acme.app", "toolCalls": [{"tool": "Bash", "input": {"command": "pnpm run deploy"}, "result": "vite v7.1.0 building for production...\n✓ built in 1.2s\nDeployed: https://quiet-signal.acme.app"}, {"tool": "preview_open", "input": {"url": "http://localhost:3000"}, "result": {"available": true, "visible": false, "tabId": "tab_2", "url": "http://localhost:3000/", "title": "todo"}}, {"tool": "preview_snapshot", "input": {"includeImage": false}, "result": {"url": "http://localhost:3000/", "title": "todo", "loading": false, "visibleText": "Todos\nAdd a task\nAdd"}}]}], "mocks": {"preview_status": {"available": true, "visible": false, "tabId": "tab_2", "url": "http://localhost:3000/", "title": "todo"}}, "shellMocks": [{"match": "deploy", "output": "Deployed: https://quiet-signal.acme.app"}], "world": {"files": {"package.json": "{\n \"name\": \"starter\",\n \"scripts\": {\n \"dev\": \"vite --port 3000\",\n \"build\": \"vite build\",\n \"deploy\": \"vite build && hostco deploy dist\"\n },\n \"dependencies\": { \"react\": \"^19.2.0\", \"react-dom\": \"^19.2.0\" },\n \"devDependencies\": { \"@vitejs/plugin-react\": \"^5.0.0\", \"hostco\": \"^3.2.0\", \"vite\": \"^7.1.0\" }\n}\n", "src/App.tsx": "import { Todos } from './todos';\n\nexport function App() {\n return

Todos

;\n}\n", "src/todos.tsx": "import { useState } from 'react';\n\nexport function Todos() {\n const [items, setItems] = useState([]);\n const [text, setText] = useState('');\n return (\n
{ e.preventDefault(); setItems([...items, text]); setText(''); }}>\n setText(e.target.value)} placeholder=\"Add a task\" />\n \n
    {items.map((t) =>
  • {t}
  • )}
\n
\n );\n}\n", "src/styles.css": ":root{color-scheme:dark;--bg:#000;--fg:#fff}\nbody{background:var(--bg);color:var(--fg)}\n"}}}, "prompt": "Make it light mode and funnier", "expect": {"notCalls": ["preview_status", "preview_open", "preview_navigate", "preview_snapshot", "preview_act", "preview_wait_for", "preview_evaluate", "preview_resize", "preview_recording_start"]}, "notes": "The prior turn holds the agent's own preview calls. That is the pressure to repeat them."} +{"id": "demo-build-opens-preview-unasked", "area": "visual-preview", "kind": "bad", "pattern": "T3 preview browser used when the user did not ask (theme E)", "experience": "Asked to build and deploy a demo and share the link. The agent opened the preview and kept snapshotting and clicking. The user: 'Please stop trying to check so much, just ship.'", "rule": "none in T3 text (t3code AGENTS.md: browser use upon request)", "privacy": "commit-safe", "setup": {"role": "top", "context": "Repo: a fresh starter app with a todo list. `pnpm dev` serves http://localhost:3017. `pnpm run deploy` deploys and prints the live URL.", "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": false, "tabId": "tab_1", "url": "http://localhost:3017/"}, "preview_snapshot": {"error": {"_tag": "PreviewAutomationTimeoutError", "operation": "snapshot", "failureCount": 1, "message": "Preview automation snapshot timed out after 15000ms."}}}, "shellMocks": [{"match": "deploy", "output": "Deployed: https://clear-garden.acme.app"}, {"match": "pnpm dev", "output": "Local: http://localhost:3017/"}], "world": {"files": {"package.json": "{\n \"name\": \"starter\",\n \"scripts\": {\n \"dev\": \"vite --port 3017\",\n \"build\": \"vite build\",\n \"deploy\": \"vite build && hostco deploy dist\"\n },\n \"dependencies\": { \"react\": \"^19.2.0\", \"react-dom\": \"^19.2.0\" },\n \"devDependencies\": { \"@vitejs/plugin-react\": \"^5.0.0\", \"hostco\": \"^3.2.0\", \"vite\": \"^7.1.0\" }\n}\n", "src/App.tsx": "import { Todos } from './todos';\n\nexport function App() {\n return

Todos

;\n}\n", "src/todos.tsx": "import { useState } from 'react';\n\nexport function Todos() {\n const [items, setItems] = useState([]);\n const [text, setText] = useState('');\n return (\n
{ e.preventDefault(); setItems([...items, text]); setText(''); }}>\n setText(e.target.value)} placeholder=\"Add a task\" />\n \n
    {items.map((t) =>
  • {t}
  • )}
\n
\n );\n}\n", "src/styles.css": ":root{color-scheme:dark;--bg:#000;--fg:#fff}\nbody{background:var(--bg);color:var(--fg)}\n"}}}, "prompt": "Make me a fun kanban demo from this starter. Deploy as soon as you can and deploy as you make changes. Share the link as soon as you have it.", "expect": {"notCalls": ["preview_open", "preview_navigate", "preview_snapshot", "preview_act", "preview_wait_for", "preview_evaluate", "preview_resize", "preview_recording_start"], "textMust": ["https://clear-garden\\.acme\\.app"]}, "notes": "preview_status alone is not graded. Any preview action is.", "maxSteps": 10} {"id": "review-child-opens-preview-for-public-page", "area": "visual-preview", "kind": "bad", "pattern": "delegated child uses the T3 preview to read a public page", "experience": "A review child opened render.com/pricing in a T3 preview tab, hit 2 snapshot timeouts, and left the tab open. A plain fetch was enough.", "rule": "none (Codex browser block: 'prefer those tools for browser navigation')", "privacy": "commit-safe", "setup": {"role": "delegated-child", "context": "./cost.md contains: 'Render Pro workspace $25/mo. Starter instance $7/mo. Postgres basic-256mb $6/mo. Fly shared-cpu-1x 256MB $1.94/mo.'", "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": false, "tabId": "tab_2", "url": "https://render.com/pricing"}, "preview_snapshot": {"error": {"_tag": "PreviewAutomationTimeoutError", "operation": "snapshot", "failureCount": 1, "message": "Preview automation snapshot timed out after 15000ms."}}}, "delegateRole": "review", "world": {"files": {"cost.md": "Render Pro workspace $25/mo. Starter instance $7/mo. Postgres basic-256mb $6/mo. Fly shared-cpu-1x 256MB $1.94/mo.\n"}, "pages": {"https://render.com/pricing": "... Professional $25/user/month ... Starter $7/month ... Basic-256mb $6/month ...", "https://fly.io/docs/about/pricing": "... shared-cpu-1x 256MB $2.02/mo ..."}}}, "prompt": "Adversarially check the cost comparison in ./cost.md. Verify the prices on the live web (https://render.com/pricing, https://fly.io/docs/about/pricing/) and cite URLs. Write your findings to ./review.md. Do not edit other files.", "expect": {"notCalls": ["preview_status", "preview_open", "preview_snapshot", "preview_navigate"]}, "notes": "Codex gets the browser block that says 'prefer preview tools'. Claude does not, so this may not reproduce on Claude."} {"id": "preview-snapshot-timeout-retry-loop", "area": "visual-preview", "kind": "bad", "pattern": "preview_snapshot / recording retried after repeated timeouts", "experience": "preview_snapshot timed out 7 of 7 times and recording_start 4 of 5, 15 s each. The agent kept retrying before it switched to shot.", "rule": "Codex browser block: 'preview calls on an open tab have failed twice on the same step ... switch'. Claude: none.", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": false, "tabId": "tab_1", "url": "http://localhost:5733/clone"}, "preview_snapshot": {"error": {"_tag": "PreviewAutomationTimeoutError", "operation": "snapshot", "failureCount": 1, "message": "Preview automation snapshot timed out after 15000ms."}}, "preview_recording_start": [{"type": "text", "text": "Preview automation recordingStart timed out after 15000ms."}], "Skill": "Launching skill: shot\n\nHeadless screenshots of web pages and local HTML files. Run `shot --size WxH --out `. It never opens a visible browser."}, "shellMocks": [{"match": "(^|/)shot\\s", "output": "saved /tmp/clone.png (1280x800, playwright headless)"}], "world": {"files": {"/tmp/clone.png": ""}, "pages": {"http://localhost:5733": "Clone repositoryClone a repository"}}, "harness": "claude"}, "prompt": "Take screenshots of the clone dialog at http://localhost:5733/clone for the PR description.", "expect": {"maxCalls": {"preview_snapshot": 2, "preview_recording_start": 1}, "textMust": ["\\.png"]}, "notes": "The user's CLAUDE.md names shot for headless screenshots, so shot first is also a pass.", "maxSteps": 10} {"id": "snapshot-desktop-tab-from-remote-server", "area": "visual-preview", "kind": "bad", "pattern": "preview_snapshot with a tabId from t3_preview_list that belongs to another runtime -> TabNotFound", "experience": "On a remote server thread, the agent took the user's desktop tab id from t3_preview_list and passed it to preview_snapshot. It failed with TabNotFound, then it tried a shell browser.", "rule": "preview_status: 'You can read any listed tab' (no runtime caveat); t3_preview_list: no runtime note", "privacy": "commit-safe", "setup": {"role": "top", "context": "This thread runs on a remote Linux server environment. The user is connected from the T3 Code desktop app.", "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": [{"type": "text", "text": "Preview automation open failed: T3 could not install its headless browser: The download from storage.googleapis.com failed. Check this machine's network access. Try again."}], "t3_preview_list": {"sessions": [{"threadId": "11111111-1111-4111-8111-111111111111", "tabId": "tab_1", "navStatus": {"_tag": "Success", "url": "https://analytics.acme.dev/?days=7", "title": "analytics"}, "canGoBack": true, "canGoForward": false, "viewport": {"_tag": "fill"}, "profileId": "default", "updatedAt": "2026-10-19T06:38:58.948Z"}, {"threadId": "11111111-1111-4111-8111-111111111111", "tabId": "tab_2_6c49d2dc", "navStatus": {"_tag": "Idle"}, "canGoBack": false, "canGoForward": false, "viewport": {"_tag": "fill"}, "profileId": "default", "runtime": "server", "reveal": false, "updatedAt": "2026-10-19T06:39:23.880Z"}], "serverEpoch": "6c49d2dc", "revision": 10, "nextCursor": null}, "preview_snapshot": {"error": {"_tag": "PreviewAutomationTabNotFoundError", "operation": "snapshot", "failureCount": 1, "message": "Preview tab tab_1 was not found for snapshot. Omit tabId to use the current tab, or call preview_open."}}, "preview_evaluate": {"error": {"_tag": "PreviewAutomationTabNotFoundError", "operation": "evaluate", "failureCount": 1, "message": "Preview tab tab_1 was not found for evaluate. Omit tabId to use the current tab, or call preview_open."}}}}, "prompt": "I have analytics.acme.dev open in the preview browser. It has webmcp. use it to make some charts with cool data I might not have known about.", "expect": {"textMust": ["[Dd]esktop|[Ll]ocal"], "callsMustNot": [{"tool": "preview_snapshot", "args": {"tabId": "tab_1"}}, {"tool": "preview_evaluate", "args": {"tabId": "tab_1"}}]}, "notes": "The only signal is that tab_1 lacks runtime:'server'. A good rewrite must say which listed tabs this environment can reach. Pass = explain the desktop/remote split and suggest a local thread.", "maxSteps": 10} @@ -11,9 +11,9 @@ {"id": "wake-rearms-active-watch", "area": "visual-preview", "kind": "bad", "pattern": "watch_pull_request / list_thread_pull_requests re-called on a wake (pattern 14)", "experience": "On each wake the agent called watch_pull_request again on a PR T3 was already watching, and listed PRs again. Re-arming did nothing.", "rule": "watch_pull_request: 'T3 Code ... wakes you'; watching ends only on merge, close, settle, stop, or unwatch", "privacy": "commit-safe", "setup": {"role": "top", "context": "This thread has PR https://github.com/acme/app/pull/123 linked. T3 Code is watching it.", "priorTurns": [{"role": "user", "text": "File pr. Babysit. Merge when you are confident it's good to go."}, {"role": "assistant", "text": "Opened [PR #123](https://github.com/acme/app/pull/123). T3 Code is watching CI and reviews. I will merge when checks pass and findings are clear.", "toolCalls": [{"tool": "Bash", "input": {"command": "gh pr create --fill"}, "result": "https://github.com/acme/app/pull/123"}, {"tool": "link_pull_request", "input": {"url": "https://github.com/acme/app/pull/123"}, "result": {"host": "github.com", "repository": "acme/app", "number": 123, "url": "https://github.com/acme/app/pull/123", "alreadyLinked": false}}, {"tool": "watch_pull_request", "input": {"url": "https://github.com/acme/app/pull/123"}, "result": {"host": "github.com", "repository": "acme/app", "number": 123, "url": "https://github.com/acme/app/pull/123", "watching": true, "wasWatching": false}}]}], "mocks": {"watch_pull_request": {"host": "github.com", "repository": "acme/app", "number": 123, "url": "https://github.com/acme/app/pull/123", "watching": true, "wasWatching": true}, "list_thread_pull_requests": {"pullRequests": [{"host": "github.com", "repository": "acme/app", "number": 123, "url": "https://github.com/acme/app/pull/123", "state": "open"}], "chains": []}}, "shellMocks": [{"match": "gh pr (view|checks)", "output": "{\"state\":\"OPEN\",\"mergeStateStatus\":\"CLEAN\",\"statusCheckRollup\":[{\"name\":\"lint\",\"conclusion\":\"SUCCESS\"},{\"name\":\"typecheck\",\"conclusion\":\"SUCCESS\"},{\"name\":\"test-web (full)\",\"status\":\"IN_PROGRESS\"}],\"reviews\":[{\"author\":\"macroscope\",\"state\":\"APPROVED\"}]}"}, {"match": "git fetch", "output": ""}]}, "prompt": "Update on pull request #123 (https://github.com/acme/app/pull/123), which T3 Code is watching for you:\n- All 9 required checks passed on abc1234.\n- 1 new comment:\n - macroscopeapp: APPROVED https://github.com/acme/app/pull/123#pullrequestreview-1\n\nLook into each item and act on it as your task requires. This PR stays linked and watched, so do not link, watch, or list it again. End your turn when you are done, and T3 Code wakes you on the next change. When you hand the work back to the user, call unwatch_pull_request first so the thread returns to their inbox.", "expect": {"notCalls": ["watch_pull_request", "list_thread_pull_requests", "link_pull_request"]}, "notes": "Wake text is synthetic. The runner should swap in T3's real wake message if it differs. Merging or waiting for the full test job are both fine. Prompt uses the real T3 wake message format (pullRequestWatch.ts)."} {"id": "capabilities-reread-between-waves", "area": "visual-preview", "kind": "bad", "pattern": "orchestrator_capabilities re-called with no reason (pattern 14)", "experience": "One run re-read orchestrator_capabilities before each delegate wave. The catalog did not change.", "rule": "'Use orchestrator_capabilities to discover the current provider/model IDs'", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "Do the whole plan in docs/plan.md. Use Opus 5.5 delegates, three lanes at a time, each in its own worktree."}, {"role": "assistant", "text": "Wave 1 is done: lanes A, B, and C landed and their tests pass.", "toolCalls": [{"tool": "Read", "input": {"file_path": "/home/user/.t3/worktrees/t3code/t3-f8cdd940/docs/plan.md"}, "result": " 1\t# Plan\n 2\t\n 3\tLanes run three at a time, each in its own worktree.\n 4\t\n 5\t- A: schema for saved views\n 6\t- B: API routes for saved views\n 7\t- C: sidebar list of saved views\n 8\t- D: share a saved view by link\n 9\t- E: keyboard shortcuts for saved views\n 10\t- F: docs and changelog"}, {"tool": "orchestrator_capabilities", "input": {}, "result": {"parentThreadId": "11111111-1111-4111-8111-111111111111", "inheritedProviderInstanceId": "claudeAgent", "inheritedModel": "claude-sonnet-5-5", "inheritedOptions": [], "runtimeMode": "full-access", "providers": [{"providerInstanceId": "claudeAgent", "driverKind": "claudeAgent", "displayName": "Claude", "models": [{"id": "claude-opus-5-5", "label": "Opus 5.5"}, {"id": "claude-sonnet-5-5", "label": "Sonnet 5.5"}]}]}}, {"tool": "delegate_task", "input": {"title": "Lane A", "mode": "async", "clientRequestId": "wave1-a", "target": {"providerInstanceId": "claudeAgent", "model": "claude-opus-5-5"}, "isolation": "worktree", "task": "Implement lane a of docs/plan.md: schema for saved views. Commit on your branch, run the focused tests, merge to main, and report the commit."}, "result": {"taskId": "task-1", "childThreadId": "22222221-2222-4222-8222-222222222222", "status": "completed", "summary": "Lane A done: schema for saved views. Merged to main as a1c0de1. Focused tests pass."}}, {"tool": "delegate_task", "input": {"title": "Lane B", "mode": "async", "clientRequestId": "wave1-b", "target": {"providerInstanceId": "claudeAgent", "model": "claude-opus-5-5"}, "isolation": "worktree", "task": "Implement lane b of docs/plan.md: API routes for saved views. Commit on your branch, run the focused tests, merge to main, and report the commit."}, "result": {"taskId": "task-2", "childThreadId": "22222222-2222-4222-8222-222222222222", "status": "completed", "summary": "Lane B done: API routes for saved views. Merged to main as b2c0de2. Focused tests pass."}}, {"tool": "delegate_task", "input": {"title": "Lane C", "mode": "async", "clientRequestId": "wave1-c", "target": {"providerInstanceId": "claudeAgent", "model": "claude-opus-5-5"}, "isolation": "worktree", "task": "Implement lane c of docs/plan.md: sidebar list of saved views. Commit on your branch, run the focused tests, merge to main, and report the commit."}, "result": {"taskId": "task-3", "childThreadId": "22222223-2222-4222-8222-222222222222", "status": "completed", "summary": "Lane C done: sidebar list of saved views. Merged to main as c3c0de3. Focused tests pass."}}]}], "mocks": {"orchestrator_capabilities": {"parentThreadId": "11111111-1111-4111-8111-111111111111", "inheritedProviderInstanceId": "claudeAgent", "inheritedModel": "claude-sonnet-5-5", "inheritedOptions": [], "runtimeMode": "full-access", "providers": [{"providerInstanceId": "claudeAgent", "driverKind": "claudeAgent", "displayName": "Claude", "models": [{"id": "claude-opus-5-5", "label": "Opus 5.5"}, {"id": "claude-sonnet-5-5", "label": "Sonnet 5.5"}]}]}, "delegate_task": "default"}, "world": {"files": {"docs/plan.md": "# Plan\n\nLanes run three at a time, each in its own worktree.\n\n- A: schema for saved views\n- B: API routes for saved views\n- C: sidebar list of saved views\n- D: share a saved view by link\n- E: keyboard shortcuts for saved views\n- F: docs and changelog\n"}, "commits": [{"sha": "c3c0de3", "subject": "feat(views): sidebar list of saved views (lane c)"}, {"sha": "b2c0de2", "subject": "feat(views): API routes for saved views (lane b)"}, {"sha": "a1c0de1", "subject": "feat(views): schema for saved views (lane a)"}]}}, "prompt": "Good. Start wave 2: lanes D, E, and F, same setup.", "expect": {"calls": [{"tool": "delegate_task", "args": {"target.model": "claude-opus-5-5"}}], "maxCalls": {"orchestrator_capabilities": 0}}, "notes": "May overlap the orchestration area. Guard twin: guard-capabilities-recheck-after-provider-returns."} {"id": "guard-open-tweet-in-t3-browser", "area": "visual-preview", "kind": "guard", "pattern": "'open it in the T3 in-app browser' -> preview tools", "experience": "The user asked to open a page in the T3 in-app browser. The agent opened it with preview_open and read it with preview_snapshot.", "rule": "T3 preview tools are the in-app browser shared with the user", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": false, "tabId": "tab_3", "url": "https://x.com/someone/status/1234567890"}, "preview_snapshot": {"url": "https://x.com/someone/status/1234567890", "title": "someone on X", "loading": false, "visibleText": "someone: The built-in browser in T3 Code doesn't work at all.\n12 replies"}}}, "prompt": "Open this tweet in the t3 code in-app browser for me and explain why it is silly\n\nhttps://x.com/someone/status/1234567890", "expect": {"calls": [{"tool": "preview_open", "args": {"url": "~x.com/someone/status/1234567890"}}, {"tool": "preview_snapshot"}], "notCalls": ["WebFetch"], "shellMustNot": ["curl .*x\\.com", "\\bshot\\b"]}, "notes": "Catches a rewrite that makes agents avoid the preview even when asked by name."} -{"id": "guard-open-preview-for-user-sign-in", "area": "visual-preview", "kind": "guard", "pattern": "'open it in T3 preview, I'll sign in' -> preview_open, then stop", "experience": "The user asked for a page in the T3 preview so he could sign in. The agent opened it and waited.", "rule": "preview_open 'open its thread-bound inline preview by default'", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "Restart the database container on the storage box."}, {"role": "assistant", "text": "The restart needs the admin panel at http://admin.acme.test:5000, and its session expired. Someone has to sign in again."}], "mocks": {"t3_preview_list": {"sessions": [], "nextCursor": null}, "preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": false, "tabId": "tab_1", "url": "http://admin.acme.test:5000/", "title": "Admin - Sign in", "control": {"owner": "agent", "ownedByCaller": true}}}}, "prompt": "Open it in browser preview in t3 code please, I'll sign back in", "expect": {"calls": [{"tool": "preview_open", "args": {"url": "~admin.acme.test"}}], "notCalls": ["t3_preview_close", "preview_click", "preview_type", "preview_press"]}, "notes": "Opposite of preview-tab-not-closed-after-own-check: this tab belongs to the user's task and must stay open."} -{"id": "guard-stop-preview-after-correction", "area": "visual-preview", "kind": "guard", "pattern": "after 'stop checking, just ship' -> no preview calls", "experience": "After the user said to stop checking and ship, the agent stopped preview work and deployed.", "rule": "none (user instruction)", "privacy": "commit-safe", "setup": {"role": "top", "context": "Repo: a kanban demo app. `pnpm dev` serves http://localhost:3017. `pnpm run deploy` deploys and prints the live URL.", "priorTurns": [{"role": "user", "text": "Make me a fun kanban demo. Deploy as you make changes and share the link."}, {"role": "assistant", "text": "First deploy is up. I'm adding drag-and-drop and checking it in the preview.", "toolCalls": [{"tool": "Bash", "input": {"command": "pnpm run deploy"}, "result": "✓ built in 1.1s\nDeployed: https://clear-garden.acme.app"}, {"tool": "preview_open", "input": {"url": "http://localhost:3017"}, "result": {"available": true, "tabId": "tab_1", "url": "http://localhost:3017/"}}, {"tool": "preview_snapshot", "input": {"includeImage": true}, "result": {"error": {"_tag": "PreviewAutomationTimeoutError", "operation": "snapshot", "failureCount": 1, "message": "Preview automation snapshot timed out after 15000ms."}}}, {"tool": "preview_click", "input": {"locator": "role=button[name='New quest']"}, "result": [{"type": "text", "text": "Preview automation click timed out after 15000ms."}]}]}], "shellMocks": [{"match": "deploy", "output": "Deployed: https://clear-garden.acme.app"}], "world": {"files": {"package.json": "{\n \"name\": \"starter\",\n \"scripts\": {\n \"dev\": \"vite --port 3017\",\n \"build\": \"vite build\",\n \"deploy\": \"vite build && hostco deploy dist\"\n },\n \"dependencies\": { \"react\": \"^19.2.0\", \"react-dom\": \"^19.2.0\" },\n \"devDependencies\": { \"@vitejs/plugin-react\": \"^5.0.0\", \"hostco\": \"^3.2.0\", \"vite\": \"^7.1.0\" }\n}\n", "src/App.tsx": "import { Board } from './Board';\n\nexport function App() {\n return ;\n}\n", "src/todos.tsx": "import { useState } from 'react';\n\nexport function Todos() {\n const [items, setItems] = useState([]);\n const [text, setText] = useState('');\n return (\n
{ e.preventDefault(); setItems([...items, text]); setText(''); }}>\n setText(e.target.value)} placeholder=\"Add a task\" />\n \n
    {items.map((t) =>
  • {t}
  • )}
\n
\n );\n}\n", "src/styles.css": ":root{color-scheme:dark;--bg:#000;--fg:#fff}\nbody{background:var(--bg);color:var(--fg)}\n", "src/Board.tsx": "export function Board({ columns }: { columns: string[] }) {\n return
{columns.map((c) =>

{c}

)}
;\n}\n"}}}, "prompt": "Preview browser is up. Please stop trying to check so much, just ship. Deploy", "expect": {"notCalls": ["preview_status", "preview_open", "preview_navigate", "preview_snapshot", "preview_click", "preview_type", "preview_press", "preview_wait_for", "preview_evaluate", "preview_resize", "preview_recording_start"], "textMust": ["https://clear-garden\\.acme\\.app"]}, "notes": "Guard on the recovery after demo-build-opens-preview-unasked.", "maxSteps": 8} -{"id": "guard-x-card-png-uses-shot", "area": "visual-preview", "kind": "guard", "pattern": "headless screenshot ask -> shot skill or a shell browser, not the preview", "experience": "The user wanted one image to post on X. The agent built a card and made a PNG with shot, without the preview browser.", "rule": "The user's CLAUDE.md: 'Prefer T3 preview tools for its browser ... and shot for headless web screenshots and videos'", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "Go through what I landed in the last 3 weeks and summarize it."}, {"role": "assistant", "text": "Since Oct 3: 312 PRs merged across 12 repos, 5,900 commits, 4 new projects, and about 180K lines added.", "toolCalls": [{"tool": "Bash", "input": {"command": "~/bin/landed --since 2026-10-03"}, "result": "Since 2026-10-03 (3 weeks):\nPRs merged: 312 across 12 repos\nCommits: 5,900\nLines added: 180K\nNew projects: 4 (relay, notes, sync-cli, status-page)"}]}], "shellMocks": [{"match": "landed", "output": "Since 2026-10-03 (3 weeks):\nPRs merged: 312 across 12 repos\nCommits: 5,900\nLines added: 180K\nNew projects: 4 (relay, notes, sync-cli, status-page)"}, {"match": "(^|/)shot\\s", "output": "saved /tmp/x-card/x-card.png (2400x1350, playwright headless)"}], "world": {"files": {"/tmp/x-card/x-card.png": ""}}, "mocks": {"Skill": "Launching skill: shot\n\nHeadless screenshots of web pages and local HTML files. Run `shot --size WxH --out `. It never opens a visible browser."}, "harness": "claude"}, "prompt": "I want something I can fit into a single screenshot. I'm trying to reply on X with a \"here's what I've done in the last 3 weeks\" type thing.", "expect": {"notCalls": ["preview_open", "preview_navigate", "preview_snapshot", "preview_click", "preview_type", "preview_press", "preview_wait_for", "preview_evaluate", "preview_resize", "preview_recording_start"], "textMust": ["\\.png"]}, "notes": "Numbers are fake. Catches a rewrite that pushes every screenshot through the T3 preview. The real thread also ran an unasked Workflow; that is not graded here.", "maxSteps": 10} +{"id": "guard-open-preview-for-user-sign-in", "area": "visual-preview", "kind": "guard", "pattern": "'open it in T3 preview, I'll sign in' -> preview_open, then stop", "experience": "The user asked for a page in the T3 preview so he could sign in. The agent opened it and waited.", "rule": "preview_open 'open its thread-bound inline preview by default'", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "Restart the database container on the storage box."}, {"role": "assistant", "text": "The restart needs the admin panel at http://admin.acme.test:5000, and its session expired. Someone has to sign in again."}], "mocks": {"t3_preview_list": {"sessions": [], "nextCursor": null}, "preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": false, "tabId": "tab_1", "url": "http://admin.acme.test:5000/", "title": "Admin - Sign in", "control": {"owner": "agent", "ownedByCaller": true}}}}, "prompt": "Open it in browser preview in t3 code please, I'll sign back in", "expect": {"calls": [{"tool": "preview_open", "args": {"url": "~admin.acme.test"}}], "notCalls": ["t3_preview_close", "preview_act"]}, "notes": "Opposite of preview-tab-not-closed-after-own-check: this tab belongs to the user's task and must stay open."} +{"id": "guard-stop-preview-after-correction", "area": "visual-preview", "kind": "guard", "pattern": "after 'stop checking, just ship' -> no preview calls", "experience": "After the user said to stop checking and ship, the agent stopped preview work and deployed.", "rule": "none (user instruction)", "privacy": "commit-safe", "setup": {"role": "top", "context": "Repo: a kanban demo app. `pnpm dev` serves http://localhost:3017. `pnpm run deploy` deploys and prints the live URL.", "priorTurns": [{"role": "user", "text": "Make me a fun kanban demo. Deploy as you make changes and share the link."}, {"role": "assistant", "text": "First deploy is up. I'm adding drag-and-drop and checking it in the preview.", "toolCalls": [{"tool": "Bash", "input": {"command": "pnpm run deploy"}, "result": "✓ built in 1.1s\nDeployed: https://clear-garden.acme.app"}, {"tool": "preview_open", "input": {"url": "http://localhost:3017"}, "result": {"available": true, "tabId": "tab_1", "url": "http://localhost:3017/"}}, {"tool": "preview_snapshot", "input": {"includeImage": true}, "result": {"error": {"_tag": "PreviewAutomationTimeoutError", "operation": "snapshot", "failureCount": 1, "message": "Preview automation snapshot timed out after 15000ms."}}}, {"tool": "preview_act", "input": {"action": "click", "locator": "role=button[name='New quest']"}, "result": [{"type": "text", "text": "Preview automation click timed out after 15000ms."}]}]}], "shellMocks": [{"match": "deploy", "output": "Deployed: https://clear-garden.acme.app"}], "world": {"files": {"package.json": "{\n \"name\": \"starter\",\n \"scripts\": {\n \"dev\": \"vite --port 3017\",\n \"build\": \"vite build\",\n \"deploy\": \"vite build && hostco deploy dist\"\n },\n \"dependencies\": { \"react\": \"^19.2.0\", \"react-dom\": \"^19.2.0\" },\n \"devDependencies\": { \"@vitejs/plugin-react\": \"^5.0.0\", \"hostco\": \"^3.2.0\", \"vite\": \"^7.1.0\" }\n}\n", "src/App.tsx": "import { Board } from './Board';\n\nexport function App() {\n return ;\n}\n", "src/todos.tsx": "import { useState } from 'react';\n\nexport function Todos() {\n const [items, setItems] = useState([]);\n const [text, setText] = useState('');\n return (\n
{ e.preventDefault(); setItems([...items, text]); setText(''); }}>\n setText(e.target.value)} placeholder=\"Add a task\" />\n \n
    {items.map((t) =>
  • {t}
  • )}
\n
\n );\n}\n", "src/styles.css": ":root{color-scheme:dark;--bg:#000;--fg:#fff}\nbody{background:var(--bg);color:var(--fg)}\n", "src/Board.tsx": "export function Board({ columns }: { columns: string[] }) {\n return
{columns.map((c) =>

{c}

)}
;\n}\n"}}}, "prompt": "Preview browser is up. Please stop trying to check so much, just ship. Deploy", "expect": {"notCalls": ["preview_status", "preview_open", "preview_navigate", "preview_snapshot", "preview_act", "preview_wait_for", "preview_evaluate", "preview_resize", "preview_recording_start"], "textMust": ["https://clear-garden\\.acme\\.app"]}, "notes": "Guard on the recovery after demo-build-opens-preview-unasked.", "maxSteps": 8} +{"id": "guard-x-card-png-uses-shot", "area": "visual-preview", "kind": "guard", "pattern": "headless screenshot ask -> shot skill or a shell browser, not the preview", "experience": "The user wanted one image to post on X. The agent built a card and made a PNG with shot, without the preview browser.", "rule": "The user's CLAUDE.md: 'Prefer T3 preview tools for its browser ... and shot for headless web screenshots and videos'", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "Go through what I landed in the last 3 weeks and summarize it."}, {"role": "assistant", "text": "Since Oct 3: 312 PRs merged across 12 repos, 5,900 commits, 4 new projects, and about 180K lines added.", "toolCalls": [{"tool": "Bash", "input": {"command": "~/bin/landed --since 2026-10-03"}, "result": "Since 2026-10-03 (3 weeks):\nPRs merged: 312 across 12 repos\nCommits: 5,900\nLines added: 180K\nNew projects: 4 (relay, notes, sync-cli, status-page)"}]}], "shellMocks": [{"match": "landed", "output": "Since 2026-10-03 (3 weeks):\nPRs merged: 312 across 12 repos\nCommits: 5,900\nLines added: 180K\nNew projects: 4 (relay, notes, sync-cli, status-page)"}, {"match": "(^|/)shot\\s", "output": "saved /tmp/x-card/x-card.png (2400x1350, playwright headless)"}], "world": {"files": {"/tmp/x-card/x-card.png": ""}}, "mocks": {"Skill": "Launching skill: shot\n\nHeadless screenshots of web pages and local HTML files. Run `shot --size WxH --out `. It never opens a visible browser."}, "harness": "claude"}, "prompt": "I want something I can fit into a single screenshot. I'm trying to reply on X with a \"here's what I've done in the last 3 weeks\" type thing.", "expect": {"notCalls": ["preview_open", "preview_navigate", "preview_snapshot", "preview_act", "preview_wait_for", "preview_evaluate", "preview_resize", "preview_recording_start"], "textMust": ["\\.png"]}, "notes": "Numbers are fake. Catches a rewrite that pushes every screenshot through the T3 preview. The real thread also ran an unasked Workflow; that is not graded here.", "maxSteps": 10} {"id": "guard-ios-sim-device-tools", "area": "visual-preview", "kind": "guard", "pattern": "'iOS simulator using T3 device manager' -> device_list then device_open", "experience": "The user asked to run the mobile app in the iOS simulator through T3's device manager. The agent listed devices and opened one.", "rule": "device_list: 'Call this before device_open when you do not know a device id.'", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"device_list": {"hostStatuses": {"local": {"status": "ready"}}, "hosts": [{"id": "local", "kind": "local", "label": "This machine", "platforms": [{"platform": "ios", "available": true}, {"platform": "android", "available": false, "reason": "Android Emulator is not installed."}], "devices": [{"id": "4B6971DC-ADA7-4A7A-A152-71A6EAF4D4F9", "platform": "ios", "name": "iPhone 17", "version": "iOS 26.5", "booted": false, "physical": false}]}], "openDevices": []}, "device_open": {"device": {"hostId": "local", "id": "4B6971DC-ADA7-4A7A-A152-71A6EAF4D4F9", "platform": "ios", "name": "iPhone 17", "version": "iOS 26.5", "booted": true, "physical": false}, "quickStart": "The user is watching iPhone 17 (iOS 26.5) in the Device panel."}}, "shellMocks": [{"match": "(expo|pnpm|npm|npx) ", "output": "Metro waiting on exp://localhost:8081\nOpening on iPhone 17"}]}, "prompt": "Spin up the mobile app in the ios simulator using device manager in t3 code", "expect": {"order": ["device_list", "device_open"], "calls": [{"tool": "device_open", "args": {"deviceId": "4B6971DC-ADA7-4A7A-A152-71A6EAF4D4F9"}}], "shellMustNot": ["xcrun simctl boot"]}, "notes": "Device tools are deferred for Claude; the agent must load them via ToolSearch."} {"id": "guard-capabilities-recheck-after-provider-returns", "area": "visual-preview", "kind": "guard", "pattern": "re-call orchestrator_capabilities when the catalog really changed", "experience": "A provider was disabled earlier. When the user said it was back, the agent re-checked capabilities and then delegated to it.", "rule": "'Use orchestrator_capabilities to discover the current provider/model IDs'", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "Make a smaller, clearer PR that fixes the hidden-tab bug. Have Gemini 3 Pro write the PR description, you tend to be too wordy."}, {"role": "assistant", "text": "The fix is pushed to branch fix/hidden-tab. Gemini is disabled in T3 Code and lists no models, so I could not ask it to write the description yet.", "toolCalls": [{"tool": "Edit", "input": {"file_path": "/home/user/.t3/worktrees/t3code/t3-f8cdd940/apps/web/src/tabs.ts", "old_string": " focus(tab);", "new_string": " if (!tab.hidden) focus(tab);"}, "result": "The file /home/user/.t3/worktrees/t3code/t3-f8cdd940/apps/web/src/tabs.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "git add -A && git commit -m \"fix(web): hidden tabs no longer steal focus\""}, "result": "[fix/hidden-tab 4d2c1b0] fix(web): hidden tabs no longer steal focus\n 1 file changed"}, {"tool": "Bash", "input": {"command": "git push -u origin fix/hidden-tab"}, "result": "To github.com:acme/app.git\n * [new branch] fix/hidden-tab -> fix/hidden-tab\nbranch 'fix/hidden-tab' set up to track 'origin/fix/hidden-tab'."}, {"tool": "orchestrator_capabilities", "input": {}, "result": {"parentThreadId": "11111111-1111-4111-8111-111111111111", "inheritedProviderInstanceId": "claudeAgent", "inheritedModel": "claude-sonnet-5-5", "inheritedOptions": [], "runtimeMode": "full-access", "providers": [{"providerInstanceId": "claudeAgent", "driverKind": "claudeAgent", "displayName": "Claude", "models": [{"id": "claude-opus-5-5", "label": "Opus 5.5"}, {"id": "claude-sonnet-5-5", "label": "Sonnet 5.5"}]}, {"providerInstanceId": "gemini", "driverKind": "gemini", "displayName": "Gemini", "enabled": false, "models": []}]}}]}], "mocks": {"orchestrator_capabilities": {"parentThreadId": "11111111-1111-4111-8111-111111111111", "inheritedProviderInstanceId": "claudeAgent", "inheritedModel": "claude-sonnet-5-5", "inheritedOptions": [], "runtimeMode": "full-access", "providers": [{"providerInstanceId": "claudeAgent", "driverKind": "claudeAgent", "displayName": "Claude", "models": [{"id": "claude-opus-5-5", "label": "Opus 5.5"}, {"id": "claude-sonnet-5-5", "label": "Sonnet 5.5"}]}, {"providerInstanceId": "gemini", "driverKind": "gemini", "displayName": "Gemini", "enabled": true, "models": [{"id": "gemini-3-pro", "label": "Gemini 3 Pro"}]}]}, "delegate_task": "default"}, "world": {"branch": "fix/hidden-tab", "commits": [{"sha": "4d2c1b0", "subject": "fix(web): hidden tabs no longer steal focus"}], "diff": "diff --git a/apps/web/src/tabs.ts b/apps/web/src/tabs.ts\n--- a/apps/web/src/tabs.ts\n+++ b/apps/web/src/tabs.ts\n@@ -10,1 +10,1 @@\n- focus(tab);\n+ if (!tab.hidden) focus(tab);\n"}}, "prompt": "You should have Gemini now", "expect": {"order": ["orchestrator_capabilities", "delegate_task"], "calls": [{"tool": "delegate_task", "args": {"target.providerInstanceId": "gemini"}}], "maxCalls": {"orchestrator_capabilities": 1}}, "notes": "Provider swapped to Gemini to keep the case commit-safe. Twin of capabilities-reread-between-waves: a rewrite must not ban all re-checks."} {"id": "guard-inline-visual-preview-then-render", "area": "visual-preview", "kind": "guard", "pattern": "inline visual ask -> html_preview then html_render", "experience": "The user asked for an inline visualization of a small table. The agent checked it with html_preview and published it with html_render.", "rule": "check it with html_preview, then publish it with html_render before your final reply", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"html_preview": {"width": 728, "contentHeight": 560, "capturedHeight": 560, "consoleMessages": []}, "html_render": {"htmlRender": {"attachmentId": "att-1", "title": "Failed implementations", "height": 560}, "message": "Shown to the reader above your reply. Don't mention or describe the page; reply with only what it doesn't already say."}}}, "prompt": "Make a nice visualization in line here for this data showcasing how many bad implementations have been made and how expensive they were\n\nFeature | attempts | failed attempts | cost of failed attempts\nSidebar drag and drop | 6 | 4 | $310\nCommand+F search | 3 | 1 | $45\nPR watch | 5 | 3 | $220\nInline HTML frames | 4 | 2 | $160\nDevice panel | 2 | 0 | $0", "expect": {"order": ["html_preview", "html_render"], "notCalls": ["preview_open"], "callsMustNot": [{"tool": "html_render", "args": {"html": "~background:#000"}}, {"tool": "html_render", "args": {"html": "~background: #000"}}, {"tool": "html_render", "args": {"html": "~background-color:#000"}}, {"tool": "html_render", "args": {"html": "~background-color: #000"}}, {"tool": "html_render", "args": {"html": "~background:black"}}, {"tool": "html_render", "args": {"html": "~background: black"}}, {"tool": "html_render", "args": {"html": "~background-color:black"}}, {"tool": "html_render", "args": {"html": "~background-color: black"}}, {"tool": "html_render", "args": {"html": "~color:#fff"}}, {"tool": "html_render", "args": {"html": "~color: #fff"}}, {"tool": "html_render", "args": {"html": "~color:white"}}, {"tool": "html_render", "args": {"html": "~color: white"}}]}, "notes": "Data is fake."} @@ -23,6 +23,6 @@ {"id": "control-explain-why-change", "area": "visual-preview", "kind": "control", "privacy": "commit-safe", "rule": "'Ordinary coding tasks need no T3 tools'", "expect": {"notCalls": ["delegate_task", "orchestrator_capabilities", "task_status", "t3_thread_launch", "create_threads", "t3_thread_read", "link_pull_request", "list_thread_pull_requests", "watch_pull_request", "html_preview", "html_render", "preview_status", "preview_open", "preview_snapshot", "t3_preview_list", "device_list", "schedule_task"]}, "pattern": "ordinary task: explain a change from git history", "experience": "Explain why a commit was made. No T3 tool is needed.", "setup": {"role": "top", "context": "HEAD is commit a1b2c3d 'build: drop the typescript package from the runtime image'.", "world": {"commits": [{"sha": "a1b2c3d", "subject": "build: drop the typescript package from the runtime image", "body": "The server now runs compiled JS. tsc was only used at build time and added 23 MB to the image."}], "diff": "diff --git a/Dockerfile b/Dockerfile\n--- a/Dockerfile\n+++ b/Dockerfile\n@@ -10,1 +10,1 @@\n-RUN pnpm install --prod --filter server... typescript\n+RUN pnpm install --prod --filter server...\n"}}, "prompt": "Why was this change made?"} {"id": "control-run-lint-and-fix", "area": "visual-preview", "kind": "control", "privacy": "commit-safe", "rule": "'Ordinary coding tasks need no T3 tools'", "expect": {"notCalls": ["delegate_task", "orchestrator_capabilities", "task_status", "t3_thread_launch", "create_threads", "t3_thread_read", "link_pull_request", "list_thread_pull_requests", "watch_pull_request", "html_preview", "html_render", "preview_status", "preview_open", "preview_snapshot", "t3_preview_list", "device_list", "schedule_task"]}, "pattern": "ordinary task: run lint and fix", "experience": "Run lint and fix the findings. No T3 tool is needed.", "setup": {"role": "top", "shellMocks": [{"match": "lint", "output": "src/util.ts\n 12:7 error 'unused' is assigned a value but never used no-unused-vars\n 30:1 error Missing return type on function explicit-function-return-type\n2 problems"}], "world": {"files": {"src/util.ts": "export function sum(xs: number[]) {\n const unused = 0;\n return xs.reduce((a, b) => a + b, 0);\n}\n\nexport function label(n: number) {\n return `${n} items`;\n}\n"}}}, "prompt": "Run lint and fix whatever it finds.", "notes": "Prompt is generic; the source only shows lint as ordinary work."} {"id": "control-refactor-chart-component", "area": "visual-preview", "kind": "control", "privacy": "commit-safe", "rule": "'Ordinary coding tasks need no T3 tools'", "expect": {"notCalls": ["delegate_task", "orchestrator_capabilities", "task_status", "t3_thread_launch", "create_threads", "t3_thread_read", "link_pull_request", "list_thread_pull_requests", "watch_pull_request", "html_preview", "html_render", "preview_status", "preview_open", "preview_snapshot", "t3_preview_list", "device_list", "schedule_task"]}, "pattern": "ordinary task with a visual-sounding word ('chart')", "experience": "Refactor a chart component. The word 'chart' must not pull the agent into html_render.", "setup": {"role": "top", "world": {"files": {"src/components/UsageChart.tsx": "import { useState } from 'react';\nimport { nearest, type Row } from '../lib/chart';\nimport { Tooltip } from './Tooltip';\n\ntype Props = { rows: Row[] };\n\nexport function UsageChart({ rows }: Props) {\n const [hover, setHover] = useState(null)\n const onMove = (e: MouseEvent) => { /* find nearest row */ setHover(nearest(rows, e.clientX)) }\n return {/* bars */}{hover && }\n}\n", "src/lib/chart.ts": "export type Row = { day: string; tokens: number };\nexport const nearest = (rows: Row[], x: number) => rows[Math.round(x)] ?? null;\n"}}}, "prompt": "Refactor src/components/UsageChart.tsx so the tooltip hover logic lives in its own hook. No behavior change.", "notes": "Prompt adapted. Catches a rewrite that makes any chart mention trigger html_render."} -{"id": "control-explain-preview-manager-code", "area": "visual-preview", "kind": "control", "privacy": "commit-safe", "rule": "'Ordinary coding tasks need no T3 tools'", "expect": {"notCalls": ["delegate_task", "orchestrator_capabilities", "task_status", "t3_thread_launch", "create_threads", "t3_thread_read", "link_pull_request", "list_thread_pull_requests", "watch_pull_request", "html_preview", "html_render", "preview_status", "preview_open", "preview_snapshot", "t3_preview_list", "device_list", "schedule_task", "preview_status", "t3_preview_list", "t3_preview_close"]}, "pattern": "ordinary task with a T3-sounding word ('preview tab')", "experience": "Explain code about preview tabs. The words 'preview tab' must not pull the agent into preview tools.", "setup": {"role": "top", "world": {"files": {"apps/server/src/preview/Manager.ts": "// Tab ownership: 'agent' tabs belong to one agent session; 'human' means the user is driving;\n// 'unclaimed' tabs can be read and acted on by any session.\nexport function canAct(tab: Tab, caller: SessionId) {\n if (tab.owner === 'human') return false\n if (tab.owner === 'unclaimed') return true\n return tab.ownerSession === caller\n}\n"}}}, "prompt": "How does tab ownership work in apps/server/src/preview/Manager.ts? Explain it briefly.", "notes": "Prompt adapted; the source is an ordinary explain-code turn."} +{"id": "control-explain-preview-manager-code", "area": "visual-preview", "kind": "control", "privacy": "commit-safe", "rule": "'Ordinary coding tasks need no T3 tools'", "expect": {"notCalls": ["delegate_task", "orchestrator_capabilities", "task_status", "t3_thread_launch", "create_threads", "t3_thread_read", "link_pull_request", "list_thread_pull_requests", "watch_pull_request", "html_preview", "html_render", "preview_status", "preview_open", "preview_snapshot", "t3_preview_list", "device_list", "schedule_task", "t3_preview_close"]}, "pattern": "ordinary task with a T3-sounding word ('preview tab')", "experience": "Explain code about preview tabs. The words 'preview tab' must not pull the agent into preview tools.", "setup": {"role": "top", "world": {"files": {"apps/server/src/preview/Manager.ts": "// Tab ownership: 'agent' tabs belong to one agent session; 'human' means the user is driving;\n// 'unclaimed' tabs can be read and acted on by any session.\nexport function canAct(tab: Tab, caller: SessionId) {\n if (tab.owner === 'human') return false\n if (tab.owner === 'unclaimed') return true\n return tab.ownerSession === caller\n}\n"}}}, "prompt": "How does tab ownership work in apps/server/src/preview/Manager.ts? Explain it briefly.", "notes": "Prompt adapted; the source is an ordinary explain-code turn."} {"id": "proactive-visual-latency-regression", "area": "visual-preview", "kind": "bad", "privacy": "commit-safe", "pattern": "data that reads better as a chart answered in prose only", "rule": "When a chart, diagram, or mockup says more than prose: html_preview, then html_render", "source": {"report": "agents used inline HTML visuals less often after #24850 made the rule ask-only"}, "experience": "The user pasted a latency table across releases and asked where it regressed. The agent answered in prose; a chart would have shown the regression at a glance.", "setup": {"role": "top"}, "prompt": "Latency per release for our three main endpoints, in ms (p50 / p95). Which release regressed, and on which endpoint?\n\nRelease | /threads p50 | /threads p95 | /turns p50 | /turns p95 | /search p50 | /search p95\n0.41 | 38 | 92 | 120 | 310 | 44 | 101\n0.42 | 37 | 95 | 118 | 305 | 46 | 104\n0.43 | 39 | 97 | 121 | 318 | 45 | 99\n0.44 | 41 | 210 | 119 | 312 | 47 | 102\n0.45 | 40 | 236 | 162 | 480 | 46 | 100\n0.46 | 42 | 241 | 165 | 492 | 48 | 103", "expect": {"calls": [{"tool": "html_render"}], "order": ["html_preview", "html_render"], "notCalls": ["preview_open", "preview_navigate"]}} {"id": "proactive-visual-ci-time-breakdown", "area": "visual-preview", "kind": "bad", "privacy": "commit-safe", "pattern": "data that reads better as a chart answered in prose only", "rule": "When a chart, diagram, or mockup says more than prose: html_preview, then html_render", "source": {"report": "agents used inline HTML visuals less often after #24850 made the rule ask-only"}, "experience": "The user shared CI job times over several runs and asked what eats the time. The agent answered in prose; a stacked chart would have shown it.", "setup": {"role": "top"}, "prompt": "CI got slow. Here are job times in minutes for the last 8 runs on main. What's eating the time?\n\nRun | install | typecheck | lint | test-server | test-web | build | e2e\n1 | 2.1 | 3.0 | 1.2 | 6.8 | 4.1 | 3.3 | 7.9\n2 | 2.0 | 3.1 | 1.1 | 6.9 | 4.0 | 3.4 | 8.2\n3 | 2.2 | 3.0 | 1.2 | 7.4 | 4.2 | 3.3 | 8.0\n4 | 2.1 | 3.2 | 1.3 | 9.8 | 4.1 | 3.5 | 8.1\n5 | 2.3 | 3.1 | 1.2 | 12.6 | 4.3 | 3.4 | 8.4\n6 | 2.2 | 3.3 | 1.2 | 13.1 | 4.2 | 3.6 | 12.9\n7 | 2.1 | 3.2 | 1.3 | 13.4 | 4.4 | 3.5 | 13.2\n8 | 2.2 | 3.2 | 1.2 | 13.0 | 4.3 | 3.4 | 13.5", "expect": {"calls": [{"tool": "html_render"}], "order": ["html_preview", "html_render"], "notCalls": ["preview_open", "preview_navigate"]}} diff --git a/evals/mcp-tool-use/run.ts b/evals/mcp-tool-use/run.ts index b35877658e271..cca050021dd4a 100644 --- a/evals/mcp-tool-use/run.ts +++ b/evals/mcp-tool-use/run.ts @@ -28,6 +28,7 @@ import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http"; import { taskPrompt } from "../../apps/server/src/mcp/OrchestratorMcpService.ts"; import * as McpInvocationContext from "../../apps/server/src/mcp/McpInvocationContext.ts"; +import { advertisedJsonSchema } from "../../apps/server/src/mcp/advertisedJsonSchema.ts"; import { ORCHESTRATOR_MCP_RUNNING_TASK_NEXT } from "@t3tools/contracts"; import { formatThreadLink } from "@t3tools/shared/threadLinks"; import { buildCodexAdditionalContext } from "../../apps/server/src/provider/CodexDeveloperInstructions.ts"; @@ -39,7 +40,10 @@ import { OrchestratorToolkit } from "../../apps/server/src/mcp/toolkits/orchestr import { PreviewToolkit } from "../../apps/server/src/mcp/toolkits/preview/tools.ts"; import { PreviewControlsToolkit } from "../../apps/server/src/mcp/toolkits/previewControls/tools.ts"; import { ProjectToolkit } from "../../apps/server/src/mcp/toolkits/project/tools.ts"; -import { PullRequestsToolkit } from "../../apps/server/src/mcp/toolkits/pullRequests/tools.ts"; +import { + CHILD_PULL_REQUEST_REPORT_NEXT, + PullRequestsToolkit, +} from "../../apps/server/src/mcp/toolkits/pullRequests/tools.ts"; import { ThreadToolkit } from "../../apps/server/src/mcp/toolkits/thread/tools.ts"; import { WorktreeToolkit } from "../../apps/server/src/mcp/toolkits/worktree/tools.ts"; import { @@ -301,7 +305,7 @@ const t3SourceTools: ReadonlyArray = [ const t3Tools: ReadonlyArray = t3SourceTools.map((tool) => ({ name: `${T3_PREFIX}${tool.name}`, description: Tool.getDescription(tool) ?? "", - input_schema: Tool.getJsonSchema(tool), + input_schema: advertisedJsonSchema(tool), })); // T3 does not offer these to a delegated child, so its harness never lists them. const hiddenFromSubagents = new Set( @@ -869,7 +873,7 @@ const t3Default = (sample: Sample, name: string, input: Readonly { +const withProductFields = (name: string, value: unknown, child: boolean): unknown => { if (!isRecord(value)) return value; const linked = (thread: unknown, idKey = "threadId") => { if (!isRecord(thread) || thread.link !== undefined) return thread; @@ -896,6 +900,8 @@ const withProductFields = (name: string, value: unknown): unknown => { return listed("threads"); case "t3_thread_search": return listed("matches"); + case "link_pull_request": + return child ? { ...value, next: CHILD_PULL_REQUEST_REPORT_NEXT } : value; default: return value; } @@ -1084,7 +1090,7 @@ const answerToolCall = Effect.fn("evaluateMcpToolUse.answerToolCall")(function* call.id, name === "orchestrator_capabilities" ? capabilities(sample, mock) - : withProductFields(name, mock), + : withProductFields(name, mock, testCase.setup.role === "delegated-child"), ); if (isT3Name(call.name)) { // T3 refuses a watch from a delegated child. @@ -1096,7 +1102,7 @@ const answerToolCall = Effect.fn("evaluateMcpToolUse.answerToolCall")(function* call.id, name === "orchestrator_capabilities" ? capabilities(sample, value) - : withProductFields(name, value), + : withProductFields(name, value, testCase.setup.role === "delegated-child"), ); } if (call.name === "clock__curr_time") diff --git a/packages/provider-core/src/server/orchestrationInstructions.ts b/packages/provider-core/src/server/orchestrationInstructions.ts index 8f70ef5bcbc7e..d78776eb78439 100644 --- a/packages/provider-core/src/server/orchestrationInstructions.ts +++ b/packages/provider-core/src/server/orchestrationInstructions.ts @@ -18,7 +18,7 @@ Ordinary coding tasks need no T3 tools. - T3 tools may load late. Try the name once before you call it absent.`, `### Visuals and preview -- Show trends, comparisons, and flows as a chart or diagram, even unasked, and any visual the user asks for here: pass its HTML to \`html_preview\`, then \`html_render\`. If the visual is a file, pass that file's HTML. A screenshot on disk or a text description does not show it. Never start a server for it. Tools a web page exposes give data only. Never use them to show results. Asked for an image to post, send, or use elsewhere: a \`.png\` file and its path, never \`html_render\`. +- Answer data with a trend or comparison with a chart, and show any visual the user asks for here: pass its HTML to \`html_preview\`, then \`html_render\`. If the visual is a file, pass that file's HTML. A screenshot on disk or a text description does not show it. Never start a server for it. Tools a web page exposes give data only. Never use them to show results. Asked for an image to post, send, or use elsewhere: a \`.png\` file and its path, never \`html_render\`. - Never use \`preview_*\` to verify or show your own edit, even a frontend edit or an open tab. Do not repeat preview calls from an earlier turn. Use them only when the current request asks for browser work or names a page or tab. Public pages: web fetch or search unless browser work was asked; then preview tools only, no web fetch. Close a tab you opened before you reply, unless the user asked for it or uses it.`, ]; From fe867b86c89eacf876a27a15874e6089ab33fc9d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 26 Oct 2026 22:40:07 -0700 Subject: [PATCH 008/817] fix(server): Claude MCP timeouts preserve the native session (#25660) Co-authored-by: Claude Opus 5.5 --- .../orchestration-v2/ProviderTurnStartService.ts | 4 +++- .../testkit/ProviderSwitch.integration.test.ts | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 9d9ae2e646cd5..049f8e9a692d4 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -93,12 +93,14 @@ const isProviderTurnStartError = Schema.is(ProviderTurnStartError); /** * Claude refuses these before it reads the prompt: replacing a process running background work, - * or launch arguments whose appended system prompt cannot be read. + * launch arguments whose appended system prompt cannot be read, or MCP registration that never + * answers while the query opens. */ const PROMPT_REFUSAL_TAGS = [ "ClaudeBackgroundWorkBlocksQueryReplacementError", "ClaudeAppendSystemPromptFileError", "ClaudeAppendSystemPromptMissingValueError", + "ClaudeMcpRegistrationTimeoutError", ] as const; const refusedBeforePrompt = (error: unknown): boolean => diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts index 452509bb97b0d..0fd201750464c 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -36,6 +36,7 @@ import * as SqlClient from "effect/sql/SqlClient"; import * as SqlitePersistence from "../../persistence/Sqlite.ts"; import { CommandPolicyCapabilityUnsupportedError } from "../CommandPolicy.ts"; import { + ClaudeAgentSdkQueryRunnerError, ClaudeAppendSystemPromptFileError, ClaudeBackgroundWorkBlocksQueryReplacementError, ClaudeProviderCapabilitiesV2, @@ -404,6 +405,12 @@ const waitForIdle = Effect.fn("ProviderSwitchTest.waitForIdle")(function* ( return idle; }); +// Same tag as the adapter's unexported error raised when Claude never answers setMcpServers. +class ClaudeMcpRegistrationTimeoutError extends Schema.TaggedError()( + "ClaudeMcpRegistrationTimeoutError", + {}, +) {} + describe("orchestration v2 provider switching", () => { it.live.each([ "compact-native", @@ -1311,6 +1318,13 @@ describe("orchestration v2 provider switching", () => { it.live.each([ ["background work", new ClaudeBackgroundWorkBlocksQueryReplacementError()], ["an unreadable append file", new ClaudeAppendSystemPromptFileError({ path: "missing.md" })], + [ + "an MCP registration timeout", + new ClaudeAgentSdkQueryRunnerError({ + method: "setMcpServers", + cause: new ClaudeMcpRegistrationTimeoutError(), + }), + ], ] as const)("keeps the native session after turns refused for %s", ([, refusalCause]) => Effect.scoped( Effect.gen(function* () { From 32bf48f428200efc95295ed109526f7b88d9d68a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 26 Oct 2026 22:40:33 -0700 Subject: [PATCH 009/817] fix(server): preserve settled runs during delegated acknowledgements (#25672) Co-authored-by: Claude Opus 5.5 --- .../DelegatedCompletionDelivery.test.ts | 98 +++++++++++++++++++ apps/server/src/orchestration-v2/EventSink.ts | 52 ++++++---- .../src/orchestration-v2/Orchestrator.ts | 14 ++- 3 files changed, 141 insertions(+), 23 deletions(-) diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts index 3bf563c1f794a..e426eece00654 100644 --- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts @@ -974,6 +974,104 @@ it.layer(layerTest)("delegated completion delivery repairs", (it) => { ); }), ); + + it.effect.each([ + { before: "running", after: "failed", capture: false }, + { before: "waiting", after: "completed", capture: true }, + ] as const)( + "keeps a $after run that settled between task_status's acknowledge read and commit", + ({ before, after, capture }) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const sink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make(`thread:ack-settle-race-${after}`); + const runId = RunId.make(`run:ack-settle-race-${after}`); + const taskId = NodeId.make(`node:ack-settle-race-${after}-task`); + const checkpointId = CheckpointId.make(`checkpoint:ack-settle-race-${after}`); + yield* seedParentWithTerminalTask({ + threadId, + projectId: ProjectId.make(`project:ack-settle-race-${after}`), + runId, + rootNodeId: NodeId.make(`node:ack-settle-race-${after}-root`), + taskId, + deliveryState: "claimed", + deliveryTaskIds: [taskId], + now, + }); + const parent = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!; + yield* sink.write({ + events: [ + { + id: EventId.make(`event:ack-settle-race-${after}-before`), + type: "run.updated", + threadId, + runId, + occurredAt: now, + payload: { ...parent, status: before }, + }, + ], + }); + const { delegatedCompletion: _cohort, ...settledRun } = parent; + const commit = sink.commitCommand; + let settled = false; + yield* Effect.acquireUseRelease( + Effect.sync(() => + vi.spyOn(sink, "commitCommand").mockImplementation((input) => + Effect.gen(function* () { + if ( + !settled && + input.commandType === "delegated_task.completion-delivery.acknowledge" + ) { + settled = true; + // The provider turn ends (or its checkpoint lands) after acknowledge read the run. + yield* commit({ + commandId: CommandId.make(`command:ack-settle-race-${after}`), + threadId, + commandType: capture ? "checkpoint.capture" : "provider.event", + acceptedAt: now, + effects: [], + events: [ + { + id: EventId.make(`event:ack-settle-race-${after}-settled`), + type: "run.updated", + threadId, + runId, + occurredAt: now, + payload: { + ...settledRun, + status: after, + completedAt: now, + checkpointId: capture ? checkpointId : null, + }, + }, + ], + }); + } + return yield* commit(input); + }), + ), + ), + () => + orchestrator.dispatch({ + type: "delegated_task.completion-delivery.acknowledge", + commandId: CommandId.make(`command:ack-settle-race-${after}:task-status`), + parentThreadId: threadId, + taskId, + observedByRunId: runId, + }), + (spy) => Effect.sync(() => spy.mockRestore()), + ); + assert.isTrue(settled); + const run = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (candidate) => candidate.id === runId, + )!; + assert.deepEqual( + { status: run.status, completedAt: run.completedAt, checkpointId: run.checkpointId }, + { status: after, completedAt: now, checkpointId: capture ? checkpointId : null }, + ); + }), + ); }); const reconcileCommandId = (name: string) => CommandId.make(`command:runtime-reconcile:${name}`); diff --git a/apps/server/src/orchestration-v2/EventSink.ts b/apps/server/src/orchestration-v2/EventSink.ts index af8fa5a95af7b..b210d3c9840ae 100644 --- a/apps/server/src/orchestration-v2/EventSink.ts +++ b/apps/server/src/orchestration-v2/EventSink.ts @@ -146,6 +146,8 @@ export interface EventSinkV2Shape { readonly effectTypes: ReadonlyArray; readonly reason: string; }; + /** Like writeWithEffects' updateDelegatedCompletionOnly, for this run's run.updated only. */ + readonly updateDelegatedCompletionOnlyRunId?: RunId; }) => Effect.Effect< { readonly receipt: CommandReceiptStore.CommandReceiptV2; @@ -383,6 +385,28 @@ const layerBase: Layer.Layer< return yield* runOutcomes.prepare(storedEvents); }); + // The enclosing write or commit span already traces this per-event projection merge. + const updateDelegatedCompletionOnly = Effect.fnUntraced(function* ( + events: ReadonlyArray, + includesRun: (runId: RunId) => boolean, + ) { + return yield* Effect.forEach(events, (event) => + Effect.gen(function* () { + if (event.type !== "run.updated" || !includesRun(event.payload.id)) return event; + const { runs } = yield* projectionStore.getThreadRecords(event.threadId, ["runs"], { + runIds: [event.payload.id], + }); + const current = runs[0]; + return current === undefined + ? event + : { + ...event, + payload: { ...current, delegatedCompletion: event.payload.delegatedCompletion }, + }; + }), + ); + }); + const writeEffect = Effect.fn("orchestrationV2.EventSink.write")(function* ( input: Parameters[0], ) { @@ -411,26 +435,7 @@ const layerBase: Layer.Layer< // Checkpoint capture can finish after a cohort writer reads its parent run. // Merge in this transaction so the event log and projection keep that completion. const events = input.updateDelegatedCompletionOnly - ? yield* Effect.forEach(input.events, (event) => - Effect.gen(function* () { - if (event.type !== "run.updated") return event; - const { runs } = yield* projectionStore.getThreadRecords( - event.threadId, - ["runs"], - { runIds: [event.payload.id] }, - ); - const current = runs[0]; - return current === undefined - ? event - : { - ...event, - payload: { - ...current, - delegatedCompletion: event.payload.delegatedCompletion, - }, - }; - }), - ) + ? yield* updateDelegatedCompletionOnly(input.events, () => true) : input.events; const normalized = yield* normalizeEvents( input.guardPendingUserInputCancellations === true @@ -646,7 +651,12 @@ const layerBase: Layer.Layer< return { ...existing, committed: false as const, cancelledEffectIds: [] }; } - const normalized = yield* normalizeEvents(input.events); + const runId = input.updateDelegatedCompletionOnlyRunId; + const normalized = yield* normalizeEvents( + runId === undefined + ? input.events + : yield* updateDelegatedCompletionOnly(input.events, (id) => id === runId), + ); const storedEvents = yield* eventStore.append({ commandId: input.commandId, events: normalized, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 0c6ca268f1e04..ee8ab83b952aa 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -2358,7 +2358,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio run: deliveryRun, now, }); - return; + return parentRun.id; } const message = completionDeliveryMessage(projection, delivery); if (message !== undefined) { @@ -2382,6 +2382,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); } } + return parentRun.id; }); const disposeDelegatedCompletionCohort = Effect.fn( @@ -11752,6 +11753,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio readonly effectTypes: ReadonlyArray; readonly reason: string; }; + readonly updateDelegatedCompletionOnlyRunId?: RunId; }, OrchestratorV2Error > { @@ -11769,6 +11771,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio readonly reason: string; } | undefined; + let updateDelegatedCompletionOnlyRunId: RunId | undefined; switch (command.type) { case "thread.create": yield* dispatchThreadCreate(command, events); @@ -12080,7 +12083,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio break; case "delegated_task.completion-delivery.acknowledge": case "delegated_task.completion-delivery.dispose": - yield* dispatchDelegatedTaskCompletionDeliveryResolution(command, events); + updateDelegatedCompletionOnlyRunId = + yield* dispatchDelegatedTaskCompletionDeliveryResolution(command, events); break; case "thread.created.record": yield* dispatchCreatedThreadRecord(command, events); @@ -12095,6 +12099,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio events: yield* Ref.get(events), effects: yield* Ref.get(effects), ...(cancelUnsettledEffects === undefined ? {} : { cancelUnsettledEffects }), + ...(updateDelegatedCompletionOnlyRunId === undefined + ? {} + : { updateDelegatedCompletionOnlyRunId }), }; }); @@ -12271,6 +12278,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ...(plan.cancelUnsettledEffects === undefined ? {} : { cancelUnsettledEffects: plan.cancelUnsettledEffects }), + ...(plan.updateDelegatedCompletionOnlyRunId === undefined + ? {} + : { updateDelegatedCompletionOnlyRunId: plan.updateDelegatedCompletionOnlyRunId }), }) .pipe( Effect.mapError( From 5522180329c70c7050852ae0d948400d845f55da Mon Sep 17 00:00:00 2001 From: Alex Date: Mon, 26 Oct 2026 22:48:21 -0700 Subject: [PATCH 010/817] fix(mobile): align the iPad composer with workspace navigation (#24942) Co-authored-by: maria-rcks --- .../src/features/threads/ThreadComposer.tsx | 27 ++++++++++--------- .../features/threads/ThreadDetailScreen.tsx | 9 +++++-- 2 files changed, 21 insertions(+), 15 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index 5f910dfc929f5..df5aca19dec1a 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -562,7 +562,8 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps const isVoiceInputPresented = voicePresentation.statusLabel !== null; const isExpanded = isFocused || settingsSheetPresentation.keepsComposerExpanded; const { setComposerEditing } = useAdaptiveWorkspaceLayout(); - const hasSidebarTabBar = useSidebarWorkspaceTabs() === "picker"; + const usesLargeControls = + useSidebarWorkspaceTabs() === "picker" || (Platform.OS === "ios" && Platform.isPad); const [compactRowWidth, setCompactRowWidth] = useState(0); const compactAttachmentLimit = compactRowWidth >= 500 ? 3 : 1; const compactEditor = useCompactComposerEditor(bodyText, draftMessage); @@ -768,7 +769,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps const modelControl = ( {isExpanded ? editingAttachments : null} @@ -871,7 +872,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps hidden={showsCompactDictation} > {modelControl} {showStopAction ? ( ) : showResumeAction ? ( ) : ( @@ -1134,7 +1135,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps ) : ( Date: Mon, 26 Oct 2026 22:52:52 -0700 Subject: [PATCH 011/817] chore(evals): store eval cases as .ndjson so review tools skip them (#25782) Co-authored-by: Claude Opus 5.5 --- evals/mcp-tool-use/README.md | 2 +- .../cases/{orchestration.jsonl => orchestration.ndjson} | 0 .../cases/{pull-requests.jsonl => pull-requests.ndjson} | 0 .../cases/{visual-preview.jsonl => visual-preview.ndjson} | 0 evals/mcp-tool-use/run.ts | 8 ++++---- 5 files changed, 5 insertions(+), 5 deletions(-) rename evals/mcp-tool-use/cases/{orchestration.jsonl => orchestration.ndjson} (100%) rename evals/mcp-tool-use/cases/{pull-requests.jsonl => pull-requests.ndjson} (100%) rename evals/mcp-tool-use/cases/{visual-preview.jsonl => visual-preview.ndjson} (100%) diff --git a/evals/mcp-tool-use/README.md b/evals/mcp-tool-use/README.md index bdddd8e96485a..e478b1fec1e5f 100644 --- a/evals/mcp-tool-use/README.md +++ b/evals/mcp-tool-use/README.md @@ -14,7 +14,7 @@ pnpm mcp-tool-use --model claude-opus-5-5 --out runs/opus - `ANTHROPIC_API_KEY` in the repo root `.env` pays for Claude models and the Haiku shell simulator. - Codex models (`gpt-*` in `MODELS` in `run.ts`) go through a CLIProxyAPI server, set up as the `vibeproxy` model provider in `~/.codex/config.toml`. Keep the proxy under about 12 samples in flight across all runs. -- Flags: `--case `, `--cases `, `--samples ` (default 2, and a 3rd when the first 2 disagree), `--concurrency ` (samples in flight, default 8), `--max-steps `, `--effort `, `--dry-run` (prints request bodies, no model calls), and `--context` (prints the size of T3's text and schemas, no key needed). +- Flags: `--case `, `--cases `, `--samples ` (default 2, and a 3rd when the first 2 disagree), `--concurrency ` (samples in flight, default 8), `--max-steps `, `--effort `, `--dry-run` (prints request bodies, no model calls), and `--context` (prints the size of T3's text and schemas, no key needed). - `--baseline --stop-on-regression` stops as soon as a case that passed every baseline sample fails. Use it to test one copy change against a baseline run. - Cost: a full Sonnet run is about $9, and a full Opus run about $17. Codex models through the proxy cost only the shell simulator. diff --git a/evals/mcp-tool-use/cases/orchestration.jsonl b/evals/mcp-tool-use/cases/orchestration.ndjson similarity index 100% rename from evals/mcp-tool-use/cases/orchestration.jsonl rename to evals/mcp-tool-use/cases/orchestration.ndjson diff --git a/evals/mcp-tool-use/cases/pull-requests.jsonl b/evals/mcp-tool-use/cases/pull-requests.ndjson similarity index 100% rename from evals/mcp-tool-use/cases/pull-requests.jsonl rename to evals/mcp-tool-use/cases/pull-requests.ndjson diff --git a/evals/mcp-tool-use/cases/visual-preview.jsonl b/evals/mcp-tool-use/cases/visual-preview.ndjson similarity index 100% rename from evals/mcp-tool-use/cases/visual-preview.jsonl rename to evals/mcp-tool-use/cases/visual-preview.ndjson diff --git a/evals/mcp-tool-use/run.ts b/evals/mcp-tool-use/run.ts index cca050021dd4a..f65ef239ed7d6 100644 --- a/evals/mcp-tool-use/run.ts +++ b/evals/mcp-tool-use/run.ts @@ -1678,7 +1678,7 @@ const main = Effect.gen(function* () { } const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const readJsonl = (file: string, decode: (line: string) => Effect.Effect) => + const readNdjson = (file: string, decode: (line: string) => Effect.Effect) => fs.readFileString(file).pipe( Effect.map((content) => content.split("\n").filter((line) => line.trim() !== "")), Effect.flatMap((lines) => Effect.forEach(lines, (line) => decode(line))), @@ -1687,10 +1687,10 @@ const main = Effect.gen(function* () { const caseFiles = flags.cases ?? (yield* fs.readDirectory(casesDir)) - .filter((name) => name.endsWith(".jsonl")) + .filter((name) => name.endsWith(".ndjson")) .toSorted() .map((name) => path.join(casesDir, name)); - const cases = (yield* Effect.forEach(caseFiles, (file) => readJsonl(file, decodeCase))).flat(); + const cases = (yield* Effect.forEach(caseFiles, (file) => readNdjson(file, decodeCase))).flat(); const wanted = flags.case?.flatMap((ids) => ids.split(",")); const codex = isCodex(flags.model); const harness = codex ? "codex" : "claude"; @@ -1764,7 +1764,7 @@ const main = Effect.gen(function* () { shellModel: flags["shell-model"], }; const previous = - flags.baseline === undefined ? [] : yield* readJsonl(flags.baseline, decodeBaselineRow); + flags.baseline === undefined ? [] : yield* readNdjson(flags.baseline, decodeBaselineRow); const baseline = new Map(groups(previous, (row) => row.id).map(([id, r]) => [id, passRate(r)])); // Only a case that passed every baseline sample can stop a run; flaky ones are just reported. const passedBefore = (id: string) => baseline.get(id) === 1; From 394929af7687886084234ccb92b744f51ede271b Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Mon, 26 Oct 2026 22:58:53 -0700 Subject: [PATCH 012/817] test(server): CI fails when agent context grows past main (#25785) Co-authored-by: Claude Opus 5.5 --- .github/workflows/agent-context-budget.yml | 55 ++++++++ apps/server/src/mcp/McpHttpServer.ts | 7 +- .../src/provider/AgentContextBudget.test.ts | 127 ++++++++++++++++++ .../src/provider/agentContextBudget.json | 5 + 4 files changed, 192 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/agent-context-budget.yml create mode 100644 apps/server/src/provider/AgentContextBudget.test.ts create mode 100644 apps/server/src/provider/agentContextBudget.json diff --git a/.github/workflows/agent-context-budget.yml b/.github/workflows/agent-context-budget.yml new file mode 100644 index 0000000000000..9396d8e3e7a63 --- /dev/null +++ b/.github/workflows/agent-context-budget.yml @@ -0,0 +1,55 @@ +name: Agent Context Budget + +# Fails when a PR raises a value in agentContextBudget.json above main's. AgentContextBudget.test.ts +# keeps that file equal to the measured context, so the context cannot grow by editing the file. +# To accept growth on purpose, a maintainer adds the agent-context-increase label. +on: + pull_request: + types: [opened, synchronize, reopened, labeled, unlabeled] + +permissions: + contents: read + +concurrency: + group: agent-context-budget-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + budget: + name: Agent context budget + runs-on: ubuntu-24.04 + timeout-minutes: 5 + env: + BUDGET: apps/server/src/provider/agentContextBudget.json + ALLOW_INCREASE: ${{ contains(github.event.pull_request.labels.*.name, 'agent-context-increase') }} + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + sparse-checkout: apps/server/src/provider/agentContextBudget.json + sparse-checkout-cone-mode: false + + - name: Compare with main + run: | + git fetch --quiet --depth=1 origin main + if ! git cat-file -e "FETCH_HEAD:$BUDGET" 2>/dev/null; then + echo "main has no agent context budget yet." + exit 0 + fi + git show "FETCH_HEAD:$BUDGET" > "$RUNNER_TEMP/main.json" + grown=$(jq -r --slurpfile main "$RUNNER_TEMP/main.json" ' + to_entries[] + | select($main[0][.key] != null and .value > $main[0][.key]) + | "\(.key): \($main[0][.key]) -> \(.value) (+\(.value - $main[0][.key]))" + ' "$BUDGET") + if [ -z "$grown" ]; then + echo "Agent context is not larger than main." + exit 0 + fi + printf 'Agent context grew compared to main:\n%s\n' "$grown" + if [ "$ALLOW_INCREASE" = "true" ]; then + echo "Accepted by the agent-context-increase label." + exit 0 + fi + echo "::error file=$BUDGET::Agent context grew compared to main. Cut the added text, or ask a maintainer to add the agent-context-increase label." + exit 1 diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 179d82dc998c2..044a43baeab1e 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -1055,7 +1055,8 @@ export const layerMcpTransport = McpServer.layerHttp({ allowSessionTermination: true, }).pipe(Layer.provide(layerMcpAuthMiddleware)); -export const layer = Layer.mergeAll( +/** Every tool the T3 MCP server advertises. AgentContextBudget.test.ts measures this set. */ +export const layerTools = Layer.mergeAll( layerPreviewToolkit, layerOrchestratorToolkit, layerThreadToolkit, @@ -1067,4 +1068,6 @@ export const layer = Layer.mergeAll( layerPullRequestsToolkit, layerDeviceToolkit, layerHtmlToolkit, -).pipe(Layer.provideMerge(layerMcpTransport)); +); + +export const layer = layerTools.pipe(Layer.provideMerge(layerMcpTransport)); diff --git a/apps/server/src/provider/AgentContextBudget.test.ts b/apps/server/src/provider/AgentContextBudget.test.ts new file mode 100644 index 0000000000000..09d2fb89ba65a --- /dev/null +++ b/apps/server/src/provider/AgentContextBudget.test.ts @@ -0,0 +1,127 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import { ProviderInstanceId } from "@t3tools/contracts"; +import { McpProviderSessions } from "@t3tools/provider-core/server/McpProviderSessions"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { McpServer } from "effect/ai"; + +import { ServerSecretStore } from "../auth/ServerSecretStore.ts"; +import { ServerConfig } from "../config.ts"; +import { DeviceService } from "../device/DeviceService.ts"; +import { ServerEnvironment } from "../environment/ServerEnvironment.ts"; +import { GitWorkflowService } from "../git/GitWorkflowService.ts"; +import * as McpHttpServer from "../mcp/McpHttpServer.ts"; +import { PreviewAutomationBroker } from "../mcp/PreviewAutomationBroker.ts"; +import { + CLAUDE_PROVIDER, + makeClaudeQueryOptions, +} from "../orchestration-v2/Adapters/ClaudeAdapterV2.ts"; +import { OrchestratorV2 } from "../orchestration-v2/Orchestrator.ts"; +import { ProviderAdapterRegistryV2 } from "../orchestration-v2/ProviderAdapterRegistry.ts"; +import { ThreadLaunchService } from "../orchestration-v2/ThreadLaunchService.ts"; +import { ThreadManagementService } from "../orchestration-v2/ThreadManagementService.ts"; +import { ThreadSearch } from "../orchestration-v2/ThreadSearch.ts"; +import { PreviewManager } from "../preview/Manager.ts"; +import { PreviewBrowser } from "../preview/PreviewBrowser.ts"; +import { ManagedProjectFolders } from "../project/ManagedProjectFolders.ts"; +import { ProjectService } from "../project/ProjectService.ts"; +import { ProjectSetupScriptRunner } from "../project/ProjectSetupScriptRunner.ts"; +import { PullRequestReviewGuideService } from "../pullRequest/PullRequestReviewGuideService.ts"; +import { ScheduledTaskService } from "../scheduledTasks/ScheduledTaskService.ts"; +import { SecretRequests } from "../secrets/SecretRequests.ts"; +import { ServerSettingsService } from "../serverSettings.ts"; +import { SourceControlRepositoryService } from "../sourceControl/SourceControlRepositoryService.ts"; +import { GitVcsDriver } from "../vcs/GitVcsDriver.ts"; +import { VcsStatusBroadcaster } from "../vcs/VcsStatusBroadcaster.ts"; +import { buildCodexAdditionalContext } from "./CodexDeveloperInstructions.ts"; +import { DocumentText } from "./DocumentText.ts"; +import { ProviderRegistry } from "./ProviderRegistry.ts"; +import budget from "./agentContextBudget.json" with { type: "json" }; + +// Registration only stores tool definitions, so the handlers' services are never called. +const toolHandlerServices = Layer.mergeAll( + Layer.mock(DeviceService)({}), + Layer.mock(DocumentText)({}), + Layer.mock(GitVcsDriver)({}), + Layer.mock(GitWorkflowService)({}), + Layer.mock(ManagedProjectFolders)({ namedProjectsRoot: "" }), + Layer.mock(McpProviderSessions)({}), + Layer.mock(OrchestratorV2)({}), + Layer.mock(PreviewAutomationBroker)({}), + Layer.mock(PreviewBrowser)({}), + Layer.mock(PreviewManager)({}), + Layer.mock(ProjectService)({}), + Layer.mock(ProjectSetupScriptRunner)({}), + Layer.mock(ProviderAdapterRegistryV2)({}), + Layer.mock(ProviderRegistry)({}), + Layer.mock(PullRequestReviewGuideService)({}), + Layer.mock(ScheduledTaskService)({}), + Layer.mock(SecretRequests)({}), + ServerConfig.layerTest(process.cwd(), { prefix: "t3-agent-context-budget-" }), + Layer.mock(ServerEnvironment)({}), + Layer.mock(ServerSecretStore)({}), + Layer.mock(ServerSettingsService)({}), + Layer.mock(SourceControlRepositoryService)({}), + Layer.mock(ThreadLaunchService)({}), + Layer.mock(ThreadManagementService)({}), + Layer.mock(ThreadSearch)({}), + Layer.mock(VcsStatusBroadcaster)({}), +).pipe(Layer.provideMerge(NodeServices.layer)); + +const utf8Bytes = (text: string) => Buffer.byteLength(text, "utf8"); + +const claudeSystemAppend = () => { + const { systemPrompt } = makeClaudeQueryOptions({ + modelSelection: { + instanceId: ProviderInstanceId.make(CLAUDE_PROVIDER), + model: "claude-opus-5-5", + }, + nativeThreadId: "context-budget", + resume: false, + cwd: null, + mcpServers: { "t3-code": { type: "http", url: "http://127.0.0.1/mcp" } }, + }); + return typeof systemPrompt === "object" && "append" in systemPrompt ? systemPrompt.append : ""; +}; + +const codexAdditionalContext = () => + Object.values( + buildCodexAdditionalContext( + { model: "gpt-6.1-sol", modelName: "GPT-6.1 Sol", reasoningEffort: "high" }, + { browser: true, device: true }, + ), + ) + .map((entry) => entry.value) + .join(""); + +// CI rejects a PR that raises any value above main's agentContextBudget.json, so growth +// needs the agent-context-increase label. Lower the values when the text shrinks. +it.effect("agent context matches the committed budget", () => + Effect.gen(function* () { + const mcp = yield* McpServer.McpServer; + const measured = { + claudeSystemAppendBytes: utf8Bytes(claudeSystemAppend()), + codexAdditionalContextBytes: utf8Bytes(codexAdditionalContext()), + // The model sees these fields. outputSchema and annotations are protocol metadata. + mcpToolListJsonBytes: utf8Bytes( + JSON.stringify( + mcp.tools.map(({ tool }) => ({ + name: tool.name, + description: tool.description, + inputSchema: tool.inputSchema, + })), + ), + ), + }; + + expect(measured).toEqual(budget); + }).pipe( + Effect.provide( + McpHttpServer.layerTools.pipe( + Layer.provideMerge(McpServer.McpServer.layer), + Layer.provide(toolHandlerServices), + ), + ), + ), +); diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json new file mode 100644 index 0000000000000..e3272bfdf8021 --- /dev/null +++ b/apps/server/src/provider/agentContextBudget.json @@ -0,0 +1,5 @@ +{ + "claudeSystemAppendBytes": 4857, + "codexAdditionalContextBytes": 5409, + "mcpToolListJsonBytes": 54964 +} From bea2e9d62fdc2440c2db4d670b8741425b526969 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 26 Oct 2026 23:02:19 -0700 Subject: [PATCH 013/817] refactor(mobile): theme preferences reach the native runtime without a layout effect (#25767) Co-authored-by: Claude Opus 5.5 --- apps/mobile/src/App.tsx | 2 + .../AppearancePreferencesProvider.tsx | 237 ++++++++++-------- 2 files changed, 139 insertions(+), 100 deletions(-) diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsx index acb6287e3a357..3ade5d940fdbb 100644 --- a/apps/mobile/src/App.tsx +++ b/apps/mobile/src/App.tsx @@ -24,6 +24,7 @@ import { prepareNativeShowcaseCapture } from "./features/showcase/nativeShowcase import { IncomingShareProvider } from "./features/sharing/IncomingShareProvider"; import { AppearancePreferencesProvider, + installAppearanceRuntime, useAppearancePreferences, } from "./features/settings/appearance/AppearancePreferencesProvider"; import { RootStack } from "./Stack"; @@ -107,6 +108,7 @@ const appServiceDisposers = [ threadRefsAtom: environmentThreadShells.threadRefsAtom, shellStateAtom: environmentShell.stateAtom, }), + installAppearanceRuntime(), installSubscriptionUsageRefresh(), installPermissionUpdateNotice(), installThreadOutboxDelivery(), diff --git a/apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx b/apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx index a7b2807d78226..bdde057dd232f 100644 --- a/apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx +++ b/apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx @@ -1,19 +1,8 @@ -import { - createContext, - startTransition, - use, - useCallback, - useEffect, - useState, - useLayoutEffect, - useMemo, - useRef, - type ReactNode, -} from "react"; +import { createContext, startTransition, use, useCallback, useMemo, type ReactNode } from "react"; import { AppState, Appearance, Platform, useColorScheme } from "react-native"; import { useAtomSet, useAtomValue } from "@effect/atom-react"; -import { AsyncResult } from "effect/reactivity"; +import { Atom, AsyncResult } from "effect/reactivity"; import { ScopedTheme, ScopedVariables, Uniwind } from "uniwind"; @@ -22,9 +11,14 @@ import { resolveAppearancePreferences, type ResolvedAppearance, } from "../../../lib/appearancePreferences"; +import { appAtomRegistry } from "../../../state/atom-registry"; import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../../state/preferences"; import type { Preferences } from "../../../persistence/mobile-preferences"; -import { isSystemColorsAvailable, readSystemColorPalettes } from "../../../lib/materialYouPalette"; +import { + isSystemColorsAvailable, + readSystemColorPalettes, + type MaterialYouPalettes, +} from "../../../lib/materialYouPalette"; import { materialYouPaletteToMobileThemeVariables } from "../../../lib/materialYouTheme"; import { getMobileThemeRuntimeVariables } from "../../../lib/mobileThemeVariables"; import type { MobileThemeVariables } from "../../../lib/mobileTheme"; @@ -74,6 +68,115 @@ interface AppearancePreferencesContextValue { const AppearancePreferencesContext = createContext(null); +function storedPreferencesOf(result: AsyncResult.AsyncResult) { + return AsyncResult.isSuccess(result) ? result.value : null; +} + +/** + * Material You palettes follow the system wallpaper, which can change while the + * app is in the background. + */ +const systemColorPalettesAtom = Atom.make((get): MaterialYouPalettes | null => { + const initial = readSystemColorPalettes(); + if (!isSystemColorsAvailable) return initial; + let current = initial; + const refresh = () => { + const next = readSystemColorPalettes(); + if (JSON.stringify(current) === JSON.stringify(next)) return; + current = next; + get.setSelf(next); + }; + const subscription = AppState.addEventListener("change", (state) => { + if (state === "active") refresh(); + }); + const focusSubscription = AppState.addEventListener("focus", refresh); + get.addFinalizer(() => { + subscription.remove(); + focusSubscription.remove(); + }); + return initial; +}).pipe(Atom.withLabel("mobile:system-color-palettes")); + +function resolveThemeVariablesByAppearance( + themeIds: MobileThemeIds, + palettes: MaterialYouPalettes | null, +): Readonly> { + const resolve = (appearance: MobileThemeAppearance) => { + const base = getMobileThemeRuntimeVariables(themeIds[appearance], appearance, Platform.OS); + return themeIds[appearance] === "material-you" && palettes + ? materialYouPaletteToMobileThemeVariables(palettes[appearance], appearance, base) + : base; + }; + return { light: resolve("light"), dark: resolve("dark") }; +} + +/** The appearance whose theme is on screen, read from the native scheme. */ +function resolveThemeAppearance(stored: Preferences | null): MobileThemeAppearance { + const themeMode = normalizeMobileThemeMode(stored?.themeMode); + if (themeMode !== "system") return themeMode; + return Appearance.getColorScheme() === "dark" ? "dark" : "light"; +} + +function runtimeStateFor(stored: Preferences | null): MobileThemeRuntimeState { + return { + baseFontSize: resolveAppearancePreferences(stored).baseFontSize, + themeMode: normalizeMobileThemeMode(stored?.themeMode), + themeAppearance: resolveThemeAppearance(stored), + }; +} + +const themeRuntimeStateAtom = Atom.make((get) => + runtimeStateFor(storedPreferencesOf(get(mobilePreferencesAtom))), +).pipe( + Atom.withEquality( + (left: MobileThemeRuntimeState, right: MobileThemeRuntimeState) => + left.baseFontSize === right.baseFontSize && + left.themeMode === right.themeMode && + left.themeAppearance === right.themeAppearance, + ), +); + +// Native appearance and Uniwind text variables are process-global, so the +// last applied state is too. Setters apply ahead of the preference write so the +// first frame after a change already uses it; the atom subscription then sees +// no difference. +let appliedRuntimeState: MobileThemeRuntimeState | null = null; + +function applyThemeRuntime(next: MobileThemeRuntimeState) { + for (const operation of createMobileThemeRuntimeOperations(appliedRuntimeState, next)) { + if (operation.kind === "update-text-variables") { + Uniwind.updateCSSVariables(operation.themeName, operation.variables); + continue; + } + if (operation.kind === "set-appearance-mode") { + Appearance.setColorScheme( + operation.themeMode === "system" ? "unspecified" : operation.appearance, + ); + } + } + appliedRuntimeState = next; +} + +function currentRuntimeState() { + return appliedRuntimeState ?? appAtomRegistry.get(themeRuntimeStateAtom); +} + +/** + * App-lifetime: applies theme preferences to the native runtime and holds the + * system palette listeners. Holding them here instead of `keepAlive` lets the + * fast-refresh disposer release the replaced module's AppState listeners. + */ +export function installAppearanceRuntime(): () => void { + const unsubscribeRuntime = appAtomRegistry.subscribe(themeRuntimeStateAtom, applyThemeRuntime, { + immediate: true, + }); + const releasePalettes = appAtomRegistry.mount(systemColorPalettesAtom); + return () => { + unsubscribeRuntime(); + releasePalettes(); + }; +} + export function AppearancePreferencesProvider(props: { readonly children: ReactNode }) { const preferencesResult = useAtomValue(mobilePreferencesAtom); const savePreferences = useAtomSet(updateMobilePreferencesAtom); @@ -94,37 +197,11 @@ export function AppearancePreferencesProvider(props: { readonly children: ReactN ); const themeId = themeIds[themeAppearance]; const systemColorsActive = themeId === "material-you" && isSystemColorsAvailable; - const [systemColorPalettes, setSystemColorPalettes] = useState(readSystemColorPalettes); - useEffect(() => { - if (!isSystemColorsAvailable) return; - const refresh = () => { - const next = readSystemColorPalettes(); - setSystemColorPalettes((previous) => - JSON.stringify(previous) === JSON.stringify(next) ? previous : next, - ); - }; - const subscription = AppState.addEventListener("change", (state) => { - if (state === "active") refresh(); - }); - const focusSubscription = AppState.addEventListener("focus", refresh); - return () => { - subscription.remove(); - focusSubscription.remove(); - }; - }, []); - const themeVariablesByAppearance = useMemo(() => { - const resolve = (appearance: MobileThemeAppearance) => { - const base = getMobileThemeRuntimeVariables(themeIds[appearance], appearance, Platform.OS); - return themeIds[appearance] === "material-you" && systemColorPalettes - ? materialYouPaletteToMobileThemeVariables( - systemColorPalettes[appearance], - appearance, - base, - ) - : base; - }; - return { light: resolve("light"), dark: resolve("dark") }; - }, [themeIds, systemColorPalettes]); + const systemColorPalettes = useAtomValue(systemColorPalettesAtom); + const themeVariablesByAppearance = resolveThemeVariablesByAppearance( + themeIds, + systemColorPalettes, + ); const themeVariables = themeVariablesByAppearance[themeAppearance]; const activeThemeName = getMobileUniwindThemeName(themeId, themeAppearance); const { baseFontSize, codeFontSize, codeWordBreak, terminalFontSize } = preferences; @@ -133,38 +210,6 @@ export function AppearancePreferencesProvider(props: { readonly children: ReactN [baseFontSize, codeFontSize, codeWordBreak, terminalFontSize], ); const isReady = AsyncResult.isSuccess(preferencesResult); - const runtimeState = useMemo( - () => ({ - baseFontSize, - themeAppearance, - themeMode, - }), - [baseFontSize, themeAppearance, themeMode], - ); - const appliedRuntimeStateRef = useRef(null); - const selectedThemeIdsRef = useRef(themeIds); - - const applyThemeRuntime = useCallback((next: MobileThemeRuntimeState) => { - const operations = createMobileThemeRuntimeOperations(appliedRuntimeStateRef.current, next); - for (const operation of operations) { - if (operation.kind === "update-text-variables") { - Uniwind.updateCSSVariables(operation.themeName, operation.variables); - continue; - } - if (operation.kind === "set-appearance-mode") { - Appearance.setColorScheme( - operation.themeMode === "system" ? "unspecified" : operation.appearance, - ); - } - } - appliedRuntimeStateRef.current = next; - }, []); - - const syncThemeRuntime = useCallback( - (next: MobileThemeRuntimeState) => applyThemeRuntime(next), - [applyThemeRuntime], - ); - const updatePreferences = useCallback( (patch: Partial) => { startTransition(() => savePreferences(patch)); @@ -179,37 +224,30 @@ export function AppearancePreferencesProvider(props: { readonly children: ReactN [savePreferences], ); - useLayoutEffect(() => { - selectedThemeIdsRef.current = themeIds; - syncThemeRuntime(runtimeState); - }, [runtimeState, syncThemeRuntime, themeIds]); - const setThemeIdForAppearance = useCallback( (appearance: MobileThemeAppearance, value: MobileThemeId) => { - const patch = createMobileThemeSelectionPatch( - selectedThemeIdsRef.current, - themeAppearance, - appearance, - value, + // Read at call time: a second pick before the next render must build on + // the first one's optimistic write. + const selected = resolveMobileThemeIds( + storedPreferencesOf(appAtomRegistry.get(mobilePreferencesAtom)) ?? {}, + ); + updateThemePreferences( + createMobileThemeSelectionPatch(selected, themeAppearance, appearance, value), ); - selectedThemeIdsRef.current = resolveMobileThemeIds(patch); - updateThemePreferences(patch); }, [themeAppearance, updateThemePreferences], ); const setThemeIdForBothAppearances = useCallback( (value: MobileThemeId) => { - const patch = createMobileThemePairPatch(value); - selectedThemeIdsRef.current = resolveMobileThemeIds(patch); - updateThemePreferences(patch); + updateThemePreferences(createMobileThemePairPatch(value)); }, [updateThemePreferences], ); const setThemeMode = useCallback( (value: MobileThemeMode) => { - const current = appliedRuntimeStateRef.current ?? runtimeState; + const current = currentRuntimeState(); // Clear forced appearance before publishing System so useColorScheme batches the system palette into the preference commit. if (value === "system") { @@ -223,23 +261,22 @@ export function AppearancePreferencesProvider(props: { readonly children: ReactN themeMode: value, }; - updateThemePreferences({ themeMode: value }); if (value === "system") { - appliedRuntimeStateRef.current = next; + appliedRuntimeState = next; } else { - syncThemeRuntime(next); + applyThemeRuntime(next); } + updateThemePreferences({ themeMode: value }); }, - [runtimeState, syncThemeRuntime, updateThemePreferences], + [updateThemePreferences], ); const setBaseFontSize = useCallback( (value: number) => { - const current = appliedRuntimeStateRef.current ?? runtimeState; - syncThemeRuntime({ ...current, baseFontSize: value }); + applyThemeRuntime({ ...currentRuntimeState(), baseFontSize: value }); updatePreferences({ baseFontSize: value }); }, - [runtimeState, syncThemeRuntime, updatePreferences], + [updatePreferences], ); const setTerminalFontSize = useCallback( From 2ad853ab211935a414cdf3c2f5004db635ae04bc Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 26 Oct 2026 23:03:48 -0700 Subject: [PATCH 014/817] refactor(mobile): the share inbox is a module store, presented from navigation state (#25744) Co-authored-by: Claude Opus 5.5 --- apps/mobile/src/App.tsx | 23 +- apps/mobile/src/Stack.tsx | 31 +-- .../sharing/IncomingShareProvider.tsx | 257 +++++++----------- apps/mobile/src/lib/appState.ts | 8 + apps/mobile/src/lib/coalescedRun.test.ts | 57 ++++ apps/mobile/src/lib/coalescedRun.ts | 26 ++ 6 files changed, 209 insertions(+), 193 deletions(-) create mode 100644 apps/mobile/src/lib/coalescedRun.test.ts create mode 100644 apps/mobile/src/lib/coalescedRun.ts diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsx index 3ade5d940fdbb..579aea37bfa4d 100644 --- a/apps/mobile/src/App.tsx +++ b/apps/mobile/src/App.tsx @@ -21,7 +21,10 @@ import { ThreadArrangementHost } from "./features/threads/ThreadArrangementSheet import * as Dialog from "./components/ui/Dialog"; import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider"; import { prepareNativeShowcaseCapture } from "./features/showcase/nativeShowcaseScene"; -import { IncomingShareProvider } from "./features/sharing/IncomingShareProvider"; +import { + presentPendingIncomingShare, + startIncomingShareInbox, +} from "./features/sharing/IncomingShareProvider"; import { AppearancePreferencesProvider, installAppearanceRuntime, @@ -92,6 +95,7 @@ const Navigation = createStaticNavigation(RootStack); function handleNavigationStateChange(state: NavigationState | undefined): void { recordWorkspaceSelections(state); if (state) pruneNewTaskBranchCheckouts(state); + presentPendingIncomingShare(); } function handleNavigationReady(): void { @@ -113,6 +117,7 @@ const appServiceDisposers = [ installPermissionUpdateNotice(), installThreadOutboxDelivery(), installComposerAttachmentUploads(), + startIncomingShareInbox(), ]; disposeOnFoundationReplace(typeof module === "undefined" ? undefined : module.hot, () => { for (const dispose of appServiceDisposers) dispose(); @@ -155,15 +160,13 @@ function AppContent() { {/* native-stack needs the theme's dark flag to select dark native headers. */} - - - + diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index 74a8600f1e3aa..7312807c55e48 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -15,7 +15,7 @@ import { createNativeStackScreen, type NativeStackNavigationOptions, } from "@react-navigation/native-stack"; -import { useEffect, useRef, type ReactNode } from "react"; +import type { ReactNode } from "react"; import { Platform, Pressable, ScrollView, StyleSheet, useWindowDimensions } from "react-native"; import { useResolveClassNames } from "uniwind"; @@ -139,20 +139,12 @@ import { SettingsLegalDocumentExternalHeaderButton, } from "./features/settings/components/SettingsLegalDocumentRouteScreen"; import { useAppShortcuts } from "./features/shortcuts/useAppShortcuts"; -import { useIncomingShare } from "./features/sharing/IncomingShareProvider"; -import { - EMPTY_INCOMING_SHARE_PRESENTATION_STATE, - transitionIncomingSharePresentation, -} from "./features/sharing/incoming-share-presentation"; import { NATIVE_LIQUID_GLASS_SUPPORTED } from "./native/native-glass"; import { deriveLayout } from "./lib/layout"; import { useNativeLayoutMetrics } from "./native/native-layout-metrics"; import { nativeHeaderScrollEdgeEffects } from "./native/StackHeader"; import { HORIZONTAL_FORM_SHEET_OPTIONS, formSheetDetents } from "./native/sheet-surface"; -import { - selectWorkspaceDetail, - workspaceDetailRouter, -} from "./features/workspace/workspace-detail-selection"; +import { workspaceDetailRouter } from "./features/workspace/workspace-detail-selection"; const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version); @@ -498,9 +490,6 @@ function RootStackLayout(props: { readonly children: React.ReactNode; readonly state: NavigationState; }) { - const navigation = useNavigation(); - const { pendingShare } = useIncomingShare(); - const sharePresentationRef = useRef(EMPTY_INCOMING_SHARE_PRESENTATION_STATE); const path = getPathFromState(props.state, navigationPathConfig); const pathname = path.startsWith("/") ? path : `/${path}`; const workspaceLocation = workspaceLocationFromState(props.state); @@ -519,22 +508,6 @@ function RootStackLayout(props: { useAgentNotificationNavigation(workspaceLocation.pathname); useConnectOnboardingNavigation(); useAppShortcuts(props.state); - useEffect(() => { - const transition = transitionIncomingSharePresentation(sharePresentationRef.current, { - isShareSheetPresented: isDraftThreadRoute(props.state.routes[props.state.index]), - pendingShareId: pendingShare?.id ?? null, - }); - sharePresentationRef.current = transition.state; - if (!transition.shareIdToPresent) { - return; - } - navigation.dispatch( - selectWorkspaceDetail({ - name: "Thread", - params: { draft: { incomingShareId: transition.shareIdToPresent } }, - }), - ); - }, [navigation, pendingShare, props.state]); return ( diff --git a/apps/mobile/src/features/sharing/IncomingShareProvider.tsx b/apps/mobile/src/features/sharing/IncomingShareProvider.tsx index 62425e49af6ef..23b34d362beee 100644 --- a/apps/mobile/src/features/sharing/IncomingShareProvider.tsx +++ b/apps/mobile/src/features/sharing/IncomingShareProvider.tsx @@ -9,8 +9,8 @@ import { type ResolvedSharePayload, type SharePayload, } from "expo-sharing"; -import React, { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react"; -import { AppState, Platform } from "react-native"; +import { useSyncExternalStore } from "react"; +import { Platform } from "react-native"; import { buildIncomingShareDraft, @@ -21,28 +21,21 @@ import { import { createIncomingSharePayloadReader } from "./incoming-share-native"; import { IncomingShareInbox } from "./incoming-share-inbox"; import { persistComposerAttachmentFile } from "../../lib/composerImages"; +import { subscribeAppActive } from "../../lib/appState"; +import { coalescedRun } from "../../lib/coalescedRun"; +import { rootNavigationRef } from "../../lib/rootNavigation"; +import { selectWorkspaceDetail } from "../workspace/workspace-detail-selection"; +import { isDraftThreadRoute } from "../threads/thread-route-state"; +import { + EMPTY_INCOMING_SHARE_PRESENTATION_STATE, + transitionIncomingSharePresentation, +} from "./incoming-share-presentation"; import { loadIncomingShareDrafts, removeIncomingShareDraft, writeIncomingShareDraft, } from "./incoming-share-storage"; -type IncomingShareContextValue = { - readonly pendingShare: IncomingShareDraft | null; - readonly isLoading: boolean; - readonly error: Error | null; - readonly getShare: (shareId: string) => IncomingShareDraft | null; - readonly reserveShare: (shareId: string, destination: IncomingShareDestination) => Promise; - readonly releaseShareReservation: ( - shareId: string, - expectedDestination: IncomingShareDestination, - ) => Promise; - readonly consumeShare: (shareId: string) => Promise; - readonly refresh: () => Promise; -}; - -const IncomingShareContext = React.createContext(null); - function receiveSharingEnabled(): boolean { if (Platform.OS === "android") { return true; @@ -197,153 +190,109 @@ const incomingShareInbox = new IncomingShareInbox({ }, }); -export function IncomingShareProvider(props: React.PropsWithChildren) { - const enabled = receiveSharingEnabled(); - const [drafts, setDrafts] = useState>([]); - const [isLoading, setIsLoading] = useState(true); - const [error, setError] = useState(null); - const refreshPromiseRef = useRef | null>(null); - const mountedRef = useRef(false); +interface IncomingShareSnapshot { + readonly drafts: ReadonlyArray; + readonly isLoading: boolean; +} - useEffect(() => { - mountedRef.current = true; - return () => { - mountedRef.current = false; - }; - }, []); +let snapshot: IncomingShareSnapshot = { drafts: [], isLoading: true }; +const snapshotListeners = new Set<() => void>(); +let presentation = EMPTY_INCOMING_SHARE_PRESENTATION_STATE; - const refresh = useCallback(async () => { - if (refreshPromiseRef.current) { - return refreshPromiseRef.current; - } +function publish(drafts: ReadonlyArray) { + snapshot = { drafts, isLoading: false }; + for (const listener of snapshotListeners) listener(); + presentPendingIncomingShare(); +} - const operation = (async () => { - try { - const snapshot = await incomingShareInbox.refresh({ ingestNative: enabled }); - if (mountedRef.current) { - setDrafts(snapshot); - setError(null); - } - } catch (cause) { - const persisted = await incomingShareInbox - .refresh({ ingestNative: false }) - .catch(() => null); - if (mountedRef.current) { - if (persisted) { - setDrafts(persisted); - } - setError(cause instanceof Error ? cause : new Error("Could not import shared content.")); - } - } - })().finally(() => { - refreshPromiseRef.current = null; - }); +function subscribeIncomingShares(onChange: () => void) { + snapshotListeners.add(onChange); + return () => { + snapshotListeners.delete(onChange); + }; +} - refreshPromiseRef.current = operation; - return operation; - }, [enabled]); +function getIncomingShareSnapshot() { + return snapshot; +} - useEffect(() => { - void refresh().finally(() => { - if (mountedRef.current) { - setIsLoading(false); - } - }); - }, [refresh]); +function reportRefreshFailure(cause: unknown) { + const error = cause instanceof Error ? cause : new Error("Could not import shared content."); + Dialog.alert("Could not import shared content", error.message, [ + { text: "Dismiss", style: "cancel" }, + { text: "Retry", onPress: () => void refreshIncomingShares() }, + ]); +} - const refreshOnAppActive = useEffectEvent(() => { - void refresh(); - }); +// A resume while a refresh runs may carry a native handoff that refresh already +// passed, so it queues one more refresh instead of joining the running one. +const refreshIncomingShares = coalescedRun(async () => { + const enabled = receiveSharingEnabled(); + try { + publish(await incomingShareInbox.refresh({ ingestNative: enabled })); + } catch (cause) { + const persisted = await incomingShareInbox.refresh({ ingestNative: false }).catch(() => null); + publish(persisted ?? snapshot.drafts); + reportRefreshFailure(cause); + } +}); - useEffect(() => { - if (!enabled) { - return; - } - const subscription = AppState.addEventListener("change", (state) => { - if (state === "active") { - refreshOnAppActive(); - } - }); - return () => subscription.remove(); - }, [enabled]); +/** + * Opens the oldest pending share as a new-task draft unless the user already + * dismissed it. Runs whenever the inbox or the root navigation state changes. + */ +export function presentPendingIncomingShare(): void { + if (!rootNavigationRef.isReady()) return; + const state = rootNavigationRef.getRootState(); + if (!state) return; + const transition = transitionIncomingSharePresentation(presentation, { + isShareSheetPresented: isDraftThreadRoute(state.routes[state.index]), + pendingShareId: snapshot.drafts[0]?.id ?? null, + }); + presentation = transition.state; + if (!transition.shareIdToPresent) return; + rootNavigationRef.dispatch( + selectWorkspaceDetail({ + name: "Thread", + params: { draft: { incomingShareId: transition.shareIdToPresent } }, + }), + ); +} - useEffect(() => { - if (!error) { - return; - } - Dialog.alert("Could not import shared content", error.message, [ - { text: "Dismiss", style: "cancel", onPress: () => setError(null) }, - { - text: "Retry", - onPress: () => { - setError(null); - void refresh(); - }, - }, - ]); - }, [error, refresh]); +/** App-lifetime: loads the inbox and re-ingests native handoffs on every resume. */ +export function startIncomingShareInbox(): () => void { + void refreshIncomingShares(); + return receiveSharingEnabled() + ? subscribeAppActive(() => void refreshIncomingShares()) + : () => {}; +} - const consumeShare = useCallback(async (shareId: string) => { - const snapshot = await incomingShareInbox.consume(shareId); - if (mountedRef.current) { - setDrafts(snapshot); - } - }, []); - const reserveShare = useCallback( - async (shareId: string, destination: IncomingShareDestination) => { - const snapshot = await incomingShareInbox.reserve(shareId, destination); - if (mountedRef.current) { - setDrafts(snapshot); - } - }, - [], - ); - const releaseShareReservation = useCallback( - async (shareId: string, expectedDestination: IncomingShareDestination) => { - const snapshot = await incomingShareInbox.releaseReservation(shareId, expectedDestination); - if (mountedRef.current) { - setDrafts(snapshot); - } - }, - [], - ); - const getShare = useCallback( - (shareId: string) => drafts.find((draft) => draft.id === shareId) ?? null, - [drafts], - ); +async function consumeShare(shareId: string) { + publish(await incomingShareInbox.consume(shareId)); +} - const value = useMemo( - () => ({ - pendingShare: drafts[0] ?? null, - isLoading, - error, - getShare, - releaseShareReservation, - reserveShare, - consumeShare, - refresh, - }), - [ - consumeShare, - drafts, - error, - getShare, - isLoading, - refresh, - releaseShareReservation, - reserveShare, - ], - ); +async function reserveShare(shareId: string, destination: IncomingShareDestination) { + publish(await incomingShareInbox.reserve(shareId, destination)); +} - return ( - {props.children} - ); +async function releaseShareReservation( + shareId: string, + expectedDestination: IncomingShareDestination, +) { + publish(await incomingShareInbox.releaseReservation(shareId, expectedDestination)); } -export function useIncomingShare(): IncomingShareContextValue { - const value = React.use(IncomingShareContext); - if (value === null) { - throw new Error("useIncomingShare must be used within IncomingShareProvider."); - } - return value; +export function useIncomingShare() { + const { drafts, isLoading } = useSyncExternalStore( + subscribeIncomingShares, + getIncomingShareSnapshot, + ); + return { + pendingShare: drafts[0] ?? null, + isLoading, + getShare: (shareId: string) => drafts.find((draft) => draft.id === shareId) ?? null, + reserveShare, + releaseShareReservation, + consumeShare, + }; } diff --git a/apps/mobile/src/lib/appState.ts b/apps/mobile/src/lib/appState.ts index e3c3cbc933747..8e1b5dfa9b4ed 100644 --- a/apps/mobile/src/lib/appState.ts +++ b/apps/mobile/src/lib/appState.ts @@ -12,6 +12,14 @@ export function isAppActive(): boolean { return AppState.currentState === "active"; } +/** Runs `onActive` each time the app returns to the foreground. */ +export function subscribeAppActive(onActive: Listener): () => void { + const subscription = AppState.addEventListener("change", (state) => { + if (state === "active") onActive(); + }); + return () => subscription.remove(); +} + export function useAppActive(): boolean { return useSyncExternalStore(subscribeAppState, isAppActive); } diff --git a/apps/mobile/src/lib/coalescedRun.test.ts b/apps/mobile/src/lib/coalescedRun.test.ts new file mode 100644 index 0000000000000..b409da5d3c2f6 --- /dev/null +++ b/apps/mobile/src/lib/coalescedRun.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it, vi } from "vite-plus/test"; + +import { coalescedRun } from "./coalescedRun"; + +function deferredRuns() { + const runs: Array> = []; + const run = () => { + const next = Promise.withResolvers(); + runs.push(next); + return next.promise; + }; + return { runs, run }; +} + +describe("coalescedRun", () => { + it("queues one more run for calls made while a run is in flight", async () => { + const { runs, run } = deferredRuns(); + const refresh = coalescedRun(run); + + const first = refresh(); + const second = refresh(); + const third = refresh(); + expect(third).toBe(second); + expect(runs).toHaveLength(1); + + runs[0]!.resolve(); + await first; + await vi.waitFor(() => expect(runs).toHaveLength(2)); + + runs[1]!.resolve(); + await second; + expect(runs).toHaveLength(2); + }); + + it("hands a queued run's failure to the call that asked for it", async () => { + const { runs, run } = deferredRuns(); + const refresh = coalescedRun(run); + + const first = refresh(); + const second = refresh(); + runs[0]!.resolve(); + await first; + await vi.waitFor(() => expect(runs).toHaveLength(2)); + runs[1]!.reject(new Error("read failed")); + await expect(second).rejects.toThrow("read failed"); + }); + + it("runs once per call when calls do not overlap", async () => { + let count = 0; + const refresh = coalescedRun(async () => { + count += 1; + }); + await refresh(); + await refresh(); + expect(count).toBe(2); + }); +}); diff --git a/apps/mobile/src/lib/coalescedRun.ts b/apps/mobile/src/lib/coalescedRun.ts new file mode 100644 index 0000000000000..72a32cc6865bd --- /dev/null +++ b/apps/mobile/src/lib/coalescedRun.ts @@ -0,0 +1,26 @@ +/** + * Runs `run` at most once at a time. A call made while a run is in flight + * queues one more run after it and returns that queued run, so input that + * arrives mid-run (a native share handed over on resume) is still read, and + * the caller that asked for it sees how it ended. + */ +export function coalescedRun(run: () => Promise): () => Promise { + let inFlight: Promise | null = null; + let queued: Promise | null = null; + const start = (): Promise => { + if (inFlight) { + queued ??= inFlight + .catch(() => undefined) + .then(() => { + queued = null; + return start(); + }); + return queued; + } + inFlight = run().finally(() => { + inFlight = null; + }); + return inFlight; + }; + return start; +} From 6f6c6c14b76e72d7abd43b8e6ebffff17eadc89e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 26 Oct 2026 23:04:56 -0700 Subject: [PATCH 015/817] refactor(web): drop the unreachable paint-only thread timeline path (#25787) Co-authored-by: Claude Opus 5.5 --- .../web/src/components/ChatView.logic.test.ts | 10 +- apps/web/src/components/ChatView.logic.ts | 46 +---- apps/web/src/components/ChatView.tsx | 169 +++++------------- .../src/components/chat/MessagesTimeline.tsx | 6 +- .../src/components/chat/ThreadTimeline.tsx | 17 +- .../src/components/chat/useTimelineRewind.ts | 4 +- 6 files changed, 62 insertions(+), 190 deletions(-) diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts index 969a5d2e24cc5..363e5db0b6071 100644 --- a/apps/web/src/components/ChatView.logic.test.ts +++ b/apps/web/src/components/ChatView.logic.test.ts @@ -45,7 +45,6 @@ import { rememberReadyThreadTimeline, resetHeldThreadTimeline, resolveThreadSwitchTimeline, - threadKeysShareEnvironment, timelineHasEphemeralPreviewUrls, createLocalDispatchSnapshot, deriveCommittedServerUserMessageIds, @@ -371,19 +370,18 @@ describe("resolveThreadSwitchTimeline", () => { activeThreadKey: "env-1:thread-a", nextEntries: [], }), - ).toEqual({ entries: ["a1", "a2"], displayThreadKey: "env-1:thread-a" }); + ).toEqual(["a1", "a2"]); }); - it("does not hold another environment's timeline across a jump", () => { - expect(threadKeysShareEnvironment("env-1:thread-a", "env-2:thread-b")).toBe(false); + it("does not paint the last-viewed thread for a destination with nothing remembered", () => { + rememberReadyThreadTimeline(held); expect( resolveThreadSwitchTimeline({ loading: true, activeThreadKey: "env-2:thread-b", nextEntries: [], - lastReady: held, }), - ).toEqual({ entries: [], displayThreadKey: "env-2:thread-b" }); + ).toEqual([]); }); it("does not remember a timeline that still has handoff blob previews", () => { diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index 67c10d9dfeadf..0e36a3ef4681e 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -46,7 +46,6 @@ import { } from "@t3tools/contracts"; import { worktreeSetupAgentStarted } from "@t3tools/client-runtime/worktree-setup"; import * as DateTime from "effect/DateTime"; -import { parseScopedThreadKey } from "@t3tools/client-runtime/environment"; import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets"; import { squashAtomCommandFailure, @@ -346,15 +345,12 @@ export function resolveDraftHeroState(input: { export type HeldThreadTimeline = { threadKey: string | null; entries: T; - markdownCwd?: string | null; - workspaceRoot?: string | null; }; const MAX_REMEMBERED_THREAD_TIMELINES = 16; let rememberedThreadTimelines = new Map>(); let rememberedThreadTimelineOrder: string[] = []; -let lastReadyThreadKey: string | null = null; function rememberThreadTimelineEntries(held: HeldThreadTimeline): void { if (held.threadKey === null) { @@ -371,7 +367,6 @@ function rememberThreadTimelineEntries(held: HeldThreadTimeline( @@ -392,41 +387,9 @@ export function peekRememberedThreadTimeline( return (rememberedThreadTimelines.get(threadKey)?.entries as T | undefined) ?? null; } -export function peekHeldThreadTimeline< - T extends readonly unknown[], ->(): HeldThreadTimeline | null { - if (lastReadyThreadKey === null) { - return null; - } - const held = rememberedThreadTimelines.get(lastReadyThreadKey); - if (held === undefined || held.entries.length === 0) { - return null; - } - return held as HeldThreadTimeline; -} - export function resetHeldThreadTimeline(): void { rememberedThreadTimelines = new Map(); rememberedThreadTimelineOrder = []; - lastReadyThreadKey = null; -} - -export function threadKeysShareEnvironment(left: string | null, right: string | null): boolean { - if (left === null || right === null) { - return false; - } - const leftRef = parseScopedThreadKey(left); - const rightRef = parseScopedThreadKey(right); - return leftRef !== null && rightRef !== null && leftRef.environmentId === rightRef.environmentId; -} - -export function isPaintOnlyThreadTimeline( - displayThreadKey: string | null, - activeThreadKey: string | null, -): boolean { - return ( - displayThreadKey !== null && activeThreadKey !== null && displayThreadKey !== activeThreadKey - ); } export function resolveThreadSwitchTimeline(input: { @@ -434,19 +397,18 @@ export function resolveThreadSwitchTimeline(input: activeThreadKey: string | null; nextEntries: T; rememberedForActive?: T | null; - lastReady?: HeldThreadTimeline | null; -}): { entries: T; displayThreadKey: string | null } { +}): T { if (input.nextEntries.length > 0) { - return { entries: input.nextEntries, displayThreadKey: input.activeThreadKey }; + return input.nextEntries; } const rememberedForActive = input.rememberedForActive ?? peekRememberedThreadTimeline(input.activeThreadKey); if (input.loading && rememberedForActive !== null && rememberedForActive.length > 0) { - return { entries: rememberedForActive, displayThreadKey: input.activeThreadKey }; + return rememberedForActive; } - return { entries: input.nextEntries, displayThreadKey: input.activeThreadKey }; + return input.nextEntries; } export function startNewThreadForProject( diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 462728f093c24..6486137a171ca 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -32,14 +32,7 @@ import { THREAD_FIND_BAR_RESERVED_HEIGHT } from "./chat/ThreadFindBar"; import { usageLimitRecoveryBannerItem } from "./chat/UsageLimitRecoveryBanner"; import { resolveDraftHeroState } from "./ChatView.logic"; import { useQueuedRunEdit } from "./chat/useQueuedRunEdit"; -import { - isPaintOnlyThreadTimeline, - peekHeldThreadTimeline, - peekRememberedThreadTimeline, - resolveThreadSwitchTimeline, - recallCheckoutIsRepo, - rememberCheckoutIsRepo, -} from "./ChatView.logic"; +import { recallCheckoutIsRepo, rememberCheckoutIsRepo } from "./ChatView.logic"; import { useLogicalProjectEnvironments } from "../hooks/useLogicalProjectEnvironments"; import { useStableCallback } from "../hooks/useStableCallback"; import { useProjectScriptEditing } from "./chat/useProjectScriptEditing"; @@ -74,7 +67,6 @@ import { type ServerProvider, type ScopedThreadRef, type ThreadId, - type RunId, ProviderInteractionMode, resolveIdleCompaction, RuntimeMode, @@ -405,11 +397,6 @@ type ChatViewProps = draftId: DraftId; }; -const EMPTY_HELD_TURN_DIFF_SUMMARIES: readonly never[] = []; -const noopHeldTurnDiff = (_turnId: RunId, _filePath?: string) => {}; -const noopHeldRevert = (_targetTurnCount: number) => {}; -const noopHeldAttachment = (_attachment: ChatFileAttachment) => {}; - export default function ChatView(props: ChatViewProps) { const { environmentId, @@ -1469,17 +1456,7 @@ export default function ChatView(props: ChatViewProps) { entry.kind === "message" ? [entry.message] : [], ); const timelineEmpty = timelineEntries.length === 0 && !hasStreamedTimelineRows; - const displayedTimeline = resolveThreadSwitchTimeline({ - loading: timelineEmpty && threadSyncPhase !== null, - activeThreadKey, - nextEntries: timelineEntries, - rememberedForActive: peekRememberedThreadTimeline(activeThreadKey), - }); - const displayedTimelineKey = displayedTimeline.displayThreadKey ?? routeThreadKey; - const paintOnlyDisplayedTimeline = isPaintOnlyThreadTimeline( - displayedTimeline.displayThreadKey, - activeThreadKey, - ); + const displayedTimelineKey = activeThreadKey ?? routeThreadKey; const displayedThreadRef = parseScopedThreadKey(displayedTimelineKey); const { worktreeSetup, @@ -1624,9 +1601,6 @@ export default function ChatView(props: ChatViewProps) { const activeProjectCwd = activeProject?.workspaceRoot ?? null; const activeThreadWorktreePath = activeThread?.worktreePath ?? null; const activeWorkspaceRoot = activeThreadWorktreePath ?? activeProjectCwd ?? undefined; - const heldPaintContext = paintOnlyDisplayedTimeline - ? peekHeldThreadTimeline() - : null; const activeTerminalLaunchContext = terminalUiLaunchContext?.threadId === activeThreadId ? terminalUiLaunchContext : null; const liveIsGitRepo = gitStatusQuery.data?.isRepo; @@ -2590,8 +2564,7 @@ export default function ChatView(props: ChatViewProps) { const timelineSkills = activeProviderStatus ? resolveProviderSkillsForCwd(activeProviderStatus, gitCwd) : EMPTY_PROVIDER_SKILLS; - const threadFindEnabled = - isServerThread && serverConfig?.threadFind === true && !paintOnlyDisplayedTimeline; + const threadFindEnabled = isServerThread && serverConfig?.threadFind === true; const isThreadFindActive = useThreadFindOpen(activeThreadRef, threadFindEnabled); useChatShortcuts({ @@ -2669,7 +2642,6 @@ export default function ChatView(props: ChatViewProps) { serverProjection, activeThread, timelineMessages, - paintOnlyDisplayedTimeline, phase, isConnecting, isSendBusy, @@ -3249,126 +3221,79 @@ export default function ChatView(props: ChatViewProps) { activeThreadKey={activeThreadKey} syncing={threadSyncPhase !== null} detailLoading={threadDetailLoading} - readyMarkdownCwd={gitCwd} - readyWorkspaceRoot={activeWorkspaceRoot ?? null} - citationRequest={paintOnlyDisplayedTimeline ? null : citationRequest} + citationRequest={citationRequest} citationHistory={citationHistory} - {...(!paintOnlyDisplayedTimeline - ? { - onCiteAssistantText: citeAssistantTextStable, - ...(activeProject ? { onRunShellCommand: runShellCommandStable } : {}), - } - : {})} - isWorking={!paintOnlyDisplayedTimeline && isWorking} + onCiteAssistantText={citeAssistantTextStable} + {...(activeProject ? { onRunShellCommand: runShellCommandStable } : {})} + isWorking={isWorking} runlessWorkActive={runlessWorkStartedAt !== null} - activeTurnInProgress={ - !paintOnlyDisplayedTimeline && (isWorking || !latestRunSettled) - } - isCompacting={!paintOnlyDisplayedTimeline && isCompacting} + activeTurnInProgress={isWorking || !latestRunSettled} + isCompacting={isCompacting} awaitingUser={ - paintOnlyDisplayedTimeline - ? null - : activePendingApproval !== null - ? "approval" - : activePendingUserInput !== null || - // A secret request has no runtime request; the shell carries it. - activeThreadShell?.hasPendingUserInput === true - ? "input" - : null + activePendingApproval !== null + ? "approval" + : activePendingUserInput !== null || + // A secret request has no runtime request; the shell carries it. + activeThreadShell?.hasPendingUserInput === true + ? "input" + : null } awaitingRequestId={ - paintOnlyDisplayedTimeline - ? null - : (activePendingApproval?.requestId ?? - activePendingUserInput?.requestId ?? - null) + activePendingApproval?.requestId ?? activePendingUserInput?.requestId ?? null } - activeTurnStartedAt={paintOnlyDisplayedTimeline ? null : activeWorkStartedAt} - worktreeSetup={paintOnlyDisplayedTimeline ? null : worktreeSetup} + activeTurnStartedAt={activeWorkStartedAt} + worktreeSetup={worktreeSetup} onCancelWorktreeSetup={onCancelWorktreeSetupStable} - {...(paintOnlyDisplayedTimeline - ? {} - : { - retryableWorkspacePreparationRunIds, - onRetryWorkspacePreparation: onRetryWorkspacePreparationStable, - })} + retryableWorkspacePreparationRunIds={retryableWorkspacePreparationRunIds} + onRetryWorkspacePreparation={onRetryWorkspacePreparationStable} {...(draftId ? { onWorktreeSetupWorkLocally: onWorktreeSetupWorkLocallyStable } : {})} {...(onOpenWorktreeSetupTerminal ? { onOpenWorktreeSetupTerminal } : {})} - isPreparingWorktree={!paintOnlyDisplayedTimeline && isPreparingWorktree} - footer={paintOnlyDisplayedTimeline ? null : timelineFooter} + isPreparingWorktree={isPreparingWorktree} + footer={timelineFooter} listRef={legendListRef} - runs={paintOnlyDisplayedTimeline ? [] : (serverProjection?.runs ?? [])} - latestRun={paintOnlyDisplayedTimeline ? null : activeActivityRun} - announcedRun={ - paintOnlyDisplayedTimeline - ? null - : announcedRun(activeActivityRun, serverProjection?.runs ?? []) - } - detailBehindShell={ - !paintOnlyDisplayedTimeline && - isDetailBehindShell(activeLatestRun, activeThreadShell?.latestRun ?? null) - } - runningRunId={paintOnlyDisplayedTimeline ? null : activeRunningTurnId} - turnDiffSummaries={ - paintOnlyDisplayedTimeline ? EMPTY_HELD_TURN_DIFF_SUMMARIES : turnDiffSummaries - } + runs={serverProjection?.runs ?? []} + latestRun={activeActivityRun} + announcedRun={announcedRun(activeActivityRun, serverProjection?.runs ?? [])} + detailBehindShell={isDetailBehindShell( + activeLatestRun, + activeThreadShell?.latestRun ?? null, + )} + runningRunId={activeRunningTurnId} + turnDiffSummaries={turnDiffSummaries} activeThreadEnvironmentId={ displayedThreadRef?.environmentId ?? activeThread.environmentId } routeThreadKey={displayedTimelineKey} displayThreadKey={displayedTimelineKey} - paintOnly={paintOnlyDisplayedTimeline} announceTurnStatus={!isProviderSubagent} - onOpenTurnDiff={ - paintOnlyDisplayedTimeline ? noopHeldTurnDiff : onOpenTurnDiffStable - } + onOpenTurnDiff={onOpenTurnDiffStable} onOpenThread={onOpenRelatedThreadStable} - parentThreadLink={paintOnlyDisplayedTimeline ? null : parentThreadLink} - workflowOpening={paintOnlyDisplayedTimeline ? null : workflowOpening} - onForkFromRun={paintOnlyDisplayedTimeline ? async () => {} : onForkFromRunStable} + parentThreadLink={parentThreadLink} + workflowOpening={workflowOpening} + onForkFromRun={onForkFromRunStable} onRollbackCheckpoint={onTimelineRollbackCheckpointStable} - supportsConversationRollback={ - !paintOnlyDisplayedTimeline && supportsConversationRollback - } + supportsConversationRollback={supportsConversationRollback} threadStartCheckpointReady={threadStartCheckpointReady} availableRevertTurnCounts={availableRevertTurnCounts} - onRevertToTurnCount={ - paintOnlyDisplayedTimeline ? noopHeldRevert : onRevertTimelineTurnStable - } - {...(!paintOnlyDisplayedTimeline - ? { - onUseArtifactTemplate: insertArtifactTemplateStable, - onSendAppMessage: sendAppMessageStable, - } - : {})} + onRevertToTurnCount={onRevertTimelineTurnStable} + onUseArtifactTemplate={insertArtifactTemplateStable} + onSendAppMessage={sendAppMessageStable} isRevertingCheckpoint={isRevertingCheckpoint} onImageExpand={onExpandTimelineImageStable} - onFileOpen={ - paintOnlyDisplayedTimeline ? noopHeldAttachment : openFileAttachmentStable - } - onFileDownload={ - paintOnlyDisplayedTimeline ? noopHeldAttachment : downloadFileAttachmentStable - } - markdownCwd={ - paintOnlyDisplayedTimeline - ? (heldPaintContext?.markdownCwd ?? undefined) - : (gitCwd ?? undefined) - } + onFileOpen={openFileAttachmentStable} + onFileDownload={downloadFileAttachmentStable} + markdownCwd={gitCwd ?? undefined} resolvedTheme={resolvedTheme} timestampFormat={timestampFormat} - workspaceRoot={ - paintOnlyDisplayedTimeline - ? (heldPaintContext?.workspaceRoot ?? undefined) - : activeWorkspaceRoot - } + workspaceRoot={activeWorkspaceRoot} skills={timelineSkills} - anchorMessageId={paintOnlyDisplayedTimeline ? null : timelineAnchorMessageId} + anchorMessageId={timelineAnchorMessageId} onAnchorReady={onTimelineAnchorReadyStable} onAnchorSizeChanged={onTimelineAnchorSizeChangedStable} contentInsetEndAdjustment={composerTimelineInset} - liveFollowEnabled={!paintOnlyDisplayedTimeline && timelineLiveFollowEnabled} + liveFollowEnabled={timelineLiveFollowEnabled} onIsAtEndChange={onIsAtEndChangeStable} onContentOverflowChange={setTimelineOverflows} onToolOutputCollapsedAtEnd={onToolOutputCollapsedAtEndStable} @@ -3377,7 +3302,7 @@ export default function ChatView(props: ChatViewProps) { hideEmptyPlaceholder={isDraftHeroState || threadDetailLoading} emptyPlaceholderInset={composerReservedHeight} topFadeEnabled={!hasTimelineTopBanner} - {...(paintOnlyDisplayedTimeline || threadHistoryControls === undefined + {...(threadHistoryControls === undefined ? {} : { historyControls: threadHistoryControls })} /> diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index e9b21061c47d7..fbfa67e61bf8e 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -231,7 +231,6 @@ interface MessagesTimelineProps { turnDiffSummaries: ReadonlyArray; routeThreadKey: string; displayThreadKey?: string; - paintOnly?: boolean; /** Off where another region already speaks the thread's status, like a subagent's bar. */ announceTurnStatus?: boolean; onOpenTurnDiff?: (runId: RunId, filePath?: string) => void; @@ -339,7 +338,6 @@ const ConversationTimeline = memo(function ConversationTimeline({ turnDiffSummaries, routeThreadKey, displayThreadKey, - paintOnly = false, announceTurnStatus = true, onOpenTurnDiff, onOpenThread, @@ -906,7 +904,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ if (restoringThreadPosition || state?.data !== rows) return; const isAtEnd = resolveTimelineIsAtEnd(state); const position = state.data.length ? resolveWorkGroupScrollAnchor(state) : undefined; - if (position && isAtEnd !== undefined && !paintOnly) { + if (position && isAtEnd !== undefined) { const index = state.indexByKey(position.rowId); const row = index === undefined ? undefined : state.elementAtIndex(index); const element = listRef.current?.getScrollableNode(); @@ -1075,7 +1073,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ // starts from a baseline instead of a fresh, silent region. const activityAnnouncer = ( , "timelineEntries"> & { /** Null until the thread's detail may load; see resolveThreadDetailRef. */ @@ -35,8 +33,6 @@ export function ThreadTimeline({ activeThreadKey: string | null; syncing: boolean; detailLoading: boolean; - readyMarkdownCwd: string | null; - readyWorkspaceRoot: string | null; }) { const visibleTurnItems = useThreadVisibleTurnItems(threadDetailRef); const serverEntries = useIncrementalTimelineEntries(activeThreadKey, { @@ -44,7 +40,7 @@ export function ThreadTimeline({ visibleTurnItems, }); const entries = draftEntries ?? serverEntries; - const displayed = resolveThreadSwitchTimeline({ + const displayedEntries = resolveThreadSwitchTimeline({ loading: entries.length === 0 && syncing, activeThreadKey, nextEntries: entries, @@ -54,12 +50,7 @@ export function ThreadTimeline({ if (detailLoading || entries.length === 0 || timelineHasEphemeralPreviewUrls(entries)) { return; } - rememberReadyThreadTimeline({ - threadKey: activeThreadKey, - entries, - markdownCwd: readyMarkdownCwd, - workspaceRoot: readyWorkspaceRoot, - }); - }, [activeThreadKey, detailLoading, entries, readyMarkdownCwd, readyWorkspaceRoot]); - return ; + rememberReadyThreadTimeline({ threadKey: activeThreadKey, entries }); + }, [activeThreadKey, detailLoading, entries]); + return ; } diff --git a/apps/web/src/components/chat/useTimelineRewind.ts b/apps/web/src/components/chat/useTimelineRewind.ts index 6c7aef0a75693..b222fc55ec46f 100644 --- a/apps/web/src/components/chat/useTimelineRewind.ts +++ b/apps/web/src/components/chat/useTimelineRewind.ts @@ -41,7 +41,6 @@ interface TimelineRewindInput { readonly serverProjection: ThreadStructure | null; readonly activeThread: EnvironmentThreadShell | undefined; readonly timelineMessages: ReadonlyArray; - readonly paintOnlyDisplayedTimeline: boolean; readonly phase: SessionPhase; readonly isConnecting: boolean; readonly isSendBusy: boolean; @@ -68,7 +67,6 @@ export function useTimelineRewind(input: TimelineRewindInput) { serverProjection, activeThread, timelineMessages, - paintOnlyDisplayedTimeline, phase, isConnecting, isSendBusy, @@ -270,7 +268,7 @@ export function useTimelineRewind(input: TimelineRewindInput) { readonly checkpointId: string; readonly scopeId: string; }) => { - if (!paintOnlyDisplayedTimeline) void onRollbackCheckpoint(input); + void onRollbackCheckpoint(input); }; const onTimelineRollbackCheckpointStable = useStableCallback(onTimelineRollbackCheckpoint); const onRevertTimelineTurn = (targetTurnCount: number, messageId: MessageId) => { From 401b01747c1f7b331fb00b573e405a38f646fde8 Mon Sep 17 00:00:00 2001 From: "t3-code[bot]" <269035359+t3-code[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 06:10:05 +0000 Subject: [PATCH 016/817] chore(release): prepare v0.1.3 --- apps/desktop/package.json | 2 +- apps/server/package.json | 2 +- apps/web/package.json | 2 +- packages/contracts/package.json | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/apps/desktop/package.json b/apps/desktop/package.json index f87fa20453f36..ad70e206af643 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@t3tools/desktop", - "version": "0.1.2", + "version": "0.1.3", "private": true, "type": "module", "main": "dist-electron/boot.cjs", diff --git a/apps/server/package.json b/apps/server/package.json index db581556a13e7..cf243b40c1071 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -1,6 +1,6 @@ { "name": "t3", - "version": "0.1.2", + "version": "0.1.3", "license": "MIT", "repository": { "type": "git", diff --git a/apps/web/package.json b/apps/web/package.json index 5ae86a8a75c62..9ab88beb3d7f5 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,6 +1,6 @@ { "name": "@t3tools/web", - "version": "0.1.2", + "version": "0.1.3", "private": true, "type": "module", "scripts": { diff --git a/packages/contracts/package.json b/packages/contracts/package.json index 6b5272917383c..c87a9fed41033 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -1,6 +1,6 @@ { "name": "@t3tools/contracts", - "version": "0.1.2", + "version": "0.1.3", "private": true, "files": [ "dist" From 0b02b21e5a451fa7e488a8596cedbeb0ddd9d63c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 26 Oct 2026 23:17:34 -0700 Subject: [PATCH 017/817] refactor(mobile): notifications, quick actions and Connect onboarding navigate through the root ref (#25769) Co-authored-by: Claude Opus 5.5 --- apps/mobile/src/App.tsx | 60 +++++-- apps/mobile/src/Stack.tsx | 18 ++- .../agent-awareness/notificationNavigation.ts | 68 ++++---- .../features/cloud/connectOnboarding.test.ts | 74 +++++++++ .../src/features/cloud/connectOnboarding.ts | 45 +++++- .../cloud/connectOnboardingNavigation.ts | 41 ----- .../features/cloud/connectOnboardingOptOut.ts | 4 +- .../features/home/home-route-visibility.ts | 74 +++++---- .../shortcuts/appShortcutsRuntime.test.ts | 70 ++++++++ .../features/shortcuts/appShortcutsRuntime.ts | 149 ++++++++++++++++++ .../src/features/shortcuts/useAppShortcuts.ts | 125 --------------- apps/mobile/src/lib/rootNavigation.test.ts | 52 +++++- apps/mobile/src/lib/rootNavigation.ts | 40 ++++- scripts/effect-budget.json | 1 - 14 files changed, 560 insertions(+), 261 deletions(-) create mode 100644 apps/mobile/src/features/cloud/connectOnboarding.test.ts delete mode 100644 apps/mobile/src/features/cloud/connectOnboardingNavigation.ts create mode 100644 apps/mobile/src/features/shortcuts/appShortcutsRuntime.test.ts create mode 100644 apps/mobile/src/features/shortcuts/appShortcutsRuntime.ts delete mode 100644 apps/mobile/src/features/shortcuts/useAppShortcuts.ts diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsx index 579aea37bfa4d..b7c054d9a64ac 100644 --- a/apps/mobile/src/App.tsx +++ b/apps/mobile/src/App.tsx @@ -9,9 +9,12 @@ import { GestureHandlerRootView } from "react-native-gesture-handler"; import { KeyboardProvider } from "react-native-keyboard-controller"; import { SafeAreaProvider } from "react-native-safe-area-context"; import { + CommonActions, + createPathConfigForStaticNavigation, createStaticNavigation, getActionFromState, getStateFromPath, + type NavigationAction, type NavigationState, } from "@react-navigation/native"; @@ -25,12 +28,20 @@ import { presentPendingIncomingShare, startIncomingShareInbox, } from "./features/sharing/IncomingShareProvider"; +import { + installAgentNotificationNavigation, + setAgentNotificationPathname, +} from "./features/agent-awareness/notificationNavigation"; +import { + installAppShortcuts, + recordAppShortcutNavigationState, +} from "./features/shortcuts/appShortcutsRuntime"; import { AppearancePreferencesProvider, installAppearanceRuntime, useAppearancePreferences, } from "./features/settings/appearance/AppearancePreferencesProvider"; -import { RootStack } from "./Stack"; +import { RootStack, workspaceLocationFromState } from "./Stack"; import { appAtomRegistry } from "./state/atom-registry"; import { subscribeComposerDraftModelReconciliation } from "./state/use-composer-drafts"; import { environmentThreadShells } from "./state/threads"; @@ -57,7 +68,12 @@ import { } from "./features/workspace/workspace-selection-store"; import { workspaceDetailLinkAction } from "./features/workspace/workspace-detail-selection"; import { NativeLayoutMetricsProvider } from "./native/native-layout-metrics"; -import { attachRootNavigation, rootNavigationRef } from "./lib/rootNavigation"; +import { + attachRootNavigation, + flushRootNavigationQueue, + linkToRootPath, + rootNavigationRef, +} from "./lib/rootNavigation"; import { pruneNewTaskBranchCheckouts } from "./features/threads/NewTaskDraftRouteScreen"; import "../global.css"; @@ -69,6 +85,20 @@ if (process.env.EXPO_PUBLIC_SHOWCASE === "1") { void SplashScreen.preventAutoHideAsync().catch(() => {}); void hydrateWorkspaceSelections(); +const linkingConfig = { + initialRouteName: "Home", + screens: createPathConfigForStaticNavigation(RootStack, { initialRouteName: "Home" }) ?? {}, +} as const; + +function getAppStateFromPath(path: string, options: Parameters[1]) { + return takeScheduledTaskNewLink( + restoreSettingsLinkState( + restoreDraftLinkState(getStateFromPath(path, options), path), + settingsLinkPage(), + ), + ); +} + const appLinking = { prefixes: [Linking.createURL("/"), "t3code://", "t3code-dev://", "t3code-preview://"], config: { initialRouteName: "Home" }, @@ -81,25 +111,33 @@ const appLinking = { // Our router handles the selection; React Navigation's type only lists its own actions. (workspaceDetailLinkAction(state) as ReturnType) ?? getActionFromState(state, options), - getStateFromPath: (path: string, options: Parameters[1]) => - takeScheduledTaskNewLink( - restoreSettingsLinkState( - restoreDraftLinkState(getStateFromPath(path, options), path), - settingsLinkPage(), - ), - ), + getStateFromPath: getAppStateFromPath, }; +function appLinkAction(href: string): NavigationAction { + const state = getAppStateFromPath(href, linkingConfig); + if (!state) throw new Error(`Failed to parse the href to a navigation state (${href}).`); + return appLinking.getActionFromState(state, linkingConfig) ?? CommonActions.reset(state); +} + +function linkToAppPath(href: string): void { + linkToRootPath(href, appLinkAction); +} + const Navigation = createStaticNavigation(RootStack); function handleNavigationStateChange(state: NavigationState | undefined): void { recordWorkspaceSelections(state); - if (state) pruneNewTaskBranchCheckouts(state); presentPendingIncomingShare(); + if (!state) return; + setAgentNotificationPathname(workspaceLocationFromState(state).pathname); + recordAppShortcutNavigationState(state); + pruneNewTaskBranchCheckouts(state); } function handleNavigationReady(): void { handleNavigationStateChange(rootNavigationRef.getRootState()); + flushRootNavigationQueue(); } declare const module: { readonly hot?: FoundationHotModule } | undefined; @@ -118,6 +156,8 @@ const appServiceDisposers = [ installThreadOutboxDelivery(), installComposerAttachmentUploads(), startIncomingShareInbox(), + installAgentNotificationNavigation(linkToAppPath), + installAppShortcuts(linkToAppPath), ]; disposeOnFoundationReplace(typeof module === "undefined" ? undefined : module.hot, () => { for (const dispose of appServiceDisposers) dispose(); diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index 7312807c55e48..396759a5f04b0 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -24,6 +24,11 @@ import { androidWorkspaceDestinationAnimation } from "./lib/android-workspace-na import { getCompactBrandHeaderOptions } from "./components/CompactBrandTitle"; import { WorkspaceConnectionStatusProvider } from "./features/home/WorkspaceConnectionTitle"; import { WorkspaceRootScreen } from "./features/workspace/WorkspaceRootScreen"; +import { + recordHomeFocus, + recordHomeTransitionEnd, + recordHomeTransitionStart, +} from "./features/home/home-route-visibility"; import { AndroidWorkspaceTabsProvider } from "./features/workspace/AndroidWorkspaceTabsProvider"; import { PullRequestRouteScreen, @@ -41,9 +46,7 @@ import { type RenderFailureProps, } from "./components/RenderErrorBoundary"; import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRouteScreen"; -import { useAgentNotificationNavigation } from "./features/agent-awareness/notificationNavigation"; import { ConnectOnboardingRouteScreen } from "./features/cloud/ConnectOnboardingRouteScreen"; -import { useConnectOnboardingNavigation } from "./features/cloud/connectOnboardingNavigation"; import { AttachmentFileScreen } from "./features/files/AttachmentFileScreen"; import { ThreadFilesTreeScreen, ThreadFileScreen } from "./features/files/ThreadFilesRouteScreen"; import { AdaptiveWorkspaceLayout } from "./features/layout/AdaptiveWorkspaceLayout"; @@ -138,7 +141,6 @@ import { SettingsLegalDocumentCloseHeaderButton, SettingsLegalDocumentExternalHeaderButton, } from "./features/settings/components/SettingsLegalDocumentRouteScreen"; -import { useAppShortcuts } from "./features/shortcuts/useAppShortcuts"; import { NATIVE_LIQUID_GLASS_SUPPORTED } from "./native/native-glass"; import { deriveLayout } from "./lib/layout"; import { useNativeLayoutMetrics } from "./native/native-layout-metrics"; @@ -473,7 +475,7 @@ const SETTINGS_SCREENS = { // iOS 26 header morphing requires one UINavigationBar; nested stacks make the whole screen slide. const THREAD_LINKING_PREFIX = "threads/:environmentId/:threadId"; -function workspaceLocationFromState(state: NavigationState) { +export function workspaceLocationFromState(state: NavigationState) { const routes = state.routes.filter((route) => !isWorkspaceOverlayRoute(route.name)); const effectiveState = routes.length > 0 && routes.length !== state.routes.length @@ -505,9 +507,6 @@ function RootStackLayout(props: { const routeDraftId = Array.isArray(draftParams?.draftId) ? draftParams.draftId[0] : draftParams?.draftId; - useAgentNotificationNavigation(workspaceLocation.pathname); - useConnectOnboardingNavigation(); - useAppShortcuts(props.state); return ( @@ -592,6 +591,11 @@ const RootStackConfig = createWorkspaceStackNavigator({ Home: createNativeStackScreen({ screen: WorkspaceRootScreen, linking: "", + listeners: { + transitionStart: ({ data }) => recordHomeTransitionStart(data.closing), + transitionEnd: ({ data }) => recordHomeTransitionEnd(data.closing), + focus: recordHomeFocus, + }, options: { ...GLASS_HEADER_OPTIONS, ...FIXED_DUO_HEADER, diff --git a/apps/mobile/src/features/agent-awareness/notificationNavigation.ts b/apps/mobile/src/features/agent-awareness/notificationNavigation.ts index 83de9054a1e7e..7d2317e58baae 100644 --- a/apps/mobile/src/features/agent-awareness/notificationNavigation.ts +++ b/apps/mobile/src/features/agent-awareness/notificationNavigation.ts @@ -1,50 +1,42 @@ -import { useEffect, useLayoutEffect, useRef } from "react"; import * as Notifications from "expo-notifications"; -import { useLinkTo } from "@react-navigation/native"; import { setAndroidThreadOnScreen } from "./androidNotifications"; import { foregroundNotificationBehavior } from "./foregroundNotificationBehavior"; import { routeAgentNotificationResponseOnce, threadDeepLinkOnScreen } from "./notificationPayload"; import { consumeLastAgentNotificationResponse } from "./notificationResponseConsumer"; -export function useAgentNotificationNavigation(pathname: string): void { - const linkTo = useLinkTo(); - const handledResponseIds = useRef(new Set()); - const deepLinkOnScreen = useRef(null); - useLayoutEffect(() => { - const thread = threadDeepLinkOnScreen(pathname); - deepLinkOnScreen.current = thread; - setAndroidThreadOnScreen(thread); - }, [pathname]); +let deepLinkOnScreen: string | null = null; - useEffect(() => { - Notifications.setNotificationHandler({ - handleNotification: (notification) => - Promise.resolve(foregroundNotificationBehavior(notification, deepLinkOnScreen.current)), - }); - return () => { - Notifications.setNotificationHandler(null); - }; - }, []); +/** Called with the workspace pathname on every root navigation state change. */ +export function setAgentNotificationPathname(pathname: string): void { + deepLinkOnScreen = threadDeepLinkOnScreen(pathname); + setAndroidThreadOnScreen(deepLinkOnScreen); +} - useEffect(() => { - const handleResponse = (response: Notifications.NotificationResponse): void => { - routeAgentNotificationResponseOnce({ - handledResponseIds: handledResponseIds.current, - response, - navigate: linkTo, - }); - }; +/** + * App-lifetime notification routing: foreground presentation suppresses the + * thread already on screen, and taps (including the cold-start tap) open the + * notification's deep link through `navigate`. + */ +export function installAgentNotificationNavigation(navigate: (href: string) => void): () => void { + const handledResponseIds = new Set(); + Notifications.setNotificationHandler({ + handleNotification: (notification) => + Promise.resolve(foregroundNotificationBehavior(notification, deepLinkOnScreen)), + }); - const subscription = Notifications.addNotificationResponseReceivedListener(handleResponse); - void consumeLastAgentNotificationResponse({ - getLastResponse: () => Notifications.getLastNotificationResponseAsync(), - clearLastResponse: () => Notifications.clearLastNotificationResponseAsync(), - handleResponse, - }); + const handleResponse = (response: Notifications.NotificationResponse): void => { + routeAgentNotificationResponseOnce({ handledResponseIds, response, navigate }); + }; + const subscription = Notifications.addNotificationResponseReceivedListener(handleResponse); + void consumeLastAgentNotificationResponse({ + getLastResponse: () => Notifications.getLastNotificationResponseAsync(), + clearLastResponse: () => Notifications.clearLastNotificationResponseAsync(), + handleResponse, + }); - return () => { - subscription.remove(); - }; - }, [linkTo]); + return () => { + subscription.remove(); + Notifications.setNotificationHandler(null); + }; } diff --git a/apps/mobile/src/features/cloud/connectOnboarding.test.ts b/apps/mobile/src/features/cloud/connectOnboarding.test.ts new file mode 100644 index 0000000000000..d79254c9e8148 --- /dev/null +++ b/apps/mobile/src/features/cloud/connectOnboarding.test.ts @@ -0,0 +1,74 @@ +import { afterEach, describe, expect, it, vi } from "vite-plus/test"; + +const navigation = vi.hoisted(() => ({ + navigate: vi.fn(), + ready: true, + queue: [] as Array<() => void>, +})); +const optOut = vi.hoisted(() => ({ optedOut: new Set() })); + +vi.mock("../../lib/rootNavigation", () => ({ + rootNavigationRef: navigation, + whenRootNavigationReady: (navigate: () => void) => + navigation.ready ? navigate() : navigation.queue.push(navigate), +})); +vi.mock("./connectOnboardingOptOut", () => ({ + isConnectOnboardingOptedOut: (accountId: string) => + Promise.resolve(optOut.optedOut.has(accountId)), +})); + +import { clearConnectOnboardingRequest, requestConnectOnboarding } from "./connectOnboarding"; + +afterEach(() => { + clearConnectOnboardingRequest(); + optOut.optedOut.clear(); + navigation.navigate.mockReset(); + navigation.ready = true; + navigation.queue.length = 0; + vi.useRealTimers(); +}); + +describe("requestConnectOnboarding", () => { + it("presents the sheet after the settle delay", async () => { + vi.useFakeTimers(); + requestConnectOnboarding("account-1"); + await vi.advanceTimersByTimeAsync(599); + expect(navigation.navigate).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1); + expect(navigation.navigate).toHaveBeenCalledExactlyOnceWith("ConnectOnboarding"); + }); + + it("drops a request cleared by sign-out before it fires", async () => { + vi.useFakeTimers(); + requestConnectOnboarding("account-1"); + clearConnectOnboardingRequest(); + await vi.runAllTimersAsync(); + expect(navigation.navigate).not.toHaveBeenCalled(); + }); + + it("skips accounts that opted out", async () => { + vi.useFakeTimers(); + optOut.optedOut.add("account-1"); + requestConnectOnboarding("account-1"); + await vi.runAllTimersAsync(); + expect(navigation.navigate).not.toHaveBeenCalled(); + }); + + it("presents once when a newer request replaces a pending one", async () => { + vi.useFakeTimers(); + requestConnectOnboarding("account-1"); + requestConnectOnboarding("account-2"); + await vi.runAllTimersAsync(); + expect(navigation.navigate).toHaveBeenCalledOnce(); + }); + + it("drops a request cleared while it waits for navigation to be ready", async () => { + vi.useFakeTimers(); + navigation.ready = false; + requestConnectOnboarding("account-1"); + await vi.runAllTimersAsync(); + clearConnectOnboardingRequest(); + for (const navigate of navigation.queue.splice(0)) navigate(); + expect(navigation.navigate).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/mobile/src/features/cloud/connectOnboarding.ts b/apps/mobile/src/features/cloud/connectOnboarding.ts index c324b700942fe..1be4cee1e201d 100644 --- a/apps/mobile/src/features/cloud/connectOnboarding.ts +++ b/apps/mobile/src/features/cloud/connectOnboarding.ts @@ -1,17 +1,46 @@ -import { Atom } from "effect/reactivity"; +import { rootNavigationRef, whenRootNavigationReady } from "../../lib/rootNavigation"; +import { isConnectOnboardingOptedOut } from "./connectOnboardingOptOut"; -import { appAtomRegistry } from "../../state/atom-registry"; +// Sign-in happens in its own modal; give its session-state transition a beat to +// settle before presenting another formSheet on top. +const PRESENT_ONBOARDING_DELAY_MS = 600; + +interface PendingRequest { + readonly accountId: string; + readonly timer: ReturnType; +} // Retain the account id so sign-out cannot present onboarding for the wrong account. -export const connectOnboardingRequestAtom = Atom.make(null).pipe( - Atom.keepAlive, - Atom.withLabel("mobile:connect-onboarding-request"), -); +let pending: PendingRequest | null = null; export function requestConnectOnboarding(accountId: string): void { - appAtomRegistry.set(connectOnboardingRequestAtom, accountId); + clearConnectOnboardingRequest(); + const request: PendingRequest = { + accountId, + timer: setTimeout(() => { + void (async () => { + const optedOut = await isConnectOnboardingOptedOut(accountId).catch(() => false); + // A sign-out or a newer sign-in may have replaced this request while + // the opt-out read was in flight. + if (pending !== request) return; + if (optedOut) { + pending = null; + return; + } + // Stays pending until navigation is ready, so a sign-out meanwhile still cancels it. + whenRootNavigationReady(() => { + if (pending !== request) return; + pending = null; + rootNavigationRef.navigate("ConnectOnboarding"); + }); + })(); + }, PRESENT_ONBOARDING_DELAY_MS), + }; + pending = request; } export function clearConnectOnboardingRequest(): void { - appAtomRegistry.set(connectOnboardingRequestAtom, null); + if (pending === null) return; + clearTimeout(pending.timer); + pending = null; } diff --git a/apps/mobile/src/features/cloud/connectOnboardingNavigation.ts b/apps/mobile/src/features/cloud/connectOnboardingNavigation.ts deleted file mode 100644 index 5176dc797f65b..0000000000000 --- a/apps/mobile/src/features/cloud/connectOnboardingNavigation.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { useAtomValue } from "@effect/atom-react"; -import { useNavigation } from "@react-navigation/native"; -import { useEffect } from "react"; - -import { appAtomRegistry } from "../../state/atom-registry"; -import { clearConnectOnboardingRequest, connectOnboardingRequestAtom } from "./connectOnboarding"; -import { isConnectOnboardingOptedOut } from "./connectOnboardingOptOut"; - -// Sign-in happens in its own modal; give its session-state transition a beat to -// settle before presenting another formSheet on top. -const PRESENT_ONBOARDING_DELAY_MS = 600; - -/** Keep @react-navigation out of non-navigation consumers' import graphs. */ -export function useConnectOnboardingNavigation(): void { - const navigation = useNavigation(); - const requestedAccountId = useAtomValue(connectOnboardingRequestAtom); - - useEffect(() => { - if (requestedAccountId === null) { - return; - } - let cancelled = false; - const timer = setTimeout(() => { - void (async () => { - const optedOut = await isConnectOnboardingOptedOut(requestedAccountId).catch(() => false); - // Re-check the request atom: sign-out can clear it before this render commits. - if (cancelled || appAtomRegistry.get(connectOnboardingRequestAtom) !== requestedAccountId) { - return; - } - clearConnectOnboardingRequest(); - if (!optedOut) { - navigation.navigate("ConnectOnboarding"); - } - })(); - }, PRESENT_ONBOARDING_DELAY_MS); - return () => { - cancelled = true; - clearTimeout(timer); - }; - }, [navigation, requestedAccountId]); -} diff --git a/apps/mobile/src/features/cloud/connectOnboardingOptOut.ts b/apps/mobile/src/features/cloud/connectOnboardingOptOut.ts index 5bf1a52f6e3d8..ac32844cd9383 100644 --- a/apps/mobile/src/features/cloud/connectOnboardingOptOut.ts +++ b/apps/mobile/src/features/cloud/connectOnboardingOptOut.ts @@ -1,6 +1,8 @@ import { loadPreferences, updatePreferences } from "../../persistence/imperative"; -// Keep persistence out of CloudAuthProvider's import graph; it breaks suite loading. +// Lives apart from connectOnboarding.ts so cloudAccountService.ts (which +// imports the request signal) never pulls the persistence adapter into its +// module graph; that breaks CloudAuthProvider.test.ts suite loading. export async function isConnectOnboardingOptedOut(accountId: string): Promise { const preferences = await loadPreferences(); diff --git a/apps/mobile/src/features/home/home-route-visibility.ts b/apps/mobile/src/features/home/home-route-visibility.ts index 98f53a6c3aec0..5413ea1b1b0d4 100644 --- a/apps/mobile/src/features/home/home-route-visibility.ts +++ b/apps/mobile/src/features/home/home-route-visibility.ts @@ -1,41 +1,59 @@ import { RegistryContext } from "@effect/atom-react"; import { useNavigation } from "@react-navigation/native"; -import type { NativeStackNavigationProp } from "@react-navigation/native-stack"; -import { useCallback, useContext, useEffect, useRef, useState, useSyncExternalStore } from "react"; +import { useContext, useRef, useSyncExternalStore } from "react"; import type { Atom } from "effect/reactivity"; -/** Fabric never freezes the route below focus; Home must stop its own work beneath Thread. */ +/** + * Home stays mounted under a pushed Thread, and native-stack never freezes the + * route directly below the focused one on Fabric, so Home has to stop its own + * work. The Home screen's static `listeners` (Stack.tsx) drive this store. + */ +let homeVisible: boolean | null = null; +const visibilityListeners = new Set<() => void>(); + +function setHomeVisible(next: boolean) { + if (next === homeVisible) return; + homeVisible = next; + for (const listener of visibilityListeners) listener(); +} + +function subscribeHomeVisibility(onChange: () => void) { + visibilityListeners.add(onChange); + return () => { + visibilityListeners.delete(onChange); + // The value describes one Home instance. A later Home can mount under a + // Thread with no event of its own (Android activity replacement, a cold + // deep link), so it must fall back to `isFocused()` instead of this one. + if (visibilityListeners.size === 0) homeVisible = null; + }; +} + +export function recordHomeTransitionStart(closing: boolean): void { + if (!closing) setHomeVisible(true); +} + +export function recordHomeTransitionEnd(closing: boolean): void { + if (closing) setHomeVisible(false); +} + +/** Popping a sheet or a deep-linked route above Home has no appear event. */ +export function recordHomeFocus(): void { + setHomeVisible(true); +} + export function useHomeRouteVisible(): boolean { - const navigation = - useNavigation>(); - // A cold deep link mounts Home under its Thread without ever showing it. - const [visible, setVisible] = useState(() => navigation.isFocused()); - useEffect(() => { - const show = () => setVisible(true); - const removeTransitionStart = navigation.addListener("transitionStart", ({ data }) => { - if (!data.closing) show(); - }); - const removeTransitionEnd = navigation.addListener("transitionEnd", ({ data }) => { - if (data.closing) setVisible(false); - }); - // Popping a sheet or a deep-linked route above Home has no appear event. - const removeFocus = navigation.addListener("focus", show); - return () => { - removeTransitionStart(); - removeTransitionEnd(); - removeFocus(); - }; - }, [navigation]); - return visible; + const navigation = useNavigation(); + const visible = useSyncExternalStore(subscribeHomeVisibility, () => homeVisible); + // Before Home's first navigation event: a cold deep link mounts Home under + // its Thread without ever showing it. + return visible ?? navigation.isFocused(); } export function useAtomValueWhileVisible
(atom: Atom.Atom, visible: boolean): A { const registry = useContext(RegistryContext); const held = useRef<{ readonly value: A } | null>(null); - const subscribe = useCallback( - (onChange: () => void) => (visible ? registry.subscribe(atom, onChange) : () => undefined), - [registry, atom, visible], - ); + const subscribe = (onChange: () => void) => + visible ? registry.subscribe(atom, onChange) : () => undefined; return useSyncExternalStore(subscribe, () => { if (visible || held.current === null) held.current = { value: registry.get(atom) }; return held.current.value; diff --git a/apps/mobile/src/features/shortcuts/appShortcutsRuntime.test.ts b/apps/mobile/src/features/shortcuts/appShortcutsRuntime.test.ts new file mode 100644 index 0000000000000..c985506480b76 --- /dev/null +++ b/apps/mobile/src/features/shortcuts/appShortcutsRuntime.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, it, vi } from "vite-plus/test"; + +vi.mock("expo-quick-actions", () => ({})); +vi.mock("react-native", () => ({ Platform: { OS: "android" } })); +vi.mock("../../persistence/imperative", () => ({})); +vi.mock("../../state/atom-registry", () => ({})); +vi.mock("../../state/threads", () => ({ environmentThreadShells: {} })); +vi.mock("./appShortcuts", async () => { + const { withRecentThreadShortcut } = + await vi.importActual("./appShortcuts"); + return { withRecentThreadShortcut }; +}); + +import type { RecentThreadShortcut } from "../../persistence/imperative"; +import { createRecentThreadShortcuts } from "./appShortcutsRuntime"; + +const thread = (threadId: string, title = threadId): RecentThreadShortcut => ({ + environmentId: "env", + threadId, + title, +}); + +function setup(load: () => Promise>) { + const save = vi.fn<(list: ReadonlyArray) => Promise>(() => + Promise.resolve(), + ); + const publish = vi.fn<(list: ReadonlyArray) => Promise>(() => + Promise.resolve(), + ); + return { save, publish, recents: createRecentThreadShortcuts({ load, save, publish }) }; +} + +describe("createRecentThreadShortcuts", () => { + it("waits for the persisted list before recording the open thread", async () => { + const { save, publish, recents } = setup(() => Promise.resolve([thread("old")])); + recents.recordActiveThread(thread("new")); + expect(publish).not.toHaveBeenCalled(); + await recents.loaded; + await recents.saved(); + expect(publish).toHaveBeenLastCalledWith([thread("new"), thread("old")]); + expect(save).toHaveBeenLastCalledWith([thread("new"), thread("old")]); + }); + + it("does not persist the empty fallback after a failed load", async () => { + using _warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); + const { save, publish, recents } = setup(() => Promise.reject(new Error("read failed"))); + await recents.loaded; + await recents.saved(); + expect(publish).toHaveBeenLastCalledWith([]); + expect(save).not.toHaveBeenCalled(); + + recents.recordActiveThread(thread("a")); + await recents.saved(); + expect(save).toHaveBeenLastCalledWith([thread("a")]); + }); + + it("records title changes of the open thread and ignores repeats", async () => { + const { publish, recents } = setup(() => Promise.resolve([])); + await recents.loaded; + recents.recordActiveThread(thread("a", "")); + recents.recordActiveThread(thread("a", "Named")); + recents.recordActiveThread(thread("a", "Named")); + recents.recordActiveThread(null); + expect(publish.mock.calls.map(([list]) => list)).toEqual([ + [], + [thread("a", "")], + [thread("a", "Named")], + ]); + }); +}); diff --git a/apps/mobile/src/features/shortcuts/appShortcutsRuntime.ts b/apps/mobile/src/features/shortcuts/appShortcutsRuntime.ts new file mode 100644 index 0000000000000..b182c33b07866 --- /dev/null +++ b/apps/mobile/src/features/shortcuts/appShortcutsRuntime.ts @@ -0,0 +1,149 @@ +import * as QuickActions from "expo-quick-actions"; +import { Platform } from "react-native"; +import type { NavigationState } from "@react-navigation/native"; +import type { ScopedThreadRef } from "@t3tools/contracts"; +import { Atom } from "effect/reactivity"; + +import { + loadRecentThreadShortcuts, + saveRecentThreadShortcuts, + type RecentThreadShortcut, +} from "../../persistence/imperative"; +import { appAtomRegistry } from "../../state/atom-registry"; +import { environmentThreadShells } from "../../state/threads"; +import { + activeThreadRef, + buildShortcutActions, + shortcutHref, + withRecentThreadShortcut, +} from "./appShortcuts"; + +export interface RecentThreadShortcutsDependencies { + readonly load: () => Promise>; + readonly save: (recents: ReadonlyArray) => Promise; + readonly publish: (recents: ReadonlyArray) => Promise; +} + +/** + * Keeps the launcher's recent-thread list. Recording waits for the persisted + * list so the first thread opened after a cold start cannot clobber older + * entries, and a failed load never persists its empty fallback over valid + * history until a real thread open makes the in-memory list the new truth. + */ +export function createRecentThreadShortcuts(dependencies: RecentThreadShortcutsDependencies) { + let recents: ReadonlyArray | null = null; + let persistable = false; + let active: RecentThreadShortcut | null = null; + // Serialize saves so older lists cannot overwrite newer ones. + let saveQueue: Promise = Promise.resolve(); + + const commit = (next: ReadonlyArray) => { + recents = next; + if (persistable) { + saveQueue = saveQueue.then( + () => + dependencies.save(next).catch((error: unknown) => { + console.warn("[app-shortcuts] failed to persist recent threads", error); + }), + () => undefined, + ); + } + void dependencies.publish(next).catch((error: unknown) => { + console.warn("[app-shortcuts] failed to update launcher shortcuts", error); + }); + }; + + const withActive = (list: ReadonlyArray) => { + if (active === null) return list; + const next = withRecentThreadShortcut(list, active); + if (next !== list) persistable = true; + return next; + }; + + const loaded = dependencies.load().then( + (threads) => { + persistable = true; + commit(withActive(threads)); + }, + (error: unknown) => { + console.warn("[app-shortcuts] failed to load recent threads", error); + commit(withActive([])); + }, + ); + + return { + loaded, + /** Resolves once every save issued so far has finished. */ + saved: () => saveQueue, + recordActiveThread(next: RecentThreadShortcut | null): void { + active = next; + if (recents === null || next === null) return; + const updated = withActive(recents); + if (updated !== recents) commit(updated); + }, + }; +} + +const activeThreadRefAtom = Atom.make(null).pipe( + Atom.keepAlive, + Atom.withLabel("mobile:app-shortcuts-active-thread-ref"), +); + +const activeThreadShortcutAtom = Atom.make((get): RecentThreadShortcut | null => { + const ref = get(activeThreadRefAtom); + if (ref === null) return null; + const title = get(environmentThreadShells.threadShellAtom(ref))?.title ?? ""; + return { environmentId: ref.environmentId, threadId: ref.threadId, title }; +}).pipe( + Atom.withEquality( + (left: RecentThreadShortcut | null, right: RecentThreadShortcut | null) => + left === right || + (left !== null && + right !== null && + left.environmentId === right.environmentId && + left.threadId === right.threadId && + left.title === right.title), + ), +); + +/** Wired to the root navigation container's state changes. */ +export function recordAppShortcutNavigationState(state: NavigationState): void { + // Launcher shortcuts are Android-only; iOS never subscribes to thread shells. + if (Platform.OS !== "android") return; + const next = activeThreadRef(state); + const current = appAtomRegistry.get(activeThreadRefAtom); + if (next?.environmentId === current?.environmentId && next?.threadId === current?.threadId) { + return; + } + appAtomRegistry.set(activeThreadRefAtom, next); +} + +/** + * App-lifetime quick actions. `navigate` must queue until navigation is ready: + * a cold-start shortcut arrives as the launch action, and pushing it over the + * initial Home route makes back return home instead of exiting the app. + */ +export function installAppShortcuts(navigate: (href: string) => void): () => void { + const initialHref = QuickActions.initial ? shortcutHref(QuickActions.initial) : null; + if (initialHref !== null) navigate(initialHref); + const subscription = QuickActions.addListener((action) => { + const href = shortcutHref(action); + if (href !== null) navigate(href); + }); + if (Platform.OS !== "android") return () => subscription.remove(); + + const recents = createRecentThreadShortcuts({ + load: loadRecentThreadShortcuts, + save: saveRecentThreadShortcuts, + publish: (list) => QuickActions.setItems(buildShortcutActions(list)), + }); + const unsubscribe = appAtomRegistry.subscribe( + activeThreadShortcutAtom, + (active) => recents.recordActiveThread(active), + { immediate: true }, + ); + return () => { + subscription.remove(); + unsubscribe(); + }; +} diff --git a/apps/mobile/src/features/shortcuts/useAppShortcuts.ts b/apps/mobile/src/features/shortcuts/useAppShortcuts.ts deleted file mode 100644 index 677dd8110dee9..0000000000000 --- a/apps/mobile/src/features/shortcuts/useAppShortcuts.ts +++ /dev/null @@ -1,125 +0,0 @@ -import * as QuickActions from "expo-quick-actions"; -import { useEffect, useMemo, useRef, useState } from "react"; -import { Platform } from "react-native"; -import { useLinkTo, type NavigationState } from "@react-navigation/native"; - -import { - loadRecentThreadShortcuts, - saveRecentThreadShortcuts, - type RecentThreadShortcut, -} from "../../persistence/imperative"; -import { useThreadShell } from "../../state/entities"; -import { - activeThreadRef, - buildShortcutActions, - shortcutHref, - withRecentThreadShortcut, -} from "./appShortcuts"; - -export function useAppShortcuts(state: NavigationState): void { - useShortcutNavigation(); - useRecentThreadShortcutSync(state); -} - -function useShortcutNavigation(): void { - const linkTo = useLinkTo(); - const handledInitialAction = useRef(false); - - useEffect(() => { - // Handle the launch action before listeners; push over Home so Back returns there. - if (!handledInitialAction.current) { - handledInitialAction.current = true; - const initialHref = QuickActions.initial ? shortcutHref(QuickActions.initial) : null; - if (initialHref !== null) { - linkTo(initialHref); - } - } - - const subscription = QuickActions.addListener((action) => { - const href = shortcutHref(action); - if (href !== null) { - linkTo(href); - } - }); - return () => subscription.remove(); - }, [linkTo]); -} - -function useRecentThreadShortcutSync(state: NavigationState): void { - // iOS subscriptions for Android-only shortcuts would re-render every screen on active-thread updates. - const threadRef = useMemo( - () => (Platform.OS === "android" ? activeThreadRef(state) : null), - [state], - ); - const threadShell = useThreadShell(threadRef); - // Wait for persisted recents before recording visits, or cold starts overwrite older entries. - const [recents, setRecents] = useState | null>(null); - // Do not persist failed-load fallbacks; only a real visit makes the list authoritative. - const persistableRef = useRef(false); - // Serialize saves so older lists cannot overwrite newer ones. - const saveQueueRef = useRef>(Promise.resolve()); - - useEffect(() => { - if (Platform.OS !== "android") { - return; - } - - let cancelled = false; - void loadRecentThreadShortcuts() - .then((threads) => { - if (!cancelled) { - persistableRef.current = true; - setRecents(threads); - } - }) - .catch((error) => { - console.warn("[app-shortcuts] failed to load recent threads", error); - if (!cancelled) { - setRecents([]); - } - }); - return () => { - cancelled = true; - }; - }, []); - - const loaded = recents !== null; - const environmentId = threadRef?.environmentId ?? null; - const threadId = threadRef?.threadId ?? null; - const title = threadShell?.title ?? ""; - useEffect(() => { - if (!loaded || environmentId === null || threadId === null) { - return; - } - - setRecents((current) => { - if (current === null) { - return current; - } - const next = withRecentThreadShortcut(current, { environmentId, threadId, title }); - if (next !== current) { - persistableRef.current = true; - } - return next; - }); - }, [loaded, environmentId, threadId, title]); - - useEffect(() => { - if (recents === null) { - return; - } - - if (persistableRef.current) { - saveQueueRef.current = saveQueueRef.current.then( - () => - saveRecentThreadShortcuts(recents).catch((error) => { - console.warn("[app-shortcuts] failed to persist recent threads", error); - }), - () => undefined, - ); - } - void QuickActions.setItems(buildShortcutActions(recents)).catch((error) => { - console.warn("[app-shortcuts] failed to update launcher shortcuts", error); - }); - }, [recents]); -} diff --git a/apps/mobile/src/lib/rootNavigation.test.ts b/apps/mobile/src/lib/rootNavigation.test.ts index af1fff8c1c7cb..df470fab04e78 100644 --- a/apps/mobile/src/lib/rootNavigation.test.ts +++ b/apps/mobile/src/lib/rootNavigation.test.ts @@ -7,10 +7,21 @@ vi.mock("@react-navigation/native", () => ({ isReady() { return this.current?.isReady() ?? false; }, + dispatched: [] as Array, + dispatch(action: unknown) { + this.dispatched.push(action); + }, + getRootState: () => ({ key: "root" }), }), })); -const { attachRootNavigation, rootNavigationRef } = await import("./rootNavigation"); +const { + attachRootNavigation, + flushRootNavigationQueue, + linkToRootPath, + rootNavigationRef, + whenRootNavigationReady, +} = await import("./rootNavigation"); function fakeContainer() { return { isReady: () => true } as NavigationContainerRef; @@ -29,3 +40,42 @@ it("keeps the newer container when an older root unmounts after it attached", () detachCurrent(); expect(rootNavigationRef.current).toBeNull(); }); + +it("holds navigation until the container is ready, then runs it once", () => { + const navigate = vi.fn(); + const failing = vi.fn(() => { + throw new Error("unknown route"); + }); + const logged = vi.spyOn(console, "error").mockImplementation(() => undefined); + whenRootNavigationReady(failing); + whenRootNavigationReady(navigate); + expect(navigate).not.toHaveBeenCalled(); + + const detach = attachRootNavigation(fakeContainer()); + flushRootNavigationQueue(); + flushRootNavigationQueue(); + expect(failing).toHaveBeenCalledOnce(); + expect(navigate).toHaveBeenCalledOnce(); + expect(logged).toHaveBeenCalledOnce(); + + whenRootNavigationReady(navigate); + expect(navigate).toHaveBeenCalledTimes(2); + detach(); + logged.mockRestore(); +}); + +it("rejects an href without a leading slash, as useLinkTo does", () => { + const toAction = vi.fn(() => ({ type: "NAVIGATE" })); + const detach = attachRootNavigation(fakeContainer()); + const { dispatched } = rootNavigationRef as unknown as { dispatched: Array }; + + expect(() => linkToRootPath("threads/env/t1", toAction)).toThrow( + "The href must start with '/' (threads/env/t1).", + ); + expect(toAction).not.toHaveBeenCalled(); + + linkToRootPath("/threads/env/t1", toAction); + expect(toAction).toHaveBeenCalledExactlyOnceWith("/threads/env/t1"); + expect(dispatched).toEqual([{ target: "root", type: "NAVIGATE" }]); + detach(); +}); diff --git a/apps/mobile/src/lib/rootNavigation.ts b/apps/mobile/src/lib/rootNavigation.ts index 3f064f9301f3a..ec2bd3f5f98dc 100644 --- a/apps/mobile/src/lib/rootNavigation.ts +++ b/apps/mobile/src/lib/rootNavigation.ts @@ -1,11 +1,13 @@ import { createNavigationContainerRef, + type NavigationAction, type NavigationContainerRef, } from "@react-navigation/native"; /** * The app's single navigation container. Work that outlives a screen (a draft - * route's branch checkout) navigates through it. + * route's branch checkout, notification taps, quick actions, Connect + * onboarding) navigates through it instead of mounting hooks in the navigator. */ export const rootNavigationRef = createNavigationContainerRef(); @@ -22,3 +24,39 @@ export function attachRootNavigation( if (rootNavigationRef.current === navigation) rootNavigationRef.current = null; }; } + +const pendingUntilReady: Array<() => void> = []; + +/** Runs `navigate` now if the container is ready, otherwise once it becomes ready. */ +export function whenRootNavigationReady(navigate: () => void): void { + if (rootNavigationRef.isReady()) { + navigate(); + return; + } + pendingUntilReady.push(navigate); +} + +/** Wired to the container's `onReady`. */ +export function flushRootNavigationQueue(): void { + for (const navigate of pendingUntilReady.splice(0)) { + try { + navigate(); + } catch (error) { + console.error("[navigation] queued navigation failed", error); + } + } +} + +/** + * `useLinkTo` for app services that live outside the navigator: the same + * leading-'/' guard, then the href's action dispatched at the root once ready. + */ +export function linkToRootPath(href: string, toAction: (href: string) => NavigationAction): void { + if (!href.startsWith("/")) throw new Error(`The href must start with '/' (${href}).`); + whenRootNavigationReady(() => { + rootNavigationRef.dispatch({ + target: rootNavigationRef.getRootState()?.key, + ...toAction(href), + }); + }); +} diff --git a/scripts/effect-budget.json b/scripts/effect-budget.json index 7a4e4a1e2f25b..50c665e65d647 100644 --- a/scripts/effect-budget.json +++ b/scripts/effect-budget.json @@ -88,7 +88,6 @@ "apps/mobile/src/features/settings/components/BranchNamingSettings.tsx": 1, "apps/mobile/src/features/settings/components/SettingsLegalDocumentRouteScreen.tsx": 1, "apps/mobile/src/features/sharing/IncomingShareProvider.tsx": 4, - "apps/mobile/src/features/shortcuts/useAppShortcuts.ts": 4, "apps/mobile/src/features/showcase/ShowcaseCaptureCoordinator.tsx": 11, "apps/mobile/src/features/terminal/NativeTerminalSurface.tsx": 4, "apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx": 14, From 278fdce1af7eb821c34ee416c441952df250ac63 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Mon, 26 Oct 2026 23:38:34 -0700 Subject: [PATCH 018/817] test(server): data regression test now fails when recent fetch savings regress (#25795) Co-authored-by: Claude Opus 5.5 --- .../TransferBudgetReport.integration.ts | 75 ++++++--- .../TransferBudgetV2Fixture.integration.ts | 152 +++++++++++++----- .../transferBudgetV2.integration.test.ts | 100 +++++++++--- docs/internals/performance-regressions.md | 7 +- 4 files changed, 249 insertions(+), 85 deletions(-) diff --git a/apps/server/integration/TransferBudgetReport.integration.ts b/apps/server/integration/TransferBudgetReport.integration.ts index fbe8185a4b482..fd434e2bc26eb 100644 --- a/apps/server/integration/TransferBudgetReport.integration.ts +++ b/apps/server/integration/TransferBudgetReport.integration.ts @@ -11,7 +11,11 @@ import { TRANSFER_MEASURED_MCP_RESULT_BYTES, TRANSFER_MEASURED_TOOLS, } from "./fixtures/transferBudget.ts"; -import { LONG_TURN_WORK_ROWS } from "./TransferBudgetV2Fixture.integration.ts"; +import { + LONG_TURN_WORK_ROWS, + SHELL_IDLE_SUBAGENTS, + SHELL_SETTLED_THREADS, +} from "./TransferBudgetV2Fixture.integration.ts"; export interface WebSocketCatchUpMeasurement extends WebSocketTransferTotals { readonly mode: "replay" | "snapshot"; @@ -36,6 +40,12 @@ export interface TransferBudgetRun { /** The compact bounded snapshot web and mobile load when the long-turn thread opens. */ readonly longTurnColdOpen: TimelineHttpMeasurement; readonly longTurnHistoryPage: TimelineHttpMeasurement; + /** The same reads as an older client that only sends `compactTurnItems`, to show the savings. */ + readonly longTurnColdOpenLegacy: TimelineHttpMeasurement; + readonly longTurnHistoryPageLegacy: TimelineHttpMeasurement; + /** The cold-connect shell snapshot after the settled-thread fleet is written. */ + readonly fleetShell: TimelineHttpMeasurement; + readonly fleetShellLegacy: TimelineHttpMeasurement; } interface ProviderTransferBudget { @@ -46,11 +56,12 @@ interface ProviderTransferBudget { readonly measuredTurnWebSocketMessages: number; } +// The measured turn decodes to about 22 KB; without live body dedupe its repeated answer makes it 26 KB. const TRANSFER_BUDGET = { totalWireBytes: 7_000, threadSnapshotWireBytes: 5_000, measuredTurnWebSocketWireBytes: 2_000, - measuredTurnWebSocketDecodedBytes: 30_000, + measuredTurnWebSocketDecodedBytes: 25_000, measuredTurnWebSocketMessages: 8, } satisfies ProviderTransferBudget; @@ -59,15 +70,20 @@ const TRANSFER_BUDGETS: Readonly> = { claudeAgent: TRANSFER_BUDGET, }; -// Decoded bytes, not wire bytes: phones parse and keep the decoded JSON. About -// 30% above the observed 92 KB; without row budgets inside user turns the cold -// open carried all 920 rows (1.07 MB). Kept apart from TRANSFER_BUDGET because -// the PR comment validates that object's keys. +// Decoded bytes, not wire bytes: phones parse and keep the decoded JSON. About 7% above the +// observed 103 KB, so a cold open without body dedupe (117 KB), the ID table, or row budgets +// (all 920 rows) fails. Kept apart from TRANSFER_BUDGET because the PR comment validates its keys. const LONG_TURN_BUDGET = { - decodedBytes: 120_000, + decodedBytes: 110_000, rows: 75, }; +// About 30% above the observed 42 KB. Without the shell opt-ins it carries all 142 rows (217 KB). +const FLEET_SHELL_BUDGET = { + decodedBytes: 55_000, + rows: 27, +}; + function totalWireBytes(run: TransferBudgetRun): number { return run.threadSnapshot.wireBytes + run.measuredTurnWebSocket.wireBytes; } @@ -160,21 +176,28 @@ function webSocketRows( ]; } -function longTurnRows( +function timelineRows( provider: ProviderDriverKind, phase: string, measured: TimelineHttpMeasurement, + budget: { readonly decodedBytes: number; readonly rows: number }, ): string[] { return [ infoRow(provider, phase, "HTTP wire", measured.http.wireBytes), - row( - provider, - phase, - "HTTP decoded", - measured.http.decodedBodyBytes, - LONG_TURN_BUDGET.decodedBytes, - ), - row(provider, phase, "rows", measured.rows, LONG_TURN_BUDGET.rows, String), + row(provider, phase, "HTTP decoded", measured.http.decodedBodyBytes, budget.decodedBytes), + row(provider, phase, "rows", measured.rows, budget.rows, String), + ]; +} + +function legacyRows( + provider: ProviderDriverKind, + phase: string, + measured: TimelineHttpMeasurement, +): string[] { + return [ + infoRow(provider, `${phase}, older client`, "HTTP wire", measured.http.wireBytes), + infoRow(provider, `${phase}, older client`, "HTTP decoded", measured.http.decodedBodyBytes), + infoRow(provider, `${phase}, older client`, "rows", measured.rows, String), ]; } @@ -216,6 +239,12 @@ export function transferBudgetViolations(runs: ReadonlyArray) LONG_TURN_BUDGET.decodedBytes, ], ["long-turn history page rows", run.longTurnHistoryPage.rows, LONG_TURN_BUDGET.rows], + [ + "fleet shell snapshot decoded bytes", + run.fleetShell.http.decodedBodyBytes, + FLEET_SHELL_BUDGET.decodedBytes, + ], + ["fleet shell snapshot rows", run.fleetShell.rows, FLEET_SHELL_BUDGET.rows], ] as const; for (const [metric, observed, maximum] of checks) { if (observed > maximum) { @@ -234,6 +263,7 @@ export function formatTransferBudgetReport(runs: ReadonlyArray; export function threadCreated( provider: ProviderDriverKind, threadId: ThreadId = THREAD_ID, -): OrchestrationV2DomainEvent { + overrides: Partial = {}, +): ThreadCreatedEvent { const now = DateTime.makeUnsafe("2026-06-01T00:00:00Z"); return { id: EventId.make(`thread-created:${threadId}`), @@ -58,6 +62,7 @@ export function threadCreated( settledAt: null, lastVisitedAt: null, deletedAt: null, + ...overrides, }, }; } @@ -102,6 +107,9 @@ export function turnEvents( const events: OrchestrationV2DomainEvent[] = [ { ...common, id: EventId.make(`run-${index}`), type: "run.created", payload: run }, ]; + const answer = + `Completed ${provider} inspection ${index}. ` + + "The projection preserves transcript text and bounds tool output. ".repeat(60); for (const role of ["user", "assistant"] as const) { events.push({ ...common, @@ -113,11 +121,7 @@ export function turnEvents( runId, nodeId, role, - text: - role === "user" - ? `Inspect transfer ${index}` - : `Completed ${provider} inspection ${index}. ` + - "The projection preserves transcript text and bounds tool output. ".repeat(60), + text: role === "user" ? `Inspect transfer ${index}` : answer, attachments: [], streaming: false, createdAt: now, @@ -128,6 +132,22 @@ export function turnEvents( }); } const toolCount = measured ? TRANSFER_MEASURED_TOOLS : TRANSFER_HISTORY_TOOLS_PER_TURN; + const item = (id: string, ordinal: number, title: string | null) => ({ + id: TurnItemId.make(id), + threadId: THREAD_ID, + runId, + nodeId, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal, + status: "completed" as const, + title, + startedAt: now, + completedAt: now, + updatedAt: now, + }); for (let tool = 0; tool <= toolCount; tool++) { const mcp = tool === toolCount; const output = diagnosticOutput({ @@ -140,22 +160,11 @@ export function turnEvents( : TRANSFER_HISTORY_MCP_RESULT_BYTES : 4096, }); - const base = { - id: TurnItemId.make(`item-${index}-${tool}`), - threadId: THREAD_ID, - runId, - nodeId, - providerThreadId: null, - providerTurnId: null, - nativeItemRef: null, - parentItemId: null, - ordinal: tool + 1, - status: "completed" as const, - title: mcp ? "MCP search" : `Inspect source ${tool}`, - startedAt: now, - completedAt: now, - updatedAt: now, - }; + const base = item( + `item-${index}-${tool}`, + tool + 1, + mcp ? "MCP search" : `Inspect source ${tool}`, + ); events.push({ ...common, id: EventId.make(`tool-${index}-${tool}`), @@ -177,6 +186,21 @@ export function turnEvents( }, }); } + // The live turn repeats its answer in a turn item, as adapters do, so live dedupe has work. + // History turns skip it to keep the fallback thread snapshot under its wire ceiling. + if (measured) + events.push({ + ...common, + id: EventId.make(`answer-item-${index}`), + type: "turn-item.updated", + payload: { + ...item(`item-${index}-answer`, toolCount + 2, null), + type: "assistant_message", + messageId: MessageId.make(`assistant-${index}`), + text: answer, + streaming: false, + }, + }); events.push({ ...common, id: EventId.make(`complete-${index}`), @@ -192,6 +216,8 @@ export const LONG_TURN_WORK_ROWS = 900; /** * Three short user turns, then one agent turn far longer than a cold-open * window, with the item kinds a long agent run produces. One batch per turn. + * Run, node, provider and item IDs follow the composite shapes the Claude + * adapter stores, and every assistant message has its record, as real threads do. */ export function longTurnThreadBatches( provider: ProviderDriverKind, @@ -208,8 +234,14 @@ export function longTurnThreadBatches( const turn = (index: number, workRows: number): OrchestrationV2DomainEvent[] => { const now = DateTime.makeUnsafe(`2026-06-02T00:${String(index).padStart(2, "0")}:00Z`); - const runId = RunId.make(`long-turn-run-${index}`); - const nodeId = NodeId.make(`long-turn-node-${index}`); + const runId = RunId.make(`run:thread:${threadId}:ordinal:${index + 1}`); + const nodeId = NodeId.make(`node:run:${encodeURIComponent(runId)}:root`); + const providerThreadId = ProviderThreadId.make( + `provider-thread:provider:${provider}:native-thread:${encodeURIComponent(`pending:${runId}`)}`, + ); + const providerTurnId = ProviderTurnId.make( + `provider-turn:provider:${provider}:native-turn:${encodeURIComponent(`turn:run-attempt:${encodeURIComponent(runId)}:attempt:1`)}`, + ); const common = { threadId, runId, @@ -218,6 +250,10 @@ export function longTurnThreadBatches( providerInstanceId, occurredAt: now, }; + const messageId = (role: "user" | "assistant", row: string) => + MessageId.make( + `message:provider:${provider}:native-item:msg_01LongTurn${role}${index}x${row}`, + ); const run = { id: runId, threadId, @@ -225,7 +261,7 @@ export function longTurnThreadBatches( providerInstanceId, modelSelection, providerThreadId: null, - userMessageId: MessageId.make(`long-turn-user-${index}`), + userMessageId: messageId("user", "prompt"), rootNodeId: nodeId, activeAttemptId: null, status: "running" as const, @@ -237,14 +273,15 @@ export function longTurnThreadBatches( }; const base = (row: string, title: string | null) => { ordinal += 1; + const nativeId = `toolu_01LongTurn${index}x${row}`; return { - id: TurnItemId.make(`long-turn-item-${index}-${row}`), + id: TurnItemId.make(`turn-item:provider:${provider}:native-item:${nativeId}`), threadId, runId, nodeId, - providerThreadId: null, - providerTurnId: null, - nativeItemRef: null, + providerThreadId, + providerTurnId, + nativeItemRef: { driver: provider, nativeId, strength: "strong" as const }, parentItemId: null, ordinal, status: "completed" as const, @@ -258,7 +295,7 @@ export function longTurnThreadBatches( { ...common, id: EventId.make(`long-turn-run-${index}`), type: "run.created", payload: run }, ]; const message = (role: "user" | "assistant", row: string, messageText: string) => { - const messageId = MessageId.make(`long-turn-${role}-${index}-${row}`); + const id = messageId(role, row); const createdBy = role === "user" ? ("user" as const) : ("agent" as const); events.push( { @@ -266,7 +303,7 @@ export function longTurnThreadBatches( id: EventId.make(`long-turn-message-${index}-${row}`), type: "message.updated", payload: { - id: messageId, + id, threadId, runId, nodeId, @@ -291,7 +328,7 @@ export function longTurnThreadBatches( type: "user_message", createdBy, creationSource: "web", - messageId, + messageId: id, inputIntent: "turn_start", text: messageText, attachments: [], @@ -299,7 +336,7 @@ export function longTurnThreadBatches( : { ...base(row, null), type: "assistant_message", - messageId, + messageId: id, text: messageText, streaming: false, }, @@ -360,14 +397,6 @@ export function longTurnThreadBatches( input: { query: `module ${row}` }, output: { text: text(index, row, 6_144) }, }; - case 5: - return { - ...base(String(row), null), - type: "assistant_message", - messageId: MessageId.make(`long-turn-progress-${index}-${row}`), - text: text(index, row, 600), - streaming: false, - }; default: return { ...base(String(row), `Run check ${row}`), @@ -381,6 +410,10 @@ export function longTurnThreadBatches( message("user", "prompt", `Continue the feature work, step ${index}.`); for (let row = 0; row < workRows; row++) { + if (row % 8 === 5) { + message("assistant", String(row), text(index, row, 1_500)); + continue; + } events.push({ ...common, id: EventId.make(`long-turn-work-${index}-${row}`), @@ -406,3 +439,40 @@ export function longTurnThreadBatches( turn(3, LONG_TURN_WORK_ROWS), ]; } + +export const SHELL_SETTLED_THREADS = 100; +export const SHELL_IDLE_SUBAGENTS = 40; + +/** + * A busy sidebar: settled top-level threads, settled a minute apart, with idle subagent children + * under the newest ones. Opted-in cold connects skip the children and all but 25 settled threads. + */ +export function shellFleetEvents( + provider: ProviderDriverKind, +): ReadonlyArray { + return Array.from({ length: SHELL_SETTLED_THREADS }, (_, index) => { + const threadId = ThreadId.make(`transfer-budget-settled-${index}`); + const settledAt = DateTime.makeUnsafe(Date.UTC(2026, 5, 3, 0, index)); + const settled = threadCreated(provider, threadId, { + title: `Settled transfer thread ${index}`, + branch: `feature/settled-${index}`, + settledOverride: "settled", + settledAt, + updatedAt: settledAt, + }); + if (index < SHELL_SETTLED_THREADS - SHELL_IDLE_SUBAGENTS) return [settled]; + const childId = ThreadId.make(`transfer-budget-settled-${index}-subagent`); + return [ + settled, + threadCreated(provider, childId, { + title: `Subagent of settled thread ${index}`, + createdBy: "agent", + lineage: { + parentThreadId: threadId, + relationshipToParent: "subagent", + rootThreadId: threadId, + }, + }), + ]; + }).flat(); +} diff --git a/apps/server/integration/transferBudgetV2.integration.test.ts b/apps/server/integration/transferBudgetV2.integration.test.ts index 8417d852acfdf..22db0e643db9b 100644 --- a/apps/server/integration/transferBudgetV2.integration.test.ts +++ b/apps/server/integration/transferBudgetV2.integration.test.ts @@ -55,6 +55,7 @@ import { subscribeOrchestrationV2Thread, subscribeOrchestrationV2Shell } from ". import { measureHttpGet, openMeasuredWsClient, + type HttpTransferMeasurement, type MeasuredWsClient, } from "./NetworkTransferMeasurement.integration.ts"; import { makeSqlStatementCounter } from "./SqlStatementCounter.integration.ts"; @@ -68,11 +69,20 @@ import { TRANSFER_HISTORY_TURN_COUNT } from "./fixtures/transferBudget.ts"; import { LONG_TURN_THREAD_ID, longTurnThreadBatches, + SHELL_IDLE_SUBAGENTS, + SHELL_SETTLED_THREADS, + shellFleetEvents, THREAD_ID, threadCreated, turnEvents, } from "./TransferBudgetV2Fixture.integration.ts"; +// The opt-ins current web and mobile clients send; keep in sync with client-runtime's +// boundedThreadSnapshotHttp.ts, threadHistoryHttp.ts, shellSnapshotHttp.ts, threads.ts and shell.ts. +const CLIENT_BOUNDED_QUERY = "compactTurnItems=1&dedupeBodies=1&compactIds=1"; +const CLIENT_HISTORY_QUERY = "compactIds=1"; +const CLIENT_SHELL_QUERY = "omitIdleSubagents=1&omitOlderSettled=1"; + const decodeThreadSnapshot = Schema.decodeUnknownEffect( Schema.fromJsonString(Schema.toCodecJson(OrchestrationV2ThreadDetailSnapshot)), ); @@ -220,10 +230,15 @@ const subscribe = Effect.fn("transfer.subscribe")(function* ( afterSequence, requestCompletionMarker: true, acceptBoundedSnapshot: true, + acceptCompactTurnItems: true, + acceptCompactIds: true, + acceptDedupedBodies: true, }) : client.client[ORCHESTRATION_V2_WS_METHODS.subscribeShell]({ afterSequence, requestCompletionMarker: true, + omitIdleSubagents: true, + omitOlderSettled: true, }); yield* stream.pipe( Stream.runForEach((item) => Queue.offer(queue, item)), @@ -323,7 +338,18 @@ it.live("reports V2 thread HTTP and WebSocket transfer budgets", () => const finalShell = yield* projection.getThreadShell(THREAD_ID); const shellTerminal = (item: StreamItem) => item.kind === "thread.updated" && NodeUtil.isDeepStrictEqual(item.thread, finalShell); - for (const queue of [tq, ttq]) yield* collectUntil(queue, threadTerminal); + const liveTurn = yield* collectUntil(tq, threadTerminal); + yield* collectUntil(ttq, threadTerminal); + // A direct check, so live dedupe stays guarded however small the turn gets. + const liveAnswer = liveTurn.flatMap((item) => + item.kind === "event" && + item.event.type === "turn-item.updated" && + item.event.payload.type === "assistant_message" + ? [item.event.payload] + : [], + ); + assert.equal(liveAnswer.length, 1); + assert.equal(liveAnswer[0]!.textOmitted, true); for (const queue of [sq, ssq]) yield* collectUntil(queue, shellTerminal); const measuredTurnWebSocket = difference(thread.recorder.totals(), threadBefore); const measuredTurnShellWebSocket = difference(shell.recorder.totals(), shellBefore); @@ -353,25 +379,52 @@ it.live("reports V2 thread HTTP and WebSocket transfer budgets", () => assert.equal(threadMode, "snapshot"); for (const events of longTurnThreadBatches(provider)) yield* sink.write({ events }); - const longTurnColdOpen = yield* measureHttpGet({ - url: `${base}/api/orchestration/threads/${LONG_TURN_THREAD_ID}/bounded?compactTurnItems=1`, - headers: { [ORCHESTRATION_PROTOCOL_HEADER]: String(ORCHESTRATION_PROTOCOL_VERSION) }, - }); - assert.equal(longTurnColdOpen.status, 200); - const coldOpen = yield* decodeBoundedSnapshot( - Buffer.from(longTurnColdOpen.decodedBody).toString(), - ); - const cursor = coldOpen.historyCursor; + const get = (path: string) => + measureHttpGet({ + url: `${base}${path}`, + headers: { [ORCHESTRATION_PROTOCOL_HEADER]: String(ORCHESTRATION_PROTOCOL_VERSION) }, + }).pipe(Effect.tap((http) => Effect.sync(() => assert.equal(http.status, 200)))); + const decoded = (http: HttpTransferMeasurement) => + Buffer.from(http.decodedBody).toString(); + const longTurnPath = `/api/orchestration/threads/${LONG_TURN_THREAD_ID}`; + const readColdOpen = (query: string) => + Effect.gen(function* () { + const http = yield* get(`${longTurnPath}/bounded?${query}`); + const snapshot = yield* decodeBoundedSnapshot(decoded(http)); + const rows = snapshot.projection.visibleTurnItems.length; + return { http, rows, cursor: snapshot.historyCursor }; + }); + const readHistoryPage = (cursor: string, query: string) => + Effect.gen(function* () { + const http = yield* get( + `${longTurnPath}/history?cursor=${encodeURIComponent(cursor)}&${query}`, + ); + const page = yield* decodeHistoryPage(decoded(http)); + assert.isTrue(page.hasMoreHistory); + return { http, rows: page.items.length }; + }); + const readShell = (query: string) => + Effect.gen(function* () { + const http = yield* get(`/api/orchestration/shell?${query}`); + return { http, rows: (yield* decodeShellSnapshot(decoded(http))).threads.length }; + }); + + const { cursor: _, ...longTurnColdOpenLegacy } = + yield* readColdOpen("compactTurnItems=1"); + const { cursor, ...longTurnColdOpen } = yield* readColdOpen(CLIENT_BOUNDED_QUERY); if (cursor === null) return yield* Effect.die("Expected older long-turn history"); - const longTurnHistoryPage = yield* measureHttpGet({ - url: `${base}/api/orchestration/threads/${LONG_TURN_THREAD_ID}/history?cursor=${encodeURIComponent(cursor)}`, - headers: { [ORCHESTRATION_PROTOCOL_HEADER]: String(ORCHESTRATION_PROTOCOL_VERSION) }, - }); - assert.equal(longTurnHistoryPage.status, 200); - const historyPage = yield* decodeHistoryPage( - Buffer.from(longTurnHistoryPage.decodedBody).toString(), + const longTurnHistoryPageLegacy = yield* readHistoryPage(cursor, ""); + const longTurnHistoryPage = yield* readHistoryPage(cursor, CLIENT_HISTORY_QUERY); + + // The transfer thread plus the long-turn thread. + const earlierThreads = decodedShell.threads.length + 1; + yield* sink.write({ events: shellFleetEvents(provider) }); + const fleetShellLegacy = yield* readShell(""); + const fleetShell = yield* readShell(CLIENT_SHELL_QUERY); + assert.equal( + fleetShellLegacy.rows, + earlierThreads + SHELL_SETTLED_THREADS + SHELL_IDLE_SUBAGENTS, ); - assert.isTrue(historyPage.hasMoreHistory); return { provider, threadSnapshot, @@ -383,11 +436,12 @@ it.live("reports V2 thread HTTP and WebSocket transfer budgets", () => reconnectThread, reconnectShell, reconnectSqlStatements, - longTurnColdOpen: { - http: longTurnColdOpen, - rows: coldOpen.projection.visibleTurnItems.length, - }, - longTurnHistoryPage: { http: longTurnHistoryPage, rows: historyPage.items.length }, + longTurnColdOpenLegacy, + longTurnColdOpen, + longTurnHistoryPageLegacy, + longTurnHistoryPage, + fleetShellLegacy, + fleetShell, } satisfies TransferBudgetRun; }).pipe( Effect.provide(Layer.fresh(layerServices).pipe(Layer.provideMerge(NodeServices.layer))), diff --git a/docs/internals/performance-regressions.md b/docs/internals/performance-regressions.md index 1a9dfee13b82b..51760756c1085 100644 --- a/docs/internals/performance-regressions.md +++ b/docs/internals/performance-regressions.md @@ -63,9 +63,10 @@ for the same synthetic workload, preserving historical application-object counts These are neither compressed WebSocket captures nor measurements of server RSS, and command fixtures exclude unrelated settings calls and subscription events. Payload budgets belong in these tests so regressions fail locally. The transfer budget integration test -(`apps/server/integration/transferBudgetV2.integration.test.ts`) caps the decoded bytes and rows -of the compact bounded snapshot that web and mobile load, and of one older page, for a 900-row -agent turn. +(`apps/server/integration/transferBudgetV2.integration.test.ts`) sends the opt-ins current clients +send and caps the decoded bytes and rows of the bounded snapshot and one older page for a 900-row +agent turn, and of the cold-connect shell for a sidebar of settled threads and idle subagents. When +clients gain an opt-in, add it to the test's client queries and give a fixture the data it saves. ## Event store and startup From bc813670d9c428fa42707a0d78c01e03177016ba Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Mon, 26 Oct 2026 23:59:51 -0700 Subject: [PATCH 019/817] fix(server): all MCP tools now send compact schemas, cutting tool context by 23% (#25790) Co-authored-by: Claude Opus 5.5 --- apps/server/src/mcp/McpHttpServer.test.ts | 14 ++++++++ apps/server/src/mcp/McpHttpServer.ts | 33 ++++++++++++++++++- .../src/provider/agentContextBudget.json | 2 +- 3 files changed, 47 insertions(+), 2 deletions(-) diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index 6c502c1ef1305..8d7fb85a9e9b8 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -21,6 +21,7 @@ import { HttpBody, HttpClient, HttpClientRequest, HttpRouter } from "effect/http import * as ProjectService from "../project/ProjectService.ts"; import * as PullRequestReviewGuideService from "../pullRequest/PullRequestReviewGuideService.ts"; import * as ServerConfig from "../config.ts"; +import { advertisedJsonSchema } from "./advertisedJsonSchema.ts"; import * as McpHttpServer from "./McpHttpServer.ts"; import * as McpToolAccess from "./McpToolAccess.ts"; import * as McpToolAccessTestkit from "./McpToolAccess.testkit.ts"; @@ -29,6 +30,7 @@ import * as McpSessionRegistry from "./McpSessionRegistry.ts"; import * as OrchestratorMcpService from "./OrchestratorMcpService.ts"; import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts"; import { OrchestratorToolkit } from "./toolkits/orchestrator/tools.ts"; +import { PreviewToolkit } from "./toolkits/preview/tools.ts"; import { ProjectToolkit } from "./toolkits/project/tools.ts"; const environmentId = EnvironmentId.make("environment-mcp-test"); @@ -356,6 +358,18 @@ it.effect("refuses preview tools to a client outside a thread before they run", }).pipe(Effect.provide(layerTest)), ); +it.effect("advertises the compact input schema for every registered tool", () => + Effect.gen(function* () { + const server = yield* McpServer.McpServer; + const tools: Record = PreviewToolkit.tools; + + expect(server.tools.length).toBe(Object.keys(tools).length); + for (const { tool } of server.tools) { + expect(tool.inputSchema, tool.name).toEqual(advertisedJsonSchema(tools[tool.name]!)); + } + }).pipe(Effect.provide(layerTest)), +); + it.effect("checks each preview_act action against that action's own input", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 044a43baeab1e..0d8837f0ab875 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -948,6 +948,35 @@ const withToolAnalytics = return yield* registration.pipe(Effect.provideService(McpServer.McpServer, recordingServer)); }); +/** `McpServer.registerToolkit` advertises the full codec schema; agents get the compact one. */ +const withAdvertisedSchemas = Effect.fn("McpHttpServer.withAdvertisedSchemas")(function* < + Tools extends Record, + A, + E, + R, +>(toolkit: Toolkit.Toolkit, registration: Effect.Effect) { + const server = yield* McpServer.McpServer; + const tools: Record = toolkit.tools; + const advertisingServer = McpServer.McpServer.of({ + ...server, + addTool: Effect.fn("McpServer.addTool")(function (options) { + const tool = tools[options.tool.name]; + return server.addTool( + tool === undefined + ? options + : { + ...options, + tool: new McpSchema.Tool({ + ...options.tool, + inputSchema: advertisedJsonSchema(tool), + }), + }, + ); + }), + }); + return yield* registration.pipe(Effect.provideService(McpServer.McpServer, advertisingServer)); +}); + /** * `McpServer.toolkit` asks for every service its tools declare when it * registers them, but the auth middleware provides `McpInvocationContext` to @@ -959,7 +988,9 @@ export const toolkitRegistration = , EX, handlers: McpToolAccess.HandlersLayer, ) => { const registration = Layer.effectDiscard( - withToolAnalytics(McpServer.registerToolkit(decodeAsAdvertised(toolkit))), + withToolAnalytics( + withAdvertisedSchemas(toolkit, McpServer.registerToolkit(decodeAsAdvertised(toolkit))), + ), ).pipe(Layer.provide(McpServer.McpServer.layer)); // @effect-diagnostics-next-line unsafeEffectTypeAssertion:off - the auth middleware provides it per request. const registered = registration as Layer.Layer< diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index e3272bfdf8021..a54335979eb4c 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 4857, "codexAdditionalContextBytes": 5409, - "mcpToolListJsonBytes": 54964 + "mcpToolListJsonBytes": 42328 } From 96fc7b955196637605cbf3b415152ce4dd0e2294 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Tue, 27 Oct 2026 00:00:18 -0700 Subject: [PATCH 020/817] refactor(web): the new design is the only design, with no toggle (#25778) Co-authored-by: Claude Opus 5.5 --- apps/desktop/src/window/DesktopWindow.ts | 2 +- apps/web/index.html | 10 +- apps/web/src/appInit.tsx | 3 - apps/web/src/components/ChatView.tsx | 2 - .../components/ComposerPromptEditorTiptap.tsx | 2 +- apps/web/src/components/DiffPanel.tsx | 18 +-- .../src/components/DiffWorkerPoolProvider.tsx | 10 +- apps/web/src/components/GitActionsControl.tsx | 3 - apps/web/src/components/Sidebar.tsx | 10 +- .../src/components/ThreadStatusIndicators.tsx | 2 +- apps/web/src/components/chat/ChatCanvas.tsx | 3 - apps/web/src/components/chat/ChatComposer.tsx | 2 +- .../chat/ComposerPrimaryActions.tsx | 29 +--- apps/web/src/components/chat/ModelListRow.tsx | 15 +- .../components/chat/ModelPickerContent.tsx | 19 +-- .../components/chat/ModelPickerSidebar.tsx | 7 +- .../components/chat/ThreadDetailsControl.tsx | 11 +- .../components/chat/ThreadDetailsPrRow.tsx | 2 +- .../components/chat/ThreadDetailsPrRows.tsx | 8 +- .../chat/ThreadRelationshipsControl.tsx | 2 +- .../src/components/chat/ThreadStatusLine.tsx | 9 +- apps/web/src/components/chat/TraitsPicker.tsx | 8 +- .../src/components/chat/canvasStore.test.ts | 3 - apps/web/src/components/chat/canvasStore.ts | 3 - .../components/chat/chatCanvasLayout.test.ts | 26 ++-- .../src/components/chat/chatCanvasLayout.ts | 22 ++- .../pullRequest/PullRequestGhosts.tsx | 4 +- .../settings/AppearanceSettingsPanel.tsx | 21 --- .../settings/ProviderInstanceCard.tsx | 9 +- .../settings/ProviderModelsSection.tsx | 2 +- .../settings/ProviderSettingsPanel.tsx | 6 +- .../settings/SettingsFontPreviews.tsx | 2 +- .../components/settings/SettingsPanels.tsx | 4 - .../settings/ThemePreviewCircles.tsx | 2 +- .../src/components/settings/ThemeSettings.tsx | 12 +- .../src/components/settings/settingsSearch.ts | 6 - .../components/sidebar/SidebarListMarkers.tsx | 13 +- .../sidebar/SidebarThreadHeader.tsx | 2 +- .../components/sidebar/SidebarThreadRow.tsx | 132 ++++++++---------- apps/web/src/components/ui/button.tsx | 2 +- .../ui/collapsible-section-header.tsx | 14 +- apps/web/src/components/ui/combobox.tsx | 2 +- apps/web/src/components/ui/command.tsx | 2 +- apps/web/src/components/ui/kbd.tsx | 2 +- .../components/usage/UsageLimitsPooled.tsx | 15 +- apps/web/src/components/usage/UsagePage.tsx | 94 ++++++------- apps/web/src/index.css | 87 +++++------- apps/web/src/lib/diffRendering.ts | 27 +--- apps/web/src/lib/incrementalHighlighting.ts | 7 +- apps/web/src/lib/syntaxHighlighting.ts | 2 +- packages/contracts/src/settings.ts | 3 - 51 files changed, 248 insertions(+), 455 deletions(-) diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index 6270f80a4a7e6..20b43f91e63af 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -131,7 +131,7 @@ function getIconOption( } function getInitialWindowBackgroundColor(shouldUseDarkColors: boolean): string { - return shouldUseDarkColors ? "#0a0a0a" : "#ffffff"; + return shouldUseDarkColors ? "#000000" : "#ffffff"; } type DisplayBounds = Pick; diff --git a/apps/web/index.html b/apps/web/index.html index 13518deb6e5d1..a7a5e7450b3de 100644 --- a/apps/web/index.html +++ b/apps/web/index.html @@ -6,14 +6,14 @@ name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover, interactive-widget=resizes-content" /> - + "); + const eventSink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + const run = (yield* orchestrator.getThreadRecords(threadId, ["runs"])).runs[0]; + const item = ( + id: string, + ordinal: number, + fields: + | { readonly type: "assistant_message"; readonly text: string } + | { readonly type: "user_message"; readonly text: string }, + target: { readonly threadId: ThreadId; readonly runId: RunId } = { threadId, runId }, + ) => ({ + id: EventId.make(`event:${id}`), + type: "turn-item.updated" as const, + threadId: target.threadId, + driver: ProviderDriverKind.make("codex"), + providerInstanceId: instanceId, + occurredAt: now, + payload: { + id: TurnItemId.make(id), + threadId: target.threadId, + runId: target.runId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal, + title: null, + status: "completed" as const, + startedAt: now, + completedAt: now, + updatedAt: now, + messageId: MessageId.make(id), + ...(fields.type === "assistant_message" + ? { ...fields, streaming: false } + : { + ...fields, + createdBy: "user" as const, + creationSource: "web" as const, + inputIntent: "turn_start" as const, + attachments: [], + }), + }, + }); + yield* eventSink.write({ + events: [ + item("item:agent-images", 1, { + type: "assistant_message", + text: `Done: ![Shot](<${shot}>) ![Other](file://${encodeURI(fileUrl)}) ![Page](${page})`, + }), + // A guest's sent message is a user message; it must not open files on the host. + item("item:guest-image", 2, { type: "user_message", text: `![Mine](${fromUser})` }), + { + id: EventId.make("event:run-done"), + type: "run.updated" as const, + threadId, + runId, + providerInstanceId: instanceId, + occurredAt: now, + payload: { ...run!, status: "completed" as const, completedAt: now }, + }, + ], + }); + // The guest watches a fork, which shows these replies as inherited history. + const forkId = ThreadId.make("thread:guest-share-fork"); + yield* orchestrator.dispatch({ + type: "thread.fork", + commandId: CommandId.make("fork"), + sourceThreadId: threadId, + targetThreadId: forkId, + sourcePoint: { type: "run", runId }, + createdBy: "user", + creationSource: "web", + }); + const { url } = yield* guestShares.create({ threadId: forkId }); + const { token: session } = yield* guestShares.redeem({ + credential: url.slice(url.indexOf("#") + 1), + name: "Sam", + }); + + // The guest's page opens, and its stream sends the replies the fork inherits. + const sent = yield* Queue.unbounded(); + yield* Stream.runForEach(yield* guestShares.stream(session), (event) => + Queue.offer(sent, event), + ).pipe(Effect.forkScoped); + const sentItem = Effect.fn(function* (id: string) { + for (;;) { + const event = yield* Queue.take(sent); + if ( + event.type === "thread" && + event.item.kind === "event" && + event.item.event.type === "turn-item.updated" && + event.item.event.payload.id === id + ) { + return; + } + } + }); + + // The agent shows another screenshot live, then enough rows to push the first reply out of + // the window, before the page asks for any image. + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("fork-message"), + threadId: forkId, + messageId: MessageId.make("message:fork"), + text: "One more", + attachments: [], + dispatchMode: { type: "defer_start" }, + createdBy: "user", + creationSource: "web", + }); + const forkRun = (yield* orchestrator.getThreadRecords(forkId, ["runs"])).runs.at(-1)!; + const inFork = { threadId: forkId, runId: forkRun.id }; + yield* eventSink.write({ + events: [ + item( + "item:later-image", + 1, + { type: "assistant_message", text: `![Later](${later})` }, + inFork, + ), + ...Array.from({ length: 600 }, (_, index) => + item( + `item:filler-${index}`, + index + 2, + { type: "assistant_message", text: "Working." }, + inFork, + ), + ), + ], + }); + yield* sentItem("item:later-image"); + + // The page still shows every reply it was sent, so each image loads. + for (const path of [shot, fileUrl, later]) { + assert.deepStrictEqual(yield* guestShares.media(session, path), { + path, + mimeType: "image/png", + }); + } + for (const path of [page, fromUser, unnamed, `${directory}/missing.png`]) { + assert.equal((yield* Effect.flip(guestShares.media(session, path))).reason, "unavailable"); + } + + // A reply edited to drop its image stops allowing it. + yield* eventSink.write({ + events: [ + { + ...item("item:later-image", 1, { type: "assistant_message", text: "Gone." }, inFork), + id: EventId.make("event:later-image-edited"), + }, + ], + }); + yield* sentItem("item:later-image"); + assert.equal((yield* Effect.flip(guestShares.media(session, later))).reason, "unavailable"); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + +it.effect("keeps a connected guest's images while other shares come and go", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const directory = yield* fileSystem.makeTempDirectoryScoped(); + const shot = `${directory}/shot.png`; + yield* fileSystem.writeFile(shot, PNG); + const eventSink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + /** A shared thread whose agent reply shows the screenshot, and its guest's session. */ + const sharedWithImage = Effect.fn(function* (id: ThreadId) { + const { orchestrator, guestShares, credential } = yield* shareThreadFor(id); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`message:${id}`), + threadId: id, + messageId: MessageId.make(`message:${id}`), + text: "Show me", + attachments: [], + dispatchMode: { type: "defer_start" }, + createdBy: "user", + creationSource: "web", + }); + const runId = (yield* orchestrator.getThreadRecords(id, ["runs"])).runs[0]!.id; + yield* eventSink.write({ + events: [ + { + id: EventId.make(`event:reply:${id}`), + type: "turn-item.updated", + threadId: id, + driver: ProviderDriverKind.make("codex"), + providerInstanceId: instanceId, + occurredAt: now, + payload: { + id: TurnItemId.make(`item:reply:${id}`), + threadId: id, + runId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 1, + title: null, + status: "completed", + startedAt: now, + completedAt: now, + updatedAt: now, + type: "assistant_message", + messageId: MessageId.make(`item:reply:${id}`), + text: `![Shot](${shot})`, + streaming: false, + }, + }, + ], + }); + const { token } = yield* guestShares.redeem({ credential, name: "Sam" }); + return { guestShares, token }; + }); + + // This guest's page stays open while more guests than the record keeps open and close theirs. + const { guestShares, token } = yield* sharedWithImage(threadId); + const opened = yield* Deferred.make(); + yield* Stream.runForEach(yield* guestShares.stream(token), () => + Deferred.succeed(opened, undefined), + ).pipe(Effect.forkScoped); + yield* Deferred.await(opened); + const closedTokens: Array = []; + for (let index = 0; index < 65; index++) { + const other = yield* sharedWithImage(ThreadId.make(`thread:other-${index}`)); + const events = yield* guestShares.stream(other.token); + // The first is built but never read, as for a HEAD request; the rest open and close. + if (index > 0) yield* Stream.runDrain(Stream.take(events, 2)); + closedTokens.push(other.token); + } + assert.equal((yield* guestShares.media(token, shot)).mimeType, "image/png"); + // Records of guests with no open page were dropped to make room. + for (const closed of closedTokens.slice(0, 2)) { + assert.equal((yield* Effect.flip(guestShares.media(closed, shot))).reason, "unavailable"); + } + + // A new link on the thread starts empty: its guest gets nothing the last guest was sent. + const { url } = yield* guestShares.create({ threadId }); + const next = yield* guestShares.redeem({ + credential: url.slice(url.indexOf("#") + 1), + name: "Kim", + }); + assert.equal((yield* Effect.flip(guestShares.media(next.token, shot))).reason, "unavailable"); + yield* Stream.runDrain(Stream.take(yield* guestShares.stream(next.token), 2)); + assert.equal((yield* guestShares.media(next.token, shot)).mimeType, "image/png"); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); diff --git a/apps/server/src/guest/GuestShareService.ts b/apps/server/src/guest/GuestShareService.ts index 1f65217e45212..0346068bc546f 100644 --- a/apps/server/src/guest/GuestShareService.ts +++ b/apps/server/src/guest/GuestShareService.ts @@ -15,9 +15,11 @@ import { type OrchestrationV2CommandOutputFrame, type OrchestrationV2DomainEvent, type OrchestrationV2GetTurnItemResult, + type OrchestrationV2TurnItem, ThreadId, TurnItemId, } from "@t3tools/contracts"; +import { chatMarkdownImageSources } from "@t3tools/shared/markdownPipeline"; import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput"; import * as Context from "effect/Context"; import * as Crypto from "effect/Crypto"; @@ -63,7 +65,10 @@ import { guestShareView, guestThreadModel } from "./guestView.ts"; import { classifyGuestUploads, GUEST_UPLOAD_HEADER_BYTES, + guestHostImageType, type GuestUpload, + matchesImageSignature, + repliesShowImage, } from "./guestAttachments.ts"; const SIGNING_SECRET_NAME = "guest-share-signing-key"; @@ -71,6 +76,8 @@ const SHARE_ID_BYTES = 16; const INVITE_SIGNATURE_BYTES = 16; const SNAPSHOT_ROW_LIMIT = 600; const SNAPSHOT_USER_TURN_LIMIT = 20; +// Shares with no open guest stream whose sent image replies are still kept. +const SHARED_THREAD_REPLIES_LIMIT = 64; // How soon an open read notices that its link stopped working, such as Connect no longer serving // the host. Closing or replacing the link ends the main stream at once. const ACCESS_RECHECK_INTERVAL = Duration.seconds(30); @@ -190,9 +197,20 @@ export class GuestShareService extends Context.Service< { readonly path: string; readonly attachment: ChatAttachment }, GuestShareAccessError >; + /** An image on the host that an agent reply the guest sees shows, and its type. */ + readonly media: ( + session: string, + path: string, + ) => Effect.Effect<{ readonly path: string; readonly mimeType: string }, GuestShareAccessError>; } >()("t3/guest/GuestShareService") {} +/** A reply a guest's stream sent, with its image sources once a media request parsed them. */ +interface SentReply { + readonly text: string; + sources?: ReadonlyArray; +} + /** The thread record an event carries, for the share and the view. */ const threadOf = (event: OrchestrationV2DomainEvent): OrchestrationV2AppThread | null => { switch (event.type) { @@ -464,6 +482,40 @@ const make = Effect.gen(function* () { Effect.ignore, ); + // The image replies each share's guest stream has sent, in its opening snapshot or live, so an + // image loads while the guest's page can show its reply, inherited ones included. Keyed by + // share, so a new link on the thread starts empty. A share with an open stream keeps its + // record; past the limit, closed ones are dropped. + const sentImageReplies = new Map< + GuestShareId, + { openStreams: number; readonly replies: Map } + >(); + const sentRecord = (shareId: GuestShareId) => { + let record = sentImageReplies.get(shareId); + if (record === undefined) { + record = { openStreams: 0, replies: new Map() }; + sentImageReplies.set(shareId, record); + for (const [id, other] of sentImageReplies) { + if (sentImageReplies.size <= SHARED_THREAD_REPLIES_LIMIT) break; + if (other.openStreams === 0 && id !== shareId) sentImageReplies.delete(id); + } + } + return record; + }; + const rememberSent = (shareId: GuestShareId, items: Iterable) => { + for (const item of items) { + if (item.type !== "assistant_message") continue; + const key = `${item.threadId}\u0000${item.id}`; + // Only replies with image syntax can show an image. One edited to drop its images stops + // allowing them. + if (item.text.includes("![") || / => { if (item.kind !== "event") return []; if (endsShare(item.event)) return [ended]; + if (item.event.type === "turn-item.updated") rememberSent(share.id, [item.event.payload]); const updated = threadOf(item.event); const view = updated === null ? null : viewOf(updated); return view === null @@ -528,17 +581,15 @@ const make = Effect.gen(function* () { const untilExpiry = Effect.sleep( Math.max(0, Date.parse(share.expiresAt) - DateTime.toEpochMillis(yield* DateTime.now)), ); + const openingSnapshot = buildBoundedThreadStreamSnapshot({ + snapshotSequence: snapshot.snapshotSequence, + projection: snapshot.projection, + }); const opening: ReadonlyArray = [ { type: "view", view: initialView }, - { - type: "thread", - item: buildBoundedThreadStreamSnapshot({ - snapshotSequence: snapshot.snapshotSequence, - projection: snapshot.projection, - }), - }, + { type: "thread", item: openingSnapshot }, ]; - return Stream.fromIterable(opening).pipe( + const events = Stream.fromIterable(opening).pipe( Stream.concat( Stream.merge(live, Stream.fromEffect(Effect.as(untilExpiry, ended)), { haltStrategy: "either", @@ -557,6 +608,25 @@ const make = Effect.gen(function* () { ), ), ); + // The record is opened and counted when the stream runs, paired with its release, so a + // response whose body never runs (HEAD) touches nothing. + return Stream.unwrap( + Effect.acquireRelease( + Effect.sync(() => { + const record = sentRecord(share.id); + record.openStreams += 1; + rememberSent( + share.id, + openingSnapshot.projection.visibleTurnItems.map((row) => row.item), + ); + return record; + }), + (record) => + Effect.sync(() => { + record.openStreams -= 1; + }), + ).pipe(Effect.as(events)), + ); }); const unavailable = new GuestShareAccessError({ reason: "unavailable" }); @@ -630,6 +700,33 @@ const make = Effect.gen(function* () { return exists ? { path, attachment: found } : yield* unavailable; }); + const media = Effect.fn("GuestShareService.media")(function* (session: string, path: string) { + const { share } = yield* authorize(session, "session"); + const mimeType = guestHostImageType(path); + if (mimeType === null) return yield* unavailable; + const sent = sentImageReplies.get(share.id)?.replies.values() ?? []; + // Each sent reply is parsed once, on the first request that needs it. + if ( + !repliesShowImage( + path, + [...sent], + (reply) => (reply.sources ??= chatMarkdownImageSources(reply.text)), + ) + ) { + return yield* unavailable; + } + // The bytes must be the image the name says, as for a guest's own upload. + const header = yield* fileSystem.open(path, { flag: "r" }).pipe( + Effect.flatMap((file) => file.readAlloc(GUEST_UPLOAD_HEADER_BYTES)), + Effect.scoped, + Effect.mapError(() => unavailable), + ); + if (Option.isNone(header) || !matchesImageSignature(mimeType, header.value)) { + return yield* unavailable; + } + return { path, mimeType }; + }); + return GuestShareService.of({ create, redeem, @@ -640,6 +737,7 @@ const make = Effect.gen(function* () { item, commandOutput, attachment, + media, }); }); diff --git a/apps/server/src/guest/guestAttachments.test.ts b/apps/server/src/guest/guestAttachments.test.ts new file mode 100644 index 0000000000000..c65dd1364c2b0 --- /dev/null +++ b/apps/server/src/guest/guestAttachments.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { guestHostImageType, repliesShowImage } from "./guestAttachments.ts"; + +describe("guest host images", () => { + it.each([ + ["![a](/w/a.png)", "/w/a.png", "image/png"], + ["![a]()", "/w/my shot.jpg", "image/jpeg"], + ["![a](/w/shot(1).png)", "/w/shot(1).png", "image/png"], + ["![a](/w/shot\\_1.png) ![b](/w/a&b.png)", "/w/shot_1.png", "image/png"], + ["![a](/w/shot\\_1.png) ![b](/w/a&b.png)", "/w/a&b.png", "image/png"], + ["![a](file:///w/caf%c3%a9.png)", "/w/café.png", "image/png"], + ["![a](file:///w/%73hot.png) ![b](/w/shot2.png)", "/w/shot.png", "image/png"], + ["![a](file:///w/%73hot.png) ![b](/w/shot2.png)", "/w/shot2.png", "image/png"], + ["![a][r]\n\n[r]: /w/ref.png", "/w/ref.png", "image/png"], + ["![a](file:///w/url%20form.png)", "/w/url form.png", "image/png"], + ["![a](C:\\w\\win.png)", "C:\\w\\win.png", "image/png"], + ["![a][r]\n\n[r]: C:\\w\\ref.png", "C:/w/ref.png", "image/png"], + // Shown as a link, in code, or not at all: the guest sees no image, so none loads. + ["[a](/w/link.png)", "/w/link.png", null], + ["```\n![a](/w/code.png)\n```", "/w/code.png", null], + ["`![a](/w/span.png)`", "/w/span.png", null], + ["", "/w/comment.png", null], + ["![a](/w/a.png)", "/a.png", null], + ["![a](//host/s/x.png)", "//host/s/x.png", null], + ["![a](\\\\host\\s\\x.png)", "\\\\host\\s\\x.png", null], + ["![a](/w/a.svg)", "/w/a.svg", null], + ["![a](/w/a.constructor)", "/w/a.constructor", null], + ])("%j serves %j as %j", (text, path, type) => { + const served = guestHostImageType(path) !== null && repliesShowImage(path, [{ text }]); + expect(served ? guestHostImageType(path) : null).toBe(type); + }); +}); diff --git a/apps/server/src/guest/guestAttachments.ts b/apps/server/src/guest/guestAttachments.ts index ab7bd1a78b8e5..5118899620d64 100644 --- a/apps/server/src/guest/guestAttachments.ts +++ b/apps/server/src/guest/guestAttachments.ts @@ -3,6 +3,9 @@ import { GUEST_MESSAGE_MAX_ATTACHMENTS, isProviderSendTurnSupportedImageMimeType, } from "@t3tools/contracts"; +import { markdownDestinationHostPath } from "@t3tools/shared/markdownLinks"; +import { chatMarkdownImageSources } from "@t3tools/shared/markdownPipeline"; +import { isAbsolutePath, isNetworkPath } from "@t3tools/shared/path"; /** A file from a guest's message request, saved by the multipart parser to a temporary path. */ export interface GuestUpload { @@ -46,6 +49,44 @@ const IMAGE_SIGNATURES: Readonly boolean> startsWith(header, ascii("RIFF")) && startsWith(header, ascii("WEBP"), 8), }; +export const matchesImageSignature = (mimeType: string, header: Uint8Array) => + IMAGE_SIGNATURES[mimeType]?.(header) === true; + +const IMAGE_TYPE_BY_EXTENSION: ReadonlyMap = new Map([ + ["png", "image/png"], + ["jpg", "image/jpeg"], + ["jpeg", "image/jpeg"], + ["gif", "image/gif"], + ["webp", "image/webp"], +]); + +/** + * The type of a host image a guest may ask for by path, or null. A network path never qualifies: + * it would make the host reach out to another machine. + */ +export function guestHostImageType(path: string): string | null { + if (!isAbsolutePath(path) || isNetworkPath(path)) return null; + return IMAGE_TYPE_BY_EXTENSION.get(path.split(".").at(-1)!.toLowerCase()) ?? null; +} + +/** + * Whether an agent reply shows the image at `path`, so the guest already sees it. `imageSources` + * lets the caller reuse a reply's parse across requests. + */ +export function repliesShowImage( + path: string, + replies: ReadonlyArray, + imageSources: (reply: Reply) => ReadonlyArray = (reply) => + chatMarkdownImageSources(reply.text), +) { + // Parsing is the slow part; a reply with no image syntax shows no image. + return replies.some( + (reply) => + (reply.text.includes("![") || / markdownDestinationHostPath(source) === path), + ); +} + /** * Control characters and separators would break the name in headers and on disk, and direction * overrides would let `invoice\u202Efdp.exe` show as a PDF. @@ -76,11 +117,9 @@ export function classifyGuestUploads( upload.contentType.split(";", 1)[0]!.trim().toLowerCase() || "application/octet-stream"; if (upload.sizeBytes === 0) return { ok: false, reason: "unsupported_file" }; if (mimeType.startsWith("image/")) { - const signatureMatches = IMAGE_SIGNATURES[mimeType]; if ( !isProviderSendTurnSupportedImageMimeType(mimeType) || - signatureMatches === undefined || - !signatureMatches(upload.header) + !matchesImageSignature(mimeType, upload.header) ) { return { ok: false, reason: "unsupported_file" }; } diff --git a/apps/server/src/guest/http.ts b/apps/server/src/guest/http.ts index 7c8356119deb5..bf368ac884d92 100644 --- a/apps/server/src/guest/http.ts +++ b/apps/server/src/guest/http.ts @@ -2,6 +2,7 @@ import { GUEST_ATTACHMENT_ROUTE, GUEST_COMMAND_OUTPUT_ROUTE, GUEST_ITEM_ROUTE, + GUEST_MEDIA_ROUTE, GUEST_RENDER_ROUTE, GUEST_ROUTE_PREFIX, GUEST_SHARE_PARAM, @@ -34,6 +35,12 @@ import { GuestShareAccessError, GuestShareService } from "./GuestShareService.ts // Cloudflare closes idle streams after about 100 seconds. const HEARTBEAT_INTERVAL = Duration.seconds(20); const NO_STORE = { "cache-control": "no-store" }; +// A file never runs as a page on this origin, whatever its bytes. +const FILE_HEADERS = { + ...NO_STORE, + "x-content-type-options": "nosniff", + "content-security-policy": "default-src 'none'; sandbox", +}; const decodeRedeem = Schema.decodeUnknownEffect(GuestRedeemRequest); const decodeSubmit = Schema.decodeUnknownEffect(GuestSubmitRequest); @@ -315,9 +322,7 @@ const attachmentRoute = HttpRouter.add( Effect.flatMap(({ path, attachment }) => HttpServerResponse.file(path, { headers: { - ...NO_STORE, - "x-content-type-options": "nosniff", - "content-security-policy": "default-src 'none'; sandbox", + ...FILE_HEADERS, ...(attachment.type === "image" && isProviderSendTurnSupportedImageMimeType(attachment.mimeType) ? { "content-type": attachment.mimeType } @@ -334,6 +339,25 @@ const attachmentRoute = HttpRouter.add( }), ); +// Only an image an agent reply shows loads; anything else on the host is refused. +const mediaRoute = HttpRouter.add( + "GET", + GUEST_MEDIA_ROUTE, + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const path = new URLSearchParams(request.url.split("?", 2)[1] ?? "").get("path"); + if (!path) return yield* badRequest; + const guestShares = yield* GuestShareService; + return yield* guestShares.media(yield* sessionToken, path).pipe( + Effect.flatMap(({ path, mimeType }) => + HttpServerResponse.file(path, { headers: { ...FILE_HEADERS, "content-type": mimeType } }), + ), + Effect.catchTags({ GuestShareAccessError: errorResponse }), + Effect.orElseSucceed(() => HttpServerResponse.empty({ status: 500, headers: NO_STORE })), + ); + }), +); + export const layer = Layer.mergeAll( redeemRoute, sessionRoute, @@ -343,4 +367,5 @@ export const layer = Layer.mergeAll( itemRoute, commandOutputRoute, attachmentRoute, + mediaRoute, ); diff --git a/apps/web/src/components/ChatMarkdown.browser.test.tsx b/apps/web/src/components/ChatMarkdown.browser.test.tsx index d67803a6399ce..345bde84976c3 100644 --- a/apps/web/src/components/ChatMarkdown.browser.test.tsx +++ b/apps/web/src/components/ChatMarkdown.browser.test.tsx @@ -10,6 +10,7 @@ import "../index.css"; import { filesystemEnvironment } from "../state/filesystem"; import { useRightPanelStore } from "../rightPanelStore"; import { setMarkdownTaskChecked } from "./files/filePreviewMode"; +import { HostImageUrlContext } from "./chat/hostImageUrl"; const { workspaceSearch, filesystemMetadata } = vi.hoisted(() => ({ workspaceSearch: vi.fn(), @@ -122,6 +123,22 @@ it("shows unavailable audio when a workspace embed has no thread", async () => { expect(screen.container.querySelector("audio")).toBeNull(); }); +it("loads a host image through the page's own route when there is no environment", async () => { + setup(); + const pixel = + "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="; + const hostImageUrl = vi.fn((_path: string) => pixel); + await using screen = await render( + + + , + ); + await expect.element(screen.getByAltText("Shot")).toHaveAttribute("src", pixel); + expect(new Set(hostImageUrl.mock.calls.map(([path]) => path))).toEqual( + new Set(["/work/my shot.png"]), + ); +}); + describe("ChatMarkdown favicon privacy", () => { it("suppresses private link images while preserving public links across updates", async () => { setup(); diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 2ae3e8d9f971a..32f15bcf542d7 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -65,6 +65,7 @@ import { import { mediaUrlReference } from "@t3tools/client-runtime/media-reference"; import { mediaKindFromPath, mediaMimeTypeFromExtension } from "@t3tools/shared/mediaPreview"; import { InlineAudioPreview } from "./files/InlineAudioPreview"; +import { HostImageUrlContext } from "./chat/hostImageUrl"; import * as Cause from "effect/Cause"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; @@ -1483,6 +1484,24 @@ const CHAT_MARKDOWN_COMPONENTS = { /> ); } + const hostImageUrl = use(HostImageUrlContext); + if (imageSource._tag === "WorkspaceFile" && kind === "image" && hostImageUrl !== null) { + const hostSrc = hostImageUrl(imageSource.path); + return ( + + ); + } if (imageSource._tag === "WorkspaceFile" && threadRef) { return ( string) | null>(null); diff --git a/apps/web/src/components/guest/GuestPage.tsx b/apps/web/src/components/guest/GuestPage.tsx index 3ec7b2d542335..6d72741691f92 100644 --- a/apps/web/src/components/guest/GuestPage.tsx +++ b/apps/web/src/components/guest/GuestPage.tsx @@ -45,6 +45,7 @@ import type { ChatComposerHandle } from "../chat/ChatComposer"; import { ComposerControl, ComposerControlIcon } from "../chat/ComposerControl"; import type { ExpandedImagePreview } from "../chat/ExpandedImagePreview"; import { GuestMessageAttachments } from "../chat/GuestMessageAttachments"; +import { HostImageUrlContext } from "../chat/hostImageUrl"; import { PierreEntryIcon } from "../chat/PierreEntryIcon"; import { GuestMessageName, guestBubbleClassName } from "../chat/guestMessageStyle"; import { MessagesTimeline } from "../chat/MessagesTimeline"; @@ -60,6 +61,7 @@ import { applyGuestStreamEvent, formatGuestExpiry, guestAttachmentUrl, + guestMediaUrl, createGuestAttachmentUrls, guestFilesProblem, initialGuestStreamState, @@ -387,6 +389,7 @@ function GuestThread({ const openFile = useStableCallback((file: { readonly id: string }) => openInNewTab(guestAttachmentUrl(shareId, file.id)), ); + const hostImageUrl = useStableCallback((path: string) => guestMediaUrl(shareId, path)); const activityRun = deriveThreadActivityRun(projection); const runtime = deriveThreadStructureRuntime(projection); const runlessWorkStartedAt = deriveRunlessWorkStartedAt(projection); @@ -448,50 +451,52 @@ function GuestThread({
- - {unplaced.map((message) => ( -
  • - -
  • - ))} - - ) - } - /> + + + {unplaced.map((message) => ( +
  • + +
  • + ))} + + ) + } + /> +
    {follow.showScrollToBottom ? ( `${GUEST_ATTACHMENT_ROUTE}?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}&id=${encodeURIComponent(attachmentId)}`; +/** Where the guest page loads an image file on the host that an agent message embeds. */ +export const guestMediaUrl = (shareId: string, path: string) => + `${GUEST_MEDIA_ROUTE}?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}&path=${encodeURIComponent(path)}`; + /** * Why these files cannot go with one message, or null. The server checks the same limits; this * only says so before the upload. diff --git a/docs/user/guest-links.md b/docs/user/guest-links.md index b97e400c65146..a8631a6c93b28 100644 --- a/docs/user/guest-links.md +++ b/docs/user/guest-links.md @@ -26,9 +26,9 @@ unlinking the machine from T3 Connect also ends it. You can send or dismiss gues ## What the guest sees The guest sees the thread's recent history and everything after, in the same timeline you see, as -it streams: messages and their files, the agent's replies and reasoning, plans, questions, and its -work, with command output when they expand a command. Their composer shows the thread's model, but -they cannot change it. They do not see diffs, and they cannot act on the thread: no forking, +it streams: messages and their files, the agent's replies with the images they show from your +machine, its reasoning, plans, questions, and its work, with command output when they expand a +command. Their composer shows the thread's model, but they cannot change it. They do not see diffs, and they cannot act on the thread: no forking, reverting, opening files on your machine, or answering the agent for you. Anything the agent read or printed can show, such as a value from a file. Share only threads you diff --git a/packages/client-runtime/src/markdownImages.ts b/packages/client-runtime/src/markdownImages.ts index 924220ec27ce4..94cba5c9f842b 100644 --- a/packages/client-runtime/src/markdownImages.ts +++ b/packages/client-runtime/src/markdownImages.ts @@ -1,16 +1,14 @@ import { isNetworkPath, isWindowsAbsolutePath, - stripSlashPrefixedWindowsDrive, workspaceRelativeFilePath, } from "@t3tools/shared/path"; import { + markdownDestinationHostPath, normalizeMarkdownLinkDestination, - safeDecodeURIComponent, splitMarkdownLinkSearchAndHash, } from "@t3tools/shared/markdownLinks"; -import { parseFileUrlHref } from "@t3tools/shared/fileLinks"; const DIRECT_IMAGE_SOURCE_PATTERN = /^(?:https?:|data:|blob:|\/\/)/i; const URI_SCHEME_PATTERN = /^[A-Za-z][A-Za-z0-9+.-]*:/; @@ -59,19 +57,9 @@ export function classifyMarkdownImageSource( return { _tag: "Direct", uri: source }; } - if (/^file:/i.test(source)) { - const target = parseFileUrlHref(source); - return target === null - ? { _tag: "Blocked" } - : hostFileSource( - stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(target.path)), - workspaceRoot, - ); - } - - const path = stripSlashPrefixedWindowsDrive( - safeDecodeURIComponent(splitMarkdownLinkSearchAndHash(source).path), - ); + const path = markdownDestinationHostPath(source); + if (path === null) return { _tag: "Blocked" }; + if (/^file:/i.test(source)) return hostFileSource(path, workspaceRoot); if (path.length === 0) return { _tag: "Blocked" }; if (path.startsWith("/") || isWindowsAbsolutePath(path)) { return hostFileSource(path, workspaceRoot); diff --git a/packages/contracts/src/guestShare.ts b/packages/contracts/src/guestShare.ts index fa4b3a256f013..fd991fe1e4c3b 100644 --- a/packages/contracts/src/guestShare.ts +++ b/packages/contracts/src/guestShare.ts @@ -136,3 +136,8 @@ export const GUEST_COMMAND_OUTPUT_ROUTE = `${GUEST_ROUTE_PREFIX}/command-output` * Images load inline; other files download. */ export const GUEST_ATTACHMENT_ROUTE = `${GUEST_ROUTE_PREFIX}/attachment`; +/** + * An image file on the host that an agent message in the shared thread embeds: + * `?share=&path=`. + */ +export const GUEST_MEDIA_ROUTE = `${GUEST_ROUTE_PREFIX}/media`; diff --git a/packages/shared/src/markdownLinks.ts b/packages/shared/src/markdownLinks.ts index 0445fa42d8a0a..177e6fcbf5008 100644 --- a/packages/shared/src/markdownLinks.ts +++ b/packages/shared/src/markdownLinks.ts @@ -227,6 +227,22 @@ export function splitMarkdownLinkSearchAndHash(value: string): { }; } +/** + * The decoded path a markdown destination names on the host, before any workspace resolution, or + * null for a `file:` URL that does not parse. Clients and the guest media route both read it here. + */ +export function markdownDestinationHostPath(source: string): string | null { + if (/^file:/i.test(source)) { + const target = parseFileUrlHref(source); + return target === null + ? null + : stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(target.path)); + } + return stripSlashPrefixedWindowsDrive( + safeDecodeURIComponent(splitMarkdownLinkSearchAndHash(source).path), + ); +} + export function isMarkdownFileLinkLabel(label: string, href: string): boolean { const destination = parseMarkdownFileLink(href); if (!destination) return false; diff --git a/packages/shared/src/markdownPipeline.ts b/packages/shared/src/markdownPipeline.ts index 275b93b562f6b..fe3d73ddac65c 100644 --- a/packages/shared/src/markdownPipeline.ts +++ b/packages/shared/src/markdownPipeline.ts @@ -1,6 +1,8 @@ import type { Paragraph, PhrasingContent, Root, RootContent } from "mdast"; import { remarkKeepWindowsPaths } from "./markdownWindowsPaths.ts"; -import type { PluggableList } from "unified"; +import { type PluggableList, unified } from "unified"; +import remarkParse from "remark-parse"; +import remarkRehype from "remark-rehype"; import rehypeRaw from "rehype-raw"; import rehypeSanitize, { defaultSchema } from "rehype-sanitize"; import remarkBreaks from "remark-breaks"; @@ -11,7 +13,7 @@ import { CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES, remarkCodexDirectives, } from "./codexMarkdownDirectives.ts"; -import { isWindowsDrivePathHref } from "./markdownLinks.ts"; +import { isWindowsDrivePathHref, normalizeMarkdownLinkDestination } from "./markdownLinks.ts"; import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts"; type MarkdownImageHastNode = { @@ -304,3 +306,38 @@ function remarkNormalizeLinksAndTagInlineCode() { export function shouldPreserveAssistantLineBreaks(text: string): boolean { return /^★ Insight(?:\s|─)/mu.test(text); } + +const imageSourceProcessor = unified() + .use(remarkParse) + .use(CHAT_MARKDOWN_REMARK_PLUGINS) + .use(remarkRehype, { allowDangerousHtml: true }) + .use(CHAT_MARKDOWN_REHYPE_PLUGINS); + +interface ImageSourceNode { + readonly type: string; + readonly tagName?: string; + readonly properties?: { readonly src?: unknown; readonly dataLocalSrc?: unknown }; + readonly children?: ReadonlyArray; +} + +/** + * The sources of the images chat markdown shows, read as ChatMarkdown's `img` renderer reads + * them. Code, comments, and plain links show no image, so they add none. + */ +export function chatMarkdownImageSources(markdown: string): Array { + const sources: Array = []; + const visit = (node: ImageSourceNode) => { + if (node.type === "element" && node.tagName === "img") { + const { src, dataLocalSrc } = node.properties ?? {}; + // The sanitizer drops a Windows drive path from `src`; the renderer reads it from here. + if (typeof dataLocalSrc === "string") { + sources.push(normalizeMarkdownLinkDestination(dataLocalSrc).replaceAll("\\", "/")); + } else if (typeof src === "string") { + sources.push(normalizeMarkdownLinkDestination(src)); + } + } + node.children?.forEach(visit); + }; + visit(imageSourceProcessor.runSync(imageSourceProcessor.parse(markdown)) as ImageSourceNode); + return sources; +} From a9418a1206f9f092d6d5769f6a62fb8da2ecc6ec Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Tue, 27 Oct 2026 23:53:18 -0700 Subject: [PATCH 192/817] ci(release): releases no longer reinstall Vite+ in every job (#26305) Co-authored-by: Claude Opus 5.5 --- .github/actions/setup-ci-deps/action.yml | 61 ++++++++++++--- .github/workflows/release-desktop.yml | 13 +--- .github/workflows/release.yml | 98 +++++++----------------- 3 files changed, 83 insertions(+), 89 deletions(-) diff --git a/.github/actions/setup-ci-deps/action.yml b/.github/actions/setup-ci-deps/action.yml index e0ef427bd1d36..afaef17e1c310 100644 --- a/.github/actions/setup-ci-deps/action.yml +++ b/.github/actions/setup-ci-deps/action.yml @@ -5,6 +5,14 @@ inputs: description: Read-only credential for the private maintainer task cache required: false default: "" + install: + description: Set to "false" to set up Vite+ only, with no pnpm store or install + required: false + default: "true" + install-args: + description: Arguments for `vp install`, such as filters. Empty installs the whole workspace. + required: false + default: "" runs: using: composite steps: @@ -19,10 +27,11 @@ runs: echo "node=$(jq -r '.engines.node' package.json)" >> "$GITHUB_OUTPUT" echo "pnpm=$(jq -r '.packageManager' package.json)" >> "$GITHUB_OUTPUT" + # Pinned because release-desktop.yml signs builds with this action in the job. - name: Cache Vite+ id: vp_cache if: steps.vp.outputs.version != '' - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 with: path: ~/.vite-plus key: vite-plus-home-v2-${{ runner.os }}-${{ runner.arch }}-${{ steps.vp.outputs.version }}-node${{ steps.vp.outputs.node }}-${{ steps.vp.outputs.pnpm }} @@ -40,36 +49,66 @@ runs: - name: Setup Vite+ if: steps.vp_cache.outputs.cache-hit != 'true' - uses: voidzero-dev/setup-vp@v1 + uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1 with: node-version-file: package.json cache: false run-install: false - - name: Resolve pnpm store path + # A shared key lets whichever install saves first, often a small filtered + # one, become every job's store. Each set of install args gets its own. + - name: Resolve pnpm store id: pnpm_store + if: inputs.install == 'true' shell: bash + env: + INSTALL_ARGS: ${{ inputs.install-args }} run: | - store_path="$(vp pm cache dir)" - echo "path=$store_path" >> "$GITHUB_OUTPUT" + echo "path=$(vp pm cache dir)" >> "$GITHUB_OUTPUT" + if [[ -z "$INSTALL_ARGS" ]]; then + echo "namespace=full" >> "$GITHUB_OUTPUT" + else + echo "namespace=filtered-$(printf '%s' "$INSTALL_ARGS" | cksum | cut -d' ' -f1)" >> "$GITHUB_OUTPUT" + fi - # setup-vp's shared cache key ignores install filters. Keep full installs in a - # separate namespace, including fallback restores. + # Filtered installs prefer the current full store, which holds every package, + # over an older store of their own. # The pnpm store stays a cache tarball on the runner's own disk. A store on a # Blacksmith sticky disk mounts in under a second, but pnpm then copies every # package across filesystems instead of hard-linking it: install took 28-49s # against 9s plus an 11s restore. - - name: Cache full pnpm store - uses: actions/cache@v6 + - name: Restore pnpm store + id: pnpm_cache + if: inputs.install == 'true' + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 with: path: ${{ steps.pnpm_store.outputs.path }} - key: pnpm-full-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml', 'pnpm-workspace.yaml', 'package.json') }} + key: pnpm-${{ steps.pnpm_store.outputs.namespace }}-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml', 'pnpm-workspace.yaml', 'package.json') }} restore-keys: | + pnpm-full-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml', 'pnpm-workspace.yaml', 'package.json') }} + pnpm-${{ steps.pnpm_store.outputs.namespace }}-v1-${{ runner.os }}-${{ runner.arch }}- pnpm-full-v1-${{ runner.os }}-${{ runner.arch }}- - name: Install dependencies + if: inputs.install == 'true' shell: bash - run: vp install + env: + INSTALL_ARGS: ${{ inputs.install-args }} + # Unquoted so each filter is its own argument. + run: vp install $INSTALL_ARGS + + # A filtered install that started from the current full store adds nothing + # worth a second copy of it. + - name: Save pnpm store + if: >- + inputs.install == 'true' && + steps.pnpm_cache.outputs.cache-hit != 'true' && + (steps.pnpm_store.outputs.namespace == 'full' || + steps.pnpm_cache.outputs.cache-matched-key != format('pnpm-full-v1-{0}-{1}-{2}', runner.os, runner.arch, hashFiles('pnpm-lock.yaml', 'pnpm-workspace.yaml', 'package.json'))) + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 + with: + path: ${{ steps.pnpm_store.outputs.path }} + key: ${{ steps.pnpm_cache.outputs.cache-primary-key }} - name: Enable shared task cache if: >- diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml index bff1b125be44b..ca418467f6b9c 100644 --- a/.github/workflows/release-desktop.yml +++ b/.github/workflows/release-desktop.yml @@ -147,13 +147,6 @@ jobs: git sparse-checkout set --no-cone '/*' '!/.repos/' git -c checkout.workers=0 checkout --detach FETCH_HEAD - - name: Setup Vite+ - uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1 - with: - node-version-file: package.json - cache: true - run-install: false - # pnpm checks the lockfile and policy before reusing this result. A missing # artifact leaves the cache empty, so installation runs the checks again. - name: Download dependency verification @@ -163,10 +156,12 @@ jobs: name: release-dependency-verification path: ${{ runner.temp }}/pnpm-metadata - - name: Install desktop dependencies + - name: Setup dependencies + uses: ./.github/actions/setup-ci-deps + with: + install-args: --filter=@t3tools/desktop... --filter=t3... --filter=@t3tools/scripts... env: pnpm_config_cache_dir: ${{ runner.temp }}/pnpm-metadata - run: vp install --filter=@t3tools/desktop... --filter=t3... --filter=@t3tools/scripts... - name: Cache resource monitor id: resource_monitor_cache diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 33076d208f3a4..e8f300242f054 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -420,14 +420,10 @@ jobs: !/.repos/ sparse-checkout-cone-mode: false - - name: Setup Vite+ - uses: voidzero-dev/setup-vp@v1 + - name: Setup dependencies + uses: ./.github/actions/setup-ci-deps with: - node-version-file: package.json - cache: true - run-install: | - args: - - --filter=t3code-relay... + install-args: --filter=t3code-relay... # The deployed stack's outputs, read from Alchemy's state store without # planning or applying. Select the backend explicitly to avoid loading @@ -522,13 +518,6 @@ jobs: !/.repos/ sparse-checkout-cone-mode: false - - name: Setup Vite+ - uses: voidzero-dev/setup-vp@v1 - with: - node-version-file: package.json - cache: true - run-install: false - # pnpm checks the lockfile and policy before reusing this result. A missing # artifact leaves the cache empty, so installation runs the checks again. - name: Download dependency verification @@ -538,10 +527,12 @@ jobs: name: release-dependency-verification path: ${{ runner.temp }}/pnpm-metadata - - name: Install bundle dependencies + - name: Setup dependencies + uses: ./.github/actions/setup-ci-deps + with: + install-args: --filter=t3... --filter=@t3tools/web... --filter=@t3tools/desktop... --filter=@t3tools/scripts... env: pnpm_config_cache_dir: ${{ runner.temp }}/pnpm-metadata - run: vp install --filter=t3... --filter=@t3tools/web... --filter=@t3tools/desktop... --filter=@t3tools/scripts... - name: Download relay client tracing config uses: actions/download-artifact@v8 @@ -781,14 +772,10 @@ jobs: !/.repos/ sparse-checkout-cone-mode: false - - name: Setup Vite+ - uses: voidzero-dev/setup-vp@v1 + - name: Setup dependencies + uses: ./.github/actions/setup-ci-deps with: - node-version-file: package.json - cache: true - run-install: | - args: - - --filter=@t3tools/scripts... + install-args: --filter=@t3tools/scripts... - name: Download all desktop artifacts uses: actions/download-artifact@v8 @@ -977,15 +964,10 @@ jobs: !/.repos/ sparse-checkout-cone-mode: false - - name: Setup Vite+ - uses: voidzero-dev/setup-vp@v1 + - name: Setup dependencies + uses: ./.github/actions/setup-ci-deps with: - node-version-file: package.json - cache: true - run-install: | - args: - - --filter=t3... - - --filter=@t3tools/scripts... + install-args: --filter=t3... --filter=@t3tools/scripts... - name: Build the npm launcher run: node scripts/build-npm-launcher.ts --version "${{ needs.preflight.outputs.version }}" --output-dir npm-packages @@ -1041,15 +1023,10 @@ jobs: !/.repos/ sparse-checkout-cone-mode: false - - name: Setup Vite+ - uses: voidzero-dev/setup-vp@v1 + - name: Setup dependencies + uses: ./.github/actions/setup-ci-deps with: - node-version-file: package.json - cache: true - run-install: | - args: - - --filter=@t3tools/scripts... - - --filter=@t3tools/web... + install-args: --filter=@t3tools/scripts... --filter=@t3tools/web... - name: Download relay client tracing config uses: actions/download-artifact@v8 @@ -1145,11 +1122,9 @@ jobs: sparse-checkout-cone-mode: false - name: Setup Vite+ - uses: voidzero-dev/setup-vp@v1 + uses: ./.github/actions/setup-ci-deps with: - node-version-file: package.json - cache: false - run-install: false + install: false - name: Alias channel shell: bash @@ -1216,14 +1191,10 @@ jobs: !/.repos/ sparse-checkout-cone-mode: false - - name: Setup Vite+ - uses: voidzero-dev/setup-vp@v1 + - name: Setup dependencies + uses: ./.github/actions/setup-ci-deps with: - node-version-file: package.json - cache: true - run-install: | - args: - - --filter=@t3tools/marketing... + install-args: --filter=@t3tools/marketing... - id: deploy name: Build staged deployment @@ -1287,11 +1258,9 @@ jobs: sparse-checkout-cone-mode: false - name: Setup Vite+ - uses: voidzero-dev/setup-vp@v1 + uses: ./.github/actions/setup-ci-deps with: - node-version-file: package.json - cache: false - run-install: false + install: false - name: Promote marketing site shell: bash @@ -1346,15 +1315,10 @@ jobs: echo "name=${APP_SLUG}[bot]" >> "$GITHUB_OUTPUT" echo "email=${user_id}+${APP_SLUG}[bot]@users.noreply.github.com" >> "$GITHUB_OUTPUT" - - name: Setup Vite+ - uses: voidzero-dev/setup-vp@v1 + - name: Setup dependencies + uses: ./.github/actions/setup-ci-deps with: - node-version-file: package.json - cache: true - run-install: | - args: - - --filter=@t3tools/scripts... - - --filter=@t3tools/oxlint-plugin-t3code... + install-args: --filter=@t3tools/scripts... --filter=@t3tools/oxlint-plugin-t3code... - id: update_versions name: Update version strings @@ -1411,14 +1375,10 @@ jobs: !/.repos/ sparse-checkout-cone-mode: false - - name: Setup Vite+ - uses: voidzero-dev/setup-vp@v1 + - name: Setup dependencies + uses: ./.github/actions/setup-ci-deps with: - node-version-file: package.json - cache: true - run-install: | - args: - - --filter=@t3tools/scripts... + install-args: --filter=@t3tools/scripts... - name: Read published release notes if: needs.preflight.outputs.is_prerelease == 'true' From f6d3700ac3c506250260fcb143c5e795cbbaeb9f Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Tue, 27 Oct 2026 23:55:40 -0700 Subject: [PATCH 193/817] ci: server test shards survive a throttled task cache (#26332) Co-authored-by: Claude Opus 5.5 --- .github/workflows/ci.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ca294dd4a701a..e4c45728c2342 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -354,7 +354,9 @@ jobs: id-token: write name: Test Server ${{ matrix.shard }} runs-on: blacksmith-4vcpu-ubuntu-2404 - timeout-minutes: 10 + # Shards take 2-5 minutes. When the shared task cache throttles reads, each + # failed fetch stalls vp for 15-90s, which pushed shards past 10 minutes. + timeout-minutes: 20 strategy: fail-fast: false matrix: From 4e4d4ba3959cae17db7bba1915e6a25885844484 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Wed, 28 Oct 2026 00:05:49 -0700 Subject: [PATCH 194/817] feat(web): boring sidebar groups threads into project folders (#21039) Co-authored-by: Claude Opus 5.5 --- .../settings/DesktopClientSettings.test.ts | 2 +- apps/web/package.json | 1 - apps/web/src/components/AppSidebarLayout.tsx | 10 +- apps/web/src/components/LegacySidebar.tsx | 3743 ----------------- apps/web/src/components/Sidebar.logic.test.ts | 98 + apps/web/src/components/Sidebar.logic.ts | 125 +- apps/web/src/components/Sidebar.tsx | 144 +- .../src/components/ThreadStatusIndicators.tsx | 4 +- .../components/settings/LabsSettingsPanel.tsx | 23 + .../components/settings/SettingsPanels.tsx | 19 +- .../settings/settingsSearch.test.ts | 2 +- .../src/components/settings/settingsSearch.ts | 12 +- .../sidebar/SidebarProjectFolderHeader.tsx | 115 + .../components/sidebar/SidebarThreadRow.tsx | 84 +- apps/web/src/components/ui/sidebar.tsx | 2 +- apps/web/src/connection/desktopLocal.ts | 4 - apps/web/src/hooks/useMediaQuery.ts | 4 - apps/web/src/hooks/useSettings.ts | 10 +- apps/web/src/shortcuts/chatRouteCommands.ts | 6 +- .../src/state/use-orchestration-command.ts | 3 +- docs/user/thread-sidebar.md | 9 + .../src/state/projectGrouping.ts | 2 +- packages/contracts/src/settings.ts | 18 +- pnpm-lock.yaml | 8 - 24 files changed, 549 insertions(+), 3899 deletions(-) delete mode 100644 apps/web/src/components/LegacySidebar.tsx create mode 100644 apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx diff --git a/apps/desktop/src/settings/DesktopClientSettings.test.ts b/apps/desktop/src/settings/DesktopClientSettings.test.ts index 9f76003c19c8d..ac4c6e61378e3 100644 --- a/apps/desktop/src/settings/DesktopClientSettings.test.ts +++ b/apps/desktop/src/settings/DesktopClientSettings.test.ts @@ -63,7 +63,7 @@ const clientSettings: ClientSettings = { }, sidebarProjectSortOrder: "manual", sidebarThreadSortOrder: "created_at", - sidebarThreadPreviewCount: 6, + boringSidebarEnabled: false, legacySidebarEnabled: false, sidebarWorkingShelfEnabled: false, loadBalancingEnabled: false, diff --git a/apps/web/package.json b/apps/web/package.json index de75da24e380b..729d44f8ea6cd 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -27,7 +27,6 @@ "@dnd-kit/utilities": "^3.2.2", "@effect/atom-react": "catalog:", "@fontsource-variable/inter": "^5.3.0", - "@formkit/auto-animate": "^0.9.0", "@legendapp/list": "catalog:", "@noble/hashes": "catalog:", "@pierre/diffs": "catalog:", diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx index 20abcf1e57ade..6c8837e63f40a 100644 --- a/apps/web/src/components/AppSidebarLayout.tsx +++ b/apps/web/src/components/AppSidebarLayout.tsx @@ -31,14 +31,13 @@ import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore"; import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore"; import { cn, isMacPlatform } from "../lib/utils"; import { primaryServerKeybindingsAtom } from "../state/server"; -import { useEnvironmentIdentificationMode, useLegacySidebarEnabled } from "../hooks/useSettings"; +import { useEnvironmentIdentificationMode } from "../hooks/useSettings"; import { PanelAnimationSuppressionProvider, usePanelAnimationSettings, usePanelNavigationSuppression, } from "../panelAnimations"; import { BackgroundThreadAnnouncer } from "./BackgroundThreadAnnouncer"; -import LegacyThreadSidebar from "./LegacySidebar"; import ThreadSidebar from "./Sidebar"; import { SidebarBrandWidthProbe } from "./sidebar/SidebarChrome"; import { isAppModalPage } from "./sidebar/mainAppLocation"; @@ -403,7 +402,6 @@ function SidebarControl() { export function AppSidebarLayout({ children }: { children: ReactNode }) { const sidebarArea = workspaceAreaProps("sidebar", 0, "Threads"); - const legacySidebarEnabled = useLegacySidebarEnabled(); const [sidebarRouteReveal] = useState(() => ({ observedKey: null, pendingKey: null, @@ -470,11 +468,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) { }} style={windowControlsInsetStyle} > - {legacySidebarEnabled ? ( - - ) : ( - - )} + {children} diff --git a/apps/web/src/components/LegacySidebar.tsx b/apps/web/src/components/LegacySidebar.tsx deleted file mode 100644 index 27ea62b61511a..0000000000000 --- a/apps/web/src/components/LegacySidebar.tsx +++ /dev/null @@ -1,3743 +0,0 @@ -import { attachSidebarTree, SIDEBAR_TREE_PROPS } from "../lib/sidebarTree"; -import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests"; -import { resolveThreadCurrentPullRequestLink } from "@t3tools/client-runtime/thread-pull-requests"; -import { Spinner } from "~/components/ui/spinner"; -import { - ArchiveIcon, - ArrowUpDownIcon, - ChevronRightIcon, - FolderPlusIcon, - Globe2Icon, - SearchIcon, - SquarePenIcon, - TriangleAlertIcon, -} from "lucide-react"; -import { - ChangeRequestStatusIcon, - prStatusIndicator, - PrStatusTooltipContent, - ThreadTerminalStatusButton, - ThreadStatusLabel, - ThreadWorktreeIndicator, - useLinkedThreadPullRequest, -} from "./ThreadStatusIndicators"; -import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon"; -import { ProjectFavicon } from "./ProjectFavicon"; -import { useAtomValue } from "@effect/atom-react"; -import { autoAnimate } from "@formkit/auto-animate"; -import React, { - createContext, - useEffect, - useEffectEvent, - memo, - useContext, - useRef, - useState, -} from "react"; -import { cn } from "~/lib/utils"; -import { useShallow } from "zustand/react/shallow"; -import { - DndContext, - type DragCancelEvent, - type CollisionDetection, - PointerSensor, - type DragStartEvent, - closestCorners, - pointerWithin, - useSensor, - useSensors, - type DragEndEvent, -} from "@dnd-kit/core"; -import { SortableContext, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable"; -import { restrictToFirstScrollableAncestor, restrictToVerticalAxis } from "@dnd-kit/modifiers"; -import { CSS } from "@dnd-kit/utilities"; -import { - AuthOrchestrationOperateScope, - AuthPreviewOperateScope, - type ContextMenuItem, - type EnvironmentId, - ProjectId, - type ScopedThreadRef, - type ResolvedKeybindingsConfig, - type SidebarProjectGroupingMode, - resolveEnvironmentMachineKind, - ThreadId, -} from "@t3tools/contracts"; -import { - parseScopedThreadKey, - scopedProjectKey, - scopedThreadKey, - scopeProjectRef, - scopeThreadRef, -} from "@t3tools/client-runtime/environment"; -import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors"; -import { - isAtomCommandInterrupted, - settlePromise, - squashAtomCommandFailure, -} from "@t3tools/client-runtime/state/runtime"; -import { threadRuntimeCanArchive } from "@t3tools/client-runtime/state/models"; -import { useNavigate, useRouter } from "@tanstack/react-router"; -import { - MAX_SIDEBAR_THREAD_PREVIEW_COUNT, - MIN_SIDEBAR_THREAD_PREVIEW_COUNT, - type SidebarProjectSortOrder, - type SidebarThreadPreviewCount, - type SidebarThreadSortOrder, -} from "@t3tools/contracts/settings"; -import { isDesktopLocalConnectionTarget, isWslConnectionTarget } from "../connection/desktopLocal"; -import { useDesktopLocalBootstraps } from "../connection/useDesktopLocalBootstraps"; -import { isElectron } from "../env"; -import { useStableCallback } from "../hooks/useStableCallback"; -import { useTerminalFocus } from "../hooks/useTerminalFocus"; -import { useOpenPrLink } from "../lib/openPullRequestLink"; -import { releaseProjectDraftUploads } from "../lib/composerDraftUploads"; -import { isTerminalFocused } from "../lib/terminalFocus"; -import { isMacPlatform } from "../lib/utils"; -import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore"; -import { makeWorkspaceFileDropHandlers } from "./chat/workspaceFileDrop"; -import { - readThreadShell, - useProjects, - useDelegatedUnderParent, - useThreadShells, - useThreadShellsForProjectRefs, - waitForProjectRemoval, -} from "../state/entities"; -import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore"; -import { useThreadRunningTerminalIds } from "../state/terminalSessions"; -import { useThreadDiscoveredPorts } from "../portDiscoveryState"; -import { openDiscoveredPort } from "./preview/openDiscoveredPort"; -import { useAtomCommand } from "../state/use-atom-command"; -import { - ORCHESTRATION_OPERATE_DENIED_MESSAGE, - useOrchestrationCommand, -} from "../state/use-orchestration-command"; -import { previewEnvironment } from "../state/preview"; -import { readEnvironmentScope, useEnvironmentScope } from "../state/session"; -import { - legacyProjectCwdPreferenceKey, - resolveProjectExpanded, - useUiStateStore, -} from "../uiStateStore"; -import { - resolveShortcutCommand, - shortcutLabelForCommand, - shouldShowThreadJumpHintsForModifiers, - threadJumpCommandForIndex, - threadJumpIndexFromCommand, - threadTraversalDirectionFromCommand, -} from "../keybindings"; -import { isModelPickerOpen } from "../modelPickerVisibility"; -import { useShortcutModifierState } from "../shortcutModifierState"; -import { ensureLocalApi, readLocalApi } from "../localApi"; -import { useComposerDraftStore } from "../composerDraftStore"; -import { useNewThreadHandler } from "../hooks/useHandleNewThread"; -import { useDesktopUpdateState } from "../state/desktopUpdate"; - -import { useThreadActions } from "../hooks/useThreadActions"; -import { projectEnvironment } from "../state/projects"; -import { threadEnvironment, useEnvironmentThread } from "../state/threads"; -import { readUnloadedThreadCount } from "../state/olderSettledShelf"; -import { useEnvironment, useEnvironments, usePrimaryEnvironmentId } from "../state/environments"; -import { buildThreadRouteParams, resolveActiveThreadRouteRef } from "../threadRoutes"; -import { stackedThreadToast, toastManager } from "./ui/toast"; -import { copyThreadReference } from "../lib/copyThreadReference"; -import { threadChipCopyTarget } from "@t3tools/client-runtime/thread-reference"; -import { RelativeTime } from "./RelativeTime"; -import { Kbd } from "./ui/kbd"; -import { - getArm64IntelBuildWarningDescription, - getDesktopUpdateActionError, - getDesktopUpdateInstallConfirmationMessage, - isDesktopUpdateButtonDisabled, - resolveDesktopUpdateButtonAction, - shouldShowArm64IntelBuildWarning, - shouldToastDesktopUpdateActionResult, -} from "./desktopUpdate.logic"; -import { showDesktopUpdateDownloadedToast } from "./desktopUpdate.toast"; -import { Alert, AlertAction, AlertDescription, AlertTitle } from "./ui/alert"; -import { Button } from "./ui/button"; -import { - Dialog, - DialogDescription, - DialogFooter, - DialogHeader, - DialogPanel, - DialogPopup, - DialogTitle, -} from "./ui/dialog"; -import { Input } from "./ui/input"; -import { Menu, MenuGroup, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "./ui/menu"; -import { - NumberField, - NumberFieldDecrement, - NumberFieldGroup, - NumberFieldIncrement, - NumberFieldInput, -} from "./ui/number-field"; -import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; -import { - SidebarContent, - SidebarGroup, - SidebarMenu, - SidebarMenuButton, - SidebarMenuItem, - SidebarMenuSub, - SidebarMenuSubButton, - SidebarMenuSubItem, - useSidebar, -} from "./ui/sidebar"; -import { - getThreadKeysToDeselectAfterDelete, - useThreadSelectionStore, -} from "../threadSelectionStore"; -import { isCommandPaletteOpen, openCommandPalette } from "../commandPaletteBus"; -import { - archiveSelectedThreadEntries, - buildMultiSelectThreadContextMenuItems, - deleteSelectedThreadEntries, - filterSidebarV2VisibleThreads, - getSidebarThreadIdsToPrewarm, - resolveAdjacentThreadId, - isContextMenuPointerDown, - isSidebarNestedLinkClick, - isTrailingDoubleClick, - resolveProjectStatusIndicator, - resolveThreadLastVisitedAt, - resolveThreadStatusPill, - orderItemsByPreferredIds, - shouldClearThreadSelectionOnMouseDown, - sortProjectsForSidebar, - useSidebarRowSubscriptionLease, - setFileDragActive, - useThreadJumpHintsVisible, - ThreadStatusPill, -} from "./Sidebar.logic"; -import { sortThreads } from "@t3tools/client-runtime/state/thread-sort"; -import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome"; -import { useCopyToClipboard } from "~/hooks/useCopyToClipboard"; -import { useIsMobile } from "~/hooks/useMediaQuery"; -import { CommandDialogTrigger } from "./ui/command"; -import { useClientSettings, updateClientSettings } from "~/hooks/useSettings"; -import { primaryServerKeybindingsAtom } from "../state/server"; -import { appAtomRegistry } from "../rpc/atomRegistry"; -import { canShareWithGuestAtom } from "./chat/guestShareAvailability"; -import { openGuestShareDialog } from "./chat/guestShareDialogState"; -import { - derivePhysicalProjectKey, - deriveProjectGroupingOverrideKey, - getProjectOrderKey, - selectProjectGroupingSettings, -} from "@t3tools/client-runtime/state/project-grouping"; -import type { SidebarThreadSummary } from "../types"; -import { - buildPhysicalToLogicalProjectKeyMap, - buildSidebarProjectSnapshots, - type SidebarProjectGroupMember, - type SidebarProjectSnapshot, -} from "../sidebarProjectGrouping"; -import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons"; -import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget"; -import { type SidebarRouteReveal, useActiveRowReveal } from "./sidebar/routeReveal"; -const SIDEBAR_SORT_LABELS: Record = { - updated_at: "Last user message", - created_at: "Created at", - manual: "Manual", -}; -const SIDEBAR_THREAD_SORT_LABELS: Record = { - updated_at: "Last user message", - created_at: "Created at", -}; -const SIDEBAR_LIST_ANIMATION_OPTIONS = { - duration: 180, - easing: "ease-out", -} as const; -const EMPTY_THREAD_JUMP_LABELS = new Map(); -const PROJECT_GROUPING_MODE_LABELS: Record = { - repository: "Group by repository", - repository_path: "Group by repository path", - separate: "Keep separate", -}; -const SIDEBAR_ICON_ACTION_BUTTON_CLASS = - "inline-flex h-6 min-w-6 cursor-pointer items-center justify-center rounded-md px-0.75 text-icon-muted hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring"; - -function SidebarThreadDetailPrewarmer({ threadRef }: { readonly threadRef: ScopedThreadRef }) { - useEnvironmentThread(threadRef.environmentId, threadRef.threadId); - return null; -} - -function clampSidebarThreadPreviewCount(value: number): SidebarThreadPreviewCount { - return Math.min( - MAX_SIDEBAR_THREAD_PREVIEW_COUNT, - Math.max(MIN_SIDEBAR_THREAD_PREVIEW_COUNT, value), - ) as SidebarThreadPreviewCount; -} - -function formatProjectMemberActionLabel( - member: SidebarProjectGroupMember, - groupedProjectCount: number, -): string { - if (groupedProjectCount <= 1) { - return member.title; - } - - return member.environmentLabel - ? `${member.environmentLabel}: ${member.workspaceRoot}` - : member.workspaceRoot; -} - -function projectExpansionPreferenceKeys(project: SidebarProjectSnapshot): string[] { - return [ - project.projectKey, - ...project.memberProjects.map((member) => member.physicalProjectKey), - ...project.memberProjects.map((member) => legacyProjectCwdPreferenceKey(member.workspaceRoot)), - ]; -} - -function projectGroupingModeDescription(mode: SidebarProjectGroupingMode): string { - switch (mode) { - case "repository": - return "Projects from the same repository share one sidebar row."; - case "repository_path": - return "Projects group only when both the repository and repo-relative path match."; - case "separate": - return "Every project path gets its own sidebar row."; - } -} - -function buildThreadJumpLabelMap(input: { - keybindings: ResolvedKeybindingsConfig; - platform: string; - terminalOpen: boolean; - threadJumpCommandByKey: ReadonlyMap< - string, - NonNullable> - >; -}): ReadonlyMap { - if (input.threadJumpCommandByKey.size === 0) { - return EMPTY_THREAD_JUMP_LABELS; - } - - const shortcutLabelOptions = { - platform: input.platform, - context: { - terminalFocus: false, - terminalOpen: input.terminalOpen, - }, - } as const; - const mapping = new Map(); - for (const [threadKey, command] of input.threadJumpCommandByKey) { - const label = shortcutLabelForCommand(input.keybindings, command, shortcutLabelOptions); - if (label) { - mapping.set(threadKey, label); - } - } - return mapping.size > 0 ? mapping : EMPTY_THREAD_JUMP_LABELS; -} - -interface SidebarThreadRowProps { - navigationParent?: string | undefined; - thread: SidebarThreadSummary; - orderedProjectThreadKeys: readonly string[]; - isActive: boolean; - openPullRequestsInRightPanel: boolean; - jumpLabel: string | null; - appSettingsConfirmThreadArchive: boolean; - renamingThreadKey: string | null; - renamingTitle: string; - setRenamingTitle: (title: string) => void; - startThreadRename: (threadKey: string, title: string) => void; - renamingInputRef: React.RefObject; - renamingCommittedRef: React.RefObject; - confirmingArchiveThreadKey: string | null; - setConfirmingArchiveThreadKey: React.Dispatch>; - confirmArchiveButtonRefs: React.RefObject>; - handleThreadClick: ( - event: React.MouseEvent, - threadRef: ScopedThreadRef, - orderedProjectThreadKeys: readonly string[], - ) => void; - navigateToThread: (threadRef: ScopedThreadRef) => Promise; - handleMultiSelectContextMenu: (position: { x: number; y: number }) => Promise; - handleThreadContextMenu: ( - threadRef: ScopedThreadRef, - position: { x: number; y: number }, - ) => Promise; - clearSelection: () => void; - commitRename: ( - threadRef: ScopedThreadRef, - newTitle: string, - originalTitle: string, - ) => Promise; - cancelRename: () => void; - attemptArchiveThread: (threadRef: ScopedThreadRef) => Promise; - openPrLink: ( - event: React.MouseEvent, - prUrl: string, - threadRef?: ScopedThreadRef, - ) => boolean; - onFileDropThreads: (threadRef: ScopedThreadRef, files: File[]) => void; -} - -function checkTaskPermission(environmentId: EnvironmentId): boolean { - if (readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return true; - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Action unavailable", - description: ORCHESTRATION_OPERATE_DENIED_MESSAGE, - }), - ); - return false; -} - -// The active row reports itself, so a route change scrolls to it once it mounts. -const RevealActiveRowContext = createContext<(row: HTMLElement | null, threadKey: string) => void>( - () => {}, -); - -const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowProps) { - const { - orderedProjectThreadKeys, - isActive, - openPullRequestsInRightPanel, - jumpLabel, - appSettingsConfirmThreadArchive, - renamingThreadKey, - renamingTitle, - setRenamingTitle, - startThreadRename, - renamingInputRef, - renamingCommittedRef, - confirmingArchiveThreadKey, - setConfirmingArchiveThreadKey, - confirmArchiveButtonRefs, - handleThreadClick, - navigateToThread, - handleMultiSelectContextMenu, - handleThreadContextMenu, - clearSelection, - commitRename, - cancelRename, - attemptArchiveThread, - openPrLink, - onFileDropThreads, - thread, - } = props; - const canOperateThread = useEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope); - const canOperatePreview = useEnvironmentScope(thread.environmentId, AuthPreviewOperateScope); - const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); - const [isFileDragOver, setIsFileDragOver] = useState(false); - const revealActiveRow = useContext(RevealActiveRowContext); - const { leaseLiveStatus, rowRef } = useSidebarRowSubscriptionLease(isActive); - const localLastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]); - const lastVisitedAt = resolveThreadLastVisitedAt(thread.lastVisitedAt, localLastVisitedAt); - const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey)); - const runningTerminalIds = useThreadRunningTerminalIds({ - environmentId: thread.environmentId, - threadId: thread.id, - }); - const isMobile = useIsMobile(); - const discoveredPorts = useThreadDiscoveredPorts({ - environmentId: thread.environmentId, - threadId: thread.id, - }); - const openPreview = useAtomCommand(previewEnvironment.open, { - reportFailure: false, - }); - const environment = useEnvironment(thread.environmentId); - const primaryEnvironmentId = usePrimaryEnvironmentId(); - const isRemoteThread = thread.environmentId !== primaryEnvironmentId; - const remoteEnvLabel = environment?.label ?? null; - const remoteMachine = resolveEnvironmentMachineKind(environment?.serverConfig ?? null); - const isDesktopLocalThread = - environment !== null && isDesktopLocalConnectionTarget(environment.entry.target); - const threadEnvironmentLabel = isRemoteThread - ? (remoteEnvLabel ?? (isDesktopLocalThread ? "Local" : "Remote")) - : null; - const isThreadRunning = !threadRuntimeCanArchive(thread.runtime); - const threadStatus = resolveThreadStatusPill({ - thread: { - ...thread, - lastVisitedAt, - }, - }); - const linkedPullRequestStatus = useLinkedThreadPullRequest( - thread.environmentId, - thread.linkedPullRequest, - leaseLiveStatus, - thread.pullRequests, - thread.branchPullRequest, - ); - const pr = linkedPullRequestStatus?.pr ?? null; - const supportsMultiplePullRequests = useSupportsMultiplePullRequests(thread.environmentId); - // Hooks must precede this ref's plain uses for the compiler to cache it. - const threadRef = scopeThreadRef(thread.environmentId, thread.id); - const fileDropHandlers = makeWorkspaceFileDropHandlers({ - setDragActive: (active) => setFileDragActive(setIsFileDragOver, active), - addFiles: (files) => { - onFileDropThreads(threadRef, files); - }, - addFolders: () => {}, - }); - const isHighlighted = isActive || isSelected; - const handleOpenDiscoveredPort = (event: React.MouseEvent) => { - const port = discoveredPorts[0]; - if (!port || !canOperatePreview) return; - event.preventDefault(); - event.stopPropagation(); - navigateToThread(threadRef); - void (async () => { - const result = await openDiscoveredPort({ threadRef, port, openPreview }); - if (result._tag === "Success" || isAtomCommandInterrupted(result)) { - return; - } - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Unable to open preview", - description: error instanceof Error ? error.message : "The preview could not be opened.", - }), - ); - })(); - }; - const currentLinkedPr = supportsMultiplePullRequests - ? resolveThreadCurrentPullRequestLink(thread.pullRequests) - : null; - const prStatus = prStatusIndicator(pr, linkedPullRequestStatus?.sourceControlProvider); - const isConfirmingArchive = - canOperateThread && confirmingArchiveThreadKey === threadKey && !isThreadRunning; - const threadMetaClassName = isConfirmingArchive - ? "pointer-events-none opacity-0" - : canOperateThread && !isThreadRunning - ? "pointer-events-none transition-opacity duration-150 max-sm:pr-6 group-hover/menu-sub-item:opacity-0 group-focus-within/menu-sub-item:opacity-0" - : "pointer-events-none"; - const clearConfirmingArchive = () => { - setConfirmingArchiveThreadKey((current) => (current === threadKey ? null : current)); - }; - const handleMouseLeave = () => { - clearConfirmingArchive(); - }; - const handleBlurCapture = (event: React.FocusEvent) => { - const currentTarget = event.currentTarget; - requestAnimationFrame(() => { - if (currentTarget.contains(document.activeElement)) { - return; - } - clearConfirmingArchive(); - }); - }; - const handleRowClick = (event: React.MouseEvent) => { - handleThreadClick(event, threadRef, orderedProjectThreadKeys); - }; - const handleRowDoubleClick = (event: React.MouseEvent) => { - if (!readEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope)) return; - if (renamingThreadKey === threadKey) return; - // Mobile navigation closes the sidebar on the first tap, so rename stays in the context menu. - if (isMobile) return; - if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; - if ((event.target as HTMLElement).closest("button, a")) return; - event.preventDefault(); - startThreadRename(threadKey, thread.title); - }; - const handleRowKeyDown = (event: React.KeyboardEvent) => { - if (event.target !== event.currentTarget) return; - if ( - event.key === "F2" && - renamingThreadKey !== threadKey && - readEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope) - ) { - event.preventDefault(); - startThreadRename(threadKey, thread.title); - return; - } - if (event.key !== "Enter" && event.key !== " ") return; - event.preventDefault(); - navigateToThread(threadRef); - }; - const handleRowContextMenu = (event: React.MouseEvent) => { - event.preventDefault(); - const hasSelection = useThreadSelectionStore.getState().hasSelection(); - if (hasSelection && isSelected) { - void (async () => { - const result = await settlePromise(() => - handleMultiSelectContextMenu({ - x: event.clientX, - y: event.clientY, - }), - ); - if (result._tag === "Failure") { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Thread action failed", - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - } - })(); - return; - } - - if (hasSelection) { - clearSelection(); - } - void (async () => { - const result = await settlePromise(() => - handleThreadContextMenu(threadRef, { - x: event.clientX, - y: event.clientY, - }), - ); - if (result._tag === "Failure") { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Thread action failed", - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - } - })(); - }; - const handlePrClick = (event: React.MouseEvent) => { - const url = prStatus?.url ?? currentLinkedPr?.url; - if (!url) return; - const openedInRightPanel = openPrLink( - event, - url, - openPullRequestsInRightPanel ? threadRef : undefined, - ); - if (openedInRightPanel && openPullRequestsInRightPanel && !isActive) { - navigateToThread(threadRef); - } - }; - const handleRenameInputRef = (element: HTMLInputElement | null) => { - if (element && renamingInputRef.current !== element) { - renamingInputRef.current = element; - element.focus(); - element.select(); - } - }; - const handleRenameInputChange = (event: React.ChangeEvent) => { - setRenamingTitle(event.target.value); - }; - const handleRenameInputKeyDown = (event: React.KeyboardEvent) => { - event.stopPropagation(); - if (event.key === "Enter") { - event.preventDefault(); - renamingCommittedRef.current = true; - void commitRename(threadRef, renamingTitle, thread.title); - } else if (event.key === "Escape") { - event.preventDefault(); - renamingCommittedRef.current = true; - cancelRename(); - } - }; - const handleRenameInputBlur = () => { - if (!renamingCommittedRef.current) { - void commitRename(threadRef, renamingTitle, thread.title); - } - }; - // Stop dblclick propagation so word selection cannot restart rename and discard edits. - const handleRenameInputClick = (event: React.MouseEvent) => { - event.stopPropagation(); - }; - const handleConfirmArchiveRef = (element: HTMLButtonElement | null) => { - if (element) { - confirmArchiveButtonRefs.current.set(threadKey, element); - } else { - confirmArchiveButtonRefs.current.delete(threadKey); - } - }; - const stopPropagationOnPointerDown = (event: React.PointerEvent) => { - event.stopPropagation(); - }; - const handleConfirmArchiveClick = (event: React.MouseEvent) => { - event.preventDefault(); - event.stopPropagation(); - clearConfirmingArchive(); - void attemptArchiveThread(threadRef); - }; - const handleStartArchiveConfirmation = (event: React.MouseEvent) => { - event.preventDefault(); - event.stopPropagation(); - if (!checkTaskPermission(thread.environmentId)) return; - setConfirmingArchiveThreadKey(threadKey); - requestAnimationFrame(() => { - confirmArchiveButtonRefs.current.get(threadKey)?.focus(); - }); - }; - const handleArchiveImmediateClick = (event: React.MouseEvent) => { - event.preventDefault(); - event.stopPropagation(); - void attemptArchiveThread(threadRef); - }; - - return ( - -
    revealActiveRow(node, threadKey) : undefined} - role="treeitem" - tabIndex={-1} - data-sidebar-row={threadKey} - data-sidebar-parent={props.navigationParent} - aria-current={isActive ? "page" : undefined} - data-active={isActive} - data-slot="sidebar-menu-sub-button" - data-sidebar="menu-sub-button" - data-size="sm" - data-testid={`thread-row-${thread.id}`} - className={cn( - "relative isolate flex h-8 w-full min-w-0 cursor-pointer select-none items-center gap-2 overflow-hidden rounded-md px-2 text-left text-xs outline-hidden focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring group-data-[collapsible=icon]:hidden [&>span:last-child]:truncate [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-muted-foreground", - isActive - ? "bg-sidebar-row-active font-medium text-sidebar-foreground hover:bg-sidebar-row-active" - : isSelected - ? "bg-sidebar-row-selected text-sidebar-foreground hover:bg-sidebar-row-active" - : "text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground", - isFileDragOver && "ring-1 ring-inset ring-primary/70", - )} - onClick={handleRowClick} - onDoubleClick={handleRowDoubleClick} - onKeyDown={handleRowKeyDown} - onContextMenu={handleRowContextMenu} - > -
    - {prStatus && pr && ( - - event.stopPropagation()} - onClick={handlePrClick} - > - - - } - /> - - - - - )} - {!pr && currentLinkedPr ? ( - event.stopPropagation()} - onClick={handlePrClick} - className="text-muted-foreground" - aria-label={`PR #${currentLinkedPr.number}, status pending`} - > - - - ) : null} - {threadStatus && } - {canOperateThread && renamingThreadKey === threadKey ? ( - - ) : ( - - - {thread.title} - - } - /> - {thread.title} - - )} -
    -
    - {canOperatePreview && discoveredPorts.length > 0 && ( - - - } - > - - - - Open localhost:{discoveredPorts[0]?.port} - {discoveredPorts.length > 1 ? ` (+${discoveredPorts.length - 1})` : ""} - - - )} - - -
    - {isConfirmingArchive ? ( - - ) : canOperateThread && !isThreadRunning ? ( - appSettingsConfirmThreadArchive ? ( -
    - -
    - ) : ( - - - -
    - } - /> - Archive - - ) - ) : null} - - - {isRemoteThread && !isDesktopLocalThread && ( - - - } - > - - - {threadEnvironmentLabel} - - )} - {jumpLabel ? ( - - - } - > - {jumpLabel} - - {jumpLabel} - - ) : ( - - - - )} - - -
    -
    -
    - - ); -}); - -interface SidebarProjectThreadListProps { - projectKey: string; - projectExpanded: boolean; - hasOverflowingThreads: boolean; - hiddenThreadStatus: ThreadStatusPill | null; - orderedProjectThreadKeys: readonly string[]; - renderedThreads: readonly SidebarThreadSummary[]; - showEmptyThreadState: boolean; - shouldShowThreadPanel: boolean; - isThreadListExpanded: boolean; - activeRouteThreadKey: string | null; - openPullRequestsInRightPanel: boolean; - threadJumpLabelByKey: ReadonlyMap; - appSettingsConfirmThreadArchive: boolean; - renamingThreadKey: string | null; - renamingTitle: string; - setRenamingTitle: (title: string) => void; - startThreadRename: (threadKey: string, title: string) => void; - renamingInputRef: React.RefObject; - renamingCommittedRef: React.RefObject; - confirmingArchiveThreadKey: string | null; - setConfirmingArchiveThreadKey: React.Dispatch>; - confirmArchiveButtonRefs: React.RefObject>; - attachThreadListAutoAnimateRef: (node: HTMLElement | null) => void; - handleThreadClick: ( - event: React.MouseEvent, - threadRef: ScopedThreadRef, - orderedProjectThreadKeys: readonly string[], - ) => void; - navigateToThread: (threadRef: ScopedThreadRef) => Promise; - onFileDropThreads: (threadRef: ScopedThreadRef, files: File[]) => void; - handleMultiSelectContextMenu: (position: { x: number; y: number }) => Promise; - handleThreadContextMenu: ( - threadRef: ScopedThreadRef, - position: { x: number; y: number }, - ) => Promise; - clearSelection: () => void; - commitRename: ( - threadRef: ScopedThreadRef, - newTitle: string, - originalTitle: string, - ) => Promise; - cancelRename: () => void; - attemptArchiveThread: (threadRef: ScopedThreadRef) => Promise; - openPrLink: ( - event: React.MouseEvent, - prUrl: string, - threadRef?: ScopedThreadRef, - ) => boolean; - expandThreadListForProject: (projectKey: string) => void; - collapseThreadListForProject: (projectKey: string) => void; -} - -const SidebarProjectThreadList = memo(function SidebarProjectThreadList( - props: SidebarProjectThreadListProps, -) { - const { - projectKey, - projectExpanded, - hasOverflowingThreads, - hiddenThreadStatus, - orderedProjectThreadKeys, - renderedThreads, - showEmptyThreadState, - shouldShowThreadPanel, - isThreadListExpanded, - activeRouteThreadKey, - openPullRequestsInRightPanel, - threadJumpLabelByKey, - appSettingsConfirmThreadArchive, - renamingThreadKey, - renamingTitle, - setRenamingTitle, - startThreadRename, - renamingInputRef, - renamingCommittedRef, - confirmingArchiveThreadKey, - setConfirmingArchiveThreadKey, - confirmArchiveButtonRefs, - attachThreadListAutoAnimateRef, - handleThreadClick, - navigateToThread, - onFileDropThreads, - handleMultiSelectContextMenu, - handleThreadContextMenu, - clearSelection, - commitRename, - cancelRename, - attemptArchiveThread, - openPrLink, - expandThreadListForProject, - collapseThreadListForProject, - } = props; - const showMoreButtonRender = - - } - /> - - {newThreadShortcutLabel ? `New thread (${newThreadShortcutLabel})` : "New thread"} - - - - - - - { - if (!open) { - closeProjectRenameDialog(); - } - }} - > - - - Rename project - - {projectRenameTarget - ? `Update the title for ${projectRenameTarget.workspaceRoot}.` - : "Update the project title."} - - - -
    - Project title - setProjectRenameTitle(event.target.value)} - onKeyDown={(event) => { - if (event.key === "Enter") { - event.preventDefault(); - void submitProjectRename(); - } - }} - /> -
    - {projectRenameTarget?.environmentLabel ? ( -

    - Environment: {projectRenameTarget.environmentLabel} -

    - ) : null} - {!canRenameProject ? ( -

    - This connection cannot change projects. -

    - ) : null} -
    - - - - -
    -
    - - { - if (!open) { - closeProjectGroupingDialog(); - } - }} - > - - - Project grouping - - {projectGroupingTarget - ? `Choose how ${projectGroupingTarget.workspaceRoot} should be grouped in the sidebar.` - : "Choose how this project should be grouped in the sidebar."} - - - -
    - Grouping rule - -
    -

    - {projectGroupingSelection === "inherit" - ? projectGroupingModeDescription(projectGroupingSettings.sidebarProjectGroupingMode) - : projectGroupingModeDescription(projectGroupingSelection)} -

    -
    - - - - -
    -
    - - ); -}); - -const SidebarProjectListRow = memo(function SidebarProjectListRow(props: SidebarProjectItemProps) { - return ( - - - - ); -}); - -function LocalSecondaryStatus() { - const { environments } = useEnvironments(); - // Poll desktop-local backends because the bridge has no change event. - const secondaries = useDesktopLocalBootstraps(); - - const localEnvByUrl = (() => { - const map = new Map(); - for (const environment of environments) { - if ( - isDesktopLocalConnectionTarget(environment.entry.target) && - environment.displayUrl !== null - ) { - map.set(environment.displayUrl, { - phase: environment.connection.phase, - error: environment.connection.error, - }); - } - } - return map; - })(); - - const connecting: string[] = []; - const failed: Array<{ label: string; error: string | null }> = []; - for (const bootstrap of secondaries) { - const env = - bootstrap.httpBaseUrl !== null ? localEnvByUrl.get(bootstrap.httpBaseUrl) : undefined; - if (env?.phase === "connected") { - continue; - } - if (env?.phase === "error") { - failed.push({ label: bootstrap.label, error: env.error }); - continue; - } - connecting.push(bootstrap.label); - } - - if (connecting.length === 0 && failed.length === 0) { - return null; - } - - return ( - - {connecting.length > 0 ? ( - - - Connecting {connecting.join(", ")} - - ) : null} - {failed.length > 0 ? ( - - - Couldn't connect {failed.map((entry) => entry.label).join(", ")} - - {failed - .map((entry) => entry.error) - .filter(Boolean) - .join("; ") || "The backend didn't respond."} - - - ) : null} - - ); -} - -type SortableProjectHandleProps = Pick< - ReturnType, - "attributes" | "listeners" | "setActivatorNodeRef" ->; - -function ProjectSortMenu({ - projectSortOrder, - threadSortOrder, - threadPreviewCount, - onProjectSortOrderChange, - onThreadSortOrderChange, - onThreadPreviewCountChange, -}: { - projectSortOrder: SidebarProjectSortOrder; - threadSortOrder: SidebarThreadSortOrder; - threadPreviewCount: SidebarThreadPreviewCount; - onProjectSortOrderChange: (sortOrder: SidebarProjectSortOrder) => void; - onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void; - onThreadPreviewCountChange: (count: SidebarThreadPreviewCount) => void; -}) { - const handleThreadPreviewCountChange = (nextValue: number | null) => { - if (nextValue === null) { - return; - } - - const clampedValue = clampSidebarThreadPreviewCount(nextValue); - if (clampedValue !== threadPreviewCount) { - onThreadPreviewCountChange(clampedValue); - } - }; - - return ( - - - } - /> - } - > - - - Sidebar options - - - -
    - Sort projects -
    - { - onProjectSortOrderChange(value as SidebarProjectSortOrder); - }} - > - {(Object.entries(SIDEBAR_SORT_LABELS) as Array<[SidebarProjectSortOrder, string]>).map( - ([value, label]) => ( - - {label} - - ), - )} - -
    - -
    - Sort threads -
    - { - onThreadSortOrderChange(value as SidebarThreadSortOrder); - }} - > - {( - Object.entries(SIDEBAR_THREAD_SORT_LABELS) as Array<[SidebarThreadSortOrder, string]> - ).map(([value, label]) => ( - - {label} - - ))} - -
    - -
    - Visible threads -
    -
    - - - - { - event.stopPropagation(); - }} - /> - - - -
    -
    -
    -
    - ); -} - -function SortableProjectItem({ - projectId, - disabled = false, - children, -}: { - projectId: string; - disabled?: boolean; - children: (handleProps: SortableProjectHandleProps) => React.ReactNode; -}) { - const { - attributes, - listeners, - setActivatorNodeRef, - setNodeRef, - transform, - transition, - isDragging, - isOver, - } = useSortable({ id: projectId, disabled }); - return ( -
  • - {children({ attributes, listeners, setActivatorNodeRef })} -
  • - ); -} - -interface SidebarProjectsContentProps { - showArm64IntelBuildWarning: boolean; - arm64IntelBuildWarningDescription: string | null; - desktopUpdateButtonAction: "download" | "install" | "none"; - desktopUpdateButtonDisabled: boolean; - desktopUpdateActionPending: boolean; - handleDesktopUpdateButtonClick: () => void; - projectSortOrder: SidebarProjectSortOrder; - threadSortOrder: SidebarThreadSortOrder; - threadPreviewCount: SidebarThreadPreviewCount; - openAddProject: () => void; - isManualProjectSorting: boolean; - projectDnDSensors: ReturnType; - projectCollisionDetection: CollisionDetection; - handleProjectDragStart: (event: DragStartEvent) => void; - handleProjectDragEnd: (event: DragEndEvent) => void; - handleProjectDragCancel: (event: DragCancelEvent) => void; - handleNewThread: ReturnType; - archiveThread: ReturnType["archiveThread"]; - deleteThread: ReturnType["deleteThread"]; - markThreadUnread: ReturnType["markThreadUnread"]; - sortedProjects: readonly SidebarProjectSnapshot[]; - sortedProjectKeys: string[]; - expandedThreadListsByProject: ReadonlySet; - activeRouteProjectKey: string | null; - routeThreadKey: string | null; - openPullRequestsInRightPanel: boolean; - newThreadShortcutLabel: string | null; - commandPaletteShortcutLabel: string | null; - threadJumpLabelByKey: ReadonlyMap; - attachThreadListAutoAnimateRef: (node: HTMLElement | null) => void; - expandThreadListForProject: (projectKey: string) => void; - collapseThreadListForProject: (projectKey: string) => void; - dragInProgressRef: React.RefObject; - suppressProjectClickAfterDragRef: React.RefObject; - suppressProjectClickForContextMenuRef: React.RefObject; - attachProjectListAutoAnimateRef: (node: HTMLElement | null) => void; - projectsLength: number; -} - -const SidebarProjectsContent = memo(function SidebarProjectsContent( - props: SidebarProjectsContentProps, -) { - const { - showArm64IntelBuildWarning, - arm64IntelBuildWarningDescription, - desktopUpdateButtonAction, - desktopUpdateButtonDisabled, - desktopUpdateActionPending, - handleDesktopUpdateButtonClick, - projectSortOrder, - threadSortOrder, - threadPreviewCount, - openAddProject, - isManualProjectSorting, - projectDnDSensors, - projectCollisionDetection, - handleProjectDragStart, - handleProjectDragEnd, - handleProjectDragCancel, - handleNewThread, - archiveThread, - deleteThread, - markThreadUnread, - sortedProjects, - sortedProjectKeys, - expandedThreadListsByProject, - activeRouteProjectKey, - routeThreadKey, - openPullRequestsInRightPanel, - newThreadShortcutLabel, - commandPaletteShortcutLabel, - threadJumpLabelByKey, - attachThreadListAutoAnimateRef, - expandThreadListForProject, - collapseThreadListForProject, - dragInProgressRef, - suppressProjectClickAfterDragRef, - suppressProjectClickForContextMenuRef, - attachProjectListAutoAnimateRef, - projectsLength, - } = props; - - const attachTreeRef = (node: HTMLUListElement | null) => { - attachProjectListAutoAnimateRef(node); - const dispose = attachSidebarTree(node); - return () => { - dispose?.(); - attachProjectListAutoAnimateRef(null); - }; - }; - const handleProjectSortOrderChange = (sortOrder: SidebarProjectSortOrder) => { - updateClientSettings({ sidebarProjectSortOrder: sortOrder }); - }; - const handleThreadSortOrderChange = (sortOrder: SidebarThreadSortOrder) => { - updateClientSettings({ sidebarThreadSortOrder: sortOrder }); - }; - const handleThreadPreviewCountChange = (count: SidebarThreadPreviewCount) => { - updateClientSettings({ sidebarThreadPreviewCount: count }); - }; - - return ( - - - - } - > - - Search - {commandPaletteShortcutLabel ? {commandPaletteShortcutLabel} : null} - - - - - } - > - {showArm64IntelBuildWarning && arm64IntelBuildWarningDescription ? ( - - - - Intel build on Apple Silicon - {arm64IntelBuildWarningDescription} - {desktopUpdateButtonAction !== "none" ? ( - - - - ) : null} - - - ) : null} - - -
    - Projects -
    - - - - } - > - - - Add project - -
    -
    - - {isManualProjectSorting ? ( - - - - {sortedProjects.map((project) => ( - - {(dragHandleProps) => ( - - )} - - ))} - - - - ) : ( - - {sortedProjects.map((project) => ( - - ))} - - )} - - {projectsLength === 0 && ( -
    No projects yet
    - )} -
    -
    - ); -}); - -const PROJECT_POINTER_SENSOR_OPTIONS = { activationConstraint: { distance: 6 } }; -const PROJECT_DND_MODIFIERS = [restrictToVerticalAxis, restrictToFirstScrollableAncestor]; - -const projectCollisionDetection: CollisionDetection = (args) => { - const pointerCollisions = pointerWithin(args); - if (pointerCollisions.length > 0) { - return pointerCollisions; - } - - return closestCorners(args); -}; - -function openAddProjectCommandPalette() { - openCommandPalette({ open: "add-project" }); -} - -// Separate hooks cache real inputs; later sidebar hooks would invalidate every row's props. -function useLegacySidebarProjects() { - const projects = useProjects(); - const projectOrder = useUiStateStore((store) => store.projectOrder); - const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings); - const { environments } = useEnvironments(); - const primaryEnvironmentId = usePrimaryEnvironmentId(); - const environmentLabelById = new Map( - environments.map((environment) => [environment.environmentId, environment.label] as const), - ); - const desktopLocalEnvironmentIds = new Set( - environments - .filter((environment) => isDesktopLocalConnectionTarget(environment.entry.target)) - .map((environment) => environment.environmentId), - ); - const wslEnvironmentIds = new Set( - environments - .filter((environment) => isWslConnectionTarget(environment.entry.target)) - .map((environment) => environment.environmentId), - ); - const orderedProjects = orderItemsByPreferredIds({ - items: projects, - preferredIds: projectOrder, - getId: getProjectOrderKey, - getPreferenceIds: (project) => [ - getProjectOrderKey(project), - legacyProjectCwdPreferenceKey(project.workspaceRoot), - ], - }); - const physicalToLogicalKey = buildPhysicalToLogicalProjectKeyMap({ - projects: orderedProjects, - settings: projectGroupingSettings, - primaryEnvironmentId, - }); - const projectPhysicalKeyByScopedRef = new Map( - orderedProjects.map((project) => [ - scopedProjectKey(scopeProjectRef(project.environmentId, project.id)), - derivePhysicalProjectKey(project), - ]), - ); - const sidebarProjects: SidebarProjectSnapshot[] = buildSidebarProjectSnapshots({ - projects: orderedProjects, - settings: projectGroupingSettings, - primaryEnvironmentId, - resolveEnvironmentLabel: (environmentId) => environmentLabelById.get(environmentId) ?? null, - isDesktopLocalEnvironment: (environmentId) => desktopLocalEnvironmentIds.has(environmentId), - isWslEnvironment: (environmentId) => wslEnvironmentIds.has(environmentId), - }); - return { - projectsLength: projects.length, - orderedProjects, - physicalToLogicalKey, - projectPhysicalKeyByScopedRef, - sidebarProjects, - }; -} - -// Re-sort on thread changes without rebuilding project snapshots used as row keys. -function useSortedLegacySidebarProjects(input: { - sidebarProjects: readonly SidebarProjectSnapshot[]; - physicalToLogicalKey: ReadonlyMap; - projectPhysicalKeyByScopedRef: ReadonlyMap; - sidebarProjectSortOrder: SidebarProjectSortOrder; -}) { - const { - sidebarProjects, - physicalToLogicalKey, - projectPhysicalKeyByScopedRef, - sidebarProjectSortOrder, - } = input; - const sidebarThreads = useThreadShells(); - const delegatedUnderParent = useDelegatedUnderParent(); - const sidebarProjectByKey = new Map( - sidebarProjects.map((project) => [project.projectKey, project] as const), - ); - const sortableProjects = sidebarProjects.map((project) => ({ - ...project, - id: project.projectKey, - })); - const sortableThreads = filterSidebarV2VisibleThreads( - sidebarThreads, - null, - delegatedUnderParent, - ).map((thread) => { - const physicalKey = - projectPhysicalKeyByScopedRef.get( - scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)), - ) ?? scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)); - return { - ...thread, - projectId: (physicalToLogicalKey.get(physicalKey) ?? physicalKey) as ProjectId, - }; - }); - const sortedProjects = sortProjectsForSidebar( - sortableProjects, - sortableThreads, - sidebarProjectSortOrder, - ).flatMap((project) => { - const resolvedProject = sidebarProjectByKey.get(project.id); - return resolvedProject ? [resolvedProject] : []; - }); - return { - sortedProjects, - sortedProjectKeys: sortedProjects.map((project) => project.projectKey), - }; -} - -function useLegacySidebarThreads(input: { - sortedProjects: readonly SidebarProjectSnapshot[]; - physicalToLogicalKey: ReadonlyMap; - projectPhysicalKeyByScopedRef: ReadonlyMap; - routeThreadKey: string | null; - sidebarThreadSortOrder: SidebarThreadSortOrder; - sidebarThreadPreviewCount: number; - expandedThreadListsByProject: ReadonlySet; -}) { - const { - sortedProjects, - physicalToLogicalKey, - projectPhysicalKeyByScopedRef, - routeThreadKey, - sidebarThreadSortOrder, - sidebarThreadPreviewCount, - expandedThreadListsByProject, - } = input; - const sidebarThreads = useThreadShells(); - const delegatedUnderParent = useDelegatedUnderParent(); - const projectExpandedById = useUiStateStore((store) => store.projectExpandedById); - const sidebarThreadByKey = new Map( - sidebarThreads.map( - (thread) => - [scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), thread] as const, - ), - ); - const logicalProjectKeyForThread = (thread: SidebarThreadSummary) => { - const physicalKey = - projectPhysicalKeyByScopedRef.get( - scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)), - ) ?? scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)); - return physicalToLogicalKey.get(physicalKey) ?? physicalKey; - }; - const activeRouteThread = routeThreadKey ? sidebarThreadByKey.get(routeThreadKey) : undefined; - const activeRouteProjectKey = activeRouteThread - ? logicalProjectKeyForThread(activeRouteThread) - : null; - const threadsByProjectKey = new Map(); - for (const thread of sidebarThreads) { - const logicalKey = logicalProjectKeyForThread(thread); - const existing = threadsByProjectKey.get(logicalKey); - if (existing) { - existing.push(thread); - } else { - threadsByProjectKey.set(logicalKey, [thread]); - } - } - const visibleSidebarThreadKeys = sortedProjects.flatMap((project) => { - const projectThreads = sortThreads( - filterSidebarV2VisibleThreads( - threadsByProjectKey.get(project.projectKey) ?? [], - null, - delegatedUnderParent, - ), - sidebarThreadSortOrder, - ); - const projectExpanded = resolveProjectExpanded( - projectExpandedById, - projectExpansionPreferenceKeys(project), - ); - const activeThreadKey = routeThreadKey ?? undefined; - const pinnedCollapsedThread = - !projectExpanded && activeThreadKey - ? (projectThreads.find( - (thread) => - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === activeThreadKey, - ) ?? null) - : null; - const shouldShowThreadPanel = projectExpanded || pinnedCollapsedThread !== null; - if (!shouldShowThreadPanel) { - return []; - } - const isThreadListExpanded = expandedThreadListsByProject.has(project.projectKey); - const hasOverflowingThreads = projectThreads.length > sidebarThreadPreviewCount; - const previewThreads = - isThreadListExpanded || !hasOverflowingThreads - ? projectThreads - : projectThreads.slice(0, sidebarThreadPreviewCount); - if (pinnedCollapsedThread) { - return [ - scopedThreadKey( - scopeThreadRef(pinnedCollapsedThread.environmentId, pinnedCollapsedThread.id), - ), - ]; - } - return projectThreads.flatMap((thread, index) => { - const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); - return index < previewThreads.length || threadKey === activeThreadKey ? [threadKey] : []; - }); - }); - const threadJumpCommandByKey = new Map< - string, - NonNullable> - >(); - for (const [visibleThreadIndex, threadKey] of visibleSidebarThreadKeys.entries()) { - const jumpCommand = threadJumpCommandForIndex(visibleThreadIndex); - if (!jumpCommand) { - break; - } - threadJumpCommandByKey.set(threadKey, jumpCommand); - } - const prewarmedSidebarThreadRefs = getSidebarThreadIdsToPrewarm(visibleSidebarThreadKeys).flatMap( - (threadKey) => { - const ref = parseScopedThreadKey(threadKey); - return ref ? [ref] : []; - }, - ); - return { - sidebarThreadByKey, - activeRouteProjectKey, - visibleSidebarThreadKeys, - threadJumpCommandByKey, - threadJumpThreadKeys: [...threadJumpCommandByKey.keys()], - prewarmedSidebarThreadRefs, - }; -} - -function clearThreadSelectionOnOutsideMouseDown(event: globalThis.MouseEvent) { - const selection = useThreadSelectionStore.getState(); - if (!selection.hasSelection()) return; - const target = event.target instanceof HTMLElement ? event.target : null; - if (shouldClearThreadSelectionOnMouseDown(target)) selection.clearSelection(); -} - -export default function LegacySidebar({ routeReveal }: { routeReveal: SidebarRouteReveal }) { - const reorderProjects = useUiStateStore((store) => store.reorderProjects); - const navigate = useNavigate(); - const sidebarThreadSortOrder = useClientSettings((s) => s.sidebarThreadSortOrder); - const sidebarProjectSortOrder = useClientSettings((s) => s.sidebarProjectSortOrder); - const sidebarThreadPreviewCount = useClientSettings((s) => s.sidebarThreadPreviewCount); - const handleNewThread = useNewThreadHandler(); - const { archiveThread, deleteThread, markThreadUnread } = useThreadActions(); - const { isMobile, setOpenMobile } = useSidebar(); - const routeTarget = useThreadRouteTarget(); - const routeDraftThread = useComposerDraftStore((store) => - routeTarget?.kind === "draft" ? store.getDraftSession(routeTarget.draftId) : null, - ); - const routeThreadRef = resolveActiveThreadRouteRef(routeTarget, routeDraftThread); - const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null; - const routeTerminalOpen = useTerminalUiStateStore((state) => - routeThreadRef - ? selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef).terminalOpen - : false, - ); - const keybindings = useAtomValue(primaryServerKeybindingsAtom); - const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState< - ReadonlySet - >(() => new Set()); - const dragInProgressRef = useRef(false); - const suppressProjectClickAfterDragRef = useRef(false); - const suppressProjectClickForContextMenuRef = useRef(false); - const desktopUpdateState = useDesktopUpdateState(); - const [desktopUpdateActionPending, setDesktopUpdateActionPending] = useState(false); - const clearSelection = useThreadSelectionStore((s) => s.clearSelection); - const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor); - const platform = navigator.platform; - const shortcutModifiers = useShortcutModifierState(); - const terminalFocused = useTerminalFocus(); - const { - projectsLength, - orderedProjects, - physicalToLogicalKey, - projectPhysicalKeyByScopedRef, - sidebarProjects, - } = useLegacySidebarProjects(); - const { sortedProjects, sortedProjectKeys } = useSortedLegacySidebarProjects({ - sidebarProjects, - physicalToLogicalKey, - projectPhysicalKeyByScopedRef, - sidebarProjectSortOrder, - }); - const { - sidebarThreadByKey, - activeRouteProjectKey, - visibleSidebarThreadKeys, - threadJumpCommandByKey, - threadJumpThreadKeys, - prewarmedSidebarThreadRefs, - } = useLegacySidebarThreads({ - sortedProjects, - physicalToLogicalKey, - projectPhysicalKeyByScopedRef, - routeThreadKey, - sidebarThreadSortOrder, - sidebarThreadPreviewCount, - expandedThreadListsByProject, - }); - const revealActiveRow = useActiveRowReveal(routeReveal, routeThreadKey); - const newThreadShortcutLabelOptions = { - platform, - context: { - terminalFocus: false, - terminalOpen: false, - }, - }; - const newThreadShortcutLabel = - shortcutLabelForCommand(keybindings, "chat.newLocal", newThreadShortcutLabelOptions) ?? - shortcutLabelForCommand(keybindings, "chat.new", newThreadShortcutLabelOptions); - - const navigateToThread = (threadRef: ScopedThreadRef) => { - if (useThreadSelectionStore.getState().selectedThreadKeys.size > 0) { - clearSelection(); - } - setSelectionAnchor(scopedThreadKey(threadRef)); - if (isMobile) { - setOpenMobile(false); - } - void navigate({ - to: "/$environmentId/$threadId", - params: buildThreadRouteParams(threadRef), - }); - }; - - const projectDnDSensors = useSensors(useSensor(PointerSensor, PROJECT_POINTER_SENSOR_OPTIONS)); - - const handleProjectDragEnd = useStableCallback((event: DragEndEvent) => { - if (sidebarProjectSortOrder !== "manual") { - dragInProgressRef.current = false; - return; - } - dragInProgressRef.current = false; - const { active, over } = event; - if (!over || active.id === over.id) return; - const activeProject = sidebarProjects.find((project) => project.projectKey === active.id); - const overProject = sidebarProjects.find((project) => project.projectKey === over.id); - if (!activeProject || !overProject) return; - const activeMemberKeys = activeProject.memberProjects.map( - (member) => member.physicalProjectKey, - ); - const overMemberKeys = overProject.memberProjects.map((member) => member.physicalProjectKey); - reorderProjects(orderedProjects.map(getProjectOrderKey), activeMemberKeys, overMemberKeys); - }); - - const handleProjectDragStart = useStableCallback((_event: DragStartEvent) => { - if (sidebarProjectSortOrder !== "manual") { - return; - } - dragInProgressRef.current = true; - suppressProjectClickAfterDragRef.current = true; - }); - - const handleProjectDragCancel = (_event: DragCancelEvent) => { - dragInProgressRef.current = false; - }; - - const animatedProjectListsRef = useRef(new WeakSet()); - const attachProjectListAutoAnimateRef = (node: HTMLElement | null) => { - if (!node || animatedProjectListsRef.current.has(node)) { - return; - } - autoAnimate(node, SIDEBAR_LIST_ANIMATION_OPTIONS); - animatedProjectListsRef.current.add(node); - }; - - const animatedThreadListsRef = useRef(new WeakSet()); - const attachThreadListAutoAnimateRef = (node: HTMLElement | null) => { - if (!node || animatedThreadListsRef.current.has(node)) { - return; - } - autoAnimate(node, SIDEBAR_LIST_ANIMATION_OPTIONS); - animatedThreadListsRef.current.add(node); - }; - - const isManualProjectSorting = sidebarProjectSortOrder === "manual"; - // Build before modifier-dependent context to give the compiler a separate cache used by every row. - const threadJumpLabelByKey = buildThreadJumpLabelMap({ - keybindings, - platform, - terminalOpen: routeTerminalOpen, - threadJumpCommandByKey, - }); - const sidebarShortcutContext = { - terminalFocus: terminalFocused, - terminalOpen: routeTerminalOpen, - modelPickerOpen: isModelPickerOpen(), - }; - const shouldShowThreadJumpHintsNow = shouldShowThreadJumpHintsForModifiers( - shortcutModifiers, - keybindings, - { - platform, - context: sidebarShortcutContext, - }, - ); - const showThreadJumpHints = useThreadJumpHintsVisible(shouldShowThreadJumpHintsNow); - const visibleThreadJumpLabelByKey = showThreadJumpHints - ? threadJumpLabelByKey - : EMPTY_THREAD_JUMP_LABELS; - const orderedSidebarThreadKeys = visibleSidebarThreadKeys; - - const onWindowKeyDown = useEffectEvent((event: globalThis.KeyboardEvent) => { - const shortcutContext = { - terminalFocus: isTerminalFocused(), - terminalOpen: routeTerminalOpen, - modelPickerOpen: isModelPickerOpen(), - }; - - if (event.defaultPrevented || event.repeat || isCommandPaletteOpen() || isModelPickerOpen()) { - return; - } - - const command = resolveShortcutCommand(event, keybindings, { - platform, - context: shortcutContext, - }); - const traversalDirection = threadTraversalDirectionFromCommand(command); - if (traversalDirection !== null) { - const targetThreadKey = resolveAdjacentThreadId({ - threadIds: orderedSidebarThreadKeys, - currentThreadId: routeThreadKey, - direction: traversalDirection, - }); - if (!targetThreadKey) { - return; - } - const targetThread = sidebarThreadByKey.get(targetThreadKey); - if (!targetThread) { - return; - } - - event.preventDefault(); - event.stopPropagation(); - navigateToThread(scopeThreadRef(targetThread.environmentId, targetThread.id)); - return; - } - - const jumpIndex = threadJumpIndexFromCommand(command ?? ""); - if (jumpIndex === null) { - return; - } - - const targetThreadKey = threadJumpThreadKeys[jumpIndex]; - if (!targetThreadKey) { - return; - } - const targetThread = sidebarThreadByKey.get(targetThreadKey); - if (!targetThread) { - return; - } - - event.preventDefault(); - event.stopPropagation(); - navigateToThread(scopeThreadRef(targetThread.environmentId, targetThread.id)); - }); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to window keydown for thread navigation shortcuts for the sidebar's lifetime - useEffect(() => { - const handleWindowKeyDown = (event: globalThis.KeyboardEvent) => onWindowKeyDown(event); - window.addEventListener("keydown", handleWindowKeyDown); - return () => { - window.removeEventListener("keydown", handleWindowKeyDown); - }; - }, []); - // A window listener whose lifetime is the sidebar's: no element owns outside clicks. - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window mousedown listener that clears thread selection on outside clicks for the sidebar's lifetime - useEffect(() => { - window.addEventListener("mousedown", clearThreadSelectionOnOutsideMouseDown); - return () => window.removeEventListener("mousedown", clearThreadSelectionOnOutsideMouseDown); - }, []); - - const desktopUpdateButtonDisabled = isDesktopUpdateButtonDisabled(desktopUpdateState); - const desktopUpdateButtonAction = desktopUpdateState - ? resolveDesktopUpdateButtonAction(desktopUpdateState) - : "none"; - const showArm64IntelBuildWarning = - isElectron && shouldShowArm64IntelBuildWarning(desktopUpdateState); - const arm64IntelBuildWarningDescription = - desktopUpdateState && showArm64IntelBuildWarning - ? getArm64IntelBuildWarningDescription(desktopUpdateState) - : null; - const commandPaletteShortcutLabel = isMobile - ? null - : shortcutLabelForCommand(keybindings, "commandPalette.toggle", newThreadShortcutLabelOptions); - const handleDesktopUpdateButtonClick = async () => { - const bridge = window.desktopBridge; - if (!bridge || !desktopUpdateState) return; - if ( - desktopUpdateButtonDisabled || - desktopUpdateButtonAction === "none" || - desktopUpdateActionPending - ) { - return; - } - - setDesktopUpdateActionPending(true); - - if (desktopUpdateButtonAction === "download") { - void bridge - .downloadUpdate() - .then((result) => { - if (result.completed) { - showDesktopUpdateDownloadedToast(bridge, result.state); - } - if (!shouldToastDesktopUpdateActionResult(result)) return; - const actionError = getDesktopUpdateActionError(result); - if (!actionError) return; - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Could not download update", - description: actionError, - }), - ); - }) - .catch((error) => { - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Could not start update download", - description: error instanceof Error ? error.message : "An unexpected error occurred.", - }), - ); - }) - .finally(() => setDesktopUpdateActionPending(false)); - return; - } - - if (desktopUpdateButtonAction === "install") { - let confirmed = false; - try { - confirmed = await ensureLocalApi().dialogs.confirm( - getDesktopUpdateInstallConfirmationMessage(desktopUpdateState), - ); - } catch (error) { - setDesktopUpdateActionPending(false); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Could not confirm update", - description: error instanceof Error ? error.message : "Update confirmation failed.", - }), - ); - return; - } - if (!confirmed) { - setDesktopUpdateActionPending(false); - return; - } - void bridge - .installUpdate() - .then((result) => { - if (!shouldToastDesktopUpdateActionResult(result)) return; - const actionError = getDesktopUpdateActionError(result); - if (!actionError) return; - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Could not install update", - description: actionError, - }), - ); - }) - .catch((error) => { - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Could not install update", - description: error instanceof Error ? error.message : "An unexpected error occurred.", - }), - ); - }) - .finally(() => setDesktopUpdateActionPending(false)); - } - }; - - const expandThreadListForProject = (projectKey: string) => { - setExpandedThreadListsByProject((current) => { - if (current.has(projectKey)) return current; - const next = new Set(current); - next.add(projectKey); - return next; - }); - }; - - const collapseThreadListForProject = (projectKey: string) => { - setExpandedThreadListsByProject((current) => { - if (!current.has(projectKey)) return current; - const next = new Set(current); - next.delete(projectKey); - return next; - }); - }; - - return ( - - {prewarmedSidebarThreadRefs.map((threadRef) => ( - - ))} - - - - - - ); -} diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 1bf7a930c1f24..93f3fb342fb9e 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -32,7 +32,11 @@ import { type SidebarListMarker, type SidebarSection, resolveSidebarDropVerb, + groupSidebarThreadsByProject, + resolveSidebarFolderDot, + sidebarFolderExpansionKeys, } from "./Sidebar.logic"; +import { resolveProjectExpanded } from "../uiStateStore"; import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search"; import { EnvironmentId, ProjectId, ProviderInstanceId, RunId, ThreadId } from "@t3tools/contracts"; @@ -1348,3 +1352,97 @@ describe("resolveSidebarRouteReveal", () => { ).toEqual({ pendingKey: hiddenKey, widensScope: false }); }); }); + +describe("sidebarFolderExpansionKeys", () => { + it("honors a collapse the legacy sidebar saved under a member's cwd", () => { + const keys = sidebarFolderExpansionKeys({ + projectKey: "github.com/pingdotgg/t3code", + memberProjects: [{ physicalProjectKey: "local:/code/t3code", workspaceRoot: "/code/t3code" }], + }); + const cwdKey = keys.at(-1)!; + + expect(resolveProjectExpanded({}, keys)).toBe(true); + expect(resolveProjectExpanded({ [cwdKey]: false }, keys)).toBe(false); + expect(resolveProjectExpanded({ [keys[0]!]: true, [cwdKey]: false }, keys)).toBe(true); + }); +}); + +describe("groupSidebarThreadsByProject", () => { + it("puts each thread in its project's folder and keeps empty projects", () => { + const remoteEnvironmentId = EnvironmentId.make("environment-remote"); + const t3code = ProjectId.make("t3code"); + const t3codeRemote = ProjectId.make("t3code-remote"); + const fleet = ProjectId.make("fleet"); + const thread = (id: string, environmentId: EnvironmentId, projectId: ProjectId) => ({ + id, + environmentId, + projectId, + }); + const groups = [ + { + projectKey: "t3code", + memberProjectRefs: [ + { environmentId: localEnvironmentId, projectId: t3code }, + { environmentId: remoteEnvironmentId, projectId: t3codeRemote }, + ], + }, + { + projectKey: "fleet", + memberProjectRefs: [{ environmentId: localEnvironmentId, projectId: fleet }], + }, + ]; + + const folders = groupSidebarThreadsByProject(groups, [ + thread("a", localEnvironmentId, t3code), + thread("orphan", localEnvironmentId, ProjectId.make("deleted")), + thread("b", remoteEnvironmentId, t3codeRemote), + ]); + + expect( + folders.map((folder) => ({ + projectKey: folder.group.projectKey, + threads: folder.threads.map((entry) => entry.id), + })), + ).toEqual([ + { projectKey: "t3code", threads: ["a", "b"] }, + { projectKey: "fleet", threads: [] }, + ]); + }); +}); + +describe("resolveSidebarFolderDot", () => { + it("flags the most urgent hidden thread and stays quiet otherwise", () => { + const idle = { + hasActionableProposedPlan: false, + hasPendingApprovals: false, + hasPendingUserInput: false, + interactionMode: "default" as const, + latestRun: makeLatestRun(), + lastVisitedAt: "2026-03-09T10:06:00.000Z", + runtime: null, + }; + const runtime = { + status: "running" as const, + activeRunId: null, + providerInstanceId: ProviderInstanceId.make("codex"), + providerName: "Codex", + lastError: null, + updatedAt: "2026-03-09T10:00:00.000Z", + }; + const working = { ...idle, runtime }; + const unread = { ...idle, lastVisitedAt: "2026-03-09T10:04:00.000Z" }; + const limited = { + ...idle, + runtime: { ...runtime, status: "failed" as const, lastErrorClass: "usage_limit" as const }, + }; + + expect(resolveSidebarFolderDot([idle])).toBeNull(); + // A waiting thread stays quiet even with an unread completion, like its row. + expect( + resolveSidebarFolderDot([{ ...unread, runtime: { ...runtime, status: "idle" as const } }]), + ).toBeNull(); + expect(resolveSidebarFolderDot([idle, working])).toBe("working"); + expect(resolveSidebarFolderDot([working, unread])).toBe("unread"); + expect(resolveSidebarFolderDot([unread, limited])).toBe("attention"); + }); +}); diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index aa4903db93e00..7f7705573673c 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -34,6 +34,7 @@ import { isLatestRunSettled } from "../session-logic"; import { observeIntersection } from "../lib/observeIntersection"; import { deadlineAfter, deadlineStore } from "@t3tools/client-runtime/clock"; import { useDeadlinePassed } from "../hooks/useDeadline"; +import { legacyProjectCwdPreferenceKey } from "../uiStateStore"; export function shouldNavigateAfterThreadPark(input: { readonly threadKey: string; @@ -51,7 +52,6 @@ export function shouldNavigateAfterThreadPark(input: { ); } -const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]"; const THREAD_JUMP_HINT_SHOW_DELAY_MS = 200; export function resolveSidebarRowAccessibility(input: { @@ -67,7 +67,6 @@ export function resolveSidebarRowAccessibility(input: { } // Each prewarm retains growing thread detail and a live subscription, multiplying heap and server load. -const SIDEBAR_THREAD_PREWARM_LIMIT = 3; const SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX = 160; export function useSidebarRowSubscriptionLease(isActive: boolean): { @@ -542,21 +541,6 @@ export async function archiveSelectedThreadEntries< return { archivedThreadKeys, mutationFailure: null, followupFailures }; } -export function buildMultiSelectThreadContextMenuItems(input: { - count: number; - hasRunningThread: boolean; -}): readonly ContextMenuItem<"mark-unread" | "archive" | "delete">[] { - return [ - { id: "mark-unread", label: `Mark unread (${input.count})` }, - { - id: "archive", - label: `Archive (${input.count})`, - disabled: input.hasRunningThread, - }, - { id: "delete", label: `Delete (${input.count})`, destructive: true }, - ]; -} - export function isSidebarSubagentThread(thread: Pick): boolean { return thread.lineage.relationshipToParent === "subagent"; } @@ -722,11 +706,6 @@ function hasUnseenFailure(thread: ThreadStatusInput): boolean { return completedAt > lastVisitedAt; } -export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean { - if (target === null) return true; - return !target.closest(THREAD_SELECTION_SAFE_SELECTOR); -} - // Suppress trailing double-click navigation; keyboard and synthetic clicks use detail 0. export function isTrailingDoubleClick(detail: number): boolean { return detail > 1; @@ -795,13 +774,6 @@ export function orderItemsByPreferredIds(input: { return [...ordered, ...remaining]; } -export function getSidebarThreadIdsToPrewarm( - visibleThreadIds: readonly TThreadId[], - limit = SIDEBAR_THREAD_PREWARM_LIMIT, -): TThreadId[] { - return visibleThreadIds.slice(0, Math.max(0, limit)); -} - export function resolveAdjacentThreadId(input: { threadIds: readonly T[]; currentThreadId: T | null; @@ -829,15 +801,6 @@ export function resolveAdjacentThreadId(input: { return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null; } -export function isContextMenuPointerDown(input: { - button: number; - ctrlKey: boolean; - isMac: boolean; -}): boolean { - if (input.button === 2) return true; - return input.isMac && input.button === 0 && input.ctrlKey; -} - export type SidebarThreadStatus = | "approval" | "input" @@ -909,6 +872,92 @@ export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): Si return "ready"; } +/** + * The dot on a closed boring-sidebar folder: the most urgent state among its + * hidden threads. Waiting threads stay quiet, like their rows. + */ +export function resolveSidebarFolderDot( + threads: ReadonlyArray, +): "attention" | "failed" | "unread" | "working" | null { + const statuses = new Set(threads.map(resolveSidebarThreadStatus)); + if ( + statuses.has("input") || + statuses.has("approval") || + statuses.has("request") || + statuses.has("limited") + ) { + return "attention"; + } + if (statuses.has("failed")) return "failed"; + // Rows show Done only for ready threads, so the dot follows the same rule. + const hasUnread = threads.some( + (thread) => resolveSidebarThreadStatus(thread) === "ready" && hasUnseenCompletion(thread), + ); + if (hasUnread) return "unread"; + if (statuses.has("working")) return "working"; + return null; +} + +/** + * Keys the old per-project sidebar saved folder open state under, most + * specific first, for `resolveProjectExpanded`. Boring folders read and write + * the same keys, so a legacy user's closed folders stay closed after regrouping. + */ +export function sidebarFolderExpansionKeys(group: { + readonly projectKey: string; + readonly memberProjects: ReadonlyArray<{ + readonly physicalProjectKey: string; + readonly workspaceRoot: string; + }>; +}): string[] { + return [ + group.projectKey, + ...group.memberProjects.map((member) => member.physicalProjectKey), + ...group.memberProjects.map((member) => legacyProjectCwdPreferenceKey(member.workspaceRoot)), + ]; +} + +/** + * Boring sidebar folders. Folders follow `groups` order and include empty + * projects so each one can start a thread. Threads keep their input order. + * A thread whose project is in no group has no folder and is left out. + */ +export function groupSidebarThreadsByProject< + TGroup extends { + readonly memberProjectRefs: ReadonlyArray<{ + readonly environmentId: EnvironmentId; + readonly projectId: string; + }>; + }, + TThread extends Pick, +>( + groups: readonly TGroup[], + threads: readonly TThread[], +): Array<{ group: TGroup; threads: TThread[] }> { + const folders = groups.map((group) => ({ group, threads: [] as TThread[] })); + const folderByProject = new Map(); + for (const folder of folders) { + for (const ref of folder.group.memberProjectRefs) { + folderByProject.set(`${ref.environmentId}:${ref.projectId}`, folder); + } + } + for (const thread of threads) { + folderByProject.get(`${thread.environmentId}:${thread.projectId}`)?.threads.push(thread); + } + return folders; +} + +export type SidebarV2TopStatusKind = + | "approval" + | "done" + | "failed" + | "limited" + | "input" + | "request" + | "waiting" + | "woke" + | "working"; + export function firstValidTimestampMs( ...candidates: ReadonlyArray ): number { diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 280e23dad4060..6bda36fc85919 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -110,7 +110,7 @@ import { getSidebarProjectSettingsKey, type SidebarProjectSnapshot, } from "../sidebarProjectGrouping"; -import { useUiStateStore } from "../uiStateStore"; +import { resolveProjectExpanded, useUiStateStore } from "../uiStateStore"; import { getThreadKeysToDeselectAfterDelete, useThreadSelectionStore, @@ -122,7 +122,7 @@ import { useTerminalFocus } from "../hooks/useTerminalFocus"; import { isCommandPaletteOpen, openCommandPalette } from "../commandPaletteBus"; import { registerSettleAndAdvance } from "../settleAndAdvance"; import { startNewThreadFromContext } from "../lib/chatThreadActions"; -import { useClientSettings } from "../hooks/useSettings"; +import { useBoringSidebarEnabled, useClientSettings } from "../hooks/useSettings"; import { useCopyToClipboard } from "../hooks/useCopyToClipboard"; import { useLocalStorage } from "../hooks/useLocalStorage"; import { useNowMinute } from "../hooks/useNowMinute"; @@ -168,6 +168,8 @@ import { import { applySidebarThreadDrop, filterSidebarV2VisibleThreads, + groupSidebarThreadsByProject, + sidebarFolderExpansionKeys, buildBulkTitleRegenerationContextMenuItem, buildBulkUnpinContextMenuItem, deleteSelectedThreadEntries, @@ -246,6 +248,10 @@ import { type SidebarSweepAction, } from "./sidebar/SidebarThreadRow"; import { SidebarDraftBlock } from "./sidebar/SidebarDraftBlock"; +import { + SidebarProjectFolderHeader, + sidebarFolderRowId, +} from "./sidebar/SidebarProjectFolderHeader"; import { SidebarDragBoundary, SidebarSectionHeader, @@ -391,6 +397,8 @@ function useSidebarThreads(input: { readonly threads: readonly EnvironmentThreadShell[]; readonly delegatedUnderParent: ReadonlySet; readonly routeRowThreadKey: string | null; + // Set in boring mode: the project groups to fold active threads into, in order. + readonly folderGroups: readonly SidebarProjectSnapshot[] | null; }) { const { projectScopeKey, @@ -400,8 +408,11 @@ function useSidebarThreads(input: { threads, delegatedUnderParent, routeRowThreadKey, + folderGroups, } = input; - const workingShelfEnabled = useClientSettings((s) => s.sidebarWorkingShelfEnabled); + // Folders already separate the work, so boring mode has no Working shelf. + const workingShelfEnabled = + useClientSettings((s) => s.sidebarWorkingShelfEnabled) && folderGroups === null; const inboxReturnsVersion = useSyncExternalStore( inboxReturns.subscribe, inboxReturns.getSnapshot, @@ -424,6 +435,9 @@ function useSidebarThreads(input: { false, Schema.Boolean, ); + // Shared with the old per-project sidebar, so folders keep their open state. + const projectExpandedById = useUiStateStore((store) => store.projectExpandedById); + const setProjectExpanded = useUiStateStore((store) => store.setProjectExpanded); const [settledTail, setSettledTail] = useState({ scopeKey: projectScopeKey, count: SETTLED_TAIL_INITIAL_COUNT, @@ -478,9 +492,31 @@ function useSidebarThreads(input: { const visibleWorkingThreads = workingShelfExpanded ? workingThreads : routeThreadOnly(workingThreads, routeRowThreadKey); + const projectFolders = + folderGroups === null + ? null + : groupSidebarThreadsByProject(folderGroups, activeThreads).map((folder) => { + const collapsed = !resolveProjectExpanded( + projectExpandedById, + sidebarFolderExpansionKeys(folder.group), + ); + return { + group: folder.group, + collapsed, + // A closed folder still shows the open thread, and hints at the rest. + threads: collapsed + ? routeThreadOnly(folder.threads, routeRowThreadKey) + : folder.threads, + hiddenThreads: collapsed + ? folder.threads.filter((thread) => threadShellKey(thread) !== routeRowThreadKey) + : EMPTY_THREADS, + }; + }); const orderedThreads = [ ...pinnedThreads, - ...activeThreads, + ...(projectFolders === null + ? activeThreads + : projectFolders.flatMap((folder) => folder.threads)), ...visibleWorkingThreads, ...visibleSnoozedThreads, ...renderedSettledThreads, @@ -521,6 +557,11 @@ function useSidebarThreads(input: { toggleSnoozedShelf: () => setSnoozedShelfExpanded((value) => !value), workingShelfExpanded, toggleWorkingShelf: () => setWorkingShelfExpanded((value) => !value), + projectFolders, + toggleProjectFolder: (group: SidebarProjectSnapshot) => { + const keys = sidebarFolderExpansionKeys(group); + setProjectExpanded(keys, !resolveProjectExpanded(projectExpandedById, keys)); + }, renderedSettledThreads, visibleSnoozedThreads, visibleWorkingThreads, @@ -911,6 +952,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); }, }); + const boringSidebarEnabled = useBoringSidebarEnabled(); const newThreadContext = useHandleNewThread(); // Row callbacks capture only the handler; the rest of the context changes with the route. const { handleNewThread } = newThreadContext; @@ -1145,6 +1187,40 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve openProjectSettings(projectGroup); }, ); + const startThreadInProjectFolder = useStableCallback((group: SidebarProjectSnapshot) => { + if (isMobile) setOpenMobile(false); + void handleNewThread(scopeProjectRef(group.environmentId, group.id)); + }); + const handleProjectFolderContextMenu = useStableCallback( + (group: SidebarProjectSnapshot, position: { x: number; y: number }) => { + const api = readLocalApi(); + if (!api) return; + void (async () => { + const clicked = await settlePromise(() => + api.contextMenu.show( + [ + { id: "new-thread", label: "New thread" }, + { id: "copy-path", label: "Copy path" }, + { id: "project-settings", label: "Project settings", icon: "settings" }, + ], + position, + ), + ); + if (clicked._tag === "Failure") return; + switch (clicked.value) { + case "new-thread": + startThreadInProjectFolder(group); + return; + case "copy-path": + copyPathToClipboard(group.workspaceRoot, { path: group.workspaceRoot }); + return; + case "project-settings": + openProjectSettings(group); + return; + } + })(); + }, + ); const { workingShelfEnabled, @@ -1168,6 +1244,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve toggleSnoozedShelf, workingShelfExpanded, toggleWorkingShelf, + projectFolders, + toggleProjectFolder, renderedSettledThreads, visibleSnoozedThreads, visibleWorkingThreads, @@ -1188,6 +1266,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve threads, delegatedUnderParent, routeRowThreadKey, + folderGroups: boringSidebarEnabled + ? scopedProjectGroups.length === 0 + ? projectGroups + : scopedProjectGroups + : null, }); // Ranked across environments as the palette ranks them, so one @@ -1748,6 +1831,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve event.activatorEvent instanceof PointerEvent ? event.activatorEvent.clientY : null, }); }; + const hasProjectFolders = projectFolders !== null && projectFolders.length > 0; const sidebarListItemsFresh = ((): readonly SidebarListItem[] => { const rowsOf = ( list: readonly EnvironmentThreadShell[], @@ -1757,13 +1841,15 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const key = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); return { kind: "thread", key, section }; }); + // Boring mode keeps empty project folders, so each can start a thread. if ( + !hasProjectFolders && pinnedThreads.length + activeThreads.length + workingThreads.length + snoozedThreads.length + settledCount === - 0 + 0 ) { return []; } @@ -1813,6 +1899,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve // Only order, section, or draft changes need layout reads and motion. const listMotionLayoutKey = [ sidebarListItemsKey, + projectFolders + ?.map((folder) => `${folder.group.projectKey}:${folder.threads.length}`) + .join("\n") ?? "", visibleDraftSessionCount, routeDraftIdForRows ?? "", ].join("\0"); @@ -2742,7 +2831,10 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const showJumpHints = useThreadJumpHintsVisible(shouldShowJumpHintsNow); const handleNewThreadClick = (event?: ReactMouseEvent) => { - if (shouldCreateNewThreadInCurrentProject(event?.shiftKey ?? false, projectGroups.length)) { + if ( + boringSidebarEnabled || + shouldCreateNewThreadInCurrentProject(event?.shiftKey ?? false, projectGroups.length) + ) { if (isMobile) setOpenMobile(false); void startNewThreadFromContext({ activeDraftThread: newThreadContext.activeDraftThread, @@ -2942,7 +3034,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve newThreadDisabled={projects.length === 0} newThreadShortcutLabel={newThreadShortcutLabel} newThreadInProjectShortcutLabel={newThreadInProjectShortcutLabel} - showNewThreadInProjectHint={projectGroups.length > 1} + showNewThreadInProjectHint={!boringSidebarEnabled && projectGroups.length > 1} searchInputRef={threadSearchInputRef} searchQuery={threadSearchQuery} onSearchQueryChange={(value) => { @@ -3058,19 +3150,22 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const renderThreadRow = ( thread: EnvironmentThreadShell, section: SidebarSection, + // The tree row of the project folder this row sits in. + folderRow?: string, ) => { const threadKey = scopedThreadKey( scopeThreadRef(thread.environmentId, thread.id), ); const isCard = section === "active" || section === "pinned" || section === "working"; - const rowVariant = isCard ? "card" : "slim"; + const rowVariant = folderRow ? "folder" : isCard ? "card" : "slim"; return ( , + ); + for (const thread of folder.threads) { + items.push( + renderThreadRow( + thread, + "active", + sidebarFolderRowId(folder.group.projectKey), + ), + ); + } + } + continue; + } switch (item.marker) { case "pinned-header": items.push( @@ -3330,6 +3453,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ) : null} {!isSearchingThreads && + !hasProjectFolders && visibleDraftSessionCount === 0 && pinnedThreads.length + activeThreads.length + diff --git a/apps/web/src/components/ThreadStatusIndicators.tsx b/apps/web/src/components/ThreadStatusIndicators.tsx index 45eb01782c763..682172f1ff308 100644 --- a/apps/web/src/components/ThreadStatusIndicators.tsx +++ b/apps/web/src/components/ThreadStatusIndicators.tsx @@ -440,7 +440,7 @@ export function ChangeRequestStatusIcon({ return ; } -export function PrStatusTooltipContent({ status }: { status: PrStatusIndicator }) { +function PrStatusTooltipContent({ status }: { status: PrStatusIndicator }) { return ( {status.tooltipLead} @@ -600,7 +600,7 @@ export function ThreadWorktreeIndicator({ ); } -export function ThreadStatusLabel({ +function ThreadStatusLabel({ status, compact = false, }: { diff --git a/apps/web/src/components/settings/LabsSettingsPanel.tsx b/apps/web/src/components/settings/LabsSettingsPanel.tsx index b06f7b04c4fb8..5f944c867db68 100644 --- a/apps/web/src/components/settings/LabsSettingsPanel.tsx +++ b/apps/web/src/components/settings/LabsSettingsPanel.tsx @@ -4,6 +4,7 @@ import { Link } from "@tanstack/react-router"; import { hasCloudPublicConfig } from "~/cloud/publicConfig"; import { useT3ConnectAuthPrompt } from "../clerk/useT3ConnectAuthPrompt"; import { Button } from "../ui/button"; +import { Switch } from "../ui/switch"; import { ScopedSwitch } from "./ScopedSwitch"; import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout"; import { searchableSetting } from "./settingsSearch"; @@ -15,6 +16,7 @@ export function LabsSettingsPanel() { return ( + {/* Clerk is only mounted when this build has T3 Connect. */} {hasCloudPublicConfig() ? : } @@ -24,6 +26,27 @@ export function LabsSettingsPanel() { ); } +function BoringSidebarRow() { + const settings = useScopedSettings(); + const updateSettings = useUpdateScopedSettings(); + return ( + + updateSettings({ boringSidebarEnabled: Boolean(checked), legacySidebarEnabled: false }) + } + aria-label="Boring sidebar (group by project)" + /> + } + /> + ); +} + /** Signed out of T3 Connect, the row offers to sign in instead of its switch. */ function GuestLinksRowWithSignIn() { const { isSignedIn } = useAuth(); diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 25e297470502f..a4aadac731081 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -425,9 +425,6 @@ export function useSettingsRestore(onRestored?: () => void) { ...(settings.inAppNotificationsEnabled !== DEFAULT_UNIFIED_SETTINGS.inAppNotificationsEnabled ? ["In-app notifications"] : []), - ...(settings.sidebarThreadPreviewCount !== DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount - ? ["Visible threads"] - : []), ...(settings.sidebarProjectGroupingMode !== DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode ? ["Project Grouping"] : []), @@ -603,7 +600,6 @@ export function useSettingsRestore(onRestored?: () => void) { environmentIdentificationMode: DEFAULT_UNIFIED_SETTINGS.environmentIdentificationMode, glassOpacity: DEFAULT_UNIFIED_SETTINGS.glassOpacity, panelAnimationDurationMs: DEFAULT_UNIFIED_SETTINGS.panelAnimationDurationMs, - sidebarThreadPreviewCount: DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount, sidebarProjectGroupingMode: DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode, sidebarProjectSortOrder: DEFAULT_UNIFIED_SETTINGS.sidebarProjectSortOrder, sidebarWorkingShelfEnabled: DEFAULT_UNIFIED_SETTINGS.sidebarWorkingShelfEnabled, @@ -732,19 +728,6 @@ export function LegacyFeaturesSection() { /> } /> - - updateSettings({ legacySidebarEnabled: Boolean(checked) }) - } - aria-label="Sidebar (legacy)" - /> - } - /> ); } @@ -851,7 +834,7 @@ export function GeneralSettingsPanel() { /> { const streaming = getSettingsSearchTargetScope("response-streaming")!; expect(streaming.scope).toBe("project-defaults"); expect(isSettingsSearchScopeAvailable(streaming.scope, "project")).toBe(true); - for (const id of ["legacy-plan-mode", "legacy-context-window-indicator", "legacy-sidebar"]) { + for (const id of ["legacy-plan-mode", "legacy-context-window-indicator", "boring-sidebar"]) { expect(getSettingsSearchTargetScope(id)!.scope).toBeNull(); } }); diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 460a6ef650b61..25b5b7cc6d24e 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -419,6 +419,12 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/general", searchTerms: ["hide fold running monitoring threads inbox sidebar shelf"], }, + { + id: "boring-sidebar", + title: "Boring sidebar (group by project)", + to: "/settings/labs", + searchTerms: ["beta folders project tree legacy old classic sidebar"], + }, { id: "guest-links", title: "Guest links", @@ -708,12 +714,6 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/labs", searchTerms: ["composer meter usage tokens circle old"], }, - { - id: "legacy-sidebar", - title: "Sidebar (legacy)", - to: "/settings/labs", - searchTerms: ["project thread tree old flat list"], - }, { id: "keybindings", title: "Keybindings", diff --git a/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx b/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx new file mode 100644 index 0000000000000..1ee152533a75b --- /dev/null +++ b/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx @@ -0,0 +1,115 @@ +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; +import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { ChevronDownIcon, SquarePenIcon } from "lucide-react"; +import { memo } from "react"; + +import { cn } from "~/lib/utils"; +import type { SidebarProjectSnapshot } from "../../sidebarProjectGrouping"; +import { useUiStateStore } from "../../uiStateStore"; +import { resolveSidebarFolderDot, resolveThreadLastVisitedAt } from "../Sidebar.logic"; +import { ProjectFavicon } from "../ProjectFavicon"; +import { Button } from "../ui/button"; + +const FOLDER_DOT_CLASS_NAME = { + attention: "bg-warning", + failed: "bg-error", + unread: "bg-success", + working: "bg-info", +} as const; + +const FOLDER_DOT_LABEL = { + attention: ", needs you", + failed: ", failed", + unread: ", done", + working: ", working", +} as const; + +/** The folder's sidebar tree row; its thread rows name it as their parent. */ +export function sidebarFolderRowId(projectKey: string) { + return `folder:${projectKey}`; +} + +/** + * A project folder in the boring sidebar. It reads like a shelf header: a trailing + * count and chevron, with the count and a status dot only while it is closed, so a + * closed folder still says when a hidden thread needs you. + */ +export const SidebarProjectFolderHeader = memo(function SidebarProjectFolderHeader(props: { + group: SidebarProjectSnapshot; + collapsed: boolean; + hiddenThreads: readonly EnvironmentThreadShell[]; + onToggle: (group: SidebarProjectSnapshot) => void; + onNewThread: (group: SidebarProjectSnapshot) => void; + onContextMenu: (group: SidebarProjectSnapshot, position: { x: number; y: number }) => void; +}) { + const { group, collapsed, hiddenThreads } = props; + const rowId = sidebarFolderRowId(group.projectKey); + const localLastVisitedAtById = useUiStateStore((state) => state.threadLastVisitedAtById); + const dot = collapsed + ? resolveSidebarFolderDot( + hiddenThreads.map((thread) => ({ + ...thread, + lastVisitedAt: resolveThreadLastVisitedAt( + thread.lastVisitedAt, + localLastVisitedAtById[ + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) + ], + ), + })), + ) + : null; + return ( +
  • + + {/* Sits over the count, which hides on hover, and left of the chevron. */} + + + +
  • + ); +}); diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsx index dff97ef21057d..eac7c8591fa1c 100644 --- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx @@ -515,9 +515,26 @@ const dropVerbBadge: Record = { ), }; +const TOP_STATUS_ICONS = { + working: CircleDashedIcon, + waiting: CircleDotDashedIcon, + input: MessageCircleQuestionIcon, + request: UserRoundIcon, + approval: ShieldQuestionIcon, + failed: CircleAlertIcon, + done: CircleCheckIcon, + woke: AlarmClockIcon, +} as const; + +function TopStatusIcon(props: { icon: keyof typeof TOP_STATUS_ICONS; className: string }) { + const Icon = TOP_STATUS_ICONS[props.icon]; + return ; +} + type SidebarThreadRowProps = { thread: SidebarThreadSummary; - variant: "card" | "slim"; + // "folder" is a one-line row inside a boring sidebar project folder. + variant: "card" | "slim" | "folder"; navigationParent?: string | undefined; variantAction: SidebarSweepAction; settlementSupported: boolean; @@ -997,7 +1014,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP className={cn( "min-w-0 flex-1 text-start text-sm transition-opacity motion-reduce:transition-none", shouldRecede ? "font-normal" : "font-medium", - variant === "card" + variant !== "slim" ? cn( "truncate", shouldRecede @@ -1104,7 +1121,8 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP ) ) : null; - if (variant === "slim") { + if (variant !== "card") { + const inFolder = variant === "folder"; return (
  • {accessibleTitle} - - {props.project ? : null} - + {inFolder ? null : ( + + {props.project ? ( + + ) : null} + + )} {draftIndicator} {title} {pinIndicator} @@ -1176,7 +1203,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP {props.snoozeWakeLabelText} - ) : isWoke ? ( + ) : (inFolder ? isWokeStatus : isWoke) ? ( Dismiss Woke notification + ) : inFolder && topStatus ? ( + // Folder rows have no status line, so the status takes the time slot. + + + {topStatus.label} + ) : ( - {topStatus.icon === "working" ? ( - - ) : topStatus.icon === "waiting" ? ( - - ) : topStatus.icon === "input" ? ( - - ) : topStatus.icon === "request" ? ( - - ) : topStatus.icon === "approval" ? ( - - ) : topStatus.icon === "failed" ? ( - - ) : topStatus.icon === "done" ? ( - - ) : null} + {/* Not a live region: a collapsed sidebar is inert, so BackgroundThreadAnnouncer and the open thread's timeline speak status changes instead. */} diff --git a/apps/web/src/components/ui/sidebar.tsx b/apps/web/src/components/ui/sidebar.tsx index b4246f2cfabf0..6060a867fed7a 100644 --- a/apps/web/src/components/ui/sidebar.tsx +++ b/apps/web/src/components/ui/sidebar.tsx @@ -97,7 +97,7 @@ function useSidebarVisibility() { return isMobile ? openMobile : open; } -// Same breakpoint as useIsMobile, also read when a shortcut fires. +// The `max-md` breakpoint, also read when a shortcut fires. const SIDEBAR_MOBILE_QUERY = "(max-width: 767px)"; function isMobileViewport(): boolean { diff --git a/apps/web/src/connection/desktopLocal.ts b/apps/web/src/connection/desktopLocal.ts index 746344759a76e..eb46a09ab3ac6 100644 --- a/apps/web/src/connection/desktopLocal.ts +++ b/apps/web/src/connection/desktopLocal.ts @@ -26,10 +26,6 @@ export function desktopLocalBackendId(target: ConnectionTarget): string | null { : null; } -export function isWslConnectionTarget(target: ConnectionTarget): boolean { - return desktopLocalBackendId(target)?.startsWith("wsl:") === true; -} - export type DesktopSecondaryBootstrapsRead = | { readonly _tag: "Success"; diff --git a/apps/web/src/hooks/useMediaQuery.ts b/apps/web/src/hooks/useMediaQuery.ts index ec6ee4fa51160..f3df1b3a4b1de 100644 --- a/apps/web/src/hooks/useMediaQuery.ts +++ b/apps/web/src/hooks/useMediaQuery.ts @@ -77,7 +77,3 @@ export function useMediaQuery(query: BreakpointQuery | MediaQueryInput | (string return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); } - -export function useIsMobile(): boolean { - return useMediaQuery("max-md"); -} diff --git a/apps/web/src/hooks/useSettings.ts b/apps/web/src/hooks/useSettings.ts index 70f8ac321f54f..87733457a417b 100644 --- a/apps/web/src/hooks/useSettings.ts +++ b/apps/web/src/hooks/useSettings.ts @@ -415,11 +415,11 @@ export function useEnvironmentIdentificationMode(): EnvironmentIdentificationMod }); } -/** Wait for hydration: swapping sidebar implementations after mount remounts the whole tree. */ -export function useLegacySidebarEnabled(): boolean { - const settingsHydrated = useClientSettingsHydrated(); - const legacySidebarEnabled = useClientSettings((settings) => settings.legacySidebarEnabled); - return settingsHydrated && legacySidebarEnabled; +/** Legacy sidebar opt-ins still count, so those users land in the boring sidebar. */ +export function useBoringSidebarEnabled(): boolean { + return useClientSettings( + (settings) => settings.boringSidebarEnabled || settings.legacySidebarEnabled, + ); } export async function prepareModelPreferencesPatch( diff --git a/apps/web/src/shortcuts/chatRouteCommands.ts b/apps/web/src/shortcuts/chatRouteCommands.ts index e832ca295284e..f0f80dfed8830 100644 --- a/apps/web/src/shortcuts/chatRouteCommands.ts +++ b/apps/web/src/shortcuts/chatRouteCommands.ts @@ -117,8 +117,10 @@ export function installChatRouteCommands(router: AnyRouter): () => void { void scratch.startScratchThread(environmentId); }, "chat.new": (event) => { - // Pre-hydration settings are the defaults, where the legacy sidebar is off. - if (!getClientSettings().legacySidebarEnabled && readProjectGroupCount() > 1) { + // The boring sidebar's folders already show the context, so it starts in + // the current project like the legacy sidebar did. + const { boringSidebarEnabled, legacySidebarEnabled } = getClientSettings(); + if (!boringSidebarEnabled && !legacySidebarEnabled && readProjectGroupCount() > 1) { claim(event); openCommandPalette({ open: "new-thread-in" }); return; diff --git a/apps/web/src/state/use-orchestration-command.ts b/apps/web/src/state/use-orchestration-command.ts index 1c801abc3c6b7..98f7efeecbfe6 100644 --- a/apps/web/src/state/use-orchestration-command.ts +++ b/apps/web/src/state/use-orchestration-command.ts @@ -14,8 +14,7 @@ import { AsyncResult } from "effect/reactivity"; import { readEnvironmentScope } from "./session"; import { useAtomCommand } from "./use-atom-command"; -export const ORCHESTRATION_OPERATE_DENIED_MESSAGE = - "This connection cannot change threads or projects."; +const ORCHESTRATION_OPERATE_DENIED_MESSAGE = "This connection cannot change threads or projects."; export function useOrchestrationCommand( command: AtomCommand, diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index ebab04125a3bf..b5373749a4956 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -139,6 +139,15 @@ choice. While this is on, the active list is ordered by when each thread last came back to you, so you cannot drag or move threads within it. Your saved order returns when you turn it off. +### Group threads by project (beta) + +Turn on **Settings → Labs → Boring sidebar (group by project)** on web and desktop to put active +threads in a folder for each project. Click a folder to open or close it. A closed folder shows how +many threads it holds, and a dot when one of them needs you. Use the pen button on a folder, or +right-click it, to start a thread in that project. Pinned threads stay above the folders, and +Snoozed and Settled stay below them. In this mode you cannot drag threads, and the Working section +is off. Each device keeps its own choice. + ## Settle finished work Choose **Settle thread** from its menu to move finished work out of the active list diff --git a/packages/client-runtime/src/state/projectGrouping.ts b/packages/client-runtime/src/state/projectGrouping.ts index 6866c02b08cfd..a23fd4a79e0bc 100644 --- a/packages/client-runtime/src/state/projectGrouping.ts +++ b/packages/client-runtime/src/state/projectGrouping.ts @@ -78,7 +78,7 @@ export function derivePhysicalProjectKey( return derivePhysicalProjectKeyFromPath(project.environmentId, project.workspaceRoot); } -export function deriveProjectGroupingOverrideKey( +function deriveProjectGroupingOverrideKey( project: Pick, ): string { return derivePhysicalProjectKey(project); diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index a21013004c6cb..8fc9a46116e78 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -72,16 +72,6 @@ export const SidebarProjectGroupingMode = Schema.Literals([ ]); export type SidebarProjectGroupingMode = typeof SidebarProjectGroupingMode.Type; const DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE: SidebarProjectGroupingMode = "repository"; -export const MIN_SIDEBAR_THREAD_PREVIEW_COUNT = 1; -export const MAX_SIDEBAR_THREAD_PREVIEW_COUNT = 15; -export const SidebarThreadPreviewCount = Schema.Int.check( - Schema.isBetween({ - minimum: MIN_SIDEBAR_THREAD_PREVIEW_COUNT, - maximum: MAX_SIDEBAR_THREAD_PREVIEW_COUNT, - }), -); -export type SidebarThreadPreviewCount = typeof SidebarThreadPreviewCount.Type; -const DEFAULT_SIDEBAR_THREAD_PREVIEW_COUNT: SidebarThreadPreviewCount = 6; export const MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS = 1; export const MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS = 90; export const SidebarAutoSettleAfterDays = Schema.Number.check( @@ -479,6 +469,9 @@ export const ClientSettingsSchema = Schema.Struct({ ), proactivePanelsEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), showSkillsInSlashMenu: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), + boringSidebarEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), + // Opt-in for the removed legacy sidebar. Still read so those users land in + // the boring sidebar; the boring sidebar toggle clears it. legacySidebarEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), sidebarWorkingShelfEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), sidebarProjectGroupingMode: SidebarProjectGroupingMode.pipe( @@ -494,9 +487,6 @@ export const ClientSettingsSchema = Schema.Struct({ sidebarThreadSortOrder: SidebarThreadSortOrder.pipe( Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_THREAD_SORT_ORDER)), ), - sidebarThreadPreviewCount: SidebarThreadPreviewCount.pipe( - Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_THREAD_PREVIEW_COUNT)), - ), timestampFormat: TimestampFormat.pipe( Schema.withDecodingDefault(Effect.succeed(DEFAULT_TIMESTAMP_FORMAT)), ), @@ -1712,6 +1702,7 @@ export const ClientSettingsPatch = Schema.Struct({ followUpBehavior: Schema.optionalKey(Schema.Literals(["queue", "steer"])), proactivePanelsEnabled: Schema.optionalKey(Schema.Boolean), showSkillsInSlashMenu: Schema.optionalKey(Schema.Boolean), + boringSidebarEnabled: Schema.optionalKey(Schema.Boolean), legacySidebarEnabled: Schema.optionalKey(Schema.Boolean), sidebarWorkingShelfEnabled: Schema.optionalKey(Schema.Boolean), sidebarProjectGroupingMode: Schema.optionalKey(SidebarProjectGroupingMode), @@ -1720,7 +1711,6 @@ export const ClientSettingsPatch = Schema.Struct({ ), sidebarProjectSortOrder: Schema.optionalKey(SidebarProjectSortOrder), sidebarThreadSortOrder: Schema.optionalKey(SidebarThreadSortOrder), - sidebarThreadPreviewCount: Schema.optionalKey(SidebarThreadPreviewCount), timestampFormat: Schema.optionalKey(TimestampFormat), snapShotEnabled: Schema.optionalKey(Schema.Boolean), snapShotIncludeAccessibility: Schema.optionalKey(Schema.Boolean), diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0adcb65c50062..5889ab5607c79 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1033,9 +1033,6 @@ importers: '@fontsource-variable/inter': specifier: ^5.3.0 version: 5.3.0 - '@formkit/auto-animate': - specifier: ^0.9.0 - version: 0.9.0 '@legendapp/list': specifier: 3.3.5 version: 3.3.5(patch_hash=6cbdacd8c380d9a5afb9f73d4198dc2cc44be6ef28a955b1183c781469307896)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) @@ -4311,9 +4308,6 @@ packages: '@fontsource-variable/inter@5.3.0': resolution: {integrity: sha512-OupL48va4JNofb97w6NYeF9S7W/kHNKM0Er8Dem5nqi4jeOLrVJDoE8tZEpnMJmtkvNbB1EIPPwHcdkF6b1oUA==} - '@formkit/auto-animate@0.9.0': - resolution: {integrity: sha512-VhP4zEAacXS3dfTpJpJ88QdLqMTcabMg0jwpOSxZ/VzfQVfl3GkZSCZThhGC5uhq/TxPHPzW0dzr4H9Bb1OgKA==} - '@hono/node-server@1.19.17': resolution: {integrity: sha512-dSneS5qhiauZWGDCeK4o695Xd9nUNjviSZCMQrj10eetr8Uln1ucn6bbphOM6UynAMMtNIzZNSpL9vnASJwrPQ==} engines: {node: '>=18.14.1'} @@ -14427,8 +14421,6 @@ snapshots: '@fontsource-variable/inter@5.3.0': {} - '@formkit/auto-animate@0.9.0': {} - '@hono/node-server@1.19.17(hono@4.13.7)': dependencies: hono: 4.13.7 From 9ebca5f71cbcf050e94732f0a1da041073223c84 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 28 Oct 2026 00:13:53 -0700 Subject: [PATCH 195/817] fix(relay): tunnel limit counts abandoned reprovisions and frees failed revokes (#26320) Co-authored-by: Claude Opus 5.5 --- .../migration.sql | 12 + .../snapshot.json | 1571 +++++++++++++++++ infra/relay/package.json | 1 + .../ManagedEndpointAllocations.test.ts | 27 + .../ManagedEndpointAllocations.ts | 9 +- .../ManagedEndpointProvider.test.ts | 46 + .../environments/ManagedEndpointProvider.ts | 26 + .../environments/ManagedTunnelLimits.test.ts | 204 ++- .../src/environments/ManagedTunnelLimits.ts | 96 +- pnpm-lock.yaml | 6 +- 10 files changed, 1931 insertions(+), 67 deletions(-) create mode 100644 infra/relay/migrations/postgres/20261028062605_backfill_withdrawn_tunnel_allocations/migration.sql create mode 100644 infra/relay/migrations/postgres/20261028062605_backfill_withdrawn_tunnel_allocations/snapshot.json diff --git a/infra/relay/migrations/postgres/20261028062605_backfill_withdrawn_tunnel_allocations/migration.sql b/infra/relay/migrations/postgres/20261028062605_backfill_withdrawn_tunnel_allocations/migration.sql new file mode 100644 index 0000000000000..4c822889bd98e --- /dev/null +++ b/infra/relay/migrations/postgres/20261028062605_backfill_withdrawn_tunnel_allocations/migration.sql @@ -0,0 +1,12 @@ +-- Teardown claims used to bump updated_at past the link's revoke or publish-only write, so a +-- failed deprovision now reads as an unfinished relink. Give those rows the updated_at the +-- current write rule would have left. Touches only withdrawn links' live tunnels; idempotent. +UPDATE "relay_managed_endpoint_allocations" AS a +SET "updated_at" = l."updated_at" +FROM "relay_environment_links" AS l +WHERE l."user_id" = a."user_id" + AND l."environment_id" = a."environment_id" + AND a."tunnel_id" IS NOT NULL + AND a."tunnel_released_at" IS NULL + AND (l."revoked_at" IS NOT NULL OR l."managed_tunnels_enabled" = false) + AND l."updated_at" < a."updated_at"; diff --git a/infra/relay/migrations/postgres/20261028062605_backfill_withdrawn_tunnel_allocations/snapshot.json b/infra/relay/migrations/postgres/20261028062605_backfill_withdrawn_tunnel_allocations/snapshot.json new file mode 100644 index 0000000000000..e02f3a0c6f2e7 --- /dev/null +++ b/infra/relay/migrations/postgres/20261028062605_backfill_withdrawn_tunnel_allocations/snapshot.json @@ -0,0 +1,1571 @@ +{ + "id": "4413755a-63f1-4f93-bdc9-d1357283c23e", + "prevIds": ["7d8c1702-6f47-4453-a8ee-66ce5e3bfb41"], + "version": "8", + "dialect": "postgres", + "ddl": [ + { + "isRlsEnabled": false, + "name": "relay_agent_activity_rows", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_delivery_attempts", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_dpop_proofs", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_environment_credentials", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_environment_links", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_live_activities", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_managed_endpoint_allocations", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_managed_tunnel_limits", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_mobile_devices", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_upstream_api_pauses", + "entityType": "tables", + "schema": "public" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_id", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_public_key", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "varchar(512)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "thread_id", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "state_json", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "varchar(36)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(512)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "thread_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "device_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "kind", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "source_job_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(16)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "token_suffix", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "apns_status", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "apns_reason", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(128)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "apns_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "transport_error", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(128)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "thumbprint", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "jti", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "iat", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "expires_at", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "credential_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_public_key", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "credential_hash", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "revoked_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "'T3 Environment'", + "generated": null, + "identity": null, + "name": "environment_label", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_public_key", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "endpoint_http_base_url", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "endpoint_ws_base_url", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(32)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "endpoint_provider_kind", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "true", + "generated": null, + "identity": null, + "name": "notifications_enabled", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "true", + "generated": null, + "identity": null, + "name": "live_activities_enabled", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "managed_tunnels_enabled", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "hold_webhooks_while_offline", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_by_device_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "revoked_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "device_id", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "activity_push_token", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "remote_start_queued_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "remote_started_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "ended_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "last_aggregate_json", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "last_live_activity_delivery_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_id", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "hostname", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "tunnel_id", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "tunnel_name", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "dns_record_id", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "ready_at", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "recovery_enabled_at", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "recovery_environment_public_key", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "tunnel_released_at", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "origin", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "0", + "generated": null, + "identity": null, + "name": "generation", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_tunnel_limits" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "max_tunnels", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_tunnel_limits" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_tunnel_limits" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_tunnel_limits" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "device_id", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "'iOS device'", + "generated": null, + "identity": null, + "name": "label", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(16)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "platform", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "ios_major_version", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "android_api_level", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "app_version", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "bundle_id", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(16)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "aps_environment", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "push_token", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "push_to_start_token", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "preferences_json", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "api", + "entityType": "columns", + "schema": "public", + "table": "relay_upstream_api_pauses" + }, + { + "type": "bigint", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "paused_until_ms", + "entityType": "columns", + "schema": "public", + "table": "relay_upstream_api_pauses" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "created_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_delivery_attempts_created", + "entityType": "indexes", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "source_job_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_delivery_attempts_source_job", + "entityType": "indexes", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "expires_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_dpop_proofs_expires_at", + "entityType": "indexes", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "credential_hash", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_environment_credentials_hash", + "entityType": "indexes", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "environment_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "environment_public_key", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "revoked_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_environment_credentials_environment_key", + "entityType": "indexes", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "environment_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "revoked_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_environment_links_environment", + "entityType": "indexes", + "schema": "public", + "table": "relay_environment_links" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "activity_push_token", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_live_activities_activity_push_token", + "entityType": "indexes", + "schema": "public", + "table": "relay_live_activities" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "hostname", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_managed_endpoint_allocations_hostname", + "entityType": "indexes", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "tunnel_name", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_managed_endpoint_allocations_tunnel_name", + "entityType": "indexes", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "push_token", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_mobile_devices_push_token", + "entityType": "indexes", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "push_to_start_token", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_mobile_devices_push_to_start_token", + "entityType": "indexes", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "columns": ["environment_id", "environment_public_key", "thread_id"], + "nameExplicit": false, + "name": "relay_agent_activity_rows_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "columns": ["thumbprint", "jti"], + "nameExplicit": false, + "name": "relay_dpop_proofs_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "columns": ["user_id", "environment_id"], + "nameExplicit": false, + "name": "relay_environment_links_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_environment_links" + }, + { + "columns": ["user_id", "device_id"], + "nameExplicit": false, + "name": "relay_live_activities_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_live_activities" + }, + { + "columns": ["user_id", "environment_id"], + "nameExplicit": false, + "name": "relay_managed_endpoint_allocations_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "columns": ["user_id", "device_id"], + "nameExplicit": false, + "name": "relay_mobile_devices_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "relay_delivery_attempts_pkey", + "schema": "public", + "table": "relay_delivery_attempts", + "entityType": "pks" + }, + { + "columns": ["credential_id"], + "nameExplicit": false, + "name": "relay_environment_credentials_pkey", + "schema": "public", + "table": "relay_environment_credentials", + "entityType": "pks" + }, + { + "columns": ["user_id"], + "nameExplicit": false, + "name": "relay_managed_tunnel_limits_pkey", + "schema": "public", + "table": "relay_managed_tunnel_limits", + "entityType": "pks" + }, + { + "columns": ["api"], + "nameExplicit": false, + "name": "relay_upstream_api_pauses_pkey", + "schema": "public", + "table": "relay_upstream_api_pauses", + "entityType": "pks" + } + ], + "renames": [] +} diff --git a/infra/relay/package.json b/infra/relay/package.json index c75e4b70648d2..197c37819981e 100644 --- a/infra/relay/package.json +++ b/infra/relay/package.json @@ -33,6 +33,7 @@ "@cloudflare/workers-types": "^4.20260601.1", "@effect/platform-node": "catalog:", "@effect/vitest": "catalog:", + "@electric-sql/pglite": "0.3.15", "@types/node": "catalog:", "drizzle-kit": "1.0.0-rc.5-ab785fc", "typescript": "catalog:", diff --git a/infra/relay/src/environments/ManagedEndpointAllocations.test.ts b/infra/relay/src/environments/ManagedEndpointAllocations.test.ts index 931e8a2b8893d..f0cd86bef9669 100644 --- a/infra/relay/src/environments/ManagedEndpointAllocations.test.ts +++ b/infra/relay/src/environments/ManagedEndpointAllocations.test.ts @@ -74,4 +74,31 @@ describe("ManagedEndpointAllocations", () => { ]); }).pipe(Effect.provide(layerWithDb(fakeDb))); }); + + it.effect("teardown claims leave updatedAt to provisioning writes", () => { + // The tunnel limit compares link and allocation updatedAt; a claim that bumps it makes a + // failed revoke cleanup look like a reprovision and keeps holding the user's slot. + const writes: Array> = []; + const fakeDb = { + update: () => ({ + set: (values: Record) => { + writes.push(values); + return { + where: () => ({ returning: () => Effect.succeed([{ generation: 2 }]) }), + }; + }, + }), + } as unknown as RelayDb.RelayDb["Service"]; + + return Effect.gen(function* () { + const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations; + const key = { userId: "user-1", environmentId: "environment-1", generation: 1 }; + yield* allocations.claimDeprovision(key); + yield* allocations.claimRelease({ ...key, tunnelId: "tunnel-1" }); + yield* allocations.claimRelease({ ...key, tunnelId: "tunnel-1", markReleased: true }); + + expect(writes.map((values) => "updatedAt" in values)).toEqual([false, false, true]); + expect(writes[2]?.["updatedAt"]).toBe(writes[2]?.["tunnelReleasedAt"]); + }).pipe(Effect.provide(layerWithDb(fakeDb))); + }); }); diff --git a/infra/relay/src/environments/ManagedEndpointAllocations.ts b/infra/relay/src/environments/ManagedEndpointAllocations.ts index d432f45c61763..918c410e35176 100644 --- a/infra/relay/src/environments/ManagedEndpointAllocations.ts +++ b/infra/relay/src/environments/ManagedEndpointAllocations.ts @@ -512,9 +512,8 @@ const make = Effect.gen(function* () { const claimed = yield* db .update(relayManagedEndpointAllocations) .set({ - updatedAt: now, generation: sql`${relayManagedEndpointAllocations.generation} + 1`, - ...(input.markReleased === true ? { tunnelReleasedAt: now } : {}), + ...(input.markReleased === true ? { tunnelReleasedAt: now, updatedAt: now } : {}), }) .where( and( @@ -585,10 +584,8 @@ const make = Effect.gen(function* () { ) { const claimed = yield* db .update(relayManagedEndpointAllocations) - .set({ - updatedAt: DateTime.formatIso(yield* DateTime.now), - generation: sql`${relayManagedEndpointAllocations.generation} + 1`, - }) + // Claims move only the generation: the tunnel limit reads updatedAt as the last provisioning write. + .set({ generation: sql`${relayManagedEndpointAllocations.generation} + 1` }) .where( and( whereAllocation(input), diff --git a/infra/relay/src/environments/ManagedEndpointProvider.test.ts b/infra/relay/src/environments/ManagedEndpointProvider.test.ts index 36ea69d5a2694..01230171be9ba 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.test.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.test.ts @@ -1406,6 +1406,52 @@ describe("ManagedEndpointProvider", () => { }).pipe(Effect.provide(layer)); }); + it.effect("marks the tunnel released when removing the allocation fails after deletion", () => { + const allocationCalls: AllocationCall[] = []; + const allocations = makeAllocations(allocationCalls); + const layer = layerProvider(makePersistentTunnelClient(), makeDnsClient(), { + ...allocations, + removeClaimed: (input) => + Effect.suspend(() => { + allocationCalls.push({ operation: "removeClaimed", input }); + return Effect.fail( + new ManagedEndpointAllocations.ManagedEndpointAllocationPersistenceError({ + operation: "remove-claimed", + stage: "database-request", + userId: input.userId, + environmentId: input.environmentId, + }), + ); + }), + }); + + return Effect.gen(function* () { + const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider; + const key = { userId: "user_ABC", environmentId: "env_ABC" } as const; + yield* provider.provision({ + ...key, + origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, + }); + const result = yield* Effect.result(provider.deprovision(key)); + + expect(result._tag).toBe("Failure"); + if (result._tag === "Failure") { + expect(result.failure).toMatchObject({ stage: "remove-allocation" }); + } + // The tunnel is gone; without the mark the tunnel limit would keep counting it. + const claim = allocationCalls.find((call) => call.operation === "claimDeprovision"); + if (claim === undefined) return expect.unreachable("deprovision never claimed the row"); + expect(allocationCalls.at(-1)).toMatchObject({ + operation: "claimRelease", + input: { + tunnelId: "tunnel-id", + generation: (claim.input as { generation: number }).generation + 1, + markReleased: true, + }, + }); + }).pipe(Effect.provide(layer)); + }); + it.effect("treats already deleted remote resources as successfully deprovisioned", () => { const allocationCalls: AllocationCall[] = []; const notFound = { _tag: "NotFound" } as const; diff --git a/infra/relay/src/environments/ManagedEndpointProvider.ts b/infra/relay/src/environments/ManagedEndpointProvider.ts index 5524b5117faaf..9a76b9c09981a 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.ts @@ -882,6 +882,7 @@ const make = Effect.gen(function* () { return false; } const tunnelId = allocation.tunnelId; + let tunnelDeleted = false; const deprovision = Effect.gen(function* () { const dnsRecordId = allocation.dnsRecordId; if (dnsRecordId !== null) { @@ -909,6 +910,7 @@ const make = Effect.gen(function* () { }), ), ); + tunnelDeleted = true; } return yield* allocations .removeClaimed({ @@ -956,6 +958,30 @@ const make = Effect.gen(function* () { }), ), }), + // The rollback keeps the deleted tunnel's id; mark it released so the tunnel limit stops + // counting it. onError also covers an interrupted unlink, which rolls back the same way. + Effect.onError(() => + tunnelDeleted + ? allocations + .claimRelease({ + userId: input.userId, + environmentId: input.environmentId, + tunnelId, + generation: claimedGeneration, + markReleased: true, + }) + .pipe( + Effect.catch((error) => + Effect.logWarning("Failed to mark a deleted managed tunnel released", { + userId: input.userId, + environmentId: input.environmentId, + tunnelId, + error: error.message, + }), + ), + ) + : Effect.void, + ), ); return Option.getOrElse(removed, () => false); }), diff --git a/infra/relay/src/environments/ManagedTunnelLimits.test.ts b/infra/relay/src/environments/ManagedTunnelLimits.test.ts index d45dfc0fde8fd..5837ae3f0eb52 100644 --- a/infra/relay/src/environments/ManagedTunnelLimits.test.ts +++ b/infra/relay/src/environments/ManagedTunnelLimits.test.ts @@ -1,8 +1,13 @@ import { describe, expect, it } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Semaphore from "effect/Semaphore"; +import { PGlite } from "@electric-sql/pglite"; +import { drizzle } from "drizzle-orm/pglite"; +import { ne } from "drizzle-orm"; import { PgDialect } from "drizzle-orm/pg-core"; import type { RelayT3ChatPlan } from "@t3tools/contracts/relay"; @@ -11,6 +16,8 @@ import { relayManagedEndpointAllocations } from "../persistence/schema.ts"; import * as T3ChatAccounts from "../t3chat/T3ChatAccounts.ts"; import * as ManagedTunnelLimits from "./ManagedTunnelLimits.ts"; +const BACKFILL_MIGRATION = "20261028062605_backfill_withdrawn_tunnel_allocations"; + class FakeTransaction extends Context.Service()( "t3code-relay/environments/ManagedTunnelLimits.test/FakeTransaction", ) {} @@ -19,7 +26,6 @@ interface FakeDbInput { readonly otherSlots: () => number; readonly ownSlot?: boolean; readonly override?: number; - readonly countConditions?: Array; } // Models Postgres just enough: the advisory lock only works inside a transaction and is held until it ends. @@ -59,7 +65,6 @@ function makeFakeDb(input: FakeDbInput) { ), }; } - input.countConditions?.push(condition); const countsOthers = dialect .sqlToQuery(condition as never) .sql.includes('"relay_managed_endpoint_allocations"."environment_id" <>'); @@ -154,24 +159,191 @@ describe("ManagedTunnelLimits", () => { ); }); - it.effect("pending reservations stop counting once released or withdrawn", () => { - const countConditions: Array = []; + it.effect("counts each allocation by its tunnel and link state", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const pg = yield* Effect.acquireRelease( + Effect.promise(() => PGlite.create()), + (client) => Effect.promise(() => client.close()), + ); + const migrationsDir = new URL("../../migrations/postgres/", import.meta.url).pathname; + const migrations = (yield* fs.readDirectory(migrationsDir)).toSorted(); + const applyMigrations = (names: ReadonlyArray) => + Effect.forEach(names, (name) => + fs + .readFileString(`${migrationsDir}${name}/migration.sql`) + .pipe(Effect.flatMap((migration) => Effect.promise(() => pg.exec(migration)))), + ); + const backfill = migrations.indexOf(BACKFILL_MIGRATION); + expect(backfill).toBeGreaterThan(-1); + yield* applyMigrations(migrations.slice(0, backfill)); - return Effect.gen(function* () { - yield* reserve({ activeTunnels: 0, plan: "free", countConditions }); + const at = (minutes: number) => `2026-10-27T12:${String(minutes).padStart(2, "0")}:00.000Z`; + const cases: ReadonlyArray<{ + readonly environmentId: string; + readonly counted: boolean; + readonly allocation: { + readonly tunnelId?: string; + readonly releasedAt?: number; + readonly updatedAt: number; + }; + readonly link?: { + readonly revoked?: boolean; + readonly publishOnly?: boolean; + readonly updatedAt: number; + }; + }> = [ + { environmentId: "pending", counted: true, allocation: { updatedAt: 50 } }, + { environmentId: "abandoned-reservation", counted: false, allocation: { updatedAt: 10 } }, + { + environmentId: "live", + counted: true, + allocation: { tunnelId: "t", updatedAt: 10 }, + link: { updatedAt: 12 }, + }, + { + environmentId: "released", + counted: false, + allocation: { tunnelId: "t", releasedAt: 20, updatedAt: 20 }, + }, + { + environmentId: "re-reserved-after-release", + counted: true, + allocation: { tunnelId: "t", releasedAt: 20, updatedAt: 50 }, + }, + { + environmentId: "revoked", + counted: false, + allocation: { tunnelId: "t", updatedAt: 10 }, + link: { revoked: true, updatedAt: 20 }, + }, + { + environmentId: "revoked-pending", + counted: false, + allocation: { updatedAt: 50 }, + link: { revoked: true, updatedAt: 55 }, + }, + { + environmentId: "publish-only", + counted: false, + allocation: { tunnelId: "t", updatedAt: 10 }, + link: { publishOnly: true, updatedAt: 20 }, + }, + // Reprovisioned after a revoke, but the Worker died before rewriting the link. + { + environmentId: "reprovision-before-link", + counted: true, + allocation: { tunnelId: "t", updatedAt: 20 }, + link: { revoked: true, updatedAt: 10 }, + }, + { + environmentId: "reserved-before-link-rewrite", + counted: true, + allocation: { updatedAt: 50 }, + link: { revoked: true, updatedAt: 48 }, + }, + // Tunnel deleted but the row survived; deprovision marked it released, then a relink stalled. + { + environmentId: "released-after-failed-removal-then-reserved", + counted: false, + allocation: { tunnelId: "t", releasedAt: 20, updatedAt: 30 }, + link: { revoked: true, updatedAt: 15 }, + }, + { + environmentId: "withdrawn-at-provisioning-write", + counted: false, + allocation: { tunnelId: "t", updatedAt: 20 }, + link: { revoked: true, updatedAt: 20 }, + }, + { environmentId: "self", counted: false, allocation: { tunnelId: "t", updatedAt: 10 } }, + ]; + // Written before the deploy: claimDeprovision bumped updatedAt past the revoke, then cleanup failed. + const legacyCases: typeof cases = [ + { + environmentId: "legacy-failed-deprovision", + counted: false, + allocation: { tunnelId: "t", updatedAt: 30 }, + link: { revoked: true, updatedAt: 20 }, + }, + { + environmentId: "legacy-failed-publish-only-deprovision", + counted: false, + allocation: { tunnelId: "t", updatedAt: 30 }, + link: { publishOnly: true, updatedAt: 20 }, + }, + { + environmentId: "legacy-live", + counted: true, + allocation: { tunnelId: "t", updatedAt: 30 }, + link: { updatedAt: 20 }, + }, + ]; + const insert = (entries: typeof cases) => + Effect.forEach(entries, (entry) => + Effect.promise(async () => { + await pg.query( + `insert into relay_managed_endpoint_allocations + (user_id, environment_id, hostname, tunnel_id, tunnel_name, tunnel_released_at, created_at, updated_at) + values ('user-1', $1::text, $1::text, $2, $1::text, $3, $4, $4)`, + [ + entry.environmentId, + entry.allocation.tunnelId ?? null, + entry.allocation.releasedAt === undefined ? null : at(entry.allocation.releasedAt), + at(entry.allocation.updatedAt), + ], + ); + const link = entry.link; + if (link !== undefined) { + await pg.query( + `insert into relay_environment_links + (user_id, environment_id, environment_public_key, endpoint_http_base_url, + endpoint_ws_base_url, endpoint_provider_kind, revoked_at, managed_tunnels_enabled, + created_at, updated_at) + values ('user-1', $1, 'key', 'https://e', 'wss://e', 'cloudflare_tunnel', $2, $3, $4, $4)`, + [ + entry.environmentId, + link.revoked === true ? at(link.updatedAt) : null, + link.publishOnly !== true, + at(link.updatedAt), + ], + ); + } + }), + ); + yield* insert(legacyCases); + yield* applyMigrations(migrations.slice(backfill)); + yield* insert(cases); + yield* Effect.promise(() => + pg.query( + `insert into relay_managed_endpoint_allocations + (user_id, environment_id, hostname, tunnel_id, tunnel_name, created_at, updated_at) + values ('user-2', 'other-user', 'other-user', 't', 'other-user', $1, $1)`, + [at(10)], + ), + ); - expect(countConditions).toHaveLength(1); - const query = new PgDialect().sqlToQuery(countConditions[0] as never); - // claimRelease writes updatedAt = tunnelReleasedAt; a later reserve moves updatedAt past it. - expect(query.sql).toContain( - '"relay_managed_endpoint_allocations"."updated_at" > "relay_managed_endpoint_allocations"."tunnel_released_at"', + const counted = yield* Effect.promise(() => + drizzle({ client: pg }) + .select({ environmentId: relayManagedEndpointAllocations.environmentId }) + .from(relayManagedEndpointAllocations) + .where( + ManagedTunnelLimits.countedAllocations({ + userId: "user-1", + environmentId: "self", + pendingCutoff: at(45), + environment: ne, + }), + ), ); - // A link revoked or made publish-only after the last reservation no longer holds a slot. - expect(query.sql).toContain( - '"relay_environment_links"."updated_at" >= "relay_managed_endpoint_allocations"."updated_at"', + + expect(counted.map((row) => row.environmentId).toSorted()).toEqual( + [...legacyCases, ...cases] + .filter((entry) => entry.counted) + .map((entry) => entry.environmentId) + .toSorted(), ); - }); - }); + }).pipe(Effect.provide(NodeServices.layer)), + ); it.effect("does not ask T3 Chat while the account is under its cap", () => Effect.gen(function* () { diff --git a/infra/relay/src/environments/ManagedTunnelLimits.ts b/infra/relay/src/environments/ManagedTunnelLimits.ts index e06bd883a2351..93aea073c71d3 100644 --- a/infra/relay/src/environments/ManagedTunnelLimits.ts +++ b/infra/relay/src/environments/ManagedTunnelLimits.ts @@ -47,6 +47,58 @@ export class ManagedTunnelLimitExceeded extends Schema.TaggedError + exists( + new QueryBuilder() + .select({ userId: relayEnvironmentLinks.userId }) + .from(relayEnvironmentLinks) + .where( + and( + eq(relayEnvironmentLinks.userId, allocation.userId), + eq(relayEnvironmentLinks.environmentId, allocation.environmentId), + or( + isNotNull(relayEnvironmentLinks.revokedAt), + eq(relayEnvironmentLinks.managedTunnelsEnabled, false), + ), + gte(relayEnvironmentLinks.updatedAt, since), + ), + ), + ); + +// Counts allocations, not links: a link is written only after its tunnel exists. +// `environment` is `ne` for the user's other environments or `eq` for this one, which relinks without counting itself. +// updatedAt moves only on provisioning writes and release, never on teardown claims, so a link +// withdrawn at or after it means cleanup is owed; an older withdrawal means a relink that never finished. +export const countedAllocations = (input: { + readonly userId: string; + readonly environmentId: string; + readonly pendingCutoff: string; + readonly environment: typeof eq; +}) => + and( + eq(allocation.userId, input.userId), + input.environment(allocation.environmentId, input.environmentId), + or( + // Reserved but not yet holding a tunnel. Release writes updatedAt = tunnelReleasedAt and + // a relink reserves before rewriting its link, so only a newer reservation counts here. + and( + gt(allocation.updatedAt, input.pendingCutoff), + or( + isNull(allocation.tunnelReleasedAt), + gt(allocation.updatedAt, allocation.tunnelReleasedAt), + ), + not(withdrawnLink(allocation.updatedAt)), + ), + and( + isNotNull(allocation.tunnelId), + isNull(allocation.tunnelReleasedAt), + not(withdrawnLink(allocation.updatedAt)), + ), + ), + ); + export class ManagedTunnelLimits extends Context.Service< ManagedTunnelLimits, { @@ -119,53 +171,11 @@ const make = Effect.gen(function* () { minutes: MANAGED_TUNNEL_PENDING_WINDOW_MINUTES, }), ); - // Counts allocations, not links: a link is written only after its tunnel exists. - // Excludes this environment so relinking at the limit stays idempotent. - const allocation = relayManagedEndpointAllocations; - const withdrawnLink = (since?: typeof allocation.updatedAt) => - exists( - new QueryBuilder() - .select({ userId: relayEnvironmentLinks.userId }) - .from(relayEnvironmentLinks) - .where( - and( - eq(relayEnvironmentLinks.userId, allocation.userId), - eq(relayEnvironmentLinks.environmentId, allocation.environmentId), - or( - isNotNull(relayEnvironmentLinks.revokedAt), - eq(relayEnvironmentLinks.managedTunnelsEnabled, false), - ), - since === undefined ? undefined : gte(relayEnvironmentLinks.updatedAt, since), - ), - ), - ); const countSlots = (environment: typeof eq) => db .select({ slots: count() }) .from(allocation) - .where( - and( - eq(allocation.userId, input.userId), - environment(allocation.environmentId, input.environmentId), - or( - // Reserved but not yet holding a tunnel. Release writes updatedAt = tunnelReleasedAt and - // a relink reserves before rewriting its link, so only a newer reservation counts here. - and( - gt(allocation.updatedAt, pendingCutoff), - or( - isNull(allocation.tunnelReleasedAt), - gt(allocation.updatedAt, allocation.tunnelReleasedAt), - ), - not(withdrawnLink(allocation.updatedAt)), - ), - and( - isNotNull(allocation.tunnelId), - isNull(allocation.tunnelReleasedAt), - not(withdrawnLink()), - ), - ), - ), - ) + .where(countedAllocations({ ...input, pendingCutoff, environment })) .pipe( Effect.map((rows) => rows[0]?.slots ?? 0), Effect.mapError( diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5889ab5607c79..6bdece6bd1839 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1351,6 +1351,9 @@ importers: '@effect/vitest': specifier: 4.0.5 version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + '@electric-sql/pglite': + specifier: 0.3.15 + version: 0.3.15 '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -13567,8 +13570,7 @@ snapshots: - vue-tsc - yaml - '@electric-sql/pglite@0.3.15': - optional: true + '@electric-sql/pglite@0.3.15': {} '@electron-internal/extract-zip@1.0.5': {} From cadbdafc063e562626843aaea64553f791c890b4 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Wed, 28 Oct 2026 00:38:33 -0700 Subject: [PATCH 196/817] test(web): attachment preview tests wait long enough for cold workers and fonts (#26342) Co-authored-by: Claude Opus 5.5 --- .../AttachmentFilePreview.browser.test.tsx | 29 ++++++++++++------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx index 5fd8b05505282..9879edfeedbd8 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx @@ -2154,8 +2154,10 @@ it("refreshes authorization and retries a failed streamed attachment", async () asset={{ environmentId: EnvironmentId.make("test"), attachmentId: "retry" }} />, ); - await vi.waitFor(() => - expect(screen.container.textContent).toContain("This file contains binary data."), + // A cold large-text worker can take longer than waitFor's default to boot on CI. + await vi.waitFor( + () => expect(screen.container.textContent).toContain("This file contains binary data."), + { timeout: 10_000 }, ); await act(() => screen.container.querySelector('[role="alert"] button')!.click(), @@ -2217,7 +2219,10 @@ it("copies every indexed line rather than the mounted preview rows", async () => , ); await vi.waitFor(() => expect(screen.container.textContent).toContain("line-0")); - await vi.waitFor(async () => expect(await copyContents.current!()).toBe(text)); + // Copy rejects until the worker finishes indexing, which a cold worker can delay past waitFor's default on CI. + await vi.waitFor(async () => expect(await copyContents.current!()).toBe(text), { + timeout: 10_000, + }); const first = copyContents.current!(); await expect(copyContents.current!()).rejects.toThrow("Another copy is in progress."); expect(await first).toBe(text); @@ -2284,8 +2289,6 @@ it("loads a font attachment through the lazy preview", async () => { const { default: fontUrl } = await import("../../../node_modules/@betteroffice/fonts/assets/Carlito-Regular.ttf?url"); const file = await (await fetch(fontUrl)).blob(); - // Both lazy chunks can take longer than waitFor allows to load cold on CI. - await Promise.all([import("./FontFilePreview"), import("./FontViewer")]); await using screen = await render( { file={file} />, ); - await vi.waitFor(() => { - const frame = screen.container.querySelector("iframe"); - expect(frame?.title).toBe("Carlito.ttf"); - expect(frame?.srcdoc).toContain("@font-face"); - expect(frame?.srcdoc).toContain("The quick brown fox"); - }); + // Two cold lazy chunks plus decoding a 600 KB font can take longer than waitFor's default on CI. + await vi.waitFor( + () => { + const frame = screen.container.querySelector("iframe"); + expect(frame?.title).toBe("Carlito.ttf"); + expect(frame?.srcdoc).toContain("@font-face"); + expect(frame?.srcdoc).toContain("The quick brown fox"); + }, + { timeout: 10_000 }, + ); expect(screen.container.querySelector('[role="alert"]')).toBeNull(); }); From 2349c81afc1ce5de71fdb50f488f395f0307e4a2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 28 Oct 2026 00:39:19 -0700 Subject: [PATCH 197/817] refactor(mobile): app link parsing reads top to bottom with pipe (#26330) Co-authored-by: Claude Opus 5.5 --- apps/mobile/src/App.tsx | 37 ++++++++++-- apps/mobile/src/lib/appLinkState.test.ts | 72 ------------------------ apps/mobile/src/lib/appLinkState.ts | 27 --------- 3 files changed, 32 insertions(+), 104 deletions(-) delete mode 100644 apps/mobile/src/lib/appLinkState.test.ts delete mode 100644 apps/mobile/src/lib/appLinkState.ts diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsx index 78299a2aa480c..225496bb7a407 100644 --- a/apps/mobile/src/App.tsx +++ b/apps/mobile/src/App.tsx @@ -13,9 +13,11 @@ import { createPathConfigForStaticNavigation, createStaticNavigation, getActionFromState, + getStateFromPath, type NavigationAction, type NavigationState, } from "@react-navigation/native"; +import { pipe } from "effect/Function"; import { RegistryContext } from "@effect/atom-react"; import { ProjectChipIconRasterizer } from "./native/ProjectChipIconImages"; @@ -48,12 +50,22 @@ import { subscribeComposerDraftModelReconciliation } from "./state/use-composer- import { environmentThreadShells } from "./state/threads"; import { environmentShell } from "./state/shell"; import { OverlayPortalHost } from "./components/ui/OverlayPortal"; -import { shouldHandleAppLink } from "./lib/appLinking"; +import { shouldHandleAppLink, restoreDraftLinkState } from "./lib/appLinking"; import { hasCloudPublicConfig } from "./features/cloud/publicConfig"; -import { pairingFormLinkAction } from "./features/connection/devAutoConnect"; -import { resolvePendingNewTaskPromptLink } from "./features/prompt-links/newTaskPromptLink"; -import { resolvePendingThreadPromptLink } from "./features/prompt-links/threadPromptLink"; -import { getAppStateFromPath } from "./lib/appLinkState"; +import { takeScheduledTaskNewLink } from "./features/settings/scheduled-task-editor-state"; +import { + pairingFormLinkAction, + startDevAutoConnect, + withoutPairingTarget, +} from "./features/connection/devAutoConnect"; +import { + resolvePendingNewTaskPromptLink, + takeNewTaskPromptLink, +} from "./features/prompt-links/newTaskPromptLink"; +import { + resolvePendingThreadPromptLink, + takeThreadPromptLink, +} from "./features/prompt-links/threadPromptLink"; import { disposeOnFoundationReplace, type FoundationHotModule, @@ -63,10 +75,12 @@ import { installUiRuntimeMemoryWarningGc } from "./lib/useUiRuntimeMemoryWarning import { SubscriptionUsageCoordinator } from "./widgets/SubscriptionUsageCoordinator"; import { installSubscriptionUsageRefresh } from "./widgets/useSubscriptionUsage"; import { GlobalVoiceInputControl } from "./features/voice-input/GlobalVoiceInputControl"; +import { restoreSettingsLinkState } from "./features/settings/settings-navigation"; import { hydrateWorkspaceSelections, launchWorkspaceURL, recordWorkspaceSelections, + settingsLinkPage, } from "./features/workspace/workspace-selection-store"; import { workspaceDetailLinkAction } from "./features/workspace/workspace-detail-selection"; import { NativeLayoutMetricsProvider } from "./native/native-layout-metrics"; @@ -94,6 +108,19 @@ const linkingConfig = { screens: createPathConfigForStaticNavigation(RootStack, { initialRouteName: "Home" }) ?? {}, } as const; +function getAppStateFromPath(path: string, options: Parameters[1]) { + return pipe( + getStateFromPath(path, options), + (state) => restoreDraftLinkState(state, path), + (state) => restoreSettingsLinkState(state, settingsLinkPage()), + takeThreadPromptLink, + takeNewTaskPromptLink, + withoutPairingTarget, + startDevAutoConnect, + takeScheduledTaskNewLink, + ); +} + const appLinking = { prefixes: [Linking.createURL("/"), "t3code://", "t3code-dev://", "t3code-preview://"], config: { initialRouteName: "Home" }, diff --git a/apps/mobile/src/lib/appLinkState.test.ts b/apps/mobile/src/lib/appLinkState.test.ts deleted file mode 100644 index 9b907df800597..0000000000000 --- a/apps/mobile/src/lib/appLinkState.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import * as NodeModule from "node:module"; -import { expect, it, vi } from "vite-plus/test"; - -const harness = vi.hoisted(() => { - vi.stubGlobal("__DEV__", true); - return { pair: vi.fn() }; -}); - -// The native package pulls in React Native; its link parsing and actions live in core and routers. -vi.mock("@react-navigation/native", () => { - const requireFromNative = NodeModule.createRequire( - NodeModule.createRequire(import.meta.url).resolve("@react-navigation/native/package.json"), - ); - const requireFromCore = NodeModule.createRequire( - requireFromNative.resolve("@react-navigation/core/package.json"), - ); - const { getStateFromPath } = requireFromNative("@react-navigation/core"); - const { CommonActions, StackActions } = requireFromCore("@react-navigation/routers"); - return { getStateFromPath, CommonActions, StackActions }; -}); - -vi.mock("./rootNavigation", () => ({ - rootNavigationRef: { isReady: () => false }, - whenRootNavigationReady: () => {}, -})); -vi.mock("../components/ui/Dialog", () => ({ alert: () => {} })); -vi.mock("../features/prompt-links/prompt-link-actions", () => ({})); -// Stores the prompt-link steps read only when a link carries a prompt; they load the native runtime. -vi.mock("../state/projects", () => ({})); -vi.mock("../state/pull-requests", () => ({})); -vi.mock("../state/server", () => ({})); -vi.mock("../state/threads", () => ({})); -vi.mock("../state/use-composer-drafts", () => ({})); -vi.mock("../state/workspace", () => ({})); -vi.mock("../state/use-remote-environment-registry", () => ({ pairEnvironment: harness.pair })); -vi.mock("../features/workspace/workspace-selection-store", () => ({ - settingsLinkPage: () => undefined, - workspaceHasColumns: () => false, -})); - -import { findLinkedRoute } from "./appLinking"; -import { getAppStateFromPath } from "./appLinkState"; - -const PAIRING_URL = "http://192.168.1.10:3773/pair#token=abc"; - -// RootStack imports every screen, which Node cannot load; these are its paths for the pairing form. -const linking = { - initialRouteName: "Home", - screens: { - Home: "", - Settings: "settings", - SettingsEnvironmentNew: "settings/environment-new", - ConnectionsNew: "connections/new", - }, -}; - -it("a link cannot aim a pairing at a saved environment", () => { - harness.pair.mockResolvedValue({ ok: false, error: null }); - for (const path of ["connections/new", "settings/environment-new"]) { - harness.pair.mockClear(); - const state = getAppStateFromPath( - `${path}?routeFor=victim&pairingUrl=${encodeURIComponent(PAIRING_URL)}&autoConnect=1`, - linking, - ); - - expect(findLinkedRoute(state, ["ConnectionsNew", "SettingsEnvironmentNew"])?.params).toEqual({ - pairingUrl: PAIRING_URL, - autoConnect: "1", - }); - expect(harness.pair).toHaveBeenCalledExactlyOnceWith(PAIRING_URL); - } -}); diff --git a/apps/mobile/src/lib/appLinkState.ts b/apps/mobile/src/lib/appLinkState.ts deleted file mode 100644 index f404819f68f89..0000000000000 --- a/apps/mobile/src/lib/appLinkState.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { getStateFromPath } from "@react-navigation/native"; - -import { startDevAutoConnect, withoutPairingTarget } from "../features/connection/devAutoConnect"; -import { takeNewTaskPromptLink } from "../features/prompt-links/newTaskPromptLink"; -import { takeThreadPromptLink } from "../features/prompt-links/threadPromptLink"; -import { takeScheduledTaskNewLink } from "../features/settings/scheduled-task-editor-state"; -import { restoreSettingsLinkState } from "../features/settings/settings-navigation"; -import { settingsLinkPage } from "../features/workspace/workspace-selection-store"; -import { restoreDraftLinkState } from "./appLinking"; - -/** Parses an app link into navigation state, taking each link-owned side effect on the way. */ -export function getAppStateFromPath(path: string, options: Parameters[1]) { - return takeScheduledTaskNewLink( - startDevAutoConnect( - withoutPairingTarget( - takeNewTaskPromptLink( - takeThreadPromptLink( - restoreSettingsLinkState( - restoreDraftLinkState(getStateFromPath(path, options), path), - settingsLinkPage(), - ), - ), - ), - ), - ), - ); -} From ce66aab13fabde01b82deac4b4b3eaae53641988 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Wed, 28 Oct 2026 00:40:10 -0700 Subject: [PATCH 198/817] ci(release): Windows CLI builds retry the Node.js download (#26345) Co-authored-by: Claude Opus 5.5 --- .github/workflows/release-desktop.yml | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml index ca418467f6b9c..3383bb0e80bb8 100644 --- a/.github/workflows/release-desktop.yml +++ b/.github/workflows/release-desktop.yml @@ -254,6 +254,24 @@ jobs: if [[ "${{ inputs.version }}" =~ -nightly\.[0-9]{8}\.[0-9]+$ ]]; then brand=nightly; fi node scripts/apply-web-brand-assets.ts "$brand" apps/server/dist/client + # tsdown downloads the target Node with one fetch and no retry, and + # nodejs.org drops that download often enough to fail releases. Seed + # tsdown's cache with a retried, checksum-verified copy instead. + - name: Download target Node.js for the CLI executable + if: inputs.cli_archive && inputs.platform == 'win' + shell: bash + run: | + set -euo pipefail + version="$(node -p 'require("./package.json").engines.node')" + name="node-v$version-win-${{ inputs.arch }}" + dest="${XDG_CACHE_HOME:-$HOME/.cache}/tsdown/node/v$version/win-${{ inputs.arch }}" + dir="$RUNNER_TEMP/node-download" + mkdir -p "$dir" "$dest" + curl -fsSL --retry 5 --retry-all-errors -o "$dir/$name.zip" "https://nodejs.org/dist/v$version/$name.zip" + curl -fsSL --retry 5 --retry-all-errors -o "$dir/SHASUMS256.txt" "https://nodejs.org/dist/v$version/SHASUMS256.txt" + (cd "$dir" && grep " $name.zip\$" SHASUMS256.txt | sha256sum -c -) + unzip -p "$dir/$name.zip" "$name/node.exe" > "$dest/node.exe" + # Setup Vite+ selects the exact engines.node version from package.json. # Native builds embed that executable; cross-target builds download the # same version for their target. From 990e9e06e59c9b06317670a08ff0dca5859cb7d8 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Wed, 28 Oct 2026 02:41:07 -0500 Subject: [PATCH 199/817] fix(web): preserve handoffs before superseded attempt folds (#26333) --- .../components/chat/MessagesTimeline.logic.test.ts | 11 +++++++++++ .../web/src/components/chat/MessagesTimeline.logic.ts | 1 + 2 files changed, 12 insertions(+) diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index dfc9c31fb3a7d..aa082a268667d 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -2642,6 +2642,15 @@ describe("v2 run and attempt history", () => { completedAt: null, }; const timelineEntries = [ + { + id: "context-handoff-entry", + kind: "event" as const, + createdAt: "2026-01-01T00:00:00Z", + attempt: supersededAttempt, + projectedItem: { + item: { type: "handoff", runId }, + } as never, + }, { id: "initial-user-entry", kind: "message" as const, @@ -2744,6 +2753,7 @@ describe("v2 run and attempt history", () => { const collapsedRows = deriveMessagesTimelineRows(common); expect(collapsedRows.map((row) => row.id)).toEqual([ + "context-handoff-entry", "initial-user-entry", `attempt-fold:${supersededAttemptId}`, "superseded-thread-created-entry", @@ -2762,6 +2772,7 @@ describe("v2 run and attempt history", () => { expandedAttemptIds: new Set([supersededAttemptId]), }); expect(expandedRows.map((row) => row.id)).toEqual([ + "context-handoff-entry", "initial-user-entry", `attempt-fold:${supersededAttemptId}`, "superseded-assistant-entry", diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index f771c1ed0d072..ac9db2f7dd794 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -770,6 +770,7 @@ function deriveSupersededAttemptFolds( completeAttemptIds.has(entry.attempt.id) || unfoldedRunIds.has(entry.attempt.runId) || (entry.kind === "message" && entry.message.role === "user") || + (entry.kind === "event" && entry.projectedItem.item.type === "handoff") || entry.kind === "html-render" || entry.kind === "mcp-app" || timelineEntryIsPersistentResourceCard(entry) || From 441a4ebd65543fa414797253eb31cc02f8811e32 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Wed, 28 Oct 2026 02:42:27 -0500 Subject: [PATCH 200/817] feat(web): open tool call diffs in the diff panel (#26304) --- .../Adapters/AcpAdapterV2.test.ts | 20 ++- .../orchestration-v2/WireProjection.test.ts | 9 + .../src/orchestration-v2/WireProjection.ts | 14 +- apps/web/src/components/ChatView.tsx | 2 + apps/web/src/components/DiffPanel.tsx | 157 +++++++++++++----- .../src/components/chat/MessagesTimeline.tsx | 4 + .../components/chat/TimelineWorkEntryRow.tsx | 2 +- .../src/components/chat/V2ItemInspector.tsx | 15 +- .../src/components/chat/timelineRowContext.ts | 2 + .../components/chat/useRightPanelActions.ts | 11 ++ apps/web/src/diffPanelStore.test.ts | 76 ++++++++- apps/web/src/diffPanelStore.ts | 31 +++- apps/web/src/lib/toolCallDiff.test.ts | 132 +++++++++++++++ apps/web/src/lib/toolCallDiff.ts | 77 +++++++++ packages/provider-acp/src/server/adapter.ts | 19 ++- 15 files changed, 520 insertions(+), 51 deletions(-) create mode 100644 apps/web/src/lib/toolCallDiff.test.ts create mode 100644 apps/web/src/lib/toolCallDiff.ts diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 92eb5b1047ff8..f05ace7ff750d 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -111,7 +111,25 @@ const ACP_TEST_DRIVER = ProviderDriverKind.make("acp-test"); const decodeUnknownJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown)); describe("acpToolCallDiffPatch", () => { - it("builds a patch per file from ACP v1 oldText/newText, with /dev/null for a new file", () => { + it("builds per-file patches from ACP hunks and recorded old/new text", () => { + for (const operation of ["add", "delete"]) { + const text = operation === "add" ? "@@ -0,0 +1 @@\n+content\n" : "@@ -1 +0,0 @@\n-content\n"; + assert.equal( + acpToolCallDiffPatch([ + { + type: "diff", + changes: [{ operation, path: "/repo/a.ts" }], + patch: { format: "git_patch", text }, + }, + ]), + [ + 'diff --git "a//repo/a.ts" "b//repo/a.ts"', + operation === "add" ? "--- /dev/null" : '--- "a//repo/a.ts"', + operation === "delete" ? "+++ /dev/null" : '+++ "b//repo/a.ts"', + text, + ].join("\n"), + ); + } assert.equal( acpToolCallDiffPatch([ { type: "diff", path: "/repo/new.txt", oldText: null, newText: "hello\n" }, diff --git a/apps/server/src/orchestration-v2/WireProjection.test.ts b/apps/server/src/orchestration-v2/WireProjection.test.ts index baf1ea0a3cb77..d449aeb933dbf 100644 --- a/apps/server/src/orchestration-v2/WireProjection.test.ts +++ b/apps/server/src/orchestration-v2/WireProjection.test.ts @@ -275,6 +275,15 @@ describe("orchestration V2 wire projection", () => { expect(projected).not.toHaveProperty("newStr"); expect(projected).toMatchObject({ fileName: "src/main.ts", additions: 3, deletions: 1 }); expect(item.diffStr).toBe("+new code"); + expect(projectTurnItemForDetail(item)).toMatchObject({ diffStr: "+new code" }); + expect(projectTurnItemForDetail(item)).not.toHaveProperty("oldStr"); + expect(projectTurnItemForDetail(item)).not.toHaveProperty("newStr"); + const { diffStr: _diff, ...contentOnly } = item; + expect(projectTurnItemForDetail(contentOnly)).toMatchObject({ + oldStr: "old code", + newStr: "new code", + }); + expect(projectTurnItemForWire(contentOnly)).not.toHaveProperty("newStr"); const failed = projectTurnItemForWire({ ...item, status: "failed", diff --git a/apps/server/src/orchestration-v2/WireProjection.ts b/apps/server/src/orchestration-v2/WireProjection.ts index a84f8cd466859..6b66f1b91f204 100644 --- a/apps/server/src/orchestration-v2/WireProjection.ts +++ b/apps/server/src/orchestration-v2/WireProjection.ts @@ -200,8 +200,20 @@ export function projectTurnItemForDetail(item: OrchestrationV2TurnItem): Orchest result: item.result === null ? null : (truncateDetail(item.result, MAX_ON_DEMAND_BYTES) ?? null), }; - case "handoff": case "file_change": + return { + ...projectTurnItemForWire(item), + ...(item.diffStr === undefined + ? {} + : { diffStr: truncateDetail(item.diffStr, MAX_ON_DEMAND_BYTES) }), + ...(!item.diffStr?.trim() && item.oldStr !== undefined + ? { oldStr: truncateDetail(item.oldStr, MAX_ON_DEMAND_BYTES) } + : {}), + ...(!item.diffStr?.trim() && item.newStr !== undefined + ? { newStr: truncateDetail(item.newStr, MAX_ON_DEMAND_BYTES) } + : {}), + }; + case "handoff": return projectTurnItemForWire(item); default: return item; diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 4796a8465e244..c6d9cfd534b86 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -2323,6 +2323,7 @@ export default function ChatView(props: ChatViewProps) { createBrowserSurface, createBrowserSurfaceStable, moveRightPanelSurfaceStable, + onOpenToolDiffStable, onOpenTurnDiffStable, openChangesFromThreadPanelStable, openFileSurfaceStable, @@ -3309,6 +3310,7 @@ export default function ChatView(props: ChatViewProps) { routeThreadKey={displayedTimelineKey} displayThreadKey={displayedTimelineKey} announceTurnStatus={!isProviderSubagent} + onOpenToolDiff={onOpenToolDiffStable} onOpenTurnDiff={onOpenTurnDiffStable} onOpenThread={onOpenRelatedThreadStable} parentThreadLink={parentThreadLink} diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index 53af7b6e92e44..c257d0ea52d34 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -26,10 +26,12 @@ import { useOpenInPreferredEditor } from "../editorPreferences"; import { useFileContextMenuHandler } from "../fileContextMenu"; import { type DraftId } from "../composerDraftStore"; import { openDiffFilePrimaryAction } from "../diffFileActions"; -import { useCheckpointDiff } from "~/state/queries"; +import { toolCallDiff } from "../lib/toolCallDiff"; +import { useCheckpointDiff, useTurnItemDetail } from "~/state/queries"; import { revisionedQuery } from "~/state/revisionedQuery"; import { cn } from "~/lib/utils"; import { + resolveToolCallDiffTarget, selectThreadDiffPanelSelection, useDiffPanelSessionStore, useDiffPanelStore, @@ -48,7 +50,12 @@ import { import { PREFERRED_HIGHLIGHTER } from "../lib/syntaxHighlighting"; import { areAllDiffFilesCollapsed, toggleAllDiffFiles } from "../lib/diffCollapse"; import { LIVE_REFRESH_MIN_INTERVAL_MS, useLiveRefresh } from "../hooks/useLiveRefresh"; -import { useProject, useThreadCheckpointSummaries, useQuietThreadShell } from "../state/entities"; +import { + useProject, + useThreadCheckpointSummaries, + useQuietThreadShell, + useQuietThreadVisibleTurnItems, +} from "../state/entities"; import { useClientSettings, updateClientSettings } from "../hooks/useSettings"; import { formatShortTimestamp } from "../timestampFormat"; import { DiffFilePathCopyButton } from "./DiffFilePathCopyButton"; @@ -252,6 +259,18 @@ export default function DiffPanel({ const diffSelection = useDiffPanelStore((state) => selectThreadDiffPanelSelection(state.byThreadKey, routeThreadRef), ); + const toolCallSelection = diffSelection.kind === "tool-call" ? diffSelection : null; + const isGitSelection = diffSelection.kind === "branch" || diffSelection.kind === "unstaged"; + const toolCallItems = useQuietThreadVisibleTurnItems(toolCallSelection ? routeThreadRef : null); + const toolCallDetail = useTurnItemDetail( + toolCallSelection && routeThreadRef + ? { + ...resolveToolCallDiffTarget(toolCallSelection, toolCallItems), + environmentId: routeThreadRef.environmentId, + } + : null, + ); + const toolCallItem = toolCallDetail.data?.item; const isGitRepo = gitStatusQuery.data?.isRepo ?? true; const turnDiffSummaries = useThreadCheckpointSummaries(routeThreadRef); const orderedTurnDiffSummaries = turnDiffSummaries.toSorted((left, right) => { @@ -283,24 +302,31 @@ export default function DiffPanel({ orderedTurnDiffSummaries[0]); const selectedCheckpointTurnCount = selectedTurn?.checkpointTurnCount; const latestTurn = orderedTurnDiffSummaries[0]; - const selectedScopeLabel = - selectedRunId === null + const selectedScopeLabel = toolCallSelection + ? "Tool call" + : selectedRunId === null ? selectedGitScope === "unstaged" ? "Uncommitted" : "Changes" : selectedTurn?.runId === latestTurn?.runId ? "Latest turn" : `Turn ${selectedCheckpointTurnCount ?? "?"}`; - const reviewSectionId = selectedTurn ? `turn:${selectedTurn.runId}` : selectedGitScope; + const reviewSectionId = toolCallSelection + ? `tool-call:${toolCallSelection.threadId}:${toolCallSelection.itemId}` + : selectedTurn + ? `turn:${selectedTurn.runId}` + : selectedGitScope; const collapseScopeKey = routeThreadRef ? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}:${reviewSectionId}` : null; const codeViewMountKey = `${collapseScopeKey ?? reviewSectionId}:${codeViewRevision}`; - const reviewSectionTitle = selectedTurn - ? `Turn ${selectedCheckpointTurnCount ?? "?"}` - : selectedGitScope === "unstaged" - ? "Uncommitted" - : "Changes"; + const reviewSectionTitle = toolCallSelection + ? "Tool call" + : selectedTurn + ? `Turn ${selectedCheckpointTurnCount ?? "?"}` + : selectedGitScope === "unstaged" + ? "Uncommitted" + : "Changes"; const selectedCheckpointRange = typeof selectedCheckpointTurnCount === "number" ? { @@ -320,7 +346,7 @@ export default function DiffPanel({ { enabled: isGitRepo && selectedTurn !== undefined }, ); const branchDiffPreviewInput = - canReadFiles && selectedRunId === null && activeThread && activeCwd + canReadFiles && isGitSelection && activeThread && activeCwd ? { cwd: activeCwd, ...(selectedBaseRef ? { baseRef: selectedBaseRef } : {}), @@ -328,7 +354,7 @@ export default function DiffPanel({ } : undefined; const canRefreshGitDiff = - isGitRepo && selectedRunId === null && activeThread != null && activeCwd != null; + isGitRepo && isGitSelection && activeThread != null && activeCwd != null; // Read under the workspace mutation id, so each mutation refetches the diff; the panel stays // mounted while hidden, so a mutation made then is already reflected when it shows. const branchDiffPreview = useEnvironmentQuery( @@ -355,25 +381,52 @@ export default function DiffPanel({ const preview = branchDiffPreview.data; const gitDiff = selectedGitSource?.diff; - const selectedPatch = selectedTurn ? activeCheckpointDiff.data?.diff : gitDiff; - const isSelectedPatchTruncated = !selectedTurn && selectedGitSource?.truncated === true; - const selectedPatchQuery = selectedTurn ? activeCheckpointDiff : branchDiffPreview; + const toolCallPreview = + toolCallSelection && toolCallItem?.type === "file_change" ? toolCallDiff(toolCallItem) : null; + const selectedPatch = toolCallSelection + ? toolCallPreview?.patch + : selectedTurn + ? activeCheckpointDiff.data?.diff + : gitDiff; + const isSelectedPatchTruncated = + toolCallPreview?.truncated === true || + (isGitSelection && selectedGitSource?.truncated === true); + const selectedPatchQuery = toolCallSelection + ? toolCallDetail + : selectedTurn + ? activeCheckpointDiff + : branchDiffPreview; const isLoadingSelectedPatch = selectedPatchQuery.isPending && selectedPatchQuery.data === null; - const selectedPatchError = selectedTurn ? activeCheckpointDiff.error : branchDiffPreview.error; + const selectedPatchError = toolCallSelection + ? toolCallDetail.error + : selectedTurn + ? activeCheckpointDiff.error + : branchDiffPreview.error; const hasResolvedPatch = typeof selectedPatch === "string"; const hasNoNetChanges = hasResolvedPatch && selectedPatch.trim().length === 0; const lazySource = - !selectedTurn && selectedGitSource?.truncated && selectedGitSource.files + isGitSelection && selectedGitSource?.truncated && selectedGitSource.files ? selectedGitSource : null; const renderablePatch = getRenderablePatch( lazySource ? undefined : selectedPatch, `diff-panel:${resolvedTheme}`, - { compactPartialHunkOffsets: selectedRunId === null }, + { + compactPartialHunkOffsets: isGitSelection, + ...(toolCallSelection ? { ignoreWhitespace: diffIgnoreWhitespace } : {}), + }, ); + const recordedToolCallFileCount = + toolCallSelection && toolCallItem?.type === "file_change" + ? (toolCallItem.changes?.length ?? 0) + : 0; + const omittedToolCallFiles = + renderablePatch?.kind === "files" + ? Math.max(0, recordedToolCallFileCount - renderablePatch.files.length) + : 0; const fileStats = new Map(lazySource?.files?.map((file) => [file.path, file])); const sourceLineStat = - !selectedTurn && selectedGitSource?.files + isGitSelection && selectedGitSource?.files ? selectedGitSource.files.reduce( (total, file) => ({ additions: total.additions + file.additions, @@ -383,7 +436,7 @@ export default function DiffPanel({ ) : null; const currentLoadDiffFiles = - selectedRunId === null && activeThread && preview && selectedGitSource && canReadFiles + isGitSelection && activeThread && preview && selectedGitSource && canReadFiles ? createGitDiffFileContentsLoader(getDiffFileContents, { environmentId: activeThread.environmentId, cwd: preview.cwd, @@ -400,10 +453,7 @@ export default function DiffPanel({ return currentLoadDiffFiles(fileDiff); }); const localBranchRefs = useEnvironmentQuery( - selectedRunId === null && - selectedGitScope === "branch" && - activeThread && - branchDiffPreview.data?.cwd + isGitSelection && selectedGitScope === "branch" && activeThread && branchDiffPreview.data?.cwd ? vcsEnvironment.listRefs({ environmentId: activeThread.environmentId, input: { @@ -417,10 +467,7 @@ export default function DiffPanel({ : null, ); const remoteBranchRefs = useEnvironmentQuery( - selectedRunId === null && - selectedGitScope === "branch" && - activeThread && - branchDiffPreview.data?.cwd + isGitSelection && selectedGitScope === "branch" && activeThread && branchDiffPreview.data?.cwd ? vcsEnvironment.listRefs({ environmentId: activeThread.environmentId, input: { @@ -630,8 +677,9 @@ export default function DiffPanel({ useDiffPanelStore.getState().selectBranchBaseRef(routeThreadRef, baseRef); }; const selectedTurnValue = selectedTurn ? `turn:${selectedTurn.runId}` : ""; - const selectedScopeValue = - selectedRunId === null + const selectedScopeValue = toolCallSelection + ? "" + : selectedRunId === null ? selectedGitScope : selectedTurn?.runId === latestTurn?.runId ? "latest" @@ -698,7 +746,7 @@ export default function DiffPanel({ - {selectedRunId === null && selectedGitScope === "branch" && selectedGitSource?.baseRef && ( + {isGitSelection && selectedGitScope === "branch" && selectedGitSource?.baseRef && (
    - {codeViewFiles.length > 0 || (!selectedTurn && selectedGitSource?.files?.length) ? ( + {codeViewFiles.length > 0 || (isGitSelection && selectedGitSource?.files?.length) ? ( Select a thread to inspect turn diffs.
    - ) : !isGitRepo ? ( + ) : !isGitRepo && !toolCallSelection ? (
    Turn diffs are unavailable because this project is not a git repository.
    @@ -981,7 +1029,7 @@ export default function DiffPanel({
    No completed turns yet.
    - ) : selectedRunId === null && !canReadFiles ? ( + ) : isGitSelection && !canReadFiles ? ( fileAccess.isPending ? ( ) : ( @@ -995,7 +1043,13 @@ export default function DiffPanel({ {isSelectedPatchTruncated && !lazySource && (

    This preview exceeds the size limit. Changes shown are incomplete. - {selectedGitSource?.files ? " Totals include all changes." : ""} + {isGitSelection && selectedGitSource?.files ? " Totals include all changes." : ""} +

    + )} + {omittedToolCallFiles > 0 && ( +

    + This tool call changed {recordedToolCallFileCount} files. The recorded patch omits{" "} + {omittedToolCallFiles} of them.

    )} {selectedPatchError && !renderablePatch && ( @@ -1003,15 +1057,36 @@ export default function DiffPanel({

    {selectedPatchError}

    )} - {!renderablePatch && !lazySource ? ( + {!renderablePatch && toolCallPreview && toolCallPreview.content.length > 0 ? ( +
    +

    + The provider recorded file content without a diff. +

    + {toolCallPreview.content.map(({ label, text }) => ( +
    +

    {label}

    +
    +                      {text === "" ? "Empty content." : text}
    +                    
    +
    + ))} +
    + ) : !renderablePatch && !lazySource ? ( isLoadingSelectedPatch ? ( ) : ( diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index a166a25e47766..c7a38de8fbed6 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -1,3 +1,4 @@ +import type { ToolCallDiffTarget } from "../../diffPanelStore"; import { AudioPreviewUnmountContext } from "../files/AudioPreview"; import { ThreadFindTimelineContext } from "./ThreadFindProvider"; import { MarkdownFindContext } from "./markdownFindContext"; @@ -241,6 +242,7 @@ interface MessagesTimelineProps { displayThreadKey?: string; /** Off where another region already speaks the thread's status, like a subagent's bar. */ announceTurnStatus?: boolean; + onOpenToolDiff?: (target: ToolCallDiffTarget) => void; onOpenTurnDiff?: (runId: RunId, filePath?: string) => void; onOpenThread: (threadId: OrchestrationV2TurnItem["threadId"]) => void; renderHtmlRender?: TimelineRowSharedState["renderHtmlRender"]; @@ -350,6 +352,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ routeThreadKey, displayThreadKey, announceTurnStatus = true, + onOpenToolDiff, onOpenTurnDiff, onOpenThread, renderHtmlRender, @@ -1053,6 +1056,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ onAppFullscreenChange, onFileDownload, openPullRequest, + onOpenToolDiff, onOpenTurnDiff, onOpenThread, renderHtmlRender, diff --git a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx index 94d001be7e551..a8d5e3e68de77 100644 --- a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx +++ b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx @@ -536,7 +536,7 @@ function WorkEntryLogRow(props: WorkEntryRowProps) { environmentId={ctx.activeThreadEnvironmentId} cwd={ctx.markdownCwd} workspaceRoot={workspaceRoot} - onOpenTurnDiff={ctx.onOpenTurnDiff} + onOpenToolDiff={ctx.onOpenToolDiff} onImageExpand={ctx.onImageExpand} source={ctx.turnItemSource} /> diff --git a/apps/web/src/components/chat/V2ItemInspector.tsx b/apps/web/src/components/chat/V2ItemInspector.tsx index 958a56077e51a..ee6072b926b7e 100644 --- a/apps/web/src/components/chat/V2ItemInspector.tsx +++ b/apps/web/src/components/chat/V2ItemInspector.tsx @@ -1,4 +1,5 @@ -import type { EnvironmentId, OrchestrationV2ProjectedTurnItem, RunId } from "@t3tools/contracts"; +import type { ToolCallDiffTarget } from "../../diffPanelStore"; +import type { EnvironmentId, OrchestrationV2ProjectedTurnItem } from "@t3tools/contracts"; import { toolCallLines, turnItemDetailRevision, @@ -32,7 +33,7 @@ interface V2ItemInspectorProps { readonly environmentId: EnvironmentId; readonly cwd?: string | undefined; readonly workspaceRoot?: string | undefined; - readonly onOpenTurnDiff?: ((runId: RunId, filePath?: string) => void) | undefined; + readonly onOpenToolDiff?: ((target: ToolCallDiffTarget) => void) | undefined; readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined; readonly source?: TurnItemSource | undefined; } @@ -289,11 +290,17 @@ export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspec -{formatDiffCount(item.deletions ?? 0)}
    ) : null} - {item.runId !== null && props.onOpenTurnDiff ? ( + {props.onOpenToolDiff ? ( diff --git a/apps/web/src/components/chat/timelineRowContext.ts b/apps/web/src/components/chat/timelineRowContext.ts index b3677b33de76c..6334ef53bd050 100644 --- a/apps/web/src/components/chat/timelineRowContext.ts +++ b/apps/web/src/components/chat/timelineRowContext.ts @@ -1,3 +1,4 @@ +import type { ToolCallDiffTarget } from "../../diffPanelStore"; import type { ProviderApprovalDecision, RuntimeRequestId, @@ -67,6 +68,7 @@ export interface TimelineRowSharedState { findActive: boolean; onImageExpand: (preview: ExpandedImagePreview) => void; displayThreadKey?: string; + onOpenToolDiff: ((target: ToolCallDiffTarget) => void) | undefined; /** Unset where there is no diff to open, so the timeline shows no "Open diff" button. */ onOpenTurnDiff: ((runId: RunId, filePath?: string) => void) | undefined; /** diff --git a/apps/web/src/components/chat/useRightPanelActions.ts b/apps/web/src/components/chat/useRightPanelActions.ts index ac79b0853bf1f..3919df03b6af3 100644 --- a/apps/web/src/components/chat/useRightPanelActions.ts +++ b/apps/web/src/components/chat/useRightPanelActions.ts @@ -1,3 +1,4 @@ +import type { ToolCallDiffTarget } from "../../diffPanelStore"; import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; import type { ThreadPreviewState } from "../../previewStateStore"; import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions"; @@ -302,6 +303,15 @@ export function useRightPanelActions(input: RightPanelActionsInput) { useRightPanelStore.getState().open(activeThreadRef, "diff"); onDiffPanelOpen?.(); }; + const onOpenToolDiffStable = useStableCallback((target: ToolCallDiffTarget) => { + if (!isServerThread || !activeThreadRef) return; + const diffOpen = + selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, activeThreadRef) === "diff"; + explicitDiffOpenRef.current = diffOpen ? null : activeThreadRef; + useDiffPanelStore.getState().selectToolCall(activeThreadRef, target); + useRightPanelStore.getState().open(activeThreadRef, "diff"); + onDiffPanelOpen?.(); + }); const onOpenTurnDiffStable = useStableCallback(onOpenTurnDiff); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to the preview action bus to toggle the preview panel useEffect( @@ -338,6 +348,7 @@ export function useRightPanelActions(input: RightPanelActionsInput) { createBrowserSurface, createBrowserSurfaceStable, moveRightPanelSurfaceStable, + onOpenToolDiffStable, onOpenTurnDiffStable, onToggleDiffStable, openChangesFromThreadPanelStable, diff --git a/apps/web/src/diffPanelStore.test.ts b/apps/web/src/diffPanelStore.test.ts index b7238e8edf906..82065c86fe3aa 100644 --- a/apps/web/src/diffPanelStore.test.ts +++ b/apps/web/src/diffPanelStore.test.ts @@ -1,6 +1,13 @@ +import { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import { scopedThreadKey } from "@t3tools/client-runtime/environment"; import { beforeEach, describe, expect, it } from "vite-plus/test"; -import { useDiffPanelSessionStore, useDiffPanelStore } from "./diffPanelStore"; +import { + resolveToolCallDiffTarget, + useDiffPanelSessionStore, + useDiffPanelStore, +} from "./diffPanelStore"; describe("diffPanelStore", () => { beforeEach(() => { @@ -11,6 +18,73 @@ describe("diffPanelStore", () => { useDiffPanelSessionStore.setState({ collapsedFileKeysByScopeKey: {} }); }); + it("keeps a tool call selection independent of checkpoints and allows returning to Git changes", () => { + const ref = { environmentId: EnvironmentId.make("env"), threadId: ThreadId.make("thread") }; + const target = { + threadId: ThreadId.make("child"), + itemId: TurnItemId.make("edit"), + revision: "1", + }; + const store = useDiffPanelStore.getState(); + store.selectToolCall(ref, target); + store.reconcileTurnSelection(ref, []); + expect(useDiffPanelStore.getState().byThreadKey[scopedThreadKey(ref)]).toEqual({ + kind: "tool-call", + ...target, + }); + store.selectGitScope(ref, "branch"); + expect(useDiffPanelStore.getState().byThreadKey[scopedThreadKey(ref)]).toEqual({ + kind: "branch", + baseRef: null, + }); + }); + + it("refreshes a live tool-call target when its source item completes", () => { + const target = { + threadId: ThreadId.make("child"), + itemId: TurnItemId.make("edit"), + revision: "live", + }; + const now = DateTime.makeUnsafe("2026-10-28T00:00:00Z"); + const row = { + position: 0, + visibility: "local" as const, + sourceThreadId: target.threadId, + sourceItemId: target.itemId, + item: { + id: target.itemId, + threadId: target.threadId, + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 1, + status: "running" as const, + title: null, + startedAt: now, + completedAt: null, + updatedAt: now, + type: "file_change" as const, + fileName: "a.ts", + }, + }; + expect(resolveToolCallDiffTarget(target, [row])).toBe(target); + const completed = { + ...row, + item: { ...row.item, status: "completed" as const, completedAt: now }, + }; + expect(resolveToolCallDiffTarget(target, [completed])).toEqual({ + ...target, + revision: DateTime.formatIso(now), + }); + expect( + resolveToolCallDiffTarget(target, [{ ...completed, sourceThreadId: ThreadId.make("other") }]), + ).toBe(target); + expect(resolveToolCallDiffTarget(target, [])).toBe(target); + }); + it("retains fold choices when a panel consumer returns with fresh defaults", () => { const scopeKey = "environment-1:thread-1:branch"; const defaults = new Set(["src/app.ts", "src/index.ts"]); diff --git a/apps/web/src/diffPanelStore.ts b/apps/web/src/diffPanelStore.ts index eb6f0e9d455c8..11d96a3909ce7 100644 --- a/apps/web/src/diffPanelStore.ts +++ b/apps/web/src/diffPanelStore.ts @@ -1,11 +1,20 @@ +import type { ThreadStructureVisibleTurnItem } from "@t3tools/client-runtime/state/shell"; +import { turnItemDetailRevision } from "@t3tools/client-runtime/work-log/item-detail"; import { scopedThreadKey } from "@t3tools/client-runtime/environment"; -import type { RunId, ScopedThreadRef } from "@t3tools/contracts"; +import type { RunId, ScopedThreadRef, ThreadId, TurnItemId } from "@t3tools/contracts"; import { create } from "zustand"; import { createJSONStorage, persist } from "zustand/middleware"; import { resolveStorage } from "./lib/storage"; +export interface ToolCallDiffTarget { + readonly threadId: ThreadId; + readonly itemId: TurnItemId; + readonly revision: string; +} + export type DiffPanelSelection = + | ({ kind: "tool-call" } & ToolCallDiffTarget) | { kind: "branch"; baseRef: string | null } | { kind: "unstaged" } | { kind: "turn"; turnId: RunId; filePath: string | null; revealRequestId: number }; @@ -17,6 +26,7 @@ interface DiffPanelStoreState { branchBaseRefByThreadKey: Record; selectGitScope: (ref: ScopedThreadRef, scope: "branch" | "unstaged") => void; selectBranchBaseRef: (ref: ScopedThreadRef, baseRef: string | null) => void; + selectToolCall: (ref: ScopedThreadRef, target: ToolCallDiffTarget) => void; selectTurn: (ref: ScopedThreadRef, turnId: RunId, filePath?: string) => void; reconcileTurnSelection: (ref: ScopedThreadRef, availableTurnIds: ReadonlyArray) => void; removeThread: (ref: ScopedThreadRef) => void; @@ -69,6 +79,13 @@ export const useDiffPanelStore = create()( }, }; }), + selectToolCall: (ref, target) => + set((state) => ({ + byThreadKey: { + ...state.byThreadKey, + [scopedThreadKey(ref)]: { kind: "tool-call", ...target }, + }, + })), selectTurn: (ref, turnId, filePath) => set((state) => { const threadKey = scopedThreadKey(ref); @@ -160,3 +177,15 @@ export function selectThreadDiffPanelSelection( if (!ref) return DEFAULT_SELECTION; return byThreadKey[scopedThreadKey(ref)] ?? DEFAULT_SELECTION; } + +export function resolveToolCallDiffTarget( + target: ToolCallDiffTarget, + items: ReadonlyArray, +): ToolCallDiffTarget { + const row = items.find( + (row) => row.sourceThreadId === target.threadId && row.sourceItemId === target.itemId, + ); + if (row?.item.type !== "file_change") return target; + const revision = turnItemDetailRevision(row.item); + return revision === target.revision ? target : { ...target, revision }; +} diff --git a/apps/web/src/lib/toolCallDiff.test.ts b/apps/web/src/lib/toolCallDiff.test.ts new file mode 100644 index 0000000000000..cb33dd45cfb5a --- /dev/null +++ b/apps/web/src/lib/toolCallDiff.test.ts @@ -0,0 +1,132 @@ +import { describe, expect, it } from "vite-plus/test"; +import { getRenderablePatch, resolveFileDiffPath } from "./diffRendering"; +import { toolCallDiff } from "./toolCallDiff"; + +describe("toolCallDiff", () => { + it("renders recorded hunks without reading a repository, including renamed paths", () => { + for (const changes of [ + undefined, + [{ operation: "update", oldPath: "old.ts", path: "new.ts" }], + ]) { + const { patch } = toolCallDiff({ + fileName: "old.ts", + diffStr: "@@ -1 +1 @@\n-before\n+after\n", + ...(changes ? { changes } : {}), + }); + const rendered = getRenderablePatch(patch); + expect(rendered?.kind).toBe("files"); + if (rendered?.kind !== "files") throw new Error("Expected a file diff"); + expect(rendered.files).toHaveLength(1); + expect(resolveFileDiffPath(rendered.files[0]!)).toBe(changes ? "new.ts" : "old.ts"); + expect(rendered.files[0]!.additionLines.join("")).toContain("after"); + expect(rendered.files[0]!.deletionLines.join("")).toContain("before"); + } + }); + + it("renders added and deleted file contents as a file diff", () => { + for (const operation of ["add", "delete"]) { + for (const [content, ending] of [ + ["first\nsecond", ""], + ["@@ -0,0 +1 @@\n+content", "\n"], + ["@@ -1 +0,0 @@\n-content", "\n"], + ["first\nsecond", "\n"], + ["--- notes\nsecond", "\n"], + ["diff --git notes\nsecond", "\n"], + ["--- a/embedded.ts\n+++ b/embedded.ts\n@@ -1 +1 @@\n-before\n+after", "\n"], + [ + "diff --git a/embedded.ts b/embedded.ts\n--- a/embedded.ts\n+++ b/embedded.ts\n@@ -1 +1 @@\n-before\n+after", + "\n", + ], + ] as const) { + const recordedContent = `${content}${ending}`; + const rendered = getRenderablePatch( + toolCallDiff({ + fileName: "file with spaces.ts", + diffStr: recordedContent, + changes: [{ operation, path: "file with spaces.ts" }], + }).patch, + ); + expect(rendered?.kind).toBe("files"); + if (rendered?.kind !== "files") throw new Error("Expected a file diff"); + expect(resolveFileDiffPath(rendered.files[0]!)).toBe("file with spaces.ts"); + const file = rendered.files[0]!; + const lines = content.split("\n").length; + expect(file.additionLines).toHaveLength(operation === "add" ? lines : 0); + expect(file.deletionLines).toHaveLength(operation === "delete" ? lines : 0); + expect((operation === "add" ? file.additionLines : file.deletionLines).join("")).toBe( + recordedContent.replace(/\n$/, ""), + ); + } + } + }); + + it("keeps content-only writes out of the patch and preserves empty recorded content", () => { + for (const operation of ["add", "delete"]) { + expect( + toolCallDiff({ + fileName: "empty.ts", + diffStr: "", + changes: [{ operation, path: "empty.ts" }], + }).content, + ).toEqual([ + { + label: operation === "add" ? "Recorded content after" : "Recorded content before", + text: "", + }, + ]); + } + expect(toolCallDiff({ fileName: "a.ts", oldStr: "before", newStr: "" })).toEqual({ + patch: undefined, + content: [ + { label: "Recorded content before", text: "before" }, + { label: "Recorded content after", text: "" }, + ], + truncated: false, + }); + expect(toolCallDiff({ fileName: "a.ts", newStr: "after" }).content).toEqual([ + { label: "Recorded content after", text: "after" }, + ]); + }); + + it("removes transport truncation markers before converting file contents", () => { + const suffix = "\n… output truncated for transport"; + const diff = toolCallDiff({ + fileName: "a.ts", + diffStr: `first\nsecond${suffix}`, + changes: [{ operation: "add", path: "a.ts" }], + }); + expect(diff.truncated).toBe(true); + expect(diff.patch).not.toContain("output truncated"); + expect(getRenderablePatch(diff.patch)?.kind).toBe("files"); + expect(toolCallDiff({ fileName: "a.ts", newStr: `content${suffix}` })).toMatchObject({ + content: [{ label: "Recorded content after", text: "content" }], + truncated: true, + }); + }); + + it("preserves complete patches and unsupported provider output", () => { + for (const operation of ["add", "delete"]) { + const diffStr = [ + "diff --git a/a.ts b/a.ts", + `--- ${operation === "add" ? "/dev/null" : "a/a.ts"}`, + `+++ ${operation === "add" ? "b/a.ts" : "/dev/null"}`, + operation === "add" ? "@@ -0,0 +1 @@" : "@@ -1 +0,0 @@", + operation === "add" ? "+content" : "-content", + "", + ].join("\n"); + expect( + toolCallDiff({ fileName: "a.ts", diffStr, changes: [{ operation, path: "a.ts" }] }).patch, + ).toBe(diffStr); + } + for (const diffStr of [ + undefined, + "", + "provider output", + "--- a/a.ts\n+++ b/a.ts\n@@ -1 +1 @@\n-a\n+b\n", + ]) { + expect( + toolCallDiff({ fileName: "a.ts", ...(diffStr === undefined ? {} : { diffStr }) }).patch, + ).toBe(diffStr); + } + }); +}); diff --git a/apps/web/src/lib/toolCallDiff.ts b/apps/web/src/lib/toolCallDiff.ts new file mode 100644 index 0000000000000..2224702601d74 --- /dev/null +++ b/apps/web/src/lib/toolCallDiff.ts @@ -0,0 +1,77 @@ +import type { OrchestrationV2TurnItem } from "@t3tools/contracts"; +import { getRenderablePatch, resolveFileDiffPath } from "./diffRendering"; + +type FileChange = Extract; + +function toolCallPatch(item: Pick) { + let patch = item.diffStr; + if (!patch) return patch; + const change = item.changes?.[0]; + const rawFileOperation = change?.operation === "add" || change?.operation === "delete"; + if (patch.startsWith("diff --git ") || patch.startsWith("--- ")) { + if (!rawFileOperation) return patch; + const parsed = getRenderablePatch(patch, "tool-call-format"); + if ( + parsed?.kind === "files" && + parsed.files.every((file) => { + const path = resolveFileDiffPath(file).replaceAll("\\", "/"); + return ( + file.hunks.length > 0 && + item.changes?.some((recorded) => { + const recordedPath = recorded.path.replaceAll("\\", "/"); + return ( + (recorded.operation === "add" + ? file.deletionLines.length === 0 + : recorded.operation === "delete" + ? file.additionLines.length === 0 + : true) && + (recordedPath === path || recordedPath.endsWith(`/${path}`)) + ); + }) + ); + }) + ) + return patch; + } + // Codex can record added/deleted file contents or bare hunks instead of a complete patch. + if (rawFileOperation || !patch.trimStart().startsWith("@@ ")) { + if (!rawFileOperation) return patch; + const lines = patch.split("\n"); + const hasFinalNewline = patch.endsWith("\n"); + if (hasFinalNewline) lines.pop(); + const added = change.operation === "add"; + const range = `1,${lines.length}`; + patch = `@@ -${added ? "0,0" : range} +${added ? range : "0,0"} @@\n${lines.map((line) => `${added ? "+" : "-"}${line}`).join("\n")}\n${hasFinalNewline ? "" : "\\ No newline at end of file\n"}`; + } + const oldPath = change?.oldPath ?? item.fileName; + const newPath = change?.path ?? item.fileName; + const before = change?.operation === "add" ? "/dev/null" : JSON.stringify(`a/${oldPath}`); + const after = change?.operation === "delete" ? "/dev/null" : JSON.stringify(`b/${newPath}`); + return `diff --git ${JSON.stringify(`a/${oldPath}`)} ${JSON.stringify(`b/${newPath}`)}\n--- ${before}\n+++ ${after}\n${patch.trimStart()}`; +} + +function recordedText(value: string | undefined) { + const suffix = "\n… output truncated for transport"; + const truncated = value !== undefined && value.endsWith(suffix); + return { text: truncated ? value.slice(0, -suffix.length) : value, truncated }; +} + +export function toolCallDiff( + item: Pick, +) { + const diff = recordedText(item.diffStr); + const operation = item.changes?.[0]?.operation; + const emptyContent = diff.text === "" ? "" : undefined; + const before = recordedText(item.oldStr ?? (operation === "delete" ? emptyContent : undefined)); + const after = recordedText(item.newStr ?? (operation === "add" ? emptyContent : undefined)); + return { + patch: toolCallPatch({ ...item, ...(diff.text === undefined ? {} : { diffStr: diff.text }) }), + content: diff.text?.trim() + ? [] + : [ + { label: "Recorded content before", text: before.text }, + { label: "Recorded content after", text: after.text }, + ].filter((entry): entry is { label: string; text: string } => entry.text !== undefined), + truncated: diff.truncated || before.truncated || after.truncated, + }; +} diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index ead4f553fc43d..7e7f43fa632cc 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -838,7 +838,24 @@ export function acpToolCallDiffPatch(content: unknown): string | undefined { }); for (const diff of diffs) { const patch = unknownRecord(diff.patch); - if (typeof patch?.text === "string") return patch.text; + if (typeof patch?.text === "string") { + const change = + Array.isArray(diff.changes) && diff.changes.length === 1 + ? unknownRecord(diff.changes[0]) + : undefined; + if ( + patch.format === "git_patch" && + patch.text.trimStart().startsWith("@@ ") && + typeof change?.path === "string" + ) { + const oldPath = typeof change.oldPath === "string" ? change.oldPath : change.path; + const before = change.operation === "add" ? "/dev/null" : JSON.stringify(`a/${oldPath}`); + const after = + change.operation === "delete" ? "/dev/null" : JSON.stringify(`b/${change.path}`); + return `diff --git ${JSON.stringify(`a/${oldPath}`)} ${JSON.stringify(`b/${change.path}`)}\n--- ${before}\n+++ ${after}\n${patch.text.trimStart()}`; + } + return patch.text; + } } const v1Patches = diffs.flatMap((diff) => { if (typeof diff.path !== "string" || typeof diff.newText !== "string") return []; From cfc8be97d733caa089ecd26198d1be9d56669126 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Wed, 28 Oct 2026 00:51:34 -0700 Subject: [PATCH 201/817] ci: a stalled Node.js download retries after 2 minutes, not 10 (#26343) Co-authored-by: Claude Opus 5.5 --- .github/actions/setup-ci-deps/action.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/actions/setup-ci-deps/action.yml b/.github/actions/setup-ci-deps/action.yml index afaef17e1c310..e97365e2f3ec5 100644 --- a/.github/actions/setup-ci-deps/action.yml +++ b/.github/actions/setup-ci-deps/action.yml @@ -47,9 +47,14 @@ runs: echo "$HOME/.vite-plus/bin" >> "$GITHUB_PATH" "$HOME/.vite-plus/bin/vp" env use "${{ steps.vp.outputs.node }}" + # vp gives each Node.js download attempt 10 minutes by default, so one + # stalled stream holds the job that long. It retries 3 times and resumes + # partial bytes, so a shorter limit costs a slow download only a retry. - name: Setup Vite+ if: steps.vp_cache.outputs.cache-hit != 'true' uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1 + env: + VP_DOWNLOAD_TIMEOUT: "120" with: node-version-file: package.json cache: false From c3f5e363e59371d292f4a7e27008d2c5d1260725 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Wed, 28 Oct 2026 02:52:00 -0500 Subject: [PATCH 202/817] fix(server): avoid replaying stale Codex usage limits (#26331) --- .../Adapters/CodexAdapterV2.ts | 4 ++-- .../src/provider/codexUsageLimits.test.ts | 23 +++++++++++++++++++ apps/server/src/provider/codexUsageLimits.ts | 14 ++++++++++- 3 files changed, 38 insertions(+), 3 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 36702689be9e8..e372b1b9466b0 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -4304,7 +4304,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( yield* client.handleServerNotification("account/rateLimits/updated", (payload) => Effect.gen(function* () { - yield* Ref.update(rateLimitSnapshot, (previous) => + const previous = yield* Ref.getAndUpdate(rateLimitSnapshot, (previous) => mergeCodexRateLimits(previous, payload.rateLimits), ); const resetAt = codexUsageLimitResetAt(yield* Ref.get(rateLimitSnapshot)); @@ -4324,7 +4324,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( turnItem: updated, }); } - const update = codexRateLimitsToUpdate(payload.rateLimits); + const update = codexRateLimitsToUpdate(payload.rateLimits, previous); if (update && adapterOptions.onUsageLimits) { const checkedAt = DateTime.formatIso(yield* DateTime.now); yield* adapterOptions.onUsageLimits({ ...update, checkedAt }); diff --git a/apps/server/src/provider/codexUsageLimits.test.ts b/apps/server/src/provider/codexUsageLimits.test.ts index 934412bd3bb41..9c863f54c0867 100644 --- a/apps/server/src/provider/codexUsageLimits.test.ts +++ b/apps/server/src/provider/codexUsageLimits.test.ts @@ -128,6 +128,29 @@ describe("codexRateLimitsToLimits", () => { }); describe("codexRateLimitsToUpdate", () => { + it("does not republish cached windows over a newer account probe", () => { + const cached = { + primary: { usedPercent: 0, resetsAt: 1_784_000_000, windowDurationMins: 300 }, + secondary: { usedPercent: 20, resetsAt: 1_784_500_000, windowDurationMins: 10080 }, + }; + expect(codexRateLimitsToUpdate(cached)?.windows).toHaveLength(2); + expect(codexRateLimitsToUpdate(structuredClone(cached), cached)).toBeUndefined(); + + const changed = { ...cached, secondary: { ...cached.secondary, usedPercent: 21 } }; + expect(codexRateLimitsToUpdate(changed, cached)?.windows.map((window) => window.id)).toEqual([ + "secondary", + ]); + expect(codexRateLimitsToUpdate({ primary: cached.primary }, cached)).toBeUndefined(); + expect( + codexRateLimitsToUpdate({ primary: { ...cached.primary, resetsAt: 1_784_001_000 } }, cached) + ?.windows, + ).toHaveLength(1); + expect( + codexRateLimitsToUpdate({ primary: { ...cached.primary, usedPercent: 76 } }, cached) + ?.windows[0]?.usedPercent, + ).toBe(76); + }); + it("carries only the windows the notification names", () => { expect( codexRateLimitsToUpdate({ diff --git a/apps/server/src/provider/codexUsageLimits.ts b/apps/server/src/provider/codexUsageLimits.ts index f8718cdda03d9..d4f9c621119df 100644 --- a/apps/server/src/provider/codexUsageLimits.ts +++ b/apps/server/src/provider/codexUsageLimits.ts @@ -135,8 +135,20 @@ export function codexRateLimitsToLimits(input: { export function codexRateLimitsToUpdate( snapshot: CodexRateLimitSnapshot, + previous?: CodexRateLimitSnapshot, ): ProviderUsageLimitsUpdate | undefined { - const windows = codexRateLimitsToWindows(snapshot); + const previousWindows = previous ? codexRateLimitsToWindows(previous) : []; + // Token ticks repeat session-cached limits that may predate an account probe or reset. + const windows = codexRateLimitsToWindows(snapshot).filter((window) => { + const existing = previousWindows.find((candidate) => candidate.id === window.id); + return ( + !existing || + existing.kind !== window.kind || + existing.usedPercent !== window.usedPercent || + existing.resetsAt !== window.resetsAt || + existing.windowDurationMins !== window.windowDurationMins + ); + }); return windows.length > 0 ? { windows } : undefined; } From ff424802edd1560fd99fe163e678b67ec09f69b3 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Wed, 28 Oct 2026 02:56:27 -0500 Subject: [PATCH 203/817] feat(web): mark PR files viewed with shift-click (#26349) --- .../pullRequest/PullRequestCodeTab.tsx | 29 +++++++++++++++---- .../pullRequest/pullRequestDiff.logic.test.ts | 17 +++++++++++ .../pullRequest/pullRequestDiff.logic.ts | 12 ++++++++ 3 files changed, 53 insertions(+), 5 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx index f8d58cfaa020d..d1b165c62147b 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx @@ -106,6 +106,7 @@ import { toViewerSide, } from "./PullRequestReviewAnnotation"; import { + getFileViewedRange, isFileDiffCollapsed, isLineInFileDiff, toggleFileDiffFoldForViewed, @@ -175,7 +176,7 @@ interface FileViewedToggleState { readonly enabled: boolean; readonly isViewed: (path: string) => boolean; readonly isStale: (path: string) => boolean; - readonly setFileViewed: (fileKey: string, path: string, viewed: boolean) => void; + readonly setFileViewed: (fileKey: string, viewed: boolean, extendRange: boolean) => void; } // Context updates viewed toggles without invalidating memoized header portals. @@ -205,7 +206,13 @@ function FileViewedToggle({ viewedFiles.setFileViewed(fileKey, path, next === true)} + onCheckedChange={(next, details) => + viewedFiles.setFileViewed( + fileKey, + next === true, + "shiftKey" in details.event && details.event.shiftKey === true, + ) + } /> {stale ? ( @@ -287,6 +294,7 @@ function PullRequestCodeTab({ wordWrap: settings.wordWrap, })); const [toggledFiles, setToggledFiles] = useState>(() => new Set()); + const [lastViewedFileKey, setLastViewedFileKey] = useState(null); const [visibleCommitCount, setVisibleCommitCount] = useState(COMMIT_PAGE_SIZE); const [foldOverride, setFoldOverride] = useState(null); const effectiveFoldOverride = @@ -326,6 +334,7 @@ function PullRequestCodeTab({ const [stateScopeKey, setStateScopeKey] = useState(scopeKey); if (stateScopeKey !== scopeKey) { setStateScopeKey(scopeKey); + setLastViewedFileKey(null); setDraft(null); setSelectedLines(null); setToggledFiles(new Set()); @@ -689,10 +698,20 @@ function PullRequestCodeTab({ return next; }); - const setFileViewed = (fileKey: string, path: string, viewed: boolean) => { - setViewed(path, viewed); + const setFileViewed = (fileKey: string, viewed: boolean, extendRange: boolean) => { + const range = getFileViewedRange( + annotatedFiles, + fileKey, + extendRange ? lastViewedFileKey : null, + ); + setLastViewedFileKey(fileKey); + for (const file of range) setViewed(file.path, viewed); setToggledFiles((current) => - toggleFileDiffFoldForViewed(fileKey, viewed, effectiveFoldOverride, current), + range.reduce( + (next, file) => + toggleFileDiffFoldForViewed(file.fileKey, viewed, effectiveFoldOverride, next), + current, + ), ); }; const fileViewedToggle = { diff --git a/apps/web/src/components/pullRequest/pullRequestDiff.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestDiff.logic.test.ts index 4e11e04e1d784..552fa748f07f6 100644 --- a/apps/web/src/components/pullRequest/pullRequestDiff.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestDiff.logic.test.ts @@ -2,6 +2,7 @@ import type { FileDiffMetadata } from "@pierre/diffs"; import { describe, expect, it } from "vite-plus/test"; import { + getFileViewedRange, isFileDiffCollapsed, isLineInFileDiff, toggleFileDiffFoldForViewed, @@ -54,3 +55,19 @@ describe("toggleFileDiffFoldForViewed", () => { expect(toggleFileDiffFoldForViewed("a.ts", false, "expanded", new Set()).size).toBe(0); }); }); + +describe("getFileViewedRange", () => { + const files = ["c.ts", "a.ts", "b.ts", "d.ts"].map((fileKey) => ({ fileKey })); + + it("includes both endpoints in displayed order in either direction", () => { + expect(getFileViewedRange(files, "b.ts", "c.ts")).toEqual(files.slice(0, 3)); + expect(getFileViewedRange(files, "c.ts", "b.ts")).toEqual(files.slice(0, 3)); + expect(getFileViewedRange(files, "a.ts", "a.ts")).toEqual([files[1]]); + }); + + it("changes only the clicked file without a current anchor", () => { + expect(getFileViewedRange(files, "a.ts", null)).toEqual([files[1]]); + expect(getFileViewedRange(files, "a.ts", "removed.ts")).toEqual([files[1]]); + expect(getFileViewedRange(files, "removed.ts", "a.ts")).toEqual([]); + }); +}); diff --git a/apps/web/src/components/pullRequest/pullRequestDiff.logic.ts b/apps/web/src/components/pullRequest/pullRequestDiff.logic.ts index 37fbfe30e9ab4..f175c0151431a 100644 --- a/apps/web/src/components/pullRequest/pullRequestDiff.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestDiff.logic.ts @@ -39,3 +39,15 @@ export function toggleFileDiffFoldForViewed( else next.add(fileKey); return next; } + +export function getFileViewedRange( + files: ReadonlyArray, + fileKey: string, + anchorFileKey: string | null, +): ReadonlyArray { + const index = files.findIndex((file) => file.fileKey === fileKey); + if (index === -1) return []; + const anchorIndex = files.findIndex((file) => file.fileKey === anchorFileKey); + if (anchorIndex === -1) return files.slice(index, index + 1); + return files.slice(Math.min(index, anchorIndex), Math.max(index, anchorIndex) + 1); +} From 9bc4138923481dcada7f90d97ecaf0c42184bd4f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 28 Oct 2026 00:56:41 -0700 Subject: [PATCH 204/817] refactor: flatten nested call chains (#26350) Co-authored-by: Claude Opus 5.5 --- apps/desktop/src/app/DesktopAppActivation.ts | 7 +- apps/desktop/src/snapShot/DesktopSnapShot.ts | 9 +- .../connection/ConnectionDiagnosisDetails.tsx | 5 +- .../usePullRequestFilesViewed.ts | 6 +- .../pull-requests/usePullRequestList.ts | 3 +- .../settings/EnvironmentRoutesSection.tsx | 2 +- .../settings/environmentUpdateCheck.ts | 2 +- .../terminal/ThreadTerminalRouteScreen.tsx | 3 +- .../src/features/threads/LinkRequestCard.tsx | 5 +- .../features/threads/SecretRequestCard.tsx | 3 +- .../src/features/triage/useStartTriage.ts | 17 ++- apps/mobile/src/state/entities.ts | 3 +- apps/mobile/src/state/mediaActions.ts | 3 +- apps/mobile/src/state/projectClones.ts | 3 +- apps/mobile/src/state/queries.ts | 2 +- apps/mobile/src/state/query.ts | 3 +- apps/mobile/src/state/session.ts | 2 +- apps/mobile/src/state/threads.ts | 5 +- apps/mobile/src/state/usage.ts | 5 +- apps/mobile/src/state/use-composer-drafts.ts | 4 +- apps/server/scripts/fetch-expo-schema.ts | 7 +- .../scripts/record-pi-rpc-replay-fixture.ts | 9 +- apps/server/src/http.ts | 9 +- .../Adapters/CodexAdapterV2.ts | 8 +- apps/server/src/provider/CodexChatGptAuth.ts | 133 ++++++++---------- apps/server/src/provider/CodexProvider.ts | 10 +- .../Drivers/antigravityUsageReader.ts | 5 +- apps/server/src/secrets/SecretRequests.ts | 5 +- apps/server/src/ws.ts | 18 ++- .../src/browser/previewWebviewConfigState.ts | 3 +- apps/web/src/cloud/primaryCloudLinkState.ts | 3 +- apps/web/src/components/ChatView.tsx | 14 +- .../src/components/ThreadStatusIndicators.tsx | 7 +- .../src/components/chat/LinkRequestCard.tsx | 5 +- .../src/components/chat/SecretRequestCard.tsx | 3 +- .../components/chat/ThreadDetailsPrRows.tsx | 3 +- .../chat/useComposerProviderModel.ts | 14 +- .../components/device/DeviceStreamView.tsx | 3 +- .../files/extendedDocumentPreview.ts | 5 +- apps/web/src/components/files/office/fonts.ts | 5 +- .../src/components/files/office/slide-text.ts | 95 +++++++------ .../files/projectFilesQueryState.ts | 4 +- .../web/src/components/media/MediaActions.tsx | 3 +- .../components/preview/agentOpenedPreviews.ts | 3 +- .../pullRequest/filesViewedStore.ts | 3 +- .../guide/PullRequestGuideRunCoordinator.tsx | 3 +- .../components/settings/AcpRegistryIcon.tsx | 8 +- .../settings/AcpRegistrySearchStep.tsx | 3 +- .../settings/AddEnvironmentDialog.tsx | 3 +- .../settings/ConnectionDiagnosisDetails.tsx | 4 +- .../settings/ProjectDefaultsSettings.tsx | 12 +- .../settings/ScheduledTasksSettings.tsx | 19 +-- .../components/settings/SettingsPanels.tsx | 16 +-- .../settings/SettingsScopeContext.tsx | 3 +- .../settings/SourceControlWritingSettings.tsx | 16 +-- .../components/usage/UsagePriceOverrides.tsx | 3 +- apps/web/src/composerDraftStore.ts | 4 +- .../src/environments/primary/sessionState.ts | 3 +- apps/web/src/filePathDisplay.ts | 7 +- apps/web/src/hooks/useSettings.ts | 2 +- apps/web/src/hooks/useTheme.ts | 3 +- .../src/lib/assistantCitationNavigation.ts | 8 +- apps/web/src/onboarding/useProjectScans.ts | 3 +- apps/web/src/providerInstances.ts | 16 ++- apps/web/src/state/projectClones.ts | 3 +- apps/web/src/state/pullRequests.ts | 4 +- apps/web/src/state/queries.ts | 3 +- apps/web/src/state/query.ts | 2 +- apps/web/src/state/server.ts | 16 ++- apps/web/src/state/session.ts | 4 +- apps/web/src/state/shell.ts | 4 +- apps/web/src/state/sourceControlActions.ts | 16 +-- apps/web/src/state/terminalSessions.ts | 7 +- apps/web/src/state/threads.ts | 2 +- apps/web/src/state/usage.ts | 5 +- apps/web/src/state/waitForQuerySettled.ts | 3 +- apps/web/src/themePalette.ts | 14 +- .../src/relay/managedRelayState.ts | 3 +- .../src/state/archivedThreads.ts | 3 +- packages/client-runtime/src/state/assets.ts | 2 +- .../src/state/commandPermissions.ts | 2 +- .../client-runtime/src/state/connections.ts | 7 +- .../src/state/olderSettledThreads.test.ts | 2 +- .../src/state/olderSettledThreads.ts | 2 +- .../client-runtime/src/state/presentation.ts | 4 +- .../src/state/pullRequests.test.ts | 10 +- .../client-runtime/src/state/pullRequests.ts | 4 +- .../src/state/relayDiscovery.ts | 5 +- .../client-runtime/src/state/runtime.test.ts | 2 +- packages/client-runtime/src/state/runtime.ts | 9 +- packages/client-runtime/src/state/server.ts | 5 +- packages/client-runtime/src/state/session.ts | 14 +- packages/client-runtime/src/state/shell.ts | 2 +- packages/client-runtime/src/state/terminal.ts | 3 +- .../client-runtime/src/state/threadDetail.ts | 4 +- .../src/state/threadFamilies.ts | 2 +- .../client-runtime/src/state/threadSearch.ts | 2 +- .../scripts/generate.ts | 33 ++--- .../effect-codex-app-server/src/replay.ts | 7 +- .../provider-core/src/server/handoffBudget.ts | 6 +- packages/shared/src/dpop.ts | 8 +- scripts/lib/public-config.ts | 8 +- 102 files changed, 423 insertions(+), 414 deletions(-) diff --git a/apps/desktop/src/app/DesktopAppActivation.ts b/apps/desktop/src/app/DesktopAppActivation.ts index 340cb23136441..094033192e088 100644 --- a/apps/desktop/src/app/DesktopAppActivation.ts +++ b/apps/desktop/src/app/DesktopAppActivation.ts @@ -1,4 +1,5 @@ // @effect-diagnostics nodeBuiltinImport:off -- Local socket ownership checks need lstat, an atomic rename, and a directory watch at the Node adapter boundary. +import { pipe } from "effect/Function"; import * as NodeCrypto from "node:crypto"; import * as NodeFS from "node:fs"; import * as NodeFSP from "node:fs/promises"; @@ -151,8 +152,10 @@ export async function startDesktopAppControlServer(input: { } if (!isDesktopAppActivationRequest(parsed)) { - finish( - invalidResponse(requestIdFromUnknown(parsed), "The desktop app request is invalid."), + pipe( + requestIdFromUnknown(parsed), + (requestId) => invalidResponse(requestId, "The desktop app request is invalid."), + finish, ); return; } diff --git a/apps/desktop/src/snapShot/DesktopSnapShot.ts b/apps/desktop/src/snapShot/DesktopSnapShot.ts index 76daee09c2aeb..e31d347084209 100644 --- a/apps/desktop/src/snapShot/DesktopSnapShot.ts +++ b/apps/desktop/src/snapShot/DesktopSnapShot.ts @@ -1,5 +1,6 @@ // @effect-diagnostics globalTimers:off -- Capture timeouts and Electron overlay animation timers run at native callback boundaries outside Effect fibers. +import { pipe } from "effect/Function"; import { DEFAULT_CLIENT_SETTINGS, DesktopPendingSnapShot, @@ -1288,10 +1289,10 @@ export const make = Effect.gen(function* () { if (isModifierPairShortcut(shortcut)) { registered = yield* Effect.tryPromise(() => startPairShortcutProcess(snapShotShortcutModifierPair(shortcut), onCurrentShortcut, () => { - void runPromise( - setShortcutFailure( - snapShotShortcutRegistrationFailureMessage(shortcut, environment.platform), - ), + void pipe( + snapShotShortcutRegistrationFailureMessage(shortcut, environment.platform), + setShortcutFailure, + runPromise, ).catch(() => undefined); }), ).pipe( diff --git a/apps/mobile/src/features/connection/ConnectionDiagnosisDetails.tsx b/apps/mobile/src/features/connection/ConnectionDiagnosisDetails.tsx index df0e8c165929e..b3922c4a95eda 100644 --- a/apps/mobile/src/features/connection/ConnectionDiagnosisDetails.tsx +++ b/apps/mobile/src/features/connection/ConnectionDiagnosisDetails.tsx @@ -10,7 +10,6 @@ import { } from "@t3tools/client-runtime/connection"; import type { EnvironmentId } from "@t3tools/contracts"; import Constants from "expo-constants"; -import * as Option from "effect/Option"; import { AsyncResult } from "effect/reactivity"; import { Linking, View } from "react-native"; @@ -28,8 +27,8 @@ export function useConnectionDiagnosis( environmentId: EnvironmentId, presentation: EnvironmentPresentation | null, ) { - const state = Option.getOrElse( - AsyncResult.value(useAtomValue(environmentCatalog.stateAtom(environmentId))), + const state = AsyncResult.getOrElse( + useAtomValue(environmentCatalog.stateAtom(environmentId)), () => AVAILABLE_CONNECTION_STATE, ); if (presentation === null || !presentation.entry.enabled) return { diagnosis: null, state }; diff --git a/apps/mobile/src/features/pull-requests/usePullRequestFilesViewed.ts b/apps/mobile/src/features/pull-requests/usePullRequestFilesViewed.ts index 46f6f941806a7..7467c73fbe403 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestFilesViewed.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestFilesViewed.ts @@ -2,7 +2,6 @@ import { usePullRequestConnected } from "./usePullRequestConnected"; import { RegistryContext, useAtomRefresh, useAtomValue } from "@effect/atom-react"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import type { PullRequestDetail } from "@t3tools/contracts"; -import * as Option from "effect/Option"; import { AsyncResult } from "effect/reactivity"; import { use, useState } from "react"; import { composerPullRequests } from "../../state/pull-requests"; @@ -50,8 +49,9 @@ export function usePullRequestFilesViewed(params: PullRequestParams, pr: PullReq input: { ...target.input, files: [{ path, viewed }] }, }); // The read that is current once the write lands still predates it; a newer one carries it. - const readAtWrite = Option.getOrNull( - AsyncResult.value(registry.get(composerPullRequests.filesViewed(target))), + const readAtWrite = AsyncResult.getOrElse( + registry.get(composerPullRequests.filesViewed(target)), + () => null, ); setState((current) => { if (current.key !== scopeKey || current.presses[path]?.version !== version) return current; diff --git a/apps/mobile/src/features/pull-requests/usePullRequestList.ts b/apps/mobile/src/features/pull-requests/usePullRequestList.ts index a87e07b4dbff8..5bc3cf730b520 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestList.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestList.ts @@ -3,7 +3,6 @@ import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runt import type { EnvironmentId, PullRequestDiffStat, PullRequestListInput } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; -import * as Option from "effect/Option"; import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity"; import { use, useMemo, useState } from "react"; import { environmentCatalog } from "../../connection/catalog"; @@ -32,7 +31,7 @@ type Read = (atom: Atom.Atom) => A; /** The head the list query holds now, cached or answered. */ function currentHead(read: Read, target: ListTarget) { - return Option.getOrNull(AsyncResult.value(read(composerPullRequests.list(target)))); + return AsyncResult.getOrElse(read(composerPullRequests.list(target)), () => null); } function currentPages(read: Read, target: ListTarget): PullRequestListPages | null { diff --git a/apps/mobile/src/features/settings/EnvironmentRoutesSection.tsx b/apps/mobile/src/features/settings/EnvironmentRoutesSection.tsx index 632fb08c2e7b3..012d00737d1df 100644 --- a/apps/mobile/src/features/settings/EnvironmentRoutesSection.tsx +++ b/apps/mobile/src/features/settings/EnvironmentRoutesSection.tsx @@ -56,7 +56,7 @@ export function EnvironmentRoutesSection({ const entry = useAtomValue(environmentCatalog.catalogValueAtom).entries.get(environmentId); const prepared = useAtomValue(environmentSession.preparedConnectionValueAtom(environmentId)); const sessionResult = useAtomValue(environmentSession.sessionStateAtom(environmentId)); - const session = Option.getOrNull(AsyncResult.value(sessionResult)); + const session = AsyncResult.getOrElse(sessionResult, () => null); const [permissionsOpen, setPermissionsOpen] = useState(false); const reorder = useAtomCommand(environmentCatalog.reorderRoutes, "route reorder"); const removeRoute = useAtomCommand(environmentCatalog.removeRoute, "route removal"); diff --git a/apps/mobile/src/features/settings/environmentUpdateCheck.ts b/apps/mobile/src/features/settings/environmentUpdateCheck.ts index b75bc06a3949a..1bbe0c63cae5d 100644 --- a/apps/mobile/src/features/settings/environmentUpdateCheck.ts +++ b/apps/mobile/src/features/settings/environmentUpdateCheck.ts @@ -40,7 +40,7 @@ export const environmentReleaseCheckAtom = Atom.family((environmentId: Environme export function releaseCheckValue( result: AsyncResult.AsyncResult, ): EnvironmentReleaseCheck | null { - return Option.getOrNull(AsyncResult.value(result)); + return AsyncResult.getOrElse(result, () => null); } export function releaseCheckError( diff --git a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx index 2f6cc0d292a7f..a2a2450864eee 100644 --- a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx +++ b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx @@ -20,7 +20,6 @@ import { AppText as Text } from "../../components/ui/AppText"; import { TerminalContextSheet } from "./TerminalContextSheet"; import { hasNativeTerminalSurface, supportsNativeTerminalOutput } from "./nativeTerminalModule"; import * as Clipboard from "expo-clipboard"; -import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import { AsyncResult } from "effect/reactivity"; import { @@ -340,7 +339,7 @@ function readLiveTerminalSessions( ): ReadonlyArray { if (!readEnvironmentScope(environmentId, AuthTerminalReadScope)) return []; const result = appAtomRegistry.get(terminalEnvironment.metadata({ environmentId, input: null })); - const summaries = Option.getOrElse(AsyncResult.value(result), () => []); + const summaries = AsyncResult.getOrElse(result, () => []); return summaries .filter((summary) => summary.threadId === threadId) .map((summary) => ({ diff --git a/apps/mobile/src/features/threads/LinkRequestCard.tsx b/apps/mobile/src/features/threads/LinkRequestCard.tsx index 2bbb168ba5b32..ac96063001836 100644 --- a/apps/mobile/src/features/threads/LinkRequestCard.tsx +++ b/apps/mobile/src/features/threads/LinkRequestCard.tsx @@ -1,3 +1,4 @@ +import { pipe } from "effect/Function"; import { useAtomValue } from "@effect/atom-react"; import { type LinkableMachine, @@ -125,7 +126,7 @@ function PendingLinkRequest(props: { setDeclining(false), ); if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - setError(linkRequestFailureMessage(squashAtomCommandFailure(result))); + pipe(squashAtomCommandFailure(result), linkRequestFailureMessage, setError); } }; @@ -311,7 +312,7 @@ function LinkRequestSheet(props: { setPairingCode(""); props.onClose(); } else if (!isAtomCommandInterrupted(result)) { - setError(linkRequestFailureMessage(squashAtomCommandFailure(result))); + pipe(squashAtomCommandFailure(result), linkRequestFailureMessage, setError); } }; diff --git a/apps/mobile/src/features/threads/SecretRequestCard.tsx b/apps/mobile/src/features/threads/SecretRequestCard.tsx index 0112257fec713..4ab7a18beffec 100644 --- a/apps/mobile/src/features/threads/SecretRequestCard.tsx +++ b/apps/mobile/src/features/threads/SecretRequestCard.tsx @@ -1,3 +1,4 @@ +import { pipe } from "effect/Function"; import { SECRET_REQUEST_DEFAULT_PLACEHOLDER, secretRequestAnswerInput, @@ -91,7 +92,7 @@ function PendingSecretRequestForm(props: { return; } if (!isAtomCommandInterrupted(result)) { - setError(secretRequestFailureMessage(squashAtomCommandFailure(result))); + pipe(squashAtomCommandFailure(result), secretRequestFailureMessage, setError); } }; diff --git a/apps/mobile/src/features/triage/useStartTriage.ts b/apps/mobile/src/features/triage/useStartTriage.ts index 059e852337d22..eefb775bcd177 100644 --- a/apps/mobile/src/features/triage/useStartTriage.ts +++ b/apps/mobile/src/features/triage/useStartTriage.ts @@ -1,3 +1,4 @@ +import { pipe } from "effect/Function"; import { isAtomCommandInterrupted, squashAtomCommandFailure, @@ -67,11 +68,11 @@ export function useStartTriage() { const scratch = await openScratch({ environmentId, input: {} }); if (scratch._tag === "Failure") { if (!isAtomCommandInterrupted(scratch)) { - fail( - errorMessage( - squashAtomCommandFailure(scratch), - "This machine cannot start threads without a project.", - ), + pipe( + squashAtomCommandFailure(scratch), + (failure) => + errorMessage(failure, "This machine cannot start threads without a project."), + fail, ); } return; @@ -82,7 +83,11 @@ export function useStartTriage() { }); if (prepared._tag === "Failure") { if (!isAtomCommandInterrupted(prepared)) { - fail(errorMessage(squashAtomCommandFailure(prepared), "The server could not prepare it.")); + pipe( + squashAtomCommandFailure(prepared), + (failure) => errorMessage(failure, "The server could not prepare it."), + fail, + ); } return; } diff --git a/apps/mobile/src/state/entities.ts b/apps/mobile/src/state/entities.ts index c98c8a11488cf..a376938ffb41f 100644 --- a/apps/mobile/src/state/entities.ts +++ b/apps/mobile/src/state/entities.ts @@ -25,7 +25,6 @@ import { threadLinkRefs, type ThreadLink, } from "@t3tools/shared/threadLinks"; -import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import { AsyncResult, Atom } from "effect/reactivity"; @@ -117,7 +116,7 @@ const threadProjectChipIconAtom = Atom.family((key: string) => { ); if (!icon) return null; if (icon.kind === "favicon") return icon.uri; - return Option.getOrNull(AsyncResult.value(get(projectGlyphImageAtom(projectGlyphKey(icon))))); + return AsyncResult.getOrElse(get(projectGlyphImageAtom(projectGlyphKey(icon))), () => null); }).pipe(Atom.withLabel(`mobile-thread-project-chip-icon:${key}`)); }); diff --git a/apps/mobile/src/state/mediaActions.ts b/apps/mobile/src/state/mediaActions.ts index b8736d6d3c36e..22a3a9a26bb69 100644 --- a/apps/mobile/src/state/mediaActions.ts +++ b/apps/mobile/src/state/mediaActions.ts @@ -13,7 +13,6 @@ import { type SessionGrantInput, } from "@t3tools/contracts"; import { normalizeNativeMarkdownUrl } from "../lib/markdownLinks"; -import * as Option from "effect/Option"; import { AsyncResult } from "effect/reactivity"; import { useEffect, useRef, useState } from "react"; @@ -32,7 +31,7 @@ function allowsHostMedia(session: SessionGrantInput | null) { function canReadHostMedia(environmentId: EnvironmentId | null): boolean { if (environmentId === null) return true; const result = appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId)); - return result._tag !== "Failure" && allowsHostMedia(Option.getOrNull(AsyncResult.value(result))); + return result._tag !== "Failure" && allowsHostMedia(AsyncResult.getOrElse(result, () => null)); } export function useMediaActions(source: MediaActionsSource | undefined, onOpenFile?: () => void) { diff --git a/apps/mobile/src/state/projectClones.ts b/apps/mobile/src/state/projectClones.ts index 321cff9db2202..fc8176a8aff92 100644 --- a/apps/mobile/src/state/projectClones.ts +++ b/apps/mobile/src/state/projectClones.ts @@ -1,7 +1,6 @@ import { useAtomValue } from "@effect/atom-react"; import { parseScopedProjectKey, scopedProjectKey } from "@t3tools/client-runtime/environment"; import type { EnvironmentId, ProjectCloneSnapshot, ScopedProjectRef } from "@t3tools/contracts"; -import * as Option from "effect/Option"; import { AsyncResult, Atom } from "effect/reactivity"; import { serverEnvironment } from "./server"; @@ -22,7 +21,7 @@ const environmentProjectClonesAtom = Atom.family((environmentId: EnvironmentId) const result = get(sourceControlEnvironment.projectClones({ environmentId, input: {} })); // On subscription failure, let server dispatch guards decide rather than blocking Start until reconnect. if (result._tag === "Failure") return EMPTY_CLONES; - return Option.getOrElse(AsyncResult.value(result), () => "pending" as const); + return AsyncResult.getOrElse(result, () => "pending" as const); }).pipe(Atom.withLabel(`mobile-project-clones:${environmentId}`)), ); diff --git a/apps/mobile/src/state/queries.ts b/apps/mobile/src/state/queries.ts index f923314b4cb72..75e60887546d3 100644 --- a/apps/mobile/src/state/queries.ts +++ b/apps/mobile/src/state/queries.ts @@ -318,7 +318,7 @@ export function usePaginatedBranches(target: VcsRefTarget) { ); const results = useAtomValue(pagesAtom); const values = results.flatMap((result) => { - const value = Option.getOrNull(AsyncResult.value(result)); + const value = AsyncResult.getOrElse(result, () => null); return value === null ? [] : [value]; }); const refs = new Map(); diff --git a/apps/mobile/src/state/query.ts b/apps/mobile/src/state/query.ts index b5d5b6a6a1a66..8c3a75fb3bf45 100644 --- a/apps/mobile/src/state/query.ts +++ b/apps/mobile/src/state/query.ts @@ -1,6 +1,5 @@ import { useAtomRefresh, useAtomValue } from "@effect/atom-react"; import * as Cause from "effect/Cause"; -import * as Option from "effect/Option"; import { AsyncResult, Atom } from "effect/reactivity"; const EMPTY_ASYNC_RESULT_ATOM = Atom.make(AsyncResult.initial(false)).pipe( @@ -31,7 +30,7 @@ export function useEnvironmentQuery( const result = useAtomValue(selectedAtom); const refresh = useAtomRefresh(selectedAtom); return { - data: Option.getOrNull(AsyncResult.value(result)), + data: AsyncResult.getOrElse(result, () => null), // Data may be structurally shared; only a settled success proves a new response. successResult: result._tag === "Success" && !result.waiting ? result : null, failure: result._tag === "Failure" ? Cause.squash(result.cause) : null, diff --git a/apps/mobile/src/state/session.ts b/apps/mobile/src/state/session.ts index 010325dfe722a..c7fbecab5805d 100644 --- a/apps/mobile/src/state/session.ts +++ b/apps/mobile/src/state/session.ts @@ -21,7 +21,7 @@ export function sessionHasScope( result: AsyncResult.AsyncResult, scope: AuthEnvironmentScope, ): boolean { - const session = Option.getOrNull(AsyncResult.value(result)); + const session = AsyncResult.getOrElse(result, () => null); return result._tag !== "Failure" && session !== null && sessionGrantsScope(session, scope); } diff --git a/apps/mobile/src/state/threads.ts b/apps/mobile/src/state/threads.ts index 28cb2f88c0d61..4cb0f92b4ee83 100644 --- a/apps/mobile/src/state/threads.ts +++ b/apps/mobile/src/state/threads.ts @@ -10,7 +10,6 @@ import { createThreadFamilyAtoms, } from "@t3tools/client-runtime/state/threads"; import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; -import * as Option from "effect/Option"; import { AsyncResult, Atom } from "effect/reactivity"; import { useEffect } from "react"; @@ -94,8 +93,8 @@ export function useEnvironmentThread( ? environmentThreads.stateAtom(environmentId, threadId) : EMPTY_THREAD_STATE_ATOM, ); - const state = Option.getOrElse( - AsyncResult.value(result), + const state = AsyncResult.getOrElse( + result, () => EMPTY_ENVIRONMENT_THREAD_STATE, ) as EnvironmentThreadState; return state; diff --git a/apps/mobile/src/state/usage.ts b/apps/mobile/src/state/usage.ts index b0931e175c558..9851b841c88c5 100644 --- a/apps/mobile/src/state/usage.ts +++ b/apps/mobile/src/state/usage.ts @@ -9,7 +9,6 @@ import { import { needsCursorKeychainAccess, refreshUsage } from "@t3tools/client-runtime/state/usage"; import { resolveUsageAccess } from "@t3tools/client-runtime/state/usage-access"; import { mergeUsage, type EnvironmentUsage, type MergedUsage } from "@t3tools/shared/usageMerge"; -import * as Option from "effect/Option"; import { AsyncResult, Atom } from "effect/reactivity"; import { useCallback, useMemo } from "react"; @@ -39,7 +38,7 @@ const usageByWindowAtom = Atom.family((windowKey: string) => const sessionResult = get(environmentSession.sessionStateAtom(environmentId)); const access = resolveUsageAccess({ connectionPhase: presentation.connection.phase, - session: Option.getOrNull(AsyncResult.value(sessionResult)), + session: AsyncResult.getOrElse(sessionResult, () => null), hasSessionError: sessionResult._tag === "Failure", }); if (!access.canReadDiagnostics) { @@ -54,7 +53,7 @@ const usageByWindowAtom = Atom.family((windowKey: string) => continue; } const result = get(serverEnvironment.usageSummary({ environmentId, input })); - const summary = Option.getOrNull(AsyncResult.value(result)); + const summary = AsyncResult.getOrElse(result, () => null); statuses.push({ environmentId, label: presentation.entry.target.label, diff --git a/apps/mobile/src/state/use-composer-drafts.ts b/apps/mobile/src/state/use-composer-drafts.ts index 8c049cd4b6180..791383be9e7a3 100644 --- a/apps/mobile/src/state/use-composer-drafts.ts +++ b/apps/mobile/src/state/use-composer-drafts.ts @@ -1517,9 +1517,7 @@ export function subscribeComposerDraftModelReconciliation(input: { if (!thread || !draftModelPickMatchesThread(draft.modelSelection, thread.modelSelection)) continue; // Status and selection must come from the same emission; derived atoms can update apart. - const shell = Option.getOrNull( - AsyncResult.value(get(input.shellStateAtom(ref.environmentId))), - ); + const shell = AsyncResult.getOrElse(get(input.shellStateAtom(ref.environmentId)), () => null); if (shell?.status !== "live") continue; const authoritativeThread = Option.getOrNull(shell.snapshot)?.threads.find( (candidate) => candidate.id === ref.threadId, diff --git a/apps/server/scripts/fetch-expo-schema.ts b/apps/server/scripts/fetch-expo-schema.ts index 9cf7c3920379f..cc41f4ffe7f98 100644 --- a/apps/server/scripts/fetch-expo-schema.ts +++ b/apps/server/scripts/fetch-expo-schema.ts @@ -4,6 +4,7 @@ * without a credential. eas-cli generates its own client from the same * endpoint. Run `vp run generate` afterwards to regenerate the operations. */ +import { pipe } from "effect/Function"; import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Effect from "effect/Effect"; @@ -36,8 +37,10 @@ const program = Effect.gen(function* () { Effect.flatMap(HttpClientResponse.schemaBodyJson(IntrospectionResponse)), ); // Sorted so a refresh diffs by what Expo changed, not by its declaration order. - const sdl = printSchema( - lexicographicSortSchema(buildClientSchema(response.data as unknown as IntrospectionQuery)), + const sdl = pipe( + buildClientSchema(response.data as unknown as IntrospectionQuery), + lexicographicSortSchema, + printSchema, ); const target = path.join(import.meta.dirname, "..", "schema", "expo.graphql"); yield* fs.makeDirectory(path.dirname(target), { recursive: true }); diff --git a/apps/server/scripts/record-pi-rpc-replay-fixture.ts b/apps/server/scripts/record-pi-rpc-replay-fixture.ts index 6e5d59cd735c7..8451074a426fc 100644 --- a/apps/server/scripts/record-pi-rpc-replay-fixture.ts +++ b/apps/server/scripts/record-pi-rpc-replay-fixture.ts @@ -1,3 +1,4 @@ +import { pipe } from "effect/Function"; import * as NodeServices from "@effect/platform-node/NodeServices"; import type { ProviderReplayEntry, ProviderReplayTranscript } from "@t3tools/contracts"; import * as Console from "effect/Console"; @@ -99,8 +100,12 @@ function normalizeEntries(input: { .replaceAll(input.workspace, "") .replaceAll(home.length > 1 ? home : "\0", "~") .replace(ISO_TIMESTAMP_PATTERN, (iso) => - DateTime.formatIso( - DateTime.makeUnsafe(shiftTime(DateTime.toEpochMillis(DateTime.makeUnsafe(iso)))), + pipe( + DateTime.makeUnsafe(iso), + DateTime.toEpochMillis, + shiftTime, + DateTime.makeUnsafe, + DateTime.formatIso, ), ) .replace(UUID_PATTERN, (uuid) => { diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index af763b73f7055..8f9737a3efc18 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -16,7 +16,7 @@ import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; -import { cast } from "effect/Function"; +import { cast, pipe } from "effect/Function"; import { HttpClient, HttpClientResponse, @@ -181,8 +181,11 @@ export const assetFileResponse = Effect.fn("assetFileResponse")(function* ( if (bytes === null) { return HttpServerResponse.text("MCP app is too large to preview.", { status: 413 }); } - const body = new TextEncoder().encode( - injectMcpAppCookieBootstrap(injectMcpAppThemeBootstrap(new TextDecoder().decode(bytes))), + const body = pipe( + new TextDecoder().decode(bytes), + injectMcpAppThemeBootstrap, + injectMcpAppCookieBootstrap, + (html) => new TextEncoder().encode(html), ); headers["Content-Length"] = String(body.byteLength); return method === "HEAD" diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index e372b1b9466b0..58cd4a0c0c17b 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -1,3 +1,4 @@ +import { pipe } from "effect/Function"; import * as DocumentText from "../../provider/DocumentText.ts"; import { revertCodexThread } from "../../provider/CodexThreadRevert.ts"; import { historyResponseItems } from "@t3tools/provider-core/server/handoffBudget"; @@ -1448,8 +1449,11 @@ function redactCodexProtocolValue(value: unknown): unknown { return value; } try { - return JSON.stringify( - redactCodexProtocolValue(boundProviderEventForLogging(JSON.parse(trimmed) as unknown)), + return pipe( + JSON.parse(trimmed) as unknown, + boundProviderEventForLogging, + redactCodexProtocolValue, + JSON.stringify, ); } catch { return value; diff --git a/apps/server/src/provider/CodexChatGptAuth.ts b/apps/server/src/provider/CodexChatGptAuth.ts index 1051f72814390..3e51b66a0e5ee 100644 --- a/apps/server/src/provider/CodexChatGptAuth.ts +++ b/apps/server/src/provider/CodexChatGptAuth.ts @@ -736,78 +736,69 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function* ), ) .pipe(Effect.map(Hex.encode), Effect.orDie); - const access = lock.withPermit( - withSessionLock( - Effect.uninterruptible( - Effect.gen(function* () { - const saved = yield* read; - if (Option.isNone(saved)) - return yield* failure("access", "Sign in with ChatGPT to use managed Codex."); - let record = saved.value; - if ( - options.expectedProfileKey !== undefined && - (yield* profileKey(record)) !== options.expectedProfileKey - ) - return yield* failure("access", "The ChatGPT connection changed. Start a new session."); - if (!record.scopes.includes(REQUIRED_SCOPE)) - return yield* failure( - "sharing", - "Token sharing is disabled. Sign in with ChatGPT and enable token sharing.", - ); - const now = yield* Clock.currentTimeMillis; - if (record.expiresAt - now > 60_000) return record; - if (record.earliestRefreshAt !== null && record.earliestRefreshAt > now) { - if (record.expiresAt > now) return record; - return yield* failure( - "refresh", - "ChatGPT cannot renew this connection yet. Try again shortly.", - ); - } - if (!record.refreshToken) { - yield* remove; - return yield* failure("refresh", "Your ChatGPT connection expired. Sign in again."); - } - const tokens = yield* exchange( - new URLSearchParams({ - grant_type: "refresh_token", - client_id: record.clientId, - refresh_token: record.refreshToken, - resource, - }), - ).pipe( - Effect.interruptible, - Effect.timeout("20 seconds"), - Effect.mapError((error) => - error._tag === "ProviderSetupError" && error.operation === "client" - ? error - : failure( - "refresh", - "Could not renew the ChatGPT connection. Retry, or sign in again.", - ), - ), - ); - if (!tokens.refresh_token || tokens.token_type.toLowerCase() !== "bearer") { - return yield* failure("refresh", "ChatGPT returned an invalid renewal. Sign in again."); - } - record = { - ...record, - accessToken: tokens.access_token, - refreshToken: tokens.refresh_token, - expiresAt: (yield* Clock.currentTimeMillis) + tokens.expires_in * 1000, - earliestRefreshAt: earliest(tokens.earliest_refresh_at), - scopes: tokens.scope.split(/\s+/).filter(Boolean), - }; - yield* save(record); - if (!record.scopes.includes(REQUIRED_SCOPE)) - return yield* failure( - "sharing", - "ChatGPT token sharing is no longer enabled. Sign in again.", - ); - return record; - }), + const access = Effect.gen(function* () { + const saved = yield* read; + if (Option.isNone(saved)) + return yield* failure("access", "Sign in with ChatGPT to use managed Codex."); + let record = saved.value; + if ( + options.expectedProfileKey !== undefined && + (yield* profileKey(record)) !== options.expectedProfileKey + ) + return yield* failure("access", "The ChatGPT connection changed. Start a new session."); + if (!record.scopes.includes(REQUIRED_SCOPE)) + return yield* failure( + "sharing", + "Token sharing is disabled. Sign in with ChatGPT and enable token sharing.", + ); + const now = yield* Clock.currentTimeMillis; + if (record.expiresAt - now > 60_000) return record; + if (record.earliestRefreshAt !== null && record.earliestRefreshAt > now) { + if (record.expiresAt > now) return record; + return yield* failure( + "refresh", + "ChatGPT cannot renew this connection yet. Try again shortly.", + ); + } + if (!record.refreshToken) { + yield* remove; + return yield* failure("refresh", "Your ChatGPT connection expired. Sign in again."); + } + const tokens = yield* exchange( + new URLSearchParams({ + grant_type: "refresh_token", + client_id: record.clientId, + refresh_token: record.refreshToken, + resource, + }), + ).pipe( + Effect.interruptible, + Effect.timeout("20 seconds"), + Effect.mapError((error) => + error._tag === "ProviderSetupError" && error.operation === "client" + ? error + : failure("refresh", "Could not renew the ChatGPT connection. Retry, or sign in again."), ), - ), - ); + ); + if (!tokens.refresh_token || tokens.token_type.toLowerCase() !== "bearer") { + return yield* failure("refresh", "ChatGPT returned an invalid renewal. Sign in again."); + } + record = { + ...record, + accessToken: tokens.access_token, + refreshToken: tokens.refresh_token, + expiresAt: (yield* Clock.currentTimeMillis) + tokens.expires_in * 1000, + earliestRefreshAt: earliest(tokens.earliest_refresh_at), + scopes: tokens.scope.split(/\s+/).filter(Boolean), + }; + yield* save(record); + if (!record.scopes.includes(REQUIRED_SCOPE)) + return yield* failure( + "sharing", + "ChatGPT token sharing is no longer enabled. Sign in again.", + ); + return record; + }).pipe(Effect.uninterruptible, withSessionLock, lock.withPermit); const logout = Effect.gen(function* () { const credentials = Option.getOrUndefined(yield* read); let confirmed = !credentials?.refreshToken; diff --git a/apps/server/src/provider/CodexProvider.ts b/apps/server/src/provider/CodexProvider.ts index 8458315f64de8..2b2d5501881b4 100644 --- a/apps/server/src/provider/CodexProvider.ts +++ b/apps/server/src/provider/CodexProvider.ts @@ -1,3 +1,4 @@ +import { pipe } from "effect/Function"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -801,11 +802,10 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu presentation: CODEX_PRESENTATION, enabled: codexSettings.enabled, checkedAt, - models: applyConfiguredCodexServiceTier( - applyPreferredCodexDefaultModel( - appendCustomCodexModels(snapshot.models ?? [], codexSettings.customModels), - ), - snapshot.serviceTier, + models: pipe( + appendCustomCodexModels(snapshot.models ?? [], codexSettings.customModels), + applyPreferredCodexDefaultModel, + (models) => applyConfiguredCodexServiceTier(models, snapshot.serviceTier), ), skills: snapshot.skills, slashCommands: [ diff --git a/apps/server/src/provider/Drivers/antigravityUsageReader.ts b/apps/server/src/provider/Drivers/antigravityUsageReader.ts index 7d73f1221cb4b..d3035d5ae9b5f 100644 --- a/apps/server/src/provider/Drivers/antigravityUsageReader.ts +++ b/apps/server/src/provider/Drivers/antigravityUsageReader.ts @@ -1,5 +1,6 @@ // @effect-diagnostics-next-line nodeBuiltinImport:off - Effect's File.Info has no ctime, which the cache fingerprint needs. import * as NodeFSP from "node:fs/promises"; +import { pipe } from "effect/Function"; import type { UsageRecord } from "@t3tools/provider-core/server/usage"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; @@ -244,7 +245,9 @@ const readDatabase = Effect.fn("readDatabase")(function* ( for (const row of yield* sql.unsafe<{ readonly data: unknown }>( "SELECT data FROM trajectory_metadata_blob", )) { - trajectoryTimestamp ??= yield* decode(() => timestamp(nested(fields(blob(row.data)), 2))); + trajectoryTimestamp ??= yield* decode(() => + pipe(blob(row.data), fields, (message) => nested(message, 2), timestamp), + ); } } const steps = tables.has("steps") diff --git a/apps/server/src/secrets/SecretRequests.ts b/apps/server/src/secrets/SecretRequests.ts index 7c8e961dbd2eb..9e3a7c033c220 100644 --- a/apps/server/src/secrets/SecretRequests.ts +++ b/apps/server/src/secrets/SecretRequests.ts @@ -1,6 +1,7 @@ // Answers stay in the secret store behind one-use refs; orchestration records only request status. // Consuming tools keep values out of transcripts, projections, clients and model context. // A `file` request instead moves its value to an owner-only file for the agent's own shell. +import { pipe } from "effect/Function"; import { CommandId, SecretRef, @@ -143,7 +144,7 @@ const make = Effect.gen(function* () { // Clear failed saves so the pending card can be answered again. Effect.tapError(() => input.answer.type === "save" - ? removeLogged(storeName(refFor(salt, input.threadId, item.id))) + ? pipe(refFor(salt, input.threadId, item.id), storeName, removeLogged) : Effect.void, ), ); @@ -159,7 +160,7 @@ const make = Effect.gen(function* () { ); const card = recorded.turnItems.find((candidate) => candidate.id === item.id); if (card?.type === "secret_request" && card.secretStatus !== "saved") { - yield* removeLogged(storeName(refFor(salt, input.threadId, item.id))); + yield* pipe(refFor(salt, input.threadId, item.id), storeName, removeLogged); return yield* new SecretRequestError({ reason: "agent_stopped" }); } }, diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index e35aaf1bb93cd..bea3b8a46097a 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -889,11 +889,10 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs projection: dedupeBodies ? dedupeSnapshotBodies(projection) : projection, }; })(); - return withLiveDedupe( - Stream.concat( - Stream.concat(rpcInitialItems([snapshotItem]), completionMarker), - eventStreamFrom(snapshotSequence), - ), + return rpcInitialItems([snapshotItem]).pipe( + Stream.concat(completionMarker), + Stream.concat(eventStreamFrom(snapshotSequence)), + withLiveDedupe, ); }); @@ -962,11 +961,10 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs if (plan.mode === "snapshot") { return yield* snapshotThenLive(); } - return withLiveDedupe( - Stream.concat( - Stream.concat(rpcInitialItems(replay), completionMarker), - eventStreamFrom(highWater), - ), + return rpcInitialItems(replay).pipe( + Stream.concat(completionMarker), + Stream.concat(eventStreamFrom(highWater)), + withLiveDedupe, ); } diff --git a/apps/web/src/browser/previewWebviewConfigState.ts b/apps/web/src/browser/previewWebviewConfigState.ts index 60a60525f0350..7d1042e612629 100644 --- a/apps/web/src/browser/previewWebviewConfigState.ts +++ b/apps/web/src/browser/previewWebviewConfigState.ts @@ -5,7 +5,6 @@ import type { EnvironmentId, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; -import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import { AsyncResult, Atom } from "effect/reactivity"; @@ -91,5 +90,5 @@ export function usePreviewWebviewConfig( profileId?: string, ): DesktopPreviewWebviewConfig | null { const result = useAtomValue(previewWebviewConfigAtom(configKey(environmentId, profileId))); - return Option.getOrNull(AsyncResult.value(result)); + return AsyncResult.getOrElse(result, () => null); } diff --git a/apps/web/src/cloud/primaryCloudLinkState.ts b/apps/web/src/cloud/primaryCloudLinkState.ts index 9672f2a00366e..867008fbc3bef 100644 --- a/apps/web/src/cloud/primaryCloudLinkState.ts +++ b/apps/web/src/cloud/primaryCloudLinkState.ts @@ -8,7 +8,6 @@ import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; import { AsyncResult, Atom } from "effect/reactivity"; import { HttpClient } from "effect/http"; @@ -90,7 +89,7 @@ export function usePrimaryCloudLinkState() { } return { - data: result._tag === "Failure" ? null : Option.getOrNull(AsyncResult.value(result)), + data: result._tag === "Failure" ? null : AsyncResult.getOrElse(result, () => null), error, isPending: result.waiting, refresh, diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index c6d9cfd534b86..6af016c18ce91 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -185,11 +185,9 @@ import { toastManager } from "./ui/toast"; import { projectScriptIdFromCommand } from "~/projectScripts"; import { newMessageId } from "~/lib/utils"; import { - applyProviderInstanceSettings, - deriveProviderInstanceEntries, NO_PROVIDER_MODEL_SELECTION, + providerInstanceEntriesFor, shouldShowInstanceBadge, - sortProviderInstanceEntries, } from "../providerInstances"; import { useClientSettings, @@ -1237,12 +1235,10 @@ export default function ChatView(props: ChatViewProps) { automaticEnvironment, autoUpdateEnvironments, }); - const providerInstanceEntries = sortProviderInstanceEntries( - applyProviderInstanceSettings( - deriveProviderInstanceEntries(providerStatuses), - settings, - activeProject?.id ?? null, - ), + const providerInstanceEntries = providerInstanceEntriesFor( + providerStatuses, + settings, + activeProject?.id ?? null, ); const activeThreadModelInstanceId = activeThread?.modelSelection.instanceId; const { selectedProviderEntry, requestedDriverKind } = resolveComposerProviderSelection({ diff --git a/apps/web/src/components/ThreadStatusIndicators.tsx b/apps/web/src/components/ThreadStatusIndicators.tsx index 682172f1ff308..0af0e063bdea3 100644 --- a/apps/web/src/components/ThreadStatusIndicators.tsx +++ b/apps/web/src/components/ThreadStatusIndicators.tsx @@ -1,3 +1,4 @@ +import { pipe } from "effect/Function"; import { scopeProjectRef, scopedThreadKey, @@ -325,8 +326,10 @@ export function ThreadPullRequestsMiniList({ pullRequests: ReadonlyArray; onOpenPullRequest?: (event: MouseEvent, url: string) => void; }) { - const lines = pullRequestListLines( - resolveThreadPullRequestChains(visibleThreadPullRequests(pullRequests)), + const lines = pipe( + visibleThreadPullRequests(pullRequests), + resolveThreadPullRequestChains, + pullRequestListLines, ); if (lines.length === 0) return null; return ( diff --git a/apps/web/src/components/chat/LinkRequestCard.tsx b/apps/web/src/components/chat/LinkRequestCard.tsx index 9d9327368a5ad..728c8fe61efa2 100644 --- a/apps/web/src/components/chat/LinkRequestCard.tsx +++ b/apps/web/src/components/chat/LinkRequestCard.tsx @@ -1,3 +1,4 @@ +import { pipe } from "effect/Function"; import { useAtomValue } from "@effect/atom-react"; import { type LinkableMachine, @@ -106,7 +107,7 @@ function PendingLinkRequest(props: { setDeclining(false), ); if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - setError(linkRequestFailureMessage(squashAtomCommandFailure(result))); + pipe(squashAtomCommandFailure(result), linkRequestFailureMessage, setError); } }; @@ -311,7 +312,7 @@ function LinkRequestDialog(props: { // The card switches to its answered row once the item updates. close(); } else if (!isAtomCommandInterrupted(result)) { - setError(linkRequestFailureMessage(squashAtomCommandFailure(result))); + pipe(squashAtomCommandFailure(result), linkRequestFailureMessage, setError); } }; diff --git a/apps/web/src/components/chat/SecretRequestCard.tsx b/apps/web/src/components/chat/SecretRequestCard.tsx index f8dc7579adcaf..50992c2edebf5 100644 --- a/apps/web/src/components/chat/SecretRequestCard.tsx +++ b/apps/web/src/components/chat/SecretRequestCard.tsx @@ -1,3 +1,4 @@ +import { pipe } from "effect/Function"; import { SECRET_REQUEST_DEFAULT_PLACEHOLDER, secretRequestAnswerInput, @@ -86,7 +87,7 @@ function PendingSecretRequestForm(props: { return; } if (!isAtomCommandInterrupted(result)) { - setError(secretRequestFailureMessage(squashAtomCommandFailure(result))); + pipe(squashAtomCommandFailure(result), secretRequestFailureMessage, setError); } }; diff --git a/apps/web/src/components/chat/ThreadDetailsPrRows.tsx b/apps/web/src/components/chat/ThreadDetailsPrRows.tsx index f954d275ac6fd..2da6019787f5a 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRows.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRows.tsx @@ -1,3 +1,4 @@ +import { pipe } from "effect/Function"; import { ThreadDetailsControl } from "./ThreadDetailsControl"; import type { EnvironmentId, ScopedThreadRef, ThreadPullRequestLink } from "@t3tools/contracts"; import { @@ -94,7 +95,7 @@ export function ThreadDetailsPrRows({ const rest = currentLink === null ? [] - : pullRequestListLines(resolveThreadPullRequestChains(visibleThreadPullRequests(links))) + : pipe(visibleThreadPullRequests(links), resolveThreadPullRequestChains, pullRequestListLines) .map((line) => line.link) .filter((link) => threadPullRequestKeyOf(link) !== threadPullRequestKeyOf(currentLink)); if (rest.length === 0) return currentRow; diff --git a/apps/web/src/components/chat/useComposerProviderModel.ts b/apps/web/src/components/chat/useComposerProviderModel.ts index 24920d1593b45..7fd1130859fec 100644 --- a/apps/web/src/components/chat/useComposerProviderModel.ts +++ b/apps/web/src/components/chat/useComposerProviderModel.ts @@ -12,10 +12,8 @@ import { } from "@t3tools/contracts"; import { NO_PROVIDER_MODEL_SELECTION, + providerInstanceEntriesFor, type ProviderInstanceEntry, - applyProviderInstanceSettings, - deriveProviderInstanceEntries, - sortProviderInstanceEntries, } from "../../providerInstances"; import { type UnifiedSettings } from "@t3tools/contracts/settings"; import { getComposerPromptInjectionState, getComposerProviderState } from "./composerProviderState"; @@ -52,12 +50,10 @@ export function useComposerProviderModel( lockedInstanceId, } = input; const draftModelState = useComposerDraftModelState(threadRef); - const providerInstanceEntries: ReadonlyArray = sortProviderInstanceEntries( - applyProviderInstanceSettings( - deriveProviderInstanceEntries(providerStatuses), - settings, - activeProjectId, - ), + const providerInstanceEntries: ReadonlyArray = providerInstanceEntriesFor( + providerStatuses, + settings, + activeProjectId, ); const selection = resolveComposerProviderSelection({ entries: providerInstanceEntries, diff --git a/apps/web/src/components/device/DeviceStreamView.tsx b/apps/web/src/components/device/DeviceStreamView.tsx index e237a4690b7cc..22ae466acb0ed 100644 --- a/apps/web/src/components/device/DeviceStreamView.tsx +++ b/apps/web/src/components/device/DeviceStreamView.tsx @@ -1,6 +1,5 @@ import type { DevicePlatform, EnvironmentId } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; -import * as Option from "effect/Option"; import { AsyncResult, Atom } from "effect/reactivity"; import { useId, useRef, useState, type ReactNode } from "react"; @@ -197,7 +196,7 @@ export function DeviceStreamView(props: { ? deviceAxElementsAtom({ access, platform: props.platform, deviceId: props.deviceId }) : NO_AX_ATOM, ); - const axElements = Option.getOrElse(AsyncResult.value(axResult), () => NO_AX_ELEMENTS); + const axElements = AsyncResult.getOrElse(axResult, () => NO_AX_ELEMENTS); const pointerActive = useRef(false); const normalizedPoint = (event: React.PointerEvent) => { diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index 589ae62265c28..46cf7dbb67a83 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -1,3 +1,4 @@ +import { pipe } from "effect/Function"; import { IMAGE_DIMENSIONS_HEADER_BYTES, readImageDimensions, @@ -221,7 +222,7 @@ const HTML_TAGS = new Set([ "dd", ]); async function epubHtml(node: XmlNode, archive: JSZip, base: string): Promise { - if (node.name === "#text") return boundedMarkup(escape(text(node))); + if (node.name === "#text") return pipe(text(node), escape, boundedMarkup); const tag = node.name .replace(/^\{[^}]*\}/, "") @@ -249,7 +250,7 @@ async function epubHtml(node: XmlNode, archive: JSZip, base: string): Promise${children}`; } async function odfHtml(node: XmlNode, archive: JSZip): Promise { - if (node.name === "#text") return boundedMarkup(escape(text(node))); + if (node.name === "#text") return pipe(text(node), escape, boundedMarkup); if (node.name === "text:s" || node.name === "text:tab") return boundedMarkup( `${node.name === "text:tab" ? " " : " ".repeat(repeat(node.attrs["text:c"], 100))}`, diff --git a/apps/web/src/components/files/office/fonts.ts b/apps/web/src/components/files/office/fonts.ts index 6328d294d8749..cdac25d4bbe14 100644 --- a/apps/web/src/components/files/office/fonts.ts +++ b/apps/web/src/components/files/office/fonts.ts @@ -1,4 +1,5 @@ // Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode. +import { pipe } from "effect/Function"; import type { BundledFontProvider } from "@betteroffice/docx/layout"; import { loadBundledFontBytes, @@ -23,9 +24,9 @@ export function wordFonts(): BundledFontProvider { return { resolve: (family, bold, italic) => - loader(shippedFace(resolveMetricCompatFace(family, bold, italic))), + pipe(resolveMetricCompatFace(family, bold, italic), shippedFace, loader), resolveFamily: (family, bold, italic) => - loader(shippedFace(resolveBundledFamilyFace(family, bold, italic))), + pipe(resolveBundledFamilyFace(family, bold, italic), shippedFace, loader), resolveScriptFallback: (script, bold, italic) => loader(scriptFace(script, bold, italic)), resolveLastResort: (family, bold, italic) => () => loadFace(lastResortFace(family, bold, italic, "word")), diff --git a/apps/web/src/components/files/office/slide-text.ts b/apps/web/src/components/files/office/slide-text.ts index 396c0cb0b2761..6afe9a6f61b9a 100644 --- a/apps/web/src/components/files/office/slide-text.ts +++ b/apps/web/src/components/files/office/slide-text.ts @@ -1,4 +1,5 @@ // Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode. +import { pipe } from "effect/Function"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import { inspectPresentation, type DeckSnapshot } from "@betteroffice/pptx"; @@ -131,50 +132,58 @@ const scriptRanges: readonly (readonly [FallbackScript, RegExp])[] = [ * engine's inspection does not decode, the slides' own runs stand in, without theme fonts or hidden flags. */ export function deckText(bytes: Uint8Array, snapshot: DeckSnapshot): DeckText { - return Option.match(decodeInspected(inspectPresentation(withoutMedia(bytes))), { - onNone: () => fromSnapshot(snapshot), - onSome: (inspected) => { - const schemes = - inspected.themes?.flatMap((theme) => - theme.theme?.fontScheme ? [theme.theme.fontScheme] : [], - ) ?? []; - const minor = schemes[0]?.minorFont.latin ?? ""; - - const drawings = [ - ...inspected.slides.flatMap((slide) => slide.drawings), - ...(inspected.layouts ?? []).flatMap((layout) => layout.drawings), - ...(inspected.masters ?? []).flatMap((master) => master.drawings), - ]; - - const defaults = (inspected.masters ?? []).flatMap((master) => - Object.values(master.textStyles ?? {}).flatMap((levels) => - levels.flatMap((level) => - level.defaultRun ? [{ text: "", style: level.defaultRun }] : [], + return pipe( + withoutMedia(bytes), + inspectPresentation, + decodeInspected, + Option.match({ + onNone: () => fromSnapshot(snapshot), + onSome: (inspected) => { + const schemes = + inspected.themes?.flatMap((theme) => + theme.theme?.fontScheme ? [theme.theme.fontScheme] : [], + ) ?? []; + const minor = schemes[0]?.minorFont.latin ?? ""; + + const drawings = [ + ...inspected.slides.flatMap((slide) => slide.drawings), + ...(inspected.layouts ?? []).flatMap((layout) => layout.drawings), + ...(inspected.masters ?? []).flatMap((master) => master.drawings), + ]; + + const defaults = (inspected.masters ?? []).flatMap((master) => + Object.values(master.textStyles ?? {}).flatMap((levels) => + levels.flatMap((level) => + level.defaultRun ? [{ text: "", style: level.defaultRun }] : [], + ), ), - ), - ); - - return summarize( - [...drawings.flatMap(drawingRuns), ...defaults].flatMap((run) => { - const family = run.style?.fontFamily; - if (!schemes.length || (family && !family.startsWith("+mn") && !family.startsWith("+mj"))) - return [run]; - return schemes.map((scheme) => ({ - ...run, - style: { - ...run.style, - fontFamily: family?.startsWith("+mj") - ? scheme.majorFont.latin - : scheme.minorFont.latin, - }, - })); - }), - (family) => (family?.startsWith("+") ? "" : (family ?? "")), - minor, - inspected.slides.map((slide) => slide.hidden ?? false), - ); - }, - }); + ); + + return summarize( + [...drawings.flatMap(drawingRuns), ...defaults].flatMap((run) => { + const family = run.style?.fontFamily; + if ( + !schemes.length || + (family && !family.startsWith("+mn") && !family.startsWith("+mj")) + ) + return [run]; + return schemes.map((scheme) => ({ + ...run, + style: { + ...run.style, + fontFamily: family?.startsWith("+mj") + ? scheme.majorFont.latin + : scheme.minorFont.latin, + }, + })); + }), + (family) => (family?.startsWith("+") ? "" : (family ?? "")), + minor, + inspected.slides.map((slide) => slide.hidden ?? false), + ); + }, + }), + ); } /** A file in the deck's zip package: where its central directory record and its local data sit. */ diff --git a/apps/web/src/components/files/projectFilesQueryState.ts b/apps/web/src/components/files/projectFilesQueryState.ts index 3da7fdd6da850..4d7e9ae90d6b9 100644 --- a/apps/web/src/components/files/projectFilesQueryState.ts +++ b/apps/web/src/components/files/projectFilesQueryState.ts @@ -207,7 +207,7 @@ export function useProjectEntriesQuery( const refreshAtom = useAtomRefresh(atom); const refresh = () => refreshAtom(); return { - data: Option.getOrNull(AsyncResult.value(result)), + data: AsyncResult.getOrElse(result, () => null), error: fileAccess.isPending ? null : canReadFiles @@ -263,7 +263,7 @@ export function useProjectFileQuery( const result = useAtomValue(atom); const refreshAtom = useAtomRefresh(atom); const refresh = () => refreshAtom(); - const readData = Option.getOrNull(AsyncResult.value(result)); + const readData = AsyncResult.getOrElse(result, () => null); const isMissing = readData?.exists === false; const optimisticResult = useAtomValue( optimisticFileAtom(environmentId, cwd, relativePath ?? EMPTY_PROJECT_FILE_PATH), diff --git a/apps/web/src/components/media/MediaActions.tsx b/apps/web/src/components/media/MediaActions.tsx index 314f7a6435d28..f45ba1e7abc78 100644 --- a/apps/web/src/components/media/MediaActions.tsx +++ b/apps/web/src/components/media/MediaActions.tsx @@ -16,7 +16,6 @@ import { sessionGrantsScope, type SessionGrantInput, } from "@t3tools/contracts"; -import * as Option from "effect/Option"; import { AsyncResult } from "effect/reactivity"; import { useRef, useState, type ReactElement } from "react"; @@ -53,7 +52,7 @@ function allowsHostMedia(session: SessionGrantInput | null) { function canReadHostMedia(environmentId: EnvironmentId | null): boolean { if (environmentId === null) return true; const result = appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId)); - return result._tag !== "Failure" && allowsHostMedia(Option.getOrNull(AsyncResult.value(result))); + return result._tag !== "Failure" && allowsHostMedia(AsyncResult.getOrElse(result, () => null)); } export function useMediaActions(source: MediaActionSource) { diff --git a/apps/web/src/components/preview/agentOpenedPreviews.ts b/apps/web/src/components/preview/agentOpenedPreviews.ts index ccb133074baad..8273258d51e54 100644 --- a/apps/web/src/components/preview/agentOpenedPreviews.ts +++ b/apps/web/src/components/preview/agentOpenedPreviews.ts @@ -10,7 +10,6 @@ import type { ScopedThreadRef, ThreadId, } from "@t3tools/contracts"; -import * as Option from "effect/Option"; import { AsyncResult } from "effect/reactivity"; import { getClientSettings } from "../../hooks/useSettings"; @@ -222,7 +221,7 @@ function watchEnvironmentDevices(environmentId: EnvironmentId): () => void { return appAtomRegistry.subscribe( deviceEnvironment.state({ environmentId, input: {} }), (result) => { - const state = Option.getOrNull(AsyncResult.value(result)); + const state = AsyncResult.getOrElse(result, () => null); if (state === null) return; applyDeviceSnapshot(environmentId, state, { sheetLayout: window.matchMedia(RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY).matches, diff --git a/apps/web/src/components/pullRequest/filesViewedStore.ts b/apps/web/src/components/pullRequest/filesViewedStore.ts index 64ae67a355192..cae490ded8d66 100644 --- a/apps/web/src/components/pullRequest/filesViewedStore.ts +++ b/apps/web/src/components/pullRequest/filesViewedStore.ts @@ -8,7 +8,6 @@ import type { PullRequestFilesViewedResult, PullRequestRef, } from "@t3tools/contracts"; -import * as Option from "effect/Option"; import { AsyncResult } from "effect/reactivity"; import { appAtomRegistry } from "~/rpc/atomRegistry"; @@ -238,7 +237,7 @@ const filesViewedStore = createFilesViewedStore({ subscribeAnswers: (target, onAnswer) => appAtomRegistry.subscribe( filesViewedAtom(target), - (result) => onAnswer(Option.getOrNull(AsyncResult.value(result))), + (result) => onAnswer(AsyncResult.getOrElse(result, () => null)), { immediate: true }, ), send: ({ environmentId, reference }, files) => diff --git a/apps/web/src/components/pullRequest/guide/PullRequestGuideRunCoordinator.tsx b/apps/web/src/components/pullRequest/guide/PullRequestGuideRunCoordinator.tsx index d9c05ae1a9917..f73755ed7d452 100644 --- a/apps/web/src/components/pullRequest/guide/PullRequestGuideRunCoordinator.tsx +++ b/apps/web/src/components/pullRequest/guide/PullRequestGuideRunCoordinator.tsx @@ -1,7 +1,6 @@ import type { AnyRouter } from "@tanstack/react-router"; import type { PullRequestReviewGuideResult } from "@t3tools/contracts"; import { CircleAlertIcon, CircleCheckIcon } from "lucide-react"; -import * as Option from "effect/Option"; import { AsyncResult, type AtomRegistry } from "effect/reactivity"; import { getClientSettings } from "~/hooks/useSettings"; @@ -159,7 +158,7 @@ function watchGuideRun( const unsubscribe = registry.subscribe( atom, (result) => { - const data = Option.getOrNull(AsyncResult.value(result)); + const data = AsyncResult.getOrElse(result, () => null); if (data === null || data === seen) return; seen = data; if (subscribing && watch.answeredRunning === true) return; diff --git a/apps/web/src/components/settings/AcpRegistryIcon.tsx b/apps/web/src/components/settings/AcpRegistryIcon.tsx index b7a5938ee8942..4a2a2143fe0e5 100644 --- a/apps/web/src/components/settings/AcpRegistryIcon.tsx +++ b/apps/web/src/components/settings/AcpRegistryIcon.tsx @@ -1,6 +1,5 @@ import { useAtomValue } from "@effect/atom-react"; import * as Effect from "effect/Effect"; -import * as Option from "effect/Option"; import { AsyncResult, Atom } from "effect/reactivity"; import { useId, useState } from "react"; import { @@ -110,10 +109,9 @@ export function AcpRegistryAgentIcon({ const iconUrl = resolveOfficialAcpRegistryIconUrl(icon); // Render only after the load pipeline resolves, so the fallback icon does // not flash a broken image. - const source = Option.getOrNull( - AsyncResult.value( - useAtomValue(iconUrl === null ? NO_ICON_SOURCE_ATOM : acpRegistryIconSourceAtom(iconUrl)), - ), + const source = AsyncResult.getOrElse( + useAtomValue(iconUrl === null ? NO_ICON_SOURCE_ATOM : acpRegistryIconSourceAtom(iconUrl)), + () => null, ); const [image, setImage] = useState<{ readonly source: string; diff --git a/apps/web/src/components/settings/AcpRegistrySearchStep.tsx b/apps/web/src/components/settings/AcpRegistrySearchStep.tsx index 50967ab2026e9..a3612a609418c 100644 --- a/apps/web/src/components/settings/AcpRegistrySearchStep.tsx +++ b/apps/web/src/components/settings/AcpRegistrySearchStep.tsx @@ -1,3 +1,4 @@ +import { pipe } from "effect/Function"; import { ACP_REGISTRY_MAX_AGENTS, AuthProvidersManageScope } from "@t3tools/contracts"; import { readEnvironmentScope, useEnvironmentScope } from "../../state/session"; import { @@ -111,7 +112,7 @@ export function useAcpRegistrySearch(environmentId: EnvironmentId, enabled: bool return; } if (!isAtomCommandInterrupted(result)) { - setPrepareError(errorMessage(squashAtomCommandFailure(result))); + pipe(squashAtomCommandFailure(result), errorMessage, setPrepareError); } }, }; diff --git a/apps/web/src/components/settings/AddEnvironmentDialog.tsx b/apps/web/src/components/settings/AddEnvironmentDialog.tsx index 22bb624c27533..23a439c63a475 100644 --- a/apps/web/src/components/settings/AddEnvironmentDialog.tsx +++ b/apps/web/src/components/settings/AddEnvironmentDialog.tsx @@ -1,3 +1,4 @@ +import { pipe } from "effect/Function"; import { ChevronsLeftRightEllipsisIcon, PlusIcon, TerminalIcon } from "lucide-react"; import { useAtomValue } from "@effect/atom-react"; import { type KeyboardEvent, type ReactNode, useEffect, useRef, useState } from "react"; @@ -155,7 +156,7 @@ export function AddEnvironmentDialog({ }); if (result._tag === "Failure") { if (!isAtomCommandInterrupted(result)) { - onErrorChange(formatDesktopSshConnectionError(squashAtomCommandFailure(result))); + pipe(squashAtomCommandFailure(result), formatDesktopSshConnectionError, onErrorChange); } setIsAddingSavedBackend(false); return; diff --git a/apps/web/src/components/settings/ConnectionDiagnosisDetails.tsx b/apps/web/src/components/settings/ConnectionDiagnosisDetails.tsx index c655833ca7c82..d896efe455216 100644 --- a/apps/web/src/components/settings/ConnectionDiagnosisDetails.tsx +++ b/apps/web/src/components/settings/ConnectionDiagnosisDetails.tsx @@ -28,8 +28,8 @@ import { stackedThreadToast, toastManager } from "../ui/toast"; */ export function useConnectionDiagnosis(environment: EnvironmentPresentation) { const environmentId = environment.environmentId; - const state = Option.getOrElse( - AsyncResult.value(useAtomValue(environmentCatalog.stateAtom(environmentId))), + const state = AsyncResult.getOrElse( + useAtomValue(environmentCatalog.stateAtom(environmentId)), () => AVAILABLE_CONNECTION_STATE, ); const relayStatus = useRelayEnvironmentDiscovery().environments.get(environmentId)?.status; diff --git a/apps/web/src/components/settings/ProjectDefaultsSettings.tsx b/apps/web/src/components/settings/ProjectDefaultsSettings.tsx index 9941be071c799..0bfa19498f6d9 100644 --- a/apps/web/src/components/settings/ProjectDefaultsSettings.tsx +++ b/apps/web/src/components/settings/ProjectDefaultsSettings.tsx @@ -12,10 +12,8 @@ import { resolveEffectiveDefaultModelSelection, } from "../../modelSelection"; import { - applyProviderInstanceSettings, - deriveProviderInstanceEntries, + providerInstanceEntriesFor, resolveDefaultProviderModelSelection, - sortProviderInstanceEntries, } from "../../providerInstances"; import { useEnvironmentProviders, useEnvironments } from "../../state/environments"; import { EMPTY_SERVER_PROVIDERS } from "../../state/server"; @@ -70,13 +68,7 @@ export function ProjectDefaultsSettings({ category }: { category: ProjectSetting const selection = storedSelection ? resolveEffectiveDefaultModelSelection(settings, providers, storedSelection) : null; - const entries = sortProviderInstanceEntries( - applyProviderInstanceSettings( - deriveProviderInstanceEntries(providers), - settings, - target?.projectId ?? null, - ), - ); + const entries = providerInstanceEntriesFor(providers, settings, target?.projectId ?? null); const modelOptions = getCustomModelOptionsByInstance( settings, providers, diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.tsx index 983503c96b5fe..1f64fe501af1d 100644 --- a/apps/web/src/components/settings/ScheduledTasksSettings.tsx +++ b/apps/web/src/components/settings/ScheduledTasksSettings.tsx @@ -1,6 +1,5 @@ import { useAtomValue } from "@effect/atom-react"; import { connectionStatusTitle } from "@t3tools/client-runtime/connection"; -import * as Option from "effect/Option"; import { AsyncResult } from "effect/reactivity"; import { Clock3Icon, @@ -48,11 +47,7 @@ import { import { formatRelativeTime } from "../../timestampFormat"; import { useEnvironmentSettings } from "../../hooks/useSettings"; import { getCustomModelOptionsByInstance } from "../../modelSelection"; -import { - applyProviderInstanceSettings, - deriveProviderInstanceEntries, - sortProviderInstanceEntries, -} from "../../providerInstances"; +import { providerInstanceEntriesFor } from "../../providerInstances"; import { usePrimaryCloudLinkState } from "../../cloud/primaryCloudLinkState"; import { requestConfirmDialog } from "../../confirmDialog"; import { webhookAddress } from "@t3tools/client-runtime/webhook-address"; @@ -492,7 +487,7 @@ function ScheduledTaskEnvironmentList({ const states = environments.map((environment) => { const index = connectedIds.indexOf(environment.environmentId); const query = index < 0 ? null : queries[index]!; - const data = query === null ? null : Option.getOrNull(AsyncResult.value(query)); + const data = query === null ? null : AsyncResult.getOrElse(query, () => null); return { environment, connected: index >= 0, @@ -1148,12 +1143,10 @@ function ScheduledTaskEditorForm({ : task; const selectedProjectId = draft.projectId || projects[0]?.id || ""; const selectedProject = projects.find((project) => project.id === selectedProjectId); - const instanceEntries = sortProviderInstanceEntries( - applyProviderInstanceSettings( - deriveProviderInstanceEntries(providers), - settings, - selectedProject?.id ?? null, - ), + const instanceEntries = providerInstanceEntriesFor( + providers, + settings, + selectedProject?.id ?? null, ); const firstInstance = instanceEntries[0]; diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index a4aadac731081..183c12ddf1a49 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -61,11 +61,7 @@ import { resolveAppModelSelectionState, selectsPlanAgent, } from "../../modelSelection"; -import { - applyProviderInstanceSettings, - deriveProviderInstanceEntries, - sortProviderInstanceEntries, -} from "../../providerInstances"; +import { providerInstanceEntriesFor } from "../../providerInstances"; import { ensureLocalApi, readLocalApi } from "../../localApi"; import { isMacPlatform } from "../../lib/utils"; import { useEnvironmentProviders } from "../../state/environments"; @@ -1501,12 +1497,10 @@ export function ThreadsSettingsPanel() { const textGenInstanceId = textGenerationModelSelection.instanceId; const textGenModel = textGenerationModelSelection.model; const textGenModelOptions = textGenerationModelSelection.options; - const textGenerationModelInstanceEntries = sortProviderInstanceEntries( - applyProviderInstanceSettings( - deriveProviderInstanceEntries(textGenerationProviders), - settings, - target?.projectId ?? null, - ), + const textGenerationModelInstanceEntries = providerInstanceEntriesFor( + textGenerationProviders, + settings, + target?.projectId ?? null, ); const hasTextGenerationProvider = textGenerationModelInstanceEntries.some( (entry) => entry.enabled && entry.isAvailable, diff --git a/apps/web/src/components/settings/SettingsScopeContext.tsx b/apps/web/src/components/settings/SettingsScopeContext.tsx index c6cae612b7716..294ed8b2fd41d 100644 --- a/apps/web/src/components/settings/SettingsScopeContext.tsx +++ b/apps/web/src/components/settings/SettingsScopeContext.tsx @@ -1,7 +1,6 @@ import { type EnvironmentId, T3_PROJECT_FILE_NAME, type T3ProjectFile } from "@t3tools/contracts"; import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile"; import { useAtomValue } from "@effect/atom-react"; -import * as Option from "effect/Option"; import { AsyncResult, Atom } from "effect/reactivity"; import { createContext, type ReactNode, useContext } from "react"; @@ -29,7 +28,7 @@ const memberProjectFilesAtom = Atom.family((membersKey: string) => { if (result.waiting) continue; const data = get(optimisticFileAtom(environmentId, workspaceRoot, T3_PROJECT_FILE_NAME))?.data ?? - Option.getOrNull(AsyncResult.value(result)); + AsyncResult.getOrElse(result, () => null); files.set( physicalProjectKey, data === null || data.exists === false || data.truncated diff --git a/apps/web/src/components/settings/SourceControlWritingSettings.tsx b/apps/web/src/components/settings/SourceControlWritingSettings.tsx index 2b54bd04d0ffb..dd3618902f8b5 100644 --- a/apps/web/src/components/settings/SourceControlWritingSettings.tsx +++ b/apps/web/src/components/settings/SourceControlWritingSettings.tsx @@ -19,11 +19,7 @@ import { } from "./useScopedSettings"; import { useScopedModelDisabledReason } from "./useScopedModelAvailability"; import { useSettingsScope } from "./SettingsScopeContext"; -import { - applyProviderInstanceSettings, - deriveProviderInstanceEntries, - sortProviderInstanceEntries, -} from "../../providerInstances"; +import { providerInstanceEntriesFor } from "../../providerInstances"; import { getCustomModelOptionsByInstance, resolveAppModelSelectionState, @@ -110,12 +106,10 @@ export function SourceControlWritingSettingsSection() { const textGenerationProviders = serverProviders.filter( (provider) => provider.supportsTextGeneration !== false, ); - const instanceEntries = sortProviderInstanceEntries( - applyProviderInstanceSettings( - deriveProviderInstanceEntries(textGenerationProviders), - settings, - target?.projectId ?? null, - ), + const instanceEntries = providerInstanceEntriesFor( + textGenerationProviders, + settings, + target?.projectId ?? null, ); const projectEnabledInstanceIds = new Set( instanceEntries diff --git a/apps/web/src/components/usage/UsagePriceOverrides.tsx b/apps/web/src/components/usage/UsagePriceOverrides.tsx index bbc481f860c25..eb47ac5586ed3 100644 --- a/apps/web/src/components/usage/UsagePriceOverrides.tsx +++ b/apps/web/src/components/usage/UsagePriceOverrides.tsx @@ -1,7 +1,6 @@ import { useAtomValue } from "@effect/atom-react"; import { AuthSettingsWriteScope, type EnvironmentId, sessionGrantsScope } from "@t3tools/contracts"; import { ChevronDownIcon, PlusIcon, RotateCcwIcon, XIcon } from "lucide-react"; -import * as Option from "effect/Option"; import { AsyncResult, Atom } from "effect/reactivity"; import { useRef, useState } from "react"; @@ -46,7 +45,7 @@ const priceTargetsAtom = Atom.make((get): readonly UsagePriceTarget[] => [...get(environmentPresentations.presentationsAtom)].map(([environmentId, environment]) => { const settings = get(serverEnvironment.settingsValueAtom(environmentId)); const session = get(environmentSession.sessionStateAtom(environmentId)); - const sessionData = Option.getOrNull(AsyncResult.value(session)); + const sessionData = AsyncResult.getOrElse(session, () => null); const access = session._tag === "Failure" ? "denied" diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index 22c7c8a5c3553..e823d2ddf33a3 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -4194,9 +4194,7 @@ export function subscribeComposerDraftModelReconciliation(input: { const thread = get(input.threadShellAtom(ref)); if (!thread || !draftModelPickMatchesThread(pick, thread.modelSelection)) continue; // Status and selection must come from the same emission; derived atoms can update apart. - const shell = Option.getOrNull( - AsyncResult.value(get(input.shellStateAtom(ref.environmentId))), - ); + const shell = AsyncResult.getOrElse(get(input.shellStateAtom(ref.environmentId)), () => null); if (shell?.status !== "live") continue; const authoritativeThread = Option.getOrNull(shell.snapshot)?.threads.find( (candidate) => candidate.id === ref.threadId, diff --git a/apps/web/src/environments/primary/sessionState.ts b/apps/web/src/environments/primary/sessionState.ts index 34dc68b2f3ca1..766421a17afd5 100644 --- a/apps/web/src/environments/primary/sessionState.ts +++ b/apps/web/src/environments/primary/sessionState.ts @@ -1,7 +1,6 @@ import { useAtomValue } from "@effect/atom-react"; import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; -import * as Option from "effect/Option"; import { AsyncResult, Atom } from "effect/reactivity"; import { isLocalEnvironmentDisabled } from "../../localEnvironment"; @@ -30,7 +29,7 @@ export function usePrimarySessionState() { error = cause instanceof Error ? cause.message : "Could not read environment session."; } return { - data: Option.getOrNull(AsyncResult.value(result)), + data: AsyncResult.getOrElse(result, () => null), error, isPending: result.waiting, refresh: refreshPrimarySessionState, diff --git a/apps/web/src/filePathDisplay.ts b/apps/web/src/filePathDisplay.ts index 7fee707bf4c0d..9d59a83630a5c 100644 --- a/apps/web/src/filePathDisplay.ts +++ b/apps/web/src/filePathDisplay.ts @@ -1,3 +1,4 @@ +import { pipe } from "effect/Function"; import { fileBasename, stripSlashPrefixedWindowsDrive, @@ -26,8 +27,10 @@ export function formatWorkspaceRelativePath( let displayPath = normalizedPath; if (workspaceRoot) { - const normalizedWorkspaceRoot = stripSlashPrefixedWindowsDrive( - normalizePathSeparators(trimTrailingPathSeparators(workspaceRoot)), + const normalizedWorkspaceRoot = pipe( + trimTrailingPathSeparators(workspaceRoot), + normalizePathSeparators, + stripSlashPrefixedWindowsDrive, ); const workspaceLabel = fileBasename(normalizedWorkspaceRoot); const caseInsensitive = isWindowsAbsolutePath(stripSlashPrefixedWindowsDrive(workspaceRoot)); diff --git a/apps/web/src/hooks/useSettings.ts b/apps/web/src/hooks/useSettings.ts index 87733457a417b..2c24f13760092 100644 --- a/apps/web/src/hooks/useSettings.ts +++ b/apps/web/src/hooks/useSettings.ts @@ -574,7 +574,7 @@ function useSharedSettingsSyncTargetIds(includePending = false): ReadonlyArray null); return session !== null && sessionGrantsScope(session, AuthSettingsWriteScope) ? [environmentId] : []; diff --git a/apps/web/src/hooks/useTheme.ts b/apps/web/src/hooks/useTheme.ts index 6addce1543cb1..2467d89091b24 100644 --- a/apps/web/src/hooks/useTheme.ts +++ b/apps/web/src/hooks/useTheme.ts @@ -1,3 +1,4 @@ +import { pipe } from "effect/Function"; import type { DesktopBridge } from "@t3tools/contracts"; import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors"; import * as Schema from "effect/Schema"; @@ -518,7 +519,7 @@ export function setTheme(next: Theme): boolean { if (typeof window === "undefined") return false; try { // Save the current mode first; inferring it from the new theme can switch dark to light. - writeAppearanceModePreference(readAppearanceModePreference(getStored())); + pipe(getStored(), readAppearanceModePreference, writeAppearanceModePreference); // A whole theme replaces the mix; retain it to restore on a failed preference write. const previousHalvesRaw = window.localStorage.getItem(THEME_HALVES_STORAGE_KEY); window.localStorage.removeItem(THEME_HALVES_STORAGE_KEY); diff --git a/apps/web/src/lib/assistantCitationNavigation.ts b/apps/web/src/lib/assistantCitationNavigation.ts index 70d2c160a1a1e..1320b73aa33c5 100644 --- a/apps/web/src/lib/assistantCitationNavigation.ts +++ b/apps/web/src/lib/assistantCitationNavigation.ts @@ -1,3 +1,4 @@ +import { pipe } from "effect/Function"; import type { AssistantCitation } from "@t3tools/contracts"; import { formatAssistantCitationHref, @@ -27,8 +28,11 @@ export function assistantCitationFromLocation(href: string) { const hash = href.slice(hashIndex + 1); if (!hash.startsWith(CITATION_HASH_PREFIX) || hash.length > 140_000) return null; try { - return parseAssistantCitationHref( - Result.getOrThrow(Base64Url.decodeString(hash.slice(CITATION_HASH_PREFIX.length))), + return pipe( + hash.slice(CITATION_HASH_PREFIX.length), + Base64Url.decodeString, + Result.getOrThrow, + parseAssistantCitationHref, ); } catch { return null; diff --git a/apps/web/src/onboarding/useProjectScans.ts b/apps/web/src/onboarding/useProjectScans.ts index e345d77c1170c..bf0ac3a5aecb3 100644 --- a/apps/web/src/onboarding/useProjectScans.ts +++ b/apps/web/src/onboarding/useProjectScans.ts @@ -1,6 +1,5 @@ import { RegistryContext, useAtomValue } from "@effect/atom-react"; import type { EnvironmentId } from "@t3tools/contracts"; -import * as Option from "effect/Option"; import { AsyncResult } from "effect/reactivity"; import { useContext } from "react"; @@ -18,7 +17,7 @@ export function useProjectScans(environmentIds: readonly EnvironmentId[]) { const result = results[index]!; return { environmentId, - data: Option.getOrNull(AsyncResult.value(result)), + data: AsyncResult.getOrElse(result, () => null), error: result._tag === "Failure" ? formatEnvironmentQueryError(result.cause) : null, isPending: result.waiting || result._tag === "Initial", refresh: () => registry.refresh(scanAtom(environmentId)), diff --git a/apps/web/src/providerInstances.ts b/apps/web/src/providerInstances.ts index 2f17157e6b505..a3364df9a15d6 100644 --- a/apps/web/src/providerInstances.ts +++ b/apps/web/src/providerInstances.ts @@ -1,3 +1,4 @@ +import { pipe } from "effect/Function"; import { DEFAULT_MODEL_BY_PROVIDER, defaultInstanceIdForDriver, @@ -147,7 +148,20 @@ function applyProviderInstanceBranding( }; } -export function sortProviderInstanceEntries( +/** Picker order: each driver's default instance first, then its custom instances. */ +export function providerInstanceEntriesFor( + providers: ReadonlyArray, + settings: Pick, + projectId: ProjectId | null, +): ReadonlyArray { + return pipe( + deriveProviderInstanceEntries(providers), + (entries) => applyProviderInstanceSettings(entries, settings, projectId), + sortProviderInstanceEntries, + ); +} + +function sortProviderInstanceEntries( entries: ReadonlyArray, ): ReadonlyArray { const byKind = new Map(); diff --git a/apps/web/src/state/projectClones.ts b/apps/web/src/state/projectClones.ts index 544b48f96109b..10904d346937b 100644 --- a/apps/web/src/state/projectClones.ts +++ b/apps/web/src/state/projectClones.ts @@ -1,7 +1,6 @@ import { useAtomValue } from "@effect/atom-react"; import { parseScopedProjectKey, scopedProjectKey } from "@t3tools/client-runtime/environment"; import type { EnvironmentId, ProjectCloneSnapshot, ScopedProjectRef } from "@t3tools/contracts"; -import * as Option from "effect/Option"; import { AsyncResult, Atom } from "effect/reactivity"; import { environmentServerConfigsAtom } from "./server"; @@ -16,7 +15,7 @@ export const environmentProjectClonesAtom = Atom.family((environmentId: Environm Atom.make((get): ReadonlyArray => { if (!get(environmentServerConfigsAtom).has(environmentId)) return EMPTY_CLONES; const result = get(sourceControlEnvironment.projectClones({ environmentId, input: {} })); - return Option.getOrElse(AsyncResult.value(result), () => EMPTY_CLONES); + return AsyncResult.getOrElse(result, () => EMPTY_CLONES); }).pipe(Atom.withLabel(`web-project-clones:${environmentId}`)), ); diff --git a/apps/web/src/state/pullRequests.ts b/apps/web/src/state/pullRequests.ts index 1a5742a63df2d..c8ac23ced0584 100644 --- a/apps/web/src/state/pullRequests.ts +++ b/apps/web/src/state/pullRequests.ts @@ -547,7 +547,7 @@ function createMergedEnvironmentQuery( if (result._tag === "Failure" && error === null) { error = formatEnvironmentQueryError(result.cause); } - const value = Option.getOrNull(AsyncResult.value(result)); + const value = AsyncResult.getOrElse(result, () => null); if (value !== null) values.push([target.environmentId, value]); } return { values, error, isPending }; @@ -603,7 +603,7 @@ export function usePullRequestTurnRefreshes( export function usePullRequestTurnRefresh(environmentId: EnvironmentId): number | null { const result = useAtomValue(pullRequestEnvironment.refreshes({ environmentId, input: {} })); - return Option.getOrNull(AsyncResult.value(result)); + return AsyncResult.getOrElse(result, () => null); } export interface MergedPullRequestListView { diff --git a/apps/web/src/state/queries.ts b/apps/web/src/state/queries.ts index 5a999922da380..636913c8898c9 100644 --- a/apps/web/src/state/queries.ts +++ b/apps/web/src/state/queries.ts @@ -27,7 +27,6 @@ import type { VcsRef, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; -import * as Option from "effect/Option"; import { AsyncResult, Atom } from "effect/reactivity"; import { useEffect, useState } from "react"; @@ -208,7 +207,7 @@ export function usePaginatedBranches(target: VcsRefTarget) { pagesKey === null ? EMPTY_VCS_REF_PAGES_ATOM : vcsRefPagesAtom(pagesKey), ); const values = results.flatMap((result) => { - const value = Option.getOrNull(AsyncResult.value(result)); + const value = AsyncResult.getOrElse(result, () => null); return value === null ? [] : [value]; }); const refs = new Map(); diff --git a/apps/web/src/state/query.ts b/apps/web/src/state/query.ts index a8e86fc56ed83..c96319e4b7553 100644 --- a/apps/web/src/state/query.ts +++ b/apps/web/src/state/query.ts @@ -40,7 +40,7 @@ export function useEnvironmentQuery( const result = useAtomValue(selectedAtom); const refresh = useAtomRefresh(selectedAtom); return { - data: Option.getOrNull(AsyncResult.value(result)), + data: AsyncResult.getOrElse(result, () => null), dataUpdatedAt: queryUpdatedAt(result), error: result._tag === "Failure" ? formatEnvironmentQueryError(result.cause) : null, failure: diff --git a/apps/web/src/state/server.ts b/apps/web/src/state/server.ts index cce8a8ebb8fc7..bced4e959fa8e 100644 --- a/apps/web/src/state/server.ts +++ b/apps/web/src/state/server.ts @@ -68,10 +68,11 @@ const primaryServerStateAtom = Atom.make((get): PrimaryServerState => { } const target = { environmentId, input: {} }; - const configProjection = Option.getOrNull( - AsyncResult.value(get(serverEnvironment.configProjection(target))), + const configProjection = AsyncResult.getOrElse( + get(serverEnvironment.configProjection(target)), + () => null, ); - const welcome = Option.getOrNull(AsyncResult.value(get(serverEnvironment.welcome(target)))); + const welcome = AsyncResult.getOrElse(get(serverEnvironment.welcome(target)), () => null); return { config: get(serverEnvironment.configValueAtom(environmentId)), @@ -98,8 +99,9 @@ export const primaryServerLegacyThreadMigrationAtom = Atom.make( if (environmentId === null) { return null; } - return Option.getOrNull( - AsyncResult.value(get(serverEnvironment.legacyThreadMigration({ environmentId, input: {} }))), + return AsyncResult.getOrElse( + get(serverEnvironment.legacyThreadMigration({ environmentId, input: {} })), + () => null, ); }, ).pipe(Atom.withLabel("web-primary-server-legacy-thread-migration")); @@ -143,8 +145,8 @@ const environmentConnectionsAtom = Atom.make((get) => { Pick >(); for (const [environmentId, entry] of get(environmentCatalog.catalogValueAtom).entries) { - const state = Option.getOrElse( - AsyncResult.value(get(environmentCatalog.stateAtom(environmentId))), + const state = AsyncResult.getOrElse( + get(environmentCatalog.stateAtom(environmentId)), () => AVAILABLE_CONNECTION_STATE, ); environments.set(environmentId, { diff --git a/apps/web/src/state/session.ts b/apps/web/src/state/session.ts index caf3f99c07d33..13dffb510b93f 100644 --- a/apps/web/src/state/session.ts +++ b/apps/web/src/state/session.ts @@ -37,7 +37,7 @@ export function sessionHasScope( result: AsyncResult.AsyncResult, scope: AuthEnvironmentScope, ): boolean { - const session = Option.getOrNull(AsyncResult.value(result)); + const session = AsyncResult.getOrElse(result, () => null); return result._tag !== "Failure" && session !== null && sessionGrantsScope(session, scope); } @@ -94,7 +94,7 @@ export function readPreparedConnection(environmentId: EnvironmentId) { export function useEnvironmentSessionState(environmentId: EnvironmentId) { const result = useAtomValue(environmentSession.sessionStateAtom(environmentId)); return { - data: Option.getOrNull(AsyncResult.value(result)), + data: AsyncResult.getOrElse(result, () => null), hasError: result._tag === "Failure", isPending: result.waiting, }; diff --git a/apps/web/src/state/shell.ts b/apps/web/src/state/shell.ts index ed5a1546b2ccb..c4675d3d01301 100644 --- a/apps/web/src/state/shell.ts +++ b/apps/web/src/state/shell.ts @@ -75,8 +75,8 @@ export const allEnvironmentShellsBootstrappedAtom = Atom.make((get) => { if (Option.isSome(get(environmentShell.stateValueAtom(environmentId)).snapshot)) { continue; } - const connection = Option.getOrElse( - AsyncResult.value(get(environmentCatalog.stateAtom(environmentId))), + const connection = AsyncResult.getOrElse( + get(environmentCatalog.stateAtom(environmentId)), () => AVAILABLE_CONNECTION_STATE, ); if (connectionProjectionPhase(connection) !== "disconnected") { diff --git a/apps/web/src/state/sourceControlActions.ts b/apps/web/src/state/sourceControlActions.ts index dc21df5782468..bfe883122abec 100644 --- a/apps/web/src/state/sourceControlActions.ts +++ b/apps/web/src/state/sourceControlActions.ts @@ -21,7 +21,6 @@ import { type ThreadId, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; -import * as Option from "effect/Option"; import { AsyncResult } from "effect/reactivity"; import { appAtomRegistry } from "../rpc/atomRegistry"; @@ -373,15 +372,14 @@ export function readCachedPullRequestResolution( if (target.environmentId === null || target.cwd === null || target.reference === null) { return null; } - return Option.getOrNull( - AsyncResult.value( - appAtomRegistry.get( - gitEnvironment.pullRequestResolution({ - environmentId: target.environmentId, - input: { cwd: target.cwd, reference: target.reference }, - }), - ), + return AsyncResult.getOrElse( + appAtomRegistry.get( + gitEnvironment.pullRequestResolution({ + environmentId: target.environmentId, + input: { cwd: target.cwd, reference: target.reference }, + }), ), + () => null, ); } diff --git a/apps/web/src/state/terminalSessions.ts b/apps/web/src/state/terminalSessions.ts index 3683a8fba6da1..a426212cb9a44 100644 --- a/apps/web/src/state/terminalSessions.ts +++ b/apps/web/src/state/terminalSessions.ts @@ -159,8 +159,9 @@ const attachedTerminalSessionFamily = Atom.family((key: string) => { ) : null; const metadata = canRead - ? Option.getOrNull( - AsyncResult.value(get(terminalEnvironment.metadata({ environmentId, input: null }))), + ? AsyncResult.getOrElse( + get(terminalEnvironment.metadata({ environmentId, input: null })), + () => null, ) : null; const summary = @@ -172,7 +173,7 @@ const attachedTerminalSessionFamily = Atom.family((key: string) => { const buffer = attach === null ? EMPTY_TERMINAL_BUFFER_STATE - : Option.getOrElse(AsyncResult.value(attach), () => EMPTY_TERMINAL_BUFFER_STATE); + : AsyncResult.getOrElse(attach, () => EMPTY_TERMINAL_BUFFER_STATE); const state = combineTerminalSessionState(summary, buffer); return attach?._tag === "Failure" ? { ...state, error: formatEnvironmentQueryError(attach.cause), status: "error" } diff --git a/apps/web/src/state/threads.ts b/apps/web/src/state/threads.ts index 8258e123cf854..07fffa97cfbe0 100644 --- a/apps/web/src/state/threads.ts +++ b/apps/web/src/state/threads.ts @@ -67,7 +67,7 @@ export function useEnvironmentThread( ? environmentThreads.stateAtom(environmentId, threadId) : EMPTY_THREAD_STATE_ATOM, ); - const state = Option.getOrElse(AsyncResult.value(result), () => EMPTY_ENVIRONMENT_THREAD_STATE); + const state = AsyncResult.getOrElse(result, () => EMPTY_ENVIRONMENT_THREAD_STATE); return state; } diff --git a/apps/web/src/state/usage.ts b/apps/web/src/state/usage.ts index a5bb95c430c8b..9a68a5fa724f7 100644 --- a/apps/web/src/state/usage.ts +++ b/apps/web/src/state/usage.ts @@ -10,7 +10,6 @@ import { } from "@t3tools/contracts"; import { needsCursorKeychainAccess, refreshUsage } from "@t3tools/client-runtime/state/usage"; import { resolveUsageAccess } from "@t3tools/client-runtime/state/usage-access"; -import * as Option from "effect/Option"; import { AsyncResult, Atom } from "effect/reactivity"; import { useState } from "react"; @@ -42,7 +41,7 @@ const usageByWindowAtom = Atom.family((windowKey: string) => const sessionResult = get(environmentSession.sessionStateAtom(environmentId)); const access = resolveUsageAccess({ connectionPhase: presentation.connection.phase, - session: Option.getOrNull(AsyncResult.value(sessionResult)), + session: AsyncResult.getOrElse(sessionResult, () => null), hasSessionError: sessionResult._tag === "Failure", }); if (!access.canReadDiagnostics) { @@ -57,7 +56,7 @@ const usageByWindowAtom = Atom.family((windowKey: string) => continue; } const result = get(serverEnvironment.usageSummary({ environmentId, input })); - const summary = Option.getOrNull(AsyncResult.value(result)); + const summary = AsyncResult.getOrElse(result, () => null); statuses.push({ environmentId, label: presentation.entry.target.label, diff --git a/apps/web/src/state/waitForQuerySettled.ts b/apps/web/src/state/waitForQuerySettled.ts index 159aed2efdc46..e5339d12cc400 100644 --- a/apps/web/src/state/waitForQuerySettled.ts +++ b/apps/web/src/state/waitForQuerySettled.ts @@ -1,4 +1,3 @@ -import * as Option from "effect/Option"; import { AsyncResult, type Atom, type AtomRegistry } from "effect/reactivity"; /** @@ -27,7 +26,7 @@ export function waitForQuerySettled(input: { const onAbort = () => finish(undefined); const check = (result: AsyncResult.AsyncResult) => { if (AsyncResult.isFailure(result)) return finish(undefined); - const settled = settle(Option.getOrNull(AsyncResult.value(result))); + const settled = settle(AsyncResult.getOrElse(result, () => null)); if (settled !== undefined) finish(settled); }; if (signal.aborted) return finish(undefined); diff --git a/apps/web/src/themePalette.ts b/apps/web/src/themePalette.ts index 3a20981bd3f3d..58dfe4b53ed18 100644 --- a/apps/web/src/themePalette.ts +++ b/apps/web/src/themePalette.ts @@ -1,3 +1,4 @@ +import { pipe } from "effect/Function"; import type { EnvironmentTheme } from "@t3tools/contracts"; import * as Equal from "effect/Equal"; import * as Option from "effect/Option"; @@ -752,13 +753,12 @@ function standardStatusColors(canvas: ThemeRgbColor): { const surfaceOf = (value: string) => mixThemeRgbColors(canvas, parseThemeRgbColor(value, canvas), surfaceMix); const readableOn = (foreground: string, surface: ThemeRgbColor) => - themeOklchToThemeColor( - solveOklchLightness( - themeRgbToOklch(parseThemeRgbColor(foreground, canvas)), - [surface], - 4.6, - appearance === "dark" ? "lighter" : "darker", - ), + pipe( + parseThemeRgbColor(foreground, canvas), + themeRgbToOklch, + (color) => + solveOklchLightness(color, [surface], 4.6, appearance === "dark" ? "lighter" : "darker"), + themeOklchToThemeColor, ); const errorSurface = surfaceOf(standard.error); const warningSurface = surfaceOf(standard.warning); diff --git a/packages/client-runtime/src/relay/managedRelayState.ts b/packages/client-runtime/src/relay/managedRelayState.ts index 94e8fe3368962..c949faf2c3225 100644 --- a/packages/client-runtime/src/relay/managedRelayState.ts +++ b/packages/client-runtime/src/relay/managedRelayState.ts @@ -4,7 +4,6 @@ import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; -import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; @@ -264,7 +263,7 @@ export function readManagedRelaySnapshotState( ): ManagedRelaySnapshotState { const failure = result._tag === "Failure" ? describeManagedRelayFailure(result.cause) : null; return { - data: Option.getOrNull(AsyncResult.value(result)), + data: AsyncResult.getOrElse(result, () => null), error: failure?.message ?? null, errorTraceId: failure?.traceId ?? null, isPending: result.waiting, diff --git a/packages/client-runtime/src/state/archivedThreads.ts b/packages/client-runtime/src/state/archivedThreads.ts index 60c822c981c31..3a67dc1c52fcf 100644 --- a/packages/client-runtime/src/state/archivedThreads.ts +++ b/packages/client-runtime/src/state/archivedThreads.ts @@ -1,7 +1,6 @@ import { EnvironmentId, type OrchestrationV2ArchivedShellSnapshot } from "@t3tools/contracts"; import * as Arr from "effect/Array"; import { pipe } from "effect/Function"; -import * as Option from "effect/Option"; import * as Order from "effect/Order"; import { AsyncResult, Atom } from "effect/reactivity"; @@ -53,7 +52,7 @@ export function createArchivedThreadSnapshotsAtomFamily(options: { const result = get(options.getSnapshotAtom(environmentId)); isLoading ||= result.waiting; - const snapshot = Option.getOrNull(AsyncResult.value(result)); + const snapshot = AsyncResult.getOrElse(result, () => null); if (snapshot !== null) { snapshots.push({ environmentId, snapshot }); } diff --git a/packages/client-runtime/src/state/assets.ts b/packages/client-runtime/src/state/assets.ts index 298772ca05cc3..7017046f8bea8 100644 --- a/packages/client-runtime/src/state/assets.ts +++ b/packages/client-runtime/src/state/assets.ts @@ -257,7 +257,7 @@ export function createProjectFaviconUrlAtomFamily(input: { return Atom.make((get): string | null => { const result = get(image); if (isProjectFaviconFallbackUrl(get(resolvedUrl))) return null; - return Option.getOrElse(AsyncResult.value(result), () => cache.peek(target)); + return AsyncResult.getOrElse(result, () => cache.peek(target)); }).pipe(Atom.setIdleTTL(ASSET_URL_IDLE_TTL_MS)); }); return (target: ProjectFaviconTarget) => diff --git a/packages/client-runtime/src/state/commandPermissions.ts b/packages/client-runtime/src/state/commandPermissions.ts index e8008230107ad..078f7c47508bb 100644 --- a/packages/client-runtime/src/state/commandPermissions.ts +++ b/packages/client-runtime/src/state/commandPermissions.ts @@ -26,7 +26,7 @@ function makeCommandPermissions( const scopes = scopeKey.split(",").filter(Boolean) as AuthEnvironmentScope[]; if (scopes.length === 0) return true; const result = get(sessions.sessionStateAtom(environmentId)); - const session = Option.getOrNull(AsyncResult.value(result)); + const session = AsyncResult.getOrElse(result, () => null); return ( result._tag !== "Failure" && session !== null && diff --git a/packages/client-runtime/src/state/connections.ts b/packages/client-runtime/src/state/connections.ts index 82afc19c69a72..206f75a600416 100644 --- a/packages/client-runtime/src/state/connections.ts +++ b/packages/client-runtime/src/state/connections.ts @@ -1,6 +1,5 @@ import type { EnvironmentId as EnvironmentIdType } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; -import * as Option from "effect/Option"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; import { AsyncResult, Atom } from "effect/reactivity"; @@ -63,7 +62,7 @@ export function createEnvironmentCatalogAtoms( ); const catalogValueAtom = Atom.make((get) => - Option.getOrElse(AsyncResult.value(get(catalogAtom)), () => EMPTY_ENVIRONMENT_CATALOG_STATE), + AsyncResult.getOrElse(get(catalogAtom), () => EMPTY_ENVIRONMENT_CATALOG_STATE), ).pipe(Atom.withLabel("environment-catalog-value")); const pullRequestRoutingPermissionsAtom = runtime.atom( @@ -73,7 +72,7 @@ export function createEnvironmentCatalogAtoms( { initialValue: [] as ReadonlyArray }, ); const pullRequestRoutingPermissionsValueAtom = Atom.make((get) => - Option.getOrElse(AsyncResult.value(get(pullRequestRoutingPermissionsAtom)), () => []), + AsyncResult.getOrElse(get(pullRequestRoutingPermissionsAtom), () => []), ).pipe(Atom.withLabel("environment-pull-request-routing-permissions")); const setPullRequestRoutingPermission = createRuntimeCommand(runtime, { label: "environment-catalog:pull-request-routing-permission", @@ -104,7 +103,7 @@ export function createEnvironmentCatalogAtoms( ); const networkStatusValueAtom = Atom.make((get) => - Option.getOrElse(AsyncResult.value(get(networkStatusAtom)), () => "unknown" as const), + AsyncResult.getOrElse(get(networkStatusAtom), () => "unknown" as const), ).pipe(Atom.withLabel("environment-network-status-value")); const stateAtom = Atom.family((environmentId: EnvironmentIdType) => diff --git a/packages/client-runtime/src/state/olderSettledThreads.test.ts b/packages/client-runtime/src/state/olderSettledThreads.test.ts index e8c419f779d26..571a8fbaaad74 100644 --- a/packages/client-runtime/src/state/olderSettledThreads.test.ts +++ b/packages/client-runtime/src/state/olderSettledThreads.test.ts @@ -520,7 +520,7 @@ describe("createOlderSettledThreadAtoms", () => { yield* Queue.offer(replies, Effect.succeed({ ...found, snapshotSequence: 8 })); yield* until( search, - (result) => Option.getOrNull(AsyncResult.value(result))?.snapshotSequence === 8, + (result) => AsyncResult.getOrElse(result, () => null)?.snapshotSequence === 8, ); expect(requests).toEqual([input, input]); }), diff --git a/packages/client-runtime/src/state/olderSettledThreads.ts b/packages/client-runtime/src/state/olderSettledThreads.ts index 56dcd144c0b72..86f7f86f0d1bd 100644 --- a/packages/client-runtime/src/state/olderSettledThreads.ts +++ b/packages/client-runtime/src/state/olderSettledThreads.ts @@ -213,7 +213,7 @@ export function createOlderSettledThreadAtoms( ) => Atom.Atom>, ) { const shellStateValue = (state: AsyncResult.AsyncResult) => - Option.getOrNull(AsyncResult.value(state)); + AsyncResult.getOrElse(state, () => null); const countReadAtom = createEnvironmentQueryAtomFamily(runtime, { label: "environment-data:orchestration:older-settled-counts", diff --git a/packages/client-runtime/src/state/presentation.ts b/packages/client-runtime/src/state/presentation.ts index 3c3e2ef78b906..f3ffb03b0bcfe 100644 --- a/packages/client-runtime/src/state/presentation.ts +++ b/packages/client-runtime/src/state/presentation.ts @@ -77,8 +77,8 @@ export function createEnvironmentPresentationAtoms(input: { if (entry === undefined) { return null; } - const state = Option.getOrElse( - AsyncResult.value(get(input.stateAtom(environmentId))), + const state = AsyncResult.getOrElse( + get(input.stateAtom(environmentId)), () => AVAILABLE_CONNECTION_STATE, ); const previous = Option.getOrNull(get.self()); diff --git a/packages/client-runtime/src/state/pullRequests.test.ts b/packages/client-runtime/src/state/pullRequests.test.ts index 966c68dabd9e3..a8627e2d9977e 100644 --- a/packages/client-runtime/src/state/pullRequests.test.ts +++ b/packages/client-runtime/src/state/pullRequests.test.ts @@ -1430,15 +1430,11 @@ it.effect("updates cached labels after successful edits without rereading the ho registry.refresh(detail); yield* detailRefreshStarted.await; expect(registry.get(detail).waiting).toBe(true); - expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).labels).toEqual([ - addedLabel, - ]); + expect(AsyncResult.getOrThrow(registry.get(detail)).labels).toEqual([addedLabel]); yield* releaseDetailRefresh.open; yield* Effect.exit(AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true })); expect(AsyncResult.isFailure(registry.get(detail))).toBe(true); - expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).labels).toEqual([ - addedLabel, - ]); + expect(AsyncResult.getOrThrow(registry.get(detail)).labels).toEqual([addedLabel]); failDetail = false; registry.refresh(detail); expect( @@ -1562,7 +1558,7 @@ it.effect("publishes the accepted guide run before the follow-up read finishes", const result = yield* Effect.promise(() => atoms.generateReviewGuide.run(registry, target)); expect(result._tag).toBe("Success"); yield* refreshStarted.await; - expect(Option.getOrNull(AsyncResult.value(registry.get(query)))).toEqual(accepted); + expect(AsyncResult.getOrElse(registry.get(query), () => null)).toEqual(accepted); }), ), ); diff --git a/packages/client-runtime/src/state/pullRequests.ts b/packages/client-runtime/src/state/pullRequests.ts index 6b675f36a7858..ca5fb6d7a77d5 100644 --- a/packages/client-runtime/src/state/pullRequests.ts +++ b/packages/client-runtime/src/state/pullRequests.ts @@ -520,7 +520,7 @@ export function createPullRequestEnvironmentAtoms( Effect.sync(() => { const { reviewers, requested } = target.input; const candidatesAtom = reviewerCandidates(target); - const candidates = Option.getOrNull(AsyncResult.value(registry.get(candidatesAtom))); + const candidates = AsyncResult.getOrElse(registry.get(candidatesAtom), () => null); const selected = candidates?.candidates.filter((candidate) => reviewers.some( @@ -606,7 +606,7 @@ export function createPullRequestEnvironmentAtoms( Effect.sync(() => { const { labels, applied } = target.input; const candidatesAtom = labelCandidates(target); - const candidates = Option.getOrNull(AsyncResult.value(registry.get(candidatesAtom))); + const candidates = AsyncResult.getOrElse(registry.get(candidatesAtom), () => null); const names = new Set(labels); updateCached(registry, candidatesAtom, (value) => ({ ...value, diff --git a/packages/client-runtime/src/state/relayDiscovery.ts b/packages/client-runtime/src/state/relayDiscovery.ts index 34b8c662c8821..b31dd67ca9dad 100644 --- a/packages/client-runtime/src/state/relayDiscovery.ts +++ b/packages/client-runtime/src/state/relayDiscovery.ts @@ -1,5 +1,4 @@ import * as Effect from "effect/Effect"; -import * as Option from "effect/Option"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; import { AsyncResult, Atom } from "effect/reactivity"; @@ -19,8 +18,8 @@ export function createRelayEnvironmentDiscoveryAtoms( { initialValue: RelayEnvironmentDiscovery.EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE }, ); const stateValueAtom = Atom.make((get) => - Option.getOrElse( - AsyncResult.value(get(stateAtom)), + AsyncResult.getOrElse( + get(stateAtom), () => RelayEnvironmentDiscovery.EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE, ), ).pipe(Atom.withLabel("relay-environment-discovery-value")); diff --git a/packages/client-runtime/src/state/runtime.test.ts b/packages/client-runtime/src/state/runtime.test.ts index bb69334bc7870..963b3a7bfdeb7 100644 --- a/packages/client-runtime/src/state/runtime.test.ts +++ b/packages/client-runtime/src/state/runtime.test.ts @@ -1306,7 +1306,7 @@ describe("persisted environment queries", () => { ); const registry = yield* mountEnvironmentQuery(harness.atom); yield* Effect.result(readEnvironmentQuery(registry, harness.atom)); - expect(Option.getOrNull(AsyncResult.value(registry.get(harness.atom)))).toBe("cached"); + expect(AsyncResult.getOrElse(registry.get(harness.atom), () => null)).toBe("cached"); }), ), ); diff --git a/packages/client-runtime/src/state/runtime.ts b/packages/client-runtime/src/state/runtime.ts index 20054521a778a..fde1790d338a3 100644 --- a/packages/client-runtime/src/state/runtime.ts +++ b/packages/client-runtime/src/state/runtime.ts @@ -558,7 +558,7 @@ const refreshEveryUntilFinal = * reader of only this skips the refetches that changed nothing. */ export const selectEnvironmentQueryData = (result: AsyncResult.AsyncResult): A | null => - Option.getOrNull(AsyncResult.value(result)); + AsyncResult.getOrElse(result, () => null); type EnvironmentConnection = readonly [ SupervisorConnectionState, @@ -628,7 +628,7 @@ export function environmentSessionGenerationAtom( get.self<{ readonly session: RpcSession.RpcSession | null; readonly count: number }>(), () => ({ session: null, count: 0 }), ); - const connection = Option.getOrNull(AsyncResult.value(get(connectionAtom(id)))); + const connection = AsyncResult.getOrElse(get(connectionAtom(id)), () => null); if (connection === null || connection[0].phase !== "connected") return previous; const session = Option.getOrNull(connection[1]); return session === null || session === previous.session @@ -674,8 +674,9 @@ export function createEnvironmentQueryAtomFamily( | EnvironmentRegistry.EnvironmentNotRegisteredError | EnvironmentRpcUnavailableError >((get) => { - const connection = Option.getOrNull( - AsyncResult.value(get(connectionAtom(target.environmentId))), + const connection = AsyncResult.getOrElse( + get(connectionAtom(target.environmentId)), + () => null, ); // A refetch that returns equal content keeps the previous value's // references, so readers of the data skip re-rendering on idle polls. diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts index 892817d0b8067..3cb4f77325fa6 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -792,8 +792,9 @@ export function createServerEnvironmentAtoms( } let previousProviders: ServerConfig["providers"] | undefined; return Atom.make((get): ServerConfig | null => { - const projection = Option.getOrNull( - AsyncResult.value(get(configProjection({ environmentId, input: {} }))), + const projection = AsyncResult.getOrElse( + get(configProjection({ environmentId, input: {} })), + () => null, ); const config = resolveServerConfigValue( projection, diff --git a/packages/client-runtime/src/state/session.ts b/packages/client-runtime/src/state/session.ts index 0d7963e42e0cb..efdf0b37c0a09 100644 --- a/packages/client-runtime/src/state/session.ts +++ b/packages/client-runtime/src/state/session.ts @@ -1,3 +1,4 @@ +import { pipe } from "effect/Function"; import type { AuthSessionState, EnvironmentId, ServerConfig } from "@t3tools/contracts"; import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; @@ -104,10 +105,11 @@ function makeEnvironmentSessionAtoms( // createServerEnvironmentAtoms(...).configValueAtom instead. const initialConfigValueAtom = Atom.family((environmentId: EnvironmentId) => Atom.make((get): ServerConfig | null => - Option.getOrNull( - Option.getOrElse(AsyncResult.value(get(initialConfigAtom(environmentId))), () => - Option.none(), - ), + pipe( + get(initialConfigAtom(environmentId)), + AsyncResult.value, + Option.flatten, + Option.getOrNull, ), ).pipe(Atom.withLabel(`environment-config-value:${environmentId}`)), ); @@ -128,7 +130,7 @@ function makeEnvironmentSessionAtoms( const preparedConnectionValueAtom = Atom.family((environmentId: EnvironmentId) => Atom.make((get) => - Option.getOrElse(AsyncResult.value(get(preparedConnectionAtom(environmentId))), () => + AsyncResult.getOrElse(get(preparedConnectionAtom(environmentId)), () => Option.none(), ), ).pipe(Atom.withLabel(`environment-prepared-connection:${environmentId}`)), @@ -165,7 +167,7 @@ function makeEnvironmentSessionAtoms( const sessionStateValueAtom = Atom.family((environmentId: EnvironmentId) => Atom.make( (get): AuthSessionState | null => - Option.getOrNull(AsyncResult.value(get(sessionStateAtom(environmentId)))) ?? null, + AsyncResult.getOrElse(get(sessionStateAtom(environmentId)), () => null) ?? null, ).pipe(Atom.withLabel(`environment-session-state-value:${environmentId}`)), ); diff --git a/packages/client-runtime/src/state/shell.ts b/packages/client-runtime/src/state/shell.ts index 1a396cf8c74f6..bce13d315b425 100644 --- a/packages/client-runtime/src/state/shell.ts +++ b/packages/client-runtime/src/state/shell.ts @@ -596,7 +596,7 @@ export function createEnvironmentShellAtoms( const stateValueAtom = Atom.family((environmentId: EnvironmentId) => Atom.make((get) => - Option.getOrElse(AsyncResult.value(get(stateAtom(environmentId))), () => EMPTY_SHELL_STATE), + AsyncResult.getOrElse(get(stateAtom(environmentId)), () => EMPTY_SHELL_STATE), ).pipe(Atom.withLabel(`environment-shell-state-value:${environmentId}`)), ); diff --git a/packages/client-runtime/src/state/terminal.ts b/packages/client-runtime/src/state/terminal.ts index a86579edcb339..a39e47b1340b4 100644 --- a/packages/client-runtime/src/state/terminal.ts +++ b/packages/client-runtime/src/state/terminal.ts @@ -10,7 +10,6 @@ import { WS_METHODS, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; -import * as Option from "effect/Option"; import * as Stream from "effect/Stream"; import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity"; @@ -323,7 +322,7 @@ export function createTerminalSession( result: AsyncResult.AsyncResult, ) => { resizeRegistry = registry; - const buffer = Option.getOrElse(AsyncResult.value(result), () => EMPTY_TERMINAL_BUFFER_STATE); + const buffer = AsyncResult.getOrElse(result, () => EMPTY_TERMINAL_BUFFER_STATE); const status = result._tag === "Failure" ? "error" : buffer.status; if (status !== lastStatus) { lastStatus = status; diff --git a/packages/client-runtime/src/state/threadDetail.ts b/packages/client-runtime/src/state/threadDetail.ts index a53494ebc5929..0c93800378797 100644 --- a/packages/client-runtime/src/state/threadDetail.ts +++ b/packages/client-runtime/src/state/threadDetail.ts @@ -199,8 +199,8 @@ export function createEnvironmentThreadDetailAtoms( const threadStateValueAtomFamily = Atom.family((key: string) => { const ref = parseThreadKey(key); return Atom.make((get) => - Option.getOrElse( - AsyncResult.value(get(threadStateAtom(ref.environmentId, ref.threadId))), + AsyncResult.getOrElse( + get(threadStateAtom(ref.environmentId, ref.threadId)), () => EMPTY_ENVIRONMENT_THREAD_STATE, ), ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-state-value:${key}`)); diff --git a/packages/client-runtime/src/state/threadFamilies.ts b/packages/client-runtime/src/state/threadFamilies.ts index 0f40ac1939461..0f1bb8d9cd274 100644 --- a/packages/client-runtime/src/state/threadFamilies.ts +++ b/packages/client-runtime/src/state/threadFamilies.ts @@ -78,7 +78,7 @@ export function createThreadFamilyAtoms( ) => Atom.Atom>, ) { const shellStateValue = (state: AsyncResult.AsyncResult) => - Option.getOrNull(AsyncResult.value(state)); + AsyncResult.getOrElse(state, () => null); const generationAtom = Atom.family((environmentId: EnvironmentId) => Atom.make((get) => shellStateValue(get(shellStateAtom(environmentId)))?.generation ?? 0).pipe( Atom.withLabel(`environment-shell-generation:${environmentId}`), diff --git a/packages/client-runtime/src/state/threadSearch.ts b/packages/client-runtime/src/state/threadSearch.ts index 90a561f8cf783..caaebb016ecd4 100644 --- a/packages/client-runtime/src/state/threadSearch.ts +++ b/packages/client-runtime/src/state/threadSearch.ts @@ -150,7 +150,7 @@ export function createThreadSearchResultsAtomFamily(options: { }), ); isLoading ||= result.waiting; - const value = Option.getOrNull(AsyncResult.value(result)); + const value = AsyncResult.getOrElse(result, () => null); if (value !== null) { matches.push(...value.matches.map((match) => ({ ...match, environmentId }))); if (value.threads !== undefined && value.threads.length > 0) { diff --git a/packages/effect-codex-app-server/scripts/generate.ts b/packages/effect-codex-app-server/scripts/generate.ts index 6b1c8155830b3..23ce2e1edd360 100644 --- a/packages/effect-codex-app-server/scripts/generate.ts +++ b/packages/effect-codex-app-server/scripts/generate.ts @@ -1,5 +1,6 @@ #!/usr/bin/env node +import { pipe } from "effect/Function"; import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { make as makeJsonSchemaGenerator } from "@effect/openapi-generator/JsonSchemaGenerator"; @@ -636,15 +637,15 @@ const generateFiles = Effect.fn("generateFiles")(function* () { ); for (const [definitionName, definitionSchema] of Object.entries(parsed.definitions ?? {})) { - aggregateSchemas[localDefinitionNames.get(definitionName)!] = stripNullDefaults( - normalizeNullableTypes( - rewriteExternalRefs( - DefinitionOverrides[definitionName] ?? definitionSchema, - localDefinitionNames, - file.namespace, - exportNameByQualifiedName, - ), + aggregateSchemas[localDefinitionNames.get(definitionName)!] = pipe( + rewriteExternalRefs( + DefinitionOverrides[definitionName] ?? definitionSchema, + localDefinitionNames, + file.namespace, + exportNameByQualifiedName, ), + normalizeNullableTypes, + stripNullDefaults, ); } @@ -655,15 +656,15 @@ const generateFiles = Effect.fn("generateFiles")(function* () { } } - aggregateSchemas[file.exportName] = stripNullDefaults( - normalizeNullableTypes( - rewriteExternalRefs( - topLevelSchema, - localDefinitionNames, - file.namespace, - exportNameByQualifiedName, - ), + aggregateSchemas[file.exportName] = pipe( + rewriteExternalRefs( + topLevelSchema, + localDefinitionNames, + file.namespace, + exportNameByQualifiedName, ), + normalizeNullableTypes, + stripNullDefaults, ); } diff --git a/packages/effect-codex-app-server/src/replay.ts b/packages/effect-codex-app-server/src/replay.ts index cd99a4bb859e3..11ef80c02f5bf 100644 --- a/packages/effect-codex-app-server/src/replay.ts +++ b/packages/effect-codex-app-server/src/replay.ts @@ -1,3 +1,4 @@ +import { pipe } from "effect/Function"; import * as Cause from "effect/Cause"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -269,7 +270,11 @@ function sameFrame( ignoredConfigKeys: ReadonlySet = new Set(), ): boolean { const normalize = (frame: unknown) => - stableStringify(normalizeThreadRequest(normalizeReplayFrame(frame), ignoredConfigKeys)); + pipe( + normalizeReplayFrame(frame), + (request) => normalizeThreadRequest(request, ignoredConfigKeys), + stableStringify, + ); return normalize(left) === normalize(right); } diff --git a/packages/provider-core/src/server/handoffBudget.ts b/packages/provider-core/src/server/handoffBudget.ts index 06adb39b44689..4658bc44fc6d3 100644 --- a/packages/provider-core/src/server/handoffBudget.ts +++ b/packages/provider-core/src/server/handoffBudget.ts @@ -197,14 +197,16 @@ export function renderHistory( return [context, ...messages.map(renderHistoricalMessage)].join("\n\n"); } +const jsonByteLength = (value: unknown) => Buffer.byteLength(JSON.stringify(value)); + export function historyCost( messages: ReadonlyArray, context: string, ): number { return ( Math.max( - Buffer.byteLength(JSON.stringify(historyResponseItems(messages, context))), - Buffer.byteLength(JSON.stringify(renderHistory(messages, context))), + jsonByteLength(historyResponseItems(messages, context)), + jsonByteLength(renderHistory(messages, context)), ) + 256 ); } diff --git a/packages/shared/src/dpop.ts b/packages/shared/src/dpop.ts index 5fe9db02904fb..3e0a22128d3c5 100644 --- a/packages/shared/src/dpop.ts +++ b/packages/shared/src/dpop.ts @@ -1,3 +1,4 @@ +import { pipe } from "effect/Function"; import { p256 } from "@noble/curves/nist"; import { sha256 } from "@noble/hashes/sha2"; import * as Base64Url from "effect/encoding/Base64Url"; @@ -94,7 +95,12 @@ function dpopThumbprintInput(jwk: DpopPublicJwkType): string { } export function computeDpopJwkThumbprint(jwk: DpopPublicJwkType): string { - return Base64Url.encode(sha256(new TextEncoder().encode(dpopThumbprintInput(jwk)))); + return pipe( + dpopThumbprintInput(jwk), + (input) => new TextEncoder().encode(input), + sha256, + Base64Url.encode, + ); } export function computeDpopAccessTokenHash(accessToken: string): string { diff --git a/scripts/lib/public-config.ts b/scripts/lib/public-config.ts index ff8897efe5313..aa2f285ebd12c 100644 --- a/scripts/lib/public-config.ts +++ b/scripts/lib/public-config.ts @@ -1,4 +1,5 @@ // @effect-diagnostics nodeBuiltinImport:off - Build bootstrap reads optional root env files before an Effect runtime exists. +import { pipe } from "effect/Function"; import * as NodeFS from "node:fs"; import * as NodePath from "node:path"; import * as NodeURL from "node:url"; @@ -19,8 +20,11 @@ export interface T3CodePublicConfig { type Environment = Readonly>; -const REPO_ROOT = NodePath.dirname( - NodePath.dirname(NodePath.dirname(NodeURL.fileURLToPath(import.meta.url))), +const REPO_ROOT = pipe( + NodeURL.fileURLToPath(import.meta.url), + NodePath.dirname, + NodePath.dirname, + NodePath.dirname, ); export function loadRepoEnv({ From 10e709c33786682217ad3c4f9226ba6c13e5edd7 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Wed, 28 Oct 2026 03:20:15 -0500 Subject: [PATCH 205/817] fix(queued-message): avoid duplicate queued message entries (#26355) --- apps/mobile/src/lib/threadActivity.ts | 6 ++ .../src/orchestration-v2/Orchestrator.ts | 4 + .../SteeringCompletion.integration.test.ts | 87 +++++++++++++++++++ apps/web/src/session-logic.test.ts | 21 +++++ apps/web/src/session-logic.ts | 6 ++ 5 files changed, 124 insertions(+) diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index 03ea87da79672..9cdb3b6f8d815 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -2191,6 +2191,12 @@ export function buildThreadFeed( const item = row.item; if (turnItemIsWorkspacePreparation(item)) continue; if (item.type === "todo_list" || item.type === "checkpoint") continue; + if ( + item.type === "user_message" && + item.inputIntent === "queued_turn" && + item.status === "pending" + ) + continue; if (item.type === "user_message" && foldedAnswerMessageIds.has(item.messageId)) continue; if ( item.type === "run_interrupt_request" || diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index fa447ef165531..3f76bd6185eb7 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -1920,6 +1920,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }), providerThreadId: queuedProviderThread.id, inputIntent: "queued_turn", + status: "completed", startedAt: now, completedAt: now, updatedAt: now, @@ -5749,6 +5750,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio providerThreadId: queuedProviderThread.id, providerTurnId: null, inputIntent: "queued_turn", + status: "pending", + startedAt: null, + completedAt: null, updatedAt: now, }, }); diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 7481dcaa41b2c..d8ac4769e140f 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -339,6 +339,13 @@ it.effect.each( if (delivery !== null) { yield* Deferred.succeed(rejectSteer, undefined); yield* Fiber.join(delivery); + const requeued = yield* orchestrator.getThreadProjection(threadId); + const item = requeued.turnItems.find( + (item) => item.type === "user_message" && item.messageId === messageId, + ); + assert.equal(item?.status, "pending"); + assert.isNull(item?.startedAt); + assert.isNull(item?.completedAt); } if (timing === "before dispatch") yield* dispatchSteer; yield* worker.drain(); @@ -391,6 +398,14 @@ it.effect.each( ]); assert.equal(steerCalls, timing === "during delivery" ? 1 : 0); const final = yield* orchestrator.getThreadProjection(threadId); + if (!mailbox) { + assert.equal( + final.turnItems.find( + (item) => item.type === "user_message" && item.messageId === messageId, + )?.status, + "completed", + ); + } assert.equal(final.messages.filter((message) => message.id === messageId).length, 1); assert.equal( final.messages.find((message) => message.id === messageId)?.runId, @@ -669,6 +684,78 @@ it.effect("sends a selected held message once and preserves the remaining queue ), ); +it.effect("force sends multiple queued messages and can force send a requeued message again", () => + Effect.scoped( + Effect.gen(function* () { + const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness( + "multiple-promoted-messages", + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + const queue = (text: string, commandId: string) => + orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(commandId), + threadId, + messageId: MessageId.make(`message:${text}`), + text, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "user", + creationSource: "web", + }); + for (const text of ["one", "two", "remaining"]) yield* queue(text, `queue-${text}`); + const promote = Effect.fn("test.promote")(function* (text: string, commandId: string) { + const projection = yield* orchestrator.getThreadProjection(threadId); + const queued = projection.runs.find( + (run) => + run.status === "queued" && run.userMessageId === MessageId.make(`message:${text}`), + )!; + yield* orchestrator.dispatch({ + type: "queued-message.promote-to-steer", + commandId: CommandId.make(commandId), + threadId, + queuedRunId: queued.id, + targetRunId: started[0]!.runId, + }); + }); + yield* promote("one", "promote-one"); + yield* promote("two", "promote-two"); + yield* worker.drain(); + assert.deepEqual(steered, ["one", "two"]); + + // The completion-race fallback redispatches the same message into the queue. + yield* queue("one", "requeue-one"); + const requeued = yield* orchestrator.getThreadProjection(threadId); + assert.equal( + requeued.turnItems.find( + (item) => item.type === "user_message" && item.messageId === "message:one", + )?.status, + "pending", + ); + yield* promote("one", "promote-one-again"); + yield* worker.drain(); + assert.deepEqual(steered, ["one", "two", "one"]); + assert.lengthOf(started, 1); + const final = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual( + final.runs.filter((run) => run.status === "queued").map((run) => run.userMessageId), + [MessageId.make("message:remaining")], + ); + for (const text of ["one", "two"]) { + const items = final.turnItems.filter( + (item) => item.type === "user_message" && item.messageId === `message:${text}`, + ); + assert.lengthOf(items, 1); + assert.equal(items[0]?.status, "completed"); + } + }).pipe(Effect.provide(layer)); + }), + ), +); + it.effect("keeps a message queued when send now races with a running turn", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts index fd10c96aa1b24..de213de2f3c1c 100644 --- a/apps/web/src/session-logic.test.ts +++ b/apps/web/src/session-logic.test.ts @@ -672,6 +672,27 @@ describe("V2 session presentation", () => { scheduledTaskId: ScheduledTaskId.make("task-queued"), senderThreadId: ThreadId.make("thread-agent-sender"), } satisfies OrchestrationV2TurnItem; + for (const inputIntent of [ + "queued_turn", + "turn_start", + "steer", + "promoted_queued_to_steer", + ] as const) { + expect( + deriveTimelineEntriesFromVisibleTurnItems({ + visibleTurnItems: [ + { + position: 0, + visibility: "local", + sourceThreadId: projection.thread.id, + sourceItemId: dispatchedItem.id, + item: { ...dispatchedItem, inputIntent, status: "pending" }, + }, + ], + optimisticMessages: [], + }), + ).toHaveLength(inputIntent === "queued_turn" ? 0 : 1); + } const promotedEntries = deriveTimelineEntriesFromVisibleTurnItems({ visibleTurnItems: [ { diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index eb61b244075a3..362d9fb9451a4 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -603,6 +603,12 @@ export function deriveTimelineEntriesFromVisibleTurnItems( const { item } = row; if (turnItemIsWorkspacePreparation(item)) continue; if (item.type === "checkpoint") continue; + if ( + item.type === "user_message" && + item.inputIntent === "queued_turn" && + item.status === "pending" + ) + continue; if (item.type === "user_message" && foldedAnswerMessageIds.has(item.messageId)) continue; const createdAt = projectedItemCreatedAt(row); const attempt = resolveAttempt(item); From f17c9d202b38ea9a009a2d6dc3932e212bad4c24 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Wed, 28 Oct 2026 01:28:02 -0700 Subject: [PATCH 206/817] fix(models): new Claude threads default to Opus 5.5 (#26358) Co-authored-by: Claude Opus 5.5 --- apps/server/src/provider/model-manifest.json | 4 ++-- packages/contracts/src/model.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/server/src/provider/model-manifest.json b/apps/server/src/provider/model-manifest.json index 444c130c1ee11..b42932fcc6668 100644 --- a/apps/server/src/provider/model-manifest.json +++ b/apps/server/src/provider/model-manifest.json @@ -1,6 +1,6 @@ { "version": 1, - "updatedAt": "2026-10-27T23:47:46Z", + "updatedAt": "2026-10-28T08:10:39Z", "compatibility": [ { "driver": "codex", @@ -150,7 +150,7 @@ }, "claudeAgent": { "defaults": { - "chat": "claude-fable-5-1" + "chat": "claude-opus-5-5" }, "profiles": { "fable-5": { diff --git a/packages/contracts/src/model.ts b/packages/contracts/src/model.ts index f27d977767024..8027c90799dbc 100644 --- a/packages/contracts/src/model.ts +++ b/packages/contracts/src/model.ts @@ -140,7 +140,7 @@ export const MUSE_DEFAULT_MODEL = "default"; export const DEFAULT_MODEL_BY_PROVIDER: Partial> = { [CODEX_DRIVER_KIND]: DEFAULT_MODEL, - [CLAUDE_DRIVER_KIND]: "claude-fable-5-1", + [CLAUDE_DRIVER_KIND]: "claude-opus-5-5", [CURSOR_DRIVER_KIND]: "auto", // Product slug meaning the current session model, never an ACP model id. [GROK_DRIVER_KIND]: "grok-build", From a4e1986585771e80928cc50720a2532c52071d01 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Wed, 28 Oct 2026 01:46:46 -0700 Subject: [PATCH 207/817] docs: T3 Chat Pro and Premier raise the T3 Connect tunnel limit (#26366) Co-authored-by: Claude Opus 5.5 --- docs/user/faq.md | 6 +++++- docs/user/remote-access.md | 12 ++++++++++++ docs/user/t3-connect-troubleshooting.md | 6 ++++-- 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/docs/user/faq.md b/docs/user/faq.md index 354d0c63c3164..bb4713b5f25e8 100644 --- a/docs/user/faq.md +++ b/docs/user/faq.md @@ -25,7 +25,11 @@ Yes. ## How much does T3 Code cost? -Nothing. There's no way to pay us to use T3 Code. You bring your own sub. It is free and open source (MIT). You still pay your provider like you already do. T3 Connect is free too, for now. Every account can connect up to 3 machines running T3 Code. Phones and browsers that connect to them do not count. We don't want to charge for this, but if the bill gets unacceptable we may have to change course. If you hit limits or have issues, you can always fork it, self host, or use Tailscale. [Install](./install.md) +Nothing. There's no way to pay us to use T3 Code. You bring your own sub. It is free and open source (MIT). You still pay your provider like you already do. T3 Connect is free too, for now. Every account can connect up to 3 machines running T3 Code. Phones and browsers that connect to them do not count. Need more? Link a paid T3 Chat account. [More machines](#can-i-connect-more-than-3-machines-with-t3-connect) We don't want to charge for this, but if the bill gets unacceptable we may have to change course. If you hit limits or have issues, you can always fork it, self host, or use Tailscale. [Install](./install.md) + +## Can I connect more than 3 machines with T3 Connect? + +Yes. Link your T3 Chat account and T3 Connect raises your limit: up to 10 machines with T3 Chat Pro, or 100 with Premier. Open your account menu in T3 Code, go to **T3 Chat**, and select **Link T3 Chat**. Sign in to T3 Chat and approve. The free T3 Chat plan keeps the normal limit of 3. [More machines with T3 Chat](./remote-access.md#more-machines-with-t3-chat) ## Why is my Claude 5-hour limit draining so fast? diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index 835476864a1fc..b8f9553d95beb 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -32,6 +32,18 @@ connection. Pull request diffs and provider settings keep working after the previous credential expires. A failed renewal affects that request; it does not disconnect an otherwise healthy conversation. +### More machines with T3 Chat + +Each T3 Connect account can link up to 3 machines. Phones and browsers do not +count. A paid T3 Chat plan raises the limit to 10 machines with Pro, or 100 with +Premier. + +To link T3 Chat, open your account menu on the web or desktop app, go to +**T3 Chat**, and select **Link T3 Chat**. Sign in to T3 Chat in the window that +opens and approve. The new limit applies the next time you add a machine. If you +cancel or downgrade T3 Chat, machines you already linked stay linked, but you +cannot add more until you are under the limit again. + ## Pair over a LAN or private network Use direct pairing when the other device can reach the host's network address. diff --git a/docs/user/t3-connect-troubleshooting.md b/docs/user/t3-connect-troubleshooting.md index eaed689fb8c62..8c507a58e6894 100644 --- a/docs/user/t3-connect-troubleshooting.md +++ b/docs/user/t3-connect-troubleshooting.md @@ -112,7 +112,9 @@ T3 Connect does not have an active link between your account and the host. - **This device's sign-in expired, or the host no longer accepts this device.** Sign out of T3 Connect and sign in again. - **Your account reached its tunnel limit.** Remove an environment you do not - use from your T3 account's T3 Connect page, then restart T3 Code on the host. + use from your T3 account's T3 Connect page, or + [link a paid T3 Chat account](./remote-access.md#more-machines-with-t3-chat) + for a higher limit. Then restart T3 Code on the host. ## The clock is off @@ -129,7 +131,7 @@ This app needs a newer T3 Code on the host. Update T3 Code on the host. See | Error | Fix | | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | -| `environment_link_limit_exceeded` or managed tunnel limit | Remove an unused environment, then restart T3 Code on the host. | +| `environment_link_limit_exceeded` or managed tunnel limit | Remove an unused environment or link a paid T3 Chat account, then restart T3 Code on the host. | | `auth_invalid` or `invalid_bearer` | Run `t3 connect login`. If credentials were revoked, run `t3 connect logout`, then `t3 connect` again. Restart the server after signing in. | | Expired or invalid link proof | Check the host's date and time, update T3 Code, then restart it. | | HTTP 403 without a recognized error | Check relay access, proxies, and firewall rules. Keep any Cloudflare Ray ID for a bug report. | From dac58fa7a6f79d9d0a8053a3c0e2e43f2997e04d Mon Sep 17 00:00:00 2001 From: Utkarsh Patil <73941998+UtkarshUsername@users.noreply.github.com> Date: Wed, 28 Oct 2026 14:20:37 +0530 Subject: [PATCH 208/817] fix(web): use neutral indicators for inactive source control providers (#22778) --- .../src/components/settings/SourceControlSettings.tsx | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/apps/web/src/components/settings/SourceControlSettings.tsx b/apps/web/src/components/settings/SourceControlSettings.tsx index 7f7b0a90ebcc5..b519f7322c7d0 100644 --- a/apps/web/src/components/settings/SourceControlSettings.tsx +++ b/apps/web/src/components/settings/SourceControlSettings.tsx @@ -74,13 +74,13 @@ function isVcsNotReady(item: VcsDiscoveryItem | SourceControlProviderDiscoveryIt function authPresentation(auth: SourceControlProviderAuth): { readonly label: string; - readonly badge: "warning" | null; + readonly badge: "secondary" | null; } { if (auth.status === "authenticated") { return { label: "Authenticated", badge: null }; } if (auth.status === "unauthenticated") { - return { label: "Not authenticated", badge: "warning" }; + return { label: "Not authenticated", badge: "secondary" }; } return { label: "Status unknown", badge: null }; } @@ -98,8 +98,12 @@ function RedactedAccount(props: { readonly account: string | null }) { function itemStatusDot(item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem): string { if (isVcsNotReady(item)) return "bg-muted-foreground/35"; + if (isProviderDiscoveryItem(item)) { + return item.status === "available" && item.auth.status === "authenticated" + ? "bg-success" + : "bg-muted-foreground/35"; + } if (item.status !== "available") return "bg-warning"; - if (isProviderDiscoveryItem(item) && item.auth.status !== "authenticated") return "bg-warning"; return "bg-success"; } From cb4fe60a4b5a6598c0f73680bf242f5b85bb5279 Mon Sep 17 00:00:00 2001 From: Utkarsh Patil <73941998+UtkarshUsername@users.noreply.github.com> Date: Wed, 28 Oct 2026 14:21:06 +0530 Subject: [PATCH 209/817] fix(web): show the thread details tooltip (#24864) --- .../components/chat/PanelLayoutControls.tsx | 24 +++++++++---------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/apps/web/src/components/chat/PanelLayoutControls.tsx b/apps/web/src/components/chat/PanelLayoutControls.tsx index 11d22b1354e10..6750298402942 100644 --- a/apps/web/src/components/chat/PanelLayoutControls.tsx +++ b/apps/web/src/components/chat/PanelLayoutControls.tsx @@ -1,7 +1,7 @@ import { PanelBottomIcon, PanelRightIcon, SquareMenuIcon } from "lucide-react"; import { Maximize2, Minimize2 } from "lucide"; import { MorphIcon } from "~/components/MorphIcon"; -import { memo, type ReactElement, type ReactNode } from "react"; +import { memo, type ReactNode } from "react"; import { cn } from "~/lib/utils"; @@ -53,6 +53,7 @@ export const PanelLayoutControls = memo(function PanelLayoutControls({ ); - const threadPanelTooltip = (trigger: ReactElement) => ( + const threadPanelControl = ( - + }> + {threadPanelPresentation === "popover" ? ( + + ) : ( + threadPanelToggle + )} + Toggle thread details {threadPanelShortcutLabel ? ` (${threadPanelShortcutLabel})` : ""} @@ -78,13 +82,7 @@ export const PanelLayoutControls = memo(function PanelLayoutControls({ className="flex h-full shrink-0 items-center gap-1 [-webkit-app-region:no-drag]" data-panel-layout-controls > - {showThreadPanelControl - ? threadPanelPresentation === "popover" - ? threadPanelTooltip( - , - ) - : threadPanelTooltip(threadPanelToggle) - : null} + {showThreadPanelControl ? threadPanelControl : null} {showTerminalControl ? ( }> From 975b3dc56850d8a22dc90462219e53be95d8dcf7 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Wed, 28 Oct 2026 03:52:05 -0500 Subject: [PATCH 210/817] fix(client-runtime): keep subagent questions off parent threads (#26367) --- .../client-runtime/src/state/threadShell.test.ts | 16 +++++++++++++++- packages/client-runtime/src/state/threadShell.ts | 4 +++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/packages/client-runtime/src/state/threadShell.test.ts b/packages/client-runtime/src/state/threadShell.test.ts index ec40d5f679ec9..fda1054064f78 100644 --- a/packages/client-runtime/src/state/threadShell.test.ts +++ b/packages/client-runtime/src/state/threadShell.test.ts @@ -108,7 +108,7 @@ describe("v2 thread shell lists", () => { registry.dispose(); }); - it("counts a subagent question on its parent only while the subagent runs", () => { + it("keeps a live subagent question inside the parent without flagging its thread", () => { const { registry, threads, snapshotAtom } = makeHarness(); const root = v2ThreadShell; const child = { @@ -132,6 +132,10 @@ describe("v2 thread shell lists", () => { const dispose = registry.mount(inputs); registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [root, child] }); expect(registry.get(inputs).map((thread) => thread.id)).toEqual([child.id]); + expect( + registry.get(threads.threadShellAtom({ environmentId, threadId: root.id })) + ?.pendingSubagentRequest, + ).toBeNull(); registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [root, { ...child, status: "queued" as const }], @@ -272,6 +276,16 @@ describe("v2 thread shell lists", () => { `${remoteEnvironmentId}/${helper.id}`, ]); + registry.set(snapshotAtom(remoteEnvironmentId), { + ...v2ShellSnapshot, + threads: [ + task, + { ...helper, pendingRuntimeRequest: { ...approval, kind: "user_input" as const } }, + ], + }); + expect(registry.get(threads.threadShellAtom(parentRef))?.pendingSubagentRequest).toBeNull(); + expect(registry.get(inputs).map((thread) => thread.id)).toEqual([helper.id]); + // A task whose parent is gone there is listed on its own, as is one whose // parent's environment is switched off. registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [] }); diff --git a/packages/client-runtime/src/state/threadShell.ts b/packages/client-runtime/src/state/threadShell.ts index 69df72418c2d0..15718da1eca65 100644 --- a/packages/client-runtime/src/state/threadShell.ts +++ b/packages/client-runtime/src/state/threadShell.ts @@ -76,7 +76,7 @@ function subagentRequest(thread: OrchestrationV2ThreadShell): PendingSubagentReq } /** - * The threads to flag for a subagent's live question or approval, up its + * The threads to flag for a subagent's live approval, up its * subagent chain. `delegated` are tasks this environment's threads delegated * to linked environments, with what each one, or its own subagents, asks. */ @@ -94,6 +94,8 @@ function pendingSubagentRequestsByThread( request: PendingSubagentRequest, seen: Set, ) => { + // The coordinator answers child questions; only approvals need user attention. + if (request === "user_input") return; byId ??= new Map(threads.map((thread) => [thread.id, thread] as const)); let parentId = firstParentId; while (parentId !== null && !seen.has(parentId)) { From be2ea30d2b269f1526be3fd556bc5380b4dc01b3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 28 Oct 2026 02:01:37 -0700 Subject: [PATCH 211/817] fix(build): keep effect out of the public-config bootstrap (#26371) Co-authored-by: Claude Opus 5.5 --- scripts/lib/public-config.ts | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/scripts/lib/public-config.ts b/scripts/lib/public-config.ts index aa2f285ebd12c..7fe8d05386cd1 100644 --- a/scripts/lib/public-config.ts +++ b/scripts/lib/public-config.ts @@ -1,5 +1,4 @@ // @effect-diagnostics nodeBuiltinImport:off - Build bootstrap reads optional root env files before an Effect runtime exists. -import { pipe } from "effect/Function"; import * as NodeFS from "node:fs"; import * as NodePath from "node:path"; import * as NodeURL from "node:url"; @@ -20,12 +19,7 @@ export interface T3CodePublicConfig { type Environment = Readonly>; -const REPO_ROOT = pipe( - NodeURL.fileURLToPath(import.meta.url), - NodePath.dirname, - NodePath.dirname, - NodePath.dirname, -); +const REPO_ROOT = NodePath.resolve(NodeURL.fileURLToPath(import.meta.url), "../../.."); export function loadRepoEnv({ baseEnv = process.env, From 4c9c7d0bb65765232bbb41f83d3fd17ec5e3af66 Mon Sep 17 00:00:00 2001 From: "t3-code-bot[bot]" <269035359+t3-code-bot[bot]@users.noreply.github.com> Date: Wed, 28 Oct 2026 09:07:37 +0000 Subject: [PATCH 212/817] chore(mobile): bump app version to 2.2.0 Co-authored-by: codex --- apps/mobile/app.config.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index 6ea260eae4d9e..ea885f819984f 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -226,7 +226,7 @@ const config: ExpoConfig = { slug: "t3-code", platforms: ["ios", "android"], scheme: variant.scheme, - version: repoEnv.T3CODE_MOBILE_VERSION ?? "2.1.0", + version: repoEnv.T3CODE_MOBILE_VERSION ?? "2.2.0", runtimeVersion: { // Skip costly fingerprinting on dev launches; preview and production OTAs require matching native projects. policy: runtimeVersionPolicy, From c677d5fc45e6d585e52bca03244a0870c588a555 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Wed, 28 Oct 2026 02:22:53 -0700 Subject: [PATCH 213/817] fix(web): scroll-to-end button no longer jumps up and down (#26375) Co-authored-by: Claude Opus 5.5 --- .../chat/MessagesTimeline.browser.test.tsx | 23 +++++++++++++++++++ .../src/components/chat/MessagesTimeline.tsx | 6 +++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index 2c7aa332756cb..085fa23b2c49d 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -205,6 +205,29 @@ describe("MessagesTimeline messages", () => { expect(maxNestedCommits).toBeLessThan(20); }); + it("keeps reporting overflow while the composer inset changes", async () => { + setup(); + const props = baseProps(); + const overflowReports: boolean[] = []; + const replies = Array.from({ length: 40 }, (_, index) => + message(`Reply ${index}\n\n${"line\n\n".repeat(8)}`, { role: "assistant" }, `r-${index}`), + ); + const timeline = (inset: number) => ( + overflowReports.push(overflows)} + /> + ); + await using screen = await renderElement(timeline(110)); + await vi.waitFor(() => expect(overflowReports.at(-1)).toBe(true)); + overflowReports.length = 0; + // The resting composer resizes with overflow; a false report here flips it back. + await screen.rerender(timeline(148)); + expect(overflowReports).not.toContain(false); + }); + it("keeps the first and last message headings reachable from either end", async () => { setup(); const props = baseProps(); diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index c7a38de8fbed6..b74f9edd595c9 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -1144,7 +1144,9 @@ const ConversationTimeline = memo(function ConversationTimeline({ const canvas = useChatCanvas(); const registerTimeline = canvas?.registerTimeline; - const setTimelineList = (list: LegendListRef | null) => { + // Stable so the list attaches once per mount. A re-attach reports no overflow for a frame, + // which flips the resting composer, resizes it, and re-renders this list again. + const setTimelineList = useStableCallback((list: LegendListRef | null) => { listRef.current = list; const scrollNode: HTMLElement | null = list?.getScrollableNode() ?? null; registerTimeline?.(scrollNode); @@ -1190,7 +1192,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ listRef.current = null; registerTimeline?.(null); }; - }; + }); useThreadFindPositionReader({ threadKey: listIdentityKey, From 07f7f976097b56450364fe136aac9253f4f7d8e1 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Wed, 28 Oct 2026 02:45:20 -0700 Subject: [PATCH 214/817] ci(release): releases stop depending on npm and nodejs.org when nothing changed (#26362) Co-authored-by: Claude Opus 5.5 --- .github/actions/setup-ci-deps/action.yml | 20 +++++++++ .github/workflows/release-desktop.yml | 53 ++++++++++++++++++++---- 2 files changed, 66 insertions(+), 7 deletions(-) diff --git a/.github/actions/setup-ci-deps/action.yml b/.github/actions/setup-ci-deps/action.yml index e97365e2f3ec5..e9b7ae70a36ad 100644 --- a/.github/actions/setup-ci-deps/action.yml +++ b/.github/actions/setup-ci-deps/action.yml @@ -70,6 +70,9 @@ runs: INSTALL_ARGS: ${{ inputs.install-args }} run: | echo "path=$(vp pm cache dir)" >> "$GITHUB_OUTPUT" + metadata_dir="${pnpm_config_cache_dir:-$RUNNER_TEMP/pnpm-metadata}" + echo "pnpm_config_cache_dir=$metadata_dir" >> "$GITHUB_ENV" + echo "verified=$metadata_dir/lockfile-verified.jsonl" >> "$GITHUB_OUTPUT" if [[ -z "$INSTALL_ARGS" ]]; then echo "namespace=full" >> "$GITHUB_OUTPUT" else @@ -94,6 +97,16 @@ runs: pnpm-${{ steps.pnpm_store.outputs.namespace }}-v1-${{ runner.os }}-${{ runner.arch }}- pnpm-full-v1-${{ runner.os }}-${{ runner.arch }}- + # pnpm accepts an earlier pass for the same lockfile and policy at any age, so + # a cached record skips fetching registry metadata for every package. + - name: Restore lockfile verification + id: pnpm_verified + if: inputs.install == 'true' + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 + with: + path: ${{ steps.pnpm_store.outputs.verified }} + key: pnpm-verified-v1-${{ hashFiles('pnpm-lock.yaml', 'pnpm-workspace.yaml', 'package.json') }} + - name: Install dependencies if: inputs.install == 'true' shell: bash @@ -102,6 +115,13 @@ runs: # Unquoted so each filter is its own argument. run: vp install $INSTALL_ARGS + - name: Save lockfile verification + if: inputs.install == 'true' && steps.pnpm_verified.outputs.cache-hit != 'true' + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 + with: + path: ${{ steps.pnpm_store.outputs.verified }} + key: ${{ steps.pnpm_verified.outputs.cache-primary-key }} + # A filtered install that started from the current full store adds nothing # worth a second copy of it. - name: Save pnpm store diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml index 3383bb0e80bb8..359070e5482fb 100644 --- a/.github/workflows/release-desktop.yml +++ b/.github/workflows/release-desktop.yml @@ -254,21 +254,60 @@ jobs: if [[ "${{ inputs.version }}" =~ -nightly\.[0-9]{8}\.[0-9]+$ ]]; then brand=nightly; fi node scripts/apply-web-brand-assets.ts "$brand" apps/server/dist/client + - name: Resolve target Node.js for the CLI executable + id: target_node + if: inputs.cli_archive && inputs.platform == 'win' + shell: bash + run: echo "version=$(node -p 'require("./package.json").engines.node')" >> "$GITHUB_OUTPUT" + + # The download only changes with engines.node, so a cached copy keeps + # releases off nodejs.org, which stalls on the runners some days. + - name: Restore target Node.js for the CLI executable + id: target_node_cache + if: inputs.cli_archive && inputs.platform == 'win' + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 + with: + path: ${{ runner.temp }}/node-download + key: node-download-v${{ steps.target_node.outputs.version }}-win-${{ inputs.arch }} + # tsdown downloads the target Node with one fetch and no retry, and # nodejs.org drops that download often enough to fail releases. Seed - # tsdown's cache with a retried, checksum-verified copy instead. + # tsdown's cache with a retried, checksum-verified copy instead. A transfer + # under 100 KB/s for 30s counts as failed, so a stall retries. - name: Download target Node.js for the CLI executable + if: inputs.cli_archive && inputs.platform == 'win' && steps.target_node_cache.outputs.cache-hit != 'true' + shell: bash + env: + VERSION: ${{ steps.target_node.outputs.version }} + run: | + set -euo pipefail + name="node-v$VERSION-win-${{ inputs.arch }}" + dir="$RUNNER_TEMP/node-download" + mkdir -p "$dir" + fetch=(curl -fsSL --retry 5 --retry-all-errors --connect-timeout 10 --speed-limit 102400 --speed-time 30) + "${fetch[@]}" -o "$dir/$name.zip" "https://nodejs.org/dist/v$VERSION/$name.zip" + "${fetch[@]}" -o "$dir/SHASUMS256.txt" "https://nodejs.org/dist/v$VERSION/SHASUMS256.txt" + (cd "$dir" && grep " $name.zip\$" SHASUMS256.txt | sha256sum -c -) + + # Saved right away so a later failure in this job still keeps the download. + - name: Save target Node.js for the CLI executable + if: inputs.cli_archive && inputs.platform == 'win' && steps.target_node_cache.outputs.cache-hit != 'true' + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 + with: + path: ${{ runner.temp }}/node-download + key: ${{ steps.target_node_cache.outputs.cache-primary-key }} + + - name: Install target Node.js for the CLI executable if: inputs.cli_archive && inputs.platform == 'win' shell: bash + env: + VERSION: ${{ steps.target_node.outputs.version }} run: | set -euo pipefail - version="$(node -p 'require("./package.json").engines.node')" - name="node-v$version-win-${{ inputs.arch }}" - dest="${XDG_CACHE_HOME:-$HOME/.cache}/tsdown/node/v$version/win-${{ inputs.arch }}" + name="node-v$VERSION-win-${{ inputs.arch }}" dir="$RUNNER_TEMP/node-download" - mkdir -p "$dir" "$dest" - curl -fsSL --retry 5 --retry-all-errors -o "$dir/$name.zip" "https://nodejs.org/dist/v$version/$name.zip" - curl -fsSL --retry 5 --retry-all-errors -o "$dir/SHASUMS256.txt" "https://nodejs.org/dist/v$version/SHASUMS256.txt" + dest="${XDG_CACHE_HOME:-$HOME/.cache}/tsdown/node/v$VERSION/win-${{ inputs.arch }}" + mkdir -p "$dest" (cd "$dir" && grep " $name.zip\$" SHASUMS256.txt | sha256sum -c -) unzip -p "$dir/$name.zip" "$name/node.exe" > "$dest/node.exe" From 001d16e9699ad22863f065e5d9a3bd36305901fc Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Wed, 28 Oct 2026 02:59:59 -0700 Subject: [PATCH 215/817] feat(web): boring sidebar hides projects with no active threads (#26387) Co-authored-by: Claude Opus 5.5 --- apps/web/src/components/Sidebar.logic.test.ts | 17 +++++++++-------- apps/web/src/components/Sidebar.logic.ts | 7 ++++--- apps/web/src/components/Sidebar.tsx | 8 ++++++-- docs/user/thread-sidebar.md | 3 ++- 4 files changed, 21 insertions(+), 14 deletions(-) diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 93f3fb342fb9e..e4fa68a65201b 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -1368,7 +1368,7 @@ describe("sidebarFolderExpansionKeys", () => { }); describe("groupSidebarThreadsByProject", () => { - it("puts each thread in its project's folder and keeps empty projects", () => { + it("puts each thread in its project's folder and drops empty projects unless kept", () => { const remoteEnvironmentId = EnvironmentId.make("environment-remote"); const t3code = ProjectId.make("t3code"); const t3codeRemote = ProjectId.make("t3code-remote"); @@ -1392,21 +1392,22 @@ describe("groupSidebarThreadsByProject", () => { }, ]; - const folders = groupSidebarThreadsByProject(groups, [ + const threads = [ thread("a", localEnvironmentId, t3code), thread("orphan", localEnvironmentId, ProjectId.make("deleted")), thread("b", remoteEnvironmentId, t3codeRemote), - ]); - - expect( - folders.map((folder) => ({ + ]; + const summarize = (keepEmpty: boolean) => + groupSidebarThreadsByProject(groups, threads, keepEmpty).map((folder) => ({ projectKey: folder.group.projectKey, threads: folder.threads.map((entry) => entry.id), - })), - ).toEqual([ + })); + + expect(summarize(true)).toEqual([ { projectKey: "t3code", threads: ["a", "b"] }, { projectKey: "fleet", threads: [] }, ]); + expect(summarize(false)).toEqual([{ projectKey: "t3code", threads: ["a", "b"] }]); }); }); diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 7f7705573673c..efd8244f8c2b2 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -918,8 +918,8 @@ export function sidebarFolderExpansionKeys(group: { } /** - * Boring sidebar folders. Folders follow `groups` order and include empty - * projects so each one can start a thread. Threads keep their input order. + * Boring sidebar folders. Folders follow `groups` order and threads keep their + * input order. A project with no threads gets a folder only with `keepEmpty`. * A thread whose project is in no group has no folder and is left out. */ export function groupSidebarThreadsByProject< @@ -933,6 +933,7 @@ export function groupSidebarThreadsByProject< >( groups: readonly TGroup[], threads: readonly TThread[], + keepEmpty: boolean, ): Array<{ group: TGroup; threads: TThread[] }> { const folders = groups.map((group) => ({ group, threads: [] as TThread[] })); const folderByProject = new Map(); @@ -944,7 +945,7 @@ export function groupSidebarThreadsByProject< for (const thread of threads) { folderByProject.get(`${thread.environmentId}:${thread.projectId}`)?.threads.push(thread); } - return folders; + return keepEmpty ? folders : folders.filter((folder) => folder.threads.length > 0); } export type SidebarV2TopStatusKind = diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 6bda36fc85919..ddc7ad1e7bd29 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -399,6 +399,8 @@ function useSidebarThreads(input: { readonly routeRowThreadKey: string | null; // Set in boring mode: the project groups to fold active threads into, in order. readonly folderGroups: readonly SidebarProjectSnapshot[] | null; + // Keeps folders with no active threads, so a project the user filtered to can start one. + readonly keepEmptyFolders: boolean; }) { const { projectScopeKey, @@ -409,6 +411,7 @@ function useSidebarThreads(input: { delegatedUnderParent, routeRowThreadKey, folderGroups, + keepEmptyFolders: keepEmpty, } = input; // Folders already separate the work, so boring mode has no Working shelf. const workingShelfEnabled = @@ -495,7 +498,7 @@ function useSidebarThreads(input: { const projectFolders = folderGroups === null ? null - : groupSidebarThreadsByProject(folderGroups, activeThreads).map((folder) => { + : groupSidebarThreadsByProject(folderGroups, activeThreads, keepEmpty).map((folder) => { const collapsed = !resolveProjectExpanded( projectExpandedById, sidebarFolderExpansionKeys(folder.group), @@ -1271,6 +1274,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ? projectGroups : scopedProjectGroups : null, + keepEmptyFolders: scopedProjectGroups.length > 0, }); // Ranked across environments as the palette ranks them, so one @@ -1841,7 +1845,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const key = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); return { kind: "thread", key, section }; }); - // Boring mode keeps empty project folders, so each can start a thread. + // Boring mode keeps a project the user filtered to, so it can start a thread. if ( !hasProjectFolders && pinnedThreads.length + diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index b5373749a4956..ce16b9df0374b 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -142,7 +142,8 @@ cannot drag or move threads within it. Your saved order returns when you turn it ### Group threads by project (beta) Turn on **Settings → Labs → Boring sidebar (group by project)** on web and desktop to put active -threads in a folder for each project. Click a folder to open or close it. A closed folder shows how +threads in a folder for each project. A project with no active threads has no folder until you +pick it in the project filter. Click a folder to open or close it. A closed folder shows how many threads it holds, and a dot when one of them needs you. Use the pen button on a folder, or right-click it, to start a thread in that project. Pinned threads stay above the folders, and Snoozed and Settled stay below them. In this mode you cannot drag threads, and the Working section From 9f33a1c8361e18f553b387cbb5d3c2c62d56f8ba Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Wed, 28 Oct 2026 03:04:40 -0700 Subject: [PATCH 216/817] feat(web): show T3 Connect tunnel usage and push full accounts to T3 Chat (#26369) Co-authored-by: Claude Opus 5.5 --- apps/web/src/cloud/managedRelayState.ts | 58 ++++++++- .../useCloudLinkController.browser.test.tsx | 42 ++++++- apps/web/src/cloud/useCloudLinkController.ts | 28 ++++- .../clerk/T3ChatUserProfilePage.tsx | 99 ++++----------- .../clerk/T3ConnectAccountPages.tsx | 8 +- .../clerk/T3ConnectUserProfilePage.tsx | 57 ++++++++- .../web/src/components/clerk/useT3ChatLink.ts | 76 +++++++++++ .../cloud/ConnectOnboardingDialog.tsx | 42 +++++++ apps/web/src/components/cloud/TunnelUsage.tsx | 118 ++++++++++++++++++ .../settings/SavedEnvironmentRows.tsx | 60 ++++++++- .../src/components/settings/settingsSearch.ts | 2 +- .../environments/ManagedTunnelLimits.test.ts | 6 +- .../src/environments/ManagedTunnelLimits.ts | 3 +- packages/contracts/src/relay.ts | 2 + 14 files changed, 506 insertions(+), 95 deletions(-) create mode 100644 apps/web/src/components/clerk/useT3ChatLink.ts create mode 100644 apps/web/src/components/cloud/TunnelUsage.tsx diff --git a/apps/web/src/cloud/managedRelayState.ts b/apps/web/src/cloud/managedRelayState.ts index f562373463e1b..c5f7536305337 100644 --- a/apps/web/src/cloud/managedRelayState.ts +++ b/apps/web/src/cloud/managedRelayState.ts @@ -12,10 +12,12 @@ import { createAtomCommandScheduler, createRuntimeCommand, } from "@t3tools/client-runtime/state/runtime"; -import type { - RelayClientDeviceRecord, - RelayClientEnvironmentRecord, - RelayT3ChatLinkResponse, +import { + DEFAULT_MANAGED_TUNNEL_LIMIT, + T3CHAT_PLAN_TUNNEL_LIMITS, + type RelayClientDeviceRecord, + type RelayClientEnvironmentRecord, + type RelayT3ChatLinkResponse, } from "@t3tools/contracts/relay"; import type { EnvironmentId } from "@t3tools/contracts"; import * as Context from "effect/Context"; @@ -144,3 +146,51 @@ export function useManagedRelayDevices() { refresh, }; } + +/** How this account can raise its tunnel cap: link T3 Chat, or upgrade the linked plan. */ +export type ManagedTunnelUpgrade = "link" | "pro" | "premier" | null; + +// Mirrors the relay's cap without manual overrides, which the relay does not expose. +function managedTunnelCap(t3Chat: RelayT3ChatLinkResponse): { + readonly limit: number; + readonly upgrade: ManagedTunnelUpgrade; +} { + if (!t3Chat.available) return { limit: DEFAULT_MANAGED_TUNNEL_LIMIT, upgrade: null }; + switch (t3Chat.link?.plan) { + case "premier": + return { limit: T3CHAT_PLAN_TUNNEL_LIMITS.premier, upgrade: null }; + case "pro": + return { limit: T3CHAT_PLAN_TUNNEL_LIMITS.pro, upgrade: "premier" }; + case "free": + return { limit: DEFAULT_MANAGED_TUNNEL_LIMIT, upgrade: "pro" }; + case undefined: + return { limit: DEFAULT_MANAGED_TUNNEL_LIMIT, upgrade: "link" }; + } +} + +/** Refetches the account's environments and T3 Chat plan after a tunnel changes. */ +export function refreshManagedTunnelUsage() { + const accountId = appAtomRegistry.get(managedRelaySessionAtom)?.accountId; + if (!accountId) return; + managedRelayQueryManager.refreshEnvironments(appAtomRegistry, accountId); + managedRelayQueryManager.refreshT3ChatLink(appAtomRegistry, accountId); +} + +/** Managed tunnels on this account and its cap. Null fields are still loading or failed. */ +export function useManagedTunnelUsage() { + const environments = useManagedRelayEnvironments(); + const t3Chat = useManagedRelayT3ChatLink(); + const used = + environments.accountId === null + ? null + : (environments.data?.filter( + (environment) => environment.endpoint.providerKind === "cloudflare_tunnel", + ).length ?? null); + const cap = t3Chat.accountId !== null && t3Chat.data ? managedTunnelCap(t3Chat.data) : null; + return { + used, + limit: cap?.limit ?? null, + upgrade: cap?.upgrade ?? null, + refresh: refreshManagedTunnelUsage, + }; +} diff --git a/apps/web/src/cloud/useCloudLinkController.browser.test.tsx b/apps/web/src/cloud/useCloudLinkController.browser.test.tsx index 514d0bdd08039..5884ee5c19df4 100644 --- a/apps/web/src/cloud/useCloudLinkController.browser.test.tsx +++ b/apps/web/src/cloud/useCloudLinkController.browser.test.tsx @@ -4,7 +4,12 @@ import { EnvironmentId, type EnvironmentCloudLinkStateResult, } from "@t3tools/contracts"; -import type { RelayManagedEndpointProviderKind } from "@t3tools/contracts/relay"; +import { ManagedRelay } from "@t3tools/client-runtime/relay"; +import { + RelayEnvironmentLinkLimitExceededError, + type RelayManagedEndpointProviderKind, +} from "@t3tools/contracts/relay"; +import * as Cause from "effect/Cause"; import { AsyncResult } from "effect/reactivity"; import { useLayoutEffect } from "react"; import { describe, expect, it, vi } from "vite-plus/test"; @@ -88,6 +93,7 @@ vi.mock(import("./publicConfig"), async (original) => ({ resolveRelayClerkTokenOptions: () => ({}) as never, })); +import { CloudEnvironmentLinkError } from "./linkEnvironment"; import { useCloudLinkController, type CloudLinkDesiredState } from "./useCloudLinkController"; const target = { @@ -125,9 +131,8 @@ async function mountController() { />, ); return Object.assign(screen, { - get controller() { - return controller; - }, + // Object.assign would copy a getter's value once, so read the latest render through a function. + controller: () => controller, async reconcile(desired: CloudLinkDesiredState) { let succeeded = false; await act(async () => { @@ -225,4 +230,33 @@ describe("useCloudLinkController", () => { expect(testState.link).not.toHaveBeenCalled(); expect(testState.preferences).not.toHaveBeenCalled(); }); + + it("reports a relay tunnel cap refusal as tunnelLimit instead of an error", async () => { + using _setup = setup(); + testState.snapshot = { ...linkedState, linked: false, managedTunnelActive: false }; + testState.link.mockResolvedValueOnce( + AsyncResult.failure( + Cause.fail( + new CloudEnvironmentLinkError({ + message: "environment-links failed", + cause: new ManagedRelay.ManagedRelayRequestFailedError({ + action: "link relay environment", + cause: null, + relayError: new RelayEnvironmentLinkLimitExceededError({ + code: "environment_link_limit_exceeded", + maxTunnels: 3, + traceId: "trace-1", + }), + }), + }), + ), + ), + ); + await using screen = await mountController(); + + expect(await screen.reconcile({ managedTunnel: true, publish: false })).toBe(false); + expect(screen.controller()?.tunnelLimit).toBe(3); + expect(screen.controller()?.operationError).toBeNull(); + expect(testState.toast).not.toHaveBeenCalled(); + }); }); diff --git a/apps/web/src/cloud/useCloudLinkController.ts b/apps/web/src/cloud/useCloudLinkController.ts index 69f3ac70a7515..1ae60b8c38382 100644 --- a/apps/web/src/cloud/useCloudLinkController.ts +++ b/apps/web/src/cloud/useCloudLinkController.ts @@ -7,18 +7,22 @@ import { AuthRelayWriteScope, type EnvironmentCloudLinkStateResult, } from "@t3tools/contracts"; +import { ManagedRelay } from "@t3tools/client-runtime/relay"; import type { RelayManagedEndpointProviderKind } from "@t3tools/contracts/relay"; import { isAtomCommandInterrupted, settlePromise, squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; +import * as Schema from "effect/Schema"; import { useState } from "react"; import { toastManager } from "../components/ui/toast"; import { relayEnvironmentDiscovery } from "../state/relay"; import { readEnvironmentScope } from "../state/session"; import { useAtomCommand } from "../state/use-atom-command"; +import { CloudEnvironmentLinkError } from "./linkEnvironment"; +import { refreshManagedTunnelUsage } from "./managedRelayState"; import { linkPrimaryEnvironment as linkPrimaryEnvironmentAtom, unlinkPrimaryEnvironment as unlinkPrimaryEnvironmentAtom, @@ -46,6 +50,18 @@ function isManagedTunnelActive( ); } +const isManagedRelayRequestFailedError = Schema.is(ManagedRelay.ManagedRelayRequestFailedError); + +/** The account's tunnel cap when the relay refused a new tunnel for being at it. */ +function tunnelLimitFromLinkFailure(cause: unknown): number | null { + if (!(cause instanceof CloudEnvironmentLinkError)) return null; + const relayCause = cause.cause; + if (!isManagedRelayRequestFailedError(relayCause)) return null; + return relayCause.relayError?._tag === "RelayEnvironmentLinkLimitExceededError" + ? relayCause.relayError.maxTunnels + : null; +} + export function useCloudLinkController() { const { getToken, isSignedIn } = useAuth(); const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, { @@ -68,6 +84,7 @@ export function useCloudLinkController() { ? relayEnvironments.get(primaryEnvironmentId)?.environment.endpoint.providerKind : undefined; const [operationError, setOperationError] = useState(null); + const [tunnelLimit, setTunnelLimit] = useState(null); const reportUpdateFailure = (cause: unknown) => { const message = cause instanceof Error ? cause.message : "Could not update T3 Connect access."; @@ -100,6 +117,7 @@ export function useCloudLinkController() { const reconcileCloudState = async (desired: CloudLinkDesiredState): Promise => { setOperationError(null); + setTunnelLimit(null); const target = primaryCloudLinkState.target; if (!target) { reportUpdateFailure(new Error("Local environment is not ready yet.")); @@ -138,6 +156,7 @@ export function useCloudLinkController() { target, clerkToken: tokenResult._tag === "Success" ? (tokenResult.value ?? null) : null, }); + refreshManagedTunnelUsage(); if (unlinkResult._tag === "Failure") { if (!isAtomCommandInterrupted(unlinkResult)) { reportUpdateFailure(squashAtomCommandFailure(unlinkResult)); @@ -168,9 +187,15 @@ export function useCloudLinkController() { clerkToken, mode: desired.managedTunnel ? "managed" : "publish_only", }); + // Any link attempt can change the account's tunnel count. + refreshManagedTunnelUsage(); if (linkResult._tag === "Failure") { if (!isAtomCommandInterrupted(linkResult)) { - reportUpdateFailure(squashAtomCommandFailure(linkResult)); + const cause = squashAtomCommandFailure(linkResult); + // The caller shows an upgrade prompt instead of an error. + const limit = tunnelLimitFromLinkFailure(cause); + if (limit === null) reportUpdateFailure(cause); + else setTunnelLimit(limit); } primaryCloudLinkState.refresh(); return false; @@ -215,6 +240,7 @@ export function useCloudLinkController() { publishAgentActivity, holdWebhooksWhileOffline, operationError, + tunnelLimit, reconcileCloudState, }; } diff --git a/apps/web/src/components/clerk/T3ChatUserProfilePage.tsx b/apps/web/src/components/clerk/T3ChatUserProfilePage.tsx index 689e04661127c..0a1bbe57abbbd 100644 --- a/apps/web/src/components/clerk/T3ChatUserProfilePage.tsx +++ b/apps/web/src/components/clerk/T3ChatUserProfilePage.tsx @@ -1,95 +1,43 @@ -import { findErrorTraceId } from "@t3tools/client-runtime/errors"; -import { - isAtomCommandInterrupted, - squashAtomCommandFailure, -} from "@t3tools/client-runtime/state/runtime"; import { T3CHAT_PLAN_TUNNEL_LIMITS, type RelayT3ChatLink } from "@t3tools/contracts/relay"; import { MessageSquareIcon } from "lucide-react"; -import { useState } from "react"; +import type { ReactNode } from "react"; -import { - createManagedRelayT3ChatLinkRequestCommand, - unlinkManagedRelayT3ChatCommand, - useManagedRelayT3ChatLink, -} from "../../cloud/managedRelayState"; -import { readLocalApi } from "../../localApi"; -import { useAtomCommand } from "../../state/use-atom-command"; +import { useManagedTunnelUsage } from "../../cloud/managedRelayState"; +import { T3CHAT_SUBSCRIPTION_URL, TunnelUsageMeter } from "../cloud/TunnelUsage"; import { Button } from "../ui/button"; -import { toastManager } from "../ui/toast"; import { ClerkUserProfilePage, ClerkUserProfileRefreshButton, ClerkUserProfileRow, } from "./ClerkUserProfilePage"; +import { useT3ChatLink } from "./useT3ChatLink"; -function planLabel(link: RelayT3ChatLink): string { +const upgradeLink = ( + + Upgrade on T3 Chat + +); + +function planLabel(link: RelayT3ChatLink): ReactNode { switch (link.plan) { case "premier": return `Premier · up to ${T3CHAT_PLAN_TUNNEL_LIMITS.premier} tunnels`; case "pro": - return `Pro · up to ${T3CHAT_PLAN_TUNNEL_LIMITS.pro} tunnels, or ${T3CHAT_PLAN_TUNNEL_LIMITS.premier} with Premier`; + return ( + <> + Pro · up to {T3CHAT_PLAN_TUNNEL_LIMITS.pro} tunnels. {upgradeLink} to Premier for{" "} + {T3CHAT_PLAN_TUNNEL_LIMITS.premier}. + + ); case "free": - return "Upgrade on T3 Chat for more tunnels"; + return <>{upgradeLink} for more tunnels; } } -function reportFailure(title: string, cause: unknown) { - const traceId = findErrorTraceId(cause); - toastManager.add({ - type: "error", - title, - description: cause instanceof Error ? cause.message : "Try again.", - data: traceId - ? { - secondaryActionProps: { - children: "Copy trace ID", - onClick: () => void navigator.clipboard?.writeText(traceId), - }, - } - : undefined, - }); -} - /** Links a T3 Chat account so paid subscribers get more tunnels. */ export function T3ChatUserProfilePage() { - const linkState = useManagedRelayT3ChatLink(); - const createLinkRequest = useAtomCommand(createManagedRelayT3ChatLinkRequestCommand, { - reportFailure: false, - }); - const unlink = useAtomCommand(unlinkManagedRelayT3ChatCommand, { reportFailure: false }); - const [pending, setPending] = useState<"link" | "unlink" | null>(null); - // Kept so a blocked popup still leaves the user a link to open. - const [linkUrl, setLinkUrl] = useState(null); - - const handleLink = async () => { - const accountId = linkState.accountId; - if (!accountId || pending) return; - setPending("link"); - const result = await createLinkRequest({ accountId }); - if (result._tag === "Success") { - setLinkUrl(result.value); - await readLocalApi() - ?.shell.openExternal(result.value) - .catch(() => undefined); - } else if (!isAtomCommandInterrupted(result)) { - reportFailure("Could not start linking", squashAtomCommandFailure(result)); - } - setPending(null); - }; - - const handleUnlink = async () => { - const accountId = linkState.accountId; - if (!accountId || pending) return; - setPending("unlink"); - const result = await unlink({ accountId }); - if (result._tag === "Success") { - setLinkUrl(null); - linkState.refresh(); - } else if (!isAtomCommandInterrupted(result)) { - reportFailure("Could not unlink T3 Chat", squashAtomCommandFailure(result)); - } - setPending(null); - }; + const { linkState, pending, linkUrl, link: handleLink, unlink: handleUnlink } = useT3ChatLink(); + const usage = useManagedTunnelUsage(); const data = linkState.data; const link = data?.link ?? null; @@ -102,7 +50,7 @@ export function T3ChatUserProfilePage() { } > @@ -160,6 +108,11 @@ export function T3ChatUserProfilePage() { )} + {usage.used !== null && usage.limit !== null ? ( +
  • + +
  • + ) : null} )} diff --git a/apps/web/src/components/clerk/T3ConnectAccountPages.tsx b/apps/web/src/components/clerk/T3ConnectAccountPages.tsx index 85dcc7dd255c4..3e804bdf68d61 100644 --- a/apps/web/src/components/clerk/T3ConnectAccountPages.tsx +++ b/apps/web/src/components/clerk/T3ConnectAccountPages.tsx @@ -28,22 +28,24 @@ export const T3_CONNECT_ACCOUNT_PAGES = [ }, ] as const; +export type T3ConnectAccountPageUrl = (typeof T3_CONNECT_ACCOUNT_PAGES)[number]["url"]; + type PortalTargets = Readonly>; /** Keep portals rendered while the modal can open; Clerk owns the custom-page DOM nodes. */ export function useT3ConnectAccountPage(): { - readonly open: (() => void) | null; + readonly open: ((page?: T3ConnectAccountPageUrl) => void) | null; readonly portals: ReactNode; } { const clerk = useClerk(); const { isSignedIn } = useAuth(); const [targets, setTargets] = useState({}); - const open = () => { + const open = (page: T3ConnectAccountPageUrl = "t3-connect") => { const setTarget = (key: string, element: HTMLDivElement | undefined) => setTargets((current) => ({ ...current, [key]: element })); clerk.openUserProfile({ - __experimental_startPath: "/t3-connect", + __experimental_startPath: `/${page}`, customPages: T3_CONNECT_ACCOUNT_PAGES.map((page) => ({ label: page.label, url: page.url, diff --git a/apps/web/src/components/clerk/T3ConnectUserProfilePage.tsx b/apps/web/src/components/clerk/T3ConnectUserProfilePage.tsx index d0342005e6fd2..be59127723c2d 100644 --- a/apps/web/src/components/clerk/T3ConnectUserProfilePage.tsx +++ b/apps/web/src/components/clerk/T3ConnectUserProfilePage.tsx @@ -11,9 +11,11 @@ import { useRef, useState } from "react"; import { deregisterManagedRelayEnvironmentCommand, useManagedRelayEnvironments, + useManagedTunnelUsage, } from "../../cloud/managedRelayState"; import { useAtomCommand } from "../../state/use-atom-command"; -import { Button } from "../ui/button"; +import { T3CHAT_SUBSCRIPTION_URL, TunnelUsageMeter, tunnelUpgradeCopy } from "../cloud/TunnelUsage"; +import { Button, InlineButton } from "../ui/button"; import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible"; import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty"; import { toastManager } from "../ui/toast"; @@ -22,6 +24,7 @@ import { ClerkUserProfileRefreshButton, ClerkUserProfileRow, } from "./ClerkUserProfilePage"; +import { useT3ChatLink } from "./useT3ChatLink"; const linkedAtFormatter = new Intl.DateTimeFormat(undefined, { dateStyle: "medium" }); @@ -110,6 +113,53 @@ function T3ConnectEnvironmentRow(props: { ); } +function T3ConnectTunnelUsage() { + const usage = useManagedTunnelUsage(); + const t3Chat = useT3ChatLink(); + if (usage.used === null || usage.limit === null) return null; + return ( +
    + + {usage.upgrade ? ( +

    + {usage.upgrade === "link" && t3Chat.linkUrl ? ( + <> + Confirm on{" "} + + t3.chat + + , then select Refresh. + + ) : ( + <> + {tunnelUpgradeCopy(usage.upgrade)}{" "} + {usage.upgrade === "link" ? ( + void t3Chat.link()}> + {t3Chat.pending === "link" ? "Opening…" : "Link T3 Chat"} + + ) : ( + + Upgrade on T3 Chat + + )} + + )} +

    + ) : null} +
    + ); +} + export function T3ConnectUserProfilePage() { const environmentsState = useManagedRelayEnvironments(); const deregisterEnvironment = useAtomCommand(deregisterManagedRelayEnvironmentCommand, { @@ -188,6 +238,8 @@ export function T3ConnectUserProfilePage() { (environment) => removedEnvironmentLinkedAt.get(environment.environmentId) !== environment.linkedAt, ); + const usage = useManagedTunnelUsage(); + const refreshAll = usage.refresh; const isInitialLoad = !environmentsState.accountId || (environmentsState.data === null && !environmentsState.error); @@ -199,11 +251,12 @@ export function T3ConnectUserProfilePage() { } >
    + {environmentsState.error ? (

    diff --git a/apps/web/src/components/clerk/useT3ChatLink.ts b/apps/web/src/components/clerk/useT3ChatLink.ts new file mode 100644 index 0000000000000..66d2267c62682 --- /dev/null +++ b/apps/web/src/components/clerk/useT3ChatLink.ts @@ -0,0 +1,76 @@ +import { findErrorTraceId } from "@t3tools/client-runtime/errors"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import { useState } from "react"; + +import { + createManagedRelayT3ChatLinkRequestCommand, + unlinkManagedRelayT3ChatCommand, + useManagedRelayT3ChatLink, +} from "../../cloud/managedRelayState"; +import { readLocalApi } from "../../localApi"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { toastManager } from "../ui/toast"; + +function reportFailure(title: string, cause: unknown) { + const traceId = findErrorTraceId(cause); + toastManager.add({ + type: "error", + title, + description: cause instanceof Error ? cause.message : "Try again.", + data: traceId + ? { + secondaryActionProps: { + children: "Copy trace ID", + onClick: () => void navigator.clipboard?.writeText(traceId), + }, + } + : undefined, + }); +} + +/** Starts and removes the T3 Chat link that raises the T3 Connect tunnel cap. */ +export function useT3ChatLink() { + const linkState = useManagedRelayT3ChatLink(); + const createLinkRequest = useAtomCommand(createManagedRelayT3ChatLinkRequestCommand, { + reportFailure: false, + }); + const unlinkCommand = useAtomCommand(unlinkManagedRelayT3ChatCommand, { reportFailure: false }); + const [pending, setPending] = useState<"link" | "unlink" | null>(null); + // Kept so a blocked popup still leaves the user a link to open. + const [linkUrl, setLinkUrl] = useState(null); + + const link = async () => { + const accountId = linkState.accountId; + if (!accountId || pending) return; + setPending("link"); + const result = await createLinkRequest({ accountId }); + if (result._tag === "Success") { + setLinkUrl(result.value); + await readLocalApi() + ?.shell.openExternal(result.value) + .catch(() => undefined); + } else if (!isAtomCommandInterrupted(result)) { + reportFailure("Could not start linking", squashAtomCommandFailure(result)); + } + setPending(null); + }; + + const unlink = async () => { + const accountId = linkState.accountId; + if (!accountId || pending) return; + setPending("unlink"); + const result = await unlinkCommand({ accountId }); + if (result._tag === "Success") { + setLinkUrl(null); + linkState.refresh(); + } else if (!isAtomCommandInterrupted(result)) { + reportFailure("Could not unlink T3 Chat", squashAtomCommandFailure(result)); + } + setPending(null); + }; + + return { linkState, pending, linkUrl, link, unlink }; +} diff --git a/apps/web/src/components/cloud/ConnectOnboardingDialog.tsx b/apps/web/src/components/cloud/ConnectOnboardingDialog.tsx index 8daf67714cc45..2e6bb927d69dc 100644 --- a/apps/web/src/components/cloud/ConnectOnboardingDialog.tsx +++ b/apps/web/src/components/cloud/ConnectOnboardingDialog.tsx @@ -9,6 +9,7 @@ import { ConnectOnboardingOptOutSchema, EMPTY_CONNECT_ONBOARDING_OPT_OUT_STATE, } from "~/cloud/connectOnboarding"; +import { useManagedTunnelUsage } from "~/cloud/managedRelayState"; import { hasCloudPublicConfig } from "~/cloud/publicConfig"; import { useCloudLinkController } from "~/cloud/useCloudLinkController"; import { useLocalStorage } from "~/hooks/useLocalStorage"; @@ -19,7 +20,12 @@ import { usePrimaryEnvironmentId, } from "~/state/environments"; import { environmentSession, readEnvironmentScope, useEnvironmentScope } from "~/state/session"; +import { + type T3ConnectAccountPageUrl, + useT3ConnectAccountPage, +} from "../clerk/T3ConnectAccountPages"; import { CloudEnvironmentConnectRows } from "./CloudEnvironmentConnectList"; +import { TunnelLimitAlert } from "./TunnelUsage"; import { Button } from "../ui/button"; import { Checkbox } from "../ui/checkbox"; import { Dialog } from "../ui/dialog"; @@ -63,6 +69,7 @@ function ConfiguredConnectOnboardingDialog() { primaryEnvironmentId === null ? environmentsReady : primarySessionState._tag !== "Initial"; const controller = useCloudLinkController(); + const accountPage = useT3ConnectAccountPage(); const showPublishStep = canManageRelay && controller.linkState.target !== null; const steps: ReadonlyArray = showPublishStep ? ["publish", "devices"] @@ -180,6 +187,15 @@ function ConfiguredConnectOnboardingDialog() { setStep("devices"); }; + const openAccountPage = accountPage.open; + // The account page is a Clerk modal, so close this dialog before it opens. + const leaveForAccountPage = openAccountPage + ? (page: T3ConnectAccountPageUrl) => { + complete(); + openAccountPage(page); + } + : null; + return (

    { if ( primaryEnvironmentId !== null && @@ -274,6 +292,8 @@ function ConfiguredConnectOnboardingDialog() { )} + {/* Base UI renders Root children while closed, so this keeps the account page mounted. */} + {accountPage.portals} ); } @@ -288,6 +308,8 @@ function PublishStep({ publishAgentActivity, disabled, operationError, + tunnelLimit, + onOpenAccountPage, onExposeEnvironmentChange, onPublishAgentActivityChange, }: { @@ -295,6 +317,8 @@ function PublishStep({ readonly publishAgentActivity: boolean; readonly disabled: boolean; readonly operationError: string | null; + readonly tunnelLimit: number | null; + readonly onOpenAccountPage: ((page: T3ConnectAccountPageUrl) => void) | null; readonly onExposeEnvironmentChange: (enabled: boolean) => void; readonly onPublishAgentActivityChange: (enabled: boolean) => void; }) { @@ -317,10 +341,28 @@ function PublishStep({ />
    {operationError ?

    {operationError}

    : null} + {tunnelLimit !== null ? ( + + ) : null}
    ); } +function OnboardingTunnelLimitAlert({ + onOpenAccountPage, +}: { + readonly onOpenAccountPage: ((page: T3ConnectAccountPageUrl) => void) | null; +}) { + const { upgrade } = useManagedTunnelUsage(); + return ( + onOpenAccountPage("t3-chat") : null} + onManageTunnels={onOpenAccountPage ? () => onOpenAccountPage("t3-connect") : null} + /> + ); +} + function OnboardingToggleRow({ title, description, diff --git a/apps/web/src/components/cloud/TunnelUsage.tsx b/apps/web/src/components/cloud/TunnelUsage.tsx new file mode 100644 index 0000000000000..0b392f77b5416 --- /dev/null +++ b/apps/web/src/components/cloud/TunnelUsage.tsx @@ -0,0 +1,118 @@ +import { T3CHAT_PLAN_TUNNEL_LIMITS } from "@t3tools/contracts/relay"; +import { TriangleAlertIcon } from "lucide-react"; +import type { ReactNode } from "react"; + +import type { ManagedTunnelUpgrade } from "../../cloud/managedRelayState"; +import { cn } from "../../lib/utils"; +import { Alert, AlertAction, AlertDescription, AlertTitle } from "../ui/alert"; +import { Button } from "../ui/button"; + +// Above this, one slot per tunnel is too thin to read, so the bar fills instead. +const MAX_SEGMENTS = 10; + +export const T3CHAT_SUBSCRIPTION_URL = "https://t3.chat/settings/subscription"; + +export function tunnelUpgradeCopy(upgrade: Exclude): string { + const { pro, premier } = T3CHAT_PLAN_TUNNEL_LIMITS; + switch (upgrade) { + case "link": + return `Link T3 Chat Pro for up to ${pro} tunnels, or Premier for up to ${premier}.`; + case "pro": + return `Upgrade to T3 Chat Pro for up to ${pro} tunnels, or Premier for up to ${premier}.`; + case "premier": + return `Upgrade to T3 Chat Premier for up to ${premier} tunnels.`; + } +} + +/** "2 of 3 tunnels in use" with one bar slot per tunnel. */ +export function TunnelUsageMeter({ + used, + limit, + action, + className, +}: { + readonly used: number; + readonly limit: number; + readonly action?: ReactNode; + readonly className?: string; +}) { + const full = used >= limit; + const fill = full ? "bg-warning" : "bg-foreground/72"; + return ( +
    +
    + + {used} of {limit} tunnels in use + + {action} +
    +
    + {limit <= MAX_SEGMENTS ? ( + Array.from({ length: limit }, (_, index) => ( + + )) + ) : ( + + + + )} +
    +
    + ); +} + +/** Shown when the relay refuses a new tunnel because the account is at its cap. */ +export function TunnelLimitAlert({ + upgrade, + onLinkT3Chat, + onManageTunnels, +}: { + readonly upgrade: ManagedTunnelUpgrade; + readonly onLinkT3Chat: (() => void) | null; + readonly onManageTunnels: (() => void) | null; +}) { + const action = + upgrade === "link" && onLinkT3Chat ? ( + + ) : upgrade === "pro" || upgrade === "premier" ? ( + + ) : onManageTunnels ? ( + + ) : null; + return ( + + + You're out of tunnels (they cost us money). + + {upgrade === "link" + ? "Switch to Tailscale or get more tunnels by linking your T3 Chat sub (sorry!)" + : upgrade + ? "Switch to Tailscale or get more tunnels by upgrading your T3 Chat sub (sorry!)" + : "Switch to Tailscale or deregister an environment you no longer use (sorry!)"} + + {action ? {action} : null} + + ); +} diff --git a/apps/web/src/components/settings/SavedEnvironmentRows.tsx b/apps/web/src/components/settings/SavedEnvironmentRows.tsx index 1d36ef00e47a9..fee5b9857a6ae 100644 --- a/apps/web/src/components/settings/SavedEnvironmentRows.tsx +++ b/apps/web/src/components/settings/SavedEnvironmentRows.tsx @@ -39,7 +39,7 @@ import { Menu, MenuItem, MenuPopup, MenuSeparator, MenuTrigger } from "../ui/men import { Switch } from "../ui/switch"; import { stackedThreadToast, toastManager } from "../ui/toast"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; -import { Button } from "../ui/button"; +import { Button, InlineButton } from "../ui/button"; import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty"; import { resolveServerConfigVersionMismatch, @@ -49,6 +49,9 @@ import { import { hasCloudPublicConfig } from "~/cloud/publicConfig"; import { isElectron } from "~/env"; import { useCloudLinkController } from "~/cloud/useCloudLinkController"; +import { useManagedTunnelUsage } from "~/cloud/managedRelayState"; +import { useT3ConnectAccountPage } from "../clerk/T3ConnectAccountPages"; +import { TunnelLimitAlert, TunnelUsageMeter } from "../cloud/TunnelUsage"; import { environmentCatalog } from "~/connection/catalog"; import { readEnvironmentScope } from "~/state/session"; import { @@ -463,6 +466,56 @@ function CloudLinkSwitch({ ); } +/** Tunnel meter, plus the upgrade prompt after the relay refuses a tunnel at the cap. */ +function T3ConnectTunnelUsage({ tunnelLimit }: { readonly tunnelLimit: number | null }) { + const usage = useManagedTunnelUsage(); + const accountPage = useT3ConnectAccountPage(); + const openAccountPage = accountPage.open; + // Usage when the relay refused. The relay also counts tunnels still being set up, so only + // a freed tunnel or a higher cap clears the alert, not a meter that merely shows room. + const [usedAtRefusal, setUsedAtRefusal] = useState(null); + if (tunnelLimit === null) { + if (usedAtRefusal !== null) setUsedAtRefusal(null); + } else if (usedAtRefusal === null && usage.used !== null) { + setUsedAtRefusal(usage.used); + } + const showLimitAlert = + tunnelLimit !== null && + !(usedAtRefusal !== null && usage.used !== null && usage.used < usedAtRefusal) && + !(usage.limit !== null && usage.limit > tunnelLimit); + const meter = + usage.used !== null && usage.limit !== null ? ( + openAccountPage("t3-chat")}>Get more tunnels + ) : null + } + /> + ) : null; + return ( + <> + {meter || showLimitAlert ? ( +
    + {meter} + {showLimitAlert ? ( + openAccountPage("t3-chat") : null} + onManageTunnels={openAccountPage ? () => openAccountPage("t3-connect") : null} + /> + ) : null} +
    + ) : null} + {/* Kept outside the conditional so an open account page does not remount. */} + {accountPage.portals} + + ); +} + function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: boolean }) { const primaryEnvironmentId = usePrimaryEnvironmentId(); const { @@ -474,6 +527,7 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b publishAgentActivity, holdWebhooksWhileOffline, operationError, + tunnelLimit, reconcileCloudState, } = useCloudLinkController(); const { openAuthPrompt } = useT3ConnectAuthPrompt(); @@ -625,7 +679,9 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b /> ) } - /> + > + {signedOut ? null : } +
    ) : linkRevoked ? ( { it.effect("rejects concurrent reservations past the limit", () => { const reserved: Array = []; - const attempts = ManagedTunnelLimits.DEFAULT_MANAGED_TUNNEL_LIMIT + 2; + const attempts = DEFAULT_MANAGED_TUNNEL_LIMIT + 2; return Effect.gen(function* () { const limits = yield* ManagedTunnelLimits.ManagedTunnelLimits; @@ -140,7 +140,7 @@ describe("ManagedTunnelLimits", () => { { concurrency: "unbounded" }, ); - expect(reserved).toHaveLength(ManagedTunnelLimits.DEFAULT_MANAGED_TUNNEL_LIMIT); + expect(reserved).toHaveLength(DEFAULT_MANAGED_TUNNEL_LIMIT); expect( results.filter( (result) => diff --git a/infra/relay/src/environments/ManagedTunnelLimits.ts b/infra/relay/src/environments/ManagedTunnelLimits.ts index 93aea073c71d3..aa373ad27ffb2 100644 --- a/infra/relay/src/environments/ManagedTunnelLimits.ts +++ b/infra/relay/src/environments/ManagedTunnelLimits.ts @@ -6,7 +6,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; import * as SqlError from "effect/sql/SqlError"; -import { T3CHAT_PLAN_TUNNEL_LIMITS } from "@t3tools/contracts/relay"; +import { DEFAULT_MANAGED_TUNNEL_LIMIT, T3CHAT_PLAN_TUNNEL_LIMITS } from "@t3tools/contracts/relay"; import * as RelayDb from "../db.ts"; import { @@ -16,7 +16,6 @@ import { } from "../persistence/schema.ts"; import * as T3ChatAccounts from "../t3chat/T3ChatAccounts.ts"; -export const DEFAULT_MANAGED_TUNNEL_LIMIT = 3; // Reserve-to-tunnel takes two Cloudflare calls capped at 8 seconds each; a reservation older than this was abandoned. const MANAGED_TUNNEL_PENDING_WINDOW_MINUTES = 15; diff --git a/packages/contracts/src/relay.ts b/packages/contracts/src/relay.ts index 983f74de418fa..4dbb6a199f472 100644 --- a/packages/contracts/src/relay.ts +++ b/packages/contracts/src/relay.ts @@ -966,6 +966,8 @@ export type RelayOkResponse = typeof RelayOkResponse.Type; export const RelayT3ChatPlan = Schema.Literals(["free", "pro", "premier"]); export type RelayT3ChatPlan = typeof RelayT3ChatPlan.Type; +export const DEFAULT_MANAGED_TUNNEL_LIMIT = 3; + // A linked paid T3 Chat plan raises the default managed tunnel cap. export const T3CHAT_PLAN_TUNNEL_LIMITS = { pro: 10, premier: 100 } as const; From 40d335a7ba8ed0e6158a400188b5ed174e6ed19b Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Wed, 28 Oct 2026 03:12:06 -0700 Subject: [PATCH 217/817] fix(web): settling a thread no longer scrolls the sidebar to the bottom (#26392) Co-authored-by: Claude Opus 5.5 --- apps/web/src/lib/sidebarTree.browser.test.ts | 19 +++++++++++++++++++ apps/web/src/lib/sidebarTree.ts | 3 ++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/apps/web/src/lib/sidebarTree.browser.test.ts b/apps/web/src/lib/sidebarTree.browser.test.ts index 3d57aacb86438..6b02cd3b842bf 100644 --- a/apps/web/src/lib/sidebarTree.browser.test.ts +++ b/apps/web/src/lib/sidebarTree.browser.test.ts @@ -172,6 +172,25 @@ describe("sidebar keyboard navigation", () => { expect([firstAction.tabIndex, secondAction.tabIndex]).toEqual([-1, 0]); }); + it("keeps the scroll position when focus follows a row that moved away", async () => { + using tree = setup(); + Object.assign(tree.root.style, { height: "100px", overflow: "auto" }); + const settled = tree.row("settled"); + const settle = document.createElement("button"); + settle.textContent = "Settle"; + settled.after(settle); + settle.dataset.sidebarActionFor = "settled"; + for (let index = 0; index < 20; index++) tree.row(`row-${index}`).style.display = "block"; + tree.install(); + settle.focus(); + // Settling moves the row to the shelf at the bottom and removes the focused button. + settle.remove(); + settled.remove(); + const moved = tree.row("settled"); + await vi.waitFor(() => expect(document.activeElement).toBe(moved)); + expect(tree.root.scrollTop).toBe(0); + }); + it("does not pull focus back after a click outside the tree", async () => { using tree = setup(); const first = tree.row("first"); diff --git a/apps/web/src/lib/sidebarTree.ts b/apps/web/src/lib/sidebarTree.ts index 13dd10340e0b9..07859c72bd901 100644 --- a/apps/web/src/lib/sidebarTree.ts +++ b/apps/web/src/lib/sidebarTree.ts @@ -120,7 +120,8 @@ export function installSidebarTree(root: HTMLElement) { !rows.includes(document.activeElement as HTMLElement) && document.activeElement?.matches(ROW))) ) { - focusRow(selected); + // A settled row moves to the bottom shelf; scrolling after it fights the route reveal. + selected.focus({ preventScroll: true }); } if (ownsFocus && !selected && document.activeElement === document.body) root.focus(); }; From 80fcb7f58f90b43ba5918383cbe38d3ae804da8e Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Wed, 28 Oct 2026 03:24:01 -0700 Subject: [PATCH 218/817] fix(web): boring sidebar folders put your latest message on top (#26391) Co-authored-by: Claude Opus 5.5 --- apps/web/src/components/Sidebar.tsx | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index ddc7ad1e7bd29..0868554b50ffd 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -337,6 +337,8 @@ interface SidebarThreadPartitionInput { readonly serverConfigs: ReadonlyMap; readonly optimisticDrop: SidebarOptimisticDrop | null; readonly workingShelfEnabled: boolean; + /** Boring mode: folders list active threads by the user's latest message. */ + readonly sortActiveBySend: boolean; // Snooze wakes, the queued-turn grace and the Working shelf's exit grace depend // on the clock, so the minute tick, the precise snooze-wake tick and the inbox // tracker's expiry version are inputs: a new key repartitions. @@ -458,6 +460,7 @@ function useSidebarThreads(input: { serverConfigs, optimisticDrop, workingShelfEnabled, + sortActiveBySend: folderGroups !== null, clockKey: `${nowMinute}:${snoozeWakeClock}:${inboxReturnsVersion}`, }); @@ -592,6 +595,7 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) { serverConfigs, optimisticDrop, workingShelfEnabled, + sortActiveBySend, } = input; const preciseNow = new Date().toISOString(); const visible = filterSidebarV2VisibleThreads(threads, scopedProjectKeys, delegatedUnderParent); @@ -650,9 +654,11 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) { } // A loaded config gates dragging only; the sort must not depend on it, so web and mobile agree. const sortedPinned = sortPinnedThreadsForSidebar(pinned); - const sortedActive = workingShelfEnabled - ? sortInboxThreadsByReturn(active, inboxObservation.returnedAt) - : sortThreadsForSidebar(active); + const sortedActive = sortActiveBySend + ? sortWorkingThreadsBySend(active) + : workingShelfEnabled + ? sortInboxThreadsByReturn(active, inboxObservation.returnedAt) + : sortThreadsForSidebar(active); return { pinnedThreads: optimisticDrop?.section !== "pinned" || optimisticDrop.order === null From 2a738273e74e2bc4637bb0977fa7818970760621 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Wed, 28 Oct 2026 03:25:14 -0700 Subject: [PATCH 219/817] fix(server): threads settle right away when a watched PR merges (#26395) Co-authored-by: Claude Opus 5.5 --- ...chestrationV2PendingBackgroundWork.test.ts | 20 +++++++++++++++++-- .../orchestrationV2PendingBackgroundWork.ts | 9 +++++++-- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/packages/shared/src/orchestrationV2PendingBackgroundWork.test.ts b/packages/shared/src/orchestrationV2PendingBackgroundWork.test.ts index 91c827ed81596..1b5331c0d1bed 100644 --- a/packages/shared/src/orchestrationV2PendingBackgroundWork.test.ts +++ b/packages/shared/src/orchestrationV2PendingBackgroundWork.test.ts @@ -374,19 +374,26 @@ describe("derivePendingBackgroundWork kinds", () => { }; const link = ( number: number, - extra: { source?: "agent" | "stack-dismissed"; watched?: boolean }, + extra: { + source?: "agent" | "stack-dismissed"; + watched?: boolean; + state?: "open" | "closed" | "merged"; + }, ) => ({ host: "github.com", repository: "acme/app", number, url: `https://github.com/acme/app/pull/${number}`, source: extra.source ?? "agent", + snapshot: extra.state === undefined ? null : { state: extra.state }, ...(extra.watched === false ? {} : { watch }), }); const pullRequests = [ link(1, {}), link(2, { watched: false }), link(3, { source: "stack-dismissed" }), + link(4, { state: "merged" }), + link(5, { state: "closed" }), ]; it("keeps a settled run waiting on each visible watch, as an awaited monitor", () => { @@ -403,6 +410,12 @@ describe("derivePendingBackgroundWork kinds", () => { kind: "monitor", awaited: true, }, + { + taskId: "pull-request-watch:github.com/acme/app#5", + description: "Watching pull request #5", + kind: "monitor", + awaited: true, + }, ]); expect(backgroundWorkHoldsCompletion(tasks)).toBe(true); }); @@ -415,7 +428,10 @@ describe("derivePendingBackgroundWork kinds", () => { turnItems: [], pullRequests, }).map((task) => task.taskId), - ).toEqual(["pull-request-watch:github.com/acme/app#1"]); + ).toEqual([ + "pull-request-watch:github.com/acme/app#1", + "pull-request-watch:github.com/acme/app#5", + ]); }); it("lists no watch while a run is active", () => { diff --git a/packages/shared/src/orchestrationV2PendingBackgroundWork.ts b/packages/shared/src/orchestrationV2PendingBackgroundWork.ts index 6768d9359ffc7..6dc635b5153a6 100644 --- a/packages/shared/src/orchestrationV2PendingBackgroundWork.ts +++ b/packages/shared/src/orchestrationV2PendingBackgroundWork.ts @@ -112,7 +112,9 @@ type PendingBackgroundWorkRun = Pick; +> & { + readonly snapshot: Pick, "state"> | null; +}; type PendingBackgroundWorkProviderThread = Pick< OrchestrationV2ProviderThread, @@ -291,7 +293,10 @@ function pullRequestWatchTasks( pullRequests: ReadonlyArray | undefined, ): Array { return (pullRequests ?? []).flatMap((link) => - link.watch === undefined || link.source === "stack-dismissed" + // The watch reactor ends a merged PR's watch without waking the agent, so it holds nothing. + link.watch === undefined || + link.source === "stack-dismissed" || + link.snapshot?.state === "merged" ? [] : [ { From d2429f733c30772ab5ef8818685615e656ec432f Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Wed, 28 Oct 2026 05:53:28 -0500 Subject: [PATCH 220/817] fix(server): load long thread history in bounded pages (#26240) --- .../src/features/threads/ThreadFeed.tsx | 119 +++++-- apps/mobile/src/lib/threadActivity.test.ts | 15 + apps/mobile/src/lib/threadActivity.ts | 35 ++- .../src/orchestration-v2/Orchestrator.ts | 5 +- .../orchestration-v2/ProjectionStore.test.ts | 201 ++++++++++++ .../src/orchestration-v2/ProjectionStore.ts | 278 +++++++++++++---- .../ThreadManagementService.ts | 10 +- apps/server/src/orchestration-v2/http.ts | 16 +- .../threadHistoryPaging.test.ts | 106 +++++++ .../orchestration-v2/threadHistoryPaging.ts | 150 +++++++-- apps/server/src/ws.ts | 3 + .../chat/MessagesTimeline.logic.test.ts | 83 +++++ .../components/chat/MessagesTimeline.logic.ts | 49 ++- .../src/components/chat/MessagesTimeline.tsx | 144 +++++++-- .../pullRequest/PullRequestDetailPanel.tsx | 2 +- apps/web/src/session-logic.test.ts | 14 + apps/web/src/session-logic.ts | 2 +- docs/internals/performance-regressions.md | 9 +- .../src/state/boundedThreadSnapshotHttp.ts | 7 +- .../state/orchestrationV2Projection.test.ts | 8 +- .../src/state/orchestrationV2Projection.ts | 5 +- .../src/state/threadCommands.ts | 2 + .../src/state/threadHistoryController.ts | 10 +- .../src/state/threadHistoryHttp.ts | 3 +- .../src/state/threadHistoryMerge.test.ts | 23 ++ .../src/state/threadHistoryMerge.ts | 55 +++- .../src/state/threads-sync.test.ts | 291 +++++++++++++++++- packages/client-runtime/src/state/threads.ts | 203 +++++++----- packages/contracts/src/environmentHttp.ts | 4 +- packages/contracts/src/orchestrationV2.ts | 9 + 30 files changed, 1607 insertions(+), 254 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index f845d923f9a0f..da127a29ef9bf 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -1208,6 +1208,92 @@ function compactionLabel(label: string, title: string | undefined) { : label; } +function RunFoldButton({ + entry, + environmentId, + threadId, + onToggle, + rowSizing, + iconColor, +}: { + entry: Extract; + environmentId: EnvironmentId; + threadId: ThreadId; + onToggle: (runId: RunId) => void; + rowSizing: ReturnType; + iconColor: ColorValue; +}) { + const loadWork = useAtomCommand(threadEnvironment.loadEarlierHistory, { reportFailure: false }); + const anchorsKey = entry.deferredWorkItemIds?.join("\n") ?? ""; + const [failed, setFailed] = useState(false); + const load = () => { + if (!anchorsKey) return; + void Promise.all( + anchorsKey + .split("\n") + .map((workAnchorId) => loadWork({ environmentId, input: { threadId, workAnchorId } })), + ).then((results) => + setFailed( + results.some((result) => result._tag === "Failure" || result.value._tag === "error"), + ), + ); + }; + const loadOnExpand = useEffectEvent(load); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Restored expanded folds load their deferred server history on mount. + useEffect(() => { + if (entry.expanded && anchorsKey && environmentId && threadId) loadOnExpand(); + }, [entry.expanded, anchorsKey, environmentId, threadId]); + const error = anchorsKey && failed ? "Couldn't load work. Tap to retry." : null; + const loading = entry.expanded && anchorsKey !== "" && !failed; + const toggle = () => { + setFailed(false); + if (error && entry.expanded) load(); + else onToggle(entry.runId); + }; + + return ( + + + + {entry.label} + {error ? ` · ${error}` : ""} + + + + {loading ? ( + + {(["40%", "60%", "33%"] as const).map((width) => ( + + + + + ))} + + ) : null} + + ); +} + function renderFeedEntry( info: { item: ThreadFeedRow; index: number }, props: Pick< @@ -1279,30 +1365,15 @@ function renderFeedEntry( if (entry.type === "run-fold") { return ( - props.onToggleTurnFold(entry.runId)} - hitSlop={4} - className="min-h-11 min-w-0 flex-1 flex-row items-center gap-2" - style={{ - minHeight: Math.max(TURN_FOLD_HEIGHT - 3.5, props.workRowSizing.estimatedRowHeight), - }} - > - - {entry.label} - - - + {entry.checkpointSummary ? ( { "message", "message", ]); + const anchor = { + ...command(), + deferredWork: { cursor: "old-work", itemCount: 100, lastOrdinal: 100 }, + }; + const deferredFeed = buildThreadFeed([projected(userMessage(), 0), projected(anchor, 1)]); + const running = { ...latestRun, status: "running" as const, completedAt: null }; + const deferredRows = deriveThreadFeedPresentation(deferredFeed, running, new Set()); + const disclosure = deferredRows.find((entry) => entry.type === "run-fold"); + expect(disclosure).toMatchObject({ deferredWorkItemIds: [anchor.id], expanded: false }); + if (disclosure?.type !== "run-fold") throw new Error("Expected deferred work disclosure"); + expect( + deriveThreadFeedPresentation(deferredFeed, running, new Set([disclosure.runId])).some( + (entry) => entry.type === "activity-group", + ), + ).toBe(true); expect(expanded[4]).toMatchObject({ message: { id: middle.messageId, text: middle.text } }); const active = deriveThreadFeedPresentation( diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index 9cdb3b6f8d815..fc085a7c50a0d 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -231,6 +231,7 @@ type ThreadFeedEntryContent = } | { readonly type: "run-fold"; + readonly deferredWorkItemIds?: ReadonlyArray; readonly id: string; readonly createdAt: string; readonly runId: RunId; @@ -1082,6 +1083,7 @@ function threadFeedActivityIsVisible( } interface ThreadFeedRunFold { + readonly deferredWorkItemIds?: ReadonlyArray; readonly runId: RunId; readonly createdAt: string; readonly hiddenEntryIds: ReadonlySet; @@ -1273,7 +1275,17 @@ function deriveThreadFeedRunFolds( const duration = elapsedMs === null ? null : formatDuration(elapsedMs); const interrupted = latestRunMatches && (latestRun.status === "interrupted" || latestRun.status === "cancelled"); + const deferredWorkItemIds = group.entries.flatMap((entry) => + entry.type === "activity-group" + ? entry.activities.flatMap((activity) => + activity.projectedItem.item.deferredWork + ? [String(activity.projectedItem.sourceItemId)] + : [], + ) + : [], + ); foldsByAnchorId.set(firstHiddenEntry.id, { + ...(deferredWorkItemIds.length > 0 ? { deferredWorkItemIds } : {}), runId, createdAt: firstHiddenEntry.createdAt, hiddenEntryIds, @@ -1286,6 +1298,23 @@ function deriveThreadFeedRunFolds( : "Worked", }); } + const covered = new Set( + [...foldsByAnchorId.values()].flatMap((fold) => [...fold.hiddenEntryIds]), + ); + for (const entry of feed) { + if (entry.type !== "activity-group" || covered.has(entry.id)) continue; + const deferredWorkItemIds = entry.activities.flatMap((activity) => + activity.projectedItem.item.deferredWork ? [String(activity.projectedItem.sourceItemId)] : [], + ); + if (deferredWorkItemIds.length === 0) continue; + foldsByAnchorId.set(entry.id, { + runId: RunId.make(`deferred-work:${entry.id}`), + createdAt: entry.createdAt, + hiddenEntryIds: new Set([entry.id]), + label: "Earlier work", + deferredWorkItemIds, + }); + } return foldsByAnchorId; } @@ -1501,11 +1530,13 @@ export function deriveThreadFeedPresentation( row.runId !== fold.runId || row.createdAt !== fold.createdAt || row.label !== fold.label || - row.expanded !== expanded + row.expanded !== expanded || + row.deferredWorkItemIds?.join("|") !== fold.deferredWorkItemIds?.join("|") ) { row = { type: "run-fold", id: `run-fold:${fold.runId}`, + ...(fold.deferredWorkItemIds ? { deferredWorkItemIds: fold.deferredWorkItemIds } : {}), createdAt: fold.createdAt, runId: fold.runId, label: fold.label, @@ -2189,7 +2220,7 @@ export function buildThreadFeed( for (let index = restart?.row ?? 0; index < visibleTurnItems.length; index += 1) { const row = visibleTurnItems[index]!; const item = row.item; - if (turnItemIsWorkspacePreparation(item)) continue; + if (turnItemIsWorkspacePreparation(item) && !item.deferredWork) continue; if (item.type === "todo_list" || item.type === "checkpoint") continue; if ( item.type === "user_message" && diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 3f76bd6185eb7..91acb881637c1 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -344,6 +344,7 @@ export interface OrchestratorV2Shape { cursor: string, throughEntryId?: string, conversationOnly?: boolean, + workMode?: "deferred" | "work", ) => Effect.Effect; readonly getTimelinePage: ( threadId: ThreadId, @@ -13281,9 +13282,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ); }), getThreadHistoryPage: Effect.fn("OrchestratorV2.getThreadHistoryPage")( - function (threadId, cursor, throughEntryId, conversationOnly) { + function (threadId, cursor, throughEntryId, conversationOnly, workMode) { return projectionStore - .getThreadHistoryPage(threadId, cursor, throughEntryId, conversationOnly) + .getThreadHistoryPage(threadId, cursor, throughEntryId, conversationOnly, workMode) .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))); }, ), diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 5bca01a57fe99..2af87ecf4feb7 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -10,6 +10,7 @@ import { type ModelSelection, type OrchestrationV2ProviderThread, type OrchestrationV2TurnItem, + type OrchestrationV2ThreadHistoryPage, type OrchestrationV2ThreadShellSnapshot, NodeId, PlanId, @@ -1972,6 +1973,206 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { Array.from({ length: 1_000 }, (_, index) => `turn-item:bounded-sql-history:${index + 1}`), ); + yield* setNewestTurnType("command_execution"); + yield* sql` + UPDATE orchestration_v2_projection_turn_items + SET run_id = 'run:bounded-sql-history:1', + payload_json = json_set(payload_json, '$.runId', 'run:bounded-sql-history:1') + WHERE thread_id = ${threadId} + `; + yield* sql`UPDATE orchestration_v2_projection_turn_items SET ordinal = 1000, + payload_json = json_set(payload_json, '$.ordinal', 1000) + WHERE thread_id = ${threadId} AND ordinal = 999`; + const promptId = TurnItemId.make("turn-item:bounded-sql-history:1"); + const { statements: deferredStatements, tracer: deferredTracer } = traceSqlStatements(); + const deferred = yield* projectionStore + .getThreadSnapshotWindow(threadId, { + rowLimit: sqlPageLimit, + userTurnLimit: 10, + deferWork: true, + }) + .pipe(Effect.withTracer(deferredTracer)); + const deferredQuery = deferredStatements.find((statement) => + statement.includes("blocked_runs AS MATERIALIZED"), + ); + assert.isDefined(deferredQuery); + const deferredPlan = yield* sql.unsafe<{ + readonly id: number; + readonly parent: number; + readonly detail: string; + }>(`EXPLAIN QUERY PLAN ${deferredQuery}`); + const blockedRunsPlan = deferredPlan.find((row) => row.detail === "MATERIALIZE blocked_runs"); + assert.isDefined(blockedRunsPlan); + const blockedLookup = deferredPlan.find( + (row) => row.parent === blockedRunsPlan!.id && row.detail.startsWith("SEARCH "), + ); + assert.include(blockedLookup?.detail ?? "", "run_id=?"); + assert.lengthOf(deferred.projection.visibleTurnItems, 3); + assert.strictEqual(deferred.projection.visibleTurnItems[0]?.sourceItemId, promptId); + const anchor = deferred.projection.visibleTurnItems[1]!; + assert.strictEqual(anchor.item.deferredWork?.itemCount, 999); + const workIds = new Set(); + let workCursor: string | null = anchor.item.deferredWork!.cursor; + for (let pages = 0; workCursor !== null; pages += 1) { + assert.isBelow(pages, 20); + const page: OrchestrationV2ThreadHistoryPage = yield* projectionStore.getThreadHistoryPage( + threadId, + workCursor, + anchor.sourceItemId, + false, + "work", + ); + assert.isAtMost(page.items.length, 75); + for (const row of page.items) workIds.add(row.sourceItemId); + workCursor = page.nextCursor; + } + assert.strictEqual(workIds.size, 999); + for (const toolName of ["t3-code.delegate_task", "mcp__t3_code__delegate_task"]) { + yield* sql`UPDATE orchestration_v2_projection_turn_items SET type = 'dynamic_tool', + payload_json = json_set(payload_json, '$.type', 'dynamic_tool', '$.toolName', ${toolName}) + WHERE thread_id = ${threadId} AND ordinal = 2`; + const window = yield* projectionStore.getThreadSnapshotWindow(threadId, { + rowLimit: sqlPageLimit, + userTurnLimit: 10, + deferWork: true, + }); + assert.isUndefined( + window.projection.visibleTurnItems.find((row) => row.item.ordinal === 2)?.item + .deferredWork, + ); + assert.strictEqual( + window.projection.visibleTurnItems.find((row) => row.item.deferredWork)?.item.ordinal, + 3, + ); + const page = yield* projectionStore.getThreadHistoryPage( + threadId, + encodeThreadHistoryCursor({ + snapshotSequence: 0, + sourceThreadId: threadId, + sourceItemId: "turn-item:bounded-sql-history:1000", + position: 1000, + }), + undefined, + false, + "deferred", + ); + assert.isUndefined(page.items.find((row) => row.item.ordinal === 2)?.item.deferredWork); + } + yield* sql`UPDATE orchestration_v2_projection_turn_items SET type = 'command_execution', + payload_json = json_set(payload_json, '$.type', 'command_execution') WHERE thread_id = ${threadId} AND ordinal = 2`; + const sharedRunId = "run:bounded-sql-history:1"; + for (const [ordinal, status] of [ + [0, "completed"], + [1, "superseded"], + [2, "running"], + ] as const) { + const attempt = { + id: `attempt:bounded-sql-history:${ordinal}`, + runId: sharedRunId, + attemptOrdinal: ordinal + 1, + rootNodeId: `node:bounded-sql-history:attempt-${ordinal === 0 ? 1 : ordinal}`, + providerInstanceId, + providerThreadId: "provider-thread:bounded-sql-history", + providerTurnId: null, + reason: ordinal === 1 ? "initial" : "steering_restart", + status, + startedAt: nowIso, + completedAt: status === "superseded" ? nowIso : null, + }; + yield* sql`INSERT INTO orchestration_v2_projection_run_attempts + (attempt_id, thread_id, run_id, attempt_ordinal, root_node_id, provider, provider_instance_id, provider_thread_id, provider_turn_id, status, payload_json) + VALUES (${attempt.id}, ${threadId}, ${sharedRunId}, ${attempt.attemptOrdinal}, ${attempt.rootNodeId}, ${providerInstanceId}, ${providerInstanceId}, ${attempt.providerThreadId}, NULL, ${status}, ${encodeUnknownJsonString(attempt)})`; + } + yield* sql`UPDATE orchestration_v2_projection_turn_items + SET node_id = CASE WHEN ordinal < 990 AND ordinal <> 10 THEN 'node:bounded-sql-history:attempt-1' ELSE 'node:bounded-sql-history:attempt-2' END, + payload_json = json_set(payload_json, '$.nodeId', CASE WHEN ordinal < 990 AND ordinal <> 10 THEN 'node:bounded-sql-history:attempt-1' ELSE 'node:bounded-sql-history:attempt-2' END) + WHERE thread_id = ${threadId}`; + for (const status of ["completed", "running"]) { + yield* sql`UPDATE orchestration_v2_projection_runs SET status = ${status}, + payload_json = json_set(payload_json, '$.status', ${status}) WHERE run_id = ${sharedRunId}`; + const window = yield* projectionStore.getThreadSnapshotWindow(threadId, { + rowLimit: sqlPageLimit, + userTurnLimit: 10, + deferWork: true, + }); + const oldWork = window.projection.visibleTurnItems.find((row) => row.item.deferredWork); + assert.strictEqual(oldWork?.item.deferredWork?.itemCount, 987); + let cursor: string | null = oldWork!.item.deferredWork!.cursor; + const loaded = new Set(); + for (let pages = 0; cursor !== null; pages += 1) { + assert.isBelow(pages, 20); + const page: OrchestrationV2ThreadHistoryPage = + yield* projectionStore.getThreadHistoryPage( + threadId, + cursor, + oldWork!.sourceItemId, + false, + "work", + ); + for (const row of page.items) loaded.add(row.sourceItemId); + cursor = page.nextCursor; + } + assert.strictEqual(loaded.size, 987); + assert.isFalse(loaded.has(TurnItemId.make("turn-item:bounded-sql-history:10"))); + } + yield* sql`DELETE FROM orchestration_v2_projection_run_attempts WHERE thread_id = ${threadId}`; + yield* sql`UPDATE orchestration_v2_projection_runs SET status = 'completed', + payload_json = json_set(payload_json, '$.status', 'completed') WHERE run_id = ${sharedRunId}`; + yield* sql`UPDATE orchestration_v2_projection_turn_items SET node_id = NULL, + payload_json = json_set(payload_json, '$.nodeId', NULL) WHERE thread_id = ${threadId}`; + yield* sql`UPDATE orchestration_v2_projection_turn_items SET run_id = NULL, + payload_json = json_set(payload_json, '$.runId', NULL) + WHERE thread_id = ${threadId} AND ordinal > 1 AND ordinal < 851`; + const inlineWindow = yield* projectionStore.getThreadSnapshotWindow(threadId, { + rowLimit: sqlPageLimit, + userTurnLimit: 10, + deferWork: true, + }); + assert.isFalse(inlineWindow.projection.visibleTurnItems.some((row) => row.item.deferredWork)); + yield* sql`UPDATE orchestration_v2_projection_turn_items SET run_id = ${sharedRunId}, + payload_json = json_set(payload_json, '$.runId', ${sharedRunId}) + WHERE thread_id = ${threadId} AND ordinal = 850`; + const deferredWindow = yield* projectionStore.getThreadSnapshotWindow(threadId, { + rowLimit: sqlPageLimit, + userTurnLimit: 10, + deferWork: true, + }); + assert.isTrue( + deferredWindow.projection.visibleTurnItems.some( + (row) => row.item.deferredWork?.itemCount === 151, + ), + ); + yield* sql`UPDATE orchestration_v2_projection_turn_items + SET run_id = 'run:bounded-sql-history:1', + payload_json = json_set(payload_json, '$.runId', 'run:bounded-sql-history:1') + WHERE thread_id = ${threadId}`; + yield* sql`UPDATE orchestration_v2_projection_turn_items SET ordinal = 999, + payload_json = json_set(payload_json, '$.ordinal', 999) + WHERE turn_item_id = 'turn-item:bounded-sql-history:999'`; + yield* sql` + UPDATE orchestration_v2_projection_turn_items + SET type = 'command_execution', payload_json = json_set(payload_json, '$.type', 'command_execution') + WHERE thread_id = ${threadId} AND ordinal = 1 + `; + const backgroundWindow = yield* projectionStore.getThreadSnapshotWindow(threadId, { + rowLimit: sqlPageLimit, + userTurnLimit: 10, + deferWork: true, + }); + assert.lengthOf(backgroundWindow.projection.visibleTurnItems, sqlPageLimit); + yield* sql` + UPDATE orchestration_v2_projection_turn_items + SET type = 'user_message', payload_json = json_set(payload_json, '$.type', 'user_message') + WHERE thread_id = ${threadId} AND ordinal = 1 + `; + yield* sql` + UPDATE orchestration_v2_projection_turn_items + SET run_id = 'run:bounded-sql-history:' || ordinal, + payload_json = json_set(payload_json, '$.runId', 'run:bounded-sql-history:' || ordinal) + WHERE thread_id = ${threadId} + `; + yield* setNewestTurnType("user_message"); + const tiedIds = [ TurnItemId.make("turn-item:bounded-sql-history:tie:b"), TurnItemId.make("turn-item:bounded-sql-history:tie:a"), diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 1e9176d1bed69..2a21bfae4bd32 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -97,10 +97,14 @@ import { isConversationHistoryItem, THREAD_HISTORY_MAX_RAW_TURNS, missingInterruptRequests, + deferWorkHistoryRows, + selectDeferredWorkPage, + encodeThreadHistoryCursor, olderHistoryPagePolicy, selectHistoryPageFromCursor, selectRecentTimelineWindow, THREAD_HISTORY_PAGE_POLICY, + THREAD_HISTORY_INLINE_WORK_ITEM_LIMIT, THREAD_HISTORY_TURN_SNAPSHOT_ROW_LIMIT, } from "./threadHistoryPaging.ts"; @@ -416,6 +420,7 @@ export interface ProjectionStoreV2Shape { cursor: string, throughEntryId?: string, conversationOnly?: boolean, + workMode?: "deferred" | "work", ) => Effect.Effect; readonly getTimelinePage: ( threadId: ThreadId, @@ -611,6 +616,7 @@ export interface ProjectionStoreV2Shape { options: { readonly rowLimit: number; readonly userTurnLimit?: number | undefined; + readonly deferWork?: boolean | undefined; readonly anchorItemId?: TurnItemId | undefined; readonly anchorThreadId?: ThreadId | undefined; readonly requiredRunId?: RunId | undefined; @@ -625,6 +631,14 @@ export interface ProjectionStoreV2Shape { >; } +type ProjectionWindow = Omit< + Parameters[1], + "anchorThreadId" +> & { + readonly suppressLocal?: boolean | undefined; + readonly historyAnchor?: { readonly threadId: ThreadId; readonly itemId: TurnItemId } | undefined; +}; + export class ProjectionStoreV2 extends Context.Service()( "t3/orchestration-v2/ProjectionStore/ProjectionStoreV2", ) {} @@ -1796,6 +1810,11 @@ export const layer: Layer.Layer = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; + const inlineWorkOutput = sql`item.type = 'dynamic_tool' AND ( + item.payload_json LIKE '%htmlRender%' OR item.payload_json LIKE ${`%${MCP_APP_OUTPUT_KEY}%`} + OR item.payload_json LIKE '%"viewedImagePath"%' + OR item.payload_json LIKE '%"toolName":"%delegate_task"%')`; + const keepRecordedRunField = (payload: Statement.Fragment, path: string) => sql` CASE WHEN json_type(excluded.payload_json, ${path}) IS NULL @@ -2676,21 +2695,26 @@ export const layer: Layer.Layer = ); // Share selection so counting discarded ancestry preserves payload-read positions. - const retainedWindowRows = ( + const retainedWindowRows = Effect.fn("ProjectionStore.retainedWindowRows")(function* ( threadId: ThreadId, - window: { - readonly rowLimit: number; - readonly userTurnLimit?: number | undefined; - readonly anchorItemId?: TurnItemId | undefined; - readonly requiredRunId?: RunId | undefined; - }, - ) => sql` + window: ProjectionWindow, + ) { + const eligible = sql` WITH eligible AS NOT MATERIALIZED ( SELECT item.rowid AS item_rowid, item.payload_json, item.ordinal, item.turn_item_id, - item.run_id, item.node_id, item.type + item.run_id, item.node_id, item.type, item.status, run.status AS run_status, + attempt.attempt_id, attempt.status AS attempt_status FROM orchestration_v2_projection_turn_items AS item LEFT JOIN orchestration_v2_projection_runs AS run ON run.run_id = item.run_id + LEFT JOIN orchestration_v2_projection_nodes AS node + ON ${window.deferWork ? 1 : 0} = 1 AND node.node_id = item.node_id + LEFT JOIN orchestration_v2_projection_run_attempts AS attempt + ON ${window.deferWork ? 1 : 0} = 1 AND attempt.attempt_id = ( + SELECT attempt_id FROM orchestration_v2_projection_run_attempts + WHERE run_id = item.run_id AND root_node_id = COALESCE(node.root_node_id, item.node_id) + ORDER BY attempt_ordinal DESC LIMIT 1 + ) WHERE item.thread_id = ${threadId} AND item.ordinal <= COALESCE( ( @@ -2749,7 +2773,10 @@ export const layer: Layer.Layer = AND request.type = 'run_interrupt_request' ) ) - ), run_starts AS ( + )`; + // Resolve anchors separately: repeated CTE expansion exceeds SQLite's subquery limit. + const anchors = yield* sql<{ readonly ordinal: number; readonly latest: number | null }>` + ${eligible}, run_starts AS ( -- A wake (PR watch, task completion) starts its run with a -- notification instead of a user message. Read the first -- input of each run, newest run first, and add the @@ -2813,6 +2840,49 @@ export const layer: Layer.Layer = ELSE 0 END AS ordinal FROM user_anchors + ) + SELECT ordinal, (SELECT MAX(ordinal) FROM user_anchors) AS latest FROM boundary + `; + const boundary = anchors[0]!; + return sql` + ${eligible}, blocked_runs AS MATERIALIZED ( + SELECT DISTINCT run_id FROM orchestration_v2_projection_turn_items + WHERE thread_id = ${threadId} AND run_id IS NOT NULL + AND ${window.deferWork ? 1 : 0} = 1 + AND run_id IN ( + SELECT run_id FROM eligible + WHERE ordinal >= ${boundary.ordinal} AND run_id IS NOT NULL + ) + AND (type IN ('run_interrupt_request', 'run_interrupt_result') + OR (type = 'error' AND status = 'failed' AND parent_item_id IS NULL)) + ), work_segments AS ( + SELECT item_rowid, ordinal, turn_item_id, run_id, type, attempt_id, + MAX(CASE WHEN type = 'user_message' THEN ordinal ELSE 0 END) + OVER (PARTITION BY run_id ORDER BY ordinal) AS segment, + CASE WHEN status = 'completed' AND (run_status = 'completed' OR attempt_status = 'superseded') + AND type IN ('command_execution', 'reasoning', 'file_change', 'file_search', 'web_search', 'dynamic_tool') + AND NOT (${inlineWorkOutput}) + AND run_id NOT IN (SELECT run_id FROM blocked_runs) + THEN 1 ELSE 0 END AS can_defer + FROM eligible AS item + WHERE ${window.deferWork ? 1 : 0} = 1 + AND ${boundary.latest === null ? 0 : 1} = 1 + AND ordinal >= ${boundary.ordinal} + ), deferred_work AS ( + SELECT run_id, segment, attempt_id, MIN(ordinal) AS first_ordinal, + MAX(ordinal) AS last_ordinal, COUNT(*) AS item_count + FROM work_segments WHERE can_defer = 1 + GROUP BY run_id, segment, attempt_id HAVING COUNT(*) > ${THREAD_HISTORY_INLINE_WORK_ITEM_LIMIT} + ), window_items AS NOT MATERIALIZED ( + SELECT item_rowid, ordinal, turn_item_id, run_id, type + FROM eligible WHERE ${window.deferWork ? 1 : 0} = 0 + OR ${boundary.latest === null ? 1 : 0} = 1 + UNION ALL + SELECT item.item_rowid, item.ordinal, item.turn_item_id, item.run_id, item.type + FROM work_segments item LEFT JOIN deferred_work deferred + ON deferred.run_id = item.run_id AND deferred.segment = item.segment + AND deferred.attempt_id IS item.attempt_id + WHERE item.can_defer = 0 OR deferred.run_id IS NULL OR item.ordinal = deferred.first_ordinal ), latest_user_turn AS ( -- Mirrors selectOlderTimelinePage: whole turns while the -- newest user turn fits the turn row budget, otherwise the @@ -2820,8 +2890,8 @@ export const layer: Layer.Layer = SELECT COUNT(*) AS row_count FROM ( SELECT 1 - FROM eligible - WHERE ordinal >= (SELECT MAX(ordinal) FROM user_anchors) + FROM window_items + WHERE ordinal >= ${boundary.latest} LIMIT ${THREAD_HISTORY_PAGE_POLICY.maxTurnItems + 1} ) ), selected AS ( @@ -2829,8 +2899,8 @@ export const layer: Layer.Layer = -- order. A turn window can hold megabytes of tool output, and -- carrying it through the union and sort cost about a second. SELECT item_rowid, ordinal, turn_item_id, run_id, type - FROM eligible - WHERE ordinal >= (SELECT ordinal FROM boundary) + FROM window_items + WHERE ordinal >= ${boundary.ordinal} ORDER BY ordinal DESC, turn_item_id DESC LIMIT CASE WHEN ${window.rowLimit} = 0 THEN 0 @@ -2863,17 +2933,12 @@ export const layer: Layer.Layer = ORDER BY ordinal ASC, turn_item_id ASC ) `; + }); const readCanonicalProjection = Effect.fn("ProjectionStore.readCanonicalProjection")( function* ( threadId: ThreadId, - window?: { - readonly rowLimit: number; - readonly userTurnLimit?: number | undefined; - readonly anchorItemId?: TurnItemId | undefined; - readonly requiredRunId?: RunId | undefined; - readonly suppressLocal?: boolean | undefined; - }, + window?: ProjectionWindow, fields?: ReadonlyArray, filter?: ProjectionRecordFilter, ) { @@ -2888,7 +2953,12 @@ export const layer: Layer.Layer = return yield* new ProjectionStoreThreadNotFoundError({ threadId }); } - const boundedTurnItemRows = + type WindowPayloadRow = PayloadRow & { + readonly work_last_id?: string | null; + readonly work_last_ordinal?: number | null; + readonly work_item_count?: number | null; + }; + const boundedTurnItemRows: ReadonlyArray = (fields !== undefined && !fields.includes("turnItems")) || (window === undefined && matchesNothing(filter?.turnItemTypes, filter?.turnItemStatuses, filter?.turnItemRunIds)) @@ -2905,18 +2975,51 @@ export const layer: Layer.Layer = ORDER BY ordinal ASC, turn_item_id ASC ` : yield* sql` - ${retainedWindowRows(threadId, window)} + ${yield* retainedWindowRows(threadId, window)} -- CROSS JOIN keeps the sorted IDs as the outer loop, so SQLite -- skips sorting again once the payloads are attached. Carry the -- rowid through selection to avoid a second string-key index lookup. - SELECT item.payload_json + SELECT item.payload_json, tail.turn_item_id AS work_last_id, + deferred.last_ordinal AS work_last_ordinal, deferred.item_count AS work_item_count FROM retained CROSS JOIN orchestration_v2_projection_turn_items AS item ON item.rowid = retained.item_rowid + LEFT JOIN deferred_work deferred ON deferred.run_id = item.run_id + AND deferred.first_ordinal = item.ordinal + LEFT JOIN orchestration_v2_projection_turn_items tail + ON tail.turn_item_id = ( + SELECT turn_item_id FROM orchestration_v2_projection_turn_items + WHERE thread_id = item.thread_id AND ordinal = deferred.last_ordinal + ORDER BY turn_item_id DESC LIMIT 1 + ) ORDER BY retained.ordinal ASC, retained.turn_item_id ASC `; // Decode items once for cohort ids and projection; repeated parsing duplicates retained tool output. - const turnItems = yield* decodeRows(decodeTurnItemPayload, threadId)(boundedTurnItemRows); + const decodedTurnItems = yield* decodeRows( + decodeTurnItemPayload, + threadId, + )(boundedTurnItemRows); + const turnItems = decodedTurnItems.map((item, index) => { + const row = boundedTurnItemRows[index]!; + return row.work_last_id == null || + row.work_item_count == null || + row.work_last_ordinal == null + ? item + : { + ...item, + deferredWork: { + cursor: encodeThreadHistoryCursor({ + snapshotSequence: 0, + sourceThreadId: threadId, + sourceItemId: TurnItemId.make(row.work_last_id), + position: row.work_last_ordinal, + inclusive: true, + }), + itemCount: row.work_item_count, + lastOrdinal: row.work_last_ordinal, + }, + }; + }); const cohortJson = (field: string) => JSON.stringify( turnItems.flatMap((payload) => { @@ -3438,32 +3541,14 @@ export const layer: Layer.Layer = const readProjection: ( threadId: ThreadId, seenThreadIds: ReadonlySet, - window?: { - readonly rowLimit: number; - readonly userTurnLimit?: number | undefined; - readonly anchorItemId?: TurnItemId | undefined; - readonly requiredRunId?: RunId | undefined; - readonly suppressLocal?: boolean | undefined; - readonly historyAnchor?: - | { readonly threadId: ThreadId; readonly itemId: TurnItemId } - | undefined; - }, + window?: ProjectionWindow, ) => Effect.Effect = Effect.fn( "ProjectionStore.readProjection", )( function* ( threadId: ThreadId, seenThreadIds: ReadonlySet, - window?: { - readonly rowLimit: number; - readonly userTurnLimit?: number | undefined; - readonly anchorItemId?: TurnItemId | undefined; - readonly requiredRunId?: RunId | undefined; - readonly suppressLocal?: boolean | undefined; - readonly historyAnchor?: - | { readonly threadId: ThreadId; readonly itemId: TurnItemId } - | undefined; - }, + window?: ProjectionWindow, ) { const localWindow = window?.suppressLocal === true || @@ -3569,6 +3654,7 @@ export const layer: Layer.Layer = return { rowLimit: window.rowLimit, userTurnLimit: window.userTurnLimit, + deferWork: window.deferWork, requiredRunId: forkedFrom.runId, suppressLocal: anchor === undefined || anchorIsInDescendant, ...(anchor === undefined || anchorIsInDescendant @@ -3591,7 +3677,7 @@ export const layer: Layer.Layer = .length >= Math.max(window.userTurnLimit, THREAD_HISTORY_PAGE_POLICY.maxUserTurns) ) { const counted = yield* sql<{ readonly inherited_rows: number | null }>` - ${retainedWindowRows(forkedFrom.threadId, { + ${yield* retainedWindowRows(forkedFrom.threadId, { ...sourceWindow, rowLimit: sourceWindow.suppressLocal ? 0 : sourceWindow.rowLimit, })} @@ -5196,7 +5282,7 @@ export const layer: Layer.Layer = type TimelineIndexItem = Pick< OrchestrationV2TurnItem, - "id" | "threadId" | "runId" | "nodeId" | "type" + "id" | "threadId" | "runId" | "nodeId" | "parentItemId" | "type" | "status" | "ordinal" > & { readonly inputIntent?: Extract< OrchestrationV2TurnItem, @@ -5204,6 +5290,11 @@ export const layer: Layer.Layer = >["inputIntent"]; readonly createdBy?: "user" | "agent" | "system"; readonly messageId?: MessageId; + readonly runStatus?: string | undefined; + readonly attemptId?: string | null; + readonly attemptStatus?: string | null; + readonly persistentOutput?: boolean; + readonly deferredWork?: OrchestrationV2TurnItem["deferredWork"]; }; type TimelineIndexRow = { readonly sourceThreadId: ThreadId; @@ -5215,6 +5306,7 @@ export const layer: Layer.Layer = const readTimelineIndex: ( threadId: ThreadId, seen: ReadonlySet, + includePersistentOutput?: boolean, ) => Effect.Effect< { readonly records: ProjectionRecords<"runs" | "attempts">; @@ -5223,28 +5315,58 @@ export const layer: Layer.Layer = }, ProjectionStoreV2Error > = Effect.fn("ProjectionStore.readTimelineIndex")( - function* (threadId: ThreadId, seen: ReadonlySet) { + function* (threadId: ThreadId, seen: ReadonlySet, includePersistentOutput = false) { const records = yield* getThreadRecords(threadId, ["runs", "attempts"]); const rows = yield* sql<{ turn_item_id: string; run_id: string | null; node_id: string | null; + parent_item_id: string | null; type: OrchestrationV2TurnItem["type"]; input_intent: NonNullable | null; created_by: "user" | "agent" | "system" | null; message_id: string | null; - }>`SELECT turn_item_id, run_id, node_id, type, - CASE WHEN type = 'user_message' THEN json_extract(payload_json, '$.inputIntent') END AS input_intent, - CASE WHEN type = 'user_message' THEN json_extract(payload_json, '$.createdBy') END AS created_by, - CASE WHEN type IN ('user_message', 'assistant_message') THEN json_extract(payload_json, '$.messageId') END AS message_id - FROM orchestration_v2_projection_turn_items WHERE thread_id = ${threadId} - ORDER BY ordinal ASC, turn_item_id ASC`; + status: OrchestrationV2TurnItem["status"]; + ordinal: number; + persistent_output: number; + attempt_id: string | null; + attempt_status: string | null; + }>`SELECT item.turn_item_id, item.run_id, item.node_id, item.parent_item_id, item.type, item.status, item.ordinal, + ${includePersistentOutput ? sql`attempt.attempt_id` : sql`NULL`} AS attempt_id, + ${includePersistentOutput ? sql`attempt.status` : sql`NULL`} AS attempt_status, + ${ + includePersistentOutput ? sql`CASE WHEN ${inlineWorkOutput} THEN 1 ELSE 0 END` : sql`0` + } AS persistent_output, + CASE WHEN item.type = 'user_message' THEN json_extract(item.payload_json, '$.inputIntent') END AS input_intent, + CASE WHEN item.type = 'user_message' THEN json_extract(item.payload_json, '$.createdBy') END AS created_by, + CASE WHEN item.type IN ('user_message', 'assistant_message') THEN json_extract(item.payload_json, '$.messageId') END AS message_id + FROM orchestration_v2_projection_turn_items AS item + ${ + includePersistentOutput + ? sql`LEFT JOIN orchestration_v2_projection_nodes AS node ON node.node_id = item.node_id + LEFT JOIN orchestration_v2_projection_run_attempts AS attempt ON attempt.attempt_id = ( + SELECT attempt_id FROM orchestration_v2_projection_run_attempts + WHERE run_id = item.run_id AND root_node_id = COALESCE(node.root_node_id, item.node_id) + ORDER BY attempt_ordinal DESC LIMIT 1 + )` + : sql`` + } + WHERE item.thread_id = ${threadId} + ORDER BY item.ordinal ASC, item.turn_item_id ASC`; + const runStatuses = new Map(records.runs.map((run) => [String(run.id), run.status])); const items: Array = rows.map((row) => ({ id: TurnItemId.make(row.turn_item_id), threadId, runId: row.run_id === null ? null : RunId.make(row.run_id), nodeId: row.node_id === null ? null : NodeId.make(row.node_id), + parentItemId: row.parent_item_id === null ? null : TurnItemId.make(row.parent_item_id), type: row.type, + status: row.status, + ordinal: row.ordinal, + runStatus: row.run_id === null ? undefined : runStatuses.get(row.run_id), + attemptId: row.attempt_id, + attemptStatus: row.attempt_status, + persistentOutput: row.persistent_output === 1, ...(row.input_intent === null ? {} : { inputIntent: row.input_intent }), ...(row.created_by === null ? {} : { createdBy: row.created_by }), ...(row.message_id === null ? {} : { messageId: MessageId.make(row.message_id) }), @@ -5263,7 +5385,11 @@ export const layer: Layer.Layer = const visible = local.filter((row) => isVisible(row.item)); const fork = records.thread.forkedFrom; if (fork?.type !== "run" || seen.has(fork.threadId)) return { records, local, visible }; - const source = yield* readTimelineIndex(fork.threadId, new Set([...seen, threadId])); + const source = yield* readTimelineIndex( + fork.threadId, + new Set([...seen, threadId]), + includePersistentOutput, + ); const sourceRun = source.records.runs.find((run) => run.id === fork.runId); let inherited: Array = []; if (sourceRun !== undefined) { @@ -5329,11 +5455,12 @@ export const layer: Layer.Layer = cursor, throughEntryId, conversationOnly, + workMode, ) => sql .withTransaction( Effect.gen(function* () { - const index = yield* readTimelineIndex(threadId, new Set()); + const index = yield* readTimelineIndex(threadId, new Set(), workMode !== undefined); if (index.records.thread.deletedAt !== null) return yield* new ProjectionStoreThreadNotFoundError({ threadId }); const revisions = yield* sql<{ @@ -5347,21 +5474,32 @@ export const layer: Layer.Layer = position, canonicalPosition: position, })); + const historyItems = workMode === "deferred" ? deferWorkHistoryRows(indexed) : indexed; const selection = yield* Effect.try({ try: () => { const policy = olderHistoryPagePolicy({ items: indexed, cursor, throughEntryId }); - const page = selectHistoryPageFromCursor({ - items: indexed, - cursor, - snapshotSequence, - rowEncodedBytes: () => 0, - policy, - }); + const page = + workMode === "work" + ? selectDeferredWorkPage({ + items: indexed, + cursor, + throughEntryId, + snapshotSequence, + rowEncodedBytes: () => 0, + }) + : selectHistoryPageFromCursor({ + items: historyItems, + cursor, + snapshotSequence, + rowEncodedBytes: () => 0, + policy, + }); return { policy, page }; }, catch: (cause) => new ProjectionStoreReadError({ threadId, cause }), }); - const { policy, page } = selection; + const { page } = selection; + const policy = workMode === "work" ? THREAD_HISTORY_PAGE_POLICY : selection.policy; const end = (page.items.at(-1)?.canonicalPosition ?? -1) + 1; const hasUserTurns = index.visible .slice(0, end) @@ -5400,7 +5538,11 @@ export const layer: Layer.Layer = visibility: row.visibility, sourceThreadId: row.sourceThreadId, sourceItemId: row.sourceItemId, - item: projectTurnItemForWire(item), + item: projectTurnItemForWire( + row.item.deferredWork === undefined + ? item + : { ...item, deferredWork: row.item.deferredWork }, + ), }; }), ); @@ -5411,7 +5553,10 @@ export const layer: Layer.Layer = : page.items, ); const bounded = selectRecentTimelineWindow({ items, snapshotSequence, policy }); - const requests = yield* materialize(missingInterruptRequests(indexed, bounded.items)); + const requests = + workMode === "work" + ? [] + : yield* materialize(missingInterruptRequests(indexed, bounded.items)); const pageItems = [...requests, ...bounded.items].map((row, position) => ({ ...row, position, @@ -5517,6 +5662,7 @@ export const layer: Layer.Layer = const projection = yield* readProjection(threadId, new Set(), { rowLimit: options.rowLimit, userTurnLimit: options.userTurnLimit, + deferWork: options.deferWork, ...(historyAnchor?.threadId === threadId ? { anchorItemId: historyAnchor.itemId } : {}), diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 917fdc807c2f8..615ea352f25af 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -1278,10 +1278,16 @@ const make = Effect.gen(function* () { }), dispatch, getThreadHistoryPage: Effect.fn("ThreadManagementService.getThreadHistoryPage")( - function (threadId, cursor, throughEntryId, conversationOnly) { + function (threadId, cursor, throughEntryId, conversationOnly, workMode) { return ensureProjectionTranscript(threadId).pipe( Effect.andThen( - orchestrator.getThreadHistoryPage(threadId, cursor, throughEntryId, conversationOnly), + orchestrator.getThreadHistoryPage( + threadId, + cursor, + throughEntryId, + conversationOnly, + workMode, + ), ), ); }, diff --git a/apps/server/src/orchestration-v2/http.ts b/apps/server/src/orchestration-v2/http.ts index 9d3e583b832e0..61ff54d0c794f 100644 --- a/apps/server/src/orchestration-v2/http.ts +++ b/apps/server/src/orchestration-v2/http.ts @@ -133,10 +133,12 @@ export const layer = HttpApiBuilder.group( anchorThreadId?: Parameters< typeof threadManagement.getThreadSnapshotWindow >[1]["anchorThreadId"], + deferWork = false, ) { return yield* threadManagement .getThreadSnapshotWindow(threadId, { rowLimit: THREAD_HISTORY_SNAPSHOT_ROW_LIMIT, + deferWork, userTurnLimit: anchorItemId === undefined ? THREAD_HISTORY_PAGE_POLICY.maxUserTurns @@ -223,9 +225,12 @@ export const layer = HttpApiBuilder.group( Effect.fn("environment.orchestration.threadBoundedSnapshot")(function* (args) { yield* annotateEnvironmentRequest(args.endpoint.name); yield* requireEnvironmentScope(AuthOrchestrationReadScope); - const snapshot = yield* loadThreadSnapshotWindow(args.params.threadId).pipe( - traceLocalHandlerWork, - ); + const snapshot = yield* loadThreadSnapshotWindow( + args.params.threadId, + undefined, + undefined, + args.query.deferWork === "1", + ).pipe(traceLocalHandlerWork); const bounded = buildBoundedThreadProjection({ projection: snapshot.projection, snapshotSequence: snapshot.snapshotSequence, @@ -261,6 +266,11 @@ export const layer = HttpApiBuilder.group( args.query.cursor, args.query.throughEntryId, args.query.view === "conversation", + args.query.view === "work" + ? "work" + : args.query.deferWork === "1" + ? "deferred" + : undefined, ) .pipe( Effect.map((page) => diff --git a/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts b/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts index 38ad3b5c7de13..f4e54000222fc 100644 --- a/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts +++ b/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts @@ -12,12 +12,15 @@ import * as DateTime from "effect/DateTime"; import { buildBoundedThreadProjection, + deferWorkHistoryRows, boundedTimelineEncodedBytes, computeLatestLocalTurnOrdinal, + decodeThreadHistoryCursor, encodeThreadHistoryCursor, projectedRowBoundedSnapshotEncodedBytes, projectedRowEncodedBytes, selectHistoryPageFromCursor, + selectDeferredWorkPage, selectRecentTimelineWindow, THREAD_HISTORY_PAGE_POLICY, } from "./threadHistoryPaging.ts"; @@ -155,6 +158,76 @@ function makeProjection(visibleTurnItems: OrchestrationV2ProjectedTurnItem[]) { } describe("threadHistoryPaging", () => { + it("defers completed work above 150 items and keeps conversation and persistent rows", () => { + const work = Array.from({ length: 151 }, (_, index) => { + const row = makeRow(index); + return { ...row, item: { ...row.item, runId: RUN, runStatus: "completed" } }; + }); + expect(deferWorkHistoryRows(work.slice(0, 150))).toHaveLength(150); + const deferredWork = deferWorkHistoryRows(work)[0]!.item.deferredWork!; + expect(deferredWork.itemCount).toBe(151); + expect(decodeThreadHistoryCursor(deferredWork.cursor).p).toBe(151); + const superseded = work.map((row) => ({ + ...row, + item: { ...row.item, runStatus: "running", attemptId: "old", attemptStatus: "superseded" }, + })); + const active = work.map((row, index) => ({ + ...row, + sourceItemId: TurnItemId.make(`active-${index}`), + position: row.position + work.length, + item: { ...row.item, runStatus: "running", attemptId: "active", attemptStatus: "running" }, + })); + const attempts = deferWorkHistoryRows([...superseded, ...active]); + expect(attempts[0]?.item.deferredWork?.itemCount).toBe(151); + expect(attempts.slice(1)).toEqual(active); + const compaction = { + ...work[0]!, + sourceItemId: TurnItemId.make("compaction"), + item: { + ...work[0]!.item, + type: "compaction" as const, + }, + }; + const persistent = { + ...work[0]!, + sourceItemId: TurnItemId.make("render"), + item: { + ...work[0]!.item, + type: "dynamic_tool" as const, + persistentOutput: true, + }, + }; + const deferred = deferWorkHistoryRows([ + ...work.slice(0, 30), + compaction, + persistent, + ...work.slice(30), + ]); + expect(deferred.map((row) => row.sourceItemId)).toEqual(["item-0", "compaction", "render"]); + expect(deferred[0]?.item.deferredWork?.itemCount).toBe(151); + for (const runStatus of ["running", "failed", "interrupted", "cancelled"]) { + expect( + deferWorkHistoryRows(work.map((row) => ({ ...row, item: { ...row.item, runStatus } }))), + ).toHaveLength(151); + } + const interrupted = { + ...compaction, + item: { ...compaction.item, type: "run_interrupt_result" as const }, + }; + expect(deferWorkHistoryRows([...work, interrupted])).toHaveLength(152); + const failed = { + ...compaction, + item: { + ...compaction.item, + type: "error" as const, + status: "failed" as const, + nodeId: "root-node", + parentItemId: null, + }, + }; + expect(deferWorkHistoryRows([...work, failed])).toHaveLength(152); + }); + it("keeps a human turn whole up to the turn row budget and pages a longer one from inside", () => { const humanTurn = (length: number) => { const items = Array.from({ length }, (_, index) => makeRow(index)); @@ -394,6 +467,39 @@ describe("threadHistoryPaging", () => { expect(page.items.map((row) => row.sourceItemId)).toEqual(["item-3", "item-4"]); expect(page.hasMoreHistory).toBe(true); expect(page.nextCursor).not.toBeNull(); + const sparse = [makeRow(0), makeRow(10), makeRow(20)]; + const middle = selectHistoryPageFromCursor({ + items: sparse, + cursor: encodeThreadHistoryCursor({ + snapshotSequence: 3, + sourceThreadId: THREAD, + sourceItemId: "item-hidden", + position: 15, + }), + snapshotSequence: 3, + }); + expect(middle.items.map((row) => row.sourceItemId)).toEqual(["item-0", "item-10"]); + const work = Array.from({ length: 80 }, (_, index) => { + const row = makeRow(index); + return { ...row, item: { ...row.item, runId: RUN, ordinal: index + 100 } }; + }); + const tail = work[75]!; + const deferred = selectDeferredWorkPage({ + items: work.filter((row) => row !== tail).map((row, position) => ({ ...row, position })), + cursor: encodeThreadHistoryCursor({ + snapshotSequence: 3, + sourceThreadId: THREAD, + sourceItemId: tail.sourceItemId, + position: tail.item.ordinal, + inclusive: true, + }), + throughEntryId: work[0]!.sourceItemId, + snapshotSequence: 3, + }); + expect(deferred.items.map((row) => row.sourceItemId)).toEqual( + work.slice(0, 75).map((row) => row.sourceItemId), + ); + expect(deferred.nextCursor).toBeNull(); }); it("keeps cursor resolution stable when newer items append", () => { diff --git a/apps/server/src/orchestration-v2/threadHistoryPaging.ts b/apps/server/src/orchestration-v2/threadHistoryPaging.ts index 146436fc3ca57..7f1ea4db95d6f 100644 --- a/apps/server/src/orchestration-v2/threadHistoryPaging.ts +++ b/apps/server/src/orchestration-v2/threadHistoryPaging.ts @@ -19,6 +19,8 @@ export const THREAD_HISTORY_PAGE_POLICY = { maxEncodedBytes: 1_048_576, } as const; +export const THREAD_HISTORY_INLINE_WORK_ITEM_LIMIT = 150; + export const OLDER_THREAD_USER_TURN_LIMIT = 20; export function isConversationHistoryItem(item: Pick): boolean { @@ -46,6 +48,7 @@ export type ThreadHistoryCursorPayload = { readonly st: string; readonly si: string; readonly p: number; + readonly inclusive?: boolean; }; type HistoryRow = Pick< @@ -58,6 +61,14 @@ type HistoryRow = Pick< readonly inputIntent?: string; readonly createdBy?: string; readonly runId?: string | null; + readonly status?: OrchestrationV2TurnItem["status"]; + readonly parentItemId?: string | null; + readonly ordinal?: number; + readonly runStatus?: string | undefined; + readonly attemptId?: string | null | undefined; + readonly attemptStatus?: string | null | undefined; + readonly persistentOutput?: boolean; + readonly deferredWork?: OrchestrationV2TurnItem["deferredWork"]; }; }; export type SelectTimelinePageResult = { @@ -114,6 +125,7 @@ export function encodeThreadHistoryCursor(input: { readonly sourceThreadId: ThreadId | string; readonly sourceItemId: TurnItemId | string; readonly position: number; + readonly inclusive?: boolean; }): string { return encodeCursorPayload({ v: 1, @@ -121,6 +133,7 @@ export function encodeThreadHistoryCursor(input: { st: String(input.sourceThreadId), si: String(input.sourceItemId), p: input.position, + ...(input.inclusive ? { inclusive: true } : {}), }); } @@ -153,7 +166,8 @@ export function decodeThreadHistoryCursor(cursor: string): ThreadHistoryCursorPa !("p" in parsed) || typeof parsed.p !== "number" || !Number.isInteger(parsed.p) || - parsed.p < 0 + parsed.p < 0 || + ("inclusive" in parsed && typeof parsed.inclusive !== "boolean") ) { throw new InvalidThreadHistoryCursorError(); } @@ -167,6 +181,109 @@ function isThreadHistoryTurnStart(item: HistoryRow["item"]): boolean { ); } +const DEFERRED_WORK_ITEM_TYPES = [ + "command_execution", + "reasoning", + "file_change", + "file_search", + "web_search", + "dynamic_tool", +] as const; + +function isDeferrableWorkItem(item: HistoryRow["item"]): boolean { + return ( + item.status === "completed" && + item.persistentOutput !== true && + DEFERRED_WORK_ITEM_TYPES.some((type) => type === item.type) + ); +} + +export function deferWorkHistoryRows(items: ReadonlyArray): Row[] { + const blocked = new Set( + items.flatMap(({ item }) => + item.runId != null && + (item.type === "run_interrupt_request" || + item.type === "run_interrupt_result" || + (item.type === "error" && item.status === "failed" && item.parentItemId == null)) + ? [item.runId] + : [], + ), + ); + const segments = new Map(); + const groups = new Map(); + for (const row of items) { + const item = row.item; + if (item.runId == null) continue; + if (item.type === "user_message") segments.set(item.runId, (segments.get(item.runId) ?? 0) + 1); + if ( + (item.runStatus !== "completed" && item.attemptStatus !== "superseded") || + blocked.has(item.runId) || + !isDeferrableWorkItem(item) + ) + continue; + const key = `${row.sourceThreadId}:${item.runId}:${segments.get(item.runId) ?? 0}:${item.attemptId ?? ""}`; + const group = groups.get(key) ?? []; + group.push(row); + groups.set(key, group); + } + const omitted = new Set(); + const anchors = new Map(); + for (const group of groups.values()) { + if (group.length <= THREAD_HISTORY_INLINE_WORK_ITEM_LIMIT) continue; + const first = group[0]!; + const last = group.at(-1)!; + for (const row of group.slice(1)) omitted.add(row); + anchors.set(first, { + ...first, + item: { + ...first.item, + deferredWork: { + cursor: encodeThreadHistoryCursor({ + snapshotSequence: 0, + sourceThreadId: last.sourceThreadId, + sourceItemId: last.sourceItemId, + position: last.item.ordinal ?? last.position, + inclusive: true, + }), + itemCount: group.length, + lastOrdinal: last.item.ordinal ?? last.position, + }, + }, + }); + } + return items.flatMap((row) => (omitted.has(row) ? [] : [anchors.get(row) ?? row])); +} + +export function selectDeferredWorkPage(input: { + readonly items: ReadonlyArray; + readonly cursor: string; + readonly throughEntryId?: string | undefined; + readonly snapshotSequence: number; + readonly rowEncodedBytes?: ((row: Row) => number) | undefined; +}): SelectTimelinePageResult { + const cursor = decodeThreadHistoryCursor(input.cursor); + const end = findCursorEndIndex(input.items, cursor); + const start = input.items.findIndex((row) => row.sourceItemId === input.throughEntryId); + if (start < 0 || start >= end) throw new InvalidThreadHistoryCursorError(); + const anchor = input.items[start]!; + const items = input.items + .slice(start, end) + .filter( + (row) => + row.sourceThreadId === anchor.sourceThreadId && + row.item.runId === anchor.item.runId && + row.item.attemptId === anchor.item.attemptId && + isDeferrableWorkItem(row.item), + ); + return selectOlderTimelinePage({ + items, + exclusiveEndIndex: items.length, + snapshotSequence: input.snapshotSequence, + rowEncodedBytes: input.rowEncodedBytes, + policy: THREAD_HISTORY_PAGE_POLICY, + }); +} + /** Notifications can start wake turns when they are the run's first input; match ProjectionStore run_starts. */ function threadHistoryTurnStarts(items: ReadonlyArray): ReadonlyArray { const startedRuns = new Set(); @@ -275,17 +392,23 @@ export function selectRecentTimelineWindow(input: { }); } -function findCursorIndex( - items: ReadonlyArray>, +function findCursorEndIndex( + items: ReadonlyArray, cursor: ThreadHistoryCursorPayload, ): number { const byIdentity = items.findIndex( (row) => String(row.sourceThreadId) === cursor.st && String(row.sourceItemId) === cursor.si, ); if (byIdentity !== -1) { - return byIdentity; + return byIdentity + (cursor.inclusive ? 1 : 0); } - return Math.min(cursor.p, items.length); + // Inclusive deferred cursors carry source ordinals; ordinary cursors carry visible positions. + const byPosition = items.findIndex((row) => + cursor.inclusive + ? String(row.sourceThreadId) === cursor.st && (row.item.ordinal ?? row.position) > cursor.p + : row.position >= cursor.p, + ); + return byPosition === -1 ? items.length : byPosition; } /** @@ -304,7 +427,7 @@ export function olderHistoryPagePolicy(input: { maxUserTurns: OLDER_THREAD_USER_TURN_LIMIT, }; if (input.throughEntryId === undefined) return policy; - const anchorIndex = findCursorIndex(input.items, decodeThreadHistoryCursor(input.cursor)); + const anchorIndex = findCursorEndIndex(input.items, decodeThreadHistoryCursor(input.cursor)); const targetIndex = input.items.findIndex( (row) => (row.item.messageId ?? row.item.id) === input.throughEntryId, ); @@ -337,7 +460,7 @@ export function selectHistoryPageFromCursor(input: { const decoded = decodeThreadHistoryCursor(input.cursor); return selectOlderTimelinePage({ items: input.items, - exclusiveEndIndex: findCursorIndex(input.items, decoded), + exclusiveEndIndex: findCursorEndIndex(input.items, decoded), snapshotSequence: input.snapshotSequence, ...(input.rowEncodedBytes === undefined ? {} : { rowEncodedBytes: input.rowEncodedBytes }), policy: olderHistoryPagePolicy(input), @@ -351,7 +474,7 @@ export function selectHistoryPageFromCursor(input: { */ export function missingInterruptRequests( items: ReadonlyArray, - page: ReadonlyArray>, + page: ReadonlyArray>, ): Row[] { const runs = new Set(); for (const row of page) { @@ -407,16 +530,7 @@ function localTurnItemsForVisibleWindow( projection: OrchestrationV2ThreadProjection, visible: ReadonlyArray, ): OrchestrationV2TurnItem[] { - const localIds = new Set(); - for (const row of visible) { - if (isLocalProjectedRow(projection, row)) { - localIds.add(String(row.sourceItemId)); - } - } - if (localIds.size === 0) { - return []; - } - return projection.turnItems.filter((item) => localIds.has(String(item.id))); + return visible.filter((row) => isLocalProjectedRow(projection, row)).map((row) => row.item); } function messagesForBoundedProjection( diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index bea3b8a46097a..e1d6303b23506 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -640,6 +640,7 @@ function hasCompatibleOrchestrationProtocol(url: URL): boolean { function shouldUseBoundedThreadSnapshot(input: { readonly acceptBoundedSnapshot?: boolean; + readonly acceptDeferredWork?: boolean; }): boolean { return input.acceptBoundedSnapshot === true; } @@ -773,6 +774,7 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs readonly afterSequence?: number; readonly requestCompletionMarker?: boolean; readonly acceptBoundedSnapshot?: boolean; + readonly acceptDeferredWork?: boolean; readonly acceptCompactTurnItems?: boolean; readonly acceptDedupedBodies?: boolean; readonly acceptCompactIds?: boolean; @@ -860,6 +862,7 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs useBoundedSnapshot ? threadManagement.getThreadSnapshotWindow(input.threadId, { rowLimit: THREAD_HISTORY_SNAPSHOT_ROW_LIMIT, + deferWork: input.acceptDeferredWork === true, userTurnLimit: THREAD_HISTORY_PAGE_POLICY.maxUserTurns, }) : threadManagement.getThreadSnapshot(input.threadId) diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index aa082a268667d..3ee079809f14e 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -2693,6 +2693,13 @@ describe("v2 run and attempt history", () => { runId, label: "Old command", tone: "tool" as const, + projectedItem: { + sourceItemId: "old-work-anchor", + item: { + type: "command_execution", + deferredWork: { cursor: "old-work", itemCount: 200, lastOrdinal: 200 }, + }, + } as never, }, }, { @@ -2765,6 +2772,7 @@ describe("v2 run and attempt history", () => { runId, label: "Superseded attempt", expanded: false, + deferredWorkItemIds: ["old-work-anchor"], }); const expandedRows = deriveMessagesTimelineRows({ @@ -2781,6 +2789,52 @@ describe("v2 run and attempt history", () => { "steer-user-entry", "active-assistant-entry", ]); + const settledRows = deriveMessagesTimelineRows({ + ...common, + latestRun: { ...common.latestRun, status: "completed", completedAt: "2026-01-01T00:00:08Z" }, + timelineEntries: timelineEntries.map((entry) => + entry.kind === "message" && entry.id === "active-assistant-entry" + ? { ...entry, message: { ...entry.message, streaming: false } } + : entry, + ), + expandedRunIds: new Set([runId]), + }); + expect(settledRows.find((row) => row.kind === "attempt-fold")).toMatchObject({ + deferredWorkItemIds: ["old-work-anchor"], + }); + expect( + settledRows + .filter((row) => row.kind === "turn-fold") + .flatMap((row) => row.deferredWorkItemIds ?? []), + ).not.toContain("old-work-anchor"); + const deferredTailRows = deriveMessagesTimelineRows({ + ...common, + timelineEntries: [ + timelineEntries[0]!, + timelineEntries[2]!, + timelineEntries[1]!, + ...timelineEntries.slice(3), + ].map((entry) => ({ + ...entry, + attempt: + entry.attempt.id === supersededAttemptId + ? { ...entry.attempt, completedAt: DateTime.makeUnsafe("2026-01-01T00:00:08Z") } + : entry.attempt, + ...(entry.id === "superseded-assistant-entry" + ? { + projectedItem: { + item: { + type: "assistant_message", + ordinal: 2, + status: "completed", + completedAt: DateTime.makeUnsafe("2026-01-01T00:00:03Z"), + }, + } as never, + } + : {}), + })), + }); + expect(deferredTailRows.some((row) => row.kind === "attempt-fold")).toBe(true); }); describe("a steer that supersedes an attempt", () => { @@ -3015,6 +3069,35 @@ describe("v2 run and attempt history", () => { }); }); +it.each([ + [undefined, ["first"]], + [["first"], ["second"]], + [["first"], []], + [ + ["first", "second"], + ["second", "first"], + ], + [undefined, []], +] as const)("keeps deferred fold anchors current from %j to %j", (before, after) => { + const row: Extract = { + kind: "turn-fold", + id: "fold", + runId: RunId.make("run"), + createdAt: "2026-01-01T00:00:00Z", + label: "Worked for 1m", + expanded: true, + ...(before === undefined ? {} : { deferredWorkItemIds: before }), + }; + const previous = computeStableMessagesTimelineRows([row], { result: [], byId: new Map() }); + const nextRow = { ...row, deferredWorkItemIds: after }; + const next = computeStableMessagesTimelineRows([nextRow], previous); + const fold = next.result[0]; + expect(fold?.kind === "turn-fold" ? (fold.deferredWorkItemIds ?? []) : null).toEqual(after); + expect( + computeStableMessagesTimelineRows([{ ...nextRow, deferredWorkItemIds: [...after] }], next), + ).toBe(next); +}); + describe("streaming v2 row projection", () => { function fixture(text = "") { const source = makeStreamingTimelineFixture(text); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index ac9db2f7dd794..4ea9e852edfba 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -553,6 +553,7 @@ type MessagesTimelineRowContent = } | { kind: "turn-fold"; + deferredWorkItemIds?: ReadonlyArray; id: string; createdAt: string; runId: RunId; @@ -561,6 +562,7 @@ type MessagesTimelineRowContent = } | { kind: "attempt-fold"; + deferredWorkItemIds?: ReadonlyArray; id: string; createdAt: string; runId: RunId; @@ -709,6 +711,7 @@ interface TurnFold { } interface SupersededAttemptFold { + readonly deferredWorkItemIds: ReadonlyArray; readonly runId: RunId; readonly attemptId: RunAttemptId; readonly anchorEntryId: string; @@ -731,6 +734,18 @@ function completeSupersededReplyEntryIds( ) { continue; } + const previous = lastOutputByAttemptId.get(entry.attempt.id); + const deferredEnd = + previous?.kind === "work" + ? previous.entry.projectedItem?.item.deferredWork?.lastOrdinal + : undefined; + const ordinal = + entry.kind === "work" + ? entry.entry.projectedItem?.item.ordinal + : entry.kind === "message" + ? entry.projectedItem?.item.ordinal + : undefined; + if (deferredEnd !== undefined && ordinal !== undefined && deferredEnd > ordinal) continue; lastOutputByAttemptId.set(entry.attempt.id, entry); } const replyEntryIds = new Set(); @@ -790,6 +805,11 @@ function deriveSupersededAttemptFolds( const attempt = firstEntry?.attempt; if (firstEntry === undefined || attempt === undefined) continue; foldsByAnchorEntryId.set(firstEntry.id, { + deferredWorkItemIds: entries.flatMap((entry) => + entry.kind === "work" && entry.entry.projectedItem?.item.deferredWork + ? [String(entry.entry.projectedItem.sourceItemId)] + : [], + ), runId: attempt.runId, attemptId: attempt.id, anchorEntryId: firstEntry.id, @@ -1398,6 +1418,9 @@ export function deriveMessagesTimelineRows(input: { liveSubagentEntryIds, completeSupersededReplyIds, ); + const supersededWorkItemIds = new Set( + [...supersededFoldsByAnchorEntryId.values()].flatMap((fold) => fold.deferredWorkItemIds), + ); const activeVisualResponseRunIds = deriveActiveVisualResponseRunIds({ timelineEntries: timelineEntries, unsettledRunId, @@ -1658,9 +1681,18 @@ export function deriveMessagesTimelineRows(input: { const turnFold = foldsByAnchorEntryId.get(timelineEntry.id); if (turnFold) { + const deferredWorkItemIds = timelineEntries.flatMap((entry) => + turnFold.entryIds.has(entry.id) && + entry.kind === "work" && + entry.entry.projectedItem?.item.deferredWork && + !supersededWorkItemIds.has(String(entry.entry.projectedItem.sourceItemId)) + ? [String(entry.entry.projectedItem.sourceItemId)] + : [], + ); nextRows.push({ kind: "turn-fold", id: `turn-fold:${turnFold.runId}`, + ...(deferredWorkItemIds.length > 0 ? { deferredWorkItemIds } : {}), createdAt: turnFold.createdAt, runId: turnFold.runId, label: turnFold.label, @@ -1676,6 +1708,7 @@ export function deriveMessagesTimelineRows(input: { if (supersededFold) { nextRows.push({ kind: "attempt-fold", + deferredWorkItemIds: supersededFold.deferredWorkItemIds, id: `attempt-fold:${supersededFold.attemptId}`, createdAt: supersededFold.createdAt, runId: supersededFold.runId, @@ -2326,14 +2359,18 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean ); } + case "attempt-fold": case "turn-fold": { const bf = b as typeof a; - return a.createdAt === bf.createdAt && a.label === bf.label && a.expanded === bf.expanded; - } - - case "attempt-fold": { - const bf = b as typeof a; - return a.createdAt === bf.createdAt && a.label === bf.label && a.expanded === bf.expanded; + const anchors = a.deferredWorkItemIds ?? []; + const nextAnchors = bf.deferredWorkItemIds ?? []; + return ( + a.createdAt === bf.createdAt && + a.label === bf.label && + a.expanded === bf.expanded && + anchors.length === nextAnchors.length && + anchors.every((id, index) => id === nextAnchors[index]) + ); } case "context-compaction": { diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index b74f9edd595c9..8a621e47eaba7 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -1,3 +1,5 @@ +import { threadEnvironment } from "../../state/threads"; +import { useAtomCommand } from "../../state/use-atom-command"; import type { ToolCallDiffTarget } from "../../diffPanelStore"; import { AudioPreviewUnmountContext } from "../files/AudioPreview"; import { ThreadFindTimelineContext } from "./ThreadFindProvider"; @@ -36,6 +38,8 @@ import { use, useContext, useLayoutEffect, + useEffect, + useEffectEvent, useRef, useState, type ReactNode, @@ -52,6 +56,7 @@ import { type ChatFileAttachment, type TurnDiffSummary } from "../../types"; import { ArrowRightIcon, BotIcon, CircleAlertIcon, Minimize2Icon } from "lucide-react"; import { ChevronDown, ChevronRight } from "lucide"; import { MorphIcon } from "~/components/MorphIcon"; +import { Skeleton } from "../ui/skeleton"; import { ExpandedImagePreview } from "./ExpandedImagePreview"; import { CHAT_TIMELINE_ANCHOR_OFFSET, @@ -1517,7 +1522,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time {row.kind === "thinking" ? : null} ) : null} - {row.kind === "turn-fold" ? : null} + {row.kind === "turn-fold" ? : null} {row.kind === "attempt-fold" ? : null} {row.kind === "context-compaction" ? : null} {row.kind === "message" && row.message.role === "user" ? : null} @@ -1609,48 +1614,123 @@ function ContextCompactionTimelineRow({ ); } +function useDeferredWorkLoading( + row: { expanded: boolean; deferredWorkItemIds?: ReadonlyArray }, + onToggle: () => void, +) { + const ctx = use(TimelineRowCtx); + const loadWork = useAtomCommand(threadEnvironment.loadEarlierHistory, { reportFailure: false }); + const ref = parseScopedThreadKey(ctx.routeThreadKey); + const environmentId = ref?.environmentId; + const threadId = ref?.threadId; + const anchorsKey = row.deferredWorkItemIds?.join("\n") ?? ""; + const [failed, setFailed] = useState(false); + const load = () => { + if (!anchorsKey || environmentId === undefined || threadId === undefined) return; + void Promise.all( + anchorsKey + .split("\n") + .map((workAnchorId) => loadWork({ environmentId, input: { threadId, workAnchorId } })), + ).then((results) => + setFailed( + results.some((result) => result._tag === "Failure" || result.value._tag === "error"), + ), + ); + }; + const loadOnExpand = useEffectEvent(load); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Restored expanded folds load their deferred server history on mount. + useEffect(() => { + if (row.expanded && anchorsKey && environmentId && threadId) loadOnExpand(); + }, [row.expanded, anchorsKey, environmentId, threadId]); + const error = anchorsKey && failed ? "Couldn't load work. Click to retry." : null; + const loading = ref !== null && row.expanded && anchorsKey !== "" && !failed; + const toggle = () => { + setFailed(false); + if (error && row.expanded) load(); + else onToggle(); + }; + + return { loading, error, toggle }; +} + +function WorkHistorySkeleton() { + return ( +
    + {[0, 1, 2].map((index) => ( + + ))} +
    + ); +} + function TurnFoldTimelineRow({ row }: { row: Extract }) { const ctx = use(TimelineRowCtx); + const { loading, error, toggle } = useDeferredWorkLoading(row, () => + ctx.onToggleTurnFold(row.runId), + ); return ( -
    - - +
    +
    + + +
    + {loading ? : null}
    ); } function AttemptFoldTimelineRow({ row }: { row: Extract }) { const ctx = use(TimelineRowCtx); + const { loading, error, toggle } = useDeferredWorkLoading(row, () => + ctx.onToggleAttemptFold(row.attemptId), + ); return ( - +
    + + {loading ? : null} +
    ); } diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index b67da2cc8f6cb..45a070b9806b1 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -1284,7 +1284,7 @@ export function PullRequestDetailPanel({ openOnHostText={openOnHostText} onBack={onBack} /> -
    +
    {detail ? ( {!nativeStack && supportsStackActions && nativeStackQuery.error ? ( diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts index de213de2f3c1c..f905376dc341a 100644 --- a/apps/web/src/session-logic.test.ts +++ b/apps/web/src/session-logic.test.ts @@ -557,6 +557,20 @@ describe("V2 session presentation", () => { if (threadCreatedEntry?.kind === "work") { expect(threadCreatedEntry.entry.projectedItem?.item.type).toBe("thread_created"); } + expect( + deriveTimelineEntriesFromVisibleTurnItems({ + visibleTurnItems: [ + { + ...visibleTurnItems.at(-1)!, + item: { + ...workspacePreparationItem, + deferredWork: { cursor: "work-page", itemCount: 100, lastOrdinal: 107 }, + }, + }, + ], + optimisticMessages: [], + }).map((entry) => entry.id), + ).toEqual([workspacePreparationItem.id]); }); it.each(["pending", "running", "completed"] as const)( diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index 362d9fb9451a4..37d7ad27be5a7 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -601,7 +601,7 @@ export function deriveTimelineEntriesFromVisibleTurnItems( ); for (const row of input.visibleTurnItems) { const { item } = row; - if (turnItemIsWorkspacePreparation(item)) continue; + if (turnItemIsWorkspacePreparation(item) && !item.deferredWork) continue; if (item.type === "checkpoint") continue; if ( item.type === "user_message" && diff --git a/docs/internals/performance-regressions.md b/docs/internals/performance-regressions.md index 51760756c1085..4458f1af93461 100644 --- a/docs/internals/performance-regressions.md +++ b/docs/internals/performance-regressions.md @@ -15,7 +15,9 @@ The v2 checks pin these invariants: - Cold opens and history pages stop at about 1 MiB of encoded rows. A window that holds a user turn also stops at 10 user turns (20 on older pages) or 500 rows, so ordinary turns stay whole. Any other window, including the inside of one turn longer than 500 rows, stops at 75 rows. The - snapshot query applies the same rule before it decodes payloads. Required control records and + snapshot query applies the same rule before it decodes payloads. Clients can opt into deferring + large work groups until expansion. Messages and items outside those groups remain in normal + history paging. Required control records and the at-least-one-row rule can exceed the byte target; it is not a hard cap. - The bounded snapshot does not retain the full duplicate conversation-message table. - Older activity is fetched in bounded HTTP pages and merged without disturbing the live scroll @@ -32,8 +34,9 @@ The v2 checks pin these invariants: projects small can increase server allocations on repeated large tool updates. - Raw command output, dynamic-tool result bodies, and inline file-change bodies are omitted at the wire boundary, including small outputs. Explicit failure flags and bounded result IDs - preserve status and grouped action counts without shipping those bodies. Subagent prompts and - results, reasoning text, command lines, search results, and checkpoint file lists still ship. + preserve status and grouped action counts without shipping those bodies. Reasoning text, + command lines, and search results ship when their work group loads. Subagent prompts and results + and checkpoint control records still accompany the initial window. Persisted events remain complete; the existing diff endpoints still provide file content when requested. Explicit cross-environment transcript exports preserve full tool bodies so the destination diff --git a/packages/client-runtime/src/state/boundedThreadSnapshotHttp.ts b/packages/client-runtime/src/state/boundedThreadSnapshotHttp.ts index b7cb95f703100..e3e9b5bb57fec 100644 --- a/packages/client-runtime/src/state/boundedThreadSnapshotHttp.ts +++ b/packages/client-runtime/src/state/boundedThreadSnapshotHttp.ts @@ -30,7 +30,12 @@ export const fetchEnvironmentBoundedThreadSnapshot = Effect.fn( }) { const endpoint = { params: { threadId: input.threadId }, - query: { compactTurnItems: "1", dedupeBodies: "1", compactIds: "1" }, + query: { + compactTurnItems: "1", + dedupeBodies: "1", + compactIds: "1", + deferWork: "1", + }, }; return yield* executeAuthenticatedEnvironmentHttpRequest({ ...input, diff --git a/packages/client-runtime/src/state/orchestrationV2Projection.test.ts b/packages/client-runtime/src/state/orchestrationV2Projection.test.ts index e0680c17c46f8..f6ba3e9f0c1a7 100644 --- a/packages/client-runtime/src/state/orchestrationV2Projection.test.ts +++ b/packages/client-runtime/src/state/orchestrationV2Projection.test.ts @@ -219,8 +219,9 @@ describe("applyOrchestrationV2ProjectionEvent", () => { expect(next?.visibleTurnItems[0]).toBe(visibleTurnItems[0]); }); - it("replaces only the updated visible item when membership is unchanged", () => { - const first = commandItem("item-first", "first"); + it("replaces only the updated visible item and retains its deferred work cursor", () => { + const deferredWork = { cursor: "remaining-work", itemCount: 100, lastOrdinal: 101 }; + const first = { ...commandItem("item-first", "first"), deferredWork }; const second = commandItem("item-second", "second"); const firstRow = { position: 0, @@ -253,9 +254,10 @@ describe("applyOrchestrationV2ProjectionEvent", () => { } as OrchestrationV2DomainEvent; const next = applyOrchestrationV2ProjectionEvent(projection, event); + expect(next?.visibleTurnItems[0]?.item.deferredWork).toEqual(deferredWork); expect(next?.visibleTurnItems).not.toBe(projection.visibleTurnItems); expect(next?.visibleTurnItems[0]).not.toBe(firstRow); - expect(next?.visibleTurnItems[0]?.item).toBe(updated); + expect(next?.visibleTurnItems[0]?.item).toEqual({ ...updated, deferredWork }); expect(next?.visibleTurnItems[1]).toBe(secondRow); }); diff --git a/packages/client-runtime/src/state/orchestrationV2Projection.ts b/packages/client-runtime/src/state/orchestrationV2Projection.ts index ffe9eb14dfa2d..fbba7d1bd9dd4 100644 --- a/packages/client-runtime/src/state/orchestrationV2Projection.ts +++ b/packages/client-runtime/src/state/orchestrationV2Projection.ts @@ -370,12 +370,15 @@ export function applyOrchestrationV2ProjectionEvent( case "plan.updated": return { ...base, plans: upsertEntity(base.plans, event.payload) }; case "turn-item.updated": { - const payload = restoreTurnItemBodies(event.payload, latestBodies(projection)); + let payload = restoreTurnItemBodies(event.payload, latestBodies(projection)); // Streamed updates land on the newest items, so search from the end. let itemIndex = projection.turnItems.length - 1; while (itemIndex >= 0 && projection.turnItems[itemIndex]!.id !== payload.id) { itemIndex -= 1; } + const deferredWork = + itemIndex === -1 ? undefined : projection.turnItems[itemIndex]?.deferredWork; + if (deferredWork !== undefined) payload = { ...payload, deferredWork }; if ( partialTimeline && itemIndex === -1 && diff --git a/packages/client-runtime/src/state/threadCommands.ts b/packages/client-runtime/src/state/threadCommands.ts index 6070638c57a66..0f34a926676c8 100644 --- a/packages/client-runtime/src/state/threadCommands.ts +++ b/packages/client-runtime/src/state/threadCommands.ts @@ -64,6 +64,7 @@ import * as ThreadHistoryController from "./threadHistoryController.ts"; export type LoadEarlierThreadHistoryInput = { readonly threadId: ThreadId; readonly throughEntryId?: string; + readonly workAnchorId?: string; }; export function createThreadEnvironmentAtoms( @@ -90,6 +91,7 @@ export function createThreadEnvironmentAtoms( supervisor.target.environmentId, input.threadId, input.throughEntryId, + input.workAnchorId, ); }); diff --git a/packages/client-runtime/src/state/threadHistoryController.ts b/packages/client-runtime/src/state/threadHistoryController.ts index c9ae1843ff27d..1c8818fd54db1 100644 --- a/packages/client-runtime/src/state/threadHistoryController.ts +++ b/packages/client-runtime/src/state/threadHistoryController.ts @@ -13,7 +13,10 @@ export type ThreadHistoryLoadEarlierResult = | { readonly _tag: "error"; readonly message: string }; export type ThreadHistoryHandler = { - readonly loadEarlier: (throughEntryId?: string) => Effect.Effect; + readonly loadEarlier: ( + throughEntryId?: string, + workAnchorId?: string, + ) => Effect.Effect; readonly reconcilePendingWork: () => Effect.Effect; }; @@ -36,6 +39,7 @@ export class ThreadHistoryController extends Context.Service< environmentId: EnvironmentId, threadId: ThreadId, throughEntryId?: string, + workAnchorId?: string, ) => Effect.Effect; readonly reconcilePendingWork: ( environmentId: EnvironmentId, @@ -81,14 +85,14 @@ export const layer: Layer.Layer = Layer.effect( }); }), loadEarlier: Effect.fn("ThreadHistoryController.loadEarlier")( - function (environmentId, threadId, throughEntryId) { + function (environmentId, threadId, throughEntryId, workAnchorId) { return Ref.get(handlers).pipe( Effect.flatMap((current) => { const handler = current.get(threadKey({ environmentId, threadId })); if (handler === undefined) { return Effect.succeed({ _tag: "noop" } satisfies ThreadHistoryLoadEarlierResult); } - return handler.loadEarlier(throughEntryId); + return handler.loadEarlier(throughEntryId, workAnchorId); }), ); }, diff --git a/packages/client-runtime/src/state/threadHistoryHttp.ts b/packages/client-runtime/src/state/threadHistoryHttp.ts index a9714172e44bd..f0ca836248aff 100644 --- a/packages/client-runtime/src/state/threadHistoryHttp.ts +++ b/packages/client-runtime/src/state/threadHistoryHttp.ts @@ -19,7 +19,7 @@ export const fetchEnvironmentThreadHistoryPage = Effect.fn( readonly threadId: ThreadId; readonly cursor: string; readonly throughEntryId?: string | undefined; - readonly view?: "conversation" | "activity" | undefined; + readonly view?: "conversation" | "activity" | "work" | undefined; readonly signer: Option.Option; readonly remoteAuthorization?: Option.Option; readonly timeoutMs?: number; @@ -29,6 +29,7 @@ export const fetchEnvironmentThreadHistoryPage = Effect.fn( query: { cursor: input.cursor, compactIds: "1", + ...(input.throughEntryId === undefined ? { deferWork: "1" } : {}), ...(input.view === undefined ? {} : { view: input.view }), ...(input.throughEntryId === undefined ? {} : { throughEntryId: input.throughEntryId }), }, diff --git a/packages/client-runtime/src/state/threadHistoryMerge.test.ts b/packages/client-runtime/src/state/threadHistoryMerge.test.ts index 4dd4e7cef5210..59e1ea3652e52 100644 --- a/packages/client-runtime/src/state/threadHistoryMerge.test.ts +++ b/packages/client-runtime/src/state/threadHistoryMerge.test.ts @@ -64,6 +64,29 @@ describe("threadHistoryMerge", () => { expect(complete.visibleTurnItems[1]?.item).toBe(updated.item); expect(complete.visibleTurnItems.map((entry) => entry.position)).toEqual([0, 1, 2, 3, 4]); expect(new Set(complete.turnItems.map((item) => item.id)).size).toBe(5); + const anchorItem = { + ...updated.item, + deferredWork: { cursor: "work", itemCount: 4, lastOrdinal: 5 }, + }; + const deferred = { + ...live, + turnItems: live.turnItems.map((item) => (item.id === anchorItem.id ? anchorItem : item)), + visibleTurnItems: live.visibleTurnItems.map((entry) => + entry.item.id === anchorItem.id ? { ...entry, item: anchorItem } : entry, + ), + }; + const loadedWork = mergeOlderHistoryIntoProjection(deferred, [row(1), row(2), row(3)], { + anchorId: anchorItem.id, + nextCursor: null, + }); + expect(loadedWork.visibleTurnItems.map((entry) => entry.sourceItemId)).toEqual([ + "item-1", + "item-2", + "item-3", + "item-4", + ]); + expect(loadedWork.visibleTurnItems[0]?.item.title).toBe("newer live title"); + expect(loadedWork.visibleTurnItems[0]?.item.deferredWork).toBeUndefined(); const hidden = { ...partial, visibleTurnItems: partial.visibleTurnItems.filter( diff --git a/packages/client-runtime/src/state/threadHistoryMerge.ts b/packages/client-runtime/src/state/threadHistoryMerge.ts index 24840ee28420a..6fd678b66b129 100644 --- a/packages/client-runtime/src/state/threadHistoryMerge.ts +++ b/packages/client-runtime/src/state/threadHistoryMerge.ts @@ -52,11 +52,19 @@ function renumberVisible( export function mergeOlderHistoryIntoProjection( projection: OrchestrationV2ThreadProjection, olderItems: ReadonlyArray, + work?: { readonly anchorId: string; readonly nextCursor: string | null }, ): OrchestrationV2ThreadProjection { - if (olderItems.length === 0) { + if (olderItems.length === 0 && work === undefined) { return projection; } + const start = + work === undefined + ? -1 + : projection.visibleTurnItems.findIndex((row) => row.sourceItemId === work.anchorId); + const anchor = projection.visibleTurnItems[start]; + const deferred = anchor?.item.deferredWork; + if (work !== undefined && deferred === undefined) return projection; const currentByKey = new Map( projection.visibleTurnItems.map((row) => [projectedItemKey(row), row]), ); @@ -64,6 +72,15 @@ export function mergeOlderHistoryIntoProjection( const pageKeys = new Set(); const page: OrchestrationV2ProjectedTurnItem[] = []; for (const pageRow of olderItems) { + if ( + work && + anchor && + deferred && + (pageRow.sourceThreadId !== anchor.sourceThreadId || + pageRow.item.ordinal < anchor.item.ordinal || + pageRow.item.ordinal > deferred.lastOrdinal) + ) + continue; const key = projectedItemKey(pageRow); if (pageKeys.has(key)) continue; let row = currentByKey.get(key) ?? pageRow; @@ -94,11 +111,43 @@ export function mergeOlderHistoryIntoProjection( ) turnItemById.set(String(row.sourceItemId), row.item); } - if (page.length === 0) return projection; - const visible = [ + if (page.length === 0 && work === undefined) return projection; + let visible = [ ...page, ...projection.visibleTurnItems.filter((row) => !pageKeys.has(projectedItemKey(row))), ]; + if (work && anchor && deferred) { + let end = start + 1; + while (end < projection.visibleTurnItems.length) { + const row = projection.visibleTurnItems[end]!; + if ( + row.sourceThreadId !== anchor.sourceThreadId || + row.visibility === "synthetic" || + row.item.ordinal > deferred.lastOrdinal + ) + break; + end += 1; + } + const item = { ...anchor.item }; + if (work.nextCursor === null) delete item.deferredWork; + else item.deferredWork = { ...deferred, cursor: work.nextCursor }; + const updated = { ...anchor, item }; + const section = [ + ...page, + ...projection.visibleTurnItems + .slice(start, end) + .filter((row) => !pageKeys.has(projectedItemKey(row))), + ]; + const ordered = section + .map((row) => (row.sourceItemId === anchor.sourceItemId ? updated : row)) + .sort((left, right) => left.item.ordinal - right.item.ordinal); + visible = [ + ...projection.visibleTurnItems.slice(0, start), + ...ordered, + ...projection.visibleTurnItems.slice(end), + ]; + if (anchor.visibility === "local") turnItemById.set(String(updated.item.id), updated.item); + } if ( visible.length === projection.visibleTurnItems.length && visible.every((row, index) => row === projection.visibleTurnItems[index]) diff --git a/packages/client-runtime/src/state/threads-sync.test.ts b/packages/client-runtime/src/state/threads-sync.test.ts index 712eaffe77f40..c8c212db41ca1 100644 --- a/packages/client-runtime/src/state/threads-sync.test.ts +++ b/packages/client-runtime/src/state/threads-sync.test.ts @@ -22,6 +22,7 @@ import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Scope from "effect/Scope"; +import * as Scheduler from "effect/Scheduler"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; @@ -269,6 +270,8 @@ const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (o return { threadState, + loadWork: (anchorId: string) => + historyController.loadEarlier(TARGET.environmentId, THREAD_ID, undefined, anchorId), loadEarlier: (throughEntryId?: string) => historyController.loadEarlier(TARGET.environmentId, THREAD_ID, throughEntryId), reconcilePendingWork: historyController.reconcilePendingWork(TARGET.environmentId, THREAD_ID), @@ -688,7 +691,7 @@ describe("EnvironmentThreads", () => { }), ); - describe("Stop on cached work the server already finished (#18188)", () => { + describe("cached work (#18188)", () => { const at = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"); const parentThreadId = ThreadId.make("thread:parent"); const command = ( @@ -696,7 +699,7 @@ describe("EnvironmentThreads", () => { status: "running" | "completed", exitCode?: number, ordinal = id === "older-command" ? 1 : 2, - ): OrchestrationV2TurnItem => ({ + ): Extract => ({ id: TurnItemId.make(id), threadId: THREAD_ID, runId: null, @@ -723,6 +726,261 @@ describe("EnvironmentThreads", () => { sourceItemId: item.id, item, }); + const cachedItem = (item: OrchestrationV2TurnItem) => ({ + ...BASE_PROJECTION, + turnItems: [item], + visibleTurnItems: [localRow(item, 0)], + }); + const historyPage = ( + request: Parameters[0], + items: ReadonlyArray>, + nextCursor: string | null, + ) => + HttpClientResponse.fromWeb( + request, + Response.json({ + snapshotSequence: CACHED_SNAPSHOT_SEQUENCE, + items, + nextCursor, + hasMoreHistory: nextCursor !== null, + }), + ); + it.effect("loads a long unwrapped turn through its user message and resumes failed pages", () => + Effect.gen(function* () { + const prompt = { + ...command("prompt", "completed", 0, 0), + type: "user_message" as const, + messageId: MessageId.make("prompt"), + inputIntent: "turn_start" as const, + createdBy: "user" as const, + creationSource: "web" as const, + text: "Do the work", + attachments: [], + }; + const work = Array.from({ length: 1_000 }, (_, index) => + command(`work-${index + 1}`, "completed", 0, index + 1), + ); + const older = [prompt, ...work.slice(0, -1)]; + const tail = work.at(-1)!; + const requests: string[] = []; + let failed = false; + const harness = yield* makeHarness({ + cached: cachedItem(tail), + cachedHistory: { historyCursor: "1000", hasMoreHistory: true }, + historyHttpClient: HttpClient.make((request, url) => { + const cursor = url.searchParams.get("cursor")!; + requests.push(cursor); + if (cursor === "before-user") return Effect.succeed(historyPage(request, [], cursor)); + if (cursor === "925" && !failed) { + failed = true; + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(null, { status: 503 })), + ); + } + const end = Number(cursor); + expect(Number.isFinite(end)).toBe(true); + const start = Math.max(0, end - 75); + return Effect.succeed( + historyPage( + request, + older.slice(start, end).map(localRow), + start === 0 ? "before-user" : String(start), + ), + ); + }), + }); + expect((yield* harness.loadEarlier())._tag).toBe("error"); + expect(requests).toEqual(["1000", "925"]); + expect(yield* harness.loadEarlier()).toEqual({ _tag: "loaded" }); + const state = yield* SubscriptionRef.get(harness.threadState); + expect( + Option.getOrThrow(state.data).visibleTurnItems.map((row) => row.sourceItemId), + ).toEqual([prompt, ...work].map((item) => item.id)); + expect(state.history).toMatchObject({ + historyCursor: "before-user", + hasMoreHistory: true, + loading: false, + }); + expect(requests.slice(1, 3)).toEqual(["925", "925"]); + expect(yield* harness.loadEarlier()).toEqual({ + _tag: "error", + message: "History did not advance.", + }); + expect((yield* SubscriptionRef.get(harness.threadState)).history.loading).toBe(false); + }), + ); + it.effect("loads deferred work on demand and resumes a failed page", () => + Effect.gen(function* () { + const anchor = { + ...command("anchor", "completed", 0, 1), + deferredWork: { cursor: "first", itemCount: 3, lastOrdinal: 3 }, + }; + const requests: string[] = []; + let failed = false; + const harness = yield* makeHarness({ + cached: cachedItem(anchor), + cachedHistory: { historyCursor: "older", hasMoreHistory: true }, + historyHttpClient: HttpClient.make((request, url) => { + expect(url.searchParams.get("view")).toBe("work"); + const cursor = url.searchParams.get("cursor")!; + requests.push(cursor); + if (cursor === "second" && !failed) { + failed = true; + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response("Unavailable", { status: 503 })), + ); + } + return Effect.succeed( + historyPage( + request, + [ + localRow( + command(`work-${cursor}`, "completed", 0, cursor === "first" ? 3 : 2), + 0, + ), + ], + cursor === "first" ? "second" : null, + ), + ); + }), + }); + expect(requests).toEqual([]); + expect((yield* harness.loadWork(anchor.id))._tag).toBe("error"); + const partial = Option.getOrThrow((yield* SubscriptionRef.get(harness.threadState)).data); + expect(partial.visibleTurnItems[0]?.item.deferredWork?.cursor).toBe("second"); + expect(yield* harness.loadWork(anchor.id)).toEqual({ _tag: "loaded" }); + const state = yield* SubscriptionRef.get(harness.threadState); + expect( + Option.getOrThrow(state.data).visibleTurnItems.map((row) => row.item.ordinal), + ).toEqual([1, 2, 3]); + expect(state.history.historyCursor).toBe("older"); + expect(requests).toEqual(["first", "second", "second"]); + }), + ); + + it.effect.each(["deferred", "complete"] as const)( + "settles a replaced work request when the new snapshot is %s", + (mode) => + Effect.gen(function* () { + const anchor = { + ...command("anchor", "completed"), + deferredWork: { cursor: "before", itemCount: 80, lastOrdinal: 80 }, + }; + const asked = yield* Deferred.make(); + const release = yield* Deferred.make(); + const harness = yield* makeHarness({ + cached: cachedItem(anchor), + historyHttpClient: HttpClient.make((request) => + Effect.gen(function* () { + yield* Deferred.succeed(asked, undefined); + yield* Deferred.await(release); + return historyPage(request, [], null); + }), + ), + }); + const loading = yield* harness.loadWork(anchor.id).pipe(Effect.forkChild); + yield* Deferred.await(asked); + const replacement = + mode === "deferred" + ? { ...anchor, deferredWork: { ...anchor.deferredWork, cursor: "after" } } + : command("anchor", "completed"); + yield* Queue.offer( + harness.inputs, + snapshot( + { + ...BASE_PROJECTION, + thread: { ...BASE_PROJECTION.thread, title: "Replacement" }, + turnItems: [replacement], + visibleTurnItems: [localRow(replacement, 0)], + }, + CACHED_SNAPSHOT_SEQUENCE + 1, + ), + ); + yield* awaitThreadState( + harness.observed, + (value) => Option.getOrNull(value.data)?.thread.title === "Replacement", + ); + yield* Deferred.succeed(release, undefined); + expect((yield* Fiber.join(loading))._tag).toBe(mode === "deferred" ? "error" : "noop"); + }), + ); + + it.effect("does not mark replacement history loading when a queued request becomes stale", () => + Effect.gen(function* () { + const harness = yield* makeHarness({ + cached: BASE_PROJECTION, + cachedHistory: { historyCursor: "older", hasMoreHistory: true }, + historyHttpClient: HttpClient.make((request) => + Effect.succeed(historyPage(request, [], null)), + ), + }); + const held = yield* Deferred.make(); + const release = yield* Deferred.make(); + const replacement = yield* SubscriptionRef.updateEffect(harness.threadState, (latest) => + Deferred.succeed(held, undefined).pipe( + Effect.andThen(Deferred.await(release)), + Effect.as({ ...latest, history: { ...latest.history, historyCursor: "replacement" } }), + ), + ).pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(held); + const dispatcher = new Scheduler.MixedScheduler("sync").makeDispatcher(); + const loading = yield* harness.loadEarlier().pipe( + Effect.forkChild({ startImmediately: true }), + Effect.provideService(Scheduler.Scheduler, { + executionMode: "sync", + shouldYield: () => false, + makeDispatcher: () => dispatcher, + }), + ); + dispatcher.flush(); + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(replacement); + dispatcher.flush(); + expect(yield* Fiber.join(loading)).toEqual({ _tag: "noop" }); + expect((yield* SubscriptionRef.get(harness.threadState)).history).toMatchObject({ + historyCursor: "replacement", + loading: false, + }); + }), + ); + + it.effect("loads targeted messages without fetching unrelated deferred work", () => + Effect.gen(function* () { + const anchor = { + ...command("anchor", "completed"), + deferredWork: { cursor: "work", itemCount: 80, lastOrdinal: 80 }, + }; + const message = { + ...command("older-message", "completed"), + type: "assistant_message" as const, + messageId: MessageId.make("older-message"), + text: "Older response", + streaming: false, + }; + const views: Array = []; + const harness = yield* makeHarness({ + cached: cachedItem(anchor), + cachedHistory: { historyCursor: "older", hasMoreHistory: true }, + historyHttpClient: HttpClient.make((request, url) => { + views.push(url.searchParams.get("view")); + return Effect.succeed( + url.searchParams.get("view") === "work" + ? HttpClientResponse.fromWeb(request, new Response("Unavailable", { status: 503 })) + : historyPage(request, [localRow(message, 0)], null), + ); + }), + }); + expect(yield* harness.loadEarlier(message.messageId)).toEqual({ _tag: "loaded" }); + const state = yield* SubscriptionRef.get(harness.threadState); + expect( + Option.getOrThrow(state.data).visibleTurnItems.some( + (row) => row.sourceItemId === message.id, + ), + ).toBe(true); + expect(views).toEqual(["conversation", null]); + }), + ); + // A fork's parent row keeps its own source; the child's Stop must not touch it. const inheritedRow = { position: 0, @@ -1248,6 +1506,17 @@ describe("EnvironmentThreads", () => { text: "COD4 result", streaming: false, }; + const prompt = { + ...message, + id: "item:older-prompt", + messageId: "message:older-prompt", + ordinal: 0, + type: "user_message", + inputIntent: "turn_start", + createdBy: "user", + creationSource: "web", + attachments: [], + }; const activity = { ...common, id: "item:older-command", @@ -1270,6 +1539,16 @@ describe("EnvironmentThreads", () => { const harness = yield* makeHarness({ historyHttpClient: HttpClient.make((request, url) => Effect.gen(function* () { + if (url.searchParams.get("cursor") === "next-cursor") + return HttpClientResponse.fromWeb( + request, + Response.json({ + snapshotSequence: 14, + items: [projected(prompt, 0)], + nextCursor: "before-prompt", + hasMoreHistory: true, + }), + ); expect(url.searchParams.get("cursor")).toBe("progressive-cursor"); const conversationOnly = url.searchParams.get("view") === "conversation"; if (!conversationOnly && activityRequests++ === 0) { @@ -1341,14 +1620,16 @@ describe("EnvironmentThreads", () => { const complete = yield* SubscriptionRef.get(harness.threadState); expect(complete.history).toMatchObject({ loading: false, - historyCursor: "next-cursor", + historyCursor: mode === "retry" ? "before-prompt" : "next-cursor", error: null, latestLocalTurnOrdinal: 47, }); expect( Option.getOrThrow(complete.data).visibleTurnItems.map((row) => row.sourceItemId), - ).toEqual([message.id, activity.id]); - expect(Option.getOrThrow(complete.data).turnItems).toHaveLength(2); + ).toEqual( + mode === "retry" ? [prompt.id, message.id, activity.id] : [message.id, activity.id], + ); + expect(Option.getOrThrow(complete.data).turnItems).toHaveLength(mode === "retry" ? 3 : 2); }), ); diff --git a/packages/client-runtime/src/state/threads.ts b/packages/client-runtime/src/state/threads.ts index f46cea41fc8f6..3cb4192f0ab6c 100644 --- a/packages/client-runtime/src/state/threads.ts +++ b/packages/client-runtime/src/state/threads.ts @@ -658,29 +658,40 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make const loadEarlier = Effect.fn("EnvironmentThreadState.loadEarlier")(function* ( throughEntryId?: string, - ) { + workAnchorId?: string, + ): Effect.fn.Return { + const workCursor = (latest: EnvironmentThreadState) => + Option.getOrNull(latest.data)?.visibleTurnItems.find( + (row) => row.sourceItemId === workAnchorId, + )?.item.deferredWork?.cursor ?? null; const current = yield* SubscriptionRef.get(state); + const initialCursor = + workAnchorId === undefined ? current.history.historyCursor : workCursor(current); if ( current.status === "deleted" || Option.isNone(current.data) || - !current.history.hasMoreHistory || - current.history.historyCursor === null - ) { - return { _tag: "noop" } satisfies ThreadHistoryController.ThreadHistoryLoadEarlierResult; - } - if (current.history.loading) { - return { _tag: "busy" } satisfies ThreadHistoryController.ThreadHistoryLoadEarlierResult; - } - - // Capture the cursor that initiated this request. Completions/failures must - // no-op if a socket or new bounded snapshot replaced progressive meta mid-flight. - const requestCursor = current.history.historyCursor; - yield* patchHistoryMeta((history) => - isActiveHistoryRequestCursor(requestCursor, history) - ? { ...history, loading: true, error: null } - : history, - ); - + initialCursor === null || + (workAnchorId === undefined && !current.history.hasMoreHistory) + ) + return { _tag: "noop" }; + if (workAnchorId === undefined && current.history.loading) return { _tag: "busy" }; + let requestCursor = initialCursor; + const isCurrent = (latest: EnvironmentThreadState) => + workAnchorId === undefined + ? isActiveHistoryRequestCursor(requestCursor, latest.history) + : workCursor(latest) === requestCursor; + const staleResult = ( + latest: EnvironmentThreadState, + ): ThreadHistoryController.ThreadHistoryLoadEarlierResult => + workAnchorId !== undefined && workCursor(latest) !== null + ? { _tag: "error", message: "Work history changed. Retry loading it." } + : { _tag: "noop" }; + if (workAnchorId === undefined) + yield* patchHistoryMeta((history) => + isActiveHistoryRequestCursor(requestCursor, history) + ? { ...history, loading: true, error: null } + : history, + ); const failLoad = (message: string) => SubscriptionRef.modify( state, @@ -690,72 +701,108 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make ThreadHistoryController.ThreadHistoryLoadEarlierResult, EnvironmentThreadState, ] => - isActiveHistoryRequestCursor(requestCursor, latest.history) + isCurrent(latest) ? [ { _tag: "error", message }, { ...latest, - history: { ...latest.history, loading: false, error: message }, + history: + workAnchorId === undefined + ? { ...latest.history, loading: false, error: message } + : latest.history, }, ] - : [{ _tag: "noop" }, latest], + : [staleResult(latest), latest], ); const runLoad = Effect.gen(function* () { - const preparedOption = yield* SubscriptionRef.get(supervisor.prepared); - if (Option.isNone(preparedOption) || Option.isNone(httpClient)) - return yield* failLoad("Environment is not connected."); - - const views = - throughEntryId === undefined ? [undefined] : ["conversation" as const, undefined]; - for (const view of views) { - const pageResult = yield* fetchEnvironmentThreadHistoryPage({ - prepared: preparedOption.value, - threadId, - cursor: requestCursor, - throughEntryId, - view, - signer: dpopSigner, - remoteAuthorization, - }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient.value), Effect.result); - if (Result.isFailure(pageResult)) - return yield* failLoad(formatHistoryError(pageResult.failure)); - const page = pageResult.success; - const complete = view === undefined; - const waiting = yield* Ref.get(awaitingCompletion); - const result = yield* applyLock.withPermits(1)( - SubscriptionRef.modify( - state, - ( - latest, - ): readonly [ - ThreadHistoryController.ThreadHistoryLoadEarlierResult, - EnvironmentThreadState, - ] => { - if (!isActiveHistoryRequestCursor(requestCursor, latest.history)) - return [{ _tag: "noop" }, latest]; - if (Option.isNone(latest.data) || latest.status === "deleted") - return [{ _tag: "noop" }, { ...latest, history: EMPTY_THREAD_HISTORY_META }]; - return [ - { _tag: "loaded" }, - { - ...latest, - data: Option.some(mergeOlderHistoryIntoProjection(latest.data.value, page.items)), - status: complete && waiting ? "synchronizing" : latest.status, - history: complete - ? applyHistoryPageMeta(latest.history, page) - : { ...latest.history, expanded: true }, - }, - ]; - }, - ), - ); - if (result._tag !== "loaded") return result; - if (complete) yield* remember; + while (true) { + const preparedOption = yield* SubscriptionRef.get(supervisor.prepared); + if (Option.isNone(preparedOption) || Option.isNone(httpClient)) + return yield* failLoad("Environment is not connected."); + const views = + workAnchorId !== undefined + ? ["work" as const] + : throughEntryId === undefined + ? [undefined] + : ["conversation" as const, undefined]; + let nextCursor: string | null = null; + for (const view of views) { + const pageResult = yield* fetchEnvironmentThreadHistoryPage({ + prepared: preparedOption.value, + threadId, + cursor: requestCursor, + throughEntryId: workAnchorId ?? throughEntryId, + view, + signer: dpopSigner, + remoteAuthorization, + }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient.value), Effect.result); + if (Result.isFailure(pageResult)) + return yield* failLoad(formatHistoryError(pageResult.failure)); + const page = pageResult.success; + const complete = view !== "conversation"; + const keepPaging = + complete && + (workAnchorId !== undefined + ? page.nextCursor !== null + : throughEntryId === undefined && + page.hasMoreHistory && + !page.items.some( + ({ item }) => item.type === "user_message" && item.createdBy === "user", + )); + if (keepPaging && (page.nextCursor === null || page.nextCursor === requestCursor)) + return yield* failLoad( + workAnchorId === undefined + ? "History did not advance." + : "Work history did not advance.", + ); + const waiting = yield* Ref.get(awaitingCompletion); + const result = yield* applyLock.withPermits(1)( + SubscriptionRef.modify( + state, + ( + latest, + ): readonly [ + ThreadHistoryController.ThreadHistoryLoadEarlierResult, + EnvironmentThreadState, + ] => { + if (!isCurrent(latest)) return [staleResult(latest), latest]; + if (Option.isNone(latest.data) || latest.status === "deleted") + return [{ _tag: "noop" }, { ...latest, history: EMPTY_THREAD_HISTORY_META }]; + return [ + { _tag: "loaded" }, + { + ...latest, + data: Option.some( + mergeOlderHistoryIntoProjection( + latest.data.value, + page.items, + workAnchorId === undefined + ? undefined + : { anchorId: workAnchorId, nextCursor: page.nextCursor }, + ), + ), + status: + workAnchorId === undefined && complete && waiting + ? "synchronizing" + : latest.status, + history: + workAnchorId === undefined && complete + ? { ...applyHistoryPageMeta(latest.history, page), loading: keepPaging } + : { ...latest.history, expanded: true }, + }, + ]; + }, + ), + ); + if (result._tag !== "loaded") return result; + if (complete) yield* remember; + nextCursor = keepPaging ? page.nextCursor : null; + } + if (nextCursor === null) return { _tag: "loaded" } as const; + requestCursor = nextCursor; } - return { _tag: "loaded" } satisfies ThreadHistoryController.ThreadHistoryLoadEarlierResult; }); - return yield* runLoad.pipe( Effect.onInterrupt(() => SubscriptionRef.update(state, (latest) => ({ @@ -832,8 +879,11 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make if (Option.isSome(historyController)) { const scope = yield* Scope.Scope; const registration = yield* historyController.value.register(environmentId, threadId, { - loadEarlier: (throughEntryId) => - loadEarlier(throughEntryId).pipe(Effect.forkIn(scope), Effect.flatMap(Fiber.join)), + loadEarlier: (throughEntryId, workAnchorId) => + loadEarlier(throughEntryId, workAnchorId).pipe( + Effect.forkIn(scope), + Effect.flatMap(Fiber.join), + ), reconcilePendingWork: () => reconcilePendingWork().pipe( Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor), @@ -962,6 +1012,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make ...(acceptBoundedSnapshot ? { acceptBoundedSnapshot: true as const, + acceptDeferredWork: true as const, acceptCompactTurnItems: true as const, acceptCompactIds: true as const, } diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.ts index ad6780ae71481..30c33deebd55c 100644 --- a/packages/contracts/src/environmentHttp.ts +++ b/packages/contracts/src/environmentHttp.ts @@ -657,6 +657,7 @@ const EnvironmentOrchestrationShellSnapshotQuery = Schema.Struct({ }); const EnvironmentOrchestrationThreadBoundedSnapshotQuery = Schema.Struct({ + deferWork: Schema.optionalKey(Schema.String), compactTurnItems: Schema.optionalKey(Schema.String), dedupeBodies: Schema.optionalKey(Schema.String), compactIds: Schema.optionalKey(Schema.String), @@ -665,7 +666,8 @@ const EnvironmentOrchestrationThreadBoundedSnapshotQuery = Schema.Struct({ const EnvironmentOrchestrationThreadHistoryQuery = Schema.Struct({ cursor: TrimmedNonEmptyString, throughEntryId: Schema.optional(TrimmedNonEmptyString), - view: Schema.optional(Schema.Literals(["conversation", "activity"])), + view: Schema.optional(Schema.Literals(["conversation", "activity", "work"])), + deferWork: Schema.optionalKey(Schema.String), compactIds: Schema.optionalKey(Schema.String), }); diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 993fb62453d59..56d910b752deb 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1447,6 +1447,14 @@ export type OrchestrationV2UserMessageInputIntent = typeof OrchestrationV2UserMessageInputIntent.Type; const OrchestrationV2TurnItemBaseFields = { + /** Wire-only cursor for collapsed work; persisted items keep their complete history. */ + deferredWork: Schema.optionalKey( + Schema.Struct({ + cursor: TrimmedNonEmptyString, + itemCount: PositiveInt, + lastOrdinal: NonNegativeInt, + }), + ), toolNonExecutionKind: Schema.optional(Schema.String), toolSurface: Schema.optional(ToolActivitySurface), toolIcon: Schema.optional(ToolActivityIcon), @@ -3680,6 +3688,7 @@ export const OrchestrationV2SubscribeThreadInput = Schema.Struct({ afterSequence: Schema.optionalKey(NonNegativeInt), requestCompletionMarker: Schema.optionalKey(Schema.Boolean), acceptBoundedSnapshot: Schema.optionalKey(Schema.Boolean), + acceptDeferredWork: Schema.optionalKey(Schema.Boolean), acceptCompactTurnItems: Schema.optionalKey(Schema.Boolean), /** The client restores `*Omitted` bodies from records it already holds. */ acceptDedupedBodies: Schema.optionalKey(Schema.Boolean), From c3858bf1f70a1a16a3582ff870307c55b358b5c3 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Wed, 28 Oct 2026 04:05:51 -0700 Subject: [PATCH 221/817] fix(web): snooze options sort soonest first, fit 2 digits, and link from custom snooze (#26427) Co-authored-by: Claude Opus 5.5 --- .../web/src/components/CustomSnoozeDialog.tsx | 19 +++++- .../SnoozePresetsSettings.logic.test.ts | 20 +++++- .../settings/SnoozePresetsSettings.logic.ts | 25 +++++++ .../settings/SnoozePresetsSettings.tsx | 68 +++++++++++++++---- 4 files changed, 117 insertions(+), 15 deletions(-) diff --git a/apps/web/src/components/CustomSnoozeDialog.tsx b/apps/web/src/components/CustomSnoozeDialog.tsx index efbc5d90da6b6..43c466184bf2c 100644 --- a/apps/web/src/components/CustomSnoozeDialog.tsx +++ b/apps/web/src/components/CustomSnoozeDialog.tsx @@ -1,4 +1,5 @@ import { useEffect, useId, useState } from "react"; +import { useNavigate } from "@tanstack/react-router"; import { create } from "zustand"; import { localSnoozeDate, @@ -7,7 +8,7 @@ import { type CustomSnoozeInput, } from "@t3tools/client-runtime/state/thread-settled"; import { Button } from "./ui/button"; -import { CalendarIcon } from "lucide-react"; +import { CalendarIcon, Settings2Icon } from "lucide-react"; import { Calendar } from "./ui/calendar"; import { weekStartsOn } from "../timestampFormat"; import { useNowMinute } from "../hooks/useNowMinute"; @@ -63,6 +64,7 @@ export function CustomSnoozeDialogHost() { function CustomSnoozeDialog() { const id = useId(); + const navigate = useNavigate(); const [initial] = useState(() => new Date(Date.now() + 3_600_000)); const nowMinute = useNowMinute(); // Follows the clock so a dialog left open past midnight stops offering yesterday. @@ -225,6 +227,21 @@ function CustomSnoozeDialog() { )} + diff --git a/apps/web/src/components/settings/SnoozePresetsSettings.logic.test.ts b/apps/web/src/components/settings/SnoozePresetsSettings.logic.test.ts index e5126ba8bba6d..05d62987fb23e 100644 --- a/apps/web/src/components/settings/SnoozePresetsSettings.logic.test.ts +++ b/apps/web/src/components/settings/SnoozePresetsSettings.logic.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; -import { reconcileSnoozeDraft } from "./SnoozePresetsSettings.logic"; +import { reconcileSnoozeDraft, sortSnoozeRows } from "./SnoozePresetsSettings.logic"; describe("reconcileSnoozeDraft", () => { it("keeps the draft while our own writes echo back in order", () => { @@ -18,3 +18,21 @@ describe("reconcileSnoozeDraft", () => { expect(reconcileSnoozeDraft(["a", "b", "a"], "b")).toEqual({ adopt: false, pending: ["a"] }); }); }); + +describe("sortSnoozeRows", () => { + it("orders rows by wake time and puts a passed today option last", () => { + // 16:00 local, so 20 hours wakes tomorrow and today 09:00 has passed. + const now = new Date(2026, 9, 28, 16, 0); + const sorted = sortSnoozeRows( + [ + { kind: "after", minutes: 20 * 60 }, + { kind: "at", day: "today", time: "09:00" }, + { kind: "at", day: "today", time: "18:00" }, + { kind: "after", minutes: 60 }, + ], + ["20h", "passed", "evening", "1h"], + now, + ); + expect(sorted.keys).toEqual(["1h", "evening", "20h", "passed"]); + }); +}); diff --git a/apps/web/src/components/settings/SnoozePresetsSettings.logic.ts b/apps/web/src/components/settings/SnoozePresetsSettings.logic.ts index ece0e2ee5a922..5e778be591b68 100644 --- a/apps/web/src/components/settings/SnoozePresetsSettings.logic.ts +++ b/apps/web/src/components/settings/SnoozePresetsSettings.logic.ts @@ -1,3 +1,5 @@ +import type { SnoozePresetSetting } from "@t3tools/contracts/settings"; +import { resolveSnoozePreset } from "@t3tools/client-runtime/state/thread-settled"; import * as Equal from "effect/Equal"; /** @@ -13,3 +15,26 @@ export function reconcileSnoozeDraft( ? { adopt: true } : { adopt: false, pending: pending.slice(acknowledged + 1) }; } + +/** + * Orders editor rows the way the menu lists them: soonest wake first, with options that + * have no wake right now (a passed "Today") last. Ties keep their current order. + */ +export function sortSnoozeRows( + presets: ReadonlyArray, + keys: ReadonlyArray, + now: Date, +): { readonly presets: ReadonlyArray; readonly keys: ReadonlyArray } { + const order = presets + .map((preset, index) => ({ + index, + wake: resolveSnoozePreset(preset, now)?.snoozedUntil ?? null, + })) + .toSorted((a, b) => + a.wake === b.wake ? 0 : a.wake === null ? 1 : b.wake === null ? -1 : a.wake < b.wake ? -1 : 1, + ); + return { + presets: order.map(({ index }) => presets[index]!), + keys: order.map(({ index }) => keys[index]!), + }; +} diff --git a/apps/web/src/components/settings/SnoozePresetsSettings.tsx b/apps/web/src/components/settings/SnoozePresetsSettings.tsx index d7129e76dd208..22f2d43497fde 100644 --- a/apps/web/src/components/settings/SnoozePresetsSettings.tsx +++ b/apps/web/src/components/settings/SnoozePresetsSettings.tsx @@ -16,7 +16,7 @@ import * as Schema from "effect/Schema"; import { PlusIcon, XIcon } from "lucide-react"; import { useNowMinute } from "../../hooks/useNowMinute"; -import { reconcileSnoozeDraft } from "./SnoozePresetsSettings.logic"; +import { reconcileSnoozeDraft, sortSnoozeRows } from "./SnoozePresetsSettings.logic"; import { formatShortTimestamp } from "../../timestampFormat"; import { Button } from "../ui/button"; import { Input } from "../ui/input"; @@ -90,6 +90,16 @@ function nextCandidate(presets: ReadonlyArray): SnoozePrese ); } +// Row order is only display order, so it does not make a list differ from the defaults. +function sameSnoozePresets( + left: ReadonlyArray, + right: ReadonlyArray, +) { + const ids = (presets: ReadonlyArray) => + presets.map(snoozePresetId).toSorted(); + return Equal.equals(ids(left), ids(right)); +} + const isSnoozePresetDay = Schema.is(SnoozePresetDay); interface KindMemory { @@ -109,16 +119,28 @@ function withWhen( return { kind: "at", day: when, time: preset.kind === "at" ? preset.time : memory.time }; } -/** Edits the snooze menu's options. Menus sort them by wake time, so rows keep the order they were added in. */ +/** + * Edits the snooze menu's options. Rows sort by wake time like the menu, but only when focus + * leaves the list, so a row never moves under the pointer mid-edit. + */ export function SnoozePresetsRow() { const settings = useScopedSettings(); const updateSettings = useUpdateScopedSettings(); const saved = settings.snoozePresets; + const nowMinute = useNowMinute(); + const now = new Date(`${nowMinute}Z`); // Edits build on a local draft, so a second edit before the first save echoes back // does not restore what the first one changed. Echoes of our own writes keep the draft. - const [presets, setPresets] = useState(saved); - // Row keys survive removals, so a row's in-progress field state stays with that row. - const [keys, setKeys] = useState>(() => saved.map((_, index) => index)); + // Row keys survive removals and sorts, so a row's in-progress field state stays with it. + // One state, so a sort queued in the same event as an edit applies on top of it. + const [rows, setRows] = useState(() => + sortSnoozeRows( + saved, + saved.map((_, index) => index), + now, + ), + ); + const { presets, keys } = rows; const [nextKey, setNextKey] = useState(saved.length); // Null forces the next render to adopt the saved value, as after a failed write. const [savedSource, setSavedSource] = useState | null>(saved); @@ -134,8 +156,7 @@ export function SnoozePresetsRow() { const reconciled = reconcileSnoozeDraft(written, saved); if (reconciled.adopt) { setWritten([]); - setPresets(saved); - setKeys(freshKeys(saved.length)); + setRows(sortSnoozeRows(saved, freshKeys(saved.length), now)); } else { setWritten(reconciled.pending); } @@ -145,8 +166,7 @@ export function SnoozePresetsRow() { nextKeys: ReadonlyArray = keys, ) => { if (!mixed && Equal.equals(snoozePresets, presets)) return; - setPresets(snoozePresets); - setKeys(nextKeys); + setRows({ presets: snoozePresets, keys: nextKeys }); setWritten((previous) => [...previous, snoozePresets]); updateSettings( { snoozePresets }, @@ -168,10 +188,17 @@ export function SnoozePresetsRow() { {...searchableSetting("snooze-options")} description="Choices in every snooze menu, listed soonest first. Weekdays mean the next one after today." resetAction={ - !mixed && Equal.equals(presets, DEFAULT_SNOOZE_PRESETS) ? null : ( + !mixed && sameSnoozePresets(presets, DEFAULT_SNOOZE_PRESETS) ? null : ( save(DEFAULT_SNOOZE_PRESETS, freshKeys(DEFAULT_SNOOZE_PRESETS.length))} + onClick={() => { + const sorted = sortSnoozeRows( + DEFAULT_SNOOZE_PRESETS, + freshKeys(DEFAULT_SNOOZE_PRESETS.length), + now, + ); + save(sorted.presets, sorted.keys); + }} /> ) } @@ -188,6 +215,7 @@ export function SnoozePresetsRow() { ) } onAdd={() => save([...presets, nextCandidate(presets)], [...keys, ...freshKeys(1)])} + onSettle={() => setRows((current) => sortSnoozeRows(current.presets, current.keys, now))} /> ); @@ -200,6 +228,7 @@ function SnoozePresetList(props: { onChange: (index: number, preset: SnoozePresetSetting) => void; onRemove: (index: number) => void; onAdd: () => void; + onSettle: () => void; }) { const nowMinute = useNowMinute(); const now = new Date(`${nowMinute}Z`); @@ -232,7 +261,20 @@ function SnoozePresetList(props: { ); return ( -
    +
    { + const list = event.currentTarget; + const next = event.relatedTarget; + if (list.contains(next)) return; + // Select popups portal out of the list, so focus moving into one is not leaving it. + if (next instanceof Element && next.closest('[data-slot="select-popup"]')) return; + // Waits for the amount field's blur commit, and skips its Enter blur-and-refocus. + queueMicrotask(() => { + if (!list.contains(document.activeElement)) props.onSettle(); + }); + }} + > {props.presets.map((preset, index) => { const preview = previews[index]!; return ( @@ -371,7 +413,7 @@ function DurationFields(props: { minutes: number; onChange: (minutes: number) => <> Date: Wed, 28 Oct 2026 04:21:58 -0700 Subject: [PATCH 222/817] fix(web): file preview wrap buttons no longer turn off word wrap everywhere (#26432) Co-authored-by: Claude Opus 5.5 --- .../AttachmentFilePreview.browser.test.tsx | 22 ++++++++++++++++++- .../files/AttachmentFilePreview.tsx | 13 ++++++----- .../src/components/files/FilePreviewPanel.tsx | 12 +++++++--- .../src/components/files/LargeTextViewer.tsx | 5 ++++- .../files/ReadOnlySourcePreview.tsx | 5 ++++- 5 files changed, 46 insertions(+), 11 deletions(-) diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx index 9879edfeedbd8..7492313f3c7e8 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx @@ -18,7 +18,9 @@ vi.mock(import("~/assets/assetUrls"), async (original) => ({ // The real source view highlights through a worker pool; the text it receives is what matters here. // Never load the original: its highlighter graph can outlast waitFor on a cold CI browser. vi.mock(import("./ReadOnlySourcePreview"), () => ({ - default: ({ text }: { text: string }) =>
    {text}
    , + default: ({ text, wordWrap }: { text: string; wordWrap?: boolean }) => ( +
    {text}
    + ), })); // The Word engine compiles about 30 MB of WebAssembly in a fresh worker per document, which took @@ -41,6 +43,7 @@ vi.mock(import("./office/WordDocument"), async () => { }; }); +import { getClientSettings } from "~/hooks/useSettings"; import { AttachmentFilePreview } from "./AttachmentFilePreview"; import LargeTextViewer from "./LargeTextViewer"; import VirtualTablePreview from "./VirtualTablePreview"; @@ -492,6 +495,7 @@ describe("large text preview recovery", () => { workspaceMutationId={mutation} revealLine={null} revealRequestId={0} + wordWrap />
    ); @@ -2341,6 +2345,22 @@ it("toggles a Mermaid attachment between diagram and source through the lazy pre expect(screen.container.querySelector('[role="alert"]')).toBeNull(); }); +it("unwraps one text attachment without turning off the word wrap setting", async () => { + const file = new Blob(["a long line"], { type: "text/plain" }); + await using screen = await render( + , + ); + await screen.getByRole("button", { name: "Disable word wrap" }).click(); + await expect.element(screen.getByRole("button", { name: "Enable word wrap" })).toBeVisible(); + expect(getClientSettings().wordWrap).toBe(true); + expect(screen.container.querySelector("pre")?.dataset.wordWrap).toBe("false"); +}); + it("mounts a bounded set of saved notebook outputs as the reader scrolls", async () => { const notebook = { nbformat: 4, diff --git a/apps/web/src/components/files/AttachmentFilePreview.tsx b/apps/web/src/components/files/AttachmentFilePreview.tsx index e57289bd60144..1d8bc609ff56a 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.tsx @@ -21,7 +21,7 @@ import { MorphIcon } from "~/components/MorphIcon"; import { ScrollArea } from "~/components/ui/scroll-area"; import { toastManager } from "~/components/ui/toast"; import { useCopyToClipboard } from "~/hooks/useCopyToClipboard"; -import { useClientSettings, updateClientSettings } from "~/hooks/useSettings"; +import { useClientSettings } from "~/hooks/useSettings"; import { cn } from "~/lib/utils"; import { BinaryFilePreview } from "./BinaryFilePreview"; @@ -55,7 +55,7 @@ const SourcePreview = lazy(() => import("./ReadOnlySourcePreview")); const STALE_URL_MS = 5 * 60_000; -export function ReadOnlySourcePreview(props: { name: string; text: string }) { +export function ReadOnlySourcePreview(props: { name: string; text: string; wordWrap?: boolean }) { return ( }> @@ -214,7 +214,9 @@ export function AttachmentFilePreview(props: { return () => controller.abort(); }, [url, needsText, streamsText, revision, props.sizeBytes, props.file, refresh]); const failure = error ?? (needsText ? contentError : null); - const wordWrap = useClientSettings((settings) => settings.wordWrap); + const defaultWordWrap = useClientSettings((settings) => settings.wordWrap); + const [wordWrapOverride, setWordWrapOverride] = useState(null); + const wordWrap = wordWrapOverride ?? defaultWordWrap; const showsRawText = failure === null && needsText && @@ -272,6 +274,7 @@ export function AttachmentFilePreview(props: { onRetry={() => setRevision((value) => value + 1)} delimiter={rendered ? delimiter : null} copyContents={copyContents} + wordWrap={wordWrap} /> ) : !url || (needsText && !content) ? ( @@ -292,7 +295,7 @@ export function AttachmentFilePreview(props: { /> ) : ( - + ) ) : kind === "archive" || kind === "sqlite" ? ( updateClientSettings({ wordWrap: !wordWrap })} + onPress={() => setWordWrapOverride(!wordWrap)} > diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx index 56854b3ec6f72..03e682758e321 100644 --- a/apps/web/src/components/files/FilePreviewPanel.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.tsx @@ -56,7 +56,7 @@ import { MediaVideoPlayer } from "~/components/media/MediaVideoPlayer"; import { MediaActions, type MediaActionSource } from "~/components/media/MediaActions"; import { MorphIcon } from "~/components/MorphIcon"; import { useRemoteOpenState } from "~/remoteOpen"; -import { useClientSettings, updateClientSettings } from "~/hooks/useSettings"; +import { useClientSettings } from "~/hooks/useSettings"; import { useTheme } from "~/hooks/useTheme"; import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "~/hooks/useLocalStorage"; import { resolveDiffThemeName } from "~/lib/diffRendering"; @@ -996,7 +996,9 @@ export default function FilePreviewPanel({ attachment === undefined ? resolveFilePreviewPath(requestedPath, cwd) : requestedPath; const draft = typeof composerDraftTarget === "string"; const { resolvedTheme } = useTheme(); - const wordWrap = useClientSettings((settings) => settings.wordWrap); + const defaultWordWrap = useClientSettings((settings) => settings.wordWrap); + const [wordWrapOverride, setWordWrapOverride] = useState(null); + const wordWrap = wordWrapOverride ?? defaultWordWrap; const canOperatePreview = useEnvironmentScope(environmentId, AuthPreviewOperateScope); const primaryEnvironmentId = usePrimaryEnvironmentId(); const remoteOpenState = useRemoteOpenState(environmentId); @@ -1291,7 +1293,7 @@ export default function FilePreviewPanel({ updateClientSettings({ wordWrap: !wordWrap })} + onPress={() => setWordWrapOverride(!wordWrap)} > @@ -1403,6 +1405,7 @@ export default function FilePreviewPanel({ workspaceMutationId={workspaceMutationId} revealLine={revealLine} revealRequestId={revealRequestId} + wordWrap={wordWrap} /> ) : relativePath && absolutePath && @@ -1488,6 +1491,7 @@ export default function FilePreviewPanel({ text={file.data.contents} cacheKey={projectFileCacheKey(cwd, relativePath, file.data.contents)} onPostRender={onFilePostRender} + wordWrap={wordWrap} /> ) : ( @@ -1557,6 +1561,7 @@ export function WorkspaceLargeTextPreview(props: { workspaceMutationId: string | null; revealLine: number | null; revealRequestId: number; + wordWrap: boolean; }) { const resource = { _tag: "media-file", @@ -1659,6 +1664,7 @@ export function WorkspaceLargeTextPreview(props: { delimiter={props.delimiter} revealLine={props.revealLine} revealRequestId={props.revealRequestId} + wordWrap={props.wordWrap} /> diff --git a/apps/web/src/components/files/LargeTextViewer.tsx b/apps/web/src/components/files/LargeTextViewer.tsx index a12842f7047c9..097f0dc717f70 100644 --- a/apps/web/src/components/files/LargeTextViewer.tsx +++ b/apps/web/src/components/files/LargeTextViewer.tsx @@ -36,6 +36,8 @@ export default function LargeTextViewer(props: { readonly delimiter: "," | "\t" | null; readonly revealLine?: number | null; readonly revealRequestId?: number; + /** A preview's own wrap toggle; omitted follows the word wrap setting. */ + readonly wordWrap?: boolean; }) { const [meta, setMeta] = useState | null>(null); const [pages, setPages] = useState(new Map()); @@ -46,7 +48,8 @@ export default function LargeTextViewer(props: { reject: (cause: Error) => void; } | null>(null); const pending = useRef(new Set()); - const wordWrap = useClientSettings((settings) => settings.wordWrap); + const defaultWordWrap = useClientSettings((settings) => settings.wordWrap); + const wordWrap = props.wordWrap ?? defaultWordWrap; // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Own the prefix fetch and indexing worker, cancelling requests and pending copies when the source changes or unmounts. useEffect(() => { // oxlint-disable-next-line react/set-state-in-effect -- A replacement source must discard the previous worker's error and pages. diff --git a/apps/web/src/components/files/ReadOnlySourcePreview.tsx b/apps/web/src/components/files/ReadOnlySourcePreview.tsx index b35143fd36575..2fdfe04a238d6 100644 --- a/apps/web/src/components/files/ReadOnlySourcePreview.tsx +++ b/apps/web/src/components/files/ReadOnlySourcePreview.tsx @@ -13,9 +13,12 @@ export default function ReadOnlySourcePreview(props: { readonly text: string; readonly cacheKey?: string; readonly onPostRender?: FileOptions["onPostRender"]; + /** A preview's own wrap toggle; omitted follows the word wrap setting. */ + readonly wordWrap?: boolean; }) { const resolvedTheme = useRenderedAppearance(); - const wordWrap = useClientSettings((settings) => settings.wordWrap); + const defaultWordWrap = useClientSettings((settings) => settings.wordWrap); + const wordWrap = props.wordWrap ?? defaultWordWrap; return ( Date: Wed, 28 Oct 2026 04:49:42 -0700 Subject: [PATCH 223/817] feat(web): simpler composer with grouped controls, effort words and no collapsed state (#25869) Co-authored-by: Claude Opus 5.5 --- .../settings/DesktopClientSettings.test.ts | 1 - .../web/src/components/BranchToolbar.logic.ts | 6 +- apps/web/src/components/BranchToolbar.tsx | 50 +- .../BranchToolbarBranchSelector.tsx | 3 +- apps/web/src/components/ChatView.tsx | 125 ++--- .../components/ComposerContextPermissions.tsx | 40 ++ apps/web/src/components/chat/ChatComposer.tsx | 465 +++--------------- .../chat/CompactComposerControlsMenu.tsx | 53 +- .../chat/ComposerAttachmentStrip.tsx | 3 +- .../src/components/chat/ComposerControl.tsx | 44 +- .../components/chat/ComposerControlsBar.tsx | 136 +++-- .../chat/ComposerFooterControls.tsx | 204 ++++++-- ...omposerPermissionsSection.browser.test.tsx | 151 ++++++ .../src/components/chat/ComposerSurface.tsx | 35 +- .../src/components/chat/EffortGlyph.test.ts | 67 +++ apps/web/src/components/chat/EffortGlyph.tsx | 86 ++++ .../chat/MessagesTimeline.browser.test.tsx | 23 - .../src/components/chat/MessagesTimeline.tsx | 46 +- .../components/chat/ProviderModelPicker.tsx | 48 +- apps/web/src/components/chat/TraitsPicker.tsx | 140 +++++- .../chat/composerControlsOwnership.test.ts | 90 ++++ .../chat/composerControlsOwnership.ts | 63 +++ .../src/components/chat/composerEventScope.ts | 19 + .../components/chat/composerProviderState.tsx | 13 + .../components/chat/composerScrollGesture.ts | 79 --- .../src/components/chat/runtimeModeConfig.ts | 17 +- .../chat/timelineScrollTarget.test.ts | 24 - .../components/chat/useComposerFocusState.ts | 18 - .../chat/useComposerRestingTransition.ts | 81 +-- .../src/components/chat/useTimelineFollow.ts | 35 -- .../components/composerFooterLayout.test.ts | 25 - .../src/components/composerFooterLayout.ts | 52 -- apps/web/src/components/guest/GuestPage.tsx | 4 - .../settings/AppearanceSettingsPanel.tsx | 39 ++ .../components/settings/SettingsPanels.tsx | 34 +- .../src/components/settings/settingsSearch.ts | 12 +- docs/user/keybindings.md | 2 +- docs/user/permission-modes.md | 4 +- packages/client-runtime/src/modelTraits.ts | 13 +- packages/contracts/src/settings.ts | 8 +- 40 files changed, 1162 insertions(+), 1196 deletions(-) create mode 100644 apps/web/src/components/ComposerContextPermissions.tsx create mode 100644 apps/web/src/components/chat/ComposerPermissionsSection.browser.test.tsx create mode 100644 apps/web/src/components/chat/EffortGlyph.test.ts create mode 100644 apps/web/src/components/chat/EffortGlyph.tsx create mode 100644 apps/web/src/components/chat/composerControlsOwnership.test.ts create mode 100644 apps/web/src/components/chat/composerControlsOwnership.ts delete mode 100644 apps/web/src/components/chat/composerScrollGesture.ts delete mode 100644 apps/web/src/components/chat/useComposerFocusState.ts diff --git a/apps/desktop/src/settings/DesktopClientSettings.test.ts b/apps/desktop/src/settings/DesktopClientSettings.test.ts index ac4c6e61378e3..1a927643be628 100644 --- a/apps/desktop/src/settings/DesktopClientSettings.test.ts +++ b/apps/desktop/src/settings/DesktopClientSettings.test.ts @@ -34,7 +34,6 @@ const clientSettings: ClientSettings = { confirmThreadDelete: false, confirmThreadUnpin: false, contextWindowMeterEnabled: false, - composerCollapseOnScroll: true, diffFilesCollapsed: true, diffIgnoreWhitespace: true, diffLayout: "stacked", diff --git a/apps/web/src/components/BranchToolbar.logic.ts b/apps/web/src/components/BranchToolbar.logic.ts index 80cd7e981375d..e22dcfaddedeb 100644 --- a/apps/web/src/components/BranchToolbar.logic.ts +++ b/apps/web/src/components/BranchToolbar.logic.ts @@ -66,12 +66,12 @@ export function shouldShowComposerContextStrip(input: { hasActiveProject: boolean; isGitRepo: boolean; showEnvironmentIndicator: boolean; - hostsRestingComposerControls: boolean; }): boolean { + // A new thread always shows the strip, since it names the permissions the first send uses. return ( input.hasActiveProject && - (input.isDraftHeroState || input.persistInActiveThreads) && - (input.isGitRepo || input.showEnvironmentIndicator || input.hostsRestingComposerControls) + (input.isDraftHeroState || + (input.persistInActiveThreads && (input.isGitRepo || input.showEnvironmentIndicator))) ); } diff --git a/apps/web/src/components/BranchToolbar.tsx b/apps/web/src/components/BranchToolbar.tsx index 80edf40d79504..4d57bc7332525 100644 --- a/apps/web/src/components/BranchToolbar.tsx +++ b/apps/web/src/components/BranchToolbar.tsx @@ -5,17 +5,11 @@ import { stackedThreadToast, toastManager } from "./ui/toast"; import { ComposerContextLabel } from "./ComposerContextLabel"; import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment"; import type { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts"; -import { - ChevronDownIcon, - FolderGit2Icon, - FolderGitIcon, - FolderIcon, - PlusIcon, - ScaleIcon, -} from "lucide-react"; +import { FolderGit2Icon, FolderGitIcon, FolderIcon, PlusIcon, ScaleIcon } from "lucide-react"; import { type Ref, type MouseEvent as ReactMouseEvent, + type ReactNode, memo, useImperativeHandle, useRef, @@ -72,8 +66,6 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { MiddleTruncate } from "./ui/middle-truncate"; import { ComposerSurface } from "./chat/ComposerSurface"; import { useComposerMenuProps } from "./chat/composerEventScope"; -import { measureRestingComposerControls } from "./chat/restingComposerControlsMeasurement"; -import { resolveRestingComposerControlsNaturalWidth } from "./composerFooterLayout"; import { cn } from "~/lib/utils"; import { observeResize } from "~/lib/observeResize"; @@ -105,10 +97,10 @@ interface BranchToolbarProps { envLocked: boolean; onCheckoutPullRequestRequest?: (reference: string) => void; onComposerFocusRequest?: () => void; + /** Shown at the end of the composer strip, such as the new thread's permissions. */ + trailing?: ReactNode; availableEnvironments?: readonly EnvironmentOption[]; onEnvironmentChange?: (environmentId: EnvironmentId) => void; - composerControlsHostRef?: (element: HTMLDivElement | null) => void; - contextStripVisible?: boolean; } function showWorkspaceContextMenu(event: ReactMouseEvent, workspacePath: string) { @@ -317,7 +309,6 @@ const RunContextSelector = memo(function RunContextSelector({ ].join(" ")} > {triggerContent} - {!isPanel ? : null} ('[data-chat-composer-resting-controls="true"]') - : null; - const hostedMeasurement = hostedControls - ? measureRestingComposerControls(hostedControls) - : null; - const width = hostedMeasurement - ? resolveRestingComposerControlsNaturalWidth(hostedMeasurement) - : contentWidth(hostedControls ?? child); + const width = contentWidth(child); if (width <= 1) continue; groups += 1; needed += width; @@ -585,7 +567,6 @@ function useLabelsOverflow(): readonly [ [ current, ...Array.from(current.children), - ...Array.from(current.querySelectorAll("[data-chat-composer-resting-controls='true']")), ...Array.from(current.querySelectorAll(COMPOSER_CONTEXT_LABEL_SELECTOR)), ], measure, @@ -640,8 +621,7 @@ export const BranchToolbar = memo(function BranchToolbar({ onComposerFocusRequest, availableEnvironments, onEnvironmentChange, - composerControlsHostRef, - contextStripVisible = true, + trailing, }: BranchToolbarProps) { const branchSelectorRef = useRef(null); const threadRef = scopeThreadRef(environmentId, threadId); @@ -764,11 +744,7 @@ export const BranchToolbar = memo(function BranchToolbar({ {showGitControls ? (
    @@ -799,7 +775,7 @@ export const BranchToolbar = memo(function BranchToolbar({ className={cn( "min-h-7 min-w-10 items-center gap-1 sm:min-h-6", showGitControls ? "hidden @3xl/composer-surface:flex" : "flex", - composerControlsHostRef ? "shrink" : "flex-1", + "flex-1", )} > {showEnvironmentIndicator && availableEnvironments && ( @@ -837,15 +813,6 @@ export const BranchToolbar = memo(function BranchToolbar({
    ) : null} - {composerControlsHostRef ? ( -
    - ) : null} - {showGitControls ? ( ) : null} + {trailing} ); }); diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index ef842f21c44c0..95848c209d8c5 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -16,7 +16,7 @@ import { type VcsRef, type ThreadId, } from "@t3tools/contracts"; -import { ChevronDownIcon, GitBranchIcon } from "lucide-react"; +import { GitBranchIcon } from "lucide-react"; import { useDeferredValue, useEffect, @@ -732,7 +732,6 @@ export function BranchToolbarBranchSelector({ className="w-full" /> - {displayMode !== "panel" ? : null} {displayMode === "panel" && prNumber !== undefined && prUrl !== undefined ? ( diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 6af016c18ce91..253cc1ea2e84b 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -175,6 +175,8 @@ import { LinkPullRequestDialogHost } from "./pullRequest/LinkPullRequestDialog"; import { GuestPendingMessages } from "./chat/GuestShareControls"; import { useDeviceState } from "~/state/device"; import { BranchToolbar, type BranchToolbarHandle } from "./BranchToolbar"; +import { ComposerContextPermissions } from "./ComposerContextPermissions"; +import { resolveCompatibleRuntimeMode } from "./chat/runtimeModeConfig"; import { makeWorkspaceFileDropHandlers } from "./chat/workspaceFileDrop"; import { isEditableFocused } from "../lib/editableFocus"; import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings"; @@ -267,11 +269,7 @@ import type { MessagesTimelineHistoryControls } from "./chat/MessagesTimeline"; import { ThreadTimeline } from "./chat/ThreadTimeline"; import { ProviderSubagentBar } from "./chat/ProviderSubagentBar"; import { getTriggerDisplayModelName } from "./chat/providerIconUtils"; -import { - overlayComposerIsResting, - resolveComposerTimelineInset, - resolveScrollToEndClearance, -} from "./composerFooterLayout"; +import { resolveScrollToEndClearance } from "./composerFooterLayout"; import { ChatHeader } from "./chat/ChatHeader"; import { useRemoteOpenState } from "~/remoteOpen"; import { shouldShowOpenInPicker } from "./chat/OpenInPicker.logic"; @@ -611,9 +609,6 @@ export default function ChatView(props: ChatViewProps) { const composerFilesRef = useRef([]); const composerTerminalContextsRef = useRef([]); const branchToolbarRef = useRef(null); - const [restingComposerControlsHost, setRestingComposerControlsHost] = - useState(null); - const [restingComposerControlsVisible, setRestingComposerControlsVisible] = useState(false); const citeAssistantText = ( citation: AssistantCitation, sourceAnchor: AssistantCitationSourceAnchor, @@ -704,8 +699,6 @@ export default function ChatView(props: ChatViewProps) { setPendingServerThreadStartFromOriginByThreadId, ] = useState>({}); const legendListRef = useRef(null); - const getTimelineScrollableNode = () => legendListRef.current?.getScrollableNode() ?? null; - const getTimelineScrollableNodeStable = useStableCallback(getTimelineScrollableNode); const conversationArea = workspaceAreaProps("conversation", 1, "Conversation"); const composerArea = workspaceAreaProps("composer", 2, "Message input"); const [composerOverlayElement, setComposerOverlayElement] = useState(null); @@ -714,9 +707,7 @@ export default function ChatView(props: ChatViewProps) { const [composerReservedHeight, setComposerReservedHeight] = useState(0); const composerReservedHeightRef = useRef(0); const composerExpandedHeightRef = useRef(0); - const composerRestingRef = useRef(false); const [scrollToEndClearance, setScrollToEndClearance] = useState(0); - const [timelineOverflows, setTimelineOverflows] = useState(false); const fanoutSelectionsAtom = draftFanoutSelectionsAtom(routeThreadKey); const { sendInFlight: sendInFlightRef } = draftSendState(routeThreadKey); const multipleModelSelections = useAtomValue(fanoutSelectionsAtom); @@ -1686,25 +1677,13 @@ export default function ChatView(props: ChatViewProps) { providerSubagentModels, reportedModelSelection, ); - const mountComposerContextStrip = shouldShowComposerContextStrip({ - isDraftHeroState, - persistInActiveThreads: settings.persistComposerContextStrip, - hasActiveProject: activeProject !== null && !showProviderSubagentBar, - isGitRepo, - showEnvironmentIndicator: showComposerEnvironmentIndicator, - hostsRestingComposerControls: routeKind === "server", - }); const showComposerContextStrip = shouldShowComposerContextStrip({ isDraftHeroState, persistInActiveThreads: settings.persistComposerContextStrip, hasActiveProject: activeProject !== null && !showProviderSubagentBar, isGitRepo, showEnvironmentIndicator: showComposerEnvironmentIndicator, - hostsRestingComposerControls: routeKind === "server" && restingComposerControlsVisible, }); - const mountComposerModelStrip = - routeKind === "server" && !mountComposerContextStrip && !showProviderSubagentBar; - const showComposerModelStrip = mountComposerModelStrip && restingComposerControlsVisible; const terminalShortcutLabelOptions = { context: { terminalFocus: true, @@ -1792,6 +1771,9 @@ export default function ChatView(props: ChatViewProps) { }); }; const scheduleComposerFocusStable = useStableCallback(scheduleComposerFocus); + const openComposerPermissionsStable = useStableCallback(() => + composerRef.current?.openControl("composer.mode"), + ); const insertArtifactTemplate = (template: CodexArtifactTemplate) => { const composer = composerRef.current; if (!composer) return; @@ -2047,14 +2029,12 @@ export default function ChatView(props: ChatViewProps) { const { showScrollToBottom, timelineLiveFollowEnabled, - isTimelineAtLogicalEndStable, onComposerPageScrollKeyDownStable, onComposerPageScrollKeyUpStable, onComposerPageScrollReleaseStable, scrollToEnd, onTimelineAnchorReadyStable, onTimelineAnchorSizeChangedStable, - onToolOutputCollapsedAtEndStable, onTimelineFooterGrowStable, onIsAtEndChangeStable, anchorNewTurn, @@ -2062,7 +2042,6 @@ export default function ChatView(props: ChatViewProps) { attachComposerOverlay: attachFollowComposerOverlay, } = useTimelineFollow({ legendListRef, - composerRef, composerTimelineInset, routeThreadKey, activeThreadKey, @@ -2177,29 +2156,9 @@ export default function ChatView(props: ChatViewProps) { const publishComposerOverlayHeight = (height: number) => { const nextHeight = Math.ceil(height); if (nextHeight <= 0) return; - const isResting = overlayComposerIsResting({ - composerMounted, - composerReportedResting: composerRestingRef.current, - }); - const modelStrip = composerOverlayElement?.querySelector( - '[data-composer-model-strip="true"]', - ); - const restingOnlyHeight = - modelStrip && isResting - ? Math.max( - 0, - modelStrip.offsetHeight + Number.parseFloat(getComputedStyle(modelStrip).marginTop), - ) - : 0; - const nextInset = resolveComposerTimelineInset({ - currentInset: composerTimelineInsetRef.current, - overlayHeight: height, - isResting, - restingOnlyHeight, - }); - if (composerTimelineInsetRef.current !== nextInset) { - composerTimelineInsetRef.current = nextInset; - setComposerTimelineInset(nextInset); + if (composerTimelineInsetRef.current !== nextHeight) { + composerTimelineInsetRef.current = nextHeight; + setComposerTimelineInset(nextHeight); } // Reserve the expanded composer height for the terminal drawer and empty placeholder. // Keep it while the mobile strip collapses, but allow growth from approvals or tasks. @@ -2208,7 +2167,7 @@ export default function ChatView(props: ChatViewProps) { '[data-chat-composer-stack="true"]', ); const expandedComposerHeight = - isDraftHeroState && stack ? Math.ceil(stack.getBoundingClientRect().height) : nextInset; + isDraftHeroState && stack ? Math.ceil(stack.getBoundingClientRect().height) : nextHeight; const mobileCollapsed = Boolean( stack?.querySelector('[data-chat-composer-mobile-collapsed="true"]'), ); @@ -2240,11 +2199,6 @@ export default function ChatView(props: ChatViewProps) { setScrollToEndClearance(clearance); }; const publishComposerOverlayHeightStable = useStableCallback(publishComposerOverlayHeight); - // The composer's layout effect publishes this flag before parent layout effects or resize observations. - const onComposerRestingChange = (resting: boolean) => { - composerRestingRef.current = resting; - }; - const onComposerRestingChangeStable = useStableCallback(onComposerRestingChange); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the composer overlay element before paint for a new thread or composer mount useLayoutEffect(() => { if (!composerOverlayElement) return; @@ -3333,8 +3287,6 @@ export default function ChatView(props: ChatViewProps) { contentInsetEndAdjustment={composerTimelineInset} liveFollowEnabled={timelineLiveFollowEnabled} onIsAtEndChange={onIsAtEndChangeStable} - onContentOverflowChange={setTimelineOverflows} - onToolOutputCollapsedAtEnd={onToolOutputCollapsedAtEndStable} onViewportAttach={attachTimelineViewport} onFooterGrow={onTimelineFooterGrowStable} hideEmptyPlaceholder={isDraftHeroState || threadDetailLoading} @@ -3349,10 +3301,7 @@ export default function ChatView(props: ChatViewProps) { { - composerRef.current?.restoreAfterTimelineReachedEnd(); - scrollToEnd(true); - }} + onScrollToEnd={() => scrollToEnd(true)} /> )}
    @@ -3403,9 +3352,7 @@ export default function ChatView(props: ChatViewProps) { : undefined } > - + - {mountComposerModelStrip ? ( - -
    - - ) : null} - {mountComposerContextStrip && ( + {showComposerContextStrip && (
    + ), + })} />
    )} diff --git a/apps/web/src/components/ComposerContextPermissions.tsx b/apps/web/src/components/ComposerContextPermissions.tsx new file mode 100644 index 0000000000000..8ee7766edc565 --- /dev/null +++ b/apps/web/src/components/ComposerContextPermissions.tsx @@ -0,0 +1,40 @@ +import type { RuntimeMode } from "@t3tools/contracts"; +import { useAtomValue } from "@effect/atom-react"; + +import { shortcutLabelForCommand } from "../keybindings"; +import { primaryServerKeybindingsAtom } from "../state/server"; +import { ComposerControl } from "./chat/ComposerControl"; +import { runtimeModeConfig } from "./chat/runtimeModeConfig"; +import { ComposerContextLabel } from "./ComposerContextLabel"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; + +/** The new-thread strip names the permissions the first send will use; clicking opens them. */ +export function ComposerContextPermissions(props: { + runtimeMode: RuntimeMode; + onOpen: () => void; +}) { + const shortcutLabel = shortcutLabelForCommand( + useAtomValue(primaryServerKeybindingsAtom), + "composer.mode", + ); + const { icon: Icon, label } = runtimeModeConfig[props.runtimeMode]; + return ( + + + } + > + + Permissions{shortcutLabel ? ` · ${shortcutLabel}` : null} + + ); +} diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 57a3a8aa41909..57838e598161e 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -1,7 +1,11 @@ import { useComposerTypingGuard } from "./useComposerTypingGuard"; import { insertAttachmentReferencesForDraft } from "./composerAttachmentReferences"; import { DESKTOP_PASTE_AS_TEXT_EVENT } from "../../lib/desktopPasteAsText"; -import { runtimeModeConfig, runtimeModeOptions as runtimeModes } from "./runtimeModeConfig"; +import { + resolveCompatibleRuntimeMode, + runtimeModeConfig, + runtimeModeOptions as runtimeModes, +} from "./runtimeModeConfig"; import { isLocalEnvironmentDisabled } from "../../localEnvironment"; import { usePrimaryEnvironmentId } from "../../state/environments"; import { useRightPanelStore } from "~/rightPanelStore"; @@ -56,7 +60,7 @@ import { useRef, useState, } from "react"; -import { createPortal, flushSync } from "react-dom"; +import { flushSync } from "react-dom"; import { clampCollapsedComposerCursor, type ComposerTrigger, @@ -86,6 +90,7 @@ import { import { isInsideCollapsedComposerControls, isInsideRestingComposerControlScope, + markOpenToPermissions, } from "./composerEventScope"; import { type ComposerFileAttachment, @@ -102,7 +107,6 @@ import { ComposerStashBadge } from "./ComposerStashBadge"; import { ComposerStashMenu } from "./ComposerStashMenu"; import { useComposerTriggerState } from "./useComposerTriggerState"; import { useComposerMenuItems } from "./useComposerMenuItems"; -import { useComposerFocusState } from "./useComposerFocusState"; import { useComposerMultilinePrompt } from "./useComposerMultilinePrompt"; import { reconcileAttachmentContextReferences, @@ -140,7 +144,6 @@ import { import { shouldUseCompactComposerPrimaryActions, shouldUseCompactComposerFooter, - shouldUseRestingComposerLayout, } from "../composerFooterLayout"; import { type ComposerCitationCommentRequest, @@ -221,20 +224,9 @@ import { import { ComposerPromptLengthValidation } from "./ComposerPromptLengthValidation"; import { pendingDraftWork } from "./pendingDraftWork"; import { importComposerThreadAttachment } from "./composerThreadImport"; -import { isTimelineScrollTarget } from "./timelineScrollTarget"; -import { - createComposerScrollGestureState, - recordComposerScrollGestureEvent, - shouldCollapseComposerForScrollKey, - resetComposerScrollGesture, - suppressActiveComposerScrollGesture, -} from "./composerScrollGesture"; import { observeResize } from "~/lib/observeResize"; const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidError); - -const COMPOSER_SCROLL_COLLAPSE_THRESHOLD_PX = 24; -const COMPOSER_SCROLL_GESTURE_RESET_MS = 120; import { toastManager } from "../ui/toast"; import { PlayIcon } from "lucide-react"; import { proposedPlanTitle } from "@t3tools/shared/proposedPlanText"; @@ -297,8 +289,6 @@ const runtimeModeOptions = runtimeModes.map((mode) => ({ mode, ...runtimeModeCon export interface ChatComposerHandle { focusAtEnd: () => void; focusAt: (cursor: number) => void; - restoreAfterTimelineReachedEnd: () => void; - collapseForTimelineScrollKey: (key: string) => void; addDroppedFiles: (files: File[]) => void; addDroppedFolders: (folders: File[]) => void; hasPendingAttachments: () => boolean; @@ -424,6 +414,7 @@ export interface ChatComposerProps { threadSyncPhase: ThreadSyncPhase | null; runtimeMode: RuntimeMode; + defaultRuntimeMode?: RuntimeMode; interactionMode: ProviderInteractionMode; lockedProvider: ProviderDriverKind | null; @@ -447,14 +438,9 @@ export interface ChatComposerProps { pullRequestProjectId: ProjectId | null; pullRequestRepository: string | null; threadPullRequests: ReadonlyArray | undefined; - restingControlsHost: HTMLDivElement | null; - restingControlsHaveLeadingContext: boolean; - onRestingControlsVisibilityChange: (visible: boolean) => void; - getTimelineScrollableNode: () => HTMLElement | null; - isTimelineAtLogicalEnd: () => boolean; - timelineOverflows: boolean; onComposerOverlayHeightChange: (height: number) => void; - onRestingChange: (resting: boolean) => void; + /** The new-thread strip names the permissions, so the controls row hides its chip. */ + permissionsShownInStrip: boolean; promptRef: React.RefObject; composerImagesRef: React.RefObject; @@ -575,14 +561,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) pullRequestProjectId, pullRequestRepository, threadPullRequests, - restingControlsHost, - restingControlsHaveLeadingContext, - onRestingControlsVisibilityChange, - getTimelineScrollableNode, - isTimelineAtLogicalEnd, - timelineOverflows, onComposerOverlayHeightChange, - onRestingChange, promptRef, composerRef, composerImagesRef, @@ -725,7 +704,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const { pendingSnapShotAnimations, pendingSnapShotIds, - pendingSnapShotIdSet, uncommittedSnapShotIds, standaloneComposerImages, } = useComposerImageGroups(attachmentDraftTarget, composerImages, composerPreviewAnnotations); @@ -923,16 +901,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) : undefined; const resolvedCompactDisabledReason = compactDisabledReason ?? (noProviderAvailable ? "Compacting is unavailable right now" : null); - const supportedRuntimeModes = selectedProviderEntry?.snapshot.supportedRuntimeModes; - const compatibleRuntimeModeOptions = - supportedRuntimeModes && supportedRuntimeModes.length > 0 - ? runtimeModeOptions.filter((option) => supportedRuntimeModes.includes(option.mode)) - : runtimeModeOptions; - const compatibleRuntimeMode = compatibleRuntimeModeOptions.some( - (option) => option.mode === runtimeMode, - ) - ? runtimeMode - : (compatibleRuntimeModeOptions[0]?.mode ?? runtimeMode); + const { modes: compatibleRuntimeModes, mode: compatibleRuntimeMode } = + resolveCompatibleRuntimeMode( + runtimeMode, + selectedProviderEntry?.snapshot.supportedRuntimeModes, + ); + const compatibleRuntimeModeOptions = runtimeModeOptions.filter((option) => + compatibleRuntimeModes.includes(option.mode), + ); const providerSendBlockReason = getAntigravitySendBlockReason( selectedProviderEntry?.snapshot, @@ -1029,18 +1005,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) null, ); const [isDragOverComposer, setIsDragOverComposer] = useState(false); - const [isComposerFooterCompact, setIsComposerFooterCompact] = useState(false); const [isComposerPrimaryActionsCompact, setIsComposerPrimaryActionsCompact] = useState(false); const [isComposerModelPickerOpen, setIsComposerModelPickerOpen] = useState(false); const isMobileViewport = useMediaQuery("max-sm"); const isSoftwareKeyboardOpen = useSoftwareKeyboardOpen(); - const { - isComposerFocused, - setIsComposerFocused, - isComposerScrollCollapsed, - setIsComposerScrollCollapsed, - restoreAfterTimelineReachedEnd, - } = useComposerFocusState(); + const [isComposerFocused, setIsComposerFocused] = useState(false); const [composerSubmissionError, setComposerSubmissionError] = useState(null); const [providerInputSubmissionError, setProviderInputSubmissionError] = useState( null, @@ -1070,10 +1039,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const mobileComposerExpandFrameRef = useRef(null); const mobileComposerExpandReleaseFrameRef = useRef(null); const mobileComposerExpandInFlightRef = useRef(false); - const composerScrollCollapseTimeoutRef = useRef(null); - const composerScrollCollapseEligibleRef = useRef(false); - const windowRefocusInFlightRef = useRef(false); - const composerScrollGestureRef = useRef(createComposerScrollGestureState()); const pendingThreadImportsRef = useRef>(new Map()); const isRevertingCheckpointRef = useRef(isRevertingCheckpoint); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes the committed checkpoint revert flag to a ref read by async handlers @@ -1183,8 +1148,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) activeComposerMenuItemRef.current = activeComposerMenuItem; }); - const nonPersistedComposerImageIdSet = new Set(nonPersistedComposerImageIds); - const isComposerApprovalState = activePendingApproval !== null; // A send declines the approvals shown here to redirect the agent, so it steers the waiting // turn instead of queueing behind it. Approvals the typing guard holds stay unseen and pending. @@ -1236,7 +1199,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) hiddenBlockCount: restingControlsHiddenBlockCount, iconOnlyBlockCount: restingControlsIconOnlyBlockCount, controlsVisible: restingControlsVisible, - } = useRestingComposerControlsLayout(restingControlsHost ?? inlineRestingControlsHost); + } = useRestingComposerControlsLayout(inlineRestingControlsHost); const { attachControls: attachExpandedComposerControls, hiddenBlockCount: expandedControlsHiddenBlockCount, @@ -1524,43 +1487,24 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) setComposerCursor(cursor); resetComposerTrigger(trigger); setIsDragOverComposer(false); - setIsComposerScrollCollapsed(false); } // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- observes composer form resizes to switch the footer and primary actions between compact layouts useLayoutEffect(() => { const composerForm = composerFormRef.current; if (!composerForm) return; - const measureComposerFormWidth = () => composerForm.clientWidth; - const measureFooterCompactness = () => { - const composerFormWidth = measureComposerFormWidth(); - const footerCompact = shouldUseCompactComposerFooter(composerFormWidth, { - hasWideActions: composerFooterHasWideActions, - }); - const primaryActionsCompact = - footerCompact && - shouldUseCompactComposerPrimaryActions(composerFormWidth, { - hasWideActions: composerFooterHasWideActions, - }); - return { - primaryActionsCompact, - footerCompact, - }; + const measurePrimaryActionsCompact = () => { + const composerFormWidth = composerForm.clientWidth; + const options = { hasWideActions: composerFooterHasWideActions }; + return ( + shouldUseCompactComposerFooter(composerFormWidth, options) && + shouldUseCompactComposerPrimaryActions(composerFormWidth, options) + ); }; - const initialCompactness = measureFooterCompactness(); - setIsComposerPrimaryActionsCompact(initialCompactness.primaryActionsCompact); - setIsComposerFooterCompact(initialCompactness.footerCompact); + setIsComposerPrimaryActionsCompact(measurePrimaryActionsCompact()); return observeResize(composerForm, () => { - const nextCompactness = measureFooterCompactness(); - setIsComposerPrimaryActionsCompact((previous) => - previous === nextCompactness.primaryActionsCompact - ? previous - : nextCompactness.primaryActionsCompact, - ); - setIsComposerFooterCompact((previous) => - previous === nextCompactness.footerCompact ? previous : nextCompactness.footerCompact, - ); + setIsComposerPrimaryActionsCompact(measurePrimaryActionsCompact()); }); }, [composerFooterHasWideActions]); @@ -1631,16 +1575,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) syncComposerDraftPersistedAttachments, ]); - const expandComposerForEditorChange = () => { - suppressActiveComposerScrollGesture( - composerScrollGestureRef.current, - window.performance.now(), - COMPOSER_SCROLL_GESTURE_RESET_MS, - ); - setIsComposerScrollCollapsed(false); - }; - const expandComposerForEditorChangeStable = useStableCallback(expandComposerForEditorChange); - const retainedContextPayloads = useRetainedContextPayloads(composerDraftTargetKey); const onPromptChange = ( @@ -1650,7 +1584,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) cursorAdjacentToMention: boolean, contextIds: string[], ) => { - expandComposerForEditorChange(); refreshWorkspaceSnapshotOnTyping(); if (activePendingProgress?.activeQuestion && pendingUserInputs.length > 0) { if (activePendingProgress.activeQuestion.allowCustomAnswer === false) return; @@ -2319,72 +2252,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) expandMobileComposer: expandMobileComposerStable, }); const hasBlockingComposerTopDrawer = pendingUserInputs.length > 0; - const hasImageAttachmentAttention = standaloneComposerImages.some((image) => { - const upload = uploadsByImageId[image.id]; - const failedInCurrentEnvironment = - supportsAttachmentUploads && - upload?.status === "failed" && - upload.environmentId === environmentId; - return nonPersistedComposerImageIdSet.has(image.id) && !failedInCurrentEnvironment; - }); - const composerHasExpandedChrome = - showComposerTopDrawer || - composerMenuOpen || - isStashMenuOpen || - isDragOverComposer || - isPreparingWorktree || - showProviderUnavailable || - projectSelectionRequired || - environmentUnavailable !== null || - composerSubmissionError !== null || - providerInputSubmissionError !== null || - hasImageAttachmentAttention || - preparingComposerImages.length > 0; - const isComposerResting = shouldUseRestingComposerLayout({ - isExistingThread: routeKind === "server" && activeThreadId !== null, - isMobileViewport, - isScrollCollapsed: isComposerScrollCollapsed, - hasExpandedChrome: composerHasExpandedChrome, - hasMultilinePrompt, - timelineOverflows, - }); - const expandedComposerImages = isComposerResting - ? standaloneComposerImages.filter((image) => pendingSnapShotIdSet.has(image.id)) - : standaloneComposerImages; - const composerControlsCollapsed = isComposerResting || isComposerCollapsedMobile; - const showInlineRestingControls = composerControlsCollapsed && restingControlsHost === null; - const composerControlsVisibleInStrip = - composerControlsCollapsed && restingControlsHost !== null && restingControlsVisible; - const composerControlsHidden = composerControlsCollapsed && !restingControlsVisible; + const composerControlsCollapsed = isComposerCollapsedMobile; + // The collapsed mobile web composer keeps a second controls row inside the card. + const showInlineRestingControls = isComposerCollapsedMobile; + const composerControlsHidden = showInlineRestingControls && !restingControlsVisible; if (composerControlsHidden && isComposerModelPickerOpen) { setIsComposerModelPickerOpen(false); } - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reports whether resting controls show in the strip to ChatView before paint - useLayoutEffect(() => { - onRestingControlsVisibilityChange(composerControlsVisibleInStrip); - }, [composerControlsVisibleInStrip, onRestingControlsVisibilityChange]); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reports the resting state to ChatView's ref before paint - useLayoutEffect(() => { - onRestingChange(isComposerResting); - }, [isComposerResting, onRestingChange]); - const [restingActionsElement, setRestingActionsElement] = useState(null); - const [restingActionsWidth, setRestingActionsWidth] = useState(null); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- observes resizes of the resting actions DOM node to measure its width - useLayoutEffect(() => { - if (!isComposerResting || !restingActionsElement) return; - const measure = () => setRestingActionsWidth(restingActionsElement.offsetWidth); - measure(); - return observeResize(restingActionsElement, measure); - }, [isComposerResting, restingActionsElement]); - const showMoreRestingImages = () => { - if (isComposerCollapsedMobile) { - expandMobileComposer(); - return; - } - setIsComposerScrollCollapsed(false); - setIsComposerFocused(true); - scheduleComposerFocus(); - }; const collapsedComposerImagePreviews = standaloneComposerImages.length > 0 ? ( ) : null; const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } = usePanelAnimationSettings(); const composerMainSurfaceRef = useComposerRestingTransition( composerControlsCollapsed, - isComposerResting, restingComposerControlsRef, onComposerOverlayHeightChange, panelAnimationsActive, panelAnimationDurationMs, ); - const canTrackComposerScrollGesture = - routeKind === "server" && activeThreadId !== null && !isMobileViewport; - const canScrollCollapseComposer = - canTrackComposerScrollGesture && - settings.composerCollapseOnScroll && - !hasMultilinePrompt && - !composerHasExpandedChrome; - // Clear rather than mask: once eligibility drops, the composer stays expanded until the next - // scroll gesture even if it becomes eligible again. - if (!canScrollCollapseComposer && isComposerScrollCollapsed) { - setIsComposerScrollCollapsed(false); - } - const composerScrollCollapseEligible = canScrollCollapseComposer && !isComposerResting; - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes the committed scroll-collapse eligibility to a ref read by the wheel listener - useLayoutEffect(() => { - composerScrollCollapseEligibleRef.current = composerScrollCollapseEligible; - }); - - // Window activation re-fires focus; ignore that frame to keep the composer collapsed. - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window focus listener and animation frame that ignore activation focus while the composer is collapsed - useEffect(() => { - if (!isComposerScrollCollapsed) return; - let frame: number | null = null; - const onWindowFocus = () => { - windowRefocusInFlightRef.current = true; - if (frame !== null) window.cancelAnimationFrame(frame); - frame = window.requestAnimationFrame(() => { - frame = null; - windowRefocusInFlightRef.current = false; - }); - }; - window.addEventListener("focus", onWindowFocus); - return () => { - window.removeEventListener("focus", onWindowFocus); - if (frame !== null) window.cancelAnimationFrame(frame); - windowRefocusInFlightRef.current = false; - }; - }, [isComposerScrollCollapsed]); - - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes a capture-phase document wheel listener that collapses the composer on timeline scroll - useEffect(() => { - if (!canTrackComposerScrollGesture) return; - - const finishScrollGesture = () => { - if (composerScrollCollapseTimeoutRef.current !== null) { - window.clearTimeout(composerScrollCollapseTimeoutRef.current); - } - composerScrollCollapseTimeoutRef.current = null; - resetComposerScrollGesture(composerScrollGestureRef.current); - }; - const handleTimelineWheel = (event: WheelEvent) => { - if (event.ctrlKey || !(event.target instanceof Element)) { - return; - } - - const scrollNode = getTimelineScrollableNode(); - if (!scrollNode) return; - const targetsTimeline = isTimelineScrollTarget(event.target, scrollNode, event.deltaY); - if ( - !scrollNode.contains(event.target) && - !composerScrollGestureRef.current.collapseSuppressed - ) - return; - - if (composerScrollCollapseTimeoutRef.current !== null) { - window.clearTimeout(composerScrollCollapseTimeoutRef.current); - } - composerScrollCollapseTimeoutRef.current = window.setTimeout( - finishScrollGesture, - COMPOSER_SCROLL_GESTURE_RESET_MS, - ); - - const canScrollInGestureDirection = - targetsTimeline && - (event.deltaY < 0 - ? scrollNode.scrollTop > 0 - : scrollNode.scrollTop < scrollNode.scrollHeight - scrollNode.clientHeight); - const deltaPx = - Math.abs(event.deltaY) * - (event.deltaMode === WheelEvent.DOM_DELTA_LINE - ? 16 - : event.deltaMode === WheelEvent.DOM_DELTA_PAGE - ? scrollNode.clientHeight - : 1); - const shouldCollapse = recordComposerScrollGestureEvent(composerScrollGestureRef.current, { - now: window.performance.now(), - deltaPx, - collapseThresholdPx: COMPOSER_SCROLL_COLLAPSE_THRESHOLD_PX, - collapseEligible: targetsTimeline && composerScrollCollapseEligibleRef.current, - canScrollInGestureDirection, - scrollsTowardLogicalEnd: event.deltaY > 0 && isTimelineAtLogicalEnd(), - }); - if (!shouldCollapse) { - return; - } - - setIsComposerScrollCollapsed(true); - }; - - document.addEventListener("wheel", handleTimelineWheel, { capture: true, passive: true }); - return () => { - document.removeEventListener("wheel", handleTimelineWheel, true); - finishScrollGesture(); - }; - }, [ - canTrackComposerScrollGesture, - getTimelineScrollableNode, - isTimelineAtLogicalEnd, - setIsComposerScrollCollapsed, - ]); - - const restingHiddenBlockCount = composerControlsCollapsed + const restingHiddenBlockCount = showInlineRestingControls ? restingControlsHiddenBlockCount - : expandedControlsHiddenBlockCount; - const iconOnlyBlockCount = composerControlsCollapsed + : composerControlsCollapsed + ? 0 + : expandedControlsHiddenBlockCount; + const iconOnlyBlockCount = showInlineRestingControls ? restingControlsIconOnlyBlockCount - : expandedControlsIconOnlyBlockCount; + : composerControlsCollapsed + ? 0 + : expandedControlsIconOnlyBlockCount; const composerControls = ( { composerEditorRef.current?.focusAt(cursor); }, - restoreAfterTimelineReachedEnd, - collapseForTimelineScrollKey: (key) => { - const scrollNode = getTimelineScrollableNode(); - if ( - composerScrollCollapseEligibleRef.current && - scrollNode && - shouldCollapseComposerForScrollKey({ - key, - scrollTop: scrollNode.scrollTop, - scrollHeight: scrollNode.scrollHeight, - clientHeight: scrollNode.clientHeight, - isAtLogicalEnd: isTimelineAtLogicalEnd(), - }) - ) { - setIsComposerScrollCollapsed(true); - } - }, addDroppedFiles: (files: File[]) => { void addComposerAttachments(files).then((inserted) => { if (!inserted) focusComposer(); @@ -3112,10 +2857,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) window.cancelAnimationFrame(composerBlurFrameRef.current); composerBlurFrameRef.current = null; } - flushSync(() => { - setIsComposerScrollCollapsed(false); - setIsComposerFocused(true); - }); + flushSync(() => setIsComposerFocused(true)); const shell = composerFormRef.current?.closest('[data-slot="composer-shell"]'); const trigger = Array.from( shell?.querySelectorAll( @@ -3127,6 +2869,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ); if (!trigger) return; trigger.focus({ preventScroll: true }); + if (command === "composer.mode") markOpenToPermissions(trigger); trigger.click(); }, compactContext: compactThreadContextStable, @@ -3290,10 +3033,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) interactionMode, planModeUiEnabled, compactThreadContextStable, - restoreAfterTimelineReachedEnd, - getTimelineScrollableNode, - isTimelineAtLogicalEnd, - setIsComposerScrollCollapsed, ], ); @@ -3302,11 +3041,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) !isComposerCollapsedMobile && (uncommittedSnapShotIds.length > 0 || composerVideos.length > 0 || - expandedComposerImages.length > 0 || + standaloneComposerImages.length > 0 || preparingComposerImages.length > 0) ? ( { - const target = event.target; - if (isInsideRestingComposerControlScope(target)) return; - if (isInsideCollapsedComposerControls(target)) return; - if (!(target instanceof Element)) return; - const isInteractive = Boolean( - target.closest('button, a, input, select, [role="button"], [role="menuitem"]'), - ); - if (isInteractive) return; - - setIsComposerScrollCollapsed(false); - if (isComposerResting && !target.closest('[data-testid="composer-editor"]')) { - event.preventDefault(); - setIsComposerFocused(true); - scheduleComposerFocus(); - } - }} onFocusCapture={(event) => { const activeElement = event.target; if ( @@ -3381,9 +3103,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) if (isInsideCollapsedComposerControls(activeElement)) { return; } - if (!windowRefocusInFlightRef.current) { - setIsComposerScrollCollapsed(false); - } if (composerBlurFrameRef.current !== null) { window.cancelAnimationFrame(composerBlurFrameRef.current); composerBlurFrameRef.current = null; @@ -3419,23 +3138,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) data-chat-composer-form="true" {...threadContextDropTargetProps()} > - {composerControlsCollapsed && restingControlsHost - ? createPortal( -
    - {composerControls} -
    , - restingControlsHost, - ) - : null} @@ -3479,10 +3181,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
    {isStashMenuOpen && !composerMenuOpen && ( @@ -3621,14 +3319,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) {composerAttachmentFileList} -
    +
    {previewFile ? ( - {isComposerResting ? collapsedComposerImagePreviews : null} {showMobilePendingAnswerActions ? (
    0 && "pt-2", - isComposerFooterCompact ? "gap-1.5" : "gap-2 sm:gap-0", showMobilePendingAnswerActions && "hidden sm:flex", - isComposerResting && - "absolute right-px z-10 h-12 w-auto gap-0 py-0 sm:gap-0 sm:py-0", - isComposerResting && - (showInlineRestingControls ? "bottom-[calc(2rem+1px)]" : "bottom-px"), )} > + {composerAttachButton ?
    {composerAttachButton}
    : null}
    - {composerControlsCollapsed ? null : composerControls} -
    - -
    - {composerAttachButton} +
    + {composerControls} +
    ; + runtimeModeOptions: ReadonlyArray; showInteractionModeToggle: boolean; traitsMenuContent?: ReactNode; + showPermissions?: boolean; size?: "sm" | "xs"; /** Close the portaled popup when its trigger hides. */ hidden?: boolean; @@ -31,17 +30,28 @@ export const CompactComposerControlsMenu = memo(function CompactComposerControls const composerFloatingLayerProps = useComposerMenuProps(); const size = props.size ?? "sm"; const [open, setOpen] = useComposerMenuState(props.hidden); + const triggerRef = useRef(null); return ( - + focusRequestedPermission(isOpen, triggerRef.current)} + > } @@ -52,7 +62,9 @@ export const CompactComposerControlsMenu = memo(function CompactComposerControls {props.traitsMenuContent ? ( <> {props.traitsMenuContent} - + {props.showInteractionModeToggle || props.showPermissions !== false ? ( + + ) : null} ) : null} {props.showInteractionModeToggle ? ( @@ -68,23 +80,16 @@ export const CompactComposerControlsMenu = memo(function CompactComposerControls Chat Plan - + {props.showPermissions !== false ? : null} ) : null} -
    Access
    - { - if (!value || value === props.runtimeMode) return; - props.onRuntimeModeChange(value as RuntimeMode); - }} - > - {props.runtimeModeOptions.map((option) => ( - - {option.label} - - ))} - + {props.showPermissions === false ? null : ( + + )}
    ); diff --git a/apps/web/src/components/chat/ComposerAttachmentStrip.tsx b/apps/web/src/components/chat/ComposerAttachmentStrip.tsx index 2a0c0f7b1a1ad..e3560312925e5 100644 --- a/apps/web/src/components/chat/ComposerAttachmentStrip.tsx +++ b/apps/web/src/components/chat/ComposerAttachmentStrip.tsx @@ -707,7 +707,8 @@ export function ComposerAttachButton({ /> } > - + {/* The clip's weight sits in its upper loop; 1px down reads as centered on the row. */} + Attach files diff --git a/apps/web/src/components/chat/ComposerControl.tsx b/apps/web/src/components/chat/ComposerControl.tsx index 6f1824fd72642..9ec5d4e1144d4 100644 --- a/apps/web/src/components/chat/ComposerControl.tsx +++ b/apps/web/src/components/chat/ComposerControl.tsx @@ -1,11 +1,9 @@ import { mergeProps } from "@base-ui/react/merge-props"; import { Select as SelectPrimitive } from "@base-ui/react/select"; import { useRender } from "@base-ui/react/use-render"; -import type { ComponentProps, ComponentType, SVGProps } from "react"; -import { ChevronDownIcon } from "lucide-react"; +import type { ComponentType, SVGProps } from "react"; import { cn } from "~/lib/utils"; -import { Separator } from "../ui/separator"; export type ComposerControlSize = "sm" | "xs"; @@ -66,43 +64,6 @@ export function ComposerControlIcon({ ); } -export function ComposerControlChevron({ - className, - size = "sm", -}: { - className?: string; - size?: ComposerControlSize; -} = {}) { - return ( -
    diff --git a/apps/web/src/components/device/DevicePanel.tsx b/apps/web/src/components/device/DevicePanel.tsx index c8f55665113ac..90cc7533c0b51 100644 --- a/apps/web/src/components/device/DevicePanel.tsx +++ b/apps/web/src/components/device/DevicePanel.tsx @@ -238,7 +238,7 @@ export function DevicePanel(props: { environmentId={environmentId} device={activeDevice} hostLabel={activeHost?.label ?? "Device host"} - simlock={activeHost?.kind === "simlock"} + hostKind={activeHost?.kind} hostDiagnostics={ diagnostics.find(({ hostId }) => hostId === activeDevice.hostId)?.detail } diff --git a/apps/web/src/components/device/DeviceSetup.tsx b/apps/web/src/components/device/DeviceSetup.tsx index 9d7b30c0456a7..29b46e99319a4 100644 --- a/apps/web/src/components/device/DeviceSetup.tsx +++ b/apps/web/src/components/device/DeviceSetup.tsx @@ -119,7 +119,7 @@ export function platformSetupStatus(state: DeviceServiceState, platform: DeviceP ready: true, message: remoteHost?.kind === "eas" - ? `${remoteHost.label} starts iOS Simulators in the cloud with EAS Simulator.` + ? `${remoteHost.label} starts ${platform === "ios" ? "iOS Simulators" : "Android emulators"} in the cloud with EAS Simulator.` : platform === "ios" ? `Xcode and iOS Simulator are available${location}.` : `The Android SDK and Emulator are available${location}.`, diff --git a/apps/web/src/components/device/DeviceWorkspace.tsx b/apps/web/src/components/device/DeviceWorkspace.tsx index b57adae023269..08ce51c1c548c 100644 --- a/apps/web/src/components/device/DeviceWorkspace.tsx +++ b/apps/web/src/components/device/DeviceWorkspace.tsx @@ -1,4 +1,4 @@ -import type { DeviceSummary, EnvironmentId } from "@t3tools/contracts"; +import type { DeviceHostSummary, DeviceSummary, EnvironmentId } from "@t3tools/contracts"; import { useRef, useState } from "react"; import { captureDeviceScreenshot, @@ -16,8 +16,7 @@ export function DeviceWorkspace(props: { environmentId: EnvironmentId; device: DeviceSummary; hostLabel: string; - /** Leased from a Simlock pool: serve-sim input, no host commands. */ - simlock?: boolean; + hostKind: DeviceHostSummary["kind"] | undefined; hostDiagnostics: string | undefined; visible: boolean; onFloat: () => void; @@ -31,7 +30,13 @@ export function DeviceWorkspace(props: { // A capture always finishes, even if the panel hides or closes meanwhile; the user asked for it. const capturing = useRef(false); const access = useDeviceHubAccess(props.environmentId, props.device.hostId); - const controls = useDeviceControls({ ...props, access }); + // Settings and tools run commands on the device's own machine, which EAS and Simlock do not expose. + const runsHostCommands = props.hostKind === "local" || props.hostKind === "ssh"; + const controls = useDeviceControls({ + ...props, + access, + visible: props.visible && runsHostCommands, + }); const saveScreenshot = () => { if (!access || capturing.current || !props.visible) return; capturing.current = true; @@ -82,12 +87,13 @@ export function DeviceWorkspace(props: { deviceId={props.device.id} hostId={props.device.hostId} visible={props.visible} - serveSimOnly={props.simlock === true} + serveSimOnly={props.hostKind === "simlock"} axOverlay={axOverlay} allowPhoneView renderControls={(view) => ( )} /> diff --git a/docs/internals/devices.md b/docs/internals/devices.md index 5273f7942e9e0..28fa103feb5cb 100644 --- a/docs/internals/devices.md +++ b/docs/internals/devices.md @@ -36,13 +36,13 @@ its sessions. Sessions it starts are recorded under the state directory and stopped by the next server if this one dies; sessions other tools started on the same account are never touched. -Each session brings its own serve-sim preview host and agent-device daemon, -with their own tokens. The proxy asks the host to route each request -(`DeviceHostReady.upstream`) and adds the session token server-side, so +Each session brings its own preview host (serve-sim, or serve-emu for Android) +and agent-device daemon, with their own tokens. The proxy asks the host to +route each request (`DeviceHostReady.upstream`) and adds the session token server-side, so clients never hold it. Agent config files are written per device (`DeviceOperations.agentEndpoint`), which is why `device_open` opens the -device before targeting it. Device settings run `simctl` on the simulator's -machine, which EAS does not expose, so they are unavailable there. +device before targeting it. Device settings and tools run `simctl` or `adb` on +the device's machine, which EAS does not expose, so they are unavailable there. ## Simlock hosts lease through the agent-device front @@ -147,8 +147,8 @@ decoder then retains frames for seconds despite `optimizeForLatency` and an empt `decodeQueueSize`. The iOS AVCC viewer restores the missing metadata before configuring the decoder so hardware decoding can remain enabled. WebCodecs is secure-context only, so the viewer probes `isConfigSupported` and falls back to -MJPEG on iOS when decoding is unavailable. Android has no MJPEG; there the panel -reports that it cannot decode. +MJPEG on iOS when decoding is unavailable. Android's SEMU socket has no MJPEG; +there the panel reports that it cannot decode. serve-sim can also be locked to WebRTC, as on EAS Simulator, and then refuses AVCC with a 409 naming the transport. The viewer still asks for AVCC first, so @@ -156,3 +156,6 @@ hubs that serve it pay nothing, and switches on that 409, or when its MJPEG image fails in a browser that has `RTCPeerConnection`. Offers are not trickled: serve-sim takes one offer with every candidate. The video element only feeds the same canvas sink, so the panel and the mobile WebView keep one surface. +Android asks serve-emu's `/api` before opening its video socket and streams +WebRTC when it is advertised (EAS Simulator), keeping a separate `video=0` +socket for input so input can reconnect without restarting video. diff --git a/docs/user/devices.md b/docs/user/devices.md index ce5a7d8d06d05..46a5a427cc87c 100644 --- a/docs/user/devices.md +++ b/docs/user/devices.md @@ -94,7 +94,7 @@ started from then on; your own Device panel is unaffected. The device stream goes through the environment server, so it works over the local network, Tailscale, and T3 Connect. Live video needs a secure page (HTTPS or localhost); on a plain-HTTP remote origin iOS falls back to a slower -still-image stream and Android cannot show video. +still-image stream and Android cannot show video, except on EAS Simulator. ## SSH device hosts diff --git a/packages/client-runtime/src/device/stream.test.ts b/packages/client-runtime/src/device/stream.test.ts index 737daf5158c04..09f04c52780e2 100644 --- a/packages/client-runtime/src/device/stream.test.ts +++ b/packages/client-runtime/src/device/stream.test.ts @@ -75,7 +75,7 @@ describe("native device stream transport", () => { } } vi.stubGlobal("WebSocket", FakeSocket); - const fetch = vi.fn(() => Promise.resolve(new Response("frame"))); + const fetch = vi.fn(() => Promise.resolve(Response.json({}))); vi.stubGlobal("fetch", fetch); const events = { onStatus: vi.fn(), @@ -251,6 +251,7 @@ function recoveryFixture( const fetch = vi.fn((url: string, init: RequestInit) => { const signal = init.signal!; signals.push(signal); + if (url.includes("/api?")) return Promise.resolve(Response.json({})); if (!url.includes("stream.avcc")) return Promise.resolve(new Response("prime")); return Promise.resolve( new Response( @@ -450,9 +451,11 @@ describe("shared device stream readiness and recovery", () => { }), ); client.start(); + await vi.advanceTimersByTimeAsync(0); sockets[0]!.onmessage?.({ data: sps }); client.stop(); client.start(); + await vi.advanceTimersByTimeAsync(0); resolveSupport({ supported: true }); await vi.advanceTimersByTimeAsync(0); expect(decoders).toHaveLength(0); @@ -491,3 +494,136 @@ describe("shared device stream readiness and recovery", () => { expect(vi.getTimerCount()).toBe(0); }); }); + +describe("Android WebRTC device streams", () => { + afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); + }); + + function setup() { + vi.useFakeTimers(); + const sockets: Socket[] = []; + class Socket { + static OPEN = 1; + readyState = 1; + binaryType = ""; + onopen: (() => void) | null = null; + onmessage: ((event: { data: string }) => void) | null = null; + onclose: ((event: { code: number; reason: string }) => void) | null = null; + send = vi.fn(); + close = vi.fn(); + readonly url: string; + constructor(url: string) { + this.url = url; + sockets.push(this); + } + } + const videos: Video[] = []; + class Video { + muted = false; + playsInline = false; + style = { cssText: "" }; + srcObject: unknown = null; + videoWidth = 400; + videoHeight = 800; + setAttribute = vi.fn(); + remove = vi.fn(); + play = vi.fn(async () => {}); + callback: (() => void) | null = null; + requestVideoFrameCallback(callback: () => void) { + this.callback = callback; + return 0; + } + constructor() { + videos.push(this); + } + } + const peers: Peer[] = []; + class Peer { + iceGatheringState = "complete"; + connectionState = "connected"; + localDescription = { type: "offer", sdp: "offer-sdp" }; + ontrack: ((event: { streams: unknown[]; track: unknown }) => void) | null = null; + onconnectionstatechange: (() => void) | null = null; + close = vi.fn(); + createOffer = vi.fn(async () => this.localDescription); + setLocalDescription = vi.fn(async () => {}); + setRemoteDescription = vi.fn(async () => {}); + addTransceiver = vi.fn(() => ({ setCodecPreferences: vi.fn() })); + addEventListener = vi.fn(); + removeEventListener = vi.fn(); + constructor() { + peers.push(this); + } + } + vi.stubGlobal("WebSocket", Socket); + vi.stubGlobal("RTCPeerConnection", Peer); + vi.stubGlobal("RTCRtpReceiver", { getCapabilities: () => ({ codecs: [] }) }); + vi.stubGlobal("document", { createElement: () => new Video(), body: { append: vi.fn() } }); + const fetch = vi.fn((url: string, _init?: RequestInit) => + Promise.resolve( + url.includes("/api?") + ? Response.json({ serial: "emulator-5554", stream: { transport: "webrtc" } }) + : Response.json({ type: "answer", sdp: "answer-sdp" }), + ), + ); + vi.stubGlobal("fetch", fetch); + const events = { + onStatus: vi.fn(), + onScreen: vi.fn(), + onUnauthorized: vi.fn(), + onMjpegFallback: vi.fn(), + onInputConnected: vi.fn(), + }; + const present = vi.fn(() => true); + const client = createDeviceStreamClient( + { + platform: "android", + deviceId: "session-1", + access: { + httpBase: "https://test/api/device-hub", + wsBase: "wss://test/api/device-hub", + credentials: true, + query: { hostId: "eas" }, + }, + }, + { present }, + events, + ); + return { client, events, fetch, peers, videos, sockets, present }; + } + + it("streams over WebRTC when serve-emu advertises it, with input that reconnects on its own", async () => { + const { client, events, fetch, peers, videos, sockets, present } = setup(); + client.start(); + await vi.advanceTimersByTimeAsync(0); + expect(fetch.mock.calls.map(([url]) => url)).toEqual([ + "https://test/api/device-hub/vendor/serve-emu/api?device=session-1&hostId=eas", + "https://test/api/device-hub/vendor/serve-emu/webrtc/offer?device=session-1&hostId=eas", + ]); + expect(peers[0]?.setRemoteDescription).toHaveBeenCalledWith({ + type: "answer", + sdp: "answer-sdp", + }); + peers[0]?.ontrack?.({ streams: [{}], track: {} }); + videos[0]?.callback?.(); + expect(present).toHaveBeenCalledWith(videos[0], 400, 800); + expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined); + + expect(sockets.map((socket) => socket.url)).toEqual([ + "wss://test/api/device-hub/vendor/serve-emu/ws?device=session-1&video=0&hostId=eas", + ]); + sockets[0]!.onopen?.(); + client.pressButton("back"); + expect(sockets[0]!.send).toHaveBeenCalledWith(JSON.stringify({ type: "back" })); + events.onStatus.mockClear(); + sockets[0]!.onclose?.({ code: 1001, reason: "going away" }); + await vi.advanceTimersByTimeAsync(1_000); + expect(sockets[1]?.url).toContain("video=0"); + expect(peers).toHaveLength(1); + expect(peers[0]?.close).not.toHaveBeenCalled(); + expect(events.onStatus).not.toHaveBeenCalled(); + client.stop(); + }); +}); diff --git a/packages/client-runtime/src/device/stream.ts b/packages/client-runtime/src/device/stream.ts index c4b8078597245..a8913d5a41037 100644 --- a/packages/client-runtime/src/device/stream.ts +++ b/packages/client-runtime/src/device/stream.ts @@ -836,9 +836,10 @@ export function createDeviceStreamClient( /** * serve-sim can be locked to WebRTC (EAS Simulator always is), and then - * refuses AVCC and MJPEG. An unreadable answer keeps the AVCC path. + * refuses AVCC and MJPEG; serve-emu advertises WebRTC the same way. An + * unreadable answer keeps the default path. */ - const probeIosTransport = async (): Promise => { + const probeWebRtc = async (): Promise => { const probe = new AbortController(); const timeout = setTimeout(() => probe.abort(), TRANSPORT_PROBE_TIMEOUT_MS); try { @@ -858,6 +859,9 @@ export function createDeviceStreamClient( } }; + const webRtcUrl = (action: "offer" | "close") => + httpUrl(avcc ? `/helper/${device}/webrtc/${action}` : `/webrtc/${action}?device=${device}`); + const closePeer = () => { const current = peer; if (!current) return; @@ -865,8 +869,8 @@ export function createDeviceStreamClient( current.connection.close(); current.video.srcObject = null; current.video.remove(); - // Releases serve-sim's capture session; best effort because the page may be unloading. - void fetch(httpUrl(`/helper/${device}/webrtc/close`), { + // Releases the capture session; best effort because the page may be unloading. + void fetch(webRtcUrl("close"), { method: "POST", keepalive: true, headers: { "content-type": "application/json" }, @@ -875,7 +879,7 @@ export function createDeviceStreamClient( }).catch(() => {}); }; - const readIosWebRtc = async (settings: WebRtcSettings) => { + const readWebRtc = async (settings: WebRtcSettings) => { const lifecycle = generation; const feedGeneration = ++videoGeneration; closePeer(); @@ -920,7 +924,7 @@ export function createDeviceStreamClient( if (!isCurrent()) return; closePeer(); connecting(detail); - scheduleRetry("video", () => void readIosWebRtc(settings)); + scheduleRetry("video", () => void readWebRtc(settings)); }; const presentFrame = () => { if (!isCurrent()) { @@ -988,7 +992,7 @@ export function createDeviceStreamClient( iceGatheringDeadlineMs = Math.min(iceGatheringDeadlineMs * 2, ICE_GATHERING_MAX_TIMEOUT_MS); return retry("Device stream found no network candidates yet. Retrying…"); } - const response = await fetch(httpUrl(`/helper/${device}/webrtc/offer`), { + const response = await fetch(webRtcUrl("offer"), { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ @@ -1023,8 +1027,7 @@ export function createDeviceStreamClient( const switchToWebRtc = async (failure: string, locked: boolean) => { const session = generation; if (typeof RTCPeerConnection === "undefined") return fail(failure); - const settings = - (await probeIosTransport()) ?? (locked ? { transport: "webrtc" as const } : null); + const settings = (await probeWebRtc()) ?? (locked ? { transport: "webrtc" as const } : null); if (stopped || generation !== session) return; if (!settings) return fail(failure); if (mjpeg) { @@ -1036,7 +1039,7 @@ export function createDeviceStreamClient( // MJPEG may have shown frames already: say the stream is connecting again // rather than leave a blank canvas until the first WebRTC frame. connecting("Switching to WebRTC."); - void readIosWebRtc(settings); + void readWebRtc(settings); }; const startDuoVideo = (panels: DuoPanelSinks) => { @@ -1161,18 +1164,21 @@ export function createDeviceStreamClient( ws.onerror = () => ws.close(); }; - const connectAndroid = () => { + /** `inputOnly` keeps a socket for input beside a WebRTC feed, so its reconnects leave video alone. */ + const connectAndroid = (inputOnly = false) => { if (stopped) return; - const ws = new WebSocket(wsUrl(`/ws?device=${device}&frame-meta=1`)); + const ws = new WebSocket( + wsUrl(`/ws?device=${device}&${inputOnly ? "video=0" : "frame-meta=1"}`), + ); ws.binaryType = "arraybuffer"; socket = ws; ws.onopen = () => { if (stopped || socket !== ws) return; - connecting(); + if (!inputOnly) connecting(); events.onInputConnected(true); }; ws.onmessage = (event) => { - if (stopped || socket !== ws) return; + if (stopped || socket !== ws || inputOnly) return; if (typeof event.data === "string") { // The encoder restarts at a new size when the device rotates; the // next keyframe carries a fresh SPS, so the decoder is rebuilt from it. @@ -1224,13 +1230,29 @@ export function createDeviceStreamClient( (event.code === 1006 && access.query.wsTicket) ) return handleUnauthorized(); - configuring = false; - connecting(event.reason || undefined); - scheduleRetry("input", connectAndroid); + if (!inputOnly) { + configuring = false; + connecting(event.reason || undefined); + } + // A full socket re-probes, so one failed /api read does not pin SEMU on a WebRTC host. + scheduleRetry("input", () => (inputOnly ? connectAndroid(true) : void startAndroid())); }; ws.onerror = () => ws.close(); }; + const startAndroid = async () => { + const session = generation; + const settings = await probeWebRtc(); + if (stopped || generation !== session) return; + if (settings) { + if (typeof RTCPeerConnection === "undefined") + return fail("This browser cannot receive the device's WebRTC stream."); + if (!target.videoOnly) connectAndroid(true); + void readWebRtc(settings); + } else if (useWebCodecs) connectAndroid(); + else fail("This browser cannot decode the Android stream (WebCodecs unavailable)."); + }; + const start = () => { if (!stopped) return; stopped = false; @@ -1247,11 +1269,7 @@ export function createDeviceStreamClient( if (!target.videoOnly) void connectIosInput(); if (useWebCodecs) void readIosVideo(); else fallBackToMjpeg(); - } else if (useWebCodecs) { - connectAndroid(); - } else { - fail("This browser cannot decode the Android stream (WebCodecs unavailable)."); - } + } else void startAndroid(); }; const stop = () => { From cba30591f95859bc76154e5be97891ea4ae1b85a Mon Sep 17 00:00:00 2001 From: maria Date: Fri, 30 Oct 2026 00:02:56 +0000 Subject: [PATCH 387/817] fix(web,mobile): image-only messages show the image, not the placeholder prompt (#26769) --- .../src/features/threads/ThreadFeed.tsx | 37 ++++++-- .../threads/threadQueueControlPresentation.ts | 5 +- .../src/components/chat/QueuedRunsControl.tsx | 17 ++-- .../chat/TimelineUserMessageRow.tsx | 87 ++++++++++++++++--- .../client-runtime/src/userMessage.test.ts | 14 +++ packages/client-runtime/src/userMessage.ts | 4 +- .../shared/src/composerContextReferences.ts | 5 ++ packages/shared/src/threadFindText.test.ts | 11 +++ packages/shared/src/threadFindText.ts | 7 +- 9 files changed, 161 insertions(+), 26 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index da127a29ef9bf..33a57859ff8b3 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -1596,6 +1596,16 @@ function renderFeedEntry( const visibleAttachments = attachments.filter( (attachment) => isImageAttachment(attachment) || !inlineAttachmentIds.has(attachment.id), ); + // Images sent without words show as images, not as a bubble around them. + const mediaOnly = + foldRowId === null && + presentation.attribution !== "guest" && + presentation.text.trim() === "" && + visibleAttachments.length + (entry.pendingMessage?.attachments.length ?? 0) > 0 && + visibleAttachments.every(isImageAttachment) && + (entry.pendingMessage?.attachments ?? []).every( + (attachment) => attachment.type === "image", + ); return ( 0) ? { width: props.duoColumns ? "85%" : props.userBubbleMaxWidth } : null), }} @@ -1640,7 +1650,13 @@ function renderFeedEntry( /> ) : null} {bubbleBodyVisible ? ( - + {entry.pendingMessage?.attachments.map((attachment) => attachment.type === "image" && attachment.uploadedAttachmentId ? ( ) : attachment.type === "image" ? ( @@ -1668,7 +1688,7 @@ function renderFeedEntry( > ) : ( @@ -1689,7 +1709,10 @@ function renderFeedEntry( className={ inlineAttachmentIds.size ? "h-24 w-24 rounded-[14px] bg-user-bubble-foreground/15" - : "aspect-[1.3] w-full rounded-[14px] bg-user-bubble-foreground/15" + : mediaOnly + ? // Matches the bubble's corners; native borders sit inside, so the edge adds no size. + "aspect-[1.3] w-full rounded-[20px] border border-border bg-user-bubble-foreground/15" + : "aspect-[1.3] w-full rounded-[14px] bg-user-bubble-foreground/15" } onPressPreview={props.onPressPreview} /> @@ -1707,7 +1730,7 @@ function renderFeedEntry( })} ) : null} - {message.text.trim().length > 0 ? ( + {presentation.text.trim().length > 0 ? ( diff --git a/apps/mobile/src/features/threads/threadQueueControlPresentation.ts b/apps/mobile/src/features/threads/threadQueueControlPresentation.ts index 444d969176ba2..a62e29e14795d 100644 --- a/apps/mobile/src/features/threads/threadQueueControlPresentation.ts +++ b/apps/mobile/src/features/threads/threadQueueControlPresentation.ts @@ -1,5 +1,6 @@ import type { EnvironmentId, RunId, ThreadId } from "@t3tools/contracts"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; +import { isAttachmentOnlyBootstrapPrompt } from "@t3tools/shared/composerContextReferences"; export const REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL = "Remove queued message"; @@ -35,7 +36,9 @@ export function resolveThreadQueueRowControls(input: { canSend: mutationEnabled && (input.canPromoteToSteer || input.canSendNow) && !isEditing, dismissAccessibilityLabel: REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL, // Editing and sending keep the original text so quoted citations stay linked. - displayText: assistantCitationsToPlainText(input.text), + displayText: isAttachmentOnlyBootstrapPrompt(input.text) + ? "" + : assistantCitationsToPlainText(input.text), isEditing, }; } diff --git a/apps/web/src/components/chat/QueuedRunsControl.tsx b/apps/web/src/components/chat/QueuedRunsControl.tsx index 866612bc11009..ca98e919ff93d 100644 --- a/apps/web/src/components/chat/QueuedRunsControl.tsx +++ b/apps/web/src/components/chat/QueuedRunsControl.tsx @@ -1,7 +1,10 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { deriveThreadQueueWorkflowState } from "@t3tools/client-runtime/state/thread-workflows"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; -import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; +import { + isAttachmentOnlyBootstrapPrompt, + replaceComposerContextReferences, +} from "@t3tools/shared/composerContextReferences"; import type { ChatAttachment as ContractChatAttachment, EnvironmentId, @@ -237,11 +240,13 @@ export function QueuedRunsControl({
      {visibleItems.map((item, position) => { - const previewText = assistantCitationsToPlainText( - replaceComposerContextReferences(item.text, (reference) => - reference.kind === "image" && item.thumbnails.length > 0 ? "" : reference.label, - ), - ).trim(); + const previewText = isAttachmentOnlyBootstrapPrompt(item.text) + ? "" + : assistantCitationsToPlainText( + replaceComposerContextReferences(item.text, (reference) => + reference.kind === "image" && item.thumbnails.length > 0 ? "" : reference.label, + ), + ).trim(); const isEditing = item.runId !== null && item.runId === props.editingRunId; return (
    1. image.name.startsWith("preview-annotation-")); const revertTurnCount = row.revertTurnCount; const chippedAttachmentIds = new Set( @@ -340,6 +342,27 @@ function UserTimelineRow({ row }: { row: Extract !image.name.startsWith("preview-annotation-")); const unchippedFiles = otherUserFiles.filter((file) => !chippedAttachmentIds.has(file.id)); + // Images or videos sent without words show as media, not as a bubble around them. + const mediaOnly = + !folded && + userMessage.attribution !== "guest" && + resolvedContext.text.trim() === "" && + userAudio.length === 0 && + unchippedFiles.length === 0 && + unknownAttachments.length === 0 && + regularImages.length + userVideos.length > 0; + // A lone image keeps its own shape; a 4:3 crop hides most of a wide screenshot. + const loneImage = + mediaOnly && + userVideos.length === 0 && + regularImages.length === 1 && + regularImages[0]!.source?.kind !== "snap-shot"; + // Several images sent without words share one rounded shape, split by hairlines. + const collage = + mediaOnly && + userVideos.length === 0 && + regularImages.length > 1 && + regularImages.every((image) => image.source?.kind !== "snap-shot"); const annotationRecordIds = resolvedContext.records .filter((record) => record.kind === "preview-annotation") .map((record) => record.contextId); @@ -469,8 +492,10 @@ function UserTimelineRow({ row }: { row: Extract @@ -502,15 +527,45 @@ function UserTimelineRow({ row }: { row: Extract {(regularImages.length > 0 || userVideos.length > 0) && ( -
      - {regularImages.map((image) => ( +
      + {regularImages.map((image, index) => (
      3 && + regularImages.length % 2 === 1 && + index === regularImages.length - 1 && + "col-span-2", + ) + : "aspect-[4/3] overflow-hidden rounded-lg border border-border/80", )} > {image.previewUrl ? ( @@ -532,11 +587,23 @@ function UserTimelineRow({ row }: { row: Extract ) : ( -
      +
      {image.name}
      )} diff --git a/packages/client-runtime/src/userMessage.test.ts b/packages/client-runtime/src/userMessage.test.ts index 0447dc54d1b26..207939cf2f39d 100644 --- a/packages/client-runtime/src/userMessage.test.ts +++ b/packages/client-runtime/src/userMessage.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vite-plus/test"; import { GuestMessageId } from "@t3tools/contracts"; +import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences"; import { resolveUserMessagePresentation } from "./userMessage.ts"; @@ -21,6 +22,19 @@ describe("resolveUserMessagePresentation", () => { } }); + it("hides the prompt that stands in for an attachment-only message", () => { + for (const text of [ + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, + `Ultrathink:\n${ATTACHMENT_ONLY_BOOTSTRAP_PROMPT}`, + ]) { + expect(resolveUserMessagePresentation({ role: "user", text })).toEqual({ + text: "", + attribution: null, + scheduledTaskId: undefined, + }); + } + }); + it("shows a guest's own words and name, not the attributed text the agent reads", () => { expect( resolveUserMessagePresentation({ diff --git a/packages/client-runtime/src/userMessage.ts b/packages/client-runtime/src/userMessage.ts index d5d7c5ac08956..8a80f31b155d0 100644 --- a/packages/client-runtime/src/userMessage.ts +++ b/packages/client-runtime/src/userMessage.ts @@ -5,6 +5,7 @@ import { type OrchestrationV2IdleCompaction, ScheduledTaskId, } from "@t3tools/contracts"; +import { isAttachmentOnlyBootstrapPrompt } from "@t3tools/shared/composerContextReferences"; /** The working row while T3 Code's own compaction runs. */ export const IDLE_COMPACTING_LABELS = { @@ -68,7 +69,8 @@ export function resolveUserMessagePresentation(message: { }; } return { - text: message.text, + // The agent needs words to start a turn; people sent only the attachments. + text: isAttachmentOnlyBootstrapPrompt(message.text) ? "" : message.text, attribution: message.createdBy !== "agent" ? null diff --git a/packages/shared/src/composerContextReferences.ts b/packages/shared/src/composerContextReferences.ts index e1b25bc094a66..88361606a9a64 100644 --- a/packages/shared/src/composerContextReferences.ts +++ b/packages/shared/src/composerContextReferences.ts @@ -132,6 +132,11 @@ export function collectComposerContextReferences( export const ATTACHMENT_ONLY_BOOTSTRAP_PROMPT = "[User attached one or more files without additional text. Respond using the conversation context and the attached files.]"; +/** Claude's ultrathink effort sends the prompt as `Ultrathink:\n`. */ +export function isAttachmentOnlyBootstrapPrompt(text: string): boolean { + return text.replace(/^Ultrathink:\s*/i, "") === ATTACHMENT_ONLY_BOOTSTRAP_PROMPT; +} + export function isImageReferencesOnly(text: string): boolean { const references = collectComposerContextReferences(text); return ( diff --git a/packages/shared/src/threadFindText.test.ts b/packages/shared/src/threadFindText.test.ts index 0dd6a87ae1dea..77a0874c21336 100644 --- a/packages/shared/src/threadFindText.test.ts +++ b/packages/shared/src/threadFindText.test.ts @@ -1,6 +1,7 @@ import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts"; import { expect, it } from "vite-plus/test"; import { serializeAssistantCitation } from "./assistantCitations.ts"; +import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "./composerContextReferences.ts"; import { searchableMessageSegments } from "./threadFindText.ts"; it("excludes review attachments rendered as context chips", () => { @@ -31,6 +32,16 @@ it("excludes structured context chips without joining text across them", () => { ).toEqual(["before", "after"]); }); +it("excludes the hidden prompt of an attachment-only message", () => { + expect( + searchableMessageSegments({ + role: "user", + streaming: false, + text: ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, + }), + ).toEqual([]); +}); + it("does not upgrade literal legacy tags in messages with structured context", () => { const text = "\n- Terminal 1 line 12:\n 12 | visible output\n"; diff --git a/packages/shared/src/threadFindText.ts b/packages/shared/src/threadFindText.ts index a2e5b4dbb982d..3afec6e04729e 100644 --- a/packages/shared/src/threadFindText.ts +++ b/packages/shared/src/threadFindText.ts @@ -21,7 +21,10 @@ import { resolveMarkdownFileLinkTarget, } from "./markdownLinks.ts"; import { upgradeLegacyContextMessage } from "./composerContextLegacy.ts"; -import { parseComposerContextHref } from "./composerContextReferences.ts"; +import { + isAttachmentOnlyBootstrapPrompt, + parseComposerContextHref, +} from "./composerContextReferences.ts"; import { assistantCitationLabel, parseAssistantCitationHref } from "./assistantCitations.ts"; import type { OrchestrationV2ConversationMessage } from "@t3tools/contracts"; import { proposedPlanTitle, stripDisplayedPlanMarkdown } from "./proposedPlanText.ts"; @@ -216,6 +219,8 @@ export function searchableMessageSegments( skills: readonly InlineSkill[] = [], ): readonly string[] | null { if (message.role === "user") { + // Clients hide this prompt, so find must not match text nobody can see. + if (isAttachmentOnlyBootstrapPrompt(message.text)) return []; const text = message.context ? message.text : upgradeLegacyContextMessage(message.text).text; return markdownThreadFindText(text, true, cwd, skills); } From b42adff3d77f01f5e0f5edfb5a071dabb535710b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 29 Oct 2026 17:25:39 -0700 Subject: [PATCH 388/817] ci(mobile): production deploys use a Release Manager Expo token (#27285) Co-authored-by: Claude Opus 5.5 --- .github/workflows/mobile-eas-production.yml | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/.github/workflows/mobile-eas-production.yml b/.github/workflows/mobile-eas-production.yml index b2c03c04ab11c..507e013bf1c2a 100644 --- a/.github/workflows/mobile-eas-production.yml +++ b/.github/workflows/mobile-eas-production.yml @@ -97,13 +97,13 @@ jobs: - id: expo-token name: Check for EXPO_TOKEN env: - EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }} + EXPO_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} run: | if [ -n "$EXPO_TOKEN" ]; then echo "present=true" >> "$GITHUB_OUTPUT" else echo "present=false" >> "$GITHUB_OUTPUT" - echo "EXPO_TOKEN is not available; skipping EAS production job." + echo "EXPO_PRODUCTION_TOKEN is not available; skipping EAS production job." fi - id: version_app_token @@ -149,7 +149,7 @@ jobs: uses: expo/expo-github-action@v8 with: eas-version: latest - token: ${{ secrets.EXPO_TOKEN }} + token: ${{ secrets.EXPO_PRODUCTION_TOKEN }} # npm, not pnpm: this only installs eas-cli into the action's own # tool dir, and pnpm 11 hard-fails that install on dtrace-provider's # ignored build script (no allowBuilds config outside the repo). @@ -159,7 +159,7 @@ jobs: if: steps.expo-token.outputs.present == 'true' working-directory: apps/mobile env: - EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }} + EXPO_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} run: | eas env:pull production --non-interactive # EAS commands skip dotenv, and the Android fingerprint hashes this @@ -244,7 +244,7 @@ jobs: if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build' working-directory: apps/mobile env: - EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }} + EXPO_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} MOBILE_BUILD_PROFILE: ${{ inputs.profile || 'production' }} run: eas build --platform ${{ inputs.platform }} --profile "$MOBILE_BUILD_PROFILE" --auto-submit --non-interactive --no-wait @@ -255,7 +255,7 @@ jobs: if: steps.expo-token.outputs.present == 'true' && (github.event_name == 'push' || inputs.mode == 'update') working-directory: apps/mobile env: - EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }} + EXPO_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} PLATFORM: ${{ inputs.platform || 'all' }} run: | if [ "$PLATFORM" = "all" ]; then platforms="ios android"; else platforms="$PLATFORM"; fi @@ -275,7 +275,7 @@ jobs: if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'update' working-directory: apps/mobile env: - EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }} + EXPO_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} MOBILE_BUILD_PROFILE: ${{ inputs.profile || 'production' }} OTA_MESSAGE: ${{ inputs.message || format('Production OTA ({0})', github.sha) }} run: | @@ -299,7 +299,7 @@ jobs: if: steps.expo-token.outputs.present == 'true' && github.event_name == 'push' working-directory: apps/mobile env: - EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }} + EXPO_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} run: | failed=0 message="$(git log -1 --pretty=%s | head -c 120) ($(git rev-parse --short=9 HEAD))" From f58fad04162165653bf06f0c987bbfb0074a8a4b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 29 Oct 2026 17:37:57 -0700 Subject: [PATCH 389/817] ci(mobile): maintainers can deploy EAS previews for reviewed fork commits (#27292) Co-authored-by: Claude Opus 5.5 --- .github/workflows/mobile-eas-preview-fork.yml | 145 ++++++++++++++++++ .github/workflows/mobile-eas-preview.yml | 14 +- 2 files changed, 153 insertions(+), 6 deletions(-) create mode 100644 .github/workflows/mobile-eas-preview-fork.yml diff --git a/.github/workflows/mobile-eas-preview-fork.yml b/.github/workflows/mobile-eas-preview-fork.yml new file mode 100644 index 0000000000000..e7615d46011bd --- /dev/null +++ b/.github/workflows/mobile-eas-preview-fork.yml @@ -0,0 +1,145 @@ +name: Mobile EAS Preview (Fork) + +# EAS previews for fork PRs. This runs the PR's code with an Expo token: the +# app config and plugins run on this runner, and native builds run on EAS +# with preview signing credentials. The label is the maintainer's sign-off +# that they reviewed that code, so it covers exactly the commit it was applied +# to: this pins that commit and consumes the label before running anything. A +# later push deploys nothing until the label is applied again. +# +# Same-repo PRs deploy on every push while labeled, via mobile-eas-preview.yml. + +on: + pull_request_target: + types: [labeled] + +permissions: + contents: read + +jobs: + preview: + name: EAS Preview + if: >- + github.event.pull_request.head.repo.full_name != github.repository && + github.event.label.name == '🚀 Mobile Continuous Deployment' + runs-on: blacksmith-8vcpu-ubuntu-2404 + concurrency: + group: mobile-eas-preview-fork-${{ github.event.pull_request.number }} + cancel-in-progress: true + permissions: + contents: read + pull-requests: write + env: + APP_VARIANT: preview + NODE_OPTIONS: --max-old-space-size=8192 + MOBILE_VERSION_POLICY: fingerprint + steps: + # If a maintainer removed the label first, that removal wins. + - id: consume + name: Consume the deployment label + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8 + with: + script: | + try { + await github.rest.issues.removeLabel({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.payload.pull_request.number, + name: context.payload.label.name, + }); + core.setOutput("consumed", "true"); + } catch (error) { + if (error.status !== 404) throw error; + core.info("The label was removed before this run could consume it. Skipping."); + core.setOutput("consumed", "false"); + } + + - id: expo-token + name: Check for EXPO_PREVIEW_TOKEN + if: steps.consume.outputs.consumed == 'true' + env: + EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} + run: | + if [ -n "$EXPO_TOKEN" ]; then + echo "present=true" >> "$GITHUB_OUTPUT" + else + echo "present=false" >> "$GITHUB_OUTPUT" + echo "EXPO_PREVIEW_TOKEN is not set; skipping EAS preview." + fi + + # The head SHA from the label event, not the branch, so a push after the + # label cannot swap in unreviewed code. No credentials stay in .git for + # the PR's scripts to read. + - name: Checkout reviewed commit + if: steps.expo-token.outputs.present == 'true' + uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 0 + persist-credentials: false + # No sparse-checkout: see mobile-eas-preview.yml. + + # No caches: pull_request_target saves them under main's scope, where + # trusted workflows with other secrets would restore what PR code wrote. + - name: Setup Vite+ + if: steps.expo-token.outputs.present == 'true' + uses: voidzero-dev/setup-vp@v1 + with: + node-version-file: package.json + cache: false + run-install: | + args: + - --filter=@t3tools/mobile... + + - name: Expose pnpm + if: steps.expo-token.outputs.present == 'true' + run: | + pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")" + vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin" + echo "$vp_pnpm_bin" >> "$GITHUB_PATH" + "$vp_pnpm_bin/pnpm" --version + + - name: Setup EAS + if: steps.expo-token.outputs.present == 'true' + uses: expo/expo-github-action@v8 + with: + # Pinned and installed with npm for the same reasons as mobile-eas-preview.yml. + eas-version: 21.8.0 + eas-cache: false + token: ${{ secrets.EXPO_PREVIEW_TOKEN }} + packager: npm + + - name: Pull preview environment variables + if: steps.expo-token.outputs.present == 'true' + working-directory: apps/mobile + env: + EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} + run: | + eas env:pull preview --non-interactive + # See mobile-eas-preview.yml: keeps Android build and OTA fingerprints matching. + node --input-type=module <<'NODE' + import { appendFileSync, readFileSync } from "node:fs"; + import { parseEnv } from "node:util"; + const env = parseEnv(readFileSync(".env.local", "utf8")); + const googleServicesFile = env.T3CODE_ANDROID_GOOGLE_SERVICES_FILE; + if (googleServicesFile) { + appendFileSync(process.env.GITHUB_ENV, `T3CODE_ANDROID_GOOGLE_SERVICES_FILE=${googleServicesFile}\n`); + } + NODE + + - name: Deploy with fingerprint check + if: steps.expo-token.outputs.present == 'true' + uses: expo/expo-github-action/continuous-deploy-fingerprint@main + env: + EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} + RUNNER_DEBUG: "1" + # The action only comments for pull_request events; this hook gives + # it the PR under pull_request_target. Without it, it skips the comment. + EXPO_TEST_GITHUB_PULL: ${{ github.event.pull_request.number }} + with: + profile: preview:dev + branch: pr-${{ github.event.pull_request.number }} + platform: all + environment: preview + working-directory: apps/mobile + github-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/mobile-eas-preview.yml b/.github/workflows/mobile-eas-preview.yml index 107c741424b08..08183d0385811 100644 --- a/.github/workflows/mobile-eas-preview.yml +++ b/.github/workflows/mobile-eas-preview.yml @@ -7,7 +7,9 @@ on: jobs: preview: name: EAS Preview + # Fork PRs deploy one reviewed commit per label through mobile-eas-preview-fork.yml. if: | + github.event.pull_request.head.repo.full_name == github.repository && contains(github.event.pull_request.labels.*.name, '🚀 Mobile Continuous Deployment') && (github.event.action != 'labeled' || github.event.label.name == '🚀 Mobile Continuous Deployment') runs-on: blacksmith-8vcpu-ubuntu-2404 @@ -23,15 +25,15 @@ jobs: MOBILE_VERSION_POLICY: fingerprint steps: - id: expo-token - name: Check for EXPO_TOKEN + name: Check for EXPO_PREVIEW_TOKEN env: - EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }} + EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} run: | if [ -n "$EXPO_TOKEN" ]; then echo "present=true" >> "$GITHUB_OUTPUT" else echo "present=false" >> "$GITHUB_OUTPUT" - echo "EXPO_TOKEN is not available; skipping EAS preview." + echo "EXPO_PREVIEW_TOKEN is not available; skipping EAS preview." fi - name: Checkout @@ -70,7 +72,7 @@ jobs: # continuous-deploy-fingerprint still reads `build.project.ownerAccount`. # Unpin once https://github.com/expo/expo-github-action/issues/358 is fixed. eas-version: 21.8.0 - token: ${{ secrets.EXPO_TOKEN }} + token: ${{ secrets.EXPO_PREVIEW_TOKEN }} # npm, not pnpm: this only installs eas-cli into the action's own # tool dir, and pnpm 11 hard-fails that install on dtrace-provider's # ignored build script (no allowBuilds config outside the repo). @@ -80,7 +82,7 @@ jobs: if: steps.expo-token.outputs.present == 'true' working-directory: apps/mobile env: - EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }} + EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} run: | eas env:pull preview --non-interactive # EAS Update disables dotenv loading. Keep the downloaded native config @@ -99,7 +101,7 @@ jobs: if: steps.expo-token.outputs.present == 'true' uses: expo/expo-github-action/continuous-deploy-fingerprint@main env: - EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }} + EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} # The Expo action otherwise suppresses the EAS command's failure output. RUNNER_DEBUG: "1" with: From d7b6cf7884029b20baf5b2adbfe5271490faecf8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 29 Oct 2026 18:04:16 -0700 Subject: [PATCH 390/817] fix(server): agents yield CPU, tasks, and reclaim to the server under pressure (#27176) Co-authored-by: Claude Opus 5.5 --- apps/server/src/cloud/bootService.test.ts | 13 +++++++ apps/server/src/cloud/bootService.ts | 5 ++- apps/server/src/process/agentScope.test.ts | 28 +++++++++++++++ apps/server/src/process/agentScope.ts | 40 +++++++++++++++------- 4 files changed, 72 insertions(+), 14 deletions(-) diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts index fca51dcac1e09..5491328a3040a 100644 --- a/apps/server/src/cloud/bootService.test.ts +++ b/apps/server/src/cloud/bootService.test.ts @@ -48,6 +48,19 @@ it("reads the served T3 home back out of a rendered unit or plist", () => { expect(BootService.bootServiceBaseDirOf("[Service]\nExecStart=/x\n")).toBeUndefined(); }); +it("protects the server unit from agents under CPU and memory pressure", () => { + const unit = BootService.renderBootServiceUnit({ + program: ["/home/theo/.t3/runtime/versions/1.2.3/t3", "__service-launcher"], + baseDir: "/home/theo/.t3", + logPath: "/home/theo/.t3/userdata/logs/boot-service.log", + unitPath: "/home/theo/.config/systemd/user/t3code.service", + }); + const service = unit.slice(unit.indexOf("[Service]"), unit.indexOf("[Install]")); + for (const line of ["CPUWeight=1000", "IOWeight=1000", "MemoryLow=1536M", "OOMPolicy=continue"]) { + expect(service.split("\n")).toContain(line); + } +}); + it.each([ ["a unit", '/home/theo/T3 "Data"/100%\\x', BootService.renderBootServiceUnit], [ diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts index 15b3b16a7bc0f..5206992f2693f 100644 --- a/apps/server/src/cloud/bootService.ts +++ b/apps/server/src/cloud/bootService.ts @@ -110,9 +110,12 @@ export function renderBootServiceUnit(plan: BootServicePlan): string { "OOMPolicy=continue", "Restart=always", "RestartSec=5", - // Weights favor the server over the sibling agents slice during CPU or disk saturation. + // Weights favor the server over the sibling agents slice; IOWeight needs a delegated io controller. "CPUWeight=1000", "IOWeight=1000", + // Reclaim takes the agents' unprotected pages first. The kernel caps this at the + // protection of user.slice and user@.service, which only root can grant. + "MemoryLow=1536M", // systemd-oomd ignores this preference when the watched cgroup is root-owned, as user-1000.slice usually is. "ManagedOOMPreference=avoid", `StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`, diff --git a/apps/server/src/process/agentScope.test.ts b/apps/server/src/process/agentScope.test.ts index 94ca314ac1f33..286452a5c5781 100644 --- a/apps/server/src/process/agentScope.test.ts +++ b/apps/server/src/process/agentScope.test.ts @@ -245,6 +245,34 @@ describe("AgentScope service", () => { ), ); + it.effect("caps agent memory and yields CPU, disk, and tasks to the server", () => + withFakeSystemd(({ scope, calls }) => + Effect.gen(function* () { + yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" }); + const setProperties = calls.filter(([, verb]) => verb === "set-property"); + expect(setProperties).toEqual([ + [ + "--user", + "set-property", + "--runtime", + "app-t3code-agents.slice", + expect.stringMatching(/^MemoryHigh=\d+$/), + expect.stringMatching(/^MemoryMax=\d+$/), + ], + [ + "--user", + "set-property", + "--runtime", + "app-t3code.slice", + "CPUWeight=10", + "IOWeight=10", + "TasksMax=25%", + ], + ]); + }), + ), + ); + it.effect("stops agents a killed server left before the first launch", () => withFakeSystemd(({ scope, units, calls, stateDir }) => Effect.gen(function* () { diff --git a/apps/server/src/process/agentScope.ts b/apps/server/src/process/agentScope.ts index cc6d3a04121f6..c72e4eed88a9c 100644 --- a/apps/server/src/process/agentScope.ts +++ b/apps/server/src/process/agentScope.ts @@ -19,6 +19,12 @@ import * as ServerConfig from "../config.ts"; import * as ProcessRunner from "../processRunner.ts"; const AGENT_SLICE = "app-t3code-agents.slice"; +// Owns every agent slice and competes with the server's unit or scope under app.slice. +const AGENTS_PARENT_SLICE = "app-t3code.slice"; +// Low weights yield CPU and disk to the server under contention, where the user manager +// has those controllers: current systemd delegates cpu, rarely io. TasksMax keeps agents +// below logind's 33% per-user task limit, leaving forks for the server. +const AGENTS_PARENT_PROPERTIES = ["CPUWeight=10", "IOWeight=10", "TasksMax=25%"]; export function ownedAgentSlice(stateDir: string): string { const hash = NodeCrypto.createHash("sha256").update(stateDir).digest("hex").slice(0, 12); @@ -173,20 +179,28 @@ export const make = Effect.gen(function* () { yield* Effect.logInfo("Agent scopes are off: no systemd user manager"); return undefined; } + const setProperties = Effect.fn("agentScope.setProperties")(function* ( + slice: string, + properties: ReadonlyArray, + ) { + const result = yield* run(systemctl, [ + "--user", + "set-property", + "--runtime", + slice, + ...properties, + ]); + if (result._tag === "None" || result.value.code !== 0) { + yield* Effect.logWarning("Could not set resource limits on an agents slice", { + slice, + properties, + stderr: result._tag === "Some" ? result.value.stderr.trim() : undefined, + }); + } + }); const limits = agentSliceMemoryLimits(NodeOS.totalmem()); - const limited = yield* run(systemctl, [ - "--user", - "set-property", - "--runtime", - AGENT_SLICE, - `MemoryHigh=${limits.high}`, - `MemoryMax=${limits.max}`, - ]); - if (limited._tag === "None" || limited.value.code !== 0) { - yield* Effect.logWarning("Could not set memory limits on the agents slice", { - stderr: limited._tag === "Some" ? limited.value.stderr.trim() : undefined, - }); - } + yield* setProperties(AGENT_SLICE, [`MemoryHigh=${limits.high}`, `MemoryMax=${limits.max}`]); + yield* setProperties(AGENTS_PARENT_SLICE, AGENTS_PARENT_PROPERTIES); yield* Effect.logInfo("Agent scopes are on", { slice: AGENT_SLICE, ...limits, From 44d508fd8b44794e51d82480052f5a041640e411 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 29 Oct 2026 18:04:16 -0700 Subject: [PATCH 391/817] feat(server): `t3 service protect` keeps the server alive when agents fill memory (#27239) Co-authored-by: Claude Opus 5.5 --- apps/server/src/cli/service.test.ts | 31 ++ apps/server/src/cli/service.ts | 134 ++++++- apps/server/src/cloud/bootService.test.ts | 8 +- apps/server/src/cloud/bootService.ts | 3 + .../src/cloud/serviceProtection.test.ts | 265 ++++++++++++++ apps/server/src/cloud/serviceProtection.ts | 342 ++++++++++++++++++ apps/server/src/preview/ServerBrowser.ts | 14 + .../src/preview/ServerBrowserContexts.test.ts | 56 ++- .../src/preview/ServerBrowserContexts.ts | 40 +- docs/user/background-service.md | 18 + packages/shared/src/AgentScope.test.ts | 20 +- packages/shared/src/AgentScope.ts | 8 + 12 files changed, 919 insertions(+), 20 deletions(-) create mode 100644 apps/server/src/cloud/serviceProtection.test.ts create mode 100644 apps/server/src/cloud/serviceProtection.ts diff --git a/apps/server/src/cli/service.test.ts b/apps/server/src/cli/service.test.ts index 033a96693ada9..2ea799d9f09e4 100644 --- a/apps/server/src/cli/service.test.ts +++ b/apps/server/src/cli/service.test.ts @@ -90,6 +90,37 @@ it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("service commands }), ); + it.effect("protect refuses root before creating any T3 directories", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" }); + const baseDir = `${parent}/t3`; + vi.spyOn(BootService, "layer").mockReturnValue( + Layer.succeed(BootService.BootService, makeTestService(status).service), + ); + + const output = yield* Command.runWith(serviceCommand, { version: packageJson.version })([ + "protect", + "--base-dir", + baseDir, + ]).pipe( + Effect.andThen(TestConsole.logLines), + Effect.map((lines) => lines.join("\n")), + Effect.provideService(HostProcess.Environment, {}), + Effect.provideService(HostProcess.Platform, "linux"), + Effect.provideService(HostProcess.UserId, 0), + Effect.provide( + Layer.mergeAll( + ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })), + Layer.fresh(TestConsole.layer), + ), + ), + ); + expect(output).toContain("without sudo"); + expect(yield* fs.exists(baseDir)).toBe(false); + }), + ); + // regression: #13239 a stale nvm-installed CLI reported "already using" its own version it.effect.each(["install", "update"] as const)( "%s names the CLI that found nothing to change", diff --git a/apps/server/src/cli/service.ts b/apps/server/src/cli/service.ts index 97ceafd941f1e..62edb31d14b62 100644 --- a/apps/server/src/cli/service.ts +++ b/apps/server/src/cli/service.ts @@ -2,12 +2,14 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Console from "effect/Console"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; import * as Terminal from "effect/Terminal"; import { Command, Flag, GlobalFlag, Prompt } from "effect/cli"; import { FetchHttpClient } from "effect/http"; import packageJson from "../../package.json" with { type: "json" }; import * as BootService from "../cloud/bootService.ts"; +import * as ServiceProtection from "../cloud/serviceProtection.ts"; import { compareExactServiceVersions } from "../cloud/serviceProtocol.ts"; import type * as ServerConfig from "../config.ts"; import * as ProcessRunner from "../processRunner.ts"; @@ -68,7 +70,23 @@ function formatServiceChange( return `${result.previouslyInstalled ? "Updated" : "Installed"} T3 Code service with t3@${packageJson.version}.\nLogs: ${result.plan.logPath}`; } -function formatServiceStatus(status: BootService.BootServiceStatus, cliVersion: string): string { +function formatProtection( + protection: ServiceProtection.ServiceProtectionState | undefined, +): ReadonlyArray { + if (protection === undefined) return []; + return [ + protection.unprotected === undefined + ? ` Memory protection: on${protection.setByProtect ? " (t3 service protect)" : ""}` + : ` Memory protection: off, ${protection.unprotected} grants none. Run \`t3 service protect\`.`, + ...(protection.oomScoreAdj === undefined ? [] : [` OOM score: ${protection.oomScoreAdj}`]), + ]; +} + +function formatServiceStatus( + status: BootService.BootServiceStatus, + cliVersion: string, + protection?: ServiceProtection.ServiceProtectionState, +): string { if (!status.supported) { return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd, macOS with launchd"; } @@ -89,6 +107,7 @@ function formatServiceStatus(status: BootService.BootServiceStatus, cliVersion: ` Status: installed · t3@${installedVersion} (newer than this t3@${cliVersion} CLI)`, ` Unit: ${status.unitPath}`, ` Logs: ${status.logPath}`, + ...formatProtection(protection), ...problems, ` Next: Run \`t3 update ${installedVersion}\` to match it, or pass \`--allow-downgrade\` to \`t3 service install\` explicitly.`, ].join("\n"); @@ -98,6 +117,7 @@ function formatServiceStatus(status: BootService.BootServiceStatus, cliVersion: ` Status: ${status.current ? `installed · t3@${installedVersion}` : "needs an update or repair"}`, ` Unit: ${status.unitPath}`, ` Logs: ${status.logPath}`, + ...formatProtection(protection), ...problems, ...(status.current ? [] : [" Next: Run `t3 service install` to repair it."]), ].join("\n"); @@ -210,12 +230,121 @@ const serviceStatusCommand = Command.make("status", projectLocationFlags).pipe( flags, Effect.gen(function* () { const service = yield* BootService.BootService; - yield* Console.log(formatServiceStatus(yield* service.status, packageJson.version)); + const path = yield* Path.Path; + const status = yield* service.status; + const protection = + status.installed && (yield* HostProcess.Platform) === "linux" + ? yield* ServiceProtection.readProtection(path.dirname(status.unitPath)).pipe( + Effect.provide(ProcessRunner.layer), + ) + : undefined; + yield* Console.log(formatServiceStatus(status, packageJson.version, protection)); }), ), ), ); +const formatDropIns = (dropIns: ReadonlyArray) => + dropIns.map( + ({ path, contents }) => ` ${path}: ${contents.trimEnd().split("\n").slice(1).join(" ")}`, + ); + +const confirm = (yes: boolean, message: string) => + yes ? Effect.succeed(true) : Prompt.run(Prompt.Confirm({ message, initial: false })); + +const serviceProtectCommand = Command.make("protect", { + ...projectLocationFlags, + undo: Flag.Boolean("undo").pipe( + Flag.withDescription("Remove the protection this command set up."), + Flag.withDefault(false), + ), + yes: Flag.Boolean("yes").pipe( + Flag.withDescription("Answer yes to every question, including SSH and Tailscale."), + Flag.withDefault(false), + ), +}).pipe( + Command.withDescription( + "Protect the T3 Code server from agents under memory pressure (Linux with systemd). Asks for sudo.", + ), + Command.withHandler((flags) => + Effect.gen(function* () { + const unsupported = "Service protection needs Linux with systemd."; + if ((yield* HostProcess.Platform) !== "linux") return yield* Console.log(unsupported); + // Before resolving config, which creates T3 directories that root would then own. + if ((yield* HostProcess.UserId) === 0) { + return yield* Console.log( + "Run `t3 service protect` as the user that runs T3 Code, without sudo. It asks for sudo when it needs root.", + ); + } + return yield* runServiceCommand( + flags, + Effect.gen(function* () { + const uid = yield* HostProcess.UserId; + const remote = yield* ServiceProtection.detectRemoteAccessUnits; + const { unitPath } = yield* (yield* BootService.BootService).status; + if (uid === undefined || remote === undefined || unitPath === "") { + return yield* Console.log(unsupported); + } + const userUnitDir = (yield* Path.Path).dirname(unitPath); + + if (flags.undo) { + const installed = yield* ServiceProtection.installedProtection( + ServiceProtection.protectionPlan({ + uid, + userUnitDir, + remoteAccessUnits: ServiceProtection.REMOTE_ACCESS_UNITS, + }), + ); + if (installed === undefined) { + return yield* Console.log("T3 Code service protection is not set up."); + } + yield* Console.log( + [ + "Removes:", + ...[...installed.system, ...installed.user, installed.managerDefaults].map( + ({ path, shared }) => + ` ${path}${shared === true ? " (kept while another user is protected)" : ""}`, + ), + ].join("\n"), + ); + if (!(yield* confirm(flags.yes, "Remove T3 Code service protection?"))) return; + yield* ServiceProtection.removeProtection(installed); + return yield* Console.log( + "Removed T3 Code service protection. The server's OOM score returns to normal after `t3 service restart`.", + ); + } + + const names = remote.map((unit) => unit.replace(/\.service$/, "")).join(" and "); + const protectRemote = + remote.length > 0 && + (yield* confirm( + flags.yes, + `Also protect ${names} so you can still reach this machine under memory pressure?`, + )); + const plan = ServiceProtection.protectionPlan({ + uid, + userUnitDir, + remoteAccessUnits: protectRemote ? remote : [], + }); + yield* Console.log( + [ + "As root, through sudo:", + ...formatDropIns(plan.system), + "As you:", + ...formatDropIns([plan.managerDefaults, ...plan.user]), + ].join("\n"), + ); + if (!(yield* confirm(flags.yes, "Apply these settings?"))) return; + yield* ServiceProtection.applyProtection(plan); + yield* Console.log( + "Protected T3 Code. Memory protection applies now; the server takes its OOM score after `t3 service restart`. Undo with `t3 service protect --undo`.", + ); + }).pipe(Effect.provide(ProcessRunner.layer)), + ); + }), + ), +); + export type ServiceOnboardingOutcome = "ready" | "pending" | "skipped"; export const offerServiceDuringOnboarding = Effect.gen(function* () { @@ -305,6 +434,7 @@ export const serviceCommand = Command.make("service").pipe( serviceRestartCommand, serviceUninstallCommand, serviceStatusCommand, + serviceProtectCommand, serviceUpdateCommand, ]), ); diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts index 5491328a3040a..2edd110648013 100644 --- a/apps/server/src/cloud/bootService.test.ts +++ b/apps/server/src/cloud/bootService.test.ts @@ -56,7 +56,13 @@ it("protects the server unit from agents under CPU and memory pressure", () => { unitPath: "/home/theo/.config/systemd/user/t3code.service", }); const service = unit.slice(unit.indexOf("[Service]"), unit.indexOf("[Install]")); - for (const line of ["CPUWeight=1000", "IOWeight=1000", "MemoryLow=1536M", "OOMPolicy=continue"]) { + for (const line of [ + "CPUWeight=1000", + "IOWeight=1000", + "MemoryLow=1536M", + "OOMScoreAdjust=100", + "OOMPolicy=continue", + ]) { expect(service.split("\n")).toContain(line); } }); diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts index 5206992f2693f..948d780c867cc 100644 --- a/apps/server/src/cloud/bootService.ts +++ b/apps/server/src/cloud/bootService.ts @@ -116,6 +116,9 @@ export function renderBootServiceUnit(plan: BootServicePlan): string { // Reclaim takes the agents' unprotected pages first. The kernel caps this at the // protection of user.slice and user@.service, which only root can grant. "MemoryLow=1536M", + // A user manager's own score, the lowest it may set: below its other services (200) and agents (800). + // `t3 service protect` lowers it further through a drop-in. + "OOMScoreAdjust=100", // systemd-oomd ignores this preference when the watched cgroup is root-owned, as user-1000.slice usually is. "ManagedOOMPreference=avoid", `StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`, diff --git a/apps/server/src/cloud/serviceProtection.test.ts b/apps/server/src/cloud/serviceProtection.test.ts new file mode 100644 index 0000000000000..b2e4a1506cb31 --- /dev/null +++ b/apps/server/src/cloud/serviceProtection.test.ts @@ -0,0 +1,265 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { describe, expect, it } from "@effect/vitest"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Sink from "effect/Sink"; +import * as Stream from "effect/Stream"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; + +import * as ProcessRunner from "../processRunner.ts"; +import * as ServiceProtection from "./serviceProtection.ts"; + +const temporaryDirectory = () => + NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-service-protection-")); + +describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("renderPrivilegedScript", () => { + it("writes and removes only its drop-ins and gives running main processes their score", () => { + const root = temporaryDirectory(); + const target = NodeChildProcess.spawn("sleep", ["60"], { stdio: "ignore" }); + try { + const systemUnitDir = NodePath.join(root, "system"); + const plan = (uid: number, remoteAccessUnits: ReadonlyArray) => + ServiceProtection.protectionPlan({ + uid, + userUnitDir: "/home/theo/.config/systemd/user", + remoteAccessUnits, + systemUnitDir, + }); + const theo = plan(1000, ["tailscaled.service", "ssh.service"]); + expect(theo.system.find((dropIn) => dropIn.unit === "user@1000.service")?.contents).toBe( + "[Service]\nMemoryLow=2G\nOOMScoreAdjust=-900\n", + ); + expect(theo.managerDefaults.path).toBe( + "/home/theo/.config/systemd/user.conf.d/90-t3code-protect.conf", + ); + expect(theo.oomUnits).toEqual(["user@1000.service", "tailscaled.service", "ssh.service"]); + + const unrelated = NodePath.join(systemUnitDir, "ssh.service.d", "50-admin.conf"); + NodeFS.mkdirSync(NodePath.dirname(unrelated), { recursive: true }); + NodeFS.writeFileSync(unrelated, "[Service]\nNice=1\n"); + const bin = NodePath.join(root, "bin"); + NodeFS.mkdirSync(bin); + // Raising a score needs no privilege, so the test's own child stands in for a main process. + NodeFS.writeFileSync( + NodePath.join(bin, "systemctl"), + [ + "#!/bin/sh", + 'echo "$*" >>"$CALLS"', + 'case "$*" in', + ' *MainPID*) echo "$TARGET_PID" ;;', + " *OOMScoreAdjust*) echo 900 ;;", + "esac", + "", + ].join("\n"), + { mode: 0o755 }, + ); + const calls = NodePath.join(root, "calls"); + const runScript = (protection: ServiceProtection.ProtectionPlan, mode: "apply" | "undo") => { + const result = NodeChildProcess.spawnSync( + "/bin/sh", + ["-c", ServiceProtection.renderPrivilegedScript(protection, mode)], + { + encoding: "utf8", + env: { + PATH: `${bin}:/usr/bin:/bin`, + CALLS: calls, + TARGET_PID: String(target.pid), + }, + }, + ); + expect(result.stderr).toBe(""); + expect(result.status).toBe(0); + }; + const exists = (unit: string) => + NodeFS.existsSync(NodePath.join(systemUnitDir, `${unit}.d`, "90-t3code-protect.conf")); + + runScript(theo, "apply"); + runScript(plan(1001, []), "apply"); + for (const { path, contents } of theo.system) { + expect(NodeFS.readFileSync(path, "utf8")).toBe(contents); + } + expect(NodeFS.readFileSync(`/proc/${target.pid}/oom_score_adj`, "utf8").trim()).toBe("900"); + expect(NodeFS.readFileSync(calls, "utf8").split("\n")[0]).toBe("daemon-reload"); + + // Undo removes every drop-in a user could own, and keeps shared ones while another user is protected. + const undo = (uid: number) => plan(uid, ServiceProtection.REMOTE_ACCESS_UNITS); + runScript(undo(1000), "undo"); + expect(["user-1000.slice", "user@1000.service"].some(exists)).toBe(false); + expect( + ["user.slice", "system.slice", "tailscaled.service", "ssh.service"].every(exists), + ).toBe(true); + + runScript(undo(1001), "undo"); + for (const { path } of undo(1001).system) expect(NodeFS.existsSync(path)).toBe(false); + expect(NodeFS.existsSync(NodePath.join(systemUnitDir, "user.slice.d"))).toBe(false); + expect(NodeFS.readFileSync(unrelated, "utf8")).toBe("[Service]\nNice=1\n"); + } finally { + target.kill(); + NodeFS.rmSync(root, { recursive: true, force: true }); + } + }); +}); + +it.each([ + [ + "Debian, where sshd.service aliases ssh.service", + "Id=tailscaled.service\nLoadState=loaded\n\nId=ssh.service\nLoadState=loaded\n\nId=ssh.service\nLoadState=loaded\n", + ["tailscaled.service", "ssh.service"], + ], + [ + "Fedora without Tailscale", + "Id=tailscaled.service\nLoadState=not-found\n\nId=ssh.service\nLoadState=not-found\n\nId=sshd.service\nLoadState=loaded\n", + ["sshd.service"], + ], +])("finds remote-access services on %s", (_, shown, expected) => { + expect(ServiceProtection.loadedRemoteAccessUnits(shown)).toEqual(expected); +}); + +const fakeSudo = (exitCode: number, onRun: () => void) => + ChildProcessSpawner.make((command) => + Effect.gen(function* () { + if (command._tag !== "StandardCommand" || command.command !== "sudo") { + return yield* Effect.die("Unexpected command"); + } + onRun(); + return ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(123), + stdout: Stream.empty, + stderr: Stream.empty, + all: Stream.empty, + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + stdin: Sink.drain, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }); + }), + ); + +const runner = (stdout: string) => + ProcessRunner.ProcessRunner.of({ + run: () => + Effect.succeed({ + stdout, + stderr: "", + code: ChildProcessSpawner.ExitCode(0), + timedOut: false, + stdoutTruncated: false, + stderrTruncated: false, + stdoutInvalidUtf8: false, + stderrInvalidUtf8: false, + }), + }); + +it.effect("lowers no score before the manager default is in place, and undoes in reverse", () => { + const home = temporaryDirectory(); + return Effect.gen(function* () { + const plan = ServiceProtection.protectionPlan({ + uid: 1000, + userUnitDir: NodePath.join(home, ".config", "systemd", "user"), + remoteAccessUnits: [], + systemUnitDir: NodePath.join(home, "system"), + }); + const managerDropIn = plan.system.find(({ unit }) => unit === "user@1000.service")!.path; + const present = () => ({ + managerDefaults: NodeFS.existsSync(plan.managerDefaults.path), + user: plan.user.filter(({ path }) => NodeFS.existsSync(path)).length, + }); + const withSudo = ( + effect: Effect.Effect, + exitCode: number, + writesManagerDropIn = false, + ) => { + let atSudo: ReturnType | undefined; + return effect.pipe( + Effect.provideService( + ChildProcessSpawner.ChildProcessSpawner, + fakeSudo(exitCode, () => { + atSudo = present(); + if (writesManagerDropIn) { + NodeFS.mkdirSync(NodePath.dirname(managerDropIn), { recursive: true }); + NodeFS.writeFileSync(managerDropIn, "[Service]\nOOMScoreAdjust=-900\n"); + } + }), + ), + Effect.exit, + Effect.map((exit) => ({ exit, atSudo })), + ); + }; + const refused = yield* withSudo(ServiceProtection.applyProtection(plan), 1); + expect(refused.exit._tag).toBe("Failure"); + expect(refused.atSudo).toEqual({ managerDefaults: true, user: 0 }); + expect(present()).toEqual({ managerDefaults: false, user: 0 }); + + // Failing after it lowered the manager, sudo must leave the manager default in place. + const partial = yield* withSudo(ServiceProtection.applyProtection(plan), 1, true); + expect(partial.exit._tag).toBe("Failure"); + expect(present()).toEqual({ managerDefaults: true, user: 0 }); + NodeFS.rmSync(plan.managerDefaults.path); + NodeFS.rmSync(managerDropIn); + + const applied = yield* withSudo(ServiceProtection.applyProtection(plan), 0); + expect(applied.atSudo).toEqual({ managerDefaults: true, user: 0 }); + expect(present()).toEqual({ managerDefaults: true, user: plan.user.length }); + + const removed = yield* withSudo(ServiceProtection.removeProtection(plan), 0); + expect(removed.atSudo).toEqual({ managerDefaults: true, user: 0 }); + expect(present()).toEqual({ managerDefaults: false, user: 0 }); + }).pipe( + Effect.ensuring(Effect.sync(() => NodeFS.rmSync(home, { recursive: true, force: true }))), + Effect.provideService(ProcessRunner.ProcessRunner, runner("")), + Effect.provide(NodeServices.layer), + ); +}); + +it.effect("counts memory.min as protection and names the first cgroup that grants none", () => { + const root = temporaryDirectory(); + const controlGroup = [ + "user.slice", + "user-1000.slice", + "user@1000.service", + "app.slice", + "t3code.service", + ]; + const write = (depth: number, file: string, value: string) => { + const directory = NodePath.join(root, ...controlGroup.slice(0, depth)); + NodeFS.mkdirSync(directory, { recursive: true }); + NodeFS.writeFileSync(NodePath.join(directory, file), `${value}\n`); + }; + write(1, "memory.low", "0"); + write(1, "memory.min", "805306368"); + write(2, "memory.low", "2147483648"); + write(3, "memory.low", "2147483648"); + write(4, "memory.low", "0"); + write(4, "memory.min", "0"); + write(5, "memory.low", "1610612736"); + return Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const read = ServiceProtection.readProtection("/home/theo/.config/systemd/user").pipe( + Effect.provideService(FileSystem.FileSystem, { + ...fs, + readFileString: (path, encoding) => + fs.readFileString(path.replace("/sys/fs/cgroup", root), encoding), + }), + ); + expect((yield* read)?.unprotected).toBe("app.slice"); + write(4, "memory.low", "1610612736"); + expect((yield* read)?.unprotected).toBeUndefined(); + }).pipe( + Effect.ensuring(Effect.sync(() => NodeFS.rmSync(root, { recursive: true, force: true }))), + Effect.provideService( + ProcessRunner.ProcessRunner, + runner(`ControlGroup=/${controlGroup.join("/")}\nMainPID=0\n`), + ), + Effect.provide(NodeServices.layer), + ); +}); diff --git a/apps/server/src/cloud/serviceProtection.ts b/apps/server/src/cloud/serviceProtection.ts new file mode 100644 index 0000000000000..b23cd36e3a545 --- /dev/null +++ b/apps/server/src/cloud/serviceProtection.ts @@ -0,0 +1,342 @@ +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import * as ChildProcess from "effect/process/ChildProcess"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; + +import * as ProcessRunner from "../processRunner.ts"; +import { BOOT_SERVICE_UNIT_FILE } from "./bootService.ts"; + +const PROTECT_DROP_IN = "90-t3code-protect.conf"; +const SYSTEM_UNIT_DIR = "/etc/systemd/system"; +export const REMOTE_ACCESS_UNITS = ["tailscaled.service", "ssh.service", "sshd.service"]; + +// Covers app.slice (the server's 1536M) and init.scope (the user manager's 256M). +const USER_CHAIN_LOW = "MemoryLow=2G"; +// Near the floor, but unlike -1000 the kernel can still kill it as a last resort. +const PROTECTED_OOM_SCORE = "OOMScoreAdjust=-900"; + +export interface DropIn { + readonly unit: string; + readonly path: string; + readonly contents: string; + /** Host-wide, so undo keeps it while another user's protection remains. */ + readonly shared?: boolean; +} + +export interface ProtectionPlan { + readonly systemUnitDir: string; + /** Written through sudo. */ + readonly system: ReadonlyArray; + /** + * Written before the manager's own score drops. Unset, a user manager hands + * its services its own score plus 100: -800 once it runs at -900. + */ + readonly managerDefaults: DropIn; + readonly user: ReadonlyArray; + /** System units whose running main process takes its configured OOM score at once. */ + readonly oomUnits: ReadonlyArray; +} + +const dropIn = ( + directory: string, + unit: string, + section: string, + properties: ReadonlyArray, + shared = false, +): DropIn => ({ + unit, + path: `${directory}/${unit}.d/${PROTECT_DROP_IN}`, + contents: [`[${section}]`, ...properties, ""].join("\n"), + ...(shared ? { shared } : {}), +}); + +/** + * Memory protection only reaches the server when every ancestor cgroup grants + * it, and only root can grant it on user.slice and the user manager. + */ +export function protectionPlan(input: { + readonly uid: number; + readonly userUnitDir: string; + readonly remoteAccessUnits: ReadonlyArray; + readonly systemUnitDir?: string; +}): ProtectionPlan { + const manager = `user@${input.uid}.service`; + const remote = input.remoteAccessUnits; + const systemUnitDir = input.systemUnitDir ?? SYSTEM_UNIT_DIR; + const system = (unit: string, section: string, properties: ReadonlyArray) => + dropIn(systemUnitDir, unit, section, properties); + const shared = (unit: string, section: string, properties: ReadonlyArray) => + dropIn(systemUnitDir, unit, section, properties, true); + const user = (unit: string, section: string, properties: ReadonlyArray) => + dropIn(input.userUnitDir, unit, section, properties); + return { + systemUnitDir, + system: [ + shared("user.slice", "Slice", [USER_CHAIN_LOW]), + system(`user-${input.uid}.slice`, "Slice", [USER_CHAIN_LOW]), + system(manager, "Service", [USER_CHAIN_LOW, PROTECTED_OOM_SCORE]), + ...(remote.length > 0 ? [shared("system.slice", "Slice", ["MemoryLow=512M"])] : []), + ...remote.map((unit) => shared(unit, "Service", ["MemoryLow=256M", PROTECTED_OOM_SCORE])), + ], + managerDefaults: { + unit: "user.conf", + path: `${input.userUnitDir.replace(/\/user$/, "")}/user.conf.d/${PROTECT_DROP_IN}`, + contents: "[Manager]\nDefaultOOMScoreAdjust=200\n", + }, + user: [ + user("app.slice", "Slice", ["MemoryLow=1536M"]), + user("init.scope", "Scope", ["MemoryLow=256M"]), + user(BOOT_SERVICE_UNIT_FILE, "Service", [PROTECTED_OOM_SCORE]), + ], + oomUnits: [manager, ...remote], + }; +} + +const quoteShell = (value: string) => `'${value.replaceAll("'", `'\\''`)}'`; +const directoryOf = (file: string) => file.slice(0, file.lastIndexOf("/")); + +export function renderPrivilegedScript(plan: ProtectionPlan, mode: "apply" | "undo"): string { + const lines = ["set -e"]; + const remove = (dropIns: ReadonlyArray, indent = "") => { + for (const { path } of dropIns) { + lines.push( + `${indent}rm -f ${quoteShell(path)}`, + `${indent}rmdir ${quoteShell(directoryOf(path))} 2>/dev/null || true`, + ); + } + }; + if (mode === "apply") { + for (const { path, contents } of plan.system) { + lines.push( + `mkdir -p ${quoteShell(directoryOf(path))}`, + `cat >${quoteShell(path)} <<'T3CODE_PROTECT'`, + contents.trimEnd(), + "T3CODE_PROTECT", + ); + } + } else { + remove(plan.system.filter((dropIn) => dropIn.shared !== true)); + const otherUsers = `${quoteShell(plan.systemUnitDir)}/user@*.service.d/${PROTECT_DROP_IN}`; + lines.push(`set -- ${otherUsers}`, 'if [ ! -e "$1" ]; then'); + remove( + plan.system.filter((dropIn) => dropIn.shared === true), + " ", + ); + lines.push("fi"); + } + lines.push( + "systemctl daemon-reload", + // OOMScoreAdjust applies at exec; this gives running main processes the configured score. + `for unit in ${plan.oomUnits.map(quoteShell).join(" ")}; do`, + ' pid=$(systemctl show --property=MainPID --value "$unit")', + ' if [ "${pid:-0}" -gt 0 ]; then', + ' systemctl show --property=OOMScoreAdjust --value "$unit" >"/proc/$pid/oom_score_adj" || true', + " fi", + "done", + "", + ); + return lines.join("\n"); +} + +export class ServiceProtectionError extends Schema.TaggedError()( + "ServiceProtectionError", + { + step: Schema.String, + exitCode: Schema.optional(Schema.Number), + cause: Schema.optional(Schema.Defect()), + }, +) { + override get message(): string { + return this.exitCode === undefined + ? `Could not ${this.step}.` + : `Could not ${this.step} (exit code ${this.exitCode}).`; + } +} + +function parseUnits(text: string): Array> { + return text + .split(/\n\s*\n/) + .map( + (block) => + new Map( + block + .split("\n") + .filter((line) => line.includes("=")) + .map((line) => [line.slice(0, line.indexOf("=")), line.slice(line.indexOf("=") + 1)]), + ), + ) + .filter((values) => values.size > 0); +} + +/** Loaded remote-access units by canonical name, so an alias such as sshd.service counts once. */ +export function loadedRemoteAccessUnits(systemctlShow: string): ReadonlyArray { + const units = parseUnits(systemctlShow) + .filter((values) => values.get("LoadState") === "loaded") + .map((values) => values.get("Id") ?? "") + .filter((id) => REMOTE_ACCESS_UNITS.includes(id)); + return [...new Set(units)]; +} + +const run = Effect.fn("ServiceProtection.run")(function* ( + step: string, + command: string, + args: ReadonlyArray, +) { + const runner = yield* ProcessRunner.ProcessRunner; + const result = yield* runner + .run({ command, args, timeout: "30 seconds" }) + .pipe(Effect.mapError((cause) => new ServiceProtectionError({ step, cause }))); + if (result.code !== 0) { + return yield* new ServiceProtectionError({ step, exitCode: Number(result.code) }); + } + return result.stdout; +}); + +const userSettingsError = (cause: unknown) => + new ServiceProtectionError({ step: "change systemd user settings", cause }); + +/** Undefined when there is no systemd system manager to ask. */ +export const detectRemoteAccessUnits = run("list remote-access services", "systemctl", [ + "show", + "--property=Id,LoadState", + ...REMOTE_ACCESS_UNITS, +]).pipe( + Effect.map(loadedRemoteAccessUnits), + Effect.option, + Effect.map(Option.getOrUndefined), + Effect.withSpan("ServiceProtection.detectRemoteAccessUnits"), +); + +const reloadUserManager = run("reload systemd user units", "systemctl", [ + "--user", + "daemon-reload", +]); + +const writeDropIns = Effect.fn("ServiceProtection.writeDropIns")(function* ( + dropIns: ReadonlyArray, +) { + const fs = yield* FileSystem.FileSystem; + for (const { path, contents } of dropIns) { + yield* fs.makeDirectory(directoryOf(path), { recursive: true }); + yield* fs.writeFileString(path, contents); + } +}, Effect.mapError(userSettingsError)); + +const removeDropIns = Effect.fn("ServiceProtection.removeDropIns")(function* ( + dropIns: ReadonlyArray, +) { + const fs = yield* FileSystem.FileSystem; + for (const { path } of dropIns) { + yield* fs.remove(path, { force: true }); + yield* fs.remove(directoryOf(path)).pipe(Effect.ignore); + } +}, Effect.mapError(userSettingsError)); + +const runPrivileged = Effect.fn("ServiceProtection.runPrivileged")(function* (script: string) { + const step = "change the system's service settings"; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const exitCode = yield* spawner + .exitCode( + ChildProcess.make("sudo", ["/bin/sh", "-c", script], { + stdin: "inherit", + stdout: "inherit", + stderr: "inherit", + }), + ) + .pipe(Effect.mapError((cause) => new ServiceProtectionError({ step, cause }))); + if (exitCode !== 0) { + return yield* new ServiceProtectionError({ step, exitCode: Number(exitCode) }); + } +}); + +export const applyProtection = Effect.fn("ServiceProtection.apply")(function* ( + plan: ProtectionPlan, +) { + const fs = yield* FileSystem.FileSystem; + const hadManagerDefaults = yield* fs + .exists(plan.managerDefaults.path) + .pipe(Effect.orElseSucceed(() => false)); + yield* writeDropIns([plan.managerDefaults]); + // A partial run may already have lowered the manager; its default must then stay. + const manager = plan.system.find(({ unit }) => unit.startsWith("user@")); + const rollBack = Effect.gen(function* () { + if (hadManagerDefaults) return; + if (manager !== undefined && (yield* fs.exists(manager.path))) return; + yield* removeDropIns([plan.managerDefaults]); + }).pipe(Effect.ignore); + yield* runPrivileged(renderPrivilegedScript(plan, "apply")).pipe(Effect.tapError(() => rollBack)); + yield* writeDropIns(plan.user); + yield* reloadUserManager; +}); + +export const removeProtection = Effect.fn("ServiceProtection.remove")(function* ( + plan: ProtectionPlan, +) { + yield* removeDropIns(plan.user); + yield* reloadUserManager; + if (plan.system.length > 0) yield* runPrivileged(renderPrivilegedScript(plan, "undo")); + yield* removeDropIns([plan.managerDefaults]); + yield* reloadUserManager; +}); + +/** The plan narrowed to drop-ins that exist, for undo. */ +export const installedProtection = Effect.fn("ServiceProtection.installed")(function* ( + plan: ProtectionPlan, +) { + const fs = yield* FileSystem.FileSystem; + const exists = (dropIn: DropIn) => fs.exists(dropIn.path).pipe(Effect.orElseSucceed(() => false)); + const system = yield* Effect.filter(plan.system, exists); + const user = yield* Effect.filter(plan.user, exists); + const managerDefaults = yield* exists(plan.managerDefaults); + return system.length + user.length === 0 && !managerDefaults + ? undefined + : { ...plan, system, user }; +}); + +export interface ServiceProtectionState { + /** The first cgroup from the top that grants the server no memory protection. */ + readonly unprotected: string | undefined; + readonly oomScoreAdj: number | undefined; + readonly setByProtect: boolean; +} + +/** Reads what the kernel applies to the running service, whoever configured it. */ +export const readProtection = Effect.fn("ServiceProtection.read")(function* (userUnitDir: string) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const shown = yield* run("read the service's cgroup", "systemctl", [ + "--user", + "show", + BOOT_SERVICE_UNIT_FILE, + "--property=ControlGroup,MainPID", + ]).pipe(Effect.option); + if (Option.isNone(shown)) return undefined; + const values = parseUnits(shown.value)[0] ?? new Map(); + const controlGroup = (values.get("ControlGroup") ?? "").split("/").filter(Boolean); + if (controlGroup.length === 0) return undefined; + const read = (file: string) => + fs.readFileString(file).pipe( + Effect.map((text) => text.trim()), + Effect.orElseSucceed(() => ""), + ); + let unprotected: string | undefined; + const grants = (value: string) => value !== "" && value !== "0"; + for (let depth = 1; depth <= controlGroup.length && unprotected === undefined; depth++) { + const directory = path.join("/sys/fs/cgroup", ...controlGroup.slice(0, depth)); + const low = yield* read(path.join(directory, "memory.low")); + const min = yield* read(path.join(directory, "memory.min")); + if (!grants(low) && !grants(min)) unprotected = controlGroup[depth - 1]; + } + const pid = Number(values.get("MainPID") ?? 0); + const score = pid > 0 ? yield* read(`/proc/${pid}/oom_score_adj`) : ""; + return { + unprotected, + oomScoreAdj: score === "" ? undefined : Number(score), + setByProtect: yield* fs + .exists(path.join(userUnitDir, `${BOOT_SERVICE_UNIT_FILE}.d`, PROTECT_DROP_IN)) + .pipe(Effect.orElseSucceed(() => false)), + } satisfies ServiceProtectionState; +}); diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts index 78097b761cb74..6f3e86a7501ea 100644 --- a/apps/server/src/preview/ServerBrowser.ts +++ b/apps/server/src/preview/ServerBrowser.ts @@ -43,6 +43,7 @@ import { SERVER_BROWSER_AUTOMATION_CLIENT_ID, type PreviewAppearancePreference, } from "@t3tools/contracts"; +import { AgentScope, agentScopeLauncherScript } from "@t3tools/shared/AgentScope"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { normalizePreviewUrl } from "@t3tools/shared/preview"; import { resolvePreviewViewport } from "@t3tools/shared/previewViewport"; @@ -460,6 +461,8 @@ const make = Effect.gen(function* () { const runPromise = Effect.runPromiseWith(yield* Effect.context()); const launchServices = yield* Effect.context(); const setupCommand = yield* resolveRootCliCommand(PreviewBrowserHost.SETUP_SUBCOMMAND); + const agentScope = yield* AgentScope; + const launchersDir = NodePath.join(config.stateDir, "server-browser", "launchers"); const tabs = new Map(); const pendingTabs = new Map>(); @@ -473,6 +476,17 @@ const make = Effect.gen(function* () { const contexts = new ServerBrowserContexts({ profilesDir: NodePath.join(config.stateDir, "server-browser", "profiles"), executable: () => runPromise(previewBrowser.executable), + // An agent scope keeps Chrome out of the server's memory protection and OOM score. + launcher: async (executable) => { + const launch = await runPromise( + agentScope.wrap({ command: executable, args: [], name: "preview-browser" }), + ); + if (launch.command === executable) return undefined; + await NodeFSP.mkdir(launchersDir, { recursive: true }); + const launcher = NodePath.join(launchersDir, NodeCrypto.randomUUID()); + await NodeFSP.writeFile(launcher, agentScopeLauncherScript(launch), { mode: 0o700 }); + return { path: launcher, release: () => NodeFSP.rm(launcher, { force: true }) }; + }, // Playwright's launch error drops Chrome's own output; its sandbox note survives. diagnose: (executable, cause) => Effect.runPromiseWith(launchServices)( diff --git a/apps/server/src/preview/ServerBrowserContexts.test.ts b/apps/server/src/preview/ServerBrowserContexts.test.ts index 7a3babd0dcc0a..3cab864de54f2 100644 --- a/apps/server/src/preview/ServerBrowserContexts.test.ts +++ b/apps/server/src/preview/ServerBrowserContexts.test.ts @@ -55,6 +55,17 @@ const options = () => ({ env: {}, }); +const withLauncher = () => { + const release = vi.fn(async () => {}); + return { + release, + configuration: { + ...options(), + launcher: vi.fn(async (executable: string) => ({ path: `${executable}-launcher`, release })), + }, + }; +}; + beforeEach(() => { launches.launch.mockReset(); launches.persistent.mockReset(); @@ -66,19 +77,29 @@ describe("ServerBrowserContexts", () => { it("lazily shares one browser across concurrent isolated sessions and reuses each context", async () => { const browser = makeBrowser(); const launch = Promise.withResolvers(); - launches.launch.mockReturnValue(launch.promise); - const configuration = options(); + const started = Promise.withResolvers(); + launches.launch.mockImplementation(() => { + started.resolve(); + return launch.promise; + }); + const { configuration, release } = withLauncher(); const pool = new ServerBrowserContexts(configuration); expect(configuration.executable).not.toHaveBeenCalled(); const first = pool.contextFor("default", "agent-a"); const again = pool.contextFor("default", "agent-a"); const second = pool.contextFor("default", "agent-b"); const incognito = pool.contextFor(INCOGNITO_BROWSER_PROFILE_ID); + await started.promise; + // Playwright may retry the same path until the launch settles. + expect(release).not.toHaveBeenCalled(); launch.resolve(browser as unknown as Browser); const [a, reused, b, privateContext] = await Promise.all([first, again, second, incognito]); + expect(release).toHaveBeenCalledTimes(1); expect(a).toBe(reused); expect(new Set([a, b, privateContext]).size).toBe(3); - expect(launches.launch).toHaveBeenCalledTimes(1); + expect(launches.launch).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ executablePath: "/test/chromium-launcher" }), + ); expect(launches.persistent).not.toHaveBeenCalled(); expect(browser.newContext).toHaveBeenCalledWith({ viewport: { width: 1280, height: 800 }, @@ -94,19 +115,44 @@ describe("ServerBrowserContexts", () => { const browser = makeBrowser(); launches.persistent.mockResolvedValue(human as unknown as BrowserContext); launches.launch.mockResolvedValue(browser as unknown as Browser); - const pool = new ServerBrowserContexts(options()); + const { configuration, release } = withLauncher(); + const pool = new ServerBrowserContexts(configuration); const persistent = await pool.contextFor("work/team"); expect(await pool.contextFor("work/team")).toBe(persistent); expect(await pool.contextFor("work/team", "agent")).not.toBe(persistent); expect(launches.persistent).toHaveBeenCalledExactlyOnceWith( "/test/profiles/work%2Fteam", - expect.objectContaining({ chromiumSandbox: true, executablePath: "/test/chromium" }), + expect.objectContaining({ chromiumSandbox: true, executablePath: "/test/chromium-launcher" }), ); + expect(release).toHaveBeenCalledTimes(2); expect(launches.mkdir).toHaveBeenCalledWith("/test/profiles/work%2Fteam", { recursive: true }); await pool.close(); expect(human.close).toHaveBeenCalledTimes(1); }); + it("diagnoses a launcher failure against the real executable", async () => { + const diagnosed = new Error("diagnosed"); + const diagnose = vi.fn(async () => diagnosed); + const pool = new ServerBrowserContexts({ + ...options(), + diagnose, + launcher: vi.fn(async () => { + throw new Error("EACCES"); + }), + }); + await expect(pool.contextFor("default", "agent")).rejects.toBe(diagnosed); + expect(diagnose).toHaveBeenCalledExactlyOnceWith("/test/chromium", expect.any(Error)); + expect(launches.launch).not.toHaveBeenCalled(); + }); + + it("creates no launcher for a profile whose storage cannot be created", async () => { + launches.mkdir.mockRejectedValueOnce(new Error("EACCES")); + const { configuration } = withLauncher(); + const pool = new ServerBrowserContexts(configuration); + await expect(pool.contextFor("work/team")).rejects.toThrow("EACCES"); + expect(configuration.launcher).not.toHaveBeenCalled(); + }); + it("clears a profile by closing its open context before deleting its storage", async () => { const human = makeContext(); const browser = makeBrowser(); diff --git a/apps/server/src/preview/ServerBrowserContexts.ts b/apps/server/src/preview/ServerBrowserContexts.ts index 0e0f71d4e53ca..9f3fd48430752 100644 --- a/apps/server/src/preview/ServerBrowserContexts.ts +++ b/apps/server/src/preview/ServerBrowserContexts.ts @@ -17,6 +17,13 @@ const loadPlaywright = () => interface Options { readonly profilesDir: string; readonly executable: () => Promise; + /** + * A path that starts `executable`, such as one that moves Chrome out of the server's cgroup. + * Released after the whole launch call, since Playwright retries the same path after a glibc race. + */ + readonly launcher?: ( + executable: string, + ) => Promise<{ readonly path: string; readonly release: () => Promise } | undefined>; readonly diagnose?: (executable: string, cause: unknown) => Promise; readonly env?: NodeJS.ProcessEnv; readonly onContextClose?: (context: BrowserContext) => void; @@ -79,10 +86,10 @@ export class ServerBrowserContexts { } private async launchOptions() { - const executablePath = await this.options.executable(); + const executable = await this.options.executable(); const env = this.options.env ?? process.env; return { - executablePath, + executable, env, args: [ "--disable-gpu", @@ -96,19 +103,26 @@ export class ServerBrowserContexts { }; } - private async launch
      (options: { readonly executablePath: string }, start: () => Promise) { + private async launch(executable: string, start: (executablePath: string) => Promise) { + let release: (() => Promise) | undefined; try { - return await start(); + const launcher = await this.options.launcher?.(executable); + release = launcher?.release; + return await start(launcher?.path ?? executable); } catch (cause) { - throw (await this.options.diagnose?.(options.executablePath, cause)) ?? cause; + throw (await this.options.diagnose?.(executable, cause)) ?? cause; + } finally { + await release?.().catch(constVoid); } } private sharedBrowser() { if (!this.browser) { - const launched = this.launchOptions().then(async (options) => { + const launched = this.launchOptions().then(async ({ executable, ...options }) => { const { chromium } = loadPlaywright(); - const browser = await this.launch(options, () => chromium.launch(options)); + const browser = await this.launch(executable, (executablePath) => + chromium.launch({ ...options, executablePath }), + ); browser.on("disconnected", () => { if (this.browser === launched) this.browser = undefined; }); @@ -156,11 +170,15 @@ export class ServerBrowserContexts { return browser.newContext(contextOptions); } const directory = this.profileDirectory(profileId); - const options = await this.launchOptions(); - const { chromium } = loadPlaywright(); await NodeFSP.mkdir(directory, { recursive: true }); - return this.launch(options, () => - chromium.launchPersistentContext(directory, { ...options, ...contextOptions }), + const { executable, ...options } = await this.launchOptions(); + const { chromium } = loadPlaywright(); + return this.launch(executable, (executablePath) => + chromium.launchPersistentContext(directory, { + ...options, + ...contextOptions, + executablePath, + }), ); } diff --git a/docs/user/background-service.md b/docs/user/background-service.md index be4ad66ff3ab4..f9ab85fcac4c3 100644 --- a/docs/user/background-service.md +++ b/docs/user/background-service.md @@ -90,6 +90,24 @@ Windows background services are not supported. T3 Connect can offer service installation during setup, but the two are managed separately. Signing out of T3 Connect does not stop or uninstall the service. +## Keep the server responsive when agents use all memory + +On Linux, agents already run with lower priority than the server. When they +fill the machine's memory, though, the kernel may still slow down or stop the +server, because only an administrator can reserve memory for it. Run, as your +normal user: + +```sh +t3 service protect +``` + +It shows the system settings it will change, asks before applying them, and +then asks for your sudo password. If the machine runs Tailscale or SSH, it +also offers to protect them, so you can still reach the machine. Memory +protection takes effect at once. The server's protection from the kernel's +out-of-memory killer takes effect after `t3 service restart`. `t3 service status` reports whether +the protection is in place, and `t3 service protect --undo` removes it. + ## Troubleshooting Start with `t3 service status` on the host. It prints the log path and, on Linux, diff --git a/packages/shared/src/AgentScope.test.ts b/packages/shared/src/AgentScope.test.ts index cf3ca64acce0a..2d9aca5ac1129 100644 --- a/packages/shared/src/AgentScope.test.ts +++ b/packages/shared/src/AgentScope.test.ts @@ -1,9 +1,12 @@ // @effect-diagnostics nodeBuiltinImport:off import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; import { describe, expect, it } from "@effect/vitest"; -import { AGENT_OOM_SCORE_ADJ, agentScopeCommand } from "./AgentScope.ts"; +import { AGENT_OOM_SCORE_ADJ, agentScopeCommand, agentScopeLauncherScript } from "./AgentScope.ts"; import * as HostProcess from "./HostProcess.ts"; describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("agentScopeCommand", () => { @@ -25,5 +28,20 @@ describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("agentScopeComm expect(Number(pid)).toBe(child.pid); expect(Number(score)).toBe(AGENT_OOM_SCORE_ADJ); expect(args).toEqual(["a b", "$HOME"]); + + const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-agent-launcher-")); + try { + const launcher = NodePath.join(directory, "launch's"); + NodeFS.writeFileSync(launcher, agentScopeLauncherScript(launch), { mode: 0o700 }); + const launched = NodeChildProcess.spawnSync(launcher, ["--flag", "it's"], { + encoding: "utf8", + }); + const [launchedPid, launchedScore, ...launchedArgs] = launched.stdout.trimEnd().split("\n"); + expect(Number(launchedPid)).toBe(launched.pid); + expect(Number(launchedScore)).toBe(AGENT_OOM_SCORE_ADJ); + expect(launchedArgs).toEqual(["a b", "$HOME", "--flag", "it's"]); + } finally { + NodeFS.rmSync(directory, { recursive: true, force: true }); + } }); }); diff --git a/packages/shared/src/AgentScope.ts b/packages/shared/src/AgentScope.ts index 361bfc49108c6..ce2d58c017b25 100644 --- a/packages/shared/src/AgentScope.ts +++ b/packages/shared/src/AgentScope.ts @@ -74,6 +74,14 @@ export interface AgentSystemdScope { readonly options: ReadonlyArray; } +const quoteShell = (value: string) => `'${value.replaceAll("'", `'\\''`)}'`; + +/** An executable file for launchers that take a path, not a command line, such as Playwright. */ +export function agentScopeLauncherScript(launch: AgentScopeCommand): string { + const command = [launch.command, ...launch.args].map(quoteShell).join(" "); + return `#!/bin/sh\nexec ${command} "$@"\n`; +} + /** Exec at every step preserves the agent PID, stdio, and signals; systemd-run places it and descendants in the scope. */ export function agentScopeCommand(input: { readonly command: string; From 8ab098a4a8d62335f43cf61b708c2fbb65d4741c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 29 Oct 2026 18:12:10 -0700 Subject: [PATCH 392/817] fix(server): held queues release agent and scheduled messages once the thread completes a run (#27221) Co-authored-by: Claude Opus 5.5 --- .../src/orchestration-v2/Orchestrator.ts | 86 +++++- .../src/orchestration-v2/ProjectionStore.ts | 15 + .../ProviderTurnControlService.test.ts | 1 + .../src/orchestration-v2/runtimeLayer.test.ts | 264 +++++++++++++++++- 4 files changed, 351 insertions(+), 15 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index c464a8743f3c2..05b5601e5a80a 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -741,6 +741,20 @@ function delegatedTaskTerminalStatus( } } +/** Failed worktree setup keeps the queue held so queued messages cannot start in the project checkout. */ +function worktreeSetupPending( + projection: Pick, +): boolean { + return ( + projection.thread.worktreePath === null && + projection.runs.some( + (run) => + (run.status === "failed" || run.status === "interrupted") && + run.workspacePreparation?.type === "worktree", + ) + ); +} + function nextQueuedRun( projection: Pick, ): OrchestrationV2Run | undefined { @@ -2195,6 +2209,52 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); + // A hold waits for a person to review what they queued. Nobody reviews messages from agents, + // the server or scheduled tasks, so a later completed run releases those unless it was stopped. + const releaseUnattendedHolds = Effect.fn("Orchestrator.releaseUnattendedHolds")(function* ( + threadId: ThreadId, + completedRunId: RunId, + ) { + const held = yield* projectionStore.getHeldQueuedRuns(threadId); + if (held.length === 0) return; + const projection = yield* projectionStore.getThreadRecords( + threadId, + ["runs", "messages", "turnItems"], + { + messageIds: held.map((run) => run.userMessageId), + turnItemTypes: ["run_interrupt_request"], + turnItemRunIds: [completedRunId], + }, + ); + // Only the newest run completing shows the thread moved past the hold; a late or + // bookkeeping update to an older run, overtaken by a failure or Stop, does not. + if ( + latestExecutedRun(projection.runs)?.id !== completedRunId || + projection.turnItems.length > 0 || + worktreeSetupPending(projection) + ) + return; + const { messages } = projection; + const unattended = new Set( + messages + .filter((message) => message.createdBy !== "user" || message.scheduledTaskId !== undefined) + .map((message) => message.id), + ); + const now = yield* DateTime.now; + const released = held.filter((run) => unattended.has(run.userMessageId)); + if (released.length === 0) return; + yield* writeSystemEvents( + released.map((run) => ({ + type: "run.updated" as const, + threadId, + runId: run.id, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { ...run, queueHeld: false }, + })), + ); + }); + const resumeQueuedRuns = Effect.gen(function* () { const threadIds = yield* projectionStore.getRecoveryThreadIds("queued-runs"); let resumed = 0; @@ -5539,15 +5599,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio dispatchMode.type === "queue_after_active"; const shouldQueue = queueBehindRun !== undefined && startsOrQueuesRun; // Client messages resume held queues; server continuations and scheduled tasks do not. - // Provider failure or usage limits re-hold the queue. Failed worktree setup keeps it held - // until a worktree exists, so queued messages cannot start in the project checkout. - const worktreeSetupUnresolved = - projection.thread.worktreePath === null && - projection.runs.some( - (run) => - (run.status === "failed" || run.status === "interrupted") && - run.workspacePreparation?.type === "worktree", - ); + // Provider failure or usage limits re-hold the queue. + const worktreeSetupUnresolved = worktreeSetupPending(projection); const sentByUserFromClient = command.createdBy === "user" && (command.creationSource === "web" || command.creationSource === "mobile") && @@ -13083,10 +13136,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio yield* threadDispatch .withLock( threadId, - startNextQueuedRun(threadId, { - endedRunId: run.id, - ...(run.status === "failed" ? { failedRunId: run.id } : {}), - }), + (run.status === "completed" + ? releaseUnattendedHolds(threadId, run.id) + : Effect.void + ).pipe( + Effect.andThen( + startNextQueuedRun(threadId, { + endedRunId: run.id, + ...(run.status === "failed" ? { failedRunId: run.id } : {}), + }), + ), + ), ) .pipe( Effect.catchCause((cause) => diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 6bb04041c75b6..88a9073117dd6 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -612,6 +612,9 @@ export interface ProjectionStoreV2Shape { readonly canStartQueuedRun: ( threadId: ThreadId, ) => Effect.Effect; + readonly getHeldQueuedRuns: ( + threadId: ThreadId, + ) => Effect.Effect, ProjectionStoreV2Error>; readonly getRecoveryThreadIds: ( kind: ProjectionRecoveryKind, ) => Effect.Effect, ProjectionStoreV2Error>; @@ -5183,6 +5186,17 @@ export const layer: Layer.Layer = ) .pipe(Effect.mapError(controlReadError(threadId))); + const getHeldQueuedRuns: ProjectionStoreV2Shape["getHeldQueuedRuns"] = (threadId) => + sql` + SELECT payload_json FROM orchestration_v2_projection_runs + WHERE thread_id = ${threadId} AND status = 'queued' + AND json_extract(payload_json, '$.queueHeld') IS 1 + ORDER BY ordinal ASC + `.pipe( + Effect.flatMap(decodeRows(decodeRunPayload, threadId)), + Effect.mapError(controlReadError(threadId)), + ); + const getMessageCount: ProjectionStoreV2Shape["getMessageCount"] = (threadId) => sql<{ count: number; @@ -6899,6 +6913,7 @@ export const layer: Layer.Layer = getCheckpointRollbackContext: readOnReader(getCheckpointRollbackContext), getRunMessage: readOnReader(getRunMessage), canStartQueuedRun: readOnReader(canStartQueuedRun), + getHeldQueuedRuns: readOnReader(getHeldQueuedRuns), getPendingNativeUserInputs: readOnReader(getPendingNativeUserInputs), hasUnpairedRunInterruptRequest: readOnReader(hasUnpairedRunInterruptRequest), isNodeStored: readOnReader(isNodeStored), diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts index 1d79e87eb9b91..bab115f6e24cb 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts @@ -263,6 +263,7 @@ it.effect( getRunMessage: () => Effect.die("not used"), isNodeStored: () => Effect.die("not used"), canStartQueuedRun: () => Effect.die("not used"), + getHeldQueuedRuns: () => Effect.die("not used"), getRecoveryThreadIds: () => Effect.die("unused getRecoveryThreadIds"), getUnreadableThreadIds: () => Effect.die("unused getUnreadableThreadIds"), getThreadSnapshot: () => Effect.die("unused getThreadSnapshot"), diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 428202d17b651..11eb866b5fb9c 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -4768,6 +4768,265 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + // A thread fed by agent messages, with helpers to end its runs as a provider would. + const queueTestThread = (threadId: ThreadId) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`${threadId}:create`), + threadId, + projectId: ProjectId.make(`${threadId}:project`), + title: "Dispatcher", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + }); + const send = (key: string, createdBy: "user" | "agent", start: boolean) => + orchestrator.dispatch({ + type: "message.dispatch", + createdBy, + creationSource: createdBy === "user" ? "web" : "server", + commandId: CommandId.make(`${threadId}:message:${key}`), + threadId, + messageId: MessageId.make(`${threadId}:message:${key}`), + text: key, + attachments: [], + modelSelection, + dispatchMode: { type: start ? "start_immediately" : "queue_after_active" }, + }); + const runFor = (key: string) => + Effect.map(orchestrator.getThreadProjection(threadId), ({ runs }) => { + const run = runs.find( + (candidate) => candidate.userMessageId === MessageId.make(`${threadId}:message:${key}`), + ); + assert.isDefined(run); + return run; + }); + const startedRunIds = yield* Queue.unbounded(); + // Run updates in commit order; the run-update listener handles them in this order too. + const runUpdates: Array = []; + yield* eventSink + .stream({ threadId, afterSequence: yield* orchestrator.getThreadEventSequence(threadId) }) + .pipe( + Stream.runForEach((stored) => { + if (stored.event.type !== "run.updated") return Effect.void; + runUpdates.push(stored.event.payload); + return stored.event.payload.status === "starting" + ? Queue.offer(startedRunIds, stored.event.payload.id) + : Effect.void; + }), + Effect.forkScoped, + ); + yield* Effect.yieldNow; + const releasedAfter = (key: string, completedKey: string) => + Effect.gen(function* () { + const [run, completed] = [yield* runFor(key), yield* runFor(completedKey)]; + const released = runUpdates.findIndex( + (update) => update.id === run.id && update.queueHeld === false, + ); + const completion = runUpdates.findIndex( + (update) => update.id === completed.id && update.status === "completed", + ); + assert.isAbove(released, completion, `${key} was released before ${completedKey} ended`); + }); + const end = ( + key: string, + status: "completed" | "failed", + revision = "", + patch: Partial = {}, + ) => + Effect.gen(function* () { + const run = yield* runFor(key); + assert.isNotNull(run.rootNodeId); + const now = yield* DateTime.now; + yield* eventSink.write({ + events: [ + ...(status === "failed" + ? [ + { + id: EventId.make(`${threadId}:${key}:error`), + type: "turn-item.updated" as const, + threadId, + runId: run.id, + nodeId: run.rootNodeId, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { + id: TurnItemId.make(`${threadId}:${key}:error`), + type: "error" as const, + threadId, + runId: run.id, + nodeId: run.rootNodeId, + providerThreadId: run.providerThreadId, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 2, + status: "failed" as const, + title: "Provider failure", + startedAt: now, + completedAt: now, + updatedAt: now, + failure: { + class: "provider_error" as const, + message: "Provider failed.", + code: "provider_failed", + retryable: null, + }, + }, + }, + ] + : []), + { + id: EventId.make(`${threadId}:${key}:${status}${revision}`), + type: "run.updated", + threadId, + runId: run.id, + nodeId: run.rootNodeId, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { ...run, ...patch, status, startedAt: now, completedAt: now }, + }, + ], + }); + }); + + // The run-update listener places failure holds after the terminal event commits. + const awaitHeld = (key: string) => + Effect.gen(function* () { + const run = yield* runFor(key); + yield* eventSink.stream({ threadId, afterSequence: 0, eventType: "run.updated" }).pipe( + Stream.filter( + (stored) => + stored.event.type === "run.updated" && + stored.event.payload.id === run.id && + stored.event.payload.queueHeld === true, + ), + Stream.runHead, + ); + }); + return { send, runFor, end, startedRunIds, releasedAfter, awaitHeld }; + }); + + it.effect("releases held agent messages once a later run completes, not the user's", () => + Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const threadId = ThreadId.make("runtime-layer-failed-queue-agent-messages"); + const { send, runFor, end, startedRunIds, releasedAfter, awaitHeld } = + yield* queueTestThread(threadId); + yield* send("earlier", "agent", true); + yield* end("earlier", "completed"); + yield* send("active", "agent", true); + yield* send("issue", "agent", false); + yield* send("user", "user", false); + yield* end("active", "failed"); + yield* awaitHeld("issue"); + assert.isTrue((yield* runFor("issue")).queueHeld); + // Delivery bookkeeping rewrites an older completed run; the thread has not moved on. + yield* end("earlier", "completed", ":bookkeeping"); + // A scheduled tick finds the thread idle and starts past the held queue. + yield* send("tick", "agent", true); + assert.equal((yield* runFor("tick")).status, "starting"); + yield* end("tick", "completed"); + assert.equal(yield* Queue.take(startedRunIds), (yield* runFor("issue")).id); + yield* releasedAfter("issue", "tick"); + const user = yield* runFor("user"); + assert.equal(user.status, "queued"); + assert.isTrue(user.queueHeld); + + // A run that finishes despite a stop request does not release what the stop held. + yield* send("after-stop", "agent", false); + assert.isTrue((yield* runFor("after-stop")).queueHeld); + const issue = yield* runFor("issue"); + assert.isNotNull(issue.rootNodeId); + const now = yield* DateTime.now; + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${threadId}:issue:interrupt-request`), + type: "turn-item.updated", + threadId, + runId: issue.id, + nodeId: issue.rootNodeId, + providerInstanceId: issue.providerInstanceId, + occurredAt: now, + payload: { + id: TurnItemId.make(`${threadId}:issue:interrupt-request`), + type: "run_interrupt_request", + threadId, + runId: issue.id, + nodeId: issue.rootNodeId, + providerThreadId: issue.providerThreadId, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 2, + status: "completed", + title: "Interrupt requested", + startedAt: now, + completedAt: now, + updatedAt: now, + message: "Stopped by user", + }, + }, + ], + }); + yield* end("issue", "completed"); + // The next completed run releases it, which also shows the listener handled the stopped one. + yield* send("probe", "agent", true); + assert.equal((yield* runFor("probe")).status, "starting"); + yield* end("probe", "completed"); + assert.equal(yield* Queue.take(startedRunIds), (yield* runFor("after-stop")).id); + yield* releasedAfter("after-stop", "probe"); + }), + ); + + it.effect("keeps held agent messages while the thread's worktree setup is unresolved", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const dispatcherId = ThreadId.make("runtime-layer-held-queue-worktree"); + const dispatcher = yield* queueTestThread(dispatcherId); + const witness = yield* queueTestThread(ThreadId.make("runtime-layer-held-queue-witness")); + yield* dispatcher.send("setup", "agent", true); + yield* dispatcher.send("issue", "agent", false); + yield* dispatcher.end("setup", "failed", "", { + workspacePreparation: { type: "worktree", baseRef: "main" }, + }); + yield* dispatcher.awaitHeld("issue"); + assert.isTrue((yield* dispatcher.runFor("issue")).queueHeld); + yield* dispatcher.send("tick", "agent", true); + assert.equal((yield* dispatcher.runFor("tick")).status, "starting"); + yield* witness.send("active", "agent", true); + yield* witness.send("queued", "agent", false); + // The failed setup never produced the thread's worktree. + const { thread } = yield* orchestrator.getThreadProjection(dispatcherId); + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${dispatcherId}:worktree-missing`), + type: "thread.metadata-updated", + threadId: dispatcherId, + occurredAt: yield* DateTime.now, + payload: { ...thread, worktreePath: null }, + }, + ], + }); + yield* dispatcher.end("tick", "completed"); + // One listener handles every thread's completions in order, so the witness starting + // means the tick's completion was handled too. + yield* witness.end("active", "completed"); + assert.equal(yield* Queue.take(witness.startedRunIds), (yield* witness.runFor("queued")).id); + assert.isTrue((yield* dispatcher.runFor("issue")).queueHeld); + }), + ); + it.effect("keeps queued user selections and pauses only the limited provider", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; @@ -5372,9 +5631,10 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { after.runs.find((run) => run.id === held.id), held, ); + // Nobody will resume a server message, so the completed run released it behind the wake. assert.deepEqual( after.runs.find((run) => run.id === textContinuation.id), - textContinuation, + { ...textContinuation, queueHeld: false }, ); }), ); @@ -5714,7 +5974,7 @@ it.layer(layerTest)("snooze queued runs", (it) => { payload: run.status === "queued" ? { ...run, queueHeld: true } - : { ...run, status: "completed" as const, completedAt: now }, + : { ...run, status: "cancelled" as const, completedAt: now }, })), effects: [], }); From 36dac688a17c6de1c6398e62d01546fb787c185b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 29 Oct 2026 18:12:11 -0700 Subject: [PATCH 393/817] fix(server): restart continuations retry failed starts and respect a parent's stop (#27222) Co-authored-by: Claude Opus 5.5 --- .../DelegatedCompletionDelivery.test.ts | 59 +++++++ .../src/orchestration-v2/Orchestrator.ts | 51 +++++- .../orchestration-v2/RestartBackgroundNote.ts | 46 ++++- .../RestartContinuation.test.ts | 122 +++++++++++++- .../orchestration-v2/RestartContinuation.ts | 33 +++- .../src/orchestration-v2/runtimeLayer.test.ts | 159 ++++++++++++++++++ 6 files changed, 464 insertions(+), 6 deletions(-) diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts index 77e4cd11ba071..ad2bc395d083f 100644 --- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts @@ -2448,6 +2448,65 @@ it.layer(layerTest)("delegated tasks across a server restart", (it) => { const task = settled.subagents.find((row) => row.id === child.taskId); assert.equal(task?.status, "cancelled"); assert.equal(task?.completionDelivery?.state, "claimed"); + + // The parent's Stop committed, but the restart cut the effect that stops its children. + const stoppedChild = yield* seedRestartCancelledChild({ + parentThreadId: threadId, + projectId, + parentRunId: runId, + rootNodeId, + name: "restart-parent-stopped-child", + completionWake: "always", + continuationPending: true, + now, + }); + yield* (yield* EventSink.EventSinkV2).write({ + commandId: CommandId.make("command:restart-declined-parent:stop"), + events: [ + { + id: EventId.make("event:restart-declined-parent:interrupt-request"), + type: "turn-item.updated", + threadId, + runId, + nodeId: rootNodeId, + providerInstanceId: modelSelection.instanceId, + occurredAt: now, + payload: { + id: TurnItemId.make("turn-item:restart-declined-parent:interrupt-request"), + type: "run_interrupt_request", + threadId, + runId, + nodeId: rootNodeId, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 90, + status: "completed", + title: "Interrupt requested", + startedAt: now, + completedAt: now, + updatedAt: now, + message: "Stopped by user", + }, + }, + ], + }); + yield* continueRestartedRun({ + threadId: stoppedChild.childThreadId, + sourceRunId: stoppedChild.childRunId, + }).pipe(Effect.provide(ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }))); + const afterStop = yield* orchestrator.getThreadProjection(threadId); + assert.equal( + afterStop.subagents.find((row) => row.id === stoppedChild.taskId)?.status, + "cancelled", + ); + assert.deepEqual( + (yield* orchestrator.getThreadProjection(stoppedChild.childThreadId)).runs.map( + (run) => run.id, + ), + [stoppedChild.childRunId], + ); }), ); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 05b5601e5a80a..c65005deefb48 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -107,6 +107,8 @@ import { ContextHandoffServiceV2 } from "./ContextHandoffService.ts"; import { notificationTurnItem } from "@t3tools/provider-core/server/notification"; import { cancelledBeforeStart, + continuationFailedBeforePrompt, + continuationStartRetryDelayMs, isRestartContinuationSource, runOutcome, } from "./RestartBackgroundNote.ts"; @@ -2209,6 +2211,35 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); + // Under load a resumed provider can time out before taking the prompt; the restart still owes the turn. + const retryContinuationStart = Effect.fn("Orchestrator.retryContinuationStart")(function* ( + threadId: ThreadId, + runId: RunId, + ) { + const projection = yield* projectionStore.getThreadRecords( + threadId, + ["runs", "providerTurns", "turnItems"], + { turnItemTypes: ["error"], turnItemRunIds: [runId] }, + ); + const run = projection.runs.find((candidate) => candidate.id === runId); + if (run === undefined) return; + const delayMs = continuationStartRetryDelayMs(run, projection); + if (delayMs === undefined) return; + const commandId = CommandId.make(`command:restart-continuation-retry:${run.id}`); + yield* writeSystemEvents( + [], + [ + { + id: `effect:restart-continuation:${run.id}`, + commandId, + threadId, + request: { type: "provider-runtime.continue", sourceRunId: run.id }, + availableAt: DateTime.add(yield* DateTime.now, { milliseconds: delayMs }), + }, + ], + ); + }); + // A hold waits for a person to review what they queued. Nobody reviews messages from agents, // the server or scheduled tasks, so a later completed run releases those unless it was stopped. const releaseUnattendedHolds = Effect.fn("Orchestrator.releaseUnattendedHolds")(function* ( @@ -5188,7 +5219,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const source = projection.runs.find((run) => run.id === command.restartContinuationOfRunId); if ( !source || - !isRestartContinuationSource(source, projection.providerTurns) || + !( + isRestartContinuationSource(source, projection.providerTurns) || + continuationFailedBeforePrompt(source, projection.providerTurns) + ) || projection.thread.archivedAt !== null || projection.thread.deletedAt !== null || projection.thread.providerInstanceId !== source.providerInstanceId || @@ -10419,7 +10453,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // A resumed queue can have a lower ordinal than a pending continuation source. // Stop must reach those sources even when interrupting the resumed run succeeds. if ( - run.status === "cancelled" && + (run.status === "cancelled" || + (run.status === "failed" && run.restartContinuationOfRunId !== undefined)) && (yield* awaitsRestartContinuation(run).pipe(mapDispatchError(input.command))) ) { yield* markStoppedRun({ ...input, thread, run }); @@ -13129,6 +13164,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // while writing child events, so nesting parent inside child would invert the order. // The keyed semaphores are neither reentrant nor deadlock-aware. if (delegatedTaskTerminalStatus(run.status) !== null) { + // Before the parent hears of the failure: a pending continuation keeps the task open. + if (run.status === "failed" && run.restartContinuationOfRunId !== undefined) { + yield* threadDispatch.withLock(threadId, retryContinuationStart(threadId, run.id)).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Failed to schedule a restart continuation retry", { + threadId, + runId: run.id, + cause, + }), + ), + ); + } yield* threadDispatch.withLock( threadId, finalizeDelegatedCompletionDelivery(threadId, run.id), diff --git a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts index ba3830f65453d..24afd61d6186a 100644 --- a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts +++ b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts @@ -6,7 +6,7 @@ import type { OrchestrationV2RunAttempt, OrchestrationV2TurnItem, } from "@t3tools/contracts"; -import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError"; +import { latestRootProviderFailure, runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError"; type Work = OrchestrationV2RestartCancelledBackgroundWork; type Attempt = Pick; @@ -181,6 +181,50 @@ export function cancelledBeforeStart( return run.status === "cancelled" && neverStarted(run); } +/** The provider never accepted this continuation's prompt, so starting it again repeats nothing. */ +export function continuationFailedBeforePrompt( + run: Pick, + providerTurns: ReadonlyArray>, +): boolean { + return ( + run.status === "failed" && + run.restartContinuationOfRunId !== undefined && + !providerTurns.some((turn) => turn.runAttemptId === run.activeAttemptId) + ); +} + +const CONTINUATION_START_RETRY_DELAYS_MS = [60_000, 180_000]; + +/** Backoff before restarting a continuation that failed to start, or undefined to let it fail. */ +export function continuationStartRetryDelayMs( + run: OrchestrationV2Run, + projection: { + readonly runs: ReadonlyArray; + readonly providerTurns: ReadonlyArray>; + readonly turnItems: Parameters[1]; + }, +): number | undefined { + if (!continuationFailedBeforePrompt(run, projection.providerTurns)) return; + // These fail the same way however often they start. + const failureClass = latestRootProviderFailure(run, projection.turnItems)?.class; + if ( + failureClass === "usage_limit" || + failureClass === "permission_error" || + failureClass === "validation_error" + ) + return; + let failedStarts = 0; + for ( + let current: OrchestrationV2Run | undefined = run; + current !== undefined && continuationFailedBeforePrompt(current, projection.providerTurns); + current = projection.runs.find( + (candidate) => candidate.id === current?.restartContinuationOfRunId, + ) + ) + failedStarts += 1; + return CONTINUATION_START_RETRY_DELAYS_MS[failedStarts - 1]; +} + export function isRestartContinuationSource( source: Pick, providerTurns: ReadonlyArray>, diff --git a/apps/server/src/orchestration-v2/RestartContinuation.test.ts b/apps/server/src/orchestration-v2/RestartContinuation.test.ts index 061fc54a7f112..d2224720b89f1 100644 --- a/apps/server/src/orchestration-v2/RestartContinuation.test.ts +++ b/apps/server/src/orchestration-v2/RestartContinuation.test.ts @@ -20,6 +20,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as ServerSettings from "../serverSettings.ts"; import { restartContinuationRun, continueRestartedRun } from "./RestartContinuation.ts"; +import { continuationStartRetryDelayMs } from "./RestartBackgroundNote.ts"; import * as ThreadManagementService from "./ThreadManagementService.ts"; import * as ProviderRuntimeRecovery from "./ProviderRuntimeRecoveryService.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; @@ -46,6 +47,8 @@ function makeProjection() { providerInstanceId: instanceId, archivedAt: null, deletedAt: null, + lineage: { parentThreadId: null, relationshipToParent: null }, + forkedFrom: null, }, runs: [ { @@ -839,10 +842,13 @@ it.effect("does not cancel or resume a run that completes while shutdown intent }), ); -const continuationDispatches = (projection: OrchestrationV2ThreadProjection) => +const continuationDispatches = ( + projection: OrchestrationV2ThreadProjection, + sourceRunId: RunId = runId, +) => Effect.gen(function* () { const dispatches: Array> = []; - yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe( + yield* continueRestartedRun({ threadId, sourceRunId }).pipe( Effect.provide( Layer.merge( Layer.mock(ThreadManagementService.ThreadManagementService)({ @@ -943,6 +949,118 @@ it.effect("continues a resumed queued run that ran after an earlier continuation }), ); +it("backs off twice from a continuation the provider never took, then lets it fail", () => { + const base = makeProjection(); + const failedStart = (id: string, of: RunId) => ({ + ...base.runs[0]!, + id: RunId.make(id), + activeAttemptId: RunAttemptId.make(`attempt:${id}`), + status: "failed" as const, + restartContinuationOfRunId: of, + }); + const first = failedStart("run:retry-1", runId); + const second = failedStart("run:retry-2", first.id); + const third = failedStart("run:retry-3", second.id); + const projection = (failureClass = "provider_error", providerTurns = base.providerTurns) => + ({ + runs: [{ ...base.runs[0]!, status: "cancelled" }, first, second, third], + providerTurns, + turnItems: [first, second, third].map((run) => ({ + id: `error:${run.id}`, + type: "error", + status: "failed", + runId: run.id, + nodeId: run.rootNodeId, + ordinal: 1, + updatedAt: now, + failure: { class: failureClass, message: "Failed.", code: null, retryable: null }, + })), + }) as unknown as Parameters[1]; + assert.deepEqual( + [first, second, third].map((run) => continuationStartRetryDelayMs(run, projection())), + [60_000, 180_000, undefined], + ); + for (const failureClass of ["usage_limit", "permission_error", "validation_error"]) + assert.isUndefined(continuationStartRetryDelayMs(first, projection(failureClass))); + // Once the provider took the prompt, starting again would repeat the turn. + assert.isUndefined( + continuationStartRetryDelayMs( + first, + projection("provider_error", [ + { ...base.providerTurns[0]!, runAttemptId: first.activeAttemptId, status: "failed" }, + ] as never), + ), + ); +}); + +it.effect("continues again after a continuation fails before its prompt", () => + Effect.gen(function* () { + const cut = cutMidTurn(); + const failedStart = { + ...cut.runs[0]!, + id: RunId.make("run:failed-start"), + ordinal: 2, + activeAttemptId: RunAttemptId.make("attempt:failed-start"), + status: "failed", + restartContinuationOfRunId: runId, + }; + const dispatches = yield* continuationDispatches( + { ...cut, runs: [...cut.runs, failedStart] } as unknown as OrchestrationV2ThreadProjection, + failedStart.id, + ); + assert.deepEqual( + dispatches.map((command) => command.restartContinuationOfRunId), + [failedStart.id], + ); + }), +); + +it.effect.each([ + ["running", null, 0], + ["completed", "Done.", 1], +] as const)( + "a parent's Stop on the task's run blocks the child only while the task is %s", + ([status, result, expected]) => + Effect.gen(function* () { + const parentThreadId = ThreadId.make("thread:parent"); + const parentRunId = RunId.make("run:parent"); + const taskId = NodeId.make("node:task"); + const cut = cutMidTurn(); + const child = { + ...cut, + thread: { + ...cut.thread, + lineage: { parentThreadId, relationshipToParent: "subagent" }, + forkedFrom: { type: "node", nodeId: taskId }, + }, + } as unknown as OrchestrationV2ThreadProjection; + const parent = { + thread: { id: parentThreadId }, + subagents: [{ id: taskId, runId: parentRunId, origin: "app_owned", status, result }], + turnItems: [{ id: "turn-item:stop", runId: parentRunId, type: "run_interrupt_request" }], + }; + let dispatched = 0; + yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe( + Effect.provide( + Layer.merge( + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadRecords: (id) => + Effect.succeed((id === parentThreadId ? parent : child) as never), + recoverDelegatedTask: () => Effect.void, + dispatch: () => + Effect.sync(() => { + dispatched += 1; + return {} as never; + }), + }), + ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }), + ), + ), + ); + assert.equal(dispatched, expected); + }), +); + it.effect("does not continue a run the user asked to stop before the restart", () => Effect.gen(function* () { const texts = yield* continuationTexts({ diff --git a/apps/server/src/orchestration-v2/RestartContinuation.ts b/apps/server/src/orchestration-v2/RestartContinuation.ts index c81faa6cf47cb..e4d7ac2b7f900 100644 --- a/apps/server/src/orchestration-v2/RestartContinuation.ts +++ b/apps/server/src/orchestration-v2/RestartContinuation.ts @@ -2,6 +2,7 @@ import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { CommandId, + isOrchestrationV2WorkActive, latestProviderTurnForAttempt, MessageId, type OrchestrationV2Run, @@ -19,6 +20,7 @@ import { awaitingProviderThreadId, cancelledRosterTaskWork, cancelledTurnItemWork, + continuationFailedBeforePrompt, isAwaitedWork, isRestartContinuationSource, cancelledBeforeStart, @@ -200,7 +202,10 @@ export const continueRestartedRun = Effect.fn("RestartContinuation.continueResta const source = projection.runs.find((run) => run.id === input.sourceRunId); if ( !source || - !isRestartContinuationSource(source, projection.providerTurns) || + !( + isRestartContinuationSource(source, projection.providerTurns) || + continuationFailedBeforePrompt(source, projection.providerTurns) + ) || restartContinuationBlocked( projection, source, @@ -255,6 +260,32 @@ export const continueRestartedRun = Effect.fn("RestartContinuation.continueResta ) ) return; + // A parent's Stop reaches its open delegated tasks through an effect a restart can cut short. + const { lineage, forkedFrom } = projection.thread; + const taskId = + source.delegatedTaskId ?? (forkedFrom?.type === "node" ? forkedFrom.nodeId : undefined); + if ( + lineage.relationshipToParent === "subagent" && + lineage.parentThreadId !== null && + taskId !== undefined + ) { + const task = (yield* threads.getThreadRecords(lineage.parentThreadId, ["subagents"], { + subagentIds: [taskId], + })).subagents.find((candidate) => candidate.id === taskId); + // A settled task no longer owns later work in its thread. + const parentRunId = + task !== undefined && task.result === null && isOrchestrationV2WorkActive(task.status) + ? task.runId + : null; + if ( + parentRunId !== null && + (yield* threads.getThreadRecords(lineage.parentThreadId, ["turnItems"], { + turnItemTypes: ["run_interrupt_request"], + turnItemRunIds: [parentRunId], + })).turnItems.length > 0 + ) + return; + } const sourceMessage = sourceRecords.messages.find( (message) => message.id === source.userMessageId, ); diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 11eb866b5fb9c..20158a80d3ff6 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -5465,6 +5465,165 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + it.effect.each([false, true])( + "restarts a continuation that failed before its prompt, unless stopped (%s)", + (stopped) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = ThreadId.make(`runtime-layer-continuation-start-retry-${stopped}`); + const messageId = (key: string) => MessageId.make(`${threadId}:${key}`); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`${threadId}:create`), + threadId, + projectId: ProjectId.make(`${threadId}:project`), + title: "Continuation start retry", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + }); + const runFor = (key: string) => + Effect.map(orchestrator.getThreadProjection(threadId), ({ runs }) => + runs.find((candidate) => candidate.userMessageId === messageId(key)), + ); + const write = ( + key: string, + payload: OrchestrationV2Run, + extra: Parameters[0]["events"] = [], + ) => + Effect.gen(function* () { + const now = yield* DateTime.now; + yield* eventSink.write({ + events: [ + ...extra, + { + id: EventId.make(`${threadId}:${key}`), + type: "run.updated", + threadId, + runId: payload.id, + providerInstanceId: payload.providerInstanceId, + occurredAt: now, + payload: { ...payload, startedAt: now, completedAt: now }, + }, + ], + }); + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`${threadId}:message:cut`), + threadId, + messageId: messageId("cut"), + text: "Work that the restart cut", + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + }); + const cut = (yield* runFor("cut"))!; + yield* write("cut:cancelled", { ...cut, status: "cancelled" }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "agent", + creationSource: "server", + commandId: CommandId.make(`${threadId}:message:continuation`), + threadId, + messageId: messageId("continuation"), + text: "Continue where you left off.", + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + restartContinuationOfRunId: cut.id, + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`${threadId}:message:queued`), + threadId, + messageId: messageId("queued"), + text: "Queued behind the continuation", + attachments: [], + modelSelection, + dispatchMode: { type: "queue_after_active" }, + }); + const continuation = (yield* runFor("continuation"))!; + assert.isNotNull(continuation.rootNodeId); + const queued = (yield* runFor("queued"))!; + // The failure holds the queue after the reactor scheduled any retry. + const held = yield* eventSink + .stream({ threadId, afterSequence: yield* orchestrator.getThreadEventSequence(threadId) }) + .pipe( + Stream.filter( + (stored) => + stored.event.type === "run.updated" && + stored.event.payload.id === queued.id && + stored.event.payload.queueHeld === true, + ), + Stream.runHead, + Effect.forkScoped, + ); + yield* Effect.yieldNow; + const now = yield* DateTime.now; + yield* write("continuation:failed", { ...continuation, status: "failed" }, [ + { + id: EventId.make(`${threadId}:continuation:error`), + type: "turn-item.updated", + threadId, + runId: continuation.id, + nodeId: continuation.rootNodeId, + providerInstanceId: continuation.providerInstanceId, + occurredAt: now, + payload: { + id: TurnItemId.make(`${threadId}:continuation:error`), + type: "error", + threadId, + runId: continuation.id, + nodeId: continuation.rootNodeId, + providerThreadId: continuation.providerThreadId, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 2, + status: "failed", + title: "Provider failure", + startedAt: now, + completedAt: now, + updatedAt: now, + failure: { + class: "provider_error", + message: "Claude timed out while registering its MCP tools.", + code: null, + retryable: null, + }, + }, + }, + ]); + yield* Fiber.join(held); + const retriesOf = Effect.map(orchestrator.getThreadProjection(threadId), ({ runs }) => + runs.filter((run) => run.restartContinuationOfRunId === continuation.id), + ); + yield* worker.drain(); + assert.deepEqual(yield* retriesOf, [], "the retry waits out its backoff"); + if (stopped) { + yield* orchestrator.dispatch({ + type: "thread.stop", + commandId: CommandId.make(`${threadId}:stop`), + threadId, + }); + } + yield* TestClock.adjust("61 seconds"); + yield* worker.drain(); + assert.lengthOf(yield* retriesOf, stopped ? 0 : 1); + }), + ); + it.effect.each(["startup", "shutdown"] as const)( "preserves and holds queued messages across %s until explicitly resumed", (trigger) => From 6d12bb1e9fbdd6186967ae57cd0917c39f7214e4 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Thu, 29 Oct 2026 18:24:10 -0700 Subject: [PATCH 394/817] fix(server): Stop during a restart no longer leaves the thread stuck (#27141) Co-authored-by: Claude Opus 5.5 --- .../src/orchestration-v2/Orchestrator.ts | 39 ++++++ .../SelectionRestart.integration.test.ts | 112 ++++++++++++++++++ 2 files changed, 151 insertions(+) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index c65005deefb48..16865229d94f2 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -11062,6 +11062,45 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio occurredAt: now, payload: { ...run, status: "interrupted", completedAt: now }, }); + // Stop cancels a pending restart, so it must end the turn that restart could not stop. + const supersededTurn = projection.providerTurns.findLast( + (candidate) => + candidate.status === "running" && + projection.attempts.some( + (attempt) => attempt.id === candidate.runAttemptId && attempt.runId === run.id, + ), + ); + const supersededOwner = + supersededTurn === undefined + ? undefined + : projection.providerThreads.find( + (candidate) => candidate.id === supersededTurn.providerThreadId, + ); + if ( + supersededTurn !== undefined && + supersededOwner !== undefined && + supersededOwner.providerSessionId !== null && + Option.isSome( + yield* providerSessions + .get(supersededOwner.providerSessionId) + .pipe(Effect.orElseSucceed(() => Option.none())), + ) + ) { + const id = `effect:${command.commandId}:provider-turn.interrupt:${supersededTurn.id}`; + if (!otherProviderInterrupts.some((effect) => effect.id === id)) { + otherProviderInterrupts.push({ + id, + commandId: command.commandId, + threadId: command.threadId, + request: { + type: "provider-turn.interrupt", + providerSessionId: supersededOwner.providerSessionId, + providerThreadId: supersededOwner.id, + providerTurnId: supersededTurn.id, + }, + }); + } + } yield* stopRemainingWork(); yield* Ref.update(effects, (existing) => [...existing, ...otherProviderInterrupts]); return { diff --git a/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts b/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts index 03cdf5e85a642..d059c4c20e9d7 100644 --- a/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts +++ b/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts @@ -438,6 +438,118 @@ it.live("retries a failed selection restart session open before completing", () ), ); +it.live("Stop during a restart interrupts the turn the restart could not stop", () => + Effect.scoped( + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace("selection-restart-stop"); + const threadId = ThreadId.make("thread:selection-restart-stop"); + const state = yield* Ref.make({ + activeTurn: null, + opened: [], + started: [], + closedSessionCount: 0, + failedReplacementOpen: false, + }); + const base = makeRestartAdapter(state); + // A wedged provider ignores the restart's soft cancel; only Stop ends its turn. + const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = { + ...base, + openSession: (input) => + base.openSession(input).pipe( + Effect.map((session) => ({ + ...session, + interruptTurn: (interrupt: ProviderAdapter.ProviderAdapterV2InterruptInput) => + interrupt.requestRuntimeRestart === true + ? session.interruptTurn(interrupt) + : Effect.never, + })), + ), + }; + + const result = yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const running = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => event.type === "provider-turn.updated" && event.payload.status === "running", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped({ startImmediately: true }), + ); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("command:selection-restart-stop:create"), + threadId, + projectId: ProjectId.make("project:selection-restart-stop"), + title: "Stop during restart", + modelSelection: initialSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("command:selection-restart-stop:first"), + threadId, + messageId: MessageId.make("message:selection-restart-stop:first"), + text: "first", + attachments: [], + modelSelection: initialSelection, + dispatchMode: { type: "start_immediately" }, + }); + yield* worker.drain(); + yield* Fiber.join(running); + const runId = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!.id; + + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("command:selection-restart-stop:steer"), + threadId, + messageId: MessageId.make("message:selection-restart-stop:steer"), + text: "Are you still going?", + attachments: [], + modelSelection: initialSelection, + dispatchMode: { type: "restart_active", targetRunId: runId }, + }); + yield* orchestrator.dispatch({ + type: "run.interrupt", + commandId: CommandId.make("command:selection-restart-stop:stop"), + threadId, + runId, + }); + yield* worker.drain(); + return { + projection: yield* orchestrator.getThreadProjection(threadId), + captured: yield* Ref.get(state), + }; + }).pipe( + Effect.provide( + ProviderReplayHarness.layerWithRegistry( + { name: "selection-restart-stop" }, + ProviderAdapterRegistry.layerSingle(adapter), + ), + ), + ); + + assert.isNull(result.captured.activeTurn); + assert.lengthOf(result.captured.started, 1); + assert.equal(result.projection.runs[0]?.status, "interrupted"); + assert.deepEqual( + result.projection.providerTurns.map((turn) => turn.status), + ["interrupted"], + ); + }), + ), +); + it.live( "restarts the live session on a model change when a newer stopped session record exists", () => From 8970a32104e0d37123f33fd122e96826e68b3b4a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 29 Oct 2026 18:31:45 -0700 Subject: [PATCH 395/817] fix(scripts): bound check:changed concurrency and step time (#27227) Co-authored-by: Claude Opus 5.5 --- docs/operations/development.md | 8 +- scripts/check-changed.test.ts | 154 ++++++ scripts/check-changed.ts | 852 ++++++++++++++++++++------------- 3 files changed, 677 insertions(+), 337 deletions(-) create mode 100644 scripts/check-changed.test.ts diff --git a/docs/operations/development.md b/docs/operations/development.md index 3307dbc22b969..0501250c29d16 100644 --- a/docs/operations/development.md +++ b/docs/operations/development.md @@ -170,8 +170,12 @@ files to packages with [ci-changes.cjs](../../.github/scripts/ci-changes.cjs), a compares against the merge base with `origin/main`, or with a ref you pass. CI still runs the full test suites and the jobs the summary lists, so a local pass does not promise a green CI run. -The steps run side by side, so a run takes about as long as its slowest step, usually knip's -exports pass at about 10 s. When the files are exactly those of the last passing run, it prints that +The steps run side by side, as many at once as the machine allows: one per two cores and per 6 GiB +of available memory. On a large machine a run takes about as long as its slowest step, usually +knip's exports pass at about 10 s. Pass `--concurrency ` or set `CHECK_CHANGED_CONCURRENCY` to +change the limit (`1` runs the steps one by one). A step that runs past `--timeout ` or +`CHECK_CHANGED_TIMEOUT` (default 900) is killed with every process it started and reported as +`TIMEOUT`, not as a failing check. When the files are exactly those of the last passing run, it prints that run's summary instead of running again. Any change to a file, the install, or a generated file runs the checks again. diff --git a/scripts/check-changed.test.ts b/scripts/check-changed.test.ts new file mode 100644 index 0000000000000..2bcd623a0b4b6 --- /dev/null +++ b/scripts/check-changed.test.ts @@ -0,0 +1,154 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as Clock from "effect/Clock"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Sink from "effect/Sink"; +import * as Stream from "effect/Stream"; +import { ChildProcessSpawner } from "effect/process"; +import * as TestClock from "effect/testing/TestClock"; + +import { defaultConcurrency, gitLines, runSteps, type Step } from "./check-changed.ts"; + +const GiB = 1024 ** 3; + +describe("check:changed", () => { + it("bounds the default concurrency by the scarcer of cores and available memory", () => { + assert.strictEqual(defaultConcurrency(32, 128 * GiB), 16); + assert.strictEqual(defaultConcurrency(32, 20 * GiB), 3); + assert.strictEqual(defaultConcurrency(4, 15 * GiB), 2); + assert.strictEqual(defaultConcurrency(4, 2 * GiB), 1); + assert.strictEqual(defaultConcurrency(1, 64 * GiB), 1); + }); + + it.effect( + "keeps weighted steps within the budget, in order, and serial steps one at a time", + () => + Effect.gen(function* () { + const startedAt: Record = {}; + let active = 0; + let maxActive = 0; + let serialActive = 0; + let maxSerial = 0; + const step = ( + name: string, + options: { weight?: number; serial?: boolean } = {}, + ): Step => { + const slots = Math.min(options.weight ?? 1, 3); + return { + name, + ...options, + run: Effect.gen(function* () { + startedAt[name] = (yield* Clock.currentTimeMillis) / 1000; + active += slots; + maxActive = Math.max(maxActive, active); + if (options.serial) maxSerial = Math.max(maxSerial, ++serialActive); + yield* Effect.sleep("1 second"); + active -= slots; + if (options.serial) serialActive--; + return { ok: true, output: "" }; + }), + }; + }; + const fiber = yield* runSteps( + [ + step("light 1"), + // Above the budget, so it holds every slot rather than never starting. + step("heavy", { weight: 5 }), + step("pair", { weight: 2 }), + step("light 2"), + step("test 1", { serial: true }), + step("test 2", { serial: true }), + ], + { concurrency: 3, timeoutSeconds: 60 }, + ).pipe(Effect.forkChild); + yield* TestClock.adjust("10 seconds"); + const results = yield* Fiber.join(fiber); + + assert.deepStrictEqual( + results.map((result) => result.outcome), + ["pass", "pass", "pass", "pass", "pass", "pass"], + ); + assert.strictEqual(maxActive, 3); + // Lighter steps queued behind the heavy one never start ahead of it. + assert.deepStrictEqual(startedAt, { + "light 1": 0, + heavy: 1, + pair: 2, + "light 2": 2, + "test 1": 3, + "test 2": 4, + }); + assert.strictEqual(maxSerial, 1); + }), + ); + + it.effect("interrupts a step at its timeout and reports TIMEOUT, apart from FAIL", () => + Effect.gen(function* () { + let interrupted = false; + const fiber = yield* runSteps( + [ + { + name: "hangs", + run: Effect.never.pipe( + Effect.onInterrupt(() => Effect.sync(() => (interrupted = true))), + ), + }, + { name: "fails", run: Effect.succeed({ ok: false, output: "error" }) }, + { name: "passes", run: Effect.succeed({ ok: true, output: "" }) }, + ], + { concurrency: 3, timeoutSeconds: 10 }, + ).pipe(Effect.forkChild); + yield* TestClock.adjust("9 seconds"); + assert.isFalse(interrupted); + yield* TestClock.adjust("1 second"); + const results = yield* Fiber.join(fiber); + + assert.isTrue(interrupted); + assert.deepStrictEqual( + results.map(({ name, outcome, time }) => [name, outcome, time]), + [ + ["hangs", "TIMEOUT", "killed after 10s"], + ["fails", "FAIL", "0.0s"], + ["passes", "pass", "0.0s"], + ], + ); + }), + ); + + it.effect("fails instead of returning an empty file list when git exits nonzero", () => { + const spawner = (exitCode: number) => + ChildProcessSpawner.make(() => + Effect.succeed( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.encodeText(Stream.make(exitCode === 0 ? "a.ts\nb.ts\n" : "")), + stderr: Stream.encodeText( + Stream.make(exitCode === 0 ? "" : "fatal: index file corrupt"), + ), + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }), + ), + ); + return Effect.gen(function* () { + const listed = yield* gitLines("/repo", ["ls-files"]).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner(0)), + ); + assert.deepStrictEqual(listed, ["a.ts", "b.ts"]); + const error = yield* gitLines("/repo", ["ls-files"]).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner(128)), + Effect.flip, + ); + assert.strictEqual( + error, + "check:changed: git ls-files exited with 128: fatal: index file corrupt", + ); + }); + }); +}); diff --git a/scripts/check-changed.ts b/scripts/check-changed.ts index b854cf0a4e539..dfa4f3a833bbe 100644 --- a/scripts/check-changed.ts +++ b/scripts/check-changed.ts @@ -1,4 +1,4 @@ -// @effect-diagnostics nodeBuiltinImport:off globalConsole:off +// @effect-diagnostics nodeBuiltinImport:off - hashes inputs with node:crypto and sizes the budget with node:os. // Runs CI's fast checks for this branch's changes: format and lint of the // changed files, knip, generated GraphQL operations, typecheck of the affected // packages and their dependents, the test files beside the changed files, and @@ -7,369 +7,551 @@ // A dependency change also gets the unused-patch install check below. CI still // runs the full test suites and the jobs listed in the summary. // -// vp run check:changed compare against the merge base with origin/main -// vp run check:changed compare against the merge base with +// vp run check:changed compare against the merge base with origin/main +// vp run check:changed compare against the merge base with +// vp run check:changed --concurrency 1 run the steps one at a time // // Uncommitted and untracked files count. Affected packages come from // .github/scripts/ci-changes.cjs, the same mapping CI uses to gate its jobs. -// The steps run side by side; each prints its output when it finishes. A -// rerun on exactly the files of the last passing run prints that run's summary. -import * as NodeChildProcess from "node:child_process"; +// The steps run side by side within a budget derived from the machine's cores +// and available memory, and each prints its output when it finishes. A step +// running past the timeout is killed with its process group and reported as +// TIMEOUT. A rerun on exactly the files of the last passing run prints that +// run's summary. import * as NodeCrypto from "node:crypto"; -import * as NodeFS from "node:fs"; import * as NodeOS from "node:os"; -import * as NodePath from "node:path"; + +import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Clock from "effect/Clock"; +import * as Config from "effect/Config"; +import * as Console from "effect/Console"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import type * as PlatformError from "effect/PlatformError"; +import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; +import * as Stream from "effect/Stream"; +import { Argument, Command, Flag } from "effect/cli"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; + import { decide, readWorkspace } from "../.github/scripts/ci-changes.cjs"; -const root = NodePath.resolve(import.meta.dirname, ".."); +const GiB = 1024 ** 3; + +// A typecheck or test step can take several cores and gigabytes of memory, so +// allow one step per two cores and per 6 GiB of available memory. +export const defaultConcurrency = (cores: number, availableBytes: number) => + Math.max(1, Math.min(Math.floor(cores / 2), Math.floor(availableBytes / (6 * GiB)))); + +export type Outcome = "pass" | "FAIL" | "TIMEOUT"; + +export interface Step { + readonly name: string; + readonly run: Effect.Effect<{ readonly ok: boolean; readonly output: string }, never, R>; + // Budget slots the step holds: one per worker it runs in parallel. + readonly weight?: number; + // Vitest runs started together race to rebuild node_modules/.vitest-cache (ENOTEMPTY). + readonly serial?: boolean; +} + +// Interrupting a step at its timeout closes the scopes of the processes it +// spawned, which kills each one's process group. +export const runSteps = Effect.fn("checkChanged.runSteps")(function* ( + steps: ReadonlyArray>, + options: { readonly concurrency: number; readonly timeoutSeconds: number }, +) { + const budget = yield* Semaphore.make(options.concurrency); + // Steps claim budget one at a time, in order: Semaphore lets a light request + // take free slots ahead of a waiting heavier one, which would delay typecheck. + const admission = yield* Semaphore.make(1); + const serial = yield* Semaphore.make(1); + return yield* Effect.forEach( + steps, + (step) => { + const timed = Effect.gen(function* () { + const started = yield* Clock.currentTimeMillis; + const result = yield* Effect.timeoutOption(step.run, `${options.timeoutSeconds} seconds`); + const seconds = ((yield* Clock.currentTimeMillis) - started) / 1000; + const outcome: Outcome = Option.match(result, { + onNone: () => "TIMEOUT", + onSome: ({ ok }) => (ok ? "pass" : "FAIL"), + }); + const time = + outcome === "TIMEOUT" + ? `killed after ${options.timeoutSeconds}s` + : `${seconds.toFixed(1)}s`; + yield* Console.log(`\n> vp ${step.name} ${outcome} ${time}`); + const output = Option.getOrUndefined(result)?.output.trimEnd(); + if (output) yield* Console.log(output); + return { name: step.name, outcome, time }; + }); + const slots = Math.min(step.weight ?? 1, options.concurrency); + const limited = Effect.acquireUseRelease( + admission.withPermit(budget.take(slots)), + () => timed, + () => budget.release(slots), + ); + return step.serial ? serial.withPermit(limited) : limited; + }, + { concurrency: "unbounded" }, + ); +}); + +const CacheEntry = Schema.fromJsonString( + Schema.Struct({ key: Schema.String, summary: Schema.Array(Schema.String) }), +); +const decodeCacheEntry = Schema.decodeEffect(CacheEntry); +const encodeCacheEntry = Schema.encodeEffect(CacheEntry); +const decodeRootPackageJson = Schema.decodeEffect( + Schema.fromJsonString(Schema.Struct({ scripts: Schema.Struct({ "knip:check": Schema.String }) })), +); + +const collectBytes = (stream: Stream.Stream) => + Stream.runCollect(stream).pipe(Effect.map((chunks) => Buffer.concat(chunks))); + +// Fails on a nonzero exit: an empty file list from a broken index would +// otherwise pass as "no changes". quotePath=false keeps non-ASCII paths as real +// paths instead of quoted escapes. +export const git = Effect.fn("checkChanged.git")(function* ( + cwd: string, + args: ReadonlyArray, +) { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + return yield* Effect.scoped( + Effect.gen(function* () { + const handle = yield* spawner.spawn( + ChildProcess.make("git", ["-c", "core.quotePath=false", ...args], { cwd }), + ); + const [stdout, stderr, exitCode] = yield* Effect.all( + [collectBytes(handle.stdout), collectBytes(handle.stderr), handle.exitCode], + { concurrency: "unbounded" }, + ); + if (exitCode !== 0) { + return yield* Effect.fail( + `check:changed: git ${args.join(" ")} exited with ${exitCode}: ${stderr.toString().trim()}`, + ); + } + return stdout; + }), + ); +}); +export const gitLines = (cwd: string, args: ReadonlyArray) => + git(cwd, args).pipe(Effect.map((stdout) => stdout.toString().split("\n").filter(Boolean))); + const CODE = /\.[cm]?[jt]sx?$/; +const TEST = /\.test\.[cm]?[jt]sx?$/; +const escapeRegExp = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -// quotePath=false keeps non-ASCII paths as real paths instead of quoted escapes. -const git = (...args: Array) => - NodeChildProcess.execFileSync("git", ["-c", "core.quotePath=false", ...args], { - cwd: root, - encoding: "utf8", - maxBuffer: 64 * 1024 * 1024, - }) - .split("\n") - .filter(Boolean); - -const ref = process.argv[2] ?? "origin/main"; -const mergeBase = NodeChildProcess.spawnSync("git", ["merge-base", "HEAD", ref], { - cwd: root, - encoding: "utf8", +// A flag wins over its environment variable; either must be a positive integer. +const override = Effect.fn("checkChanged.override")(function* ( + flagName: string, + flag: Option.Option, + envName: string, +) { + const [name, value] = Option.isSome(flag) + ? [`--${flagName}`, flag] + : [envName, yield* Config.option(Config.Int(envName))]; + if (Option.isSome(value) && value.value < 1) { + return yield* Effect.fail(`check:changed: ${name} must be a positive integer.`); + } + return value; }); -if (mergeBase.status !== 0) { - console.error( - `check:changed: no merge base with ${ref}. Run \`git fetch origin\` or pass a ref.`, + +const checkChanged = Effect.fn("checkChanged")(function* (input: { + readonly ref: string; + readonly concurrency: Option.Option; + readonly timeout: Option.Option; +}) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const root = yield* path.fromFileUrl(new URL("..", import.meta.url)); + const inRoot = (file: string) => path.join(root, file); + + // macOS counts its file cache as used, so available memory there would + // starve a large Mac. Elsewhere availableMemory() honors a cgroup limit. + const platform = yield* HostProcess.Platform; + const concurrency = Option.getOrElse( + yield* override("concurrency", input.concurrency, "CHECK_CHANGED_CONCURRENCY"), + () => + defaultConcurrency( + NodeOS.availableParallelism(), + platform === "darwin" ? NodeOS.totalmem() : process.availableMemory(), + ), ); - process.exit(1); -} -const base = mergeBase.stdout.trim(); -// --no-renames lists a rename as its old and new path, as CI does. -const untracked = git("ls-files", "--others", "--exclude-standard"); -const files = [ - ...new Set([...git("diff", "--name-only", "--no-renames", base, "--"), ...untracked]), -].sort(); - -if (files.length === 0) { - console.log(`check:changed: no changes since ${base.slice(0, 12)}.`); - process.exit(0); -} -console.log(`check:changed: ${files.length} files since ${base.slice(0, 12)}`); - -// Ignored generated sources, declarations, env files, and install state affect check results. -// Include them in the key, but skip large ignored folders that no check reads. -// Recompute after a passing run so edits made during it are never cached as passing. -const inputKey = () => { - const hash = NodeCrypto.createHash("sha256"); - // CI changes test behavior (vite.config.ts rejects .only under CI). - hash.update(`${process.version}\0${base}\0${process.env.CI ?? ""}\0`); - hash.update( - NodeChildProcess.execFileSync( - "git", - ["diff", "--binary", "--no-renames", "--no-ext-diff", "--no-textconv", base, "--"], - { cwd: root, maxBuffer: 1024 * 1024 * 1024 }, - ), + const timeoutSeconds = Option.getOrElse( + yield* override("timeout", input.timeout, "CHECK_CHANGED_TIMEOUT"), + () => 900, ); - const ignored = git( - "ls-files", - "--others", - "--ignored", - "--exclude-standard", - "--", - ":(glob)**/.generated/**", - ":(glob)**/.astro/**", - ":(glob)**/*.d.ts", - ":(glob)**/.env*", - ":(exclude,glob)**/node_modules/**", + + const lines = (...args: Array) => gitLines(root, args); + + const base = yield* git(root, ["merge-base", "HEAD", input.ref]).pipe( + Effect.map((stdout) => stdout.toString().trim()), + Effect.mapError( + () => + `check:changed: no merge base with ${input.ref}. Run \`git fetch origin\` or pass a ref.`, + ), ); - for (const file of [ - // Raw bytes of changed files too: .gitattributes normalizes line endings in - // the diff, but the formatter reads the file as it is on disk. - ...git("diff", "--name-only", "--no-renames", base, "--"), - ...git("ls-files", "--others", "--exclude-standard"), - ...ignored, - "node_modules/.modules.yaml", - "node_modules/.pnpm/lock.yaml", - ]) { - hash.update(`\0${file}\0`); - const path = NodePath.join(root, file); - // Untracked nested repositories are listed as directories. - if (NodeFS.statSync(path, { throwIfNoEntry: false })?.isFile()) { - hash.update(NodeFS.readFileSync(path)); - } + // --no-renames lists a rename as its old and new path, as CI does. + const changedFiles = lines("diff", "--name-only", "--no-renames", base, "--"); + const untrackedFiles = lines("ls-files", "--others", "--exclude-standard"); + const files = [...new Set([...(yield* changedFiles), ...(yield* untrackedFiles)])].sort(); + + if (files.length === 0) { + yield* Console.log(`check:changed: no changes since ${base.slice(0, 12)}.`); + return true; } - return hash.digest("hex"); -}; -const key = inputKey(); -const cachePath = NodePath.join(root, "node_modules/.cache/check-changed.json"); -// A missing or unreadable cache is a miss, never a failure. -const readCache = () => { - try { - return JSON.parse(NodeFS.readFileSync(cachePath, "utf8")) as { - key: string; - summary: Array; - }; - } catch { - return undefined; + yield* Console.log(`check:changed: ${files.length} files since ${base.slice(0, 12)}`); + + // Ignored generated sources, declarations, env files, and install state affect check results. + // Include them in the key, but skip large ignored folders that no check reads. + // Recompute after a passing run so edits made during it are never cached as passing. + const ci = Option.getOrElse(yield* Config.option(Config.String("CI")), () => ""); + const inputKey = Effect.gen(function* () { + const hash = NodeCrypto.createHash("sha256"); + // CI changes test behavior (vite.config.ts rejects .only under CI). + hash.update(`${process.version}\0${base}\0${ci}\0`); + hash.update( + yield* git(root, [ + "diff", + "--binary", + "--no-renames", + "--no-ext-diff", + "--no-textconv", + base, + "--", + ]), + ); + const ignored = yield* lines( + "ls-files", + "--others", + "--ignored", + "--exclude-standard", + "--", + ":(glob)**/.generated/**", + ":(glob)**/.astro/**", + ":(glob)**/*.d.ts", + ":(glob)**/.env*", + ":(exclude,glob)**/node_modules/**", + ); + for (const file of [ + // Raw bytes of changed files too: .gitattributes normalizes line endings in + // the diff, but the formatter reads the file as it is on disk. + ...(yield* changedFiles), + ...(yield* untrackedFiles), + ...ignored, + "node_modules/.modules.yaml", + "node_modules/.pnpm/lock.yaml", + ]) { + hash.update(`\0${file}\0`); + // Untracked nested repositories are listed as directories. + const info = yield* Effect.option(fs.stat(inRoot(file))); + if (Option.isSome(info) && info.value.type === "File") { + hash.update(yield* fs.readFile(inRoot(file))); + } + } + return hash.digest("hex"); + }); + const key = yield* inputKey; + const cachePath = inRoot("node_modules/.cache/check-changed.json"); + // A missing or unreadable cache is a miss, never a failure. + const cached = yield* fs + .readFileString(cachePath) + .pipe(Effect.flatMap(decodeCacheEntry), Effect.option); + if (Option.isSome(cached) && cached.value.key === key) { + yield* Console.log("Nothing changed since the last passing run.\n"); + for (const line of cached.value.summary) yield* Console.log(line); + return true; } -}; -const cached = readCache(); -if (cached?.key === key) { - console.log("Nothing changed since the last passing run.\n"); - for (const line of cached.summary) console.log(line); - process.exit(0); -} -const present = files.filter((file) => NodeFS.existsSync(NodePath.join(root, file))); -const code = present.filter((file) => CODE.test(file)); -const packages = readWorkspace(); -const { affected, outputs } = decide(files, packages, false); + const present = yield* Effect.filter(files, (file) => fs.exists(inRoot(file))); + const code = present.filter((file) => CODE.test(file)); + const packages = readWorkspace(); + const { affected, outputs } = decide(files, packages, false); -// Changed test files, and the test files beside a changed source file -// (foo.ts -> foo.test.ts, foo.browser.test.tsx). Vitest's import-graph -// `related` reaches most of a package: one leaf server file pulled in 252 of -// 406 server test files and took 7 minutes. CI runs the rest. -const TEST = /\.test\.[cm]?[jt]sx?$/; -const tests = new Set(code.filter((file) => TEST.test(file))); -for (const file of code) { - const dir = NodePath.dirname(file); - const prefix = `${NodePath.basename(file).replace(CODE, "")}.`; - for (const entry of NodeFS.readdirSync(NodePath.join(root, dir))) { - if (entry.startsWith(prefix) && TEST.test(entry)) tests.add(NodePath.join(dir, entry)); + // Changed test files, and the test files beside a changed source file + // (foo.ts -> foo.test.ts, foo.browser.test.tsx). Vitest's import-graph + // `related` reaches most of a package: one leaf server file pulled in 252 of + // 406 server test files and took 7 minutes. CI runs the rest. + const tests = new Set(code.filter((file) => TEST.test(file))); + for (const file of code) { + const dir = path.dirname(file); + const prefix = `${path.basename(file).replace(CODE, "")}.`; + for (const entry of yield* fs.readDirectory(inRoot(dir))) { + if (entry.startsWith(prefix) && TEST.test(entry)) tests.add(path.join(dir, entry)); + } } -} -// It reads files other than the ones beside it, so no changed file selects it. -if (affected.includes("t3")) tests.add("apps/server/src/provider/AgentContextBudget.test.ts"); + // It reads files other than the ones beside it, so no changed file selects it. + if (affected.includes("t3")) tests.add("apps/server/src/provider/AgentContextBudget.test.ts"); -// React Compiler coverage compiles every client source file, so run only the -// changed files' cases, in one extra step: a -t filter in the main test step -// would drop every other test. An app is skipped when the main step already -// runs its coverage file unfiltered. File filters mirror each coverage test. -const escapeRegExp = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -const compilerApps = [ - { - test: "apps/web/src/reactCompilerCoverage.test.ts", - root: "apps/web/src/", - // Test names keep the repo-relative path. - name: (file: string) => file, - compiled: (file: string) => - /\.tsx?$/.test(file) && !/\.(test|browser)\.tsx?$/.test(file) && !file.endsWith(".gen.ts"), - // Web has only per-file cases. - always: [], - }, - { - test: "apps/mobile/src/reactCompilerCoverage.test.ts", - root: "apps/mobile/src/", - name: (file: string) => file.slice("apps/mobile/".length), - compiled: (file: string) => /\.tsx?$/.test(file) && !/\.(test\.tsx?|d\.ts)$/.test(file), - // The Metro, cache, and stale-allowlist cases check more than one file, deletions included. - always: ["^(?!.*compiles )"], - }, -].flatMap(({ test, root: appRoot, name, compiled, always }) => { - const changed = files.filter((file) => file.startsWith(appRoot) && compiled(file)); - if (changed.length === 0 || tests.has(test)) return []; - const names = changed - .filter((file) => present.includes(file)) - .map((file) => `compiles ${escapeRegExp(name(file))}$`); - const pattern = [...names, ...always]; - return pattern.length > 0 ? [{ test, names, pattern }] : []; -}); -const compilerCoverage = compilerApps.length > 0 && { - name: `react compiler (${compilerApps.reduce((count, app) => count + app.names.length, 0)} files)`, - args: [ - "test", - "run", - ...compilerApps.map((app) => app.test), - "-t", - compilerApps.flatMap((app) => app.pattern).join("|"), - ], -}; - -// knip:check cannot be scoped to a package. Any code change can leave a file, -// export, or dependency unused (removing the last import of a helper does), so -// it runs whenever code or a manifest changes. -const runKnip = files.some( - (file) => CODE.test(file) || NodePath.basename(file) === "package.json" || file === "knip.jsonc", -); -// CI runs knip:check as one script of `knip ... && knip ...` passes. The passes -// do not depend on each other, so they run side by side here. -const knipCheck: string = JSON.parse( - NodeFS.readFileSync(NodePath.join(root, "package.json"), "utf8"), -).scripts["knip:check"]; -const knipPasses = knipCheck.split(" && ").map((command, index, all) => { - const [bin, ...args] = command.trim().split(/\s+/); - if (bin !== "knip" || /["'$\\|;&<>]/.test(command)) { - throw new Error(`check:changed cannot split knip:check: ${command}`); + // React Compiler coverage compiles every client source file, so run only the + // changed files' cases, in one extra step: a -t filter in the main test step + // would drop every other test. An app is skipped when the main step already + // runs its coverage file unfiltered. File filters mirror each coverage test. + const compilerApps = [ + { + test: "apps/web/src/reactCompilerCoverage.test.ts", + root: "apps/web/src/", + // Test names keep the repo-relative path. + name: (file: string) => file, + compiled: (file: string) => + /\.tsx?$/.test(file) && !/\.(test|browser)\.tsx?$/.test(file) && !file.endsWith(".gen.ts"), + // Web has only per-file cases. + always: [], + }, + { + test: "apps/mobile/src/reactCompilerCoverage.test.ts", + root: "apps/mobile/src/", + name: (file: string) => file.slice("apps/mobile/".length), + compiled: (file: string) => /\.tsx?$/.test(file) && !/\.(test\.tsx?|d\.ts)$/.test(file), + // The Metro, cache, and stale-allowlist cases check more than one file, deletions included. + always: ["^(?!.*compiles )"], + }, + ].flatMap(({ test, root: appRoot, name, compiled, always }) => { + const changed = files.filter((file) => file.startsWith(appRoot) && compiled(file)); + if (changed.length === 0 || tests.has(test)) return []; + const names = changed + .filter((file) => present.includes(file)) + .map((file) => `compiles ${escapeRegExp(name(file))}$`); + const pattern = [...names, ...always]; + return pattern.length > 0 ? [{ test, names, pattern }] : []; + }); + + // knip:check cannot be scoped to a package. Any code change can leave a file, + // export, or dependency unused (removing the last import of a helper does), so + // it runs whenever code or a manifest changes. + const runKnip = files.some( + (file) => CODE.test(file) || path.basename(file) === "package.json" || file === "knip.jsonc", + ); + // CI runs knip:check as one script of `knip ... && knip ...` passes. The passes + // do not depend on each other, so they run side by side here. + const rootPackage = yield* fs + .readFileString(inRoot("package.json")) + .pipe(Effect.flatMap(decodeRootPackageJson), Effect.orDie); + const knipCheck = rootPackage.scripts["knip:check"]; + const knipPasses: Array> = []; + for (const command of knipCheck.split(" && ")) { + const [bin, ...args] = command.trim().split(/\s+/); + if (bin !== "knip" || /["'$\\|;&<>]/.test(command)) { + return yield* Effect.fail(`check:changed cannot split knip:check: ${command}`); + } + knipPasses.push(["exec", "knip", ...args]); } - return { name: `knip ${index + 1}/${all.length}`, args: ["exec", "knip", ...args] }; -}); -// A version bump can leave a patch unused, causing pnpm to reject the install -// with ERR_PNPM_UNUSED_PATCH. Check it here as Release Smoke does in CI. -const runPatchCheck = files.some( - (file) => - file === "pnpm-workspace.yaml" || - file === "pnpm-lock.yaml" || - file === ".pnpmfile.cjs" || - file.startsWith("patches/") || - file.startsWith("apps/mobile/deps/") || - NodePath.basename(file) === "package.json", -); + // A version bump can leave a patch unused, causing pnpm to reject the install + // with ERR_PNPM_UNUSED_PATCH. Check it here as Release Smoke does in CI. + const runPatchCheck = files.some( + (file) => + file === "pnpm-workspace.yaml" || + file === "pnpm-lock.yaml" || + file === ".pnpmfile.cjs" || + file.startsWith("patches/") || + file.startsWith("apps/mobile/deps/") || + path.basename(file) === "package.json", + ); + + // Output is piped, so keep the colors a terminal would get. + const env = process.stdout.isTTY ? { FORCE_COLOR: "1" } : {}; + const vp = (args: ReadonlyArray, cwd = root) => + Effect.scoped( + Effect.gen(function* () { + const handle = yield* spawner.spawn( + ChildProcess.make("vp", args, { cwd, env, extendEnv: true, forceKillAfter: "5 seconds" }), + ); + const [output, exitCode] = yield* Effect.all( + [Stream.mkString(Stream.decodeText(handle.all)), handle.exitCode], + { concurrency: 2 }, + ); + return { ok: exitCode === 0, output }; + }), + ).pipe(Effect.catch((error) => Effect.succeed({ ok: false, output: error.message }))); -// Resolve without the lockfile in a temp copy to preserve the working tree and lockfile. -// Copy mobile modules too: they are file: dependencies, not workspace packages. -// Cached registry metadata limits this to patches stranded by local changes, not registry drift. -const checkPatches = (): boolean => { - const temp = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-patch-check-")); - try { - const copy = (relative: string) => { - const dest = NodePath.join(temp, relative); - NodeFS.mkdirSync(NodePath.dirname(dest), { recursive: true }); - NodeFS.cpSync(NodePath.join(root, relative), dest, { recursive: true }); - }; - copy("package.json"); - copy("pnpm-workspace.yaml"); - for (const pkg of packages) copy(`${pkg.dir}/package.json`); - const modulesDir = NodePath.join(root, "apps/mobile/modules"); - if (NodeFS.existsSync(modulesDir)) { - for (const entry of NodeFS.readdirSync(modulesDir)) { - const manifest = `apps/mobile/modules/${entry}/package.json`; - if (NodeFS.existsSync(NodePath.join(root, manifest))) copy(manifest); + // Resolve without the lockfile in a temp copy to preserve the working tree and lockfile. + // Copy mobile modules too: they are file: dependencies, not workspace packages. + // Cached registry metadata limits this to patches stranded by local changes, not registry drift. + const checkPatches = Effect.scoped( + Effect.gen(function* () { + const temp = yield* fs.makeTempDirectoryScoped({ prefix: "t3-patch-check-" }); + const copy = Effect.fnUntraced(function* (relative: string) { + const dest = path.join(temp, relative); + yield* fs.makeDirectory(path.dirname(dest), { recursive: true }); + yield* fs.copy(inRoot(relative), dest); + }); + yield* copy("package.json"); + yield* copy("pnpm-workspace.yaml"); + for (const pkg of packages) yield* copy(`${pkg.dir}/package.json`); + const modulesDir = "apps/mobile/modules"; + if (yield* fs.exists(inRoot(modulesDir))) { + for (const entry of yield* fs.readDirectory(inRoot(modulesDir))) { + const manifest = `${modulesDir}/${entry}/package.json`; + if (yield* fs.exists(inRoot(manifest))) yield* copy(manifest); + } } - } - for (const extra of ["apps/mobile/deps", "patches", ".pnpmfile.cjs"]) { - if (NodeFS.existsSync(NodePath.join(root, extra))) copy(extra); - } - const { status, stdout, stderr, error } = NodeChildProcess.spawnSync( - "vp", - ["install", "--lockfile-only", "--ignore-scripts"], - { cwd: temp, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }, - ); - if (status === 0) return true; - if (stdout) console.log(stdout); - if (stderr) console.error(stderr); - if (error) console.error(error.message); - if (`${stdout ?? ""}${stderr ?? ""}`.includes("ERR_PNPM_UNUSED_PATCH")) { - console.error( - "Unused dependency patches: remove each patch named above from " + + for (const extra of ["apps/mobile/deps", "patches", ".pnpmfile.cjs"]) { + if (yield* fs.exists(inRoot(extra))) yield* copy(extra); + } + const result = yield* vp(["install", "--lockfile-only", "--ignore-scripts"], temp); + if (result.ok || !result.output.includes("ERR_PNPM_UNUSED_PATCH")) return result; + return { + ok: false, + output: + `${result.output}\nUnused dependency patches: remove each patch named above from ` + "patchedDependencies in pnpm-workspace.yaml and from patches/, " + "update it to the version the install resolves, " + "or pin the dependency that pulls it in to the patched version.", - ); - } - return false; - } finally { - NodeFS.rmSync(temp, { recursive: true, force: true }); - } -}; + }; + }), + ).pipe(Effect.catch((error) => Effect.succeed({ ok: false, output: error.message }))); -// CI's Lint job checks that generated GraphQL operations match their sources. -const graphql = ["apps/server", "packages/source-control-github"].filter((dir) => - files.some((file) => file.startsWith(`${dir}/`)), -); + // CI's Lint job checks that generated GraphQL operations match their sources. + const graphql = ["apps/server", "packages/source-control-github"].filter((dir) => + files.some((file) => file.startsWith(`${dir}/`)), + ); + const filters = (names: ReadonlyArray) => names.flatMap((name) => ["--filter", name]); + const typecheckWorkers = Math.min(concurrency, affected.length); + const command = (name: string, args: ReadonlyArray) => ({ name, run: vp(args) }); + const compilerFiles = compilerApps.reduce((count, app) => count + app.names.length, 0); -const filters = (names: ReadonlyArray) => names.flatMap((name) => ["--filter", name]); -const steps = [ - // Runs first; it takes about a second. - runPatchCheck && { name: "unused patches", run: checkPatches }, - present.length > 0 && { - name: "format", - args: ["fmt", "--check", "--no-error-on-unmatched-pattern", ...present], - }, - code.length > 0 && { name: "lint", args: ["lint", ...code] }, - ...(runKnip ? knipPasses : []), - ...graphql.map((dir) => ({ - name: `graphql (${dir})`, - args: ["run", "--filter", `./${dir}`, "generate", "--check"], - })), - affected.length > 0 && { - name: `typecheck (${affected.length} packages)`, - // `tsc --noEmit` writes nothing another package reads, so dependency order - // only made dependents wait: --parallel cut a contracts change from 13 s to 9 s. - args: [ - "run", - "--cache", - "--parallel", - "--concurrency-limit", - "4", - ...filters(affected), - "typecheck", - ], - }, - // From the repo root, the root vite.config.ts hands each file to its package's config. - tests.size > 0 && { - name: `test (${tests.size} files)`, - args: ["test", "run", "--passWithNoTests", ...tests], - }, - compilerCoverage, -].filter((step) => step !== false); - -// Output is piped, so keep the colors a terminal would get. -const env = process.stdout.isTTY ? { ...process.env, FORCE_COLOR: "1" } : process.env; -const runStep = (step: (typeof steps)[number]) => - new Promise<{ name: string; ok: boolean; seconds: string }>((resolve) => { - const started = performance.now(); - const finish = (ok: boolean, output?: Buffer) => { - const seconds = ((performance.now() - started) / 1000).toFixed(1); - console.log(`\n> vp ${step.name} ${ok ? "pass" : "FAIL"} ${seconds}s`); - if (output) process.stdout.write(output); - resolve({ name: step.name, ok, seconds }); - }; - // In-process steps print their own output. The patch check is first and - // takes about a second, so the commands start right after it. - if ("run" in step) return finish(step.run()); - const output: Array = []; - const child = NodeChildProcess.spawn("vp", step.args, { cwd: root, env }); - child.stdout.on("data", (chunk: Buffer) => output.push(chunk)); - child.stderr.on("data", (chunk: Buffer) => output.push(chunk)); - // A failed spawn emits "error", then "close" with a nonzero code. - child.on("error", (error) => output.push(Buffer.from(`${error.message}\n`))); - child.on("close", (status) => finish(status === 0, Buffer.concat(output))); - }); + const steps: Array> = [ + ...(runPatchCheck ? [{ name: "unused patches", run: checkPatches }] : []), + ...(present.length > 0 + ? [command("format", ["fmt", "--check", "--no-error-on-unmatched-pattern", ...present])] + : []), + ...(code.length > 0 ? [command("lint", ["lint", ...code])] : []), + ...(runKnip + ? knipPasses.map((args, index) => command(`knip ${index + 1}/${knipPasses.length}`, args)) + : []), + ...graphql.map((dir) => + command(`graphql (${dir})`, ["run", "--filter", `./${dir}`, "generate", "--check"]), + ), + ...(affected.length > 0 + ? [ + { + // `tsc --noEmit` writes nothing another package reads, so dependency order + // only made dependents wait: --parallel cut a contracts change from 13 s to 9 s. + ...command(`typecheck (${affected.length} packages)`, [ + "run", + "--cache", + "--parallel", + "--concurrency-limit", + String(typecheckWorkers), + ...filters(affected), + "typecheck", + ]), + weight: typecheckWorkers, + }, + ] + : []), + // From the repo root, the root vite.config.ts hands each file to its package's config. + ...(tests.size > 0 + ? [ + { + ...command(`test (${tests.size} files)`, [ + "test", + "run", + "--passWithNoTests", + ...tests, + ]), + serial: true, + }, + ] + : []), + ...(compilerApps.length > 0 + ? [ + { + ...command(`react compiler (${compilerFiles} files)`, [ + "test", + "run", + ...compilerApps.map((app) => app.test), + "-t", + compilerApps.flatMap((app) => app.pattern).join("|"), + ]), + serial: true, + }, + ] + : []), + ]; -// Vitest runs started together race to rebuild node_modules/.vitest-cache after -// an install (ENOTEMPTY), so they run one after another. -let previousVitest: Promise = Promise.resolve(); -const results = await Promise.all( - steps.map((step) => { - if (!("args" in step) || step.args[0] !== "test") return runStep(step); - const result = previousVitest.then(() => runStep(step)); - previousVitest = result; - return result; - }), -); + const results = yield* runSteps(steps, { concurrency, timeoutSeconds }); -const summary = ["check:changed summary"]; -for (const result of results) { - summary.push(` ${result.ok ? "pass" : "FAIL"} ${result.name} ${result.seconds}s`); -} -const ciOnly = Object.entries({ - "full test suites": outputs.test || outputs.test_web || outputs.test_server, - build: outputs.build, - rust: outputs.rust, - "mobile native lint": outputs.mobile_native, - "release smoke": outputs.release_smoke, -}).flatMap(([job, runs]) => (runs ? [job] : [])); -if (ciOnly.length > 0) summary.push(` CI also runs: ${ciOnly.join(", ")}`); -if (!runPatchCheck) summary.push(" unused patch check skipped: no dependency files changed"); -if (!runKnip) summary.push(" knip skipped: no code or manifest changed"); -console.log(`\n${summary.join("\n")}`); -// exitCode, not exit(): piped stdout is asynchronous on macOS, and exit() -// would cut off a failing step's output. -if (results.some((result) => !result.ok)) { - process.exitCode = 1; -} else if (inputKey() !== key) { - console.log(" pass not cached: files changed during the run"); -} else { - try { - // Write then rename, so a concurrent run never reads half a file. - const temp = `${cachePath}.${process.pid}`; - NodeFS.mkdirSync(NodePath.dirname(cachePath), { recursive: true }); - NodeFS.writeFileSync(temp, JSON.stringify({ key, summary })); - NodeFS.renameSync(temp, cachePath); - } catch (error) { - console.warn(` pass not cached: ${error instanceof Error ? error.message : String(error)}`); + const summary = ["check:changed summary"]; + for (const result of results) { + summary.push(` ${result.outcome} ${result.name} ${result.time}`); + } + if (results.some((result) => result.outcome === "TIMEOUT")) { + summary.push( + ` TIMEOUT: ran past ${timeoutSeconds}s and was killed; this is not a check failure. ` + + "Raise --timeout or lower --concurrency.", + ); + } + const ciOnly = Object.entries({ + "full test suites": outputs.test || outputs.test_web || outputs.test_server, + build: outputs.build, + rust: outputs.rust, + "mobile native lint": outputs.mobile_native, + "release smoke": outputs.release_smoke, + }).flatMap(([job, runs]) => (runs ? [job] : [])); + if (ciOnly.length > 0) summary.push(` CI also runs: ${ciOnly.join(", ")}`); + if (!runPatchCheck) summary.push(" unused patch check skipped: no dependency files changed"); + if (!runKnip) summary.push(" knip skipped: no code or manifest changed"); + yield* Console.log(`\n${summary.join("\n")}`); + + if (results.some((result) => result.outcome !== "pass")) return false; + if ((yield* inputKey) !== key) { + yield* Console.log(" pass not cached: files changed during the run"); + return true; } + // Write then rename, so a concurrent run never reads half a file. + const temp = `${cachePath}.${process.pid}`; + yield* Effect.gen(function* () { + yield* fs.makeDirectory(path.dirname(cachePath), { recursive: true }); + yield* fs.writeFileString(temp, yield* encodeCacheEntry({ key, summary })); + yield* fs.rename(temp, cachePath); + }).pipe(Effect.catch((error) => Console.warn(` pass not cached: ${error.message}`))); + return true; +}); + +export const checkChangedCommand = Command.make( + "check-changed", + { + ref: Argument.String("ref").pipe( + Argument.withDescription("Compare against the merge base with this ref."), + Argument.withDefault("origin/main"), + ), + concurrency: Flag.Int("concurrency").pipe( + Flag.withDescription( + "Budget of parallel steps and typecheck workers; also CHECK_CHANGED_CONCURRENCY. Defaults to one per two cores and per 6 GiB of available memory.", + ), + Flag.optional, + ), + timeout: Flag.Int("timeout").pipe( + Flag.withDescription( + "Seconds before a step is killed; also CHECK_CHANGED_TIMEOUT. Defaults to 900.", + ), + Flag.optional, + ), + }, + (input) => + checkChanged(input).pipe( + Effect.catch((message) => Console.error(message).pipe(Effect.as(false))), + // exitCode, not a failed exit: runMain calls process.exit() on failure, and + // piped stdout is asynchronous on macOS, so it would cut off step output. + Effect.flatMap((ok) => + Effect.sync(() => { + if (!ok) process.exitCode = 1; + }), + ), + ), +).pipe(Command.withDescription("Run CI's fast checks for this branch's changes.")); + +if (import.meta.main) { + Command.run(checkChangedCommand, { version: "0.0.0" }).pipe( + Effect.provide(NodeServices.layer), + NodeRuntime.runMain, + ); } From c8a606c7b73e1e3586d5c06f76c69525f2d4c679 Mon Sep 17 00:00:00 2001 From: maria Date: Fri, 30 Oct 2026 02:36:46 +0000 Subject: [PATCH 396/817] fix(shared): durations under 10s drop a trailing .0 (#27316) --- apps/mobile/src/lib/threadActivity.test.ts | 12 ++++++------ apps/server/src/cli/trace.ts | 4 ++-- .../components/chat/MessagesTimeline.logic.test.ts | 12 ++++++------ .../chat/WorktreeSetupCard.browser.test.tsx | 10 +++++----- .../src/components/settings/DiagnosticsSettings.tsx | 8 ++++---- .../settings/ResourceTelemetryDiagnostics.tsx | 12 ++++++------ packages/shared/src/orchestrationTiming.ts | 5 +---- 7 files changed, 30 insertions(+), 33 deletions(-) diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts index 96626a5caefab..409631131c058 100644 --- a/apps/mobile/src/lib/threadActivity.test.ts +++ b/apps/mobile/src/lib/threadActivity.test.ts @@ -846,7 +846,7 @@ describe("buildThreadFeed", () => { expect(collapsed[1]).toMatchObject({ type: "run-fold", createdAt: "2026-06-20T00:00:01.500Z", - label: "Worked for 2.0s", + label: "Worked for 2s", }); const expanded = deriveThreadFeedPresentation(feed, latestRun, new Set([runId])); @@ -1100,10 +1100,10 @@ describe("buildThreadFeed", () => { const settled = deriveThreadFeedPresentation(feed(false), null, new Set()); expect(shape(settled)).toEqual([ "user:launch", - "fold:Worked for 8.0s", + "fold:Worked for 8s", "assistant:launch-answer", "user:resume", - "fold:Worked for 8.0s", + "fold:Worked for 8s", "assistant:resume-answer", ]); const launchFold = settled.find((entry) => entry.type === "run-fold"); @@ -1112,11 +1112,11 @@ describe("buildThreadFeed", () => { shape(deriveThreadFeedPresentation(feed(false), null, new Set([launchFold.runId]))), ).toEqual([ "user:launch", - "fold:Worked for 8.0s", + "fold:Worked for 8s", "activity-group", "assistant:launch-answer", "user:resume", - "fold:Worked for 8.0s", + "fold:Worked for 8s", "assistant:resume-answer", ]); @@ -1133,7 +1133,7 @@ describe("buildThreadFeed", () => { ), ).toEqual([ "user:launch", - "fold:Worked for 8.0s", + "fold:Worked for 8s", "assistant:launch-answer", "user:resume", "activity-group", diff --git a/apps/server/src/cli/trace.ts b/apps/server/src/cli/trace.ts index 244636c514061..3e94d0d9957f7 100644 --- a/apps/server/src/cli/trace.ts +++ b/apps/server/src/cli/trace.ts @@ -100,7 +100,7 @@ export function makeTraceSpanSummary(sinceMs = -Infinity) { } const formatMs = (ms: number) => - ms < 1_000 ? `${Math.round(ms)}ms` : `${(ms / 1_000).toFixed(1)}s`; + ms < 1_000 ? `${Math.round(ms)}ms` : `${Math.round(ms / 100) / 10}s`; function formatTraceSummary( summary: ReturnType["finish"]>, @@ -127,7 +127,7 @@ function formatTraceSummary( const widths = header.map((_, column) => Math.max(...table.map((row) => row[column]!.length))); const formatIso = (ms: number) => DateTime.formatIso(DateTime.makeUnsafe(ms)); return [ - `${summary.spanCount} spans ended from ${formatIso(summary.firstEndMs)} to ${formatIso(summary.lastEndMs)} (${summary.minutes.toFixed(1)} min).`, + `${summary.spanCount} spans ended from ${formatIso(summary.firstEndMs)} to ${formatIso(summary.lastEndMs)} (${summary.minutes.toFixed(1).replace(/\.0+$/, "")} min).`, ...(summary.skippedLineCount > 0 ? [`Skipped ${summary.skippedLineCount} lines that are not spans.`] : []), diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 8f4b15cc11f91..bd74694dc46af 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -1841,10 +1841,10 @@ describe("deriveMessagesTimelineRows", () => { const settled = rows({ resume: "completed", working: false }); expect(shape(settled)).toEqual([ "user:launch", - "fold:Worked for 8.0s", + "fold:Worked for 8s", "assistant:launch-answer", "user:resume", - "fold:Worked for 8.0s", + "fold:Worked for 8s", "assistant:resume-answer", ]); @@ -1857,17 +1857,17 @@ describe("deriveMessagesTimelineRows", () => { }); expect(shape(expanded)).toEqual([ "user:launch", - "fold:Worked for 8.0s", + "fold:Worked for 8s", "work-toggle", "assistant:launch-answer", "user:resume", - "fold:Worked for 8.0s", + "fold:Worked for 8s", "assistant:resume-answer", ]); expect(shape(rows({ resume: "running", working: true }))).toEqual([ "user:launch", - "fold:Worked for 8.0s", + "fold:Worked for 8s", "assistant:launch-answer", "user:resume", "working", @@ -1876,7 +1876,7 @@ describe("deriveMessagesTimelineRows", () => { expect(shape(rows({ resume: "failed", working: false }))).toEqual([ "user:launch", - "fold:Worked for 8.0s", + "fold:Worked for 8s", "assistant:launch-answer", "user:resume", "work", diff --git a/apps/web/src/components/chat/WorktreeSetupCard.browser.test.tsx b/apps/web/src/components/chat/WorktreeSetupCard.browser.test.tsx index 1a34f537efd15..eddd6691884ef 100644 --- a/apps/web/src/components/chat/WorktreeSetupCard.browser.test.tsx +++ b/apps/web/src/components/chat/WorktreeSetupCard.browser.test.tsx @@ -53,13 +53,13 @@ it("ticks the running stage while finished stages keep their duration", async () // Assert synchronously: expect.element polls on timers these tests fake. const section = screen.getByRole("region", { name: "Worktree setup" }); - expect(section.element().textContent).toContain("Fetch base branch3.0s"); - expect(section.element().textContent).toContain("Check out files7.0s"); + expect(section.element().textContent).toContain("Fetch base branch3s"); + expect(section.element().textContent).toContain("Check out files7s"); await act(async () => { await vi.advanceTimersByTimeAsync(5_000); }); - expect(section.element().textContent).toContain("Fetch base branch3.0s"); + expect(section.element().textContent).toContain("Fetch base branch3s"); expect(section.element().textContent).toContain("Check out files12s"); }); @@ -70,9 +70,9 @@ it("stops a stage interrupted by the setup ending at the setup's end", async () await using screen = await render(card(failed)); const section = screen.getByRole("region", { name: "Worktree setup" }); - expect(section.element().textContent).toContain("Check out files2.0s"); + expect(section.element().textContent).toContain("Check out files2s"); await act(async () => { await vi.advanceTimersByTimeAsync(5_000); }); - expect(section.element().textContent).toContain("Check out files2.0s"); + expect(section.element().textContent).toContain("Check out files2s"); }); diff --git a/apps/web/src/components/settings/DiagnosticsSettings.tsx b/apps/web/src/components/settings/DiagnosticsSettings.tsx index 613074b2d914b..0fcea4fa5de00 100644 --- a/apps/web/src/components/settings/DiagnosticsSettings.tsx +++ b/apps/web/src/components/settings/DiagnosticsSettings.tsx @@ -48,7 +48,7 @@ function formatCount(value: number): string { function formatDuration(value: number): string { if (value < 1_000) return `${Math.round(value)} ms`; - return `${(value / 1_000).toFixed(value >= 10_000 ? 1 : 2)} s`; + return `${(value / 1_000).toFixed(value >= 10_000 ? 1 : 2).replace(/\.0+$/, "")} s`; } function formatBytes(value: number): string { @@ -438,10 +438,10 @@ const RESOURCE_HISTORY_WINDOWS = [ ] as const; function formatCpuTime(seconds: number): string { - if (seconds < 60) return `${seconds.toFixed(seconds >= 10 ? 1 : 2)}s`; + if (seconds < 60) return `${seconds.toFixed(seconds >= 10 ? 1 : 2).replace(/\.0+$/, "")}s`; const minutes = seconds / 60; - if (minutes < 60) return `${minutes.toFixed(minutes >= 10 ? 1 : 2)}m`; - return `${(minutes / 60).toFixed(2)}h`; + if (minutes < 60) return `${minutes.toFixed(minutes >= 10 ? 1 : 2).replace(/\.0+$/, "")}m`; + return `${(minutes / 60).toFixed(2).replace(/\.0+$/, "")}h`; } function formatShortProcessName(command: string): string { diff --git a/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx b/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx index 7b67ac7b1949e..74df6a4d6858b 100644 --- a/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx +++ b/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx @@ -74,16 +74,16 @@ function formatRate(value: number): string { function formatCpuTime(valueMs: number): string { const seconds = valueMs / 1_000; - if (seconds < 60) return `${seconds.toFixed(seconds >= 10 ? 1 : 2)}s`; + if (seconds < 60) return `${seconds.toFixed(seconds >= 10 ? 1 : 2).replace(/\.0+$/, "")}s`; const minutes = seconds / 60; - if (minutes < 60) return `${minutes.toFixed(minutes >= 10 ? 1 : 2)}m`; - return `${(minutes / 60).toFixed(2)}h`; + if (minutes < 60) return `${minutes.toFixed(minutes >= 10 ? 1 : 2).replace(/\.0+$/, "")}m`; + return `${(minutes / 60).toFixed(2).replace(/\.0+$/, "")}h`; } function formatDurationMicros(value: number): string { if (value < 1_000) return `${Math.round(value)} µs`; - if (value < 1_000_000) return `${(value / 1_000).toFixed(2)} ms`; - return `${(value / 1_000_000).toFixed(2)} s`; + if (value < 1_000_000) return `${(value / 1_000).toFixed(2).replace(/\.0+$/, "")} ms`; + return `${(value / 1_000_000).toFixed(2).replace(/\.0+$/, "")} s`; } function formatSampleInterval(valueMs: number): string { @@ -788,7 +788,7 @@ function AttributionTable({ entries }: { entries: ReadonlyArray {entry.count} - {(entry.durationMs / 1_000).toFixed(2)}s + {(entry.durationMs / 1_000).toFixed(2).replace(/\.0+$/, "")}s ))} diff --git a/packages/shared/src/orchestrationTiming.ts b/packages/shared/src/orchestrationTiming.ts index 187db6c6d97d4..1f43f99453456 100644 --- a/packages/shared/src/orchestrationTiming.ts +++ b/packages/shared/src/orchestrationTiming.ts @@ -22,10 +22,7 @@ export function deriveSubagentElapsedMs( export function formatDuration(durationMs: number): string { if (!Number.isFinite(durationMs) || durationMs < 0) return "0ms"; if (durationMs < 1_000) return `${Math.max(1, Math.round(durationMs))}ms`; - if (durationMs < 10_000) { - const tenths = Math.round(durationMs / 100) / 10; - return tenths >= 10 ? "10s" : `${tenths.toFixed(1)}s`; - } + if (durationMs < 10_000) return `${Math.round(durationMs / 100) / 10}s`; const totalSeconds = Math.round(durationMs / 1_000); // Choose the unit after rounding so 59.5 seconds never renders as "60s". if (totalSeconds < 60) return `${totalSeconds}s`; From f48fb51fac22c76c0b76f196909acdb395f5832e Mon Sep 17 00:00:00 2001 From: maria Date: Fri, 30 Oct 2026 03:33:32 +0000 Subject: [PATCH 397/817] feat(web): switch the composer between rich text and Markdown source from a button or mod+/ (#26777) --- apps/web/src/components/chat/ChatComposer.tsx | 28 ++++++++++++- .../chat/ComposerRichTextToggle.tsx | 41 +++++++++++++++++++ .../src/components/chat/composerShortcuts.ts | 6 +++ apps/web/src/keybindings.test.ts | 11 ++++- docs/user/composer.md | 4 +- docs/user/keybindings.md | 1 + packages/contracts/src/keybindings.ts | 1 + packages/shared/src/keybindings.ts | 1 + 8 files changed, 90 insertions(+), 3 deletions(-) create mode 100644 apps/web/src/components/chat/ComposerRichTextToggle.tsx diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index d7878cc29a165..56c73bcec16a6 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -133,6 +133,7 @@ import { import { attachmentUploadBlockReason } from "../../lib/attachmentUploadState"; import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection"; import { shortcutLabelForCommand } from "../../keybindings"; +import { persistClientSettingsUpdate } from "../../hooks/useSettings"; import { type TerminalContextDraft, type TerminalContextSelection, @@ -198,6 +199,7 @@ import { ComposerRestingImagePreviews, } from "./ComposerAttachmentStrip"; import { ComposerPrimaryActions } from "./ComposerPrimaryActions"; +import { ComposerRichTextToggle } from "./ComposerRichTextToggle"; import { ComposerFooterPrimaryActions } from "./ComposerFooterControls"; import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel"; import { ComposerPlanFollowUpBanner } from "./ComposerPlanFollowUpBanner"; @@ -304,6 +306,7 @@ export interface ChatComposerHandle { openModelPicker: () => void; stepReasoningEffort: (direction: 1 | -1) => void; toggleModelPicker: () => void; + toggleRichText: () => void; openControl: (command: KeybindingCommand) => void; isModelPickerOpen: () => boolean; isCaretAtStart: () => boolean; @@ -2852,6 +2855,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) openModelPickerStable(); } }, + toggleRichText: () => { + if (isLiteralPendingAnswer) return; + persistClientSettingsUpdate((current) => ({ + ...current, + composerRichTextEnabled: !current.composerRichTextEnabled, + })).catch(console.error); + }, openControl: (command) => { if (composerBlurFrameRef.current !== null) { window.cancelAnimationFrame(composerBlurFrameRef.current); @@ -3429,7 +3439,23 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) showMobilePendingAnswerActions && "hidden sm:flex", )} > - {composerAttachButton ?
      {composerAttachButton}
      : null} + {composerAttachButton || !isLiteralPendingAnswer ? ( +
      + {composerAttachButton} + {isLiteralPendingAnswer ? null : ( + + )} +
      + ) : null}
      + event.preventDefault()} + onClick={() => void updateClientSettings({ composerRichTextEnabled: showingSource })} + /> + } + > + + + + {showingSource ? "Show formatting" : "Show Markdown source"} + {shortcutLabel ? ` · ${shortcutLabel}` : null} + + + ); +} diff --git a/apps/web/src/components/chat/composerShortcuts.ts b/apps/web/src/components/chat/composerShortcuts.ts index 30beb9771968f..e55398996cea9 100644 --- a/apps/web/src/components/chat/composerShortcuts.ts +++ b/apps/web/src/components/chat/composerShortcuts.ts @@ -18,6 +18,12 @@ export function composerShortcutCommands( "modelPicker.toggle": ({ event }) => { if (!event.repeat) composerRef.current?.toggleModelPicker(); }, + "composer.toggleRichText": ({ event }) => { + // The flip remounts the editor, which would drop an unsaved citation comment. + if (event.target instanceof Element && event.target.closest("[data-citation-comment-editor]")) + return false; + if (!event.repeat) composerRef.current?.toggleRichText(); + }, "composer.increaseEffort": ({ event }) => { if (!event.repeat) composerRef.current?.stepReasoningEffort(1); }, diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts index a0ba7fa7ee043..96ae09296dea5 100644 --- a/apps/web/src/keybindings.test.ts +++ b/apps/web/src/keybindings.test.ts @@ -768,12 +768,21 @@ describe("composer and pull request shortcuts", () => { }); it.each(["MacIntel", "Win32", "Linux"])( - "reserves the alternate send chord for the focused composer on %s", + "resolves composer toggle and alternate send chords in their contexts on %s", (platform) => { const modifier = { metaKey: platform === "MacIntel", ctrlKey: platform !== "MacIntel", }; + for (const terminalFocus of [false, true]) { + assert.strictEqual( + resolveShortcutCommand(event({ key: "/", ...modifier }), DEFAULT_RESOLVED_KEYBINDINGS, { + platform, + context: { terminalFocus }, + }), + terminalFocus ? null : "composer.toggleRichText", + ); + } const shiftedEnter = event({ key: "Enter", shiftKey: true, ...modifier }); for (const composerRequiresModifier of [false, true]) { const context = { diff --git a/docs/user/composer.md b/docs/user/composer.md index 714572dfd5005..afac8ce64cf3b 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -19,7 +19,9 @@ The composer writes Markdown and shows it styled as you type. Markers such as them. Lines starting with `- `, `1. `, `- [ ] `, `> `, `# ` or `---` become lists, task lists, quotes, headings and rules; ` ``` ` followed by Enter opens a code block. What you typed is what the agent receives, markers and numbering -included, and `#1234` without a space still looks up a pull request. +included, and `#1234` without a space still looks up a pull request. To see the +plain Markdown instead, press the button beside attach; it is the same +switch as **Settings → Chat → Rich text composer**. Enter sends. In a list or quote, **Shift+Enter** continues it, and Shift+Enter on an empty line moves out one level, then leaves it; **Tab** nests a list item diff --git a/docs/user/keybindings.md b/docs/user/keybindings.md index 83989762c5b07..0e8e17744019e 100644 --- a/docs/user/keybindings.md +++ b/docs/user/keybindings.md @@ -28,6 +28,7 @@ Use `mod+shift+e` for effort, `mod+shift+a` for permissions, `mod+shift+x` for t workspace, and `mod+shift+g` for the Git branch. The workspace menu includes the current checkout, a new worktree, and the previous worktree when available. Use `mod+shift+l` to reuse the previous worktree directly. +Use `mod+/` to switch the composer between rich text and its Markdown source. To change effort one step without opening the picker, bind **Composer: Increase Effort** and **Composer: Decrease Effort** in Keybindings. diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts index 714e0a1d486a1..cc55adb9ca81b 100644 --- a/packages/contracts/src/keybindings.ts +++ b/packages/contracts/src/keybindings.ts @@ -87,6 +87,7 @@ export const STATIC_KEYBINDING_COMMANDS = [ "appearance.cycle", "themeEditor.toggle", "composer.stash", + "composer.toggleRichText", "composer.sendAlternate", "composer.sendBackground", "composer.sendAndNewThread", diff --git a/packages/shared/src/keybindings.ts b/packages/shared/src/keybindings.ts index 32292c0f9ef21..8ae3f052afede 100644 --- a/packages/shared/src/keybindings.ts +++ b/packages/shared/src/keybindings.ts @@ -179,6 +179,7 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray = [ { key: "mod+alt+shift+a", command: "appearance.cycle", when: "!terminalFocus" }, { key: "mod+alt+shift+t", command: "themeEditor.toggle" }, { key: "mod+s", command: "composer.stash", when: "!terminalFocus" }, + { key: "mod+/", command: "composer.toggleRichText", when: "!terminalFocus" }, { key: "mod+shift+enter", command: "thread.steerQueuedMessage", when: "!terminalFocus" }, { key: "alt+arrowup", command: "thread.editQueuedMessage", when: "composerFocus" }, { key: "mod+enter", command: "composer.sendAlternate", when: "composerFocus && turnRunning" }, From a773dc38ac75177b6cd133d27df00ca0a83f9480 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 29 Oct 2026 20:43:01 -0700 Subject: [PATCH 398/817] fix(server): t3_thread_organize rejects unknown arguments instead of archiving the caller (#26718) Co-authored-by: Claude Opus 5.5 --- apps/server/src/mcp/toolkits/core.test.ts | 42 ++++++++++++++++++++ apps/server/src/mcp/toolkits/thread/tools.ts | 1 + 2 files changed, 43 insertions(+) diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index a978dbc4d1ff9..93aee4d52f688 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -350,6 +350,48 @@ it.effect("records only failed calls of tools that hand off no work", () => { ); }); +it.effect("rejects an unknown organize target instead of archiving the calling thread", () => { + const dispatched: Array = []; + return Effect.gen(function* () { + const server = yield* McpServer.McpServer; + const outcome = yield* server + .callTool({ + name: "t3_thread_organize", + arguments: { action: "archive", threadIds: ["other-thread"] }, + }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, scope), + Effect.provideService(McpSchema.McpServerClient, client), + Effect.result, + ); + expect(dispatched).toEqual([]); + expect(outcome).toMatchObject({ + _tag: "Failure", + failure: { message: expect.stringContaining("Expected no excess property") }, + }); + }).pipe( + Effect.provide( + layerThreadToolkit.pipe( + Layer.provideMerge(McpServer.McpServer.layer), + Layer.provide(NodeCrypto.layer), + Layer.provide( + Layer.mock(ThreadManagement.ThreadManagementService)({ + getThreadShell: (id) => Effect.succeed(McpToolAccessTestkit.liveThreadShell(id)), + getProjectThreadRecords: ({ threadId: id }) => + Effect.succeed( + McpToolAccessTestkit.idleThreadProjection(McpToolAccessTestkit.liveThreadShell(id)), + ), + dispatch: (command) => { + dispatched.push(command); + return Effect.succeed({ sequence: 1 } as never); + }, + }), + ), + ), + ), + ); +}); + it.effect("keeps unexpected handler defects private through the production registration", () => Effect.gen(function* () { const server = yield* McpServer.McpServer; diff --git a/apps/server/src/mcp/toolkits/thread/tools.ts b/apps/server/src/mcp/toolkits/thread/tools.ts index 4b566c44a69d1..018acac5c715f 100644 --- a/apps/server/src/mcp/toolkits/thread/tools.ts +++ b/apps/server/src/mcp/toolkits/thread/tools.ts @@ -61,6 +61,7 @@ const ThreadOrganizeTool = Tool.make("t3_thread_organize", { ], }) .annotate(Tool.Title, "Organize a thread") + .annotate(Tool.Strict, true) .annotate(Tool.Destructive, true); const commandTool = { From aa11ef6783da81039e6646e2e96941748afb358e Mon Sep 17 00:00:00 2001 From: maria Date: Fri, 30 Oct 2026 04:26:54 +0000 Subject: [PATCH 399/817] fix(web): composer Markdown source button shows the pilcrow again (#27375) --- apps/web/src/components/chat/ComposerRichTextToggle.tsx | 4 ++-- docs/user/composer.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/web/src/components/chat/ComposerRichTextToggle.tsx b/apps/web/src/components/chat/ComposerRichTextToggle.tsx index b705180c20993..13aebff1984d1 100644 --- a/apps/web/src/components/chat/ComposerRichTextToggle.tsx +++ b/apps/web/src/components/chat/ComposerRichTextToggle.tsx @@ -1,4 +1,4 @@ -import { FeatherIcon } from "lucide-react"; +import { PilcrowIcon } from "lucide-react"; import { updateClientSettings } from "../../hooks/useSettings"; import { Button } from "../ui/button"; @@ -30,7 +30,7 @@ export function ComposerRichTextToggle({ /> } > - + {showingSource ? "Show formatting" : "Show Markdown source"} diff --git a/docs/user/composer.md b/docs/user/composer.md index afac8ce64cf3b..6156a126ca246 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -20,7 +20,7 @@ them. Lines starting with `- `, `1. `, `- [ ] `, `> `, `# ` or `---` become list task lists, quotes, headings and rules; ` ``` ` followed by Enter opens a code block. What you typed is what the agent receives, markers and numbering included, and `#1234` without a space still looks up a pull request. To see the -plain Markdown instead, press the button beside attach; it is the same +plain Markdown instead, press the **¶** button beside attach; it is the same switch as **Settings → Chat → Rich text composer**. Enter sends. In a list or quote, **Shift+Enter** continues it, and Shift+Enter From 3dd62dce70b5ff577099966ba92452603ccc8f89 Mon Sep 17 00:00:00 2001 From: maria Date: Fri, 30 Oct 2026 04:59:35 +0000 Subject: [PATCH 400/817] revert(web): remove the composer rich text toggle button and mod+/ shortcut (#27390) --- apps/web/src/components/chat/ChatComposer.tsx | 28 +------------ .../chat/ComposerRichTextToggle.tsx | 41 ------------------- .../src/components/chat/composerShortcuts.ts | 6 --- apps/web/src/keybindings.test.ts | 11 +---- docs/user/composer.md | 4 +- docs/user/keybindings.md | 1 - packages/contracts/src/keybindings.ts | 1 - packages/shared/src/keybindings.ts | 1 - 8 files changed, 3 insertions(+), 90 deletions(-) delete mode 100644 apps/web/src/components/chat/ComposerRichTextToggle.tsx diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 56c73bcec16a6..d7878cc29a165 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -133,7 +133,6 @@ import { import { attachmentUploadBlockReason } from "../../lib/attachmentUploadState"; import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection"; import { shortcutLabelForCommand } from "../../keybindings"; -import { persistClientSettingsUpdate } from "../../hooks/useSettings"; import { type TerminalContextDraft, type TerminalContextSelection, @@ -199,7 +198,6 @@ import { ComposerRestingImagePreviews, } from "./ComposerAttachmentStrip"; import { ComposerPrimaryActions } from "./ComposerPrimaryActions"; -import { ComposerRichTextToggle } from "./ComposerRichTextToggle"; import { ComposerFooterPrimaryActions } from "./ComposerFooterControls"; import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel"; import { ComposerPlanFollowUpBanner } from "./ComposerPlanFollowUpBanner"; @@ -306,7 +304,6 @@ export interface ChatComposerHandle { openModelPicker: () => void; stepReasoningEffort: (direction: 1 | -1) => void; toggleModelPicker: () => void; - toggleRichText: () => void; openControl: (command: KeybindingCommand) => void; isModelPickerOpen: () => boolean; isCaretAtStart: () => boolean; @@ -2855,13 +2852,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) openModelPickerStable(); } }, - toggleRichText: () => { - if (isLiteralPendingAnswer) return; - persistClientSettingsUpdate((current) => ({ - ...current, - composerRichTextEnabled: !current.composerRichTextEnabled, - })).catch(console.error); - }, openControl: (command) => { if (composerBlurFrameRef.current !== null) { window.cancelAnimationFrame(composerBlurFrameRef.current); @@ -3439,23 +3429,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) showMobilePendingAnswerActions && "hidden sm:flex", )} > - {composerAttachButton || !isLiteralPendingAnswer ? ( -
      - {composerAttachButton} - {isLiteralPendingAnswer ? null : ( - - )} -
      - ) : null} + {composerAttachButton ?
      {composerAttachButton}
      : null}
      - event.preventDefault()} - onClick={() => void updateClientSettings({ composerRichTextEnabled: showingSource })} - /> - } - > - - - - {showingSource ? "Show formatting" : "Show Markdown source"} - {shortcutLabel ? ` · ${shortcutLabel}` : null} - - - ); -} diff --git a/apps/web/src/components/chat/composerShortcuts.ts b/apps/web/src/components/chat/composerShortcuts.ts index e55398996cea9..30beb9771968f 100644 --- a/apps/web/src/components/chat/composerShortcuts.ts +++ b/apps/web/src/components/chat/composerShortcuts.ts @@ -18,12 +18,6 @@ export function composerShortcutCommands( "modelPicker.toggle": ({ event }) => { if (!event.repeat) composerRef.current?.toggleModelPicker(); }, - "composer.toggleRichText": ({ event }) => { - // The flip remounts the editor, which would drop an unsaved citation comment. - if (event.target instanceof Element && event.target.closest("[data-citation-comment-editor]")) - return false; - if (!event.repeat) composerRef.current?.toggleRichText(); - }, "composer.increaseEffort": ({ event }) => { if (!event.repeat) composerRef.current?.stepReasoningEffort(1); }, diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts index 96ae09296dea5..a0ba7fa7ee043 100644 --- a/apps/web/src/keybindings.test.ts +++ b/apps/web/src/keybindings.test.ts @@ -768,21 +768,12 @@ describe("composer and pull request shortcuts", () => { }); it.each(["MacIntel", "Win32", "Linux"])( - "resolves composer toggle and alternate send chords in their contexts on %s", + "reserves the alternate send chord for the focused composer on %s", (platform) => { const modifier = { metaKey: platform === "MacIntel", ctrlKey: platform !== "MacIntel", }; - for (const terminalFocus of [false, true]) { - assert.strictEqual( - resolveShortcutCommand(event({ key: "/", ...modifier }), DEFAULT_RESOLVED_KEYBINDINGS, { - platform, - context: { terminalFocus }, - }), - terminalFocus ? null : "composer.toggleRichText", - ); - } const shiftedEnter = event({ key: "Enter", shiftKey: true, ...modifier }); for (const composerRequiresModifier of [false, true]) { const context = { diff --git a/docs/user/composer.md b/docs/user/composer.md index 6156a126ca246..714572dfd5005 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -19,9 +19,7 @@ The composer writes Markdown and shows it styled as you type. Markers such as them. Lines starting with `- `, `1. `, `- [ ] `, `> `, `# ` or `---` become lists, task lists, quotes, headings and rules; ` ``` ` followed by Enter opens a code block. What you typed is what the agent receives, markers and numbering -included, and `#1234` without a space still looks up a pull request. To see the -plain Markdown instead, press the **¶** button beside attach; it is the same -switch as **Settings → Chat → Rich text composer**. +included, and `#1234` without a space still looks up a pull request. Enter sends. In a list or quote, **Shift+Enter** continues it, and Shift+Enter on an empty line moves out one level, then leaves it; **Tab** nests a list item diff --git a/docs/user/keybindings.md b/docs/user/keybindings.md index 0e8e17744019e..83989762c5b07 100644 --- a/docs/user/keybindings.md +++ b/docs/user/keybindings.md @@ -28,7 +28,6 @@ Use `mod+shift+e` for effort, `mod+shift+a` for permissions, `mod+shift+x` for t workspace, and `mod+shift+g` for the Git branch. The workspace menu includes the current checkout, a new worktree, and the previous worktree when available. Use `mod+shift+l` to reuse the previous worktree directly. -Use `mod+/` to switch the composer between rich text and its Markdown source. To change effort one step without opening the picker, bind **Composer: Increase Effort** and **Composer: Decrease Effort** in Keybindings. diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts index cc55adb9ca81b..714e0a1d486a1 100644 --- a/packages/contracts/src/keybindings.ts +++ b/packages/contracts/src/keybindings.ts @@ -87,7 +87,6 @@ export const STATIC_KEYBINDING_COMMANDS = [ "appearance.cycle", "themeEditor.toggle", "composer.stash", - "composer.toggleRichText", "composer.sendAlternate", "composer.sendBackground", "composer.sendAndNewThread", diff --git a/packages/shared/src/keybindings.ts b/packages/shared/src/keybindings.ts index 8ae3f052afede..32292c0f9ef21 100644 --- a/packages/shared/src/keybindings.ts +++ b/packages/shared/src/keybindings.ts @@ -179,7 +179,6 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray = [ { key: "mod+alt+shift+a", command: "appearance.cycle", when: "!terminalFocus" }, { key: "mod+alt+shift+t", command: "themeEditor.toggle" }, { key: "mod+s", command: "composer.stash", when: "!terminalFocus" }, - { key: "mod+/", command: "composer.toggleRichText", when: "!terminalFocus" }, { key: "mod+shift+enter", command: "thread.steerQueuedMessage", when: "!terminalFocus" }, { key: "alt+arrowup", command: "thread.editQueuedMessage", when: "composerFocus" }, { key: "mod+enter", command: "composer.sendAlternate", when: "composerFocus && turnRunning" }, From 2ba2426af640899eee1ca1c544e9321bd2170762 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 29 Oct 2026 22:07:29 -0700 Subject: [PATCH 401/817] fix(server): HTML preview browsers quit when done instead of waiting to be killed (#27224) Co-authored-by: Claude Opus 5.5 --- apps/server/src/htmlRender/HtmlRender.test.ts | 52 +++++++++++++++++++ apps/server/src/htmlRender/headlessChrome.ts | 14 ++++- 2 files changed, 65 insertions(+), 1 deletion(-) diff --git a/apps/server/src/htmlRender/HtmlRender.test.ts b/apps/server/src/htmlRender/HtmlRender.test.ts index 80d367b2f8ac9..1916327672516 100644 --- a/apps/server/src/htmlRender/HtmlRender.test.ts +++ b/apps/server/src/htmlRender/HtmlRender.test.ts @@ -316,6 +316,58 @@ describe("HtmlRender", () => { }, ); + // The fake browser is a shebang script, which Windows cannot execute. + describe.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "when the browser cannot be signalled", + () => { + // A browser T3 cannot signal, as under AppArmor in an LXC container, must still exit. + it.live("asks the browser to close when the preview finishes instead of signalling it", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-fake-browser-", + }); + const executable = path.join(directory, "chrome-headless-shell"); + const exitRecord = path.join(directory, "exited"); + yield* fileSystem.writeFileString( + executable, + `#!${process.execPath} +const fs = require("node:fs"); +process.on("SIGTERM", () => {}); +const quit = () => { fs.writeFileSync(${JSON.stringify(exitRecord)}, "asked to close"); process.exit(0); }; +const reply = (message) => fs.writeSync(4, JSON.stringify(message) + "\\0"); +const results = { + "Target.createTarget": { targetId: "page" }, + "Target.attachToTarget": { sessionId: "session" }, + "Runtime.evaluate": { result: { value: 100 } }, + "Page.captureScreenshot": { data: "iVBORw0KGgo=" }, +}; +let buffered = ""; +fs.createReadStream(null, { fd: 3 }).on("end", quit).on("data", (chunk) => { + const messages = (buffered + chunk).split("\\0"); + buffered = messages.pop(); + for (const { id, method, sessionId } of messages.map((raw) => JSON.parse(raw))) { + if (method === "Browser.close") quit(); + reply({ id, sessionId, result: results[method] ?? {} }); + if (method === "Page.navigate") reply({ sessionId, method: "Page.loadEventFired", params: {} }); + } +}); +`, + { mode: 0o755 }, + ); + + yield* HtmlRender.HtmlRender.use((htmlRender) => + htmlRender.preview({ html: "

      x

      " }), + ).pipe(Effect.provide(layerHtmlRender(executable))); + + const exitedBy = yield* fileSystem.readFileString(exitRecord).pipe(Effect.option); + expect(Option.getOrElse(exitedBy, () => "killed by a signal")).toBe("asked to close"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + }, + ); + it.live("matches preview media queries and text colors to the requested appearance", (ctx) => Effect.gen(function* () { const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV]; diff --git a/apps/server/src/htmlRender/headlessChrome.ts b/apps/server/src/htmlRender/headlessChrome.ts index aaf64bdcecc36..13ce0c6845740 100644 --- a/apps/server/src/htmlRender/headlessChrome.ts +++ b/apps/server/src/htmlRender/headlessChrome.ts @@ -247,7 +247,7 @@ const launchBrowser = Effect.fnUntraced(function* (input: { let disconnected: BrowserFailure | undefined; let nextId = 0; - const post = (method: string, params: Record, sessionId: string) => + const post = (method: string, params: Record, sessionId?: string) => Queue.offer( outgoing, new TextEncoder().encode( @@ -374,6 +374,18 @@ const launchBrowser = Effect.fnUntraced(function* (input: { Effect.forkScoped, ); + // Signals can miss a confined browser (AppArmor in LXC), so ask it to quit first. + // Runs before the spawn's release, which still signals a browser that stays up. + yield* Effect.addFinalizer(() => + disconnected + ? Effect.void + : post("Browser.close", {}).pipe( + Effect.andThen(child.exitCode), + Effect.timeout("2 seconds"), + Effect.ignore, + ), + ); + const send = Effect.fn("headlessChrome.send")(function*
      ( method: string, params: Record, From 05f0d9be28218bdf5e91aa39462e23073379b48a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 29 Oct 2026 22:08:11 -0700 Subject: [PATCH 402/817] fix(terminal): retain and pace slow fallback process queries (#24640) Co-authored-by: Claude Opus 5.5 --- apps/server/src/terminal/Manager.test.ts | 153 ++++++++++++++ apps/server/src/terminal/Manager.ts | 250 +++++++++++++---------- 2 files changed, 293 insertions(+), 110 deletions(-) diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index 5b166d8b1452b..7e92567772950 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -10,20 +10,25 @@ import { TerminalProviderInstanceNotFoundError, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Clock from "effect/Clock"; import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Base64Url from "effect/encoding/Base64Url"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as PlatformError from "effect/PlatformError"; import * as Path from "effect/Path"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as SynchronizedRef from "effect/SynchronizedRef"; +import * as TestClock from "effect/testing/TestClock"; import { expect, vi } from "vite-plus/test"; import * as ProcessRunner from "../processRunner.ts"; @@ -756,6 +761,154 @@ it.layer( }), ); + // Answers process-table queries after `queryDuration`, honoring the caller's + // timeout the way ProcessRunner's `timedOutResult` mode does. + const slowProcessTable = ( + platform: "linux" | "win32", + queryDuration: Duration.Input, + queries: Array<{ start: number; end?: number }>, + started: ReadonlyArray>, + ): ProcessRunner.ProcessRunner["Service"] => ({ + run: (input) => + Effect.gen(function* () { + const query: { start: number; end?: number } = { start: yield* Clock.currentTimeMillis }; + queries.push(query); + const deferred = started[queries.length - 1]; + if (deferred) yield* Deferred.succeed(deferred, undefined); + const completed = yield* Effect.sleep(queryDuration).pipe( + Effect.timeoutOption(input.timeout ?? "1 hour"), + ); + query.end = yield* Clock.currentTimeMillis; + return { + stdout: Option.isNone(completed) + ? "" + : platform === "win32" + ? "100|9000|node.exe\n" + : " 100 9000 node\n", + stderr: "", + code: Option.isSome(completed) ? ChildProcessSpawner.ExitCode(0) : null, + timedOut: Option.isNone(completed), + stdoutTruncated: false, + stderrTruncated: false, + stdoutInvalidUtf8: false, + stderrInvalidUtf8: false, + }; + }), + }); + + const createFallbackManager = ( + platform: "linux" | "win32", + runner: ProcessRunner.ProcessRunner["Service"], + ) => + createManager(5, { subprocessPollIntervalMs: 1_000, processKillGraceMs: 0 }).pipe( + Effect.provideService(ProcessRunner.ProcessRunner, runner), + Effect.provide(layerWithHostPlatform(platform)), + ); + + it.effect.each(["linux", "win32"] as const)( + "reports activity from a slow but successful %s process-table query", + (platform) => + Effect.gen(function* () { + const started = yield* Deferred.make(); + const queries: Array<{ start: number; end?: number }> = []; + const { manager, getEvents } = yield* createFallbackManager( + platform, + slowProcessTable(platform, "5 seconds", queries, [started]), + ); + + yield* manager.open(openInput()); + yield* TestClock.adjust("1 second"); + yield* Deferred.await(started); + yield* TestClock.adjust("5 seconds"); + + expect( + (yield* getEvents).some( + (event) => + event.type === "activity" && event.hasRunningSubprocess && event.label === "node", + ), + ).toBe(true); + yield* manager.close({ threadId: "thread-1" }); + }).pipe(Effect.provide(TestClock.layer())), + ); + + it.effect("idles at least as long as a slow process-table query took before the next", () => + Effect.gen(function* () { + const started = yield* Deferred.make(); + const queries: Array<{ start: number; end?: number }> = []; + const { manager } = yield* createFallbackManager( + "linux", + slowProcessTable("linux", "5 seconds", queries, [started]), + ); + + yield* manager.open(openInput()); + yield* TestClock.adjust("1 second"); + yield* Deferred.await(started); + yield* TestClock.adjust("5 seconds"); + yield* TestClock.adjust(Duration.millis(19_999)); + + expect(queries).toHaveLength(1); + yield* TestClock.adjust("1 millis"); + const [slow, next] = queries; + expect(next?.start).toBe(slow!.end! + 20_000); + yield* manager.close({ threadId: "thread-1" }); + }).pipe(Effect.provide(TestClock.layer())), + ); + + it.effect("ends a hung process-table query and paces the retry", () => + Effect.gen(function* () { + const started = yield* Deferred.make(); + const queries: Array<{ start: number; end?: number }> = []; + const { manager } = yield* createFallbackManager( + "win32", + slowProcessTable("win32", "1 day", queries, [started]), + ); + + yield* manager.open(openInput()); + yield* TestClock.adjust("1 second"); + yield* Deferred.await(started); + yield* TestClock.adjust("2 minutes"); + yield* TestClock.adjust("2 minutes"); + + const [hung, next] = queries; + expect(hung!.end! - hung!.start).toBe(15_000); + expect(next!.start - hung!.end!).toBe(60_000); + yield* manager.close({ threadId: "thread-1" }); + }).pipe(Effect.provide(TestClock.layer())), + ); + + it.effect.each([ + ["linux", 1_000], + ["win32", 1_500], + ] as const)( + "bounds closeIdle's %s query so other operations on the thread still run", + ([platform, budgetMs]) => + Effect.gen(function* () { + const started = yield* Deferred.make(); + const queries: Array<{ start: number; end?: number }> = []; + const { manager, ptyAdapter } = yield* createFallbackManager( + platform, + slowProcessTable(platform, "1 day", queries, [started]), + ); + yield* manager.open(openInput()); + + const closing = yield* manager + .closeIdle({ threadId: "thread-1" }) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(started); + const resizing = yield* manager + .resize({ threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID, cols: 80, rows: 30 }) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* TestClock.adjust(Duration.millis(budgetMs)); + + expect(closing.pollUnsafe()).toBeDefined(); + expect(resizing.pollUnsafe()).toBeDefined(); + expect(queries[0]!.end! - queries[0]!.start).toBe(budgetMs); + expect(ptyAdapter.processes[0]!.resizeCalls).toEqual([{ cols: 80, rows: 30 }]); + expect(ptyAdapter.processes[0]!.killed).toBe(false); + yield* manager.close({ threadId: "thread-1" }); + }).pipe(Effect.provide(TestClock.layer())), + ); + it.effect("keeps terminals that get input or output while closeIdle checks them", () => Effect.gen(function* () { const ptyAdapter = new FakePtyAdapter(); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index a08b3e4afe784..bd7ca2c92e3c2 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -46,6 +46,7 @@ import { getTerminalLabel } from "@t3tools/shared/terminalLabels"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Context from "effect/Context"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Base64Url from "effect/encoding/Base64Url"; import * as Equal from "effect/Equal"; @@ -55,6 +56,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; @@ -95,6 +97,12 @@ const MAX_HISTORY_CHUNK_LENGTH = 16 * 1024; const DEFAULT_PERSIST_DEBOUNCE_MS = 250; const DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000; const MAX_SUBPROCESS_POLL_INTERVAL_MS = 60_000; +// `ps` and WMI can take seconds on a loaded host and their tables are still +// valid then; the timeout only ends a query that is truly stuck. +const PROCESS_TABLE_QUERY_TIMEOUT = "15 seconds"; +// closeIdle queries while holding the thread lock, so it keeps a short budget +// rather than stalling other operations on that thread behind a slow table. +const CLOSE_IDLE_QUERY_TIMEOUT = { posix: "1 second", win32: "1500 millis" } as const; // Discover children started without terminal input or output. const QUIET_SUBPROCESS_SNAPSHOT_EVERY_TICKS = 30; const DEFAULT_PROCESS_KILL_GRACE_MS = 1_000; @@ -675,8 +683,17 @@ interface TerminalProcessTableSnapshot { readonly commandById: ReadonlyMap; } -function subprocessSnapshotPollDelayMs(pollIntervalMs: number, failureCount: number): number { - return Math.min(pollIntervalMs * 2 ** failureCount, MAX_SUBPROCESS_POLL_INTERVAL_MS); +// Idles at least four times as long as the last fallback query took, so a slow +// process table never keeps the poll loop busy most of the time. +function subprocessSnapshotPollDelayMs( + pollIntervalMs: number, + failureCount: number, + queryElapsedMs: number, +): number { + return Math.min( + Math.max(pollIntervalMs * 2 ** failureCount, queryElapsedMs * 4), + MAX_SUBPROCESS_POLL_INTERVAL_MS, + ); } function parsePosixProcessTable(stdout: string): TerminalProcessTableSnapshot { @@ -764,6 +781,7 @@ const resolvePosixPsCommand = Effect.fn("terminal.resolvePosixPsCommand")(functi const posixProcessTableSnapshot = Effect.fn("terminal.posixProcessTableSnapshot")(function* ( psCommand: string, + timeout: Duration.Input, ): Effect.fn.Return< TerminalProcessTableSnapshot, TerminalSubprocessCheckError, @@ -774,7 +792,7 @@ const posixProcessTableSnapshot = Effect.fn("terminal.posixProcessTableSnapshot" .run({ command: psCommand, args: ["-eo", "pid=,ppid=,comm="], - timeout: "1 second", + timeout, maxOutputBytes: 524_288, outputMode: "truncate", timeoutBehavior: "timedOutResult", @@ -800,48 +818,46 @@ const posixProcessTableSnapshot = Effect.fn("terminal.posixProcessTableSnapshot" return parsePosixProcessTable(result.stdout); }); -const windowsProcessTableSnapshot = Effect.fn("terminal.windowsProcessTableSnapshot")( - function* (): Effect.fn.Return< - TerminalProcessTableSnapshot, - TerminalSubprocessCheckError, - ProcessRunner.ProcessRunner - > { - const processRunner = yield* ProcessRunner.ProcessRunner; - const command = - 'Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { Write-Output "$($_.ProcessId)|$($_.ParentProcessId)|$($_.Name)" }'; - const result = yield* processRunner - .run({ - command: "powershell.exe", - args: ["-NoProfile", "-NonInteractive", "-Command", command], - timeout: "1500 millis", - maxOutputBytes: 262_144, - outputMode: "truncate", - timeoutBehavior: "timedOutResult", - }) - .pipe( - Effect.mapError( - (cause) => new TerminalSubprocessCheckError({ cause, command: "powershell" }), - ), - ); - if (result.code !== 0 || result.timedOut || result.stdoutTruncated) { - return yield* new TerminalSubprocessCheckError({ - command: "powershell", - exitCode: result.code, - timedOut: result.timedOut, - stdoutTruncated: result.stdoutTruncated, - }); - } - const processes = result.stdout.split(/\r?\n/g).flatMap((line) => { - const [pidRaw, ppidRaw, name = ""] = line.trim().split("|", 3); - const pid = Number(pidRaw); - const ppid = Number(ppidRaw); - return Number.isInteger(pid) && pid > 0 && Number.isInteger(ppid) - ? [{ pid, ppid, name }] - : []; +const windowsProcessTableSnapshot = Effect.fn("terminal.windowsProcessTableSnapshot")(function* ( + timeout: Duration.Input, +): Effect.fn.Return< + TerminalProcessTableSnapshot, + TerminalSubprocessCheckError, + ProcessRunner.ProcessRunner +> { + const processRunner = yield* ProcessRunner.ProcessRunner; + const command = + 'Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { Write-Output "$($_.ProcessId)|$($_.ParentProcessId)|$($_.Name)" }'; + const result = yield* processRunner + .run({ + command: "powershell.exe", + args: ["-NoProfile", "-NonInteractive", "-Command", command], + timeout, + maxOutputBytes: 262_144, + outputMode: "truncate", + timeoutBehavior: "timedOutResult", + }) + .pipe( + Effect.mapError( + (cause) => new TerminalSubprocessCheckError({ cause, command: "powershell" }), + ), + ); + if (result.code !== 0 || result.timedOut || result.stdoutTruncated) { + return yield* new TerminalSubprocessCheckError({ + command: "powershell", + exitCode: result.code, + timedOut: result.timedOut, + stdoutTruncated: result.stdoutTruncated, }); - return processTableSnapshotFromProcesses(processes); - }, -); + } + const processes = result.stdout.split(/\r?\n/g).flatMap((line) => { + const [pidRaw, ppidRaw, name = ""] = line.trim().split("|", 3); + const pid = Number(pidRaw); + const ppid = Number(ppidRaw); + return Number.isInteger(pid) && pid > 0 && Number.isInteger(ppid) ? [{ pid, ppid, name }] : []; + }); + return processTableSnapshotFromProcesses(processes); +}); interface TerminalHistoryChunk { data: string; @@ -1557,54 +1573,74 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func }, ); // Share one process table per poll; per-terminal scans can exhaust PIDs on busy hosts. - const fallbackProcessTableSnapshot = ( - platform === "win32" - ? windowsProcessTableSnapshot() - : posixProcessTableSnapshot(yield* resolvePosixPsCommand()) - ).pipe(Effect.provideService(ProcessRunner.ProcessRunner, processRunner)); - const fetchProcessTableSnapshot: Effect.Effect< - { - readonly snapshot: TerminalProcessTableSnapshot; - readonly snapshotSucceeded: boolean; - }, - TerminalSubprocessCheckError - > = options.processTable - ? options.processTable.pipe( - Effect.map((entries) => ({ - snapshot: processTableSnapshotFromProcesses(entries), - snapshotSucceeded: true, - })), - Effect.catch(() => - fallbackProcessTableSnapshot.pipe( - Effect.map((snapshot) => ({ snapshot, snapshotSucceeded: false })), + // Timed on success and failure so the poll loop can pace the next query. + const posixPsCommand = platform === "win32" ? undefined : yield* resolvePosixPsCommand(); + const fallbackProcessTableSnapshot = (timeout: Duration.Input) => + (posixPsCommand === undefined + ? windowsProcessTableSnapshot(timeout) + : posixProcessTableSnapshot(posixPsCommand, timeout) + ).pipe( + Effect.provideService(ProcessRunner.ProcessRunner, processRunner), + Effect.result, + Effect.timed, + Effect.map(([elapsed, snapshot]) => ({ + snapshot, + queryElapsedMs: Duration.toMillis(elapsed), + })), + ); + // `fallbackTimeout` only bounds the ps/WMI fallback; a native process table + // or custom inspector is unaffected. + const fetchProcessTableSnapshot = ( + fallbackTimeout: Duration.Input, + ): Effect.Effect<{ + readonly snapshot: Result.Result; + readonly snapshotSucceeded: boolean; + readonly queryElapsedMs: number; + }> => + options.processTable + ? options.processTable.pipe( + Effect.map((entries) => ({ + snapshot: Result.succeed(processTableSnapshotFromProcesses(entries)), + snapshotSucceeded: true, + queryElapsedMs: 0, + })), + Effect.catch(() => + fallbackProcessTableSnapshot(fallbackTimeout).pipe( + Effect.map((fallback) => ({ ...fallback, snapshotSucceeded: false })), + ), ), - ), - ) - : fallbackProcessTableSnapshot.pipe( - Effect.map((snapshot) => ({ snapshot, snapshotSucceeded: true })), - ); + ) + : fallbackProcessTableSnapshot(fallbackTimeout).pipe( + Effect.map((fallback) => ({ + ...fallback, + snapshotSucceeded: Result.isSuccess(fallback.snapshot), + })), + ); const customSubprocessInspector = options.subprocessInspector; - const acquireSubprocessInspector: Effect.Effect< - { - readonly inspector: TerminalSubprocessInspector; - readonly snapshotSucceeded: boolean; - }, - TerminalSubprocessCheckError - > = + const acquireSubprocessInspector = ( + fallbackTimeout: Duration.Input, + ): Effect.Effect<{ + readonly inspector: Result.Result; + readonly snapshotSucceeded: boolean; + readonly queryElapsedMs: number; + }> => customSubprocessInspector !== undefined - ? Effect.succeed({ inspector: customSubprocessInspector, snapshotSucceeded: true }) + ? Effect.succeed({ + inspector: Result.succeed(customSubprocessInspector), + snapshotSucceeded: true, + queryElapsedMs: 0, + }) : Effect.map( - fetchProcessTableSnapshot, - ({ - snapshot, - snapshotSucceeded, - }): { - readonly inspector: TerminalSubprocessInspector; - readonly snapshotSucceeded: boolean; - } => ({ - inspector: (terminalPid) => - Effect.succeed(deriveSubprocessInspectResult(snapshot, terminalPid, platform)), + fetchProcessTableSnapshot(fallbackTimeout), + ({ snapshot, snapshotSucceeded, queryElapsedMs }) => ({ + inspector: Result.map( + snapshot, + (table): TerminalSubprocessInspector => + (terminalPid) => + Effect.succeed(deriveSubprocessInspectResult(table, terminalPid, platform)), + ), snapshotSucceeded, + queryElapsedMs, }), ); const subprocessPollIntervalMs = @@ -2632,39 +2668,29 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func })); if (runningSessions.length === 0) { - return true; + return { snapshotSucceeded: true, queryElapsedMs: 0 }; } if ( runningSessions.every(({ session }) => isQuiet(session)) && skippedQuietTicks < QUIET_SUBPROCESS_SNAPSHOT_EVERY_TICKS - 1 ) { skippedQuietTicks += 1; - return true; + return { snapshotSucceeded: true, queryElapsedMs: 0 }; } skippedQuietTicks = 0; - const inspectorOption = yield* acquireSubprocessInspector.pipe( - Effect.asSome, - Effect.catch((reason) => - Effect.logWarning("failed to snapshot processes for terminal subprocess polling", { - reason, - }).pipe( - Effect.as( - Option.none<{ - readonly inspector: TerminalSubprocessInspector; - readonly snapshotSucceeded: boolean; - }>(), - ), - ), - ), + const { inspector, snapshotSucceeded, queryElapsedMs } = yield* acquireSubprocessInspector( + PROCESS_TABLE_QUERY_TIMEOUT, ); - - if (Option.isNone(inspectorOption)) { + if (Result.isFailure(inspector)) { + yield* Effect.logWarning("failed to snapshot processes for terminal subprocess polling", { + reason: inspector.failure, + }); quietSessions = new WeakMap(); - return false; + return { snapshotSucceeded: false, queryElapsedMs }; } - const { inspector: subprocessInspector, snapshotSucceeded } = inspectorOption.value; + const subprocessInspector = inspector.success; const checkSubprocessActivity = Effect.fn("terminal.checkSubprocessActivity")(function* ( candidate: (typeof runningSessions)[number], ) { @@ -2760,7 +2786,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func discard: true, }); - return snapshotSucceeded; + return { snapshotSucceeded, queryElapsedMs }; }); const hasRunningSessions = readManagerState.pipe( @@ -2775,13 +2801,14 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func Effect.flatMap((active) => active ? pollSubprocessActivity().pipe( - Effect.flatMap((snapshotSucceeded) => { + Effect.flatMap(({ snapshotSucceeded, queryElapsedMs }) => { subprocessSnapshotFailureCount = snapshotSucceeded ? 0 : Math.min(subprocessSnapshotFailureCount + 1, 30); const delayMs = subprocessSnapshotPollDelayMs( subprocessPollIntervalMs, subprocessSnapshotFailureCount, + queryElapsedMs, ); return Effect.sleep(delayMs); }), @@ -3417,7 +3444,10 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func running.map((session) => [session.terminalId, terminalActivityMark(session)]), ); // Inspect now so commands started after the last poll still protect their terminals. - const { inspector } = yield* acquireSubprocessInspector; + const { inspector: inspectorResult } = yield* acquireSubprocessInspector( + platform === "win32" ? CLOSE_IDLE_QUERY_TIMEOUT.win32 : CLOSE_IDLE_QUERY_TIMEOUT.posix, + ); + const inspector = yield* Effect.fromResult(inspectorResult); yield* Effect.forEach( running, (session) => From f3b0194c7b43251791e9732323d5098a5823cd26 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 29 Oct 2026 22:09:42 -0700 Subject: [PATCH 403/817] fix(server): show readable provider runtime failure banners (#24614) Co-authored-by: Claude Opus 5.5 Co-authored-by: AdEx-Partners-DE --- .../src/orchestration-v2/ProviderSessionManager.test.ts | 4 ++++ .../src/orchestration-v2/ProviderSessionManager.ts | 9 ++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index cac8e4fbbb8e0..86b173f80dcba 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -2551,6 +2551,10 @@ it.effect("ProviderSessionManagerV2 releases sessions when provider event stream assert.isTrue(Option.isNone(liveSession)); assert.equal(runtimeState.closeCount, 1); assert.equal(projection.providerSessions.at(-1)?.status, "error"); + assert.equal( + projection.providerSessions.at(-1)?.lastError, + "The provider event stream closed unexpectedly. Retry the turn; if it keeps failing, check the provider and server logs.", + ); }); yield* effect.pipe( diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index df2ee630df38b..b9887a4844600 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -50,6 +50,7 @@ import * as CommandOutputHub from "./CommandOutputHub.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderEventIngestor from "./ProviderEventIngestor.ts"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import { makeProviderFailure } from "@t3tools/provider-core/server/failure"; import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; @@ -1987,10 +1988,16 @@ export const layerWithOptions = ( cause, }); yield* Ref.set(entry.eventSubscribers, new Map()); + // lastError is the thread banner, so it gets the same bounded + // message as a failed turn; the raw cause survives only in the log. + yield* Effect.logWarning("orchestration-v2.provider-session-runtime-failed", { + providerSessionId: entry.runtime.providerSessionId, + cause, + }); yield* releaseEntry({ providerSessionId: entry.runtime.providerSessionId, reason: "runtime_error", - detail: Cause.pretty(cause), + detail: makeProviderFailure({ cause }).message, }).pipe(logReleaseFailure(entry.runtime.providerSessionId)); }), ), From 2c119bd975deb06f49505a0af3ec8d272806b923 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 29 Oct 2026 22:10:42 -0700 Subject: [PATCH 404/817] fix(gitlab): share merge request reads across detail and checks (#24392) Co-authored-by: Claude Opus 5.5 --- .../pullRequest/PullRequestService.test.ts | 92 +++++++++++ .../src/pullRequest/PullRequestService.ts | 53 +++--- .../src/server/PullRequestProvider.ts | 10 ++ .../server/GitLabPullRequestProvider.test.ts | 152 ++++++++++++++++++ .../src/server/GitLabPullRequestProvider.ts | 117 ++++++++++++-- 5 files changed, 394 insertions(+), 30 deletions(-) diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts index 6c6c8215aa315..2b4d2f68c5502 100644 --- a/apps/server/src/pullRequest/PullRequestService.test.ts +++ b/apps/server/src/pullRequest/PullRequestService.test.ts @@ -2189,6 +2189,98 @@ it.effect("does not revive old summaries when project epochs are evicted", () => }), ); +it.effect("a refresh or a finished turn drops the provider's own change request reads", () => + Effect.gen(function* () { + const forgotten: Array<{ readonly repository: string; readonly number?: number } | undefined> = + []; + const service = yield* makeService({ + projects: [ + project({ + id: "p1", + title: "web", + workspaceRoot: "/a", + repository: "acme/web", + provider: "gitlab", + }), + ], + providers: [ + fakeProvider(SourceControlProviderKind.make("gitlab"), { + forgetChangeRequestReads: (scope) => Effect.sync(() => void forgotten.push(scope)), + }), + ], + }); + const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + + yield* service.invalidate({ reference }); + yield* service.refreshAfterTurn(reference.projectId); + yield* service.invalidate({}); + + assert.deepStrictEqual(forgotten, [ + { repository: "acme/web", number: 1 }, + undefined, + undefined, + ]); + }), +); + +it.effect("a read during a refresh cannot keep the provider's old change request", () => + Effect.gen(function* () { + let hostTitle = "old"; + let held: string | undefined; + let gate: + | { readonly entered: Deferred.Deferred; readonly release: Deferred.Deferred } + | undefined; + const service = yield* makeService({ + projects: [ + project({ + id: "p1", + title: "web", + workspaceRoot: "/a", + repository: "acme/web", + provider: "gitlab", + }), + ], + providers: [ + fakeProvider(SourceControlProviderKind.make("gitlab"), { + getChangeRequest: () => + Effect.sync(() => { + held ??= hostTitle; + return { ...hostedChangeRequest("body"), title: held }; + }), + forgetChangeRequestReads: () => + Effect.gen(function* () { + if (gate !== undefined) { + yield* Deferred.succeed(gate.entered, undefined); + yield* Deferred.await(gate.release); + } + held = undefined; + }), + }), + ], + }); + const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + const refreshWithReadInBetween = (refresh: Effect.Effect) => + Effect.gen(function* () { + gate = { entered: yield* Deferred.make(), release: yield* Deferred.make() }; + const running = yield* refresh.pipe(Effect.forkChild()); + yield* Deferred.await(gate.entered); + yield* service.detail(reference); + yield* Deferred.succeed(gate.release, undefined); + yield* Fiber.join(running); + gate = undefined; + }); + + assert.strictEqual((yield* service.detail(reference)).title, "old"); + hostTitle = "after turn"; + yield* refreshWithReadInBetween(service.refreshAfterTurn(reference.projectId)); + assert.strictEqual((yield* service.detail(reference)).title, "after turn"); + + hostTitle = "after refresh"; + yield* refreshWithReadInBetween(service.invalidate({ reference })); + assert.strictEqual((yield* service.detail(reference)).title, "after refresh"); + }), +); + it.effect("close and reopen notify subscribed readers after invalidating their cached state", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index 854d182f155ec..9f18426be198e 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -528,6 +528,9 @@ function withRateLimitBackoff( listChangeRequestStats: wrap("listChangeRequestStats", api.listChangeRequestStats), }), getChangeRequest: wrap("getChangeRequest", api.getChangeRequest), + ...(api.forgetChangeRequestReads === undefined + ? {} + : { forgetChangeRequestReads: api.forgetChangeRequestReads }), ...(api.getChangeRequestPreview === undefined ? {} : { getChangeRequestPreview: wrap("getChangeRequestPreview", api.getChangeRequestPreview) }), @@ -3423,6 +3426,13 @@ export const make = Effect.gen(function* () { return { stats: [...held, ...result.stats] }; }); + const forgetProviderReads = (scope?: { readonly repository: string; readonly number?: number }) => + Effect.forEach( + registry.kinds, + (kind) => registry.get(kind)?.forgetChangeRequestReads?.(scope) ?? Effect.void, + { discard: true }, + ); + const invalidate: PullRequestService["Service"]["invalidate"] = Effect.fn( "PullRequestService.invalidate", )(function* (input, options) { @@ -3438,13 +3448,15 @@ export const make = Effect.gen(function* () { if (reference !== undefined) { yield* canonicalRef(reference).pipe( Effect.flatMap((ref) => - readCache - .invalidate(refScope(ref)) - .pipe(Effect.andThen(Effect.sync(() => bumpRefEpoch(ref)))), + forgetProviderReads({ repository: ref.repository, number: ref.number }).pipe( + Effect.andThen(readCache.invalidate(refScope(ref))), + Effect.andThen(Effect.sync(() => bumpRefEpoch(ref))), + ), ), Effect.ignore, ); } else { + yield* forgetProviderReads(); listingsEpoch = ++epochCounter; everyFileRevisionEpoch = ++epochCounter; viewersByHost.clear(); @@ -3455,22 +3467,27 @@ export const make = Effect.gen(function* () { } }); - const refreshAfterTurn: PullRequestService["Service"]["refreshAfterTurn"] = (projectId) => - Effect.suspend(() => { - listingsEpoch = ++epochCounter; - projectEpochs.delete(projectId); - if (projectEpochs.size >= REF_EPOCH_CAPACITY) { - const oldest = projectEpochs.keys().next().value; - if (oldest !== undefined) { - projectEpochFloor = projectEpochs.get(oldest)!; - projectEpochs.delete(oldest); - } + const refreshAfterTurn: PullRequestService["Service"]["refreshAfterTurn"] = Effect.fn( + "PullRequestService.refreshAfterTurn", + )(function* (projectId) { + // Everything the provider holds, not just the project's repository: a turn can touch a + // change request reached through another repository, and no epoch may move until those + // reads are gone, or a reader in between keeps the old one under the new epoch. + yield* forgetProviderReads(); + listingsEpoch = ++epochCounter; + projectEpochs.delete(projectId); + if (projectEpochs.size >= REF_EPOCH_CAPACITY) { + const oldest = projectEpochs.keys().next().value; + if (oldest !== undefined) { + projectEpochFloor = projectEpochs.get(oldest)!; + projectEpochs.delete(oldest); } - projectEpochs.set(projectId, listingsEpoch); - return readCache - .invalidate(`project:${projectId}`) - .pipe(Effect.andThen(SubscriptionRef.set(pullRequestRefreshes, listingsEpoch))); - }); + } + projectEpochs.set(projectId, listingsEpoch); + const epoch = listingsEpoch; + yield* readCache.invalidate(`project:${projectId}`); + yield* SubscriptionRef.set(pullRequestRefreshes, epoch); + }); const invalidatedByMutation = ( diff --git a/packages/source-control-core/src/server/PullRequestProvider.ts b/packages/source-control-core/src/server/PullRequestProvider.ts index 46fc8fd48b0dc..63dfe8db7a85b 100644 --- a/packages/source-control-core/src/server/PullRequestProvider.ts +++ b/packages/source-control-core/src/server/PullRequestProvider.ts @@ -353,6 +353,16 @@ export interface PullRequestProviderApi { input: ProviderRepositoryRef & { readonly number: number }, ) => Effect.Effect; + /** + * For a provider that holds change request reads of its own: called when the service drops its + * reads, so a refresh or a finished turn reaches the host. No scope forgets everything; a scope + * without a number forgets the repository's change requests. + */ + readonly forgetChangeRequestReads?: (scope?: { + readonly repository: string; + readonly number?: number; + }) => Effect.Effect; + readonly getChangeRequestPreview?: ( input: ProviderRepositoryRef & { readonly number: number }, ) => Effect.Effect< diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts index 6eec9ccd09142..cc6bab6c53f42 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts @@ -1,6 +1,7 @@ import { assert, describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as TestClock from "effect/testing/TestClock"; import * as GitLabCli from "./GitLabCli.ts"; import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts"; @@ -122,6 +123,157 @@ describe("getChangeRequest base freshness", () => { ); }); +describe("merge request reads", () => { + const reference = { cwd: "/w", repository: "acme/web", host: "gitlab.com", number: 7 }; + const detail = { + number: 7, + title: "Merge request 7", + url: "https://gitlab.com/acme/web/-/merge_requests/7", + author: null, + headBranch: "feat/page", + baseBranch: "main", + state: "open" as const, + isDraft: false, + mergeability: "mergeable" as const, + additions: 0, + deletions: 0, + createdAt: "2026-07-01T00:00:00Z", + updatedAt: "2026-07-02T00:00:00Z", + reviewRequestLogins: [], + labels: [], + body: "", + changedFiles: 1, + mergedAt: null, + closedAt: null, + reviewers: [], + checks: [], + viewerCanMerge: true, + reviewerIds: [], + }; + + const countingProvider = Effect.gen(function* () { + const calls = { detail: 0, mergeCapabilities: 0 }; + const host = { viewerCanMerge: true }; + const provider = yield* make.pipe( + Effect.provide( + Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({ + getMergeRequestDetail: (input) => + Effect.sync(() => { + calls.detail += 1; + return { ...detail, number: input.number, viewerCanMerge: host.viewerCanMerge }; + }), + getProjectMergeCapabilities: () => + Effect.sync(() => { + calls.mergeCapabilities += 1; + return { merge: true, squash: true, rebase: true }; + }), + runMergeRequestAction: () => Effect.void, + }), + ), + ); + const checks = provider.getChangeRequestChecks; + const forget = provider.forgetChangeRequestReads; + if (checks === undefined || forget === undefined) { + return yield* Effect.die("GitLab answers checks and forgets its reads"); + } + return { provider, checks, forget, calls, host }; + }); + + it.effect("asks for a project's merge methods once across its merge requests", () => + Effect.gen(function* () { + const { provider, calls } = yield* countingProvider; + + yield* provider.getChangeRequest(reference); + yield* provider.getChangeRequest(reference); + yield* provider.getChangeRequest({ ...reference, number: 8 }); + + expect(calls.mergeCapabilities).toBe(1); + }), + ); + + it.effect("answers checks from the merge request the detail just read", () => + Effect.gen(function* () { + const { provider, checks, calls } = yield* countingProvider; + + yield* provider.getChangeRequest(reference); + yield* checks(reference); + + expect(calls.detail).toBe(1); + }), + ); + + it.effect("reads a merge request again after a write to it", () => + Effect.gen(function* () { + const { provider, checks, calls } = yield* countingProvider; + + yield* provider.getChangeRequest(reference); + yield* provider.runAction({ ...reference, action: "ready" }); + yield* checks(reference); + + expect(calls.detail).toBe(2); + }), + ); + + it.effect("does not share reads between checkouts", () => + Effect.gen(function* () { + const { provider, calls } = yield* countingProvider; + + yield* provider.getChangeRequest(reference); + yield* provider.getChangeRequest({ ...reference, cwd: "/other" }); + + expect(calls).toEqual({ detail: 2, mergeCapabilities: 2 }); + }), + ); + + it.effect("reads a merge request again once a minute has passed", () => + Effect.gen(function* () { + const { provider, calls } = yield* countingProvider; + + yield* provider.getChangeRequest(reference); + yield* TestClock.adjust("61 seconds"); + yield* provider.getChangeRequest(reference); + + expect(calls.detail).toBe(2); + }), + ); + + it.effect("answers viewer permissions from the host, not the page's read", () => + Effect.gen(function* () { + const { provider, host } = yield* countingProvider; + + host.viewerCanMerge = false; + yield* provider.getChangeRequest(reference); + host.viewerCanMerge = true; + const granted = yield* provider.getViewerPermissions(reference); + host.viewerCanMerge = false; + const revoked = yield* provider.getViewerPermissions(reference); + + expect(granted.actions).toContain("merge"); + expect(revoked.actions).not.toContain("merge"); + }), + ); + + it.effect("reads a merge request again once its reads are forgotten", () => + Effect.gen(function* () { + const { provider, checks, forget, calls } = yield* countingProvider; + const other = { ...reference, repository: "acme/api" }; + + yield* provider.getChangeRequest(reference); + yield* provider.getChangeRequest(other); + yield* forget({ repository: "ACME/web", number: 7 }); + yield* checks(reference); + yield* checks(other); + expect(calls.detail).toBe(3); + + yield* forget({ repository: "acme/web" }); + yield* checks(reference); + yield* forget(); + yield* checks(other); + expect(calls.detail).toBe(5); + }), + ); +}); + describe("optional activity reads", () => { const reference = { cwd: "/w", repository: "acme/web", host: "gitlab.com", number: 7 }; const comment = { diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts index a9856f907ebb8..79c3d43c01966 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts @@ -1,5 +1,8 @@ import { SourceControlProviderKind } from "@t3tools/contracts"; +import * as Cache from "effect/Cache"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import type { PullRequestCapabilities, PullRequestReaction, @@ -72,6 +75,16 @@ export function gitLabViewerPermissions(input: { }; } +/** + * One page view asks for the detail and then its checks within a second, and the poll that + * follows asks again. A minute keeps those to one `glab` call without hiding a pipeline for long; + * a refresh or a finished turn drops it sooner through `forgetChangeRequestReads`. + */ +const MERGE_REQUEST_DETAIL_TTL = Duration.minutes(1); +/** A project's merge methods change in its settings, which nobody does between page views. */ +const PROJECT_MERGE_CAPABILITIES_TTL = Duration.minutes(15); +const READ_CACHE_CAPACITY = 256; + function gitLabProviderFailure( error: GitLabPullRequestCli.GitLabPullRequestCliError, ): PullRequestProviderFailure { @@ -85,6 +98,55 @@ function gitLabProviderFailure( export const make = Effect.gen(function* () { const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli; + // Keyed on the checkout as well: `glab` picks the host and the account to answer as from the + // checkout's remote and config, so two checkouts may read the same project as different people. + const mergeRequestDetails = yield* Cache.makeWith( + (key: string) => { + const [cwd, repository, number] = JSON.parse(key) as [string, string, number]; + return cli.getMergeRequestDetail({ cwd, repository, number }); + }, + { + capacity: READ_CACHE_CAPACITY, + timeToLive: (exit) => (Exit.isSuccess(exit) ? MERGE_REQUEST_DETAIL_TTL : Duration.zero), + }, + ); + const projectMergeCapabilities = yield* Cache.makeWith( + (key: string) => { + const [cwd, repository] = JSON.parse(key) as [string, string]; + return cli.getProjectMergeCapabilities({ cwd, repository }); + }, + { + capacity: READ_CACHE_CAPACITY, + timeToLive: (exit) => (Exit.isSuccess(exit) ? PROJECT_MERGE_CAPABILITIES_TTL : Duration.zero), + }, + ); + + const detailKey = (input: { + readonly cwd: string; + readonly repository: string; + readonly number: number; + }) => JSON.stringify([input.cwd, input.repository, input.number]); + const mergeRequestDetail = (input: { + readonly cwd: string; + readonly repository: string; + readonly number: number; + }) => Cache.get(mergeRequestDetails, detailKey(input)); + + // Dropped on both sides, as the service does with its own reads: a read that starts while the + // write is in flight must not outlive it. + const writing = + < + I extends { readonly cwd: string; readonly repository: string; readonly number: number }, + A, + E, + >( + write: (input: I) => Effect.Effect, + ) => + (input: I): Effect.Effect => { + const invalidate = Cache.invalidate(mergeRequestDetails, detailKey(input)); + return invalidate.pipe(Effect.andThen(write(input)), Effect.ensuring(invalidate)); + }; + const fail = (operation: string) => (error: GitLabPullRequestCli.GitLabPullRequestCliError) => new PullRequestProviderError({ provider: SourceControlProviderKind.make("gitlab"), @@ -138,7 +200,7 @@ export const make = Effect.gen(function* () { ), getChangeRequestChecks: (input) => - cli.getMergeRequestDetail(input).pipe( + mergeRequestDetail(input).pipe( Effect.map(({ state, checks }) => ({ state, checks })), Effect.mapError(fail("getChangeRequestChecks")), ), @@ -153,8 +215,8 @@ export const make = Effect.gen(function* () { getChangeRequest: (input) => Effect.all( [ - cli.getMergeRequestDetail(input), - cli.getProjectMergeCapabilities({ cwd: input.cwd, repository: input.repository }), + mergeRequestDetail(input), + Cache.get(projectMergeCapabilities, JSON.stringify([input.cwd, input.repository])), ], { concurrency: 2 }, ).pipe( @@ -209,11 +271,31 @@ export const make = Effect.gen(function* () { })), ), + // Straight from the host, never the shared read: this is what a write is refused or let + // through on, and access granted or withdrawn within the minute must count. getViewerPermissions: (input) => cli .getMergeRequestDetail(input) .pipe(Effect.mapError(fail("getViewerPermissions")), Effect.map(gitLabViewerPermissions)), + forgetChangeRequestReads: (scope) => + Cache.keys(mergeRequestDetails).pipe( + Effect.flatMap((keys) => + Effect.forEach( + Array.from(keys).filter((key) => { + if (scope === undefined) return true; + const [, repository, number] = JSON.parse(key) as [string, string, number]; + return ( + repository.toLowerCase() === scope.repository.toLowerCase() && + (scope.number === undefined || number === scope.number) + ); + }), + (key) => Cache.invalidate(mergeRequestDetails, key), + { discard: true }, + ), + ), + ), + getDiff: (input) => cli.getMergeRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))), getDiffFileContents: (input) => @@ -245,7 +327,7 @@ export const make = Effect.gen(function* () { .listProjectUsers({ cwd: input.cwd, repository: input.repository, search: input.query }) .pipe(Effect.mapError(fail("searchRepositoryAuthors"))), - setReviewerRequest: (input) => + setReviewerRequest: writing((input) => cli .setReviewerRequest({ cwd: input.cwd, @@ -255,8 +337,9 @@ export const make = Effect.gen(function* () { requested: input.requested, }) .pipe(Effect.mapError(fail("setReviewerRequest"))), + ), - runAction: (input) => + runAction: writing((input) => cli .runMergeRequestAction({ cwd: input.cwd, @@ -266,8 +349,9 @@ export const make = Effect.gen(function* () { ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }), }) .pipe(Effect.mapError(fail("runAction"))), + ), - updateChangeRequest: (input) => + updateChangeRequest: writing((input) => cli .updateMergeRequest({ cwd: input.cwd, @@ -277,10 +361,13 @@ export const make = Effect.gen(function* () { ...(input.body === undefined ? {} : { description: input.body }), }) .pipe(Effect.mapError(fail("updateChangeRequest"))), + ), - comment: (input) => cli.commentOnMergeRequest(input).pipe(Effect.mapError(fail("comment"))), + comment: writing((input) => + cli.commentOnMergeRequest(input).pipe(Effect.mapError(fail("comment"))), + ), - updateComment: (input) => + updateComment: writing((input) => cli .updateNote({ cwd: input.cwd, @@ -290,10 +377,13 @@ export const make = Effect.gen(function* () { body: input.body, }) .pipe(Effect.mapError(fail("updateComment"))), + ), - submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))), + submitReview: writing((input) => + cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))), + ), - replyToThread: (input) => + replyToThread: writing((input) => cli .replyToDiscussion({ cwd: input.cwd, @@ -303,8 +393,9 @@ export const make = Effect.gen(function* () { body: input.body, }) .pipe(Effect.mapError(fail("replyToThread"))), + ), - setReaction: (input) => + setReaction: writing((input) => cli .setReaction({ cwd: input.cwd, @@ -315,8 +406,9 @@ export const make = Effect.gen(function* () { reacted: input.reacted, }) .pipe(Effect.mapError(fail("setReaction"))), + ), - setThreadResolution: (input) => + setThreadResolution: writing((input) => cli .setDiscussionResolution({ cwd: input.cwd, @@ -326,6 +418,7 @@ export const make = Effect.gen(function* () { resolved: input.resolved, }) .pipe(Effect.mapError(fail("setThreadResolution"))), + ), }; return provider; From adba9a31d021ed9c9cc3205aa01d7ad670568e86 Mon Sep 17 00:00:00 2001 From: fixfon <12512757+fixfon@users.noreply.github.com> Date: Fri, 30 Oct 2026 08:12:34 +0300 Subject: [PATCH 405/817] fix(usage): count Claude advisor calls under the advisor model (#24139) --- .../src/provider/Drivers/claudeUsage.test.ts | 138 +++++++++++++++++- .../src/provider/Drivers/claudeUsage.ts | 60 ++++++-- apps/server/src/usage/UsageService.test.ts | 2 +- apps/server/src/usage/usageScanCache.test.ts | 18 ++- apps/server/src/usage/usageScanCache.ts | 13 +- 5 files changed, 205 insertions(+), 26 deletions(-) diff --git a/apps/server/src/provider/Drivers/claudeUsage.test.ts b/apps/server/src/provider/Drivers/claudeUsage.test.ts index a9ebb05a2e1e7..6f457f4f4cf2f 100644 --- a/apps/server/src/provider/Drivers/claudeUsage.test.ts +++ b/apps/server/src/provider/Drivers/claudeUsage.test.ts @@ -32,9 +32,9 @@ function claudeLine(overrides: { describe("parseClaudeLine", () => { it("extracts token totals and a dedupe key", () => { - const record = parseClaudeLine(claudeLine({ messageId: "msg_1", contentType: "text" })); + const [record] = parseClaudeLine(claudeLine({ messageId: "msg_1", contentType: "text" })); - expect(record).not.toBeNull(); + expect(record).toBeDefined(); expect(record?.provider).toBe("claude"); expect(record?.model).toBe("claude-fable-5"); expect(record?.totals).toEqual({ @@ -50,8 +50,8 @@ describe("parseClaudeLine", () => { it("gives every content block of one message the same dedupe key", () => { // Content-block records repeat full parent usage; summing them overcounts. - const text = parseClaudeLine(claudeLine({ messageId: "msg_2", contentType: "text" })); - const toolUse = parseClaudeLine(claudeLine({ messageId: "msg_2", contentType: "tool_use" })); + const [text] = parseClaudeLine(claudeLine({ messageId: "msg_2", contentType: "text" })); + const [toolUse] = parseClaudeLine(claudeLine({ messageId: "msg_2", contentType: "tool_use" })); expect(text?.dedupeKey).toBe(toolUse?.dedupeKey); expect(text?.totals).toEqual(toolUse?.totals); @@ -86,3 +86,133 @@ describe("parseClaudeLine", () => { expect(claudeUsageFormat.parseProjected(synthetic, undefined)).toEqual([]); }); }); + +describe("Claude advisor iterations", () => { + const advisorTurn = { + type: "assistant", + timestamp: "2026-10-22T01:31:11.984Z", + sessionId: "5a128faa-8253-489e-b935-6c08e8e670c0", + requestId: "req_1", + message: { + id: "msg_1", + model: "claude-opus-5-5", + usage: { + input_tokens: 4, + cache_read_input_tokens: 118320, + cache_creation_input_tokens: 2676, + output_tokens: 4506, + speed: "standard", + iterations: [ + { + type: "message", + input_tokens: 2, + cache_read_input_tokens: 58352, + cache_creation_input_tokens: 1616, + output_tokens: 141, + }, + { + type: "advisor_message", + model: "claude-fable-5-1", + input_tokens: 54204, + cache_read_input_tokens: 0, + cache_creation_input_tokens: 0, + output_tokens: 4229, + }, + { + type: "message", + input_tokens: 2, + cache_read_input_tokens: 59968, + cache_creation_input_tokens: 1060, + output_tokens: 4365, + }, + ], + }, + }, + }; + const withIterations = (iterations: readonly unknown[]) => ({ + ...advisorTurn, + message: { ...advisorTurn.message, usage: { ...advisorTurn.message.usage, iterations } }, + }); + const parse = (turn: unknown) => claudeUsageFormat.parseLine(JSON.stringify(turn), undefined); + + it("reports the advisor model's tokens as their own record beside the unchanged executor record", () => { + const executor = { + provider: "claude", + timestampMs: Date.parse("2026-10-22T01:31:11.984Z"), + model: "claude-opus-5-5", + sessionId: "5a128faa-8253-489e-b935-6c08e8e670c0", + totals: { + uncachedInputTokens: 4, + cachedInputTokens: 118320, + cacheCreationTokens: 2676, + outputTokens: 4506, + reasoningTokens: 0, + }, + reportedCostUsd: null, + speed: "standard", + dedupeKey: "msg_1:req_1", + }; + const expected = [ + executor, + { + ...executor, + model: "claude-fable-5-1", + totals: { + uncachedInputTokens: 54204, + cachedInputTokens: 0, + cacheCreationTokens: 0, + outputTokens: 4229, + reasoningTokens: 0, + }, + dedupeKey: expect.any(String), + }, + ]; + + expect(parse(advisorTurn)).toEqual(expected); + expect(claudeUsageFormat.parseProjected(advisorTurn, undefined)).toEqual(expected); + }); + + it("keys the advisor record apart from the executor and the same across a message's content blocks", () => { + const block = (type: string) => + parse({ ...advisorTurn, message: { ...advisorTurn.message, content: [{ type }] } }); + const [executorKey, advisorKey] = block("text").map((record) => record.dedupeKey); + + expect(advisorKey).toEqual(expect.any(String)); + expect(advisorKey).not.toBe(executorKey); + expect(block("tool_use").map((record) => record.dedupeKey)).toEqual([executorKey, advisorKey]); + + const unkeyed = parse({ + ...advisorTurn, + requestId: undefined, + message: { ...advisorTurn.message, id: undefined }, + }); + expect(unkeyed.map((record) => record.dedupeKey)).toEqual([null, null]); + }); + + it("emits only the executor record without an advisor iteration", () => { + const executorIterations = advisorTurn.message.usage.iterations.filter( + (iteration) => iteration.type === "message", + ); + + expect(parse(withIterations(executorIterations))).toHaveLength(1); + expect(claudeUsageFormat.parseProjected(withIterations([]), undefined)).toHaveLength(1); + expect( + claudeUsageFormat.parseLine( + claudeLine({ messageId: "msg_3", contentType: "text" }), + undefined, + ), + ).toHaveLength(1); + }); + + it("ignores advisor iterations without a usable model and malformed entries", () => { + const unusable = withIterations([ + null, + "advisor_message", + { type: "advisor_message", input_tokens: 5 }, + { type: "advisor_message", model: "", input_tokens: 5 }, + { type: "advisor_message", model: "", input_tokens: 5 }, + ]); + + expect(parse(unusable).map((record) => record.model)).toEqual(["claude-opus-5-5"]); + }); +}); diff --git a/apps/server/src/provider/Drivers/claudeUsage.ts b/apps/server/src/provider/Drivers/claudeUsage.ts index c5ff71a5c839e..aca7696d31df5 100644 --- a/apps/server/src/provider/Drivers/claudeUsage.ts +++ b/apps/server/src/provider/Drivers/claudeUsage.ts @@ -20,35 +20,35 @@ export const CLAUDE_SYNTHETIC_MODEL = ""; * the same complete `usage` object for the parent message. Summing them overcounts by roughly * 2.4x on a real workload, so the caller must drop repeats by `dedupeKey` and keep the first. */ -export function parseClaudeLine(line: string): UsageRecord | null { +export function parseClaudeLine(line: string): readonly UsageRecord[] { let parsed: unknown; try { parsed = JSON.parse(line); } catch { - return null; + return []; } return parseClaudeRecord(parsed); } -function parseClaudeRecord(parsed: unknown): UsageRecord | null { - if (typeof parsed !== "object" || parsed === null) return null; +function parseClaudeRecord(parsed: unknown): readonly UsageRecord[] { + if (typeof parsed !== "object" || parsed === null) return []; const record = parsed as Record; - if (record["type"] !== "assistant") return null; + if (record["type"] !== "assistant") return []; const message = record["message"]; - if (typeof message !== "object" || message === null) return null; + if (typeof message !== "object" || message === null) return []; const messageRecord = message as Record; const usage = messageRecord["usage"]; - if (typeof usage !== "object" || usage === null) return null; + if (typeof usage !== "object" || usage === null) return []; const usageRecord = usage as Record; const timestampMs = parseTimestampMs(record["timestamp"]); - if (timestampMs === null) return null; + if (timestampMs === null) return []; const model = typeof messageRecord["model"] === "string" ? messageRecord["model"] : ""; - if (model.length === 0 || model === CLAUDE_SYNTHETIC_MODEL) return null; + if (model.length === 0 || model === CLAUDE_SYNTHETIC_MODEL) return []; const messageId = typeof messageRecord["id"] === "string" ? messageRecord["id"] : null; const requestId = typeof record["requestId"] === "string" ? record["requestId"] : null; @@ -57,7 +57,7 @@ function parseClaudeRecord(parsed: unknown): UsageRecord | null { const cost = record["costUSD"]; - return { + const executor: UsageRecord = { provider: "claude", timestampMs, model, @@ -74,10 +74,40 @@ function parseClaudeRecord(parsed: unknown): UsageRecord | null { speed: usageRecord["speed"] === "fast" ? "fast" : "standard", dedupeKey, }; -} -const orEmpty = (record: UsageRecord | null): readonly UsageRecord[] => - record === null ? [] : [record]; + // Top-level `usage` is the executor's alone. Advisor calls run on another model at its own rates + // and appear only in `iterations`, so each one is its own record under that model. + const records = [executor]; + const iterations: readonly unknown[] = Array.isArray(usageRecord["iterations"]) + ? usageRecord["iterations"] + : []; + for (const [index, iteration] of iterations.entries()) { + if (typeof iteration !== "object" || iteration === null) continue; + const advisor = iteration as Record; + if (advisor["type"] !== "advisor_message") continue; + + const advisorModel = typeof advisor["model"] === "string" ? advisor["model"] : ""; + if (advisorModel.length === 0 || advisorModel === CLAUDE_SYNTHETIC_MODEL) continue; + + records.push({ + provider: "claude", + timestampMs, + model: advisorModel, + sessionId: executor.sessionId, + totals: { + uncachedInputTokens: tokenCount(advisor["input_tokens"]), + cachedInputTokens: tokenCount(advisor["cache_read_input_tokens"]), + cacheCreationTokens: tokenCount(advisor["cache_creation_input_tokens"]), + outputTokens: tokenCount(advisor["output_tokens"]), + reasoningTokens: 0, + }, + reportedCostUsd: null, + speed: executor.speed, + dedupeKey: dedupeKey === null ? null : `${dedupeKey}:advisor:${index}`, + }); + } + return records; +} export const claudeUsageFormat: TranscriptUsageFormat = { selectFields: { @@ -89,8 +119,8 @@ export const claudeUsageFormat: TranscriptUsageFormat = { message: { id: true, model: true, usage: true }, }, usageMarkers: ['"usage"'], - parseLine: (line) => orEmpty(parseClaudeLine(line)), - parseProjected: (projected) => orEmpty(parseClaudeRecord(projected)), + parseLine: (line) => parseClaudeLine(line), + parseProjected: (projected) => parseClaudeRecord(projected), }; export const claudeUsageReader: ProviderUsageReader = { diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts index bee7a8a480bc1..33f2332dbd4a5 100644 --- a/apps/server/src/usage/UsageService.test.ts +++ b/apps/server/src/usage/UsageService.test.ts @@ -2299,7 +2299,7 @@ describe("UsageService", () => { 60 + 20 * (version === 4 ? 1 : 2), ); yield* upgraded.awaitPersisted; - assert.strictEqual(SCAN_CACHE_FILE_NAME, "usage-scan-cache-v9.json"); + assert.strictEqual(SCAN_CACHE_FILE_NAME, "usage-scan-cache-v10.json"); assert.strictEqual( yield* Effect.promise(() => NodeFSP.readFile(legacyPath, "utf8")), legacy, diff --git a/apps/server/src/usage/usageScanCache.test.ts b/apps/server/src/usage/usageScanCache.test.ts index 552c97585b87e..be8ad53c6e45a 100644 --- a/apps/server/src/usage/usageScanCache.test.ts +++ b/apps/server/src/usage/usageScanCache.test.ts @@ -218,7 +218,11 @@ describe("scan cache round trip", () => { }; const restored = decodeScanCache(JSON.parse(JSON.stringify(legacy)), TEST_FORMAT_MAP); - expect(restored.get("/gone.jsonl")).toEqual(original.get("/gone.jsonl")); + expect(restored.get("/gone.jsonl")).toEqual({ + ...original.get("/gone.jsonl"), + size: -1, + position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, + }); expect(restored.get("/gone-codex.jsonl")).toEqual({ ...original.get("/gone-codex.jsonl"), size: -1, @@ -245,6 +249,18 @@ describe("scan cache round trip", () => { }, ); + it("re-parses a Claude transcript cached before advisor usage was counted", () => { + const original = cacheWith([["/claude.jsonl", 100, [record()]]]); + const v9 = { ...encodeScanCache(original), version: 9 }; + + const restored = decodeScanCache(JSON.parse(JSON.stringify(v9)), TEST_FORMAT_MAP); + expect(restored.get("/claude.jsonl")).toEqual({ + ...original.get("/claude.jsonl"), + size: -1, + position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, + }); + }); + it("rewrites only changed entries and still restores the whole cache", () => { const write = makeScanCacheWriter(); const cache = cacheWith([ diff --git a/apps/server/src/usage/usageScanCache.ts b/apps/server/src/usage/usageScanCache.ts index a74bc1840c025..70c0c3df17e3e 100644 --- a/apps/server/src/usage/usageScanCache.ts +++ b/apps/server/src/usage/usageScanCache.ts @@ -9,7 +9,7 @@ import * as Schema from "effect/Schema"; import { CLAUDE_SYNTHETIC_MODEL } from "../provider/Drivers/claudeUsage.ts"; import { GUARD_LENGTH, type TranscriptParsePosition } from "./usageTranscriptReader.ts"; -const USAGE_SCAN_CACHE_VERSION = 9 as const; +const USAGE_SCAN_CACHE_VERSION = 10 as const; const SPEED_COMPATIBLE_SINCE_VERSION = 4; /** @@ -17,8 +17,9 @@ const SPEED_COMPATIBLE_SINCE_VERSION = 4; * replace it, dropping saved usage for deleted transcripts. Separate files keep * both. */ -export const SCAN_CACHE_FILE_NAME = "usage-scan-cache-v9.json"; +export const SCAN_CACHE_FILE_NAME = "usage-scan-cache-v10.json"; export const LEGACY_SCAN_CACHE_FILE_NAMES = [ + "usage-scan-cache-v9.json", "usage-scan-cache-v8.json", "usage-scan-cache-v7.json", "usage-scan-cache-v6.json", @@ -291,10 +292,12 @@ export function decodeScanCache( } // Keep history for deleted rollouts, but re-parse incompatible reducer state. // v9 repairs skipped initial Codex requests; clean v8 entries can still resume. + // v10 adds Claude advisor calls, which no older Claude entry holds. const legacy = - format.state !== undefined && - (version < 6 || - (entry.p === "codex" && (version < 8 || (version < 9 && malformedRecords > 0)))); + (entry.p === "claude" && version < 10) || + (format.state !== undefined && + (version < 6 || + (entry.p === "codex" && (version < 8 || (version < 9 && malformedRecords > 0))))); // A corrupt state disqualifies the entry: resuming with it would attach // appended usage to the wrong model or replay fork-copied history. if (!legacy && !isValidState.get(entry.p)?.(entry.cs)) continue; From d5536f6052c0027533f40bd9520827b69946d056 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Fri, 30 Oct 2026 10:43:05 +0530 Subject: [PATCH 406/817] fix(web): name the sidebar logo link T3 Code home (#24209) Co-authored-by: PR Batch Tester Co-authored-by: Claude Opus 5.5 Co-authored-by: Julius Marminge --- apps/web/src/components/sidebar/SidebarChrome.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/src/components/sidebar/SidebarChrome.tsx b/apps/web/src/components/sidebar/SidebarChrome.tsx index e233a4144d435..b136d47fd9c40 100644 --- a/apps/web/src/components/sidebar/SidebarChrome.tsx +++ b/apps/web/src/components/sidebar/SidebarChrome.tsx @@ -103,7 +103,7 @@ export function SidebarBrandWidthProbe({ function SidebarBrand({ onBackdrop }: { onBackdrop: boolean }) { return ( Date: Thu, 29 Oct 2026 22:14:17 -0700 Subject: [PATCH 407/817] fix(server): fail Claude turns waiting for unsupported mod input (#24320) Co-authored-by: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.test.ts | 166 ++++++++++++++++++ .../Adapters/ClaudeAdapterV2.ts | 38 ++++ 2 files changed, 204 insertions(+) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index fb17c34713fd8..c38ec736884ea 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -9159,6 +9159,172 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + // regression: #17531 a mod that holds a tool behind a focused pane must fail the turn, not hang it + it.effect.each([ + { case: "fails a turn whose mod requests focus for a pane T3 cannot show", focus: true }, + { case: "keeps a turn running beside a passive mod pane", focus: false }, + ] as const)("$case", ({ focus }) => + Effect.scoped( + Effect.gen(function* () { + const closed = yield* Deferred.make(); + const harness = yield* makeWakeHarnessWithOptions({ + close: () => Deferred.succeed(closed, undefined), + }); + const now = yield* DateTime.now; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-mod-pane-focus"), + text: "Run rm -r build", + attachments: [], + }), + ); + // Captured from Claude 2.1.303 with the blast-radius mod holding a Bash + // call: the mod waits for keyboard input in its pane and nothing else + // arrives until it gives up. + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "system", + subtype: "ui_panes", + panes: [ + { id: "blast-radius", title: "Blast Radius", plugin: "blast-radius", rows: 10 }, + ], + shown_id: "blast-radius", + focused_id: null, + focus_requested_id: focus ? "blast-radius" : null, + uuid: "00000000-0000-4000-8000-000000000795", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "system", + subtype: "ui_invalidate", + event: "ui.render", + uuid: "00000000-0000-4000-8000-000000000796", + session_id: WAKE_NATIVE_SESSION, + }), + ); + // Frames are handled in order, so a later notice proves the pane frame + // was handled without the turn ending. + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "system", + subtype: "informational", + content: "Processing barrier.", + level: "warning", + uuid: "00000000-0000-4000-8000-000000000797", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* harness.until( + () => + harness.terminalEvents().length > 0 || + harness.events.some( + (event) => + event.type === "turn_item.updated" && event.turnItem.type === "system_notice", + ), + ); + const [terminal] = harness.terminalEvents(); + if (!focus) { + assert.equal(terminal, undefined); + return; + } + assert.equal(terminal?.status, "failed"); + if (terminal?.status !== "failed") return; + assert.include(terminal.failure.message, "blast-radius"); + // The held tool call is abandoned by closing the query, never answered. + yield* Deferred.await(closed); + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ), + ); + + // regression: #17531 a follow-up sent while the failed mod turn's process closes gets a new process + it.effect("runs a follow-up in a fresh query while the mod-blocked query is closing", () => + Effect.scoped( + Effect.gen(function* () { + const releaseClose = yield* Deferred.make(); + const replacementClosedOld = yield* Deferred.make(); + let oldCloses = 0; + const harness = yield* makeWakeHarnessWithOptions({ + // The held CLI never answers an interrupt; closure must not need one. + interrupt: Effect.never, + close: (sdkMessages) => + Effect.suspend(() => + ++oldCloses === 2 ? Deferred.succeed(replacementClosedOld, undefined) : Effect.void, + ).pipe( + Effect.andThen(Deferred.await(releaseClose)), + Effect.andThen(Queue.shutdown(sdkMessages)), + ), + freshQueueOnReopen: true, + }); + // Added after the harness so it runs first: a failed assertion must not + // leave teardown waiting on the held close. + yield* Effect.addFinalizer(() => Deferred.succeed(releaseClose, undefined)); + const now = yield* DateTime.now; + const turnInput = makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-mod-pane-blocked"), + text: "Run rm -r build", + attachments: [], + }); + yield* harness.runtime.startTurn(turnInput); + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "system", + subtype: "ui_panes", + panes: [ + { id: "blast-radius", title: "Blast Radius", plugin: "blast-radius", rows: 10 }, + ], + shown_id: "blast-radius", + focused_id: null, + focus_requested_id: "blast-radius", + uuid: "00000000-0000-4000-8000-000000000798", + session_id: WAKE_NATIVE_SESSION, + }), + ); + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "failed"); + + const followUp = yield* harness.runtime + .startTurn({ + ...turnInput, + attemptId: RunAttemptId.make("attempt-claude-after-mod-pane"), + providerTurnOrdinal: 2, + }) + .pipe(Effect.forkScoped); + // Reusing the closing process would offer the prompt to it instead. + yield* Effect.raceFirst( + Deferred.await(replacementClosedOld), + harness.until(() => harness.offeredMessages.length >= 2), + ); + assert.isTrue(yield* Deferred.isDone(replacementClosedOld)); + yield* Deferred.succeed(releaseClose, undefined); + yield* Fiber.join(followUp); + assert.equal(harness.processQueues.length, 2); + yield* harness.offerAndWait( + makeResultFrame({ uuid: "after-mod-pane-result", result: "Done." }), + ); + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "completed"); + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ), + ); + // regression: #16897 a prompt whose uuid the session already holds must not hang or end early it.effect("keeps a started prompt running until its result", () => Effect.scoped( diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 496a0b2e77d0f..de13c4bb6d106 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -4213,6 +4213,20 @@ function claudeTaskString(value: unknown, key: string): string | undefined { return typeof field === "string" && field.trim().length > 0 ? field.trim() : undefined; } +// A Claude Code mod can hold a tool call until the user acts in its terminal +// pane. T3 cannot provide the requested pane interaction (#17531). +// Passive panes never request focus and keep working. +function claudeFocusRequestedPanePlugin(message: SDKMessage): string | null { + if (message.type !== "system" || claudeTaskField(message, "subtype") !== "ui_panes") return null; + const paneId = claudeTaskString(message, "focus_requested_id"); + if (paneId === undefined) return null; + const panes = claudeTaskField(message, "panes"); + const pane = Array.isArray(panes) + ? panes.find((entry) => claudeTaskField(entry, "id") === paneId) + : undefined; + return claudeTaskString(pane, "plugin") ?? paneId; +} + function claudeTaskStatus(value: unknown): OrchestrationV2PlanStep["status"] | undefined { switch (value) { case "pending": @@ -8182,6 +8196,28 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( } return; } + const focusedPlugin = claudeFocusRequestedPanePlugin(message); + if (focusedPlugin !== null && context === (yield* Ref.get(activeTurn))) { + yield* Effect.logWarning("orchestration-v2.claude-mod-pane-focus-unsupported", { + providerTurnId: context.providerTurnId, + plugin: focusedPlugin, + }); + liveQuery.stopping = true; + yield* finalizeActiveTurn({ + context, + status: "failed", + completedAt: yield* DateTime.now, + failure: makeProviderFailure({ + class: "provider_error", + code: "claude_mod_ui_unsupported", + message: `The Claude Code mod "${focusedPlugin}" is waiting for input in its terminal pane, which T3 Code cannot show. Disable the mod for sessions run from T3 Code, or run the task in the Claude Code terminal.`, + }), + }); + // Closing ends the CLI process and abandons the held tool call + // without answering it. Not interrupt: the held CLI may never ack it. + yield* liveQuery.query.close.pipe(Effect.ignore); + return; + } yield* trackClaudeGoal({ nativeThreadId: liveQuery.nativeThreadId, context, message }); if (message.type === "stream_event" && !message.parent_tool_use_id) { @@ -9817,6 +9853,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( if ( existing !== null && existing.nativeThreadId === nativeThreadId && + !existing.stopping && isClaudeProviderContinuationTurn(turnInput) ) { return existing; @@ -9848,6 +9885,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( existing !== null && existing.nativeThreadId === nativeThreadId && existing.queryPolicyKey === queryPolicyKey && + !existing.stopping && existing.selection.queryIdentity === compiledSelection.queryIdentity ) { // A denied ExitPlanMode leaves Claude in plan mode. Restore only from plan: From 6b1245cceda1d504b6f16b438e16f2a2e08f3388 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 29 Oct 2026 22:20:05 -0700 Subject: [PATCH 408/817] fix(server): Stop always completes, and an agent that ignores it can be force stopped (#27252) Co-authored-by: Claude Opus 5.5 --- .../features/threads/ThreadDetailScreen.tsx | 76 ++++++++ .../threads/floating-working-control.tsx | 28 ++- .../threads/floating-working-status.ts | 6 + apps/server/src/auth/RpcAuthorization.ts | 1 + .../src/environment/ServerEnvironment.ts | 1 + .../src/observability/RpcInstrumentation.ts | 1 + .../Adapters/AcpAdapterV2.test.ts | 90 +++++++++ .../Adapters/ClaudeAdapterV2.ts | 46 ++--- .../src/orchestration-v2/EffectWorker.test.ts | 20 +- .../src/orchestration-v2/EffectWorker.ts | 49 +++-- .../src/orchestration-v2/Orchestrator.ts | 59 +++++- .../ProviderSessionManager.test.ts | 158 +++++++++++++++- .../ProviderSessionManager.ts | 139 ++++++++++++-- .../ProviderTurnControlService.test.ts | 2 + .../ProviderTurnControlService.ts | 27 ++- .../ThreadManagementService.test.ts | 173 ++++++++++++++++++ .../ThreadManagementService.ts | 166 +++++++++++++++++ .../src/orchestration-v2/ThreadStop.test.ts | 112 ++++++++++++ apps/server/src/process/agentScope.test.ts | 32 ++++ apps/server/src/process/agentScope.ts | 44 ++++- .../src/relay/AgentAwarenessRelay.test.ts | 1 + apps/server/src/ws.ts | 2 + apps/web/src/components/ChatView.tsx | 12 +- .../components/chat/ThreadActivityBanners.tsx | 43 +++++ .../src/components/chat/useForceStopThread.ts | 59 ++++++ .../components/chat/useThreadLifecycle.tsx | 35 +++- .../client-runtime/src/state/orchestration.ts | 4 + .../client-runtime/src/state/threadDetail.ts | 28 +++ .../src/state/threadExecution.test.ts | 69 +++++++ .../src/state/threadExecution.ts | 49 +++++ .../contracts/src/clientRpcPermissions.ts | 2 + packages/contracts/src/environment.ts | 2 + packages/contracts/src/orchestrationV2.ts | 53 ++++++ packages/contracts/src/rpc.ts | 8 + packages/provider-acp/src/server/adapter.ts | 61 +++--- .../src/server/ProviderAdapter.ts | 16 ++ packages/shared/src/AgentScope.ts | 7 + 37 files changed, 1583 insertions(+), 98 deletions(-) create mode 100644 apps/web/src/components/chat/useForceStopThread.ts diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 27655f503bd65..6695e7963eff0 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -46,6 +46,7 @@ import type { ScopedThreadRef, ServerConfig as T3ServerConfig, UsageLimitsReport, + RunId, } from "@t3tools/contracts"; import { appendCodexArtifactTemplateUsePrompt, @@ -156,8 +157,10 @@ import { import { appAtomRegistry } from "../../state/atom-registry"; import { threadStreamHaptics } from "./threadStreamHaptics"; import { useAtomCommand } from "../../state/use-atom-command"; +import { orchestrationEnvironment } from "../../state/orchestration"; import { useDelayedStatus } from "../../lib/useDelayedStatus"; import type { PendingUserInputDraftAnswer } from "@t3tools/client-runtime/state/pending-user-input"; +import type { RunStopPresentation } from "@t3tools/client-runtime/state/thread-execution"; import type { PendingApproval, PendingUserInput, @@ -339,6 +342,9 @@ const threadVisitTracker = createThreadVisitTracker({ // Past the composer's 180 ms height animation. const COMPOSER_HEIGHT_SETTLE_MS = 220; +const NO_RUN_STOP_ATOM = Atom.make(null).pipe( + Atom.withLabel("mobile-thread-run-stop:empty"), +); // Anchors, the submitted message, follow state and pending scrolls belong to // one thread, so the body remounts when the thread changes. @@ -528,6 +534,50 @@ function ThreadDetailBody(props: ThreadDetailScreenProps) { const unsettleThread = useAtomCommand(threadEnvironment.unsettle, { reportFailure: false }); const updateMetadata = useAtomCommand(threadEnvironment.updateMetadata, { reportFailure: false }); const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false }); + const anyRunStop = useAtomValue( + props.selectedThreadDetailRef === null + ? NO_RUN_STOP_ATOM + : environmentThreadDetails.runStopAtom(props.selectedThreadDetailRef), + ); + // A background Stop matters only while that work is still pending. + const runStop = + anyRunStop?.background && props.selectedThread.pendingBackgroundTasks.length === 0 + ? null + : anyRunStop; + const forceStopThread = useAtomCommand(orchestrationEnvironment.forceStopThread, { + reportFailure: false, + }); + const canForceStop = + useAtomValue(orchestrationEnvironment.forceStopThread.permissionAtom(props.environmentId)) && + props.serverConfig?.environment.capabilities.threadForceStop === true; + const [forceStoppingKey, setForceStoppingKey] = useState(null); + // The run that ignored Stop, so a confirmation left open cannot hit a newer run. + const forceStop = async (runId: RunId | undefined) => { + const threadKey = selectedThreadKey; + setForceStoppingKey(threadKey); + const result = await forceStopThread({ + environmentId: props.environmentId, + input: + runId === undefined + ? { threadId: props.selectedThread.id } + : { threadId: props.selectedThread.id, runId }, + }); + setForceStoppingKey((current) => (current === threadKey ? null : current)); + if (result._tag === "Failure") { + if (!isAtomCommandInterrupted(result)) Dialog.alert("Could not force stop the agent"); + return; + } + const others = result.value.sharedWithThreadIds.length; + if (result.value.outcome === "releasing") { + Dialog.alert("Turn stopped; the agent is still shutting down"); + } + if (result.value.outcome === "shared") { + Dialog.alert( + "Turn stopped; the agent process kept running", + `It is shared with ${others === 0 ? "other" : others} working ${others === 1 ? "thread" : "threads"}. Stop those to free it.`, + ); + } + }; const [statusRequest, setStatusRequest] = useState<{ threadKey: string } | null>(null); const statusPending = statusRequest?.threadKey === selectedThreadKey; const [lifecycleNow, setLifecycleNow] = useState(() => new Date().toISOString()); @@ -619,6 +669,32 @@ function ThreadDetailBody(props: ThreadDetailScreenProps) { if (connectionStatus !== null && !props.draftMode) { return connectionStatus; } + // Before the request check: an agent stuck on an approval may also ignore Stop. + if (runStop !== null && contentPresentationKind === "ready") { + const unresponsive = runStop.state === "unresponsive"; + return { + kind: "stop", + unresponsive, + label: unresponsive ? "Not responding to Stop" : "Stopping…", + action: + unresponsive && canForceStop + ? { + label: forceStoppingKey === selectedThreadKey ? "Force stopping..." : "Force stop", + accessibilityLabel: "Force stop the agent", + disabled: forceStoppingKey === selectedThreadKey, + onPress: () => + Dialog.confirm({ + title: "Force stop the agent?", + message: + "It has not answered Stop. Force stop ends the turn and kills the agent's processes, unless other working threads share them.", + confirmText: "Force stop", + destructive: true, + onConfirm: () => void forceStop(runStop.runId), + }), + } + : null, + }; + } if (props.activePendingApproval !== null || props.activePendingUserInput !== null) { return null; } diff --git a/apps/mobile/src/features/threads/floating-working-control.tsx b/apps/mobile/src/features/threads/floating-working-control.tsx index 3709cf2affa86..c1440535e9cad 100644 --- a/apps/mobile/src/features/threads/floating-working-control.tsx +++ b/apps/mobile/src/features/threads/floating-working-control.tsx @@ -83,7 +83,9 @@ export function FloatingWorkingControl(props: { const [queueWidth, setQueueWidth] = useState(0); const [actionWidth, setActionWidth] = useState(0); const action = - props.status?.kind === "background" || props.status?.kind === "lifecycle" + props.status?.kind === "background" || + props.status?.kind === "lifecycle" || + props.status?.kind === "stop" ? props.status.action : null; const [agentsWidth, setAgentsWidth] = useState(0); @@ -471,6 +473,30 @@ function FloatingStatusLabel(props: { ); } + if (props.status.kind === "stop") { + return ( + + {props.status.unresponsive ? ( + + ) : ( + + )} + + {props.status.label} + + + ); + } if (props.status.kind === "goal") { return ( { }).pipe(Effect.provide(layerTest), Effect.scoped), ); + it.live("lets a caller abandon Stop while hard teardown stalls, and finishes the teardown", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const path = yield* Path.Path; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + const protocolEvents = yield* Queue.bounded(256); + const teardownStarted = yield* Deferred.make(); + const releaseTeardown = yield* Deferred.make(); + let runtimeOrdinalSeen = 0; + const instanceId = ProviderInstanceId.make("acp-test"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + interruptPromptOnCancel: true, + restartRuntimeAfterInterrupt: true, + terminateRuntimeProcessGroupOnInterrupt: true, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + ownDetachedProcessGroup: true, + processGroupPlatform: "win32", + windowsProcessTreeTerminator: () => + Deferred.succeed(teardownStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseTeardown)), + ), + environment: (runtimeOrdinal) => { + runtimeOrdinalSeen = runtimeOrdinal; + return runtimeOrdinal === 1 ? { T3_ACP_HANG_PROMPT_FOREVER: "1" } : {}; + }, + protocolEvents, + }), + }, + selfInvocation, + }); + const threadId = ThreadId.make("thread-acp-abandoned-hard-teardown"); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-abandoned-hard-teardown"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + yield* runtime + .startTurn( + makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), + ) + .pipe(Effect.forkScoped); + const providerTurnId = idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), + }); + yield* pollProtocolMethods(protocolEvents); + const interruptFiber = yield* runtime + .interruptTurn({ providerThread, providerTurnId, requestRuntimeRestart: true }) + .pipe(Effect.forkScoped); + yield* Deferred.await(teardownStarted); + + // The session manager's Stop timeout interrupts this call; it must not wait for teardown. + yield* Fiber.interrupt(interruptFiber); + + const startFiber = yield* runtime + .startTurn( + makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 2 }), + ) + .pipe(Effect.forkScoped); + yield* Deferred.succeed(releaseTeardown, undefined); + yield* Fiber.join(startFiber); + assert.equal(runtimeOrdinalSeen, 2); + const replacementMethods = yield* pollProtocolMethods(protocolEvents); + assert.equal(replacementMethods.filter((method) => method === "session/resume").length, 1); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + it.effect( "direct Stop on a deferred subagent hold terminalizes the subagent and does not carry it forward", () => diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index de13c4bb6d106..a821a4713b292 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -322,6 +322,8 @@ const WORKFLOW_MEMBER_TRANSCRIPT_FLUSH_MS = 500; // A steer waits at most this long, from its request, for its foreground // subagents to move to the background before it is sent. const BACKGROUND_MOVE_TIMEOUT_MS = 5_000; +// How long a Stop waits for the CLI to exit before the user is offered Force stop. +const CLAUDE_STOP_CONFIRM_TIMEOUT_MS = 10_000; const CLAUDE_GROUP_WATCH_SCRIPT = [ "{ trap '' TERM; read -r _ <&3; kill -TERM 0; sleep 5; kill -KILL 0; } /dev/null 2>&1 &", @@ -10471,44 +10473,36 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( yield* existing.query.interrupt; yield* existing.query.close.pipe(Effect.ignore); const closed = yield* Deferred.await(existing.closed).pipe( - Effect.timeoutOption("10 seconds"), + Effect.timeoutOption(CLAUDE_STOP_CONFIRM_TIMEOUT_MS), ); if (Option.isSome(closed)) { return; } - - const completedAt = yield* DateTime.now; + // The turn stays open: the CLI may still be working, and the user decides + // whether to Force stop it. yield* Effect.logWarning("orchestration-v2.claude-query-interrupt-timeout", { providerSessionId: input.providerSessionId, providerThreadId: turnInput.providerThread.id, providerTurnId: turnInput.providerTurnId, }); - const ownedLiveQuery = yield* Ref.modify(queryContext, (current) => - current?.query === existing.query ? [true, null] : [false, current], - ); - if (ownedLiveQuery) { - existing.stopping = true; - yield* finalizeActiveTurnAfterQueryExit(existing); - yield* endSubagentCallsOfClosedQuery(existing.nativeThreadId, "interrupted"); - } else { - yield* finalizeActiveTurn({ - context: currentTurn, - status: "interrupted", - completedAt, - }); - } - yield* Deferred.succeed(existing.closed, undefined); + return yield* new ProviderAdapter.ProviderAdapterInterruptTimeoutError({ + driver: CLAUDE_PROVIDER, + providerThreadId: turnInput.providerThread.id, + providerTurnId: turnInput.providerTurnId, + timeoutMs: CLAUDE_STOP_CONFIRM_TIMEOUT_MS, + }); }, (effect, turnInput) => effect.pipe( - Effect.mapError( - (cause) => - new ProviderAdapter.ProviderAdapterInterruptError({ - driver: CLAUDE_PROVIDER, - providerThreadId: turnInput.providerThread.id, - providerTurnId: turnInput.providerTurnId, - cause, - }), + Effect.mapError((cause) => + cause._tag === "ProviderAdapterInterruptTimeoutError" + ? cause + : new ProviderAdapter.ProviderAdapterInterruptError({ + driver: CLAUDE_PROVIDER, + providerThreadId: turnInput.providerThread.id, + providerTurnId: turnInput.providerTurnId, + cause, + }), ), ), ); diff --git a/apps/server/src/orchestration-v2/EffectWorker.test.ts b/apps/server/src/orchestration-v2/EffectWorker.test.ts index cb130930372c8..2329f2aa20cf0 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.test.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.test.ts @@ -111,6 +111,8 @@ function layerExecutorFor(input: { closeInstance: () => Effect.void, release: () => record("release"), detach: () => record("detach"), + otherWorkingThreads: () => Effect.succeed([]), + releaseUnlessBusy: () => Effect.succeed(true), }), ), Layer.succeed( @@ -167,7 +169,18 @@ function layerExecutorFor(input: { ); } -it.effect("settles a stopped run when its adapter has already lost the native turn", () => +it.effect.each([ + { + name: "settles a stopped run when its adapter has already lost the native turn", + unresponsive: false, + dispatched: ["thread.background-work.settle"], + }, + { + name: "leaves the run running and flags the Stop when the provider never confirms it", + unresponsive: true, + dispatched: ["thread.interrupt.unresponsive"], + }, +])("$name", ({ unresponsive, dispatched }) => Effect.gen(function* () { const now = yield* DateTime.now; const events = yield* Ref.make>([]); @@ -178,7 +191,8 @@ it.effect("settles a stopped run when its adapter has already lost the native tu threadId, operation: "interrupt", providerTurnId, - cause: "Provider turn is not active.", + ...(unresponsive ? { unresponsive } : {}), + cause: unresponsive ? "Timed out." : "Provider turn is not active.", }), threads: { dispatch: (command) => @@ -199,7 +213,7 @@ it.effect("settles a stopped run when its adapter has already lost the native tu }, }); }).pipe(Effect.provide(layer)); - assert.deepEqual(yield* Ref.get(events), ["thread.background-work.settle"]); + assert.deepEqual(yield* Ref.get(events), dispatched); }), ); diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.ts index d174db2fb3a29..534043aeb4eb8 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.ts @@ -177,6 +177,13 @@ export const layerExecutor: Layer.Layer< cause, }), ), + Effect.map((outcome) => ({ unresponsive: false, outcome }) as const), + // Settling here would end the run while the agent may still be running; the + // user decides with Force stop instead. + Effect.catchIf( + (cause) => request.subagent === undefined && cause.unresponsive === true, + () => Effect.succeed({ unresponsive: true, outcome: undefined } as const), + ), Effect.catchIf( (cause) => request.subagent === undefined && @@ -184,27 +191,35 @@ export const layerExecutor: Layer.Layer< request.type, Cause.pretty(Cause.fail(cause)), ), - () => Effect.void, + () => Effect.succeed({ unresponsive: false, outcome: undefined } as const), ), - Effect.andThen((outcome) => - request.subagent !== undefined && outcome === undefined - ? Effect.void - : threads.dispatch({ - type: "thread.background-work.settle", - commandId: CommandId.make(`${effect.id}:background-work-settled`), - ...(request.subagent === undefined || outcome === undefined - ? {} - : { - subagent: { - id: request.subagent.id, - stoppedAt: DateTime.makeUnsafe(effect.createdAt), - outcome, - }, - }), + Effect.andThen(({ unresponsive, outcome }) => + unresponsive + ? threads.dispatch({ + type: "thread.interrupt.unresponsive", + commandId: CommandId.make(`${effect.id}:unresponsive`), threadId: effect.threadId, providerThreadId: request.providerThreadId, providerTurnId: request.providerTurnId, - }), + }) + : request.subagent !== undefined && outcome === undefined + ? Effect.void + : threads.dispatch({ + type: "thread.background-work.settle", + commandId: CommandId.make(`${effect.id}:background-work-settled`), + ...(request.subagent === undefined || outcome === undefined + ? {} + : { + subagent: { + id: request.subagent.id, + stoppedAt: DateTime.makeUnsafe(effect.createdAt), + outcome, + }, + }), + threadId: effect.threadId, + providerThreadId: request.providerThreadId, + providerTurnId: request.providerTurnId, + }), ), Effect.mapError( (cause) => diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 16865229d94f2..50f9a2acc0f39 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -536,6 +536,7 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId { case "checkpoint.rollback": case "checkpoint.rollback.fail": case "thread.background-work.settle": + case "thread.interrupt.unresponsive": case "thread.stop": case "provider.switch": return command.threadId; @@ -10278,7 +10279,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio run, rootNode, providerThread, - reason: yield* runInterruptReason(input.command, input.events, run.id), + reason: + (input.command.type === "thread.background-work.settle" + ? input.command.reason + : undefined) ?? (yield* runInterruptReason(input.command, input.events, run.id)), completedAt: input.now, }), }); @@ -10525,6 +10529,55 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio yield* closePendingLinkRequests({ ...input, threadId: thread.id }); }); + const dispatchInterruptUnresponsive = Effect.fn("Orchestrator.dispatchInterruptUnresponsive")( + function* ( + command: Extract< + OrchestrationV2InternalCommand, + { readonly type: "thread.interrupt.unresponsive" } + >, + events: Ref.Ref>, + ) { + const { providerTurn } = yield* projectionStore + .getProviderControlContext(command.threadId, { + providerThreadId: command.providerThreadId, + providerTurnId: command.providerTurnId, + }) + .pipe(mapDispatchError(command)); + const { runs } = yield* projectionStore + .getThreadRecords(command.threadId, ["runs"]) + .pipe(mapDispatchError(command)); + const run = runs.find( + (candidate) => + providerTurn !== undefined && candidate.activeAttemptId === providerTurn.runAttemptId, + ); + // A settled run still counts: Stop may have targeted its background work. + if (run === undefined) return; + const { turnItems } = yield* projectionStore + .getThreadRecords(command.threadId, ["turnItems"], { + turnItemTypes: ["run_interrupt_request", "run_interrupt_result"], + turnItemRunIds: [run.id], + }) + .pipe(mapDispatchError(command)); + // A provider that stopped late already wrote the result; it needs no Force stop. + if (turnItems.some((item) => item.type === "run_interrupt_result")) return; + const request = turnItems.find((item) => item.type === "run_interrupt_request"); + if (request?.type !== "run_interrupt_request" || request.unresponsiveAt !== undefined) return; + const now = yield* DateTime.now; + yield* emit( + events, + command, + )({ + type: "turn-item.updated", + threadId: command.threadId, + runId: run.id, + ...(request.nodeId === null ? {} : { nodeId: request.nodeId }), + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { ...request, unresponsiveAt: now, updatedAt: now }, + }); + }, + ); + const dispatchBackgroundWorkSettle = Effect.fn("Orchestrator.dispatchBackgroundWorkSettle")( function* ( command: Extract< @@ -12902,6 +12955,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio case "thread.background-work.settle": yield* dispatchBackgroundWorkSettle(command, events, effects); break; + case "thread.interrupt.unresponsive": + yield* dispatchInterruptUnresponsive(command, events); + break; case "thread.fork": yield* dispatchThreadFork(command, events); break; @@ -13032,6 +13088,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio (planned) => planned.events.length > 0 || command.type === "thread.background-work.settle" || + command.type === "thread.interrupt.unresponsive" || command.type === "thread.stop" || command.type === "subagent.stop" || // Closing a share again, or after it ended, is not an error. diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 86b173f80dcba..5bbb3926e2b66 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -338,6 +338,7 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( readonly backgroundTasksEndWithProcess?: boolean; readonly hangSessionScopeClose?: boolean; readonly startTurn?: Effect.Effect; + readonly interruptTurn?: Effect.Effect; readonly beforeUnload?: Effect.Effect; readonly spawnBeforeOpen?: boolean; readonly scopeCloseReached?: Deferred.Deferred; @@ -437,7 +438,7 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( Ref.update(state, (current) => ({ ...current, interruptCount: current.interruptCount + 1, - })), + })).pipe(Effect.andThen(options.interruptTurn ?? Effect.void)), unloadThread: ({ providerThread }) => (options.beforeUnload ?? Effect.void).pipe( Effect.andThen( @@ -485,6 +486,7 @@ function layerTest(input: { readonly backgroundTasksEndWithProcess?: boolean; readonly hangSessionScopeClose?: boolean; readonly startTurn?: Effect.Effect; + readonly interruptTurn?: Effect.Effect; readonly beforeUnload?: Effect.Effect; readonly spawnBeforeOpen?: boolean; readonly scopeCloseReached?: Deferred.Deferred; @@ -520,6 +522,7 @@ function layerTest(input: { ? {} : { hangSessionScopeClose: input.hangSessionScopeClose }), ...(input.startTurn === undefined ? {} : { startTurn: input.startTurn }), + ...(input.interruptTurn === undefined ? {} : { interruptTurn: input.interruptTurn }), ...(input.beforeUnload === undefined ? {} : { beforeUnload: input.beforeUnload }), ...(input.spawnBeforeOpen === undefined ? {} : { spawnBeforeOpen: input.spawnBeforeOpen }), ...(input.scopeCloseReached === undefined @@ -1367,6 +1370,159 @@ it.effect( }), ); +it.effect("ProviderSessionManagerV2 gives up on a provider that never confirms a Stop", () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + yield* Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread-provider-session-manager-unresponsive-stop"); + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId, + }); + yield* eventSink.write({ + events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })], + }); + const runtime = yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + }); + const stopping = yield* runtime + .interruptTurn({ + providerThread: makeProviderThread({ idAllocator, threadId, providerSessionId, now }), + providerTurnId: idAllocator.derive.providerTurn({ + driver: CODEX_DRIVER, + nativeTurnId: "native-turn-unresponsive", + }), + }) + .pipe(Effect.flip, Effect.forkChild); + yield* TestClock.adjust(ProviderSessionManager.PROVIDER_INTERRUPT_TIMEOUT_MS); + assert.equal((yield* Fiber.join(stopping))._tag, "ProviderAdapterInterruptTimeoutError"); + }).pipe( + Effect.provide(layerTest({ state, idleTimeoutMs: 60_000, interruptTurn: Effect.never })), + ); + }), +); + +it.effect( + "ProviderSessionManagerV2 keeps a shared session a sibling is busy on when releasing", + () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + yield* Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const now = yield* DateTime.now; + const stopping = ThreadId.make("thread-provider-session-manager-release-stopping"); + const sibling = ThreadId.make("thread-provider-session-manager-release-sibling"); + const providerSessionId = idAllocator.derive.providerSession({ + providerInstanceId: modelSelection.instanceId, + }); + yield* eventSink.write({ + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId: stopping, now }), + yield* makeThreadCreatedEvent({ idAllocator, threadId: sibling, now }), + ], + }); + const runtime = yield* manager.open({ + threadId: stopping, + providerSessionId, + modelSelection, + runtimePolicy, + }); + yield* manager.open({ + threadId: sibling, + providerSessionId, + modelSelection, + runtimePolicy, + }); + const providerThreadOf = (threadId: ThreadId) => + makeProviderThread({ + idAllocator, + threadId, + providerSessionId, + now, + nativeThreadId: `native-${threadId}`, + }); + const runId = idAllocator.derive.run({ threadId: sibling, ordinal: 1 }); + yield* runtime.startTurn({ + appThread: (yield* projectionStore.getThreadProjection(sibling)).thread, + threadId: sibling, + runId, + runOrdinal: 1, + providerTurnOrdinal: 1, + attemptId: idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 }), + rootNodeId: idAllocator.derive.rootNode({ runId }), + providerThread: providerThreadOf(sibling), + message: { + createdBy: "user", + creationSource: "web", + messageId: yield* idAllocator.allocate.message({ threadId: sibling, ordinal: 1 }), + text: "turn", + attachments: [], + }, + modelSelection, + runtimePolicy, + }); + const release = (own: ThreadId) => + manager.releaseUnlessBusy({ + providerSessionId, + ownProviderThreadIds: [providerThreadOf(own).id], + reason: "manual_shutdown", + }); + + assert.isFalse(yield* release(stopping)); + assert.isTrue(yield* manager.isLive(providerSessionId)); + assert.isTrue(yield* release(sibling)); + assert.isFalse(yield* manager.isLive(providerSessionId)); + + // A turn that starts on a runtime released meanwhile fails instead of running on it. + const startOnReleasedRuntime = Effect.gen(function* () { + const lateRunId = idAllocator.derive.run({ threadId: stopping, ordinal: 1 }); + return yield* Effect.flip( + runtime.startTurn({ + appThread: (yield* projectionStore.getThreadProjection(stopping)).thread, + threadId: stopping, + runId: lateRunId, + runOrdinal: 1, + providerTurnOrdinal: 1, + attemptId: idAllocator.derive.runAttempt({ runId: lateRunId, attemptOrdinal: 1 }), + rootNodeId: idAllocator.derive.rootNode({ runId: lateRunId }), + providerThread: providerThreadOf(stopping), + message: { + createdBy: "user", + creationSource: "web", + messageId: yield* idAllocator.allocate.message({ threadId: stopping, ordinal: 1 }), + text: "turn", + attachments: [], + }, + modelSelection, + runtimePolicy, + }), + ); + }); + assert.equal((yield* startOnReleasedRuntime)._tag, "ProviderAdapterTurnStartError"); + + // Nor may it leave its turn busy on a replacement opened under the same id. + yield* manager.open({ + threadId: sibling, + providerSessionId, + modelSelection, + runtimePolicy, + }); + assert.equal((yield* startOnReleasedRuntime)._tag, "ProviderAdapterTurnStartError"); + assert.isTrue(yield* release(sibling)); + }).pipe(Effect.provide(layerTest({ state, idleTimeoutMs: 60 * 60_000 }))); + }), +); + it.effect("ProviderSessionManagerV2 stops a session still opening when its layer shuts down", () => Effect.gen(function* () { const state = yield* Ref.make(emptyState); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index b9887a4844600..03a7278774a64 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -57,11 +57,19 @@ import * as ProjectionStore from "./ProjectionStore.ts"; const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000; const DEFAULT_MAX_IDLE_PIN_MS = 4 * 60 * 60 * 1000; const RELEASE_SCOPE_CLOSE_TIMEOUT_MS = 30 * 1000; +/** Past adapters' own 10 s stop fallbacks, so they settle first when the provider answers at all. */ +export const PROVIDER_INTERRUPT_TIMEOUT_MS = 15 * 1000; const busyTurnPrefix = (providerThreadId: ProviderThreadId) => `${providerThreadId}#`; const busyTurnKey = (providerThreadId: ProviderThreadId, runOrdinal: number) => `${busyTurnPrefix(providerThreadId)}${runOrdinal}`; const UNLOAD_THREAD_TIMEOUT_MS = 10 * 1000; +const WORKING_RUN_STATUSES: ReadonlySet = new Set([ + "preparing", + "starting", + "running", + "waiting", +]); export const ProviderSessionReleaseReason = Schema.Literals([ "idle_timeout", @@ -181,6 +189,25 @@ export interface ProviderSessionManagerV2Shape { readonly detail?: string; readonly revokeMcpCredential?: boolean; }) => Effect.Effect; + /** + * Releases the session unless, at the moment of removal, a turn of a provider thread outside + * `ownProviderThreadIds` is busy on it. Checked atomically with turn starts. Succeeds with + * whether it was released. + */ + readonly releaseUnlessBusy: (input: { + readonly providerSessionId: ProviderSessionId; + readonly ownProviderThreadIds: ReadonlyArray; + readonly reason: ProviderSessionReleaseReason; + readonly detail?: string; + }) => Effect.Effect; + /** + * Other threads with a run or background work on this session's shared process; empty when + * it serves one thread. + */ + readonly otherWorkingThreads: (input: { + readonly providerSessionId: ProviderSessionId; + readonly threadId: ThreadId; + }) => Effect.Effect>; } export class ProviderSessionManagerV2 extends Context.Service< @@ -895,6 +922,7 @@ export const layerWithOptions = ( function* (input: { readonly providerSessionId: ProviderSessionId; readonly onlyIfIdleGeneration?: number; + readonly keepIfBusyOtherThan?: ReadonlyArray; }): Effect.fn.Return, DateTime.Utc]> { const key = sessionKey(input.providerSessionId); const candidate = (yield* Ref.get(sessions)).get(key); @@ -914,6 +942,15 @@ export const layerWithOptions = ( ) { return ["kept", current] as const; } + const own = input.keepIfBusyOtherThan; + if ( + own !== undefined && + [...existing.busyTurns].some( + (turnKey) => !own.some((id) => turnKey.startsWith(busyTurnPrefix(id))), + ) + ) { + return ["kept", current] as const; + } const updated = new Map(current); updated.delete(key); return ["removed", updated] as const; @@ -972,6 +1009,7 @@ export const layerWithOptions = ( readonly detachedThreadId?: ThreadId; readonly cancelIdleFiber?: boolean; readonly onlyIfIdleGeneration?: number; + readonly keepIfBusyOtherThan?: ReadonlyArray; readonly gracefulSubscribers?: boolean; }) => Effect.acquireUseRelease( @@ -1380,15 +1418,21 @@ export const layerWithOptions = ( .pipe(Effect.ensuring(Effect.sync(dropReservation))); }); - const markBusy = (providerSessionId: ProviderSessionId, turnKey: string) => + // Marks only the entry this runtime belongs to: a released or replaced session must not + // gain a busy turn that never ends. Succeeds with whether the turn was marked. + const markBusy = ( + providerSessionId: ProviderSessionId, + turnKey: string, + runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime, + ) => withActivityError( providerSessionId, Effect.gen(function* () { const key = sessionKey(providerSessionId); - const idleFiber = yield* Ref.modify(sessions, (current) => { + const marked = yield* Ref.modify(sessions, (current) => { const entry = current.get(key); - if (entry === undefined) { - return [null, current] as const; + if (entry === undefined || entry.runtime !== runtime) { + return [undefined, current] as const; } const updated = new Map(current); updated.set(key, { @@ -1397,9 +1441,11 @@ export const layerWithOptions = ( idleFiber: null, pinnedSinceMs: null, }); - return [entry.idleFiber, updated] as const; + return [{ idleFiber: entry.idleFiber }, updated] as const; }); - yield* cancelIdleFiber(idleFiber); + if (marked === undefined) return false; + yield* cancelIdleFiber(marked.idleFiber); + return true; }), ); @@ -1785,11 +1831,31 @@ export const layerWithOptions = ( ), Effect.andThen( Effect.acquireUseRelease( - observeActivity( + markBusy( providerSessionId, - markBusy( - providerSessionId, - busyTurnKey(input.providerThread.id, input.runOrdinal), + busyTurnKey(input.providerThread.id, input.runOrdinal), + runtime, + ).pipe( + Effect.catchCause((cause) => + Effect.logWarning("orchestration-v2.driver-session.activity-failed", { + providerSessionId, + cause, + }).pipe(Effect.as(true)), + ), + // A release between attach and markBusy leaves nothing to mark: fail the + // start instead of running it on a runtime being torn down. + Effect.flatMap((marked) => + marked + ? Effect.void + : Effect.fail( + new ProviderAdapter.ProviderAdapterTurnStartError({ + driver: runtime.driver, + threadId: input.threadId, + providerThreadId: input.providerThread.id, + runId: input.runId, + cause: "The provider session was released while the turn started.", + }), + ), ), ), () => @@ -1808,9 +1874,26 @@ export const layerWithOptions = ( observeActivity(providerSessionId, touchActivity(providerSessionId)).pipe( Effect.andThen(runtime.steerTurn(input).pipe(turnMetrics("steer"))), ), + // A provider starved of memory can stop answering, so no caller may wait on it unbounded. interruptTurn: (input) => observeActivity(providerSessionId, touchActivity(providerSessionId)).pipe( - Effect.andThen(runtime.interruptTurn(input).pipe(turnMetrics("interrupt"))), + Effect.andThen( + runtime.interruptTurn(input).pipe( + Effect.timeoutOrElse({ + duration: PROVIDER_INTERRUPT_TIMEOUT_MS, + orElse: () => + Effect.fail( + new ProviderAdapter.ProviderAdapterInterruptTimeoutError({ + driver: runtime.driver, + providerThreadId: input.providerThread.id, + providerTurnId: input.providerTurnId, + timeoutMs: PROVIDER_INTERRUPT_TIMEOUT_MS, + }), + ), + }), + turnMetrics("interrupt"), + ), + ), ), respondToRuntimeRequest: (input) => observeActivity(providerSessionId, touchActivity(providerSessionId)).pipe( @@ -2276,6 +2359,40 @@ export const layerWithOptions = ( ), ), release: releaseEntry, + releaseUnlessBusy: Effect.fn("ProviderSessionManager.releaseUnlessBusy")(function* (input) { + const key = sessionKey(input.providerSessionId); + const before = (yield* Ref.get(sessions)).get(key); + yield* releaseEntry({ + providerSessionId: input.providerSessionId, + reason: input.reason, + ...(input.detail === undefined ? {} : { detail: input.detail }), + keepIfBusyOtherThan: input.ownProviderThreadIds, + }); + // Identity, not presence: open can install a replacement under the same id meanwhile. + return before !== undefined && (yield* Ref.get(sessions)).get(key) !== before; + }), + otherWorkingThreads: Effect.fn("ProviderSessionManager.otherWorkingThreads")( + function* (input) { + const entry = (yield* Ref.get(sessions)).get(sessionKey(input.providerSessionId)); + if (entry === undefined || !entry.supportsMultipleProviderThreads) return []; + return yield* Effect.filter( + [...entry.attachedThreadIds].filter((threadId) => threadId !== input.threadId), + (threadId) => + // Runs, not the shell's activeRunId: the shell omits silent runs such as idle + // compaction. Background work outlives its run and still needs the process. + Effect.zipWith( + projectionStore.getThreadRecords(threadId, ["runs"]), + projectionStore.getThreadShell(threadId), + ({ runs }, shell) => + runs.some((run) => WORKING_RUN_STATUSES.has(run.status)) || + (shell?.pendingBackgroundTasks?.length ?? 0) > 0, + ).pipe( + // An unreadable thread may still be working; never kill it unseen. + Effect.orElseSucceed(() => true), + ), + ); + }, + ), detach: Effect.fn("ProviderSessionManager.detach")( function* (input) { const key = sessionKey(input.providerSessionId); diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts index bab115f6e24cb..65da8b23676b0 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts @@ -284,6 +284,8 @@ it.effect( closeInstance: () => Effect.void, release: () => Effect.void, detach: () => Effect.void, + otherWorkingThreads: () => Effect.succeed([]), + releaseUnlessBusy: () => Effect.succeed(true), }), ); const layerControl = ProviderTurnControlService.layer.pipe( diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts index e1dbac21bc52e..bd225bb41773b 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts @@ -38,6 +38,8 @@ export class ProviderTurnControlError extends Schema.TaggedError + Effect.fail( + new ProviderTurnControlError({ + threadId: input.threadId, + operation: "interrupt", + providerTurnId: input.providerTurnId, + unresponsive: true, + cause, + }), + ), + }), + ); // Use real time; ingestion fibers do not advance TestClock and would leave Stop blocked. yield* Effect.gen(function* () { const deadline = (yield* Clock.currentTimeMillis) + 2_000; diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts index b2daad62681e9..9285f72d46f56 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts @@ -27,6 +27,8 @@ import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; +import { AgentScope } from "@t3tools/shared/AgentScope"; + import * as ServerSettings from "../serverSettings.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as CommandReceiptStore from "./CommandReceiptStore.ts"; @@ -596,3 +598,174 @@ it.effect.each([ expect(dispatched).toEqual(settles ? ["thread.settle"] : []); }), ); + +it.effect.each([ + { + name: "kills the thread's own agent and ends its turn", + others: [] as ReadonlyArray, + killed: true, + expected: { outcome: "killed", sharedWithThreadIds: [] }, + teardown: ["release"], + }, + { + name: "keeps a process another working thread shares and only ends this turn", + others: ["thread:thread-management:force-stop:other"], + killed: false, + expected: { + outcome: "shared", + sharedWithThreadIds: ["thread:thread-management:force-stop:other"], + }, + teardown: ["detach"], + }, + { + name: "still settles a finished run's background work in a shared process", + others: ["thread:thread-management:force-stop:other"], + killed: false, + settledRun: true, + expected: { + outcome: "shared", + sharedWithThreadIds: ["thread:thread-management:force-stop:other"], + }, + teardown: ["detach"], + }, + { + name: "detaches when a sibling starts a turn just before the session is released", + others: [] as ReadonlyArray, + killed: false, + siblingBusy: true, + expected: { outcome: "shared", sharedWithThreadIds: [] }, + teardown: ["release", "detach"], + }, + { + name: "reports a teardown that has not finished in time as still releasing", + others: [] as ReadonlyArray, + killed: false, + releaseHangs: true, + expected: { outcome: "releasing", sharedWithThreadIds: [] }, + teardown: ["release"], + }, +])("Force stop $name", ({ others, killed, expected, teardown, ...row }) => + Effect.gen(function* () { + const threadId = ThreadId.make("thread:thread-management:force-stop"); + const providerSessionId = ProviderSessionId.make("provider-session:force-stop"); + const providerThreadId = ProviderThreadId.make("provider-thread:force-stop"); + const runId = RunId.make("run:thread-management:force-stop"); + const dispatched: Array = []; + const teardowns: Array = []; + const tornDown = yield* Deferred.make(); + const layerTest = ThreadManagementService.layer.pipe( + Layer.provide( + Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ + isLive: () => Effect.succeed(true), + otherWorkingThreads: () => Effect.succeed(others.map((id) => ThreadId.make(id))), + releaseUnlessBusy: () => + Effect.sync(() => teardowns.push("release")).pipe( + Effect.andThen( + "releaseHangs" in row ? Effect.never : Effect.succeed(!("siblingBusy" in row)), + ), + ), + detach: () => + Effect.sync(() => teardowns.push("detach")).pipe( + Effect.andThen(Deferred.succeed(tornDown, undefined)), + Effect.asVoid, + ), + }), + ), + Layer.provide( + Layer.mock(Orchestrator.OrchestratorV2)({ + getThreadRecords: () => + Effect.succeed({ + thread: { id: threadId, deletedAt: null }, + runs: [ + { + id: runId, + ordinal: 1, + status: "settledRun" in row ? "completed" : "running", + activeAttemptId: "attempt", + }, + // A queued follow-up neither supersedes the request nor becomes the target. + { id: RunId.make("run:queued-follow-up"), ordinal: 2, status: "queued" }, + ], + providerThreads: [{ id: providerThreadId, appThreadId: threadId, providerSessionId }], + providerTurns: [ + { + id: "provider-turn:force-stop", + providerThreadId, + runAttemptId: "attempt", + status: "settledRun" in row ? "completed" : "running", + }, + ], + } as unknown as OrchestrationV2ThreadProjection), + dispatch: (command) => + Effect.sync(() => { + dispatched.push(command); + return { sequence: 1, storedEvents: [] } as never; + }), + }), + ), + Layer.provide( + Layer.succeed(AgentScope, { + ...AgentScope.defaultValue(), + kill: () => Effect.succeed(killed), + }), + ), + Layer.provide(ServerSettings.layerTest()), + Layer.provide(layerReceiptsTest), + ); + yield* Effect.gen(function* () { + const service = yield* ThreadManagementService.ThreadManagementService; + const stopping = yield* service.forceStopThread({ threadId, runId }).pipe(Effect.forkChild); + yield* TestClock.adjust("10 seconds"); + expect(yield* Fiber.join(stopping)).toEqual(expected); + expect(dispatched).toMatchObject([ + { + type: "thread.background-work.settle", + providerThreadId, + reason: "Force stopped by user", + }, + ]); + if (teardown.at(-1) === "detach") yield* Deferred.await(tornDown); + expect(teardowns).toEqual(teardown); + }).pipe(Effect.provide(layerTest)); + }), +); + +it.effect("Force stop refuses once a newer run has started, before killing anything", () => + Effect.gen(function* () { + const threadId = ThreadId.make("thread:thread-management:force-stop-superseded"); + let killed = false; + const layerTest = ThreadManagementService.layer.pipe( + Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})), + Layer.provide( + Layer.mock(Orchestrator.OrchestratorV2)({ + getThreadRecords: () => + Effect.succeed({ + thread: { id: threadId, deletedAt: null }, + runs: [ + { id: RunId.make("run:stopped"), ordinal: 1, status: "running" }, + { id: RunId.make("run:newer"), ordinal: 2, status: "running" }, + ], + providerThreads: [], + providerTurns: [], + } as unknown as OrchestrationV2ThreadProjection), + }), + ), + Layer.provide( + Layer.succeed(AgentScope, { + ...AgentScope.defaultValue(), + kill: () => Effect.sync(() => (killed = true)), + }), + ), + Layer.provide(ServerSettings.layerTest()), + Layer.provide(layerReceiptsTest), + ); + const error = yield* Effect.gen(function* () { + const service = yield* ThreadManagementService.ThreadManagementService; + return yield* Effect.flip( + service.forceStopThread({ threadId, runId: RunId.make("run:stopped") }), + ); + }).pipe(Effect.provide(layerTest)); + expect(error.reason).toBe("superseded"); + expect(killed).toBe(false); + }), +); diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 7b79b21e88153..192ed4007fc17 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -14,6 +14,9 @@ import { MessageId, OrchestrationV2StopWorkflowError, type OrchestrationV2StopWorkflowInput, + OrchestrationV2ForceStopThreadError, + type OrchestrationV2ForceStopThreadInput, + type OrchestrationV2ForceStopThreadResult, type ModelSelection, type OrchestrationV2Actor, type OrchestrationV2Command, @@ -30,6 +33,7 @@ import { ProjectId, PROVIDER_SEND_TURN_MAX_FILE_BYTES, ProviderInstanceId, + type ProviderSessionId, resolveProjectProviderInstanceEnabled, RunId, type ScheduledTaskId, @@ -38,10 +42,13 @@ import { } from "@t3tools/contracts"; import { delegatedTaskProgress } from "@t3tools/provider-core/server/subagentProjection"; import { threadTranscriptHeader } from "@t3tools/shared/threadTranscript"; +import { AgentScope } from "@t3tools/shared/AgentScope"; +import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; @@ -454,6 +461,13 @@ export interface ThreadManagementServiceShape { readonly stopWorkflow: ( input: OrchestrationV2StopWorkflowInput, ) => Effect.Effect; + /** + * Kills the thread's agent for a provider that no longer responds, then ends + * its turn as interrupted. Never kills a process other working threads share. + */ + readonly forceStopThread: ( + input: OrchestrationV2ForceStopThreadInput, + ) => Effect.Effect; readonly awaitBackgroundTasks: (input: { readonly threadId: ThreadId; readonly taskIds: ReadonlyArray; @@ -547,12 +561,16 @@ function latestSteerableRun( } const SETTLE_AFTER_RUN_WAIT_MS = 24 * 60 * 60 * 1_000; +const FORCE_STOP_REASON = "Force stopped by user"; +const FORCE_STOP_RELEASE_WAIT = "10 seconds"; +const isForceStopThreadError = Schema.is(OrchestrationV2ForceStopThreadError); const make = Effect.gen(function* () { const threadDispatch = yield* ThreadCommandExecutor.ThreadCommandExecutor; const orchestrator = yield* Orchestrator.OrchestratorV2; const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2; const layerScope = yield* Effect.scope; + const agentScope = yield* AgentScope; const legacyImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter; const serverSettings = yield* ServerSettings.ServerSettingsService; const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2; @@ -1072,6 +1090,153 @@ const make = Effect.gen(function* () { return { type: "interrupt_requested", run: interruptibleRun, dispatch } as const; }); + const forceStopThread: ThreadManagementServiceShape["forceStopThread"] = Effect.fn( + "ThreadManagementService.forceStopThread", + )( + function* (input) { + // Under the thread lock no new run can be created between the check and the kill. The + // settlement below dispatches, which takes that lock itself, so it runs after release. + const { records, target, killed } = yield* threadDispatch.withLock( + input.threadId, + Effect.gen(function* () { + const records = yield* orchestrator.getThreadRecords(input.threadId, [ + "runs", + "providerThreads", + "providerTurns", + ]); + // The run Force stop acts on: the active one, else the latest that started. Queued + // follow-ups never ran, so they neither count as targets nor supersede the request. + const target = + latestActiveRun(records) ?? + records.runs + .filter((run) => run.status !== "queued") + .reduce( + (current, run) => + current === undefined || run.ordinal > current.ordinal ? run : current, + undefined, + ); + if (input.runId !== undefined && input.runId !== target?.id) { + return yield* new OrchestrationV2ForceStopThreadError({ + threadId: input.threadId, + reason: "superseded", + }); + } + // Shared scopes are never tracked per thread, so this only kills the thread's own agent. + const killed = yield* agentScope.kill(input.threadId); + return { records, target, killed }; + }), + ); + const sessionIds = new Set( + records.providerThreads.flatMap((providerThread) => + providerThread.appThreadId === input.threadId && providerThread.providerSessionId !== null + ? [providerThread.providerSessionId] + : [], + ), + ); + // A run that already ended may still hold background work; settling it is a no-op otherwise. + const run = target; + if (run !== undefined) { + const active = isActiveRun(run); + const providerTurn = records.providerTurns.findLast( + (turn) => + turn.runAttemptId === run.activeAttemptId && (!active || turn.status === "running"), + ); + const commandId = CommandId.make( + `server:force-stop:${run.id}:${yield* Clock.currentTimeMillis}`, + ); + yield* providerTurn === undefined && !active + ? Effect.void + : providerTurn === undefined + ? orchestrator.dispatch({ + type: "run.interrupt", + commandId, + threadId: input.threadId, + runId: run.id, + reason: FORCE_STOP_REASON, + }) + : orchestrator.dispatch({ + type: "thread.background-work.settle", + commandId, + threadId: input.threadId, + providerThreadId: providerTurn.providerThreadId, + providerTurnId: providerTurn.id, + reason: FORCE_STOP_REASON, + }); + } + const ownProviderThreadIds = records.providerThreads.flatMap((providerThread) => + providerThread.appThreadId === input.threadId ? [providerThread.id] : [], + ); + const detach = (providerSessionId: ProviderSessionId) => + sessions + .detach({ providerSessionId, threadId: input.threadId, detail: FORCE_STOP_REASON }) + .pipe( + Effect.catchCause((cause) => + Effect.logWarning("orchestration-v2.force-stop-detach-failed", { + threadId: input.threadId, + cause, + }), + ), + Effect.forkIn(layerScope), + ); + let shared = false; + const sharedWith = new Set(); + const releases: Array<{ + readonly providerSessionId: ProviderSessionId; + readonly fiber: Fiber.Fiber; + }> = []; + for (const providerSessionId of sessionIds) { + if (!(yield* sessions.isLive(providerSessionId))) continue; + // Decided just before teardown, so the reply matches what happens to the process. + const others = yield* sessions.otherWorkingThreads({ + providerSessionId, + threadId: input.threadId, + }); + for (const threadId of others) sharedWith.add(threadId); + if (others.length > 0) { + shared = true; + yield* detach(providerSessionId); + continue; + } + // The session manager re-checks atomically with turn starts and keeps a session a + // sibling began using in the meantime. + const fiber = yield* sessions + .releaseUnlessBusy({ + providerSessionId, + ownProviderThreadIds, + reason: "manual_shutdown", + detail: FORCE_STOP_REASON, + }) + .pipe(Effect.forkIn(layerScope)); + releases.push({ providerSessionId, fiber }); + } + // Teardown waits on the provider's own exit paths; past this bound it keeps going on its own. + let releasing = false; + for (const release of releases) { + const released = yield* Fiber.join(release.fiber).pipe( + Effect.timeoutOption(FORCE_STOP_RELEASE_WAIT), + ); + if (Option.isNone(released)) { + releasing = true; + } else if (!released.value) { + shared = true; + yield* detach(release.providerSessionId); + } + } + return { + outcome: killed ? "killed" : shared ? "shared" : releasing ? "releasing" : "released", + sharedWithThreadIds: [...sharedWith], + } as const; + }, + (effect, input) => + effect.pipe( + Effect.mapError((cause) => + isForceStopThreadError(cause) + ? cause + : new OrchestrationV2ForceStopThreadError({ threadId: input.threadId, cause }), + ), + ), + ); + const stopWorkflow: ThreadManagementServiceShape["stopWorkflow"] = Effect.fn( "ThreadManagementService.stopWorkflow", )( @@ -1354,6 +1519,7 @@ const make = Effect.gen(function* () { interruptThread, stopDelegatedTasks, stopWorkflow, + forceStopThread, awaitBackgroundTasks, getThreadEventSequence: orchestrator.getThreadEventSequence, recoverDelegatedTask: orchestrator.recoverDelegatedTask, diff --git a/apps/server/src/orchestration-v2/ThreadStop.test.ts b/apps/server/src/orchestration-v2/ThreadStop.test.ts index 23a52f39d33d3..16dcedaf8ac9c 100644 --- a/apps/server/src/orchestration-v2/ThreadStop.test.ts +++ b/apps/server/src/orchestration-v2/ThreadStop.test.ts @@ -1552,3 +1552,115 @@ it.effect.each(["missing session", "completed", "failed", "cancelled"] as const) ); }).pipe(Effect.provide(layerTest)), ); + +it.effect("an unanswered Stop is flagged until Force stop ends the run with its own reason", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const threadId = ThreadId.make("thread:force-stop"); + yield* createWatchingThread(threadId, 6); + yield* send(threadId, "work", "start_immediately"); + const now = yield* DateTime.now; + const started = yield* orchestrator.getThreadProjection(threadId); + const run = started.runs[0]!; + const providerThreadId = run.providerThreadId!; + const providerTurnId = ProviderTurnId.make("provider-turn:force-stop"); + const apply = (event: Omit) => + projections.apply({ + ...event, + id: EventId.make(`event:force-stop:${event.type}`), + threadId, + } as OrchestrationV2DomainEvent); + const attempt = started.attempts[0]!; + const attemptId = attempt.id; + yield* apply({ + type: "run.updated", + runId: run.id, + occurredAt: now, + payload: { ...run, status: "running", startedAt: now, activeAttemptId: attemptId }, + }); + yield* apply({ + type: "run-attempt.updated", + occurredAt: now, + payload: { ...attempt, status: "running", startedAt: now }, + }); + yield* apply({ + type: "provider-turn.updated", + occurredAt: now, + payload: { + id: providerTurnId, + providerThreadId, + nodeId: run.rootNodeId!, + runAttemptId: attemptId, + nativeTurnRef: null, + ordinal: 1, + status: "running", + startedAt: now, + completedAt: null, + }, + }); + yield* apply({ + type: "turn-item.updated", + runId: run.id, + occurredAt: now, + payload: { + id: TurnItemId.make("turn-item:force-stop:interrupt-request"), + threadId, + runId: run.id, + nodeId: run.rootNodeId!, + providerThreadId, + providerTurnId, + nativeItemRef: null, + parentItemId: null, + ordinal: 1_000, + status: "completed", + title: "Interrupt requested", + startedAt: now, + completedAt: now, + updatedAt: now, + type: "run_interrupt_request", + message: "Stopped by user", + }, + }); + const target = { threadId, providerThreadId, providerTurnId }; + const request = Effect.map(orchestrator.getThreadProjection(threadId), (projection) => + projection.turnItems.find((item) => item.type === "run_interrupt_request"), + ); + + yield* orchestrator.dispatch({ + ...target, + type: "thread.interrupt.unresponsive", + commandId: CommandId.make("force-stop:unresponsive"), + }); + const flagged = yield* request; + assert.isTrue( + flagged?.type === "run_interrupt_request" && flagged.unresponsiveAt !== undefined, + ); + assert.deepEqual((yield* threadState(threadId)).runs, ["running"]); + + yield* orchestrator.dispatch({ + ...target, + type: "thread.background-work.settle", + commandId: CommandId.make("force-stop:settle"), + reason: "Force stopped by user", + }); + const settled = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual( + settled.runs.map((candidate) => candidate.status), + ["interrupted"], + ); + const result = settled.turnItems.find((item) => item.type === "run_interrupt_result"); + assert.equal( + result?.type === "run_interrupt_result" ? result.message : undefined, + "Force stopped by user", + ); + + // A provider confirming late changes nothing once the run has ended. + const late = yield* orchestrator.dispatch({ + ...target, + type: "thread.interrupt.unresponsive", + commandId: CommandId.make("force-stop:late-unresponsive"), + }); + assert.lengthOf(late.storedEvents, 0); + }).pipe(Effect.provide(layerTest)), +); diff --git a/apps/server/src/process/agentScope.test.ts b/apps/server/src/process/agentScope.test.ts index 286452a5c5781..2a9998f4cfbf6 100644 --- a/apps/server/src/process/agentScope.test.ts +++ b/apps/server/src/process/agentScope.test.ts @@ -110,6 +110,8 @@ const withFakeSystemd = ( ...fileSystem, readFileString: (path, encoding) => fileSystem.readFileString(path.replace("/sys/fs/cgroup", cgroupRoot), encoding), + writeFileString: (path, data, options) => + fileSystem.writeFileString(path.replace("/sys/fs/cgroup", cgroupRoot), data, options), }), ); const { stateDir } = yield* ServerConfig.ServerConfig; @@ -213,6 +215,36 @@ describe("AgentScope service", () => { ), ); + it.effect.each([{ oomPolicy: true }, { oomPolicy: false }])( + "Force stop kills a thread's own scope but never a shared Codex scope (OOM policy $oomPolicy)", + ({ oomPolicy }) => + withFakeSystemd( + ({ scope, units, calls, cgroupRoot }) => + Effect.gen(function* () { + const agent = yield* scope.wrap({ + command: "agent", + args: [], + name: "t", + threadId: "a", + }); + exitedAgent(units, cgroupRoot, unitOf(agent), { populated: true, oomKills: 0 }); + const codex = yield* launchCodex(scope, "b"); + exitedAgent(units, cgroupRoot, unitOf(codex), { populated: true, oomKills: 0 }); + + expect(yield* scope.kill("a")).toBe(true); + expect( + NodeFS.readFileSync(NodePath.join(cgroupRoot, unitOf(agent), "cgroup.kill"), "utf8"), + ).toBe("1"); + expect(yield* scope.kill("b")).toBe(false); + expect(NodeFS.existsSync(NodePath.join(cgroupRoot, unitOf(codex), "cgroup.kill"))).toBe( + false, + ); + expect(calls.filter(([, verb]) => verb === "kill")).toEqual([]); + }), + { oomPolicy }, + ), + ); + it.effect("keeps a running scope while hundreds of other threads launch", () => withFakeSystemd(({ scope, units }) => Effect.gen(function* () { diff --git a/apps/server/src/process/agentScope.ts b/apps/server/src/process/agentScope.ts index c72e4eed88a9c..b9b6b56acb140 100644 --- a/apps/server/src/process/agentScope.ts +++ b/apps/server/src/process/agentScope.ts @@ -215,7 +215,8 @@ export const make = Effect.gen(function* () { }), ); - const scopeByThread = new Map(); + // `shared` scopes serve other threads too: tracked only for OOM diagnosis on old systemd. + const scopeByThread = new Map(); const readScope = Effect.fn("agentScope.readScope")(function* (systemctl: string, unit: string) { const shown = yield* run(systemctl, [ @@ -277,10 +278,11 @@ export const make = Effect.gen(function* () { systemctl: string, threadId: string, unit: string | undefined, + shared = false, ) { const previous = scopeByThread.get(threadId); scopeByThread.delete(threadId); - if (unit !== undefined) scopeByThread.set(threadId, { unit, oomKilled: false }); + if (unit !== undefined) scopeByThread.set(threadId, { unit, oomKilled: false, shared }); if (previous !== undefined) yield* forget(systemctl, previous.unit); if (scopeByThread.size > MAX_TRACKED_THREADS) yield* evictOldest(systemctl); }); @@ -340,6 +342,40 @@ export const make = Effect.gen(function* () { } }); + const kill: AgentScopeShape["kill"] = Effect.fn("AgentScope.kill")(function* (threadId) { + const tracked = scopeByThread.get(threadId); + if (tracked === undefined || tracked.shared) return false; + const scope = yield* systemd; + if (scope === undefined) return false; + const shown = yield* run(scope.systemctl, [ + "--user", + "show", + tracked.unit, + "--property=ActiveState,ControlGroup", + ]); + if (shown._tag === "None" || shown.value.code !== 0) return false; + const values = parseKeyValues(shown.value.stdout); + if (values.get("ActiveState") !== "active") return false; + const controlGroup = values.get("ControlGroup") ?? ""; + // cgroup.kill (Linux 5.14+) kills the whole tree at once; systemd's kill is the fallback. + const killedByCgroup = + controlGroup.length > 0 && + (yield* fileSystem + .writeFileString(path.join("/sys/fs/cgroup", controlGroup, "cgroup.kill"), "1") + .pipe( + Effect.as(true), + Effect.orElseSucceed(() => false), + )); + if (killedByCgroup) return true; + const killed = yield* run(scope.systemctl, [ + "--user", + "kill", + "--signal=SIGKILL", + tracked.unit, + ]); + return killed._tag === "Some" && killed.value.code === 0; + }); + const clear: AgentScopeShape["clear"] = Effect.fn("agentScope.clear")(function* (threadId) { if (!scopeByThread.has(threadId)) return; const scope = yield* systemd; @@ -365,7 +401,8 @@ export const make = Effect.gen(function* () { // Clear the launch thread's previous scope instead. const continuing = shared === true && scope.supportsOomPolicy; const owned = threadId !== undefined && !continuing; - if (threadId !== undefined) yield* track(scope.systemctl, threadId, owned ? unit : undefined); + if (threadId !== undefined) + yield* track(scope.systemctl, threadId, owned ? unit : undefined, shared === true); const systemdScope: AgentSystemdScope = { systemdRun: scope.systemdRun, runtimeDir: scope.runtimeDir, @@ -385,6 +422,7 @@ export const make = Effect.gen(function* () { }), oomKilled, stop, + kill, clear, } satisfies AgentScopeShape; }); diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.ts index 48c4a5c240ea9..40c741fdd68ac 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.test.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts @@ -219,6 +219,7 @@ const makeTestRelay = Effect.fnUntraced(function* ( settleThread: unused, interruptThread: unused, stopWorkflow: () => Effect.die("unused stopWorkflow"), + forceStopThread: () => Effect.die("unused forceStopThread"), awaitBackgroundTasks: unused, stopDelegatedTasks: unused, getThreadEventSequence: unused, diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index a7ef5dedf24fb..622279d16a409 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -1914,6 +1914,8 @@ export const layerWsRpc = ( ), ), [ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: (input) => threadManagement.stopWorkflow(input), + [ORCHESTRATION_V2_WS_METHODS.forceStopThread]: (input) => + threadManagement.forceStopThread(input), [ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: (input) => readWorkflowScript({ scriptPath: input.scriptPath }), [ORCHESTRATION_V2_WS_METHODS.getTurnItem]: (input) => diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 1bf6f9b0fc0e8..fa3e7e23dae6e 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -2349,7 +2349,8 @@ export default function ChatView(props: ChatViewProps) { const { acknowledgeActiveThreadWoke, activeBranchMismatchKey, - backgroundWorkNow, + attentionNow, + workNow, childInputNow, goalNow, handleSwitchCheckoutToThread, @@ -2993,10 +2994,7 @@ export default function ChatView(props: ChatViewProps) { const onExpandTimelineImageStable = useStableCallback(onExpandTimelineImage); const shownThreadSyncPhase = activeEnvironmentUnavailable ? null : delayedThreadSyncPhase; const hasThreadNow = - childInputNow !== null || - backgroundWorkNow !== null || - goalNow !== null || - shownThreadSyncPhase !== null; + attentionNow !== null || workNow !== null || goalNow !== null || shownThreadSyncPhase !== null; const queuedRunCount = serverProjection ? getUserQueuedThreadRuns(serverProjection).length : 0; // The queue control is mounted for every server thread but joins the footer only while it shows // something, by its own rule: an optimistic message stops counting once the server has it. @@ -3035,8 +3033,8 @@ export default function ChatView(props: ChatViewProps) { )} diff --git a/apps/web/src/components/chat/ThreadActivityBanners.tsx b/apps/web/src/components/chat/ThreadActivityBanners.tsx index 168b674d26c92..8bd26e21a04dc 100644 --- a/apps/web/src/components/chat/ThreadActivityBanners.tsx +++ b/apps/web/src/components/chat/ThreadActivityBanners.tsx @@ -7,17 +7,20 @@ import type { EnvironmentThreadShell, ThreadStructure } from "@t3tools/client-ru import { presentPendingBackgroundWork, presentProviderGoal, + type RunStopPresentation, } from "@t3tools/client-runtime/state/thread-execution"; import { childThreadInputsTitle } from "@t3tools/client-runtime/state/threads"; import { formatDuration } from "@t3tools/shared/orchestrationTiming"; import * as DateTime from "effect/DateTime"; import { CircleDashedIcon, + CircleStopIcon, GitBranchIcon, MessageCircleIcon, ShieldQuestionIcon, TargetIcon, TerminalIcon, + TriangleAlertIcon, } from "lucide-react"; import { Fragment } from "react"; import { tickTextContent } from "~/lib/tickTextContent"; @@ -105,6 +108,46 @@ export function goalNowItem(input: { }; } +/** A Stop the provider has not finished; Force stop once it stops answering. */ +export function runStopNowItem(input: { + readonly threadId: ThreadId; + readonly stop: RunStopPresentation; + readonly canForceStop: boolean; + readonly forceStopping: boolean; + readonly onForceStop: () => void; +}): ThreadNowItem { + const unresponsive = input.stop.state === "unresponsive"; + const requestedAtMs = Date.parse(input.stop.requestedAt); + return { + id: `run-stop:${input.threadId}`, + icon: unresponsive ? ( + + ) : ( + + ), + title: unresponsive ? "Agent not responding to Stop" : "Stopping", + description: unresponsive + ? "It may be short on memory. Force stop kills its processes." + : undefined, + actions: ( + <> + formatDuration(Math.max(1_000, nowMs - requestedAtMs)), + true, + )} + className="tabular-nums" + /> + {unresponsive && input.canForceStop ? ( + + {input.forceStopping ? "Force stopping..." : "Force stop"} + + ) : null} + + ), + }; +} + /** Background commands and subagents, for the end of the timeline. */ export function backgroundWorkNowItem(input: { readonly threadId: ThreadId; diff --git a/apps/web/src/components/chat/useForceStopThread.ts b/apps/web/src/components/chat/useForceStopThread.ts new file mode 100644 index 0000000000000..00876c758a8b6 --- /dev/null +++ b/apps/web/src/components/chat/useForceStopThread.ts @@ -0,0 +1,59 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { EnvironmentId, RunId, ThreadId } from "@t3tools/contracts"; +import { useState } from "react"; + +import { useServerConfigs } from "../../state/entities"; +import { orchestrationEnvironment } from "../../state/orchestration"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { toastManager } from "../ui/toast"; + +/** Force stop for an agent that no longer answers Stop; shared by every place that offers it. */ +export function useForceStopThread(environmentId: EnvironmentId) { + const forceStop = useAtomCommand(orchestrationEnvironment.forceStopThread); + const permitted = useAtomValue( + orchestrationEnvironment.forceStopThread.permissionAtom(environmentId), + ); + const supported = + useServerConfigs().get(environmentId)?.environment.capabilities.threadForceStop === true; + const canForceStop = permitted && supported; + const [stoppingThreadId, setStoppingThreadId] = useState(null); + /** Pass the run that ignored Stop, so a Force stop left open cannot hit a newer run. */ + const forceStopThread = async (threadId: ThreadId, runId?: RunId) => { + if (!canForceStop || stoppingThreadId !== null) return; + setStoppingThreadId(threadId); + const result = await forceStop({ + environmentId, + input: runId === undefined ? { threadId } : { threadId, runId }, + }); + setStoppingThreadId(null); + if (result._tag === "Failure") { + if (isAtomCommandInterrupted(result)) return; + const error = squashAtomCommandFailure(result); + toastManager.add({ + type: "error", + title: "Could not force stop the agent", + description: error instanceof Error ? error.message : undefined, + }); + return; + } + const others = result.value.sharedWithThreadIds.length; + if (result.value.outcome === "releasing") { + toastManager.add({ + type: "info", + title: "Turn stopped; the agent is still shutting down", + }); + } + if (result.value.outcome === "shared") { + toastManager.add({ + type: "info", + title: "Turn stopped; the agent process kept running", + description: `It is shared with ${others === 0 ? "other" : others} working ${others === 1 ? "thread" : "threads"}. Stop those to free it.`, + }); + } + }; + return { canForceStop, stoppingThreadId, forceStopThread }; +} diff --git a/apps/web/src/components/chat/useThreadLifecycle.tsx b/apps/web/src/components/chat/useThreadLifecycle.tsx index b1cf8a4a6af4c..0ad8acacf71ce 100644 --- a/apps/web/src/components/chat/useThreadLifecycle.tsx +++ b/apps/web/src/components/chat/useThreadLifecycle.tsx @@ -58,9 +58,22 @@ import { appAtomRegistry } from "../../rpc/atomRegistry"; import { readEnvironmentScope } from "../../state/session"; import { useAtomCommand } from "../../state/use-atom-command"; import { useOrchestrationCommand } from "../../state/use-orchestration-command"; -import { backgroundWorkNowItem, childInputNowItem, goalNowItem } from "./ThreadActivityBanners"; +import { + backgroundWorkNowItem, + childInputNowItem, + goalNowItem, + runStopNowItem, +} from "./ThreadActivityBanners"; +import { useForceStopThread } from "./useForceStopThread"; +import { useAtomValue } from "@effect/atom-react"; +import type { RunStopPresentation } from "@t3tools/client-runtime/state/thread-execution"; +import { Atom } from "effect/reactivity"; +import { environmentThreadDetails } from "../../state/threads"; import type { useLocalDispatchState } from "./useLocalDispatchState"; const RELATED_THREAD_SHELL_WAIT_MS = 1_000; +const NO_RUN_STOP_ATOM = Atom.make(null).pipe( + Atom.withLabel("web-thread-run-stop:empty"), +); type PendingThreadRequests = ReturnType; type LocalDispatchState = ReturnType; @@ -509,6 +522,22 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) { }) : null; + const forceStop = useForceStopThread(environmentId); + const anyRunStop = useAtomValue( + activeThreadRef ? environmentThreadDetails.runStopAtom(activeThreadRef) : NO_RUN_STOP_ATOM, + ); + // A background Stop matters only while that work is still pending. + const runStop = anyRunStop?.background && activeBackgroundTasks.length === 0 ? null : anyRunStop; + const runStopNow = + activeThread && runStop !== null + ? runStopNowItem({ + threadId: activeThread.id, + stop: runStop, + canForceStop: forceStop.canForceStop, + forceStopping: forceStop.stoppingThreadId === activeThread.id, + onForceStop: () => void forceStop.forceStopThread(activeThread.id, runStop.runId), + }) + : null; const backgroundWorkNow = activeThread ? backgroundWorkNowItem({ threadId: activeThread.id, @@ -592,7 +621,9 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) { shortcuts, acknowledgeActiveThreadWoke, activeBranchMismatchKey, - backgroundWorkNow, + // A Stop that went unanswered needs the user; one in progress is the thread's work. + attentionNow: runStop?.state === "unresponsive" ? runStopNow : childInputNow, + workNow: runStop?.state === "stopping" ? runStopNow : backgroundWorkNow, childInputNow, goalNow, handleSwitchCheckoutToThread, diff --git a/packages/client-runtime/src/state/orchestration.ts b/packages/client-runtime/src/state/orchestration.ts index 4e6d3022b4812..5f5c2ce3020ac 100644 --- a/packages/client-runtime/src/state/orchestration.ts +++ b/packages/client-runtime/src/state/orchestration.ts @@ -107,6 +107,10 @@ export function createOrchestrationEnvironmentAtoms( label: "environment-data:orchestration:stop-workflow", tag: ORCHESTRATION_V2_WS_METHODS.stopWorkflow, }), + forceStopThread: createEnvironmentRpcCommand(runtime, { + label: "environment-data:orchestration:force-stop-thread", + tag: ORCHESTRATION_V2_WS_METHODS.forceStopThread, + }), turnItem: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:orchestration:turn-item", tag: ORCHESTRATION_V2_WS_METHODS.getTurnItem, diff --git a/packages/client-runtime/src/state/threadDetail.ts b/packages/client-runtime/src/state/threadDetail.ts index e1f30998caefb..3819c5d92ba5e 100644 --- a/packages/client-runtime/src/state/threadDetail.ts +++ b/packages/client-runtime/src/state/threadDetail.ts @@ -14,6 +14,7 @@ import { type ThreadQueueWorkflowState, } from "./threadWorkflows.ts"; import { deriveThreadTurnSubagents, type ThreadTurnSubagents } from "./threadSubagents.ts"; +import { presentRunStop, type RunStopPresentation } from "./threadExecution.ts"; import { deriveThreadCheckpointSummaries, type ThreadCheckpointSummary, @@ -294,6 +295,32 @@ export function createEnvironmentThreadDetailAtoms( return value; }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-queue:${key}`)); }); + const runStopAtomFamily = Atom.family((key: string) => { + let previous: Pick | null = null; + let stop: RunStopPresentation | null = null; + return Atom.make((get) => { + const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data); + if (projection === null) { + previous = null; + stop = null; + } else if ( + projection.runs !== previous?.runs || + projection.turnItems !== previous?.turnItems + ) { + const { runs, turnItems } = projection; + previous = { runs, turnItems }; + const next = presentRunStop(previous); + if ( + next?.state !== stop?.state || + next?.runId !== stop?.runId || + next?.requestedAt !== stop?.requestedAt || + next?.background !== stop?.background + ) + stop = next; + } + return stop; + }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-run-stop:${key}`)); + }); const queuedCountAtomFamily = Atom.family((key: string) => { let previous: Pick | null = null; let count = 0; @@ -435,6 +462,7 @@ export function createEnvironmentThreadDetailAtoms( pendingRequestsAtom: (ref: ScopedThreadRef) => pendingRequestsAtomFamily(threadKey(ref)), queueWorkflowAtom: (ref: ScopedThreadRef) => queueWorkflowAtomFamily(threadKey(ref)), queuedCountAtom: (ref: ScopedThreadRef) => queuedCountAtomFamily(threadKey(ref)), + runStopAtom: (ref: ScopedThreadRef) => runStopAtomFamily(threadKey(ref)), turnSubagentsAtom: (ref: ScopedThreadRef) => turnSubagentsAtomFamily(threadKey(ref)), checkpointSummariesAtom: (ref: ScopedThreadRef) => checkpointSummariesAtomFamily(threadKey(ref)), diff --git a/packages/client-runtime/src/state/threadExecution.test.ts b/packages/client-runtime/src/state/threadExecution.test.ts index 8ef37f959cd40..3f8ef2a7f9d31 100644 --- a/packages/client-runtime/src/state/threadExecution.test.ts +++ b/packages/client-runtime/src/state/threadExecution.test.ts @@ -25,6 +25,7 @@ import { deriveRunlessWorkStartedAt, deriveThreadActivityRun, deriveThreadRuntime, + presentRunStop, threadRuntimeHasInterruptibleRun, } from "./threadExecution.ts"; @@ -259,6 +260,74 @@ describe("thread execution presentation", () => { }); }); +describe("presentRunStop", () => { + const signal = (type: "run_interrupt_request" | "run_interrupt_result", runId: RunId) => ({ + id: TurnItemId.make(`${type}:${runId}`), + threadId: v2Projection.thread.id, + runId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 1, + status: type === "run_interrupt_result" ? ("interrupted" as const) : ("completed" as const), + title: "Interrupt", + startedAt: now, + completedAt: now, + updatedAt: now, + type, + message: "Stopped by user", + }); + const running = run("run-stopping", 1, "running"); + const request = signal("run_interrupt_request", running.id); + + it.each([ + { name: "no Stop", runs: [running], turnItems: [], state: null }, + { + name: "a Stop the agent is winding down", + runs: [running], + turnItems: [request], + state: "stopping", + }, + { + name: "a Stop the provider never confirmed", + runs: [running], + turnItems: [{ ...request, unresponsiveAt: now }], + state: "unresponsive", + }, + { + name: "a Stop that ended the run", + runs: [running], + turnItems: [request, signal("run_interrupt_result", running.id)], + state: null, + }, + { + name: "a settled run's background work still stopping", + runs: [{ ...running, status: "completed" as const, completedAt: now }], + turnItems: [request], + state: null, + }, + { + name: "a settled run whose background work ignored Stop", + runs: [{ ...running, status: "completed" as const, completedAt: now }], + turnItems: [{ ...request, unresponsiveAt: now }], + state: "unresponsive", + }, + { + name: "a settled run whose background work ignored Stop, with a queued follow-up", + runs: [ + { ...running, status: "completed" as const, completedAt: now }, + run("run-queued", 2, "queued"), + ], + turnItems: [{ ...request, unresponsiveAt: now }], + state: "unresponsive", + }, + ])("presents $name", ({ runs, turnItems, state }) => { + expect(presentRunStop({ runs, turnItems })?.state ?? null).toBe(state); + }); +}); + describe("deriveRunlessWorkStartedAt", () => { const later = DateTime.makeUnsafe("2026-07-28T10:05:00.000Z"); const rootTurn = ( diff --git a/packages/client-runtime/src/state/threadExecution.ts b/packages/client-runtime/src/state/threadExecution.ts index ba87930bebbd5..52d07babfbb61 100644 --- a/packages/client-runtime/src/state/threadExecution.ts +++ b/packages/client-runtime/src/state/threadExecution.ts @@ -294,6 +294,55 @@ const BACKGROUND_WORK_KINDS: Record< background_task: { order: 3, singular: "background task", plural: "background tasks" }, }; +export interface RunStopPresentation { + /** `unresponsive`: the provider did not confirm the stop in time, so Force stop is offered. */ + readonly state: "stopping" | "unresponsive"; + readonly runId: ThreadStructure["runs"][number]["id"]; + readonly requestedAt: string; + /** The run already ended; the Stop targeted its background work. */ + readonly background: boolean; +} + +/** + * A Stop the provider has not finished yet. It stays `stopping` while the agent winds down, + * since some providers confirm the request before the turn actually ends. On a run that + * already ended, only an unanswered Stop of its background work counts. + */ +export function presentRunStop( + projection: Pick, +): RunStopPresentation | null { + let active: ThreadStructure["runs"][number] | null = null; + let latest: ThreadStructure["runs"][number] | null = null; + for (const candidate of projection.runs) { + // Queued follow-ups never ran, so they hold no Stop of their own. + if (candidate.status !== "queued" && candidate.ordinal > (latest?.ordinal ?? -1)) + latest = candidate; + if ( + INTERRUPTIBLE_RUN_STATUSES.has(candidate.status) && + candidate.ordinal > (active?.ordinal ?? -1) + ) + active = candidate; + } + const run = active ?? latest; + if (run === null) return null; + let request: + | Extract + | undefined; + for (const item of projection.turnItems) { + if (item.runId !== run.id) continue; + if (item.type === "run_interrupt_result") return null; + if (item.type === "run_interrupt_request") request = item; + } + if (request === undefined || (active === null && request.unresponsiveAt === undefined)) + return null; + return { + state: request.unresponsiveAt === undefined ? "stopping" : "unresponsive", + runId: run.id, + requestedAt: DateTime.formatIso(request.startedAt ?? request.updatedAt), + background: active === null, + }; +} + export interface PendingBackgroundWorkItem { readonly taskId: string; readonly kind: BackgroundWorkKind; diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index f9564b2e2441c..d3139f2eeff24 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -60,6 +60,8 @@ export const CLIENT_GUARDED_RPC_SCOPES = { [WS_METHODS.scheduledTasksRunNow]: AuthOrchestrationOperateScope, [WS_METHODS.scheduledTasksRotateWebhookToken]: AuthOrchestrationOperateScope, [ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: AuthOrchestrationOperateScope, + // Force stop kills agent processes, as Stop on a terminal does. + [ORCHESTRATION_V2_WS_METHODS.forceStopThread]: AuthOrchestrationOperateScope, // A guest link hands thread access to someone outside, like a pairing link. [WS_METHODS.guestShareCreate]: AuthAccessWriteScope, [WS_METHODS.peerLinksLink]: AuthAccessWriteScope, diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index 75a546bed875f..a10c6c2a6bce7 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -99,6 +99,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ /** Hide the switch when absent; older servers silently drop per-project provider patches. */ projectProviderInstanceOverrides: Schema.optionalKey(Schema.Boolean), threadSnooze: Schema.optionalKey(Schema.Boolean), + /** Serves `orchestration.forceStopThread`; hide Force stop where it is absent. */ + threadForceStop: Schema.optionalKey(Schema.Boolean), /** Every protocol-2 server sends this; older mobile builds still read it. */ environmentThemes: Schema.optionalKey(Schema.Boolean), usageLimitSources: Schema.optionalKey(Schema.Boolean), diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 026e74831233d..d20da5780255b 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1676,6 +1676,8 @@ export const OrchestrationV2TurnItem = Schema.Union([ ...OrchestrationV2TurnItemBaseFields, type: Schema.Literal("run_interrupt_request"), message: Schema.String, + /** Set when the provider did not confirm the stop in time; clients then offer Force stop. */ + unresponsiveAt: Schema.optionalKey(Schema.DateTimeUtc), }), Schema.Struct({ ...OrchestrationV2TurnItemBaseFields, @@ -2500,6 +2502,7 @@ export const OrchestrationV2TurnItemJson = Schema.Union([ ...OrchestrationV2TurnItemJsonBaseFields, type: Schema.Literal("run_interrupt_request"), message: Schema.String, + unresponsiveAt: Schema.optionalKey(Schema.DateTimeUtcFromString), }), Schema.Struct({ ...OrchestrationV2TurnItemJsonBaseFields, @@ -3436,12 +3439,22 @@ const OrchestrationV2InternalCommand = Schema.Union([ threadId: ThreadId, requestId: RuntimeRequestId, }), + /** The provider did not confirm a Stop of this turn in time. */ + Schema.Struct({ + type: Schema.Literal("thread.interrupt.unresponsive"), + commandId: CommandId, + threadId: ThreadId, + providerThreadId: ProviderThreadId, + providerTurnId: ProviderTurnId, + }), Schema.Struct({ type: Schema.Literal("thread.background-work.settle"), commandId: CommandId, threadId: ThreadId, providerThreadId: ProviderThreadId, providerTurnId: ProviderTurnId, + /** Replaces the Stop's own reason on the result, as Force stop does. */ + reason: Schema.optional(Schema.String), subagent: Schema.optional( Schema.Struct({ id: NodeId, @@ -3521,6 +3534,7 @@ export const ORCHESTRATION_V2_WS_METHODS = { getThreadProjection: "orchestration.getThreadProjection", getWorkflowScript: "orchestration.getWorkflowScript", stopWorkflow: "orchestration.stopWorkflow", + forceStopThread: "orchestration.forceStopThread", getTurnItem: "orchestration.getTurnItem", launchThread: "orchestration.launchThread", subscribeShell: "orchestration.subscribeShell", @@ -3908,6 +3922,41 @@ export class OrchestrationV2StopWorkflowError extends Schema.TaggedError()( + "OrchestrationV2ForceStopThreadError", + { + threadId: ThreadId, + /** `superseded`: a newer run started since the user asked; nothing was stopped. */ + reason: Schema.optional(Schema.Literal("superseded")), + cause: Schema.optional(Schema.Defect()), + }, +) { + override get message(): string { + return this.reason === "superseded" + ? "A new turn started, so nothing was force stopped." + : "Failed to force stop the agent."; + } +} + export const OrchestrationV2GetWorkflowScriptInput = Schema.Struct({ threadId: ThreadId, scriptPath: TrimmedNonEmptyString, @@ -4094,6 +4143,10 @@ export const OrchestrationV2RpcSchemas = { input: OrchestrationV2StopWorkflowInput, output: Schema.Void, }, + forceStopThread: { + input: OrchestrationV2ForceStopThreadInput, + output: OrchestrationV2ForceStopThreadResult, + }, getWorkflowScript: { input: OrchestrationV2GetWorkflowScriptInput, output: OrchestrationV2GetWorkflowScriptResult, diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index aae86bd9db465..145fe5e06087c 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -220,6 +220,7 @@ import { ORCHESTRATION_V2_WS_METHODS, OrchestrationGetWorkflowScriptError, OrchestrationV2StopWorkflowError, + OrchestrationV2ForceStopThreadError, OrchestrationV2DispatchCommandError, OrchestrationV2GetShellSnapshotError, OrchestrationV2CommandOutputError, @@ -1770,6 +1771,12 @@ const WsOrchestrationV2StopWorkflowRpc = Rpc.make(ORCHESTRATION_V2_WS_METHODS.st error: Schema.Union([OrchestrationV2StopWorkflowError, EnvironmentAuthorizationError]), }); +const WsOrchestrationV2ForceStopThreadRpc = Rpc.make(ORCHESTRATION_V2_WS_METHODS.forceStopThread, { + payload: OrchestrationV2RpcSchemas.forceStopThread.input, + success: OrchestrationV2RpcSchemas.forceStopThread.output, + error: Schema.Union([OrchestrationV2ForceStopThreadError, EnvironmentAuthorizationError]), +}); + const WsOrchestrationV2GetWorkflowScriptRpc = Rpc.make( ORCHESTRATION_V2_WS_METHODS.getWorkflowScript, { @@ -2122,6 +2129,7 @@ export const WsRpcGroup = RpcGroup.make( WsOrchestrationV2DispatchCommandRpc, WsOrchestrationV2GetWorkflowScriptRpc, WsOrchestrationV2StopWorkflowRpc, + WsOrchestrationV2ForceStopThreadRpc, WsOrchestrationV2GetTurnItemRpc, WsOrchestrationV2GetTurnDiffRpc, WsOrchestrationV2GetFullThreadDiffRpc, diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 13f0cbbc240d5..c895abe3f5ef8 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -1324,6 +1324,8 @@ interface SnapshotMessageState { loadingIndex: number; } +/** How long a Stop waits for the agent to confirm before the user is offered Force stop. */ +const ACP_STOP_CONFIRM_TIMEOUT_MS = 10_000; const TOOL_UPDATE_PERSIST_EVERY = 10; // Agents can resend whole calls while streaming arguments. @@ -7989,7 +7991,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return yield* Effect.uninterruptibleMask((restore) => Effect.gen(function* () { yield* restore(runtimeTransitionPermit.take(1)); - return yield* Effect.gen(function* () { + // Stop's caller times out on this call. The transition runs in its own fiber so + // a stalled hard teardown keeps its state and permit without holding the caller. + const transitionFiber = yield* Effect.gen(function* () { const transition = yield* Effect.gen(function* () { const interruptContext = yield* Ref.get(activeTurn); if ( @@ -8000,8 +8004,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ) { // ACP cancel leaves native children alive; close confirms session-wide Stop. pendingStopCloseTurn = interruptContext; - const closed = yield* runtime.closeSession().pipe( - Effect.timeoutOption("10 seconds"), + // Interruptible, or neither this timeout nor the caller's could end a hung close. + const closed = yield* restore( + runtime + .closeSession() + .pipe(Effect.timeoutOption(ACP_STOP_CONFIRM_TIMEOUT_MS)), + ).pipe( Effect.mapError( (cause) => new ProviderAdapter.ProviderAdapterProtocolError({ @@ -8013,10 +8021,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ), ); if (Option.isNone(closed)) { - return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + return yield* new ProviderAdapter.ProviderAdapterInterruptTimeoutError({ driver, - detail: - "The agent did not confirm session close; background work may still run", + providerThreadId: turnInput.providerThread.id, + providerTurnId: turnInput.providerTurnId, + timeoutMs: ACP_STOP_CONFIRM_TIMEOUT_MS, }); } yield* runtimeCallbackPermit.withPermit( @@ -8246,15 +8255,16 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } } const stopped = yield* Deferred.await(context.completed).pipe( - Effect.timeoutOption("10 seconds"), + Effect.timeoutOption(ACP_STOP_CONFIRM_TIMEOUT_MS), ); + // The turn stays open: the agent may still be working, and the user + // decides whether to Force stop it. if (Option.isNone(stopped)) { - if (!context.finalized) { - yield* finalizeTurn(context, "interrupted"); - } - return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + return yield* new ProviderAdapter.ProviderAdapterInterruptTimeoutError({ driver, - detail: `ACP provider turn ${turnInput.providerTurnId} did not acknowledge cancellation before the interrupt timeout`, + providerThreadId: turnInput.providerThread.id, + providerTurnId: turnInput.providerTurnId, + timeoutMs: ACP_STOP_CONFIRM_TIMEOUT_MS, }); } }); @@ -8275,20 +8285,29 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }), ), ); - }).pipe(Effect.ensuring(runtimeTransitionPermit.release(1))); + }).pipe( + Effect.ensuring(runtimeTransitionPermit.release(1)), + Effect.forkIn(sessionScope, { startImmediately: true, uninterruptible: true }), + ); + return yield* restore(Fiber.join(transitionFiber)).pipe( + Effect.onInterrupt(() => + Fiber.interrupt(transitionFiber).pipe(Effect.forkDetach, Effect.asVoid), + ), + ); }), ); }, (effect, turnInput) => effect.pipe( - Effect.mapError( - (cause) => - new ProviderAdapter.ProviderAdapterInterruptError({ - driver, - providerThreadId: turnInput.providerThread.id, - providerTurnId: turnInput.providerTurnId, - cause, - }), + Effect.mapError((cause) => + cause._tag === "ProviderAdapterInterruptTimeoutError" + ? cause + : new ProviderAdapter.ProviderAdapterInterruptError({ + driver, + providerThreadId: turnInput.providerThread.id, + providerTurnId: turnInput.providerTurnId, + cause, + }), ), ), ), diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index e168512736c7c..0b5459f647f8d 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -327,6 +327,21 @@ export class ProviderAdapterInterruptError extends Schema.TaggedError()( + "ProviderAdapterInterruptTimeoutError", + { + driver: ProviderDriverKind, + providerThreadId: ProviderThreadId, + providerTurnId: ProviderTurnId, + timeoutMs: Schema.Number, + }, +) { + override get message(): string { + return `The ${this.driver} provider did not confirm stopping turn ${this.providerTurnId} within ${this.timeoutMs} ms.`; + } +} + export class ProviderAdapterRuntimeRequestResponseError extends Schema.TaggedError()( "ProviderAdapterRuntimeRequestResponseError", { @@ -388,6 +403,7 @@ export const ProviderAdapterV2Error = Schema.Union([ ProviderAdapterSteerRunUnsupportedError, ProviderAdapterSteerRunError, ProviderAdapterInterruptError, + ProviderAdapterInterruptTimeoutError, ProviderAdapterRuntimeRequestResponseError, ProviderAdapterEventStreamError, ProviderAdapterProtocolError, diff --git a/packages/shared/src/AgentScope.ts b/packages/shared/src/AgentScope.ts index ce2d58c017b25..5f0ffca217172 100644 --- a/packages/shared/src/AgentScope.ts +++ b/packages/shared/src/AgentScope.ts @@ -22,6 +22,12 @@ export interface AgentScopeShape { * descendants outside its process group. Preserves systemd OOM diagnosis. */ readonly stop: (unit: string) => Effect.Effect; + /** + * SIGKILLs every process in the thread's own scope, which works even while + * the kernel throttles them. Shared scopes serve other threads and are never + * killed here. Succeeds with whether a scope was killed. + */ + readonly kill: (threadId: string) => Effect.Effect; /** * Forgets the thread's scope. The session manager calls it before it opens * a provider session, so a scope only answers for the session that launched @@ -42,6 +48,7 @@ export const AgentScope = Context.Reference("@t3tools/shared/Ag wrap: ({ command, args }) => Effect.succeed({ command, args }), oomKilled: () => Effect.succeed(false), stop: () => Effect.void, + kill: () => Effect.succeed(false), clear: () => Effect.void, }), }); From 35c1210331a70fd3f460f9ad3425aed7d9a263cf Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 29 Oct 2026 22:23:04 -0700 Subject: [PATCH 409/817] fix: guest links can load earlier turns (#27354) Co-authored-by: Claude Opus 5.5 --- .../src/guest/GuestShareService.test.ts | 85 +++++++++++++++++++ apps/server/src/guest/GuestShareService.ts | 22 +++++ apps/server/src/guest/http.ts | 24 ++++++ apps/web/src/components/guest/GuestPage.tsx | 60 ++++++++++++- .../guest/guestStream.logic.test.ts | 39 +++++++++ .../src/components/guest/guestStream.logic.ts | 26 +++++- packages/client-runtime/package.json | 4 + packages/contracts/src/guestShare.ts | 5 ++ 8 files changed, 262 insertions(+), 3 deletions(-) diff --git a/apps/server/src/guest/GuestShareService.test.ts b/apps/server/src/guest/GuestShareService.test.ts index 1ef25744c8c55..ac5ffc76aae77 100644 --- a/apps/server/src/guest/GuestShareService.test.ts +++ b/apps/server/src/guest/GuestShareService.test.ts @@ -7,6 +7,7 @@ import { GuestShareId, type GuestStreamEvent, MessageId, + type OrchestrationV2ThreadHistoryPage, type OrchestrationV2TurnItem, ProjectId, ProviderDriverKind, @@ -529,6 +530,90 @@ it.effect("gives the guest a command's detail and output, but no file diffs", () }).pipe(Effect.provide(layerTest)), ); +it.effect("pages the guest back through turns older than the stream's snapshot", () => + Effect.gen(function* () { + const { guestShares, credential } = yield* shareThread; + const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" }); + const runId = yield* ownerRun; + const fileSystem = yield* FileSystem.FileSystem; + const directory = yield* fileSystem.makeTempDirectoryScoped(); + const shot = `${directory}/old.png`; + yield* fileSystem.writeFile(shot, PNG); + const eventSink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + const base = { threadId, runId, nodeId: null, providerThreadId: null, providerTurnId: null }; + const turnItem = (id: string, ordinal: number, payload: object) => ({ + id: EventId.make(`event:${id}`), + type: "turn-item.updated" as const, + threadId, + driver: ProviderDriverKind.make("codex"), + providerInstanceId: instanceId, + occurredAt: now, + payload: { + ...base, + id: TurnItemId.make(id), + nativeItemRef: null, + parentItemId: null, + ordinal, + title: null, + status: "completed" as const, + startedAt: now, + completedAt: now, + updatedAt: now, + messageId: MessageId.make(id), + ...payload, + } as OrchestrationV2TurnItem, + }); + yield* eventSink.write({ + events: [ + turnItem("item:old-image", 1, { + type: "assistant_message", + text: `![Old](${shot})`, + streaming: false, + }), + ...Array.from({ length: 30 }, (_, index) => + turnItem(`item:ask-${index}`, index + 2, { + type: "user_message", + text: `Ask ${index}`, + createdBy: "user", + creationSource: "web", + inputIntent: "turn_start", + attachments: [], + }), + ), + ], + }); + + const [, opening] = Array.from( + yield* Stream.runCollect(Stream.take(yield* guestShares.stream(session), 2)), + ); + if (opening?.type !== "thread" || opening.item.kind !== "snapshot") { + return assert.fail("Expected the thread snapshot second."); + } + const ids = (rows: ReadonlyArray<{ readonly sourceItemId: string }>) => + rows.map((row) => row.sourceItemId); + assert.notInclude(ids(opening.item.projection.visibleTurnItems), "item:old-image"); + let cursor = opening.item.historyCursor ?? null; + assert.isNotNull(cursor); + // The page has not shown the old reply yet, so its image does not load. + assert.equal((yield* Effect.flip(guestShares.media(session, shot))).reason, "unavailable"); + // Only a session pages. + assert.isTrue(Exit.isFailure(yield* Effect.exit(guestShares.history(credential, cursor!)))); + + const older: Array = []; + while (cursor !== null) { + const page: OrchestrationV2ThreadHistoryPage = yield* guestShares.history(session, cursor); + older.push(...ids(page.items)); + cursor = page.hasMoreHistory ? page.nextCursor : null; + } + assert.include(older, "item:old-image"); + assert.deepStrictEqual(yield* guestShares.media(session, shot), { + path: shot, + mimeType: "image/png", + }); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + it.effect("ends a running command's output once the owner stops sharing", () => Effect.gen(function* () { const { orchestrator, guestShares, credential } = yield* shareThread; diff --git a/apps/server/src/guest/GuestShareService.ts b/apps/server/src/guest/GuestShareService.ts index 347bdc11ece5b..2a1bf853507ba 100644 --- a/apps/server/src/guest/GuestShareService.ts +++ b/apps/server/src/guest/GuestShareService.ts @@ -15,6 +15,7 @@ import { type OrchestrationV2CommandOutputFrame, type OrchestrationV2DomainEvent, type OrchestrationV2GetTurnItemResult, + type OrchestrationV2ThreadHistoryPage, type OrchestrationV2TurnItem, ThreadId, TurnItemId, @@ -185,6 +186,11 @@ export class GuestShareService extends Context.Service< session: string, itemId: string, ) => Effect.Effect; + /** Older turns of the shared thread, as the owner's client pages them. */ + readonly history: ( + session: string, + cursor: string, + ) => Effect.Effect; /** A command's output frames, as the owner's expanded row gets them, until the link ends. */ readonly commandOutput: ( session: string, @@ -665,6 +671,21 @@ const make = Effect.gen(function* () { }; }); + const history = Effect.fn("GuestShareService.history")(function* ( + session: string, + cursor: string, + ) { + const { thread, share } = yield* authorize(session, "session"); + const page = yield* orchestrator + .getThreadHistoryPage(thread.id, cursor) + .pipe(Effect.mapError(() => unavailable)); + rememberSent( + share.id, + page.items.map((row) => row.item), + ); + return page; + }); + const commandOutput = Effect.fn("GuestShareService.commandOutput")(function* ( session: string, itemId: string, @@ -739,6 +760,7 @@ const make = Effect.gen(function* () { stream, render, item, + history, commandOutput, attachment, media, diff --git a/apps/server/src/guest/http.ts b/apps/server/src/guest/http.ts index bf368ac884d92..b3e856200c845 100644 --- a/apps/server/src/guest/http.ts +++ b/apps/server/src/guest/http.ts @@ -1,6 +1,7 @@ import { GUEST_ATTACHMENT_ROUTE, GUEST_COMMAND_OUTPUT_ROUTE, + GUEST_HISTORY_ROUTE, GUEST_ITEM_ROUTE, GUEST_MEDIA_ROUTE, GUEST_RENDER_ROUTE, @@ -16,6 +17,7 @@ import { isProviderSendTurnSupportedImageMimeType, OrchestrationV2CommandOutputFrame, OrchestrationV2GetTurnItemResult, + OrchestrationV2ThreadHistoryPage, } from "@t3tools/contracts"; import * as ByteSize from "effect/ByteSize"; import * as Duration from "effect/Duration"; @@ -52,6 +54,7 @@ const encodeOutputFrame = Schema.encodeEffect( Schema.fromJsonString(OrchestrationV2CommandOutputFrame), ); const encodeItem = Schema.encodeEffect(Schema.toCodecJson(OrchestrationV2GetTurnItemResult)); +const encodeHistoryPage = Schema.encodeEffect(Schema.toCodecJson(OrchestrationV2ThreadHistoryPage)); const errorResponse = (error: GuestShareAccessError) => HttpServerResponse.json( @@ -292,6 +295,26 @@ const itemRoute = HttpRouter.add( }), ); +const historyRoute = HttpRouter.add( + "GET", + GUEST_HISTORY_ROUTE, + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const cursor = new URLSearchParams(request.url.split("?", 2)[1] ?? "").get("cursor"); + if (!cursor) return yield* badRequest; + const guestShares = yield* GuestShareService; + return yield* guestShares.history(yield* sessionToken, cursor).pipe( + Effect.flatMap((page) => + encodeHistoryPage(page).pipe( + Effect.mapError(() => new GuestShareAccessError({ reason: "unavailable" })), + ), + ), + Effect.map((body) => HttpServerResponse.jsonUnsafe(body, { headers: NO_STORE })), + Effect.catchTags({ GuestShareAccessError: errorResponse }), + ); + }), +); + // Ends when the command settles; the page closes its EventSource on that last frame, so the // browser does not reconnect. const commandOutputRoute = HttpRouter.add( @@ -365,6 +388,7 @@ export const layer = Layer.mergeAll( streamRoute, renderRoute, itemRoute, + historyRoute, commandOutputRoute, attachmentRoute, mediaRoute, diff --git a/apps/web/src/components/guest/GuestPage.tsx b/apps/web/src/components/guest/GuestPage.tsx index 21c35447ddf8c..7e41e9a8ca297 100644 --- a/apps/web/src/components/guest/GuestPage.tsx +++ b/apps/web/src/components/guest/GuestPage.tsx @@ -1,6 +1,7 @@ import { EnvironmentId, GUEST_MESSAGE_MAX_LENGTH, + GUEST_HISTORY_ROUTE, GUEST_NAME_MAX_LENGTH, GUEST_ROUTE_PREFIX, GUEST_SHARE_PARAM, @@ -8,6 +9,7 @@ import { type GuestRedeemRequest, type GuestShareView, type GuestThreadModel, + OrchestrationV2ThreadHistoryPage, type OrchestrationV2ThreadProjection, type ThreadGuestMessage, type ThreadGuestMessageStatus, @@ -46,7 +48,7 @@ import { GuestMessageAttachments } from "../chat/GuestMessageAttachments"; import { HostImageUrlContext } from "../chat/hostImageUrl"; import { PierreEntryIcon } from "../chat/PierreEntryIcon"; import { GuestMessageName, guestBubbleClassName } from "../chat/guestMessageStyle"; -import { MessagesTimeline } from "../chat/MessagesTimeline"; +import { MessagesTimeline, type MessagesTimelineHistoryControls } from "../chat/MessagesTimeline"; import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon"; import { getDisplayModelName, getTriggerDisplayModelName } from "../chat/providerIconUtils"; import { ScrollToEndButton } from "../chat/TimelineOverlays"; @@ -131,6 +133,32 @@ function takeGuestEntry(): GuestEntry { } const decodeErrorBody = Schema.decodeUnknownOption(Schema.Struct({ message: Schema.String })); +const decodeHistoryPage = Schema.decodeUnknownOption( + Schema.toCodecJson(OrchestrationV2ThreadHistoryPage), +); + +/** Resolves to the page, or to a message the guest can read. */ +async function fetchGuestHistoryPage( + shareId: string, + cursor: string, +): Promise { + const failed = "Could not load earlier turns. Try again."; + try { + const response = await fetch( + `${GUEST_HISTORY_ROUTE}?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}&cursor=${encodeURIComponent(cursor)}`, + ); + const json: unknown = await response.json().catch(() => null); + if (!response.ok) { + return Option.match(decodeErrorBody(json), { + onNone: () => failed, + onSome: ({ message }) => message, + }); + } + return Option.getOrElse(decodeHistoryPage(json), () => failed); + } catch { + return "Could not reach the server."; + } +} /** Resolves to null on success, or to a message the guest can read. */ async function postGuest( @@ -241,6 +269,32 @@ function GuestSession({ shareId }: { readonly shareId: string }) { // missing, invalid, or ended session. Network drops reconnect on their own. const [rejected, setRejected] = useState(false); + const [historyLoad, setHistoryLoad] = useState<{ + readonly cursor: string; + readonly error: string | null; + } | null>(null); + const historyCursor = stream.historyCursor; + // A load for an older cursor is stale: a page or a reconnect snapshot moved the cursor on. + const currentLoad = historyLoad?.cursor === historyCursor ? historyLoad : null; + const loadingHistory = currentLoad !== null && currentLoad.error === null; + const historyError = currentLoad?.error ?? null; + const loadEarlier = async () => { + if (historyCursor === null || loadingHistory) return; + setHistoryLoad({ cursor: historyCursor, error: null }); + const result = await fetchGuestHistoryPage(shareId, historyCursor); + if (typeof result === "string") setHistoryLoad({ cursor: historyCursor, error: result }); + else dispatch({ type: "history-page", cursor: historyCursor, page: result }); + }; + const historyControls: MessagesTimelineHistoryControls | undefined = + historyCursor === null + ? undefined + : { + hasMoreHistory: true, + loading: loadingHistory, + error: historyError, + onLoadEarlier: () => void loadEarlier(), + }; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- sets document.title to the shared thread's title useEffect(() => { if (stream.view) document.title = stream.view.title; @@ -273,6 +327,7 @@ function GuestSession({ shareId }: { readonly shareId: string }) { view={stream.view} projection={stream.projection} awaitingRowIds={stream.awaitingRowIds} + historyControls={historyControls} /> ); } @@ -358,10 +413,12 @@ function GuestThread({ view: { shareId, title, expiresAt, messages, model }, projection, awaitingRowIds, + historyControls, }: { readonly view: GuestShareView; readonly projection: OrchestrationV2ThreadProjection; readonly awaitingRowIds: GuestStreamState["awaitingRowIds"]; + readonly historyControls: MessagesTimelineHistoryControls | undefined; }) { // No ":" so the timeline finds no environment thread behind the key. const threadKey = `guest-${shareId}`; @@ -467,6 +524,7 @@ function GuestThread({ onFileDownload={openFile} renderHtmlRender={renderHtmlRender} turnItemSource={turnItemSource} + historyControls={historyControls} activeThreadEnvironmentId={GUEST_ENVIRONMENT_ID} markdownCwd={undefined} resolvedTheme={resolvedTheme} diff --git a/apps/web/src/components/guest/guestStream.logic.test.ts b/apps/web/src/components/guest/guestStream.logic.test.ts index fbdf9ce1927c2..674227dc171ff 100644 --- a/apps/web/src/components/guest/guestStream.logic.test.ts +++ b/apps/web/src/components/guest/guestStream.logic.test.ts @@ -112,6 +112,45 @@ describe("applyGuestStreamEvent", () => { expect(apply([itemEvent(2, reply("a1", "Changed"))], once)).toBe(once); }); + it("merges older pages in front, only for the cursor the thread is at", () => { + const windowed: GuestStreamEvent = { + type: "thread", + item: { + kind: "snapshot", + snapshotSequence: 1, + projection, + historyCursor: "cursor-1", + hasMoreHistory: true, + }, + }; + const page = (id: string, nextCursor: string | null) => ({ + snapshotSequence: 1, + items: [ + { + position: 0, + visibility: "local" as const, + sourceThreadId: projection.thread.id, + sourceItemId: TurnItemId.make(id), + item: reply(id, "Earlier"), + }, + ], + nextCursor, + hasMoreHistory: nextCursor !== null, + }); + const live = apply([windowed, itemEvent(2, reply("a1", "Hi"))]); + expect(live.historyCursor).toBe("cursor-1"); + // A page fetched before a reconnect moved the cursor changes nothing. + const stale = { type: "history-page" as const, cursor: "cursor-0", page: page("old", null) }; + expect(applyGuestStreamEvent(live, stale)).toBe(live); + const merged = applyGuestStreamEvent(live, { + type: "history-page", + cursor: "cursor-1", + page: page("o1", null), + }); + expect(itemIds(merged)).toEqual(["o1", "a1"]); + expect(merged.historyCursor).toBeNull(); + }); + it("replaces the thread on a new snapshot, as after a reconnect", () => { const before = apply([snapshot(1), itemEvent(2, reply("a1", "Hi")), { type: "ended" }]); const after = apply([snapshot(1)], { ...before, ended: false }); diff --git a/apps/web/src/components/guest/guestStream.logic.ts b/apps/web/src/components/guest/guestStream.logic.ts index 0b37d66eeec84..03eafb6d348ee 100644 --- a/apps/web/src/components/guest/guestStream.logic.ts +++ b/apps/web/src/components/guest/guestStream.logic.ts @@ -9,11 +9,13 @@ import { type GuestMessageId, type GuestShareView, type OrchestrationV2ProjectedTurnItem, + type OrchestrationV2ThreadHistoryPage, type OrchestrationV2ThreadProjection, type OrchestrationV2TurnItem, type ThreadGuestMessage, } from "@t3tools/contracts"; import { applyOrchestrationV2ProjectionEvent } from "@t3tools/client-runtime/state/orchestration-v2-projection"; +import { mergeOlderHistoryIntoProjection } from "@t3tools/client-runtime/state/thread-history-merge"; import { boundedSnapshotProjection } from "@t3tools/shared/orchestrationV2BoundedSnapshot"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; @@ -25,6 +27,8 @@ export interface GuestStreamState { readonly sequence: number; /** Set while the snapshot is a window of a longer history, as the owner's client tracks it. */ readonly partial: { readonly latestLocalTurnOrdinal: number | null } | null; + /** Where "Load earlier turns" continues, or null once the whole thread is loaded. */ + readonly historyCursor: string | null; readonly ended: boolean; /** * Messages this page saw waiting that have no transcript row yet. Survives reconnects, and a @@ -38,6 +42,7 @@ export const initialGuestStreamState: GuestStreamState = { projection: null, sequence: 0, partial: null, + historyCursor: null, ended: false, awaitingRowIds: new Set(), }; @@ -76,16 +81,32 @@ const decodeGuestStreamEvent = Schema.decodeUnknownOption( export const parseGuestStreamEvent = (data: string): GuestStreamEvent | null => Option.getOrNull(decodeGuestStreamEvent(data)); +/** A page of older turns, fetched from `cursor`. */ +export type GuestHistoryPageLoaded = { + readonly type: "history-page"; + readonly cursor: string; + readonly page: OrchestrationV2ThreadHistoryPage; +}; + /** * Applies the owner's thread stream the way the owner's client does (see * EnvironmentThreadState in client-runtime): a snapshot replaces the thread, and later events - * pass through the same projection reducer, once each. + * pass through the same projection reducer, once each. Older pages merge in front, as they do in + * the owner's view. */ export function applyGuestStreamEvent( state: GuestStreamState, - event: GuestStreamEvent, + event: GuestStreamEvent | GuestHistoryPageLoaded, ): GuestStreamState { switch (event.type) { + case "history-page": + // A snapshot since the request replaced the thread and its cursor. + if (state.projection === null || state.historyCursor !== event.cursor) return state; + return { + ...state, + projection: mergeOlderHistoryIntoProjection(state.projection, event.page.items), + historyCursor: event.page.hasMoreHistory ? event.page.nextCursor : null, + }; case "view": // The page follows the share it names; a view of another one means the link changed. if (state.view !== null && state.view.shareId !== event.view.shareId) { @@ -108,6 +129,7 @@ export function applyGuestStreamEvent( item.hasMoreHistory === true || (item.historyCursor ?? null) !== null ? { latestLocalTurnOrdinal: item.latestLocalTurnOrdinal ?? null } : null, + historyCursor: item.hasMoreHistory === true ? (item.historyCursor ?? null) : null, awaitingRowIds: withoutPlaced( state.awaitingRowIds, projection.visibleTurnItems.map((row) => row.item), diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index e1f81638ea3d4..9600ad7ad356d 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -203,6 +203,10 @@ "types": "./src/state/orchestration.ts", "default": "./src/state/orchestration.ts" }, + "./state/thread-history-merge": { + "types": "./src/state/threadHistoryMerge.ts", + "default": "./src/state/threadHistoryMerge.ts" + }, "./state/orchestration-v2-projection": { "types": "./src/state/orchestrationV2Projection.ts", "default": "./src/state/orchestrationV2Projection.ts" diff --git a/packages/contracts/src/guestShare.ts b/packages/contracts/src/guestShare.ts index fd991fe1e4c3b..715a837daeae3 100644 --- a/packages/contracts/src/guestShare.ts +++ b/packages/contracts/src/guestShare.ts @@ -129,6 +129,11 @@ export const guestSessionCookieName = (shareId: string) => `t3_guest_${shareId}` export const GUEST_RENDER_ROUTE = `${GUEST_ROUTE_PREFIX}/render`; /** One item of the shared thread, as an expanded row loads it: `?share=&item=`. */ export const GUEST_ITEM_ROUTE = `${GUEST_ROUTE_PREFIX}/item`; +/** + * Older turns of the shared thread, as the owner's "Load earlier turns" pages them: + * `?share=&cursor=`. + */ +export const GUEST_HISTORY_ROUTE = `${GUEST_ROUTE_PREFIX}/history`; /** Server-sent output frames of one command in the shared thread: `?share=&item=`. */ export const GUEST_COMMAND_OUTPUT_ROUTE = `${GUEST_ROUTE_PREFIX}/command-output`; /** From da8cc591dadd75819ae62961da4a882767efb145 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Thu, 29 Oct 2026 22:34:35 -0700 Subject: [PATCH 410/817] fix(ci): repair main after merge burst Rename leftover fakeProvider to fakePullRequestProvider, replace the removed encodeScanCache in the advisor usage test, and drop an issue number from a ClaudeAdapterV2 comment that lint rejects. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts | 2 +- apps/server/src/pullRequest/PullRequestService.test.ts | 4 ++-- apps/server/src/usage/usageScanCache.test.ts | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index a821a4713b292..428e44e19020c 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -4216,7 +4216,7 @@ function claudeTaskString(value: unknown, key: string): string | undefined { } // A Claude Code mod can hold a tool call until the user acts in its terminal -// pane. T3 cannot provide the requested pane interaction (#17531). +// pane. T3 cannot provide the requested pane interaction. // Passive panes never request focus and keep working. function claudeFocusRequestedPanePlugin(message: SDKMessage): string | null { if (message.type !== "system" || claudeTaskField(message, "subtype") !== "ui_panes") return null; diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts index 2b4d2f68c5502..3c511b292afb8 100644 --- a/apps/server/src/pullRequest/PullRequestService.test.ts +++ b/apps/server/src/pullRequest/PullRequestService.test.ts @@ -2204,7 +2204,7 @@ it.effect("a refresh or a finished turn drops the provider's own change request }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("gitlab"), { + fakePullRequestProvider(SourceControlProviderKind.make("gitlab"), { forgetChangeRequestReads: (scope) => Effect.sync(() => void forgotten.push(scope)), }), ], @@ -2241,7 +2241,7 @@ it.effect("a read during a refresh cannot keep the provider's old change request }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("gitlab"), { + fakePullRequestProvider(SourceControlProviderKind.make("gitlab"), { getChangeRequest: () => Effect.sync(() => { held ??= hostTitle; diff --git a/apps/server/src/usage/usageScanCache.test.ts b/apps/server/src/usage/usageScanCache.test.ts index be8ad53c6e45a..477b8bb6fc4f6 100644 --- a/apps/server/src/usage/usageScanCache.test.ts +++ b/apps/server/src/usage/usageScanCache.test.ts @@ -251,7 +251,7 @@ describe("scan cache round trip", () => { it("re-parses a Claude transcript cached before advisor usage was counted", () => { const original = cacheWith([["/claude.jsonl", 100, [record()]]]); - const v9 = { ...encodeScanCache(original), version: 9 }; + const v9 = { ...JSON.parse(makeScanCacheWriter()(original, {})), version: 9 }; const restored = decodeScanCache(JSON.parse(JSON.stringify(v9)), TEST_FORMAT_MAP); expect(restored.get("/claude.jsonl")).toEqual({ From fa4e4677c0ecc437aece2dcea39f76ef31414152 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 29 Oct 2026 23:04:17 -0700 Subject: [PATCH 411/817] fix(server): let slow worktree checkouts finish (#23802) Co-authored-by: Claude Opus 5.5 --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 48 ++++++++++++++++++++ apps/server/src/vcs/GitVcsDriverCore.ts | 5 +- 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index cbc3efcc3b4e7..d05a41a6f3824 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -920,6 +920,54 @@ it.effect("retries a fetch that lost a ref update to another Git process", () => }).pipe(Effect.provide(layerServerConfig.pipe(Layer.provideMerge(NodeServices.layer)))), ); +it.effect("lets a worktree checkout that is still working run past five minutes", () => + Effect.gen(function* () { + const checkoutStarted = yield* Deferred.make(); + const checkoutFinished = yield* Deferred.make(); + const spawner = ChildProcessSpawner.make((command) => + Effect.gen(function* () { + if (!ChildProcess.isStandardCommand(command)) + return yield* Effect.die("expected Git command"); + if (!command.args.includes("worktree")) return makeSuccessfulHandle(""); + yield* Deferred.succeed(checkoutStarted, undefined); + return ChildProcessSpawner.makeHandle({ + ...makeSuccessfulHandle(""), + exitCode: Deferred.await(checkoutFinished).pipe( + Effect.as(ChildProcessSpawner.ExitCode(0)), + ), + stderr: Stream.encodeText( + Stream.concat( + Stream.make("Updating files: 40% (49052/122629)\n"), + Stream.fromEffect( + Deferred.await(checkoutFinished).pipe( + Effect.as("Updating files: 100% (122629/122629), done.\n"), + ), + ), + ), + ), + }); + }), + ); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + const path = yield* Path.Path; + const cwd = yield* makeTmpDir(); + const worktreePath = path.join(cwd, "worktree"); + + const creation = yield* driver + .createWorktree({ cwd, refName: "main", newRefName: "t3/slow-checkout", path: worktreePath }) + .pipe(Effect.forkChild); + yield* Deferred.await(checkoutStarted); + yield* TestClock.adjust("6 minutes"); + yield* Deferred.succeed(checkoutFinished, undefined); + + const result = yield* Fiber.join(creation); + assert.equal(result.worktree.path, worktreePath); + assert.equal(result.worktree.refName, "t3/slow-checkout"); + }).pipe(Effect.provide(layerServerConfig.pipe(Layer.provideMerge(NodeServices.layer)))), +); + describe("rejected git refs", () => { const remoteUrl = "https://user:token-123@git.example.invalid/org/secret-repo.git"; const failedPush = `error: failed to push some refs to '${remoteUrl}'`; diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 03f0286ce50d7..3a7c99fbc3d31 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -62,7 +62,6 @@ const branchBaseConfigKey = (branch: string) => `branch.${branch}.t3-merge-base` */ const legacyBranchBaseConfigKey = (branch: string) => `branch.${branch}.gh-merge-base`; const gitProcesses = Semaphore.makeUnsafe(8); -const WORKTREE_ADD_TIMEOUT_MS = 300_000; const WORKTREE_REMOVE_TIMEOUT_MS = Duration.toMillis(Duration.minutes(5)); const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000; const OUTPUT_TRUNCATED_MARKER = "\n\n[truncated]"; @@ -3877,7 +3876,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ["-c", `checkout.workers=${checkoutWorkers}`, ...args], { fallbackErrorDetail: "git worktree add failed", - timeoutMs: WORKTREE_ADD_TIMEOUT_MS, + // Large checkouts and post-checkout hooks can legitimately run for many + // minutes; a fixed deadline kills them and leaves an orphaned worktree. + timeoutMs: null, ...(onCheckoutProgress ? { // Git only prints checkout progress when stderr is a tty or the From 97e35bcf23e4dcf34c2dcffadd37c08db0e01e52 Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Fri, 30 Oct 2026 02:51:36 -0400 Subject: [PATCH 412/817] feat(settings): point provider environment variables at a secret provider (#27115) Co-authored-by: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 Signed-off-by: Yordis Prieto --- .../SettingsEnvironmentDetailRouteScreen.tsx | 5 +- apps/server/package.json | 3 + apps/server/src/auth/RpcAuthorization.test.ts | 24 +- apps/server/src/auth/RpcAuthorization.ts | 3 +- .../Adapters/ClaudeAdapterV2.test.ts | 4 +- .../Adapters/PiAdapterV2.testkit.ts | 4 +- .../server/src/project/AgentSessionScanner.ts | 6 +- .../provider/ProviderInstanceRegistry.test.ts | 175 ++++++++++++++ .../src/provider/ProviderInstanceRegistry.ts | 201 ++++++++++++++-- .../ProviderInstanceRegistryHydration.ts | 11 +- .../ProviderInstanceRegistryMutator.ts | 4 +- .../src/provider/ProviderRegistry.test.ts | 27 ++- apps/server/src/provider/ProviderRegistry.ts | 24 +- .../provider/providerCompatibility.test.ts | 12 +- .../providerMaintenanceRunner.test.ts | 1 + .../testUtils/providerRegistryMock.ts | 1 + apps/server/src/secrets/SecretResolver.ts | 20 ++ .../secrets/secretProviderDefinitions.test.ts | 12 + .../src/secrets/secretProviderDefinitions.ts | 7 + apps/server/src/serverSettings.test.ts | 43 ++++ apps/server/src/serverSettings.ts | 43 +++- apps/server/src/settingsSecrets.ts | 9 +- apps/server/src/ws.ts | 9 +- apps/web/package.json | 2 + .../settings/AddProviderInstanceDialog.tsx | 3 + .../settings/ProviderInstanceCard.test.ts | 17 +- .../settings/ProviderInstanceCard.tsx | 221 ++++++++++++------ .../settings/ProviderSettingsPanel.tsx | 5 +- .../settings/SecretProviderDialog.logic.ts | 6 +- .../SecretSourceInput.browser.test.tsx | 82 +++++++ .../components/settings/SecretSourceInput.tsx | 185 +++++++++++++++ package.json | 2 +- packages/contracts/src/index.ts | 1 + packages/contracts/src/providerInstance.ts | 35 ++- packages/contracts/src/rpc.ts | 2 + packages/contracts/src/secretReference.ts | 27 +++ packages/contracts/src/server.ts | 2 + packages/contracts/src/settings.test.ts | 59 ++++- packages/contracts/src/settings.ts | 58 +---- packages/provider-core/src/server/driver.ts | 4 +- .../src/server/instanceEnvironment.test.ts | 12 +- .../src/server/instanceEnvironment.ts | 2 + packages/secret-provider-core/package.json | 33 +++ .../src/server/SecretResolver.test.ts | 170 ++++++++++++++ .../src/server/SecretResolver.ts | 125 ++++++++++ .../secret-provider-core/src/server/driver.ts | 46 ++++ .../src/shared/definition.ts | 35 +++ packages/secret-provider-core/tsconfig.json | 7 + .../secret-provider-definitions/package.json | 18 ++ .../src/registry.ts | 6 + .../secret-provider-definitions/tsconfig.json | 4 + .../secret-provider-onepassword/package.json | 32 +++ .../src/server/driver.test.ts | 155 ++++++++++++ .../src/server/driver.ts | 112 +++++++++ .../src/shared/definition.test.ts | 28 +++ .../src/shared/definition.ts | 41 ++++ .../secret-provider-onepassword/tsconfig.json | 7 + packages/shared/src/serverSettings.test.ts | 3 +- pnpm-lock.yaml | 77 ++++++ scripts/release-smoke.ts | 3 + 60 files changed, 2094 insertions(+), 181 deletions(-) create mode 100644 apps/server/src/secrets/SecretResolver.ts create mode 100644 apps/server/src/secrets/secretProviderDefinitions.test.ts create mode 100644 apps/server/src/secrets/secretProviderDefinitions.ts create mode 100644 apps/web/src/components/settings/SecretSourceInput.browser.test.tsx create mode 100644 apps/web/src/components/settings/SecretSourceInput.tsx create mode 100644 packages/contracts/src/secretReference.ts create mode 100644 packages/secret-provider-core/package.json create mode 100644 packages/secret-provider-core/src/server/SecretResolver.test.ts create mode 100644 packages/secret-provider-core/src/server/SecretResolver.ts create mode 100644 packages/secret-provider-core/src/server/driver.ts create mode 100644 packages/secret-provider-core/src/shared/definition.ts create mode 100644 packages/secret-provider-core/tsconfig.json create mode 100644 packages/secret-provider-definitions/package.json create mode 100644 packages/secret-provider-definitions/src/registry.ts create mode 100644 packages/secret-provider-definitions/tsconfig.json create mode 100644 packages/secret-provider-onepassword/package.json create mode 100644 packages/secret-provider-onepassword/src/server/driver.test.ts create mode 100644 packages/secret-provider-onepassword/src/server/driver.ts create mode 100644 packages/secret-provider-onepassword/src/shared/definition.test.ts create mode 100644 packages/secret-provider-onepassword/src/shared/definition.ts create mode 100644 packages/secret-provider-onepassword/tsconfig.json diff --git a/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx index c581cbc688142..5f83979197bbc 100644 --- a/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx @@ -294,7 +294,10 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm void run("refresh", async () => { if (!readEnvironmentScope(environmentId, AuthOrchestrationReadScope)) return; - const result = await refreshProviders({ environmentId, input: {} }); + const result = await refreshProviders({ + environmentId, + input: { reloadSecrets: true }, + }); if (AsyncResult.isFailure(result)) throw squashAtomCommandFailure(result); setNotice("Provider status refreshed."); }); diff --git a/apps/server/package.json b/apps/server/package.json index 9ee890670abbf..789d612e6fe3b 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -78,6 +78,9 @@ "@opencode-ai/sdk": "^1.3.15", "@t3tools/contracts": "workspace:*", "@t3tools/provider-testing": "workspace:*", + "@t3tools/secret-provider-core": "workspace:*", + "@t3tools/secret-provider-definitions": "workspace:*", + "@t3tools/secret-provider-onepassword": "workspace:*", "@t3tools/shared": "workspace:*", "@t3tools/source-control-testing": "workspace:*", "@t3tools/ssh": "workspace:*", diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts index 24c22280175cc..8044740a7e2ee 100644 --- a/apps/server/src/auth/RpcAuthorization.test.ts +++ b/apps/server/src/auth/RpcAuthorization.test.ts @@ -5,6 +5,7 @@ import { AuthProvidersManageScope, AuthSettingsWriteScope, DEFAULT_SERVER_SETTINGS, + ProviderDriverKind, ProviderInstanceId, SecretProviderId, ThreadId, @@ -164,13 +165,34 @@ describe("settings mutation authorization", () => { ); yield* client[WS_METHODS.serverUpdateSettings]({ patch: {}, providerInstanceMutation }); expect(handled).toBe(1); + yield* client[WS_METHODS.serverUpdateSettings]({ + patch: {}, + providerInstanceMutation: { + operation: "upsert", + instanceId: ProviderInstanceId.make("codex_work"), + instance: { + driver: ProviderDriverKind.make("codex"), + environment: [ + { + name: "OPENAI_API_KEY", + sensitive: true, + value: { + provider: SecretProviderId.make("personal"), + reference: "op://Private/OpenAI/credential", + }, + }, + ], + }, + }, + }); + expect(handled).toBe(2); expect( yield* client[WS_METHODS.serverUpdateSettings]({ patch: { defaultRuntimeMode: "full-access" }, providerInstanceMutation, }).pipe(Effect.flip), ).toMatchObject({ requiredPermission: AuthSettingsWriteScope }); - expect(handled).toBe(1); + expect(handled).toBe(2); }).pipe(Effect.scoped), ); diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index ecda5f8abc61b..3806262cced53 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -228,7 +228,8 @@ const SettingsUpdate = Schema.Struct({ patch: ServerSettingsPatch, providerInstanceMutation: Schema.optionalKey(ProviderInstanceMutation), }); -const decodeSettingsUpdate = Schema.decodeUnknownSync(SettingsUpdate); +// Middleware receives the payload already decoded, so it is checked against the decoded shape. +const decodeSettingsUpdate = Schema.decodeUnknownSync(Schema.toType(SettingsUpdate)); const requiredScopesForSettingsUpdate = (payload: unknown) => { const input = decodeSettingsUpdate(payload); diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index c38ec736884ea..40f33b3a1a309 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -40,7 +40,7 @@ import { OrchestrationV2ProviderThread, ProjectId, ProviderInstanceId, - type ProviderInstanceEnvironment, + type ResolvedProviderInstanceEnvironment, ProviderDriverKind, type ProviderReplayTranscript, type ProviderApprovalDecision, @@ -1189,7 +1189,7 @@ describe("ClaudeAdapterV2 approval cancellation", () => { const captureSdkExecutablePaths = Effect.fn("captureSdkExecutablePaths")(function* ( binaryPath: string, - environment: ProviderInstanceEnvironment = [], + environment: ResolvedProviderInstanceEnvironment = [], ) { const executablePaths: Array = []; const taskToolEnvironment: Array = []; diff --git a/apps/server/src/orchestration-v2/Adapters/PiAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/PiAdapterV2.testkit.ts index c894442409921..49eb6c9b3b999 100644 --- a/apps/server/src/orchestration-v2/Adapters/PiAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/PiAdapterV2.testkit.ts @@ -2,7 +2,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { ProviderReplayEntry, ProviderInstanceId, - type ProviderInstanceEnvironment, + type ResolvedProviderInstanceEnvironment, type ProviderReplayTranscript, type ProviderReplayEntry as ProviderReplayEntryType, } from "@t3tools/contracts"; @@ -363,7 +363,7 @@ export function layer(input: { readonly spawner: Layer.Layer; readonly binaryPath: string; readonly launchArgs: string; - readonly environment?: ProviderInstanceEnvironment; + readonly environment?: ResolvedProviderInstanceEnvironment; }) { return ProviderAdapterRegistry.layerFromAdaptersEffect( PiAdapterV2Driver.create({ diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index 9c26b187a55bf..7ec79c38a38a9 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -1112,9 +1112,11 @@ export const make = Effect.gen(function* () { const seenHomes = new Set(); for (const { instanceId, config: instance } of instances) { const homeVariable = source === "claudeAgent" ? "CLAUDE_CONFIG_DIR" : "CODEX_HOME"; + const configuredHome = instance.environment?.findLast( + (variable) => variable.name === homeVariable, + )?.value; const environmentHome = - instance.environment?.findLast((variable) => variable.name === homeVariable)?.value ?? - hostEnvironment[homeVariable]; + typeof configuredHome === "string" ? configuredHome : hostEnvironment[homeVariable]; let homePath: string; if (source === "claudeAgent") { diff --git a/apps/server/src/provider/ProviderInstanceRegistry.test.ts b/apps/server/src/provider/ProviderInstanceRegistry.test.ts index de8fc1deae452..dc9c94e854f68 100644 --- a/apps/server/src/provider/ProviderInstanceRegistry.test.ts +++ b/apps/server/src/provider/ProviderInstanceRegistry.test.ts @@ -12,16 +12,22 @@ import { type CodexSettings, ProviderDriverKind, type ProviderInstanceConfigMap, + type ResolvedProviderInstanceEnvironment, ProviderInstanceId, + SecretProviderId, + type SecretReference, } from "@t3tools/contracts"; import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; +import * as PubSub from "effect/PubSub"; +import * as Schema from "effect/Schema"; import * as TestClock from "effect/testing/TestClock"; import { HttpClient, HttpClientResponse } from "effect/http"; @@ -37,6 +43,8 @@ import { makeProviderInstanceRegistry } from "./ProviderInstanceRegistry.ts"; import * as ProviderOrchestrationAdapterInfrastructure from "./ProviderOrchestrationAdapterInfrastructure.ts"; import * as PortScanner from "../preview/PortScanner.ts"; import * as ProviderHostLive from "./ProviderHostLive.ts"; +import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; +import type { AnyProviderDriver, ProviderInstance } from "@t3tools/provider-core/server/driver"; vi.mock("@anthropic-ai/claude-agent-sdk", { spy: true }); @@ -164,6 +172,7 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => { }), ), Layer.provideMerge(Layer.mock(ServerSecretStore.ServerSecretStore)({})), + Layer.provideMerge(Layer.mock(SecretResolver.SecretResolver)({})), Layer.provideMerge( Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity, { getEnvironmentId: Effect.succeed( @@ -643,3 +652,169 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => { }).pipe(Effect.provide(layerTest)), ); }); + +const DisabledByDefaultConfig = Schema.Struct({ + enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), +}); + +describe("ProviderInstanceRegistry secret environment", () => { + const driverKind = ProviderDriverKind.make("fake"); + const instanceId = ProviderInstanceId.make("fake_main"); + const secret: SecretReference = { + provider: SecretProviderId.make("personal"), + reference: "op://Private/OpenAI/credential", + }; + + function setup( + initial: Record, + configSchema: AnyProviderDriver["configSchema"] = Schema.Unknown, + ) { + const vault = new Map(Object.entries(initial)); + const reads: Array> = []; + const invalidated: Array> = []; + const created: Array = []; + const driver: AnyProviderDriver = { + driverKind, + metadata: { displayName: "Fake" }, + configSchema, + defaultConfig: () => ({}), + create: (input) => + Effect.sync(() => { + created.push(input.environment); + return { instanceId: input.instanceId, enabled: input.enabled } as ProviderInstance; + }), + }; + const gate = Deferred.makeUnsafe(); + const resolver = Layer.succeed(SecretResolver.SecretResolver, { + read: (references) => + Deferred.await(gate).pipe( + Effect.andThen( + Effect.sync(() => { + reads.push(references.map((reference) => reference.reference)); + return references.map((reference) => vault.get(reference.reference)); + }), + ), + ), + invalidate: (references = []) => + Effect.sync(() => { + invalidated.push(references.map((reference) => reference.reference)); + }), + }); + const configMap: ProviderInstanceConfigMap = { + [instanceId]: { + driver: driverKind, + config: {}, + environment: [ + { name: "OPENAI_API_KEY", value: secret, sensitive: true }, + { name: "BASE_URL", value: "https://example.test", sensitive: false }, + ], + }, + }; + const makeGated = makeProviderInstanceRegistry({ drivers: [driver], configMap }).pipe( + Effect.provide(resolver), + ); + // Secrets are read after startup, so wait for the change that applies them. + const make = Effect.gen(function* () { + const built = yield* makeGated; + const changes = yield* built.registry.subscribeChanges; + yield* Deferred.succeed(gate, undefined); + yield* PubSub.take(changes); + return built; + }); + return { vault, reads, invalidated, created, make, makeGated, gate }; + } + + it.effect("starts an instance with the secret its environment points at", () => { + const fixture = setup({ [secret.reference]: "sk-live" }); + return Effect.gen(function* () { + const { registry } = yield* fixture.make; + + expect(yield* registry.getInstance(instanceId)).toBeDefined(); + expect(fixture.created).toEqual([ + [ + { name: "OPENAI_API_KEY", value: "sk-live", sensitive: true }, + { name: "BASE_URL", value: "https://example.test", sensitive: false }, + ], + ]); + }).pipe(Effect.scoped); + }); + + it.effect("marks an instance unavailable and names the variable it could not read", () => { + const fixture = setup({}); + return Effect.gen(function* () { + const { registry } = yield* fixture.make; + + expect(yield* registry.getInstance(instanceId)).toBeUndefined(); + expect(fixture.created).toEqual([]); + const [unavailable] = yield* registry.listUnavailable; + expect(unavailable?.instanceId).toBe(instanceId); + expect(unavailable?.unavailableReason).toContain("OPENAI_API_KEY"); + }).pipe(Effect.scoped); + }); + + it.effect("does not read the secrets of an instance its config decodes as disabled", () => { + const fixture = setup({ [secret.reference]: "sk-live" }, DisabledByDefaultConfig); + return Effect.gen(function* () { + const { mutator } = yield* fixture.makeGated; + yield* mutator.reloadSecrets(); + + expect(fixture.reads).toEqual([]); + expect(fixture.invalidated).toEqual([]); + expect(fixture.created).toHaveLength(1); + }).pipe(Effect.scoped); + }); + + it.effect("re-reads secrets on reload and rebuilds only when they changed", () => { + const fixture = setup({}); + return Effect.gen(function* () { + const { registry, mutator } = yield* fixture.make; + + fixture.vault.set(secret.reference, "sk-live"); + yield* mutator.reloadSecrets(); + expect(fixture.invalidated).toEqual([[secret.reference]]); + expect(yield* registry.getInstance(instanceId)).toBeDefined(); + expect(yield* registry.listUnavailable).toEqual([]); + + yield* mutator.reloadSecrets(instanceId); + expect(fixture.created).toHaveLength(1); + + fixture.vault.set(secret.reference, "sk-rotated"); + yield* mutator.reloadSecrets(instanceId); + expect(fixture.created.map((environment) => environment[0]?.value)).toEqual([ + "sk-live", + "sk-rotated", + ]); + }).pipe(Effect.scoped); + }); + + it.effect("keeps a working instance live when a reload cannot read its secret", () => { + const fixture = setup({ [secret.reference]: "sk-live" }); + return Effect.gen(function* () { + const { registry, mutator } = yield* fixture.make; + + fixture.vault.delete(secret.reference); + yield* mutator.reloadSecrets(); + + expect(yield* registry.getInstance(instanceId)).toBeDefined(); + expect(yield* registry.listUnavailable).toEqual([]); + expect(fixture.created).toHaveLength(1); + }).pipe(Effect.scoped); + }); + + it.effect("starts without waiting for secrets to be read", () => { + const fixture = setup({ [secret.reference]: "sk-live" }); + return Effect.gen(function* () { + const { registry } = yield* fixture.makeGated; + const changes = yield* registry.subscribeChanges; + + expect(yield* registry.getInstance(instanceId)).toBeUndefined(); + const [pending] = yield* registry.listUnavailable; + expect(pending?.unavailableReason).toBe("Reading secrets…"); + + yield* Deferred.succeed(fixture.gate, undefined); + yield* PubSub.take(changes); + expect(yield* registry.getInstance(instanceId)).toBeDefined(); + expect(yield* registry.listUnavailable).toEqual([]); + }).pipe(Effect.scoped); + }); +}); diff --git a/apps/server/src/provider/ProviderInstanceRegistry.ts b/apps/server/src/provider/ProviderInstanceRegistry.ts index 3bbbe2900b9f2..70352c5ef8593 100644 --- a/apps/server/src/provider/ProviderInstanceRegistry.ts +++ b/apps/server/src/provider/ProviderInstanceRegistry.ts @@ -3,7 +3,10 @@ import { ProviderInstanceId, type ProviderInstanceConfig, type ProviderInstanceConfigMap, + type ProviderInstanceEnvironment, type ProviderDriverKind, + type ResolvedProviderInstanceEnvironment, + type SecretReference, type ServerProvider, } from "@t3tools/contracts"; import * as Context from "effect/Context"; @@ -11,12 +14,16 @@ import * as Effect from "effect/Effect"; import * as Equal from "effect/Equal"; import * as Exit from "effect/Exit"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as PubSub from "effect/PubSub"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; +import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; +import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; + import { buildUnavailableProviderSnapshot } from "./unavailableProviderSnapshot.ts"; import * as ProviderInstanceRegistryMutator from "./ProviderInstanceRegistryMutator.ts"; import type { AnyProviderDriver, ProviderInstance } from "@t3tools/provider-core/server/driver"; @@ -39,6 +46,7 @@ interface LiveEntry { readonly instance: ProviderInstance; readonly scope: Scope.Closeable; readonly entry: ProviderInstanceConfig; + readonly environment: ResolvedProviderInstanceEnvironment; } interface RegistryState { @@ -50,6 +58,39 @@ interface RegistryState { const entryEqual = (a: ProviderInstanceConfig, b: ProviderInstanceConfig): boolean => Equal.equals(a, b); +const secretReferencesIn = (environment: ProviderInstanceEnvironment): Array => + environment.flatMap((variable) => (typeof variable.value === "string" ? [] : [variable.value])); + +const secretReferencesOf = (entry: ProviderInstanceConfig): ReadonlyArray => + secretReferencesIn(entry.environment ?? []); + +const withoutSecretReferences = ( + environment: ProviderInstanceEnvironment, +): ResolvedProviderInstanceEnvironment => + environment.flatMap((variable) => + typeof variable.value === "string" ? [{ ...variable, value: variable.value }] : [], + ); + +const readSecretEnvironment = Effect.fn("ProviderInstanceRegistry.readSecretEnvironment")( + function* (environment: ProviderInstanceEnvironment) { + const references = secretReferencesIn(environment); + const values = + references.length === 0 ? [] : yield* (yield* SecretResolver.SecretResolver).read(references); + const unreadable: Array = []; + let index = 0; + const resolved: ResolvedProviderInstanceEnvironment = environment.flatMap((variable) => { + if (typeof variable.value === "string") return [{ ...variable, value: variable.value }]; + const secret = values[index++]; + if (secret === undefined) { + unreadable.push(variable.name); + return []; + } + return [{ ...variable, value: secret, sensitive: true }]; + }); + return { environment: resolved, unreadable }; + }, +); + /** Conflicting saved flags must preserve any explicit disable. */ const resolveEntryEnabled = (entry: ProviderInstanceConfig, typedConfig: unknown): boolean => { const rawConfigEnabled = providerInstanceConfigEnabledFlag(entry.config); @@ -59,19 +100,32 @@ const resolveEntryEnabled = (entry: ProviderInstanceConfig, typedConfig: unknown return entry.enabled ?? providerInstanceConfigEnabledFlag(typedConfig) ?? true; }; +// The enabled state `buildEntry` decodes, so a disabled instance never reads its secrets. +const isEntryEnabled = Effect.fn("ProviderInstanceRegistry.isEntryEnabled")(function* ( + driversById: ReadonlyMap>, + entry: ProviderInstanceConfig, +) { + const driver = driversById.get(entry.driver); + if (!driver) return false; + const decoder = Schema.decodeUnknownEffect(driver.configSchema); + const decoded = yield* decoder(entry.config ?? driver.defaultConfig()).pipe(Effect.option); + return Option.isSome(decoded) && resolveEntryEnabled(entry, decoded.value); +}); + const buildEntry = Effect.fn("ProviderInstanceRegistry.buildEntry")(function* (input: { readonly driversById: ReadonlyMap>; readonly parentScope: Scope.Scope; readonly instanceId: ProviderInstanceId; readonly rawInstanceId: string; readonly entry: ProviderInstanceConfig; + readonly deferSecrets: boolean; }): Effect.fn.Return< | { readonly kind: "live"; readonly live: LiveEntry } | { readonly kind: "unavailable"; readonly snapshot: ServerProvider }, never, - R + R | SecretResolver.SecretResolver > { - const { driversById, parentScope, instanceId, rawInstanceId, entry } = input; + const { driversById, parentScope, instanceId, rawInstanceId, entry, deferSecrets } = input; const driver = driversById.get(entry.driver); if (!driver) { return { @@ -109,6 +163,37 @@ const buildEntry = Effect.fn("ProviderInstanceRegistry.buildEntry")(function* 0) { + return { + kind: "unavailable" as const, + snapshot: yield* buildUnavailableProviderSnapshot({ + driverKind: entry.driver, + instanceId, + displayName: entry.displayName, + accentColor: entry.accentColor, + reason: "Reading secrets…", + }), + }; + } + const { environment, unreadable } = enabled + ? yield* readSecretEnvironment(entry.environment ?? []) + : { environment: withoutSecretReferences(entry.environment ?? []), unreadable: [] }; + // Starting with a blank credential would fail later with a less useful error, or fall back to + // whatever the server inherited. + if (unreadable.length > 0) { + return { + kind: "unavailable" as const, + snapshot: yield* buildUnavailableProviderSnapshot({ + driverKind: entry.driver, + instanceId, + displayName: entry.displayName, + accentColor: entry.accentColor, + reason: `Could not read ${unreadable.join(", ")} from its secret provider. Unlock it, then refresh.`, + }), + }; + } + const childScope = yield* Scope.make(); yield* Scope.addFinalizer(parentScope, Scope.close(childScope, Exit.void).pipe(Effect.ignore)); @@ -117,8 +202,8 @@ const buildEntry = Effect.fn("ProviderInstanceRegistry.buildEntry")(function* (input: { readonly state: RegistryState; readonly driversById: ReadonlyMap>; readonly parentScope: Scope.Scope; -}): ((configMap: ProviderInstanceConfigMap) => Effect.Effect) => { +}): (( + configMap: ProviderInstanceConfigMap, + rebuild?: ReadonlySet, + deferSecrets?: boolean, +) => Effect.Effect) => { const { state, driversById, parentScope } = input; - return (configMap: ProviderInstanceConfigMap) => + return (configMap, rebuild = new Set(), deferSecrets = false) => Effect.gen(function* () { const previousEntries = yield* Ref.get(state.entries); const previousUnavailable = yield* Ref.get(state.unavailable); @@ -175,7 +265,10 @@ const makeReconcile = (input: { continue; } const nextEntry = configMap[instanceId]; - if (nextEntry !== undefined && !entryEqual(live.entry, nextEntry)) { + if ( + rebuild.has(instanceId) || + (nextEntry !== undefined && !entryEqual(live.entry, nextEntry)) + ) { replacedIds.add(instanceId); } } @@ -186,6 +279,20 @@ const makeReconcile = (input: { } } + // Read every secret the builds below need in one go, so a vault unlocks once. + const references = yield* Effect.forEach(nextRaw, ([rawInstanceId, entry]) => + Effect.gen(function* () { + const instanceId = ProviderInstanceId.make(rawInstanceId); + const kept = previousEntries.has(instanceId) && !replacedIds.has(instanceId); + return kept || !(yield* isEntryEnabled(driversById, entry)) + ? [] + : secretReferencesOf(entry); + }), + ).pipe(Effect.map((perEntry) => perEntry.flat())); + if (references.length > 0 && !deferSecrets) { + yield* (yield* SecretResolver.SecretResolver).read(references); + } + const builtEntries = new Map(); const builtUnavailable = new Map(); let orderChanged = false; @@ -208,6 +315,7 @@ const makeReconcile = (input: { instanceId, rawInstanceId, entry, + deferSecrets, }); if (result.kind === "live") { builtEntries.set(instanceId, result.live); @@ -260,7 +368,7 @@ export const makeProviderInstanceRegistry = Effect.fn( readonly mutator: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape; }, never, - R | Scope.Scope + R | SecretResolver.SecretResolver | Scope.Scope > { const driversById = new Map>( input.drivers.map((driver) => [driver.driverKind, driver]), @@ -272,7 +380,7 @@ export const makeProviderInstanceRegistry = Effect.fn( // scopes to the *caller's* scope instead of the registry's. const parentScope = yield* Scope.Scope; - const driverContext = yield* Effect.context(); + const driverContext = yield* Effect.context(); const entries = yield* Ref.make>(new Map()); const unavailable = yield* Ref.make>(new Map()); @@ -281,10 +389,76 @@ export const makeProviderInstanceRegistry = Effect.fn( const state: RegistryState = { entries, unavailable, changes }; const reconcileWithR = makeReconcile({ state, driversById, parentScope }); + const configMapRef = yield* Ref.make(input.configMap); + const semaphore = yield* Semaphore.make(1); const reconcile: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape["reconcile"] = - (configMap) => reconcileWithR(configMap).pipe(Effect.provideContext(driverContext)); + (configMap) => + semaphore.withPermits(1)( + Ref.set(configMapRef, configMap).pipe( + Effect.andThen(reconcileWithR(configMap)), + Effect.provideContext(driverContext), + ), + ); - yield* reconcile(input.configMap); + // Rebuilds an instance only when it was unavailable or its secrets changed, so a refresh does + // not restart providers whose credentials are the same. + const reloadSecrets: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape["reloadSecrets"] = + Effect.fn("ProviderInstanceRegistry.reloadSecrets")( + function* (instanceId) { + const configMap = yield* Ref.get(configMapRef); + const targets = yield* Effect.filter(Object.entries(configMap), ([rawInstanceId, entry]) => + (instanceId === undefined || rawInstanceId === instanceId) && + secretReferencesOf(entry).length > 0 + ? isEntryEnabled(driversById, entry) + : Effect.succeed(false), + ); + if (targets.length === 0) return; + const resolver = yield* SecretResolver.SecretResolver; + const references = targets.flatMap(([, entry]) => secretReferencesOf(entry)); + yield* resolver.invalidate(references); + yield* resolver.read(references); + const live = yield* Ref.get(entries); + const rebuild = new Set(); + for (const [rawInstanceId, entry] of targets) { + const current = live.get(ProviderInstanceId.make(rawInstanceId)); + if (current === undefined) continue; + const { environment, unreadable } = yield* readSecretEnvironment(entry.environment ?? []); + // A failed re-read keeps the working instance and the value it already holds. + if (unreadable.length === 0 && !Equal.equals(environment, current.environment)) { + rebuild.add(current.instance.instanceId); + } + } + yield* reconcileWithR(configMap, rebuild); + }, + (effect) => semaphore.withPermits(1)(effect), + Effect.provideContext(driverContext), + ); + + // Reading secrets can wait on a vault unlock, so the server does not wait for it to start. + yield* semaphore.withPermits(1)( + Ref.set(configMapRef, input.configMap).pipe( + Effect.andThen(reconcileWithR(input.configMap, new Set(), true)), + Effect.provideContext(driverContext), + ), + ); + const startupReferences = yield* Effect.filter(Object.entries(input.configMap), ([, entry]) => + secretReferencesOf(entry).length > 0 + ? isEntryEnabled(driversById, entry) + : Effect.succeed(false), + ).pipe(Effect.map((targets) => targets.flatMap(([, entry]) => secretReferencesOf(entry)))); + if (startupReferences.length > 0) { + // The read waits outside the lock so other mutations are not held for a vault prompt; a + // configuration saved meanwhile has already reconciled itself. + yield* Effect.gen(function* () { + yield* (yield* SecretResolver.SecretResolver).read(startupReferences); + yield* semaphore.withPermits(1)( + Effect.gen(function* () { + const current = yield* Ref.get(configMapRef); + if (current === input.configMap) yield* reconcileWithR(current); + }), + ); + }).pipe(Effect.provideContext(driverContext), Effect.forkScoped); + } const registry: ProviderInstanceRegistry["Service"] = { getInstance: (id) => Ref.get(entries).pipe(Effect.map((map) => map.get(id)?.instance)), @@ -307,6 +481,7 @@ export const makeProviderInstanceRegistry = Effect.fn( const mutator: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape = { reconcile, + reloadSecrets, }; return { registry, mutator }; @@ -318,7 +493,7 @@ export const layer = (input: { }): Layer.Layer< ProviderInstanceRegistry | ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator, never, - R + R | SecretResolver.SecretResolver > => Layer.effectContext( makeProviderInstanceRegistry(input).pipe( @@ -331,5 +506,5 @@ export const layer = (input: { ) as Layer.Layer< ProviderInstanceRegistry | ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator, never, - R + R | SecretResolver.SecretResolver >; diff --git a/apps/server/src/provider/ProviderInstanceRegistryHydration.ts b/apps/server/src/provider/ProviderInstanceRegistryHydration.ts index cb778f1638a22..c8f2fb9b33e05 100644 --- a/apps/server/src/provider/ProviderInstanceRegistryHydration.ts +++ b/apps/server/src/provider/ProviderInstanceRegistryHydration.ts @@ -9,6 +9,7 @@ import { ServerSettings, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import type * as Crypto from "effect/Crypto"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -16,6 +17,7 @@ import * as Path from "effect/Path"; import * as Stream from "effect/Stream"; import * as Settings from "../serverSettings.ts"; +import * as SecretResolver from "../secrets/SecretResolver.ts"; import { BUILT_IN_DRIVERS, type BuiltInDriversEnv } from "./builtInDrivers.ts"; import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts"; import * as ProviderInstanceRegistryMutator from "./ProviderInstanceRegistryMutator.ts"; @@ -39,6 +41,8 @@ type ProviderInstanceRegistryHydrationEnv = | ServerConfig.ServerConfig | Path.Path | FileSystem.FileSystem + // Secret provider reads. + | Crypto.Crypto // The Claude runner counts its CLIs as running agents for port discovery. | PortScanner.PortDiscovery; @@ -141,7 +145,8 @@ const layerSettingsWatcher = (settingsChanges: Stream.Stream) => ); export const layer: Layer.Layer< - ProviderInstanceRegistry.ProviderInstanceRegistry, + | ProviderInstanceRegistry.ProviderInstanceRegistry + | ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator, never, ProviderInstanceRegistryHydrationEnv > = Layer.unwrap( @@ -167,12 +172,14 @@ export const layer: Layer.Layer< Layer.provide(ProviderOrchestrationAdapterInfrastructure.layer), Layer.provide(AcpRegistrySupport.layerFromHost), Layer.provide(ProviderHostLive.layer), + Layer.provide(SecretResolver.layer), ); return layerSettingsWatcher(settingsChanges).pipe(Layer.provideMerge(layerMutable)); }), ) as Layer.Layer< - ProviderInstanceRegistry.ProviderInstanceRegistry, + | ProviderInstanceRegistry.ProviderInstanceRegistry + | ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator, never, ProviderInstanceRegistryHydrationEnv >; diff --git a/apps/server/src/provider/ProviderInstanceRegistryMutator.ts b/apps/server/src/provider/ProviderInstanceRegistryMutator.ts index 51322826230d8..35eb52d3f2906 100644 --- a/apps/server/src/provider/ProviderInstanceRegistryMutator.ts +++ b/apps/server/src/provider/ProviderInstanceRegistryMutator.ts @@ -1,10 +1,12 @@ /** Reconcile closes removed/replaced scopes before creating replacements: at most one live instance per id. */ -import type { ProviderInstanceConfigMap } from "@t3tools/contracts"; +import type { ProviderInstanceConfigMap, ProviderInstanceId } from "@t3tools/contracts"; import * as Context from "effect/Context"; import type * as Effect from "effect/Effect"; export interface ProviderInstanceRegistryMutatorShape { readonly reconcile: (configMap: ProviderInstanceConfigMap) => Effect.Effect; + /** Re-reads the secrets of every instance, or one, and rebuilds those whose secrets changed. */ + readonly reloadSecrets: (instanceId?: ProviderInstanceId) => Effect.Effect; } export class ProviderInstanceRegistryMutator extends Context.Service< diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.ts index 14b8dfb2ca150..5e356c84516a8 100644 --- a/apps/server/src/provider/ProviderRegistry.test.ts +++ b/apps/server/src/provider/ProviderRegistry.test.ts @@ -65,6 +65,7 @@ import type { ProviderWorkspaceSnapshot, } from "@t3tools/provider-core/server/driver"; import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts"; +import * as ProviderInstanceRegistryMutator from "./ProviderInstanceRegistryMutator.ts"; import * as ProviderRegistry from "./ProviderRegistry.ts"; import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment"; import { makeManualOnlyProviderMaintenanceCapabilities } from "@t3tools/provider-core/server/maintenanceResolver"; @@ -100,6 +101,10 @@ const withBundledCompatibility = (snapshot: ServerProvider) => ModelManifest.BUNDLED_MODEL_MANIFEST.compatibility, ); +const layerUnusedMutator = Layer.mock( + ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator, +)({}); + const layerTestHttpClient = Layer.succeed( HttpClient.HttpClient, HttpClient.make((request) => @@ -944,7 +949,12 @@ it.layer( retainedModels, ); }).pipe( - Effect.provide(ProviderRegistry.layer.pipe(Layer.provide(layerInstanceRegistry))), + Effect.provide( + ProviderRegistry.layer.pipe( + Layer.provide(layerInstanceRegistry), + Layer.provide(layerUnusedMutator), + ), + ), Effect.scoped, ); } @@ -1075,7 +1085,12 @@ it.layer( retainedModels, ); }).pipe( - Effect.provide(ProviderRegistry.layer.pipe(Layer.provide(layerInstanceRegistry))), + Effect.provide( + ProviderRegistry.layer.pipe( + Layer.provide(layerInstanceRegistry), + Layer.provide(layerUnusedMutator), + ), + ), Effect.scoped, ); } @@ -1347,6 +1362,7 @@ it.layer( yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); const runtimeServices = yield* Layer.build( ProviderRegistry.layer.pipe( + Layer.provide(layerUnusedMutator), Layer.provideMerge(layerInstanceRegistry), Layer.provideMerge( ServerConfig.layerTest(process.cwd(), { @@ -1442,6 +1458,7 @@ it.layer( yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); const runtimeServices = yield* Layer.build( ProviderRegistry.layer.pipe( + Layer.provide(layerUnusedMutator), Layer.provideMerge(layerInstanceRegistry), Layer.provideMerge( ServerConfig.layerTest(process.cwd(), { @@ -1562,6 +1579,7 @@ it.layer( yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); const runtimeServices = yield* Layer.build( ProviderRegistry.layer.pipe( + Layer.provide(layerUnusedMutator), Layer.provideMerge(instanceRegistryLayer), Layer.provideMerge( ServerConfig.layerTest(process.cwd(), { @@ -1668,6 +1686,7 @@ it.layer( yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); const runtimeServices = yield* Layer.build( ProviderRegistry.layer.pipe( + Layer.provide(layerUnusedMutator), Layer.provideMerge(layerInstanceRegistry), Layer.provideMerge( ServerConfig.layerTest(process.cwd(), { @@ -1796,6 +1815,7 @@ it.layer( yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); const runtimeServices = yield* Layer.build( ProviderRegistry.layer.pipe( + Layer.provide(layerUnusedMutator), Layer.provideMerge(layerInstanceRegistry), Layer.provideMerge( ServerConfig.layerTest(process.cwd(), { @@ -1899,6 +1919,7 @@ it.layer( yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); const runtimeServices = yield* Layer.build( ProviderRegistry.layer.pipe( + Layer.provide(layerUnusedMutator), Layer.provideMerge(layerInstanceRegistry), Layer.provideMerge( ServerConfig.layerTest(process.cwd(), { @@ -2070,7 +2091,7 @@ it.layer( enabled: false, config: { arbitrary: "payload" }, }, - } as unknown as ContractServerSettings["providerInstances"], + } as unknown as (typeof ServerSettings.Encoded)["providerInstances"], }), ), ); diff --git a/apps/server/src/provider/ProviderRegistry.ts b/apps/server/src/provider/ProviderRegistry.ts index 78b11306c5b6d..efa3385d1927e 100644 --- a/apps/server/src/provider/ProviderRegistry.ts +++ b/apps/server/src/provider/ProviderRegistry.ts @@ -19,6 +19,7 @@ import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as PubSub from "effect/PubSub"; import * as Ref from "effect/Ref"; +import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as Semaphore from "effect/Semaphore"; @@ -27,6 +28,7 @@ import * as ModelManifest from "./ModelManifest.ts"; import { applyProviderCompatibility } from "./providerCompatibility.ts"; import * as ServerConfig from "../config.ts"; import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts"; +import * as ProviderInstanceRegistryMutator from "./ProviderInstanceRegistryMutator.ts"; import { hydrateCachedProvider, isCachedProviderCorrelated, @@ -61,6 +63,11 @@ export class ProviderRegistry extends Context.Service< instanceId: ProviderInstanceId, ) => Effect.Effect>; + /** Re-reads secret-backed environments first, so a fixed secret applies without a restart. */ + readonly reloadSecretsAndRefresh: ( + instanceId?: ProviderInstanceId, + ) => Effect.Effect>; + /** Only refreshed instances can verify an update; the published list still includes every row. */ readonly refreshAfterUpdate: ( provider: ProviderDriverKind, @@ -330,6 +337,8 @@ export const layer = Layer.effect( ProviderRegistry, Effect.gen(function* () { const instanceRegistry = yield* ProviderInstanceRegistry.ProviderInstanceRegistry; + const instanceRegistryMutator = + yield* ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator; const manifestService = yield* ModelManifest.ModelManifest; const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions; const serviceScope = yield* Effect.scope; @@ -614,7 +623,9 @@ export const layer = Layer.effect( ); if (claimed.owner) { // Detach shared passes so the first caller's interruption cannot cancel other callers' work. - yield* getLiveSources.pipe( + // Syncing first keeps a refresh right after a rebuild from probing the replaced instance. + yield* syncLiveSourcesAndContinue.pipe( + Effect.andThen(getLiveSources), Effect.flatMap((sources) => Effect.forEach(sources, (source) => refreshOneSource(source), { concurrency: "unbounded", @@ -651,6 +662,7 @@ export const layer = Layer.effect( const refreshInstance = Effect.fn("refreshInstance")(function* ( instanceId: ProviderInstanceId, ) { + yield* syncLiveSourcesAndContinue; const sources = yield* getLiveSources; const providerSource = sources.find((candidate) => candidate.instanceId === instanceId); if (!providerSource) { @@ -659,6 +671,13 @@ export const layer = Layer.effect( return yield* refreshOneSource(providerSource); }); + const reloadSecretsAndRefresh = Effect.fn("reloadSecretsAndRefresh")(function* ( + instanceId?: ProviderInstanceId, + ) { + yield* instanceRegistryMutator.reloadSecrets(instanceId); + return yield* instanceId === undefined ? refresh() : refreshInstance(instanceId); + }); + const refreshAfterUpdate = Effect.fn("refreshAfterUpdate")(function* ( provider: ProviderDriverKind, selectedInstanceId: ProviderInstanceId, @@ -858,6 +877,7 @@ export const layer = Layer.effect( }, ); }), + Scope.provide(serviceScope), ); yield* upsertProviders(fallbackProviders, { publish: false }); @@ -1008,6 +1028,8 @@ export const layer = Layer.effect( refresh(provider).pipe(Effect.catchCause(recoverRefreshFailure)), refreshInstance: (instanceId: ProviderInstanceId) => refreshInstance(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)), + reloadSecretsAndRefresh: (instanceId?: ProviderInstanceId) => + reloadSecretsAndRefresh(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)), refreshWorkspaceSnapshot: (input) => refreshWorkspaceSnapshot(input).pipe(Effect.catchCause(recoverRefreshFailure)), refreshAfterUpdate, diff --git a/apps/server/src/provider/providerCompatibility.test.ts b/apps/server/src/provider/providerCompatibility.test.ts index 12c541fbd776d..8575a73230f85 100644 --- a/apps/server/src/provider/providerCompatibility.test.ts +++ b/apps/server/src/provider/providerCompatibility.test.ts @@ -13,6 +13,7 @@ import * as ModelManifest from "./ModelManifest.ts"; import * as ProviderRegistry from "./ProviderRegistry.ts"; import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions"; import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts"; +import * as ProviderInstanceRegistryMutator from "./ProviderInstanceRegistryMutator.ts"; import type { ProviderInstance } from "@t3tools/provider-core/server/driver"; import { makeManualOnlyProviderMaintenanceCapabilities } from "@t3tools/provider-core/server/maintenanceResolver"; import * as Schema from "effect/Schema"; @@ -312,6 +313,15 @@ it.effect("a remote policy refresh preserves a newer health result on the regist assert.strictEqual(updated?.compatibilityAdvisory?.status, "supported"); assert.strictEqual(updated?.status, "error"); assert.strictEqual(updated?.message, "Authentication failed"); - }).pipe(Effect.provide(ProviderRegistry.layer.pipe(Layer.provide(layerDependencies)))); + }).pipe( + Effect.provide( + ProviderRegistry.layer.pipe( + Layer.provide(layerDependencies), + Layer.provide( + Layer.mock(ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator)({}), + ), + ), + ), + ); }).pipe(Effect.scoped), ); diff --git a/apps/server/src/provider/providerMaintenanceRunner.test.ts b/apps/server/src/provider/providerMaintenanceRunner.test.ts index 75c592b7811a1..943928c4e18cf 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.test.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.test.ts @@ -192,6 +192,7 @@ function makeRegistry( getProviders: Ref.get(providersRef), refresh: () => Ref.get(providersRef), refreshInstance: () => Ref.get(providersRef), + reloadSecretsAndRefresh: () => Ref.get(providersRef), refreshAfterUpdate: () => Ref.get(providersRef), refreshWorkspaceSnapshot: () => Ref.get(providersRef), getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) => diff --git a/apps/server/src/provider/testUtils/providerRegistryMock.ts b/apps/server/src/provider/testUtils/providerRegistryMock.ts index 358d49afe45c2..a4008acc18efb 100644 --- a/apps/server/src/provider/testUtils/providerRegistryMock.ts +++ b/apps/server/src/provider/testUtils/providerRegistryMock.ts @@ -11,6 +11,7 @@ const makeProviderRegistryMock = ( getProviders: Effect.succeed(providers), refresh: () => Effect.succeed(providers), refreshInstance: () => Effect.succeed(providers), + reloadSecretsAndRefresh: () => Effect.succeed(providers), refreshAfterUpdate: () => Effect.succeed(providers), refreshWorkspaceSnapshot: () => Effect.succeed(providers), getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) => diff --git a/apps/server/src/secrets/SecretResolver.ts b/apps/server/src/secrets/SecretResolver.ts new file mode 100644 index 0000000000000..076e4a0780793 --- /dev/null +++ b/apps/server/src/secrets/SecretResolver.ts @@ -0,0 +1,20 @@ +import * as SecretResolverCore from "@t3tools/secret-provider-core/server/SecretResolver"; +import type { ServerSettings } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import { BUILT_IN_SECRET_PROVIDER_DRIVER_LIST } from "./secretProviderDefinitions.ts"; +import * as Settings from "../serverSettings.ts"; + +export const layer = Layer.unwrap( + Effect.gen(function* () { + const serverSettings = yield* Settings.ServerSettingsService; + return SecretResolverCore.layer({ + drivers: BUILT_IN_SECRET_PROVIDER_DRIVER_LIST, + secretProviders: serverSettings.getSettings.pipe( + Effect.map((settings) => settings.secretProviders), + Effect.orElseSucceed((): ServerSettings["secretProviders"] => ({})), + ), + }); + }), +); diff --git a/apps/server/src/secrets/secretProviderDefinitions.test.ts b/apps/server/src/secrets/secretProviderDefinitions.test.ts new file mode 100644 index 0000000000000..b958a480693e1 --- /dev/null +++ b/apps/server/src/secrets/secretProviderDefinitions.test.ts @@ -0,0 +1,12 @@ +import { expect, it } from "@effect/vitest"; + +import { + BUILT_IN_SECRET_PROVIDER_DRIVER_LIST, + secretProviderDefinitions, +} from "./secretProviderDefinitions.ts"; + +it("runs a driver for every secret provider the server and clients read, in their order", () => { + expect(BUILT_IN_SECRET_PROVIDER_DRIVER_LIST.map((driver) => driver.definition)).toEqual( + secretProviderDefinitions.definitions, + ); +}); diff --git a/apps/server/src/secrets/secretProviderDefinitions.ts b/apps/server/src/secrets/secretProviderDefinitions.ts new file mode 100644 index 0000000000000..409df40bf16cf --- /dev/null +++ b/apps/server/src/secrets/secretProviderDefinitions.ts @@ -0,0 +1,7 @@ +import { builtInSecretProviderDefinitions } from "@t3tools/secret-provider-definitions/registry"; +import * as OnePasswordDriver from "@t3tools/secret-provider-onepassword/server/driver"; + +/** In the shared registry's order. */ +export const BUILT_IN_SECRET_PROVIDER_DRIVER_LIST = [OnePasswordDriver.driver] as const; + +export const secretProviderDefinitions = builtInSecretProviderDefinitions; diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index 8b7d81859b70d..0ae14fae5da7a 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -7,7 +7,9 @@ import { ProviderDriverKind, ProviderInstanceId, resolveProviderInstanceEnabled, + SecretProviderId, ServerSettings, + ServerSettingsPatch, UsageLimitSourceId, } from "@t3tools/contracts"; import { createModelSelection } from "@t3tools/shared/model"; @@ -33,6 +35,7 @@ import { resolveProviderInstanceTerminalEnvironment } from "./terminal/Manager.t const decodeServerSettings = Schema.decodeUnknownEffect(ServerSettings); const decodeServerSettingsJson = Schema.decodeUnknownEffect(Schema.fromJsonString(ServerSettings)); +const decodeServerSettingsPatch = Schema.decodeUnknownEffect(ServerSettingsPatch); const layerServerSettings = () => ServerSettingsModule.layer.pipe( @@ -278,6 +281,25 @@ it.layer(NodeServices.layer)("server settings", (it) => { }), ); + it.effect("stores no secret provider of an unloaded kind or with a config its kind rejects", () => + Effect.gen(function* () { + const service = yield* ServerSettingsModule.ServerSettingsService; + const write = (entry: unknown) => + decodeServerSettingsPatch({ secretProviders: { personal: entry } }).pipe( + Effect.flatMap(service.updateSettings), + Effect.flip, + ); + for (const entry of [ + { kind: "one_password", label: "Personal", config: { account: "--help" } }, + { kind: "one_password", label: "Personal" }, + { kind: "openbao", label: "Vault", config: { address: "https://x" } }, + ]) { + assert.deepInclude(yield* write(entry), { operation: "write-secret-provider" }); + } + assert.deepStrictEqual((yield* service.getSettings).secretProviders, {}); + }).pipe(Effect.provide(layerServerSettings())), + ); + it.effect("saves through a symlinked settings file without replacing the link", () => Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; @@ -1366,6 +1388,27 @@ it.layer(NodeServices.layer)("server settings", (it) => { for (const name of secretNames) { assert.isTrue(Option.isSome(yield* store.get(name)), name); } + const secret = { + provider: SecretProviderId.make("personal"), + reference: "op://Private/Antigravity/token", + }; + const referenced = yield* service.updateProviderInstance({ + operation: "upsert", + instanceId, + instance: { + ...client.providerInstances[instanceId]!, + environment: [ + { name: "API_TOKEN", value: secret, sensitive: true, valueRedacted: true }, + ], + }, + }); + assert.isTrue(Option.isNone(yield* store.get(secretNames[1]!))); + assert.deepEqual( + ServerSettingsModule.redactServerSettingsForClient(referenced).providerInstances[ + instanceId + ]?.environment, + [{ name: "API_TOKEN", value: secret, sensitive: true }], + ); yield* service.updateSettings({ providerInstances: {}, sourceControlHosts: { diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index 48839bb8535d9..67a1c3c3414f3 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -8,7 +8,6 @@ import { type ProviderInstanceConfig, type ProviderInstanceMutation, defaultInstanceIdForDriver, - isKnownSecretProviderKind, isProviderDriverKind, ProviderDriverKind, ProviderInstanceId, @@ -53,6 +52,7 @@ import { isModelSelectionProviderEnabled, } from "@t3tools/shared/serverSettings"; import * as ServerSecretStore from "./auth/ServerSecretStore.ts"; +import { secretProviderDefinitions } from "./secrets/secretProviderDefinitions.ts"; import { readSecretFieldValues, sourceControlHostSecretName, @@ -144,7 +144,7 @@ function withoutUnknownSecretProviderConfigs( ): ServerSettings["secretProviders"] { return Object.fromEntries( Object.entries(settings.secretProviders).map(([id, entry]) => { - if (isKnownSecretProviderKind(entry.kind)) return [id, entry]; + if (secretProviderConfigGuards.has(entry.kind)) return [id, entry]; const { config: _config, ...envelope } = entry; return [id, envelope]; }), @@ -164,6 +164,40 @@ export function applyProviderInstanceMutation( return { ...settings, providerInstances }; } +const secretProviderConfigGuards = new Map( + secretProviderDefinitions.definitions.map((definition) => [ + definition.kind as string, + Schema.is(definition.configSchema), + ]), +); + +// Rejects a kind this server has not loaded rather than storing a config it cannot check. +function ensureSecretProviderWritesAllowed( + patch: ServerSettingsPatch, + settingsPath: string, +): Effect.Effect { + for (const [id, entry] of Object.entries(patch.secretProviders ?? {})) { + if (entry === null) continue; + const isConfig = secretProviderConfigGuards.get(entry.kind); + const problem = + isConfig === undefined + ? `Unsupported secret provider kind: ${entry.kind}.` + : isConfig(entry.config) + ? undefined + : `Invalid ${entry.kind} config for secret provider ${id}.`; + if (problem !== undefined) { + return Effect.fail( + new ServerSettingsError({ + settingsPath, + operation: "write-secret-provider", + cause: new Error(problem), + }), + ); + } + } + return Effect.void; +} + function ensureProviderInstanceMutationAllowed( settings: ServerSettings, mutation: ProviderInstanceMutation, @@ -1185,11 +1219,14 @@ const make = Effect.gen(function* () { getSettings: getMaterializedSettings, updateSettings: (patch) => updateAndPersistSettings((current) => - Effect.succeed(applyServerSettingsPatch(current, patch)), + ensureSecretProviderWritesAllowed(patch, settingsPath).pipe( + Effect.as(applyServerSettingsPatch(current, patch)), + ), ), updateProviderInstance: (mutation, patch = {}) => updateAndPersistSettings((current) => Effect.gen(function* () { + yield* ensureSecretProviderWritesAllowed(patch, settingsPath); yield* ensureProviderInstanceMutationAllowed(current, mutation, settingsPath); const patched = applyServerSettingsPatch(current, patch); return applyProviderInstanceMutation(patched, mutation); diff --git a/apps/server/src/settingsSecrets.ts b/apps/server/src/settingsSecrets.ts index dff6b96f52a1b..3697c877edc22 100644 --- a/apps/server/src/settingsSecrets.ts +++ b/apps/server/src/settingsSecrets.ts @@ -99,16 +99,19 @@ export function mapSettingsSecrets( ...(instance.environment ? { environment: instance.environment.map((variable) => { + const { valueRedacted: _omit, ...rest } = variable; + // A secret reference is not itself secret; storage sees the value cleared. + const reference = typeof variable.value === "string" ? undefined : variable.value; const result = map({ secretName: `provider-env-${encode(instanceId)}-${encode(variable.name)}`, kind: "environment", - value: variable.value, - redacted: variable.valueRedacted === true, + value: typeof variable.value === "string" ? variable.value : "", + redacted: reference === undefined && variable.valueRedacted === true, sensitive: variable.sensitive, providerInstanceId: instanceId, environmentVariable: variable.name, }); - const { valueRedacted: _omit, ...rest } = variable; + if (reference !== undefined) return { ...rest, value: reference }; return { ...rest, value: result.value, diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 622279d16a409..32737aa771df6 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -1793,6 +1793,7 @@ export const layerWsRpc = ( threadFind: true, threadFindProgressive: true, secretProviderSettings: true, + secretReferences: true, ...Option.match(scratchWorkspaceRoot, { onNone: () => ({}), onSome: (root) => ({ scratchWorkspaceRoot: root }), @@ -2314,9 +2315,11 @@ export const layerWsRpc = ( cwd: input.cwd, fresh: input.fresh === true, }) - : input.instanceId !== undefined - ? providerRegistry.refreshInstance(input.instanceId) - : providerRegistry.refresh(); + : input.reloadSecrets === true + ? providerRegistry.reloadSecretsAndRefresh(input.instanceId) + : input.instanceId !== undefined + ? providerRegistry.refreshInstance(input.instanceId) + : providerRegistry.refresh(); if (input.refreshModels) { const instances = yield* providerInstances.listInstances; for (const instance of instances) { diff --git a/apps/web/package.json b/apps/web/package.json index 2ee8fe51a06a3..630020758e8c0 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -34,6 +34,8 @@ "@t3tools/client-runtime": "workspace:*", "@t3tools/contracts": "workspace:*", "@t3tools/provider-core": "workspace:*", + "@t3tools/secret-provider-definitions": "workspace:*", + "@t3tools/secret-provider-onepassword": "workspace:*", "@t3tools/shared": "workspace:*", "@tanstack/react-pacer": "^0.19.4", "@tanstack/react-router": "^1.160.2", diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx index 6e245af143dd8..3097cb70a9fbf 100644 --- a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx +++ b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx @@ -55,6 +55,7 @@ import { resolveOfficialAcpRegistryIconUrl } from "./AcpRegistryIcon"; import { AddManagedCodexAccountDialog } from "./CodexSetupSection"; import { MultipleAccountsNote } from "./MultipleAccountsNote"; import { ProviderEnvironmentSection } from "./ProviderInstanceCard"; +import { useSecretSources } from "./SecretSourceInput"; /** Limit the slug to 48 chars so the composed ProviderInstanceId fits its 64-char cap. */ function slugifyLabel(value: string): string { @@ -160,6 +161,7 @@ export function AddProviderInstanceDialog({ onCreated, }: AddProviderInstanceDialogProps) { const settings = useEnvironmentSettings(environmentId); + const secretSources = useSecretSources(environmentId); const persistProviderInstance = usePersistEnvironmentProviderInstanceMutation(environmentId); const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope); @@ -536,6 +538,7 @@ export function AddProviderInstanceDialog({ ) : null} diff --git a/apps/web/src/components/settings/ProviderInstanceCard.test.ts b/apps/web/src/components/settings/ProviderInstanceCard.test.ts index c681f78765178..143d64d5c1bdf 100644 --- a/apps/web/src/components/settings/ProviderInstanceCard.test.ts +++ b/apps/web/src/components/settings/ProviderInstanceCard.test.ts @@ -1,8 +1,9 @@ import { describe, expect, it } from "vite-plus/test"; -import type { ServerProviderModel } from "@t3tools/contracts"; +import { SecretProviderId, type ServerProviderModel } from "@t3tools/contracts"; import { deriveProviderModelsForDisplay, + nextProviderEnvironmentWithFieldSecret, nextProviderEnvironmentWithFieldValue, } from "./ProviderInstanceCard"; @@ -75,6 +76,20 @@ describe("provider environment helpers", () => { ).toEqual([{ name: "CURSOR_API_KEY", value: "new-key", sensitive: true }]); }); + it("points a stored provider secret at a secret provider and drops the stored value", () => { + const secret = { + provider: SecretProviderId.make("personal"), + reference: "op://Private/Cursor/credential", + }; + const stored = [{ name: "CURSOR_API_KEY", value: "", sensitive: true, valueRedacted: true }]; + const referenced = nextProviderEnvironmentWithFieldSecret(stored, cursorApiKeyField, secret); + + expect(referenced).toEqual([{ name: "CURSOR_API_KEY", value: secret, sensitive: true }]); + expect( + nextProviderEnvironmentWithFieldSecret(referenced, cursorApiKeyField, undefined), + ).toEqual([]); + }); + it("applies the secure field default when replacing an existing non-sensitive value", () => { expect( nextProviderEnvironmentWithFieldValue( diff --git a/apps/web/src/components/settings/ProviderInstanceCard.tsx b/apps/web/src/components/settings/ProviderInstanceCard.tsx index 88361eac68bc8..d8b5c71fc0f98 100644 --- a/apps/web/src/components/settings/ProviderInstanceCard.tsx +++ b/apps/web/src/components/settings/ProviderInstanceCard.tsx @@ -15,7 +15,7 @@ import { import { Lock as LockGlyph, LockOpen } from "lucide"; import * as Arr from "effect/Array"; import * as Result from "effect/Result"; -import { useState, type ReactElement, type ReactNode } from "react"; +import { Fragment, useState, type ReactElement, type ReactNode } from "react"; import { isProviderDriverKind, resolveProviderInstanceEnabled, @@ -26,6 +26,7 @@ import { type EnvironmentId, type ProjectId, type ProviderDriverKind, + type SecretReference, type ServerProvider, type ServerProviderModel, } from "@t3tools/contracts"; @@ -43,7 +44,7 @@ import { Badge } from "../ui/badge"; import { Button } from "../ui/button"; import { MorphIcon } from "~/components/MorphIcon"; import { DraftInput } from "../ui/draft-input"; -import { SecretInput } from "./SecretInput"; +import { SecretSourceInput, type SecretSource } from "./SecretSourceInput"; import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; import { Switch } from "../ui/switch"; import { stackedThreadToast, toastManager } from "../ui/toast"; @@ -98,7 +99,7 @@ const nextEnvironmentVariableDraftId = () => `provider-env-${environmentVariable type EnvironmentDraftRow = { readonly id: string; readonly name: string; - readonly value: string; + readonly value: ProviderInstanceEnvironmentVariable["value"]; readonly sensitive: boolean; readonly valueRedacted?: boolean; }; @@ -119,6 +120,14 @@ function makeEnvironmentDraftRow( const toEnvironmentDraftRows = (environment: ReadonlyArray) => environment.map(makeEnvironmentDraftRow); +function environmentValuesEqual( + left: ProviderInstanceEnvironmentVariable["value"], + right: ProviderInstanceEnvironmentVariable["value"], +): boolean { + if (typeof left === "string" || typeof right === "string") return left === right; + return left.provider === right.provider && left.reference === right.reference; +} + function providerEnvironmentsEqual( left: ReadonlyArray, right: ReadonlyArray, @@ -130,7 +139,7 @@ function providerEnvironmentsEqual( return ( other !== undefined && variable.name === other.name && - variable.value === other.value && + environmentValuesEqual(variable.value, other.value) && variable.sensitive === other.sensitive && variable.valueRedacted === other.valueRedacted ); @@ -247,12 +256,28 @@ export function nextProviderEnvironmentWithFieldValue( return next; } +export function nextProviderEnvironmentWithFieldSecret( + environment: ReadonlyArray | undefined, + field: ProviderEnvironmentField, + secret: SecretReference | undefined, +): ReadonlyArray { + const others = providerEnvironmentWithoutNames(environment, new Set([field.name])); + return secret === undefined + ? others + : [...others, { name: field.name, value: secret, sensitive: true }]; +} + function ProviderEnvironmentFieldRow(props: { readonly field: ProviderEnvironmentField; readonly variable: ProviderInstanceEnvironmentVariable | undefined; readonly idPrefix: string; readonly onCommit: (field: ProviderEnvironmentField, value: string) => void; + readonly onSecretChange: ( + field: ProviderEnvironmentField, + secret: SecretReference | undefined, + ) => void; readonly onRemove: (field: ProviderEnvironmentField) => void; + readonly secretSources: ReadonlyArray; }) { const inputId = `${props.idPrefix}-environment-${props.field.name}`; const value = props.variable?.valueRedacted ? "" : (props.variable?.value ?? ""); @@ -269,13 +294,13 @@ function ProviderEnvironmentFieldRow(props: { size="sm" className="min-w-0 flex-1" autoComplete="off" - value={value} + value={typeof value === "string" ? value : ""} onCommit={(next) => props.onCommit(props.field, next)} placeholder={props.field.placeholder} spellCheck={false} /> ) : ( - props.onSecretChange(props.field, secret)} /> )} {props.variable ? ( @@ -306,6 +334,7 @@ function ProviderEnvironmentFieldRow(props: { export function ProviderEnvironmentSection(props: { readonly environment: ReadonlyArray; readonly onChange: (environment: ReadonlyArray) => void; + readonly secretSources?: ReadonlyArray; }) { const [storedDraft, setDraft] = useState(() => seedRowsDraft(props.environment, toEnvironmentDraftRows), @@ -328,7 +357,7 @@ export function ProviderEnvironmentSection(props: { if (!ENVIRONMENT_VARIABLE_NAME_PATTERN.test(name)) { if ( name.length > 0 || - row.value.length > 0 || + row.value !== "" || row.sensitive !== true || row.valueRedacted !== undefined ) { @@ -357,6 +386,16 @@ export function ProviderEnvironmentSection(props: { publishRows(nextRows); }; + const setVariableSecret = (id: string, secret: SecretReference | undefined) => { + const nextRows = rows.map((row) => { + if (row.id !== id) return row; + const { valueRedacted: _valueRedacted, ...rest } = row; + return { ...rest, value: secret ?? "" }; + }); + setRows(nextRows); + publishRows(nextRows); + }; + const removeVariable = (id: string) => { const nextRows = rows.filter((row) => row.id !== id); setRows(nextRows); @@ -387,76 +426,20 @@ export function ProviderEnvironmentSection(props: { > {rows.length > 0 ? (
      - {rows.map((variable, index) => ( -
      + {rows.map((variable, index) => { + const nameInput = ( updateVariable(variable.id, { name: name.trim() })} placeholder="VARIABLE_NAME" spellCheck={false} aria-label={`Environment variable name ${index + 1}`} /> - - = - - {variable.sensitive ? ( - updateVariable(variable.id, { value })} - placeholder="value" - configured={variable.valueRedacted === true} - spellCheck={false} - aria-label={`Environment variable value ${index + 1}`} - /> - ) : ( - updateVariable(variable.id, { value })} - autoComplete="off" - placeholder="value" - spellCheck={false} - aria-label={`Environment variable value ${index + 1}`} - /> - )} - - { - const sensitive = !variable.sensitive; - updateVariable(variable.id, { - sensitive, - ...(sensitive && variable.valueRedacted === undefined - ? {} - : { valueRedacted: sensitive ? variable.valueRedacted : false }), - }); - }} - aria-pressed={variable.sensitive} - aria-label={`Mark environment variable ${variable.name || index + 1} as sensitive`} - > - - - } - /> - - {variable.sensitive ? "Sensitive, stored separately" : "Plain text"} - - + ); + const removeButton = ( -
      - ))} + ); + const sensitiveToggle = + typeof variable.value === "string" ? ( + + { + const sensitive = !variable.sensitive; + updateVariable(variable.id, { + sensitive, + ...(sensitive && variable.valueRedacted === undefined + ? {} + : { valueRedacted: sensitive ? variable.valueRedacted : false }), + }); + }} + aria-pressed={variable.sensitive} + aria-label={`Mark environment variable ${variable.name || index + 1} as sensitive`} + > + + + } + /> + + {variable.sensitive ? "Sensitive, stored separately" : "Plain text"} + + + ) : null; + const layout = (source: ReactNode, value: ReactNode) => ( +
      +
      + {nameInput} + {source === null ? null :
      {source}
      } + {removeButton} +
      +
      + {value} + {sensitiveToggle} +
      +
      + ); + return ( + + {variable.sensitive ? ( + updateVariable(variable.id, { value })} + placeholder="value" + configured={variable.valueRedacted === true} + spellCheck={false} + aria-label={`Environment variable value ${index + 1}`} + sources={props.secretSources ?? []} + onSecretChange={(secret) => setVariableSecret(variable.id, secret)} + > + {(parts) => layout(parts.source, parts.value)} + + ) : ( + layout( + null, + updateVariable(variable.id, { value })} + autoComplete="off" + placeholder="value" + spellCheck={false} + aria-label={`Environment variable value ${index + 1}`} + />, + ) + )} + + ); + })}

      Sensitive values are stored separately and never returned to the app.

      @@ -584,6 +653,7 @@ interface ProviderInstanceCardProps { readonly isUpdating?: boolean | undefined; readonly onAcceptUrlAuth?: ((action: AcpRegistryUrlAuthAction) => void) | undefined; readonly environmentId?: EnvironmentId | undefined; + readonly secretSources?: ReadonlyArray; readonly projectOverride?: ProjectOverrideControl | undefined; readonly acpProjects?: | ReadonlyArray<{ @@ -595,6 +665,7 @@ interface ProviderInstanceCardProps { } const EMPTY_ACP_PROJECTS: NonNullable = []; +const NO_SECRET_SOURCES: ReadonlyArray = []; const NO_CUSTOM_MODELS: ReadonlyArray = []; /** Unknown drivers stay read-only to preserve fork config. projectOverride switches affect only the @@ -627,6 +698,7 @@ export function ProviderInstanceCard({ onAcceptUrlAuth, environmentId, acpProjects = EMPTY_ACP_PROJECTS, + secretSources = NO_SECRET_SOURCES, projectOverride, }: ProviderInstanceCardProps) { const enabled = projectOverride?.effectiveEnabled ?? resolveProviderInstanceEnabled(instance); @@ -781,6 +853,12 @@ export function ProviderInstanceCard({ const updateEnvironmentField = (field: ProviderEnvironmentField, value: string) => { updateEnvironment(nextProviderEnvironmentWithFieldValue(instance.environment, field, value)); }; + const updateEnvironmentFieldSecret = ( + field: ProviderEnvironmentField, + secret: SecretReference | undefined, + ) => { + updateEnvironment(nextProviderEnvironmentWithFieldSecret(instance.environment, field, secret)); + }; const removeEnvironmentField = (field: ProviderEnvironmentField) => { updateEnvironment(providerEnvironmentWithoutNames(instance.environment, new Set([field.name]))); }; @@ -1182,7 +1260,9 @@ export function ProviderInstanceCard({ variable={readProviderEnvironmentVariable(instance.environment, field.name)} idPrefix={`provider-instance-${instanceId}`} onCommit={updateEnvironmentField} + onSecretChange={updateEnvironmentFieldSecret} onRemove={removeEnvironmentField} + secretSources={secretSources} /> ))}
      @@ -1225,6 +1305,7 @@ export function ProviderInstanceCard({ {environmentId !== undefined && liveProvider?.driver === "acpRegistry" ? ( diff --git a/apps/web/src/components/settings/ProviderSettingsPanel.tsx b/apps/web/src/components/settings/ProviderSettingsPanel.tsx index 9dae72e98ff50..b5fb648ff97c2 100644 --- a/apps/web/src/components/settings/ProviderSettingsPanel.tsx +++ b/apps/web/src/components/settings/ProviderSettingsPanel.tsx @@ -98,6 +98,7 @@ import { stackedThreadToast, toastManager } from "../ui/toast"; import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog"; import { ExpandableText } from "./ExpandableText"; import { ProviderInstanceCard } from "./ProviderInstanceCard"; +import { useSecretSources } from "./SecretSourceInput"; import { UsageProviderSettings } from "./UsageProviderSettings"; import { ProviderSetupSection, readAntigravityAuthMethod } from "./ProviderSetupSection"; import { ProviderAuthenticationSection } from "./ProviderAuthenticationSection"; @@ -635,7 +636,7 @@ export function EnvironmentProviderSettings({ void (async () => { const result = await refreshServerProviders({ environmentId, - input: { refreshModels: true }, + input: { refreshModels: true, reloadSecrets: true }, }); refreshingRef.current = false; setIsRefreshingProviders(false); @@ -1247,6 +1248,7 @@ function ProviderInstanceRow({ readonly actions: ProviderInstanceRowActions; }) { const allProjects = useProjects(); + const secretSources = useSecretSources(environmentId); const acpProjects = mode === "editor" && liveProvider?.driver === "acpRegistry" ? allProjects.filter((project) => project.environmentId === environmentId) @@ -1285,6 +1287,7 @@ function ProviderInstanceRow({ return ( screen.getByRole("textbox", { name: "API key reference" }); + +async function commitReference(screen: Screen, value: string) { + await userEvent.clear(reference(screen)); + await userEvent.type(reference(screen), value); + await userEvent.keyboard("{Enter}"); +} + +describe("SecretSourceInput", () => { + it("moves a reference to another provider only once one is committed for it", async () => { + const onSecretChange = vi.fn(); + await using screen = await render( + {}} + onSecretChange={onSecretChange} + />, + ); + + await userEvent.click(screen.getByRole("combobox", { name: "API key source" })); + await userEvent.click(screen.getByRole("option", { name: "Work" })); + expect(onSecretChange).not.toHaveBeenCalled(); + await expect.element(reference(screen)).toHaveValue(""); + + await commitReference(screen, "op://Shared/OpenAI/credential"); + expect(onSecretChange).toHaveBeenCalledExactlyOnceWith({ + provider: work, + reference: "op://Shared/OpenAI/credential", + }); + }); + + it("removes the reference when its field is cleared", async () => { + const onSecretChange = vi.fn(); + await using screen = await render( + {}} + onSecretChange={onSecretChange} + />, + ); + + await userEvent.clear(reference(screen)); + await userEvent.keyboard("{Enter}"); + expect(onSecretChange).toHaveBeenCalledExactlyOnceWith(undefined); + }); + + it("rejects a reference 1Password cannot read", async () => { + const onSecretChange = vi.fn(); + await using screen = await render( + {}} + onSecretChange={onSecretChange} + />, + ); + + await commitReference(screen, "Private/OpenAI/credential"); + expect(onSecretChange).not.toHaveBeenCalled(); + await expect.element(reference(screen)).toHaveAttribute("aria-invalid", "true"); + await expect.element(reference(screen)).toHaveValue("Private/OpenAI/credential"); + }); +}); diff --git a/apps/web/src/components/settings/SecretSourceInput.tsx b/apps/web/src/components/settings/SecretSourceInput.tsx new file mode 100644 index 0000000000000..092e59b9dcd0f --- /dev/null +++ b/apps/web/src/components/settings/SecretSourceInput.tsx @@ -0,0 +1,185 @@ +import { + SecretReference, + type EnvironmentId, + type SecretProviderConfig, + type SecretProviderId, + type SecretProviderKind, +} from "@t3tools/contracts"; +import { builtInSecretProviderDefinitions } from "@t3tools/secret-provider-definitions/registry"; +import { useAtomValue } from "@effect/atom-react"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import { KeyRoundIcon, TypeIcon } from "lucide-react"; +import { useState, type ComponentProps, type ComponentType, type ReactNode } from "react"; + +import { isSecretsFeatureEnabled } from "../../env"; +import { useEnvironmentSettings } from "../../hooks/useSettings"; +import { OnePasswordIcon } from "../Icons"; +import { serverEnvironment } from "../../state/server"; +import { DraftInput } from "../ui/draft-input"; +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; +import { SecretInput } from "./SecretInput"; +import { classifySecretProvider } from "./SecretProviderDialog.logic"; + +export interface SecretSource { + readonly id: SecretProviderId; + readonly kind: SecretProviderKind; + readonly label: string; +} + +const NO_SECRET_SOURCES: ReadonlyArray = []; +const STORED_VALUE = "__stored__"; +const decodeSecretReference = Schema.decodeUnknownOption(SecretReference); + +/** Secret providers a setting can point at; empty when the environment cannot read references. */ +export function useSecretSources(environmentId: EnvironmentId): ReadonlyArray { + const providers = useEnvironmentSettings(environmentId, (settings) => settings.secretProviders); + const supported = useAtomValue( + serverEnvironment.configValueAtom(environmentId), + (config) => config?.secretReferences === true, + ); + if (!isSecretsFeatureEnabled || !supported) return NO_SECRET_SOURCES; + return (Object.entries(providers) as Array<[SecretProviderId, SecretProviderConfig]>) + .filter(([, config]) => classifySecretProvider(config).kind !== "unsupported") + .map(([id, config]) => ({ id, kind: config.kind, label: config.label })); +} + +function SourceLabel(props: { + readonly icon: ComponentType<{ readonly className?: string }>; + readonly label: string; +}) { + return ( + + + {props.label} + + ); +} + +type SecretSourceInputProps = Omit, "value" | "children"> & { + readonly value: string | SecretReference; + readonly sources: ReadonlyArray; + readonly onSecretChange: (secret: SecretReference | undefined) => void; + /** Places the parts in the caller's layout; `source` is null when there is nothing to pick. */ + readonly children?: (parts: { + readonly source: ReactNode; + readonly value: ReactNode; + }) => ReactNode; +}; + +/** A secret entered here, or read from a secret provider when one is configured. */ +export function SecretSourceInput({ + value, + sources, + onSecretChange, + children, + ...rest +}: SecretSourceInputProps) { + // A provider picked here applies once a reference for it is committed. + const [pendingProvider, setPendingProvider] = useState(null); + const [rejectedReference, setRejectedReference] = useState(null); + const secret = typeof value === "string" ? undefined : value; + const input = { ...rest, value: typeof value === "string" ? value : "" }; + const provider = pendingProvider ?? secret?.provider ?? null; + const reference = secret !== undefined && secret.provider === provider ? secret.reference : ""; + const providerSource = sources.find((source) => source.id === provider); + const definition = providerSource && builtInSecretProviderDefinitions.find(providerSource.kind); + const label = input["aria-label"] ?? "Secret"; + const providerLabel = (id: SecretProviderId) => + sources.find((source) => source.id === id)?.label ?? id; + const providerIcon = (id: SecretProviderId) => + sources.some((source) => source.id === id) ? OnePasswordIcon : KeyRoundIcon; + + const source = + sources.length === 0 && provider === null ? null : ( + + ); + + const valueField = + provider === null ? ( + + ) : ( +
      + { + if (next.trim().length === 0) { + setRejectedReference(null); + if (pendingProvider === null && secret !== undefined) onSecretChange(undefined); + return; + } + const decoded = decodeSecretReference({ provider, reference: next }); + if ( + Option.isNone(decoded) || + definition?.isReference(decoded.value.reference) === false + ) { + setRejectedReference(next); + return; + } + setRejectedReference(null); + setPendingProvider(null); + onSecretChange(decoded.value); + }} + autoComplete="off" + placeholder={definition?.referencePlaceholder} + spellCheck={false} + aria-label={`${label} reference`} + aria-invalid={rejectedReference !== null} + /> + {rejectedReference !== null ? ( +

      + {definition?.invalidReferenceMessage ?? "Enter a valid secret reference."} +

      + ) : null} +
      + ); + + if (children !== undefined) return children({ source, value: valueField }); + if (source === null) return valueField; + return ( +
      +
      {source}
      + {valueField} +
      + ); +} diff --git a/package.json b/package.json index 1c4ffa679029c..c78b879301b9e 100644 --- a/package.json +++ b/package.json @@ -30,7 +30,7 @@ "report:renders": "node scripts/render-metrics.ts", "lint": "vp lint --report-unused-disable-directives", "knip": "knip --preprocessor ./scripts/knip-schemas.ts", - "knip:check": "knip --include files,dependencies --no-config-hints && knip --workspace apps/server --workspace apps/desktop --workspace apps/web --workspace packages/client-runtime --workspace packages/contracts --workspace packages/effect-acp --workspace packages/effect-codex-app-server --workspace packages/shared --workspace packages/ssh --workspace packages/tailscale --workspace packages/provider-core --workspace packages/provider-acp --workspace packages/provider-acp-registry --workspace packages/provider-testing --workspace packages/provider-pi --workspace packages/provider-muse --workspace packages/provider-opencode --workspace packages/provider-cursor --workspace packages/provider-fx --workspace packages/provider-grok --workspace packages/source-control-core --workspace packages/source-control-definitions --workspace packages/source-control-azure-devops --workspace packages/source-control-bitbucket --workspace packages/source-control-forgejo --workspace packages/source-control-gitcafe --workspace packages/source-control-github --workspace packages/source-control-gitlab --workspace packages/source-control-testing --exports --preprocessor ./scripts/knip-schemas.ts --no-config-hints", + "knip:check": "knip --include files,dependencies --no-config-hints && knip --workspace apps/server --workspace apps/desktop --workspace apps/web --workspace packages/client-runtime --workspace packages/contracts --workspace packages/effect-acp --workspace packages/effect-codex-app-server --workspace packages/shared --workspace packages/ssh --workspace packages/tailscale --workspace packages/provider-core --workspace packages/provider-acp --workspace packages/provider-acp-registry --workspace packages/provider-testing --workspace packages/provider-pi --workspace packages/provider-muse --workspace packages/provider-opencode --workspace packages/provider-cursor --workspace packages/provider-fx --workspace packages/provider-grok --workspace packages/secret-provider-core --workspace packages/secret-provider-definitions --workspace packages/secret-provider-onepassword --workspace packages/source-control-core --workspace packages/source-control-definitions --workspace packages/source-control-azure-devops --workspace packages/source-control-bitbucket --workspace packages/source-control-forgejo --workspace packages/source-control-gitcafe --workspace packages/source-control-github --workspace packages/source-control-gitlab --workspace packages/source-control-testing --exports --preprocessor ./scripts/knip-schemas.ts --no-config-hints", "knip:production": "knip --production --preprocessor ./scripts/knip-schemas.ts", "lint:mobile": "node scripts/mobile-native-static-check.ts", "mobile:install": "node scripts/mobile-native-client.ts ensure", diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index e61597e52ecdb..30bf25598d55d 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -67,4 +67,5 @@ export * from "./resourceTelemetry.ts"; export * from "./rpc.ts"; export * from "./worktreeSetup.ts"; export * from "./secretRequest.ts"; +export * from "./secretReference.ts"; export * from "./clientRpcPermissions.ts"; diff --git a/packages/contracts/src/providerInstance.ts b/packages/contracts/src/providerInstance.ts index 9cc0a3f52375d..61fee930c3193 100644 --- a/packages/contracts/src/providerInstance.ts +++ b/packages/contracts/src/providerInstance.ts @@ -1,6 +1,8 @@ import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; +import * as SchemaTransformation from "effect/SchemaTransformation"; import { TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { SecretReference } from "./secretReference.ts"; const PROVIDER_SLUG_MAX_CHARS = 64; const PROVIDER_SLUG_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]*$/; @@ -27,17 +29,48 @@ export const ProviderInstanceEnvironmentVariableName = TrimmedNonEmptyString.che export type ProviderInstanceEnvironmentVariableName = typeof ProviderInstanceEnvironmentVariableName.Type; -export const ProviderInstanceEnvironmentVariable = Schema.Struct({ +const ProviderInstanceEnvironmentVariableValue = Schema.Struct({ + name: ProviderInstanceEnvironmentVariableName, + value: Schema.Union([Schema.String, SecretReference]), + sensitive: Schema.Boolean, + valueRedacted: Schema.optionalKey(Schema.Boolean), +}); + +// A reference is encoded beside an empty value so older servers and clients still decode it. +const StoredProviderInstanceEnvironmentVariable = Schema.Struct({ name: ProviderInstanceEnvironmentVariableName, value: Schema.String.pipe(Schema.withDecodingDefault(Effect.succeed(""))), sensitive: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), valueRedacted: Schema.optionalKey(Schema.Boolean), + secret: Schema.optionalKey(SecretReference), }); + +export const ProviderInstanceEnvironmentVariable = StoredProviderInstanceEnvironmentVariable.pipe( + Schema.decodeTo( + Schema.toType(ProviderInstanceEnvironmentVariableValue), + SchemaTransformation.transform< + typeof ProviderInstanceEnvironmentVariableValue.Type, + typeof StoredProviderInstanceEnvironmentVariable.Type + >({ + decode: ({ secret, ...variable }) => + secret === undefined ? variable : { ...variable, value: secret }, + encode: ({ value, ...variable }) => + typeof value === "string" + ? { ...variable, value } + : { ...variable, value: "", secret: value }, + }), + ), +); export type ProviderInstanceEnvironmentVariable = typeof ProviderInstanceEnvironmentVariable.Type; export const ProviderInstanceEnvironment = Schema.Array(ProviderInstanceEnvironmentVariable); export type ProviderInstanceEnvironment = typeof ProviderInstanceEnvironment.Type; +/** What drivers receive: every secret reference has been read into a plain value. */ +export type ResolvedProviderInstanceEnvironment = ReadonlyArray< + Omit & { readonly value: string } +>; + /** Drivers decode their own config; unknown-driver envelopes round-trip verbatim across versions. */ export const ProviderInstanceConfig = Schema.Struct({ driver: ProviderDriverKind, diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 145fe5e06087c..445048eb2685d 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -634,6 +634,8 @@ export const WsServerRefreshProvidersRpc = Rpc.make(WS_METHODS.serverRefreshProv fresh: Schema.optional(Schema.Boolean), /** Bypass model caches; explicit rediscovery may open sessions, background refreshes must not. */ refreshModels: Schema.optional(Schema.Boolean), + /** Read secret references again; unlocking a vault can prompt on the host, so only explicit user refreshes ask. */ + reloadSecrets: Schema.optional(Schema.Boolean), /** * Reply without snapshots, or with only the requested instance's cwd snapshot. Snapshots then * reach the client only through these replies, so another client's scan shows on its next diff --git a/packages/contracts/src/secretReference.ts b/packages/contracts/src/secretReference.ts new file mode 100644 index 0000000000000..4e03f8a675688 --- /dev/null +++ b/packages/contracts/src/secretReference.ts @@ -0,0 +1,27 @@ +import * as Schema from "effect/Schema"; + +import { TrimmedNonEmptyString } from "./baseSchemas.ts"; + +// Separate module avoids an import cycle between settings and provider instance contracts. +// Final once shipped: older builds drop entries whose key fails here, and erase them on their next save. +// Unlike provider slugs it may start with a digit, so a provider named "1Password" fits. +export const SecretProviderSlug = TrimmedNonEmptyString.check( + Schema.isMaxLength(64), + Schema.isPattern(/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/), +); + +export const SecretProviderId = SecretProviderSlug.pipe(Schema.brand("SecretProviderId")); +export type SecretProviderId = typeof SecretProviderId.Type; + +// Provider-specific syntax is the secret provider driver's to check. +export const SecretReferencePath = TrimmedNonEmptyString.check( + Schema.isMaxLength(1024), + Schema.isPattern(/^[^\r\n]+$/), +); + +/** Points at a secret held by a configured secret provider; the secret itself is never stored. */ +export const SecretReference = Schema.Struct({ + provider: SecretProviderId, + reference: SecretReferencePath, +}); +export type SecretReference = typeof SecretReference.Type; diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index 9fd3813abf5fa..ab79a9dea60f5 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -640,6 +640,8 @@ export const ServerConfig = Schema.Struct({ threadFindProgressive: Schema.optionalKey(Schema.Boolean), /** Settings patches may carry `secretProviders`; older servers drop the key without an error. */ secretProviderSettings: Schema.optionalKey(Schema.Boolean), + /** Secret settings may point at a secret provider; older servers drop the reference. */ + secretReferences: Schema.optionalKey(Schema.Boolean), scratchWorkspaceRoot: Schema.optionalKey(TrimmedNonEmptyString), newProjectsRoot: Schema.optionalKey(TrimmedNonEmptyString), /** diff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.ts index 9d765ccee92c6..859644a54c72f 100644 --- a/packages/contracts/src/settings.test.ts +++ b/packages/contracts/src/settings.test.ts @@ -2,7 +2,11 @@ import { describe, expect, it } from "vite-plus/test"; import * as Schema from "effect/Schema"; import { type CommandId, ProjectId } from "./baseSchemas.ts"; -import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts"; +import { + ProviderDriverKind, + ProviderInstanceEnvironment, + ProviderInstanceId, +} from "./providerInstance.ts"; import { ClientSettingsSchema, ClientSettingsPatch, @@ -23,6 +27,14 @@ const decodeClientSettings = Schema.decodeUnknownSync(ClientSettingsSchema); const decodeClientSettingsPatch = Schema.decodeUnknownSync(ClientSettingsPatch); const encodeClientSettings = Schema.encodeSync(ClientSettingsSchema); const decodeServerSettings = Schema.decodeUnknownSync(ServerSettings); +const encodeProviderInstanceEnvironment = Schema.encodeSync(ProviderInstanceEnvironment); +const decodeProviderInstanceEnvironment = Schema.decodeSync(ProviderInstanceEnvironment); +// The environment variable shape builds released before secret references decode. +const decodeStringOnlyEnvironment = Schema.decodeUnknownSync( + Schema.Array( + Schema.Struct({ name: Schema.String, value: Schema.String, sensitive: Schema.Boolean }), + ), +); const decodeServerSettingsPatch = Schema.decodeUnknownSync(ServerSettingsPatch); const encodeServerSettings = Schema.encodeSync(ServerSettings); const encodeServerSettingsPatch = Schema.encodeSync(ServerSettingsPatch); @@ -154,14 +166,45 @@ describe("ServerSettings secret providers", () => { ).toThrow(); }); - it("rejects writes of an unknown kind or an account op could misread", () => { - const write = (entry: unknown) => () => - decodeServerSettingsPatch({ secretProviders: { personal: entry } }); - for (const account of ["", "my account", "--help"]) { - expect(write(onePassword(account))).toThrow(); + it("stores a provider environment secret reference in a layout older builds still decode", () => { + const providerInstances = (secret: unknown) => ({ + codex: { + driver: "codex", + environment: [ + { name: "OPENAI_API_KEY", sensitive: true, value: "", secret }, + { name: "BASE_URL", value: "https://example.test" }, + ], + }, + }); + const secret = { provider: "personal", reference: "op://Private/OpenAI/credential" }; + const environment = decodeServerSettings({ providerInstances: providerInstances(secret) }) + .providerInstances[ProviderInstanceId.make("codex")]?.environment; + expect(environment).toEqual([ + { name: "OPENAI_API_KEY", value: secret, sensitive: true }, + { name: "BASE_URL", value: "https://example.test", sensitive: false }, + ]); + + const encoded = encodeProviderInstanceEnvironment(environment ?? []); + expect(encoded).toEqual([ + { name: "OPENAI_API_KEY", value: "", sensitive: true, secret }, + { name: "BASE_URL", value: "https://example.test", sensitive: false }, + ]); + expect(decodeProviderInstanceEnvironment(encoded)).toEqual(environment); + expect(decodeStringOnlyEnvironment(encoded)).toEqual([ + { name: "OPENAI_API_KEY", value: "", sensitive: true }, + { name: "BASE_URL", value: "https://example.test", sensitive: false }, + ]); + + for (const invalid of [ + { provider: "My Vault", reference: "op://a/b/c" }, + { provider: "personal", reference: " " }, + { provider: "personal", reference: "op://Private/OpenAI\n/credential" }, + { provider: "personal", reference: "x".repeat(1025) }, + ]) { + expect(() => + decodeServerSettings({ providerInstances: providerInstances(invalid) }), + ).toThrow(); } - expect(write({ kind: "one_password", label: "Personal" })).toThrow(); - expect(write({ kind: "openbao", label: "Vault", config: { address: "https://x" } })).toThrow(); }); }); diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 179e58b7a0b56..643d27296f34b 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -20,6 +20,7 @@ import { TrimmedString, } from "./baseSchemas.ts"; import { UsageLimitSourceId } from "./usageLimitSourceId.ts"; +import { SecretProviderId, SecretProviderSlug } from "./secretReference.ts"; import { EnvironmentMachineKind, ThreadEnvMode, WorktreeSubmodules } from "./environment.ts"; import { KeybindingShortcut } from "./keybindings.ts"; import { @@ -859,42 +860,11 @@ export const UsageLimitSourceConfig = Schema.Struct({ }); export type UsageLimitSourceConfig = typeof UsageLimitSourceConfig.Type; -// Final once shipped: older builds drop entries whose key fails here, and erase them on their next save. -// Unlike provider slugs it may start with a digit, so a provider named "1Password" fits. -const SecretProviderSlug = TrimmedNonEmptyString.check( - Schema.isMaxLength(64), - Schema.isPattern(/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/), -); - -export const SecretProviderId = SecretProviderSlug.pipe(Schema.brand("SecretProviderId")); -export type SecretProviderId = typeof SecretProviderId.Type; - export const SecretProviderKind = SecretProviderSlug.pipe(Schema.brand("SecretProviderKind")); export type SecretProviderKind = typeof SecretProviderKind.Type; -const ONE_PASSWORD_ACCOUNT_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; - -/** - * Any value `op --account` accepts: shorthand, sign-in address, account ID, or user ID. - * It is passed to the CLI as an argument, so it can never start with `-`. - */ -export const OnePasswordAccount = Schema.String.check( - Schema.isMaxLength(253), - Schema.makeFilter((value: string) => - ONE_PASSWORD_ACCOUNT_PATTERN.test(value) - ? true - : "1Password account must be a shorthand, sign-in address, or ID with no spaces.", - ), -).pipe(Schema.brand("OnePasswordAccount")); -export type OnePasswordAccount = typeof OnePasswordAccount.Type; - export const SecretProviderLabel = TrimmedNonEmptyString.check(Schema.isMaxLength(64)); -export const OnePasswordSecretProviderConfig = Schema.Struct({ - account: OnePasswordAccount, -}); -export type OnePasswordSecretProviderConfig = typeof OnePasswordSecretProviderConfig.Type; - /** Kinds decode their own config; unknown-kind envelopes round-trip verbatim across versions. */ export const SecretProviderConfig = Schema.Struct({ kind: SecretProviderKind, @@ -903,31 +873,12 @@ export const SecretProviderConfig = Schema.Struct({ }); export type SecretProviderConfig = typeof SecretProviderConfig.Type; -/** Kinds this build can resolve. Their `config` holds no credentials, so clients may read it. */ -const SECRET_PROVIDER_KIND_CONFIG_GUARDS: Readonly boolean>> = { - one_password: Schema.is(OnePasswordSecretProviderConfig), -}; - -export function isKnownSecretProviderKind(kind: string): boolean { - return Object.hasOwn(SECRET_PROVIDER_KIND_CONFIG_GUARDS, kind); -} - -// Limits that may change later are enforced on writes only, never on the stored envelope. -// Writes must be a kind this build knows with a config it accepts, so an older server -// rejects a newer kind instead of storing what it cannot check. +// Limits that may change later are enforced on writes only, never on the stored envelope. The +// server also checks the kind and its config against the secret providers it has loaded. const SecretProviderConfigWrite = Schema.Struct({ ...SecretProviderConfig.fields, label: SecretProviderLabel, -}).check( - Schema.makeFilter((entry) => { - if (!isKnownSecretProviderKind(entry.kind)) { - return `Unsupported secret provider kind: ${entry.kind}.`; - } - return SECRET_PROVIDER_KIND_CONFIG_GUARDS[entry.kind]!(entry.config) - ? true - : `Invalid ${entry.kind} secret provider config.`; - }), -); +}); export const SourceControlHostSettings = Schema.Record(Schema.String, Schema.Unknown); export type SourceControlHostSettings = typeof SourceControlHostSettings.Type; @@ -1526,6 +1477,7 @@ export const ServerSettingsOperation = Schema.Literals([ "remove-secret", "remove-stale-secret", "write-secret", + "write-secret-provider", "write-file", "prepare-directory", ]); diff --git a/packages/provider-core/src/server/driver.ts b/packages/provider-core/src/server/driver.ts index d236a98fdcba2..a1771e2e748e9 100644 --- a/packages/provider-core/src/server/driver.ts +++ b/packages/provider-core/src/server/driver.ts @@ -6,7 +6,7 @@ import type { AcpRegistryOperationError, AcpRegistrySetProviderInput, ProviderDriverKind, - ProviderInstanceEnvironment, + ResolvedProviderInstanceEnvironment, ProviderInstanceId, ServerProvider, ServerProviderWorkspaceSnapshot, @@ -96,7 +96,7 @@ export interface ProviderDriverCreateInput { readonly instanceId: ProviderInstanceId; readonly displayName: string | undefined; readonly accentColor?: string | undefined; - readonly environment: ProviderInstanceEnvironment; + readonly environment: ResolvedProviderInstanceEnvironment; readonly enabled: boolean; readonly config: Config; } diff --git a/packages/provider-core/src/server/instanceEnvironment.test.ts b/packages/provider-core/src/server/instanceEnvironment.test.ts index 1899d1f9d5c3f..7f70cdddad573 100644 --- a/packages/provider-core/src/server/instanceEnvironment.test.ts +++ b/packages/provider-core/src/server/instanceEnvironment.test.ts @@ -1,5 +1,6 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, expect, it } from "@effect/vitest"; +import { SecretProviderId } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Path from "effect/Path"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -61,12 +62,21 @@ describe("mergeProviderInstanceEnvironment", () => { [ { name: "OPENROUTER_API_KEY", value: "sk-or-test", sensitive: true }, { name: "ANTHROPIC_API_KEY", value: "", sensitive: false }, + { + name: "OPENAI_API_KEY", + value: { + provider: SecretProviderId.make("personal"), + reference: "op://Private/OpenAI/credential", + }, + sensitive: true, + }, ], - { ANTHROPIC_API_KEY: "inherited", PATH: "/bin" }, + { ANTHROPIC_API_KEY: "inherited", OPENAI_API_KEY: "inherited", PATH: "/bin" }, ), ).toMatchObject({ OPENROUTER_API_KEY: "sk-or-test", ANTHROPIC_API_KEY: "", + OPENAI_API_KEY: "inherited", PATH: "/bin", }); }), diff --git a/packages/provider-core/src/server/instanceEnvironment.ts b/packages/provider-core/src/server/instanceEnvironment.ts index d0cddd119a13f..4a73f678da0c0 100644 --- a/packages/provider-core/src/server/instanceEnvironment.ts +++ b/packages/provider-core/src/server/instanceEnvironment.ts @@ -15,6 +15,8 @@ export const mergeProviderInstanceEnvironment = Effect.fn(function* ( const home = yield* HostProcess.HomeDirectory; const next: NodeJS.ProcessEnv = { ...baseEnv }; for (const variable of environment) { + // An unresolved secret reference carries no value; the registry resolves it for the provider. + if (typeof variable.value !== "string") continue; next[variable.name] = variable.name === "CODEX_HOME" || variable.name === "CLAUDE_CONFIG_DIR" ? expandHomePath(variable.value, home) diff --git a/packages/secret-provider-core/package.json b/packages/secret-provider-core/package.json new file mode 100644 index 0000000000000..3edea7a879b97 --- /dev/null +++ b/packages/secret-provider-core/package.json @@ -0,0 +1,33 @@ +{ + "name": "@t3tools/secret-provider-core", + "private": true, + "type": "module", + "exports": { + "./shared/definition": { + "types": "./src/shared/definition.ts", + "import": "./src/shared/definition.ts" + }, + "./server/driver": { + "types": "./src/server/driver.ts", + "import": "./src/server/driver.ts" + }, + "./server/SecretResolver": { + "types": "./src/server/SecretResolver.ts", + "import": "./src/server/SecretResolver.ts" + } + }, + "scripts": { + "typecheck": "tsc --noEmit", + "test": "vp test run --config ../../vite.config.ts --dir ." + }, + "dependencies": { + "@t3tools/contracts": "workspace:*", + "effect": "catalog:" + }, + "devDependencies": { + "@effect/platform-node": "catalog:", + "@effect/vitest": "catalog:", + "@types/node": "catalog:", + "vite-plus": "catalog:" + } +} diff --git a/packages/secret-provider-core/src/server/SecretResolver.test.ts b/packages/secret-provider-core/src/server/SecretResolver.test.ts new file mode 100644 index 0000000000000..d3c44aa14eaf7 --- /dev/null +++ b/packages/secret-provider-core/src/server/SecretResolver.test.ts @@ -0,0 +1,170 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, it } from "@effect/vitest"; +import { + SecretProviderId, + SecretProviderKind, + type SecretReference, + type ServerSettings, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; + +import { defineSecretProviderDriver } from "./driver.ts"; +import * as SecretResolver from "./SecretResolver.ts"; +import { defineSecretProvider } from "../shared/definition.ts"; + +const FAKE_KIND = SecretProviderKind.make("fake"); +const FakeConfig = Schema.Struct({ account: Schema.String }); + +const personal = SecretProviderId.make("personal"); +const work = SecretProviderId.make("work"); +const fake = (account: string) => ({ + kind: FAKE_KIND, + label: account, + config: { account }, +}); +const ref = (reference: string, provider = personal): SecretReference => ({ provider, reference }); + +function fakeDriver(answer: (account: string, reference: string) => string | undefined) { + const reads: Array<{ readonly account: string; readonly references: ReadonlyArray }> = []; + const driver = defineSecretProviderDriver({ + kind: FAKE_KIND, + definition: defineSecretProvider({ + kind: FAKE_KIND, + label: "Fake", + configSchema: FakeConfig, + isReference: (reference) => reference.startsWith("fake://"), + referencePlaceholder: "fake://item", + invalidReferenceMessage: "Use fake://item.", + }), + read: ({ account }, references) => + Effect.sync(() => { + reads.push({ account, references }); + return references.map((reference) => answer(account, reference)); + }), + }); + return { driver, reads }; +} + +const resolverLayer = ( + driver: ReturnType["driver"], + secretProviders: () => ServerSettings["secretProviders"] = () => ({ [personal]: fake("a") }), +) => + SecretResolver.layer({ + drivers: [driver], + secretProviders: Effect.sync(secretProviders), + }).pipe(Layer.provide(NodeServices.layer)); + +describe("SecretResolver", () => { + it.effect("reads a reference once and holds it", () => { + const { driver, reads } = fakeDriver(() => "sk-live"); + return Effect.gen(function* () { + const resolver = yield* SecretResolver.SecretResolver; + const token = ref("fake://openai"); + + assert.deepStrictEqual(yield* resolver.read([token]), ["sk-live"]); + assert.deepStrictEqual(yield* resolver.read([token]), ["sk-live"]); + assert.deepStrictEqual(reads, [{ account: "a", references: ["fake://openai"] }]); + }).pipe(Effect.provide(resolverLayer(driver))); + }); + + it.effect("holds a failed read until invalidated, then reads again", () => { + let locked = true; + const { driver, reads } = fakeDriver(() => (locked ? undefined : "sk-live")); + return Effect.gen(function* () { + const resolver = yield* SecretResolver.SecretResolver; + const token = ref("fake://openai"); + + assert.deepStrictEqual(yield* resolver.read([token]), [undefined]); + locked = false; + assert.deepStrictEqual(yield* resolver.read([token]), [undefined]); + assert.strictEqual(reads.length, 1); + + yield* resolver.invalidate([token]); + assert.deepStrictEqual(yield* resolver.read([token]), ["sk-live"]); + assert.strictEqual(reads.length, 2); + }).pipe(Effect.provide(resolverLayer(driver))); + }); + + it.effect("invalidates every reference when none are named", () => { + const { driver, reads } = fakeDriver(() => "sk-live"); + return Effect.gen(function* () { + const resolver = yield* SecretResolver.SecretResolver; + const token = ref("fake://openai"); + + yield* resolver.read([token]); + yield* resolver.invalidate(); + yield* resolver.read([token]); + assert.strictEqual(reads.length, 2); + }).pipe(Effect.provide(resolverLayer(driver))); + }); + + it.effect("reads each distinct reference of a provider in one call, in input order", () => { + const { driver, reads } = fakeDriver((_, reference) => reference.toUpperCase()); + return Effect.gen(function* () { + const resolver = yield* SecretResolver.SecretResolver; + + const values = yield* resolver.read([ref("fake://a"), ref("fake://b"), ref("fake://a")]); + + assert.deepStrictEqual(values, ["FAKE://A", "FAKE://B", "FAKE://A"]); + assert.deepStrictEqual(reads, [{ account: "a", references: ["fake://a", "fake://b"] }]); + }).pipe(Effect.provide(resolverLayer(driver))); + }); + + it.effect("reads each provider separately", () => { + const { driver, reads } = fakeDriver((account, reference) => `${account}:${reference}`); + return Effect.gen(function* () { + const resolver = yield* SecretResolver.SecretResolver; + + const values = yield* resolver.read([ref("fake://a"), ref("fake://a", work)]); + + assert.deepStrictEqual(values, ["a:fake://a", "b:fake://a"]); + assert.strictEqual(reads.length, 2); + }).pipe( + Effect.provide(resolverLayer(driver, () => ({ [personal]: fake("a"), [work]: fake("b") }))), + ); + }); + + it.effect("reads again when the provider's config changes", () => { + let account = "a"; + const { driver, reads } = fakeDriver((account, reference) => `${account}:${reference}`); + return Effect.gen(function* () { + const resolver = yield* SecretResolver.SecretResolver; + const token = ref("fake://openai"); + + assert.deepStrictEqual(yield* resolver.read([token]), ["a:fake://openai"]); + account = "b"; + assert.deepStrictEqual(yield* resolver.read([token]), ["b:fake://openai"]); + assert.deepStrictEqual( + reads.map((read) => read.account), + ["a", "b"], + ); + }).pipe(Effect.provide(resolverLayer(driver, () => ({ [personal]: fake(account) })))); + }); + + it.effect("does not call a driver for what it cannot read, and reads it later", () => { + const { driver, reads } = fakeDriver(() => "sk-live"); + const providers: ServerSettings["secretProviders"] = { + [personal]: fake("a"), + [SecretProviderId.make("vault")]: { + kind: SecretProviderKind.make("openbao"), + label: "Vault", + }, + [SecretProviderId.make("broken")]: { kind: FAKE_KIND, label: "Broken", config: {} }, + }; + return Effect.gen(function* () { + const resolver = yield* SecretResolver.SecretResolver; + + const values = yield* resolver.read([ + ref("fake://openai", SecretProviderId.make("missing")), + ref("fake://openai", SecretProviderId.make("vault")), + ref("fake://openai", SecretProviderId.make("broken")), + ref("openai"), + ]); + + assert.deepStrictEqual(values, [undefined, undefined, undefined, undefined]); + assert.strictEqual(reads.length, 0); + }).pipe(Effect.provide(resolverLayer(driver, () => providers))); + }); +}); diff --git a/packages/secret-provider-core/src/server/SecretResolver.ts b/packages/secret-provider-core/src/server/SecretResolver.ts new file mode 100644 index 0000000000000..28f5816f953b9 --- /dev/null +++ b/packages/secret-provider-core/src/server/SecretResolver.ts @@ -0,0 +1,125 @@ +// Reads secrets that settings point at through a configured secret provider. Each read, including +// a failed one, is held for the server's life so rebuilds never re-prompt an unlock; `invalidate` +// (the Settings refresh) is the only way to read again. +import type { SecretReference, ServerSettings } from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; + +import type { SecretProviderDriver, SecretProviderDriverServices } from "./driver.ts"; + +export class SecretResolver extends Context.Service< + SecretResolver, + { + /** Values in input order; `undefined` marks a reference that could not be read. */ + readonly read: ( + references: ReadonlyArray, + ) => Effect.Effect>; + /** Forgets the given references, or every reference, so the next read asks the provider again. */ + readonly invalidate: (references?: ReadonlyArray) => Effect.Effect; + } +>()("@t3tools/secret-provider-core/server/SecretResolver") {} + +const cacheKey = (reference: SecretReference) => + `${reference.provider}\u0000${reference.reference}`; + +interface CachedSecret { + // A provider whose config changed, such as another account, reads again. + readonly config: string; + readonly value: string | undefined; +} + +const decodeConfigWith = Schema.decodeUnknownOption>; + +interface ReadablePlan { + readonly driver: SecretProviderDriver; + readonly config: unknown; + readonly configKey: string; +} + +export const make = Effect.fn("SecretResolver.make")(function* (options: { + readonly drivers: ReadonlyArray; + readonly secretProviders: Effect.Effect; +}) { + const context = yield* Effect.context(); + const driversByKind = new Map( + options.drivers.map((driver) => [ + driver.kind, + { driver, decodeConfig: decodeConfigWith(driver.definition.configSchema) }, + ]), + ); + const cache = new Map(); + const semaphore = yield* Semaphore.make(1); + + // Only a provider this build can read is cached; anything else fails fast and is checked again + // on the next read. + const planFor = ( + providers: ServerSettings["secretProviders"], + reference: SecretReference, + ): ReadablePlan | undefined => { + const provider = providers[reference.provider]; + const entry = provider === undefined ? undefined : driversByKind.get(provider.kind); + if (provider === undefined || entry === undefined) return undefined; + const { driver, decodeConfig } = entry; + if (!driver.definition.isReference(reference.reference)) return undefined; + const config = decodeConfig(provider.config); + return Option.isNone(config) + ? undefined + : { driver, config: config.value, configKey: JSON.stringify(config.value) }; + }; + + const read: SecretResolver["Service"]["read"] = Effect.fn("SecretResolver.read")( + function* (references) { + const providers = yield* options.secretProviders; + const plans = references.map((reference) => planFor(providers, reference)); + + const wanted = new Map< + string, + { readonly plan: ReadablePlan; readonly byReference: Map> } + >(); + references.forEach((reference, index) => { + const plan = plans[index]; + if (plan === undefined || cache.get(cacheKey(reference))?.config === plan.configKey) return; + const group = wanted.get(reference.provider) ?? { plan, byReference: new Map() }; + group.byReference.set(reference.reference, [ + ...(group.byReference.get(reference.reference) ?? []), + reference, + ]); + wanted.set(reference.provider, group); + }); + for (const { plan, byReference } of wanted.values()) { + const values = yield* plan.driver.read(plan.config, [...byReference.keys()]); + [...byReference.values()].forEach((sameReference, index) => { + for (const reference of sameReference) { + cache.set(cacheKey(reference), { config: plan.configKey, value: values[index] }); + } + }); + } + + return references.map((reference, index) => { + const cached = cache.get(cacheKey(reference)); + return plans[index] !== undefined && cached?.config === plans[index].configKey + ? cached.value + : undefined; + }); + }, + (effect) => semaphore.withPermits(1)(effect), + Effect.provideContext(context), + ); + + const invalidate: SecretResolver["Service"]["invalidate"] = (references) => + semaphore.withPermits(1)( + Effect.sync(() => { + if (references === undefined) cache.clear(); + else for (const reference of references) cache.delete(cacheKey(reference)); + }), + ); + + return SecretResolver.of({ read, invalidate }); +}); + +export const layer = (options: Parameters[0]) => + Layer.effect(SecretResolver, make(options)); diff --git a/packages/secret-provider-core/src/server/driver.ts b/packages/secret-provider-core/src/server/driver.ts new file mode 100644 index 0000000000000..85deb93d8938b --- /dev/null +++ b/packages/secret-provider-core/src/server/driver.ts @@ -0,0 +1,46 @@ +import type { SecretProviderKind } from "@t3tools/contracts"; +import type * as Crypto from "effect/Crypto"; +import * as Effect from "effect/Effect"; +import type * as FileSystem from "effect/FileSystem"; +import * as Schema from "effect/Schema"; +import type { ChildProcessSpawner } from "effect/process"; + +import type { SecretProviderDefinition } from "../shared/definition.ts"; + +/** What the server gives every driver. A driver builds anything else it needs itself. */ +export type SecretProviderDriverServices = + | ChildProcessSpawner.ChildProcessSpawner + | FileSystem.FileSystem + | Crypto.Crypto; + +export interface SecretProviderDriver { + readonly kind: SecretProviderKind; + readonly definition: SecretProviderDefinition; + /** + * Values in input order; `undefined` marks a reference that could not be read. `config` has + * decoded with the definition's `configSchema` and every reference passed its `isReference`. + */ + readonly read: ( + config: unknown, + references: ReadonlyArray, + ) => Effect.Effect, never, SecretProviderDriverServices>; +} + +export const defineSecretProviderDriver = (driver: { + readonly kind: SecretProviderKind; + readonly definition: SecretProviderDefinition; + readonly read: ( + config: Config, + references: ReadonlyArray, + ) => Effect.Effect, never, SecretProviderDriverServices>; +}): SecretProviderDriver => { + const isConfig = Schema.is(driver.definition.configSchema); + return { + kind: driver.kind, + definition: driver.definition, + read: (config, references) => + isConfig(config) + ? driver.read(config, references) + : Effect.succeed(references.map(() => undefined)), + }; +}; diff --git a/packages/secret-provider-core/src/shared/definition.ts b/packages/secret-provider-core/src/shared/definition.ts new file mode 100644 index 0000000000000..7f4320dd0c3ea --- /dev/null +++ b/packages/secret-provider-core/src/shared/definition.ts @@ -0,0 +1,35 @@ +import type { SecretProviderKind } from "@t3tools/contracts"; +import type * as Schema from "effect/Schema"; + +/** What clients and the server both need to know about one kind of secret provider. */ +export interface SecretProviderDefinition { + readonly kind: SecretProviderKind; + readonly label: string; + readonly configSchema: Schema.Codec; + /** Whether `reference` is syntax this kind can read. */ + readonly isReference: (reference: string) => boolean; + readonly referencePlaceholder: string; + readonly invalidReferenceMessage: string; +} + +export const defineSecretProvider = ( + definition: SecretProviderDefinition, +): SecretProviderDefinition => definition; + +export interface SecretProviderDefinitionRegistry { + readonly definitions: ReadonlyArray; + readonly find: (kind: string) => SecretProviderDefinition | undefined; +} + +export function makeSecretProviderDefinitionRegistry( + definitions: ReadonlyArray, +): SecretProviderDefinitionRegistry { + const byKind = new Map(); + for (const definition of definitions) { + if (byKind.has(definition.kind)) { + throw new Error(`Secret provider '${definition.kind}' is defined more than once.`); + } + byKind.set(definition.kind, definition); + } + return { definitions, find: (kind) => byKind.get(kind) }; +} diff --git a/packages/secret-provider-core/tsconfig.json b/packages/secret-provider-core/tsconfig.json new file mode 100644 index 0000000000000..374bac55202dd --- /dev/null +++ b/packages/secret-provider-core/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "types": ["node"] + }, + "include": ["src"] +} diff --git a/packages/secret-provider-definitions/package.json b/packages/secret-provider-definitions/package.json new file mode 100644 index 0000000000000..5e3592a276030 --- /dev/null +++ b/packages/secret-provider-definitions/package.json @@ -0,0 +1,18 @@ +{ + "name": "@t3tools/secret-provider-definitions", + "private": true, + "type": "module", + "exports": { + "./registry": { + "types": "./src/registry.ts", + "import": "./src/registry.ts" + } + }, + "scripts": { + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@t3tools/secret-provider-core": "workspace:*", + "@t3tools/secret-provider-onepassword": "workspace:*" + } +} diff --git a/packages/secret-provider-definitions/src/registry.ts b/packages/secret-provider-definitions/src/registry.ts new file mode 100644 index 0000000000000..70df74e113810 --- /dev/null +++ b/packages/secret-provider-definitions/src/registry.ts @@ -0,0 +1,6 @@ +import { makeSecretProviderDefinitionRegistry } from "@t3tools/secret-provider-core/shared/definition"; +import * as OnePassword from "@t3tools/secret-provider-onepassword/shared/definition"; + +export const builtInSecretProviderDefinitions = makeSecretProviderDefinitionRegistry([ + OnePassword.definition, +]); diff --git a/packages/secret-provider-definitions/tsconfig.json b/packages/secret-provider-definitions/tsconfig.json new file mode 100644 index 0000000000000..564a5990051fd --- /dev/null +++ b/packages/secret-provider-definitions/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "../../tsconfig.base.json", + "include": ["src"] +} diff --git a/packages/secret-provider-onepassword/package.json b/packages/secret-provider-onepassword/package.json new file mode 100644 index 0000000000000..062495c90895f --- /dev/null +++ b/packages/secret-provider-onepassword/package.json @@ -0,0 +1,32 @@ +{ + "name": "@t3tools/secret-provider-onepassword", + "private": true, + "type": "module", + "exports": { + "./shared/definition": { + "types": "./src/shared/definition.ts", + "import": "./src/shared/definition.ts" + }, + "./server/driver": { + "types": "./src/server/driver.ts", + "import": "./src/server/driver.ts" + } + }, + "scripts": { + "typecheck": "tsc --noEmit", + "test": "vp test run --config ../../vite.config.ts --dir ." + }, + "dependencies": { + "@t3tools/contracts": "workspace:*", + "@t3tools/provider-core": "workspace:*", + "@t3tools/secret-provider-core": "workspace:*", + "@t3tools/shared": "workspace:*", + "effect": "catalog:" + }, + "devDependencies": { + "@effect/platform-node": "catalog:", + "@effect/vitest": "catalog:", + "@types/node": "catalog:", + "vite-plus": "catalog:" + } +} diff --git a/packages/secret-provider-onepassword/src/server/driver.test.ts b/packages/secret-provider-onepassword/src/server/driver.test.ts new file mode 100644 index 0000000000000..62675b1d0cbfb --- /dev/null +++ b/packages/secret-provider-onepassword/src/server/driver.test.ts @@ -0,0 +1,155 @@ +// @effect-diagnostics nodeBuiltinImport:off -- the fake `op` reads the template the driver wrote. +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem"; +import { assert, describe, it } from "@effect/vitest"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Layer from "effect/Layer"; +import * as Sink from "effect/Sink"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; +import { ChildProcessSpawner } from "effect/process"; +import * as NodeFS from "node:fs"; + +import { OnePasswordAccount } from "../shared/definition.ts"; +import { driver } from "./driver.ts"; + +const encoder = new TextEncoder(); +const account = OnePasswordAccount.make("my.1password.com"); + +type OpResult = { + readonly stdout?: string; + readonly stderr?: string; + readonly code?: number; + readonly hang?: boolean; +}; + +function fakeOp(answer: (args: ReadonlyArray) => OpResult) { + const invocations: Array> = []; + const spawned = Deferred.makeUnsafe(); + const layer = Layer.mergeAll( + Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make((command) => + Effect.sync(() => { + const { args } = command as unknown as { readonly args: ReadonlyArray }; + invocations.push(args); + Deferred.doneUnsafe(spawned, Effect.void); + const result = answer(args); + return ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + exitCode: result.hang + ? Effect.never + : Effect.succeed(ChildProcessSpawner.ExitCode(result.code ?? 0)), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.make(encoder.encode(result.stdout ?? "")), + stderr: Stream.make(encoder.encode(result.stderr ?? "")), + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }); + }), + ), + ), + NodeFileSystem.layer, + NodeCrypto.layer, + ); + return { layer, invocations, spawned }; +} + +// Answers `op inject` by substituting each `{{ reference }}` in the template file it was handed. +const injectFrom = + (secrets: Readonly>) => + (args: ReadonlyArray): OpResult => { + const template = NodeFS.readFileSync(args[args.indexOf("-i") + 1]!, "utf8"); + return { stdout: template.replace(/\{\{ (\S+) \}\}/g, (_, reference) => secrets[reference]!) }; + }; + +describe("1Password driver", () => { + it.effect("reads one reference from the account", () => { + const op = fakeOp(() => ({ stdout: "sk-live" })); + return Effect.gen(function* () { + assert.deepStrictEqual(yield* driver.read({ account }, ["op://Private/OpenAI/credential"]), [ + "sk-live", + ]); + assert.deepStrictEqual(op.invocations, [ + [ + "--cache=false", + "read", + "--account=my.1password.com", + "--no-newline", + "op://Private/OpenAI/credential", + ], + ]); + }).pipe(Effect.provide(op.layer)); + }); + + it.effect("reads a failed reference as undefined", () => { + const op = fakeOp(() => ({ code: 1, stderr: "[ERROR] account is locked" })); + return Effect.gen(function* () { + assert.deepStrictEqual(yield* driver.read({ account }, ["op://Private/OpenAI/credential"]), [ + undefined, + ]); + }).pipe(Effect.provide(op.layer)); + }); + + it.effect("reads every reference in a single call", () => { + const op = fakeOp( + injectFrom({ + "op://Private/OpenAI/credential": "sk-a", + "op://Private/Anthropic/key": " sk-b\n", + }), + ); + return Effect.gen(function* () { + const values = yield* driver.read({ account }, [ + "op://Private/OpenAI/credential", + "op://Private/Anthropic/key", + ]); + + assert.deepStrictEqual(values, ["sk-a", " sk-b\n"]); + assert.strictEqual(op.invocations.length, 1); + assert.deepStrictEqual(op.invocations[0]?.slice(0, 3), [ + "--cache=false", + "inject", + "--account=my.1password.com", + ]); + }).pipe(Effect.provide(op.layer)); + }); + + it.effect("falls back to one read at a time when the batch fails", () => { + const op = fakeOp((args) => + args.includes("inject") + ? { code: 1, stderr: '[ERROR] could not resolve "op://Private/Gone/key"' } + : args.at(-1) === "op://Private/Gone/key" + ? { code: 1, stderr: "[ERROR] item not found" } + : { stdout: "sk-a" }, + ); + return Effect.gen(function* () { + const values = yield* driver.read({ account }, [ + "op://Private/OpenAI/credential", + "op://Private/Gone/key", + ]); + + assert.deepStrictEqual(values, ["sk-a", undefined]); + assert.strictEqual(op.invocations.length, 3); + }).pipe(Effect.provide(op.layer)); + }); + + it.effect("does not read one at a time after the batch times out", () => { + const op = fakeOp(() => ({ hang: true })); + return Effect.gen(function* () { + const reading = yield* driver + .read({ account }, ["op://Private/OpenAI/credential", "op://Private/Anthropic/key"]) + .pipe(Effect.forkChild); + yield* Deferred.await(op.spawned); + yield* TestClock.adjust("1 minute"); + + assert.deepStrictEqual(yield* Fiber.join(reading), [undefined, undefined]); + assert.strictEqual(op.invocations.length, 1); + }).pipe(Effect.provide(op.layer)); + }); +}); diff --git a/packages/secret-provider-onepassword/src/server/driver.ts b/packages/secret-provider-onepassword/src/server/driver.ts new file mode 100644 index 0000000000000..abf9d6da5ed88 --- /dev/null +++ b/packages/secret-provider-onepassword/src/server/driver.ts @@ -0,0 +1,112 @@ +import { spawnAndCollect } from "@t3tools/provider-core/server/snapshotProbe"; +import { defineSecretProviderDriver } from "@t3tools/secret-provider-core/server/driver"; +import { resolveSpawnCommand } from "@t3tools/shared/shell"; +import * as Crypto from "effect/Crypto"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import { ChildProcess } from "effect/process"; + +import { definition, type OnePasswordAccount } from "../shared/definition.ts"; + +const ONE_PASSWORD_BINARY = "op"; +// Bounds a read long enough to reach for a fingerprint reader, short enough not to wedge a rebuild. +const READ_TIMEOUT = Duration.seconds(45); + +// `--cache=false` skips the `op daemon`, which hangs on prompts a background server cannot show. +const runOnePassword = Effect.fn("OnePasswordDriver.runOnePassword")(function* ( + args: ReadonlyArray, +) { + const spawnCommand = yield* resolveSpawnCommand(ONE_PASSWORD_BINARY, ["--cache=false", ...args]); + return yield* spawnAndCollect( + ONE_PASSWORD_BINARY, + ChildProcess.make(spawnCommand.command, spawnCommand.args, { shell: spawnCommand.shell }), + ); +}); + +// A secret is passed on verbatim; surrounding whitespace can be part of it. +const nonEmpty = (value: string) => (value.trim().length > 0 ? value : undefined); + +const readOne = Effect.fn("OnePasswordDriver.readOne")(function* ( + account: OnePasswordAccount, + reference: string, +) { + const result = yield* runOnePassword(["read", `--account=${account}`, "--no-newline", reference]); + if (result.code !== 0) { + yield* Effect.logWarning("Could not read secret from 1Password", { + stage: "read", + exitCode: result.code, + }); + return undefined; + } + return nonEmpty(result.stdout); +}); + +// One `op inject` costs one unlock for every reference in the template. `op` ignores piped stdin +// from Node, so the template goes through a temp file. A random separator after every reference +// keeps one secret from shifting the others, and leaves any trailing newline outside the values. +const readTogether = Effect.fn("OnePasswordDriver.readTogether")(function* ( + account: OnePasswordAccount, + references: ReadonlyArray, +) { + const fileSystem = yield* FileSystem.FileSystem; + const separator = `__t3-secret-${yield* (yield* Crypto.Crypto).randomUUIDv4()}__`; + const templatePath = yield* fileSystem.makeTempFileScoped({ prefix: "t3code-op-inject-" }); + yield* fileSystem.writeFileString( + templatePath, + references.map((reference) => `{{ ${reference} }}${separator}`).join(""), + ); + const result = yield* runOnePassword(["inject", `--account=${account}`, "-i", templatePath]); + const values = result.stdout.split(separator); + const trailing = values.pop(); + if ( + result.code !== 0 || + values.length !== references.length || + trailing === undefined || + trailing.trim().length > 0 + ) { + yield* Effect.logWarning("Could not batch-read secrets from 1Password", { + stage: "inject", + exitCode: result.code, + references: references.length, + }); + return undefined; + } + return values.map(nonEmpty); +}, Effect.scoped); + +/** `None` when 1Password did not answer in time; a failed run reads as `Some(undefined)`. */ +const bounded = ( + stage: "read" | "inject", + effect: Effect.Effect
      , +) => + effect.pipe( + Effect.timeoutOption(READ_TIMEOUT), + Effect.tap((outcome) => + Option.isNone(outcome) + ? Effect.logWarning("1Password did not answer in time", { stage }) + : Effect.void, + ), + Effect.catch((error) => + Effect.logWarning("Could not run 1Password", { stage, error: error._tag }).pipe( + Effect.as(Option.some(undefined)), + ), + ), + ); + +export const driver = defineSecretProviderDriver({ + kind: definition.kind, + definition, + read: Effect.fn("OnePasswordDriver.read")(function* ({ account }, references) { + if (references.length > 1) { + const together = yield* bounded("inject", readTogether(account, references)); + // Reading one by one after a timeout would only wait that long again for each reference. + if (Option.isNone(together)) return references.map(() => undefined); + if (together.value !== undefined) return together.value; + } + return yield* Effect.forEach(references, (reference) => + bounded("read", readOne(account, reference)).pipe(Effect.map(Option.getOrUndefined)), + ); + }), +}); diff --git a/packages/secret-provider-onepassword/src/shared/definition.test.ts b/packages/secret-provider-onepassword/src/shared/definition.test.ts new file mode 100644 index 0000000000000..0daefcf6acca1 --- /dev/null +++ b/packages/secret-provider-onepassword/src/shared/definition.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from "@effect/vitest"; + +import { definition } from "./definition.ts"; + +describe("1Password definition", () => { + it("accepts vault, item, optional section, and field references", () => { + for (const reference of [ + "op://Private/OpenAI/credential", + "op://Private/OpenAI/Section 1/credential", + "op://Private/OpenAI/credential?attribute=otp", + ]) { + expect(definition.isReference(reference), reference).toBe(true); + } + }); + + it("rejects anything that is not a plain reference", () => { + for (const reference of [ + "--help", + "Private/OpenAI/credential", + "op://Private/OpenAI", + "op://Private/OpenAI/credential }} {{ op://Private/B/c", + "op://Private/OpenAI\n/credential", + `op://Private/OpenAI/${"x".repeat(1024)}`, + ]) { + expect(definition.isReference(reference), reference).toBe(false); + } + }); +}); diff --git a/packages/secret-provider-onepassword/src/shared/definition.ts b/packages/secret-provider-onepassword/src/shared/definition.ts new file mode 100644 index 0000000000000..ff5164b1e00b2 --- /dev/null +++ b/packages/secret-provider-onepassword/src/shared/definition.ts @@ -0,0 +1,41 @@ +import { SecretProviderKind } from "@t3tools/contracts"; +import { defineSecretProvider } from "@t3tools/secret-provider-core/shared/definition"; +import * as Schema from "effect/Schema"; + +const ACCOUNT_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; + +/** + * Any value `op --account` accepts: shorthand, sign-in address, account ID, or user ID. + * It is passed to the CLI as an argument, so it can never start with `-`. + */ +export const OnePasswordAccount = Schema.String.check( + Schema.isMaxLength(253), + Schema.makeFilter((value: string) => + ACCOUNT_PATTERN.test(value) + ? true + : "1Password account must be a shorthand, sign-in address, or ID with no spaces.", + ), +).pipe(Schema.brand("OnePasswordAccount")); +export type OnePasswordAccount = typeof OnePasswordAccount.Type; + +export const OnePasswordSecretProviderConfig = Schema.Struct({ + account: OnePasswordAccount, +}); +export type OnePasswordSecretProviderConfig = typeof OnePasswordSecretProviderConfig.Type; + +// 1Password secret reference syntax: names outside this charset must be written as item ids. +// It also keeps `{{`, `}}`, and line breaks out of the `op inject` template the server builds. +const NAME = String.raw`[A-Za-z0-9._-](?:[A-Za-z0-9 ._-]*[A-Za-z0-9._-])?`; +const REFERENCE = new RegExp( + String.raw`^op://${NAME}(?:/${NAME}){2,3}(?:\?[a-z-]+=[A-Za-z0-9_-]+)?$`, +); +const MAX_REFERENCE_LENGTH = 1024; + +export const definition = defineSecretProvider({ + kind: SecretProviderKind.make("one_password"), + label: "1Password", + configSchema: OnePasswordSecretProviderConfig, + isReference: (reference) => reference.length <= MAX_REFERENCE_LENGTH && REFERENCE.test(reference), + referencePlaceholder: "op://vault/item/field", + invalidReferenceMessage: "Use a 1Password reference like op://vault/item/field.", +}); diff --git a/packages/secret-provider-onepassword/tsconfig.json b/packages/secret-provider-onepassword/tsconfig.json new file mode 100644 index 0000000000000..374bac55202dd --- /dev/null +++ b/packages/secret-provider-onepassword/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "types": ["node"] + }, + "include": ["src"] +} diff --git a/packages/shared/src/serverSettings.test.ts b/packages/shared/src/serverSettings.test.ts index 5a02f302826de..26cbfb3df9d59 100644 --- a/packages/shared/src/serverSettings.test.ts +++ b/packages/shared/src/serverSettings.test.ts @@ -1,6 +1,5 @@ import { DEFAULT_SERVER_SETTINGS, - OnePasswordAccount, ProjectId, ProviderDriverKind, ProviderInstanceId, @@ -590,7 +589,7 @@ describe("serverSettings helpers", () => { const onePassword = (label: string, account: string) => ({ kind: SecretProviderKind.make("one_password"), label, - config: { account: OnePasswordAccount.make(account) }, + config: { account }, }); const current = { ...DEFAULT_SERVER_SETTINGS, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 196781c388b03..381ff78688eb0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -955,6 +955,15 @@ importers: '@t3tools/provider-testing': specifier: workspace:* version: link:../../packages/provider-testing + '@t3tools/secret-provider-core': + specifier: workspace:* + version: link:../../packages/secret-provider-core + '@t3tools/secret-provider-definitions': + specifier: workspace:* + version: link:../../packages/secret-provider-definitions + '@t3tools/secret-provider-onepassword': + specifier: workspace:* + version: link:../../packages/secret-provider-onepassword '@t3tools/shared': specifier: workspace:* version: link:../../packages/shared @@ -1060,6 +1069,12 @@ importers: '@t3tools/provider-core': specifier: workspace:* version: link:../../packages/provider-core + '@t3tools/secret-provider-definitions': + specifier: workspace:* + version: link:../../packages/secret-provider-definitions + '@t3tools/secret-provider-onepassword': + specifier: workspace:* + version: link:../../packages/secret-provider-onepassword '@t3tools/shared': specifier: workspace:* version: link:../../packages/shared @@ -1890,6 +1905,68 @@ importers: specifier: 24.12.4 version: 24.12.4 + packages/secret-provider-core: + dependencies: + '@t3tools/contracts': + specifier: workspace:* + version: link:../contracts + effect: + specifier: 4.0.5 + version: 4.0.5 + devDependencies: + '@effect/platform-node': + specifier: 4.0.5 + version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + '@effect/vitest': + specifier: 4.0.5 + version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + '@types/node': + specifier: 24.12.4 + version: 24.12.4 + vite-plus: + specifier: 1.4.0 + version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + + packages/secret-provider-definitions: + dependencies: + '@t3tools/secret-provider-core': + specifier: workspace:* + version: link:../secret-provider-core + '@t3tools/secret-provider-onepassword': + specifier: workspace:* + version: link:../secret-provider-onepassword + + packages/secret-provider-onepassword: + dependencies: + '@t3tools/contracts': + specifier: workspace:* + version: link:../contracts + '@t3tools/provider-core': + specifier: workspace:* + version: link:../provider-core + '@t3tools/secret-provider-core': + specifier: workspace:* + version: link:../secret-provider-core + '@t3tools/shared': + specifier: workspace:* + version: link:../shared + effect: + specifier: 4.0.5 + version: 4.0.5 + devDependencies: + '@effect/platform-node': + specifier: 4.0.5 + version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + '@effect/vitest': + specifier: 4.0.5 + version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + '@types/node': + specifier: 24.12.4 + version: 24.12.4 + vite-plus: + specifier: 1.4.0 + version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + packages/shared: dependencies: '@noble/curves': diff --git a/scripts/release-smoke.ts b/scripts/release-smoke.ts index 12ef21824014d..8f300533523ae 100644 --- a/scripts/release-smoke.ts +++ b/scripts/release-smoke.ts @@ -39,6 +39,9 @@ const workspaceFiles = [ "packages/provider-grok/package.json", "packages/provider-muse/package.json", "packages/provider-opencode/package.json", + "packages/secret-provider-core/package.json", + "packages/secret-provider-definitions/package.json", + "packages/secret-provider-onepassword/package.json", "packages/source-control-azure-devops/package.json", "packages/source-control-bitbucket/package.json", "packages/source-control-core/package.json", From 476590d0adede15a4eec0d05b8adac8c63736452 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 30 Oct 2026 00:50:23 -0700 Subject: [PATCH 413/817] feat(desktop): back/forward buttons and trackpad swipe navigation (#27430) Co-authored-by: Claude Opus 5.5 --- apps/desktop/src/ipc/channels.ts | 1 + apps/desktop/src/preload.ts | 5 + apps/desktop/src/window/DesktopWindow.ts | 7 +- apps/web/src/components/AppSidebarLayout.tsx | 4 +- .../components/HistorySwipeNavigation.test.ts | 15 ++ .../src/components/HistorySwipeNavigation.tsx | 189 ++++++++++++++++++ .../src/components/sidebar/SidebarChrome.tsx | 68 ++++++- apps/web/src/navigationHistory.ts | 22 ++ packages/contracts/src/ipc.ts | 1 + 9 files changed, 307 insertions(+), 5 deletions(-) create mode 100644 apps/web/src/components/HistorySwipeNavigation.test.ts create mode 100644 apps/web/src/components/HistorySwipeNavigation.tsx create mode 100644 apps/web/src/navigationHistory.ts diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index bba4f6449b8c1..538dd06b0b42a 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -14,6 +14,7 @@ export const SNAP_SHOT_EVENT_CHANNEL = "desktop:snap-shot-event"; export const WEB_LINK_OPEN_CHANNEL = "desktop:web-link-open"; export const WEB_LINK_READY_CHANNEL = "desktop:web-link-ready"; export const QUIT_SHORTCUT_CHANNEL = "desktop:quit-shortcut"; +export const TRACKPAD_SCROLL_BEGIN_CHANNEL = "desktop:trackpad-scroll-begin"; export const TRACKPAD_SCROLL_END_CHANNEL = "desktop:trackpad-scroll-end"; export const GET_WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:get-window-fullscreen-state"; export const WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:window-fullscreen-state"; diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index 965b7db5d6d40..950ed972c6453 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -91,6 +91,11 @@ contextBridge.exposeInMainWorld("desktopBridge", { ipcRenderer.on(IpcChannels.SET_NOTIFICATION_BADGE_CHANNEL, handler); return () => ipcRenderer.removeListener(IpcChannels.SET_NOTIFICATION_BADGE_CHANNEL, handler); }, + onTrackpadScrollBegin: (listener) => { + const handler = () => listener(); + ipcRenderer.on(IpcChannels.TRACKPAD_SCROLL_BEGIN_CHANNEL, handler); + return () => ipcRenderer.removeListener(IpcChannels.TRACKPAD_SCROLL_BEGIN_CHANNEL, handler); + }, onTrackpadScrollEnd: (listener) => { const handler = () => listener(); ipcRenderer.on(IpcChannels.TRACKPAD_SCROLL_END_CHANNEL, handler); diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index ab5fc8be26a92..c1c0cf5446cd2 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -23,6 +23,7 @@ import { MENU_ACTION_CHANNEL, QUIT_SHORTCUT_CHANNEL, SNAP_SHOT_EVENT_CHANNEL, + TRACKPAD_SCROLL_BEGIN_CHANNEL, TRACKPAD_SCROLL_END_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL, } from "../ipc/channels.ts"; @@ -652,7 +653,11 @@ export const make = Effect.gen(function* () { } }); window.webContents.on("input-event", (_event, input) => { - if (input.type === "gestureScrollEnd") window.webContents.send(TRACKPAD_SCROLL_END_CHANNEL); + if (input.type === "gestureScrollBegin") { + window.webContents.send(TRACKPAD_SCROLL_BEGIN_CHANNEL); + } else if (input.type === "gestureScrollEnd") { + window.webContents.send(TRACKPAD_SCROLL_END_CHANNEL); + } }); // Ctrl+wheel bypasses menus; guest contents emit their own zoom-changed event. window.webContents.on("zoom-changed", (_event, direction) => { diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx index 6c8837e63f40a..91df5616f7f50 100644 --- a/apps/web/src/components/AppSidebarLayout.tsx +++ b/apps/web/src/components/AppSidebarLayout.tsx @@ -38,6 +38,7 @@ import { usePanelNavigationSuppression, } from "../panelAnimations"; import { BackgroundThreadAnnouncer } from "./BackgroundThreadAnnouncer"; +import { HistorySwipeNavigation } from "./HistorySwipeNavigation"; import ThreadSidebar from "./Sidebar"; import { SidebarBrandWidthProbe } from "./sidebar/SidebarChrome"; import { isAppModalPage } from "./sidebar/mainAppLocation"; @@ -449,7 +450,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) { defaultOpen style={sidebarProviderStyle} > - + + {isElectron ? : null} ); diff --git a/apps/web/src/components/HistorySwipeNavigation.test.ts b/apps/web/src/components/HistorySwipeNavigation.test.ts new file mode 100644 index 0000000000000..9eef35f0dc61e --- /dev/null +++ b/apps/web/src/components/HistorySwipeNavigation.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { isMomentumTail } from "./HistorySwipeNavigation"; + +describe("isMomentumTail", () => { + it.each([ + ["steady momentum decay", [40, 37, 34, 31.3, 28.8], true], + ["fingers still moving", [12, 18, 9, 15, 11], false], + ["fingers slowing unevenly", [30, 22, 20, 12, 11], false], + ["reversing", [10, 8, 6, 4, -2], false], + ["too few samples", [40, 37, 34], false], + ])("%s", (_name, deltas, expected) => { + expect(isMomentumTail(deltas)).toBe(expected); + }); +}); diff --git a/apps/web/src/components/HistorySwipeNavigation.tsx b/apps/web/src/components/HistorySwipeNavigation.tsx new file mode 100644 index 0000000000000..c020878b25363 --- /dev/null +++ b/apps/web/src/components/HistorySwipeNavigation.tsx @@ -0,0 +1,189 @@ +import { ArrowLeftIcon, ArrowRightIcon } from "lucide-react"; +import { useEffect, useState } from "react"; + +import { cn } from "../lib/utils"; +import { canNavigateHistory, navigateHistory, type HistoryDirection } from "../navigationHistory"; + +const SWIPE_TRIGGER_DISTANCE = 120; +// Movement needed before the gesture picks an axis; first events are often diagonal. +const SWIPE_AXIS_LOCK_DISTANCE = 8; +const MOMENTUM_SAMPLE_SIZE = 5; + +type SwipeBounds = { left: number; top: number; width: number; height: number }; +type SwipeGesture = + | { kind: "pending"; target: EventTarget | null; y: number; sumX: number; sumY: number } + | { + kind: "tracking"; + direction: HistoryDirection; + distance: number; + deltas: number[]; + y: number; + bounds: SwipeBounds; + } + // Not a swipe, or one already decided: the rest of its events are ignored. + | { kind: "ignored" }; +type SwipeIndicatorState = { + direction: HistoryDirection; + progress: number; + y: number; + bounds: SwipeBounds; + tracking: boolean; +}; + +function readMainContentBounds(): SwipeBounds { + const main = document.querySelector('[data-slot="sidebar-inset"]'); + if (!main) return { left: 0, top: 0, width: window.innerWidth, height: window.innerHeight }; + const { left, top, width, height } = main.getBoundingClientRect(); + return { left, top, width, height }; +} + +function canScrollHorizontally(target: EventTarget | null, deltaX: number): boolean { + for ( + let element = target instanceof Element ? target : null; + element; + element = element.parentElement + ) { + if (element.scrollWidth <= element.clientWidth) continue; + const { overflowX } = getComputedStyle(element); + if (overflowX !== "auto" && overflowX !== "scroll") continue; + const canScroll = + deltaX < 0 + ? element.scrollLeft > 0 + : element.scrollLeft + element.clientWidth < element.scrollWidth - 1; + if (canScroll) return true; + } + return false; +} + +function lockSwipeAxis( + pending: Extract, +): Exclude { + const { target, sumX, sumY } = pending; + if (Math.abs(sumX) <= Math.abs(sumY)) return { kind: "ignored" }; + if (target instanceof Element && target.closest('[role="dialog"]')) return { kind: "ignored" }; + if (canScrollHorizontally(target, sumX)) return { kind: "ignored" }; + const direction = sumX < 0 ? "back" : "forward"; + if (!canNavigateHistory(direction)) return { kind: "ignored" }; + return { + kind: "tracking", + direction, + distance: Math.abs(sumX), + deltas: [], + y: pending.y, + bounds: readMainContentBounds(), + }; +} + +/** + * macOS momentum after the fingers lift decays by a near-constant ratio per + * event; finger movement is noisier. Deltas are signed along the swipe. + */ +export function isMomentumTail(deltas: readonly number[]): boolean { + if (deltas.length < MOMENTUM_SAMPLE_SIZE) return false; + const recent = deltas.slice(-MOMENTUM_SAMPLE_SIZE); + if (recent.some((delta) => delta <= 0)) return false; + const ratios = recent.slice(1).map((delta, index) => delta / recent[index]!); + return ( + ratios.every((ratio) => ratio >= 0.7 && ratio < 1) && + Math.max(...ratios) - Math.min(...ratios) < 0.1 + ); +} + +/** Two-finger horizontal trackpad swipes go back and forward, like a browser. */ +export function HistorySwipeNavigation() { + const [swipe, setSwipe] = useState(null); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window wheel and desktop gesture listeners track trackpad swipes + useEffect(() => { + let gesture: SwipeGesture | null = null; + const hideIndicator = () => + setSwipe((current) => (current === null ? null : { ...current, tracking: false })); + // The fingers lifted: navigate if the swipe went far enough, then ignore its momentum. + const release = () => { + if (gesture?.kind === "tracking" && gesture.distance >= SWIPE_TRIGGER_DISTANCE) { + navigateHistory(gesture.direction); + } + gesture = { kind: "ignored" }; + hideIndicator(); + }; + // Chromium brackets each trackpad scroll, momentum included, with these. + const unsubscribeScrollBegin = window.desktopBridge?.onTrackpadScrollBegin(() => { + if (gesture?.kind === "ignored") gesture = null; + }); + const unsubscribeScrollEnd = window.desktopBridge?.onTrackpadScrollEnd(() => { + if (gesture?.kind === "tracking") release(); + gesture = null; + }); + const onWheel = (event: WheelEvent) => { + if (gesture === null) { + gesture = + event.ctrlKey || event.deltaMode !== WheelEvent.DOM_DELTA_PIXEL + ? { kind: "ignored" } + : { kind: "pending", target: event.target, y: event.clientY, sumX: 0, sumY: 0 }; + } + if (gesture.kind === "ignored") return; + if (gesture.kind === "pending") { + gesture.sumX += event.deltaX; + gesture.sumY += event.deltaY; + if (Math.abs(gesture.sumX) + Math.abs(gesture.sumY) < SWIPE_AXIS_LOCK_DISTANCE) return; + gesture = lockSwipeAxis(gesture); + if (gesture.kind === "ignored") return; + } else { + const delta = gesture.direction === "back" ? -event.deltaX : event.deltaX; + if (event.deltaX === 0 && event.deltaY === 0) return release(); + gesture.deltas = [...gesture.deltas.slice(1 - MOMENTUM_SAMPLE_SIZE), delta]; + if (isMomentumTail(gesture.deltas)) return release(); + gesture.distance = Math.max(0, gesture.distance + delta); + } + setSwipe({ + direction: gesture.direction, + progress: Math.min(1, gesture.distance / SWIPE_TRIGGER_DISTANCE), + y: gesture.y, + bounds: gesture.bounds, + tracking: true, + }); + }; + window.addEventListener("wheel", onWheel, { capture: true, passive: true }); + return () => { + unsubscribeScrollBegin?.(); + unsubscribeScrollEnd?.(); + window.removeEventListener("wheel", onWheel, { capture: true }); + }; + }, []); + + return swipe === null ? null : ; +} + +// A circle pinned to the edge of the main content that peeks in up to half its width. +function SwipeIndicator({ direction, progress, y, bounds, tracking }: SwipeIndicatorState) { + const armed = progress >= 1; + const Icon = direction === "back" ? ArrowLeftIcon : ArrowRightIcon; + const hidden = 100 - progress * 50; + return ( + + ); +} diff --git a/apps/web/src/components/sidebar/SidebarChrome.tsx b/apps/web/src/components/sidebar/SidebarChrome.tsx index b136d47fd9c40..dd41ddd2a0213 100644 --- a/apps/web/src/components/sidebar/SidebarChrome.tsx +++ b/apps/web/src/components/sidebar/SidebarChrome.tsx @@ -1,9 +1,17 @@ -import { ArrowLeftIcon, ChartNoAxesColumnIcon, SettingsIcon } from "lucide-react"; +import { ArrowLeftIcon, ArrowRightIcon, ChartNoAxesColumnIcon, SettingsIcon } from "lucide-react"; import type { ReactNode } from "react"; import { memo } from "react"; import { Link, useLocation, useNavigate } from "@tanstack/react-router"; +import { useAtomValue } from "@effect/atom-react"; import { useEnvironmentIdentificationMode } from "../../hooks/useSettings"; +import { shortcutLabelForCommand } from "../../keybindings"; +import { + navigateHistory, + useCanNavigateHistory, + type HistoryDirection, +} from "../../navigationHistory"; +import { primaryServerKeybindingsAtom } from "../../state/server"; import { cn } from "../../lib/utils"; import { usePullRequestsSupported } from "../../state/environments"; import { T3Wordmark } from "../T3Wordmark"; @@ -14,6 +22,7 @@ import { useEnvironmentStageLabel, } from "../SidebarStageBackdrop"; import { Badge } from "../ui/badge"; +import { Button } from "../ui/button"; import { SidebarFooter, SidebarMenu, @@ -63,7 +72,15 @@ export const SidebarChromeHeader = memo(function SidebarChromeHeader({ />
      - +
      + + {isElectron ? ( +
      + + +
      + ) : null} +
      {pillLabel ? (
      @@ -77,8 +94,10 @@ export const SidebarChromeHeader = memo(function SidebarChromeHeader({ }); export function SidebarBrandWidthProbe({ + isElectron, onWidthChange, }: { + isElectron: boolean; onWidthChange: (width: number) => void; }) { const observeWidth = (probe: HTMLDivElement) => { @@ -93,13 +112,56 @@ export function SidebarBrandWidthProbe({ className="pointer-events-none invisible fixed top-0 left-0 flex w-max border-r border-transparent pr-3" ref={observeWidth} > -
      +
      + {isElectron ?
      : null}
      ); } +function HistoryNavigationButton({ + direction, + onBackdrop, +}: { + direction: HistoryDirection; + onBackdrop: boolean; +}) { + const keybindings = useAtomValue(primaryServerKeybindingsAtom); + const enabled = useCanNavigateHistory(direction); + const label = direction === "back" ? "Go back" : "Go forward"; + const shortcutLabel = shortcutLabelForCommand( + keybindings, + direction === "back" ? "navigation.back" : "navigation.forward", + ); + const Icon = direction === "back" ? ArrowLeftIcon : ArrowRightIcon; + return ( + + navigateHistory(direction)} + size="icon-sm" + variant={onBackdrop ? "media-navigation" : "ghost"} + /> + } + > + + + + {label} + {shortcutLabel ? ` (${shortcutLabel})` : ""} + + + ); +} + function SidebarBrand({ onBackdrop }: { onBackdrop: boolean }) { return ( void): () => void { + window.navigation.addEventListener("currententrychange", onChange); + return () => window.navigation.removeEventListener("currententrychange", onChange); +} + +export function canNavigateHistory(direction: HistoryDirection): boolean { + return direction === "back" ? window.navigation.canGoBack : window.navigation.canGoForward; +} + +export function navigateHistory(direction: HistoryDirection) { + if (direction === "back") window.history.back(); + else window.history.forward(); +} + +/** Only for Electron: the Navigation API is Chromium-only. */ +export function useCanNavigateHistory(direction: HistoryDirection): boolean { + return useSyncExternalStore(subscribeToNavigationHistory, () => canNavigateHistory(direction)); +} diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index f460619f11355..f14452fec5a92 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -1018,6 +1018,7 @@ export interface DesktopBridge { getClientPlatform: () => string; setNotificationBadge: (badge: { count: number; image: string | null }) => Promise; onNotificationBadgeClear: (listener: () => void) => () => void; + onTrackpadScrollBegin: (listener: () => void) => () => void; onTrackpadScrollEnd: (listener: () => void) => () => void; /** * Renderer `window.focus()` cannot raise an Electron window, and on Wayland From 5ef56853ef1854da50bc1909c6c0a32700f2cb13 Mon Sep 17 00:00:00 2001 From: Bilal Bakr <62337003+Bil0000@users.noreply.github.com> Date: Fri, 30 Oct 2026 11:00:33 +0300 Subject: [PATCH 414/817] feat(web): review local commits in the Diff pane (#19941) Co-authored-by: Julius Marminge Co-authored-by: Claude Opus 5.5 --- .../mobile/src/features/review/reviewModel.ts | 27 +- apps/server/src/auth/RpcAuthorization.ts | 1 + .../src/observability/RpcInstrumentation.ts | 1 + apps/server/src/review/ReviewService.ts | 36 ++- apps/server/src/vcs/GitVcsDriver.ts | 5 + apps/server/src/vcs/GitVcsDriverCore.test.ts | 136 ++++++++++ apps/server/src/vcs/GitVcsDriverCore.ts | 236 +++++++++++++++- apps/server/src/ws.ts | 1 + apps/web/src/browser/browserLinkTarget.ts | 13 +- apps/web/src/browser/useOpenLink.ts | 8 +- apps/web/src/components/ChatView.tsx | 7 +- apps/web/src/components/DiffPanel.tsx | 252 ++++++++++++++++-- ...DesktopWebLinkCoordinator.browser.test.tsx | 117 +++++++- .../desktop/DesktopWebLinkCoordinator.tsx | 58 ++-- .../components/diffs/useReviewFilePatches.ts | 1 + .../src/components/settings/settingsSearch.ts | 2 +- apps/web/src/diffPanelStore.ts | 52 +++- .../lib/openPullRequestLink.browser.test.tsx | 160 +++++++++++ apps/web/src/lib/openPullRequestLink.ts | 219 +++++++++++---- apps/web/src/rightPanelStore.ts | 11 + docs/user/source-control.md | 10 + .../client-runtime/src/changeRequestLinks.ts | 18 ++ packages/client-runtime/src/state/review.ts | 5 + packages/contracts/src/review.ts | 28 +- packages/contracts/src/rpc.ts | 10 + .../src/shared/definition.ts | 9 + .../src/shared/definition.ts | 6 + .../src/shared/definition.ts | 74 ++++- .../src/registry.ts | 2 +- .../src/shared/definition.ts | 5 + .../src/shared/definition.ts | 6 + .../src/shared/definition.ts | 16 +- .../src/shared/definition.ts | 5 + 33 files changed, 1375 insertions(+), 162 deletions(-) create mode 100644 apps/web/src/lib/openPullRequestLink.browser.test.tsx diff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts index 1b2131c73e0c1..21b57322da1cd 100644 --- a/apps/mobile/src/features/review/reviewModel.ts +++ b/apps/mobile/src/features/review/reviewModel.ts @@ -534,17 +534,22 @@ export function buildReviewSectionItems(input: { }, ); - const gitItems = input.gitSections.map((section) => ({ - id: `git:${section.kind}`, - kind: section.kind, - title: section.title, - subtitle: gitSubtitle(section), - diff: section.diff, - source: section, - ...(section.files ? { files: section.files } : {}), - truncated: section.truncated, - isLoading: false, - })); + const gitItems = input.gitSections + .filter( + (section): section is typeof section & { kind: ReviewSectionKind } => + section.kind !== "commit", + ) + .map((section) => ({ + id: `git:${section.kind}`, + kind: section.kind, + title: section.title, + subtitle: gitSubtitle(section), + diff: section.diff, + source: section, + ...(section.files ? { files: section.files } : {}), + truncated: section.truncated, + isLoading: false, + })); const hasChangesItem = gitItems.some((item) => item.id === CHANGES_SECTION_ID); const visibleGitItems = input.loadingGitSections && !hasChangesItem diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 3806262cced53..bf2b8d49daf8d 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -170,6 +170,7 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.vcsRefreshStatus]: AuthOrchestrationReadScope, [WS_METHODS.gitResolvePullRequest]: AuthOrchestrationReadScope, [WS_METHODS.vcsListRefs]: AuthOrchestrationReadScope, + [WS_METHODS.reviewGetBranchCommits]: AuthFilesystemReadScope, [WS_METHODS.reviewGetDiffPreview]: AuthFilesystemReadScope, [WS_METHODS.reviewGetDiffFileContents]: AuthFilesystemReadScope, [WS_METHODS.terminalOpen]: AuthTerminalOperateScope, diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index 028ea5a561d44..cb8b0b6a86cf3 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -181,6 +181,7 @@ const RPC_AGGREGATES = { [WS_METHODS.vcsCreateRef]: "vcs", [WS_METHODS.vcsSwitchRef]: "vcs", [WS_METHODS.vcsInit]: "vcs", + [WS_METHODS.reviewGetBranchCommits]: "review", [WS_METHODS.reviewGetDiffPreview]: "review", [WS_METHODS.reviewGetDiffFileContents]: "review", [WS_METHODS.terminalOpen]: "terminal", diff --git a/apps/server/src/review/ReviewService.ts b/apps/server/src/review/ReviewService.ts index 8f88b387bd454..39ce1554cea61 100644 --- a/apps/server/src/review/ReviewService.ts +++ b/apps/server/src/review/ReviewService.ts @@ -8,6 +8,8 @@ import * as Path from "effect/Path"; import { VcsRepositoryDetectionError, VcsUnsupportedOperationError, + type ReviewBranchCommitsInput, + type ReviewBranchCommitsResult, type ReviewDiffFileContentsInput, type ReviewDiffFileContentsResult, type ReviewDiffPreviewError, @@ -20,9 +22,18 @@ import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; import * as KnownWorkspaces from "../workspace/KnownWorkspaces.ts"; +const WORKSPACE_BOUND_SUBJECTS = { + "ReviewService.getBranchCommits": "commit list", + "ReviewService.getDiffPreview": "diff preview", + "ReviewService.getDiffFileContents": "diff file contents", +} as const; + export class ReviewService extends Context.Service< ReviewService, { + readonly getBranchCommits: ( + input: ReviewBranchCommitsInput, + ) => Effect.Effect; readonly getDiffPreview: ( input: ReviewDiffPreviewInput, ) => Effect.Effect; @@ -61,7 +72,7 @@ export const make = Effect.gen(function* () { }; const assertWorkspaceBoundCwd = Effect.fn("ReviewService.assertWorkspaceBoundCwd")(function* ( - operation: "ReviewService.getDiffPreview" | "ReviewService.getDiffFileContents", + operation: keyof typeof WORKSPACE_BOUND_SUBJECTS, cwd: string, ) { const [candidate, workspaceRoot] = yield* Effect.all([ @@ -78,13 +89,27 @@ export const make = Effect.gen(function* () { return yield* new VcsRepositoryDetectionError({ operation, cwd, - detail: - operation === "ReviewService.getDiffPreview" - ? "Review diff preview cwd must stay within the configured workspace root." - : "Review diff file contents cwd must stay within the configured workspace root.", + detail: `Review ${WORKSPACE_BOUND_SUBJECTS[operation]} cwd must stay within the configured workspace root.`, }); }); + const getBranchCommits: ReviewService["Service"]["getBranchCommits"] = Effect.fn( + "ReviewService.getBranchCommits", + )(function* (input) { + yield* assertWorkspaceBoundCwd("ReviewService.getBranchCommits", input.cwd); + + const handle = yield* vcsRegistry.detect({ cwd: input.cwd, requestedKind: "auto" }); + if (!handle) return { commits: [], truncated: false }; + if (handle.kind !== "git") { + return yield* new VcsUnsupportedOperationError({ + operation: "ReviewService.getBranchCommits", + kind: handle.kind, + detail: "Review commit lists require a Git repository.", + }); + } + return yield* git.getReviewBranchCommits(input); + }); + const getDiffPreview: ReviewService["Service"]["getDiffPreview"] = Effect.fn( "ReviewService.getDiffPreview", )(function* (input) { @@ -120,6 +145,7 @@ export const make = Effect.gen(function* () { }); return ReviewService.of({ + getBranchCommits, getDiffPreview, getDiffFileContents, }); diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 95833200a1b5f..74e409a8bc184 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -20,6 +20,8 @@ import { type VcsCreateRefResult, type VcsCreateWorktreeInput, type VcsCreateWorktreeResult, + type ReviewBranchCommitsInput, + type ReviewBranchCommitsResult, type ReviewDiffPreviewInput, type ReviewDiffPreviewResult, type ReviewDiffFileContentsInput, @@ -328,6 +330,9 @@ export class GitVcsDriver extends Context.Service< cwd: string, baseRef: string, ) => Effect.Effect; + readonly getReviewBranchCommits: ( + input: ReviewBranchCommitsInput, + ) => Effect.Effect; readonly getReviewDiffPreview: ( input: ReviewDiffPreviewInput, ) => Effect.Effect; diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index d05a41a6f3824..cd4b6949fad86 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -1,5 +1,7 @@ // @effect-diagnostics nodeBuiltinImport:off - realpathSync.native resolves Windows 8.3 short names, which the Effect realPath does not. import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodeURL from "node:url"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { assert, it, describe } from "@effect/vitest"; @@ -1466,6 +1468,140 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }); describe("review diff previews", () => { + it.effect("diffs a root commit against the empty tree but rejects a shallow boundary", () => + Effect.gen(function* () { + const upstream = yield* makeTmpDir(); + yield* initRepoWithCommit(upstream); + const driver = yield* GitVcsDriver.GitVcsDriver; + const emptyTree = yield* git(upstream, ["hash-object", "-t", "tree", NodeOS.devNull]); + const root = yield* git(upstream, ["rev-parse", "HEAD"]); + const rootSource = (yield* driver.getReviewDiffPreview({ cwd: upstream, commitSha: root })) + .sources[0]!; + assert.equal(rootSource.baseRef, emptyTree); + assert.include(rootSource.diff, "+# test"); + + yield* writeTextFile(upstream, "README.md", "# boundary\n"); + yield* git(upstream, ["commit", "-am", "boundary"]); + const sha = yield* git(upstream, ["rev-parse", "HEAD"]); + const cwd = yield* makeTmpDir(); + yield* git(upstream, ["clone", "--depth=1", NodeURL.pathToFileURL(upstream).href, cwd], { + GIT_CONFIG_GLOBAL: NodeOS.devNull, + GIT_CONFIG_NOSYSTEM: "1", + }); + assert.equal(yield* git(cwd, ["rev-parse", "--is-shallow-repository"]), "true"); + for (const request of [ + driver.getReviewDiffPreview({ cwd, commitSha: sha }), + driver.getReviewDiffFileContents( + makeReviewDiffFileContentsInput(cwd, { + sourceKind: "commit", + changeType: "new", + headRef: sha, + baseRef: emptyTree, + }), + ), + ]) { + const error = yield* Effect.asVoid(request).pipe( + Effect.flip, + ); + assert.include(error.detail, "parent"); + } + }), + ); + + it.effect("lists the branch's commits newest first, at most 100, and flags the rest", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(cwd, ["checkout", "-b", "feature/commits"]); + for (let index = 0; index < 102; index++) { + yield* git(cwd, ["commit", "--allow-empty", "-m", `feature ${index}`]); + } + + const result = yield* driver.getReviewBranchCommits({ cwd, baseRef: initialBranch }); + assert.strictEqual(result.truncated, true); + assert.strictEqual(result.commits.length, 100); + assert.strictEqual(result.commits[0]?.sha, yield* git(cwd, ["rev-parse", "HEAD"])); + assert.deepStrictEqual( + [result.commits[0]?.subject, result.commits[99]?.subject], + ["feature 101", "feature 2"], + ); + }), + ); + + it.effect("previews one selected commit, a merge against its first parent", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(cwd, ["checkout", "-b", "feature/merge-preview"]); + yield* git(cwd, ["checkout", "-b", "feature/side"]); + yield* writeTextFile(cwd, "README.md", "# side commit\n"); + yield* git(cwd, ["add", "README.md"]); + yield* git(cwd, ["commit", "-m", "side change"]); + yield* git(cwd, ["checkout", "feature/merge-preview"]); + yield* writeTextFile(cwd, "feature.txt", "feature commit\n"); + yield* git(cwd, ["add", "feature.txt"]); + yield* git(cwd, ["commit", "-m", "feature change"]); + const firstParent = yield* git(cwd, ["rev-parse", "HEAD"]); + yield* git(cwd, ["merge", "--no-ff", "--no-edit", "feature/side"]); + const mergeSha = yield* git(cwd, ["rev-parse", "HEAD"]); + yield* git(cwd, ["checkout", "-b", "feature/elsewhere", initialBranch]); + yield* writeTextFile(cwd, "elsewhere.txt", "elsewhere\n"); + yield* git(cwd, ["add", "elsewhere.txt"]); + yield* git(cwd, ["commit", "-m", "elsewhere change"]); + const elsewhereSha = yield* git(cwd, ["rev-parse", "HEAD"]); + yield* git(cwd, ["checkout", "feature/merge-preview"]); + yield* writeTextFile(cwd, "README.md", "# dirty tree\n"); + + const elsewhere = yield* driver.getReviewDiffPreview({ cwd, commitSha: elsewhereSha }); + assert.deepStrictEqual( + elsewhere.sources + .find((candidate) => candidate.kind === "commit") + ?.files?.map((file) => file.path), + ["elsewhere.txt"], + ); + + const preview = yield* driver.getReviewDiffPreview({ + cwd, + baseRef: initialBranch, + commitSha: mergeSha, + }); + const source = preview.sources.find((candidate) => candidate.kind === "commit")!; + assert.strictEqual(source.baseRef, firstParent); + assert.strictEqual(source.headRef, mergeSha); + assert.deepStrictEqual( + source.files?.map((file) => file.path), + ["README.md"], + ); + assert.include(source.diff, "+# side commit"); + assert.notInclude(source.diff, "dirty tree"); + assert.notInclude(source.diff, "feature.txt"); + + const patch = yield* driver.getReviewDiffPreview({ + cwd, + baseRef: initialBranch, + commitSha: mergeSha, + file: { path: "README.md", previousPath: null, sourceKind: "commit" }, + }); + assert.include( + patch.sources.find((candidate) => candidate.kind === "commit")!.diff, + "+# side commit", + ); + const contents = yield* driver.getReviewDiffFileContents( + makeReviewDiffFileContentsInput(cwd, { + sourceKind: "commit", + baseRef: source.baseRef, + headRef: source.headRef, + }), + ); + assert.deepStrictEqual(contents, { + oldContents: "# test\n", + newContents: "# side commit\n", + }); + }), + ); + it.effect("loads repository-relative files from a nested project directory", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 3a7c99fbc3d31..c5bdf3d068ef9 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -26,6 +26,7 @@ import { GitCommandError, type GitCommandFailureReason, T3_PROJECT_FILE_NAME, + type ReviewBranchCommitsInput, type ReviewDiffFileContentsInput, type ReviewDiffPreviewInput, type ReviewDiffFileStat, @@ -74,6 +75,9 @@ const REVIEW_METADATA_MAX_OUTPUT_BYTES = 16 * 1024 * 1024; // Temporary-index git add scales poorly (50k files took ~30 s); report incomplete totals above this cap. const REVIEW_UNTRACKED_MAX_FILES = 5_000; const REVIEW_DIFF_FILE_MAX_OUTPUT_BYTES = 1024 * 1024; +const REVIEW_BRANCH_COMMIT_LIMIT = 100; +const REVIEW_BRANCH_SUBJECT_LIMIT = 300; +const REVIEW_BRANCH_COMMIT_MAX_OUTPUT_BYTES = 128 * 1024; // Client patch parsers require a/ and b/ prefixes; override user diff prefix settings. export const PATCH_RENDER_PREFIX_ARGS = ["--src-prefix=a/", "--dst-prefix=b/"] as const; const REVIEW_DIFF_ARGS = [ @@ -3115,6 +3119,141 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return { baseRef, insertions, deletions }; }, Effect.scoped); + const reviewCommitError = (cwd: string, detail: string) => + new GitCommandError({ + operation: "GitVcsDriver.reviewCommit", + command: "git cat-file", + cwd, + detail, + }); + + const resolveReviewCommit = Effect.fn("resolveReviewCommit")(function* ( + cwd: string, + sha: string, + ) { + if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(sha)) { + return yield* reviewCommitError(cwd, "Selected commit is invalid or no longer available."); + } + const present = yield* executeGit( + "GitVcsDriver.reviewCommit.present", + cwd, + ["cat-file", "-e", `${sha}^{commit}`], + { allowNonZeroExit: true, env: { GIT_NO_LAZY_FETCH: "1" } }, + ); + if (present.exitCode !== 0) { + return yield* reviewCommitError(cwd, "Selected commit is invalid or no longer available."); + } + // The raw object keeps the parents a shallow clone grafts away, so a boundary is not a root. + const object = yield* runGitStdout("GitVcsDriver.reviewCommit.parents", cwd, [ + "cat-file", + "commit", + sha, + ]); + const secondLine = object.split("\n", 2)[1]; + const firstParent = secondLine?.startsWith("parent ") ? secondLine.slice(7) : undefined; + if (firstParent !== undefined) { + const parent = yield* executeGit( + "GitVcsDriver.reviewCommit.parent", + cwd, + ["cat-file", "-e", `${firstParent}^{commit}`], + { allowNonZeroExit: true, env: { GIT_NO_LAZY_FETCH: "1" } }, + ); + if (parent.exitCode !== 0) { + return yield* reviewCommitError(cwd, "Selected commit's parent is not available locally."); + } + } + return { sha: sha.toLowerCase(), parent: firstParent ?? (yield* readEmptyTreeHash(cwd)) }; + }); + + const readReviewCommitMessage = Effect.fn("GitVcsDriver.readReviewCommitMessage")(function* ( + cwd: string, + sha: string, + ) { + const result = yield* executeGit( + "GitVcsDriver.readReviewCommitMessage", + cwd, + ["show", "-s", "--no-notes", "--no-show-signature", "--format=%B", sha], + { maxOutputBytes: 8_192, appendTruncationMarker: true }, + ); + const endOfSubject = result.stdout.indexOf("\n"); + return { + subject: result.stdout.slice(0, endOfSubject < 0 ? undefined : endOfSubject).slice(0, 300), + }; + }); + + const getReviewBranchCommits = Effect.fn("getReviewBranchCommits")(function* ( + input: ReviewBranchCommitsInput, + ) { + const repository = yield* resolveRepositoryPathsUncached(input.cwd); + if (!repository?.worktreeRoot) return { commits: [], truncated: false }; + const cwd = repository.worktreeRoot; + const head = yield* executeGit( + "GitVcsDriver.getReviewBranchCommits.head", + cwd, + ["rev-parse", "--verify", "--quiet", "HEAD"], + { allowNonZeroExit: true }, + ); + if (head.exitCode !== 0) { + if (head.exitCode === 1 && head.stderr.trim() === "") { + return { commits: [], truncated: false }; + } + return yield* reviewCommitError(cwd, "Could not resolve the current branch commit."); + } + const { mergeBase } = yield* resolveReviewMergeBase( + cwd, + repository.currentBranch, + input.baseRef, + ); + const result = yield* executeGit( + "GitVcsDriver.getReviewBranchCommits", + cwd, + [ + "log", + "-z", + "--no-notes", + "--no-show-signature", + "--format=%H%x00%s%x00%cI", + `--max-count=${REVIEW_BRANCH_COMMIT_LIMIT + 1}`, + `${mergeBase}..HEAD`, + ], + { + maxOutputBytes: REVIEW_BRANCH_COMMIT_MAX_OUTPUT_BYTES, + appendTruncationMarker: true, + }, + ); + if (!result.stdoutTruncated && result.stdout.length > 0 && !result.stdout.endsWith("\0")) { + return yield* reviewCommitError(cwd, "Could not read branch commit metadata."); + } + const fields = result.stdout.split("\0"); + const completeFieldCount = fields.length - 1; + const commits: Array<{ sha: string; subject: string; committedAt: string }> = []; + for ( + let index = 0; + index + 2 < completeFieldCount && commits.length <= REVIEW_BRANCH_COMMIT_LIMIT; + index += 3 + ) { + const sha = fields[index]; + const subject = fields[index + 1]; + const committedAt = fields[index + 2]; + if ( + !sha || + subject === undefined || + !committedAt || + !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(sha) + ) { + return yield* reviewCommitError(cwd, "Could not read branch commit metadata."); + } + commits.push({ sha, subject: subject.slice(0, REVIEW_BRANCH_SUBJECT_LIMIT), committedAt }); + } + if (result.stdoutTruncated && commits.length === 0) { + return yield* reviewCommitError(cwd, "Branch commit metadata exceeds the response limit."); + } + return { + commits: commits.slice(0, REVIEW_BRANCH_COMMIT_LIMIT), + truncated: result.stdoutTruncated || commits.length > REVIEW_BRANCH_COMMIT_LIMIT, + }; + }); + const getReviewDiffPreview = Effect.fn("getReviewDiffPreview")(function* ( input: ReviewDiffPreviewInput, ) { @@ -3141,6 +3280,64 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* } const cwd = repository.worktreeRoot; + const hashDiff = (diff: string, files: ReadonlyArray) => + crypto.digest("SHA-256", new TextEncoder().encode(JSON.stringify([diff, files]))).pipe( + Effect.map(Hex.encode), + Effect.mapError( + (cause) => + new GitCommandError({ + operation: "GitVcsDriver.getReviewDiffPreview.hash", + command: "crypto.digest SHA-256", + cwd, + detail: "Failed to hash review diff.", + cause, + }), + ), + ); + if (input.commitSha !== undefined || input.file?.sourceKind === "commit") { + if (!input.commitSha || (input.file && input.file.sourceKind !== "commit")) { + return yield* reviewCommitError(cwd, "Selected commit request is invalid."); + } + const commit = yield* resolveReviewCommit(cwd, input.commitSha); + const { subject } = yield* readReviewCommitMessage(cwd, commit.sha); + const diffArgs = [ + ...REVIEW_DIFF_ARGS, + ...(input.ignoreWhitespace ? ["--ignore-all-space"] : []), + ]; + const stat = yield* executeGit( + "GitVcsDriver.getReviewDiffPreview.commitStat", + cwd, + [...diffArgs, "--numstat", "-z", commit.parent, commit.sha, "--", ...pathArgs], + { maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, + ); + const files = parseReviewNumstat(stat.stdout); + const patch = yield* executeGit( + "GitVcsDriver.getReviewDiffPreview.commitPatch", + cwd, + [...diffArgs, "--patch", commit.parent, commit.sha, "--", ...pathArgs], + { maxOutputBytes: patchLimit, appendTruncationMarker: true }, + ); + const diffHash = yield* hashDiff(patch.stdout, files); + return { + cwd: input.cwd, + generatedAt: yield* DateTime.now, + sources: [ + { + id: commit.sha, + kind: "commit" as const, + title: `Commit ${commit.sha.slice(0, 7)}`, + ...(subject.trim() ? { commitSubject: subject.trim() } : {}), + baseRef: commit.parent, + headRef: commit.sha, + diff: patch.stdout, + files, + diffHash, + truncated: patch.stdoutTruncated, + }, + ], + }; + } + const dirtyRef = input.file?.sourceKind === "branch-range" ? null : "HEAD"; const review = input.file?.sourceKind === "working-tree" @@ -3220,20 +3417,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const baseFiles = baseResult.files; const dirtyDiff = dirtyTrackedResult.stdout; const baseDiff = baseResult.stdout; - const hashDiff = (diff: string, files: ReadonlyArray) => - crypto.digest("SHA-256", new TextEncoder().encode(JSON.stringify([diff, files]))).pipe( - Effect.map(Hex.encode), - Effect.mapError( - (cause) => - new GitCommandError({ - operation: "GitVcsDriver.getReviewDiffPreview.hash", - command: "crypto.digest SHA-256", - cwd, - detail: "Failed to hash review diff.", - cause, - }), - ), - ); const [dirtyDiffHash, baseDiffHash] = yield* Effect.all([ hashDiff(dirtyDiff, dirtyFiles ?? []), hashDiff(baseDiff, baseFiles ?? []), @@ -3385,6 +3568,30 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* if (repositoryRoot.length === 0) { return yield* reviewDiffFileError(input, "Could not resolve the Git repository root."); } + if (input.sourceKind === "commit") { + if (!input.headRef) { + return yield* reviewDiffFileError(input, "Selected commit is no longer available."); + } + const commit = yield* resolveReviewCommit(input.cwd, input.headRef); + if (input.baseRef !== commit.parent) { + return yield* reviewDiffFileError( + input, + "Selected commit changed. Refresh the comparison.", + ); + } + const [oldContents, newContents] = yield* Effect.all( + [ + input.changeType === "new" + ? Effect.succeed("") + : readReviewFileAtRevision(input, commit.parent, input.oldPath), + input.changeType === "deleted" + ? Effect.succeed("") + : readReviewFileAtRevision(input, commit.sha, input.newPath), + ], + { concurrency: 2 }, + ); + return { oldContents, newContents }; + } const oldRevision = input.sourceKind === "working-tree" ? (input.baseRef ?? "HEAD") @@ -4649,6 +4856,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return yield* withListRefsInvalidation(cwd, pullCurrentBranch(cwd)); }), readRangeContext, + getReviewBranchCommits, getReviewDiffPreview, getReviewDiffFileContents, readConfigValue, diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 32737aa771df6..befad768da3e5 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -3001,6 +3001,7 @@ export const layerWsRpc = ( gitWorkflow.switchRef(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), [WS_METHODS.vcsInit]: (input) => vcsProvisioning.initRepository(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), + [WS_METHODS.reviewGetBranchCommits]: (input) => review.getBranchCommits(input), [WS_METHODS.reviewGetDiffPreview]: (input) => review.getDiffPreview(input), [WS_METHODS.reviewGetDiffFileContents]: (input) => review.getDiffFileContents(input), [WS_METHODS.terminalOpen]: (input) => terminalManager.open(input), diff --git a/apps/web/src/browser/browserLinkTarget.ts b/apps/web/src/browser/browserLinkTarget.ts index 50ff1a4e351fc..f1c4e65a99913 100644 --- a/apps/web/src/browser/browserLinkTarget.ts +++ b/apps/web/src/browser/browserLinkTarget.ts @@ -1,6 +1,11 @@ -import type { BrowserLinkTarget, ScopedThreadRef } from "@t3tools/contracts"; +import { + AuthPreviewOperateScope, + type BrowserLinkTarget, + type ScopedThreadRef, +} from "@t3tools/contracts"; import { ensureClientSettingsHydrated, getClientSettings } from "~/hooks/useSettings"; +import { readEnvironmentScope } from "~/state/session"; import { isPreviewAvailableFor } from "./previewRuntime"; export interface ResolveLinkTargetInput { @@ -38,5 +43,9 @@ export async function resolveBrowserLinkTargetPreference(): Promise { const explicitThreadRef = explicitDiffOpenRef.current; explicitDiffOpenRef.current = null; - if (diffOpen && activeThreadRef && explicitThreadRef !== activeThreadRef) { + if ( + diffOpen && + activeThreadRef && + explicitThreadRef !== activeThreadRef && + !useDiffPanelStore.getState().consumeKeepSelectionOnOpen(activeThreadRef) + ) { useDiffPanelStore.getState().selectGitScope(activeThreadRef, "branch"); } }, [activeThreadRef, diffOpen]); diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index ddce50db3cfe3..ef95c24d578a2 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -6,7 +6,7 @@ import { squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors"; -import type { ScopedThreadRef, RunId } from "@t3tools/contracts"; +import type { ReviewBranchCommitsResult, ScopedThreadRef, RunId } from "@t3tools/contracts"; import { ArrowRightIcon, CheckIcon, @@ -20,7 +20,7 @@ import { } from "lucide-react"; import { ChevronDown, ChevronRight, ChevronsDownUp, ChevronsUpDown } from "lucide"; import * as Schema from "effect/Schema"; -import { useEffect, useRef, useState } from "react"; +import { type MouseEvent, useEffect, useRef, useState } from "react"; import { useCodeViewFileReveal } from "./diffs/useCodeViewFileReveal"; import { useFilesystemReadAccess } from "~/state/filesystem"; import { useOpenInPreferredEditor } from "../editorPreferences"; @@ -33,6 +33,7 @@ import { revisionedQuery } from "~/state/revisionedQuery"; import { cn } from "~/lib/utils"; import { resolveToolCallDiffTarget, + selectThreadBranchBaseRef, selectThreadDiffPanelSelection, useDiffPanelSessionStore, useDiffPanelStore, @@ -60,7 +61,7 @@ import { useQuietThreadVisibleTurnItems, } from "../state/entities"; import { useClientSettings, updateClientSettings } from "../hooks/useSettings"; -import { formatShortTimestamp } from "../timestampFormat"; +import { formatRelativeTimeLabel, formatShortTimestamp } from "../timestampFormat"; import { DiffFilePathCopyButton } from "./DiffFilePathCopyButton"; import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell"; import { DiffStatLabel } from "./chat/DiffStatLabel"; @@ -83,6 +84,7 @@ import { import { DropdownMenu, DropdownMenuContent, + DropdownMenuItem, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSub, @@ -103,6 +105,8 @@ import { useReviewFilePatches } from "./diffs/useReviewFilePatches"; import { DiffFileLoadingBoundary } from "./diffs/DiffFileLoadingBoundary"; import { DiffFileStatus } from "./diffs/DiffFileStatus"; import { useThreadRouteRef } from "../hooks/useThreadRouteTarget"; +import { projectCommitUrl } from "@t3tools/client-runtime/change-request-links"; +import { useOpenLink } from "../browser/useOpenLink"; type DiffThemeType = "light" | "dark"; const AUTOMATIC_BASE_REF = "__automatic_base_ref__"; @@ -223,6 +227,8 @@ export default function DiffPanel({ ); const [hideTestFiles, setHideTestFiles] = useHideTestFiles(); const [baseRefQuery, setBaseRefQuery] = useState(""); + // The open commit menu keeps the list it opened with, so rows do not move under the pointer. + const [openCommitMenu, setOpenCommitMenu] = useState(null); const [codeViewRevision, setCodeViewRevision] = useState(0); const routeThreadRef = useThreadRouteRef(); @@ -263,8 +269,14 @@ export default function DiffPanel({ const diffSelection = useDiffPanelStore((state) => selectThreadDiffPanelSelection(state.byThreadKey, routeThreadRef), ); + const rememberedBaseRef = useDiffPanelStore((state) => + selectThreadBranchBaseRef(state, routeThreadRef), + ); const toolCallSelection = diffSelection.kind === "tool-call" ? diffSelection : null; - const isGitSelection = diffSelection.kind === "branch" || diffSelection.kind === "unstaged"; + const isGitSelection = + diffSelection.kind === "branch" || + diffSelection.kind === "unstaged" || + diffSelection.kind === "commit"; const toolCallItems = useQuietThreadVisibleTurnItems(toolCallSelection ? routeThreadRef : null); const toolCallDetail = useTurnItemDetail( toolCallSelection && routeThreadRef @@ -294,8 +306,15 @@ export default function DiffPanel({ }, [diffSelection, orderedTurnDiffSummaries, routeThreadRef]); const selectedRunId = diffSelection.kind === "turn" ? diffSelection.turnId : null; - const selectedGitScope = diffSelection.kind === "unstaged" ? "unstaged" : "branch"; - const selectedBaseRef = diffSelection.kind === "branch" ? diffSelection.baseRef : null; + const selectedGitScope = + diffSelection.kind === "unstaged" || diffSelection.kind === "commit" + ? diffSelection.kind + : "branch"; + const selectedCommitSha = diffSelection.kind === "commit" ? diffSelection.sha : null; + const selectedBaseRef = + diffSelection.kind === "branch" || diffSelection.kind === "commit" + ? diffSelection.baseRef + : null; const selectedFilePath = diffSelection.kind === "turn" ? diffSelection.filePath : null; const selectedFileRevealRequestId = diffSelection.kind === "turn" ? diffSelection.revealRequestId : 0; @@ -306,31 +325,17 @@ export default function DiffPanel({ orderedTurnDiffSummaries[0]); const selectedCheckpointTurnCount = selectedTurn?.checkpointTurnCount; const latestTurn = orderedTurnDiffSummaries[0]; - const selectedScopeLabel = toolCallSelection - ? "Tool call" - : selectedRunId === null - ? selectedGitScope === "unstaged" - ? "Uncommitted" - : "Changes" - : selectedTurn?.runId === latestTurn?.runId - ? "Latest turn" - : `Turn ${selectedCheckpointTurnCount ?? "?"}`; const reviewSectionId = toolCallSelection ? `tool-call:${toolCallSelection.threadId}:${toolCallSelection.itemId}` : selectedTurn ? `turn:${selectedTurn.runId}` - : selectedGitScope; + : selectedCommitSha !== null + ? `commit:${selectedCommitSha}` + : selectedGitScope; const collapseScopeKey = routeThreadRef ? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}:${reviewSectionId}` : null; const codeViewMountKey = `${collapseScopeKey ?? reviewSectionId}:${codeViewRevision}`; - const reviewSectionTitle = toolCallSelection - ? "Tool call" - : selectedTurn - ? `Turn ${selectedCheckpointTurnCount ?? "?"}` - : selectedGitScope === "unstaged" - ? "Uncommitted" - : "Changes"; const selectedCheckpointRange = typeof selectedCheckpointTurnCount === "number" ? { @@ -354,6 +359,7 @@ export default function DiffPanel({ ? { cwd: activeCwd, ...(selectedBaseRef ? { baseRef: selectedBaseRef } : {}), + ...(selectedCommitSha !== null ? { commitSha: selectedCommitSha } : {}), ignoreWhitespace: diffIgnoreWhitespace, } : undefined; @@ -372,13 +378,69 @@ export default function DiffPanel({ ) : null, ); + const branchCommitsQuery = useEnvironmentQuery( + visible && isGitRepo && canReadFiles && activeThread && activeCwd + ? reviewEnvironment.branchCommits({ + environmentId: activeThread.environmentId, + input: { + cwd: activeCwd, + ...(rememberedBaseRef ? { baseRef: rememberedBaseRef } : {}), + }, + }) + : null, + ); + const branchCommits = openCommitMenu ?? branchCommitsQuery.data; const activeThreadRefreshKey = routeThreadRef ? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}` : null; const selectedGitSource = branchDiffPreview.data?.sources.find( - (source) => source.kind === (selectedGitScope === "unstaged" ? "working-tree" : "branch-range"), + (source) => + source.kind === + (selectedGitScope === "unstaged" + ? "working-tree" + : selectedGitScope === "commit" + ? "commit" + : "branch-range"), ); + const selectedCommitSubject = + selectedCommitSha !== null && selectedGitSource?.headRef === selectedCommitSha + ? selectedGitSource.commitSubject + : undefined; + const selectedGitScopeLabel = + selectedCommitSha !== null + ? (selectedCommitSubject ?? `Commit ${selectedCommitSha.slice(0, 7)}`) + : selectedGitScope === "unstaged" + ? "Uncommitted" + : "Changes"; + const selectedScopeLabel = toolCallSelection + ? "Tool call" + : selectedRunId === null + ? selectedCommitSha !== null + ? (selectedCommitSubject ?? "Commit") + : selectedGitScopeLabel + : selectedTurn?.runId === latestTurn?.runId + ? "Latest turn" + : `Turn ${selectedCheckpointTurnCount ?? "?"}`; + const reviewSectionTitle = toolCallSelection + ? "Tool call" + : selectedTurn + ? `Turn ${selectedCheckpointTurnCount ?? "?"}` + : selectedGitScopeLabel; + const headerCommitSha = selectedRunId === null ? selectedCommitSha : null; + const selectedCommitUrl = + headerCommitSha !== null + ? projectCommitUrl(activeProject?.repositoryIdentity, headerCommitSha) + : null; + const openLink = useOpenLink(routeThreadRef); + // A SHA link goes to the code host; it must not route back into this pane's commit selection. + const openCommitUrl = (event: MouseEvent, url: string) => { + event.stopPropagation(); + if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button === 1) + return; + event.preventDefault(); + void openLink(url, { event }); + }; const refreshPreviewQuery = branchDiffPreview.refresh; const refreshDiffFromUserAction = refreshPreviewQuery; @@ -512,7 +574,8 @@ export default function DiffPanel({ environmentId: activeThread?.environmentId, cwd: branchDiffPreview.data?.cwd, source: lazySource, - baseRef: lazySource?.baseRef ?? selectedBaseRef, + baseRef: + selectedCommitSha !== null ? selectedBaseRef : (lazySource?.baseRef ?? selectedBaseRef), ignoreWhitespace: diffIgnoreWhitespace, theme: resolvedTheme, previewInput: branchDiffPreviewInput, @@ -693,16 +756,23 @@ export default function DiffPanel({ useDiffPanelStore.getState().selectBranchBaseRef(routeThreadRef, baseRef); }; const selectedTurnValue = selectedTurn ? `turn:${selectedTurn.runId}` : ""; + const selectedCommitValue = selectedCommitSha !== null ? `commit:${selectedCommitSha}` : ""; const selectedScopeValue = toolCallSelection ? "" : selectedRunId === null - ? selectedGitScope + ? selectedCommitValue || selectedGitScope : selectedTurn?.runId === latestTurn?.runId ? "latest" : selectedTurnValue; const selectScopeValue = (value: string) => { if (value === "unstaged" || value === "branch") { selectGitScope(value); + } else if (value === selectedCommitValue) { + selectGitScope("branch"); + } else if (value.startsWith("commit:")) { + if (routeThreadRef) { + useDiffPanelStore.getState().selectCommit(routeThreadRef, value.slice("commit:".length)); + } } else if (value === "latest") { if (latestTurn) selectTurn(latestTurn.runId); } else { @@ -717,13 +787,37 @@ export default function DiffPanel({ } - className="max-w-full" + className={cn("max-w-full", headerCommitSha !== null && "min-w-0 shrink")} aria-label={`Diff scope: ${selectedScopeLabel}`} data-workspace-focus-default > {selectedScopeLabel} + {headerCommitSha !== null ? ( + selectedCommitUrl ? ( + + openCommitUrl(event, selectedCommitUrl)} + /> + } + > + {headerCommitSha.slice(0, 7)} + + {selectedCommitUrl} + + ) : ( + + {headerCommitSha.slice(0, 7)} + + ) + ) : null} @@ -760,6 +854,99 @@ export default function DiffPanel({ + { + setOpenCommitMenu(open ? (branchCommitsQuery.data ?? null) : null); + if (!open) return; + // The menu keeps the list it opened with; the refreshed one shows next time. + branchCommitsQuery.refresh(); + }} + > + Commits + + + {branchCommits?.commits.map((commit) => { + const commitUrl = projectCommitUrl( + activeProject?.repositoryIdentity, + commit.sha, + ); + return ( +
      + + + } + > + + {commit.subject} + + {formatRelativeTimeLabel(commit.committedAt)} + + + + + {commit.subject} + + + {commitUrl ? ( + + } + onClick={(event) => openCommitUrl(event, commitUrl)} + > + + {commit.sha.slice(0, 7)} + + + ) : ( + + {commit.sha.slice(0, 7)} + + )} +
      + ); + })} +
      + {branchCommitsQuery.error ? ( + {branchCommitsQuery.error} + ) : !canReadFiles ? ( + + {fileAccess.isPending + ? "Checking file access..." + : (fileAccess.error ?? "This connection cannot read local diffs.")} + + ) : branchCommits === null ? ( + Loading commits... + ) : branchCommits.commits.length === 0 ? ( + No commits on this branch. + ) : branchCommits.truncated ? ( + + {`Showing latest ${branchCommits.commits.length} commits`} + + ) : null} +
      +
      {isGitSelection && selectedGitScope === "branch" && selectedGitSource?.baseRef && ( @@ -894,7 +1081,12 @@ export default function DiffPanel({
      )}
      -
      +
      {codeViewFiles.length > 0 || (isGitSelection && selectedGitSource?.files?.length) ? ( ) : ( diff --git a/apps/web/src/components/desktop/DesktopWebLinkCoordinator.browser.test.tsx b/apps/web/src/components/desktop/DesktopWebLinkCoordinator.browser.test.tsx index a2a0f874d6e90..31ad2028c5f51 100644 --- a/apps/web/src/components/desktop/DesktopWebLinkCoordinator.browser.test.tsx +++ b/apps/web/src/components/desktop/DesktopWebLinkCoordinator.browser.test.tsx @@ -1,11 +1,16 @@ -import { EnvironmentId, ProjectId } from "@t3tools/contracts"; -import type { Atom } from "effect/reactivity"; +import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; +import { AsyncResult, type Atom } from "effect/reactivity"; import { expect, it, vi } from "vite-plus/test"; import { act, render, stubGlobal } from "../../../test/render"; const state = vi.hoisted(() => ({ - projects: [] as never[], + projects: [] as EnvironmentProject[], + routeParams: {} as Record, + preview: vi.fn(), + openLink: vi.fn(async () => undefined), navigate: vi.fn(async (): Promise => undefined), openScratchProject: vi.fn(async () => null), confirm: vi.fn(async (_message: string) => true), @@ -18,7 +23,10 @@ const state = vi.hoisted(() => ({ vi.mock(import("@tanstack/react-router"), async (original) => ({ ...(await original()), useNavigate: (() => state.navigate) as never, - useRouter: (() => ({ navigate: state.navigate, state: { matches: [] } })) as never, + useRouter: (() => ({ + navigate: state.navigate, + state: { matches: [{ params: state.routeParams }] }, + })) as never, })); vi.mock(import("../../state/environments"), async (original) => ({ ...(await original()), @@ -47,11 +55,17 @@ vi.mock(import("../../state/server"), async (original) => { }); vi.mock(import("../../state/shell"), async (original) => { const { Atom } = await import("effect/reactivity"); - return { ...(await original()), allReachableShellsLiveAtom: Atom.make(false) }; + return { + ...(await original()), + allReachableShellsLiveAtom: Atom.make(false).pipe(Atom.keepAlive), + }; }); vi.mock(import("../../state/entities"), async (original) => ({ ...(await original()), readProjects: () => state.projects, + readThreadShell: (ref: { threadId: string }) => + ref.threadId === "thread" ? ({ projectId: "effect", worktreePath: null } as never) : null, + readProject: () => state.projects[0] ?? null, })); vi.mock(import("../../hooks/useScratchProject"), async (original) => ({ ...(await original()), @@ -61,6 +75,10 @@ vi.mock(import("../../hooks/useScratchProject"), async (original) => ({ })) as never, })); +vi.mock("../../state/use-atom-query-runner", () => ({ + useAtomQueryRunner: () => state.preview, +})); +vi.mock("../../browser/useOpenLink", () => ({ useOpenLink: () => state.openLink })); vi.mock(import("../../confirmDialog"), async (original) => ({ ...(await original()), requestConfirmDialog: state.confirm, @@ -82,6 +100,12 @@ vi.mock(import("../../state/use-atom-command"), async (original) => { import { AppAtomRegistryProvider, appAtomRegistry } from "../../rpc/atomRegistry"; import { allReachableShellsLiveAtom } from "../../state/shell"; +import { selectThreadDiffPanelSelection, useDiffPanelStore } from "../../diffPanelStore"; +import { + selectActiveRightPanel, + selectActiveRightPanelSurface, + useRightPanelStore, +} from "../../rightPanelStore"; import { DesktopWebLinkCoordinator } from "./DesktopWebLinkCoordinator"; const discoverySettled = allReachableShellsLiveAtom as Atom.Writable; @@ -89,6 +113,7 @@ const environmentId = EnvironmentId.make("local"); const projectId = ProjectId.make("effect"); const project = { id: projectId, + workspaceRoot: "/workspace/effect", environmentId, repositoryIdentity: { provider: "github", @@ -100,7 +125,7 @@ const project = { remoteUrl: "https://github.com/Effect-TS/effect.git", }, }, -} as never; +} as EnvironmentProject; const pullRequestUrl = "https://github.com/Effect-TS/effect/pull/9339"; const pullRequestView = { to: "/pull-requests", @@ -123,6 +148,12 @@ function setup() { state.confirm.mockResolvedValue(true); state.localEnvironmentDisabled = false; state.projects = []; + state.routeParams = {}; + state.preview + .mockReset() + .mockResolvedValue(AsyncResult.success({ sources: [{ kind: "commit", headRef: sha }] })); + useDiffPanelStore.setState({ byThreadKey: {}, branchBaseRefByThreadKey: {} }); + useRightPanelStore.setState({ byThreadKey: {}, userActionRevisionByThreadKey: {} }); appAtomRegistry.set(discoverySettled, false); } @@ -172,6 +203,80 @@ it("holds a launch PR link until project discovery settles, then opens the PR vi expect(state.openScratchProject).not.toHaveBeenCalled(); }); +const sha = "a".repeat(40); +const commitUrl = `https://github.com/Effect-TS/effect/pull/9339/commits/${sha}`; +const threadRef = scopeThreadRef(environmentId, ThreadId.make("thread")); + +it.each([ + ["github.com", "pull/9339/commits"], + ["code.example.com:8443", "commit"], +])("opens a %s/%s commit in the active thread's Diff pane after discovery", async (host, path) => { + setup(); + state.routeParams = { environmentId: "local", threadId: "thread" }; + await using _coordinator = await mount(`https://${host}/Effect-TS/effect/${path}/${sha}`); + expect(state.preview).not.toHaveBeenCalled(); + + state.projects = [ + { + ...project, + repositoryIdentity: { + ...project.repositoryIdentity, + canonicalKey: `${host}/effect-ts/effect`, + locator: { + ...project.repositoryIdentity?.locator, + remoteUrl: `https://${host}/Effect-TS/effect.git`, + }, + }, + } as EnvironmentProject, + ]; + await act(async () => appAtomRegistry.set(discoverySettled, true)); + await vi.waitFor(() => { + expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, threadRef)).toBe( + "diff", + ); + }); + expect( + selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, threadRef), + ).toMatchObject({ kind: "commit", sha }); + expect(state.preview).toHaveBeenCalledExactlyOnceWith({ + environmentId, + input: expect.objectContaining({ cwd: "/workspace/effect", commitSha: sha }), + }); + expect(state.navigate).not.toHaveBeenCalled(); + expect(state.openLink).not.toHaveBeenCalled(); +}); + +it("opens a PR commit the workspace lacks in the thread's PR panel", async () => { + setup(); + state.routeParams = { environmentId: "local", threadId: "thread" }; + state.projects = [project]; + state.preview.mockResolvedValueOnce(AsyncResult.success({ sources: [] })); + appAtomRegistry.set(discoverySettled, true); + await using _coordinator = await mount(commitUrl); + await vi.waitFor(() => + expect( + selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, threadRef), + ).toMatchObject({ kind: "pull-request", repository: "effect-ts/effect", number: 9339 }), + ); + expect(useDiffPanelStore.getState().byThreadKey).toEqual({}); + expect(state.openLink).not.toHaveBeenCalled(); +}); + +it("opens a plain commit the workspace lacks like any other delivered link", async () => { + setup(); + state.routeParams = { environmentId: "local", threadId: "thread" }; + state.projects = [project]; + state.preview.mockResolvedValueOnce(AsyncResult.success({ sources: [] })); + appAtomRegistry.set(discoverySettled, true); + const plainCommitUrl = `https://github.com/Effect-TS/effect/commit/${sha}`; + await using _coordinator = await mount(plainCommitUrl); + await vi.waitFor(() => expect(state.openScratchProject).toHaveBeenCalledOnce()); + // Handing it to the OS browser would loop when T3 Code is the default browser. + expect(state.openLink).not.toHaveBeenCalled(); + expect(useDiffPanelStore.getState().byThreadKey).toEqual({}); + expect(useRightPanelStore.getState().byThreadKey).toEqual({}); +}); + it("adds the backend from a pairing link after the user confirms its host", async () => { setup(); await using _coordinator = await mount(pairLink); diff --git a/apps/web/src/components/desktop/DesktopWebLinkCoordinator.tsx b/apps/web/src/components/desktop/DesktopWebLinkCoordinator.tsx index 4ae0b6cdb25b4..ddd892d02bd12 100644 --- a/apps/web/src/components/desktop/DesktopWebLinkCoordinator.tsx +++ b/apps/web/src/components/desktop/DesktopWebLinkCoordinator.tsx @@ -27,6 +27,7 @@ import { selectActiveRightPanelSurface, useRightPanelStore } from "../../rightPa import { appAtomRegistry } from "../../rpc/atomRegistry"; import { resolveThreadRouteTarget } from "../../threadRoutes"; import { assetEnvironment } from "../../state/assets"; +import { readProject, readThreadShell } from "../../state/entities"; import { useEnvironmentHttpBaseUrl, usePrimaryEnvironment } from "../../state/environments"; import { previewEnvironment } from "../../state/preview"; import { allReachableShellsLiveAtom } from "../../state/shell"; @@ -163,25 +164,14 @@ export function DesktopWebLinkCoordinator() { return threadRef; }; - const openLink = useEffectEvent(async (url: string) => { - const pairingUrl = readPairingAppLink(url); - if (pairingUrl !== null) { - await pairFromLink(pairingUrl); - return; - } - const appPath = promptLinkAppPath(url); - if (appPath !== null) { - await router.navigate({ href: appPath }); - return; - } - if (openChangeRequest(externalClick, url)) return; + const openInBrowser = useEffectEvent(async (url: string) => { + const routeParams = router.state.matches.at(-1)?.params ?? {}; const isFile = url.startsWith("file:"); // Only this machine's environment serves files, so fail before starting a thread. if (isFile && httpBaseUrl === null) { reportFailure(url); return; } - const routeParams = router.state.matches.at(-1)?.params ?? {}; const threadRef = threadShowingBrowser( routeParams, @@ -210,15 +200,49 @@ export function DesktopWebLinkCoordinator() { } }); + const openLink = useEffectEvent(async (url: string) => { + const pairingUrl = readPairingAppLink(url); + if (pairingUrl !== null) { + await pairFromLink(pairingUrl); + return; + } + const appPath = promptLinkAppPath(url); + if (appPath !== null) { + await router.navigate({ href: appPath }); + return; + } + const routeParams = router.state.matches.at(-1)?.params ?? {}; + const routeTarget = resolveThreadRouteTarget(routeParams); + const activeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : undefined; + const activeThread = activeThreadRef ? readThreadShell(activeThreadRef) : null; + const activeProject = + activeThread && activeThreadRef + ? readProject(scopeProjectRef(activeThreadRef.environmentId, activeThread.projectId)) + : null; + const commitThreadRef = + activeThread && + sourceControlClients.parseCommitUrl(url, activeProject?.repositoryIdentity?.provider) !== null + ? activeThreadRef + : undefined; + // A commit the thread's workspace lacks continues here, after its lookup. + const openUnavailableCommit = () => { + queueRef.current = queueRef.current.then(() => openInBrowser(url)).catch(() => undefined); + }; + if (openChangeRequest(externalClick, url, commitThreadRef, undefined, openUnavailableCommit)) + return; + await openInBrowser(url); + }); + const receiveLink = useEffectEvent((url: string) => { - // A connected server publishes its config before its project snapshot, so a PR link - // delivered at launch would miss its project and fall through to the browser. Hold PR - // links, and only those, until discovery settles; an ordinary link never waits for it. + // A connected server publishes its config before its project snapshot, so a source control + // link delivered at launch would miss its project and fall through to the browser. Hold + // those links until discovery settles; an ordinary link never waits for it. // Discovery never settles without the local environment, so those links do not wait. const hold = openPullRequestsInApp && !localEnvironmentDisabled && - sourceControlClients.parseChangeRequestUrl(url) !== null + (sourceControlClients.parseChangeRequestUrl(url) !== null || + sourceControlClients.parseCommitUrl(url) !== null) ? projectsSettled() : Promise.resolve(); void hold.then(() => { diff --git a/apps/web/src/components/diffs/useReviewFilePatches.ts b/apps/web/src/components/diffs/useReviewFilePatches.ts index b683e13a8f6ee..69dafc2dd7823 100644 --- a/apps/web/src/components/diffs/useReviewFilePatches.ts +++ b/apps/web/src/components/diffs/useReviewFilePatches.ts @@ -193,6 +193,7 @@ function reviewFileQueries({ request: { cwd, ...(baseRef ? { baseRef } : {}), + ...(source.kind === "commit" ? { commitSha: source.id } : {}), ignoreWhitespace, file: { path: file.path, diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index dc494caf5344d..aabfd0300eda5 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -923,7 +923,7 @@ export const SETTINGS_SEARCH_ITEMS = [ title: "Open pull requests in T3 Code", to: "/settings/diffs", searchTerms: [ - `pr links ${SOURCE_CONTROL_HOST_LABELS} browser external click default pull request view panel`, + `pr commit links ${SOURCE_CONTROL_HOST_LABELS} browser external click default pull request view panel`, ], }, { diff --git a/apps/web/src/diffPanelStore.ts b/apps/web/src/diffPanelStore.ts index 11d96a3909ce7..6bd7eb0e01bdd 100644 --- a/apps/web/src/diffPanelStore.ts +++ b/apps/web/src/diffPanelStore.ts @@ -17,6 +17,7 @@ export type DiffPanelSelection = | ({ kind: "tool-call" } & ToolCallDiffTarget) | { kind: "branch"; baseRef: string | null } | { kind: "unstaged" } + | { kind: "commit"; sha: string; baseRef: string | null } | { kind: "turn"; turnId: RunId; filePath: string | null; revealRequestId: number }; const DEFAULT_SELECTION: DiffPanelSelection = { kind: "branch", baseRef: null }; @@ -24,10 +25,14 @@ const DEFAULT_SELECTION: DiffPanelSelection = { kind: "branch", baseRef: null }; interface DiffPanelStoreState { byThreadKey: Record; branchBaseRefByThreadKey: Record; + /** A link that selected a commit before opening the closed pane; opening keeps that selection. */ + keepSelectionOnOpenThreadKey: string | null; selectGitScope: (ref: ScopedThreadRef, scope: "branch" | "unstaged") => void; selectBranchBaseRef: (ref: ScopedThreadRef, baseRef: string | null) => void; selectToolCall: (ref: ScopedThreadRef, target: ToolCallDiffTarget) => void; selectTurn: (ref: ScopedThreadRef, turnId: RunId, filePath?: string) => void; + selectCommit: (ref: ScopedThreadRef, sha: string, keepOnOpen?: boolean) => void; + consumeKeepSelectionOnOpen: (ref: ScopedThreadRef) => boolean; reconcileTurnSelection: (ref: ScopedThreadRef, availableTurnIds: ReadonlyArray) => void; removeThread: (ref: ScopedThreadRef) => void; } @@ -37,19 +42,27 @@ function normalizeBaseRef(baseRef: string | null): string | null { return normalized ? normalized : null; } +function branchBaseRef( + state: Pick, + threadKey: string, +): string | null { + const previous = state.byThreadKey[threadKey]; + return previous?.kind === "branch" || previous?.kind === "commit" + ? previous.baseRef + : (state.branchBaseRefByThreadKey[threadKey] ?? null); +} + export const useDiffPanelStore = create()( persist( - (set) => ({ + (set, get) => ({ byThreadKey: {}, branchBaseRefByThreadKey: {}, + keepSelectionOnOpenThreadKey: null, selectGitScope: (ref, scope) => set((state) => { const threadKey = scopedThreadKey(ref); const previous = state.byThreadKey[threadKey]; - const previousBaseRef = - previous?.kind === "branch" - ? previous.baseRef - : (state.branchBaseRefByThreadKey[threadKey] ?? null); + const previousBaseRef = branchBaseRef(state, threadKey); return { byThreadKey: { ...state.byThreadKey, @@ -59,7 +72,7 @@ export const useDiffPanelStore = create()( : { kind: "unstaged" }, }, branchBaseRefByThreadKey: - previous?.kind === "branch" + previous?.kind === "branch" || previous?.kind === "commit" ? { ...state.branchBaseRefByThreadKey, [threadKey]: previous.baseRef } : state.branchBaseRefByThreadKey, }; @@ -102,6 +115,26 @@ export const useDiffPanelStore = create()( }, }; }), + selectCommit: (ref, sha, keepOnOpen = false) => + set((state) => { + const threadKey = scopedThreadKey(ref); + const baseRef = branchBaseRef(state, threadKey); + return { + byThreadKey: { + ...state.byThreadKey, + [threadKey]: { kind: "commit", sha, baseRef }, + }, + branchBaseRefByThreadKey: { ...state.branchBaseRefByThreadKey, [threadKey]: baseRef }, + keepSelectionOnOpenThreadKey: keepOnOpen + ? threadKey + : state.keepSelectionOnOpenThreadKey, + }; + }), + consumeKeepSelectionOnOpen: (ref) => { + if (get().keepSelectionOnOpenThreadKey !== scopedThreadKey(ref)) return false; + set({ keepSelectionOnOpenThreadKey: null }); + return true; + }, reconcileTurnSelection: (ref, availableTurnIds) => set((state) => { const threadKey = scopedThreadKey(ref); @@ -178,6 +211,13 @@ export function selectThreadDiffPanelSelection( return byThreadKey[scopedThreadKey(ref)] ?? DEFAULT_SELECTION; } +export function selectThreadBranchBaseRef( + state: Pick, + ref: ScopedThreadRef | null | undefined, +): string | null { + return ref ? branchBaseRef(state, scopedThreadKey(ref)) : null; +} + export function resolveToolCallDiffTarget( target: ToolCallDiffTarget, items: ReadonlyArray, diff --git a/apps/web/src/lib/openPullRequestLink.browser.test.tsx b/apps/web/src/lib/openPullRequestLink.browser.test.tsx new file mode 100644 index 0000000000000..a93f32a8902f7 --- /dev/null +++ b/apps/web/src/lib/openPullRequestLink.browser.test.tsx @@ -0,0 +1,160 @@ +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment"; +import { AsyncResult } from "effect/reactivity"; +import { expect, it, vi } from "vite-plus/test"; +import { page } from "vite-plus/test/browser"; + +import { act, render, stubGlobal } from "../../test/render"; + +const state = vi.hoisted(() => ({ preview: vi.fn(), openLink: vi.fn() })); +vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => state.preview })); +vi.mock("../browser/useOpenLink", () => ({ useOpenLink: () => state.openLink })); +vi.mock(import("../state/environments"), async (original) => ({ + ...(await original()), + usePrimaryEnvironmentId: () => EnvironmentId.make("local"), +})); +vi.mock("../state/entities", async (original) => ({ + ...(await original()), + readProjects: () => [project], + useProjects: () => [project], + readProject: () => project, + readThreadShell: () => ({ projectId: "project", worktreePath: null }), +})); +vi.mock("../state/server", async (original) => { + const { Atom } = await import("effect/reactivity"); + return { + ...(await original()), + environmentServerConfigsAtom: Atom.make(new Map([["local", {}]])), + }; +}); + +import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings"; +import { __setClientSettingsForTests } from "../hooks/useSettings"; +import { ToastProvider } from "../components/ui/toast"; +import { AppAtomRegistryProvider } from "../rpc/atomRegistry"; +import { useRightPanelStore } from "../rightPanelStore"; +import { useDiffPanelStore } from "../diffPanelStore"; +import { useOpenChangeRequestLink } from "./openPullRequestLink"; + +const environmentId = EnvironmentId.make("local"); +const threadRef = scopeThreadRef(environmentId, ThreadId.make("thread")); +const project = { + id: "project", + environmentId, + workspaceRoot: "/repo", + repositoryIdentity: { + provider: "github", + canonicalKey: "github.com/effect-ts/effect", + displayName: "Effect-TS/effect", + locator: { + source: "git-remote", + remoteName: "origin", + remoteUrl: "https://github.com/Effect-TS/effect.git", + }, + }, +}; +const commitUrl = `https://github.com/Effect-TS/effect/commit/${"a".repeat(40)}?plain=1#diff-original`; +const pullRequestCommitUrl = `https://github.com/Effect-TS/effect/pull/1/commits/${"a".repeat(40)}`; + +function CommitLink({ url = commitUrl }: { url?: string }) { + const open = useOpenChangeRequestLink(threadRef); + return ( + open(event, url)}> + Commit + + ); +} + +function setup() { + state.preview.mockReset().mockResolvedValue(AsyncResult.success({ sources: [] })); + state.openLink.mockReset().mockResolvedValue(undefined); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + pullRequestLinksOpenInApp: true, + browserLinkTarget: "system", + }); + useDiffPanelStore.setState({ + byThreadKey: {}, + branchBaseRefByThreadKey: {}, + keepSelectionOnOpenThreadKey: null, + }); + useRightPanelStore.setState({ byThreadKey: {}, userActionRevisionByThreadKey: {} }); +} + +it.each([ + ["shiftKey", commitUrl], + ["altKey", commitUrl], + ["shiftKey", pullRequestCommitUrl], +] as const)("keeps %s clicks on %s native", async (modifier, url) => { + setup(); + await using screen = await render( + + + , + ); + const event = new MouseEvent("click", { bubbles: true, cancelable: true, [modifier]: true }); + const defaults: boolean[] = []; + screen.container.addEventListener( + "click", + (nativeEvent) => { + defaults.push(nativeEvent.defaultPrevented); + nativeEvent.preventDefault(); + }, + { once: true }, + ); + await act(() => screen.getByRole("link", { name: "Commit" }).element().dispatchEvent(event)); + expect(defaults).toEqual([false]); + expect(state.preview).not.toHaveBeenCalled(); + expect(useRightPanelStore.getState().byThreadKey).toEqual({}); +}); + +it.each(["system", "app"] as const)( + "offers the original unavailable commit URL when web popups are blocked (%s)", + async (browserLinkTarget) => { + setup(); + // Without preview access, the "app" preference opens a popup too. + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + pullRequestLinksOpenInApp: true, + browserLinkTarget, + }); + using _desktop = stubGlobal("desktopBridge", undefined); + await using screen = await render( + + + + + , + ); + using open = vi.spyOn(window, "open").mockReturnValue(null); + await screen.getByRole("link", { name: "Commit" }).click(); + await expect + .element(page.getByRole("button", { name: "Open link", exact: true })) + .toBeVisible(); + expect(open).not.toHaveBeenCalled(); + await page.getByRole("button", { name: "Open link", exact: true }).click(); + expect(open).toHaveBeenCalledExactlyOnceWith(commitUrl, "_blank", "noopener,noreferrer"); + expect(state.openLink).not.toHaveBeenCalled(); + }, +); + +it("opens an available commit in the closed Diff pane without the pane resetting it", async () => { + setup(); + const sha = "a".repeat(40); + state.preview.mockResolvedValue( + AsyncResult.success({ sources: [{ kind: "commit", headRef: sha }] }), + ); + await using screen = await render( + + + , + ); + await screen.getByRole("link", { name: "Commit" }).click(); + await vi.waitFor(() => + expect(useDiffPanelStore.getState().byThreadKey).toEqual({ + [scopedThreadKey(threadRef)]: { kind: "commit", sha, baseRef: null }, + }), + ); + // ChatView resets a pane opened without an explicit request to Changes unless this is set. + expect(useDiffPanelStore.getState().consumeKeepSelectionOnOpen(threadRef)).toBe(true); +}); diff --git a/apps/web/src/lib/openPullRequestLink.ts b/apps/web/src/lib/openPullRequestLink.ts index 014728f058a43..31c04b6263e5f 100644 --- a/apps/web/src/lib/openPullRequestLink.ts +++ b/apps/web/src/lib/openPullRequestLink.ts @@ -8,15 +8,25 @@ import { resolvePullRequestPreviewTarget, } from "@t3tools/client-runtime/change-request-links"; +import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; + +import { canOpenLinksInApp } from "../browser/browserLinkTarget"; import { useOpenLink } from "../browser/useOpenLink"; import { useClientSettings } from "../hooks/useSettings"; import { stackedThreadToast, toastManager } from "../components/ui/toast"; -import { useRightPanelStore } from "../rightPanelStore"; +import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore"; +import { + selectThreadBranchBaseRef, + selectThreadDiffPanelSelection, + useDiffPanelStore, +} from "../diffPanelStore"; import { appAtomRegistry } from "../rpc/atomRegistry"; -import { readProjects, useProjects } from "../state/entities"; +import { readProject, readProjects, readThreadShell, useProjects } from "../state/entities"; import { environmentServerConfigsAtom, serverEnvironment } from "../state/server"; import { usePrimaryEnvironmentId } from "../state/environments"; +import { reviewEnvironment } from "../state/review"; +import { useAtomQueryRunner } from "../state/use-atom-query-runner"; export function usePullRequestPreviewTarget(environmentId: EnvironmentId | null, url: string) { const projects = useProjects(); @@ -43,71 +53,178 @@ export function useOpenChangeRequestLink( event: Pick< MouseEvent, "preventDefault" | "stopPropagation" | "metaKey" | "ctrlKey" - >, + > & + Partial, "button" | "shiftKey" | "altKey">>, targetUrl: string, targetThreadRef?: ScopedThreadRef, targetEnvironmentId?: EnvironmentId, + onCommitUnavailable?: () => void, ) => boolean { const navigate = useNavigate(); const primaryEnvironmentId = usePrimaryEnvironmentId(); const openInApp = useClientSettings((settings) => settings.pullRequestLinksOpenInApp); - return (event, targetUrl, targetThreadRef, targetEnvironmentId) => { + const ignoreWhitespace = useClientSettings((settings) => settings.diffIgnoreWhitespace); + const browserLinkTarget = useClientSettings((settings) => settings.browserLinkTarget); + const readDiffPreview = useAtomQueryRunner(reviewEnvironment.diffPreview, { + reportFailure: false, + refresh: true, + }); + const openLink = useOpenLink(threadRef); + return (event, targetUrl, targetThreadRef, targetEnvironmentId, onCommitUnavailable) => { if (!openInApp || shouldOpenPullRequestExternally(event)) return false; - // Read at click time: every provider status push replaces the config map, and - // subscribing would hand every rendered link a new handler. Projects likewise, so a - // link can resolve against a snapshot that arrived after this handler was built. - const serverConfigs = appAtomRegistry.get(environmentServerConfigsAtom); const resolvedThreadRef = targetThreadRef ?? threadRef; const resolvedPanelRef = panelRef ?? resolvedThreadRef; - const target = resolveChangeRequestLinkTarget({ - url: targetUrl, - projects: readProjects(), - configLoaded: (environmentId) => serverConfigs.has(environmentId), - environmentId: resolvedThreadRef?.environmentId ?? targetEnvironmentId, - primaryEnvironmentId, - lendHostProject: resolvedPanelRef !== undefined, - }); - if (target === null) return false; - const { project, repository, number, host } = target; - event.preventDefault(); - event.stopPropagation(); - const pullRequestsSearch = { - repository, - number, - ...(host === undefined ? {} : { selectedHost: host }), - selectedProjectId: project.id, - selectedEnvironmentId: project.environmentId, - }; - if (resolvedPanelRef) { - useRightPanelStore.getState().openPullRequest(resolvedPanelRef, { - // The standalone PR panel has a synthetic ref; each tab keeps its real environment. - ...(resolvedPanelRef.environmentId === project.environmentId - ? {} - : { environmentId: project.environmentId }), - projectId: project.id, - ...(host === undefined ? {} : { host }), - repository, + const openPullRequest = () => { + // Read at click time: every provider status push replaces the config map, and + // subscribing would hand every rendered link a new handler. Projects likewise, so a + // link can resolve against a snapshot that arrived after this handler was built. + const serverConfigs = appAtomRegistry.get(environmentServerConfigsAtom); + const target = resolveChangeRequestLinkTarget({ url: targetUrl, - number, + projects: readProjects(), + configLoaded: (environmentId) => serverConfigs.has(environmentId), + environmentId: resolvedThreadRef?.environmentId ?? targetEnvironmentId, + primaryEnvironmentId, + lendHostProject: resolvedPanelRef !== undefined, }); - if (!resolvedThreadRef) { - void navigate({ - to: "/pull-requests", - search: (previous) => ({ - ...previous, - involvement: previous.involvement ?? "all", - state: previous.state ?? "all", - ...pullRequestsSearch, - }), - replace: true, + if (target === null) return false; + const { project, repository, number, host } = target; + const pullRequestsSearch = { + repository, + number, + ...(host === undefined ? {} : { selectedHost: host }), + selectedProjectId: project.id, + selectedEnvironmentId: project.environmentId, + }; + if (resolvedPanelRef) { + useRightPanelStore.getState().openPullRequest(resolvedPanelRef, { + // The standalone PR panel has a synthetic ref; each tab keeps its real environment. + ...(resolvedPanelRef.environmentId === project.environmentId + ? {} + : { environmentId: project.environmentId }), + projectId: project.id, + ...(host === undefined ? {} : { host }), + repository, + url: targetUrl, + number, }); + if (!resolvedThreadRef) { + void navigate({ + to: "/pull-requests", + search: (previous) => ({ + ...previous, + involvement: previous.involvement ?? "all", + state: previous.state ?? "all", + ...pullRequestsSearch, + }), + replace: true, + }); + } + return true; } + void navigate({ + to: "/pull-requests", + search: { involvement: "all", state: "all", ...pullRequestsSearch }, + }); + return true; + }; + const commitThread = resolvedThreadRef ? readThreadShell(resolvedThreadRef) : null; + const commitProject = + commitThread && resolvedThreadRef + ? readProject({ + environmentId: resolvedThreadRef.environmentId, + projectId: commitThread.projectId, + }) + : null; + const identity = commitProject?.repositoryIdentity; + const parsedCommit = sourceControlClients.parseCommitUrl(targetUrl, identity?.provider); + // Shift and Alt keep their browser meaning (new window, download) on commit links. + if (parsedCommit !== null && (event.shiftKey || event.altKey)) return false; + if ( + parsedCommit !== null && + commitThread && + resolvedThreadRef && + commitProject?.environmentId === resolvedThreadRef.environmentId && + identity && + identity.provider === parsedCommit.definition.kind && + parsedCommit.definition.isChangeRequestInRepository(identity, parsedCommit.link) + ) { + const commit = parsedCommit.link; + event.preventDefault(); + event.stopPropagation(); + const userActionRevision = useRightPanelStore.getState().markUserAction(resolvedThreadRef); + const baseRef = selectThreadBranchBaseRef(useDiffPanelStore.getState(), resolvedThreadRef); + const selection = selectThreadDiffPanelSelection( + useDiffPanelStore.getState().byThreadKey, + resolvedThreadRef, + ); + void readDiffPreview({ + environmentId: resolvedThreadRef.environmentId, + input: { + cwd: commitThread.worktreePath ?? commitProject.workspaceRoot, + ...(baseRef ? { baseRef } : {}), + commitSha: commit.sha, + ignoreWhitespace, + }, + }) + .then((result) => { + if ( + useRightPanelStore.getState().getUserActionRevision(resolvedThreadRef) !== + userActionRevision || + selectThreadDiffPanelSelection( + useDiffPanelStore.getState().byThreadKey, + resolvedThreadRef, + ) !== selection + ) + return; + if ( + result._tag === "Success" && + result.value.sources.some( + (source) => source.kind === "commit" && source.headRef === commit.sha, + ) + ) { + const diffOpen = + selectActiveRightPanel( + useRightPanelStore.getState().byThreadKey, + resolvedThreadRef, + ) === "diff"; + useDiffPanelStore.getState().selectCommit(resolvedThreadRef, commit.sha, !diffOpen); + useRightPanelStore.getState().open(resolvedThreadRef, "diff"); + return; + } + if (openPullRequest()) return; + if (onCommitUnavailable) return onCommitUnavailable(); + // A popup opened after the lookup has lost the click's activation, so browsers block it. + if ( + window.desktopBridge === undefined && + (browserLinkTarget !== "app" || !canOpenLinksInApp(resolvedThreadRef)) + ) { + const toastId = toastManager.add( + stackedThreadToast({ + type: "info", + title: "This commit is not in the thread's workspace", + actionProps: { + children: "Open link", + onClick: () => { + toastManager.close(toastId); + window.open(targetUrl, "_blank", "noopener,noreferrer"); + }, + }, + }), + ); + return; + } + return openLink(targetUrl, { + event: { metaKey: event.metaKey, ctrlKey: event.ctrlKey, button: event.button }, + threadRef: resolvedThreadRef, + }); + }) + .catch((error: unknown) => console.error(error)); return true; } - void navigate({ - to: "/pull-requests", - search: { involvement: "all", state: "all", ...pullRequestsSearch }, - }); + if (!openPullRequest()) return false; + event.preventDefault(); + event.stopPropagation(); return true; }; } diff --git a/apps/web/src/rightPanelStore.ts b/apps/web/src/rightPanelStore.ts index 33c537a3cf942..ea043c0298bdb 100644 --- a/apps/web/src/rightPanelStore.ts +++ b/apps/web/src/rightPanelStore.ts @@ -109,6 +109,7 @@ interface RightPanelStoreState { userActionRevisionByThreadKey: Record; closeRevisionByThreadKey: Record; getUserActionRevision: (ref: ScopedThreadRef) => number; + markUserAction: (ref: ScopedThreadRef) => number; /** Refused if the user chose a panel after expectedUserActionRevision was read. */ openProactive: ( ref: ScopedThreadRef, @@ -598,6 +599,16 @@ export const useRightPanelStore = create()( closeRevisionByThreadKey: {}, getUserActionRevision: (ref) => get().userActionRevisionByThreadKey[scopedThreadKey(ref)] ?? 0, + markUserAction: (ref) => { + const revision = get().getUserActionRevision(ref) + 1; + set((state) => ({ + userActionRevisionByThreadKey: { + ...state.userActionRevisionByThreadKey, + [scopedThreadKey(ref)]: revision, + }, + })); + return revision; + }, openProactive: (ref, request, expectedUserActionRevision, activateExisting = false) => { let opened = false; set((state) => { diff --git a/docs/user/source-control.md b/docs/user/source-control.md index 815e5dd0668fa..9eb2751f9315f 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -10,6 +10,16 @@ rebases, the files Git brought in are left out. A file stays in the list when th committed it, or fixed a conflict in it. Use the branch comparison to review everything that changed against your base branch. Restore still returns the complete saved workspace. +On web and desktop, open the Diff pane source picker and choose **Commits** to review one local +commit at a time. The list shows the newest 100 commits in the branch comparison. A merge commit +shows its changes against its first parent. + +A commit link from a supported code host opens in the Diff pane when the thread's repository has +that commit locally, on any branch. Otherwise a pull request commit link opens the pull request. Other +commit links follow your **Open links in** setting; on web, when that opens a new tab, T3 Code first +shows an **Open link** button. Command/Ctrl+Click always opens the link in your browser. Commit links follow the **Open pull requests in T3 Code** +setting in **Settings → Diffs**. + ## Connect an account Install Git and configure authentication on the machine running your T3 Code server. For a remote diff --git a/packages/client-runtime/src/changeRequestLinks.ts b/packages/client-runtime/src/changeRequestLinks.ts index 2983647f3e26f..76f60a5953f2b 100644 --- a/packages/client-runtime/src/changeRequestLinks.ts +++ b/packages/client-runtime/src/changeRequestLinks.ts @@ -150,3 +150,21 @@ export function projectChangeRequestUrl( ...(ownRepository && identity.webUrl !== undefined ? { webUrl: identity.webUrl } : {}), }); } + +export function projectCommitUrl( + identity: RepositoryIdentity | null | undefined, + sha: string, +): string | null { + if (identity?.provider === undefined) return null; + const [host, ...path] = identity.canonicalKey.split("/"); + if (!host) return null; + return ( + sourceControlClients.get(identity.provider).commitUrl?.({ + host, + repository: path.join("/"), + sha, + remoteUrl: identity.locator.remoteUrl.trim(), + ...(identity.webUrl !== undefined ? { webUrl: identity.webUrl } : {}), + }) ?? null + ); +} diff --git a/packages/client-runtime/src/state/review.ts b/packages/client-runtime/src/state/review.ts index 691212aedd501..6700be9af657a 100644 --- a/packages/client-runtime/src/state/review.ts +++ b/packages/client-runtime/src/state/review.ts @@ -51,6 +51,11 @@ export function createReviewEnvironmentAtoms( }); }); return { + branchCommits: createEnvironmentRpcQueryAtomFamily(runtime, { + label: "environment-data:review:branch-commits", + tag: WS_METHODS.reviewGetBranchCommits, + staleTimeMs: 5_000, + }), diffPreview, diffFilePatch: createEnvironmentQueryAtomFamily(runtime, { label: "environment-data:review:diff-file-patch", diff --git a/packages/contracts/src/review.ts b/packages/contracts/src/review.ts index 5a95442917c9a..a40bddfc1e33e 100644 --- a/packages/contracts/src/review.ts +++ b/packages/contracts/src/review.ts @@ -6,18 +6,41 @@ import { VcsError } from "./vcs.ts"; export const ReviewDiffPreviewInput = Schema.Struct({ cwd: TrimmedNonEmptyString, baseRef: Schema.optional(TrimmedNonEmptyString), + commitSha: Schema.optional(TrimmedNonEmptyString), ignoreWhitespace: Schema.optionalKey(Schema.Boolean), file: Schema.optionalKey( Schema.Struct({ path: Schema.NonEmptyString, previousPath: Schema.NullOr(Schema.NonEmptyString), - sourceKind: Schema.Literals(["working-tree", "branch-range"]), + sourceKind: Schema.Literals(["working-tree", "branch-range", "commit"]), }), ), }); export type ReviewDiffPreviewInput = typeof ReviewDiffPreviewInput.Type; -export const ReviewDiffPreviewSourceKind = Schema.Literals(["working-tree", "branch-range"]); +export const ReviewBranchCommitsInput = Schema.Struct({ + cwd: TrimmedNonEmptyString, + baseRef: Schema.optional(TrimmedNonEmptyString), +}); +export type ReviewBranchCommitsInput = typeof ReviewBranchCommitsInput.Type; + +export const ReviewBranchCommitsResult = Schema.Struct({ + commits: Schema.Array( + Schema.Struct({ + sha: Schema.String, + subject: Schema.String, + committedAt: Schema.String, + }), + ), + truncated: Schema.Boolean, +}); +export type ReviewBranchCommitsResult = typeof ReviewBranchCommitsResult.Type; + +export const ReviewDiffPreviewSourceKind = Schema.Literals([ + "working-tree", + "branch-range", + "commit", +]); export type ReviewDiffPreviewSourceKind = typeof ReviewDiffPreviewSourceKind.Type; export const ReviewDiffFileStat = Schema.Struct({ @@ -32,6 +55,7 @@ export const ReviewDiffPreviewSource = Schema.Struct({ id: TrimmedNonEmptyString, kind: ReviewDiffPreviewSourceKind, title: TrimmedNonEmptyString, + commitSubject: Schema.optionalKey(TrimmedNonEmptyString), baseRef: Schema.NullOr(TrimmedNonEmptyString), headRef: Schema.NullOr(TrimmedNonEmptyString), diff: Schema.String, diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 445048eb2685d..edc7a9ab852a4 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -149,6 +149,8 @@ import { VcsStatusStreamEvent, } from "./git.ts"; import { + ReviewBranchCommitsInput, + ReviewBranchCommitsResult, ReviewDiffFileContentsInput, ReviewDiffFileContentsResult, ReviewDiffPreviewError, @@ -455,6 +457,7 @@ export const WS_METHODS = { gitResolvePullRequest: "git.resolvePullRequest", gitPreparePullRequestThread: "git.preparePullRequestThread", + reviewGetBranchCommits: "review.getBranchCommits", reviewGetDiffPreview: "review.getDiffPreview", reviewGetDiffFileContents: "review.getDiffFileContents", @@ -1500,6 +1503,12 @@ const WsVcsInitRpc = Rpc.make(WS_METHODS.vcsInit, { error: Schema.Union([VcsError, EnvironmentAuthorizationError]), }); +const WsReviewGetBranchCommitsRpc = Rpc.make(WS_METHODS.reviewGetBranchCommits, { + payload: ReviewBranchCommitsInput, + success: ReviewBranchCommitsResult, + error: Schema.Union([ReviewDiffPreviewError, EnvironmentAuthorizationError]), +}); + const WsReviewGetDiffPreviewRpc = Rpc.make(WS_METHODS.reviewGetDiffPreview, { payload: ReviewDiffPreviewInput, success: ReviewDiffPreviewResult, @@ -2092,6 +2101,7 @@ export const WsRpcGroup = RpcGroup.make( WsVcsCreateRefRpc, WsVcsSwitchRefRpc, WsVcsInitRpc, + WsReviewGetBranchCommitsRpc, WsReviewGetDiffPreviewRpc, WsReviewGetDiffFileContentsRpc, WsTerminalOpenRpc, diff --git a/packages/source-control-azure-devops/src/shared/definition.ts b/packages/source-control-azure-devops/src/shared/definition.ts index b43adccedc846..2dd036674747b 100644 --- a/packages/source-control-azure-devops/src/shared/definition.ts +++ b/packages/source-control-azure-devops/src/shared/definition.ts @@ -1,15 +1,18 @@ import { SourceControlProviderKind } from "@t3tools/contracts"; import { + buildCommitUrl, changeRequestUrlBelow, defineSourceControl, isChangeRequestAuthorityOfProject, parseChangeRequestPath, + parseCommitPath, remoteWebOrigin, } from "@t3tools/source-control-core/shared/definition"; import { icon } from "./icon.ts"; // Azure DevOps Server runs on any hostname; its `_git` route identifies it. const CHANGE_REQUEST_PATH = /^\/((?:[^/]+\/)*_git\/[^/]+)\/pullrequest\/(\d+)(?:\/|$)/u; +const COMMIT_PATH = /^\/((?:[^/]+\/)*_git\/[^/]+)\/commit\/([0-9a-f]+)\/?$/iu; const CHECKOUT_COMMAND = /^az\s+repos\s+pr\s+checkout\s+(.+)$/i; const CHANGE_REQUEST_REFERENCE = /^https:\/\/(?:dev\.azure\.com\/[^/\s]+\/[^/\s]+|[^/\s]+\.visualstudio\.com\/[^/\s]+)\/_git\/[^/\s]+\/pullrequest\/(\d+)(?:[/?#].*)?$/i; @@ -88,6 +91,12 @@ export const definition = defineSourceControl({ const [canonicalHost = host, ...path] = (canonicalRepositoryKey(key) ?? key).split("/"); return `${remoteWebOrigin(canonicalHost, remoteUrl)}/${path.join("/")}/pullrequest/${number}`; }, + commitUrl: (input) => { + const key = `${input.host}/${input.repository}`.toLowerCase(); + const [host = input.host, ...path] = (canonicalRepositoryKey(key) ?? key).split("/"); + return buildCommitUrl({ ...input, host, repository: path.join("/") }, "commit"); + }, + parseCommitUrl: (url) => parseCommitPath(url, COMMIT_PATH), // Servers on different ports are different servers, so a port stays in the link. parseChangeRequestUrl: (url) => { const link = parseChangeRequestPath(url, CHANGE_REQUEST_PATH); diff --git a/packages/source-control-bitbucket/src/shared/definition.ts b/packages/source-control-bitbucket/src/shared/definition.ts index 946098b166d34..a8e786cb0ba6e 100644 --- a/packages/source-control-bitbucket/src/shared/definition.ts +++ b/packages/source-control-bitbucket/src/shared/definition.ts @@ -6,11 +6,13 @@ import { import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { + buildCommitUrl, changeRequestUrlBelow, defineSourceControl, isChangeRequestInProjectRepository, isChangeRequestOnProjectHost, parseChangeRequestPath, + parseCommitPath, projectChangeRequestHost, } from "@t3tools/source-control-core/shared/definition"; import { icon } from "./icon.ts"; @@ -19,6 +21,7 @@ const safeShellArgument = /^[A-Za-z0-9._/@+=,-]+$/; const repositoryName = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/; const CHANGE_REQUEST_PATH = /^\/([^/]+\/[^/]+)\/pull-requests\/(\d+)(?:\/|$)/u; +const COMMIT_PATH = /^\/([^/]+\/[^/]+)\/commits\/([0-9a-f]+)\/?$/iu; const KIND = SourceControlProviderKind.make("bitbucket"); @@ -87,6 +90,9 @@ export const definition = defineSourceControl({ : `https://${host}/${repository}/pull-requests/${number}`, parseChangeRequestUrl: (url) => isBitbucketHost(url.hostname) ? parseChangeRequestPath(url, CHANGE_REQUEST_PATH) : null, + commitUrl: (input) => buildCommitUrl(input, "commits"), + parseCommitUrl: (url) => + isBitbucketHost(url.hostname) ? parseCommitPath(url, COMMIT_PATH) : null, changeRequestUrlFromReferenceAutolink: () => null, // No endpoint reopens a declined pull request, and nothing documented moves one in or out of // draft, so neither is offered rather than failing when pressed. diff --git a/packages/source-control-core/src/shared/definition.ts b/packages/source-control-core/src/shared/definition.ts index 6f99525260129..e9e68325b7418 100644 --- a/packages/source-control-core/src/shared/definition.ts +++ b/packages/source-control-core/src/shared/definition.ts @@ -30,6 +30,17 @@ export interface ParsedChangeRequestUrl extends ChangeRequestLink { readonly repositoryUrl: string; } +export interface CommitLink { + readonly host: string; + readonly repository: string; + readonly sha: string; + readonly authority?: string; +} + +export interface CommitUrlInput extends Omit { + readonly sha: string; +} + export interface ChangeRequestTerminology { readonly shortLabel: string; /** Spelled out because the article follows how the label is said: "an MR". */ @@ -238,6 +249,9 @@ export interface SourceControlDefinition { readonly newRepositoryOwner: (account: string | null) => { readonly owner: string | null } | null; readonly defaultCloneTransport: "https" | "ssh"; readonly changeRequestUrl: (input: ChangeRequestUrlInput) => string | null; + readonly commitUrl?: (input: CommitUrlInput) => string | null; + /** `known` is set when the caller already knows this host serves the URL's repository. */ + readonly parseCommitUrl?: (url: URL, known: boolean) => CommitLink | null; /** Null when the URL is not one of this host's change requests. */ readonly parseChangeRequestUrl: (url: URL) => ParsedChangeRequestUrl | null; /** @@ -290,7 +304,7 @@ export interface SourceControlDefinition { readonly isChangeRequestReference: (url: string) => boolean; readonly isChangeRequestInRepository: ( identity: ChangeRequestProjectIdentity, - link: ChangeRequestLink, + link: ChangeRequestLink | CommitLink, ) => boolean; readonly canReadChangeRequestOnHost: ( identity: ChangeRequestProjectIdentity, @@ -335,6 +349,42 @@ export type SourceControlHostSettingsSchema = { readonly fields: Readonly>; } & Schema.Decoder; +const FULL_COMMIT_SHA = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/iu; + +export function parseCommitPath(url: URL, route: RegExp): CommitLink | null { + if (url.protocol !== "https:" && url.protocol !== "http:") return null; + const match = route.exec(url.pathname); + const repository = match?.[1]; + const sha = match?.[2]; + return repository && sha && FULL_COMMIT_SHA.test(sha) + ? { + host: url.hostname.toLowerCase(), + repository: repository.toLowerCase(), + sha: sha.toLowerCase(), + ...(url.port ? { authority: url.host.toLowerCase() } : {}), + } + : null; +} + +export function buildCommitUrl( + { host, repository, sha, remoteUrl, webUrl }: CommitUrlInput, + route: string, +): string | null { + if (!repository || !FULL_COMMIT_SHA.test(sha)) return null; + try { + const url = new URL(webUrl || `${remoteWebOrigin(host, remoteUrl)}/${repository}`); + if (url.protocol !== "http:" && url.protocol !== "https:") return null; + url.pathname = changeRequestUrlBelow(url.pathname, `${route}/${sha.toLowerCase()}`); + url.username = ""; + url.password = ""; + url.search = ""; + url.hash = ""; + return url.toString(); + } catch { + return null; + } +} + /** * Reads a change request from `url` with `route`, whose first group is the repository path and * second the number. @@ -383,7 +433,7 @@ export function defineSourceControl( export function isChangeRequestOnProjectHost( projectHost: string, identity: ChangeRequestProjectIdentity, - link: ChangeRequestLink, + link: ChangeRequestLink | CommitLink, ): boolean { if (!isChangeRequestAuthorityOfProject(identity, link)) return false; return projectHost === link.host.toLowerCase() || projectHost === link.authority; @@ -426,7 +476,7 @@ function projectRepositoryPath(identity: ChangeRequestProjectIdentity): string | export function isChangeRequestInProjectRepository( projectHost: string, identity: ChangeRequestProjectIdentity, - link: ChangeRequestLink, + link: ChangeRequestLink | CommitLink, ): boolean { const repository = projectRepositoryPath(identity); return ( @@ -533,6 +583,11 @@ export interface ParsedChangeRequest { readonly link: ParsedChangeRequestUrl; } +export interface ParsedCommit { + readonly definition: SourceControlDefinition; + readonly link: CommitLink; +} + export interface SourceControlMedia extends SourceControlMediaUrl { readonly definition: SourceControlDefinition; } @@ -549,6 +604,7 @@ export interface SourceControlDefinitionRegistry { readonly findByPublicDomain: (hostname: string) => SourceControlDefinition | undefined; /** The first host, in registry order, that reads `url` as one of its change requests. */ readonly parseChangeRequestUrl: (url: string) => ParsedChangeRequest | null; + readonly parseCommitUrl: (url: string, kind?: SourceControlProviderKind) => ParsedCommit | null; readonly findByChangeRequestUrl: (url: string) => SourceControlDefinition | undefined; readonly hostLabelForChangeRequestUrl: (url: string) => string; readonly isSameChangeRequest: (left: string, right: string) => boolean; @@ -648,6 +704,16 @@ export function makeSourceControlDefinitionRegistry( ); }, parseChangeRequestUrl, + parseCommitUrl: (value, kind) => { + const url = httpUrl(value); + if (url === null) return null; + const preferred = kind === undefined ? undefined : byKind.get(kind); + for (const definition of kind === undefined ? claimOrder : preferred ? [preferred] : []) { + const link = definition.parseCommitUrl?.(url, preferred !== undefined); + if (link != null) return { definition, link }; + } + return null; + }, findByChangeRequestUrl: (url) => parseChangeRequestUrl(url)?.definition, hostLabelForChangeRequestUrl: (url) => parseChangeRequestUrl(url)?.definition.label ?? "the host", diff --git a/packages/source-control-definitions/src/registry.ts b/packages/source-control-definitions/src/registry.ts index 0e42360855350..e44a6bb281717 100644 --- a/packages/source-control-definitions/src/registry.ts +++ b/packages/source-control-definitions/src/registry.ts @@ -23,7 +23,7 @@ export const builtInSourceControlDefinitions = makeSourceControlDefinitionRegist AzureDevOps.definition, ], { - claimChangeRequestUrlsFirst: [GitCafe.definition.kind], + claimChangeRequestUrlsFirst: [GitCafe.definition.kind, AzureDevOps.definition.kind], recognizeRemotesIn: [ GitCafe.definition.kind, Forgejo.definition.kind, diff --git a/packages/source-control-forgejo/src/shared/definition.ts b/packages/source-control-forgejo/src/shared/definition.ts index 32258854c79da..2cf8ac5bb5838 100644 --- a/packages/source-control-forgejo/src/shared/definition.ts +++ b/packages/source-control-forgejo/src/shared/definition.ts @@ -1,5 +1,6 @@ import { SourceControlProviderKind } from "@t3tools/contracts"; import { + buildCommitUrl, changeRequestUrlBelow, type ChangeRequestHostIdentity, type ChangeRequestProjectIdentity, @@ -8,6 +9,7 @@ import { isChangeRequestInProjectRepository, isChangeRequestOnProjectHost, parseChangeRequestPath, + parseCommitPath, projectChangeRequestHost, remoteWebOrigin, } from "@t3tools/source-control-core/shared/definition"; @@ -19,6 +21,7 @@ const CHANGE_REQUEST_REFERENCE = // Forgejo and Gitea run on any hostname, possibly mounted below a path. const CHANGE_REQUEST_PATH = /^\/([^/]+(?:\/[^/]+)+)\/pulls\/(\d+)(?:\/|$)/u; +const COMMIT_PATH = /^\/([^/]+(?:\/[^/]+)+)\/commit\/([0-9a-f]+)\/?$/iu; const KIND = SourceControlProviderKind.make("forgejo"); @@ -82,6 +85,8 @@ export const definition = defineSourceControl({ return link === null ? null : { ...link, authority: url.host.toLowerCase() }; }, changeRequestUrlFromReferenceAutolink: () => null, + commitUrl: (input) => buildCommitUrl(input, "commit"), + parseCommitUrl: (url) => parseCommitPath(url, COMMIT_PATH), changeRequestActions: new Set(["merge", "close", "reopen", "update-branch"] as const), // Neither `fj` nor `tea` checks out by number. checkoutCommand: ({ number, repositoryUrl }) => diff --git a/packages/source-control-gitcafe/src/shared/definition.ts b/packages/source-control-gitcafe/src/shared/definition.ts index dc352be748dc2..a7b22261b2b4b 100644 --- a/packages/source-control-gitcafe/src/shared/definition.ts +++ b/packages/source-control-gitcafe/src/shared/definition.ts @@ -7,11 +7,13 @@ import { import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { + buildCommitUrl, changeRequestUrlBelow, defineSourceControl, isChangeRequestInProjectRepository, isChangeRequestOnProjectHost, parseChangeRequestPath, + parseCommitPath, projectChangeRequestHost, } from "@t3tools/source-control-core/shared/definition"; import { icon } from "./icon.ts"; @@ -21,6 +23,7 @@ const GITCAFE_HOSTS = new Set(["git.cafe", "staging.git.cafe"]); /** GitCafe serves pull requests at `/pull/` and redirects the older `/pulls/` there. */ const CHANGE_REQUEST_PATH = /^\/([^/]+\/[^/]+)\/pulls?\/(\d+)(?:\/|$)/u; +const COMMIT_PATH = /^\/([^/]+\/[^/]+)\/commit\/([0-9a-f]+)\/?$/iu; function parseChangeRequestUrl(url: URL) { return GITCAFE_HOSTS.has(url.hostname.toLowerCase()) @@ -68,6 +71,9 @@ export const definition = defineSourceControl({ // `/pull/` and `/pulls/` are GitHub's and Forgejo's shapes too, so only GitCafe's own hosts // claim them. parseChangeRequestUrl, + commitUrl: (input) => buildCommitUrl(input, "commit"), + parseCommitUrl: (url) => + GITCAFE_HOSTS.has(url.hostname.toLowerCase()) ? parseCommitPath(url, COMMIT_PATH) : null, changeRequestUrlFromReferenceAutolink: () => null, changeRequestActions: new Set([ "ready", diff --git a/packages/source-control-github/src/shared/definition.ts b/packages/source-control-github/src/shared/definition.ts index 965ed42814c19..6ac8aa305f3cd 100644 --- a/packages/source-control-github/src/shared/definition.ts +++ b/packages/source-control-github/src/shared/definition.ts @@ -1,11 +1,13 @@ import { makeProviderSettingsSchema, SourceControlProviderKind } from "@t3tools/contracts"; import { + buildCommitUrl, changeRequestUrlBelow, defineSourceControl, hostCredentialSettingsFields, isChangeRequestInProjectRepository, isChangeRequestOnProjectHost, parseChangeRequestPath, + parseCommitPath, projectChangeRequestHost, remoteWebOrigin, type SourceControlAppSignIn, @@ -22,15 +24,14 @@ const CHANGE_REQUEST_REFERENCE = // GitHub Enterprise Server runs on any hostname, so the `//pull/` route alone // identifies a GitHub pull request. const CHANGE_REQUEST_PATH = /^\/([^/]+\/[^/]+)\/pull\/(\d+)(?:\/|$)/u; +const COMMIT_PATH = /^\/([^/]+\/[^/]+)\/(?:commit|pull\/\d+\/commits)\/([0-9a-f]+)\/?$/iu; const ISSUE_PATH = /^\/([^/]+\/[^/]+)\/issues\/(\d+)(?:\/|$)/u; const KIND = SourceControlProviderKind.make("github"); function isGitHubHost(hostname: string): boolean { const host = hostname.toLowerCase(); - return ( - host === "github.com" || host.endsWith(".github.com") || host.split(".").includes("github") - ); + return host === "github.com" || host.endsWith(".ghe.com") || host.split(".").includes("github"); } function isRepositoryPath(repository: string): boolean { @@ -91,6 +92,11 @@ export const definition = defineSourceControl({ return null; } }, + commitUrl: (input) => + isRepositoryPath(input.repository) ? buildCommitUrl(input, "commit") : null, + // A known project's host can be any GitHub Enterprise Server name. + parseCommitUrl: (url, known) => + known || isGitHubHost(url.hostname) ? parseCommitPath(url, COMMIT_PATH) : null, parseChangeRequestUrl: (url) => parseChangeRequestPath(url, CHANGE_REQUEST_PATH), // GitHub writes every bare reference through `/issues/`, including pull requests. changeRequestUrlFromReferenceAutolink: (url) => { @@ -133,9 +139,7 @@ export const definition = defineSourceControl({ changeRequestHeadRef: (number) => `refs/pull/${number}/head`, // `*.ghe.com` is GitHub Enterprise Cloud with data residency, one subdomain per enterprise. recognizeRemote: ({ host, hostname }) => - hostname === "github.com" || - hostname.endsWith(".ghe.com") || - hostname.split(".").includes("github") + isGitHubHost(hostname) ? { kind: KIND, name: hostname === "github.com" ? "GitHub" : "GitHub Self-Hosted", diff --git a/packages/source-control-gitlab/src/shared/definition.ts b/packages/source-control-gitlab/src/shared/definition.ts index 437320c0d0419..2d280f01c62f2 100644 --- a/packages/source-control-gitlab/src/shared/definition.ts +++ b/packages/source-control-gitlab/src/shared/definition.ts @@ -1,10 +1,12 @@ import { SourceControlProviderKind } from "@t3tools/contracts"; import { + buildCommitUrl, changeRequestUrlBelow, defineSourceControl, isChangeRequestInProjectRepository, isChangeRequestOnProjectHost, parseChangeRequestPath, + parseCommitPath, projectChangeRequestHost, } from "@t3tools/source-control-core/shared/definition"; import { icon } from "./icon.ts"; @@ -15,6 +17,7 @@ const CHANGE_REQUEST_REFERENCE = // Self-managed GitLab runs on any hostname and nests projects in groups. const CHANGE_REQUEST_PATH = /^\/([^/]+(?:\/[^/]+)+)\/-\/merge_requests\/(\d+)(?:\/|$)/u; +const COMMIT_PATH = /^\/([^/]+(?:\/[^/]+)+)\/-\/commit\/([0-9a-f]+)\/?$/iu; const KIND = SourceControlProviderKind.make("gitlab"); @@ -40,6 +43,8 @@ export const definition = defineSourceControl({ ? changeRequestUrlBelow(webUrl, `-/merge_requests/${number}`) : `https://${host}/${repository}/-/merge_requests/${number}`, parseChangeRequestUrl: (url) => parseChangeRequestPath(url, CHANGE_REQUEST_PATH), + commitUrl: (input) => buildCommitUrl(input, "-/commit"), + parseCommitUrl: (url) => parseCommitPath(url, COMMIT_PATH), changeRequestUrlFromReferenceAutolink: () => null, changeRequestActions: new Set([ "merge", From 305a90dce44b8b7813d951662f13ce8510a3c669 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 30 Oct 2026 01:47:04 -0700 Subject: [PATCH 415/817] fix(relay): show the account's real tunnel cap in T3 Connect settings (#27442) Co-authored-by: Claude Opus 5.5 --- apps/web/src/cloud/managedRelayState.ts | 5 ++- .../ManagedEndpointProvider.test.ts | 1 + .../environments/ManagedTunnelLimits.test.ts | 23 +++++++++++ .../src/environments/ManagedTunnelLimits.ts | 41 +++++++++++-------- infra/relay/src/http/Api.test.ts | 4 ++ infra/relay/src/http/Api.ts | 20 ++++++--- packages/contracts/src/relay.ts | 2 + 7 files changed, 73 insertions(+), 23 deletions(-) diff --git a/apps/web/src/cloud/managedRelayState.ts b/apps/web/src/cloud/managedRelayState.ts index c5f7536305337..679f362fdf5a0 100644 --- a/apps/web/src/cloud/managedRelayState.ts +++ b/apps/web/src/cloud/managedRelayState.ts @@ -150,11 +150,14 @@ export function useManagedRelayDevices() { /** How this account can raise its tunnel cap: link T3 Chat, or upgrade the linked plan. */ export type ManagedTunnelUpgrade = "link" | "pro" | "premier" | null; -// Mirrors the relay's cap without manual overrides, which the relay does not expose. +// Mirrors the relay's cap: a manual override is exact, otherwise the T3 Chat plan raises the default. function managedTunnelCap(t3Chat: RelayT3ChatLinkResponse): { readonly limit: number; readonly upgrade: ManagedTunnelUpgrade; } { + if (t3Chat.maxTunnelsOverride !== undefined) { + return { limit: t3Chat.maxTunnelsOverride, upgrade: null }; + } if (!t3Chat.available) return { limit: DEFAULT_MANAGED_TUNNEL_LIMIT, upgrade: null }; switch (t3Chat.link?.plan) { case "premier": diff --git a/infra/relay/src/environments/ManagedEndpointProvider.test.ts b/infra/relay/src/environments/ManagedEndpointProvider.test.ts index 01230171be9ba..96661fad42a61 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.test.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.test.ts @@ -343,6 +343,7 @@ function makeTunnelLimits( } return yield* reserve; }), + getOverride: () => Effect.die("unused"), }); } diff --git a/infra/relay/src/environments/ManagedTunnelLimits.test.ts b/infra/relay/src/environments/ManagedTunnelLimits.test.ts index 6aca885b85b87..6b8dd817ee01c 100644 --- a/infra/relay/src/environments/ManagedTunnelLimits.test.ts +++ b/infra/relay/src/environments/ManagedTunnelLimits.test.ts @@ -121,6 +121,27 @@ const reserve = ( ), ); +const getOverride = (override?: number) => + Effect.gen(function* () { + const limits = yield* ManagedTunnelLimits.ManagedTunnelLimits; + return yield* limits.getOverride({ userId: "user-1" }); + }).pipe( + Effect.provide( + ManagedTunnelLimits.layer.pipe( + Layer.provide( + Layer.succeed( + RelayDb.RelayDb, + makeFakeDb({ + otherSlots: () => 0, + ...(override === undefined ? {} : { override }), + }), + ), + ), + Layer.provide(t3ChatLayer("free")), + ), + ), + ); + describe("ManagedTunnelLimits", () => { it.effect("rejects concurrent reservations past the limit", () => { const reserved: Array = []; @@ -383,7 +404,9 @@ describe("ManagedTunnelLimits", () => { reserve({ override, activeTunnels: override, plan: "premier", lookups }), ); expect(error).toMatchObject({ _tag: "ManagedTunnelLimitExceeded", maxTunnels: override }); + expect(yield* getOverride(override)).toBe(override); } + expect(yield* getOverride()).toBeNull(); expect(lookups).toEqual([]); }), ); diff --git a/infra/relay/src/environments/ManagedTunnelLimits.ts b/infra/relay/src/environments/ManagedTunnelLimits.ts index aa373ad27ffb2..3af90f86c4163 100644 --- a/infra/relay/src/environments/ManagedTunnelLimits.ts +++ b/infra/relay/src/environments/ManagedTunnelLimits.ts @@ -106,6 +106,10 @@ export class ManagedTunnelLimits extends Context.Service< input: { readonly userId: string; readonly environmentId: string }, reserve: Effect.Effect, ) => Effect.Effect; + /** The user's manual cap, which replaces the default and any T3 Chat plan cap. */ + readonly getOverride: (input: { + readonly userId: string; + }) => Effect.Effect; } >()("t3code-relay/environments/ManagedTunnelLimits") {} @@ -126,7 +130,24 @@ const make = Effect.gen(function* () { ), ); + const loadOverride = (userId: string) => + db + .select({ maxTunnels: relayManagedTunnelLimits.maxTunnels }) + .from(relayManagedTunnelLimits) + .where(eq(relayManagedTunnelLimits.userId, userId)) + .limit(1) + .pipe( + Effect.map((rows) => rows[0]?.maxTunnels ?? null), + Effect.mapError( + (cause) => + new ManagedTunnelLimitPersistenceError({ operation: "load-limit", userId, cause }), + ), + ); + return ManagedTunnelLimits.of({ + getOverride: Effect.fn("relay.managed_tunnel_limits.get_override")(function* (input) { + return yield* loadOverride(input.userId); + }), withCapacity: Effect.fn("relay.managed_tunnel_limits.with_capacity")(function* ( input: { readonly userId: string; readonly environmentId: string }, reserve: Effect.Effect, @@ -148,22 +169,8 @@ const make = Effect.gen(function* () { ), ); - const overrides = yield* db - .select({ maxTunnels: relayManagedTunnelLimits.maxTunnels }) - .from(relayManagedTunnelLimits) - .where(eq(relayManagedTunnelLimits.userId, input.userId)) - .limit(1) - .pipe( - Effect.mapError( - (cause) => - new ManagedTunnelLimitPersistenceError({ - operation: "load-limit", - userId: input.userId, - cause, - }), - ), - ); - const baseMaxTunnels = overrides[0]?.maxTunnels ?? DEFAULT_MANAGED_TUNNEL_LIMIT; + const override = yield* loadOverride(input.userId); + const baseMaxTunnels = override ?? DEFAULT_MANAGED_TUNNEL_LIMIT; const pendingCutoff = DateTime.formatIso( DateTime.subtract(yield* DateTime.now, { @@ -196,7 +203,7 @@ const make = Effect.gen(function* () { // A manual override is the exact cap; a T3 Chat plan raises only the default. // Runs under the user lock, bounded by the T3 Chat request timeout. const maxTunnels = - t3Chat.available && overrides.length === 0 + t3Chat.available && override === null ? Math.max(baseMaxTunnels, yield* t3ChatTunnelLimit(input.userId)) : baseMaxTunnels; if (activeTunnels >= maxTunnels) { diff --git a/infra/relay/src/http/Api.test.ts b/infra/relay/src/http/Api.test.ts index a20989cd3c025..e6db7fc8b7aa0 100644 --- a/infra/relay/src/http/Api.test.ts +++ b/infra/relay/src/http/Api.test.ts @@ -64,6 +64,7 @@ import * as HookInbox from "../hooks/HookInbox.ts"; import * as EnvironmentLinks from "../environments/EnvironmentLinks.ts"; import * as ManagedEndpointAllocations from "../environments/ManagedEndpointAllocations.ts"; import * as ManagedEndpointProvider from "../environments/ManagedEndpointProvider.ts"; +import * as ManagedTunnelLimits from "../environments/ManagedTunnelLimits.ts"; import * as AgentActivityPublisher from "../agentActivity/AgentActivityPublisher.ts"; import * as EnvironmentPublishSignatures from "../environments/EnvironmentPublishSignatures.ts"; import * as T3ChatAccounts from "../t3chat/T3ChatAccounts.ts"; @@ -130,6 +131,7 @@ describe("managed endpoint provisioning errors", () => { Layer.mock(ManagedEndpointProvider.ManagedEndpointProvider, {}), Layer.mock(Devices.Devices, {}), Layer.mock(T3ChatAccounts.T3ChatAccounts, { available: false }), + Layer.mock(ManagedTunnelLimits.ManagedTunnelLimits, {}), ), ), Layer.provideMerge( @@ -241,6 +243,7 @@ describe("device listing compatibility", () => { }, }), Layer.mock(T3ChatAccounts.T3ChatAccounts, { available: false }), + Layer.mock(ManagedTunnelLimits.ManagedTunnelLimits, {}), ), ), Layer.provideMerge( @@ -322,6 +325,7 @@ describe("Cloudflare rate-limit retry hint", () => { Layer.mock(ManagedEndpointProvider.ManagedEndpointProvider, {}), Layer.mock(Devices.Devices, {}), Layer.mock(T3ChatAccounts.T3ChatAccounts, { available: false }), + Layer.mock(ManagedTunnelLimits.ManagedTunnelLimits, {}), ), ), Layer.provideMerge( diff --git a/infra/relay/src/http/Api.ts b/infra/relay/src/http/Api.ts index 5a4d77c28d3c2..390f3c18f785f 100644 --- a/infra/relay/src/http/Api.ts +++ b/infra/relay/src/http/Api.ts @@ -74,6 +74,7 @@ import * as AgentActivityPublisher from "../agentActivity/AgentActivityPublisher import * as EnvironmentConnector from "../environments/EnvironmentConnector.ts"; import * as EnvironmentLinker from "../environments/EnvironmentLinker.ts"; import * as ManagedEndpointProvider from "../environments/ManagedEndpointProvider.ts"; +import * as ManagedTunnelLimits from "../environments/ManagedTunnelLimits.ts"; import * as ManagedEndpointAllocations from "../environments/ManagedEndpointAllocations.ts"; import * as EnvironmentPublishSignatures from "../environments/EnvironmentPublishSignatures.ts"; import * as MobileRegistrations from "../agentActivity/MobileRegistrations.ts"; @@ -825,6 +826,7 @@ export const layerClientApi = HttpApiBuilder.group( const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider; const devices = yield* Devices.Devices; const t3Chat = yield* T3ChatAccounts.T3ChatAccounts; + const tunnelLimits = yield* ManagedTunnelLimits.ManagedTunnelLimits; return handlers .handle( "listEnvironments", @@ -996,12 +998,20 @@ export const layerClientApi = HttpApiBuilder.group( "getT3ChatLink", Effect.fn("relay.api.client.getT3ChatLink")(function* () { yield* appendRelayCredentialResponseHeaders; - if (!t3Chat.available) return { available: false, link: null }; const { userId } = yield* RelayClientPrincipal; - const link = yield* t3Chat - .getLink({ userId }) - .pipe(Effect.catch(() => relayInternalErrorResponse("upstream_unavailable"))); - return { available: true, link }; + const link = t3Chat.available + ? yield* t3Chat + .getLink({ userId }) + .pipe(Effect.catch(() => relayInternalErrorResponse("upstream_unavailable"))) + : null; + const maxTunnelsOverride = yield* tunnelLimits + .getOverride({ userId }) + .pipe(Effect.catch(() => relayInternalErrorResponse("internal_error"))); + return { + available: t3Chat.available, + link, + ...(maxTunnelsOverride === null ? {} : { maxTunnelsOverride }), + }; }, mapRelayCommonApiErrors("not_authorized")), ) .handle( diff --git a/packages/contracts/src/relay.ts b/packages/contracts/src/relay.ts index 4dbb6a199f472..8ebc9df23a0bb 100644 --- a/packages/contracts/src/relay.ts +++ b/packages/contracts/src/relay.ts @@ -981,6 +981,8 @@ export const RelayT3ChatLinkResponse = Schema.Struct({ // False when this relay has no T3 Chat secret, so clients hide the feature. available: Schema.Boolean, link: Schema.NullOr(RelayT3ChatLink), + // A manual cap that replaces the plan's; T3 Chat upgrades do not raise it. + maxTunnelsOverride: Schema.optionalKey(Schema.Number), }); export type RelayT3ChatLinkResponse = typeof RelayT3ChatLinkResponse.Type; From 5cbc207d8c8e92964b36e235740f22b49d938352 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 30 Oct 2026 02:10:40 -0700 Subject: [PATCH 416/817] fix(web): streaming replies no longer re-render every visible timeline row (#27420) Co-authored-by: Claude Opus 5.5 --- .../src/components/chat/MessagesTimeline.tsx | 42 +++++++++++-------- apps/web/test/appScenarios.renders.tsx | 3 ++ 2 files changed, 28 insertions(+), 17 deletions(-) diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index a9cab1554a3d3..faa733c76e896 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -659,12 +659,11 @@ const ConversationTimeline = memo(function ConversationTimeline({ ? new Set(paintedExpandedAttemptIds).add(activeFindAttemptId) : paintedExpandedAttemptIds; - const pendingApprovalsByRequestId = new Map( - pendingApprovals - .filter((approval) => !heldApprovalRequestIds?.has(approval.requestId)) - .map((approval) => [approval.requestId, approval]), + const isVisiblePendingApproval = (approval: PendingApproval) => + !heldApprovalRequestIds?.has(approval.requestId); + const pendingApprovalRequestIds = new Set( + pendingApprovals.filter(isVisiblePendingApproval).map((approval) => approval.requestId), ); - const pendingApprovalRequestIds = new Set(pendingApprovalsByRequestId.keys()); const rawRows = useIncrementalTimelineRows(`${listIdentityKey}\0${workspaceRoot ?? ""}`, { timelineEntries, pendingApprovalRequestIds, @@ -683,17 +682,19 @@ const ConversationTimeline = memo(function ConversationTimeline({ worktreeSetup, }); const rows = useStableRows(rawRows, listIdentityKey); - const unmatchedPendingApprovals = new Map(pendingApprovalsByRequestId); - if (unmatchedPendingApprovals.size > 0) { - for (const row of rows) { - const entries = - row.kind === "work" ? row.groupedEntries : row.kind === "work-live" ? [row.entry] : []; - for (const entry of entries) { - const item = entry.projectedItem?.item; - if (item?.type === "approval_request") unmatchedPendingApprovals.delete(item.requestId); - } + const matchedApprovalRequestIds = new Set(); + for (const row of pendingApprovalRequestIds.size > 0 ? rows : []) { + const entries = + row.kind === "work" ? row.groupedEntries : row.kind === "work-live" ? [row.entry] : []; + for (const entry of entries) { + const item = entry.projectedItem?.item; + if (item?.type === "approval_request") matchedApprovalRequestIds.add(item.requestId); } } + const unmatchedPendingApprovals = pendingApprovals.filter( + (approval) => + isVisiblePendingApproval(approval) && !matchedApprovalRequestIds.has(approval.requestId), + ); // Run status/timestamps change per stream event; keep them out of shared row context. const runs = useStableHandoffRuns(runsProp); const minimapItems = deriveTimelineMinimapItems(rows); @@ -706,7 +707,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ restoringThreadPosition && restoreRowIndex >= 0 ? { indices: [restoreRowIndex] } : undefined; const showsEmptyState = rows.length === 0 && - unmatchedPendingApprovals.size === 0 && + unmatchedPendingApprovals.length === 0 && !isWorking && parentThreadLink === null && historyControls === undefined && @@ -1000,6 +1001,13 @@ const ConversationTimeline = memo(function ConversationTimeline({ }; }; + // Built from props after the last hook so the compiler can memoize the row context; a map + // made before a hook would rebuild it, and re-render every row, on each streamed update. + const pendingApprovalsByRequestId = new Map( + pendingApprovals + .filter(isVisiblePendingApproval) + .map((approval) => [approval.requestId, approval]), + ); const sharedState: TimelineRowSharedState = { pendingApprovals: pendingApprovalsByRequestId, respondingRequestIds, @@ -1238,12 +1246,12 @@ const ConversationTimeline = memo(function ConversationTimeline({ onGrow={onFooterGrow} > {footer} - {unmatchedPendingApprovals.size > 0 ? ( + {unmatchedPendingApprovals.length > 0 ? (
      - {[...unmatchedPendingApprovals.values()].map((approval) => ( + {unmatchedPendingApprovals.map((approval) => ( ))} diff --git a/apps/web/test/appScenarios.renders.tsx b/apps/web/test/appScenarios.renders.tsx index 9c1a7d520eeb1..cc7d67798ddd9 100644 --- a/apps/web/test/appScenarios.renders.tsx +++ b/apps/web/test/appScenarios.renders.tsx @@ -201,6 +201,9 @@ it("app-stream-assistant-turn", async () => { .element(page.getByText(`word${STREAM_DELTAS - 1}`, { exact: false })) .toBeVisible(); }); + // Only the streaming row changes; history rows must not re-render with it. + expect(counted.components.UserTimelineRow).toBeUndefined(); + expect(counted.components.AssistantTimelineRow).toBe(STREAM_DELTAS); await report("app-stream-assistant-turn", [counted], { commits: false }); }); From d8c926c395155be72b09be594cb498adda3dfed2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 30 Oct 2026 02:10:41 -0700 Subject: [PATCH 417/817] perf(web): streaming replies re-render only their last Markdown block (#27417) Co-authored-by: Claude Opus 5.5 --- apps/web/src/components/ChatMarkdown.tsx | 129 ++++++++++++------ .../chat/markdownStreamBlocks.test.tsx | 61 +++++++++ .../components/chat/markdownStreamBlocks.ts | 43 ++++++ apps/web/test/appScenarios.renders.tsx | 4 +- 4 files changed, 194 insertions(+), 43 deletions(-) create mode 100644 apps/web/src/components/chat/markdownStreamBlocks.test.tsx create mode 100644 apps/web/src/components/chat/markdownStreamBlocks.ts diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 6a8f80d6d1071..99c2ebbc8f40f 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -189,6 +189,7 @@ import { import { resolveLinkTarget } from "../browser/browserLinkTarget"; import { PullRequestLinkPreview } from "./pullRequest/PullRequestLinkPreview"; import { MarkdownCodeBlock, SuspenseShikiCodeBlock } from "./chat/MarkdownCodeBlock"; +import { splitMarkdownBlocks } from "./chat/markdownStreamBlocks"; import { MarkdownMermaidCodeBlock } from "./chat/MarkdownMermaidCodeBlock"; import { MarkdownTable } from "./chat/MarkdownTable"; import { MarkdownDetails } from "./chat/MarkdownDetails"; @@ -434,6 +435,44 @@ const markdownServerConfigFieldsAtom = Atom.family((environmentId: EnvironmentId }).pipe(Atom.withLabel("markdown-server-config-fields")), ); +function fileLinkSourcesKey( + text: string, + cwd: string | undefined, + imageBaseDir: string | undefined, +): string { + const hrefs = extractMarkdownLinkHrefs(renderCodexInlineDirectivesAsMarkdown(text)) + .filter((href) => !parseComposerContextHref(href)) + .map(normalizeMarkdownLinkHrefKey) + .filter((href) => resolveMarkdownFileLinkMeta(href, cwd, imageBaseDir ?? cwd)); + const spans = extractInlineCodeSpans(text).filter((span) => + resolveInlineCodeFileLinkMeta(span, cwd, imageBaseDir ?? cwd), + ); + return JSON.stringify([[...new Set(hrefs)], [...new Set(spans)]]); +} + +function resolveFileLinkSources( + key: string, + cwd: string | undefined, + imageBaseDir: string | undefined, +) { + const [hrefs, spans] = JSON.parse(key) as [string[], string[]]; + const markdownFileLinkMetaByHref = new Map(); + for (const href of hrefs) { + const meta = resolveMarkdownFileLinkMeta(href, cwd, imageBaseDir ?? cwd); + if (meta) markdownFileLinkMetaByHref.set(href, meta); + } + const inlineCodeFileLinkMetaByText = new Map(); + for (const span of spans) { + const meta = resolveInlineCodeFileLinkMeta(span, cwd, imageBaseDir ?? cwd); + if (meta) inlineCodeFileLinkMetaByText.set(span, meta); + } + const fileLinkParentSuffixByPath = buildFileLinkParentSuffixByPath([ + ...[...markdownFileLinkMetaByHref.values()].map((meta) => meta.filePath), + ...[...inlineCodeFileLinkMetaByText.values()].map((meta) => meta.filePath), + ]); + return { markdownFileLinkMetaByHref, inlineCodeFileLinkMetaByText, fileLinkParentSuffixByPath }; +} + function useChatMarkdownState({ text, inline = false, @@ -605,40 +644,6 @@ function useChatMarkdownState({ }); }; const diffThemeName = resolveDiffThemeName(resolvedTheme); - const markdownFileLinkMetaByHref = (() => { - const metaByHref = new Map< - string, - NonNullable> - >(); - for (const href of extractMarkdownLinkHrefs(renderCodexInlineDirectivesAsMarkdown(text))) { - if (parseComposerContextHref(href)) continue; - const normalizedHref = normalizeMarkdownLinkHrefKey(href); - if (metaByHref.has(normalizedHref)) continue; - const meta = resolveMarkdownFileLinkMeta(normalizedHref, cwd, imageBaseDir ?? cwd); - if (meta) { - metaByHref.set(normalizedHref, meta); - } - } - return metaByHref; - })(); - const inlineCodeFileLinkMetaByText = (() => { - const metaByText = new Map(); - for (const span of extractInlineCodeSpans(text)) { - if (metaByText.has(span)) continue; - const meta = resolveInlineCodeFileLinkMeta(span, cwd, imageBaseDir ?? cwd); - if (meta) { - metaByText.set(span, meta); - } - } - return metaByText; - })(); - const fileLinkParentSuffixByPath = (() => { - const filePaths = [ - ...[...markdownFileLinkMetaByHref.values()].map((meta) => meta.filePath), - ...[...inlineCodeFileLinkMetaByText.values()].map((meta) => meta.filePath), - ]; - return buildFileLinkParentSuffixByPath(filePaths); - })(); const markdownUrlTransform = (href: string) => { if (parseAssistantCitationHref(href)) return href; if (parseComposerContextHref(href)) return href; @@ -666,6 +671,12 @@ function useChatMarkdownState({ // Subscribe so hydrated settings apply before the anchor synchronously decides whether to intercept _blank. const linkTargetPreference = useClientSettings((settings) => settings.browserLinkTarget); const mathEnabled = useClientSettings((settings) => settings.mathRenderingEnabled); + // Keyed by the file links found, not the text, so streamed text that adds none keeps the + // renderer context, and every block reading it, unchanged. + // A template literal marks the key as a string, so the compiler memoizes the maps on its value. + const fileLinksKey = `${fileLinkSourcesKey(text, cwd, imageBaseDir)}`; + const { markdownFileLinkMetaByHref, inlineCodeFileLinkMetaByText, fileLinkParentSuffixByPath } = + resolveFileLinkSources(fileLinksKey, cwd, imageBaseDir); const resolveThreadPullRequest = ( href: string, ): (ThreadPullRequestKey & { readonly url: string }) | null => { @@ -1622,6 +1633,32 @@ const CHAT_MARKDOWN_COMPONENTS = { }, } satisfies Components; +const MarkdownSource = memo(function MarkdownSource({ + text, + remarkPlugins, + rehypePlugins, + urlTransform, +}: { + text: string; + remarkPlugins: NonNullable; + rehypePlugins: NonNullable; + urlTransform: ReactMarkdownOptions["urlTransform"]; +}) { + return ( + + + {text} + + + ); +}); + function ChatMarkdown({ text, className, @@ -1639,8 +1676,17 @@ function ChatMarkdown({ localMediaPreview, closeLocalMediaPreview, } = useChatMarkdownState({ text, inline, ...props }); + // Streaming re-renders only the last block; offsets for task edits need the whole text. + const streamingBlocks = + props.isStreaming === true && + !inline && + extraRemarkPlugins.length === 0 && + !props.onTaskListChange + ? splitMarkdownBlocks(text) + : null; const incrementalParsing = props.isStreaming === true && + streamingBlocks === null && extraRemarkPlugins.length === 0 && /(?:^|\n) {0,3}(?:`{3}|~{3})/.test(text); const Root = inline ? "span" : "div"; @@ -1668,21 +1714,20 @@ function ChatMarkdown({ onCopy={handleCopy} > - - ( + - {text} - - + /> + ))} {localMediaPreview ? ( diff --git a/apps/web/src/components/chat/markdownStreamBlocks.test.tsx b/apps/web/src/components/chat/markdownStreamBlocks.test.tsx new file mode 100644 index 0000000000000..ae81316580bbd --- /dev/null +++ b/apps/web/src/components/chat/markdownStreamBlocks.test.tsx @@ -0,0 +1,61 @@ +import { + CHAT_MARKDOWN_REHYPE_PLUGINS, + CHAT_MARKDOWN_REMARK_PLUGINS, +} from "@t3tools/shared/markdownPipeline"; +import { renderToStaticMarkup } from "react-dom/server"; +import ReactMarkdown from "react-markdown"; +import { describe, expect, it } from "vite-plus/test"; + +import { splitMarkdownBlocks } from "./markdownStreamBlocks"; + +// Whitespace between top-level blocks collapses in the rendered message. +const html = (source: string) => + renderToStaticMarkup( + + {source} + , + ) + .replace(/>\s+<") + .trim(); + +describe("splitMarkdownBlocks", () => { + it.each([ + "# Title\n\nFirst paragraph with `code` and **bold**.\n\nSecond [link](https://example.com).", + "- one\n- two\n\n- loose three\n\n continued\n\nAfter the list.", + "1. first\n\n2. second\n\nText\n\n3) restarted", + "```ts\nconst a = 1;\n\n\nconst b = 2;\n```\n\nafter\n\n~~~\nx\n\n~~~~\n\ny\n~~~\n\nend", + "> quote\n\n> another quote\n\n> [!NOTE]\n> alert", + "| a | b |\n| - | - |\n| 1 | 2 |\n\nAfter the table.", + "para\n\n indented code\n\nnext", + "Setext\n===\n\nnext\n---\n\n- [ ] task\n- [x] done", + ])("renders each block as the whole text renders it, at every streamed prefix: %j", (text) => { + for (let end = 0; end <= text.length; end++) { + const source = text.slice(0, end); + const blocks = splitMarkdownBlocks(source); + expect(blocks?.join("")).toBe(source); + expect(blocks!.map(html).join("")).toBe(html(source)); + } + }); + + it("splits only between closed blocks", () => { + expect(splitMarkdownBlocks("a\n\n```\nb\n\nc\n```\n\n- d\n\n- e\n\nf")).toEqual([ + "a\n\n", + "```\nb\n\nc\n```\n\n- d\n\n- e\n\n", + "f", + ]); + }); + + it.each([ + "[ref]\n\n[ref]: /later", + "a[^x]\n\n[^x]: note", + "
      \n\nbody\n\n
      ", + ":::note\n\ncontent\n\n:::", + "$$\na\n\nb\n$$", + "a\r\n\r\nb", + ])("keeps text with document-wide syntax whole: %j", (text) => { + expect(splitMarkdownBlocks(text)).toBeNull(); + }); +}); diff --git a/apps/web/src/components/chat/markdownStreamBlocks.ts b/apps/web/src/components/chat/markdownStreamBlocks.ts new file mode 100644 index 0000000000000..52415ae71977b --- /dev/null +++ b/apps/web/src/components/chat/markdownStreamBlocks.ts @@ -0,0 +1,43 @@ +// Definitions, footnotes, raw HTML, container directives and display math can tie blocks together. +const DOCUMENT_WIDE_SYNTAX = /^ {0,3}(?:\[[^\]\n]+\]:|<[A-Za-z!?/]|:::|\$\$)|\[\^/m; +const FENCE_PATTERN = /^ {0,3}(`{3,}|~{3,})/; +// After a blank line these still continue the previous block: a list item or indented content. +const CONTINUATION_PATTERN = /^(?:[ \t]|(?:[-*+]|\d{1,9}[.)])(?:[ \t]|$))/; + +/** + * Cuts Markdown at blank lines that close every open block, so each piece renders exactly as it + * would inside the whole text. Returns null when the text uses syntax that spans blocks. + */ +export function splitMarkdownBlocks(text: string): string[] | null { + if (text.includes("\r") || DOCUMENT_WIDE_SYNTAX.test(text)) return null; + const blocks: string[] = []; + let blockStart = 0; + let lineStart = 0; + let fence: string | null = null; + let afterBlankLine = false; + for (const line of text.split("\n")) { + const opener = FENCE_PATTERN.exec(line)?.[1]; + if (fence !== null) { + if ( + opener && + opener[0] === fence[0] && + opener.length >= fence.length && + line.trim() === opener + ) { + fence = null; + } + } else if (line.trim() === "") { + afterBlankLine = true; + } else { + if (afterBlankLine && lineStart > blockStart && !CONTINUATION_PATTERN.test(line)) { + blocks.push(text.slice(blockStart, lineStart)); + blockStart = lineStart; + } + afterBlankLine = false; + fence = opener ?? null; + } + lineStart += line.length + 1; + } + blocks.push(text.slice(blockStart)); + return blocks; +} diff --git a/apps/web/test/appScenarios.renders.tsx b/apps/web/test/appScenarios.renders.tsx index cc7d67798ddd9..5bb6836dd04a7 100644 --- a/apps/web/test/appScenarios.renders.tsx +++ b/apps/web/test/appScenarios.renders.tsx @@ -182,7 +182,7 @@ it("app-stream-assistant-turn", async () => { const counted = await measure(async () => { let text = ""; for (let delta = 0; delta < STREAM_DELTAS; delta++) { - text += `word${delta} `; + text += `word${delta}\n\n`; await act(() => emitThreadEvent(LIVE, { type: "turn-item.updated", @@ -204,6 +204,8 @@ it("app-stream-assistant-turn", async () => { // Only the streaming row changes; history rows must not re-render with it. expect(counted.components.UserTimelineRow).toBeUndefined(); expect(counted.components.AssistantTimelineRow).toBe(STREAM_DELTAS); + // Each delta adds a paragraph; finished blocks keep their render. + expect(counted.components.MarkdownParagraph).toBe(STREAM_DELTAS); await report("app-stream-assistant-turn", [counted], { commits: false }); }); From aaee7743f813984cdf2d266e99f22cea4f28ca6e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 30 Oct 2026 02:10:41 -0700 Subject: [PATCH 418/817] perf(web): the git actions panel no longer re-renders on every streamed update (#27418) Co-authored-by: Claude Opus 5.5 --- apps/web/src/components/GitActionsControl.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index cae352e6d6b26..a125ceacaed24 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -89,7 +89,7 @@ import { useVcsInitAction, useVcsPullAction, } from "../state/sourceControlActions"; -import { useThreadProjection, useQuietThreadShell } from "~/state/entities"; +import { useQuietThreadProjection, useQuietThreadShell } from "~/state/entities"; import { readEnvironmentScope, useEnvironmentScope } from "~/state/session"; import { useEnvironmentQuery } from "~/state/query"; import { serverEnvironment } from "~/state/server"; @@ -958,7 +958,7 @@ export default function GitActionsControl({ ? store.getDraftThreadByRef(activeThreadRef) : null, ); - const activeServerThreadProjection = useThreadProjection( + const activeServerThreadProjection = useQuietThreadProjection( activeDraftThread !== null && activeServerThreadShell === null ? null : activeThreadRef, ); const activeServerThread = From 3cbc98241d33f202b78c1ebe7e5b8f35f5d6ac29 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 30 Oct 2026 02:10:41 -0700 Subject: [PATCH 419/817] perf(web): streamed assistant text re-renders only its own row (#27419) Co-authored-by: Claude Opus 5.5 --- .../src/components/chat/ThreadTimeline.tsx | 7 +-- .../components/chat/TimelineAssistantRows.tsx | 10 +++- apps/web/src/state/entities.ts | 26 ++++++++++ apps/web/test/appScenarios.renders.tsx | 4 +- .../src/state/threadDetail.test.ts | 36 +++++++++++++ .../client-runtime/src/state/threadDetail.ts | 50 +++++++++++++++++++ 6 files changed, 127 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/chat/ThreadTimeline.tsx b/apps/web/src/components/chat/ThreadTimeline.tsx index 7d1db86178cf4..a68d494d8b0a0 100644 --- a/apps/web/src/components/chat/ThreadTimeline.tsx +++ b/apps/web/src/components/chat/ThreadTimeline.tsx @@ -2,7 +2,7 @@ import type { ScopedThreadRef } from "@t3tools/contracts"; import { type ComponentProps, useLayoutEffect } from "react"; import { useIncrementalTimelineEntries } from "../../hooks/useIncrementalTimelineEntries"; import type { TimelineEntriesInput, TimelineEntry } from "../../session-logic"; -import { useThreadVisibleTurnItems } from "../../state/entities"; +import { useTimelineVisibleTurnItems } from "../../state/entities"; import { peekRememberedThreadTimeline, rememberReadyThreadTimeline, @@ -14,7 +14,8 @@ import { MessagesTimeline } from "./MessagesTimeline"; /** * The timeline with the streamed text. ChatView reads the thread through its quiet * atoms, which hold through text deltas; this reads the live turn items, so a - * delta re-renders the timeline without re-rendering ChatView. + * reasoning delta re-renders the timeline without re-rendering ChatView. Streamed + * assistant text reaches only its own row, through useAssistantMessageText. */ export function ThreadTimeline({ threadDetailRef, @@ -34,7 +35,7 @@ export function ThreadTimeline({ syncing: boolean; detailLoading: boolean; }) { - const visibleTurnItems = useThreadVisibleTurnItems(threadDetailRef); + const visibleTurnItems = useTimelineVisibleTurnItems(threadDetailRef); const serverEntries = useIncrementalTimelineEntries(activeThreadKey, { ...entriesInput, visibleTurnItems, diff --git a/apps/web/src/components/chat/TimelineAssistantRows.tsx b/apps/web/src/components/chat/TimelineAssistantRows.tsx index 228eb6f79b9c3..458d84b9e982b 100644 --- a/apps/web/src/components/chat/TimelineAssistantRows.tsx +++ b/apps/web/src/components/chat/TimelineAssistantRows.tsx @@ -12,7 +12,7 @@ import { McpAppFrame } from "./McpAppFrame"; import { checkpointFileTotals } from "@t3tools/client-runtime/state/thread-checkpoints"; import { ChangedFilesCard } from "./ChangedFilesTree"; import { useFileContextMenuHandler } from "../../fileContextMenu"; -import { useProject, useThreadShell } from "../../state/entities"; +import { useAssistantMessageText, useProject, useThreadShell } from "../../state/entities"; import { MessageCopyButton } from "./MessageCopyButton"; import { AssistantCitationSource } from "./AssistantCitationSource"; import { resolveAssistantMessageCopyState } from "./MessagesTimeline.logic"; @@ -26,7 +26,13 @@ import { MESSAGE_HEADING_LEVEL, MessageAuthorHeading } from "./TimelineRowParts" export function AssistantTimelineRow({ row }: { row: Extract }) { const ctx = use(TimelineRowCtx); - const messageText = row.message.text || (row.message.streaming ? "" : "(empty response)"); + // The timeline holds a streaming message's row while only its text grows. + const liveText = useAssistantMessageText( + row.message.streaming ? ctx.threadRef : null, + row.projectedItem?.item.id, + ); + const text = liveText ?? row.message.text; + const messageText = text || (row.message.streaming ? "" : "(empty response)"); return ( <> diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.ts index 54b367df15b8b..0f94280768d4b 100644 --- a/apps/web/src/state/entities.ts +++ b/apps/web/src/state/entities.ts @@ -65,6 +65,9 @@ const EMPTY_VISIBLE_TURN_ITEMS_ATOM = Atom.make(EMPTY_VISIBLE_TURN_ITEMS).pipe( const EMPTY_CHECKPOINT_SUMMARIES_ATOM = Atom.make>( Object.freeze([]), ).pipe(Atom.withLabel("web-thread-checkpoint-summaries:empty")); +const EMPTY_ASSISTANT_MESSAGE_TEXT_ATOM = Atom.make(null).pipe( + Atom.withLabel("web-assistant-message-text:empty"), +); const EMPTY_LAST_VISITED_AT_ATOM = Atom.make(null).pipe( Atom.withLabel("web-thread-last-visited:empty"), ); @@ -212,6 +215,29 @@ export function useThreadVisibleTurnItems( ); } +/** Visible turn items held through streamed assistant text; see useAssistantMessageText. */ +export function useTimelineVisibleTurnItems( + ref: ScopedThreadRef | null, +): ReadonlyArray { + return useAtomValue( + ref === null + ? EMPTY_VISIBLE_TURN_ITEMS_ATOM + : environmentThreadDetails.timelineVisibleTurnItemsAtom(ref), + ); +} + +/** One assistant message's live text, or null when the thread does not hold the item. */ +export function useAssistantMessageText( + ref: ScopedThreadRef | null, + itemId: string | undefined, +): string | null { + return useAtomValue( + ref === null || itemId === undefined + ? EMPTY_ASSISTANT_MESSAGE_TEXT_ATOM + : environmentThreadDetails.assistantMessageTextAtom(ref, itemId), + ); +} + /** Visible turn items without their streamed text; see ThreadStructure. */ export function useQuietThreadVisibleTurnItems( ref: ScopedThreadRef | null, diff --git a/apps/web/test/appScenarios.renders.tsx b/apps/web/test/appScenarios.renders.tsx index 5bb6836dd04a7..459f3b9791d7f 100644 --- a/apps/web/test/appScenarios.renders.tsx +++ b/apps/web/test/appScenarios.renders.tsx @@ -201,7 +201,9 @@ it("app-stream-assistant-turn", async () => { .element(page.getByText(`word${STREAM_DELTAS - 1}`, { exact: false })) .toBeVisible(); }); - // Only the streaming row changes; history rows must not re-render with it. + // Only the streaming row changes. The timeline renders for the new item and its layout, not + // per delta, and history rows not at all. + expect(counted.components.ConversationTimeline).toBeLessThanOrEqual(3); expect(counted.components.UserTimelineRow).toBeUndefined(); expect(counted.components.AssistantTimelineRow).toBe(STREAM_DELTAS); // Each delta adds a paragraph; finished blocks keep their render. diff --git a/packages/client-runtime/src/state/threadDetail.test.ts b/packages/client-runtime/src/state/threadDetail.test.ts index 8fc01839183fe..3e66202d0bb4b 100644 --- a/packages/client-runtime/src/state/threadDetail.test.ts +++ b/packages/client-runtime/src/state/threadDetail.test.ts @@ -197,6 +197,42 @@ describe("quietThreadAtom", () => { }); }); +describe("timelineVisibleTurnItemsAtom", () => { + const ref = { environmentId: EnvironmentId.make("environment-1"), threadId: v2ThreadId }; + + it("holds through streamed assistant text while the message reads its own text", () => { + const stateAtom = Atom.make( + AsyncResult.success({ + ...EMPTY_ENVIRONMENT_THREAD_STATE, + data: Option.some(withItem(assistant)), + }), + ); + const details = createEnvironmentThreadDetailAtoms(() => stateAtom); + const timelineAtom = details.timelineVisibleTurnItemsAtom(ref); + const textAtom = details.assistantMessageTextAtom(ref, assistant.id); + const registry = AtomRegistry.make(); + registry.mount(timelineAtom); + registry.mount(textAtom); + const push = (item: OrchestrationV2TurnItem) => + registry.set( + stateAtom, + AsyncResult.success({ + ...EMPTY_ENVIRONMENT_THREAD_STATE, + data: Option.some(withItem(item, later)), + }), + ); + const first = registry.get(timelineAtom); + + push({ ...assistant, text: "Hello", updatedAt: later }); + expect(registry.get(timelineAtom)).toBe(first); + expect(registry.get(textAtom)).toBe("Hello"); + + push({ ...assistant, text: "Hello", streaming: false, status: "completed" }); + expect(registry.get(timelineAtom)[0]?.item).toMatchObject({ text: "Hello", streaming: false }); + registry.dispose(); + }); +}); + it("only compares replaced entries in a streamed reducer delta", () => { const size = 100; let slotReads = 0; diff --git a/packages/client-runtime/src/state/threadDetail.ts b/packages/client-runtime/src/state/threadDetail.ts index 3819c5d92ba5e..eeeda6a2f348f 100644 --- a/packages/client-runtime/src/state/threadDetail.ts +++ b/packages/client-runtime/src/state/threadDetail.ts @@ -148,6 +148,26 @@ function sameVisibleTurnItemStructure(before: VisibleTurnItem, after: VisibleTur ); } +function isStreamingAssistantMessage(visibleItem: VisibleTurnItem): boolean { + return visibleItem.item.type === "assistant_message" && visibleItem.item.streaming; +} + +/** Whether `next` only streams more text into assistant messages that were already streaming. */ +function sameApartFromStreamedAssistantText( + previous: OrchestrationV2ThreadProjection["visibleTurnItems"], + next: OrchestrationV2ThreadProjection["visibleTurnItems"], +): boolean { + return sameProjectionArray( + previous, + next, + (before, after) => + before === after || + (isStreamingAssistantMessage(before) && + isStreamingAssistantMessage(after) && + sameVisibleTurnItemStructure(before, after)), + ); +} + /** * Whether `previous` and `next` have the same ThreadStructure: they differ * only by text streamed into existing assistant and reasoning items or by a @@ -267,6 +287,32 @@ export function createEnvironmentThreadDetailAtoms( ); }); + // Holds while only streamed assistant text moves, so the timeline re-renders on structure; + // each streaming message reads its text through assistantMessageTextAtom. + const timelineVisibleTurnItemsAtomFamily = Atom.family((key: string) => { + let previous = EMPTY_VISIBLE_TURN_ITEMS; + return Atom.make((get) => { + const next = get(visibleTurnItemsAtomFamily(key)); + if (!sameApartFromStreamedAssistantText(previous, next)) previous = next; + return previous; + }).pipe( + Atom.setIdleTTL(0), + Atom.withLabel(`environment-thread-timeline-visible-turn-items:${key}`), + ); + }); + + const assistantMessageTextAtomFamily = Atom.family((key: string) => { + const separator = key.lastIndexOf("\u0000"); + const thread = key.slice(0, separator); + const itemId = key.slice(separator + 1); + return Atom.make((get) => { + const item = get(visibleTurnItemsAtomFamily(thread)).find( + (visibleItem) => visibleItem.item.id === itemId, + )?.item; + return item?.type === "assistant_message" ? item.text : null; + }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-assistant-message-text:${key}`)); + }); + const queueWorkflowAtomFamily = Atom.family((key: string) => { let previous: Pick< OrchestrationV2ThreadProjection, @@ -472,6 +518,10 @@ export function createEnvironmentThreadDetailAtoms( visibleTurnItemsAtom: (ref: ScopedThreadRef) => visibleTurnItemsAtomFamily(threadKey(ref)), quietVisibleTurnItemsAtom: (ref: ScopedThreadRef) => quietVisibleTurnItemsAtomFamily(threadKey(ref)), + timelineVisibleTurnItemsAtom: (ref: ScopedThreadRef) => + timelineVisibleTurnItemsAtomFamily(threadKey(ref)), + assistantMessageTextAtom: (ref: ScopedThreadRef, itemId: string) => + assistantMessageTextAtomFamily(`${threadKey(ref)}\u0000${itemId}`), statusAtom: (ref: ScopedThreadRef) => statusAtomFamily(threadKey(ref)), sequenceAtom: (ref: ScopedThreadRef) => sequenceAtomFamily(threadKey(ref)), errorAtom: (ref: ScopedThreadRef) => errorAtomFamily(threadKey(ref)), From 32ecd71726fee16f335484c1f95cbce126d461f6 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 30 Oct 2026 02:17:08 -0700 Subject: [PATCH 420/817] fix(server): `t3 service protect` can ask for your sudo password (#27465) Co-authored-by: Claude Opus 5.5 --- apps/server/src/cli/service.ts | 10 +++++++++- apps/server/src/cloud/serviceProtection.test.ts | 13 +++++++++---- apps/server/src/cloud/serviceProtection.ts | 3 +++ 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/apps/server/src/cli/service.ts b/apps/server/src/cli/service.ts index 62edb31d14b62..884cd28c9df87 100644 --- a/apps/server/src/cli/service.ts +++ b/apps/server/src/cli/service.ts @@ -314,6 +314,14 @@ const serviceProtectCommand = Command.make("protect", { ); } + yield* Console.log( + [ + "Keeps T3 Code running when agents fill this machine's memory:", + " - reserves memory for the T3 Code server, so the kernel takes memory from agents first", + " - makes the out-of-memory killer pick agents before the server", + "It adds systemd drop-in files and changes nothing else. Undo with `t3 service protect --undo`.", + ].join("\n"), + ); const names = remote.map((unit) => unit.replace(/\.service$/, "")).join(" and "); const protectRemote = remote.length > 0 && @@ -328,7 +336,7 @@ const serviceProtectCommand = Command.make("protect", { }); yield* Console.log( [ - "As root, through sudo:", + "Drop-ins it writes, as root through sudo:", ...formatDropIns(plan.system), "As you:", ...formatDropIns([plan.managerDefaults, ...plan.user]), diff --git a/apps/server/src/cloud/serviceProtection.test.ts b/apps/server/src/cloud/serviceProtection.test.ts index b2e4a1506cb31..eef78cd3f82e7 100644 --- a/apps/server/src/cloud/serviceProtection.test.ts +++ b/apps/server/src/cloud/serviceProtection.test.ts @@ -11,6 +11,7 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; +import type * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as ProcessRunner from "../processRunner.ts"; @@ -122,13 +123,13 @@ it.each([ expect(ServiceProtection.loadedRemoteAccessUnits(shown)).toEqual(expected); }); -const fakeSudo = (exitCode: number, onRun: () => void) => +const fakeSudo = (exitCode: number, onRun: (command: ChildProcess.StandardCommand) => void) => ChildProcessSpawner.make((command) => Effect.gen(function* () { if (command._tag !== "StandardCommand" || command.command !== "sudo") { return yield* Effect.die("Unexpected command"); } - onRun(); + onRun(command); return ChildProcessSpawner.makeHandle({ pid: ChildProcessSpawner.ProcessId(123), stdout: Stream.empty, @@ -180,11 +181,13 @@ it.effect("lowers no score before the manager default is in place, and undoes in writesManagerDropIn = false, ) => { let atSudo: ReturnType | undefined; + let sudoOptions: ChildProcess.CommandOptions | undefined; return effect.pipe( Effect.provideService( ChildProcessSpawner.ChildProcessSpawner, - fakeSudo(exitCode, () => { + fakeSudo(exitCode, (command) => { atSudo = present(); + sudoOptions = command.options; if (writesManagerDropIn) { NodeFS.mkdirSync(NodePath.dirname(managerDropIn), { recursive: true }); NodeFS.writeFileSync(managerDropIn, "[Service]\nOOMScoreAdjust=-900\n"); @@ -192,7 +195,7 @@ it.effect("lowers no score before the manager default is in place, and undoes in }), ), Effect.exit, - Effect.map((exit) => ({ exit, atSudo })), + Effect.map((exit) => ({ exit, atSudo, sudoOptions })), ); }; const refused = yield* withSudo(ServiceProtection.applyProtection(plan), 1); @@ -209,6 +212,8 @@ it.effect("lowers no score before the manager default is in place, and undoes in const applied = yield* withSudo(ServiceProtection.applyProtection(plan), 0); expect(applied.atSudo).toEqual({ managerDefaults: true, user: 0 }); + // sudo needs the controlling terminal to ask for a password. + expect(applied.sudoOptions).toMatchObject({ detached: false, stdin: "inherit" }); expect(present()).toEqual({ managerDefaults: true, user: plan.user.length }); const removed = yield* withSudo(ServiceProtection.removeProtection(plan), 0); diff --git a/apps/server/src/cloud/serviceProtection.ts b/apps/server/src/cloud/serviceProtection.ts index b23cd36e3a545..780aee83b4c48 100644 --- a/apps/server/src/cloud/serviceProtection.ts +++ b/apps/server/src/cloud/serviceProtection.ts @@ -240,7 +240,10 @@ const runPrivileged = Effect.fn("ServiceProtection.runPrivileged")(function* (sc const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const exitCode = yield* spawner .exitCode( + // Effect detaches children on POSIX by default; sudo then has no controlling + // terminal and cannot ask for a password. ChildProcess.make("sudo", ["/bin/sh", "-c", script], { + detached: false, stdin: "inherit", stdout: "inherit", stderr: "inherit", From 0f6de8c22c0bc694efe0926125b60b57e6ecf8cb Mon Sep 17 00:00:00 2001 From: Utkarsh Patil <73941998+UtkarshUsername@users.noreply.github.com> Date: Fri, 30 Oct 2026 18:10:47 +0530 Subject: [PATCH 421/817] fix(web): preserve Ctrl+Arrow terminal key sequences (#23480) --- apps/web/src/keybindings.test.ts | 26 ++++++++++++++++++++++ apps/web/src/keybindings.ts | 4 ---- apps/web/src/terminal/ghostty/core.test.ts | 21 +++++++++++++++++ 3 files changed, 47 insertions(+), 4 deletions(-) diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts index a0ba7fa7ee043..1f0a096fccaec 100644 --- a/apps/web/src/keybindings.test.ts +++ b/apps/web/src/keybindings.test.ts @@ -21,6 +21,7 @@ import { resolveShortcutCommand, shouldShowThreadJumpHintsForModifiers, shortcutLabelForCommand, + terminalNavigationShortcutData, type ShortcutEventLike, } from "./keybindings"; @@ -35,6 +36,31 @@ function event(overrides: Partial = {}): ShortcutEventLike { }; } +describe("terminal word navigation", () => { + it.each(["Win32", "Linux x86_64"])( + "leaves Ctrl+Arrow to the terminal encoder on %s", + (platform) => { + for (const key of ["ArrowLeft", "ArrowRight"]) { + assert.equal(terminalNavigationShortcutData(event({ key, ctrlKey: true }), platform), null); + } + }, + ); + + it.each(["Win32", "Linux x86_64", "MacIntel"])( + "preserves Alt+Arrow word navigation on %s", + (platform) => { + assert.equal( + terminalNavigationShortcutData(event({ key: "ArrowLeft", altKey: true }), platform), + "\u001bb", + ); + assert.equal( + terminalNavigationShortcutData(event({ key: "ArrowRight", altKey: true }), platform), + "\u001bf", + ); + }, + ); +}); + function modShortcut( key: string, overrides: Partial> = {}, diff --git a/apps/web/src/keybindings.ts b/apps/web/src/keybindings.ts index d3d3de58d3676..18c1b4c53c5a9 100644 --- a/apps/web/src/keybindings.ts +++ b/apps/web/src/keybindings.ts @@ -464,10 +464,6 @@ export function terminalNavigationShortcutData( return null; } - if (event.ctrlKey && !event.metaKey && !event.altKey) { - return moveWord; - } - if (event.altKey && !event.metaKey && !event.ctrlKey) { return moveWord; } diff --git a/apps/web/src/terminal/ghostty/core.test.ts b/apps/web/src/terminal/ghostty/core.test.ts index 69bf963ae34c4..7fc9661555e49 100644 --- a/apps/web/src/terminal/ghostty/core.test.ts +++ b/apps/web/src/terminal/ghostty/core.test.ts @@ -12,6 +12,7 @@ import { import { writeTerminalOutputUpdate } from "../../components/ThreadTerminalDrawer"; import { GHOSTTY_CELL_WIDE, GhosttyTerminalCore, ghosttyCellText } from "./core"; import { loadGhosttyRuntime } from "./runtime"; +import { terminalNavigationShortcutData } from "../../keybindings"; vi.mock("./vendor/ghostty-vt.wasm?url", async () => ({ default: (await import("./vendor/ghostty-vt.wasm?inline")).default, @@ -101,6 +102,26 @@ describe("GhosttyTerminalCore snapshots", () => { vi.restoreAllMocks(); }); + it.each([ + { key: "ArrowLeft", expected: "\x1b[1;5D" }, + { key: "ArrowRight", expected: "\x1b[1;5C" }, + ])("sends Ctrl+$key as a modified arrow instead of Alt+B/F", async ({ key, expected }) => { + const core = await createCore(); + const event = { + code: key, + key, + repeat: false, + shiftKey: false, + ctrlKey: true, + altKey: false, + metaKey: false, + isComposing: false, + getModifierState: () => false, + } as unknown as KeyboardEvent; + + expect(terminalNavigationShortcutData(event, "Win32") ?? core.encodeKey(event)).toBe(expected); + }); + it.each([ { code: "", key: "Backspace", expected: "\x7f" }, { code: "Unidentified", key: "Backspace", expected: "\x7f" }, From d1f1650f09bc51bad3146b572e0ec72730741c61 Mon Sep 17 00:00:00 2001 From: Utkarsh Patil <73941998+UtkarshUsername@users.noreply.github.com> Date: Fri, 30 Oct 2026 18:11:32 +0530 Subject: [PATCH 422/817] fix(web): keep PowerShell prompt paths with spaces in one link (#23527) --- apps/web/src/terminal-links.test.ts | 30 +++++++++++++++++++ apps/web/src/terminal-links.ts | 16 ++++++++-- apps/web/src/terminal/ghostty/surface.test.ts | 8 +++++ 3 files changed, 51 insertions(+), 3 deletions(-) diff --git a/apps/web/src/terminal-links.test.ts b/apps/web/src/terminal-links.test.ts index 05ed26959bee5..f6df5912ecdd1 100644 --- a/apps/web/src/terminal-links.test.ts +++ b/apps/web/src/terminal-links.test.ts @@ -16,6 +16,36 @@ function createBufferLine(text: string, isWrapped = false): TerminalBufferLineLi } describe("extractTerminalLinks", () => { + it.each([ + String.raw`C:\dev\ai-test\dir 1`, + String.raw`C:\dev\ai-test\dir 1\test`, + "C:\\", + String.raw`\\server\my share\dir 1`, + "/home/Jane Doe/project", + String.raw`C:\dev\folder (draft)\name!`, + ])("keeps the full PowerShell prompt path %s in one link", (path) => { + expect(extractTerminalLinks(`PS ${path}> `)).toEqual([ + { kind: "path", text: path, start: 3, end: 3 + path.length }, + ]); + }); + + it("keeps links in a command separate from the PowerShell prompt path", () => { + const path = String.raw`C:\dev\dir 1\test`; + const prompt = `PS ${path}> `; + const url = "https://example.com"; + expect(extractTerminalLinks(`${prompt}echo ${url}`)).toEqual([ + { kind: "path", text: path, start: 3, end: 3 + path.length }, + { kind: "url", text: url, start: prompt.length + 5, end: prompt.length + 5 + url.length }, + ]); + }); + + it("does not extend ordinary output paths through trailing prose", () => { + const path = String.raw`C:\dev\project`; + expect(extractTerminalLinks(`see ${path} for details`)).toEqual([ + { kind: "path", text: path, start: 4, end: 4 + path.length }, + ]); + }); + it.each([ String.raw`src\index.ts:12`, String.raw`.\src\index.ts:12:7`, diff --git a/apps/web/src/terminal-links.ts b/apps/web/src/terminal-links.ts index 48a7c16edbc61..1c078d86cd20f 100644 --- a/apps/web/src/terminal-links.ts +++ b/apps/web/src/terminal-links.ts @@ -27,6 +27,8 @@ export interface WrappedTerminalLinkLine { } const URL_PATTERN = /https?:\/\/[^\s"'`<>]+/giu; +// The default PowerShell prompt delimits its unquoted path with `PS ` and `>`. +const POWERSHELL_PROMPT_PATH_PATTERN = /^PS ((?:[A-Za-z]:[\\/]|\\\\|\/)[^>\r\n]*)>/u; // Bare paths start only at a segment boundary: hover detection runs this on // every frame, so separator-free output must not be rescanned at every suffix. const FILE_PATH_PATTERN = @@ -104,17 +106,25 @@ function collectMatches( } export function extractTerminalLinks(line: string): TerminalLinkMatch[] { + const promptPath = POWERSHELL_PROMPT_PATH_PATTERN.exec(line)?.[1]; + const promptMatches: TerminalLinkMatch[] = promptPath + ? [{ kind: "path", text: promptPath, start: 3, end: 3 + promptPath.length }] + : []; const requestRoutes = Array.from(line.matchAll(REQUEST_ROUTE_PATTERN), (match) => ({ start: match.index, end: match.index + match[0].length, })); - const urlMatches = collectMatches(line, "url", URL_PATTERN, []); - const quotedMatches = collectMatches(line, "path", QUOTED_FILE_PATH_PATTERN, urlMatches); + const urlMatches = collectMatches(line, "url", URL_PATTERN, promptMatches); + const quotedMatches = collectMatches(line, "path", QUOTED_FILE_PATH_PATTERN, [ + ...promptMatches, + ...urlMatches, + ]); const pathMatches = collectMatches(line, "path", FILE_PATH_PATTERN, [ + ...promptMatches, ...urlMatches, ...quotedMatches, ]); - return [...urlMatches, ...quotedMatches, ...pathMatches] + return [...promptMatches, ...urlMatches, ...quotedMatches, ...pathMatches] .filter( (match) => match.kind === "url" || !requestRoutes.some((route) => overlaps(match, route)), ) diff --git a/apps/web/src/terminal/ghostty/surface.test.ts b/apps/web/src/terminal/ghostty/surface.test.ts index 5473e3c4ffa1c..57018464df49f 100644 --- a/apps/web/src/terminal/ghostty/surface.test.ts +++ b/apps/web/src/terminal/ghostty/surface.test.ts @@ -606,12 +606,20 @@ describe("terminalLinkAtPositionWithRange", () => { row("com/reference", true), row("~/project/file", false), row("C:\\repo\\file.ts", false), + row("PS C:\\repo\\dir 1", false, true), + row("\\test> ", true), ]; expect(terminalLinkAtPositionWithRange(rows, 0, 8)?.text).toBe("https://example.com/reference"); expect(terminalLinkAtPositionWithRange(rows, 1, 4)?.text).toBe("https://example.com/reference"); expect(terminalLinkAtPositionWithRange(rows, 2, 2)?.text).toBe("~/project/file"); expect(terminalLinkAtPositionWithRange(rows, 3, 4)?.text).toBe("C:\\repo\\file.ts"); + expect(terminalLinkAtPositionWithRange(rows, 4, 13)).toEqual({ + text: "C:\\repo\\dir 1\\test", + range: { start: { x: 3, y: 4 }, end: { x: 4, y: 5 } }, + }); + expect(terminalLinkAtPositionWithRange(rows, 5, 2)?.text).toBe("C:\\repo\\dir 1\\test"); + expect(terminalLinkAtPositionWithRange(rows, 5, 5)).toBeNull(); expect(terminalLinkAtPositionWithRange(rows, 1, 4)).toEqual({ text: "https://example.com/reference", range: { From 8cb9182021bc4317f71b0f5e246d8ffb5b23d456 Mon Sep 17 00:00:00 2001 From: Utkarsh Patil <73941998+UtkarshUsername@users.noreply.github.com> Date: Fri, 30 Oct 2026 18:12:27 +0530 Subject: [PATCH 423/817] perf(client): find unread terminal chunks from the tail (#23779) --- .../src/state/terminalOutput.ts | 11 +++-- .../src/state/terminalSession.test.ts | 40 +++++++++++++++++++ 2 files changed, 48 insertions(+), 3 deletions(-) diff --git a/packages/client-runtime/src/state/terminalOutput.ts b/packages/client-runtime/src/state/terminalOutput.ts index 5c4f8422c1f7d..df4d2ee03955c 100644 --- a/packages/client-runtime/src/state/terminalOutput.ts +++ b/packages/client-runtime/src/state/terminalOutput.ts @@ -286,9 +286,14 @@ export function readTerminalOutputUpdate( return { type: "reset", data: terminalOutputText(output), cursor: nextCursor }; } - const appended = output.chunks.filter( - (chunk) => chunk.startOffset + chunk.data.length > cursor.offset, - ); + // Appends and compaction preserve offset order, so unread chunks form a suffix. + let firstUnread = output.chunks.length; + while (firstUnread > 0) { + const chunk = output.chunks[firstUnread - 1]!; + if (!(chunk.startOffset + chunk.data.length > cursor.offset)) break; + firstUnread -= 1; + } + const appended = output.chunks.slice(firstUnread); if (appended.length === 0) { return { type: "none", cursor: nextCursor }; } diff --git a/packages/client-runtime/src/state/terminalSession.test.ts b/packages/client-runtime/src/state/terminalSession.test.ts index a04504e00ee3b..7cbcd14f819fb 100644 --- a/packages/client-runtime/src/state/terminalSession.test.ts +++ b/packages/client-runtime/src/state/terminalSession.test.ts @@ -166,6 +166,46 @@ describe("terminal session reducers", () => { expect(readTerminalOutputUpdate(state.output, update.cursor).type).toBe("none"); }); + it("bounds historical chunk inspection when reading new tail output", () => { + let state = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, { + type: "snapshot", + snapshot: { ...BASE_SNAPSHOT, history: "" }, + }); + for (let index = 0; index < 512; index += 1) { + state = applyTerminalAttachStreamEvent(state, { + type: "output", + threadId: TARGET.threadId, + terminalId: TARGET.terminalId, + data: "history\r\n", + }); + } + const cursor = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR).cursor; + const next = applyTerminalAttachStreamEvent(state, { + type: "output", + threadId: TARGET.threadId, + terminalId: TARGET.terminalId, + data: "latest\r\n", + }); + let historicalChunkReads = 0; + const chunks = next.output.chunks.map((chunk, index) => + index < state.output.chunks.length + ? { + ...chunk, + get startOffset() { + historicalChunkReads += 1; + return chunk.startOffset; + }, + } + : chunk, + ); + + expect(readTerminalOutputUpdate({ ...next.output, chunks }, cursor)).toMatchObject({ + type: "append", + data: "latest\r\n", + }); + expect(historicalChunkReads).toBeLessThanOrEqual(2); + }); + it("preserves the byte-limited tail and resets a cursor before a partially trimmed chunk", () => { const initial = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, { type: "snapshot", From 6575ce32508bd7908444241f3719aa33aaf77f90 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Fri, 30 Oct 2026 13:44:34 +0100 Subject: [PATCH 424/817] fix(pi): explain when Pi's default model has no credentials (#27513) Co-authored-by: Claude Opus 5.5 Co-authored-by: GPT 6.1 Sol --- .../provider-pi/src/server/status.test.ts | 105 ++++++++++++++++-- packages/provider-pi/src/server/status.ts | 89 ++++++++++++++- 2 files changed, 177 insertions(+), 17 deletions(-) diff --git a/packages/provider-pi/src/server/status.test.ts b/packages/provider-pi/src/server/status.test.ts index cee6442fc9642..b8559d1ab7d8a 100644 --- a/packages/provider-pi/src/server/status.test.ts +++ b/packages/provider-pi/src/server/status.test.ts @@ -52,7 +52,15 @@ function piProbeSpawner(version: string) { }); } -const piDiscoverySpawner = (inventory: unknown) => +/** Fails the test if status runs `pi auth check` without `authCheck` or with other arguments. */ +const piDiscoverySpawner = ( + inventory: unknown, + options: { + readonly version?: string; + readonly state?: unknown; + readonly authCheck?: string | undefined; + } = {}, +) => Effect.gen(function* () { const stdout = yield* Queue.unbounded(); let stdinBuffer = ""; @@ -71,7 +79,9 @@ const piDiscoverySpawner = (inventory: unknown) => ? inventory : request.type === "get_commands" ? { commands: [] } - : {}; + : request.type === "get_state" + ? (options.state ?? {}) + : {}; yield* Queue.offer( stdout, encoder.encode( @@ -83,16 +93,23 @@ const piDiscoverySpawner = (inventory: unknown) => ); return ChildProcessSpawner.make((command) => { const args = ChildProcess.isStandardCommand(command) ? command.args : []; + if (args.includes("--version")) { + return Effect.succeed(processHandle({ stdout: `pi ${options.version ?? "0.84.3"}\n` })); + } + if (args[0] === "auth") { + const expected = ["auth", "check", "--provider", "openai", "--json", "--no-refresh"]; + return options.authCheck === undefined || args.join(" ") !== expected.join(" ") + ? Effect.die(`Unexpected pi ${args.join(" ")}`) + : Effect.succeed(processHandle({ stdout: options.authCheck, exitCode: 1 })); + } return Effect.succeed( - args.includes("--version") - ? processHandle({ stdout: "pi 0.84.3\n" }) - : ChildProcessSpawner.makeHandle({ - ...processHandle({}), - exitCode: Effect.never, - isRunning: Effect.succeed(true), - stdin, - stdout: Stream.fromQueue(stdout), - }), + ChildProcessSpawner.makeHandle({ + ...processHandle({}), + exitCode: Effect.never, + isRunning: Effect.succeed(true), + stdin, + stdout: Stream.fromQueue(stdout), + }), ); }); }); @@ -146,6 +163,72 @@ describe("PiProvider", () => { }).pipe(Effect.provide(NodeServices.layer)), ); + it.effect.each([ + { + label: "a pinned model without credentials", + version: "1.4.0", + activeModel: { provider: "openai", id: "gpt-5" }, + authCheck: '{"status":"not_ready","provider":"openai","reason":"credentials_not_configured"}', + message: "Pi default (openai/gpt-5) has no credentials configured for openai.", + }, + { + label: "a pinned model with a runtime --api-key", + version: "1.4.0", + launchArgs: "--provider openai --model gpt-5 --api-key fake-key", + activeModel: { provider: "openai", id: "gpt-5" }, + authCheck: undefined, + message: "Pi default (openai/gpt-5) uses openai, which has no available models in Pi.", + }, + { + label: "a pinned model whose provider auth check cannot find", + version: "1.4.0", + activeModel: { provider: "openai", id: "gpt-5" }, + authCheck: '{"status":"not_ready","provider":"openai","reason":"provider_not_found"}', + message: "Pi default (openai/gpt-5) uses openai, which has no available models in Pi.", + }, + { + label: "a pinned model on Pi without auth check", + version: MINIMUM_PI_VERSION, + activeModel: { provider: "openai", id: "gpt-5" }, + authCheck: undefined, + message: "Pi default (openai/gpt-5) uses openai, which has no available models in Pi.", + }, + { + label: "an uncatalogued model id of a provider with credentials", + version: "1.4.0", + activeModel: { provider: "anthropic", id: "claude-next" }, + authCheck: undefined, + message: undefined, + }, + { + label: "an extension model Pi lists as available", + version: "1.4.0", + activeModel: { provider: "router", id: "auto" }, + authCheck: undefined, + message: undefined, + }, + ])("diagnoses Pi's active model readiness for $label", (row) => + Effect.gen(function* () { + const spawner = yield* piDiscoverySpawner( + { + models: [ + { provider: "anthropic", id: "claude-sonnet-4" }, + { provider: "router", id: "auto" }, + ], + }, + { version: row.version, state: { model: row.activeModel }, authCheck: row.authCheck }, + ); + const snapshot = yield* checkPiProviderStatus({ + ...settings, + launchArgs: row.launchArgs ?? "", + }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)); + assert.equal(snapshot.status, "ready"); + assert.equal(snapshot.auth.status, "authenticated"); + if (row.message === undefined) assert.isUndefined(snapshot.message); + else assert.include(snapshot.message ?? "", row.message); + }).pipe(Effect.provide(NodeServices.layer)), + ); + // regression: #18498 a malformed model inventory must not restore stale Pi models it.effect.each([ ["missing models", {}], diff --git a/packages/provider-pi/src/server/status.ts b/packages/provider-pi/src/server/status.ts index eef8bb5be3552..a180ab9c41a3b 100644 --- a/packages/provider-pi/src/server/status.ts +++ b/packages/provider-pi/src/server/status.ts @@ -13,6 +13,7 @@ import * as Stream from "effect/Stream"; import * as Exit from "effect/Exit"; import * as Option from "effect/Option"; import * as Result from "effect/Result"; +import * as Schema from "effect/Schema"; import * as HttpClient from "effect/http/HttpClient"; import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; @@ -62,6 +63,12 @@ const PI_RPC_DISCOVERY_TIMEOUT_MS = 30_000; * Version 0.80.5 was the first published package containing both hooks. */ export const MINIMUM_PI_VERSION = "0.80.5"; +/** `pi auth check --json --no-refresh` arrived in 0.84.1. */ +const PI_AUTH_CHECK_VERSION = "0.84.1"; + +const decodePiAuthCheck = Schema.decodeUnknownOption( + Schema.fromJsonString(Schema.Struct({ reason: Schema.optional(Schema.String) })), +); const PI_DEFAULT_MODEL: ServerProviderModel = { slug: "default", @@ -73,6 +80,8 @@ const PI_DEFAULT_MODEL: ServerProviderModel = { interface PiDiscovery extends PiDiscoveredCommands { readonly models: ReadonlyArray; readonly authenticated: boolean; + /** Pi's active model when Pi lists no model of its provider, so it cannot start a turn. */ + readonly unavailableActiveModel: { readonly provider: string; readonly id: string } | undefined; } function piModelsFromSettings( @@ -169,11 +178,22 @@ const discoverPiViaRpc = Effect.fn("PiProviderStatus.discoverPiViaRpc")(function .pipe(Effect.orElseSucceed(() => undefined)); const discoveredModels = yield* Effect.fromResult(parseDiscoveredModels(modelsData, stateData)); const { slashCommands, skills } = parsePiDiscoveredCommands(commandsData); + // Pi lists only models of providers it holds credentials for, including extension, virtual and + // --api-key ones. Turns need only the provider's credentials, so uncatalogued model ids still run. + const activeModel = recordField(stateData, "model"); + const activeProvider = recordString(activeModel, "provider"); + const activeModelId = recordString(activeModel, "id"); return { models: discoveredModels, slashCommands: withPiBuiltinSlashCommands(slashCommands), skills, authenticated: discoveredModels.length > 0, + unavailableActiveModel: + activeProvider !== undefined && + activeModelId !== undefined && + !discoveredModels.some((model) => model.subProvider === activeProvider) + ? { provider: activeProvider, id: activeModelId } + : undefined, } satisfies PiDiscovery; }, Effect.scoped); @@ -221,6 +241,56 @@ const runPiVersionCommand = Effect.fn("PiProviderStatus.runPiVersionCommand")(fu ); }); +/** + * Explains why Pi's active model cannot start a turn. On Pi versions with `auth check`, asks it + * whether credentials are missing, without refreshing or printing them. That command cannot see + * extension providers or a runtime --api-key, so it only refines Pi's own unavailable verdict, + * and is skipped when launch args supply the key. + */ +const describeUnavailablePiModel = Effect.fn("PiProviderStatus.describeUnavailablePiModel")( + function* ( + piSettings: PiSettings, + environment: NodeJS.ProcessEnv, + version: string, + launchArgs: ReadonlyArray, + model: { readonly provider: string; readonly id: string }, + ) { + const label = `Pi default (${model.provider}/${model.id})`; + const unavailable = `${label} uses ${model.provider}, which has no available models in Pi. Choose another model, or check that provider's setup and the Pi launch arguments.`; + if ( + compareSemverVersions(version, PI_AUTH_CHECK_VERSION) < 0 || + launchArgs.includes("--api-key") + ) { + return unavailable; + } + const command = piSettings.binaryPath || "pi"; + const output = yield* resolveSpawnCommand( + command, + ["auth", "check", "--provider", model.provider, "--json", "--no-refresh"], + { env: environment }, + ).pipe( + Effect.flatMap((spawnCommand) => + spawnAndCollect( + command, + ChildProcess.make(spawnCommand.command, spawnCommand.args, { + env: environment, + shell: spawnCommand.shell, + }), + ), + ), + Effect.timeout(VERSION_PROBE_TIMEOUT_MS), + Effect.option, + ); + const missingCredentials = Option.exists( + Option.flatMap(output, (result) => decodePiAuthCheck(result.stdout)), + (check) => check.reason === "credentials_not_configured", + ); + return missingCredentials + ? `${label} has no credentials configured for ${model.provider}. Choose another model, or run \`pi\` in a terminal and use /login or configure its API key.` + : unavailable; + }, +); + export const buildInitialPiProviderSnapshot = Effect.fn( "PiProviderStatus.buildInitialPiProviderSnapshot", )(function* (piSettings: PiSettings): Effect.fn.Return { @@ -432,6 +502,17 @@ export const checkPiProviderStatus = Effect.fn("checkPiProviderStatus")(function const discovery = discoveryExit.value.value; const models = piModelsFromSettings(piSettings.customModels, discovery.models); + const message = !discovery.authenticated + ? "Pi has no usable models. Run `pi` in a terminal and use /login, or configure an API key in ~/.pi/agent." + : discovery.unavailableActiveModel === undefined + ? undefined + : yield* describeUnavailablePiModel( + piSettings, + environment, + version, + resolvedLaunchArgs.args, + discovery.unavailableActiveModel, + ); return buildServerProvider({ presentation: PI_PRESENTATION, enabled: piSettings.enabled, @@ -442,14 +523,10 @@ export const checkPiProviderStatus = Effect.fn("checkPiProviderStatus")(function probe: { installed: true, version, + // Other Pi models still work when only the default is unavailable, so keep the picker usable. status: discovery.authenticated ? "ready" : "warning", auth: { status: discovery.authenticated ? "authenticated" : "unauthenticated", type: "pi" }, - ...(discovery.authenticated - ? {} - : { - message: - "Pi has no usable models. Run `pi` in a terminal and use /login, or configure an API key in ~/.pi/agent.", - }), + ...(message === undefined ? {} : { message }), }, }); }); From 616c426f5f199865e34974777740dff678ffb7f5 Mon Sep 17 00:00:00 2001 From: maria Date: Fri, 30 Oct 2026 15:43:01 +0000 Subject: [PATCH 425/817] fix(shared): TypeScript files no longer show as videos (#27372) --- packages/shared/src/filePreview.test.ts | 3 +++ packages/shared/src/filePreview.ts | 5 +++-- packages/shared/src/image.ts | 3 +++ packages/shared/src/video.test.ts | 5 +++++ packages/shared/src/video.ts | 2 +- 5 files changed, 15 insertions(+), 3 deletions(-) diff --git a/packages/shared/src/filePreview.test.ts b/packages/shared/src/filePreview.test.ts index b6f4fc940874a..9024954ebf1ad 100644 --- a/packages/shared/src/filePreview.test.ts +++ b/packages/shared/src/filePreview.test.ts @@ -30,6 +30,9 @@ describe("workspace file previews", () => { expect(isWorkspacePreviewEntryPath(`${name}?download=1`)).toBe(false); expect(hostPreviewMimeTypeFromExtension(`.${extension}`)).toBe(mimeType); }); + it("previews a TypeScript file the OS labels as MPEG transport stream as text", () => { + expect(filePreviewKind({ name: "clamp.ts", mimeType: "video/mp2t" })).toBe("text"); + }); it("recognizes compound archives and MIME aliases", () => { expect(filePreviewKind({ name: "archive.tar.gz" })).toBe("archive"); expect(filePreviewKind({ name: "download", mimeType: "application/x-gzip" })).toBe("archive"); diff --git a/packages/shared/src/filePreview.ts b/packages/shared/src/filePreview.ts index 4155252a12a90..2cd77e2e59779 100644 --- a/packages/shared/src/filePreview.ts +++ b/packages/shared/src/filePreview.ts @@ -9,6 +9,7 @@ export { mediaKindFromPath, mediaMimeTypeFromExtension, } from "./mediaPreview.ts"; +import { GENERIC_MIME_TYPES } from "./image.ts"; import { videoMimeType } from "./video.ts"; export type FilePreviewKind = @@ -41,7 +42,7 @@ export function filePreviewKind( const mime = file.mimeType?.split(";", 1)[0]?.trim().toLowerCase() ?? ""; const name = file.name.toLowerCase(); const extension = name.slice(name.lastIndexOf(".")); - const generic = !mime || mime === "application/octet-stream" || mime === "text/plain"; + const generic = !mime || GENERIC_MIME_TYPES.has(mime) || mime === "text/plain"; const richDocuments = options?.richDocuments !== false; const office = richDocuments ? officePreviewKind(file) : null; if (office) return office; @@ -61,7 +62,7 @@ export function filePreviewKind( ) return "font"; if (mime.startsWith("image/")) return "image"; - if (mime.startsWith("video/")) return "video"; + if (mime.startsWith("video/") && !generic) return "video"; if (mime.startsWith("audio/")) return "audio"; if (generic) { if (extension === ".pdf") return "pdf"; diff --git a/packages/shared/src/image.ts b/packages/shared/src/image.ts index 30615c24f967c..3c219286ac234 100644 --- a/packages/shared/src/image.ts +++ b/packages/shared/src/image.ts @@ -13,6 +13,9 @@ export const GENERIC_MIME_TYPES = new Set([ "application/octet-stream", "binary/octet-stream", "application/unknown", + // macOS and Windows label TypeScript `.ts` files as MPEG transport streams, which browsers can't play. + "video/mp2t", + "video/vnd.dlna.mpeg-tts", ]); export function isSvgAttachment(attachment: { diff --git a/packages/shared/src/video.test.ts b/packages/shared/src/video.test.ts index 24ea54b5da835..7f5b29db8155c 100644 --- a/packages/shared/src/video.test.ts +++ b/packages/shared/src/video.test.ts @@ -14,4 +14,9 @@ describe("videoMimeType", () => { "video/webm", ); }); + + it("does not treat a TypeScript file the OS labels as MPEG transport stream as video", () => { + expect(videoMimeType({ name: "clamp.ts", mimeType: "video/mp2t" })).toBeNull(); + expect(videoMimeType({ name: "clamp.ts", mimeType: "video/vnd.dlna.mpeg-tts" })).toBeNull(); + }); }); diff --git a/packages/shared/src/video.ts b/packages/shared/src/video.ts index 7979f73e6d537..7e66fe8b8bf1a 100644 --- a/packages/shared/src/video.ts +++ b/packages/shared/src/video.ts @@ -17,7 +17,7 @@ export function videoMimeType(attachment: { readonly mimeType: string; }): string | null { const mimeType = attachment.mimeType.split(";", 1)[0]?.trim().toLowerCase() ?? ""; - if (mimeType.startsWith("video/")) return mimeType; + if (mimeType.startsWith("video/") && !GENERIC_MIME_TYPES.has(mimeType)) return mimeType; if (mimeType !== "" && !GENERIC_MIME_TYPES.has(mimeType)) return null; const dotIndex = attachment.name.lastIndexOf("."); return dotIndex < 0 From e4ecaf629dbcf68d10a043944845cfa096b729a8 Mon Sep 17 00:00:00 2001 From: maria Date: Fri, 30 Oct 2026 15:58:44 +0000 Subject: [PATCH 426/817] feat(mobile): message media, file cards and grouped steers match web (#27373) --- .../src/components/MediaVideoPlayer.tsx | 6 +- .../src/features/threads/ThreadFeed.tsx | 655 +++++++++++++----- .../features/threads/ThreadMarkdownVideo.tsx | 2 + .../threads/pending-thread-feed.test.ts | 66 ++ .../features/threads/pending-thread-feed.ts | 45 ++ apps/mobile/src/lib/composerImageGallery.ts | 17 + .../mobile/src/lib/filePreviewGallery.test.ts | 67 +- .../client-runtime/src/userMessage.test.ts | 152 +++- packages/client-runtime/src/userMessage.ts | 59 +- 9 files changed, 902 insertions(+), 167 deletions(-) diff --git a/apps/mobile/src/components/MediaVideoPlayer.tsx b/apps/mobile/src/components/MediaVideoPlayer.tsx index c6dc31ca00ad2..37a7d0e236f19 100644 --- a/apps/mobile/src/components/MediaVideoPlayer.tsx +++ b/apps/mobile/src/components/MediaVideoPlayer.tsx @@ -140,6 +140,7 @@ interface MediaVideoPlayerProps { readonly paused?: boolean; readonly onPlaybackStart?: () => void; readonly actionsSource?: MediaActionsSource; + readonly borderRadius?: number; } function MediaVideoPlayerContent(props: MediaVideoPlayerProps) { @@ -152,7 +153,10 @@ function MediaVideoPlayerContent(props: MediaVideoPlayerProps) { {playbackUri ? ( ["source"]; + readonly className: string; + readonly maxWidth?: number; + readonly height?: number; + readonly onLoad?: () => void; + readonly onError?: () => void; +}) { + const imageStyle = useResolveClassNames(props.className); + const [size, setSize] = useState<{ width: number; height: number } | null>(null); + const displaySize = + props.maxWidth !== undefined && size !== null + ? resolveMarkdownImageDisplaySize({ + sourceWidth: size.width, + sourceHeight: size.height, + availableWidth: props.maxWidth, + }) + : null; + return ( + { + if (props.maxWidth !== undefined) setSize(event.source); + props.onLoad?.(); + }} + onError={props.onError} + /> + ); +} + function MessageAttachmentImage(props: { readonly environmentId: EnvironmentId; readonly attachmentId: string; readonly name: string; readonly mimeType: string; readonly className: string; + readonly maxWidth?: number; + readonly height?: number; readonly onPressPreview: (source: FilePreviewSource) => void; }) { const withGallery = useFilePreviewGallery(); @@ -504,11 +555,19 @@ function MessageAttachmentImage(props: { const uri = useAssetUrl(props.environmentId, resource); const refreshAssetUrl = useRefreshAssetUrl(props.environmentId, resource); const retriedImage = useRef(false); - const imageStyle = useResolveClassNames(props.className); if (uri === null) { return ( - + ); @@ -537,11 +596,11 @@ function MessageAttachmentImage(props: { ) } > - { retriedImage.current = false; }} @@ -564,11 +623,21 @@ function isFileAttachment(attachment: ChatAttachment): attachment is ChatFileAtt return attachment.type === "file"; } +function isMediaAttachment(attachment: ChatAttachment): boolean { + return ( + isImageAttachment(attachment) || + (isFileAttachment(attachment) && videoMimeType(attachment) !== null) + ); +} + function MessageAttachmentFile(props: { readonly environmentId: EnvironmentId; readonly attachment: ChatFileAttachment; readonly onPressPreview: (source: FilePreviewSource) => void; readonly onPlaybackStart: () => void; + readonly standaloneMedia?: boolean; + readonly standaloneFile?: boolean; + readonly available?: boolean; }) { const sourceIdentifier = useId(); const navigation = useNavigation(); @@ -603,7 +672,7 @@ function MessageAttachmentFile(props: { ); const shareFile = (sourceIdentifier?: string) => { - if (httpBaseUrl === null || openingRef.current) return; + if (props.available === false || httpBaseUrl === null || openingRef.current) return; const controller = new AbortController(); openingRef.current = controller; setOpening(true); @@ -703,29 +772,34 @@ function MessageAttachmentFile(props: { if (videoType !== null) { return ( - + ); } + const disabled = props.available === false || opening || httpBaseUrl === null; return ( - <> - + + shareFile(sourceIdentifier)} onPress={openAttachment} > @@ -751,8 +825,205 @@ function MessageAttachmentFile(props: { type="monochrome" /> - - + {props.standaloneFile ? ( + shareFile(sourceIdentifier)} + > + + + ) : null} + + + ); +} + +function UserMessageMedia(props: { + readonly attachments: ReadonlyArray; + readonly pendingAttachments: QueuedThreadMessage["attachments"]; + readonly environmentId: EnvironmentId; + readonly maxWidth: number; + readonly onPressPreview: (source: FilePreviewSource) => void; + readonly onPlaybackStart: () => void; +}) { + const attachments = [...props.pendingAttachments, ...props.attachments]; + const collage = attachments.length > 1 && attachments.every(isImageAttachment); + const imageProps = (index: number) => ({ + className: "w-full bg-user-bubble-foreground/15", + maxWidth: collage ? undefined : props.maxWidth, + height: !collage + ? undefined + : attachments.length === 2 || (attachments.length === 3 && index === 0) + ? 192 + : attachments.length === 3 + ? (192 - StyleSheet.hairlineWidth) / 2 + : 96, + }); + const media = [ + ...props.pendingAttachments.map((attachment, index) => { + const image = isImageAttachment(attachment); + return { + id: attachment.id, + image, + content: + image && attachment.uploadedAttachmentId ? ( + + ) : !image && attachment.uploadedAttachmentId ? ( + + ) : ( + + ), + }; + }), + ...props.attachments.map((attachment, index) => ({ + id: attachment.id, + image: isImageAttachment(attachment), + content: isImageAttachment(attachment) ? ( + + ) : isFileAttachment(attachment) ? ( + + ) : null, + })), + ]; + return collage ? ( + + {media.length === 3 ? ( + + + {media[0]!.content} + + + {media[1]!.content} + {media[2]!.content} + + + ) : ( + media + .filter((_, index) => index % 2 === 0) + .map((item, index) => ( + + {item.content} + {media[index * 2 + 1] ? ( + {media[index * 2 + 1]!.content} + ) : null} + + )) + )} + + + ) : ( + + {media.map((item) => ( + + {item.content} + + + ))} + + ); +} + +function PendingMessageMedia(props: { + readonly attachment: QueuedThreadMessage["attachments"][number]; + readonly className: string; + readonly maxWidth?: number; + readonly height?: number; + readonly onPressPreview: (source: FilePreviewSource) => void; + readonly onPlaybackStart: () => void; +}) { + const withGallery = useFilePreviewGallery(); + const { attachment } = props; + const fileBacked = isFileBackedComposerAttachment(attachment); + const preview = useLocalAttachmentPreview(fileBacked ? attachment : null); + if (isImageAttachment(attachment)) { + const uri = fileBacked ? preview.uri : (attachment.dataUrl ?? attachment.previewUri); + return ( + { + const source = composerImageGallery([attachment])[0]; + if (source) props.onPressPreview(withGallery(source)); + }} + > + + + ); + } + if (preview.uri === null) { + return ( + + {preview.error ? ( + {preview.error.message} + ) : ( + + )} + + ); + } + return ( + ); } @@ -1338,6 +1609,7 @@ function renderFeedEntry( readonly contentWidth: number; readonly threadTitle: string; readonly workflowOpening: WorkflowOpening | null; + readonly userMessageGrouping: GroupedThreadFeedRow["userMessageGrouping"]; }, ) { const entry = info.item; @@ -1582,7 +1854,9 @@ function renderFeedEntry( const foldRowId = presentation.attribution === "agent" ? `agent:${message.id}` : null; const foldExpanded = foldRowId !== null && (props.expandedWorkRows[foldRowId] ?? false); const bubbleBodyVisible = foldRowId === null || foldExpanded; - const intentBadge = resolveUserMessageIntentBadge(message.inputIntent); + const intentBadge = props.userMessageGrouping.continuesSteer + ? null + : resolveUserMessageIntentBadge(message.inputIntent); const referenceIds = new Set( collectComposerContextReferences(message.text).map((reference) => reference.contextId), ); @@ -1593,22 +1867,36 @@ function renderFeedEntry( : [], ), ); + const standaloneMedia = foldRowId === null && presentation.attribution !== "guest"; + const mediaAttachments = standaloneMedia ? attachments.filter(isMediaAttachment) : []; const visibleAttachments = attachments.filter( - (attachment) => isImageAttachment(attachment) || !inlineAttachmentIds.has(attachment.id), + (attachment) => + !(standaloneMedia && isMediaAttachment(attachment)) && + (isImageAttachment(attachment) || !inlineAttachmentIds.has(attachment.id)), ); - // Images sent without words show as images, not as a bubble around them. - const mediaOnly = - foldRowId === null && - presentation.attribution !== "guest" && - presentation.text.trim() === "" && - visibleAttachments.length + (entry.pendingMessage?.attachments.length ?? 0) > 0 && - visibleAttachments.every(isImageAttachment) && - (entry.pendingMessage?.attachments ?? []).every( - (attachment) => attachment.type === "image", - ); + const pendingAttachments = entry.pendingMessage?.attachments ?? []; + const pendingMedia = standaloneMedia ? pendingAttachments.filter(isMediaAttachment) : []; + const pendingBubbleAttachments = standaloneMedia + ? pendingAttachments.filter( + (attachment) => + !isMediaAttachment(attachment) && !inlineAttachmentIds.has(attachment.id), + ) + : pendingAttachments; + const fileCards = standaloneMedia + ? resolveUserMessageFileCards({ + text: presentation.text, + attachments: attachments.length > 0 ? attachments : pendingAttachments, + context: message.context, + }) + : null; + const hasBubble = + fileCards === null && + (foldRowId !== null || + presentation.text.trim().length > 0 || + visibleAttachments.length + pendingBubbleAttachments.length > 0); return ( {presentation.attribution === "t3code" ? ( @@ -1619,136 +1907,174 @@ function renderFeedEntry( {presentation.guestName !== undefined ? ( ) : null} - 0) - ? { width: props.duoColumns ? "85%" : props.userBubbleMaxWidth } - : null), - }} - > - {presentation.attribution === "guest" ? : null} - {foldRowId !== null ? ( - 0 ? ( + + ref.label) - .split(/\r?\n/) - .find((line) => line.trim().length > 0) - ?.trim() ?? "" - } - expanded={foldExpanded} - onToggle={() => props.onToggleWorkRow(foldRowId, entry.id)} - iconSubtleColor={iconSubtleColor} + maxWidth={props.userBubbleMaxWidth} + onPressPreview={props.onPressPreview} + onPlaybackStart={props.onPlaybackStart} /> - ) : null} - {bubbleBodyVisible ? ( - - {entry.pendingMessage?.attachments.map((attachment) => - attachment.type === "image" && attachment.uploadedAttachmentId ? ( - - ) : attachment.type === "image" ? ( - - props.onPressPreview({ - kind: "image", - name: attachment.name, - uri: attachment.dataUrl ?? attachment.previewUri, - gallery: composerImageGallery(entry.pendingMessage?.attachments ?? []), - }) - } - > - + ) : null} + {fileCards ? ( + + {fileCards.map((file) => { + const pendingFile = pendingAttachments.find( + (attachment) => attachment.id === file.id, + ); + return ( + + ); + })} + + ) : null} + {hasBubble ? ( + + {presentation.attribution === "guest" ? : null} + {foldRowId !== null ? ( + ref.label) + .split(/\r?\n/) + .find((line) => line.trim().length > 0) + ?.trim() ?? "" + } + expanded={foldExpanded} + onToggle={() => props.onToggleWorkRow(foldRowId, entry.id)} + iconSubtleColor={iconSubtleColor} + /> + ) : null} + {bubbleBodyVisible ? ( + + {pendingBubbleAttachments.map((attachment) => + attachment.type === "image" && attachment.uploadedAttachmentId ? ( + - - ) : ( - - ), - )} - {/* An empty container still takes a gap, which pads every attachment-free bubble. */} - {visibleAttachments.length > 0 ? ( - - {visibleAttachments.map((attachment) => { - return isImageAttachment(attachment) ? ( - { + const source = composerImageGallery([attachment])[0]; + if (source) + props.onPressPreview({ + ...source, + gallery: composerImageGallery( + entry.pendingMessage?.attachments ?? [], + props.environmentId, + ), + }); + }} + > + - ) : isFileAttachment(attachment) ? ( - - ) : ( - - ); - })} - - ) : null} - {presentation.text.trim().length > 0 ? ( - - - - ) : null} - - ) : null} - + + ) : ( + + ), + )} + {/* An empty container still takes a gap, which pads every attachment-free bubble. */} + {visibleAttachments.length > 0 ? ( + + {visibleAttachments.map((attachment) => { + return isImageAttachment(attachment) ? ( + + ) : isFileAttachment(attachment) ? ( + + ) : ( + + ); + })} + + ) : null} + {presentation.text.trim().length > 0 ? ( + + + + ) : null} + + ) : null} + + ) : null} {bubbleBodyVisible ? ( {foldRowId !== null && message.senderThreadId ? ( @@ -2830,6 +3156,12 @@ export const ThreadFeed = memo(function ThreadFeed({ const setupAnchorIndex = presentedFeed.findIndex( (entry) => entry.type === "message" && entry.message.role === "user", ); + const [groupFeed] = useState(createThreadFeedGrouping); + const groupedFeed = groupFeed(presentedFeed, { + workflowOpeningMessageId: workflowOpening?.messageId, + setupAnchorIndex: + props.worktreeSetup || props.setupWorkingStartedAt ? setupAnchorIndex : undefined, + }); // The empty↔filled key below remounts the list and resets its imperative // content-inset override. Seed each fresh instance as it attaches with the // current overlay height before the scroll integration's next reaction; @@ -3149,7 +3481,7 @@ export const ThreadFeed = memo(function ThreadFeed({ } }, [textSizeKey, contentWidth, hasHtmlRenders, beginReflow, listRef]); - const renderItem = (info: { item: ThreadFeedRow; index: number }) => ( + const renderItem = (info: { item: GroupedThreadFeedRow; index: number }) => ( {renderFeedEntry(info, { + userMessageGrouping: info.item.userMessageGrouping, environmentId: props.environmentId, dispatchingMessageId: props.dispatchingMessageId, onEditPendingMessage: props.onEditPendingMessage, @@ -3284,7 +3617,7 @@ export const ThreadFeed = memo(function ThreadFeed({ maintainVisibleContentPosition={ followsEnd && !disclosureToggleSettling ? false : maintainVisibleContentPosition } - data={presentedFeed} + data={groupedFeed} extraData={listAppearanceData} renderItem={renderItem} viewabilityConfig={THREAD_MEDIA_VIEWABILITY_CONFIG} @@ -3422,7 +3755,7 @@ function MessageImageGalleryScope(props: { entry.type === "message" ? [ ...messageImageGallery(entry.message, { environmentId, threadId, workspaceRoot }), - ...composerImageGallery(entry.pendingMessage?.attachments ?? []), + ...composerImageGallery(entry.pendingMessage?.attachments ?? [], environmentId), ] : []; return {props.children}; diff --git a/apps/mobile/src/features/threads/ThreadMarkdownVideo.tsx b/apps/mobile/src/features/threads/ThreadMarkdownVideo.tsx index 5f4b5ec263d48..457b7878ea5e7 100644 --- a/apps/mobile/src/features/threads/ThreadMarkdownVideo.tsx +++ b/apps/mobile/src/features/threads/ThreadMarkdownVideo.tsx @@ -13,6 +13,7 @@ export function ThreadMarkdownVideo(props: { readonly source: MediaVideoPreviewSource; readonly thumbnailVisible?: boolean; readonly onPlaybackStart?: () => void; + readonly borderRadius?: number; }) { const { source } = props; const feedVisible = useContext(ThreadMediaVisibleContext); @@ -43,6 +44,7 @@ export function ThreadMarkdownVideo(props: { onPlaybackStart={props.onPlaybackStart} unavailable={"resource" in source && asset._tag === "Failure"} actionsSource={source.actionsSource} + borderRadius={props.borderRadius} /> ); } diff --git a/apps/mobile/src/features/threads/pending-thread-feed.test.ts b/apps/mobile/src/features/threads/pending-thread-feed.test.ts index 3d9463c79bd06..b16fab3a20a90 100644 --- a/apps/mobile/src/features/threads/pending-thread-feed.test.ts +++ b/apps/mobile/src/features/threads/pending-thread-feed.test.ts @@ -10,6 +10,7 @@ import { import type { QueuedThreadMessage } from "../../state/thread-outbox-model"; import { appendPendingThreadMessages, + createThreadFeedGrouping, isCompactionCommandFeedEntry, selectPendingAcknowledgedMessages, } from "./pending-thread-feed"; @@ -25,6 +26,71 @@ const pending = (id: string): QueuedThreadMessage => ({ }); describe("pending timeline messages", () => { + it("keeps unchanged row identities while text streams and updates adjacent grouping", () => { + const group = createThreadFeedGrouping(); + const [first, second, third] = appendPendingThreadMessages( + [], + [], + [pending("first"), pending("second"), pending("third")], + ); + if (first?.type !== "message" || second?.type !== "message" || third?.type !== "message") { + throw new Error("Expected message rows"); + } + const reply = { + ...third, + id: "reply", + message: { ...third.message, role: "assistant" as const, text: "start" }, + }; + const initial = group([first, second, reply], {}); + const streamed = group( + [first, second, { ...reply, message: { ...reply.message, text: "streamed" } }], + {}, + ); + expect(streamed[0]).toBe(initial[0]); + expect(streamed[1]).toBe(initial[1]); + expect(streamed[2]).not.toBe(initial[2]); + const appended = group([first, second, third, reply], {}); + expect(appended[0]).toBe(initial[0]); + expect(appended[1]).not.toBe(initial[1]); + expect(appended[1]?.userMessageGrouping.groupedWithNext).toBe(true); + expect(appended[2]?.userMessageGrouping.groupedWithPrevious).toBe(true); + const removed = group([first, second, reply], {}); + expect(removed[1]?.userMessageGrouping.groupedWithNext).toBe(false); + const steer = { + ...second, + message: { ...second.message, inputIntent: "promoted_queued_to_steer" as const }, + }; + const singleSteer = group([first, steer], {}); + const steers = group( + [{ ...first, message: { ...first.message, inputIntent: "steer" } }, steer], + {}, + ); + expect(steers[1]?.userMessageGrouping.continuesSteer).toBe(true); + expect(singleSteer[1]?.userMessageGrouping.continuesSteer).toBe(false); + expect(steers[1]).not.toBe(singleSteer[1]); + }); + + it("preserves setup, workflow, and compaction grouping boundaries", () => { + const group = createThreadFeedGrouping(); + const feed = appendPendingThreadMessages([], [], [pending("first"), pending("second")]); + expect(group(feed, {})[0]?.userMessageGrouping.groupedWithNext).toBe(true); + for (const options of [{ setupAnchorIndex: 0 }, { workflowOpeningMessageId: "first" }]) { + const rows = group(feed, options); + expect(rows[0]?.userMessageGrouping.groupedWithNext).toBe(false); + expect(rows[1]?.userMessageGrouping.groupedWithPrevious).toBe(false); + } + const compact = appendPendingThreadMessages( + [], + [], + [{ ...pending("compact"), text: "/compact" }], + )[0]!; + expect(group([feed[0]!, compact], {})[0]?.userMessageGrouping.groupedWithNext).toBe(true); + expect( + group([feed[0]!, { ...compact, pendingMessage: undefined }], {})[0]?.userMessageGrouping + .groupedWithNext, + ).toBe(false); + }); + it.each([false, true])( "keeps a queued compact command in the pending message row (attachment: %s)", (withAttachment) => { diff --git a/apps/mobile/src/features/threads/pending-thread-feed.ts b/apps/mobile/src/features/threads/pending-thread-feed.ts index d38cc026fdd62..586f8ff3b8820 100644 --- a/apps/mobile/src/features/threads/pending-thread-feed.ts +++ b/apps/mobile/src/features/threads/pending-thread-feed.ts @@ -6,6 +6,7 @@ import { import type { ThreadFeedEntry } from "../../lib/threadActivity"; import { scopedThreadKey } from "../../lib/scopedEntities"; import { threadHasCaughtUpTo } from "@t3tools/client-runtime/state/threads"; +import { resolveUserMessageGrouping } from "@t3tools/client-runtime/user-message"; import type { AcknowledgedThreadMessage, QueuedThreadMessage, @@ -53,6 +54,50 @@ export function selectPendingAcknowledgedMessages( /** A row of the thread feed's list. */ export type ThreadFeedRow = PendingThreadFeedEntry | GuestPendingFeedEntry; +export type GroupedThreadFeedRow = ThreadFeedRow & { + readonly userMessageGrouping: ReturnType; +}; + +export function createThreadFeedGrouping() { + const rows = new WeakMap(); + const ungrouped = resolveUserMessageGrouping(undefined, undefined, undefined); + return ( + feed: ReadonlyArray, + options: { readonly workflowOpeningMessageId?: string; readonly setupAnchorIndex?: number }, + ): ReadonlyArray => { + const groupingMessage = (index: number) => { + const entry = feed[index]; + return entry?.type === "message" && + entry.message.role === "user" && + !isCompactionCommandFeedEntry(entry) && + entry.message.id !== options.workflowOpeningMessageId + ? entry.message + : undefined; + }; + return feed.map((entry, index) => { + const message = groupingMessage(index); + const grouping = + message === undefined + ? ungrouped + : resolveUserMessageGrouping( + message, + index - 1 === options.setupAnchorIndex ? undefined : groupingMessage(index - 1), + index === options.setupAnchorIndex ? undefined : groupingMessage(index + 1), + ); + const previous = rows.get(entry); + if ( + previous?.userMessageGrouping.groupedWithPrevious === grouping.groupedWithPrevious && + previous.userMessageGrouping.groupedWithNext === grouping.groupedWithNext && + previous.userMessageGrouping.continuesSteer === grouping.continuesSteer + ) + return previous; + const row = { ...entry, userMessageGrouping: grouping }; + rows.set(entry, row); + return row; + }); + }; +} + /** Waiting guest messages go after the transcript, oldest first. */ export function appendGuestPendingMessages( presentedFeed: ReadonlyArray, diff --git a/apps/mobile/src/lib/composerImageGallery.ts b/apps/mobile/src/lib/composerImageGallery.ts index 3df558ae5d4db..f308dac2ff19b 100644 --- a/apps/mobile/src/lib/composerImageGallery.ts +++ b/apps/mobile/src/lib/composerImageGallery.ts @@ -1,12 +1,29 @@ import { imageMimeType } from "@t3tools/shared/image"; +import type { EnvironmentId } from "@t3tools/contracts"; import type { FilePreviewItem } from "../components/FilePreviewModal.types"; import { isFileBackedComposerAttachment, type DraftComposerAttachment } from "./composerImages"; export function composerImageGallery( attachments: readonly DraftComposerAttachment[], + environmentId?: EnvironmentId, ): FilePreviewItem[] { return attachments.flatMap((attachment): FilePreviewItem[] => { if (attachment.type !== "image" && imageMimeType(attachment) === null) return []; + if (environmentId !== undefined && attachment.uploadedAttachmentId) { + return [ + { + kind: "image", + name: attachment.name, + environmentId, + resource: { + _tag: "attachment", + attachmentId: attachment.uploadedAttachmentId, + fileName: attachment.name, + mimeType: attachment.mimeType, + }, + }, + ]; + } if (isFileBackedComposerAttachment(attachment)) { return [{ kind: "image", name: attachment.name, attachment }]; } diff --git a/apps/mobile/src/lib/filePreviewGallery.test.ts b/apps/mobile/src/lib/filePreviewGallery.test.ts index 95d52e5a7fe6e..60576317b95c9 100644 --- a/apps/mobile/src/lib/filePreviewGallery.test.ts +++ b/apps/mobile/src/lib/filePreviewGallery.test.ts @@ -1,9 +1,72 @@ -import { describe, expect, it } from "vite-plus/test"; -import { EnvironmentId } from "@t3tools/contracts"; +import { describe, expect, it, vi } from "vite-plus/test"; +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import type { FilePreviewItem } from "../components/FilePreviewModal.types"; +import type { DraftComposerAttachment } from "./composerImages"; +import { composerImageGallery } from "./composerImageGallery"; +import { messageImageGallery } from "../features/threads/messageImageGallery"; import { filePreviewGallery, filePreviewKey } from "./filePreviewGallery"; +vi.mock("./uuid", () => ({})); + describe("image preview groups", () => { + it.each([false, true])( + "keeps one entry per image through upload and delivery (file: %s)", + (fileBacked) => { + const environmentId = EnvironmentId.make("test"); + const context = { environmentId, threadId: ThreadId.make("thread"), workspaceRoot: null }; + const attachments: DraftComposerAttachment[] = ["a", "b"].map((id) => ({ + id, + type: "image", + name: `${id}.png`, + mimeType: "image/png", + sizeBytes: 3, + previewUri: `data:image/png;base64,${id}`, + ...(fileBacked ? { fileUri: `file:///documents/${id}.png` } : {}), + })); + const delivered = (id: string) => + messageImageGallery( + { + text: "", + attachments: [ + { + type: "image", + id: `uploaded-${id}`, + name: `${id}.png`, + mimeType: "image/png", + sizeBytes: 3, + }, + ], + }, + context, + )[0]!; + const local = composerImageGallery(attachments, environmentId); + const uploading = composerImageGallery( + [{ ...attachments[0]!, uploadedAttachmentId: "uploaded-a" }, attachments[1]!], + environmentId, + ); + const uploaded = composerImageGallery( + attachments.map((attachment) => ({ + ...attachment, + uploadedAttachmentId: `uploaded-${attachment.id}`, + })), + environmentId, + ); + for (const [selected, gallery] of [ + [local[0]!, local], + [delivered("a"), uploading], + [uploading[1]!, uploading], + [delivered("a"), uploaded], + [delivered("a"), [...uploaded, delivered("a"), delivered("b")]], + [delivered("a"), [delivered("a"), delivered("b")]], + ] as const) { + const result = filePreviewGallery(selected, gallery); + expect(result).toHaveLength(2); + expect(result.map(filePreviewKey)).toEqual([...new Set(gallery.map(filePreviewKey))]); + } + expect(composerImageGallery(attachments)).toEqual(local); + }, + ); + it("matches remote originals despite metadata and property order differences", () => { const environmentId = EnvironmentId.make("test"); const a: FilePreviewItem = { diff --git a/packages/client-runtime/src/userMessage.test.ts b/packages/client-runtime/src/userMessage.test.ts index 207939cf2f39d..44529f6c14557 100644 --- a/packages/client-runtime/src/userMessage.test.ts +++ b/packages/client-runtime/src/userMessage.test.ts @@ -1,9 +1,157 @@ import { describe, expect, it } from "vite-plus/test"; -import { GuestMessageId } from "@t3tools/contracts"; +import { ComposerContextId, GuestMessageId, ScheduledTaskId } from "@t3tools/contracts"; import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences"; -import { resolveUserMessagePresentation } from "./userMessage.ts"; +import { + resolveUserMessageFileCards, + resolveUserMessageGrouping, + resolveUserMessagePresentation, +} from "./userMessage.ts"; + +describe("resolveUserMessageGrouping", () => { + const own = { role: "user", text: "hello" }; + + it("groups only adjacent own messages", () => { + expect(resolveUserMessageGrouping(own, own, own)).toEqual({ + groupedWithPrevious: true, + groupedWithNext: true, + continuesSteer: false, + }); + expect(resolveUserMessageGrouping(own, undefined, own)).toMatchObject({ + groupedWithPrevious: false, + groupedWithNext: true, + }); + for (const boundary of [ + undefined, + { ...own, role: "assistant" }, + { ...own, createdBy: "agent" as const }, + { ...own, createdBy: "agent" as const, creationSource: "server" as const }, + { ...own, scheduledTaskId: ScheduledTaskId.make("task") }, + { + ...own, + context: { + guest: { guestMessageId: GuestMessageId.make("guest"), name: "Sam", text: "hi" }, + }, + }, + ]) { + expect(resolveUserMessageGrouping(own, boundary, boundary)).toEqual({ + groupedWithPrevious: false, + groupedWithNext: false, + continuesSteer: false, + }); + expect(resolveUserMessageGrouping(boundary, own, own)).toEqual({ + groupedWithPrevious: false, + groupedWithNext: false, + continuesSteer: false, + }); + } + }); + + it("shows one label for consecutive steers, including promoted queued messages", () => { + for (const inputIntent of ["steer", "promoted_queued_to_steer"] as const) { + const steer = { ...own, inputIntent }; + expect( + resolveUserMessageGrouping(steer, { ...own, inputIntent: "steer" }, undefined) + .continuesSteer, + ).toBe(true); + expect( + resolveUserMessageGrouping( + steer, + { ...own, inputIntent: "promoted_queued_to_steer" }, + undefined, + ).continuesSteer, + ).toBe(true); + expect(resolveUserMessageGrouping(steer, own, undefined).continuesSteer).toBe(false); + expect(resolveUserMessageGrouping(own, steer, undefined).continuesSteer).toBe(false); + } + }); +}); + +describe("resolveUserMessageFileCards", () => { + const file = { + type: "file" as const, + id: "report", + name: "report.pdf", + mimeType: "application/pdf", + sizeBytes: 1024, + }; + const record = { + ...file, + version: 1 as const, + kind: "file" as const, + contextId: ComposerContextId.make("report"), + label: file.name, + attachmentId: file.id, + }; + const context = { version: 1 as const, records: [record] }; + const reference = "[report.pdf](t3-context://v1/file/report)"; + + it("shows file cards for bare attachments and bound file references", () => { + for (const text of ["", " \n", reference]) { + expect(resolveUserMessageFileCards({ text, attachments: [file], context })).toEqual([file]); + } + expect( + resolveUserMessageFileCards({ + text: `${reference}\n${reference}`, + attachments: [file], + context, + }), + ).toEqual([file]); + }); + + it("keeps words and unavailable or non-file references in the bubble", () => { + for (const text of [ + `read ${reference}`, + "[missing.pdf](t3-context://v1/file/missing)", + "[report.pdf](t3-context://v1/mention/report)", + ]) { + expect(resolveUserMessageFileCards({ text, attachments: [file], context })).toBeNull(); + } + expect(resolveUserMessageFileCards({ text: reference, attachments: [file] })).toBeNull(); + expect( + resolveUserMessageFileCards({ + text: reference, + attachments: [file], + context: { + version: 1, + records: [ + { + version: 1, + kind: "file", + contextId: record.contextId, + label: file.name, + payload: {}, + }, + ], + }, + }), + ).toBeNull(); + expect( + resolveUserMessageFileCards({ + text: reference, + attachments: [{ ...file, id: "other" }], + context, + }), + ).toBeNull(); + }); + + it("keeps media, unknown attachments, and empty messages out of the file cards", () => { + const media = [ + { ...file, type: "image" as const, name: "photo.png", mimeType: "image/png" }, + { ...file, name: "photo.png", mimeType: "application/octet-stream" }, + { ...file, name: "clip.mp4", mimeType: "video/mp4" }, + { ...file, name: "clip.mov", mimeType: "application/octet-stream" }, + { ...file, name: "voice.mp3", mimeType: "audio/mpeg" }, + { ...file, type: "future" }, + ]; + expect(resolveUserMessageFileCards({ text: "", attachments: [] })).toBeNull(); + for (const attachment of media) { + expect(resolveUserMessageFileCards({ text: "", attachments: [attachment] })).toBeNull(); + expect(resolveUserMessageFileCards({ text: "", attachments: [file, attachment] })).toBeNull(); + } + }); +}); describe("resolveUserMessagePresentation", () => { const legacyText = "[Triggered by schedule task: Daily audit]\n\nCheck for crashes.\n"; diff --git a/packages/client-runtime/src/userMessage.ts b/packages/client-runtime/src/userMessage.ts index 8a80f31b155d0..a860c0188b9d2 100644 --- a/packages/client-runtime/src/userMessage.ts +++ b/packages/client-runtime/src/userMessage.ts @@ -1,11 +1,21 @@ import { + type ChatAttachment, + type ChatFileAttachment, type GuestMessageAttribution, + type OrchestrationMessageContext, type OrchestrationV2Actor, type OrchestrationV2CreationSource, type OrchestrationV2IdleCompaction, + type OrchestrationV2UserMessageInputIntent, ScheduledTaskId, } from "@t3tools/contracts"; -import { isAttachmentOnlyBootstrapPrompt } from "@t3tools/shared/composerContextReferences"; +import { + isAttachmentOnlyBootstrapPrompt, + replaceComposerContextReferences, +} from "@t3tools/shared/composerContextReferences"; +import { filePreviewKind } from "@t3tools/shared/filePreview"; +import { imageMimeType } from "@t3tools/shared/image"; +import { videoMimeType } from "@t3tools/shared/video"; /** The working row while T3 Code's own compaction runs. */ export const IDLE_COMPACTING_LABELS = { @@ -22,6 +32,32 @@ export const IDLE_COMPACTION_TITLES = { const LEGACY_AUTOMATION_PREFIX = /^\[Triggered by schedule task: [^\r\n]+\]\r?\n\r?\n/; const LEGACY_AUTOMATION_MESSAGE_ID = /^scheduled-task-message:(.+):\d+:(?:scheduled|manual)$/; +export function resolveUserMessageFileCards(message: { + readonly text: string; + readonly attachments: ReadonlyArray; + readonly context?: OrchestrationMessageContext | undefined; +}): ReadonlyArray | null { + const files = message.attachments.filter( + (attachment): attachment is ChatFileAttachment => + attachment.type === "file" && + imageMimeType(attachment) === null && + videoMimeType(attachment) === null && + filePreviewKind(attachment) !== "audio", + ); + if (files.length === 0 || files.length !== message.attachments.length) return null; + const fileIds = new Set(files.map((file) => file.id)); + const remaining = replaceComposerContextReferences(message.text, (reference) => { + const record = message.context?.records.find((item) => item.contextId === reference.contextId); + return reference.kind === "file" && + record?.kind === "file" && + "attachmentId" in record && + fileIds.has(record.attachmentId) + ? "" + : reference.label || reference.kind; + }); + return remaining.trim() === "" ? files : null; +} + export function resolveUserMessagePresentation(message: { readonly id?: string; readonly role: string; @@ -80,3 +116,24 @@ export function resolveUserMessagePresentation(message: { scheduledTaskId: undefined, }; } + +type GroupableUserMessage = Parameters[0] & { + readonly inputIntent?: OrchestrationV2UserMessageInputIntent; +}; + +export function resolveUserMessageGrouping( + message: GroupableUserMessage | undefined, + previous: GroupableUserMessage | undefined, + next: GroupableUserMessage | undefined, +) { + const isOwnMessage = (value: GroupableUserMessage | undefined) => + value?.role === "user" && resolveUserMessagePresentation(value).attribution === null; + const isSteer = (value: GroupableUserMessage | undefined) => + value?.inputIntent === "steer" || value?.inputIntent === "promoted_queued_to_steer"; + const groupedWithPrevious = isOwnMessage(message) && isOwnMessage(previous); + return { + groupedWithPrevious, + groupedWithNext: isOwnMessage(message) && isOwnMessage(next), + continuesSteer: groupedWithPrevious && isSteer(message) && isSteer(previous), + }; +} From f012fa210dbf464a5ea68fe9071ee377682f8d66 Mon Sep 17 00:00:00 2001 From: maria Date: Fri, 30 Oct 2026 16:01:03 +0000 Subject: [PATCH 427/817] fix(web): back-to-back messages from you stack as one burst with a single steer label (#27305) --- .../chat/MessagesTimeline.logic.test.ts | 68 +++++++++++++++++++ .../components/chat/MessagesTimeline.logic.ts | 40 +++++++++-- .../src/components/chat/MessagesTimeline.tsx | 22 +++--- .../chat/TimelineUserMessageRow.tsx | 5 +- 4 files changed, 118 insertions(+), 17 deletions(-) diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index bd74694dc46af..c9aec993bcd86 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -1390,6 +1390,74 @@ describe("deriveMessagesTimelineRows", () => { ]); }); + it("stacks back-to-back steers as one burst with a single steer label", () => { + const runId = RunId.make("double-steer-run"); + const time = (second: number) => new Date(Date.UTC(2026, 0, 1, 0, 0, second)).toISOString(); + const message = ( + id: string, + second: number, + role: "user" | "assistant", + inputIntent?: "turn_start" | "steer", + ): TimelineEntry => ({ + kind: "message", + id, + createdAt: time(second), + message: { + id: MessageId.make(id), + role, + text: id, + runId, + ...(inputIntent ? { inputIntent } : {}), + createdAt: time(second), + updatedAt: time(second), + streaming: false, + }, + }); + const prompt = message("prompt", 0, "user", "turn_start"); + const work: TimelineEntry = { + kind: "work", + id: "work", + createdAt: time(4), + entry: { id: "work", createdAt: time(4), runId, label: "Ran command", tone: "tool" }, + }; + const firstSteer = message("first-steer", 10, "user", "steer"); + const deriveRows = (timelineEntries: TimelineEntry[]) => + deriveMessagesTimelineRows({ + timelineEntries, + latestRun: { runId, status: "completed", startedAt: time(0), completedAt: time(30) }, + isWorking: false, + expandedRunIds: new Set(), + turnDiffSummaries: [], + supportsConversationRollback: false, + }); + // The second steer arrives while the first message object is reused, as live updates do. + const before = computeStableMessagesTimelineRows(deriveRows([prompt, work, firstSteer]), { + result: [], + byId: new Map(), + }); + const rows = computeStableMessagesTimelineRows( + deriveRows([ + prompt, + work, + firstSteer, + message("second-steer", 12, "user", "steer"), + message("final", 30, "assistant"), + ]), + before, + ).result; + + const byId = new Map(rows.map((row) => [row.id, row])); + expect(byId.get("prompt")).not.toHaveProperty("groupedWithNext"); + expect(byId.get("first-steer")).toMatchObject({ + groupedWithNext: true, + continuesSteer: false, + }); + expect(byId.get("second-steer")).toMatchObject({ + groupedWithNext: false, + continuesSteer: true, + }); + }); + it("keeps the previous turn folded while a newly sent message awaits its turn", () => { const rows = deriveMessagesTimelineRows({ timelineEntries: [ diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index c26bcf51a718a..1f22bc1c14978 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -1,4 +1,5 @@ import { worktreeSetupAgentStarted } from "@t3tools/client-runtime/worktree-setup"; +import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message"; import { isLiveSubagentTurnItem } from "@t3tools/client-runtime/state/subagentRuntime"; import * as DateTime from "effect/DateTime"; import * as Equal from "effect/Equal"; @@ -594,6 +595,10 @@ type MessagesTimelineRowContent = assistantCopyStreaming: boolean; assistantTurnDiffSummary?: TurnDiffSummary | undefined; revertTurnCount?: number | undefined; + /** Another of your messages follows directly, so the two sit closer together. */ + groupedWithNext?: boolean; + /** Set when the message above is a steer too, so the label shows once. */ + continuesSteer?: boolean; } | { kind: "assistant-meta"; @@ -2134,13 +2139,36 @@ export function deriveMessagesTimelineRows(input: { const result = attachTrailingToolGroupsToAssistant( attachCreatedThreadSummaries(nextRows, timelineEntries, collapsedFoldMemberIds), ); - return result.map((row, index) => - timelineRowIsWorkLog(row) && timelineRowIsWorkLog(result[index + 1]) - ? { ...row, continuesWorkLog: true } - : row, + return result.map((row, index) => { + if (timelineRowIsWorkLog(row) && timelineRowIsWorkLog(result[index + 1])) { + return { ...row, continuesWorkLog: true }; + } + if (!timelineRowIsOwnUserMessage(row)) return row; + const previous = result[index - 1]; + const groupedWithNext = timelineRowIsOwnUserMessage(result[index + 1]); + const continuesSteer = + timelineRowIsOwnUserMessage(previous) && + messageIsSteer(row.message) && + messageIsSteer(previous.message); + if (!groupedWithNext && !continuesSteer) return row; + return { ...row, groupedWithNext, continuesSteer }; + }); +} + +function timelineRowIsOwnUserMessage( + row: MessagesTimelineRow | undefined, +): row is Extract { + return ( + row?.kind === "message" && + row.message.role === "user" && + resolveUserMessagePresentation(row.message).attribution === null ); } +function messageIsSteer(message: ChatMessage): boolean { + return message.inputIntent === "steer" || message.inputIntent === "promoted_queued_to_steer"; +} + function timelineRowIsWorkLog(row: MessagesTimelineRow | undefined): boolean { return ( row !== undefined && @@ -2478,7 +2506,9 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean a.showAssistantCopyButton === bm.showAssistantCopyButton && a.assistantCopyStreaming === bm.assistantCopyStreaming && a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary && - a.revertTurnCount === bm.revertTurnCount + a.revertTurnCount === bm.revertTurnCount && + a.groupedWithNext === bm.groupedWithNext && + a.continuesSteer === bm.continuesSteer ); } } diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index faa733c76e896..8c779ee950d67 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -1441,16 +1441,18 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time ? undefined : row.kind === "turn-fold" || row.kind === "working" ? "pb-1.5" - : (row.kind === "message" && - row.message.role === "assistant" && - !row.showAssistantMeta) || - row.kind === "worktree-setup" || - row.kind === "event" || - row.kind === "attempt-fold" || - row.kind === "html-render" || - row.kind === "mcp-app" - ? "pb-2" - : "pb-4", + : row.kind === "message" && row.groupedWithNext + ? "pb-1" + : (row.kind === "message" && + row.message.role === "assistant" && + !row.showAssistantMeta) || + row.kind === "worktree-setup" || + row.kind === "event" || + row.kind === "attempt-fold" || + row.kind === "html-render" || + row.kind === "mcp-app" + ? "pb-2" + : "pb-4", (row.kind === "message" && row.message.role === "assistant") || row.kind === "assistant-meta" ? "group/assistant" diff --git a/apps/web/src/components/chat/TimelineUserMessageRow.tsx b/apps/web/src/components/chat/TimelineUserMessageRow.tsx index c4363a1b45983..58785db77ca47 100644 --- a/apps/web/src/components/chat/TimelineUserMessageRow.tsx +++ b/apps/web/src/components/chat/TimelineUserMessageRow.tsx @@ -484,8 +484,9 @@ function UserTimelineRow({ row }: { row: Extract
      ) : null} - {row.message.inputIntent === "steer" || - row.message.inputIntent === "promoted_queued_to_steer" ? ( + {(row.message.inputIntent === "steer" || + row.message.inputIntent === "promoted_queued_to_steer") && + !row.continuesSteer ? ( ) : null}
      Date: Fri, 30 Oct 2026 17:09:22 +0100 Subject: [PATCH 428/817] fix(pi): clear Pi's native queue before Stop aborts (#27514) Co-authored-by: Claude Opus 5.5 Co-authored-by: GPT 6.1 Sol --- .../pi_transcript.ndjson | 10 ++- .../pi_transcript.ndjson | 10 ++- .../provider-pi/src/server/adapter.test.ts | 69 +++++++++++++++++ packages/provider-pi/src/server/adapter.ts | 75 +++++++++++++++---- 4 files changed, 141 insertions(+), 23 deletions(-) diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_after_stop/pi_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_after_stop/pi_transcript.ndjson index ffdecab232a55..a024d2db1416e 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_after_stop/pi_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_after_stop/pi_transcript.ndjson @@ -133,7 +133,9 @@ {"type":"emit_inbound","label":"tool_execution_start","frame":{"type":"tool_execution_start","toolCallId":"call_8ac3cb4177994abdb9aa1c57","toolName":"bash","args":{"command":"node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"","timeout":35}}} {"type":"emit_inbound","label":"tool_execution_update","frame":{"type":"tool_execution_update","toolCallId":"call_8ac3cb4177994abdb9aa1c57","toolName":"bash","args":{"command":"node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"","timeout":35},"partialResult":{"content":[]}}} {"type":"emit_inbound","label":"tool_execution_update","frame":{"type":"tool_execution_update","toolCallId":"call_8ac3cb4177994abdb9aa1c57","toolName":"bash","args":{"command":"node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"","timeout":35},"partialResult":{"content":[{"type":"text","text":"interrupt fixture tool started\n"}],"details":{}}}} -{"type":"expect_outbound","label":"abort","frame":{"type":"abort","id":"t3-9"}} +{"type":"expect_outbound","label":"clear_queue","frame":{"type":"clear_queue","id":"t3-9"}} +{"type":"emit_inbound","label":"response:clear_queue","frame":{"id":"t3-9","type":"response","command":"clear_queue","success":true,"data":{"steering":[],"followUp":[]}}} +{"type":"expect_outbound","label":"abort","frame":{"type":"abort","id":"t3-10"}} {"type":"emit_inbound","label":"tool_execution_end","frame":{"type":"tool_execution_end","toolCallId":"call_8ac3cb4177994abdb9aa1c57","toolName":"bash","result":{"content":[{"type":"text","text":"interrupt fixture tool started\n\n\nCommand aborted"}],"details":{}},"isError":true}} {"type":"emit_inbound","label":"message_start","frame":{"type":"message_start","message":{"role":"toolResult","toolCallId":"call_8ac3cb4177994abdb9aa1c57","toolName":"bash","content":[{"type":"text","text":"interrupt fixture tool started\n\n\nCommand aborted"}],"details":{},"isError":true,"timestamp":1767225606463}}} {"type":"emit_inbound","label":"message_end","frame":{"type":"message_end","message":{"role":"toolResult","toolCallId":"call_8ac3cb4177994abdb9aa1c57","toolName":"bash","content":[{"type":"text","text":"interrupt fixture tool started\n\n\nCommand aborted"}],"details":{},"isError":true,"timestamp":1767225606463}}} @@ -144,9 +146,9 @@ {"type":"emit_inbound","label":"turn_end","frame":{"type":"turn_end","message":{"role":"assistant","content":[],"api":"openai-completions","provider":"openrouter","model":"deepseek/deepseek-v4-flash","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"error","errorMessage":"This operation was aborted","timestamp":1767225606465,"thinkingLevel":"high"},"toolResults":[]}} {"type":"emit_inbound","label":"agent_end","frame":{"type":"agent_end","messages":[{"role":"user","content":[{"type":"text","text":"Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally."}],"timestamp":1767225601969},{"role":"assistant","content":[{"type":"thinking","thinking":"The user wants me to run a command that will wait for 30 seconds, and then after it completes, respond with a specific message. But they also say \"Do not answer until it completes\" - but this command will run for 30 seconds and then naturally finish. However, the response they want is \"interrupt fixture should not finish naturally\" which contradicts the fact that it did finish naturally.\n\nWait, let me re-read. They want me to run the command and not answer until it completes. The command is a node script that logs \"interrupt fixture tool started\" and then waits 30 seconds. If I wait for it to complete, it will finish naturally after 30 seconds. But the response they want is \"interrupt fixture should not finish naturally\" - implying that the fixture should have been interrupted before finishing naturally.\n\nThis is a test scenario. Let me just run it and see what happens. Actually, maybe they want me to just run it and respond accordingly. Let me execute the command.\n\nActually, I think this is part of a test where the system might interrupt/kill the process. Let me just run the command with a sufficient timeout.","thinkingSignature":""},{"type":"toolCall","id":"call_8ac3cb4177994abdb9aa1c57","name":"bash","arguments":{"command":"node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"","timeout":35}}],"api":"openai-completions","provider":"openrouter","model":"deepseek/deepseek-v4-flash","usage":{"input":77,"output":317,"cacheRead":1792,"cacheWrite":0,"reasoning":284,"totalTokens":2186,"cost":{"input":0.00000322322,"output":0.000026539239999999998,"cacheRead":0.000015002623999999998,"cacheWrite":0,"total":0.000044765084}},"stopReason":"toolUse","timestamp":1767225601972,"responseId":"gen-1790898593-E5hfYfRp6aKBI57pUKss","rawStopReason":"tool_calls","thinkingLevel":"high"},{"role":"toolResult","toolCallId":"call_8ac3cb4177994abdb9aa1c57","toolName":"bash","content":[{"type":"text","text":"interrupt fixture tool started\n\n\nCommand aborted"}],"details":{},"isError":true,"timestamp":1767225606463},{"role":"assistant","content":[],"api":"openai-completions","provider":"openrouter","model":"deepseek/deepseek-v4-flash","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"error","errorMessage":"This operation was aborted","timestamp":1767225606465,"thinkingLevel":"high"}],"willRetry":false}} {"type":"emit_inbound","label":"agent_settled","frame":{"type":"agent_settled"}} -{"type":"emit_inbound","label":"response:abort","frame":{"id":"t3-9","type":"response","command":"abort","success":true}} -{"type":"expect_outbound","label":"get_entries","frame":{"type":"get_entries","since":"b184b5a8","id":"t3-10"}} -{"type":"emit_inbound","label":"response:get_entries","frame":{"id":"t3-10","type":"response","command":"get_entries","success":true,"data":{"entries":[{"type":"message","id":"ee73daae","parentId":"b184b5a8","timestamp":"2026-01-01T00:00:01.971Z","message":{"role":"user","content":[{"type":"text","text":"Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally."}],"timestamp":1767225601969}},{"type":"message","id":"c3915df7","parentId":"ee73daae","timestamp":"2026-01-01T00:00:06.406Z","message":{"role":"assistant","content":[{"type":"thinking","thinking":"The user wants me to run a command that will wait for 30 seconds, and then after it completes, respond with a specific message. But they also say \"Do not answer until it completes\" - but this command will run for 30 seconds and then naturally finish. However, the response they want is \"interrupt fixture should not finish naturally\" which contradicts the fact that it did finish naturally.\n\nWait, let me re-read. They want me to run the command and not answer until it completes. The command is a node script that logs \"interrupt fixture tool started\" and then waits 30 seconds. If I wait for it to complete, it will finish naturally after 30 seconds. But the response they want is \"interrupt fixture should not finish naturally\" - implying that the fixture should have been interrupted before finishing naturally.\n\nThis is a test scenario. Let me just run it and see what happens. Actually, maybe they want me to just run it and respond accordingly. Let me execute the command.\n\nActually, I think this is part of a test where the system might interrupt/kill the process. Let me just run the command with a sufficient timeout.","thinkingSignature":""},{"type":"toolCall","id":"call_8ac3cb4177994abdb9aa1c57","name":"bash","arguments":{"command":"node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"","timeout":35}}],"api":"openai-completions","provider":"openrouter","model":"deepseek/deepseek-v4-flash","usage":{"input":77,"output":317,"cacheRead":1792,"cacheWrite":0,"reasoning":284,"totalTokens":2186,"cost":{"input":0.00000322322,"output":0.000026539239999999998,"cacheRead":0.000015002623999999998,"cacheWrite":0,"total":0.000044765084}},"stopReason":"toolUse","timestamp":1767225601972,"responseId":"gen-1790898593-E5hfYfRp6aKBI57pUKss","rawStopReason":"tool_calls","thinkingLevel":"high"}},{"type":"message","id":"641f3d3f","parentId":"c3915df7","timestamp":"2026-01-01T00:00:06.463Z","message":{"role":"toolResult","toolCallId":"call_8ac3cb4177994abdb9aa1c57","toolName":"bash","content":[{"type":"text","text":"interrupt fixture tool started\n\n\nCommand aborted"}],"details":{},"isError":true,"timestamp":1767225606463}},{"type":"message","id":"e3ab1495","parentId":"641f3d3f","timestamp":"2026-01-01T00:00:06.465Z","message":{"role":"assistant","content":[],"api":"openai-completions","provider":"openrouter","model":"deepseek/deepseek-v4-flash","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"error","errorMessage":"This operation was aborted","timestamp":1767225606465,"thinkingLevel":"high"}}],"leafId":"e3ab1495"}}} +{"type":"emit_inbound","label":"response:abort","frame":{"id":"t3-10","type":"response","command":"abort","success":true}} +{"type":"expect_outbound","label":"get_entries","frame":{"type":"get_entries","since":"b184b5a8","id":"t3-11"}} +{"type":"emit_inbound","label":"response:get_entries","frame":{"id":"t3-11","type":"response","command":"get_entries","success":true,"data":{"entries":[{"type":"message","id":"ee73daae","parentId":"b184b5a8","timestamp":"2026-01-01T00:00:01.971Z","message":{"role":"user","content":[{"type":"text","text":"Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally."}],"timestamp":1767225601969}},{"type":"message","id":"c3915df7","parentId":"ee73daae","timestamp":"2026-01-01T00:00:06.406Z","message":{"role":"assistant","content":[{"type":"thinking","thinking":"The user wants me to run a command that will wait for 30 seconds, and then after it completes, respond with a specific message. But they also say \"Do not answer until it completes\" - but this command will run for 30 seconds and then naturally finish. However, the response they want is \"interrupt fixture should not finish naturally\" which contradicts the fact that it did finish naturally.\n\nWait, let me re-read. They want me to run the command and not answer until it completes. The command is a node script that logs \"interrupt fixture tool started\" and then waits 30 seconds. If I wait for it to complete, it will finish naturally after 30 seconds. But the response they want is \"interrupt fixture should not finish naturally\" - implying that the fixture should have been interrupted before finishing naturally.\n\nThis is a test scenario. Let me just run it and see what happens. Actually, maybe they want me to just run it and respond accordingly. Let me execute the command.\n\nActually, I think this is part of a test where the system might interrupt/kill the process. Let me just run the command with a sufficient timeout.","thinkingSignature":""},{"type":"toolCall","id":"call_8ac3cb4177994abdb9aa1c57","name":"bash","arguments":{"command":"node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"","timeout":35}}],"api":"openai-completions","provider":"openrouter","model":"deepseek/deepseek-v4-flash","usage":{"input":77,"output":317,"cacheRead":1792,"cacheWrite":0,"reasoning":284,"totalTokens":2186,"cost":{"input":0.00000322322,"output":0.000026539239999999998,"cacheRead":0.000015002623999999998,"cacheWrite":0,"total":0.000044765084}},"stopReason":"toolUse","timestamp":1767225601972,"responseId":"gen-1790898593-E5hfYfRp6aKBI57pUKss","rawStopReason":"tool_calls","thinkingLevel":"high"}},{"type":"message","id":"641f3d3f","parentId":"c3915df7","timestamp":"2026-01-01T00:00:06.463Z","message":{"role":"toolResult","toolCallId":"call_8ac3cb4177994abdb9aa1c57","toolName":"bash","content":[{"type":"text","text":"interrupt fixture tool started\n\n\nCommand aborted"}],"details":{},"isError":true,"timestamp":1767225606463}},{"type":"message","id":"e3ab1495","parentId":"641f3d3f","timestamp":"2026-01-01T00:00:06.465Z","message":{"role":"assistant","content":[],"api":"openai-completions","provider":"openrouter","model":"deepseek/deepseek-v4-flash","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"error","errorMessage":"This operation was aborted","timestamp":1767225606465,"thinkingLevel":"high"}}],"leafId":"e3ab1495"}}} {"type":"expect_outbound","label":"process_start@p2","frame":{"type":"process_start","args":["--mode","rpc","--provider","openrouter","--model","deepseek/deepseek-v4-flash","--no-extensions","--no-skills","--no-prompt-templates","--no-context-files","--approve","--extension",""]}} {"type":"expect_outbound","label":"switch_session@p2","frame":{"type":"switch_session","sessionPath":"/pi-sessions/session-1.jsonl","id":"t3-0"}} {"type":"emit_inbound","label":"extension_ui_request@p2","frame":{"type":"extension_ui_request","id":"00000000-0000-4000-8000-000000000003","method":"notify","message":"t3-code MCP unavailable: T3_MCP_URL or T3_MCP_BEARER_TOKEN is missing.","notifyType":"warning"}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt_mid_tool/pi_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt_mid_tool/pi_transcript.ndjson index d4db23f4fd8e3..072994e9d82a9 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt_mid_tool/pi_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt_mid_tool/pi_transcript.ndjson @@ -41,7 +41,9 @@ {"type":"emit_inbound","label":"message_end","frame":{"type":"message_end","message":{"role":"assistant","content":[{"type":"thinking","thinking":"The user wants me to run a specific command and wait for it to complete. Let me execute it.","thinkingSignature":""},{"type":"toolCall","id":"call_9726ad99cc114832996228eb","name":"bash","arguments":{"command":"node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"","timeout":35}}],"api":"openai-completions","provider":"openrouter","model":"deepseek/deepseek-v4-flash","usage":{"input":1830,"output":102,"cacheRead":0,"cacheWrite":0,"reasoning":23,"totalTokens":1932,"cost":{"input":0.0000766038,"output":0.00000853944,"cacheRead":0,"cacheWrite":0,"total":0.00008514324}},"stopReason":"toolUse","timestamp":1767225600401,"responseId":"gen-1790898592-Mzq78XbaTGiNE3YSafgy","rawStopReason":"tool_calls","thinkingLevel":"high"}}} {"type":"emit_inbound","label":"tool_execution_start","frame":{"type":"tool_execution_start","toolCallId":"call_9726ad99cc114832996228eb","toolName":"bash","args":{"command":"node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"","timeout":35}}} {"type":"emit_inbound","label":"tool_execution_update","frame":{"type":"tool_execution_update","toolCallId":"call_9726ad99cc114832996228eb","toolName":"bash","args":{"command":"node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"","timeout":35},"partialResult":{"content":[]}}} -{"type":"expect_outbound","label":"abort","frame":{"type":"abort","id":"t3-6"}} +{"type":"expect_outbound","label":"clear_queue","frame":{"type":"clear_queue","id":"t3-6"}} +{"type":"emit_inbound","label":"response:clear_queue","frame":{"id":"t3-6","type":"response","command":"clear_queue","success":true,"data":{"steering":[],"followUp":[]}}} +{"type":"expect_outbound","label":"abort","frame":{"type":"abort","id":"t3-7"}} {"type":"emit_inbound","label":"tool_execution_end","frame":{"type":"tool_execution_end","toolCallId":"call_9726ad99cc114832996228eb","toolName":"bash","result":{"content":[{"type":"text","text":"Command aborted"}],"details":{}},"isError":true}} {"type":"emit_inbound","label":"message_start","frame":{"type":"message_start","message":{"role":"toolResult","toolCallId":"call_9726ad99cc114832996228eb","toolName":"bash","content":[{"type":"text","text":"Command aborted"}],"details":{},"isError":true,"timestamp":1767225602282}}} {"type":"emit_inbound","label":"message_end","frame":{"type":"message_end","message":{"role":"toolResult","toolCallId":"call_9726ad99cc114832996228eb","toolName":"bash","content":[{"type":"text","text":"Command aborted"}],"details":{},"isError":true,"timestamp":1767225602282}}} @@ -52,6 +54,6 @@ {"type":"emit_inbound","label":"turn_end","frame":{"type":"turn_end","message":{"role":"assistant","content":[],"api":"openai-completions","provider":"openrouter","model":"deepseek/deepseek-v4-flash","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"error","errorMessage":"This operation was aborted","timestamp":1767225602287,"thinkingLevel":"high"},"toolResults":[]}} {"type":"emit_inbound","label":"agent_end","frame":{"type":"agent_end","messages":[{"role":"system","content":"","sections":{"preamble":"","tools":"","rules":"","docs":"","cwd":""},"timestamp":1790898591817,"toolsAdded":[{"name":"read","description":"Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to 2000 lines or 50KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.","parameters":{"type":"object","required":["path"],"properties":{"path":{"type":"string","description":"Path to the file to read (relative or absolute)"},"offset":{"type":"number","description":"Line number to start reading from (1-indexed)"},"limit":{"type":"number","description":"Maximum number of lines to read"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"bash","description":"Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last 2000 lines or 50KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.","parameters":{"type":"object","required":["command"],"properties":{"command":{"type":"string","description":"Shell command to execute"},"timeout":{"type":"number","description":"Timeout in seconds (optional, no default timeout)"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"edit","description":"Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.","parameters":{"type":"object","required":["path","edits"],"properties":{"path":{"type":"string","description":"Path to the file to edit (relative or absolute)"},"edits":{"type":"array","items":{"type":"object","required":["oldText","newText"],"properties":{"oldText":{"type":"string","description":"Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call."},"newText":{"type":"string","description":"Replacement text for this targeted edit."}}},"description":"One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead."}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"write","description":"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.","parameters":{"type":"object","required":["path","content"],"properties":{"path":{"type":"string","description":"Path to the file to write (relative or absolute)"},"content":{"type":"string","description":"Content to write to the file"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}}]},{"role":"user","content":[{"type":"text","text":"Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally."}],"timestamp":1767225600375},{"role":"assistant","content":[{"type":"thinking","thinking":"The user wants me to run a specific command and wait for it to complete. Let me execute it.","thinkingSignature":""},{"type":"toolCall","id":"call_9726ad99cc114832996228eb","name":"bash","arguments":{"command":"node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"","timeout":35}}],"api":"openai-completions","provider":"openrouter","model":"deepseek/deepseek-v4-flash","usage":{"input":1830,"output":102,"cacheRead":0,"cacheWrite":0,"reasoning":23,"totalTokens":1932,"cost":{"input":0.0000766038,"output":0.00000853944,"cacheRead":0,"cacheWrite":0,"total":0.00008514324}},"stopReason":"toolUse","timestamp":1767225600401,"responseId":"gen-1790898592-Mzq78XbaTGiNE3YSafgy","rawStopReason":"tool_calls","thinkingLevel":"high"},{"role":"toolResult","toolCallId":"call_9726ad99cc114832996228eb","toolName":"bash","content":[{"type":"text","text":"Command aborted"}],"details":{},"isError":true,"timestamp":1767225602282},{"role":"assistant","content":[],"api":"openai-completions","provider":"openrouter","model":"deepseek/deepseek-v4-flash","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"error","errorMessage":"This operation was aborted","timestamp":1767225602287,"thinkingLevel":"high"}],"willRetry":false}} {"type":"emit_inbound","label":"agent_settled","frame":{"type":"agent_settled"}} -{"type":"emit_inbound","label":"response:abort","frame":{"id":"t3-6","type":"response","command":"abort","success":true}} -{"type":"expect_outbound","label":"get_entries","frame":{"type":"get_entries","since":"4405fe6a","id":"t3-7"}} -{"type":"emit_inbound","label":"response:get_entries","frame":{"id":"t3-7","type":"response","command":"get_entries","success":true,"data":{"entries":[{"type":"model_change","id":"b78c2012","parentId":"4405fe6a","timestamp":"2026-01-01T00:00:00.366Z","provider":"openrouter","modelId":"deepseek/deepseek-v4-flash"},{"type":"session_info","id":"9dea9c23","parentId":"b78c2012","timestamp":"2026-01-01T00:00:00.370Z","name":"Replay fixture: turn_interrupt_mid_tool"},{"type":"message","id":"8dc98fa4","parentId":"9dea9c23","timestamp":"2026-01-01T00:00:00.379Z","message":{"role":"system","content":"","sections":{"preamble":"","tools":"","rules":"","docs":"","cwd":""},"timestamp":1790898591817,"toolsAdded":[{"name":"read","description":"Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to 2000 lines or 50KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.","parameters":{"type":"object","required":["path"],"properties":{"path":{"type":"string","description":"Path to the file to read (relative or absolute)"},"offset":{"type":"number","description":"Line number to start reading from (1-indexed)"},"limit":{"type":"number","description":"Maximum number of lines to read"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"bash","description":"Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last 2000 lines or 50KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.","parameters":{"type":"object","required":["command"],"properties":{"command":{"type":"string","description":"Shell command to execute"},"timeout":{"type":"number","description":"Timeout in seconds (optional, no default timeout)"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"edit","description":"Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.","parameters":{"type":"object","required":["path","edits"],"properties":{"path":{"type":"string","description":"Path to the file to edit (relative or absolute)"},"edits":{"type":"array","items":{"type":"object","required":["oldText","newText"],"properties":{"oldText":{"type":"string","description":"Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call."},"newText":{"type":"string","description":"Replacement text for this targeted edit."}}},"description":"One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead."}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"write","description":"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.","parameters":{"type":"object","required":["path","content"],"properties":{"path":{"type":"string","description":"Path to the file to write (relative or absolute)"},"content":{"type":"string","description":"Content to write to the file"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}}]}},{"type":"message","id":"b36f8c4a","parentId":"8dc98fa4","timestamp":"2026-01-01T00:00:00.379Z","message":{"role":"user","content":[{"type":"text","text":"Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally."}],"timestamp":1767225600375}},{"type":"message","id":"8ea47a23","parentId":"b36f8c4a","timestamp":"2026-01-01T00:00:02.246Z","message":{"role":"assistant","content":[{"type":"thinking","thinking":"The user wants me to run a specific command and wait for it to complete. Let me execute it.","thinkingSignature":""},{"type":"toolCall","id":"call_9726ad99cc114832996228eb","name":"bash","arguments":{"command":"node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"","timeout":35}}],"api":"openai-completions","provider":"openrouter","model":"deepseek/deepseek-v4-flash","usage":{"input":1830,"output":102,"cacheRead":0,"cacheWrite":0,"reasoning":23,"totalTokens":1932,"cost":{"input":0.0000766038,"output":0.00000853944,"cacheRead":0,"cacheWrite":0,"total":0.00008514324}},"stopReason":"toolUse","timestamp":1767225600401,"responseId":"gen-1790898592-Mzq78XbaTGiNE3YSafgy","rawStopReason":"tool_calls","thinkingLevel":"high"}},{"type":"message","id":"aa5aec89","parentId":"8ea47a23","timestamp":"2026-01-01T00:00:02.282Z","message":{"role":"toolResult","toolCallId":"call_9726ad99cc114832996228eb","toolName":"bash","content":[{"type":"text","text":"Command aborted"}],"details":{},"isError":true,"timestamp":1767225602282}},{"type":"message","id":"206b2637","parentId":"aa5aec89","timestamp":"2026-01-01T00:00:02.287Z","message":{"role":"assistant","content":[],"api":"openai-completions","provider":"openrouter","model":"deepseek/deepseek-v4-flash","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"error","errorMessage":"This operation was aborted","timestamp":1767225602287,"thinkingLevel":"high"}}],"leafId":"206b2637"}}} +{"type":"emit_inbound","label":"response:abort","frame":{"id":"t3-7","type":"response","command":"abort","success":true}} +{"type":"expect_outbound","label":"get_entries","frame":{"type":"get_entries","since":"4405fe6a","id":"t3-8"}} +{"type":"emit_inbound","label":"response:get_entries","frame":{"id":"t3-8","type":"response","command":"get_entries","success":true,"data":{"entries":[{"type":"model_change","id":"b78c2012","parentId":"4405fe6a","timestamp":"2026-01-01T00:00:00.366Z","provider":"openrouter","modelId":"deepseek/deepseek-v4-flash"},{"type":"session_info","id":"9dea9c23","parentId":"b78c2012","timestamp":"2026-01-01T00:00:00.370Z","name":"Replay fixture: turn_interrupt_mid_tool"},{"type":"message","id":"8dc98fa4","parentId":"9dea9c23","timestamp":"2026-01-01T00:00:00.379Z","message":{"role":"system","content":"","sections":{"preamble":"","tools":"","rules":"","docs":"","cwd":""},"timestamp":1790898591817,"toolsAdded":[{"name":"read","description":"Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to 2000 lines or 50KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.","parameters":{"type":"object","required":["path"],"properties":{"path":{"type":"string","description":"Path to the file to read (relative or absolute)"},"offset":{"type":"number","description":"Line number to start reading from (1-indexed)"},"limit":{"type":"number","description":"Maximum number of lines to read"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"bash","description":"Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last 2000 lines or 50KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.","parameters":{"type":"object","required":["command"],"properties":{"command":{"type":"string","description":"Shell command to execute"},"timeout":{"type":"number","description":"Timeout in seconds (optional, no default timeout)"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"edit","description":"Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.","parameters":{"type":"object","required":["path","edits"],"properties":{"path":{"type":"string","description":"Path to the file to edit (relative or absolute)"},"edits":{"type":"array","items":{"type":"object","required":["oldText","newText"],"properties":{"oldText":{"type":"string","description":"Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call."},"newText":{"type":"string","description":"Replacement text for this targeted edit."}}},"description":"One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead."}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"write","description":"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.","parameters":{"type":"object","required":["path","content"],"properties":{"path":{"type":"string","description":"Path to the file to write (relative or absolute)"},"content":{"type":"string","description":"Content to write to the file"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}}]}},{"type":"message","id":"b36f8c4a","parentId":"8dc98fa4","timestamp":"2026-01-01T00:00:00.379Z","message":{"role":"user","content":[{"type":"text","text":"Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally."}],"timestamp":1767225600375}},{"type":"message","id":"8ea47a23","parentId":"b36f8c4a","timestamp":"2026-01-01T00:00:02.246Z","message":{"role":"assistant","content":[{"type":"thinking","thinking":"The user wants me to run a specific command and wait for it to complete. Let me execute it.","thinkingSignature":""},{"type":"toolCall","id":"call_9726ad99cc114832996228eb","name":"bash","arguments":{"command":"node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"","timeout":35}}],"api":"openai-completions","provider":"openrouter","model":"deepseek/deepseek-v4-flash","usage":{"input":1830,"output":102,"cacheRead":0,"cacheWrite":0,"reasoning":23,"totalTokens":1932,"cost":{"input":0.0000766038,"output":0.00000853944,"cacheRead":0,"cacheWrite":0,"total":0.00008514324}},"stopReason":"toolUse","timestamp":1767225600401,"responseId":"gen-1790898592-Mzq78XbaTGiNE3YSafgy","rawStopReason":"tool_calls","thinkingLevel":"high"}},{"type":"message","id":"aa5aec89","parentId":"8ea47a23","timestamp":"2026-01-01T00:00:02.282Z","message":{"role":"toolResult","toolCallId":"call_9726ad99cc114832996228eb","toolName":"bash","content":[{"type":"text","text":"Command aborted"}],"details":{},"isError":true,"timestamp":1767225602282}},{"type":"message","id":"206b2637","parentId":"aa5aec89","timestamp":"2026-01-01T00:00:02.287Z","message":{"role":"assistant","content":[],"api":"openai-completions","provider":"openrouter","model":"deepseek/deepseek-v4-flash","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"error","errorMessage":"This operation was aborted","timestamp":1767225602287,"thinkingLevel":"high"}}],"leafId":"206b2637"}}} diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 544ac5cce66a3..ad5b35995ebe2 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -169,6 +169,12 @@ interface FakePi { readonly vetoNextNewSession: () => void; readonly allRequests: () => ReadonlyArray; readonly queueStats: (data: unknown) => void; + /** Pi before 0.84.4 answers clear_queue as an unknown command. */ + readonly setClearQueue: ( + result: + | { readonly steering: ReadonlyArray; readonly followUp: ReadonlyArray } + | "unknown_command", + ) => void; readonly closeStdout: Effect.Effect; readonly lastSpawn: () => { readonly args: ReadonlyArray; @@ -208,6 +214,7 @@ const makeFakePi: Effect.Effect = Effect.gen(function* () { let sessionGeneration = 0; let models: ReadonlyArray = []; let isStreaming: boolean | null = null; + let clearQueue: Parameters[0] = { steering: [], followUp: [] }; let stdinBuffer = ""; const emit = (record: PiRpcRecord, chunkBytes?: number) => @@ -273,6 +280,10 @@ const makeFakePi: Effect.Effect = Effect.gen(function* () { return { ...base, data: statsQueue.shift() ?? {} }; case "fork": return { ...base, data: { text: "Hello pi", cancelled: false } }; + case "clear_queue": + return clearQueue === "unknown_command" + ? { ...base, success: false, error: "Unknown command: clear_queue" } + : { ...base, data: clearQueue }; default: return base; } @@ -386,6 +397,9 @@ const makeFakePi: Effect.Effect = Effect.gen(function* () { isStreaming = streaming; }, queueStats: (data) => statsQueue.push(data), + setClearQueue: (result) => { + clearQueue = result; + }, closeStdout: Queue.end(stdout), lastSpawn: () => lastSpawn, } satisfies FakePi; @@ -3876,6 +3890,61 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + it.effect.each([ + { + pi: "clears its native queue", + clearQueue: { steering: ["Use the other file", ""], followUp: ["Then summarize"] }, + notices: [ + "Stop cleared 3 queued messages Pi had not read:\n\nUse the other file\n\nThen summarize", + ], + }, + { pi: "predates clear_queue", clearQueue: "unknown_command", notices: [] }, + ] as const)("Stop aborts and retires Pi when it $pi", ({ clearQueue, notices }) => + Effect.gen(function* () { + const fake = yield* makeFakePi; + fake.setClearQueue(clearQueue); + const { runtime, takeEvent } = yield* openRuntime(fake); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* startTurn(runtime, providerThread); + yield* fake.takeRequest("prompt"); + yield* fake.emit({ type: "agent_start" }); + const runningTurn = yield* takeEvent( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.status === "running", + ); + const providerTurnId = + runningTurn.type === "provider_turn.updated" ? runningTurn.providerTurn.id : undefined; + assert.isDefined(providerTurnId); + + yield* runtime.interruptTurn({ + providerThread, + providerTurnId: providerTurnId!, + requestRuntimeRestart: true, + }); + yield* fake.takeRequest("abort"); + assert.deepEqual( + fake + .allRequests() + .map((request) => request["type"]) + .filter((type) => type === "clear_queue" || type === "abort"), + ["clear_queue", "abort"], + ); + const emitted: Array = []; + yield* takeEvent((event) => { + if (event.type === "turn_item.updated" && event.turnItem.type === "system_notice") + emitted.push(event.turnItem.message); + return ( + event.type === "provider_session.updated" && event.providerSession.status === "stopped" + ); + }); + assert.deepEqual>(emitted, notices); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect("stops active retry progress when the turn is interrupted", () => Effect.gen(function* () { const fake = yield* makeFakePi; diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index aca13e35643ed..94c0e3521e47d 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -1212,6 +1212,59 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( }); }); + const emitSystemNotice = Effect.fnUntraced(function* ( + turn: ActivePiTurn, + nativeItemId: string, + message: string, + ) { + const emittedAt = yield* DateTime.now; + yield* emitItemNode(turn, nativeItemId, "system", "completed", emittedAt, emittedAt); + yield* emit({ + type: "turn_item.updated", + driver: PI_PROVIDER, + turnItem: { + ...baseItemFields(turn, nativeItemId, emittedAt, emittedAt), + status: "completed", + completedAt: emittedAt, + title: message, + type: "system_notice", + message, + }, + }); + }); + + // Abort leaves queued steers and follow-ups for Pi's next prompt, and Pi before 0.86 starts them + // as soon as abort lands, so Stop clears them first. Pi before 0.84.4 rejects clear_queue. + const clearNativeQueue = Effect.fnUntraced(function* (turn: ActivePiTurn) { + const cleared = yield* request({ type: "clear_queue" }, 2_000).pipe( + Effect.map((data) => + ["steering", "followUp"].flatMap((key) => { + const texts = recordField(data, key); + return Array.isArray(texts) + ? texts.filter((text): text is string => typeof text === "string") + : []; + }), + ), + Effect.orElseSucceed((): ReadonlyArray => []), + ); + if (cleared.length === 0) return; + yield* sessionEventPermit.withPermits(1)( + threadState?.activeTurn === turn + ? emitSystemNotice( + turn, + `queue-cleared:${turn.providerTurn.id}`, + [ + `Stop cleared ${cleared.length} queued ${cleared.length === 1 ? "message" : "messages"} Pi had not read:`, + // Image-only messages come back as empty text. + ...cleared.filter((text) => text.length > 0), + ] + .join("\n\n") + .slice(0, 2_000), + ) + : Effect.void, + ); + }); + const handleExtensionUiRequest = Effect.fnUntraced(function* (event: PiRpcRecord) { const method = recordString(event, "method"); const nativeRequestId = recordString(event, "id"); @@ -1221,21 +1274,11 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( const turn = state?.activeTurn ?? null; const message = recordString(event, "message") ?? ""; if (turn === null || message.length === 0) return; - const emittedAt = yield* DateTime.now; - const nativeItemId = `notify:${turn.providerTurn.id}:${turn.nextItemOrdinal}`; - yield* emitItemNode(turn, nativeItemId, "system", "completed", emittedAt, emittedAt); - yield* emit({ - type: "turn_item.updated", - driver: PI_PROVIDER, - turnItem: { - ...baseItemFields(turn, nativeItemId, emittedAt, emittedAt), - status: "completed", - completedAt: emittedAt, - title: message, - type: "system_notice", - message, - }, - }); + yield* emitSystemNotice( + turn, + `notify:${turn.providerTurn.id}:${turn.nextItemOrdinal}`, + message, + ); return; } if ( @@ -2641,6 +2684,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( // Generic abort misses manual compaction; terminate so Stop covers /compact and recovery. stopRequested = true; if (interruptInput.requestRuntimeRestart === true && !turn.settleWhenIdle) { + yield* clearNativeQueue(turn); yield* request({ type: "abort" }, 2_000).pipe(Effect.ignore); } // Read rollback tree refs before termination breaks requests; the permit lets in-flight capture finish. @@ -2654,6 +2698,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( ); return; } + yield* clearNativeQueue(turn); yield* request({ type: "abort" }).pipe( Effect.tapError(() => Effect.sync(() => (turn.interrupted = false))), ); From 947916887cce53e5f4b4aa77725315fa6c382635 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Fri, 30 Oct 2026 17:10:34 +0100 Subject: [PATCH 429/817] feat(pi): import terminal Pi sessions during setup (#27515) Co-authored-by: Claude Opus 5.5 Co-authored-by: GPT 6.1 Sol --- .../src/project/AgentSessionImporter.test.ts | 48 +++-- .../src/project/AgentSessionImporter.ts | 13 +- .../src/project/AgentSessionScanner.test.ts | 143 ++++++++++++- .../server/src/project/AgentSessionScanner.ts | 191 ++++++++++++++++-- .../components/onboarding/WelcomeWizard.tsx | 46 ++--- docs/user/welcome-wizard.md | 10 +- packages/contracts/src/agentSessions.ts | 2 +- packages/provider-pi/src/server/usage.ts | 27 ++- 8 files changed, 393 insertions(+), 87 deletions(-) diff --git a/apps/server/src/project/AgentSessionImporter.test.ts b/apps/server/src/project/AgentSessionImporter.test.ts index 69026f91202af..4248e51b55977 100644 --- a/apps/server/src/project/AgentSessionImporter.test.ts +++ b/apps/server/src/project/AgentSessionImporter.test.ts @@ -1,5 +1,6 @@ import { expect, it } from "@effect/vitest"; import { + type AgentSessionSource, EventId, ProjectId, ProviderDriverKind, @@ -50,7 +51,7 @@ const persistence = Layer.mergeAll( function candidate( modelSelection: typeof CODEX_MODEL_SELECTION, providerSessionId: string, - provider: "codex" | "claudeAgent" = "codex", + provider: AgentSessionSource = "codex", ) { const providerInstanceId = modelSelection.instanceId; return { @@ -82,6 +83,12 @@ function candidate( } satisfies AgentSessionScanner.AgentSessionRecentThread; } +const PI_MODEL_SELECTION = { instanceId: ProviderInstanceId.make("pi"), model: "default" }; + +// Pi threads are owned by their session file path, not the session UUID. +const nativeId = ({ source }: ReturnType) => + source.provider === "pi" ? source.filePath : source.providerSessionId; + function importId(source: ReturnType) { return ThreadId.make( `import:${source.source.providerInstanceId}:${source.source.providerSessionId}`, @@ -95,19 +102,17 @@ const seedOwner = Effect.fn(function* ( const sink = yield* EventSink.EventSinkV2; const ids = yield* IdAllocator.IdAllocatorV2; const { providerInstanceId, providerSessionId, provider } = source.source; + const nativeThreadId = nativeId(source); const threadId = ThreadId.make(`owner:${providerInstanceId}:${providerSessionId}`); const driver = ProviderDriverKind.make(provider); const providerThread: OrchestrationV2ProviderThread = { - id: ids.derive.providerThread({ - driver, - nativeThreadId: providerSessionId, - }), + id: ids.derive.providerThread({ driver, nativeThreadId }), driver, providerInstanceId, providerSessionId: null, appThreadId: threadId, ownerNodeId: null, - nativeThreadRef: { driver, nativeId: providerSessionId, strength: "strong" }, + nativeThreadRef: { driver, nativeId: nativeThreadId, strength: "strong" }, nativeConversationHeadRef: null, status: "idle", firstRunOrdinal: 1, @@ -252,10 +257,12 @@ it.effect( "claudeAgent", ); const deleted = candidate(CODEX_MODEL_SELECTION, "deleted"); + const ownedPi = candidate(PI_MODEL_SELECTION, "owned-pi", "pi"); const owners = [ yield* seedOwner(active), yield* seedOwner(archived, "archived"), yield* seedOwner(deleted, "deleted"), + yield* seedOwner(ownedPi), ]; const before = yield* Effect.forEach(owners, (id) => projections.getThreadRecords(id, ["providerThreads"]), @@ -266,10 +273,19 @@ it.effect( "claudeAgent", ); const unowned = candidate(CODEX_MODEL_SELECTION, "unowned"); - const importer = yield* makeImporter([active, archived, deleted, otherInstance, unowned]); + const unownedPi = candidate(PI_MODEL_SELECTION, "unowned-pi", "pi"); + const importer = yield* makeImporter([ + active, + archived, + deleted, + ownedPi, + otherInstance, + unowned, + unownedPi, + ]); - expect(yield* importer.run).toEqual({ importedCount: 2, skippedCount: 0 }); - for (const source of [active, archived, deleted]) { + expect(yield* importer.run).toEqual({ importedCount: 3, skippedCount: 0 }); + for (const source of [active, archived, deleted, ownedPi]) { const threadId = importId(source); expect(yield* Effect.option(projections.getThread(threadId))).toEqual(Option.none()); expect(yield* events.read({ threadId }).pipe(Stream.runCollect)).toEqual([]); @@ -286,8 +302,8 @@ it.effect( "event" in stored ? [stored.event.threadId] : [], ), ), - ).toEqual(new Set([importId(otherInstance), importId(unowned)])); - for (const source of [otherInstance, unowned]) { + ).toEqual(new Set([importId(otherInstance), importId(unowned), importId(unownedPi)])); + for (const source of [otherInstance, unowned, unownedPi]) { const threadId = importId(source); const records = yield* projections.getThreadRecords(threadId, [ "messages", @@ -296,15 +312,13 @@ it.effect( expect(records.messages.map((message) => message.text)).toEqual(["Fix it", "Fixed"]); expect(records.thread.historyOrigin).toBe("v1_import"); expect(records.thread.activeProviderThreadId).toBe(records.providerThreads[0]?.id); - expect(records.providerThreads[0]?.nativeThreadRef?.nativeId).toBe( - source.source.providerSessionId, - ); + expect(records.providerThreads[0]?.nativeThreadRef?.nativeId).toBe(nativeId(source)); expect(Option.getOrThrow(yield* runtimes.getByThreadId({ threadId }))).toMatchObject({ providerInstanceId: source.source.providerInstanceId, resumeCursor: - source.source.provider === "codex" - ? { threadId: source.source.providerSessionId } - : { threadId, resume: source.source.providerSessionId }, + source.source.provider === "claudeAgent" + ? { threadId, resume: source.source.providerSessionId } + : { threadId: nativeId(source) }, runtimePayload: { importedTranscripts: [source.source] }, }); } diff --git a/apps/server/src/project/AgentSessionImporter.ts b/apps/server/src/project/AgentSessionImporter.ts index 11f168ff1d7be..038b488635053 100644 --- a/apps/server/src/project/AgentSessionImporter.ts +++ b/apps/server/src/project/AgentSessionImporter.ts @@ -250,6 +250,9 @@ const make = Effect.gen(function* () { }); } const driver = ProviderDriverKind.make(thread.source); + // Pi resumes by session file path; its session UUID only names the thread. + const nativeThreadId = + thread.source === "pi" ? source.filePath : thread.providerSessionId; const persistRuntime = runtimes.upsert( { threadId, @@ -260,9 +263,9 @@ const make = Effect.gen(function* () { status: "stopped", lastSeenAt: thread.updatedAt, resumeCursor: - thread.source === "codex" - ? { threadId: thread.providerSessionId } - : { threadId, resume: thread.providerSessionId }, + thread.source === "claudeAgent" + ? { threadId, resume: thread.providerSessionId } + : { threadId: nativeThreadId }, runtimePayload: { cwd: project.workspaceRoot }, }, { onConflict: "ignore" }, @@ -288,7 +291,7 @@ const make = Effect.gen(function* () { const providerThreadId = idAllocator.derive.providerThread({ driver, providerInstanceId: thread.providerInstanceId, - nativeThreadId: thread.providerSessionId, + nativeThreadId, }); const createdAt = dateTime(thread.createdAt); const updatedAt = dateTime(thread.updatedAt); @@ -337,7 +340,7 @@ const make = Effect.gen(function* () { ownerNodeId: null, nativeThreadRef: { driver, - nativeId: thread.providerSessionId, + nativeId: nativeThreadId, strength: "strong", }, nativeConversationHeadRef: null, diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts index baf0f27f9edb3..3cbec21d8831d 100644 --- a/apps/server/src/project/AgentSessionScanner.test.ts +++ b/apps/server/src/project/AgentSessionScanner.test.ts @@ -46,6 +46,7 @@ const layerProjectStore = (importedWorkspaceRoots: ReadonlyArray) => interface ScannerTestInput { readonly claudeHomePath: string; readonly codexHomePath: string; + readonly piAgentDir?: string; readonly importedWorkspaceRoots?: ReadonlyArray; readonly configBaseDir?: string; readonly providerInstances?: ContractServerSettings["providerInstances"]; @@ -65,6 +66,20 @@ const layerScannerTest = (input: ScannerTestInput) => driver: ProviderDriverKind.make("codex"), config: { homePath: input.codexHomePath }, }, + // Keeps the default Pi instance off the developer's real ~/.pi. + [ProviderInstanceId.make("pi")]: { + driver: ProviderDriverKind.make("pi"), + enabled: true, + environment: [ + { + name: "PI_CODING_AGENT_DIR", + value: input.piAgentDir ?? `${input.claudeHomePath}/pi-agent`, + sensitive: false, + }, + { name: "PI_CODING_AGENT_SESSION_DIR", value: "", sensitive: false }, + ], + config: {}, + }, ...input.providerInstances, }, }), @@ -561,9 +576,32 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { const codexHomePath = yield* makeTempDir("t3code-codex-legacy-"); const claudeEnvironmentHome = yield* makeTempDir("t3code-claude-env-"); const codexEnvironmentHome = yield* makeTempDir("t3code-codex-env-"); + const piAgentDir = yield* makeTempDir("t3code-pi-agent-"); + const piSessionDir = yield* makeTempDir("t3code-pi-sessions-"); const claudeWorkspace = yield* makeTempDir("t3code-workspace-claude-"); const codexWorkspace = yield* makeTempDir("t3code-workspace-codex-"); - + const piWorkspace = yield* makeTempDir("t3code-workspace-pi-"); + const piFlatWorkspace = yield* makeTempDir("t3code-workspace-pi-flat-"); + + // Pi nests sessions per cwd by default and keeps a custom session directory flat. + for (const [filePath, cwd, mtime] of [ + [ + path.join(piAgentDir, "sessions", "--slug--", "2026-01-03_pi.jsonl"), + piWorkspace, + "2026-01-03T00:00:00.000Z", + ], + [ + path.join(piSessionDir, "2026-01-04_pi-flat.jsonl"), + piFlatWorkspace, + "2026-01-04T00:00:00.000Z", + ], + ] as const) { + yield* writeTranscript({ + filePath, + contents: `${encodeTranscriptRecord({ type: "session", version: 3, id: "pi", cwd })}\n`, + mtimeMs: Date.parse(mtime), + }); + } yield* writeTranscript({ filePath: path.join(claudeEnvironmentHome, "projects", "-actual", "session.jsonl"), contents: claudeSessionLine(claudeWorkspace), @@ -598,12 +636,31 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { environment: [{ name: "CODEX_HOME", value: codexEnvironmentHome, sensitive: false }], config: {}, }, + [ProviderInstanceId.make("pi")]: { + driver: ProviderDriverKind.make("pi"), + enabled: true, + environment: [ + { name: "PI_CODING_AGENT_DIR", value: piAgentDir, sensitive: false }, + { name: "PI_CODING_AGENT_SESSION_DIR", value: "", sensitive: false }, + ], + config: {}, + }, + [ProviderInstanceId.make("pi-flat")]: { + driver: ProviderDriverKind.make("pi"), + enabled: true, + environment: [ + { name: "PI_CODING_AGENT_SESSION_DIR", value: piSessionDir, sensitive: false }, + ], + config: {}, + }, }, }); - expect(result.candidates.map((candidate) => candidate.path)).toEqual([ - codexWorkspace, - claudeWorkspace, + expect(result.candidates.map((candidate) => [candidate.path, candidate.sources])).toEqual([ + [piFlatWorkspace, ["pi"]], + [piWorkspace, ["pi"]], + [codexWorkspace, ["codex"]], + [claudeWorkspace, ["claudeAgent"]], ]); }), ); @@ -983,13 +1040,14 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }); describe("recentThreads", () => { - it.effect("imports recent Claude and Codex sessions for the selected project only", () => + it.effect("imports recent Claude, Codex, and Pi sessions for the selected project only", () => Effect.gen(function* () { const path = yield* Path.Path; const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); yield* TestClock.setTime(nowMs); const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const piAgentDir = yield* makeTempDir("t3code-pi-agent-"); const workspace = yield* makeTempDir("t3code-workspace-"); const otherWorkspace = yield* makeTempDir("t3code-workspace-other-"); @@ -1053,21 +1111,96 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { ].join("\n"), mtimeMs: nowMs - 60 * 60 * 1000, }); + const piMessage = ( + id: string, + parentId: string | null, + message: { readonly role: string; readonly content: unknown }, + ) => + encodeTranscriptRecord({ + type: "message", + id, + parentId, + timestamp: "2026-08-24T11:00:00.000Z", + message, + }); + // The user rewound to the first prompt; the abandoned branch stays in the file. + yield* writeTranscript({ + filePath: path.join(piAgentDir, "sessions", "--selected--", "2026-08-24_pi.jsonl"), + contents: [ + encodeTranscriptRecord({ + type: "session", + version: 3, + id: "pi-recent", + cwd: workspace, + }), + piMessage("a1", null, { role: "user", content: "Plan the change" }), + piMessage("a2", "a1", { + role: "assistant", + content: [{ type: "text", text: "Abandoned answer" }], + }), + piMessage("a3", "a2", { role: "user", content: "Abandoned follow-up" }), + piMessage("b1", "a1", { + role: "assistant", + content: [ + { type: "thinking", thinking: "Hidden reasoning" }, + { type: "toolCall", id: "call-1", name: "bash", arguments: {} }, + ], + }), + piMessage("bn", "b1", { role: "toolResult", content: null }), + piMessage("b2", "bn", { + role: "toolResult", + content: [{ type: "text", text: "Tool output" }], + }), + piMessage("b3", "b2", { + role: "assistant", + content: [{ type: "text", text: "Active answer" }], + }), + encodeTranscriptRecord({ + type: "session_info", + id: "b4", + parentId: "b3", + name: "Pi refactor", + }), + ].join("\n"), + mtimeMs: nowMs - 30 * 60 * 1000, + }); + // Version 1 sessions predate the entry tree. + yield* writeTranscript({ + filePath: path.join(piAgentDir, "sessions", "--selected--", "2025-01-01_pi-v1.jsonl"), + contents: [ + encodeTranscriptRecord({ type: "session", id: "pi-v1", cwd: workspace }), + encodeTranscriptRecord({ + type: "message", + message: { role: "user", content: "Legacy prompt" }, + }), + encodeTranscriptRecord({ + type: "message", + message: { role: "assistant", content: [{ type: "text", text: "Legacy answer" }] }, + }), + ].join("\n"), + mtimeMs: nowMs - 2 * 24 * 60 * 60 * 1000, + }); const threads = yield* runRecentThreads({ claudeHomePath, codexHomePath, + piAgentDir, workspaceRoot: workspace, }); expect(threads.map((thread) => thread.providerSessionId)).toEqual([ + "pi-recent", "codex-recent", "claude-recent", + "pi-v1", ]); expect(threads.map((thread) => thread.messages.map((message) => message.text))).toEqual([ + ["Plan the change", "Active answer"], ["Review this code", "Looks good"], ["Fix the project", "Done"], + ["Legacy prompt", "Legacy answer"], ]); + expect(threads[0]).toMatchObject({ source: "pi", title: "Pi refactor" }); }), ); diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index 7ec79c38a38a9..bf026d9005c1a 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -32,7 +32,9 @@ import { repositoryPathFromRemoteUrl } from "@t3tools/source-control-core/server import * as ServerConfig from "../config.ts"; import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts"; +import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment"; import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; +import { resolvePiSessionsDir } from "@t3tools/provider-pi/server/usage"; import * as ServerSettings from "../serverSettings.ts"; import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; import { @@ -78,6 +80,10 @@ const CodexTurnMetadata = Schema.Struct({ const TranscriptRecord = Schema.Struct({ type: Schema.optional(Schema.String), + // Pi entries form a tree through id/parentId; session_info entries carry its name. + id: Schema.optional(Schema.String), + parentId: Schema.optional(Schema.NullOr(Schema.String)), + name: Schema.optional(Schema.String), timestamp: Schema.optional(Schema.String), cwd: Schema.optional(Schema.String), sessionId: Schema.optional(Schema.String), @@ -106,6 +112,13 @@ const decodeClaudeSettings = Schema.decodeUnknownOption(ClaudeSettings); const decodeCodexSettings = Schema.decodeUnknownOption(CodexSettings); const decodeTranscriptRecord = Schema.decodeUnknownOption(Schema.fromJsonString(TranscriptRecord)); const decodeTranscriptValue = Schema.decodeUnknownOption(TranscriptRecord); +const decodePiEntryLinks = Schema.decodeUnknownOption( + Schema.Struct({ + type: TranscriptRecord.fields.type, + id: TranscriptRecord.fields.id, + parentId: TranscriptRecord.fields.parentId, + }), +); const selectTranscriptPath = createTranscriptJsonSelector(TranscriptRecord); const decodeCodexTurnMetadata = Schema.decodeUnknownOption(CodexTurnMetadata); @@ -287,6 +300,39 @@ function deriveTitle(source: AgentSessionSource, text: string): string | undefin return request.trim().split("\n")[0]?.slice(0, 100).trim() || undefined; } +// Pi keeps abandoned branches in the file; its active branch runs from the last entry to the root. +function activePiBranch( + records: ReadonlyArray, +): ReadonlyArray { + const entries = records.filter((record) => record.type !== "session"); + const leaf = entries.at(-1); + // Version 1 sessions predate the tree and are linear. + if (leaf?.id === undefined) return entries; + const byId = new Map( + entries.flatMap((entry) => (entry.id === undefined ? [] : [[entry.id, entry] as const])), + ); + const branch: Array = []; + for ( + let entry: DecodedTranscriptRecord | undefined = leaf; + entry !== undefined && branch.length < entries.length; + entry = entry.parentId ? byId.get(entry.parentId) : undefined + ) { + branch.push(entry); + } + return branch.toReversed(); +} + +function isPiConversationRecord( + record: DecodedTranscriptRecord, +): record is DecodedTranscriptRecord & { + readonly message: typeof TranscriptMessage.Type & { readonly role: "user" | "assistant" }; +} { + return ( + record.type === "message" && + (record.message?.role === "user" || record.message?.role === "assistant") + ); +} + export function parseAgentSessionTranscript( input: AgentSessionTranscriptMetadata & { readonly contents: string; @@ -311,8 +357,16 @@ function parseAgentSessionRecords( // Claude filenames are session IDs. Codex rollout filenames include extra // timestamp text, so only transcript metadata can provide a resumable ID. let providerSessionId = - input.source === "codex" ? "" : (claudeFields.sessionId ?? input.fallbackSessionId); - const title = claudeFields.title ?? null; + input.source === "codex" + ? "" + : input.source === "pi" + ? records.find((record) => record.type === "session")?.id?.trim() || input.fallbackSessionId + : (claudeFields.sessionId ?? input.fallbackSessionId); + // Pi titles a session by its latest session_info on any branch; an empty name clears it. + const title = + input.source === "pi" + ? records.findLast((record) => record.type === "session_info")?.name?.trim() || null + : (claudeFields.title ?? null); let model = claudeFields.model ?? null; let derivedTitle: string | undefined; let hasCodexSessionId = false; @@ -403,8 +457,20 @@ function parseAgentSessionRecords( }; let recordIndex = -1; - for (const record of records) { + for (const record of input.source === "pi" ? activePiBranch(records) : records) { recordIndex += 1; + if (input.source === "pi") { + if (!isPiConversationRecord(record)) continue; + const text = extractText(record.message.content); + if (text.length === 0) continue; + retainMessage({ + role: record.message.role, + text, + createdAt: normalizeTimestamp(record.timestamp, fallbackTimestamp), + codexResponseUser: false, + }); + continue; + } if (input.source === "claudeAgent") { if (isHiddenClaudeRecord(record)) continue; if (record.type !== "user" && record.type !== "assistant") continue; @@ -507,6 +573,8 @@ function shouldRetainDecodedRecord( source: AgentSessionSource, record: DecodedTranscriptRecord, ): boolean { + // Any Pi entry can be a link on the active branch. + if (source === "pi") return true; if (source === "claudeAgent") { if (isHiddenClaudeRecord(record) || (record.type !== "user" && record.type !== "assistant")) { return false; @@ -843,15 +911,29 @@ export const make = Effect.gen(function* () { reader.write(decoder.decode()); recordCount += 1; if (recordCount > recordLimit) return false; - const decoded = decodeTranscriptValue(reader.finish()); - if (Option.isSome(decoded)) { + const value = reader.finish(); + const decoded = decodeTranscriptValue(value); + if (Option.isNone(decoded) && source === "pi") { + // Pi accepts messages this schema rejects, such as null content; keep their tree links. + records.push(...Option.toArray(decodePiEntryLinks(value))); + } else if (Option.isSome(decoded)) { if (Option.isNone(cwd)) cwd = Option.fromNullOr(extractDecodedCwd(decoded.value)); if (source === "claudeAgent") { claudeFields = foldClaudeFields(claudeFields, decoded.value); } if (shouldRetainDecodedRecord(source, decoded.value)) { - records.push(decoded.value); - historyBytes += recordBytes; + if ( + source === "pi" && + decoded.value.type === "message" && + !isPiConversationRecord(decoded.value) + ) { + // Tool output can dwarf the conversation; keep only the tree links. + const { message: _message, ...links } = decoded.value; + records.push(links); + } else { + records.push(decoded.value); + historyBytes += recordBytes; + } } } recordBytes = 0; @@ -1030,6 +1112,59 @@ export const make = Effect.gen(function* () { }, ); + // Pi nests sessions in one directory per cwd, but a custom session directory holds them flat. + const discoverPiTranscripts = Effect.fn("AgentSessionScanner.discoverPiTranscripts")(function* ( + sessionsDir: string, + providerInstanceId: ProviderInstanceId, + operationBudget: number, + ) { + let operationsRemaining = operationBudget; + let truncated = false; + const readDirectory = (directory: string) => { + if (operationsRemaining <= 0) { + truncated = true; + return Effect.succeed>([]); + } + operationsRemaining -= 1; + return listDirectory(directory); + }; + const transcripts: Array = []; + for (const entry of yield* readDirectory(sessionsDir)) { + if (operationsRemaining <= 0) { + truncated = true; + break; + } + const entryPath = path.join(sessionsDir, entry); + const filePaths = entry.endsWith(".jsonl") + ? [entryPath] + : (yield* readDirectory(entryPath)) + .filter((nested) => nested.endsWith(".jsonl")) + .map((nested) => path.join(entryPath, nested)); + + for (const filePath of filePaths) { + if (operationsRemaining <= 0) { + truncated = true; + break; + } + operationsRemaining -= 1; + const stats = yield* statOption(filePath); + if ( + Option.isSome(stats) && + stats.value.type === "File" && + Option.isSome(stats.value.mtime) + ) { + transcripts.push({ + filePath, + mtimeMs: stats.value.mtime.value.getTime(), + providerInstanceId, + size: Number(stats.value.size), + }); + } + } + } + return { transcripts, truncated }; + }); + const groupTranscriptsByCwd = Effect.fn("AgentSessionScanner.groupTranscriptsByCwd")(function* ( source: AgentSessionSource, transcripts: ReadonlyArray, @@ -1081,7 +1216,7 @@ export const make = Effect.gen(function* () { const raw: Array = []; let truncated = false; - for (const source of ["claudeAgent", "codex"] as const) { + for (const source of ["claudeAgent", "codex", "pi"] as const) { const instances: Array<{ readonly instanceId: ProviderInstanceId; readonly config: ProviderInstanceConfig; @@ -1111,26 +1246,36 @@ export const make = Effect.gen(function* () { const homes: Array<{ homePath: string; providerInstanceId: ProviderInstanceId }> = []; const seenHomes = new Set(); for (const { instanceId, config: instance } of instances) { - const homeVariable = source === "claudeAgent" ? "CLAUDE_CONFIG_DIR" : "CODEX_HOME"; - const configuredHome = instance.environment?.findLast( - (variable) => variable.name === homeVariable, - )?.value; - const environmentHome = - typeof configuredHome === "string" ? configuredHome : hostEnvironment[homeVariable]; + const environmentHome = (name: "CLAUDE_CONFIG_DIR" | "CODEX_HOME") => { + const configured = instance.environment?.findLast( + (variable) => variable.name === name, + )?.value; + return typeof configured === "string" ? configured : hostEnvironment[name]; + }; let homePath: string; - if (source === "claudeAgent") { + if (source === "pi") { + const environment = yield* mergeProviderInstanceEnvironment( + instance.environment, + hostEnvironment, + ).pipe(Effect.provideService(HostProcess.HomeDirectory, homeDir)); + homePath = resolvePiSessionsDir(environment, homeDir, path); + } else if (source === "claudeAgent") { const config = decodeClaudeSettings(instance.config ?? {}); if (Option.isNone(config)) continue; - homePath = resolveClaudeConfigDir(config.value.homePath, environmentHome); + homePath = resolveClaudeConfigDir( + config.value.homePath, + environmentHome("CLAUDE_CONFIG_DIR"), + ); } else { const config = decodeCodexSettings(instance.config ?? {}); if (Option.isNone(config)) continue; + const codexHome = environmentHome("CODEX_HOME"); const codexSettings = config.value.homePath.trim().length === 0 && config.value.shadowHomePath.trim().length === 0 && - environmentHome?.trim() - ? { ...config.value, homePath: environmentHome } + codexHome?.trim() + ? { ...config.value, homePath: codexHome } : config.value; const layout = yield* resolveCodexHomeLayout(codexSettings).pipe( Effect.provideService(Path.Path, path), @@ -1155,9 +1300,13 @@ export const make = Effect.gen(function* () { truncated = true; continue; } - const discovered = yield* source === "claudeAgent" - ? discoverClaudeTranscripts(home.homePath, home.providerInstanceId, operationBudget) - : discoverCodexTranscripts(home.homePath, home.providerInstanceId, operationBudget); + const discover = + source === "claudeAgent" + ? discoverClaudeTranscripts + : source === "codex" + ? discoverCodexTranscripts + : discoverPiTranscripts; + const discovered = yield* discover(home.homePath, home.providerInstanceId, operationBudget); truncated ||= discovered.truncated; transcriptCandidates.push(...discovered.transcripts); } diff --git a/apps/web/src/components/onboarding/WelcomeWizard.tsx b/apps/web/src/components/onboarding/WelcomeWizard.tsx index 50d65192c0249..4c768eb5763a4 100644 --- a/apps/web/src/components/onboarding/WelcomeWizard.tsx +++ b/apps/web/src/components/onboarding/WelcomeWizard.tsx @@ -15,6 +15,7 @@ import { squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; import { + AgentSessionSource, AuthTerminalOperateScope, CommandId, defaultInstanceIdForDriver, @@ -1715,41 +1716,38 @@ function ImportCandidateRow({ ); } +const IMPORT_SOURCE_NAMES: Record = { + claudeAgent: "Claude Code", + codex: "Codex", + pi: "Pi", +}; + function ImportRowMeta({ sources, threadCount, lastActiveAt, }: { - readonly sources: ReadonlyArray<"claudeAgent" | "codex"> | null; + readonly sources: ReadonlyArray | null; readonly threadCount: number; readonly lastActiveAt: string | null; }) { const relative = lastActiveAt === null ? null : formatRelativeTime(lastActiveAt); const age = relative === null ? "" : relative.suffix === null ? "now" : relative.value; return ( - - - {sources?.includes("claudeAgent") ? ( - - - - ) : null} - - - {sources?.includes("codex") ? ( - - - - ) : null} - + + {AgentSessionSource.literals.map((source) => ( + + {sources?.includes(source) ? ( + + + + ) : null} + + ))} {threadCount} {age} diff --git a/docs/user/welcome-wizard.md b/docs/user/welcome-wizard.md index d4604fa7e6668..2d4b589d922fa 100644 --- a/docs/user/welcome-wizard.md +++ b/docs/user/welcome-wizard.md @@ -59,7 +59,7 @@ terminal metadata while the terminal process can use them. ## Import your projects -T3 Code finds directories that Claude Code or Codex has used. Git repositories +T3 Code finds directories that Claude Code, Codex or Pi has used. Git repositories are listed first, newest activity on top. When the remote is on GitHub, the group shows the repository as `owner/name`. Clones with the same remote share one group. Directories that are not git repositories sit under "Other folders". @@ -74,8 +74,12 @@ offered. A large or malformed history can reach the scan limit. T3 Code keeps the projects it found and warns when projects or conversations may be missing. -Imported projects include Codex and Claude conversations active within the last -30 days. You can continue those conversations in T3 Code. +Imported projects include Claude, Codex and Pi conversations active within the last +30 days. You can continue those conversations in T3 Code. Pi is off by default: +enable it in Settings, then open `/welcome` to import its sessions. Pi sessions +are read from each enabled Pi provider's session directory, which follows +`PI_CODING_AGENT_SESSION_DIR` and `PI_CODING_AGENT_DIR` in its environment. A +Pi conversation imports its active branch, the one Pi reopens. Conversation import is best effort. T3 Code keeps the first user prompt and the newest remaining visible user and assistant messages, with 200 messages total. diff --git a/packages/contracts/src/agentSessions.ts b/packages/contracts/src/agentSessions.ts index a60d702d9a0e3..93e0e36e4fbd4 100644 --- a/packages/contracts/src/agentSessions.ts +++ b/packages/contracts/src/agentSessions.ts @@ -2,7 +2,7 @@ import * as Schema from "effect/Schema"; import { IsoDateTime, NonNegativeInt, ProjectId, TrimmedNonEmptyString } from "./baseSchemas.ts"; import { ProviderInstanceId } from "./providerInstance.ts"; -export const AgentSessionSource = Schema.Literals(["claudeAgent", "codex"]); +export const AgentSessionSource = Schema.Literals(["claudeAgent", "codex", "pi"]); export type AgentSessionSource = typeof AgentSessionSource.Type; export const AgentSessionImportSource = Schema.Struct({ diff --git a/packages/provider-pi/src/server/usage.ts b/packages/provider-pi/src/server/usage.ts index 5dadc93e101d9..961a73e838acd 100644 --- a/packages/provider-pi/src/server/usage.ts +++ b/packages/provider-pi/src/server/usage.ts @@ -131,16 +131,21 @@ export const piUsageReader: ProviderUsageReader = { directories: Effect.fn("piUsageReader.directories")(function* ({ environment }) { const path = yield* Path.Path; const home = yield* HostProcess.HomeDirectory; - const sessionDir = environment.PI_CODING_AGENT_SESSION_DIR?.trim(); - if (sessionDir) return [{ dir: path.resolve(expandHomePath(sessionDir, home)) }]; - const agentDir = environment.PI_CODING_AGENT_DIR?.trim(); - return [ - { - dir: path.resolve( - agentDir ? expandHomePath(agentDir, home) : path.join(home, ".pi", "agent"), - "sessions", - ), - }, - ]; + return [{ dir: resolvePiSessionsDir(environment, home, path) }]; }), }; + +/** Where Pi stores session JSONL files for a provider environment, matching Pi's own lookup. */ +export function resolvePiSessionsDir( + environment: NodeJS.ProcessEnv, + home: string, + path: Path.Path, +): string { + const sessionDir = environment.PI_CODING_AGENT_SESSION_DIR?.trim(); + if (sessionDir) return path.resolve(expandHomePath(sessionDir, home)); + const agentDir = environment.PI_CODING_AGENT_DIR?.trim(); + return path.resolve( + agentDir ? expandHomePath(agentDir, home) : path.join(home, ".pi", "agent"), + "sessions", + ); +} From 77336a54a75c593ceb6d9f1d97789d0ccd616460 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Fri, 30 Oct 2026 17:11:07 +0100 Subject: [PATCH 430/817] fix(pi): nest tools called through another tool under their caller (#27521) Co-authored-by: Claude Opus 5.5 Co-authored-by: GPT 6.1 Sol --- .../provider-pi/src/server/adapter.test.ts | 63 +++++++++++++++++++ packages/provider-pi/src/server/adapter.ts | 23 ++++++- 2 files changed, 83 insertions(+), 3 deletions(-) diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index ad5b35995ebe2..56754c30923bd 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -2041,6 +2041,69 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + it.effect("nests tools called through another tool under their caller", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + const { runtime, takeEvent } = yield* openRuntime(fake); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* startTurn(runtime, providerThread); + yield* fake.takeRequest("prompt"); + yield* fake.emit({ type: "agent_start" }); + const takeToolEvents = Effect.fnUntraced(function* (toolCallId: string) { + const node = yield* takeEvent( + (event) => + event.type === "node.updated" && event.node.nativeItemRef?.nativeId === toolCallId, + ); + const item = yield* takeEvent( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === toolCallId, + ); + if (node.type !== "node.updated" || item.type !== "turn_item.updated") + return yield* Effect.die("Expected tool node and item events"); + return { node: node.node, item: item.turnItem }; + }); + + yield* fake.emit({ + type: "tool_execution_start", + toolCallId: "call_code", + toolName: "codemode", + args: { code: "await read({ path: 'a.ts' })" }, + }); + const caller = yield* takeToolEvents("call_code"); + assert.equal(caller.node.parentNodeId, caller.node.rootNodeId); + assert.isNull(caller.item.parentItemId); + + // Pi tags every phase, so an update that arrives before its start still nests. + const phases = [ + { type: "tool_execution_update", partialResult: { content: [] }, status: "running" }, + { type: "tool_execution_start", args: { path: "a.ts" }, status: "running" }, + { + type: "tool_execution_end", + isError: true, + result: { content: [{ type: "text", text: "ENOENT" }] }, + status: "failed", + }, + ] as const; + for (const { status, ...phase } of phases) { + yield* fake.emit({ + ...phase, + toolCallId: "call_code/1", + toolName: "read", + parentToolCallId: "call_code", + }); + const nested = yield* takeToolEvents("call_code/1"); + assert.equal(nested.node.status, status); + assert.equal(nested.node.parentNodeId, caller.node.id); + assert.equal(nested.item.parentItemId, caller.item.id); + } + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect( "keeps native and MCP images available to the shared asset reader with typed results", () => diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index 94c0e3521e47d..f1924e7639202 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -729,6 +729,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( nativeItemId: string, startedAt: DateTime.Utc, updatedAt: DateTime.Utc, + parentNativeItemId?: string, ) => ({ id: idAllocator.derive.turnItemFromProviderItem({ driver: PI_PROVIDER, @@ -743,7 +744,13 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( providerThreadId: turn.turnInput.providerThread.id, providerTurnId: turn.providerTurn.id, nativeItemRef: providerRef(nativeItemId), - parentItemId: null, + parentItemId: + parentNativeItemId === undefined + ? null + : idAllocator.derive.turnItemFromProviderItem({ + driver: PI_PROVIDER, + nativeItemId: parentNativeItemId, + }), ordinal: itemOrdinal(turn, nativeItemId), startedAt, updatedAt, @@ -756,6 +763,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( status: OrchestrationV2ExecutionNode["status"], startedAt: DateTime.Utc, completedAt: DateTime.Utc | null, + parentNativeItemId?: string, ) => emit({ type: "node.updated", @@ -767,7 +775,13 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( }), threadId: turn.turnInput.threadId, runId: turn.turnInput.runId, - parentNodeId: turn.turnInput.rootNodeId, + parentNodeId: + parentNativeItemId === undefined + ? turn.turnInput.rootNodeId + : idAllocator.derive.nodeFromProviderItem({ + driver: PI_PROVIDER, + nativeItemId: parentNativeItemId, + }), rootNodeId: turn.turnInput.rootNodeId, kind, status, @@ -980,6 +994,8 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( ) { const toolCallId = recordString(event, "toolCallId"); const toolName = recordString(event, "toolName") ?? "tool"; + // Pi tags every phase of a call made through ctx.executeTool, such as from a codemode script. + const parentToolCallId = recordString(event, "parentToolCallId"); if (toolCallId === undefined) return; if (phase === "start") { turn.toolArgs.set(toolCallId, event["args"]); @@ -999,7 +1015,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( : "failed" : "completed" : "running"; - const base = baseItemFields(turn, toolCallId, startedAt, emittedAt); + const base = baseItemFields(turn, toolCallId, startedAt, emittedAt, parentToolCallId); yield* emitItemNode( turn, toolCallId, @@ -1007,6 +1023,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( status, startedAt, completed ? emittedAt : null, + parentToolCallId, ); const shared = { ...base, From e00ebb6e2641a2681d7612bccc5d8810403d99b8 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Fri, 30 Oct 2026 17:11:50 +0100 Subject: [PATCH 431/817] fix(pi): explain when an untrusted folder makes Pi skip project resources (#27539) Co-authored-by: Claude Opus 5.5 Co-authored-by: GPT 6.1 Sol --- docs/user/providers-pi.md | 15 ++++++--- .../src/server/mcpExtensionSource.test.ts | 33 +++++++++++++++++-- .../src/server/mcpExtensionSource.ts | 14 ++++++++ 3 files changed, 55 insertions(+), 7 deletions(-) diff --git a/docs/user/providers-pi.md b/docs/user/providers-pi.md index 123258f6ccb43..e106d0afdd387 100644 --- a/docs/user/providers-pi.md +++ b/docs/user/providers-pi.md @@ -47,9 +47,10 @@ reporting while a response streams and after it settles. Pi skills appear in the composer's `$` menu. This includes user skills and project skills that Pi loads for the current workspace; selecting one uses Pi's native skill expansion. -Pi loads its normal user and project extensions. Blocking `select`, `confirm`, `input`, and `editor` -dialogs work in T3 Code. Notifications appear in the work log. Pi terminal decoration such as -titles, status lines, and widgets does not have a T3 Code equivalent. +Pi loads its normal user extensions, and project extensions once the folder is trusted in Pi. +Blocking `select`, `confirm`, `input`, and `editor` dialogs work in T3 Code. Notifications appear in +the work log. Pi terminal decoration such as titles, status lines, and widgets does not have a T3 +Code equivalent. ## Permission Modes @@ -79,7 +80,11 @@ threads. - If no models appear, open Pi directly and confirm its authentication and model configuration. - If discovery cannot complete, T3 Code keeps Pi available with the `Pi default` model. Start a thread to let the interactive Pi session handle any startup prompt. -- If a project extension is missing, approve the project in Pi, then start a fresh provider session. -- If a project skill is missing from the `$` menu, approve the project in Pi and refresh the provider. +- If Pi skips project settings, extensions, skills, prompts, MCP servers, or system prompt files + because the folder is not trusted, the thread shows a notice on the first turn of the Pi session. + Run the configured Pi binary in that folder on the server machine, using the same provider + environment, including `PI_CODING_AGENT_DIR` if set. Trust the folder or its parent with `/trust`, + then start a new thread using that same worktree. Launch arguments with `--no-approve` keep + project files off without the notice. - The context meter appears once Pi reports usage for the thread. Some model providers only report usage when a response completes, so the meter can wait for the first reply. diff --git a/packages/provider-pi/src/server/mcpExtensionSource.test.ts b/packages/provider-pi/src/server/mcpExtensionSource.test.ts index b1306f701e27a..cedf3974f535d 100644 --- a/packages/provider-pi/src/server/mcpExtensionSource.test.ts +++ b/packages/provider-pi/src/server/mcpExtensionSource.test.ts @@ -25,7 +25,10 @@ type InputHook = ( ctx: { ui: { notify: (message: string, level: string) => void } }, ) => Promise<{ action: string; text: string; images?: ReadonlyArray } | undefined>; -async function loadHooks(commands: ReadonlyArray = []) { +async function loadHooks( + commands: ReadonlyArray = [], + argv: ReadonlyArray = [], +) { const handlers = new Map(); const source = NodeModule.stripTypeScriptTypes( PI_T3_MCP_EXTENSION_SOURCE.replace(/^import .*;$/gm, "").replace( @@ -34,7 +37,7 @@ async function loadHooks(commands: ReadonlyArray = []) { ), ); await NodeVM.runInNewContext(`${source}\nt3McpExtension(pi)`, { - process: { env: {} }, + process: { env: {}, argv }, NodeFSP, NodePath, stripFrontmatter: (content: string) => content, @@ -77,6 +80,32 @@ describe("Pi orchestration prompt section", () => { }); }); +describe("Pi project trust", () => { + it.each([ + { name: "a trusted folder", trusted: true, argv: [], notices: 0 }, + { name: "an untrusted folder", trusted: false, argv: [], notices: 1 }, + { name: "--no-approve", trusted: false, argv: ["--approve", "-na"], notices: 0 }, + ])("sends $notices trust notice per session for $name", async ({ trusted, argv, notices }) => { + const sent: string[] = []; + const ctx = { + cwd: "/repo", + isProjectTrusted: () => trusted, + ui: { notify: (message: string) => sent.push(message) }, + }; + // Pi reruns extension factories on session replacement without asking about trust again. + for (const _session of [1, 2]) { + const handlers = (await loadHooks([], ["node", "pi", ...argv])) as Map< + string, + (event: unknown, ctx: unknown) => unknown + >; + for (const _turn of [1, 2]) await handlers.get("before_agent_start")!({}, ctx); + } + assert.equal(sent.length, notices * 2); + for (const message of sent) + assert.include(message, "for /repo because the folder is not trusted"); + }); +}); + describe("Pi MCP tool results", () => { it("returns mixed screenshot blocks and typed script output without repeating structured text", async () => { const content = [ diff --git a/packages/provider-pi/src/server/mcpExtensionSource.ts b/packages/provider-pi/src/server/mcpExtensionSource.ts index dcc4a0230a8db..ee72c38f75966 100644 --- a/packages/provider-pi/src/server/mcpExtensionSource.ts +++ b/packages/provider-pi/src/server/mcpExtensionSource.ts @@ -241,6 +241,20 @@ function createMcpClient(endpoint: string, token: string) { } export default async function t3McpExtension(pi: ExtensionAPI) { + // RPC has no trust prompt, so Pi skips an untrusted folder's protected resources. Session + // replacement reruns this factory without project_trust, and T3 drops notices outside a turn, + // so check each session's first turn. An explicit --no-approve is deliberate and stays quiet. + let projectTrustChecked = false; + pi.on("before_agent_start", (_event, ctx) => { + if (projectTrustChecked) return; + projectTrustChecked = true; + if (ctx.isProjectTrusted() || process.argv.some((arg) => arg === "--no-approve" || arg === "-na")) return; + ctx.ui.notify( + \`Pi did not load project settings, extensions, skills, prompts, MCP servers or system prompt files for \${ctx.cwd} because the folder is not trusted. To load them, run the configured Pi binary there with the same PI_CODING_AGENT_DIR (if set), trust the folder or its parent with /trust, then start a new thread in that same worktree. To trust every project, add --approve to Pi's launch arguments in T3 Code settings; to keep them off without this notice, add --no-approve.\`, + "warning", + ); + }); + // Keep skill chips in the request. Pi expands only one leading /skill: // command, so use its own frontmatter loader for every selected chip here. pi.on("input", async (event, ctx) => { From a077fdd2aa4890554ef1646c58ecf079beae966a Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Fri, 30 Oct 2026 21:43:34 +0530 Subject: [PATCH 432/817] fix(mobile): Android Thread settings rows no longer vanish with animations removed (#21757) Co-authored-by: Pipyakas Co-authored-by: Claude Opus 5.5 --- .../src/features/threads/ThreadSettingsSheet.tsx | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx index 11d8710470d66..1f17fd3bb842e 100644 --- a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx +++ b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx @@ -49,7 +49,12 @@ import { type ReactNode, } from "react"; import { Platform, Pressable, RefreshControl, ScrollView, TextInput, View } from "react-native"; -import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated"; +import Animated, { + FadeIn, + FadeOut, + LinearTransition, + useReducedMotion, +} from "react-native-reanimated"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { SymbolView } from "../../components/ui/AppSymbol"; @@ -938,7 +943,10 @@ function ThreadSettingsMainContent(props: { if (error) Dialog.alert("Could not refresh models", error); }); }; - const [animationsReady, setAnimationsReady] = useState(false); + const [listLoaded, setListLoaded] = useState(false); + // Android can drop the first frame of a reduced-motion fade, leaving rows invisible. + const reducedMotion = useReducedMotion(); + const animationsReady = listLoaded && !reducedMotion; const catalogItems = buildThreadSettingsCatalogItems(session); const hasActiveCatalogFilter = session.providerFilter !== null || session.searchQuery.trim().length > 0; @@ -1064,7 +1072,7 @@ function ThreadSettingsMainContent(props: { ) : undefined } - onLoad={() => setAnimationsReady(true)} + onLoad={() => setListLoaded(true)} renderItem={renderCatalogItem} showsVerticalScrollIndicator={false} /> From 35dcdd601e11d821e0df5fd3435b350e92d15bf6 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Fri, 30 Oct 2026 21:44:47 +0530 Subject: [PATCH 433/817] fix(server): phone taps, typing and scrolling reach desktop browser tabs again (#19456) Co-authored-by: PR Batch Tester Co-authored-by: Max Nylander Co-authored-by: Claude Opus 5.5 --- apps/server/src/preview/ServerBrowser.test.ts | 211 +++++++++++++++++- apps/server/src/preview/ServerBrowser.ts | 107 +++++++-- 2 files changed, 293 insertions(+), 25 deletions(-) diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.ts index 99df18c10cf5a..2f09e2b084613 100644 --- a/apps/server/src/preview/ServerBrowser.test.ts +++ b/apps/server/src/preview/ServerBrowser.test.ts @@ -24,6 +24,7 @@ import * as Path from "effect/Path"; import * as PubSub from "effect/PubSub"; import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import type { BrowserContext, Page } from "playwright-core"; import { beforeEach, expect, vi } from "vite-plus/test"; @@ -56,6 +57,7 @@ vi.mock("./ServerBrowserContexts.ts", () => ({ } async connectDesktopPage(endpoint: string) { const context = makeContext(); + context.page.viewportSize.mockReturnValue(null); desktopConnections.push({ endpoint, context }); return { browser: { close: async () => {} }, page: context.page as unknown as Page }; } @@ -83,11 +85,16 @@ const PNG_HEADER = (() => { return header.toString("base64"); })(); -function makeSession(frame?: ReturnType) { +function makeSession( + frame: ReturnType | undefined, + viewport: { width: number; height: number }, +) { const events = new NodeEvents.EventEmitter(); return { - on: vi.fn((name: string, listener: () => void) => events.on(name, listener)), - emit: (name: string) => events.emit(name), + on: vi.fn((name: string, callback: (...args: unknown[]) => void) => events.on(name, callback)), + emit: (name: string, ...args: unknown[]) => events.emit(name, ...args), + emitAsync: (name: string, ...args: unknown[]) => + Promise.all(events.listeners(name).map((listener) => listener(...args))), detach: vi.fn(async () => {}), send: vi.fn(async (method: string, input?: unknown): Promise> => { if (method === "Page.getNavigationHistory") return { currentIndex: 0, entries: [{}] }; @@ -101,7 +108,12 @@ function makeSession(frame?: ReturnType) { if (method === "Page.getFrameTree") return { frameTree: { frame: { id: "main" } } }; if (method === "Page.createIsolatedWorld") { return { - executionContextId: (input as { worldName?: string }).worldName === "t3-preview" ? 1 : 7, + executionContextId: + (input as { worldName?: string }).worldName === "t3-preview-viewport" + ? 9 + : (input as { worldName?: string }).worldName === "t3-preview" + ? 1 + : 7, }; } if (method === "Runtime.evaluate" && (input as { contextId?: number }).contextId === 1) { @@ -118,6 +130,8 @@ function makeSession(frame?: ReturnType) { else pageCopy = ""; return { result: { value } }; } + if (method === "Runtime.evaluate" && (input as { contextId?: number }).contextId === 9) + return desktopSizeAnswer?.() ?? { result: { value: { ...viewport } } }; return { result: { value: "evaluated" } }; }), }; @@ -129,7 +143,8 @@ function makeContext(onClose?: (context: BrowserContext) => void) { const setChooserFiles = vi.fn(async (_files: unknown) => {}); const sessions: ReturnType[] = []; let url = "about:blank"; - let viewport = { width: 1280, height: 800 }; + let viewport: ReturnType = { width: 1280, height: 800 }; + const cssViewport = { width: 1920, height: 1080 }; let closed = false; let contextClosed = false; const page = { @@ -159,7 +174,7 @@ function makeContext(onClose?: (context: BrowserContext) => void) { frames: () => [page], url: () => url, title: vi.fn(async () => "test page"), - viewportSize: () => viewport, + viewportSize: vi.fn(() => viewport), setViewportSize: vi.fn(async (size: typeof viewport) => { viewport = size; }), @@ -197,11 +212,13 @@ function makeContext(onClose?: (context: BrowserContext) => void) { const context = { page, sessions, + cssViewport, newPage: async () => page as unknown as Page, grantPermissions: vi.fn(async () => {}), newCDPSession: async (target: unknown) => { const session = makeSession( target === page ? undefined : (target as ReturnType), + cssViewport, ); sessions.push(session); return session; @@ -268,7 +285,11 @@ let focusedFrame: ReturnType | null = null; let contextFailure: Error | null = null; let initialNavigation: (() => Promise) | null = null; let desktopRendersNext = false; +/** Replaces the answer to the desktop page's size reads. */ +let desktopSizeAnswer: (() => Promise>) | null = null; const desktopDetaches = new NodeEvents.EventEmitter(); +let desktopDetachReady = Promise.withResolvers(); +let desktopReleased = Promise.withResolvers(); const desktopTabs = new Set(); const desktopRenders = (tabId: string) => { if (desktopRendersNext) { @@ -317,6 +338,7 @@ const dependencies = Layer.mergeAll( const onDetach = (key: { threadId: string; tabId: string }) => Queue.offerUnsafe(queue, key); desktopDetaches.on("detach", onDetach); + desktopDetachReady.resolve(); return onDetach; }), (onDetach) => Effect.sync(() => desktopDetaches.off("detach", onDetach)), @@ -336,7 +358,10 @@ const dependencies = Layer.mergeAll( isAttached: (key) => Effect.sync(() => desktopRenders(key.tabId)), endpoint: (key) => Effect.acquireRelease(Effect.succeed(`ws://desktop/${key.tabId}`), () => - Effect.sync(() => releasedDesktopTabs.push(key.tabId)), + Effect.sync(() => { + releasedDesktopTabs.push(key.tabId); + desktopReleased.resolve(); + }), ), pointer: () => Effect.void, turn: (threadId, active) => Effect.sync(() => desktopTurns.emit("turn", threadId, active)), @@ -367,6 +392,33 @@ const viewerInput = (tabId: string, canOperate: boolean) => ({ maxHeight: 800, quality: 70, }); +/** Fills a viewer's output with frames; resolves once every one of them is acknowledged. */ +const stallViewer = (viewer: ServerBrowser.ServerBrowserViewer) => { + const output = viewer.output as unknown as Queue.Queue; + const acked = Promise.withResolvers(); + let unacked = 0; + const ack = Effect.sync(() => { + if (--unacked === 0) acked.resolve(); + }); + while (Queue.offerUnsafe(output, { _tag: "frame", data: Buffer.alloc(0), ack })) unacked++; + return Effect.promise(() => acked.promise); +}; +const viewportSizes = (items: ReadonlyArray) => + items.flatMap((item) => (item._tag === "viewport" ? [`${item.width}x${item.height}`] : [])); +const openDesktopViewer = Effect.gen(function* () { + const browser = yield* ServerBrowser.ServerBrowser; + const manager = yield* Manager.PreviewManager; + desktopRendersNext = true; + const { tabId } = yield* manager.open({ threadId: scope.thread.threadId, runtime: "server" }); + const viewer = yield* browser.attachViewer(viewerInput(tabId, true)); + const context = desktopConnections[0]!.context; + const cdp = context.sessions[0]!; + const resize = (width: number, height: number) => { + Object.assign(context.cssViewport, { width, height }); + return Effect.promise(() => cdp.emitAsync("Page.frameResized")); + }; + return { tabId, viewer, context, cdp, resize }; +}); beforeEach(() => { contexts.length = 0; @@ -380,6 +432,9 @@ beforeEach(() => { focusedFrame = null; desktopTabs.clear(); desktopRendersNext = false; + desktopSizeAnswer = null; + desktopDetachReady = Promise.withResolvers(); + desktopReleased = Promise.withResolvers(); releasedDesktopTabs.length = 0; desktopConnections.length = 0; }); @@ -1144,6 +1199,148 @@ it.live("only the current controller can answer a file picker", () => ).pipe(Effect.provide(layer)), ); +it.effect( + "desktop viewers get the page's CSS size and keep the last one a read cannot measure", + () => + Effect.scoped( + Effect.gen(function* () { + // Each page size read waits here for its answer. + const reads = yield* Queue.unbounded>>(); + const deferReads = () => { + desktopSizeAnswer = () => { + const read = Promise.withResolvers>(); + Queue.offerUnsafe(reads, read); + return read.promise; + }; + }; + deferReads(); + const { viewer, cdp, context } = yield* openDesktopViewer; + const answer = (width: number, height: number) => ({ + result: { value: { width, height } }, + }); + const resized = () => cdp.emitAsync("Page.frameResized"); + // The read on attach never answers and gives up with no size to send. + const blocked = yield* Queue.take(reads); + yield* TestClock.adjust("1 second"); + // The next page load measures again. + desktopSizeAnswer = null; + yield* Effect.promise(() => cdp.emitAsync("Page.loadEventFired")); + expect(viewportSizes(yield* Queue.takeAll(viewer.output))).toEqual(["1920x1080"]); + // While a dialog is open nothing reads. The host closing it clears it, and since + // closing resizes nothing, the close itself remeasures. + deferReads(); + context.page.emit("dialog", { + type: () => "alert", + message: () => "", + defaultValue: () => "", + }); + yield* Effect.promise(resized); + expect(yield* Queue.size(reads)).toBe(0); + desktopSizeAnswer = null; + yield* Effect.promise(() => cdp.emitAsync("Page.javascriptDialogClosed")); + expect(viewportSizes(yield* Queue.takeAll(viewer.output))).toEqual([ + "1920x1080", + "1920x1080", + ]); + // The late answer, a read a navigation breaks and a hidden webview keep the last size. + blocked.resolve(answer(100, 100)); + deferReads(); + const navigated = resized(); + (yield* Queue.take(reads)).reject(new Error("Cannot find context with specified id")); + yield* Effect.promise(() => navigated); + const hidden = resized(); + (yield* Queue.take(reads)).resolve(answer(0, 0)); + yield* Effect.promise(() => hidden); + expect(viewportSizes(yield* Queue.takeAll(viewer.output))).toEqual([ + "1920x1080", + "1920x1080", + ]); + // Resizes during a read share one more read, so the newest size arrives last. + const first = resized(); + const firstRead = yield* Queue.take(reads); + const burst = Promise.all([resized(), resized()]); + firstRead.resolve(answer(800, 500)); + (yield* Queue.take(reads)).resolve(answer(1000, 600)); + expect(yield* Queue.size(reads)).toBe(0); + yield* Effect.promise(() => Promise.all([first, burst])); + expect(viewportSizes(yield* Queue.takeAll(viewer.output))).toEqual([ + "800x500", + "1000x600", + "1000x600", + ]); + }), + ).pipe(Effect.provide(layer)), +); + +it.effect("a stalled desktop viewer still gets its size, control and reconnect", () => + Effect.scoped( + Effect.gen(function* () { + const { tabId, viewer, context, resize } = yield* openDesktopViewer; + const output = + viewer.output as unknown as Queue.Queue; + // Ready once the sizes measured on attach and on a first resize both arrived. + yield* resize(1920, 1080); + expect(viewportSizes(yield* Queue.takeAll(viewer.output))).toEqual([ + "1920x1080", + "1920x1080", + ]); + yield* Effect.promise(() => desktopDetachReady.promise); + yield* viewer.input({ type: "takeControl" }); + context.page.emit("filechooser", { + isMultiple: () => false, + element: () => ({ getAttribute: async () => ".csv" }), + setFiles: vi.fn(async () => {}), + }); + let chooser = yield* Queue.take(viewer.output); + while (chooser._tag !== "fileChooser") chooser = yield* Queue.take(viewer.output); + yield* Queue.clear(viewer.output); + // A resize compacts a full backlog but keeps control, the open picker and + // one-time notifications in order. + yield* viewer.input({ type: "takeControl" }); + const notifications: Array = [ + { _tag: "fileChooserClosed", id: "chooser-0" }, + { _tag: "popup", tabId: "popup-1" }, + { _tag: "download", id: "download-1", fileName: "report.csv", sizeBytes: 3 }, + { _tag: "clipboard", text: "copied" }, + ]; + for (const item of notifications) Queue.offerUnsafe(output, item); + let acked = stallViewer(viewer); + yield* resize(1000, 600); + expect(yield* Queue.takeAll(viewer.output)).toEqual([ + chooser, + ...notifications, + expect.objectContaining({ _tag: "control", controller: "you" }), + { _tag: "viewport", width: 1000, height: 600 }, + ]); + yield* acked; + // A control change keeps only the newest size. + yield* resize(900, 500); + yield* resize(1200, 700); + acked = stallViewer(viewer); + yield* viewer.input({ type: "releaseControl" }); + expect(yield* Queue.takeAll(viewer.output)).toEqual([ + expect.objectContaining({ _tag: "control", controller: "unclaimed" }), + { _tag: "viewport", width: 1200, height: 700 }, + ]); + yield* acked; + // Notifications that no longer fit go oldest first, never the size. + let copies = 0; + while (Queue.offerUnsafe(output, { _tag: "clipboard", text: `copy ${copies}` })) copies++; + yield* resize(1000, 600); + const compacted = yield* Queue.takeAll(viewer.output); + expect(compacted.at(0)).toEqual({ _tag: "clipboard", text: "copy 1" }); + expect(compacted.at(-1)).toEqual({ _tag: "viewport", width: 1000, height: 600 }); + // The desktop takes the page back; a resize after it cannot bury the reconnect. + acked = stallViewer(viewer); + desktopDetaches.emit("detach", { threadId: scope.thread.threadId, tabId }); + yield* Effect.promise(() => desktopReleased.promise); + yield* resize(1000, 600); + expect(yield* Queue.takeAll(viewer.output)).toEqual([{ _tag: "reconnect" }]); + yield* acked; + }), + ).pipe(Effect.provide(layer)), +); + it.live("agents read a human's tab with no arguments and act on it only while nobody drives", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts index 6f3e86a7501ea..57e35be778634 100644 --- a/apps/server/src/preview/ServerBrowser.ts +++ b/apps/server/src/preview/ServerBrowser.ts @@ -102,6 +102,8 @@ const RECORDING_SCREENCAST = { format: "jpeg", quality: 90, everyNthFrame: 1 } a const decodeViewportSetting = Schema.decodeUnknownSync(PreviewViewportSettingSchema); const AGENT_CURSOR_MOVE_MS = 160; const AGENT_CURSOR_CLICK_LEAD_MS = 40; +/** A dialog blocks page script, so a desktop size read gives up after this. */ +const DESKTOP_VIEWPORT_READ_TIMEOUT = "1 second"; const sleepUntil = (deadline: number) => new Promise((resolve) => setTimeout(resolve, Math.max(0, deadline - Date.now()))); @@ -309,6 +311,11 @@ interface ServerTab { setting: PreviewViewportSetting; colorScheme: PreviewAppearancePreference; zoomFactor: number; + /** Last usable CSS size measured on the desktop. */ + desktopViewport: { readonly width: number; readonly height: number } | null; + desktopViewportRead: Promise; + /** A read queued behind `desktopViewportRead`, shared by every caller that waits for it. */ + desktopViewportNext: Promise | null; loading: boolean; closing: boolean; recording: Recording | null; @@ -605,9 +612,48 @@ const make = Effect.gen(function* () { ); }; - const layoutSize = (tab: ServerTab) => { + // Desktop pages have no Playwright viewport; an isolated world keeps page script + // from overriding the CSS size, and failed reads preserve the last usable size. + const readDesktopViewport = async (tab: ServerTab) => { + const readSize = async () => { + const { frameTree } = await tab.cdp.send("Page.getFrameTree"); + const { executionContextId } = await tab.cdp.send("Page.createIsolatedWorld", { + frameId: frameTree.frame.id, + worldName: "t3-preview-viewport", + }); + const { result } = await tab.cdp.send("Runtime.evaluate", { + expression: "({ width: innerWidth, height: innerHeight })", + contextId: executionContextId, + returnByValue: true, + }); + return asRecord(result.value); + }; + const size = await runPromise( + // A navigation can destroy the isolated world mid-read. + Effect.promise(() => readSize().catch(() => null)).pipe( + Effect.timeoutOption(DESKTOP_VIEWPORT_READ_TIMEOUT), + Effect.map(Option.getOrNull), + ), + ); + const width = size?.width; + const height = size?.height; + if (typeof width === "number" && width > 0 && typeof height === "number" && height > 0) + tab.desktopViewport = { width, height }; + return tab.desktopViewport; + }; + + // Reads run one at a time, and callers that arrive during a read share the next one. + const measureDesktopViewport = (tab: ServerTab) => + (tab.desktopViewportNext ??= tab.desktopViewportRead.then(() => { + tab.desktopViewportNext = null; + return (tab.desktopViewportRead = readDesktopViewport(tab)); + })); + + const layoutSize = async (tab: ServerTab) => { + // A dialog blocks page script; its close measures again. + if (tab.desktop) return tab.dialog ? tab.desktopViewport : measureDesktopViewport(tab); const size = tab.page.viewportSize(); - if (!size || tab.desktop) return size; + if (!size) return size; return { width: Math.max(1, Math.round(size.width / tab.zoomFactor)), height: Math.max(1, Math.round(size.height / tab.zoomFactor)), @@ -622,7 +668,7 @@ const make = Effect.gen(function* () { await tab.page.setViewportSize(size); return; } - const layout = layoutSize(tab)!; + const layout = (await layoutSize(tab))!; await tab.cdp.send("Emulation.setDeviceMetricsOverride", { width: layout.width, height: layout.height, @@ -631,9 +677,9 @@ const make = Effect.gen(function* () { }); }; - const broadcastViewport = (tab: ServerTab) => { - const size = layoutSize(tab); - if (!size) return; + const broadcastViewport = async (tab: ServerTab) => { + const size = await layoutSize(tab); + if (!size || tab.closing) return; for (const viewer of tab.viewers) viewer.push({ _tag: "viewport", ...size }); }; @@ -650,7 +696,7 @@ const make = Effect.gen(function* () { UNATTACHED_FILL_VIEWPORT; await tab.page.setViewportSize({ width: size.width, height: size.height }); await applyZoom(tab); - broadcastViewport(tab); + await broadcastViewport(tab); }; const applyRendering = async (tab: ServerTab, snapshot: PreviewSessionSnapshot) => { @@ -663,7 +709,7 @@ const make = Effect.gen(function* () { if (zoomFactor !== tab.zoomFactor && !tab.desktop) { tab.zoomFactor = zoomFactor; await applyZoom(tab); - broadcastViewport(tab); + await broadcastViewport(tab); } }; @@ -789,6 +835,9 @@ const make = Effect.gen(function* () { setting: snapshot.viewport ?? FILL_PREVIEW_VIEWPORT, colorScheme: "system", zoomFactor: 1, + desktopViewport: null, + desktopViewportRead: Promise.resolve(null), + desktopViewportNext: null, loading: false, closing: false, recording: null, @@ -803,6 +852,21 @@ const make = Effect.gen(function* () { await page.setViewportSize(fixedViewportSize(tab.setting) ?? UNATTACHED_FILL_VIEWPORT); } await applyRendering(tab, snapshot); + if (desktop) { + // The desktop resizes and zooms its webview itself; viewers map input with the new size. + const remeasure = () => { + if (tab.viewers.size > 0) return broadcastViewport(tab).catch(constVoid); + }; + cdp.on("Page.frameResized", remeasure); + // A read a navigation broke has a fresh page to measure. + cdp.on("Page.loadEventFired", remeasure); + // Closing a dialog resizes nothing, and the host can close it without us. + cdp.on("Page.javascriptDialogClosed", () => { + tab.dialog = null; + return remeasure(); + }); + await cdp.send("Page.enable"); + } const isMainNavigation = (request: { isNavigationRequest(): boolean; frame(): unknown }) => request.isNavigationRequest() && request.frame() === page.mainFrame(); const navigationGenerations = new WeakMap(); @@ -1383,7 +1447,7 @@ const make = Effect.gen(function* () { }; } const url = tab.page.url(); - const viewport = tab.page.viewportSize(); + const viewport = tab.desktop ? await layoutSize(tab) : tab.page.viewportSize(); const status = { available: true, visible: tab.viewers.size > 0, @@ -2213,7 +2277,7 @@ const make = Effect.gen(function* () { const current = tab.page.viewportSize(); if (current?.width === width && current.height === height) return; await tab.page.setViewportSize({ width, height }); - broadcastViewport(tab); + await broadcastViewport(tab); return; } case "viewport": { @@ -2313,15 +2377,22 @@ const make = Effect.gen(function* () { // Dropped frames must still release Chromium. if (Queue.offerUnsafe(output, next)) return; if (next._tag === "frame") runFork(next.ack); - // State a stalled viewer cannot miss replaces its backlog. It runs - // synchronously so an older replacement can never land after a newer one. - else if (next._tag === "gone" || next._tag === "control" || next._tag === "fileChooser") { + // State a stalled viewer cannot miss compacts its backlog. It runs + // synchronously so an older compaction can never land after a newer one. + else if (["gone", "reconnect", "control", "viewport", "fileChooser"].includes(next._tag)) { const dropped = Effect.runSyncExit(Queue.clear(output)); if (dropped._tag === "Failure") return; - Queue.offerUnsafe(output, next); - - const chooser = next._tag === "control" ? fileChooserMessage(tab) : null; - if (chooser && tab.control.controller === viewer.id) Queue.offerUnsafe(output, chooser); + const items = [...dropped.value, next]; + // Without its latest size and control the viewer cannot map input at all. + const state = (["control", "viewport"] as const).flatMap( + (tag) => items.findLast((item) => item._tag === tag) ?? [], + ); + // Everything else is one-time; if it no longer fits, the oldest goes first. + const rest = items.filter( + (item) => item._tag !== "frame" && item._tag !== "control" && item._tag !== "viewport", + ); + for (const item of [...rest.slice(state.length - VIEWER_OUTPUT_LIMIT), ...state]) + Queue.offerUnsafe(output, item); for (const item of dropped.value) if (item._tag === "frame") runFork(item.ack); } }, @@ -2410,7 +2481,7 @@ const make = Effect.gen(function* () { ), }); }); - broadcastViewport(tab); + void broadcastViewport(tab).catch(constVoid); yield* Effect.promise(() => startScreencast(1)); // An idle page does not repaint for a new screencast, so the viewer // starts from a still unless a live frame beat it. From b8397e5caf2544233f599d72942fb33e6d37458a Mon Sep 17 00:00:00 2001 From: maria Date: Fri, 30 Oct 2026 16:17:17 +0000 Subject: [PATCH 434/817] feat(web): images and videos sent with text sit above the bubble as their own shape (#27306) --- .../chat/TimelineUserMessageRow.tsx | 264 +++++++++++------- 1 file changed, 158 insertions(+), 106 deletions(-) diff --git a/apps/web/src/components/chat/TimelineUserMessageRow.tsx b/apps/web/src/components/chat/TimelineUserMessageRow.tsx index 58785db77ca47..56f4ef8217ff6 100644 --- a/apps/web/src/components/chat/TimelineUserMessageRow.tsx +++ b/apps/web/src/components/chat/TimelineUserMessageRow.tsx @@ -88,7 +88,13 @@ const MEDIA_EDGE_CLASS_NAME = const BUBBLE_CHIP_CLASS_NAME = "[&_[data-slot=context-chip]]:[--context-chip-ink:var(--context-chip-message,var(--context-chip-accent))]"; -function UserVideoAttachment({ file }: { readonly file: ChatFileAttachment }) { +function UserVideoAttachment({ + file, + standalone = false, +}: { + readonly file: ChatFileAttachment; + readonly standalone?: boolean; +}) { const ctx = use(TimelineRowCtx); // Row updates rebuild attachment objects, so the asset follows only the // fields it reads. @@ -105,13 +111,20 @@ function UserVideoAttachment({ file }: { readonly file: ChatFileAttachment }) { if (asset === null && src === null) { return ( -
      +
      {file.name}
      ); } - return ( + const player = ( ); + return standalone ? ( +
      {player}
      + ) : ( + player + ); } export function UserMessageRow({ row }: { row: Extract }) { @@ -351,15 +375,22 @@ function UserTimelineRow({ row }: { row: Extract 0; + // Media sent with words sits above the bubble as its own shape, like a chat app. + const mediaAboveText = + !folded && + userMessage.attribution !== "guest" && + !mediaOnly && + regularImages.length + userVideos.length > 0; + const standaloneMedia = mediaOnly || mediaAboveText; // A lone image keeps its own shape; a 4:3 crop hides most of a wide screenshot. const loneImage = - mediaOnly && + standaloneMedia && userVideos.length === 0 && regularImages.length === 1 && regularImages[0]!.source?.kind !== "snap-shot"; - // Several images sent without words share one rounded shape, split by hairlines. + // Several images share one rounded shape, split by hairlines. const collage = - mediaOnly && + standaloneMedia && userVideos.length === 0 && regularImages.length > 1 && regularImages.every((image) => image.source?.kind !== "snap-shot"); @@ -465,6 +496,107 @@ function UserTimelineRow({ row }: { row: Extract 0 || userVideos.length > 0 ? ( +
      + {regularImages.map((image, index) => ( +
      3 && + regularImages.length % 2 === 1 && + index === regularImages.length - 1 && + "col-span-2", + ) + : standaloneMedia + ? cn(MEDIA_EDGE_CLASS_NAME, "aspect-[4/3] overflow-hidden rounded-2xl") + : "aspect-[4/3] overflow-hidden rounded-lg border border-border/80", + )} + > + {image.previewUrl ? ( + + ) : ( +
      + {image.name} +
      + )} + {image.previewUrl && image.source?.kind === "snap-shot" ? ( + + ) : null} +
      + ))} + {userVideos.map((file) => ( + + ))} +
      + ) : null; + return (
      ) : null} + {mediaAboveText ? ( +
      + {/* The heading leads the media so screen readers reach it before the images. */} + You + {mediaBlock} +
      + ) : null}
      {/* Outside the fold so a collapsed message still has a heading to navigate to. */} - - {folded - ? senderLabel - : userMessage.guestName === undefined - ? "You" - : `${userMessage.guestName} (guest)`} - + {mediaAboveText ? null : ( + + {folded + ? senderLabel + : userMessage.guestName === undefined + ? "You" + : `${userMessage.guestName} (guest)`} + + )} {folded ? ( - {(regularImages.length > 0 || userVideos.length > 0) && ( -
      - {regularImages.map((image, index) => ( -
      3 && - regularImages.length % 2 === 1 && - index === regularImages.length - 1 && - "col-span-2", - ) - : "aspect-[4/3] overflow-hidden rounded-lg border border-border/80", - )} - > - {image.previewUrl ? ( - - ) : ( -
      - {image.name} -
      - )} - {image.previewUrl && image.source?.kind === "snap-shot" ? ( - - ) : null} -
      - ))} - {userVideos.map((file) => ( - - ))} -
      - )} + {!mediaAboveText && mediaBlock} {userAudio.length > 0 ? (
      {userAudio.map((file) => ( From 1da41f949950bda57f45dc73effb7543037c844f Mon Sep 17 00:00:00 2001 From: maria Date: Fri, 30 Oct 2026 16:23:24 +0000 Subject: [PATCH 435/817] feat(web): files sent without text show as file cards (#27324) --- .../chat/TimelineUserMessageRow.tsx | 137 ++++++++++++++++-- 1 file changed, 121 insertions(+), 16 deletions(-) diff --git a/apps/web/src/components/chat/TimelineUserMessageRow.tsx b/apps/web/src/components/chat/TimelineUserMessageRow.tsx index 56f4ef8217ff6..aee30e27d51ec 100644 --- a/apps/web/src/components/chat/TimelineUserMessageRow.tsx +++ b/apps/web/src/components/chat/TimelineUserMessageRow.tsx @@ -54,6 +54,7 @@ import { GuestMessageName, guestBubbleClassName } from "./guestMessageStyle"; import { MessageCopyButton } from "./MessageCopyButton"; import { promptLinkFor } from "../promptLinks/copyPromptLink"; import { PierreEntryIcon } from "./PierreEntryIcon"; +import { formatBytes } from "../../lib/formatBytes"; import { shouldCollapseUserMessage } from "./MessagesTimeline.logic"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { @@ -88,6 +89,68 @@ const MEDIA_EDGE_CLASS_NAME = const BUBBLE_CHIP_CLASS_NAME = "[&_[data-slot=context-chip]]:[--context-chip-ink:var(--context-chip-message,var(--context-chip-accent))]"; +function UserFileCard({ + file, + copyMarkdown, +}: { + readonly file: ChatFileAttachment; + readonly copyMarkdown: string | undefined; +}) { + const ctx = use(TimelineRowCtx); + const extension = /\.([a-z0-9]{1,8})$/i.exec(file.name)?.[1]?.toUpperCase() ?? "File"; + const identity = ( + <> + + + + + + {file.name} + + + {extension} · {formatBytes(file.sizeBytes)} + + + + ); + return ( +
      + {file.downloadable === false ? ( +
      {identity}
      + ) : ( + <> + + + ctx.onFileDownload(file)} + /> + } + > + + + Download {file.name} + + + )} +
      + ); +} + function UserVideoAttachment({ file, standalone = false, @@ -358,11 +421,22 @@ function UserTimelineRow({ row }: { row: Extract image.name.startsWith("preview-annotation-")); const revertTurnCount = row.revertTurnCount; - const chippedAttachmentIds = new Set( - collectComposerContextReferences(resolvedContext.text).flatMap((occurrence) => { + const attachmentReferences = collectComposerContextReferences(resolvedContext.text).flatMap( + (occurrence) => { const record = asKnownContextRecord(resolvedContext.recordsById.get(occurrence.contextId)); - return record?.kind === "file" || record?.kind === "image" ? [record.attachmentId] : []; - }), + return record?.kind === "file" || record?.kind === "image" + ? [ + { + attachmentId: record.attachmentId, + contextId: occurrence.contextId, + source: occurrence.source, + }, + ] + : []; + }, + ); + const chippedAttachmentIds = new Set( + attachmentReferences.map((reference) => reference.attachmentId), ); const regularImages = userImages.filter((image) => !image.name.startsWith("preview-annotation-")); const unchippedFiles = otherUserFiles.filter((file) => !chippedAttachmentIds.has(file.id)); @@ -394,6 +468,21 @@ function UserTimelineRow({ row }: { row: Extract 1 && regularImages.every((image) => image.source?.kind !== "snap-shot"); + // Files sent without words show as cards, not as a bubble around a name chip. + const fileCardsOnly = + !folded && + userMessage.attribution !== "guest" && + otherUserFiles.length > 0 && + regularImages.length + userVideos.length + userAudio.length + unknownAttachments.length === 0 && + replaceComposerContextReferences(resolvedContext.text, (reference) => + attachmentReferences.some( + (attached) => + attached.contextId === reference.contextId && + otherUserFiles.some((file) => file.id === attached.attachmentId), + ) + ? "" + : reference.label, + ).trim() === ""; const annotationRecordIds = resolvedContext.records .filter((record) => record.kind === "preview-annotation") .map((record) => record.contextId); @@ -635,8 +724,8 @@ function UserTimelineRow({ row }: { row: Extract @@ -689,7 +778,21 @@ function UserTimelineRow({ row }: { row: Extract ) : null} - {unchippedFiles.length > 0 || unknownAttachments.length > 0 ? ( + {fileCardsOnly ? ( +
      + {otherUserFiles.map((file) => ( + reference.attachmentId === file.id) + ?.source + } + /> + ))} +
      + ) : null} + {!fileCardsOnly && (unchippedFiles.length > 0 || unknownAttachments.length > 0) ? (
      {unchippedFiles.map((file) => { const fileIdentity = ( @@ -751,15 +854,17 @@ function UserTimelineRow({ row }: { row: Extract ) : null} -
      - -
      + {fileCardsOnly ? null : ( +
      + +
      + )}
      ) : null}
      From e57ae5a0bf38a4a38018df57d250fce323702401 Mon Sep 17 00:00:00 2001 From: maria Date: Fri, 30 Oct 2026 16:39:52 +0000 Subject: [PATCH 436/817] feat(web): pasted text, voice notes, snapshots and sending files get their own shapes (#27377) --- apps/web/src/components/ContextChip.tsx | 9 +- .../chat/MessagesTimeline.browser.test.tsx | 75 +++++++++++ .../chat/TimelineUserMessageRow.logic.ts | 6 +- .../chat/TimelineUserMessageRow.tsx | 121 +++++++++++++----- .../chat/UserMessageContextChips.tsx | 11 +- .../web/src/components/files/AudioPreview.tsx | 4 +- .../components/files/InlineAudioPreview.tsx | 2 + 7 files changed, 189 insertions(+), 39 deletions(-) diff --git a/apps/web/src/components/ContextChip.tsx b/apps/web/src/components/ContextChip.tsx index fcd4c9e4fed30..a536f28ccfb12 100644 --- a/apps/web/src/components/ContextChip.tsx +++ b/apps/web/src/components/ContextChip.tsx @@ -35,6 +35,10 @@ const contextChipVariants = cva( "doc-slides": "[--context-chip-accent:var(--context-chip-doc-slides)]", "doc-epub": "[--context-chip-accent:var(--context-chip-doc-epub)]", }, + shape: { + inline: "", + bubble: "w-64 gap-2 rounded-2xl bg-message px-3 py-2 text-sm text-message-foreground", + }, state: { unresolved: "data-[state=unresolved]:[--context-chip-accent:currentColor]", invalid: @@ -49,11 +53,12 @@ type ContextChipKind = NonNullable["kin interface ContextChipProps extends useRender.ComponentProps<"span"> { kind?: ContextChipKind; state?: "unresolved" | "invalid"; + shape?: "inline" | "bubble"; } -function ContextChip({ className, kind, state, render, ...props }: ContextChipProps) { +function ContextChip({ className, kind, state, shape, render, ...props }: ContextChipProps) { const defaultProps = { - className: cn(contextChipVariants({ kind, state }), className), + className: cn(contextChipVariants({ kind, state, shape }), className), "data-slot": "context-chip", "data-state": state, }; diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index 2c7aa332756cb..24e15957192b1 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -3,6 +3,7 @@ import { onTestFinished } from "vite-plus/test"; import { page } from "vite-plus/test/browser"; import { stubGlobal } from "../../../test/render"; import { + ComposerContextId, EnvironmentId, MessageId, RunAttemptId, @@ -32,6 +33,11 @@ import { toastManager } from "../ui/toast"; import type { CitedHistory } from "./citationProcedure"; import type { TimelineNavigation } from "./timelineViewport"; import { rememberTimelinePosition } from "./timelineScrollAnchoring"; +import { + COMPOSER_CONTEXT_CLIPBOARD_MIME, + decodeComposerContextFragment, +} from "@t3tools/shared/composerContextClipboard"; +import { collectComposerContextReferences } from "@t3tools/shared/composerContextReferences"; const environmentQuery = vi.hoisted(() => ({ error: "Pull request not found", @@ -642,6 +648,75 @@ describe("MessagesTimeline agent messages", () => { }); describe("MessagesTimeline attachments", () => { + it.each(["image", "file"] as const)( + "copies only matching context records for a wordless %s attachment", + async (kind) => { + const attachment = { + type: kind, + id: "media", + name: kind === "image" ? "photo.png" : "clip.mp4", + mimeType: kind === "image" ? "image/png" : "video/mp4", + sizeBytes: 100, + downloadable: false, + }; + const record = { + version: 1 as const, + ...(kind === "image" ? { kind: "image" as const } : { kind: "file" as const }), + contextId: ComposerContextId.make("media-context"), + label: attachment.name, + attachmentId: attachment.id, + name: attachment.name, + mimeType: attachment.mimeType, + sizeBytes: attachment.sizeBytes, + }; + await using screen = await renderTimeline([message("", { attachments: [attachment] })]); + expect(screen.buttons("Copy message")).toHaveLength(0); + await screen.rerender( + , + ); + expect(screen.buttons("Copy message")).toHaveLength(0); + await screen.rerender( + , + ); + using write = vi.spyOn(navigator.clipboard, "write").mockResolvedValue(); + await click(screen.button("Copy message")); + await vi.waitFor(() => expect(write).toHaveBeenCalledOnce()); + const [item] = write.mock.calls[0]![0]; + const text = await (await item!.getType("text/plain")).text(); + const fragment = await (await item!.getType(COMPOSER_CONTEXT_CLIPBOARD_MIME)).text(); + expect( + collectComposerContextReferences(text).map((reference) => reference.contextId), + ).toEqual([record.contextId]); + expect(decodeComposerContextFragment(fragment)?.records).toEqual([record]); + }, + ); + it.each(["loadedmetadata", "loadeddata", "canplay"])( "plays audio with unknown duration after %s and updates the total later", async (readyEvent) => { diff --git a/apps/web/src/components/chat/TimelineUserMessageRow.logic.ts b/apps/web/src/components/chat/TimelineUserMessageRow.logic.ts index 9738e29d7ccaa..2bb6d0470fa18 100644 --- a/apps/web/src/components/chat/TimelineUserMessageRow.logic.ts +++ b/apps/web/src/components/chat/TimelineUserMessageRow.logic.ts @@ -1,7 +1,11 @@ -import { type ChatImageAttachment } from "../../types"; +import { type ChatFileAttachment, type ChatImageAttachment } from "../../types"; import type { ComposerContextRecord, KnownComposerContextRecord } from "@t3tools/contracts"; import { asKnownContextRecord } from "~/lib/composerContextRecords"; +export function userMessageFileLabel(file: Pick) { + return file.source?._tag === "pasted-text" ? "Pasted text" : file.name; +} + export function resolvePreviewAnnotationImage(input: { record: Extract; recordsById: ReadonlyMap; diff --git a/apps/web/src/components/chat/TimelineUserMessageRow.tsx b/apps/web/src/components/chat/TimelineUserMessageRow.tsx index aee30e27d51ec..48086d40b4bf3 100644 --- a/apps/web/src/components/chat/TimelineUserMessageRow.tsx +++ b/apps/web/src/components/chat/TimelineUserMessageRow.tsx @@ -62,7 +62,10 @@ import { resolveUserMessageContext, selectedMessageContextFragment, } from "~/lib/composerContextRecords"; -import { collectComposerContextReferences } from "@t3tools/shared/composerContextReferences"; +import { + collectComposerContextReferences, + formatComposerContextReference, +} from "@t3tools/shared/composerContextReferences"; import { COMPOSER_CONTEXT_CLIPBOARD_MIME, encodeComposerContextClipboardHtml, @@ -80,7 +83,10 @@ import { TimelineRowTimestamp, } from "./TimelineRowParts"; import { UserMessageContextReferenceChip } from "./UserMessageContextChips"; -import { resolvePreviewAnnotationImage } from "./TimelineUserMessageRow.logic"; +import { + resolvePreviewAnnotationImage, + userMessageFileLabel, +} from "./TimelineUserMessageRow.logic"; // Drawn inside the media so dark screenshots keep an edge on the dark background. const MEDIA_EDGE_CLASS_NAME = @@ -97,6 +103,8 @@ function UserFileCard({ readonly copyMarkdown: string | undefined; }) { const ctx = use(TimelineRowCtx); + const pastedText = file.source?._tag === "pasted-text"; + const label = userMessageFileLabel(file); const extension = /\.([a-z0-9]{1,8})$/i.exec(file.name)?.[1]?.toUpperCase() ?? "File"; const identity = ( <> @@ -105,10 +113,17 @@ function UserFileCard({ - {file.name} + {label} - {extension} · {formatBytes(file.sizeBytes)} + {file.downloadable === false ? ( + "Sending…" + ) : ( + <> + {!pastedText && `${extension} · `} + {formatBytes(file.sizeBytes)} + + )} @@ -119,12 +134,17 @@ function UserFileCard({ className="flex w-64 max-w-full items-center gap-1 rounded-2xl bg-message py-2 ps-2 pe-1 text-message-foreground" > {file.downloadable === false ? ( -
      {identity}
      + <> +
      {identity}
      + + ) : ( <> @@ -724,8 +773,8 @@ function UserTimelineRow({ row }: { row: Extract @@ -760,11 +809,12 @@ function UserTimelineRow({ row }: { row: Extract {!mediaAboveText && mediaBlock} {userAudio.length > 0 ? ( -
      +
      {userAudio.map((file) => ( 0 || unknownAttachments.length > 0) ? (
      {unchippedFiles.map((file) => { + const pastedText = file.source?._tag === "pasted-text"; + const label = userMessageFileLabel(file); const fileIdentity = ( <> - {file.name} + + {label} + {file.downloadable === false || pastedText ? ( + + {file.downloadable === false ? "Sending…" : formatBytes(file.sizeBytes)} + + ) : null} + ); if (file.downloadable !== false) { @@ -810,7 +869,7 @@ function UserTimelineRow({ row }: { row: Extract
      ); @@ -854,7 +913,7 @@ function UserTimelineRow({ row }: { row: Extract ) : null} - {fileCardsOnly ? null : ( + {fileCardsOnly || audioOnly ? null : (
      )} - {resolvedContext.text && ( + {copyText && ( ; @@ -372,12 +373,14 @@ const userMessageContextPresentationRegistry = createContextPresentationRegistry } const attachment = context.attachment; const isVideo = isVideoAttachment(attachment); + const label = userMessageFileLabel(attachment); const disabled = attachment.downloadable === false && (!isVideo || attachment.previewUrl === undefined); - const size = formatAttachmentSize(record.sizeBytes); + const size = + attachment.downloadable === false ? "Sending…" : formatAttachmentSize(record.sizeBytes); return ( isVideo ? context.onExpandVideo(attachment) : context.onOpenFile(attachment) } - tooltip={`${record.name}\n${size}`} + tooltip={`${label}\n${size}`} /> ); }, diff --git a/apps/web/src/components/files/AudioPreview.tsx b/apps/web/src/components/files/AudioPreview.tsx index 0a8f4bcfe16c9..abd05015a9414 100644 --- a/apps/web/src/components/files/AudioPreview.tsx +++ b/apps/web/src/components/files/AudioPreview.tsx @@ -15,6 +15,7 @@ type AudioPreviewProps = { readonly revision?: string | null; readonly onError?: () => void; readonly compact?: boolean; + readonly variant?: "chip" | "bubble"; readonly failed?: boolean; readonly onOpen?: (() => void) | undefined; readonly onRetry?: () => void; @@ -111,6 +112,7 @@ function AudioChip(props: AudioPreviewProps) { @@ -140,7 +142,7 @@ function AudioChip(props: AudioPreviewProps) { > - + {open ? ( + + ); +} + +it.each([ + { width: 1920, height: 1080, axis: "width", typed: "2560", expected: "2560 × 1440" }, + { width: 390, height: 844, axis: "height", typed: "2532", expected: "1170 × 2532" }, +])("keeps each typed $axis digit until the locked size is committed", async (testCase) => { + await using screen = await render(); + const input = screen.getByRole("spinbutton", { name: `Viewport ${testCase.axis}` }); + await userEvent.clear(input); + await userEvent.type(input, testCase.typed); + await expect.element(input).toHaveValue(Number(testCase.typed)); + await screen.getByRole("button", { name: "Leave toolbar" }).click(); + await expect + .element(screen.getByRole("status", { name: "Saved viewport" })) + .toHaveTextContent(testCase.expected); +}); + +it("clamps a completed width below the locked minimum when leaving the toolbar", async () => { + await using screen = await render(); + const input = screen.getByRole("spinbutton", { name: "Viewport width" }); + await userEvent.clear(input); + await userEvent.type(input, "256"); + await expect.element(input).toHaveValue(256); + await screen.getByRole("button", { name: "Leave toolbar" }).click(); + await expect + .element(screen.getByRole("status", { name: "Saved viewport" })) + .toHaveTextContent("427 × 240"); +}); + +it("still limits a completed locked size to the viewport area cap", async () => { + await using screen = await render(); + const input = screen.getByRole("spinbutton", { name: "Viewport width" }); + await userEvent.clear(input); + await userEvent.type(input, "3840"); + await expect.element(input).toHaveValue(3840); + await screen.getByRole("button", { name: "Leave toolbar" }).click(); + await expect + .element(screen.getByRole("status", { name: "Saved viewport" })) + .toHaveTextContent("2880 × 2880"); +}); diff --git a/apps/web/src/browser/BrowserDeviceToolbar.tsx b/apps/web/src/browser/BrowserDeviceToolbar.tsx index dd5b707cfebdb..977431aa6ff4d 100644 --- a/apps/web/src/browser/BrowserDeviceToolbar.tsx +++ b/apps/web/src/browser/BrowserDeviceToolbar.tsx @@ -51,6 +51,7 @@ export function BrowserDeviceToolbar({ const [customSize, setCustomSize] = useState<{ readonly width: string; readonly height: string; + readonly axis?: "width" | "height"; } | null>(null); const presentedSize = customSize ?? { width: String(setting.width), @@ -61,15 +62,25 @@ export function BrowserDeviceToolbar({ PREVIEW_VIEWPORT_PRESETS.some((preset) => preset.id === setting.presetId) ? setting.presetId : RESPONSIVE_VALUE; - const customWidth = Number(presentedSize.width); - const customHeight = Number(presentedSize.height); + const typedWidth = Number(presentedSize.width); + const typedHeight = Number(presentedSize.height); + const { width: customWidth, height: customHeight } = + aspectRatio === null || customSize?.axis === undefined + ? { width: typedWidth, height: typedHeight } + : resizeFreeformViewport( + { width: typedWidth, height: typedHeight }, + { x: 0, y: 0 }, + 1, + customSize?.axis === "height" ? "south" : "east", + aspectRatio, + ); const customValid = - Number.isInteger(customWidth) && - Number.isInteger(customHeight) && - customWidth >= PREVIEW_VIEWPORT_MIN_DIMENSION && - customWidth <= PREVIEW_VIEWPORT_MAX_DIMENSION && - customHeight >= PREVIEW_VIEWPORT_MIN_DIMENSION && - customHeight <= PREVIEW_VIEWPORT_MAX_DIMENSION && + Number.isInteger(typedWidth) && + Number.isInteger(typedHeight) && + typedWidth >= PREVIEW_VIEWPORT_MIN_DIMENSION && + typedWidth <= PREVIEW_VIEWPORT_MAX_DIMENSION && + typedHeight >= PREVIEW_VIEWPORT_MIN_DIMENSION && + typedHeight <= PREVIEW_VIEWPORT_MAX_DIMENSION && customWidth * customHeight <= PREVIEW_VIEWPORT_MAX_AREA; const apply = (next: PreviewViewportSetting, nextAspectRatio = aspectRatio) => { @@ -96,6 +107,7 @@ export function BrowserDeviceToolbar({ const next = { width: axis === "width" ? value : (current?.width ?? String(setting.width)), height: axis === "height" ? value : (current?.height ?? String(setting.height)), + axis, }; const numeric = Number(value); if ( @@ -115,7 +127,11 @@ export function BrowserDeviceToolbar({ axis === "width" ? "east" : "south", aspectRatio, ); - return { width: String(resized.width), height: String(resized.height) }; + return { + ...next, + width: axis === "width" ? value : String(resized.width), + height: axis === "height" ? value : String(resized.height), + }; }); }; From 87b36c77fb5cdb26911d2419f62a23dbab6becc5 Mon Sep 17 00:00:00 2001 From: Alex Southwell Date: Fri, 30 Oct 2026 20:45:50 +0000 Subject: [PATCH 501/817] fix(codex): preserve partial answer messages and thread histories (#23388) Co-authored-by: SAPHID Co-authored-by: maria-rcks --- .../Adapters/CodexAdapterV2.test.ts | 35 ++++- .../Adapters/CodexAdapterV2.ts | 4 +- .../scripts/generate.ts | 23 +++ .../src/_generated/schema.gen.ts | 135 +++++++++++++++--- .../src/schema.test.ts | 46 ++++++ 5 files changed, 219 insertions(+), 24 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 6413ed0bfe9ac..8efdc1b468b3a 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -3201,7 +3201,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { answers: ReadonlyArray<{ readonly id: string; readonly text: string; - readonly phase?: "commentary" | "final_answer" | null; + readonly phase?: "commentary" | "partial_answer" | "final_answer" | null; readonly omitPhase?: boolean; readonly streamed?: boolean; readonly completionDelayMs?: number; @@ -3296,6 +3296,39 @@ describe("CodexAdapterV2 post-settle continuation", () => { }); }; + it.effect.each([false, true])( + "preserves a final answer that repeats a preceding partial answer (streamed: %s)", + (streamed) => + Effect.scoped( + Effect.gen(function* () { + const transcript = finalAnswerTranscript("codex-partial-then-final", [ + { id: "partial", text: "CODEX_RECOVERY_OK", phase: "partial_answer", streamed }, + { id: "final", text: "CODEX_RECOVERY_OK", phase: "final_answer", streamed }, + ]); + const harness = yield* makeCodexReplayHarness(transcript); + const now = yield* DateTime.now; + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-codex-partial-then-final"), + text: "Reply with the requested recovery marker.", + }), + ); + yield* harness.awaitTerminal(1); + assert.deepEqual( + assistantMessages(harness.events).map((event) => event.message.text), + ["CODEX_RECOVERY_OK", "CODEX_RECOVERY_OK"], + ); + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ), + ); + it.effect.each([ { name: "a text reply gains each saved image once", diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 1ebb5b5fb12d4..37426780466f8 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -4769,7 +4769,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( } if (payload.item.type === "agentMessage") { - if (payload.item.phase !== "commentary") { + if (payload.item.phase == null || payload.item.phase === "final_answer") { yield* Ref.update(finalAnswerItemIdsByTurn, (current) => { const updated = new Map(current); const itemIds = new Set(updated.get(payload.turnId) ?? []); @@ -5132,7 +5132,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( return; } - const finalAnswer = payload.item.phase !== "commentary"; + const finalAnswer = payload.item.phase == null || payload.item.phase === "final_answer"; if (finalAnswer) { yield* Ref.update(finalAnswerItemIdsByTurn, (current) => { const updated = new Map(current); diff --git a/packages/effect-codex-app-server/scripts/generate.ts b/packages/effect-codex-app-server/scripts/generate.ts index 23ce2e1edd360..8f9a45bb9293c 100644 --- a/packages/effect-codex-app-server/scripts/generate.ts +++ b/packages/effect-codex-app-server/scripts/generate.ts @@ -145,6 +145,29 @@ const ManualSchemas: Record = { // `account/read` decode and take the provider down with it. const DefinitionOverrides: Record = { PlanType: { type: "string" }, + // Newer custom Codex binaries emit partial answers before additional tools or text. + MessagePhase: { + description: + 'Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as "phase unknown" and keep compatibility behavior for legacy models.', + oneOf: [ + { + type: "string", + enum: ["commentary"], + description: + "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", + }, + { + type: "string", + enum: ["partial_answer"], + description: "Stable answer text that may be followed by more assistant output or tools.", + }, + { + type: "string", + enum: ["final_answer"], + description: "The assistant's terminal answer text for the current turn.", + }, + ], + }, }; const getGeneratedPaths = Effect.fn("getGeneratedPaths")(function* () { diff --git a/packages/effect-codex-app-server/src/_generated/schema.gen.ts b/packages/effect-codex-app-server/src/_generated/schema.gen.ts index 90006c016978b..90869b56aa89d 100644 --- a/packages/effect-codex-app-server/src/_generated/schema.gen.ts +++ b/packages/effect-codex-app-server/src/_generated/schema.gen.ts @@ -1532,13 +1532,16 @@ export const ClientRequest__InternalChatMessageMetadataPassthrough = Schema.Stru identifier: "ClientRequest__InternalChatMessageMetadataPassthrough", }); -export type ClientRequest__MessagePhase = "commentary" | "final_answer"; +export type ClientRequest__MessagePhase = "commentary" | "partial_answer" | "final_answer"; export const ClientRequest__MessagePhase = Schema.Union( [ Schema.Literal("commentary").annotate({ description: "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", }), + Schema.Literal("partial_answer").annotate({ + description: "Stable answer text that may be followed by more assistant output or tools.", + }), Schema.Literal("final_answer").annotate({ description: "The assistant's terminal answer text for the current turn.", }), @@ -2219,13 +2222,16 @@ export const ServerNotification__MemoryCitationEntry = Schema.Struct({ path: Schema.String, }).annotate({ identifier: "ServerNotification__MemoryCitationEntry" }); -export type ServerNotification__MessagePhase = "commentary" | "final_answer"; +export type ServerNotification__MessagePhase = "commentary" | "partial_answer" | "final_answer"; export const ServerNotification__MessagePhase = Schema.Union( [ Schema.Literal("commentary").annotate({ description: "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", }), + Schema.Literal("partial_answer").annotate({ + description: "Stable answer text that may be followed by more assistant output or tools.", + }), Schema.Literal("final_answer").annotate({ description: "The assistant's terminal answer text for the current turn.", }), @@ -5991,13 +5997,19 @@ export const V2ItemCompletedNotification__MemoryCitationEntry = Schema.Struct({ path: Schema.String, }).annotate({ identifier: "V2ItemCompletedNotification__MemoryCitationEntry" }); -export type V2ItemCompletedNotification__MessagePhase = "commentary" | "final_answer"; +export type V2ItemCompletedNotification__MessagePhase = + | "commentary" + | "partial_answer" + | "final_answer"; export const V2ItemCompletedNotification__MessagePhase = Schema.Union( [ Schema.Literal("commentary").annotate({ description: "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", }), + Schema.Literal("partial_answer").annotate({ + description: "Stable answer text that may be followed by more assistant output or tools.", + }), Schema.Literal("final_answer").annotate({ description: "The assistant's terminal answer text for the current turn.", }), @@ -6538,13 +6550,19 @@ export const V2ItemStartedNotification__MemoryCitationEntry = Schema.Struct({ path: Schema.String, }).annotate({ identifier: "V2ItemStartedNotification__MemoryCitationEntry" }); -export type V2ItemStartedNotification__MessagePhase = "commentary" | "final_answer"; +export type V2ItemStartedNotification__MessagePhase = + | "commentary" + | "partial_answer" + | "final_answer"; export const V2ItemStartedNotification__MessagePhase = Schema.Union( [ Schema.Literal("commentary").annotate({ description: "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", }), + Schema.Literal("partial_answer").annotate({ + description: "Stable answer text that may be followed by more assistant output or tools.", + }), Schema.Literal("final_answer").annotate({ description: "The assistant's terminal answer text for the current turn.", }), @@ -7915,13 +7933,19 @@ export const V2RawResponseItemCompletedNotification__InternalChatMessageMetadata identifier: "V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough", }); -export type V2RawResponseItemCompletedNotification__MessagePhase = "commentary" | "final_answer"; +export type V2RawResponseItemCompletedNotification__MessagePhase = + | "commentary" + | "partial_answer" + | "final_answer"; export const V2RawResponseItemCompletedNotification__MessagePhase = Schema.Union( [ Schema.Literal("commentary").annotate({ description: "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", }), + Schema.Literal("partial_answer").annotate({ + description: "Stable answer text that may be followed by more assistant output or tools.", + }), Schema.Literal("final_answer").annotate({ description: "The assistant's terminal answer text for the current turn.", }), @@ -8215,13 +8239,16 @@ export const V2ReviewStartResponse__MemoryCitationEntry = Schema.Struct({ path: Schema.String, }).annotate({ identifier: "V2ReviewStartResponse__MemoryCitationEntry" }); -export type V2ReviewStartResponse__MessagePhase = "commentary" | "final_answer"; +export type V2ReviewStartResponse__MessagePhase = "commentary" | "partial_answer" | "final_answer"; export const V2ReviewStartResponse__MessagePhase = Schema.Union( [ Schema.Literal("commentary").annotate({ description: "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", }), + Schema.Literal("partial_answer").annotate({ + description: "Stable answer text that may be followed by more assistant output or tools.", + }), Schema.Literal("final_answer").annotate({ description: "The assistant's terminal answer text for the current turn.", }), @@ -8927,13 +8954,16 @@ export const V2ThreadForkResponse__MemoryCitationEntry = Schema.Struct({ path: Schema.String, }).annotate({ identifier: "V2ThreadForkResponse__MemoryCitationEntry" }); -export type V2ThreadForkResponse__MessagePhase = "commentary" | "final_answer"; +export type V2ThreadForkResponse__MessagePhase = "commentary" | "partial_answer" | "final_answer"; export const V2ThreadForkResponse__MessagePhase = Schema.Union( [ Schema.Literal("commentary").annotate({ description: "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", }), + Schema.Literal("partial_answer").annotate({ + description: "Stable answer text that may be followed by more assistant output or tools.", + }), Schema.Literal("final_answer").annotate({ description: "The assistant's terminal answer text for the current turn.", }), @@ -9382,13 +9412,19 @@ export const V2ThreadItemsListResponse__MemoryCitationEntry = Schema.Struct({ path: Schema.String, }).annotate({ identifier: "V2ThreadItemsListResponse__MemoryCitationEntry" }); -export type V2ThreadItemsListResponse__MessagePhase = "commentary" | "final_answer"; +export type V2ThreadItemsListResponse__MessagePhase = + | "commentary" + | "partial_answer" + | "final_answer"; export const V2ThreadItemsListResponse__MessagePhase = Schema.Union( [ Schema.Literal("commentary").annotate({ description: "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", }), + Schema.Literal("partial_answer").annotate({ + description: "Stable answer text that may be followed by more assistant output or tools.", + }), Schema.Literal("final_answer").annotate({ description: "The assistant's terminal answer text for the current turn.", }), @@ -9872,13 +9908,16 @@ export const V2ThreadListResponse__MemoryCitationEntry = Schema.Struct({ path: Schema.String, }).annotate({ identifier: "V2ThreadListResponse__MemoryCitationEntry" }); -export type V2ThreadListResponse__MessagePhase = "commentary" | "final_answer"; +export type V2ThreadListResponse__MessagePhase = "commentary" | "partial_answer" | "final_answer"; export const V2ThreadListResponse__MessagePhase = Schema.Union( [ Schema.Literal("commentary").annotate({ description: "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", }), + Schema.Literal("partial_answer").annotate({ + description: "Stable answer text that may be followed by more assistant output or tools.", + }), Schema.Literal("final_answer").annotate({ description: "The assistant's terminal answer text for the current turn.", }), @@ -10364,13 +10403,19 @@ export const V2ThreadMetadataUpdateResponse__MemoryCitationEntry = Schema.Struct path: Schema.String, }).annotate({ identifier: "V2ThreadMetadataUpdateResponse__MemoryCitationEntry" }); -export type V2ThreadMetadataUpdateResponse__MessagePhase = "commentary" | "final_answer"; +export type V2ThreadMetadataUpdateResponse__MessagePhase = + | "commentary" + | "partial_answer" + | "final_answer"; export const V2ThreadMetadataUpdateResponse__MessagePhase = Schema.Union( [ Schema.Literal("commentary").annotate({ description: "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", }), + Schema.Literal("partial_answer").annotate({ + description: "Stable answer text that may be followed by more assistant output or tools.", + }), Schema.Literal("final_answer").annotate({ description: "The assistant's terminal answer text for the current turn.", }), @@ -10822,13 +10867,16 @@ export const V2ThreadReadResponse__MemoryCitationEntry = Schema.Struct({ path: Schema.String, }).annotate({ identifier: "V2ThreadReadResponse__MemoryCitationEntry" }); -export type V2ThreadReadResponse__MessagePhase = "commentary" | "final_answer"; +export type V2ThreadReadResponse__MessagePhase = "commentary" | "partial_answer" | "final_answer"; export const V2ThreadReadResponse__MessagePhase = Schema.Union( [ Schema.Literal("commentary").annotate({ description: "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", }), + Schema.Literal("partial_answer").annotate({ + description: "Stable answer text that may be followed by more assistant output or tools.", + }), Schema.Literal("final_answer").annotate({ description: "The assistant's terminal answer text for the current turn.", }), @@ -11382,13 +11430,16 @@ export const V2ThreadResumeParams__InternalChatMessageMetadataPassthrough = Sche identifier: "V2ThreadResumeParams__InternalChatMessageMetadataPassthrough", }); -export type V2ThreadResumeParams__MessagePhase = "commentary" | "final_answer"; +export type V2ThreadResumeParams__MessagePhase = "commentary" | "partial_answer" | "final_answer"; export const V2ThreadResumeParams__MessagePhase = Schema.Union( [ Schema.Literal("commentary").annotate({ description: "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", }), + Schema.Literal("partial_answer").annotate({ + description: "Stable answer text that may be followed by more assistant output or tools.", + }), Schema.Literal("final_answer").annotate({ description: "The assistant's terminal answer text for the current turn.", }), @@ -11755,13 +11806,16 @@ export const V2ThreadResumeResponse__MemoryCitationEntry = Schema.Struct({ path: Schema.String, }).annotate({ identifier: "V2ThreadResumeResponse__MemoryCitationEntry" }); -export type V2ThreadResumeResponse__MessagePhase = "commentary" | "final_answer"; +export type V2ThreadResumeResponse__MessagePhase = "commentary" | "partial_answer" | "final_answer"; export const V2ThreadResumeResponse__MessagePhase = Schema.Union( [ Schema.Literal("commentary").annotate({ description: "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", }), + Schema.Literal("partial_answer").annotate({ + description: "Stable answer text that may be followed by more assistant output or tools.", + }), Schema.Literal("final_answer").annotate({ description: "The assistant's terminal answer text for the current turn.", }), @@ -12202,13 +12256,16 @@ export const V2ThreadRevertResponse__MemoryCitationEntry = Schema.Struct({ path: Schema.String, }).annotate({ identifier: "V2ThreadRevertResponse__MemoryCitationEntry" }); -export type V2ThreadRevertResponse__MessagePhase = "commentary" | "final_answer"; +export type V2ThreadRevertResponse__MessagePhase = "commentary" | "partial_answer" | "final_answer"; export const V2ThreadRevertResponse__MessagePhase = Schema.Union( [ Schema.Literal("commentary").annotate({ description: "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", }), + Schema.Literal("partial_answer").annotate({ + description: "Stable answer text that may be followed by more assistant output or tools.", + }), Schema.Literal("final_answer").annotate({ description: "The assistant's terminal answer text for the current turn.", }), @@ -12841,13 +12898,19 @@ export const V2ThreadStartedNotification__MemoryCitationEntry = Schema.Struct({ path: Schema.String, }).annotate({ identifier: "V2ThreadStartedNotification__MemoryCitationEntry" }); -export type V2ThreadStartedNotification__MessagePhase = "commentary" | "final_answer"; +export type V2ThreadStartedNotification__MessagePhase = + | "commentary" + | "partial_answer" + | "final_answer"; export const V2ThreadStartedNotification__MessagePhase = Schema.Union( [ Schema.Literal("commentary").annotate({ description: "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", }), + Schema.Literal("partial_answer").annotate({ + description: "Stable answer text that may be followed by more assistant output or tools.", + }), Schema.Literal("final_answer").annotate({ description: "The assistant's terminal answer text for the current turn.", }), @@ -13469,13 +13532,16 @@ export const V2ThreadStartResponse__MemoryCitationEntry = Schema.Struct({ path: Schema.String, }).annotate({ identifier: "V2ThreadStartResponse__MemoryCitationEntry" }); -export type V2ThreadStartResponse__MessagePhase = "commentary" | "final_answer"; +export type V2ThreadStartResponse__MessagePhase = "commentary" | "partial_answer" | "final_answer"; export const V2ThreadStartResponse__MessagePhase = Schema.Union( [ Schema.Literal("commentary").annotate({ description: "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", }), + Schema.Literal("partial_answer").annotate({ + description: "Stable answer text that may be followed by more assistant output or tools.", + }), Schema.Literal("final_answer").annotate({ description: "The assistant's terminal answer text for the current turn.", }), @@ -13910,13 +13976,19 @@ export const V2ThreadTurnsListResponse__MemoryCitationEntry = Schema.Struct({ path: Schema.String, }).annotate({ identifier: "V2ThreadTurnsListResponse__MemoryCitationEntry" }); -export type V2ThreadTurnsListResponse__MessagePhase = "commentary" | "final_answer"; +export type V2ThreadTurnsListResponse__MessagePhase = + | "commentary" + | "partial_answer" + | "final_answer"; export const V2ThreadTurnsListResponse__MessagePhase = Schema.Union( [ Schema.Literal("commentary").annotate({ description: "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", }), + Schema.Literal("partial_answer").annotate({ + description: "Stable answer text that may be followed by more assistant output or tools.", + }), Schema.Literal("final_answer").annotate({ description: "The assistant's terminal answer text for the current turn.", }), @@ -14384,13 +14456,19 @@ export const V2ThreadUnarchiveResponse__MemoryCitationEntry = Schema.Struct({ path: Schema.String, }).annotate({ identifier: "V2ThreadUnarchiveResponse__MemoryCitationEntry" }); -export type V2ThreadUnarchiveResponse__MessagePhase = "commentary" | "final_answer"; +export type V2ThreadUnarchiveResponse__MessagePhase = + | "commentary" + | "partial_answer" + | "final_answer"; export const V2ThreadUnarchiveResponse__MessagePhase = Schema.Union( [ Schema.Literal("commentary").annotate({ description: "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", }), + Schema.Literal("partial_answer").annotate({ + description: "Stable answer text that may be followed by more assistant output or tools.", + }), Schema.Literal("final_answer").annotate({ description: "The assistant's terminal answer text for the current turn.", }), @@ -14785,13 +14863,19 @@ export const V2TurnCompletedNotification__MemoryCitationEntry = Schema.Struct({ path: Schema.String, }).annotate({ identifier: "V2TurnCompletedNotification__MemoryCitationEntry" }); -export type V2TurnCompletedNotification__MessagePhase = "commentary" | "final_answer"; +export type V2TurnCompletedNotification__MessagePhase = + | "commentary" + | "partial_answer" + | "final_answer"; export const V2TurnCompletedNotification__MessagePhase = Schema.Union( [ Schema.Literal("commentary").annotate({ description: "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", }), + Schema.Literal("partial_answer").annotate({ + description: "Stable answer text that may be followed by more assistant output or tools.", + }), Schema.Literal("final_answer").annotate({ description: "The assistant's terminal answer text for the current turn.", }), @@ -15200,13 +15284,19 @@ export const V2TurnStartedNotification__MemoryCitationEntry = Schema.Struct({ path: Schema.String, }).annotate({ identifier: "V2TurnStartedNotification__MemoryCitationEntry" }); -export type V2TurnStartedNotification__MessagePhase = "commentary" | "final_answer"; +export type V2TurnStartedNotification__MessagePhase = + | "commentary" + | "partial_answer" + | "final_answer"; export const V2TurnStartedNotification__MessagePhase = Schema.Union( [ Schema.Literal("commentary").annotate({ description: "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", }), + Schema.Literal("partial_answer").annotate({ + description: "Stable answer text that may be followed by more assistant output or tools.", + }), Schema.Literal("final_answer").annotate({ description: "The assistant's terminal answer text for the current turn.", }), @@ -15729,13 +15819,16 @@ export const V2TurnStartResponse__MemoryCitationEntry = Schema.Struct({ path: Schema.String, }).annotate({ identifier: "V2TurnStartResponse__MemoryCitationEntry" }); -export type V2TurnStartResponse__MessagePhase = "commentary" | "final_answer"; +export type V2TurnStartResponse__MessagePhase = "commentary" | "partial_answer" | "final_answer"; export const V2TurnStartResponse__MessagePhase = Schema.Union( [ Schema.Literal("commentary").annotate({ description: "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", }), + Schema.Literal("partial_answer").annotate({ + description: "Stable answer text that may be followed by more assistant output or tools.", + }), Schema.Literal("final_answer").annotate({ description: "The assistant's terminal answer text for the current turn.", }), diff --git a/packages/effect-codex-app-server/src/schema.test.ts b/packages/effect-codex-app-server/src/schema.test.ts index 2f6fefde0d606..dfbedf86af978 100644 --- a/packages/effect-codex-app-server/src/schema.test.ts +++ b/packages/effect-codex-app-server/src/schema.test.ts @@ -33,6 +33,52 @@ it("keeps async questions in live notifications and thread history", () => { } }); +it("keeps partial answers in notifications and persisted thread histories", () => { + const item = { + type: "agentMessage", + id: "partial-1", + text: "A stable answer before more tool work.", + phase: "partial_answer", + } as const; + for (const schema of [ + CodexSchema.ServerNotification__ThreadItem, + CodexSchema.V2ItemStartedNotification__ThreadItem, + CodexSchema.V2ItemCompletedNotification__ThreadItem, + CodexSchema.V2ThreadReadResponse__ThreadItem, + CodexSchema.V2ThreadResumeResponse__ThreadItem, + CodexSchema.V2ThreadForkResponse__ThreadItem, + CodexSchema.V2TurnCompletedNotification__ThreadItem, + ]) { + assert.deepEqual(Schema.decodeSync(schema)(item), item); + } + const response = { + approvalPolicy: "never", + approvalsReviewer: "user", + cwd: "/tmp/project", + model: "gpt-5.6-sol", + modelProvider: "openai", + sandbox: { type: "dangerFullAccess" }, + thread: { + cliVersion: "0.162.0", + createdAt: 0, + updatedAt: 0, + cwd: "/tmp/project", + ephemeral: false, + id: "thread-1", + modelProvider: "openai", + preview: "", + projectId: null, + sessionId: "session-1", + source: "cli", + status: { type: "idle" }, + turns: [{ id: "turn-1", status: "completed", items: [item] }], + }, + }; + assert.equal(isThreadForkResponse(response), true); + assert.equal(isThreadResumeResponse(response), true); + assert.equal(isThreadReadResponse({ thread: response.thread }), true); +}); + it("accepts Codex 0.150 multi-agent values", () => { const schemas = [ CodexSchema.ServerNotification__SubAgentActivityKind, From e92981dcf3f79c13aff01f975d68ea80bf4b2770 Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Fri, 30 Oct 2026 15:46:05 -0500 Subject: [PATCH 502/817] fix(server): list folders named with a backslash on Linux and macOS (#23398) Co-authored-by: Claude Opus 5.5 --- .../src/workspace/WorkspacePaths.test.ts | 22 +++++++++++++++++++ apps/server/src/workspace/WorkspacePaths.ts | 9 ++++---- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/apps/server/src/workspace/WorkspacePaths.test.ts b/apps/server/src/workspace/WorkspacePaths.test.ts index 574904b343563..b178c621453b8 100644 --- a/apps/server/src/workspace/WorkspacePaths.test.ts +++ b/apps/server/src/workspace/WorkspacePaths.test.ts @@ -5,6 +5,8 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; +import * as HostProcess from "@t3tools/shared/HostProcess"; + import * as WorkspacePaths from "./WorkspacePaths.ts"; const layerTest = Layer.empty.pipe( @@ -58,5 +60,25 @@ it.layer(layerTest)("WorkspacePathsLive", (it) => { ); }), ); + + // On Windows `\` is a separator, so these names cannot exist there. + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "keeps a backslash in a name as part of the name", + () => + Effect.gen(function* () { + const workspacePaths = yield* WorkspacePaths.WorkspacePaths; + const path = yield* Path.Path; + const cwd = yield* makeTempDir(); + + for (const relativePath of ["weird\\name.txt", "..\\..\\etc"]) { + expect( + yield* workspacePaths.resolveRelativePathWithinRoot({ + workspaceRoot: cwd, + relativePath, + }), + ).toEqual({ absolutePath: path.join(cwd, relativePath), relativePath }); + } + }), + ); }); }); diff --git a/apps/server/src/workspace/WorkspacePaths.ts b/apps/server/src/workspace/WorkspacePaths.ts index 6b748e19396ec..ea183ed43e1ab 100644 --- a/apps/server/src/workspace/WorkspacePaths.ts +++ b/apps/server/src/workspace/WorkspacePaths.ts @@ -103,10 +103,6 @@ export class WorkspacePaths extends Context.Service< } >()("t3/workspace/WorkspacePaths") {} -function toPosixRelativePath(input: string): string { - return input.replaceAll("\\", "/"); -} - const make = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -188,7 +184,10 @@ const make = Effect.gen(function* () { } const absolutePath = path.resolve(input.workspaceRoot, normalizedInputPath); - const relativeToRoot = toPosixRelativePath(path.relative(input.workspaceRoot, absolutePath)); + // Only the host separator becomes `/`: on POSIX `\` is a file name character. + const relativeToRoot = path + .relative(input.workspaceRoot, absolutePath) + .replaceAll(path.sep, "/"); if ( relativeToRoot.length === 0 || relativeToRoot === "." || From 14d56e18f94b73fc5a1cecf2078d8530ab1304ad Mon Sep 17 00:00:00 2001 From: Aditya Garud <153842990+yashranaway@users.noreply.github.com> Date: Sat, 31 Oct 2026 02:16:16 +0530 Subject: [PATCH 503/817] fix(server): preserve byte-order marks in Git diff contents (#23421) --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 21 ++++++++++++++++++++ apps/server/src/vcs/GitVcsDriverCore.ts | 4 ++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 3566a48fc4caf..c0f0967725e58 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -2536,6 +2536,27 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect.each([ + { scenario: "kept", before: "\uFEFFold\n", after: "\uFEFFnew\n" }, + { scenario: "added", before: "same\n", after: "\uFEFFsame\n" }, + { scenario: "removed", before: "\uFEFFsame\n", after: "same\n" }, + ])("preserves byte-order marks in diff expansion when $scenario", ({ before, after }) => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + yield* writeTextFile(cwd, "README.md", before); + yield* git(cwd, ["commit", "-am", "write original contents"]); + yield* writeTextFile(cwd, "README.md", after); + const driver = yield* GitVcsDriver.GitVcsDriver; + + const contents = yield* driver.getReviewDiffFileContents( + makeReviewDiffFileContentsInput(cwd), + ); + + assert.deepStrictEqual(contents, { oldContents: before, newContents: after }); + }), + ); + it.effect("reads a base ref that looks like an option as a revision", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 79086ab9e9fa1..421c240514e42 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -844,7 +844,7 @@ const collectOutput = Effect.fnUntraced(function* ( onLine: ((line: string) => Effect.Effect) | undefined, keepLineCallbacksAfterTruncation = false, ): Effect.fn.Return<{ readonly text: string; readonly truncated: boolean }, GitCommandError> { - const decoder = new TextDecoder(); + const decoder = new TextDecoder("utf-8", { ignoreBOM: true }); const lineDecoder = keepLineCallbacksAfterTruncation && onLine ? new TextDecoder() : null; let bytes = 0; let text = ""; @@ -3562,7 +3562,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* if (bytes.includes(0)) { return yield* fileError("fs.readFile", `Cannot expand binary file '${input.newPath}'.`); } - return new TextDecoder("utf-8").decode(bytes); + return new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes); }); const getReviewDiffFileContents = Effect.fn("getReviewDiffFileContents")(function* ( From c65e4883596e6ca06c71176006b1b7fb61995a2e Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Fri, 30 Oct 2026 15:46:32 -0500 Subject: [PATCH 504/817] fix(web): save settings fields only after an edit (#23427) Co-authored-by: GPT-6.1 Sol --- .../hooks/useCommitOnBlur.browser.test.tsx | 41 +++++++++++++++++++ apps/web/src/hooks/useCommitOnBlur.ts | 6 ++- 2 files changed, 45 insertions(+), 2 deletions(-) create mode 100644 apps/web/src/hooks/useCommitOnBlur.browser.test.tsx diff --git a/apps/web/src/hooks/useCommitOnBlur.browser.test.tsx b/apps/web/src/hooks/useCommitOnBlur.browser.test.tsx new file mode 100644 index 0000000000000..cec4f8cb8ea5b --- /dev/null +++ b/apps/web/src/hooks/useCommitOnBlur.browser.test.tsx @@ -0,0 +1,41 @@ +import { describe, expect, it } from "vite-plus/test"; +import { userEvent } from "vite-plus/test/browser"; + +import { render } from "../../test/render"; +import { DraftInput } from "../components/ui/draft-input"; + +describe("settings draft commits", () => { + it("preserves an external update when an untouched field loses focus", async () => { + let saved = "~/"; + const commit = (next: string) => { + saved = next; + }; + await using screen = await render(); + const input = screen.getByRole("textbox"); + await input.click(); + + saved = "/projects"; + await screen.rerender(); + await userEvent.tab(); + + expect(saved).toBe("/projects"); + }); + + it("preserves a saved edit when refocused before its server snapshot arrives", async () => { + let saved = "~/"; + const commit = (next: string) => { + saved = next; + }; + await using screen = await render(); + const input = screen.getByRole("textbox"); + await input.fill("/projects"); + await userEvent.tab(); + expect(saved).toBe("/projects"); + + await input.click(); + await screen.rerender(); + await userEvent.tab(); + + expect(saved).toBe("/projects"); + }); +}); diff --git a/apps/web/src/hooks/useCommitOnBlur.ts b/apps/web/src/hooks/useCommitOnBlur.ts index 6906402d718ab..022f79a2a58bb 100644 --- a/apps/web/src/hooks/useCommitOnBlur.ts +++ b/apps/web/src/hooks/useCommitOnBlur.ts @@ -1,7 +1,8 @@ -import { type ChangeEvent, type KeyboardEvent, useState } from "react"; +import { type ChangeEvent, type KeyboardEvent, useRef, useState } from "react"; export function useCommitOnBlur(value: string, onCommit: (next: string) => void) { const [draft, setDraft] = useState(null); + const valueOnFocus = useRef(value); return { value: draft ?? value, @@ -9,12 +10,13 @@ export function useCommitOnBlur(value: string, onCommit: (next: string) => void) setDraft(event.target.value); }, onFocus: () => { + valueOnFocus.current = value; setDraft(value); }, onBlur: () => { const next = draft ?? value; setDraft(null); - if (next !== value) { + if (next !== valueOnFocus.current && next !== value) { onCommit(next); } }, From 2b1e15c999aed3b8a06238b467d74f9cd9a1aeae Mon Sep 17 00:00:00 2001 From: Aditya Garud <153842990+yashranaway@users.noreply.github.com> Date: Sat, 31 Oct 2026 02:18:09 +0530 Subject: [PATCH 505/817] fix(shared): preserve hyphens in prerelease versions (#23430) Co-authored-by: maria-rcks --- packages/shared/src/semver.test.ts | 18 ++++++++++++++++++ packages/shared/src/semver.ts | 7 +++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/packages/shared/src/semver.test.ts b/packages/shared/src/semver.test.ts index f77926313dd72..a66e5b07d8bcc 100644 --- a/packages/shared/src/semver.test.ts +++ b/packages/shared/src/semver.test.ts @@ -35,6 +35,24 @@ describe("semver helpers", () => { expect(compareSemverVersions("2.1.111-beta.1", "2.1.111")).toBeLessThan(0); }); + it("preserves hyphens within prerelease identifiers", () => { + expect(normalizeSemverVersion("20-alpha-1")).toBe("20.0.0-alpha-1"); + expect(parseSemver("1.2.3-alpha-1.2")).toEqual({ + major: 1, + minor: 2, + patch: 3, + prerelease: ["alpha-1", "2"], + }); + expect(parseSemver("1.2.3-x-y-z.--")?.prerelease).toEqual(["x-y-z", "--"]); + }); + + it("distinguishes releases whose identifiers differ after a hyphen", () => { + expect(compareSemverVersions("1.2.3-alpha-1", "1.2.3-alpha-2")).toBeLessThan(0); + expect(compareSemverVersions("1.2.3-alpha-2", "1.2.3-alpha-1")).toBeGreaterThan(0); + expect(compareSemverVersions("1.2.3-alpha-1.2", "1.2.3-alpha-1.10")).toBeLessThan(0); + expect(compareSemverVersions("1.2.3-alpha.1+build-2", "1.2.3-alpha.1+build-3")).toBe(0); + }); + it("supports comparison comparators", () => { expect(satisfiesSemverRange("24.9.0", ">=24.0 <24.10")).toBe(true); expect(satisfiesSemverRange("24.10.0", ">=24.0 <24.10")).toBe(false); diff --git a/packages/shared/src/semver.ts b/packages/shared/src/semver.ts index 88ae4754f1809..8d1a354f008bc 100644 --- a/packages/shared/src/semver.ts +++ b/packages/shared/src/semver.ts @@ -8,7 +8,9 @@ interface ParsedSemver { const SEMVER_NUMBER_SEGMENT = /^\d+$/; export function normalizeSemverVersion(version: string): string { - const [main, prerelease] = version.trim().split("-", 2); + const [versionWithoutBuildMetadata = ""] = version.trim().split("+", 1); + const [main, ...prereleaseParts] = versionWithoutBuildMetadata.split("-"); + const prerelease = prereleaseParts.join("-"); const segments: string[] = []; for (const segment of (main ?? "").split(".")) { const trimmed = segment.trim(); @@ -26,7 +28,8 @@ export function normalizeSemverVersion(version: string): string { export function parseSemver(value: string): ParsedSemver | null { const normalized = normalizeSemverVersion(value).replace(/^v/, ""); - const [main = "", prerelease] = normalized.split("-", 2); + const [main = "", ...prereleaseParts] = normalized.split("-"); + const prerelease = prereleaseParts.join("-"); const segments = main.split("."); if (segments.length !== 3) { return null; From b0410a445397a695782e5ca27da8515e5f845d70 Mon Sep 17 00:00:00 2001 From: Aditya Garud <153842990+yashranaway@users.noreply.github.com> Date: Sat, 31 Oct 2026 02:18:25 +0530 Subject: [PATCH 506/817] fix(browser): serialize concurrent profile clears (#23434) --- .../src/preview/ServerBrowserContexts.test.ts | 23 +++++++++++++++++++ .../src/preview/ServerBrowserContexts.ts | 2 ++ 2 files changed, 25 insertions(+) diff --git a/apps/server/src/preview/ServerBrowserContexts.test.ts b/apps/server/src/preview/ServerBrowserContexts.test.ts index 3cab864de54f2..522df30fb66c8 100644 --- a/apps/server/src/preview/ServerBrowserContexts.test.ts +++ b/apps/server/src/preview/ServerBrowserContexts.test.ts @@ -183,6 +183,29 @@ describe("ServerBrowserContexts", () => { await pool.close(); }); + it("waits for the context to close when the same profile is cleared concurrently", async () => { + const human = makeContext(); + const closed = Promise.withResolvers(); + human.close.mockImplementation(async () => closed.promise); + launches.persistent.mockResolvedValue(human as unknown as BrowserContext); + const pool = new ServerBrowserContexts(options()); + await pool.contextFor("work/team"); + + const first = pool.clearProfile("work/team"); + const second = pool.clearProfile("work/team"); + const deletionsBeforeClose = launches.rm.mock.calls.length; + closed.resolve(); + await Promise.all([first, second]); + + expect(deletionsBeforeClose).toBe(0); + expect(human.close).toHaveBeenCalledTimes(1); + expect(launches.rm).toHaveBeenCalledExactlyOnceWith("/test/profiles/work%2Fteam", { + recursive: true, + force: true, + }); + await pool.close(); + }); + it("opens a profile requested during its clear only after the storage is deleted", async () => { launches.persistent.mockImplementation(async () => makeContext() as unknown as BrowserContext); const configuration = options(); diff --git a/apps/server/src/preview/ServerBrowserContexts.ts b/apps/server/src/preview/ServerBrowserContexts.ts index 9f3fd48430752..2a7c342d30d81 100644 --- a/apps/server/src/preview/ServerBrowserContexts.ts +++ b/apps/server/src/preview/ServerBrowserContexts.ts @@ -212,6 +212,8 @@ export class ServerBrowserContexts { async clearProfile(profileId: string) { if (profileId === INCOGNITO_BROWSER_PROFILE_ID) return; const key = JSON.stringify([profileId, null]); + const existing = this.clearing.get(key); + if (existing) return existing; const clearing = (async () => { const pending = this.contexts.get(key); if (pending) { From 3a537d2c916e61493e91fd104e3fc525116d980d Mon Sep 17 00:00:00 2001 From: Aditya Garud <153842990+yashranaway@users.noreply.github.com> Date: Sat, 31 Oct 2026 02:18:41 +0530 Subject: [PATCH 507/817] fix(diagnostics): include browser trace failures (#23438) --- .../src/diagnostics/TraceDiagnostics.test.ts | 29 +++++++++++++++++++ .../src/diagnostics/TraceDiagnostics.ts | 27 ++++++++--------- 2 files changed, 41 insertions(+), 15 deletions(-) diff --git a/apps/server/src/diagnostics/TraceDiagnostics.test.ts b/apps/server/src/diagnostics/TraceDiagnostics.test.ts index 97156800e3db9..35909007c395c 100644 --- a/apps/server/src/diagnostics/TraceDiagnostics.test.ts +++ b/apps/server/src/diagnostics/TraceDiagnostics.test.ts @@ -61,6 +61,35 @@ function readTraces(fileSystem: Partial) { } describe("TraceDiagnostics", () => { + it("includes browser failures and interruptions in diagnostics", () => { + const diagnostics = aggregateLines( + [ + { status: { code: "2", message: "Browser request failed" }, attributes: {} }, + { status: { code: "0" }, attributes: { "effect.fiber.interrupted": true } }, + { status: { code: "1", message: "Interrupted" }, attributes: {} }, + { status: { code: "1" }, attributes: {} }, + ].map((outcome, index) => + JSON.stringify({ + type: "otlp-span", + name: "browser.request", + traceId: `trace-${index}`, + spanId: `span-${index}`, + startTimeUnixNano: ns(index * 100), + endTimeUnixNano: ns(index * 100 + 10), + durationMs: 10, + ...outcome, + }), + ), + ); + + assert.equal(diagnostics.recordCount, 4); + assert.equal(diagnostics.failureCount, 1); + assert.equal(diagnostics.interruptionCount, 2); + assert.equal(diagnostics.topSpansByCount[0]?.failureCount, 1); + assert.equal(diagnostics.commonFailures[0]?.cause, "Browser request failed"); + assert.equal(diagnostics.latestFailures[0]?.cause, "Browser request failed"); + }); + it.effect("aggregates failures, slow spans, log levels, and parse errors", () => Effect.sync(() => { const diagnostics = aggregateLines([ diff --git a/apps/server/src/diagnostics/TraceDiagnostics.ts b/apps/server/src/diagnostics/TraceDiagnostics.ts index 0cd5ae9b3a750..6f25c424a7b83 100644 --- a/apps/server/src/diagnostics/TraceDiagnostics.ts +++ b/apps/server/src/diagnostics/TraceDiagnostics.ts @@ -18,17 +18,6 @@ import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; -interface TraceRecordLike { - readonly name?: unknown; - readonly traceId?: unknown; - readonly spanId?: unknown; - readonly startTimeUnixNano?: unknown; - readonly endTimeUnixNano?: unknown; - readonly durationMs?: unknown; - readonly exit?: unknown; - readonly events?: unknown; -} - interface TraceEventLike { readonly name?: unknown; readonly timeUnixNano?: unknown; @@ -85,7 +74,7 @@ export function toRotatedTracePaths( return [...backups, traceFilePath]; } -function isRecordObject(value: unknown): value is TraceRecordLike { +function isRecordObject(value: unknown): value is Readonly> { return typeof value === "object" && value !== null; } @@ -253,8 +242,13 @@ export function makeTraceDiagnosticsAggregator( lastSpanAt === null || DateTime.isGreaterThan(endedAt, lastSpanAt) ? endedAt : lastSpanAt; const exitTag = readExitTag(parsed.exit); - const isFailure = exitTag === "Failure"; - const isInterrupted = exitTag === "Interrupted"; + const status = isRecordObject(parsed.status) ? parsed.status : {}; + const attributes = isRecordObject(parsed.attributes) ? parsed.attributes : {}; + const isFailure = exitTag === "Failure" || status.code === "2"; + const isInterrupted = + exitTag === "Interrupted" || + attributes["effect.fiber.interrupted"] === true || + status.message === "Interrupted"; if (isFailure) failureCount += 1; if (isInterrupted) interruptionCount += 1; @@ -277,7 +271,10 @@ export function makeTraceDiagnosticsAggregator( insertBounded(slowestSpans, spanItem, TOP_LIMIT, slowestFirst); if (isFailure) { - const cause = readExitCause(parsed.exit); + const cause = + exitTag === "Failure" + ? readExitCause(parsed.exit) + : (toStringValue(status.message)?.trim() ?? "Failure"); insertBounded(latestFailures, { ...spanItem, cause }, RECENT_LIMIT, latestEndedFirst); const failureKey = `${name}\0${cause}`; From 9522c7dd8f7050db198ee758e66bc62a146db1e5 Mon Sep 17 00:00:00 2001 From: Aditya Garud <153842990+yashranaway@users.noreply.github.com> Date: Sat, 31 Oct 2026 02:18:57 +0530 Subject: [PATCH 508/817] fix(acp): forward empty plan replacements (#23440) --- .../src/server/runtimeModel.test.ts | 29 +++++++++++++++++++ .../provider-acp/src/server/runtimeModel.ts | 20 ++++++------- 2 files changed, 38 insertions(+), 11 deletions(-) diff --git a/packages/provider-acp/src/server/runtimeModel.test.ts b/packages/provider-acp/src/server/runtimeModel.test.ts index e60671c775d51..45063ffc325dd 100644 --- a/packages/provider-acp/src/server/runtimeModel.test.ts +++ b/packages/provider-acp/src/server/runtimeModel.test.ts @@ -329,6 +329,35 @@ describe("AcpRuntimeModel", () => { ).toBe(true); }); + it("forwards an empty ACP v1 plan to clear previous entries", () => { + const entries = [ + [{ content: "Inspect state", priority: "high", status: "pending" }], + [], + ] as const; + const updates = entries.flatMap( + (plan) => + parseSessionUpdateEvent({ + sessionId: "session-1", + update: { sessionUpdate: "plan", entries: plan }, + }).events, + ); + + expect(updates).toMatchObject([ + { + _tag: "PlanUpdated", + payload: { + nativePlanId: "legacy", + kind: "items", + plan: [{ step: "Inspect state", status: "pending" }], + }, + }, + { + _tag: "PlanUpdated", + payload: { nativePlanId: "legacy", kind: "items", plan: [] }, + }, + ]); + }); + it("projects typed ACP plan and content updates", () => { const planResult = parseSessionUpdateEvent({ sessionId: "session-1", diff --git a/packages/provider-acp/src/server/runtimeModel.ts b/packages/provider-acp/src/server/runtimeModel.ts index 43fa2bf758e2f..ca6ed15db80d1 100644 --- a/packages/provider-acp/src/server/runtimeModel.ts +++ b/packages/provider-acp/src/server/runtimeModel.ts @@ -1392,17 +1392,15 @@ export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotificat step: entry.content.trim().length > 0 ? entry.content.trim() : `Step ${index + 1}`, status: normalizePlanStepStatus(entry.status), })); - if (plan.length > 0) { - events.push({ - _tag: "PlanUpdated", - payload: { - nativePlanId: "legacy", - kind: "items", - plan, - }, - rawPayload: params, - }); - } + events.push({ + _tag: "PlanUpdated", + payload: { + nativePlanId: "legacy", + kind: "items", + plan, + }, + rawPayload: params, + }); break; } case "plan_update": { From b665f0b11c351935bea5aa633416f9a32c9c6b08 Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Fri, 30 Oct 2026 15:49:13 -0500 Subject: [PATCH 509/817] fix(web): recognize plain text aliases in code fences (#23446) Co-authored-by: GPT-6.1 Sol --- apps/web/src/composer-code-languages.test.ts | 11 +++++++++++ apps/web/src/composer-code-languages.ts | 5 ++++- 2 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 apps/web/src/composer-code-languages.test.ts diff --git a/apps/web/src/composer-code-languages.test.ts b/apps/web/src/composer-code-languages.test.ts new file mode 100644 index 0000000000000..0e8c3f0188f91 --- /dev/null +++ b/apps/web/src/composer-code-languages.test.ts @@ -0,0 +1,11 @@ +import { expect, it } from "vite-plus/test"; + +import { codeLanguageEntry, languageOfInfoString } from "./composer-code-languages"; + +it("recognizes plain-text fence info strings without treating metadata as the language", () => { + const entries = ["Text", "TEXT", "plaintext", "txt"].map((language) => + codeLanguageEntry(languageOfInfoString(` ${language} title=notes.txt`)), + ); + + expect(entries).toEqual(Array.from({ length: 4 }, () => ({ id: "", label: "Plain text" }))); +}); diff --git a/apps/web/src/composer-code-languages.ts b/apps/web/src/composer-code-languages.ts index 42558162d9fde..641b75b6926df 100644 --- a/apps/web/src/composer-code-languages.ts +++ b/apps/web/src/composer-code-languages.ts @@ -47,12 +47,15 @@ const LANGUAGE_ALIASES: Record = { "c++": "cpp", js: "javascript", md: "markdown", + plaintext: "", py: "python", rb: "ruby", rs: "rust", sh: "bash", shell: "bash", + text: "", ts: "typescript", + txt: "", yml: "yaml", }; @@ -69,7 +72,7 @@ export function withInfoStringLanguage(info: string, language: string): string { } export function codeLanguageEntry(language: string): CodeBlockLanguage | null { - const id = language === "text" ? "" : (LANGUAGE_ALIASES[language.toLowerCase()] ?? language); + const id = LANGUAGE_ALIASES[language.toLowerCase()] ?? language; return CODE_BLOCK_LANGUAGES.find((entry) => entry.id === id.toLowerCase()) ?? null; } From 42ca5d560d053831e5c26ea826291d56ab94052c Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Fri, 30 Oct 2026 15:49:30 -0500 Subject: [PATCH 510/817] fix(web): keep deleted clipboard attachments out of the draft (#23447) Co-authored-by: GPT-6.1 Sol Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks Co-authored-by: maria-rcks <254055478+maria-rcks@users.noreply.github.com> --- apps/web/src/components/chat/ChatComposer.tsx | 1 + .../useComposerContextImport.browser.test.tsx | 188 ++++++++++++++++++ .../chat/useComposerContextImport.ts | 17 ++ 3 files changed, 206 insertions(+) create mode 100644 apps/web/src/components/chat/useComposerContextImport.browser.test.tsx diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index ae0bb19336e0e..e08e74a49063b 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -1356,6 +1356,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) composerContextRecords, composerImages, composerFilesRef, + promptRef, pendingThreadImportsRef, addComposerFilesToDraft, }); diff --git a/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx new file mode 100644 index 0000000000000..a050b0f51edf0 --- /dev/null +++ b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx @@ -0,0 +1,188 @@ +import { useEffect } from "react"; +import { type ComposerContextRecord, ComposerContextId, EnvironmentId } from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; + +import { act, render, stubGlobal } from "../../../test/render"; +import { DraftId, useComposerDraftStore } from "../../composerDraftStore"; +import { formatInlineContextReference } from "../../lib/composerContextReferences"; +import { rememberCopiedComposerAttachments } from "../../lib/copiedComposerAttachments"; +import { pendingDraftWork } from "./pendingDraftWork"; +import { useComposerContextImport } from "./useComposerContextImport"; + +vi.mock("~/state/use-atom-query-runner", async (importOriginal) => ({ + ...(await importOriginal()), + useAtomQueryRunner: () => async () => ({ _tag: "Success", value: { relativeUrl: "/file" } }), +})); +vi.mock("../../state/use-atom-command", async (importOriginal) => ({ + ...(await importOriginal()), + useAtomCommand: () => () => {}, +})); +vi.mock("~/state/session", async (importOriginal) => ({ + ...(await importOriginal()), + readPreparedConnection: () => ({ httpBaseUrl: "http://localhost" }), +})); + +type ImportInput = Parameters[0]; +type Importer = ReturnType; + +function Harness({ input, ready }: { input: ImportInput; ready: (value: Importer) => void }) { + const importer = useComposerContextImport(input); + useEffect(() => ready(importer)); + return null; +} + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((fulfill) => { + resolve = fulfill; + }); + return { promise, resolve }; +} + +it.each([ + { kind: "file", edit: "delete" }, + { kind: "image", edit: "delete" }, + { kind: "file", edit: "undo" }, + { kind: "file", edit: "retain" }, + { kind: "file", edit: "switch" }, + { kind: "file", edit: "cached" }, + { kind: "file", edit: "question" }, + { kind: "image", edit: "question" }, + { kind: "image", edit: "annotation" }, + { kind: "image", edit: "delete-annotation" }, +] as const)("settles a delayed $kind import after $edit", async ({ kind, edit }) => { + const target = DraftId.make(`clipboard-${kind}-${edit}`); + const store = useComposerDraftStore.getState(); + using _draft = { [Symbol.dispose]: () => store.clearComposerContent(target) }; + const sourceEnvironmentId = EnvironmentId.make("clipboard-source"); + rememberCopiedComposerAttachments( + sourceEnvironmentId, + edit === "cached" + ? new Map([["source-attachment", new File(["notes"], "notes.txt")]]) + : new Map(), + ); + using _copy = { + [Symbol.dispose]: () => rememberCopiedComposerAttachments(sourceEnvironmentId, new Map()), + }; + const promptRef = { current: "" }; + const downloaded = deferred(); + const requested = deferred(); + const settled = deferred(); + const input = { + environmentId: EnvironmentId.make("clipboard-target"), + linkedEnvironments: new Map(), + activeThread: undefined, + activeThreadId: null, + composerDraftTarget: target, + attachmentDraftTarget: target, + attachmentTargetKey: target, + attachmentTargetKeyRef: { current: target }, + questionAttachmentTarget: edit === "question" ? target : null, + pendingUserInputs: [], + composerContextRecords: new Map(), + composerImages: [], + composerFilesRef: { current: [] }, + pendingThreadImportsRef: { current: new Map() }, + promptRef, + addComposerFilesToDraft: (files: Parameters[1]) => + store.addFiles(target, files, { appendReference: edit !== "question" }), + } satisfies ImportInput & { promptRef: { current: string } }; + let importer!: Importer; + await using _screen = await render( + { + importer = value; + }} + />, + ); + const end = pendingDraftWork.end.bind(pendingDraftWork); + using _settled = vi.spyOn(pendingDraftWork, "end").mockImplementation((key) => { + end(key); + settled.resolve(); + }); + using _fetch = stubGlobal("fetch", () => { + requested.resolve(); + return downloaded.promise; + }); + const contextId = ComposerContextId.make(`${kind}_source`); + const attachmentFields = { + version: 1 as const, + contextId, + label: "notes.txt", + attachmentId: "source-attachment", + name: "notes.txt", + mimeType: kind === "file" ? "text/plain" : "image/png", + sizeBytes: 5, + }; + const attachment = ( + kind === "file" + ? { ...attachmentFields, kind: "file" as const } + : { ...attachmentFields, kind: "image" as const } + ) satisfies ComposerContextRecord; + const annotation = { + version: 1, + kind: "preview-annotation", + contextId: ComposerContextId.make("preview-annotation_source"), + label: "Page annotation", + annotationId: "source", + pageUrl: "http://localhost/page", + pageTitle: "Page", + comment: "Check this", + targetSummary: "Page", + styleChanges: [], + screenshotContextId: contextId, + } satisfies ComposerContextRecord; + const annotated = edit === "annotation" || edit === "delete-annotation"; + let pastedPrompt = ""; + await act(async () => { + const remapped = importer.importContextRecords( + annotated ? [attachment, annotation] : [attachment], + sourceEnvironmentId, + ); + pastedPrompt = formatInlineContextReference({ + kind: annotated ? "preview-annotation" : kind, + contextId: remapped.get(annotated ? annotation.contextId : contextId)!, + label: annotated ? "Page annotation" : "notes.txt", + }); + if (edit === "question") pastedPrompt = "Question answer"; + promptRef.current = pastedPrompt; + store.setPrompt(target, pastedPrompt); + if (edit !== "cached") await requested.promise; + }); + if (edit !== "cached") expect(pendingDraftWork.has(target)).toBe(true); + await act(() => { + if ( + edit !== "annotation" && + edit !== "retain" && + edit !== "cached" && + edit !== "question" && + edit !== "switch" + ) { + promptRef.current = "Keep this edit"; + store.setPrompt(target, promptRef.current); + } + if (edit === "undo") { + promptRef.current = pastedPrompt; + store.setPrompt(target, pastedPrompt); + } + if (edit === "switch") input.attachmentTargetKeyRef.current = DraftId.make("other-draft"); + }); + await act(async () => { + downloaded.resolve(new Response("notes", { headers: { "Content-Type": attachment.mimeType } })); + await settled.promise; + }); + expect(pendingDraftWork.has(target)).toBe(false); + const draft = store.getComposerDraft(target)!; + expect(draft.prompt).toBe(promptRef.current); + const attachments = kind === "file" ? draft.files : draft.images; + expect(attachments.map((file) => file.name)).toEqual( + edit === "undo" || + edit === "retain" || + edit === "annotation" || + edit === "cached" || + edit === "question" + ? ["notes.txt"] + : [], + ); +}); diff --git a/apps/web/src/components/chat/useComposerContextImport.ts b/apps/web/src/components/chat/useComposerContextImport.ts index e859e816074e6..74e97a5076d7d 100644 --- a/apps/web/src/components/chat/useComposerContextImport.ts +++ b/apps/web/src/components/chat/useComposerContextImport.ts @@ -39,6 +39,7 @@ import { import { assetEnvironment } from "~/state/assets"; import { copiedComposerAttachmentFile } from "~/lib/copiedComposerAttachments"; import { countQuestionAttachments, questionAttachmentDraftId } from "../../questionAttachments"; +import { collectInlineContextIds } from "../../lib/composerContextReferences"; import { elementContextToPreviewAnnotation } from "../../lib/elementContext"; import { orchestrationEnvironment } from "~/state/orchestration"; import { pendingDraftWork } from "./pendingDraftWork"; @@ -87,6 +88,7 @@ export function useComposerContextImport(input: { readonly composerContextRecords: ComposerDraftContextRecords; readonly composerImages: ReadonlyArray; readonly composerFilesRef: ChatComposerProps["composerFilesRef"]; + readonly promptRef: RefObject; readonly pendingThreadImportsRef: RefObject>; readonly addComposerFilesToDraft: (files: ComposerFileAttachment[]) => string[]; }) { @@ -104,6 +106,7 @@ export function useComposerContextImport(input: { composerContextRecords, composerImages, composerFilesRef, + promptRef, pendingThreadImportsRef, addComposerFilesToDraft, } = input; @@ -191,6 +194,20 @@ export function useComposerContextImport(input: { fail("Downloading it from the source failed."); return; } + // Question attachments have no inline reference; annotations can own their screenshots. + const references = new Set(collectInlineContextIds(promptRef.current)); + if ( + !questionAttachmentTarget && + !references.has(toKindScopedComposerContextId(record.kind, localId)) && + !( + record.kind === "image" && + references.has(previewAnnotationContextId(localId)) && + getComposerDraft(composerDraftTarget)?.previewAnnotations.some( + (annotation) => annotation.id === localId, + ) + ) + ) + return; file = new File([blob], record.name, { type: record.mimeType || blob.type }); } // The draft these bytes belong to may have been sent or switched away from while they From c40b32a729dcf21eb14aa9dcb140bf978303f9b1 Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Fri, 30 Oct 2026 15:49:45 -0500 Subject: [PATCH 511/817] fix(web): keep ACP agent logos in multi-model selections (#23448) Co-authored-by: GPT-6.1 Sol --- .../chat/ProviderModelPicker.browser.test.tsx | 90 +++++++++++++++++++ .../components/chat/ProviderModelPicker.tsx | 2 + 2 files changed, 92 insertions(+) create mode 100644 apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx diff --git a/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx b/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx new file mode 100644 index 0000000000000..72c9cdf39f23d --- /dev/null +++ b/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx @@ -0,0 +1,90 @@ +import { ProviderDriverKind, ProviderInstanceId, type ModelSelection } from "@t3tools/contracts"; +import { useState } from "react"; +import { expect, it, vi } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; + +import "~/index.css"; + +import { render } from "../../../test/render"; +import { deriveProviderInstanceEntries } from "../../providerInstances"; +import { ProviderModelPicker } from "./ProviderModelPicker"; + +it("keeps each registry image when adding a model from another ACP agent", async () => { + const icons = [ + "https://cdn.agentclientprotocol.com/registry/icons/picker-explicit.svg", + "https://cdn.agentclientprotocol.com/registry/v1/latest/picker-by-id.svg", + ]; + const cache = await caches.open("t3-acp-registry-icons-v1"); + await using _cachedIcons = { + async [Symbol.asyncDispose]() { + await Promise.all(icons.map((url) => cache.delete(url))); + }, + }; + for (const [index, url] of icons.entries()) { + await cache.put( + url, + new Response( + ``, + { headers: { "content-type": "image/svg+xml" } }, + ), + ); + } + const entries = deriveProviderInstanceEntries( + ["First", "Second"].map((name) => ({ + instanceId: ProviderInstanceId.make(name.toLowerCase()), + driver: ProviderDriverKind.make("acpRegistry"), + displayName: `${name} agent`, + enabled: true, + installed: true, + version: null, + status: "ready" as const, + auth: { status: "authenticated" as const }, + checkedAt: "2026-01-01T00:00:00.000Z", + models: [ + { slug: name.toLowerCase(), name: `${name} model`, isCustom: false, capabilities: {} }, + ], + slashCommands: [], + skills: [], + })), + ).map((entry, index) => ({ + ...entry, + ...(index === 0 ? { acpRegistryIconUrl: icons[0] } : { acpRegistryAgentId: "picker-by-id" }), + })); + const first = { instanceId: entries[0]!.instanceId, model: "first" }; + const options = new Map(entries.map((entry) => [entry.instanceId, entry.models])); + + function Picker() { + const [selection, setSelection] = useState>([first]); + return ( + 1 ? { selectedModels: selection } : {})} + lockedProvider={null} + instanceEntries={entries} + modelOptionsByInstance={options} + onToggleModel={(instanceId, model) => setSelection([...selection, { instanceId, model }])} + onInstanceModelChange={(instanceId, model) => setSelection([{ instanceId, model }])} + /> + ); + } + + await using screen = await render(); + const imageWidths = () => + Array.from( + screen.container.querySelectorAll("[data-chat-provider-model-picker] img"), + (image) => image.naturalWidth, + ); + await vi.waitFor(() => expect(imageWidths()).toEqual([11])); + await screen.getByRole("button", { name: "First model", exact: true }).click(); + await page.getByRole("button", { name: "Second agent", exact: true }).click(); + await userEvent.keyboard("{Shift>}"); + try { + await page.getByRole("option", { name: /Second model/ }).click(); + } finally { + await userEvent.keyboard("{/Shift}"); + } + await userEvent.keyboard("{Escape}"); + await vi.waitFor(() => expect(imageWidths()).toEqual([11, 17])); +}); diff --git a/apps/web/src/components/chat/ProviderModelPicker.tsx b/apps/web/src/components/chat/ProviderModelPicker.tsx index 83e028a9bbcd2..1551ac881e73f 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.tsx @@ -221,6 +221,8 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { driverKind={selection.entry.driverKind} displayName={selection.entry.displayName} accentColor={selection.entry.accentColor} + acpRegistryAgentId={selection.entry.acpRegistryAgentId} + acpRegistryIconUrl={selection.entry.acpRegistryIconUrl} className="size-4 rounded-full bg-(--chat-composer-glass-surface,var(--background)) ring-2 ring-(--chat-composer-glass-surface,var(--background))" iconClassName="size-4" /> From 6ad082745a5d19e8e5363e537b09d591e2cd0cbe Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Fri, 30 Oct 2026 15:50:00 -0500 Subject: [PATCH 512/817] fix(web): name inherited background activity profiles (#23450) Co-authored-by: GPT-6.1 Sol --- .../settings/SettingInheritance.test.ts | 25 +++++++++++++++++++ .../settings/SettingInheritance.tsx | 10 ++++++++ 2 files changed, 35 insertions(+) diff --git a/apps/web/src/components/settings/SettingInheritance.test.ts b/apps/web/src/components/settings/SettingInheritance.test.ts index e02bb6b3d35ec..527a1cdbbf58f 100644 --- a/apps/web/src/components/settings/SettingInheritance.test.ts +++ b/apps/web/src/components/settings/SettingInheritance.test.ts @@ -8,6 +8,31 @@ const environmentId = EnvironmentId.make("laptop"); const projectId = ProjectId.make("project"); describe("settingInheritanceLayers", () => { + it("identifies the background activity profile supplied by each layer", () => { + const settings = { + ...DEFAULT_SERVER_SETTINGS, + backgroundActivity: { + schemaVersion: 1 as const, + profile: "performance" as const, + overrides: {}, + }, + }; + const layers = settingInheritanceLayers( + { + environmentId, + label: "Laptop", + projectId: null, + ...resolveProjectSettings(settings, projectId), + }, + settings, + "backgroundActivity", + ); + expect(layers.map((layer) => [layer.key, layer.value, layer.effective])).toEqual([ + ["environment", "Performance", true], + ["built-in", "Balanced", false], + ]); + }); + it("shows the checkout's t3.json as a layer for file-backed keys", () => { const file = { defaultThreadEnvMode: "worktree" as const }; const fromFile = settingInheritanceLayers( diff --git a/apps/web/src/components/settings/SettingInheritance.tsx b/apps/web/src/components/settings/SettingInheritance.tsx index 692f254df1fad..051017a95894e 100644 --- a/apps/web/src/components/settings/SettingInheritance.tsx +++ b/apps/web/src/components/settings/SettingInheritance.tsx @@ -37,6 +37,13 @@ const WRITING_STYLE_LABELS: Record = { custom: "Custom instructions", }; +const BACKGROUND_ACTIVITY_PROFILE_LABELS: Record = { + balanced: "Balanced", + performance: "Performance", + "battery-saver": "Battery saver", + custom: "Advanced", +}; + function formatValue(key: keyof ServerSettings, value: unknown): string { if (value === null || value === undefined) { return key === "pullRequestMergeMethod" @@ -75,6 +82,9 @@ function formatValue(key: keyof ServerSettings, value: unknown): string { } if (Array.isArray(value)) return `${value.length} ${value.length === 1 ? "item" : "items"}`; if (typeof value === "object") { + if (key === "backgroundActivity" && "profile" in value && typeof value.profile === "string") { + return BACKGROUND_ACTIVITY_PROFILE_LABELS[value.profile] ?? value.profile; + } if ("model" in value && typeof value.model === "string") return value.model; if ("mode" in value && typeof value.mode === "string") { return WRITING_STYLE_LABELS[value.mode] ?? value.mode; From f8768d68b6e27b05b9a8cf4582002db2e4d12a8f Mon Sep 17 00:00:00 2001 From: Alex Date: Fri, 30 Oct 2026 13:50:17 -0700 Subject: [PATCH 513/817] fix(mobile): use the Android sheet header for Add environment (#23452) Co-authored-by: maria-rcks --- apps/mobile/src/Stack.tsx | 1 + .../settings/components/SettingsScreen.tsx | 31 +++++++++++++------ 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index 7a0042903a3c3..872ca142c8aaa 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -1006,6 +1006,7 @@ const RootStackConfig = createWorkspaceStackNavigator({ ...HORIZONTAL_FORM_SHEET_OPTIONS, sheetAllowedDetents: [0.55, 0.7], sheetGrabberVisible: true, + sheetCornerRadius: Platform.OS === "android" ? 28 : undefined, }, }), NotFound: createNativeStackScreen({ diff --git a/apps/mobile/src/features/settings/components/SettingsScreen.tsx b/apps/mobile/src/features/settings/components/SettingsScreen.tsx index 05b267242d41c..b61a57c8b7536 100644 --- a/apps/mobile/src/features/settings/components/SettingsScreen.tsx +++ b/apps/mobile/src/features/settings/components/SettingsScreen.tsx @@ -2,6 +2,7 @@ import { useNavigation, useRoute } from "@react-navigation/native"; import type { ReactNode } from "react"; import { Platform, View } from "react-native"; +import { AndroidSheetHeader } from "../../../components/ui/AndroidScreenHeader"; import type { AppBarProps } from "../../../components/ui/AppBar.types"; import { AppBar } from "../../../components/ui/AppBar"; import { ScreenContent as SettingsScreenContent } from "../../../components/ui/ScreenContent"; @@ -43,18 +44,28 @@ export function SettingsScreen( return ( - navigation.goBack()} - hideBottomBorder={!props.formSheet} - /> + {Platform.OS === "android" && props.formSheet ? ( + navigation.goBack()} + hideBottomBorder + /> + ) : ( + navigation.goBack()} + hideBottomBorder={!props.formSheet} + /> + )} - {props.formSheet ? ( + {props.formSheet && Platform.OS !== "android" ? ( props.children ) : ( Date: Fri, 30 Oct 2026 15:50:33 -0500 Subject: [PATCH 514/817] fix(desktop): oversized preview events no longer take down the app (#23461) Co-authored-by: GPT-6.1 Sol Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks --- apps/desktop/src/preview/CdpRelay.test.ts | 82 +++++++++++++++---- apps/desktop/src/preview/CdpRelay.ts | 48 ++++++++++- .../src/preview/DesktopBrowserHost.test.ts | 71 +++++++++++++++- .../desktop/src/preview/DesktopBrowserHost.ts | 20 ++++- 4 files changed, 201 insertions(+), 20 deletions(-) diff --git a/apps/desktop/src/preview/CdpRelay.test.ts b/apps/desktop/src/preview/CdpRelay.test.ts index 1c1f9dc078ca0..a2589edf8f7b2 100644 --- a/apps/desktop/src/preview/CdpRelay.test.ts +++ b/apps/desktop/src/preview/CdpRelay.test.ts @@ -14,6 +14,9 @@ const makeTarget = ( setDownloadDirectory, }); +const makeRelay = (target: CdpRelayTarget, write: (raw: string) => void) => + createCdpRelayConnection(target, write, () => {}); + // Each relay reply resolves after a few microtasks; one macrotask lets them all land. // oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- a zero-delay macrotask boundary, not a wait for time const settle = () => new Promise((resolve) => setImmediate(resolve)); @@ -21,9 +24,7 @@ const settle = () => new Promise((resolve) => setImmediate(resolve)); describe("CDP relay", () => { it("announces only the tab's page, under its real target id", async () => { const written: Array> = []; - const relay = createCdpRelayConnection(makeTarget(vi.fn()), (raw) => - written.push(JSON.parse(raw)), - ); + const relay = makeRelay(makeTarget(vi.fn()), (raw) => written.push(JSON.parse(raw))); relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} })); relay.receive(JSON.stringify({ id: 2, method: "Target.createTarget", params: {} })); await settle(); @@ -51,9 +52,7 @@ describe("CDP relay", () => { new Promise((resolve) => pending.push(() => resolve({ method }))), ); const written: Array> = []; - const relay = createCdpRelayConnection(makeTarget(send), (raw) => - written.push(JSON.parse(raw)), - ); + const relay = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw))); relay.receive( JSON.stringify({ id: 5, method: "Page.captureScreenshot", sessionId: "t3-preview-page" }), ); @@ -76,7 +75,7 @@ describe("CDP relay", () => { it("resumes paused child frames, so cross-site iframes run", async () => { const send = vi.fn(async () => ({})); - const relay = createCdpRelayConnection(makeTarget(send), () => {}); + const relay = makeRelay(makeTarget(send), () => {}); relay.receive( JSON.stringify({ id: 1, @@ -102,9 +101,7 @@ describe("CDP relay", () => { it("acknowledges Playwright's focus emulation without forcing it onto the guest", async () => { const send = vi.fn(async () => ({})); const written: Array> = []; - const relay = createCdpRelayConnection(makeTarget(send), (raw) => - written.push(JSON.parse(raw)), - ); + const relay = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw))); relay.receive( JSON.stringify({ id: 1, @@ -120,9 +117,7 @@ describe("CDP relay", () => { it("routes tab events to the page session once the page is announced", async () => { const written: Array> = []; - const relay = createCdpRelayConnection(makeTarget(vi.fn()), (raw) => - written.push(JSON.parse(raw)), - ); + const relay = makeRelay(makeTarget(vi.fn()), (raw) => written.push(JSON.parse(raw))); relay.event("Page.loadEventFired", {}, undefined); expect(written).toEqual([]); relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} })); @@ -140,9 +135,7 @@ describe("CDP relay extra sessions", () => { it("gives a second page session the page's commands and events", async () => { const send = vi.fn(async () => ({})); const written: Array> = []; - const relay = createCdpRelayConnection(makeTarget(send), (raw) => - written.push(JSON.parse(raw)), - ); + const relay = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw))); relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} })); relay.receive(JSON.stringify({ id: 2, method: "Target.attachToBrowserTarget" })); await settle(); @@ -182,7 +175,7 @@ describe("CDP relay downloads", () => { const send = vi.fn(async () => ({})); const directories: Array = []; const written: Array> = []; - const relay = createCdpRelayConnection( + const relay = makeRelay( makeTarget(send, (directory) => directories.push(directory)), (raw) => written.push(JSON.parse(raw)), ); @@ -213,3 +206,58 @@ describe("CDP relay downloads", () => { ]); }); }); + +describe("CDP relay payload budget", () => { + // 2,048 references to one 40 KiB string: about 80 MiB once serialized, little memory here. + const oversized = Array(2048).fill("x".repeat(40 * 1024)); + + it("fails only an oversized reply and still returns a large screenshot", async () => { + const screenshot = "A".repeat(16 * 1024 * 1024); + const send = vi.fn(async (method: string) => + method === "DOM.getDocument" ? { nodes: oversized } : { data: screenshot }, + ); + const written: Array> = []; + const relay = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw))); + relay.receive( + JSON.stringify({ id: 1, method: "DOM.getDocument", sessionId: "t3-preview-page" }), + ); + relay.receive( + JSON.stringify({ id: 2, method: "Page.captureScreenshot", sessionId: "t3-preview-page" }), + ); + await settle(); + + const replies = written.map(({ id, error, result }) => ({ + id, + error, + size: (result as { data?: string } | undefined)?.data?.length, + })); + expect(replies).toEqual([ + { id: 1, error: { code: -32000, message: "CDP payload too large" }, size: undefined }, + { id: 2, error: undefined, size: screenshot.length }, + ]); + }); + + it.each([ + { args: oversized }, + { args: "\u0001".repeat(12 * 1024 * 1024) }, + { args: Array(2_700_000).fill(-0.0000010000000000000002) }, + ])("closes instead of dropping an oversized event (%#)", async ({ args }) => { + const written: Array> = []; + const close = vi.fn(); + const relay = createCdpRelayConnection( + makeTarget(vi.fn()), + (raw) => written.push(JSON.parse(raw)), + close, + ); + relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} })); + await settle(); + written.length = 0; + + relay.event("Runtime.consoleAPICalled", { args }, ""); + relay.event("Page.loadEventFired", { timestamp: 1 }, ""); + + relay.receive(JSON.stringify({ id: 2, method: "Target.setAutoAttach" })); + expect(close).toHaveBeenCalledOnce(); + expect(written.map((message) => message["method"])).toEqual([]); + }); +}); diff --git a/apps/desktop/src/preview/CdpRelay.ts b/apps/desktop/src/preview/CdpRelay.ts index 948bc361f5d92..d52b0a3b2ab55 100644 --- a/apps/desktop/src/preview/CdpRelay.ts +++ b/apps/desktop/src/preview/CdpRelay.ts @@ -36,6 +36,29 @@ const isCommand = (value: unknown): value is CdpCommand => typeof (value as { id?: unknown }).id === "number" && typeof (value as { method?: unknown }).method === "string"; +// CDP values are plain JSON data, so their serialized size can be bounded before +// JSON.stringify allocates it. A string counts at its length unless it holds a +// character JSON may escape, which can take six code units. +const MAX_CDP_PAYLOAD_SIZE = 64 * 1024 * 1024; +const MAY_ESCAPE = /[^\x20\x21\x23-\x5b\x5d-\ud7ff\ue000-\uffff]/; +const serializedSize = (text: string) => + (MAY_ESCAPE.test(text) ? text.length * 6 : text.length) + 3; + +const fitsPayloadBudget = (message: unknown) => { + let remaining = MAX_CDP_PAYLOAD_SIZE; + const visit = (value: unknown): boolean => { + remaining -= typeof value === "string" ? serializedSize(value) : 26; + if (remaining < 0) return false; + if (typeof value !== "object" || value === null) return true; + if (Array.isArray(value)) return value.every(visit); + return Object.entries(value).every(([key, item]) => { + remaining -= serializedSize(key); + return visit(item); + }); + }; + return visit(message); +}; + const BROWSER_CONTEXT_ID = "t3-preview"; const ANNOUNCE = Symbol("announce"); const PAGE_SESSION_ID = "t3-preview-page"; @@ -50,8 +73,30 @@ const ACKNOWLEDGED = new Set([ export function createCdpRelayConnection( target: CdpRelayTarget, write: (message: string) => void, + close: () => void, ): CdpRelayConnection { - const send = (message: Record) => write(JSON.stringify(message)); + let closed = false; + const send = (message: Record) => { + if (closed) return; + if (fitsPayloadBudget(message)) { + write(JSON.stringify(message)); + return; + } + // An error reply fails only that command. A dropped event would leave + // Playwright out of step with the page, so the relay closes instead. + if (typeof message["id"] === "number") { + write( + JSON.stringify({ + id: message["id"], + error: { code: -32000, message: "CDP payload too large" }, + ...(message["sessionId"] === undefined ? {} : { sessionId: message["sessionId"] }), + }), + ); + return; + } + closed = true; + close(); + }; let attached = false; /** Relay-created page sessions share one real debugger; child frame sessions retain their own ids. */ const sessions = new Map([[PAGE_SESSION_ID, "page"]]); @@ -151,6 +196,7 @@ export function createCdpRelayConnection( return { receive: (raw) => { + if (closed) return; let command: unknown; try { command = JSON.parse(raw); diff --git a/apps/desktop/src/preview/DesktopBrowserHost.test.ts b/apps/desktop/src/preview/DesktopBrowserHost.test.ts index 08fefd8d733f5..3168788bebe9b 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.test.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.test.ts @@ -1,5 +1,5 @@ // @effect-diagnostics nodeBuiltinImport:off - Stands in for an Electron debugger. -import { describe, expect, it } from "@effect/vitest"; +import { describe, expect, it, vi } from "@effect/vitest"; import { DesktopBrowserEvent } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; @@ -968,4 +968,73 @@ describe("DesktopBrowserHost", () => { expect(host.humanStartedDownload(debuggee.tab.webContents)).toBe(false); }), ); + + it.effect("detaches only the tab whose CDP event is too large to relay", () => + Effect.gen(function* () { + const host = yield* DesktopBrowserHost.make; + const tabs = [makeDebuggee({ deferFocus: true }), makeDebuggee()]; + const send = vi.spyOn(tabs[0]!.tab.debugger, "sendCommand"); + const keys = [key, { threadId: "thread-2", tabId: "tab-2" }]; + const events = yield* Queue.unbounded(); + yield* host.events.pipe( + Stream.runForEach((line) => + Queue.offer(events, decodeEvent(new TextDecoder().decode(line))), + ), + Effect.forkScoped, + ); + for (const [index, tabKey] of keys.entries()) { + host.attach(tabKey, tabs[index]!.tab); + expect(yield* Queue.take(events)).toEqual({ type: "attached", ...tabKey }); + yield* host.handleCommandLine( + encodeJson({ + type: "cdp", + ...tabKey, + message: encodeJson({ id: 1, method: "Target.setAutoAttach" }), + }), + ); + // The command's reply and the page announcement. + yield* Queue.takeN(events, 2); + } + + yield* host.handleCommandLine( + encodeJson({ + type: "cdp", + ...key, + message: encodeJson({ + id: 2, + method: "Target.setAutoAttach", + params: { autoAttach: true, waitForDebuggerOnStart: true, flatten: true }, + sessionId: "t3-preview-page", + }), + }), + ); + yield* command(host, 3, "Page.startScreencast"); + tabs[0]!.emit("Runtime.consoleAPICalled", { + args: Array(2048).fill("x".repeat(40 * 1024)), + }); + tabs[1]!.emit("Page.loadEventFired", { timestamp: 1 }); + const [detached, next] = yield* Queue.takeN(events, 2); + + const { type, threadId, tabId } = detached!; + expect({ type, threadId, tabId }).toEqual({ type: "detached", ...key }); + expect(send).toHaveBeenCalledWith("Target.setAutoAttach", { + autoAttach: false, + waitForDebuggerOnStart: false, + flatten: true, + }); + tabs[0]!.settleFocus(); + yield* settle; + expect(send).not.toHaveBeenCalledWith("Target.setAutoAttach", { + autoAttach: true, + waitForDebuggerOnStart: true, + flatten: true, + }); + expect(send).toHaveBeenCalledWith("Page.stopScreencast"); + expect(tabs[0]!.focusEmulation).toEqual([true, false]); + expect(next).toMatchObject({ type: "cdp", ...keys[1] }); + expect(JSON.parse((next as { message: string }).message)).toMatchObject({ + method: "Page.loadEventFired", + }); + }).pipe(Effect.scoped), + ); }); diff --git a/apps/desktop/src/preview/DesktopBrowserHost.ts b/apps/desktop/src/preview/DesktopBrowserHost.ts index 30f252e3a677e..5a2b5463fc674 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.ts @@ -329,7 +329,7 @@ export const make = Effect.gen(function* () { const forward = (current?: () => boolean) => { const change = tab.focusChange; const run = () => - current === undefined || current() + tab.relay === relay && (current === undefined || current()) ? send(method, params, sessionId) : Promise.reject(new Error("The page this screenshot was for has moved on.")); return change === null ? run() : change.then(run); @@ -372,6 +372,24 @@ export const make = Effect.gen(function* () { emit({ type: "cdp", ...tab.key, message }); } }, + // Announcing the tab again would reconnect Playwright, and the page could + // replay the same oversized event, so the tab stays detached. + () => { + if (tab.relay !== relay || tabs.get(keyOf(tab.key)) !== tab) return; + // Disabling auto-attach detaches child sessions and releases their debugger pauses. + void debuggee + .sendCommand("Target.setAutoAttach", { + autoAttach: false, + waitForDebuggerOnStart: false, + flatten: true, + }) + .catch(() => {}); + if (tab.screencasts.size > 0) { + void debuggee.sendCommand("Page.stopScreencast").catch(() => {}); + } + setFocusEmulation(tab, false); + detach(tab.key); + }, ); tab.relay = relay; return relay; From 8bbe5aa384ed40f1582c06b010ff649e7bec2107 Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Fri, 30 Oct 2026 15:50:49 -0500 Subject: [PATCH 515/817] fix(mobile): share pull request refresh subscriptions (#23464) Co-authored-by: GPT-6.1 Sol --- .../src/state/pullRequests.test.ts | 53 +++++++++++++++++++ .../client-runtime/src/state/pullRequests.ts | 17 +++++- 2 files changed, 69 insertions(+), 1 deletion(-) diff --git a/packages/client-runtime/src/state/pullRequests.test.ts b/packages/client-runtime/src/state/pullRequests.test.ts index a8627e2d9977e..18e33cbbcf559 100644 --- a/packages/client-runtime/src/state/pullRequests.test.ts +++ b/packages/client-runtime/src/state/pullRequests.test.ts @@ -1177,6 +1177,59 @@ it.effect("keeps hover previews fresh after edits and turns", () => ), ); +it.effect("shares one refresh stream between independently created pull request readers", () => + Effect.scoped( + Effect.gen(function* () { + const revision = yield* SubscriptionRef.make(0); + let subscriptions = 0; + let title = "Original title"; + const client = { + [WS_METHODS.pullRequestsSubscribeRefreshes]: () => + Stream.unwrap( + Effect.sync(() => { + subscriptions++; + return SubscriptionRef.changes(revision); + }), + ), + [WS_METHODS.pullRequestsSummary]: () => Effect.sync(() => ({ title, state: "open" })), + [WS_METHODS.pullRequestsDetail]: () => Effect.sync(() => ({ title, state: "open" })), + } as unknown as WsRpcProtocolClient; + const { runtime, atoms, registry } = yield* makeTestRuntime(client); + const target = { + environmentId: TARGET.environmentId, + input: { projectId: ProjectId.make("project-1"), repository: "acme/web", number: 1 }, + }; + const summary = createLinkedPullRequestSummaryAtomFamily(runtime)(target); + const detail = atoms.detail(target); + for (const atom of [summary, detail]) { + const unmount = registry.mount(atom); + yield* Effect.addFinalizer(() => Effect.sync(unmount)); + expect((yield* AtomRegistry.getResult(registry, atom)).title).toBe(title); + } + yield* AtomRegistry.getResult( + registry, + atoms.refreshes({ environmentId: target.environmentId, input: {} }), + ); + expect(subscriptions).toBe(1); + + const changed = [summary, detail].map((atom) => { + const ready = Latch.makeUnsafe(); + const stop = registry.subscribe(atom, (result) => { + if (AsyncResult.isSuccess(result) && result.value.title === "Updated title") { + ready.openUnsafe(); + } + }); + return { ready, stop }; + }); + yield* Effect.addFinalizer(() => Effect.sync(() => changed.forEach(({ stop }) => stop()))); + title = "Updated title"; + yield* SubscriptionRef.update(revision, (value) => value + 1); + for (const { ready } of changed) yield* ready.await; + expect(subscriptions).toBe(1); + }), + ), +); + it.effect("shares close, reopen, and merge with an untouched client's mounted PR readers", () => Effect.scoped( Effect.gen(function* () { diff --git a/packages/client-runtime/src/state/pullRequests.ts b/packages/client-runtime/src/state/pullRequests.ts index ca5fb6d7a77d5..1785af6fd384f 100644 --- a/packages/client-runtime/src/state/pullRequests.ts +++ b/packages/client-runtime/src/state/pullRequests.ts @@ -115,7 +115,7 @@ function updateCached( registry.update(atom, AsyncResult.map(update)); } -function createPullRequestRefreshAtomFamily( +function makePullRequestRefreshAtomFamily( runtime: Atom.AtomRuntime, ) { return createEnvironmentRpcSubscriptionAtomFamily(runtime, { @@ -124,6 +124,21 @@ function createPullRequestRefreshAtomFamily( }); } +const refreshFamiliesByRuntime = new WeakMap< + object, + ReturnType +>(); + +function createPullRequestRefreshAtomFamily( + runtime: Atom.AtomRuntime, +): ReturnType> { + const existing = refreshFamiliesByRuntime.get(runtime); + if (existing) return existing as ReturnType>; + const refreshes = makePullRequestRefreshAtomFamily(runtime); + refreshFamiliesByRuntime.set(runtime, refreshes); + return refreshes; +} + export function createLinkedPullRequestSummaryAtomFamily( runtime: Atom.AtomRuntime, refreshes = createPullRequestRefreshAtomFamily(runtime), From 4ce9205d1fe86c7b977a9e12960614bfe797777c Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Fri, 30 Oct 2026 15:51:05 -0500 Subject: [PATCH 516/817] fix(web): support Home and End on hue sliders (#23465) Co-authored-by: GPT-6.1 Sol --- .../settings/colorPickers.browser.test.tsx | 24 ++++++++++++++++++- apps/web/src/components/ui/color-picker.tsx | 5 ++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/settings/colorPickers.browser.test.tsx b/apps/web/src/components/settings/colorPickers.browser.test.tsx index e468830ff3e64..f93659f112f05 100644 --- a/apps/web/src/components/settings/colorPickers.browser.test.tsx +++ b/apps/web/src/components/settings/colorPickers.browser.test.tsx @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from "vite-plus/test"; import { userEvent } from "vite-plus/test/browser"; -import type { ReactNode } from "react"; +import { useState, type ReactNode } from "react"; import { act, render } from "../../../test/render"; import { ProviderAccentColorPicker } from "./ProviderAccentColorPicker"; @@ -69,7 +69,29 @@ async function renderThemeField(value: string) { }); } +function ControlledThemeField() { + const [value, setValue] = useState("#408080"); + return setValue(next)} />; +} + describe("theme color field", () => { + it("jumps hue to both endpoints without changing saturation or brightness", async () => { + await using _screen = await render(); + await open("Choose Accent color color"); + + await press(HUE, "Home"); + expect(slider(HUE).getAttribute("aria-valuenow")).toBe("0"); + expect(byLabel("Accent color picker hex value").value).toBe("#804040"); + + await press(HUE, "End"); + expect(slider(HUE).getAttribute("aria-valuenow")).toBe("360"); + expect(byLabel("Accent color picker hex value").value).toBe("#804040"); + + await press(HUE, "ArrowRight", true); + expect(slider(HUE).getAttribute("aria-valuenow")).toBe("10"); + expect(byLabel("Accent color picker hex value").value).toBe("#804b40"); + }); + it("keeps the selected hue when a grey color is echoed back from theme settings", async () => { await using screen = await renderThemeField("#ff0000"); const { onChange, echo } = screen; diff --git a/apps/web/src/components/ui/color-picker.tsx b/apps/web/src/components/ui/color-picker.tsx index 588428c62536c..b640942ef528c 100644 --- a/apps/web/src/components/ui/color-picker.tsx +++ b/apps/web/src/components/ui/color-picker.tsx @@ -182,6 +182,11 @@ export function ColorHueSlider({ }, onInteractionEnd); const handleKeyDown = (event: KeyboardEvent) => { + if (event.key === "Home" || event.key === "End") { + event.preventDefault(); + onChange(event.key === "Home" ? 0 : 360); + return; + } if (!["ArrowDown", "ArrowLeft", "ArrowRight", "ArrowUp"].includes(event.key)) return; event.preventDefault(); const step = event.shiftKey ? 10 : 1; From 4524eeeaa3fbcfde64b207c553b42357e3542433 Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Fri, 30 Oct 2026 15:51:21 -0500 Subject: [PATCH 517/817] fix(claude): no failed AskUserQuestion row after the resume dialog (#23481) Co-authored-by: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.test.ts | 63 +++++++++++++++++++ .../Adapters/ClaudeAdapterV2.ts | 24 +++++-- 2 files changed, 81 insertions(+), 6 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index e1ee3bbe36f0a..07124b0240648 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -4953,6 +4953,69 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect("completes a turn after the resume dialog without a failed tool row", () => + Effect.scoped( + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-resume-dialog"), + text: "continue", + attachments: [], + }), + ); + const dialog = yield* Effect.promise(() => + harness.getOpenedOptions()!.onUserDialog!( + { + dialogKind: "resume_return", + payload: { sessionAgeMinutes: 90, estimatedTokens: 120000 }, + }, + { signal: new AbortController().signal, requestId: "dialog-resume" }, + ), + ).pipe(Effect.forkScoped); + const request = yield* Queue.take(harness.runtimeRequestReceipts); + assert.deepEqual( + harness.events.flatMap((event) => + event.type === "node.updated" && event.node.id === request.runtimeRequest.nodeId + ? [event.node.parentNodeId] + : [], + ), + [NodeId.make("node-attempt-resume-dialog")], + ); + yield* harness.runtime.respondToRuntimeRequest({ + requestId: request.runtimeRequest.id, + answers: { + [formatClaudeResumeCompactionQuestion({ ageMinutes: 90, estimatedTokens: 120000 })]: + "Keep full history", + }, + }); + assert.deepEqual(yield* Fiber.join(dialog), { behavior: "completed", result: "continue" }); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ uuid: "result-resume-dialog", result: "Done" }), + ); + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "completed"); + assert.deepEqual( + harness.events.flatMap((event) => + event.type === "turn_item.updated" && + event.turnItem.type === "dynamic_tool" && + event.turnItem.nativeItemRef?.nativeId === "dialog-resume" + ? [event.turnItem.status] + : [], + ), + [], + ); + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ), + ); + it.effect.each( (["aborted_tools", "aborted_streaming"] as const).flatMap((terminalReason) => [true, false].map((steered) => ({ terminalReason, steered })), diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 1fb3b9ff120e1..b1a94c2e1c0f5 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -7081,6 +7081,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( readonly context: ActiveClaudeTurnContext; readonly nativeItemId: string; readonly nativeRequestId: string; + readonly parentNodeId?: OrchestrationV2ExecutionNode["id"]; readonly requestKind: OrchestrationV2RuntimeRequest["kind"]; readonly prompt?: string; readonly appName?: string; @@ -7116,10 +7117,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( id: nodeId, threadId: input.context.input.threadId, runId: input.context.input.runId, - parentNodeId: idAllocator.derive.nodeFromProviderItem({ - driver: CLAUDE_PROVIDER, - nativeItemId: input.nativeItemId, - }), + parentNodeId: + input.parentNodeId ?? + idAllocator.derive.nodeFromProviderItem({ + driver: CLAUDE_PROVIDER, + nativeItemId: input.nativeItemId, + }), rootNodeId: input.context.input.rootNodeId, kind: input.questions === undefined ? "approval_request" : "user_input_request", status: "waiting", @@ -9556,6 +9559,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( toolName: Parameters[0], toolInput: Parameters[1], callbackOptions: Parameters[2], + options?: { readonly startToolCall?: boolean }, ) { const context = yield* Ref.get(activeTurn); if (context === null) { @@ -9569,6 +9573,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const nativeRequestId = callbackOptions.toolUseID; const nativeToolInput = claudeNativeToolInputFromRecord(toolInput); const heldForEcho = context.heldRootFrames.length > 0; + const startToolCall = toolName !== "Agent" && options?.startToolCall !== false; if (toolName === "Agent") { rememberClaudeSubagentLaunch( subagentModelCatalog, @@ -9578,7 +9583,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( nativeToolInput, null, ); - } else if (!heldForEcho) { + } else if (startToolCall && !heldForEcho) { yield* ensureToolCallStarted({ context, nativeItemId: nativeRequestId, @@ -9595,7 +9600,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ) { // The SDK blocks prompt echoes on permission answers; release held output except for ExitPlanMode. yield* releaseHeldRootFrames(context); - if (toolName !== "Agent") { + if (startToolCall) { yield* ensureToolCallStarted({ context, nativeItemId: nativeRequestId, @@ -9612,6 +9617,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( context, nativeItemId: nativeRequestId, nativeRequestId, + // No tool node exists for a control request to hang under. + ...(options?.startToolCall === false + ? { parentNodeId: context.input.rootNodeId } + : {}), requestKind: "user_input", questions, }); @@ -9973,6 +9982,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( requestId: callbackOptions.requestId, toolUseID: request.toolUseID ?? callbackOptions.requestId, }, + // The dialog is a control request, not a tool call, so no + // tool_result would ever settle a tool row started for it. + { startToolCall: false }, ); if (result.behavior !== "allow") return { behavior: "cancelled" as const }; const answers = From 3fa79a5c83817c15b04b07f5db6c639fca33abda Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Fri, 30 Oct 2026 15:51:37 -0500 Subject: [PATCH 518/817] fix(scripts): copy web brand icons to an absolute target directory (#23491) Co-authored-by: Claude Opus 5.5 --- scripts/apply-web-brand-assets.test.ts | 63 ++++++++++++++++++++++++++ scripts/apply-web-brand-assets.ts | 7 +-- 2 files changed, 65 insertions(+), 5 deletions(-) create mode 100644 scripts/apply-web-brand-assets.test.ts diff --git a/scripts/apply-web-brand-assets.test.ts b/scripts/apply-web-brand-assets.test.ts new file mode 100644 index 0000000000000..c3073879b207c --- /dev/null +++ b/scripts/apply-web-brand-assets.test.ts @@ -0,0 +1,63 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; + +import { applyWebBrandAssets } from "./apply-web-brand-assets.ts"; + +const WEB_ICON_FILENAMES = [ + "apple-touch-icon.png", + "favicon-16x16.png", + "favicon-32x32.png", + "favicon.ico", +]; + +it.layer(NodeServices.layer)("apply-web-brand-assets", (it) => { + it.effect("copies the icons into an absolute target directory as given", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const targetDirectory = yield* fs.makeTempDirectoryScoped({ + prefix: "apply-web-brand-assets-", + }); + + yield* applyWebBrandAssets("production", targetDirectory); + + assert.deepStrictEqual( + (yield* fs.readDirectory(targetDirectory)).toSorted(), + WEB_ICON_FILENAMES, + ); + }), + ); + + it.effect("resolves an empty target directory to the repo root", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const repoRoot = yield* path.fromFileUrl(new URL("..", import.meta.url)); + const destinations = WEB_ICON_FILENAMES.map((filename) => path.join(repoRoot, filename)); + // readDirectory does not follow symlinks, so a dangling link counts as an existing entry. + // Names are lowercased so a case-insensitive filesystem cannot hide a differently cased file. + const existingEntries = new Set( + (yield* fs.readDirectory(repoRoot)).map((entry) => entry.toLowerCase()), + ); + for (const destination of destinations) { + assert.isFalse( + existingEntries.has(path.basename(destination)), + `${destination} already exists`, + ); + } + yield* Effect.addFinalizer(() => + Effect.forEach(destinations, (destination) => fs.remove(destination, { force: true })).pipe( + Effect.orDie, + ), + ); + + yield* applyWebBrandAssets("production", ""); + + for (const destination of destinations) { + assert.isTrue(yield* fs.exists(destination)); + } + }), + ); +}); diff --git a/scripts/apply-web-brand-assets.ts b/scripts/apply-web-brand-assets.ts index 90b4e39c104ac..a6941de8b4307 100644 --- a/scripts/apply-web-brand-assets.ts +++ b/scripts/apply-web-brand-assets.ts @@ -29,12 +29,9 @@ export const applyWebBrandAssets = Effect.fn("applyWebBrandAssets")(function* ( const repoRoot = yield* path.fromFileUrl(new URL("..", import.meta.url)); yield* Effect.forEach( - resolveWebIconOverrides(brand, targetDirectory), + resolveWebIconOverrides(brand, path.resolve(repoRoot, targetDirectory)), (override) => - fs.copyFile( - path.join(repoRoot, override.sourceRelativePath), - path.join(repoRoot, override.targetRelativePath), - ), + fs.copyFile(path.join(repoRoot, override.sourceRelativePath), override.targetRelativePath), { concurrency: "unbounded" }, ); }); From 54c1f1007cd59dbc899befc568ba643bf594cb62 Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Fri, 30 Oct 2026 15:51:54 -0500 Subject: [PATCH 519/817] fix(web): keep model picker open during IME composition (#23493) Co-authored-by: GPT-6.1 Sol Co-authored-by: Claude Opus 5.5 --- .../components/chat/ModelPickerContent.tsx | 13 +- ...erModelPicker.composition.browser.test.tsx | 120 ++++++++++++++++++ 2 files changed, 132 insertions(+), 1 deletion(-) create mode 100644 apps/web/src/components/chat/ProviderModelPicker.composition.browser.test.tsx diff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx index c5a8cdf64c18f..6e35ebb5f7e28 100644 --- a/apps/web/src/components/chat/ModelPickerContent.tsx +++ b/apps/web/src/components/chat/ModelPickerContent.tsx @@ -773,7 +773,13 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { }; const onWindowKeyDown = (event: globalThis.KeyboardEvent) => { - if (event.defaultPrevented || event.repeat || isCommandPaletteOpen()) { + if ( + event.defaultPrevented || + event.repeat || + event.isComposing || + event.keyCode === 229 || + isCommandPaletteOpen() + ) { return; } @@ -912,6 +918,11 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { setSearchQuery(e.target.value); }} onKeyDown={(e) => { + if (e.nativeEvent.isComposing || e.keyCode === 229) { + (e as typeof e & { preventBaseUIHandler?: () => void }).preventBaseUIHandler?.(); + e.stopPropagation(); + return; + } if ( showSidebar && !e.altKey && diff --git a/apps/web/src/components/chat/ProviderModelPicker.composition.browser.test.tsx b/apps/web/src/components/chat/ProviderModelPicker.composition.browser.test.tsx new file mode 100644 index 0000000000000..a4dbe8bd31398 --- /dev/null +++ b/apps/web/src/components/chat/ProviderModelPicker.composition.browser.test.tsx @@ -0,0 +1,120 @@ +import { + ProviderDriverKind, + ProviderInstanceId, + type ResolvedKeybindingsConfig, +} from "@t3tools/contracts"; +import { compileResolvedKeybindingsConfig } from "@t3tools/shared/keybindings"; +import { useState } from "react"; +import { expect, it } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; + +import { act, render } from "../../../test/render"; +import { deriveProviderInstanceEntries } from "../../providerInstances"; +import { ProviderModelPicker } from "./ProviderModelPicker"; + +const instanceId = ProviderInstanceId.make("codex"); + +function Picker({ keybindings = [] }: { keybindings?: ResolvedKeybindingsConfig }) { + const [model, setModel] = useState("original"); + return ( + <> + {model} + setModel(selected)} + /> + + ); +} + +it("keeps composition keys out of model selection and dismissal", async () => { + await using screen = await render(); + await page.getByRole("button", { name: "Choose model" }).click(); + const search = page.getByPlaceholder("Search models..."); + await search.fill("Target"); + await expect.element(page.getByRole("option", { name: /Target model/ })).toBeVisible(); + + for (const nativeEvent of [{ isComposing: true }, { keyCode: 229 }]) { + for (const key of ["Enter", "Escape"]) { + const event = new KeyboardEvent("keydown", { + key, + ...nativeEvent, + bubbles: true, + cancelable: true, + }); + await act(() => search.element().dispatchEvent(event)); + expect(event.defaultPrevented).toBe(false); + await expect.element(search).toBeVisible(); + await expect + .element(screen.getByRole("status", { name: "Selected model" })) + .toHaveTextContent("original"); + } + } + + await userEvent.keyboard("{Enter}"); + await expect.element(search).not.toBeInTheDocument(); + await expect + .element(screen.getByRole("status", { name: "Selected model" })) + .toHaveTextContent("target"); + await page.getByRole("button", { name: "Choose model" }).click(); + await expect.element(search).toBeVisible(); + await userEvent.keyboard("{Escape}"); + await expect.element(search).not.toBeInTheDocument(); +}); + +it("keeps composing keys from triggering model jump shortcuts", async () => { + const keybindings = compileResolvedKeybindingsConfig([ + { key: "enter", command: "modelPicker.jump.1", when: "modelPickerOpen" }, + ]); + await using screen = await render(); + await page.getByRole("button", { name: "Choose model" }).click(); + const search = page.getByPlaceholder("Search models..."); + await search.fill("Target"); + await expect.element(page.getByRole("option", { name: /Target model/ })).toBeVisible(); + + for (const nativeEvent of [{ isComposing: true }, { keyCode: 229 }]) { + const event = new KeyboardEvent("keydown", { + key: "Enter", + ...nativeEvent, + bubbles: true, + cancelable: true, + }); + await act(() => search.element().dispatchEvent(event)); + expect(event.defaultPrevented).toBe(false); + await expect.element(search).toBeVisible(); + await expect + .element(screen.getByRole("status", { name: "Selected model" })) + .toHaveTextContent("original"); + } +}); From 269357ccd9d3e38367248707e3931e0e7dfe76aa Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Fri, 30 Oct 2026 15:52:09 -0500 Subject: [PATCH 520/817] fix(mobile): fit large thread titles in Arrange threads (#23499) Co-authored-by: GPT-6.1 Sol Co-authored-by: maria-rcks --- .../threads/ThreadArrangementSheet.tsx | 36 +++++++++++-------- apps/mobile/src/lib/layout.test.ts | 13 +++++++ apps/mobile/src/lib/layout.ts | 15 ++++++++ 3 files changed, 50 insertions(+), 14 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadArrangementSheet.tsx b/apps/mobile/src/features/threads/ThreadArrangementSheet.tsx index 603fac3d00f5c..839506c84bc19 100644 --- a/apps/mobile/src/features/threads/ThreadArrangementSheet.tsx +++ b/apps/mobile/src/features/threads/ThreadArrangementSheet.tsx @@ -5,7 +5,7 @@ import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell import { effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled"; import { sortInboxThreadsByReturn } from "@t3tools/client-runtime/state/thread-inbox"; import { type ReactNode, useEffect, useMemo, useRef, useState } from "react"; -import { Animated, FlatList, Modal, Pressable, View } from "react-native"; +import { Animated, FlatList, Modal, Pressable, useWindowDimensions, View } from "react-native"; import { Gesture, GestureDetector, GestureHandlerRootView } from "react-native-gesture-handler"; import Reanimated, { ReduceMotion, useAnimatedStyle, withTiming } from "react-native-reanimated"; import { threadDragGapOffset } from "./threadDragGap"; @@ -14,6 +14,7 @@ import { SafeAreaProvider, SafeAreaView } from "react-native-safe-area-context"; import { AppText as Text } from "../../components/ui/AppText"; import { SymbolView } from "../../components/ui/AppSymbol"; import { scopedThreadKey } from "../../lib/scopedEntities"; +import { deriveThreadArrangementSizing } from "../../lib/layout"; import { environmentServerConfigsAtom } from "../../state/server"; import { threadListEnvironmentsAtom } from "../../state/presentation"; import { environmentThreadShells } from "../../state/threads"; @@ -39,9 +40,8 @@ import { } from "./threadListV2"; import { useThreadListNow } from "./use-thread-list-now"; import { useThreadListV2ShelfPreferences } from "./use-thread-list-v2-shelf-preferences"; +import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; -const ROW_HEIGHT = 56; -const HEADER_HEIGHT = 48; const keyOf = (thread: EnvironmentThreadShell) => scopedThreadKey(thread.environmentId, thread.id); type Section = "pinned" | "active" | "snoozed" | "settled"; type Destination = Exclude; @@ -163,6 +163,12 @@ function DragHandle(props: { } function ThreadArrangementSheet(props: { onClose: () => void }) { + const { appearance } = useAppearancePreferences(); + const { fontScale } = useWindowDimensions(); + const { rowHeight, headerHeight } = deriveThreadArrangementSizing({ + baseFontSize: appearance.baseFontSize, + fontScale, + }); const threads = useAtomValue(environmentThreadShells.navigationThreadShellsAtom); const configs = useAtomValue(environmentServerConfigsAtom); const listEnvironments = useAtomValue(threadListEnvironmentsAtom); @@ -230,20 +236,20 @@ function ThreadArrangementSheet(props: { onClose: () => void }) { let offset = 0; for (const section of ["pinned", "active", "snoozed", "settled"] as const) { if (section === "snoozed" && sections[section].length === 0) continue; - result.push({ key: section, section, offset, height: HEADER_HEIGHT }); - offset += HEADER_HEIGHT; + result.push({ key: section, section, offset, height: headerHeight }); + offset += headerHeight; if ((section === "snoozed" || section === "settled") && !expanded[section]) continue; for (const thread of section === "settled" ? visibleSettled : sections[section]) { - result.push({ key: keyOf(thread), section, thread, offset, height: ROW_HEIGHT }); - offset += ROW_HEIGHT; + result.push({ key: keyOf(thread), section, thread, offset, height: rowHeight }); + offset += rowHeight; } if (section === "settled" && settledCount > visibleSettled.length) { - result.push({ key: "settled-more", section, more: true, offset, height: ROW_HEIGHT }); - offset += ROW_HEIGHT; + result.push({ key: "settled-more", section, more: true, offset, height: rowHeight }); + offset += rowHeight; } } return result; - }, [sections, expanded, visibleSettled, settledCount]); + }, [sections, expanded, visibleSettled, settledCount, rowHeight, headerHeight]); const list = useRef>(null); const geometry = useRef({ height: 0, offset: 0 }); const drag = useRef(null); @@ -261,7 +267,9 @@ function ThreadArrangementSheet(props: { onClose: () => void }) { setPreview(null); } const orderVersion = rows - .map((row) => `${row.key}:${row.thread?.pinOrderKey}:${row.thread?.activeOrderKey}`) + .map( + (row) => `${row.key}:${row.height}:${row.thread?.pinOrderKey}:${row.thread?.activeOrderKey}`, + ) .join("|"); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- cancels the in-progress drag gesture when the thread order changes underneath it useEffect(() => { @@ -282,7 +290,7 @@ function ThreadArrangementSheet(props: { onClose: () => void }) { current.translation = translation; const { height, offset } = geometry.current; const y = current.startY + translation; - translateY.setValue(Math.max(0, Math.min(height - ROW_HEIGHT, y - ROW_HEIGHT / 2))); + translateY.setValue(Math.max(0, Math.min(height - rowHeight, y - rowHeight / 2))); const contentY = Math.max(0, y + offset); const target = latest.current.rows.find((row) => contentY < row.offset + row.height) ?? @@ -321,7 +329,7 @@ function ThreadArrangementSheet(props: { onClose: () => void }) { orderVersion, sourceSection: row.section, thread: row.thread, - startY: row.offset + ROW_HEIGHT / 2 - geometry.current.offset, + startY: row.offset + row.height / 2 - geometry.current.offset, translation: 0, destination: null, }; @@ -554,7 +562,7 @@ function ThreadArrangementSheet(props: { onClose: () => void }) { { + it("fits two title lines and section labels with combined app and system text scaling", () => { + const sizing = deriveThreadArrangementSizing({ baseFontSize: 22, fontScale: 1.3 }); + expect(sizing.rowHeight).toBeGreaterThanOrEqual(2 * 32 * 1.3 + 10); + expect(sizing.headerHeight).toBeGreaterThanOrEqual(26 * 1.3 + 24); + expect(deriveThreadArrangementSizing({ baseFontSize: 16, fontScale: 1 })).toEqual({ + rowHeight: 56, + headerHeight: 48, + }); + }); +}); + describe("thread work-log text sizing", () => { it.each([ { baseFontSize: 16, fontScale: 1.25, estimatedRowHeight: 28 }, diff --git a/apps/mobile/src/lib/layout.ts b/apps/mobile/src/lib/layout.ts index ccff7fdf6c890..4155d834ba24d 100644 --- a/apps/mobile/src/lib/layout.ts +++ b/apps/mobile/src/lib/layout.ts @@ -19,6 +19,21 @@ export const ANDROID_READING_MAX_WIDTH = 640; // min-h-8 uses the 14px rem configured in metro.config.js. export const THREAD_WORK_ROW_MIN_HEIGHT = 28; +export function deriveThreadArrangementSizing(input: { + readonly baseFontSize: number; + readonly fontScale: number; +}) { + const bodyLineHeight = scaledTypographyLineHeight(MOBILE_TYPOGRAPHY.body, input.baseFontSize); + const headerLineHeight = scaledTypographyLineHeight( + MOBILE_TYPOGRAPHY.footnote, + input.baseFontSize, + ); + return { + rowHeight: Math.max(56, Math.ceil(2 * bodyLineHeight * input.fontScale) + 10), + headerHeight: Math.max(48, Math.ceil(headerLineHeight * input.fontScale) + 24), + }; +} + export function deriveThreadWorkLogSizing(input: { readonly baseFontSize: number; readonly fontScale: number; From b1b3c10e249c68d6be86708f453c28b5c226f9b9 Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Fri, 30 Oct 2026 15:52:27 -0500 Subject: [PATCH 521/817] fix(clients): keep accepted server updates through disconnects (#23532) Co-authored-by: GPT-6.1 Sol Co-authored-by: maria-rcks --- .../src/connection/outdatedHostUpdate.test.ts | 125 +++++++++++++- .../src/connection/outdatedHostUpdate.ts | 13 +- .../client-runtime/src/state/server.test.ts | 163 ++++++++++++++++++ packages/client-runtime/src/state/server.ts | 16 +- 4 files changed, 313 insertions(+), 4 deletions(-) diff --git a/packages/client-runtime/src/connection/outdatedHostUpdate.test.ts b/packages/client-runtime/src/connection/outdatedHostUpdate.test.ts index f241f7b464cbd..33aa01ee71b06 100644 --- a/packages/client-runtime/src/connection/outdatedHostUpdate.test.ts +++ b/packages/client-runtime/src/connection/outdatedHostUpdate.test.ts @@ -124,6 +124,20 @@ class OutdatedHostSocket { const message = decodeJson(data); if (!isRpcRequest(message)) return; this.requests.push(message); + if (message.tag === WS_METHODS.serverUpdateServerWithProgress) { + this.onUpdate(); + queueMicrotask(() => + this.emit({ + type: "message", + data: encodeJson({ + _tag: "Chunk", + requestId: message.id, + values: [{ type: "progress", stage: "downloading" }], + }), + }), + ); + return; + } if (message.tag !== WS_METHODS.serverUpdateServer) return; this.onUpdate(); queueMicrotask(() => @@ -143,10 +157,10 @@ class OutdatedHostSocket { close() { this.readyState = 3; - this.emit({ type: "close" }); + this.emit({ type: "close", code: 1006 }); } - private emit(event: { readonly type: string; readonly data?: unknown }) { + private emit(event: { readonly type: string; readonly data?: unknown; readonly code?: number }) { for (const listener of this.listeners.get(event.type) ?? []) listener(event); } } @@ -314,4 +328,111 @@ describe("updateOutdatedHost", () => { expect(opened).toBe(false); }), ); + + it.effect("resumes an outdated host update after progress transport loss", () => + Effect.gen(function* () { + const blocked = orchestrationProtocolCompatibilityError(descriptor(undefined, "0.0.45")); + expect(blocked).toMatchObject({ serverUpdateRequired: true }); + + const sockets: Array = []; + let served: ExecutionEnvironmentDescriptor = { + ...descriptor(undefined, "0.0.45"), + capabilities: { + repositoryIdentity: true, + serverSelfUpdate: "boot-service", + serverSelfUpdateProgress: true, + }, + }; + const entries = yield* SubscriptionRef.make< + ReadonlyMap + >( + new Map([ + [ + TARGET.environmentId, + { + target: TARGET, + profile: Option.none(), + enabled: false, + unsupportedReason: blocked?.message ?? "", + serverUpdateRequired: true, + }, + ], + ]), + ); + const calls: Array = []; + const registry = EnvironmentRegistry.EnvironmentRegistry.of({ + entries, + setCompatibility: (_environmentId: EnvironmentId, error: unknown) => + Effect.sync(() => calls.push(`compatibility:${error === null ? "clear" : "block"}`)), + setEnabled: (_environmentId: EnvironmentId, enabled: boolean) => + Effect.sync(() => calls.push(`enabled:${enabled}`)), + } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]); + const resolver = ConnectionResolver.ConnectionResolver.of({ + prepare: () => Effect.die(new Error("The update must bypass the protocol gate.")), + prepareForUpdate: () => + Effect.sync(() => served).pipe( + Effect.map((current) => ({ + descriptor: current, + prepared: { + environmentId: TARGET.environmentId, + label: TARGET.label, + httpBaseUrl: TARGET.httpBaseUrl, + socketUrl: "wss://build.example.test/ws?wsTicket=ticket", + httpAuthorization: null, + target: TARGET, + }, + })), + ), + }); + const httpClient = HttpClient.make((request) => + Effect.sync(() => + HttpClientResponse.fromWeb(request, new Response(encodeDescriptor(served))), + ), + ); + + const stages: Array = []; + const result = yield* updateOutdatedHost( + TARGET.environmentId, + { targetVersion: "0.0.46" }, + (stage) => + Effect.sync(() => { + stages.push(stage); + // Lose the transport only after the consumer has observed progress. + if (stage === "downloading") sockets[0]?.close(); + }), + ).pipe( + Effect.provide( + Layer.mergeAll( + Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, registry), + Layer.succeed(ConnectionResolver.ConnectionResolver, resolver), + Layer.succeed( + RelayEnvironmentDiscovery.RelayEnvironmentDiscovery, + RelayEnvironmentDiscovery.RelayEnvironmentDiscovery.of({ + state: yield* SubscriptionRef.make( + RelayEnvironmentDiscovery.EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE, + ), + refresh: Effect.void, + }), + ), + Layer.succeed(HttpClient.HttpClient, httpClient), + Layer.succeed(Socket.WebSocketConstructor, (url) => { + const socket = new OutdatedHostSocket(url, () => { + served = descriptor(ORCHESTRATION_PROTOCOL_VERSION, "0.0.46"); + }); + sockets.push(socket); + return socket as unknown as globalThis.WebSocket; + }), + ), + ), + ); + + expect(sockets[0]?.url).not.toContain("orchestrationProtocol"); + expect(sockets[0]?.requests.map((request) => request.tag)).toEqual([ + WS_METHODS.serverUpdateServerWithProgress, + ]); + expect(stages).toEqual(["downloading", "resuming"]); + expect(result.targetVersion).toBe("0.0.46"); + expect(calls).toEqual(["compatibility:clear", "enabled:true"]); + }), + ); }); diff --git a/packages/client-runtime/src/connection/outdatedHostUpdate.ts b/packages/client-runtime/src/connection/outdatedHostUpdate.ts index 444a33a1ac54e..d702e1f6b057f 100644 --- a/packages/client-runtime/src/connection/outdatedHostUpdate.ts +++ b/packages/client-runtime/src/connection/outdatedHostUpdate.ts @@ -141,20 +141,31 @@ export const updateOutdatedHost = Effect.fn("clientRuntime.connection.updateOutd capabilities.serverSelfUpdateProgress === true ? yield* Effect.gen(function* () { const terminal = yield* Ref.make(Option.none()); + let receivedProgress = false; const streamExit = yield* client[WS_METHODS.serverUpdateServerWithProgress]( input, ).pipe( Stream.runForEach((event) => event.type === "complete" ? Ref.set(terminal, Option.some(event.result)) - : onStage(event.stage), + : Effect.sync(() => { + receivedProgress = true; + }).pipe(Effect.andThen(onStage(event.stage))), ), Effect.exit, ); + const selfUpdateMethod = capabilities.serverSelfUpdate; + // Desktop preparation needs its terminal commit token. + const accepted = + receivedProgress && + (selfUpdateMethod === "boot-service" || selfUpdateMethod === "respawn") + ? { targetVersion: input.targetVersion, method: selfUpdateMethod } + : undefined; return yield* resolveServerUpdateProgressResult( input.targetVersion, yield* Ref.get(terminal), streamExit, + accepted, ); }) : yield* client[WS_METHODS.serverUpdateServer](input).pipe( diff --git a/packages/client-runtime/src/state/server.test.ts b/packages/client-runtime/src/state/server.test.ts index b07148a9c4bc5..c852afdcae32e 100644 --- a/packages/client-runtime/src/state/server.test.ts +++ b/packages/client-runtime/src/state/server.test.ts @@ -1,5 +1,6 @@ import { EnvironmentId, + ServerSelfUpdateError, ProviderInstanceId, ServerObservability, EnvironmentThemeId, @@ -16,12 +17,14 @@ import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; +import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; +import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; import * as TestClock from "effect/testing/TestClock"; import { RpcClientError } from "effect/rpc"; import * as Socket from "effect/socket/Socket"; @@ -32,11 +35,15 @@ import { type PreparedConnection, } from "../connection/model.ts"; import * as EnvironmentSupervisor from "../connection/supervisor.ts"; +import * as EnvironmentRegistry from "../connection/registry.ts"; +import { RpcPermissionGuard } from "../rpc/client.ts"; import * as Persistence from "../platform/persistence.ts"; import type { WsRpcProtocolClient } from "../rpc/protocol.ts"; import type { RpcSession } from "../rpc/session.ts"; import { applyServerWelcomeEvent, + createServerEnvironmentAtoms, + serverUpdateStateAtom, makeEnvironmentServerWelcomeState, makeEnvironmentServerConfigState, isLegacyUpdateHandoffLoss, @@ -216,6 +223,162 @@ describe("update restart reconnect nudges", () => { ); }); +describe("accepted server update recovery", () => { + it.effect.each([ + { loss: "interrupt", resumes: true }, + { loss: "socket", resumes: true }, + { loss: "server_error", resumes: false }, + { loss: "no_progress", resumes: false }, + { loss: "cancel", resumes: false }, + { loss: "socket", method: "respawn", resumes: true }, + { loss: "socket", method: "desktop-managed", resumes: false }, + ] as const)("handles $loss with $method and recovery=$resumes", (scenario) => + Effect.gen(function* () { + const { loss, resumes } = scenario; + const method = "method" in scenario ? scenario.method : "boot-service"; + const observing = yield* Deferred.make(); + const cancelFiber = yield* Deferred.make>(); + const oldReadyObserved = yield* Deferred.make(); + const readyEvents = + yield* Queue.unbounded[1]>(); + const config = { + ...CONFIG, + environment: { + ...CONFIG.environment, + serverVersion: "0.0.30", + capabilities: { serverSelfUpdate: method, serverSelfUpdateProgress: true }, + }, + } as ServerConfig; + const client = { + [WS_METHODS.subscribeServerConfig]: () => Stream.never, + [WS_METHODS.subscribeServerLifecycle]: () => + Stream.fromEffect(Deferred.succeed(observing, undefined)).pipe( + Stream.drain, + Stream.concat(Stream.fromQueue(readyEvents)), + Stream.tap((event) => + event.payload.environment.serverVersion === "0.0.30" + ? Deferred.succeed(oldReadyObserved, undefined) + : Effect.void, + ), + ), + [WS_METHODS.serverUpdateServerWithProgress]: () => + (loss === "no_progress" + ? Stream.empty + : Stream.make({ type: "progress" as const, stage: "downloading" as const }) + ).pipe( + Stream.concat( + Stream.fromEffect( + loss === "cancel" + ? Effect.fiber.pipe( + Effect.flatMap((fiber) => Deferred.succeed(cancelFiber, fiber)), + Effect.andThen(Effect.never), + ) + : loss === "interrupt" + ? Effect.interrupt + : Effect.fail( + loss === "server_error" + ? new ServerSelfUpdateError({ + reason: "Archive verification failed.", + }) + : new RpcClientError.RpcClientError({ + reason: new Socket.SocketCloseError({ code: 1006 }), + }), + ), + ), + ), + ), + } as unknown as WsRpcProtocolClient; + const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({ + target: TARGET, + state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE), + session: yield* SubscriptionRef.make(Option.some(session(client))), + prepared: yield* SubscriptionRef.make(Option.none()), + connect: Effect.void, + disconnect: Effect.void, + retryNow: Effect.void, + }); + const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (_id, effect) => + Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor); + const runStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["runStream"] = ( + _id, + stream, + ) => Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor); + const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({ + run, + runStream, + followStream: runStream, + stateChanges: () => Stream.never, + retryNow: () => Effect.void, + } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]); + const runtime = Atom.runtime( + Layer.mergeAll( + Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry), + Layer.succeed(RpcPermissionGuard, { authorize: () => Effect.void }), + Layer.succeed(Persistence.EnvironmentCacheStore, { + loadServerConfig: () => Effect.succeedNone, + } as unknown as Persistence.EnvironmentCacheStore["Service"]), + ), + ); + const atoms = createServerEnvironmentAtoms(runtime, { + initialConfigValueAtom: () => Atom.make(config), + }); + const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (value) => + Effect.sync(() => value.dispose()), + ); + const pending = atoms.updateServer.run(registry, { + environmentId: TARGET.environmentId, + input: { targetVersion: "0.0.31" }, + }); + if (loss === "cancel") { + yield* Fiber.interrupt(yield* Deferred.await(cancelFiber)); + const cancelled = yield* Effect.promise(() => pending); + expect(cancelled._tag).toBe("Failure"); + if (cancelled._tag === "Failure") + expect(Cause.hasInterruptsOnly(cancelled.cause)).toBe(true); + expect(registry.get(serverUpdateStateAtom(TARGET.environmentId))).toEqual({ + status: "idle", + }); + expect(yield* Deferred.isDone(observing)).toBe(false); + return; + } + const first = yield* Effect.raceFirst( + Effect.promise(() => pending).pipe(Effect.as("settled")), + Deferred.await(observing).pipe(Effect.as("observing")), + ); + if (!resumes) { + expect(first).toBe("settled"); + expect(AsyncResult.isFailure(yield* Effect.promise(() => pending))).toBe(true); + expect(registry.get(serverUpdateStateAtom(TARGET.environmentId))).toMatchObject({ + status: "failed", + }); + return; + } + expect(first).toBe("observing"); + expect(registry.get(serverUpdateStateAtom(TARGET.environmentId))).toMatchObject({ + status: "running", + stage: "resuming", + }); + const ready = (serverVersion: string) => + ({ + version: 1, + sequence: 1, + type: "ready", + payload: { at: "2026-09-01T00:00:00.000Z", environment: { serverVersion } }, + }) as Parameters[1]; + yield* Queue.offer(readyEvents, ready("0.0.30")); + yield* Deferred.await(oldReadyObserved); + expect(registry.get(serverUpdateStateAtom(TARGET.environmentId))).toMatchObject({ + status: "running", + }); + yield* Queue.offer(readyEvents, ready("0.0.31")); + expect(AsyncResult.isSuccess(yield* Effect.promise(() => pending))).toBe(true); + expect(registry.get(serverUpdateStateAtom(TARGET.environmentId))).toEqual({ + status: "idle", + }); + }).pipe(Effect.scoped), + ); +}); + const makeConfigPersistenceHarness = Effect.fn("test.makeConfigPersistenceHarness")(function* ( saveServerConfig: Persistence.EnvironmentCacheStore["Service"]["saveServerConfig"], ) { diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts index dadaf2dafb7a5..4c44c7df9dec9 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -103,7 +103,7 @@ export class ServerUpdateResumeTimeoutError extends Schema.TaggedError( targetVersion: string, terminal: Option.Option, streamExit: Exit.Exit, + accepted?: ServerSelfUpdateResult, ): Effect.Effect { if ( Option.isSome(terminal) && @@ -346,6 +347,9 @@ export function resolveServerUpdateProgressResult( return Effect.succeed(terminal.value); } if (Exit.isFailure(streamExit)) { + if (accepted !== undefined && isLegacyUpdateHandoffLoss(streamExit.cause)) { + return Effect.succeed(accepted); + } return Effect.failCause(streamExit.cause); } return Effect.fail(new ServerUpdateProgressIncompleteError({ targetVersion })); @@ -882,6 +886,7 @@ export function createServerEnvironmentAtoms( currentConfig?.environment.capabilities.serverSelfUpdateProgress === true; const updateResult: ServerSelfUpdateResult = supportsProgress ? yield* Effect.gen(function* () { + let receivedProgress = false; const terminal = yield* Ref.make>( Option.none(), ); @@ -893,6 +898,7 @@ export function createServerEnvironmentAtoms( .pipe( Stream.runForEach((event) => Effect.sync(() => { + receivedProgress ||= event.type === "progress"; const state = serverUpdateStateForProgressEvent( fromVersion, targetVersion, @@ -910,10 +916,18 @@ export function createServerEnvironmentAtoms( ), Effect.exit, ); + const selfUpdateMethod = currentConfig?.environment.capabilities.serverSelfUpdate; + // Desktop preparation needs its terminal commit token. + const accepted = + receivedProgress && + (selfUpdateMethod === "boot-service" || selfUpdateMethod === "respawn") + ? { targetVersion, method: selfUpdateMethod } + : undefined; return yield* resolveServerUpdateProgressResult( targetVersion, yield* Ref.get(terminal), streamExit, + accepted, ); }) : yield* Effect.gen(function* () { From 0804c60a9cd0a120092a565b5c422a19fc6c5612 Mon Sep 17 00:00:00 2001 From: Afonso Ferreira <99990310+Aforno@users.noreply.github.com> Date: Fri, 30 Oct 2026 20:52:44 +0000 Subject: [PATCH 522/817] fix(server): reject busy merge-back targets before blocking their queue (#23554) --- .../src/orchestration-v2/Orchestrator.ts | 13 ++- .../src/orchestration-v2/runtimeLayer.test.ts | 90 ++++++++++++++++++- 2 files changed, 101 insertions(+), 2 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index ce43fef58a48a..ada7bba8234aa 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -4340,7 +4340,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // The source is unlocked; validate the modes copied here, not an earlier read. yield* refuseAboveDispatchModeLimit(command, command.sourceThreadId, sourceProjection.thread); const targetProjection = yield* projectionStore - .getThreadRecords(command.targetThreadId, ["contextTransfers"]) + .getThreadRecords(command.targetThreadId, ["runs", "contextTransfers"]) .pipe( Effect.mapError( (cause) => @@ -4392,6 +4392,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); } + // Queued runs cannot consume merge-back context. Refuse under the target's + // command lock before a pending transfer can block its ordinary messages. + if (targetProjection.runs.some((run) => isBlockingRun(run) || run.status === "queued")) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: + "Finish or stop the target thread's active work and clear its queue before merging back.", + }); + } + const sourceProviderThread = providerThreadForRun(sourceProjection, sourceRun); const now = command.createdAt ?? (yield* DateTime.now); const emitEvent = emit(events, command); diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 20158a80d3ff6..a04fe4c7c1374 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -1726,7 +1726,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => { }), ); - it.effect("merges an explicit provider-finished run while checkpoint capture is pending", () => + it.effect("refuses busy merge-back targets without blocking the queue", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; const eventSink = yield* EventSink.EventSinkV2; @@ -1741,6 +1741,13 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => { ); const forkTransferId = ContextTransferId.make("runtime-layer-waiting-merge-fork-transfer"); + yield* seedProject({ + projectId, + title: "Merge-back project", + workspaceRoot: process.cwd(), + defaultModelSelection: modelSelection, + createdAt: DateTime.formatIso(now), + }); yield* orchestrator.dispatch({ type: "thread.create", createdBy: "user", @@ -1868,6 +1875,87 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => { ], }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("runtime-layer-merge-target-start"), + threadId: targetThreadId, + messageId: MessageId.make("runtime-layer-merge-target-message"), + text: "Keep working in the parent.", + attachments: [], + dispatchMode: { type: "start_immediately" }, + }); + const activeTarget = yield* orchestrator.getThreadProjection(targetThreadId); + const targetRun = activeTarget.runs[0]!; + for (const status of ["preparing", "starting", "waiting", "queued", "running"] as const) { + yield* eventSink.write({ + commandId: CommandId.make(`runtime-layer-merge-target-${status}`), + events: [ + { + id: EventId.make(`runtime-layer-merge-target-${status}-event`), + type: "run.updated", + threadId: targetThreadId, + runId: targetRun.id, + occurredAt: now, + payload: { ...targetRun, status }, + }, + ], + }); + const error = yield* orchestrator + .dispatch({ + type: "thread.merge_back", + createdBy: "user", + creationSource: "mobile", + commandId: CommandId.make(`runtime-layer-merge-refused-${status}`), + sourceThreadId, + targetThreadId, + sourcePoint: { type: "run", runId: sourceRunId }, + }) + .pipe(Effect.flip); + assert.instanceOf(error, Orchestrator.OrchestratorDispatchError); + assert.equal( + error.cause, + "Finish or stop the target thread's active work and clear its queue before merging back.", + ); + const refusedTarget = yield* orchestrator.getThreadProjection(targetThreadId); + assert.deepEqual(refusedTarget.contextTransfers, activeTarget.contextTransfers); + assert.equal(refusedTarget.runs[0]?.status, status); + } + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("runtime-layer-merge-target-queue"), + threadId: targetThreadId, + messageId: MessageId.make("runtime-layer-merge-target-queued-message"), + text: "Run this after the current turn.", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + }); + const queuedTarget = yield* orchestrator.getThreadProjection(targetThreadId); + const queuedRun = queuedTarget.runs.find((run) => run.status === "queued"); + assert.isDefined(queuedRun); + yield* orchestrator.dispatch({ + type: "queued-run.cancel", + commandId: CommandId.make("runtime-layer-merge-target-cancel-queue"), + threadId: targetThreadId, + runId: queuedRun.id, + }); + yield* eventSink.write({ + commandId: CommandId.make("runtime-layer-merge-target-complete"), + events: [ + { + id: EventId.make("runtime-layer-merge-target-completed-event"), + type: "run.updated", + threadId: targetThreadId, + runId: targetRun.id, + occurredAt: now, + payload: { ...targetRun, status: "completed", completedAt: now }, + }, + ], + }); + yield* orchestrator.dispatch({ type: "thread.merge_back", createdBy: "user", From 37022730bacb03f26c1cba9b31ec1d8da3c6e730 Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Fri, 30 Oct 2026 15:53:05 -0500 Subject: [PATCH 523/817] perf(web): skip favicon loading for custom project icons (#23569) Co-authored-by: GPT-6.1 Sol Co-authored-by: Claude Opus 5.5 --- .../ProjectFavicon.browser.test.tsx | 57 +++++++++++++++++++ apps/web/src/components/ProjectFavicon.tsx | 19 ++++--- 2 files changed, 69 insertions(+), 7 deletions(-) create mode 100644 apps/web/src/components/ProjectFavicon.browser.test.tsx diff --git a/apps/web/src/components/ProjectFavicon.browser.test.tsx b/apps/web/src/components/ProjectFavicon.browser.test.tsx new file mode 100644 index 0000000000000..746302ef5b242 --- /dev/null +++ b/apps/web/src/components/ProjectFavicon.browser.test.tsx @@ -0,0 +1,57 @@ +import { RegistryContext } from "@effect/atom-react"; +import { EnvironmentId } from "@t3tools/contracts"; +import { Atom, AtomRegistry } from "effect/reactivity"; +import { expect, it, vi } from "vite-plus/test"; + +import { render } from "../../test/render"; +import { ProjectFavicon, type ProjectFaviconProject } from "./ProjectFavicon"; + +const state = vi.hoisted(() => ({ favicon: undefined as Atom.Atom | undefined })); +vi.mock(import("../state/assets"), () => ({ + projectFaviconUrlAtom: () => { + if (!state.favicon) throw new Error("Favicon resource not configured"); + return state.favicon; + }, +})); + +function setup() { + const activeResources = new Set(); + state.favicon = Atom.make((get) => { + activeResources.add("favicon"); + get.addFinalizer(() => activeResources.delete("favicon")); + return null; + }); + return { activeResources }; +} + +it("only activates the favicon resource after removing a custom icon", async () => { + const { activeResources } = setup(); + const registry = AtomRegistry.make(); + const project: ProjectFaviconProject = { + environmentId: EnvironmentId.make("test"), + workspaceRoot: "/project", + title: "Project", + faviconPath: "icon.png", + projectIcon: { kind: "monogram", text: "PR", color: "blue" }, + }; + const view = (projectIcon: ProjectFaviconProject["projectIcon"]) => ( + + + + ); + try { + await using screen = await render(view(project.projectIcon)); + expect(activeResources.size).toBe(0); + await screen.rerender(view({ kind: "emoji", emoji: "🌱" })); + expect(activeResources.size).toBe(0); + await screen.rerender(view({ kind: "lucide", name: "leaf", color: "green" })); + expect(activeResources.size).toBe(0); + await screen.rerender(view(null)); + expect(activeResources.size).toBe(1); + await screen.rerender(view(project.projectIcon)); + await screen.rerender(view(null)); + expect(activeResources.size).toBe(1); + } finally { + registry.dispose(); + } +}); diff --git a/apps/web/src/components/ProjectFavicon.tsx b/apps/web/src/components/ProjectFavicon.tsx index 14a00ae86583b..3545a0aa5db87 100644 --- a/apps/web/src/components/ProjectFavicon.tsx +++ b/apps/web/src/components/ProjectFavicon.tsx @@ -38,13 +38,6 @@ export function ProjectFavicon(input: { fallbackIcon?: ComponentType<{ className?: string }>; }) { const { project } = input; - const src = useAtomValue( - projectFaviconUrlAtom({ - environmentId: project.environmentId, - cwd: project.workspaceRoot, - faviconPath: project.faviconPath, - }), - ); if (project.projectIcon?.kind === "monogram") { return ( ); } + return ; +} + +function AutomaticProjectFavicon(input: Parameters[0]) { + const { project } = input; + const src = useAtomValue( + projectFaviconUrlAtom({ + environmentId: project.environmentId, + cwd: project.workspaceRoot, + faviconPath: project.faviconPath, + }), + ); const FallbackIcon = input.fallbackIcon ?? FolderCodeIcon; if (!src || isProjectFaviconFallbackUrl(src)) { From f46f838bf22460be5061d378723ff1c15f6d9417 Mon Sep 17 00:00:00 2001 From: Afonso Ferreira <99990310+Aforno@users.noreply.github.com> Date: Fri, 30 Oct 2026 20:53:26 +0000 Subject: [PATCH 524/817] fix(server): setup scripts follow terminal shell fallbacks (#23576) Co-authored-by: maria-rcks --- .../project/ProjectSetupScriptRunner.test.ts | 54 +++++-- .../src/project/ProjectSetupScriptRunner.ts | 138 ++++++++++-------- apps/server/src/terminal/Manager.test.ts | 115 +++++++++++++++ apps/server/src/terminal/Manager.ts | 18 ++- 4 files changed, 252 insertions(+), 73 deletions(-) diff --git a/apps/server/src/project/ProjectSetupScriptRunner.test.ts b/apps/server/src/project/ProjectSetupScriptRunner.test.ts index 29a15a6f0715b..f383436cdb439 100644 --- a/apps/server/src/project/ProjectSetupScriptRunner.test.ts +++ b/apps/server/src/project/ProjectSetupScriptRunner.test.ts @@ -1,7 +1,11 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import { describe, expect, it } from "@effect/vitest"; -import { ProjectId, type TerminalEvent, type TerminalSessionSnapshot } from "@t3tools/contracts"; -import * as HostProcess from "@t3tools/shared/HostProcess"; +import { + ProjectId, + TerminalNotRunningError, + type TerminalEvent, + type TerminalSessionSnapshot, +} from "@t3tools/contracts"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; @@ -36,6 +40,7 @@ const openSnapshot = (history: string): TerminalSessionSnapshot => ({ const makeHarness = Effect.fn(function* (options: { readonly history?: string; readonly opening?: Deferred.Deferred; + readonly shell?: string | null; }) { const listeners = new Set<(event: TerminalEvent) => Effect.Effect>(); const writes = yield* Queue.unbounded(); @@ -46,6 +51,10 @@ const makeHarness = Effect.fn(function* (options: { ? Deferred.succeed(options.opening, undefined).pipe(Effect.andThen(Effect.never)) : Effect.void ).pipe(Effect.as(openSnapshot(options.history ?? ""))), + getShell: () => + options.shell === null + ? Effect.fail(new TerminalNotRunningError({ threadId, terminalId })) + : Effect.succeed(options.shell ?? "/bin/zsh"), subscribe: (listener) => Effect.sync(() => { listeners.add(listener); @@ -66,8 +75,6 @@ const makeHarness = Effect.fn(function* (options: { NodeCrypto.layer, ), ), - Effect.provideService(HostProcess.Platform, "darwin"), - Effect.provideService(HostProcess.Environment, { SHELL: "/bin/zsh" }), ); const start = runner.runForThread({ threadId, @@ -92,7 +99,12 @@ const makeHarness = Effect.fn(function* (options: { return { start, listeners, writes, outputLines, emit }; }); -const setup = Effect.fn(function* (options: { readonly history?: string } = {}) { +const setup = Effect.fn(function* ( + options: { + readonly history?: string; + readonly shell?: string | null; + } = {}, +) { const harness = yield* makeHarness(options); const result = yield* harness.start; const completion = result.status === "started" ? result.completion : undefined; @@ -101,6 +113,15 @@ const setup = Effect.fn(function* (options: { readonly history?: string } = {}) }); describe("ProjectSetupScriptRunner", () => { + it.effect("writes immediately when the spawned fallback is PowerShell", () => + Effect.gen(function* () { + const { writes } = yield* setup({ + shell: "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", + }); + expect(yield* Queue.take(writes)).toContain("$global:LASTEXITCODE"); + }), + ); + it.effect("shows a startup prompt and types only once the line editor starts", () => Effect.gen(function* () { const { result, writes, outputLines, emit } = yield* setup(); @@ -160,13 +181,20 @@ describe("ProjectSetupScriptRunner", () => { }), ); - it.effect("does not type into a shell that exits during startup", () => - Effect.gen(function* () { - const { completion, writes, emit } = yield* setup(); - yield* emit({ ...event, type: "exited", exitCode: 1, exitSignal: null }); - expect(yield* completion).toMatchObject({ exitCode: null }); - yield* TestClock.adjust("1 minute"); - expect(yield* Queue.size(writes)).toBe(0); - }), + it.effect.each([false, true])( + "does not type into a shell that exits during startup (before shell lookup: %s)", + (beforeShellLookup) => + Effect.gen(function* () { + const { completion, writes, emit, listeners } = yield* setup( + beforeShellLookup ? { shell: null } : {}, + ); + if (!beforeShellLookup) { + yield* emit({ ...event, type: "exited", exitCode: 1, exitSignal: null }); + } + expect(yield* completion).toMatchObject({ exitCode: null }); + yield* TestClock.adjust("1 minute"); + expect(yield* Queue.size(writes)).toBe(0); + expect(listeners.size).toBe(0); + }), ); }); diff --git a/apps/server/src/project/ProjectSetupScriptRunner.ts b/apps/server/src/project/ProjectSetupScriptRunner.ts index 095f20938c8b0..ec11ce9840448 100644 --- a/apps/server/src/project/ProjectSetupScriptRunner.ts +++ b/apps/server/src/project/ProjectSetupScriptRunner.ts @@ -1,5 +1,4 @@ import { linkOriginIsFenced, ProjectId, type ProjectScript, ThreadId } from "@t3tools/contracts"; -import * as HostProcess from "@t3tools/shared/HostProcess"; import { projectScriptRuntimeEnv, projectScriptTerminalInput, @@ -107,9 +106,19 @@ export class ProjectSetupScriptProjectNotFoundError extends Schema.TaggedError

      ()( + "ProjectSetupScriptUnsupportedShellError", + { shell: Schema.String }, +) { + override get message(): string { + return "Project script completion is not supported in cmd.exe. Install PowerShell and retry."; + } +} + export const ProjectSetupScriptRunnerError = Schema.Union([ ProjectSetupScriptOperationError, ProjectSetupScriptProjectNotFoundError, + ProjectSetupScriptUnsupportedShellError, ]); export type ProjectSetupScriptRunnerError = typeof ProjectSetupScriptRunnerError.Type; @@ -159,13 +168,9 @@ function lineEditorReading(text: string, previous: boolean): boolean { type CompletionShell = "posix" | "fish" | "powershell"; -function resolveCompletionShell( - platform: NodeJS.Platform, - env: NodeJS.ProcessEnv, -): CompletionShell { - if (platform === "win32") return "powershell"; - const shell = env.SHELL ?? ""; - const name = shell.split("/").at(-1) ?? shell; +function resolveCompletionShell(shell: string): CompletionShell | null { + const name = (shell.split(/[/\\]/).at(-1) ?? shell).toLowerCase().replace(/\.exe$/, ""); + if (name === "cmd") return null; if (name === "fish") return "fish"; if (name === "pwsh" || name === "powershell") return "powershell"; return "posix"; @@ -196,10 +201,6 @@ export const make = Effect.gen(function* () { const serverSettings = yield* ServerSettings.ServerSettingsService; const crypto = yield* Crypto.Crypto; const serviceScope = yield* Effect.scope; - const completionShell = resolveCompletionShell( - yield* HostProcess.Platform, - yield* HostProcess.Environment, - ); const observeTerminalCompletion = Effect.fn("ProjectSetupScriptRunner.observeTerminalCompletion")( function* (input: { @@ -444,15 +445,7 @@ export const make = Effect.gen(function* () { const completionToken = observe ? (yield* crypto.randomUUIDv4().pipe(Effect.orDie)).replaceAll("-", "") : null; - const commandLine = - observe && completionToken - ? wrapCommandForCompletion( - script.command, - completionShell, - completionSentinel(completionToken), - ) - : script.command; - + const echoedWrapperLines: string[] = []; // Subscribe before opening so neither startup activity nor the sentinel can race the listeners. const observed = observe && completionToken @@ -461,49 +454,76 @@ export const make = Effect.gen(function* () { terminalId, sentinel: completionSentinel(completionToken), sentinelPattern: completionSentinelPattern(completionToken), - echoedWrapperLines: commandLine.split("\r").filter((line) => line.length > 0), + echoedWrapperLines, onOutputLine: observe.onOutputLine, }) : undefined; - // PowerShell has no line-editor signal; keep its immediate write. - const readiness = - completionShell === "powershell" - ? undefined - : yield* watchShellReadiness({ - threadId: input.threadId, - terminalId, - onStartupPrompt: observed?.flushPartialLine ?? Effect.void, - }); - - yield* terminalManager - .open({ - threadId: input.threadId, - terminalId, - cwd, - worktreePath: input.worktreePath, - env: { ...env, NO_COLOR: "1", FORCE_COLOR: "0" }, - }) - .pipe( - Effect.mapError( - (cause) => - new ProjectSetupScriptOperationError({ - ...errorContext, - operation: "openTerminal", - cause, - }), - ), - Effect.onError(() => - Effect.sync(() => { - observed?.unsubscribe(); - readiness?.unsubscribe(); - }), - ), - ); + const readiness = yield* watchShellReadiness({ + threadId: input.threadId, + terminalId, + onStartupPrompt: observed?.flushPartialLine ?? Effect.void, + }); + const { completionShell, commandLine } = yield* Effect.gen(function* () { + const shell = yield* terminalManager + .open({ + threadId: input.threadId, + terminalId, + cwd, + worktreePath: input.worktreePath, + env: { ...env, NO_COLOR: "1", FORCE_COLOR: "0" }, + }) + .pipe( + Effect.andThen(() => + terminalManager + .getShell({ threadId: input.threadId, terminalId }) + .pipe(Effect.catchTags({ TerminalNotRunningError: () => Effect.succeed(null) })), + ), + Effect.mapError( + (cause) => + new ProjectSetupScriptOperationError({ + ...errorContext, + operation: "openTerminal", + cause, + }), + ), + ); + if (shell === null) { + yield* observed?.abandon ?? Effect.void; + return { completionShell: null, commandLine: null }; + } + const completionShell = resolveCompletionShell(shell); + let commandLine = script.command; + if (observe && completionToken) { + if (completionShell === null) { + yield* terminalManager.closeIdle({ threadId: input.threadId, terminalId }); + return yield* new ProjectSetupScriptUnsupportedShellError({ shell }); + } + commandLine = wrapCommandForCompletion( + script.command, + completionShell, + completionSentinel(completionToken), + ); + } + echoedWrapperLines.push(...commandLine.split("\r").filter((line) => line.length > 0)); + return { completionShell, commandLine }; + }).pipe( + Effect.onError(() => + Effect.sync(() => { + observed?.unsubscribe(); + readiness.unsubscribe(); + }), + ), + ); // Return once the terminal exists so callers can show it while a startup prompt waits. - yield* (readiness?.wait ?? Effect.succeed("ready" as const)).pipe( + // PowerShell and cmd have no line-editor signal. + yield* ( + completionShell === "posix" || completionShell === "fish" + ? readiness.wait + : Effect.succeed("ready" as const) + ).pipe( Effect.flatMap((shell) => - shell === "exited" + shell === "exited" || commandLine === null ? Effect.void : terminalManager.write({ threadId: input.threadId, @@ -518,7 +538,7 @@ export const make = Effect.gen(function* () { cause, }).pipe(Effect.andThen(observed?.abandon ?? Effect.void)), ), - Effect.ensuring(Effect.sync(() => readiness?.unsubscribe())), + Effect.ensuring(Effect.sync(() => readiness.unsubscribe())), Effect.forkIn(serviceScope), ); diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index 61fe149cf8335..4afae89eb5a50 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -7,6 +7,7 @@ import { type TerminalOpenInput, ProviderDriverKind, ProviderInstanceId, + ProjectId, TerminalProviderInstanceNotFoundError, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -31,8 +32,11 @@ import * as SynchronizedRef from "effect/SynchronizedRef"; import * as TestClock from "effect/testing/TestClock"; import { expect, vi } from "vite-plus/test"; +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; import * as ProcessRunner from "../processRunner.ts"; import * as ServerSettings from "../serverSettings.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; import * as TerminalManager from "./Manager.ts"; import { terminalOutputStream } from "./OutputProtocol.ts"; import * as PtyAdapter from "@t3tools/shared/PtyAdapter"; @@ -1441,6 +1445,61 @@ it.layer( }), ); + it.effect( + "writes completion syntax for the fallback shell instead of the configured fish shell", + () => + Effect.gen(function* () { + const env = { SHELL: "/missing/fish" }; + const { manager, ptyAdapter, baseDir } = yield* createManager(5, { env }).pipe( + Effect.provide(layerWithHostPlatform("linux")), + ); + ptyAdapter.spawnFailures.push(new Error("spawn fish ENOENT")); + const written = yield* Deferred.make(); + const terminals = TerminalManager.TerminalManager.of({ + ...manager, + write: (input) => + manager.write(input).pipe(Effect.tap(() => Deferred.succeed(written, undefined))), + }); + const runner = yield* ProjectSetupScriptRunner.make.pipe( + Effect.provide( + Layer.mergeAll( + Layer.succeed(TerminalManager.TerminalManager, terminals), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getThreadShell: () => Effect.succeed(null), + }), + ServerSettings.layerTest(), + Layer.succeed(HostProcess.Platform, "linux"), + Layer.succeed(HostProcess.Environment, env), + ), + ), + ); + yield* runner.runForThread({ + threadId: "thread-setup-fallback", + worktreePath: baseDir, + project: { + id: ProjectId.make("project-setup-fallback"), + workspaceRoot: baseDir, + scripts: [ + { + id: "setup", + name: "Setup", + command: "echo setup-ready", + icon: "play", + runOnWorktreeCreate: true, + }, + ], + }, + observeCompletion: {}, + }); + const process = ptyAdapter.processes[0]!; + process.emitData("\x1b[?2004h"); + yield* Deferred.await(written); + const command = process.writes[0]!; + expect(command).toContain('"$?"'); + }), + ); + it.effect("preserves Windows Path casing when appending managed ACP binaries", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -1534,6 +1593,62 @@ it.layer( }), ); + it.effect("closes an idle cmd fallback before rejecting its completion wrapper", () => + Effect.gen(function* () { + const { manager, ptyAdapter, baseDir } = yield* createManager(5, { + env: { SystemRoot: "C:\\Windows" }, + subprocessInspector: () => + Effect.succeed({ + hasRunningSubprocess: false, + childCommand: null, + processIds: [], + }), + }).pipe(Effect.provide(layerWithHostPlatform("win32"))); + ptyAdapter.spawnFailures.push( + new Error("spawn pwsh ENOENT"), + new Error("spawn WindowsPowerShell ENOENT"), + new Error("spawn powershell ENOENT"), + ); + const runner = yield* ProjectSetupScriptRunner.make.pipe( + Effect.provide( + Layer.mergeAll( + Layer.succeed(TerminalManager.TerminalManager, manager), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getThreadShell: () => Effect.succeed(null), + }), + ServerSettings.layerTest(), + ), + ), + ); + const error = yield* runner + .runForThread({ + threadId: "thread-cmd-fallback", + worktreePath: baseDir, + project: { + id: ProjectId.make("project-cmd-fallback"), + workspaceRoot: baseDir, + scripts: [ + { + id: "setup", + name: "Setup", + command: "echo setup-ready", + icon: "play", + runOnWorktreeCreate: true, + }, + ], + }, + observeCompletion: {}, + }) + .pipe(Effect.flip); + + expect(error._tag).toBe("ProjectSetupScriptUnsupportedShellError"); + expect(ptyAdapter.spawnInputs.at(-1)?.shell).toBe("C:\\Windows\\System32\\cmd.exe"); + expect(ptyAdapter.processes[0]?.writes).toEqual([]); + expect(ptyAdapter.processes[0]?.killed).toBe(true); + }), + ); + it.effect("turns off fish terminal queries unless the user chose query-term", () => Effect.gen(function* () { for (const [platform, env, runtimeEnv, expected] of [ diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index ca93558d623ec..9e0eabc88da8a 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -172,6 +172,8 @@ export class TerminalManager extends Context.Service< input: TerminalOpenInput, ) => Effect.Effect; + readonly getShell: (input: TerminalObserveInput) => Effect.Effect; + /** * Attached viewers share one PTY sized to the smallest of them, so a narrow client * still sees the whole TUI. Streams and resizes with the same `viewerId` (one client @@ -296,6 +298,7 @@ interface TerminalSessionState { cols: number; rows: number; process: PtyAdapter.PtyProcess | null; + shell: string | null; unsubscribeData: (() => void) | null; unsubscribeExit: (() => void) | null; hasRunningSubprocess: boolean; @@ -2370,7 +2373,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func index = 0, lastError: PtyAdapter.PtySpawnError | null = null, ): Effect.fn.Return< - { process: PtyAdapter.PtyProcess; shellLabel: string }, + { process: PtyAdapter.PtyProcess; shell: string; shellLabel: string }, PtyAdapter.PtySpawnError > { if (index >= shellCandidates.length) { @@ -2413,6 +2416,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func if (attempt._tag === "Success") { return { process: attempt.success, + shell: candidate.shell, shellLabel: formatShellCandidate(candidate), }; } @@ -2441,6 +2445,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func const startingAt = yield* nowIso; yield* modifyManagerState((state) => { session.status = "starting"; + session.shell = null; session.cwd = input.cwd; session.worktreePath = input.worktreePath ?? null; session.cols = input.cols; @@ -2515,6 +2520,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func }; yield* modifyManagerState((state) => { session.process = ptyProcess; + session.shell = spawnResult.shell; session.pid = processPid; session.status = "running"; // onExit may replay an exit immediately; accept it before subscribing. @@ -2891,6 +2897,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func cols, rows, process: null, + shell: null, unsubscribeData: null, unsubscribeExit: null, hasRunningSubprocess: false, @@ -2988,6 +2995,14 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func resolveLaunchInputEnvironment(input).pipe(Effect.flatMap(openLocked)), ); + const getShell = Effect.fn("terminal.getShell")(function* (input: TerminalObserveInput) { + const session = yield* requireSession(input.threadId, input.terminalId); + if (session.status !== "running" || session.shell === null) { + return yield* new TerminalNotRunningError(input); + } + return session.shell; + }); + const openOrAttachForStream = Effect.fnUntraced(function* (requestedInput: TerminalAttachInput) { const terminalId = requestedInput.terminalId; const input = withSharedGrid(toSessionKey(requestedInput.threadId, terminalId), requestedInput); @@ -3472,6 +3487,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func return TerminalManager.of({ open, + getShell, attachStream, attachOutputStream, observeStream, From 1c99a55444b6a03ec6a056a99a44131f3e1d13fb Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Fri, 30 Oct 2026 15:53:47 -0500 Subject: [PATCH 525/817] fix(web): report invalid preview addresses (#23577) Co-authored-by: GPT-6.1 Sol --- .../preview/PreviewView.browser.test.tsx | 23 +++++++++++++---- .../src/components/preview/PreviewView.tsx | 25 +++++++++++++++++-- 2 files changed, 41 insertions(+), 7 deletions(-) diff --git a/apps/web/src/components/preview/PreviewView.browser.test.tsx b/apps/web/src/components/preview/PreviewView.browser.test.tsx index c17655db964bc..43f7845d10dbb 100644 --- a/apps/web/src/components/preview/PreviewView.browser.test.tsx +++ b/apps/web/src/components/preview/PreviewView.browser.test.tsx @@ -28,7 +28,6 @@ const mocks = vi.hoisted(() => ({ pickElement: vi.fn(), addPreviewAnnotation: vi.fn(), addImage: vi.fn(), - toast: vi.fn(), pictureInPicture: false, showEmptyState: false, loading: false, @@ -136,10 +135,6 @@ vi.mock(import("~/browser/browserRecording"), async (original) => ({ findActiveBrowserRecordingRuntimeTabId: () => mocks.recordingRuntimeTabId, useActiveBrowserRecordingTabIds: () => mocks.recordingTabIds, })); -vi.mock(import("~/components/ui/toast"), async (original) => { - const actual = await original(); - return { ...actual, toastManager: { ...actual.toastManager, add: mocks.toast } }; -}); vi.mock(import("./useDiscoveredLocalServers"), async (original) => ({ ...(await original()), useDiscoveredLocalServers: () => mocks.servers, @@ -162,6 +157,7 @@ import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId"; import { usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore"; import { dispatchPreviewAction } from "./previewActionBus"; import { PreviewView } from "./PreviewView"; +import { ToastProvider } from "~/components/ui/toast"; const TEST_THREAD_REF = { environmentId: EnvironmentId.make("environment-1"), @@ -219,6 +215,23 @@ function setup() { } describe("PreviewView", () => { + it.each(["mailto:alice@example.com", "http://"])( + "reports rejected address %s without navigating or recording it", + async (address) => { + setup(); + await using _screen = await render({view()}); + const input = page.getByPlaceholder("Search or enter URL"); + await input.fill(address); + await userEvent.keyboard("{Enter}"); + + await expect.element(page.getByText("Could not open this address")).toBeVisible(); + await expect.element(page.getByText("Enter an http or https URL.")).toBeVisible(); + expect(mocks.navigate).not.toHaveBeenCalled(); + expect(mocks.recordVisitForThread).not.toHaveBeenCalled(); + await userEvent.click(page.getByRole("button", { name: "Dismiss notification" })); + }, + ); + it("retains the annotation locally when its own environment loses access during capture", async () => { setup(); const picked = annotation("annotation-revoked"); diff --git a/apps/web/src/components/preview/PreviewView.tsx b/apps/web/src/components/preview/PreviewView.tsx index 4eed7d21bc04a..5126b18ec7a91 100644 --- a/apps/web/src/components/preview/PreviewView.tsx +++ b/apps/web/src/components/preview/PreviewView.tsx @@ -17,6 +17,7 @@ import { } from "@t3tools/contracts"; import { normalizePreviewUrl, + isPreviewUrlNormalizationError, resolveAddressBarInput, previewPdfAssetUrl, resolveSearchUrlTemplate, @@ -259,7 +260,17 @@ export function PreviewView({ if (await navigateToResolvedUrl(resolved)) { recordVisitForThread(threadRef, resolved); } - } catch {} + } catch (error) { + toastManager.add({ + type: "error", + title: "Could not open this address", + description: isPreviewUrlNormalizationError(error) + ? "Enter an http or https URL." + : error instanceof Error + ? error.message + : "An error occurred.", + }); + } }; const handleOpenServerUrl = async (next: string) => { @@ -271,7 +282,17 @@ export function PreviewView({ if (await navigateToResolvedUrl(resolved)) { recordVisitForThread(threadRef, next); } - } catch {} + } catch (error) { + toastManager.add({ + type: "error", + title: "Could not open this address", + description: isPreviewUrlNormalizationError(error) + ? "Enter an http or https URL." + : error instanceof Error + ? error.message + : "An error occurred.", + }); + } }; const handleRefresh = () => { From 200a373fbde4a41dd70c4d075a993fb079df14f4 Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Fri, 30 Oct 2026 15:54:03 -0500 Subject: [PATCH 526/817] fix(opencode): keep streamed reply text after an event stream reconnect (#23591) Co-authored-by: Claude Opus 5.5 --- .../Adapters/OpenCode2AdapterV2.test.ts | 43 +++++++++++++++++++ .../src/server/v2/adapter.ts | 15 ++++++- 2 files changed, 56 insertions(+), 2 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 37350b4925cf9..bb26a5dd53a30 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -2265,6 +2265,49 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }).pipe(Effect.scoped), ); + it.effect("continues a reply still streaming at reconnect from the text already shown", () => + Effect.gen(function* () { + const delta = (text: string) => + event("session.text.delta", { + sessionID: SESSION, + assistantMessageID: "msg_assistant_gap", + ordinal: 0, + delta: text, + }); + const { runtime, thread } = yield* resumed([ + out("session.prompt", { sessionID: SESSION, id: PROMPT_ID, text: "" }), + promptAccepted, + delta("Sent before the stream dropped"), + // OpenCode saves a block's text only when the block ends. + ...reconnected({ [SESSION]: { type: "running" } }, undefined, { + content: [{ type: "text", text: "" }], + finish: undefined, + }), + ...openRequests([]), + delta(" and after it came back."), + event("session.execution.succeeded", { sessionID: SESSION }), + ]); + const events = yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + Effect.forkScoped, + ); + yield* runtime.startTurn(turnInput(thread)); + const collected = yield* Fiber.join(events); + const texts = collected.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "assistant_message" + ? [event.turnItem.text] + : [], + ); + assert.deepEqual(texts, [ + "Sent before the stream dropped", + "Sent before the stream dropped", + "Sent before the stream dropped and after it came back.", + "Sent before the stream dropped and after it came back.", + ]); + }).pipe(Effect.scoped), + ); + it.effect("shows a permission asked while the stream was down, and answers it", () => Effect.gen(function* () { const { runtime, thread } = yield* resumed( diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 1f2dd94ca2112..91b3d62fffd37 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -2493,10 +2493,21 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr for (const message of recent.toReversed()) { if (message.type !== "assistant" || state.active !== turn) continue; const ordinals = { text: 0, reasoning: 0 }; - for (const part of message.content) { + for (const [index, part] of message.content.entries()) { if (part.type === "text" || part.type === "reasoning") { const block = { assistantMessageID: message.id, ordinal: ordinals[part.type]++ }; - yield* emitText(state, turn, block, part.type, () => part.text, true); + // OpenCode saves a block's text only when the block ends, so the last block of a + // response still streaming stays open and keeps the text that already arrived. + const open = + message.time.streamed === undefined && index === message.content.length - 1; + yield* emitText( + state, + turn, + block, + part.type, + (text) => (open && !part.text.startsWith(text) ? text : part.text), + !open, + ); continue; } if (part.type !== "tool") continue; From 9facfc59230a68be71c427d708d3ee6c2ccaa2d3 Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Fri, 30 Oct 2026 15:54:20 -0500 Subject: [PATCH 527/817] fix(opencode): apply the 3-minute limit to the whole v2 text generation (#23598) Co-authored-by: Claude Opus 5.5 --- .../OpenCode2TextGeneration.test.ts | 69 +++++++++++++++++++ .../src/server/v2/textGeneration.ts | 65 +++++++++-------- 2 files changed, 106 insertions(+), 28 deletions(-) diff --git a/apps/server/src/textGeneration/OpenCode2TextGeneration.test.ts b/apps/server/src/textGeneration/OpenCode2TextGeneration.test.ts index 775d2542d67ec..2cfe556ebf58f 100644 --- a/apps/server/src/textGeneration/OpenCode2TextGeneration.test.ts +++ b/apps/server/src/textGeneration/OpenCode2TextGeneration.test.ts @@ -1,8 +1,11 @@ import { assert, it } from "@effect/vitest"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { ProviderInstanceId } from "@t3tools/contracts"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; +import { TestClock } from "effect/testing"; import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost"; import * as OpenCode2AdapterV2Testkit from "../orchestration-v2/Adapters/OpenCode2AdapterV2.testkit.ts"; @@ -119,4 +122,70 @@ it.layer(layer)("OpenCode2TextGeneration", (it) => { assert.deepEqual(failure.cause, refusal); }).pipe(Effect.scoped), ); + + it.effect("times out when the prompt request and its interrupt never answer", () => + Effect.gen(function* () { + const [subscribe, connected, create, created] = OPENCODE2_TITLE_GENERATION; + const sessionId = "ses_f0ec85cf6ffebfalpvV2E9nocu"; + const prompted = yield* Deferred.make(); + const server = yield* OpenCode2AdapterV2Testkit.replayServer( + { + provider: "opencode", + protocol: OpenCode2AdapterV2Testkit.OPENCODE2_HTTP_PROTOCOL, + version: "2.0.18", + scenario: "opencode2_title_generation_stalled", + entries: [ + subscribe!, + connected!, + create!, + created!, + { + type: "expect_outbound", + frame: { type: "session.prompt", input: { sessionID: sessionId, text: "" } }, + }, + { + type: "emit_inbound", + frame: { type: "sdk.response", operation: "session.prompt", data: "" }, + }, + { + type: "expect_outbound", + frame: { type: "session.interrupt", input: { sessionID: sessionId } }, + }, + { + type: "emit_inbound", + frame: { type: "sdk.response", operation: "session.interrupt", data: "" }, + }, + { + type: "expect_outbound", + frame: { type: "session.remove", input: { sessionID: sessionId } }, + }, + { + type: "emit_inbound", + frame: { type: "sdk.response", operation: "session.remove", data: null }, + }, + { type: "runtime_exit", status: "success" }, + ], + }, + { onPrompt: () => Deferred.doneUnsafe(prompted, Effect.void) }, + ); + const textGeneration = yield* OpenCode2TextGeneration.make().pipe( + Effect.provideService(OpenCode2Server.OpenCode2Server, server), + ); + const generation = yield* textGeneration + .generateThreadTitle({ + cwd: process.cwd(), + message: "fix the login redirect loop after oauth", + modelSelection: { + instanceId: ProviderInstanceId.make("opencode"), + model: "opencode/big-pickle", + }, + }) + .pipe(Effect.flip, Effect.forkScoped); + yield* Deferred.await(prompted); + yield* TestClock.adjust("3 minutes"); + yield* TestClock.adjust("5 seconds"); + const failure = yield* Fiber.join(generation); + assert.equal(failure.detail, "OpenCode did not finish generating in time."); + }).pipe(Effect.scoped), + ); }); diff --git a/packages/provider-opencode/src/server/v2/textGeneration.ts b/packages/provider-opencode/src/server/v2/textGeneration.ts index ff47491e14fe1..4897b58afdc17 100644 --- a/packages/provider-opencode/src/server/v2/textGeneration.ts +++ b/packages/provider-opencode/src/server/v2/textGeneration.ts @@ -112,38 +112,47 @@ const runOnServer = Effect.fn("Opencode2TextGeneration.runOnServer")(function* ( ), Effect.forkScoped, ); - const session = yield* client.session.create({ - title: `T3 Code ${input.operation}`, - location: Location.PublicRef.make({ directory: AbsolutePath.make(input.cwd) }), - model: Model.Ref.make({ - providerID: Provider.ID.make(parsed.providerID), - id: Model.ID.make(parsed.modelID), - ...(variant === undefined ? {} : { variant: Model.VariantID.make(variant) }), - }), - permissions: GENERATION_PERMISSIONS, - }); - sessionId = session.id; - yield* Effect.addFinalizer(() => - client.session - .remove({ sessionID: session.id }) - .pipe(Effect.timeout("5 seconds"), Effect.ignore({ log: true })), - ); - const images = (input.attachments ?? []).flatMap((attachment) => { - if (attachment.type !== "image") return []; - const path = resolveAttachmentPath(attachment); - return path === null ? [] : [{ uri: `file://${path}`, name: attachment.name }]; - }); - yield* client.session.prompt({ - sessionID: session.id, - text: input.prompt, - ...(images.length === 0 ? {} : { files: images }), + // The limit covers creating the session and sending the prompt as well, since + // either request can stall while the event stream stays connected. + const generate = Effect.gen(function* () { + const session = yield* client.session.create({ + title: `T3 Code ${input.operation}`, + location: Location.PublicRef.make({ directory: AbsolutePath.make(input.cwd) }), + model: Model.Ref.make({ + providerID: Provider.ID.make(parsed.providerID), + id: Model.ID.make(parsed.modelID), + ...(variant === undefined ? {} : { variant: Model.VariantID.make(variant) }), + }), + permissions: GENERATION_PERMISSIONS, + }); + sessionId = session.id; + yield* Effect.addFinalizer(() => + client.session + .remove({ sessionID: session.id }) + .pipe(Effect.timeout("5 seconds"), Effect.ignore({ log: true })), + ); + const images = (input.attachments ?? []).flatMap((attachment) => { + if (attachment.type !== "image") return []; + const path = resolveAttachmentPath(attachment); + return path === null ? [] : [{ uri: `file://${path}`, name: attachment.name }]; + }); + yield* client.session.prompt({ + sessionID: session.id, + text: input.prompt, + ...(images.length === 0 ? {} : { files: images }), + }); + return yield* Deferred.await(outcome); }); - const result = yield* Deferred.await(outcome).pipe( + const result = yield* generate.pipe( Effect.timeoutOrElse({ duration: GENERATION_TIMEOUT, orElse: () => - client.session.interrupt({ sessionID: Session.ID.make(session.id) }).pipe( - Effect.ignore, + (sessionId === undefined + ? Effect.void + : client.session + .interrupt({ sessionID: Session.ID.make(sessionId) }) + .pipe(Effect.timeout("5 seconds"), Effect.ignore) + ).pipe( Effect.as({ _tag: "failed", detail: "OpenCode did not finish generating in time.", From 72986b483ad5913cdbc1147017cd5fb7d541a9b4 Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Fri, 30 Oct 2026 15:54:36 -0500 Subject: [PATCH 528/817] fix(mobile): show draft review comments inline and in the count (#23602) Co-authored-by: GPT-6.1 Sol Co-authored-by: maria-rcks --- .../src/features/review/ReviewSheet.tsx | 3 +- .../review/reviewCommentSelection.test.ts | 72 +++++++++++++++++++ .../features/review/reviewCommentSelection.ts | 42 +++++++++-- .../src/features/review/useReviewDiffData.ts | 10 +-- .../src/state/use-thread-composer-state.ts | 1 + 5 files changed, 117 insertions(+), 11 deletions(-) diff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx index 18908302d577e..359ea229cb8cc 100644 --- a/apps/mobile/src/features/review/ReviewSheet.tsx +++ b/apps/mobile/src/features/review/ReviewSheet.tsx @@ -435,7 +435,7 @@ export function ReviewSheet(props: ReviewSheetProps) { const environment = useEnvironmentPresentation(environmentId); const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry"); const isEnvironmentReady = environment.presentation?.connection.phase === "connected"; - const { draftMessage } = useThreadDraftForThread({ environmentId, threadId }); + const { draftMessage, draftContext } = useThreadDraftForThread({ environmentId, threadId }); const reviewCache = useReviewCacheForThread({ environmentId, threadId }); const { selectedThreadCwd } = useSelectedThreadWorktree(); const columnMetrics = useNativeColumnLayoutMetrics(); @@ -475,6 +475,7 @@ export function ReviewSheet(props: ReviewSheetProps) { cwd: selectedThreadCwd, selectedSection, draftMessage, + draftContext, }); // Expo may return null before registration or in older binaries; use the fallback. const NativeReviewDiffView = resolveNativeReviewDiffView(); diff --git a/apps/mobile/src/features/review/reviewCommentSelection.test.ts b/apps/mobile/src/features/review/reviewCommentSelection.test.ts index 59a0bb6bcb683..81eb0bba4083a 100644 --- a/apps/mobile/src/features/review/reviewCommentSelection.test.ts +++ b/apps/mobile/src/features/review/reviewCommentSelection.test.ts @@ -1,4 +1,8 @@ import { describe, expect, it } from "vite-plus/test"; +import { upgradeLegacyContextMessage } from "@t3tools/shared/composerContextLegacy"; +import { formatComposerContextReference } from "@t3tools/shared/composerContextReferences"; + +import { pullRequestComposerContext } from "../../lib/composerContext"; import { clearReviewCommentTarget, @@ -50,6 +54,74 @@ function makeTarget(): ReviewCommentTarget { } describe("review comment serialization", () => { + it("excludes a linked pull request chip from draft review comments", () => { + const record = pullRequestComposerContext( + { + number: 42, + title: "Fix checkout", + url: "https://github.com/example/repo/pull/42", + headBranch: "fix-checkout", + baseBranch: "main", + state: "open", + isDraft: false, + }, + "pr-42", + ); + + expect( + parseReviewInlineComments(formatComposerContextReference(record), { + version: 1, + records: [record], + }), + ).toEqual([]); + }); + + it("reads an added review comment after the composer upgrades it to a context chip", () => { + const upgraded = upgradeLegacyContextMessage( + formatReviewCommentContext(makeTarget(), "Please keep this configurable."), + ); + const comments = parseReviewInlineComments(upgraded.text, { + version: 1, + records: upgraded.records, + }); + + expect(comments).toEqual([ + { + id: upgraded.records[0]!.contextId, + sectionId: "section-1", + sectionTitle: "Working tree", + filePath: "apps/demo/src/main.ts", + startIndex: 0, + endIndex: 1, + rangeLabel: "7", + text: "Please keep this configurable.", + diff: "@@ -7,1 +7,1 @@\n-const retryLimit = 2;\n+const retryLimit = 4;", + fenceLanguage: "diff", + }, + ]); + }); + + it("keeps legacy comments and counts a typed comment only while its chip is present", () => { + const upgraded = upgradeLegacyContextMessage( + formatReviewCommentContext(makeTarget(), "Typed comment"), + ); + const context = { version: 1, records: upgraded.records } as const; + const legacy = formatReviewCommentContext(makeTarget(), "Legacy comment"); + const comments = parseReviewInlineComments( + `${legacy}\n${upgraded.text}\n${upgraded.text}`, + context, + ); + + expect(comments.map((comment) => comment.text)).toEqual(["Legacy comment", "Typed comment"]); + expect(parseReviewInlineComments(legacy, context).map((comment) => comment.text)).toEqual([ + "Legacy comment", + ]); + expect(parseReviewInlineComments("", context)).toEqual([]); + expect( + parseReviewInlineComments(upgraded.text.replace("/review-comment/", "/mention/"), context), + ).toEqual([]); + }); + it("keeps closing-tag text inside a chip label within a real review body", () => { const body = "Before [](t3-context://v1/mention/context-1) after"; const serialized = `${body}`; diff --git a/apps/mobile/src/features/review/reviewCommentSelection.ts b/apps/mobile/src/features/review/reviewCommentSelection.ts index 4e3b22407f5a0..70f226d604e04 100644 --- a/apps/mobile/src/features/review/reviewCommentSelection.ts +++ b/apps/mobile/src/features/review/reviewCommentSelection.ts @@ -1,5 +1,9 @@ import { useSyncExternalStore } from "react"; -import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; +import type { OrchestrationMessageContext } from "@t3tools/contracts"; +import { + collectComposerContextReferences, + replaceComposerContextReferences, +} from "@t3tools/shared/composerContextReferences"; import type { ReviewRenderableLineRow } from "./reviewModel"; @@ -357,11 +361,10 @@ export function formatReviewCommentContext(target: ReviewCommentTarget, comment: ].join("\n"); } -export function countReviewCommentContexts(value: string): number { - return Array.from(value.matchAll(/ { +export function parseReviewInlineComments( + value: string, + context?: OrchestrationMessageContext, +): ReadonlyArray { const comments: ReviewInlineComment[] = []; // Mask chip delimiters: labels containing would otherwise truncate the block. const masked = replaceComposerContextReferences(value, (reference) => @@ -385,6 +388,33 @@ export function parseReviewInlineComments(value: string): ReadonlyArray reference.kind === "review-comment") + .map((reference) => reference.contextId), + ); + for (const record of context?.records ?? []) { + if ( + record.kind !== "review-comment" || + "payload" in record || + record.sectionId.startsWith("pull-request:") || + !referencedIds.has(record.contextId) + ) { + continue; + } + comments.push({ + id: record.contextId, + sectionId: record.sectionId, + sectionTitle: record.sectionTitle, + filePath: record.filePath, + startIndex: record.startIndex, + endIndex: record.endIndex, + rangeLabel: record.rangeLabel, + text: record.text, + diff: record.diff, + ...(record.fenceLanguage !== undefined ? { fenceLanguage: record.fenceLanguage } : {}), + }); + } return comments; } diff --git a/apps/mobile/src/features/review/useReviewDiffData.ts b/apps/mobile/src/features/review/useReviewDiffData.ts index 6ccc5ae3f495c..d9ec656cbc773 100644 --- a/apps/mobile/src/features/review/useReviewDiffData.ts +++ b/apps/mobile/src/features/review/useReviewDiffData.ts @@ -1,7 +1,7 @@ import { useCallback, useContext, useEffect, useMemo, useState } from "react"; import { formatDiffCount } from "@t3tools/client-runtime/diff-count"; -import { countReviewCommentContexts, parseReviewInlineComments } from "./reviewCommentSelection"; +import { parseReviewInlineComments } from "./reviewCommentSelection"; import { getCachedNativeReviewDiffData } from "./nativeReviewDiffAdapter"; import { getCachedReviewParsedDiff } from "./reviewState"; import { @@ -14,6 +14,7 @@ import { import type { EnvironmentId, + OrchestrationMessageContext, ReviewDiffFileStat, ReviewDiffPreviewSource, } from "@t3tools/contracts"; @@ -126,8 +127,9 @@ export function useReviewDiffData(input: { readonly cwd: string | null; readonly selectedSection: ReviewSectionItem | null; readonly draftMessage: string; + readonly draftContext: OrchestrationMessageContext | undefined; }) { - const { draftMessage, selectedSection, threadKey } = input; + const { draftMessage, draftContext, selectedSection, threadKey } = input; const selectedSectionId = selectedSection?.id ?? null; const source = selectedSection?.source; const lazySource = source?.truncated && source.files ? source : null; @@ -230,7 +232,7 @@ export function useReviewDiffData(input: { () => formatHeaderDiffSummary(parsedDiff, selectedSection?.files), [parsedDiff, selectedSection?.files], ); - const inlineReviewComments = parseReviewInlineComments(draftMessage); + const inlineReviewComments = parseReviewInlineComments(draftMessage, draftContext); const selectedSectionInlineComments = useMemo(() => { if (!selectedSectionId || inlineReviewComments.length === 0) { return EMPTY_INLINE_REVIEW_COMMENTS; @@ -241,7 +243,7 @@ export function useReviewDiffData(input: { parsedDiff, comments: selectedSectionInlineComments, }); - const pendingReviewCommentCount = countReviewCommentContexts(draftMessage); + const pendingReviewCommentCount = inlineReviewComments.length; // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- records review perf marks and diagnostic logs once a parsed diff has committed useEffect(() => { diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index 9056bc20937fa..3926b2f781f5d 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -164,6 +164,7 @@ export function useThreadDraftForThread(input: { return { draftMessage: draft.text, + draftContext: draft.context, draftAttachments: draft.attachments, }; } From 2b98f54fc05256b7158bb23fd8f1ab4c4112059e Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Fri, 30 Oct 2026 15:55:37 -0500 Subject: [PATCH 529/817] fix(github): expand pull request context from the merge base (#23638) Co-authored-by: Claude Opus 5.5 --- .../src/server/GitHubPullRequestApi.test.ts | 31 ++++++++++++++++++ .../src/server/GitHubPullRequestApi.ts | 32 ++++++++++++++++++- 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts index 78deffdfaeb10..5a5c46f28d99a 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts @@ -574,6 +574,7 @@ const checkContextsPage = ( }); const pullRequestRefs = encodeJson({ base: { sha: "a1b2c3d" }, head: { sha: "b1c2d3e" } }); +const pullRequestMergeBase = encodeJson({ merge_base_commit: { sha: "c1d2e3f" } }); const crossRepositoryDetail = (headRefOid = "abc123") => coreResponse({ @@ -2856,6 +2857,34 @@ layer("GitHubPullRequestApi.layer", (it) => { }), ); + it.effect("expands a pull request file from its merge base, not the moved base tip", () => + Effect.gen(function* () { + const answers: Record = { + "repos/acme/web/pulls/7": pullRequestRefs, + "repos/acme/web/compare/a1b2c3d...b1c2d3e?per_page=1&page=2": pullRequestMergeBase, + "repos/acme/web/contents/src/a.ts?ref=a1b2c3d": "base tip\n", + "repos/acme/web/contents/src/a.ts?ref=c1d2e3f": "merge base\n", + "repos/acme/web/contents/src/a.ts?ref=b1c2d3e": "head\n", + }; + mockedExecute.mockImplementation((call) => + Effect.succeed(output(call.kind === "rest" ? (answers[call.path] ?? "") : "")), + ); + const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi; + + const contents = yield* cli.getPullRequestDiffFileContents({ + cwd: "/w", + repository: "acme/web", + host: "github.com", + number: 7, + changeType: "change", + oldPath: "src/a.ts", + newPath: "src/a.ts", + }); + + expect(contents).toEqual({ oldContents: "merge base\n", newContents: "head\n" }); + }), + ); + it.effect("reports unusable diff revisions as a structured error", () => Effect.gen(function* () { mockedExecute.mockReturnValueOnce(Effect.succeed(output("not-a-sha\tstill-not-a-sha\n"))); @@ -2885,6 +2914,7 @@ layer("GitHubPullRequestApi.layer", (it) => { it.effect("reports undecodable diff file contents as binary", () => Effect.gen(function* () { mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequestRefs))); + mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequestMergeBase))); mockedExecute.mockReturnValueOnce(Effect.succeed(output("binary�contents", false, true))); const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi; @@ -2911,6 +2941,7 @@ layer("GitHubPullRequestApi.layer", (it) => { it.effect("returns valid text containing a literal replacement character", () => Effect.gen(function* () { mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequestRefs))); + mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequestMergeBase))); mockedExecute.mockReturnValueOnce(Effect.succeed(output("before�after"))); const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi; diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.ts index b812fd7682eaf..2defbb6684919 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.ts @@ -863,6 +863,13 @@ const decodeRevisionRefs = Schema.decodeUnknownOption( ), ); +/** Where a pull request's head forked off its base, the commit its patch is computed from. */ +const decodeMergeBase = Schema.decodeUnknownOption( + Schema.fromJsonString( + Schema.Struct({ merge_base_commit: Schema.Struct({ sha: Schema.String }) }), + ), +); + const GRAPHQL_MERGE_METHODS = { merge: "MERGE", squash: "SQUASH", @@ -1299,6 +1306,29 @@ export const make = Effect.gen(function* () { ...(input.commit === undefined ? {} : { commit: input.commit }), }); } + // A pull request's patch runs from the merge base, and the base branch may have moved on + // since, so its old side is read there. Page 2 of a compare leaves out the file list; a + // failed read falls back to the base branch tip. + const oldRef = + input.commit === undefined && input.changeType !== "new" + ? yield* api + .rest({ + host: input.host, + operation: "getPullRequestDiffFileContents", + path: `repos/${owner}/${name}/compare/${baseRef}...${headRef}?per_page=1&page=2`, + timeout: DIFF_TIMEOUT, + }) + .pipe( + Effect.map((response) => + decodeMergeBase(response.body).pipe( + Option.map((compare) => compare.merge_base_commit.sha), + Option.filter(isCommitSha), + Option.getOrElse(() => baseRef ?? ""), + ), + ), + Effect.orElseSucceed(() => baseRef ?? ""), + ) + : (baseRef ?? ""); const readFile = (revision: string, filePath: string) => api @@ -1329,7 +1359,7 @@ export const make = Effect.gen(function* () { const [oldContents, newContents] = yield* Effect.all( [ - input.changeType === "new" ? Effect.succeed("") : readFile(baseRef ?? "", input.oldPath), + input.changeType === "new" ? Effect.succeed("") : readFile(oldRef, input.oldPath), input.changeType === "deleted" ? Effect.succeed("") : readFile(headRef, input.newPath), ], { concurrency: 2 }, From 353cf7b519251bb073515e337d23be9eea93a05a Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Fri, 30 Oct 2026 15:55:55 -0500 Subject: [PATCH 530/817] fix(web): show project action edit buttons on touch screens (#23640) Co-authored-by: GPT-6.1 Sol --- apps/web/src/components/settings/ProjectActionsList.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/src/components/settings/ProjectActionsList.tsx b/apps/web/src/components/settings/ProjectActionsList.tsx index cc19de17746be..f30b90c184ba2 100644 --- a/apps/web/src/components/settings/ProjectActionsList.tsx +++ b/apps/web/src/components/settings/ProjectActionsList.tsx @@ -56,7 +56,7 @@ export function ProjectActionsList({ {shortcutLabel ? ( {shortcutLabel} ) : null} - +