From 3d8a02371b361a3e0096782d8b26c78a0e62bdcd Mon Sep 17 00:00:00 2001 From: Turner Monroe Date: Sat, 21 Nov 2026 13:16:29 +0100 Subject: [PATCH 001/139] fix(forgejo): issue links on a self-hosted Forgejo hostname resolve (#40271) Co-authored-by: Julius Marminge --- apps/server/src/issue/IssueService.test.ts | 18 ++++++++++++++++++ .../src/shared/definition.ts | 6 ++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/apps/server/src/issue/IssueService.test.ts b/apps/server/src/issue/IssueService.test.ts index 231559e9eb4df..a291d5bee11f7 100644 --- a/apps/server/src/issue/IssueService.test.ts +++ b/apps/server/src/issue/IssueService.test.ts @@ -283,6 +283,24 @@ describe("IssueService", () => { yield* enterprise.resolveUrl("https://code.acme.test/acme/web/issues/7"), ).toMatchObject({ projectId: "ghes", host: "code.acme.test", key: "7", writable: true }); + // The same holds for a self-hosted Forgejo. + const forgejo = yield* makeService({ + projects: [ + project({ + id: "forge", + repository: "acme/web", + provider: "forgejo", + host: "code.acme.test", + }), + ], + trackers: [fakeTracker({ kind: IssueTrackerKind.make("forgejo") })], + }); + expect(yield* forgejo.resolveUrl("https://code.acme.test/acme/web/issues/7")).toMatchObject({ + projectId: "forge", + host: "code.acme.test", + key: "7", + }); + // A fork lists its upstream's issues and its own, counted once, and may write to both. const fork = project({ id: "fork", repository: "acme/web" }); const forked = yield* makeService({ diff --git a/packages/source-control-forgejo/src/shared/definition.ts b/packages/source-control-forgejo/src/shared/definition.ts index 73bd2caa8ae8f..1f0b67fc4ccbc 100644 --- a/packages/source-control-forgejo/src/shared/definition.ts +++ b/packages/source-control-forgejo/src/shared/definition.ts @@ -99,8 +99,10 @@ export const definition = defineSourceControl({ const link = parseChangeRequestPath(url, CHANGE_REQUEST_PATH); return link === null ? null : { ...link, authority: url.host.toLowerCase() }; }, - // `/issues/` is too generic a path to believe from a host not named after Forgejo or Gitea. - parseIssueUrl: (url) => (isForgejoHost(url.hostname) ? parseIssuePath(url, ISSUE_PATH) : null), + // `/issues/` is too generic a path to believe from a host not named after Forgejo or Gitea, + // unless a Forgejo project on that host vouches for it. + parseIssueUrl: (url, known) => + known || isForgejoHost(url.hostname) ? parseIssuePath(url, ISSUE_PATH) : null, changeRequestUrlFromReferenceAutolink: () => null, commitUrl: (input) => buildCommitUrl(input, "commit"), parseCommitUrl: (url) => parseCommitPath(url, COMMIT_PATH), From 47525fa3d6bca7cc1ad66404d42de90cc6785e91 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 04:31:08 -0800 Subject: [PATCH 002/139] fix(web): switching threads no longer restarts the Changes and git status reads (#40215) --- apps/web/src/components/ChatView.tsx | 42 +++++-- apps/web/src/components/DiffPanel.tsx | 12 +- apps/web/src/components/GitActionsControl.tsx | 14 +-- .../chat/RightPanelSurfaceContent.tsx | 4 +- .../src/hooks/useWorkspaceRevision.test.ts | 51 ++++++++ apps/web/src/hooks/useWorkspaceRevision.ts | 68 +++++++++++ apps/web/src/state/revisionedQuery.test.ts | 110 +++++++++++++++++- apps/web/src/state/revisionedQuery.ts | 73 ++++++++---- 8 files changed, 327 insertions(+), 47 deletions(-) create mode 100644 apps/web/src/hooks/useWorkspaceRevision.test.ts create mode 100644 apps/web/src/hooks/useWorkspaceRevision.ts diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 0cf9138843010..77c47d668daf4 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -168,7 +168,7 @@ import { isLatestRunSettled, } from "../session-logic"; import { type LegendListRef } from "@legendapp/list/react"; -import { useWorkspaceMutationRefresh } from "../hooks/useWorkspaceMutationRefresh"; +import { useWorkspaceRevision } from "../hooks/useWorkspaceRevision"; import { DEFAULT_INTERACTION_MODE, type ChatMessage } from "../types"; import { buildThreadRouteParams } from "../threadRoutes"; import { useTheme } from "../hooks/useTheme"; @@ -261,6 +261,7 @@ import { collectInlineContextIds } from "../lib/composerContextReferences"; import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore"; import { useKnownTerminalSessions, useThreadRunningTerminalIds } from "../state/terminalSessions"; import { useEnvironmentQueryRefresh } from "../state/query"; +import { revisionedQuery } from "../state/revisionedQuery"; import { useEnvironmentScope } from "~/state/session"; import { primaryServerKeybindingsAtom, serverEnvironment } from "../state/server"; import { hostEnvironmentIdAtom } from "../state/primaryEnvironment"; @@ -395,7 +396,7 @@ import { ChatRightPanel } from "./chat/ChatRightPanel"; import { useDraftEnvironmentRouting } from "./chat/useDraftEnvironmentRouting"; import { branchMismatchBannerItem, extensionStatusBannerItem } from "./chat/ThreadActivityBanners"; import { ThreadNow } from "./chat/ThreadNow"; -import type { ThreadStructure } from "@t3tools/client-runtime/state/shell"; +import { threadRuntimeIsActive, type ThreadStructure } from "@t3tools/client-runtime/state/shell"; import { useDelayedStatus } from "../hooks/useDelayedStatus"; import { useTimelineFollow } from "./chat/useTimelineFollow"; import { @@ -1716,16 +1717,36 @@ export default function ChatView(props: ChatViewProps) { environmentId, input: { cwd: gitStatusCwd }, }); + const workspaceRevision = useWorkspaceRevision({ + threadKey: activeThreadKey, + // A running thread can change the workspace after this visit's reads began. + unloaded: + routeThreadDetailRef !== null && + threadStatus !== "live" && + threadStatus !== "deleted" && + !threadRuntimeIsActive(serverThreadShell?.runtime), + mutationId: workspaceMutationId, + }); + // Per thread: opening a thread with workspace changes reads a cached status again. + const gitStatusRevision = + workspaceRevision.revision === null + ? undefined + : `${activeThreadKey ?? ""}\u0000${workspaceRevision.revision}`; const gitStatusQuery = { - data: useAtomValue(gitStatusAtom ? chatGitStatusAtom(gitStatusAtom) : NO_CHAT_GIT_STATUS_ATOM), + data: useAtomValue( + gitStatusAtom + ? chatGitStatusAtom( + workspaceRevision.pending + ? revisionedQuery(gitStatusAtom, undefined, { startedUnder: gitStatusRevision }) + : revisionedQuery( + gitStatusAtom, + workspaceMutationId === null ? undefined : gitStatusRevision, + ), + ) + : NO_CHAT_GIT_STATUS_ATOM, + ), refresh: useEnvironmentQueryRefresh(gitStatusAtom).refresh, }; - useWorkspaceMutationRefresh({ - enabled: gitStatusCwd !== null, - mutationId: workspaceMutationId, - refresh: gitStatusQuery.refresh, - resourceKey: `git-status:${activeThreadKey ?? ""}:${gitStatusCwd ?? ""}`, - }); const keybindings = useAtomValue(primaryServerKeybindingsAtom); const backgroundThread = use(BackgroundThreadContext); const scriptKeybindings = @@ -3359,6 +3380,7 @@ export default function ChatView(props: ChatViewProps) { keybindings={keybindings} configuredPreviewUrls={configuredPreviewUrls} workspaceMutationId={workspaceMutationId} + workspaceRevision={workspaceRevision.revision} getShortcutContext={getShortcutContextStable} onSendAnnotation={sendPreviewAnnotationStable} onCloseSurface={closeRightPanelSurface} @@ -4039,7 +4061,7 @@ export default function ChatView(props: ChatViewProps) { ) } gitCwd={gitCwd} - workspaceMutationId={workspaceMutationId} + workspaceMutationId={workspaceRevision.revision} isGitRepo={isGitRepo} envLocked={envLocked} availableEnvironments={logicalProjectEnvironments} diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index c6460fabc53d2..561bcd2b3e040 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -105,7 +105,7 @@ import { DropdownMenuTrigger, } from "./ui/menu"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; -import { useEnvironmentQuery } from "../state/query"; +import { useEnvironmentQuery, useEnvironmentQueryRefresh } from "../state/query"; import { useAtomCommand } from "../state/use-atom-command"; import { serverEnvironment } from "../state/server"; import { reviewEnvironment } from "../state/review"; @@ -459,7 +459,7 @@ export default function DiffPanel({ const canRefreshGitDiff = isGitRepo && isGitSelection && activeThread != null && gitCwd != 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( + const branchDiffPreviewAtom = branchDiffPreviewInput && activeThread ? revisionedQuery( reviewEnvironment.diffPreview({ @@ -468,9 +468,9 @@ export default function DiffPanel({ }), canRefreshGitDiff ? workspaceMutationId : undefined, ) - : null, - messages, - ); + : null; + const branchDiffPreview = useEnvironmentQuery(branchDiffPreviewAtom, messages); + const branchDiffPreviewIsPending = useEnvironmentQueryRefresh(branchDiffPreviewAtom).isPending; const branchCommitsQuery = useEnvironmentQuery( visible && isGitRepo && canReadFiles && activeThread && gitCwd ? reviewEnvironment.branchCommits({ @@ -728,6 +728,8 @@ export default function DiffPanel({ useLiveRefresh( branchDiffPreview.data !== null && !branchDiffPreview.isPending ? () => { + // A read that began after this render, as a thread switch's, is that revalidation. + if (branchDiffPreviewIsPending()) return; if (Date.now() - branchDiffPreview.dataUpdatedAt < LIVE_REFRESH_MIN_INTERVAL_MS) return; refreshBranchDiffPreview(); } diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index d1fef4ad5a617..1c42f176d89b4 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -1071,12 +1071,11 @@ function CheckoutGitActionsControl({ const ignoreWhitespace = useDiffPanelSessionStore((state) => state.ignoreWhitespace) ?? ignoreWhitespaceSetting; const { canReadFiles } = useFilesystemReadAccess(activeEnvironmentId, messages); - // Same input as the Diff panel's branch query, so both read one cached result. Status - // totals join the revision because edits, pulls and resets outside a turn leave the mutation - // id as is. - const changesRevision = gitStatusForActions + // Same input and workspace revision as the Diff panel's branch query, so both read one + // cached result. Status totals are this reader's own revision because edits, pulls and + // resets outside a turn leave the mutation id as is. + const changesStatusRevision = gitStatusForActions ? JSON.stringify([ - workspaceMutationId, gitStatusForActions.refName, gitStatusForActions.workingTree.insertions, gitStatusForActions.workingTree.deletions, @@ -1089,7 +1088,7 @@ function CheckoutGitActionsControl({ showChanges && isRepo && canReadFiles && - changesRevision !== null && + changesStatusRevision !== null && activeEnvironmentId !== null && gitCwd !== null ? revisionedQuery( @@ -1103,7 +1102,8 @@ function CheckoutGitActionsControl({ sourceKind: "branch-range", }, }), - changesRevision, + workspaceMutationId, + { detail: changesStatusRevision }, ) : null, ); diff --git a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx index 22ef904e2c13f..076c78d88d468 100644 --- a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx +++ b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx @@ -73,6 +73,8 @@ export function RightPanelSurfaceContent(props: { readonly keybindings: ResolvedKeybindingsConfig; readonly configuredPreviewUrls: ReadonlyArray; readonly workspaceMutationId: string | null; + /** What the diff is read under, as the Changes totals are; see `useWorkspaceRevision`. */ + readonly workspaceRevision: string | null; readonly getShortcutContext: () => ShortcutMatchContext; readonly onSendAnnotation: ( annotation: PreviewAnnotationPayload, @@ -118,7 +120,7 @@ export function RightPanelSurfaceContent(props: { key={scopedThreadKey(threadRef)} mode="embedded" composerDraftTarget={props.composerDraftTarget} - workspaceMutationId={props.workspaceMutationId} + workspaceMutationId={props.workspaceRevision} visible={visible} /> diff --git a/apps/web/src/hooks/useWorkspaceRevision.test.ts b/apps/web/src/hooks/useWorkspaceRevision.test.ts new file mode 100644 index 0000000000000..36f2c769bf425 --- /dev/null +++ b/apps/web/src/hooks/useWorkspaceRevision.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { advanceWorkspaceVisit, workspaceRevisionOf } from "./useWorkspaceRevision"; + +function visitThread(threadKey: string, unloaded: boolean, mutationId: string | null) { + let visit = advanceWorkspaceVisit(null, { threadKey, unloaded, mutationId }, "view"); + return (next: { unloaded: boolean; mutationId: string | null }) => { + visit = advanceWorkspaceVisit(visit, { threadKey, ...next }, "view"); + return workspaceRevisionOf(visit, next.mutationId); + }; +} + +describe("workspace revision", () => { + it("keeps the visit's revision for the mutation id the history loads with, not for a later one", () => { + const render = visitThread("thread-b", true, null); + const pending = render({ unloaded: true, mutationId: null }); + expect(pending.pending).toBe(true); + expect(pending.revision).not.toBeNull(); + + expect(render({ unloaded: false, mutationId: "b1" })).toEqual({ + revision: pending.revision, + pending: false, + }); + expect(render({ unloaded: false, mutationId: "b2" }).revision).toBe("b2"); + expect(render({ unloaded: false, mutationId: "b1" }).revision).toBe(pending.revision); + }); + + it("treats the first mutation of a thread whose history loaded without one as a change", () => { + const render = visitThread("thread-b", true, null); + const loaded = render({ unloaded: false, mutationId: null }); + expect(loaded.revision).not.toBeNull(); + expect(render({ unloaded: false, mutationId: "b1" }).revision).toBe("b1"); + }); + + it("is the mutation id when the visit began with the history known", () => { + const render = visitThread("thread-b", false, "b1"); + expect(render({ unloaded: false, mutationId: "b1" })).toEqual({ + revision: "b1", + pending: false, + }); + }); + + it("starts over, under another revision, for another thread and for a later visit", () => { + const input = { unloaded: true, mutationId: null }; + const first = advanceWorkspaceVisit(null, { threadKey: "thread-a", ...input }, "view"); + const second = advanceWorkspaceVisit(first, { threadKey: "thread-b", ...input }, "view"); + const again = advanceWorkspaceVisit(second, { threadKey: "thread-a", ...input }, "view"); + expect(new Set([first.revision, second.revision, again.revision]).size).toBe(3); + expect(workspaceRevisionOf(again, null).pending).toBe(true); + }); +}); diff --git a/apps/web/src/hooks/useWorkspaceRevision.ts b/apps/web/src/hooks/useWorkspaceRevision.ts new file mode 100644 index 0000000000000..cfbb4033043e6 --- /dev/null +++ b/apps/web/src/hooks/useWorkspaceRevision.ts @@ -0,0 +1,68 @@ +import { useId, useState } from "react"; + +interface WorkspaceVisit { + readonly threadKey: string | null; + readonly visit: number; + /** The revision this visit's reads start under. */ + readonly revision: string; + /** Whether this visit's reads cover the mutation id the history will load with. */ + readonly awaitsBaseline: boolean; + /** The mutation id the history loaded with; `undefined` until it loads. */ + readonly baseline: string | null | undefined; +} + +interface WorkspaceVisitInput { + readonly threadKey: string | null; + /** A settled server thread whose history is not synchronized yet. */ + readonly unloaded: boolean; + readonly mutationId: string | null; +} + +export interface WorkspaceRevision { + /** What workspace queries are read under; changes only when the workspace may have. */ + readonly revision: string | null; + /** The history is not synchronized: the mutation id is unknown, not absent. */ + readonly pending: boolean; +} + +export function advanceWorkspaceVisit( + visit: WorkspaceVisit | null, + input: WorkspaceVisitInput, + instanceId: string, +): WorkspaceVisit { + if (visit === null || visit.threadKey !== input.threadKey) { + const next = (visit?.visit ?? 0) + 1; + return { + threadKey: input.threadKey, + visit: next, + revision: `visit:${instanceId}:${next}:${input.threadKey ?? ""}`, + awaitsBaseline: input.unloaded, + baseline: undefined, + }; + } + return visit.awaitsBaseline && visit.baseline === undefined && !input.unloaded + ? { ...visit, baseline: input.mutationId } + : visit; +} + +export function workspaceRevisionOf( + visit: WorkspaceVisit, + mutationId: string | null, +): WorkspaceRevision { + if (!visit.awaitsBaseline) return { revision: mutationId, pending: false }; + if (visit.baseline === undefined) return { revision: visit.revision, pending: true }; + return { revision: mutationId === visit.baseline ? visit.revision : mutationId, pending: false }; +} + +/** + * The revision a thread's workspace queries are read under. The mutation id a thread's history + * loads with was made before the visit began, so the reads the visit already started cover it: + * the visit keeps one revision of its own until an id replaces that one. + */ +export function useWorkspaceRevision(input: WorkspaceVisitInput): WorkspaceRevision { + const instanceId = useId(); + const [visit, setVisit] = useState(() => advanceWorkspaceVisit(null, input, instanceId)); + const current = advanceWorkspaceVisit(visit, input, instanceId); + if (current !== visit) setVisit(current); + return workspaceRevisionOf(current, input.mutationId); +} diff --git a/apps/web/src/state/revisionedQuery.test.ts b/apps/web/src/state/revisionedQuery.test.ts index 7b21dd1d29aee..acc148af5bd10 100644 --- a/apps/web/src/state/revisionedQuery.test.ts +++ b/apps/web/src/state/revisionedQuery.test.ts @@ -1,6 +1,8 @@ +import * as Effect from "effect/Effect"; import { Atom, AtomRegistry } from "effect/reactivity"; import { describe, expect, it } from "vite-plus/test"; +import { advanceWorkspaceVisit, workspaceRevisionOf } from "../hooks/useWorkspaceRevision"; import { revisionedQuery } from "./revisionedQuery"; // A stand-in query that counts its fetches. @@ -21,8 +23,11 @@ function setup(readQuery: (cache: Atom.Atom) => Atom.Atom = (cac return fetches; }).pipe(Atom.keepAlive), ); - const mount = async (revision: string | null | undefined) => { - const release = registry.mount(revisionedQuery(query, revision)); + const mount = async ( + revision: string | null | undefined, + options?: Parameters[2], + ) => { + const release = registry.mount(revisionedQuery(query, revision, options)); // A stale read refetches in a microtask, after the render that read it. await Promise.resolve(); return () => { @@ -128,4 +133,105 @@ describe("revisionedQuery", () => { // A refetch that ran now would throw "registry is disposed" as an uncaught error. await Promise.resolve(); }); + + it("records a fetch started without a revision under the one it names", async () => { + const fresh = setup(); + (await fresh.mount(undefined, { startedUnder: "visit-b" }))(); + (await fresh.mount("visit-b"))(); + expect(fresh.fetches()).toBe(1); + + // Cached before that read: the revision still refetches it. + const cached = setup(); + (await cached.mount("thread-a-1"))(); + (await cached.mount(undefined, { startedUnder: "visit-b" }))(); + expect(cached.fetches()).toBe(1); + (await cached.mount("visit-b"))(); + expect(cached.fetches()).toBe(2); + }); + + it("refetches once for two readers of one query, and not when a thread's history loads", async () => { + const { mount, fetches } = setup(); + (await mount("thread-a-1", { detail: "status" }))(); + (await mount("thread-a-1"))(); + expect(fetches()).toBe(1); + + let visit = advanceWorkspaceVisit( + null, + { threadKey: "thread-b", unloaded: true, mutationId: null }, + "view", + ); + // The Changes totals, which add status totals of their own, then the Diff panel. + const render = async (unloaded: boolean, mutationId: string | null) => { + visit = advanceWorkspaceVisit(visit, { threadKey: "thread-b", unloaded, mutationId }, "view"); + const { revision } = workspaceRevisionOf(visit, mutationId); + (await mount(revision, { detail: "status" }))(); + (await mount(revision))(); + }; + + await render(true, null); + expect(fetches()).toBe(2); + await render(false, "thread-b-1"); + expect(fetches()).toBe(2); + await render(false, "thread-b-2"); + expect(fetches()).toBe(3); + }); + + it("refetches when a reader's own detail changes, whatever the other readers read", async () => { + const { mount, fetches } = setup(); + + (await mount("mutation-1", { detail: "status-1" }))(); + (await mount("mutation-1"))(); + (await mount("mutation-1", { detail: "status-1" }))(); + expect(fetches()).toBe(1); + + (await mount("mutation-1", { detail: "status-2" }))(); + expect(fetches()).toBe(2); + (await mount("mutation-1"))(); + expect(fetches()).toBe(2); + }); + + it("leaves a fetch that began after the revision changed to finish", async () => { + let fetches = 0; + const registry = AtomRegistry.make(); + const query = Atom.make( + Effect.suspend(() => ((fetches += 1) === 1 ? Effect.succeed(fetches) : Effect.never)), + ).pipe(Atom.keepAlive); + + registry.mount(revisionedQuery(query, "mutation-1")); + await Promise.resolve(); + expect(fetches).toBe(1); + + // Another reader's own refresh lands between the read and its deferred refetch. + registry.mount(revisionedQuery(query, "mutation-2")); + registry.refresh(query); + await Promise.resolve(); + expect(fetches).toBe(2); + + // A fetch already in flight when the revision changes started before the change. + registry.mount(revisionedQuery(query, "mutation-3")); + await Promise.resolve(); + expect(fetches).toBe(3); + }); + + it("does not restart the fetch of a query whose cache is gone", async () => { + let fetches = 0; + const scheduled: Array<() => void> = []; + const registry = AtomRegistry.make({ + scheduleTask: (task) => { + scheduled.push(task); + return () => {}; + }, + }); + const query = Atom.make(() => (fetches += 1)); + const read = async (revision: string) => { + const release = registry.mount(revisionedQuery(query, revision)); + await Promise.resolve(); + release(); + for (const task of scheduled.splice(0)) task(); + }; + + await read("mutation-1"); + await read("mutation-2"); + expect(fetches).toBe(2); + }); }); diff --git a/apps/web/src/state/revisionedQuery.ts b/apps/web/src/state/revisionedQuery.ts index 90c147b664741..6f63a64bbd54b 100644 --- a/apps/web/src/state/revisionedQuery.ts +++ b/apps/web/src/state/revisionedQuery.ts @@ -1,9 +1,19 @@ import * as Option from "effect/Option"; -import { Atom, type AtomRegistry } from "effect/reactivity"; +import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity"; // Outside the nodes: a node is dropped once unmounted, and the next read must // still compare against the revision the query was last read under. -const readRevisions = new WeakMap>(); +type LastRead = WeakMap>; +const readRevisions: LastRead = new WeakMap(); +const readDetails: LastRead = new WeakMap(); +const lastReadOf = (lastRead: LastRead, registry: AtomRegistry.AtomRegistry) => { + let byQuery = lastRead.get(registry); + if (byQuery === undefined) { + byQuery = new WeakMap(); + lastRead.set(registry, byQuery); + } + return byQuery; +}; // The registry keys serializable atoms' nodes by their key, not the atom. const hasNode = (registry: AtomRegistry.AtomRegistry, atom: Atom.Atom) => @@ -15,40 +25,58 @@ const isCached = (registry: AtomRegistry.AtomRegistry, query: Atom.Atom hasNode(registry, query) || (query.initialValueTarget !== undefined && hasNode(registry, query.initialValueTarget)); +const isWaiting = (value: unknown) => AsyncResult.isAsyncResult(value) && value.waiting; + const makeRevisionedFamily = (query: Atom.Atom) => - Atom.family((revision: string | null) => - Atom.readable( + Atom.family((key: string) => { + const { revision, startedUnder, detail } = JSON.parse(key) as { + readonly revision?: string | null; + readonly startedUnder?: string; + readonly detail?: string; + }; + return Atom.readable( (get) => { // Only a node's first build compares: a node still mounted under the old // revision rebuilds when the query refetches, and must not refetch it again. if (Option.isNone(get.self())) { - let revisions = readRevisions.get(get.registry); - if (revisions === undefined) { - revisions = new WeakMap(); - readRevisions.set(get.registry, revisions); + const revisions = lastReadOf(readRevisions, get.registry); + // Nothing cached: the read below fetches fresh, which a refresh would only restart. + const cached = isCached(get.registry, query); + if (revision === undefined) { + if (!cached && startedUnder !== undefined) revisions.set(query, startedUnder); + return get(query); } + const details = lastReadOf(readDetails, get.registry); const stale = revisions.has(query) - ? revisions.get(query) !== revision + ? revisions.get(query) !== revision || + (detail !== undefined && details.has(query) && details.get(query) !== detail) : // A reader without a revision may have cached it before the latest - // workspace change; a query nobody has read yet fetches fresh anyway. - revision !== null && isCached(get.registry, query); + // workspace change. + revision !== null || detail !== undefined; + revisions.set(query, revision); + if (detail !== undefined) details.set(query, detail); + const value = get(query); // Deferred: this builds while React renders, and a refresh would synchronously // re-render the query's other readers, which React rejects. - if (stale) { + if (stale && cached) { const registry = get.registry; + const wasWaiting = isWaiting(value); queueMicrotask(() => { // No node, as after the registry is disposed: nothing cached to refetch. - if (isCached(registry, query)) registry.refresh(query); + if (!isCached(registry, query)) return; + // A fetch that began since, as another reader's refresh, reads the same workspace. + if (!wasWaiting && isWaiting(registry.get(query))) return; + registry.refresh(query); }); } - revisions.set(query, revision); + return value; } return get(query); }, // Refreshing the reader refetches the query it reads. (refresh) => refresh(query), - ), - ); + ); + }); // Held as long as the query lives, so one (query, revision) pair keeps one atom; an // `Atom.family` would hold the inner family only weakly and could swap the atom under a reader. @@ -66,15 +94,16 @@ const revisionedFamily = (query: Atom.Atom) => { }; /** - * Reads `query` under a workspace revision (latest mutation id); a different - * revision than the last read refetches it. The first read records the revision, - * and refetches only a query that a reader without a revision already cached. - * `undefined` reads without taking part, for readers that must not refetch now. + * Reads `query` under a workspace revision (latest mutation id), which its readers share; a + * revision other than the last one read refetches a cached query. `undefined` reads without + * taking part. `startedUnder` records a fetch such a read starts as read under that revision; + * `detail` is one reader's own second revision, which the other readers neither see nor reset. */ export function revisionedQuery( query: Atom.Atom, revision: string | null | undefined, + options: { readonly startedUnder?: string | undefined; readonly detail?: string } = {}, ): Atom.Atom { - if (revision === undefined) return query; - return revisionedFamily(query)(revision) as Atom.Atom; + if (revision === undefined && options.startedUnder === undefined) return query; + return revisionedFamily(query)(JSON.stringify({ revision, ...options })) as Atom.Atom; } From 0854259384cf755016e9df66f452c72763152eaf Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 04:35:55 -0800 Subject: [PATCH 003/139] fix(web): clipped Files tree names show the full name on hover (#40308) --- .../web/src/components/diffs/DiffFileTree.tsx | 7 ++++++- .../src/components/files/FileBrowserPanel.tsx | 7 ++++++- apps/web/src/pierre-tree-theme.ts | 19 ++++++++++++++++++- 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/apps/web/src/components/diffs/DiffFileTree.tsx b/apps/web/src/components/diffs/DiffFileTree.tsx index ce48a468f66ec..57bc23b33130c 100644 --- a/apps/web/src/components/diffs/DiffFileTree.tsx +++ b/apps/web/src/components/diffs/DiffFileTree.tsx @@ -7,7 +7,11 @@ import { useEffect, useRef, useState, useSyncExternalStore, type ReactNode } fro import { useStableCallback } from "~/hooks/useStableCallback"; import { useTheme } from "~/hooks/useTheme"; import { cn } from "~/lib/utils"; -import { PIERRE_TREE_UNSAFE_CSS, pierreTreeStyle } from "~/pierre-tree-theme"; +import { + PIERRE_TREE_UNSAFE_CSS, + pierreTreeStyle, + titleClippedPierreTreeRow, +} from "~/pierre-tree-theme"; import { areAllDirectoriesExpanded, @@ -253,6 +257,7 @@ export function DiffFileTree({ }} className="min-h-0 flex-1 overflow-hidden" style={pierreTreeStyle(resolvedTheme)} + onPointerOver={titleClippedPierreTreeRow} /> {footer} diff --git a/apps/web/src/components/files/FileBrowserPanel.tsx b/apps/web/src/components/files/FileBrowserPanel.tsx index 1fee7db238727..cd44d99220939 100644 --- a/apps/web/src/components/files/FileBrowserPanel.tsx +++ b/apps/web/src/components/files/FileBrowserPanel.tsx @@ -27,7 +27,11 @@ import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh import { useFileContextMenu, type FileContextMenuAction } from "~/fileContextMenu"; import { readLocalApi } from "~/localApi"; import { T3_PIERRE_ICONS } from "~/pierre-icons"; -import { PIERRE_TREE_UNSAFE_CSS, pierreTreeStyle } from "~/pierre-tree-theme"; +import { + PIERRE_TREE_UNSAFE_CSS, + pierreTreeStyle, + titleClippedPierreTreeRow, +} from "~/pierre-tree-theme"; import { joinHostPath } from "./filePath"; import { createFileTreeDragMentionController } from "./fileTreeDragMention"; @@ -646,6 +650,7 @@ export default function FileBrowserPanel({ aria-label={gt("{projectName} files", { projectName })} className="min-h-0 flex-1 overflow-hidden" style={pierreTreeStyle(resolvedTheme)} + onPointerOver={titleClippedPierreTreeRow} /> )} diff --git a/apps/web/src/pierre-tree-theme.ts b/apps/web/src/pierre-tree-theme.ts index ada2a7d1abc7b..7deb41db7dcf0 100644 --- a/apps/web/src/pierre-tree-theme.ts +++ b/apps/web/src/pierre-tree-theme.ts @@ -1,4 +1,4 @@ -import type { CSSProperties } from "react"; +import type { CSSProperties, PointerEvent } from "react"; export const PIERRE_TREE_UNSAFE_CSS = ` :host { @@ -27,3 +27,20 @@ export function pierreTreeStyle(colorScheme: "light" | "dark"): CSSProperties { ["--trees-status-ignored-override" as string]: "var(--contrast-muted-foreground)", }; } + +// Clipped labels are unreadable and the tree cannot scroll sideways, so a clipped row gets its full name as a native tooltip. +export function titleClippedPierreTreeRow(event: PointerEvent) { + const row = event.nativeEvent + .composedPath() + .find( + (node): node is HTMLElement => + node instanceof HTMLElement && node.matches("button[data-type='item']"), + ); + if (!row) return; + const label = row.getAttribute("aria-label"); + const clipped = Array.from( + row.querySelectorAll("[data-truncate-content='visible']"), + ).some((element) => element.scrollWidth > element.clientWidth); + if (label && clipped) row.title = label; + else row.removeAttribute("title"); +} From 66441268e800dc7a73acd71810e34e6fa4b82e32 Mon Sep 17 00:00:00 2001 From: gero3 Date: Sat, 21 Nov 2026 13:39:40 +0100 Subject: [PATCH 004/139] fix(cli): update Windows launchers outside PATH (#40309) Co-authored-by: Julius Marminge --- apps/server/src/cli/update.test.ts | 26 ++++++++++++++++++++++++++ apps/server/src/cli/update.ts | 28 ++++++++++++++++++++++------ 2 files changed, 48 insertions(+), 6 deletions(-) diff --git a/apps/server/src/cli/update.test.ts b/apps/server/src/cli/update.test.ts index b5d3394f23fd2..2de00fc24bf54 100644 --- a/apps/server/src/cli/update.test.ts +++ b/apps/server/src/cli/update.test.ts @@ -229,6 +229,32 @@ it.layer(NodeServices.layer)("t3 update launcher", (it) => { }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")), ); + it.effect("repoints a recorded Windows launcher outside PATH", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped(); + const baseDir = path.join(root, "home"); + const runtimeDir = path.join(baseDir, "runtime"); + const launcher = path.join(root, "custom bin", "t3.cmd"); + const launchedAs = path.join(runtimeDir, "versions", "1.0.0", "t3.exe"); + const targetEntryPath = path.join(runtimeDir, "versions", "2.0.0", "t3.exe"); + yield* fs.makeDirectory(runtimeDir, { recursive: true }); + yield* fs.makeDirectory(path.dirname(launcher), { recursive: true }); + yield* fs.writeFileString(launcher, `@echo off\r\n"${launchedAs}" %*`); + yield* fs.writeFileString(path.join(runtimeDir, "launchers"), `${launcher}\r\n`); + + const repointed = yield* repointLauncher({ launchedAs, baseDir, targetEntryPath }); + + assert.equal(Option.getOrUndefined(repointed), launcher); + assert.equal(yield* fs.readFileString(launcher), `@echo off\r\n"${targetEntryPath}" %*`); + }).pipe( + Effect.scoped, + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService(HostProcess.Environment, { PATH: "" }), + ), + ); + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( "finds the script that ran this executable and rewrites it, keeping aliases and arguments", () => diff --git a/apps/server/src/cli/update.ts b/apps/server/src/cli/update.ts index b7b76f2f34223..07f3458fb3b66 100644 --- a/apps/server/src/cli/update.ts +++ b/apps/server/src/cli/update.ts @@ -25,6 +25,7 @@ import * as BootService from "../cloud/bootService.ts"; import { ensurePinnedRuntimeInstalled, findPosixLauncher, + generatedWindowsShimTarget, launcherOwnsVersionsDir, isUnpublishedRelease, pinnedRuntimePaths, @@ -171,7 +172,7 @@ export const repointLauncher = Effect.fn("cli.update.repoint_launcher")(function ); if (platform === "win32") { - const shimPath = yield* findWindowsShim(input.launchedAs); + const shimPath = yield* findWindowsShim(input.launchedAs, versionsDir); if (shimPath === undefined) return Option.none(); const current = yield* fs.readFileString(shimPath).pipe(Effect.option); const quoted = Option.isSome(current) ? windowsShimTarget(current.value) : undefined; @@ -203,9 +204,10 @@ export const repointLauncher = Effect.fn("cli.update.repoint_launcher")(function return Option.some(launcher); }); -/** Windows executables see their own path, so find the installer shim by matching t3.cmd targets on PATH. */ +/** Windows executables see their own path, so locate the installer shim by matching its target. */ export const findWindowsShim = Effect.fn("cli.update.find_windows_shim")(function* ( executablePath: string, + versionsDir?: string, ) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -213,12 +215,26 @@ export const findWindowsShim = Effect.fn("cli.update.find_windows_shim")(functio const candidates = [ ...(environment["T3CODE_INSTALL_BIN_DIR"] ? [environment["T3CODE_INSTALL_BIN_DIR"]] : []), ...(environment["PATH"] ?? environment["Path"] ?? "").split(";"), - ].filter((entry) => entry.trim().length > 0); - for (const directory of candidates) { - const shimPath = path.join(directory, "t3.cmd"); + ] + .filter((entry) => entry.trim().length > 0) + .map((directory) => ({ + shimPath: path.join(directory, "t3.cmd"), + parseTarget: windowsShimTarget, + })); + if (versionsDir !== undefined) { + const recorded = yield* fs + .readFileString(path.join(path.dirname(versionsDir), "launchers")) + .pipe(Effect.orElseSucceed(() => "")); + for (const shimPath of recorded.split(/\r?\n/)) { + if (path.isAbsolute(shimPath) && path.basename(shimPath).toLowerCase() === "t3.cmd") { + candidates.push({ shimPath, parseTarget: generatedWindowsShimTarget }); + } + } + } + for (const { shimPath, parseTarget } of candidates) { const contents = yield* fs.readFileString(shimPath).pipe(Effect.option); if (Option.isNone(contents)) continue; - const target = windowsShimTarget(contents.value); + const target = parseTarget(contents.value); if ( target !== undefined && path.resolve(target).toLowerCase() === path.resolve(executablePath).toLowerCase() From 69228fe179815a9446531eb9cf73d8deaa26db4c Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:16:58 +0530 Subject: [PATCH 005/139] fix(server): typed-message commits stage the worktree once (#40282) Co-authored-by: Julius Marminge --- apps/server/src/git/GitManager.test.ts | 45 +++++++++++++ apps/server/src/git/GitManager.ts | 27 ++++++-- apps/server/src/vcs/GitVcsDriver.ts | 22 +++++- apps/server/src/vcs/GitVcsDriverCore.test.ts | 45 ++++++++++++- apps/server/src/vcs/GitVcsDriverCore.ts | 71 ++++++++++++++++++++ 5 files changed, 201 insertions(+), 9 deletions(-) diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 0528d08f36c29..9dc3407597a4f 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -3584,6 +3584,51 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + it.effect("stages the worktree once for a typed commit message", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "typed\n"); + const gitCommands: string[] = []; + const { manager } = yield* makeManager({ gitCommands }); + + const created = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit", + commitMessage: "Typed subject\n\nTyped body", + }); + + expect(created.commit).toMatchObject({ status: "created", subject: "Typed subject" }); + expect(gitCommands.filter((args) => args.endsWith("add -A"))).toHaveLength(1); + expect((yield* runGit(repoDir, ["log", "-1", "--pretty=%B"])).stdout.trim()).toBe( + "Typed subject\n\nTyped body", + ); + + // Status shows the staged change, but staging the reverted worktree leaves nothing. + NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "staged\n"); + yield* runGit(repoDir, ["add", "README.md"]); + NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "typed\n"); + const head = (yield* runGit(repoDir, ["rev-parse", "HEAD"])).stdout; + + const skipped = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit", + commitMessage: "Nothing to commit", + }); + + expect(skipped.commit.status).toBe("skipped_no_changes"); + expect((yield* runGit(repoDir, ["rev-parse", "HEAD"])).stdout).toBe(head); + expect((yield* runGit(repoDir, ["show", ":README.md"])).stdout).toBe("staged\n"); + + // A generated message already checked a scratch index, so staging again stays at two. + NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "generated\n"); + gitCommands.length = 0; + const generated = yield* runStackedAction(manager, { cwd: repoDir, action: "commit" }); + expect(generated.commit.status).toBe("created"); + expect(gitCommands.filter((args) => args.endsWith("add -A"))).toHaveLength(2); + }), + ); + it.effect("lowercases a capitalized Conventional Commits description", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index 118e4ffd461ae..9db4fbfc27755 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -2494,7 +2494,13 @@ export const make = Effect.gen(function* () { } as GitActionProgressEvent) : Effect.void; - let suggestion: CommitAndBranchSuggestion | null | undefined = preResolvedSuggestion; + const customCommit = parseCustomCommitMessage(commitMessage ?? ""); + let suggestion: CommitAndBranchSuggestion | null | undefined = + preResolvedSuggestion ?? + (customCommit && { + ...customCommit, + commitMessage: formatCommitMessage(customCommit.subject, customCommit.body), + }); if (!suggestion) { const needsGeneration = !commitMessage?.trim(); if (needsGeneration) { @@ -2566,11 +2572,20 @@ export const make = Effect.gen(function* () { }, } : null; - const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body, { - timeoutMs: COMMIT_TIMEOUT_MS, - stage: filePaths ? { filePaths } : {}, - ...(commitProgress ? { progress: commitProgress } : {}), - }); + const committed = yield* gitCore + .commit(cwd, suggestion.subject, suggestion.body, { + timeoutMs: COMMIT_TIMEOUT_MS, + stage: { + ...(filePaths ? { filePaths } : {}), + ...(!preResolvedSuggestion && customCommit ? { unverified: true } : {}), + }, + ...(commitProgress ? { progress: commitProgress } : {}), + }) + .pipe(Effect.catchTags({ GitNothingToCommitError: () => Effect.succeed(null) })); + if (!committed) { + return { status: "skipped_no_changes" as const }; + } + const { commitSha } = committed; if (currentHookName !== null) { yield* emit({ kind: "hook_finished", diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 5164e6f4585c8..700ad3b3571c9 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -10,6 +10,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 Schema from "effect/Schema"; import { ChildProcessSpawner } from "effect/process"; import { @@ -76,6 +77,19 @@ export interface ExecuteGitResult { readonly stderrTruncated: boolean; } +export class GitNothingToCommitError extends Schema.TaggedError()( + "GitNothingToCommitError", + { + operation: Schema.String, + cwd: Schema.String, + detail: Schema.String, + }, +) { + override get message(): string { + return `Nothing to commit in ${this.operation} (${this.cwd}): ${this.detail}`; + } +} + export interface GitStatusDetails { isRepo: boolean; sourceControlProvider?: VcsStatusResult["sourceControlProvider"]; @@ -173,7 +187,11 @@ export interface GitCommitProgress { export interface GitCommitOptions { readonly timeoutMs?: number; readonly progress?: GitCommitProgress; - readonly stage?: { readonly filePaths?: readonly string[] }; + readonly stage?: { + readonly filePaths?: readonly string[]; + /** The caller has not run `prepareCommitContext`, so an empty result must keep the index. */ + readonly unverified?: boolean; + }; } export interface GitDeleteLocalBranchInput { @@ -361,7 +379,7 @@ export class GitVcsDriver extends Context.Service< subject: string, body: string, options?: GitCommitOptions, - ) => Effect.Effect<{ commitSha: string }, GitCommandError>; + ) => Effect.Effect<{ commitSha: string }, GitCommandError | GitNothingToCommitError>; readonly pushCurrentBranch: ( cwd: string, fallbackBranch: string | null, diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index e23343ed67165..8789b54d31562 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -8621,6 +8621,17 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { assert.notInclude(context?.stagedSummary ?? "", "b.txt"); assert.equal(yield* git(repository, ["diff", "--cached", "--name-only"]), ""); + // A selected file staged and then reverted stages to nothing, like git commit --only. + const head = yield* git(repository, ["rev-parse", "HEAD"]); + yield* writeTextFile(repository, "README.md", "staged\n"); + yield* git(repository, ["add", "README.md"]); + yield* git(repository, ["restore", "--source=HEAD", "--worktree", "--", "README.md"]); + const empty = yield* driver + .commit(cwd, "Empty", "", { stage: { filePaths: ["README.md"] } }) + .pipe(Effect.flip); + assert.equal(empty._tag, "GitNothingToCommitError"); + assert.equal(yield* git(repository, ["rev-parse", "HEAD"]), head); + const commit = yield* driver.commit(cwd, "Add a", "", { stage: { filePaths: [selected] }, }); @@ -8840,6 +8851,8 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { // A branch named MERGE_HEAD is not a merge in progress. yield* git(cwd, ["branch", "MERGE_HEAD"]); assert.isNull(yield* driver.prepareCommitContext(cwd, undefined, { includePatch: false })); + const empty = yield* driver.commit(cwd, "Empty", "", { stage: {} }).pipe(Effect.flip); + assert.equal(empty._tag, "GitNothingToCommitError"); yield* git(cwd, ["branch", "-D", "MERGE_HEAD"]); yield* git(cwd, ["checkout", "-b", "feature"]); yield* writeTextFile(cwd, "README.md", "feature version\n"); @@ -8859,6 +8872,13 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { assert.isNotNull( yield* driver.prepareCommitContext(cwd, undefined, { includePatch: false }), ); + const mainHead = yield* git(cwd, ["rev-parse", "HEAD"]); + const featureHead = yield* git(cwd, ["rev-parse", "feature"]); + yield* driver.commit(cwd, "Merge feature", "", { stage: {} }); + assert.equal( + yield* git(cwd, ["show", "-s", "--format=%P", "HEAD"]), + `${mainHead} ${featureHead}`, + ); }), ); @@ -9004,6 +9024,9 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { yield* writeTextFile(cwd, "README.md", "stashed version\n"); yield* git(cwd, ["stash"]); yield* writeTextFile(cwd, "README.md", "committed version\n"); + yield* writeTextFile(cwd, "same.txt", "same\n"); + yield* writeTextFile(cwd, "gone.txt", "gone\n"); + yield* git(cwd, ["add", "same.txt", "gone.txt"]); yield* git(cwd, ["commit", "-am", "Change README"]); const pop = yield* driver.execute({ operation: "test.stashPop", @@ -9012,9 +9035,29 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { allowNonZeroExit: true, }); assert.equal(pop.exitCode, 1); + const unmerged = yield* git(cwd, ["ls-files", "--unmerged"]); + + // A selected file staged and then reverted has nothing to commit despite the conflict. + const unchangedHead = yield* git(cwd, ["rev-parse", "HEAD"]); + yield* writeTextFile(cwd, "same.txt", "staged\n"); + yield* git(cwd, ["add", "same.txt"]); + yield* git(cwd, ["restore", "--source=HEAD", "--worktree", "--", "same.txt"]); + const empty = yield* driver + .commit(cwd, "Empty", "", { stage: { filePaths: ["same.txt"] } }) + .pipe(Effect.flip); + assert.equal(empty._tag, "GitNothingToCommitError"); + assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), unchangedHead); + assert.equal(yield* git(cwd, ["ls-files", "--unmerged"]), unmerged); + + yield* (yield* FileSystem.FileSystem).remove((yield* Path.Path).join(cwd, "gone.txt")); + yield* driver.commit(cwd, "Remove gone", "", { stage: { filePaths: ["gone.txt"] } }); + assert.equal( + yield* git(cwd, ["show", "--pretty=", "--name-status", "HEAD"]), + "D\tgone.txt", + ); + yield* writeTextFile(cwd, "other.txt", "other\n"); const head = yield* git(cwd, ["rev-parse", "HEAD"]); - const unmerged = yield* git(cwd, ["ls-files", "--unmerged"]); const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const nested = path.join(cwd, "nested"); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index ab9b10563c690..27927f5dc5c8b 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -3399,10 +3399,81 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* body, options?: GitVcsDriver.GitCommitOptions, ) { + const diffCached = [ + "-c", + "diff.relative=false", + "diff", + "--cached", + "--no-ext-diff", + "--no-textconv", + ]; + if (options?.stage?.unverified) { + const indexMatchesHead = + (yield* executeGit("GitVcsDriver.commit.indexChanges", cwd, [...diffCached, "--quiet"], { + allowNonZeroExit: true, + })).exitCode === 0; + // Staging an empty result would overwrite what is already staged, so check a scratch index. + if ( + !indexMatchesHead && + (yield* prepareCommitContext(cwd, options.stage.filePaths, { includePatch: false })) === + null + ) { + return yield* new GitVcsDriver.GitNothingToCommitError({ + operation: "GitVcsDriver.commit", + cwd, + detail: "Staging found no changes.", + }); + } + } const partialCommitPaths = options?.stage !== undefined ? yield* stageCommitChanges(cwd, options.stage.filePaths) : undefined; + // Preserved unselected conflicts always show as index changes, so only selected paths count. + const selectedPaths = partialCommitPaths && new Set(options?.stage?.filePaths); + const hasStagedChanges = selectedPaths + ? (yield* runGitStdoutWithOptions( + "GitVcsDriver.commit.stagedChanges", + cwd, + [...diffCached, "--no-renames", "--name-only", "-z"], + { maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, + )) + .split("\0") + .some((file) => file.length > 0 && selectedPaths.has(file)) + : (yield* executeGit("GitVcsDriver.commit.stagedChanges", cwd, [...diffCached, "--quiet"], { + allowNonZeroExit: true, + })).exitCode !== 0; + if (!hasStagedChanges) { + // Like git commit, a merge resolved to HEAD's tree still records its merge commit. + const mergeHeadPath = yield* runGitStdout("GitVcsDriver.commit.mergeHead", cwd, [ + "rev-parse", + "--git-path", + "MERGE_HEAD", + ]); + const merging = yield* fileSystem.realPath(cwd).pipe( + Effect.orElseSucceed(() => cwd), + Effect.flatMap((physicalCwd) => + fileSystem.exists(path.resolve(physicalCwd, mergeHeadPath.trim())), + ), + Effect.mapError( + (cause) => + new GitCommandError({ + operation: "GitVcsDriver.commit.mergeHead", + command: "git commit", + cwd, + detail: "Could not check whether a merge is in progress.", + cause, + }), + ), + ); + if (!merging) { + return yield* new GitVcsDriver.GitNothingToCommitError({ + operation: "GitVcsDriver.commit", + cwd, + detail: "Staging found no changes.", + }); + } + } const args = ["commit", "-m", subject]; const trimmedBody = body.trim(); if (trimmedBody.length > 0) { From 7ef7ba0e3b1bc0582e44f1379bff1cc5559cf0d2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 04:49:13 -0800 Subject: [PATCH 006/139] perf(server): a tracked file's Diff panel patch skips the untracked-file listing (#40304) --- .../src/features/review/useReviewDiffData.ts | 1 + apps/server/src/vcs/GitVcsDriverCore.test.ts | 54 ++++++++++++++++++- apps/server/src/vcs/GitVcsDriverCore.ts | 26 +++++++-- .../components/diffs/useReviewFilePatches.ts | 1 + packages/contracts/src/review.ts | 20 +++---- 5 files changed, 88 insertions(+), 14 deletions(-) diff --git a/apps/mobile/src/features/review/useReviewDiffData.ts b/apps/mobile/src/features/review/useReviewDiffData.ts index 35cf8f2f14b3c..d530279f8ca25 100644 --- a/apps/mobile/src/features/review/useReviewDiffData.ts +++ b/apps/mobile/src/features/review/useReviewDiffData.ts @@ -219,6 +219,7 @@ export function useReviewDiffData(input: { file: { path: file.path, previousPath: file.previousPath, + ...(file.changeType ? { changeType: file.changeType } : {}), sourceKind: lazySource.kind, }, }, diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 8789b54d31562..e745669fda5c2 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -3463,7 +3463,12 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const scoped = yield* driver.getReviewDiffPreview({ cwd: projectDirectory, baseRef: initialBranch, - file: { path: file.path, previousPath: file.previousPath, sourceKind: source.kind }, + file: { + path: file.path, + previousPath: file.previousPath, + sourceKind: source.kind, + ...(file.changeType ? { changeType: file.changeType } : {}), + }, }); const patch = scoped.sources.find((item) => item.kind === source.kind)!; assert.deepStrictEqual(patch.files, [file]); @@ -3474,6 +3479,53 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect( + "lists untracked files for a file the preview called tracked only when it is not", + () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + yield* writeTextFile(cwd, "tracked.txt", "one\n"); + yield* git(cwd, ["add", "."]); + yield* git(cwd, ["commit", "-m", "tracked"]); + yield* writeTextFile(cwd, "tracked.txt", "two\n"); + yield* writeTextFile(cwd, "README.md", "dirty\n"); + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + let listings = 0; + const spawner = ChildProcessSpawner.make((command) => { + if (ChildProcess.isStandardCommand(command) && command.args.includes("--others")) { + listings++; + } + return delegate.spawn(command); + }); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + const read = (path: string, changeType?: "change") => + driver + .getReviewDiffPreview({ + cwd, + file: { + path, + previousPath: null, + sourceKind: "working-tree", + ...(changeType ? { changeType } : {}), + }, + }) + .pipe(Effect.map((preview) => preview.sources[0]!)); + + const tracked = yield* read("tracked.txt", "change"); + assert.include(tracked.diff, "+two"); + assert.equal(listings, 0); + + // A stale hint: the file left the index after the preview listed it. + yield* git(cwd, ["rm", "--cached", "-q", "README.md"]); + const stale = yield* read("README.md", "change"); + assert.equal(listings, 1); + assert.deepStrictEqual(stale, yield* read("README.md")); + }), + ); + it.effect("rejects a file selector for a different source than the request", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 27927f5dc5c8b..7c4363b1647be 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -4788,13 +4788,30 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* exitCode: result.exitCode, }); }); + // A file the preview did not list as new is stat-ed against the real index first. `git diff` + // lists an indexed path as anything but deleted, and `ls-files --others` never lists one. + const indexedRef = + input.file && !input.trackedOnly && input.file.changeType && input.file.changeType !== "new" + ? (dirtyRef ?? review.mergeBase) + : null; + const indexedStat = indexedRef === null ? undefined : yield* readStats(indexedRef); + const indexed = + indexedStat?.files.some( + (file) => + file.path === input.file?.path && + file.changeType !== undefined && + file.changeType !== "deleted", + ) === true; const readTrackedDiff = Effect.fn("GitVcsDriver.getReviewDiffPreview.tracked")(function* ( ref: string | null, env?: NodeJS.ProcessEnv, metadataOnly = false, ) { if (ref === null) return { stdout: "", stdoutTruncated: false, files: [] }; - const stat = yield* readStats(ref, env); + const stat = + env === undefined && ref === indexedRef && indexedStat !== undefined + ? indexedStat + : yield* readStats(ref, env); if (metadataOnly || stat.files.length === 0) { return { stdout: "", stdoutTruncated: false, files: stat.files }; } @@ -4807,9 +4824,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return { ...patch, files: stat.files }; }); const [dirtyTrackedResult, baseResult] = yield* Effect.gen(function* () { - const untracked = input.trackedOnly - ? { env: undefined, omitted: false } - : yield* prepareUntrackedReviewIndex(cwd, pathArgs, input.file?.path); + const untracked = + input.trackedOnly || indexed + ? { env: undefined, omitted: false } + : yield* prepareUntrackedReviewIndex(cwd, pathArgs, input.file?.path); // Untracked files left out make the file list partial, so the bounded patch is sent instead. const complete = untracked !== null && !untracked.omitted; // With no untracked files to add, the tracked read already is the complete diff. diff --git a/apps/web/src/components/diffs/useReviewFilePatches.ts b/apps/web/src/components/diffs/useReviewFilePatches.ts index 94fee877f0f4b..0c889d501264d 100644 --- a/apps/web/src/components/diffs/useReviewFilePatches.ts +++ b/apps/web/src/components/diffs/useReviewFilePatches.ts @@ -206,6 +206,7 @@ function reviewFileQueries({ file: { path: file.path, previousPath: file.previousPath, + ...(file.changeType ? { changeType: file.changeType } : {}), sourceKind: source.kind, }, }, diff --git a/packages/contracts/src/review.ts b/packages/contracts/src/review.ts index ab5cae42624d4..d43946e217219 100644 --- a/packages/contracts/src/review.ts +++ b/packages/contracts/src/review.ts @@ -8,6 +8,15 @@ const ReviewMergeBase = Schema.String.check( Schema.isPattern(/^(?:[0-9a-f]{40}|[0-9a-f]{64}|HEAD)$/), ); +export const ReviewDiffChangeType = Schema.Literals([ + "change", + "rename-pure", + "rename-changed", + "new", + "deleted", +]); +export type ReviewDiffChangeType = typeof ReviewDiffChangeType.Type; + export const ReviewDiffPreviewInput = Schema.Struct({ cwd: TrimmedNonEmptyString, baseRef: Schema.optional(TrimmedNonEmptyString), @@ -25,6 +34,8 @@ export const ReviewDiffPreviewInput = Schema.Struct({ path: Schema.NonEmptyString, previousPath: Schema.NullOr(Schema.NonEmptyString), sourceKind: Schema.Literals(["working-tree", "branch-range", "commit"]), + // The preview's change type; the server still confirms a tracked path before relying on it. + changeType: Schema.optionalKey(ReviewDiffChangeType), }), ), }); @@ -55,15 +66,6 @@ export const ReviewDiffPreviewSourceKind = Schema.Literals([ ]); export type ReviewDiffPreviewSourceKind = typeof ReviewDiffPreviewSourceKind.Type; -export const ReviewDiffChangeType = Schema.Literals([ - "change", - "rename-pure", - "rename-changed", - "new", - "deleted", -]); -export type ReviewDiffChangeType = typeof ReviewDiffChangeType.Type; - export const ReviewDiffFileStat = Schema.Struct({ path: Schema.String, previousPath: Schema.NullOr(Schema.String), From 0775dc450fcf4a6f85cc7db955f3c5b5f7d4f42a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 04:57:44 -0800 Subject: [PATCH 007/139] fix(mobile): mark the linked line in the native source viewer (#40295) --- .../main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt | 3 ++- apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt index 8b0a84a952caf..e2d5a12d76304 100644 --- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt @@ -1314,12 +1314,13 @@ private class DiffCanvasView(context: Context) : View(context) { } val selected = selectedRowIds.contains(row.id) if (selected) { + // Source files hide the change bar (width 0); the selection marker still needs to show. fill( canvas, withAlpha(theme.hunkText, 242), 0f, top.toFloat(), - style.changeBarWidthPx, + maxOf(style.changeBarWidthPx, 4f * density), bottom.toFloat() ) } diff --git a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift index 7fe4a068f9bbb..0c65ddf19460a 100644 --- a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift +++ b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift @@ -2661,8 +2661,9 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { return } + // Source files hide the change bar (width 0); the selection marker still needs to show. theme.hunkText.withAlphaComponent(0.95).setFill() - context.fill(CGRect(x: 0, y: rect.minY, width: style.changeBarWidth, height: rect.height)) + context.fill(CGRect(x: 0, y: rect.minY, width: max(style.changeBarWidth, 4), height: rect.height)) } private func drawWordDiffRanges( From c3853775447b466b402f38452ce81bcb1617e491 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:40:15 +0530 Subject: [PATCH 008/139] fix(server): slash commands sent during a turn wait instead of steering (#40316) Co-authored-by: Julius Marminge --- .../orchestration-v2/CommandPolicy.test.ts | 24 +++ .../src/orchestration-v2/CommandPolicy.ts | 20 +++ .../src/orchestration-v2/Orchestrator.ts | 66 +++++++-- .../SteeringCompletion.integration.test.ts | 138 +++++++++++++++--- .../ThreadLaunchService.test.ts | 2 +- .../src/components/chat/QueuedRunsControl.tsx | 31 ++-- apps/web/src/i18n/translations/de.json | 4 +- apps/web/src/i18n/translations/en.json | 4 +- apps/web/src/i18n/translations/es.json | 4 +- apps/web/src/i18n/translations/fr.json | 4 +- apps/web/src/i18n/translations/ja.json | 4 +- apps/web/src/i18n/translations/ko.json | 4 +- apps/web/src/i18n/translations/pt-BR.json | 4 +- apps/web/src/i18n/translations/ru.json | 4 +- apps/web/src/i18n/translations/sv.json | 4 +- apps/web/src/i18n/translations/zh.json | 4 +- docs/user/composer.md | 9 +- packages/shared/src/composerTrigger.ts | 8 + .../steered-compact-waits-for-turn.e2e.ts | 71 +++++++++ 19 files changed, 353 insertions(+), 56 deletions(-) create mode 100644 scripts/scenarios/steered-compact-waits-for-turn.e2e.ts diff --git a/apps/server/src/orchestration-v2/CommandPolicy.test.ts b/apps/server/src/orchestration-v2/CommandPolicy.test.ts index e9f829524948b..d5b06dbf6c47f 100644 --- a/apps/server/src/orchestration-v2/CommandPolicy.test.ts +++ b/apps/server/src/orchestration-v2/CommandPolicy.test.ts @@ -252,6 +252,30 @@ it("steers a Grok follow-up into its running turn without restarting it", () => assert.isTrue(grok.turns.supportsActiveSteering); }); +// regression: #32606 a slash command steered into a running turn replaced the task +it.each([ + ["/compact", { type: "queue_after_active" }], + ["/context", { type: "queue_after_active" }], + [" /context all\n", { type: "queue_after_active" }], + ["/plugin:review-pr 12", { type: "queue_after_active" }], + ["/home/me/x.ts fails", { type: "steer_active", targetRunId: activeRunId }], + ["/ context", { type: "steer_active", targetRunId: activeRunId }], + ["$skill /context", { type: "steer_active", targetRunId: activeRunId }], +] as const)("steers %j only when it is not a slash command", (text, expected) => { + const projection = dispatchProjection(baseCapabilities); + for (const deliveryIntent of ["auto", "steer"] as const) { + assert.deepEqual( + CommandPolicy.resolveMessageDispatch(projection, { + dispatchMode: { type: "start_immediately" }, + deliveryIntent, + text, + attachments: [], + }), + expected, + ); + } +}); + it.each(["/compact", " /LOGOUT "])("queues a steer sent while %s runs", (text) => { const projection = dispatchProjection(baseCapabilities); const maintenance = { diff --git a/apps/server/src/orchestration-v2/CommandPolicy.ts b/apps/server/src/orchestration-v2/CommandPolicy.ts index 451ca978b9e51..1319083cca030 100644 --- a/apps/server/src/orchestration-v2/CommandPolicy.ts +++ b/apps/server/src/orchestration-v2/CommandPolicy.ts @@ -10,6 +10,7 @@ import { ProviderInstanceId, ThreadId, } from "@t3tools/contracts"; +import { isSlashCommand } from "@t3tools/shared/composerTrigger"; import { latestExecutedRun } from "@t3tools/shared/orchestrationV2ThreadError"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; @@ -101,6 +102,25 @@ export function goalCommandStopsActiveRun( } } +export function resolveMessageDispatch( + projection: OrchestrationV2ThreadProjection, + message: Pick< + Extract, + "dispatchMode" | "deliveryIntent" | "text" | "attachments" + >, +): MessageDispatchMode { + const mode = resolveMessageDispatchIntent( + projection, + message.dispatchMode, + message.deliveryIntent, + ); + // A provider runs a steered command in place of the turn's task, so commands wait. + return mode.type === "steer_active" && isSlashCommand(message) + ? { type: "queue_after_active" } + : mode; +} + +/** How a message joins active work when it is free to steer. */ export function resolveMessageDispatchIntent( projection: OrchestrationV2ThreadProjection, requestedMode: MessageDispatchMode, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 00939843c13f1..e27fe09d07d1b 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -92,6 +92,7 @@ import { isPlaceholderThreadTitle } from "./placeholderThreadTitle.ts"; import { combinePullRequestWatchWakes, type PullRequestWatchWake } from "./pullRequestWatch.ts"; import { outputRequestProblem } from "./runOutput.ts"; import { recordThreadOpen } from "@t3tools/shared/paletteSearch"; +import { isSlashCommand } from "@t3tools/shared/composerTrigger"; import { backgroundWorkHoldsCompletion, derivePendingBackgroundWork, @@ -126,6 +127,7 @@ import { isNativeMaintenanceCommand, providerSwitchWaitsForTurn, providerTurnCapabilities, + resolveMessageDispatch, resolveMessageDispatchIntent, } from "./CommandPolicy.ts"; import { CommandReceiptStoreV2, type CommandReceiptV2 } from "./CommandReceiptStore.ts"; @@ -6308,6 +6310,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); } yield* ensureSteeringMessage(input.command, input); + // An explicit restart already gives up the turn, so only steering holds commands back. + if (!input.forceRestart && isSlashCommand(input)) { + return yield* new OrchestratorDispatchError({ + commandId: input.command.commandId, + commandType: input.command.type, + cause: + "Commands must run as a separate turn. Queue it or wait for the active turn to finish.", + }); + } const targetMessage = input.projection.messages.find( (message) => message.id === targetRun.userMessageId, ); @@ -7416,11 +7427,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio projection = applyToProjection(projection, event); } let modelSelection = command.modelSelection ?? projection.thread.modelSelection; - let dispatchMode = resolveMessageDispatchIntent( - projection, - command.dispatchMode, - command.deliveryIntent, - ); + // Native goal commands must not steer an existing turn. + const parsedGoalCommand = parseGoalCommand(command); + const goalCommand = + parsedGoalCommand === null || + (yield* goalDriverFor(command, modelSelection.instanceId)) === undefined + ? null + : parsedGoalCommand; + // A goal command keeps the run it was sent at; the goal handling below queues it. + let dispatchMode = + goalCommand === null + ? resolveMessageDispatch(projection, command) + : resolveMessageDispatchIntent(projection, command.dispatchMode, command.deliveryIntent); if (dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") { const targetRunId = dispatchMode.targetRunId; const target = projection.runs.find((run) => run.id === targetRunId); @@ -7515,13 +7533,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ) { dispatchMode = { type: "queue_after_active" }; } - // Native goal commands must not steer an existing turn. - const parsedGoalCommand = parseGoalCommand(command); - const goalCommand = - parsedGoalCommand === null || - (yield* goalDriverFor(command, modelSelection.instanceId)) === undefined - ? null - : parsedGoalCommand; let queuedRunStop: | { readonly runId: RunId; readonly reason: string; readonly skipsHeldQueue?: true } | undefined; @@ -7672,6 +7683,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const commandNotice = noticeKind === "command" && command.creationSource === "server"; if ( !freshContext && + // Steering refuses a command, so a notice that reads like one stays queued. + !isSlashCommand(command) && (delegatedCompletion !== undefined ? delegatedCompletion.taskIds.every( (id) => @@ -11856,8 +11869,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: "A message that asks for a result can't steer the current turn.", }); } - if (goalCommand !== null) { - yield* ensureGoalCommandSupported(command, queuedMessage, modelSelection.instanceId); + // A steered command replaces the turn's task, so promoting one only moves it first. + if (goalCommand !== null || isSlashCommand(queuedMessage)) { + if (goalCommand !== null) { + yield* ensureGoalCommandSupported(command, queuedMessage, modelSelection.instanceId); + } const goal = projection.providerThreads.find( (candidate) => candidate.id === target?.providerThreadId, )?.goal; @@ -11871,6 +11887,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio payload: { ...queuedRun, queuePosition: 1 }, }); const stops = + goalCommand !== null && target !== undefined && isLiveRun(target) && goalCommandStopsActiveRun(goalCommand, goal?.status ?? null) && @@ -12298,6 +12315,25 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }), }); } + // A command cannot steer, so an edit into one keeps it queued where it is. + if ( + queuedRun.steerWhenReadyRunId !== undefined && + isSlashCommand({ + text: command.text, + attachments: command.attachments ?? queuedMessage.attachments, + }) + ) { + const { steerWhenReadyRunId: _, ...queued } = queuedRun; + yield* emitEvent({ + type: "run.updated", + threadId: command.threadId, + runId: queuedRun.id, + ...(queuedRun.rootNodeId === null ? {} : { nodeId: queuedRun.rootNodeId }), + providerInstanceId: queuedRun.providerInstanceId, + occurredAt: now, + payload: queued, + }); + } // Thread deletion only cleans files the thread still references. const keptAttachmentIds = new Set( (command.attachments ?? queuedMessage.attachments).map((attachment) => attachment.id), @@ -14182,7 +14218,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); - /** Puts a queued goal command first and, given a target, stops the run in its way. */ + /** Puts a queued command first and, given a target, stops the run in its way. */ const stopRunForQueuedCommand = Effect.fn("Orchestrator.stopRunForQueuedCommand")( function* (input: { readonly command: Extract< diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index cc14fde257da8..3ef67192ceb77 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -711,14 +711,15 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* it.effect.each([ { notice: "delegated task question", goal: null, steers: true }, + { notice: "delegated task question", goal: null, steers: false, summary: "/review is ready" }, { notice: "background command", goal: "active", steers: true }, { notice: "background command", goal: null, steers: false }, ] as const)( "a $notice notice steers into the running turn: $steers (goal $goal)", - ({ notice, goal, steers }) => + ({ notice, goal, steers, ...row }) => Effect.gen(function* () { const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness( - `notice-steer-${notice.replaceAll(" ", "-")}-${goal ?? "none"}`, + `notice-steer-${notice.replaceAll(" ", "-")}-${goal ?? "none"}-${steers}`, ); yield* Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; @@ -762,7 +763,7 @@ it.effect.each([ childThreadId: ThreadId.make("thread:question-child"), }, outcome: "updated" as const, - summary: "Delegated task has a question", + summary: "summary" in row ? row.summary : "Delegated task has a question", } : { source: { kind: "command" as const }, @@ -945,6 +946,7 @@ it.effect.each( const edited = (yield* orchestrator.getThreadProjection(threadId)).runs.find( (candidate) => candidate.userMessageId === MessageId.make("message:edited-steer"), )!; + assert.equal(edited.steerWhenReadyRunId, run.id); yield* orchestrator.dispatch({ type: "queued-run.edit", commandId: CommandId.make("edit-steer-to-compact"), @@ -952,6 +954,11 @@ it.effect.each( runId: edited.id, text: "/compact", }); + const compact = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (candidate) => candidate.id === edited.id, + )!; + assert.isUndefined(compact.steerWhenReadyRunId); + assert.equal(compact.queuePosition, edited.queuePosition); } if (direct) { yield* orchestrator.dispatch({ @@ -998,16 +1005,18 @@ it.effect.each( const maintenance = (yield* orchestrator.getThreadProjection(threadId)).runs.find( (candidate) => candidate.userMessageId === MessageId.make(`message:${text}`), )!; - const error = yield* orchestrator - .dispatch({ - type: "queued-message.promote-to-steer", - commandId: CommandId.make(`promote-${text}`), - threadId, - queuedRunId: maintenance.id, - targetRunId: run.id, - }) - .pipe(Effect.flip); - assert.equal(error._tag, "OrchestratorDispatchError"); + yield* orchestrator.dispatch({ + type: "queued-message.promote-to-steer", + commandId: CommandId.make(`promote-${text}`), + threadId, + queuedRunId: maintenance.id, + targetRunId: run.id, + }); + const promoted = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (candidate) => candidate.id === maintenance.id, + )!; + assert.equal(promoted.status, "queued"); + assert.equal(promoted.queuePosition, 1); } const command = { type: "queued-message.promote-to-steer" as const, @@ -3165,15 +3174,12 @@ it.effect.each([undefined, false, true])( const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; const threadId = yield* startFirstTurn; yield* send("queued", "queued", "queue"); - const sending = send("goal", "/goal all tests pass", "auto"); - if (nativeGoals === false) { - yield* Effect.flip(sending); - } else yield* sending; + yield* send("goal", "/goal all tests pass", "auto"); yield* worker.drain(); assert.deepEqual(steered, []); assert.deepEqual(yield* read(threadId), { - queue: ["queued"], + queue: nativeGoals === false ? ["queued", "/goal all tests pass"] : ["queued"], started: nativeGoals === false ? ["first"] : ["first", "/goal all tests pass"], stopRequested: nativeGoals !== false, }); @@ -3472,6 +3478,70 @@ it.effect("queues a goal clear without stopping work when no goal drives it", () }), ); +it.effect("promoting a queued /context moves it first and does not steer", () => + Effect.gen(function* () { + const { started, steered, layer, startFirstTurn, send, read } = + yield* goalHarness("slash-promote"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + yield* send("queued", "queued", "queue"); + yield* send("context", "/context", "queue"); + const queuedRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.userMessageId === MessageId.make("message:context"), + )!; + yield* orchestrator.dispatch({ + type: "queued-message.promote-to-steer", + commandId: CommandId.make("promote"), + threadId, + queuedRunId: queuedRun.id, + targetRunId: started[0]!.runId, + }); + yield* worker.drain(); + + assert.deepEqual(steered, []); + assert.deepEqual(yield* read(threadId), { + queue: ["/context", "queued"], + started: ["first"], + stopRequested: false, + }); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect("restarts the turn for a slash command sent as an explicit restart", () => + Effect.gen(function* () { + const { started, steered, interrupted, layer, startFirstTurn } = + yield* nextTurnSelectionHarness("slash-restart", true); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("restart-context"), + threadId, + messageId: MessageId.make("message:restart-context"), + text: "/context", + attachments: [], + modelSelection: runSelection, + dispatchMode: { type: "restart_active", targetRunId: started[0]!.runId }, + createdBy: "user", + creationSource: "web", + }); + yield* worker.drain(); + + assert.deepEqual(steered, []); + assert.lengthOf(interrupted, 1); + assert.deepEqual( + started.map((turn) => turn.message.text), + ["first", "/context"], + ); + }).pipe(Effect.provide(layer)); + }), +); + it.effect("promotes a queued goal by stopping the running turn", () => Effect.gen(function* () { const { started, steered, layer, startFirstTurn, send, read } = @@ -3504,6 +3574,38 @@ it.effect("promotes a queued goal by stopping the running turn", () => }), ); +it.effect("stops the running turn for a goal an agent steers into it", () => + Effect.gen(function* () { + const { started, steered, layer, startFirstTurn, read } = yield* goalHarness("goal-raw-steer"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + // Agent sends carry a raw steer target and no delivery intent. + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("goal"), + threadId, + messageId: MessageId.make("message:goal"), + text: "/goal ship it", + attachments: [], + modelSelection: runSelection, + dispatchMode: { type: "steer_active", targetRunId: started[0]!.runId }, + createdBy: "agent", + creationSource: "server", + }); + yield* worker.drain(); + + assert.deepEqual(steered, []); + assert.deepEqual(yield* read(threadId), { + queue: [], + started: ["first", "/goal ship it"], + stopRequested: true, + }); + }).pipe(Effect.provide(layer)); + }), +); + // A fresh message skips compaction as its own turn, which steering a running turn would not. it.effect.each(["next", "/goal ship it", "fresh next"])( "promoting %s into a compaction stops it and sends it next", diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index 2a3a8e5510550..73eaabdde2016 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -913,7 +913,7 @@ it.effect("keeps native maintenance commands out of steering and restart message attachments: [], dispatchMode: { type: scenario.mode, targetRunId: targetRun.id }, }); - if (scenario.name.startsWith("steer-")) { + if (scenario.mode === "steer_active") { yield* dispatch; const queued = (yield* threads.getThreadProjection(launched.threadId)).runs[1]; assert.equal(queued?.status, "queued"); diff --git a/apps/web/src/components/chat/QueuedRunsControl.tsx b/apps/web/src/components/chat/QueuedRunsControl.tsx index fb82f9c858d61..d8318b7279e7d 100644 --- a/apps/web/src/components/chat/QueuedRunsControl.tsx +++ b/apps/web/src/components/chat/QueuedRunsControl.tsx @@ -5,16 +5,18 @@ import { } from "@t3tools/client-runtime/state/runtime"; import { deriveThreadQueueWorkflowState } from "@t3tools/client-runtime/state/thread-workflows"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; +import { isSlashCommand } from "@t3tools/shared/composerTrigger"; import { isAttachmentOnlyBootstrapPrompt, replaceComposerContextReferences, } from "@t3tools/shared/composerContextReferences"; -import type { - ChatAttachment as ContractChatAttachment, - EnvironmentId, - MessageId, - RunId, - ThreadId, +import { + parseGoalCommand, + type ChatAttachment as ContractChatAttachment, + type EnvironmentId, + type MessageId, + type RunId, + type ThreadId, } from "@t3tools/contracts"; import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message"; import { Link } from "@tanstack/react-router"; @@ -273,6 +275,9 @@ export function QueuedRunsControl({ replaceComposerContextReferences(item.text, (reference) => reference.label), ).trim(); const isEditing = item.runId !== null && item.runId === props.editingRunId; + // The server decides on the agent's text, and a goal command can stop the turn. + const sentText = { text: item.message?.text ?? item.text, attachments: item.attachments }; + const movesCommandFirst = isSlashCommand(sentText) && parseGoalCommand(sentText) === null; return (
  • diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 0e48b30d674da..4f60fef9f6088 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -12458,5 +12458,7 @@ "27d76249d09eb69f": "Review-Leitfaden bereit", "faa3bb26abb39c93": "Review-Leitfaden fehlgeschlagen", "b7df38b7d8792d78": "Leitfaden öffnen", - "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden" + "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden", + "d8aaf932f90429c4": "Diesen Befehl an den Anfang der Warteschlange verschieben ({shortcut})", + "425ab15036aec8a4": "Diesen Befehl an den Anfang der Warteschlange verschieben" } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index e5d8d3dc2ed21..6453de11f9da0 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -12467,5 +12467,7 @@ "27d76249d09eb69f": "Review guide ready", "faa3bb26abb39c93": "Review guide failed", "b7df38b7d8792d78": "Open guide", - "9e91e9a77b664e4e": "Could not start a review guide" + "9e91e9a77b664e4e": "Could not start a review guide", + "d8aaf932f90429c4": "Move this command to the front of the queue ({shortcut})", + "425ab15036aec8a4": "Move this command to the front of the queue" } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 4a2868a7e97dc..a73a02ec3bcc9 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -12453,5 +12453,7 @@ "27d76249d09eb69f": "Guía de revisión lista", "faa3bb26abb39c93": "Falló la guía de revisión", "b7df38b7d8792d78": "Abrir guía", - "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión" + "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión", + "d8aaf932f90429c4": "Mover este comando al principio de la cola ({shortcut})", + "425ab15036aec8a4": "Mover este comando al principio de la cola" } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index a0962e52bed39..95ea50d6bf22d 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -12458,5 +12458,7 @@ "27d76249d09eb69f": "Guide de revue prêt", "faa3bb26abb39c93": "Échec du guide de revue", "b7df38b7d8792d78": "Ouvrir le guide", - "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue" + "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue", + "d8aaf932f90429c4": "Placer cette commande en tête de la file d’attente ({shortcut})", + "425ab15036aec8a4": "Placer cette commande en tête de la file d’attente" } diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 0c149c28fbe91..96bf9c7c7bf48 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -12407,5 +12407,7 @@ "27d76249d09eb69f": "レビューガイドの準備ができました", "faa3bb26abb39c93": "レビューガイドの作成に失敗しました", "b7df38b7d8792d78": "ガイドを開く", - "9e91e9a77b664e4e": "レビューガイドを開始できませんでした" + "9e91e9a77b664e4e": "レビューガイドを開始できませんでした", + "d8aaf932f90429c4": "このコマンドをキューの先頭に移動 ({shortcut})", + "425ab15036aec8a4": "このコマンドをキューの先頭に移動" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index c01191b387b4f..d7b1a7628ffc6 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -12402,5 +12402,7 @@ "27d76249d09eb69f": "검토 가이드 준비됨", "faa3bb26abb39c93": "검토 가이드 실패", "b7df38b7d8792d78": "가이드 열기", - "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다" + "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다", + "d8aaf932f90429c4": "이 명령을 대기열 맨 앞으로 이동 ({shortcut})", + "425ab15036aec8a4": "이 명령을 대기열 맨 앞으로 이동" } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5feb95d75c3da..5097324486fb8 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -12458,5 +12458,7 @@ "27d76249d09eb69f": "Guia de revisão pronto", "faa3bb26abb39c93": "O guia de revisão falhou", "b7df38b7d8792d78": "Abrir guia", - "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão" + "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão", + "d8aaf932f90429c4": "Mover este comando para o início da fila ({shortcut})", + "425ab15036aec8a4": "Mover este comando para o início da fila" } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 65a8eede879fa..4c19189200eb5 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -12458,5 +12458,7 @@ "27d76249d09eb69f": "Гид по ревью готов", "faa3bb26abb39c93": "Не удалось создать гид по ревью", "b7df38b7d8792d78": "Открыть гид", - "9e91e9a77b664e4e": "Не удалось запустить гид по ревью" + "9e91e9a77b664e4e": "Не удалось запустить гид по ревью", + "d8aaf932f90429c4": "Переместить эту команду в начало очереди ({shortcut})", + "425ab15036aec8a4": "Переместить эту команду в начало очереди" } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 081857c5dae81..7add0fa009b1d 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -12465,5 +12465,7 @@ "27d76249d09eb69f": "Granskningsguiden är klar", "faa3bb26abb39c93": "Granskningsguiden misslyckades", "b7df38b7d8792d78": "Öppna guiden", - "9e91e9a77b664e4e": "Kunde inte starta en granskningsguide" + "9e91e9a77b664e4e": "Kunde inte starta en granskningsguide", + "d8aaf932f90429c4": "Flytta det här kommandot först i kön ({shortcut})", + "425ab15036aec8a4": "Flytta det här kommandot först i kön" } diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 17d0dd6a93303..5a5c7160230de 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -12484,5 +12484,7 @@ "27d76249d09eb69f": "审查导览已就绪", "faa3bb26abb39c93": "审查导览生成失败", "b7df38b7d8792d78": "打开导览", - "9e91e9a77b664e4e": "无法开始生成审查导览" + "9e91e9a77b664e4e": "无法开始生成审查导览", + "d8aaf932f90429c4": "将此命令移到队列最前面 ({shortcut})", + "425ab15036aec8a4": "将此命令移到队列最前面" } diff --git a/docs/user/composer.md b/docs/user/composer.md index 94b0219e5ab5a..53017052a2a01 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -69,6 +69,10 @@ are saved on the server and can be edited or removed before they send. When Enter sends, `Cmd+Enter` on macOS or `Ctrl+Enter` on Windows and Linux uses the opposite action: it steers when your default is Queue and queues when your default is Steer. +A slash command such as `/compact` or `/context` waits for the current turn to +finish, because a command steered into a turn would replace the agent's task. +Sending a queued command now moves it to the front of the queue. [Goal](#goals) +commands are the exception: some can stop the current turn. If your **Send shortcut** requires `Cmd+Enter` or `Ctrl+Enter`, that shortcut uses your default follow-up behavior; add **Shift** to use the opposite action. This applies only to multiline messages when you choose the multiline send option. @@ -271,8 +275,9 @@ shortcut described above. On web and desktop, queued messages appear at the end of the thread as dashed messages that have not been sent yet. On mobile they appear above the composer. Each shows its text and any attached -images. **Send now** sends a message right away, into the running turn if there is one. You can -also edit or remove it. +images. **Send now** sends a message right away, into the running turn if there is one. While a +turn runs, a slash command moves to the front of the queue instead. You can also edit or +remove it. If you stop the agent or the server restarts, queued messages keep their order and are held. Press **Resume** in an empty composer to continue. For stopped runs and usage limits, diff --git a/packages/shared/src/composerTrigger.ts b/packages/shared/src/composerTrigger.ts index 96a0a877d14df..2a95d6b34cd0a 100644 --- a/packages/shared/src/composerTrigger.ts +++ b/packages/shared/src/composerTrigger.ts @@ -137,6 +137,14 @@ export function replaceTextRange( return { text: nextText, cursor: safeStart + replacement.length }; } +/** A message that only invokes a slash command, such as `/context all`, not a path like `/src/a.ts`. */ +export function isSlashCommand(message: { + readonly text: string; + readonly attachments: ReadonlyArray; +}): boolean { + return message.attachments.length === 0 && /^\/[\w:-]+(?:\s|$)/u.test(message.text.trim()); +} + /** `/clear` as the whole message arms a fresh session instead of sending. */ export function isClearComposerCommand(text: string): boolean { return /^\/clear\s*$/i.test(text.trim()); diff --git a/scripts/scenarios/steered-compact-waits-for-turn.e2e.ts b/scripts/scenarios/steered-compact-waits-for-turn.e2e.ts new file mode 100644 index 0000000000000..7ed990805fd22 --- /dev/null +++ b/scripts/scenarios/steered-compact-waits-for-turn.e2e.ts @@ -0,0 +1,71 @@ +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; + +import { T3_HOME } from "../e2e.config.ts"; +import { makeState, runPromise, test, WEB } from "./t3.ts"; + +const SettingsJson = Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)); +const decodeSettings = Schema.decodeEffect(SettingsJson); +const encodeSettings = Schema.encodeEffect(SettingsJson); + +const threadRuntimeSettings = Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const settingsPath = (yield* Path.Path).join(T3_HOME, "userdata/settings.json"); + const original = yield* fs.readFileString(settingsPath); + const settings = yield* decodeSettings(original); + return { + supervise: fs.writeFileString( + settingsPath, + yield* encodeSettings({ ...settings, defaultRuntimeMode: "approval-required" }), + ), + restore: fs.writeFileString(settingsPath, original), + }; +}); + +test("/compact sent while the agent works waits for the turn", WEB, async ({ t3, app, screen }) => { + const project = await t3.project("demo"); + // The showcase recording streams for several seconds, long enough to send into its turn. + const thread = await t3.thread({ + project, + title: "Long work", + messages: ["Show me around"], + model: "showcase", + }); + await t3.open(thread); + + const composer = screen.getByRole("textbox"); + await composer.tap(); + await composer.pressSequentially("Show me again"); + await composer.press("Enter"); + await expect(screen.getByRole("button", "Stop generation")).toBeVisible(); + + // The trailing space closes the slash menu so Enter sends instead of picking a command. + await composer.pressSequentially("/compact "); + await composer.press("Enter"); + await app.screenshot("compact-sent"); + await expect(screen.getByRole("button", "Edit queued message")).toBeVisible(); + + const settings = await runPromise(threadRuntimeSettings); + try { + // An approval holds this turn open, so the queued command stays put while Send now is hovered. + await runPromise(settings.supervise); + const waiting = await t3.thread({ + project, + title: "Waiting work", + messages: ["Change the file"], + model: "approval", + }); + await runPromise(makeState(T3_HOME).cli(["thread", "send", waiting.threadId, "/compact"])); + await t3.open(waiting); + await screen.getByRole("button", "Send now").hover(); + await expect( + screen.getByText("Move this command to the front of the queue", { exact: false }), + ).toBeVisible(); + await app.screenshot("send-now-tooltip"); + } finally { + await runPromise(settings.restore); + } +}); From 989d7ec882aa1b7e510cd44f93ab5fe61368058b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 05:17:55 -0800 Subject: [PATCH 009/139] perf(server): push and commit-and-push read the full git status once instead of three times (#40305) --- apps/server/src/git/GitManager.test.ts | 2 +- apps/server/src/git/GitManager.ts | 4 +++- apps/server/src/vcs/GitVcsDriver.ts | 2 ++ apps/server/src/vcs/GitVcsDriverCore.ts | 24 +++++++++++++++++------- 4 files changed, 23 insertions(+), 9 deletions(-) diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 9dc3407597a4f..064427a3727f5 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -4198,7 +4198,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { ), ); yield* Deferred.await(gate.reached); - NodeFS.writeFileSync(NodePath.join(repoDir, ".git", "index.lock"), ""); + NodeFS.appendFileSync(NodePath.join(repoDir, ".git", "config"), "\n[broken\n"); yield* Deferred.succeed(gate.release, undefined); const result = yield* Fiber.join(action); diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index 9db4fbfc27755..dab6d4d20924e 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -2256,7 +2256,9 @@ export const make = Effect.gen(function* () { const finalStatus = result.action === "commit" ? null - : yield* gitCore.statusDetails(cwd).pipe(Effect.orElseSucceed(() => null)); + : yield* gitCore + .statusDetailsRemote(cwd, { refreshUpstream: false, includeAheadOfDefault: false }) + .pipe(Effect.orElseSucceed(() => null)); if (finalStatus?.branch) { finalBranchContext = { branch: finalStatus.branch, diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 700ad3b3571c9..f341ebd987a6c 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -337,6 +337,8 @@ export interface GitSetBranchUpstreamInput { export interface GitRemoteStatusOptions { readonly refreshUpstream?: boolean; + /** False skips the base-branch lookup and reports `aheadOfDefaultCount` as 0. */ + readonly includeAheadOfDefault?: boolean; } /** diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 7c4363b1647be..7fe1dab187ac5 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -2540,6 +2540,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const readStatusDetailsRemote = Effect.fn("readStatusDetailsRemote")(function* ( cwd: string, refreshUpstream: boolean, + includeAheadOfDefault = true, ) { const branchResult = yield* executeGitWithStableDiagnostics( "GitVcsDriver.statusDetailsRemote.branch", @@ -2640,7 +2641,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* (branch === defaultBranch || (defaultBranch === null && (branch === "main" || branch === "master"))); const aheadOfDefaultCount = - branch && !isDefaultBranch + branch && !isDefaultBranch && includeAheadOfDefault ? upstreamRef === null ? aheadCount : yield* computeAheadCountAgainstBase(cwd, branch).pipe(Effect.orElseSucceed(() => 0)) @@ -3004,22 +3005,29 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return yield* readStatusDetailsLocal(cwd, options); }); - const statusDetails: GitVcsDriver.GitVcsDriver["Service"]["statusDetails"] = Effect.fn( - "statusDetails", - )(function* (cwd) { - yield* refreshStatusUpstreamIfStale(cwd).pipe( + const refreshStatusUpstream = (cwd: string) => + refreshStatusUpstreamIfStale(cwd).pipe( Effect.catchTags({ GitCommandError: (error) => isMissingGitCwdError(error) ? Effect.void : Effect.fail(error), }), Effect.ignoreCause({ log: true }), ); + + const statusDetails: GitVcsDriver.GitVcsDriver["Service"]["statusDetails"] = Effect.fn( + "statusDetails", + )(function* (cwd) { + yield* refreshStatusUpstream(cwd); return yield* readStatusDetailsLocal(cwd); }); const statusDetailsRemote: GitVcsDriver.GitVcsDriver["Service"]["statusDetailsRemote"] = Effect.fn("statusDetailsRemote")(function* (cwd, options) { - return yield* readStatusDetailsRemote(cwd, options?.refreshUpstream !== false); + return yield* readStatusDetailsRemote( + cwd, + options?.refreshUpstream !== false, + options?.includeAheadOfDefault !== false, + ); }); const status: GitVcsDriver.GitVcsDriver["Service"]["status"] = (input) => @@ -3658,7 +3666,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const pushCurrentBranch: GitVcsDriver.GitVcsDriver["Service"]["pushCurrentBranch"] = Effect.fn( "pushCurrentBranch", )(function* (cwd, fallbackBranch, options) { - const details = yield* statusDetails(cwd); + // Refresh first so the branch, upstream and divergence reads below stay close together. + yield* refreshStatusUpstream(cwd); + const details = yield* readStatusDetailsRemote(cwd, false, false); const branch = details.branch ?? fallbackBranch; if (!branch) { return yield* new GitCommandError({ From 0c921e1fdf6feda7d1bab2be83e3916c6f4509c2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 05:28:23 -0800 Subject: [PATCH 010/139] fix(server): ACP session/load replay no longer pins background work (#40328) --- .../Adapters/AcpAdapterV2.test.ts | 89 +++++++++++ packages/provider-acp/src/server/adapter.ts | 149 ++++++++++-------- 2 files changed, 173 insertions(+), 65 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 4946377c94502..d79257944c8e9 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -9234,6 +9234,95 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect("session/load replay does not leave post-settle background work pending", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const instanceId = ProviderInstanceId.make("acp-test"); + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdateHandler: Parameters[0] | undefined; + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + enablePostSettleContinuation: true, + normalizeToolCall: normalizeXAiAcpToolCallState, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime) => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdateHandler = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + }), + }), + }, + continuationRequests: { offer: () => Effect.void }, + }); + const threadId = ThreadId.make("thread-acp-load-replay-background"); + 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-load-replay-background"), + modelSelection, + runtimePolicy, + }); + if (runtime.hasPendingBackgroundWork === undefined) { + return yield* Effect.die("ACP runtime must expose hasPendingBackgroundWork."); + } + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + assert.isFalse(yield* runtime.hasPendingBackgroundWork); + assert.isDefined(sessionUpdateHandler, "session update handler must be wired"); + + // A large session/load replays its tail after the session is active. + yield* sessionUpdateHandler!({ + sessionId: "mock-session-1", + _meta: { isReplay: true }, + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "old reply from history" }, + }, + }); + yield* sessionUpdateHandler!({ + sessionId: "mock-session-1", + _meta: { isReplay: true }, + update: { + sessionUpdate: "tool_call", + toolCallId: "replayed-tool-1", + title: "run_command", + kind: "execute", + status: "completed", + rawInput: { command: "echo old" }, + }, + }); + yield* Effect.yieldNow; + + assert.isFalse( + yield* runtime.hasPendingBackgroundWork, + "replayed history must not pin background work", + ); + const snapshot = yield* runtime.readThreadSnapshot({ providerThread }); + assert.deepEqual( + snapshot.messages.map((message) => message.text), + ["old reply from history"], + ); + }).pipe(Effect.provide(layerTest)), + ); + it.effect("projects completed-root carryover eagerly and drain cannot resurrect it", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index cf7bb6c0f92fd..a712d40629e60 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -87,6 +87,7 @@ import { mergeToolCallState, parsePermissionRequest, parseSessionUpdateEvent, + sessionUpdateIsReplay, toolCallVisibleOutputChanged, withTrackedPermissionToolCall, type AcpPlanUpdate, @@ -5650,6 +5651,80 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ), ); + const recordLoadedHistory = Effect.fnUntraced(function* ( + notification: EffectAcpSchema.SessionNotification, + live: boolean, + ) { + const update = notification.update; + if ( + notification.sessionId !== + ((yield* Ref.get(loadingSessionId)) ?? (yield* Ref.get(activeSessionId))) + ) + return; + if ( + update.sessionUpdate === "user_message_chunk" || + update.sessionUpdate === "agent_message_chunk" || + update.sessionUpdate === "agent_thought_chunk" + ) { + const text = acpContentBlockDisplayText(update.content); + if (text === undefined) return; + const lateBackgroundMutations = + update.content.type === "text" + ? (flavor.extractBackgroundToolMutation?.(text) ?? []) + : []; + if (live) { + for (const lateBackgroundMutation of lateBackgroundMutations) { + yield* applyLateBackgroundMutation(notification.sessionId, lateBackgroundMutation); + } + } + if (lateBackgroundMutations.length === 0 && !acpIsMonitorChatter(text)) { + yield* appendLoadedHistory( + notification, + update.sessionUpdate === "user_message_chunk" + ? "user" + : update.sessionUpdate === "agent_thought_chunk" + ? "thought" + : "assistant", + text, + ); + } + } else if ( + update.sessionUpdate === "user_message" || + update.sessionUpdate === "agent_message" || + update.sessionUpdate === "agent_thought" + ) { + if (update.content === undefined) return; + const text = (update.content ?? []) + .flatMap((content) => { + const display = acpContentBlockDisplayText(content); + return display === undefined ? [] : [display]; + }) + .join("\n"); + yield* appendLoadedHistory( + notification, + update.sessionUpdate === "user_message" + ? "user" + : update.sessionUpdate === "agent_thought" + ? "thought" + : "assistant", + text, + true, + ); + } else if ( + update.sessionUpdate === "tool_call" || + update.sessionUpdate === "tool_call_update" || + update.sessionUpdate === "plan" || + update.sessionUpdate === "plan_update" || + update.sessionUpdate === "plan_removed" + ) { + yield* Ref.update(snapshot, (current) => ({ + ...current, + loadingRole: null, + loadingMessageId: null, + })); + } + }); + const handleSessionUpdate = Effect.fnUntraced(function* ( notification: EffectAcpSchema.SessionNotification, ) { @@ -5898,71 +5973,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (wakeOutcome.stopProcessing) { return; } - if ( - notification.sessionId !== - ((yield* Ref.get(loadingSessionId)) ?? (yield* Ref.get(activeSessionId))) - ) - return; - if ( - update.sessionUpdate === "user_message_chunk" || - update.sessionUpdate === "agent_message_chunk" || - update.sessionUpdate === "agent_thought_chunk" - ) { - const text = acpContentBlockDisplayText(update.content); - if (text === undefined) return; - const lateBackgroundMutations = - update.content.type === "text" - ? (flavor.extractBackgroundToolMutation?.(text) ?? []) - : []; - for (const lateBackgroundMutation of lateBackgroundMutations) { - yield* applyLateBackgroundMutation(notification.sessionId, lateBackgroundMutation); - } - if (lateBackgroundMutations.length === 0 && !acpIsMonitorChatter(text)) { - yield* appendLoadedHistory( - notification, - update.sessionUpdate === "user_message_chunk" - ? "user" - : update.sessionUpdate === "agent_thought_chunk" - ? "thought" - : "assistant", - text, - ); - } - } else if ( - update.sessionUpdate === "user_message" || - update.sessionUpdate === "agent_message" || - update.sessionUpdate === "agent_thought" - ) { - if (update.content === undefined) return; - const text = (update.content ?? []) - .flatMap((content) => { - const display = acpContentBlockDisplayText(content); - return display === undefined ? [] : [display]; - }) - .join("\n"); - yield* appendLoadedHistory( - notification, - update.sessionUpdate === "user_message" - ? "user" - : update.sessionUpdate === "agent_thought" - ? "thought" - : "assistant", - text, - true, - ); - } else if ( - update.sessionUpdate === "tool_call" || - update.sessionUpdate === "tool_call_update" || - update.sessionUpdate === "plan" || - update.sessionUpdate === "plan_update" || - update.sessionUpdate === "plan_removed" - ) { - yield* Ref.update(snapshot, (current) => ({ - ...current, - loadingRole: null, - loadingMessageId: null, - })); - } + yield* recordLoadedHistory(notification, true); return; } if (context.finalized) return; @@ -7016,6 +7027,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( Effect.fnUntraced( function* (rawNotification: EffectAcpSchema.SessionNotification) { if (flavor.ignoreSessionUpdate?.(rawNotification) === true) return; + // Replayed history feeds snapshots only; it must not drive live turn or wake state. + if (sessionUpdateIsReplay(rawNotification)) { + yield* recordLoadedHistory( + flavor.normalizeSessionUpdate?.(rawNotification) ?? rawNotification, + false, + ); + return; + } yield* notePromptProgress(rawNotification); const nativePromptId = flavor.forkFromTurn?.nativeTurnId(rawNotification); if (nativePromptId !== undefined) { From 232f52c8db1998fc566c4bb5940db6a12c898c8d Mon Sep 17 00:00:00 2001 From: Arif Ali <51419655+arifali123@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:28:38 -0800 Subject: [PATCH 011/139] fix(mobile): confirming a push to the default branch no longer opens the thread a second time (#40311) Co-authored-by: Orin Co-authored-by: Julius Marminge --- .../features/threads/git/GitConfirmSheet.tsx | 10 +++-- .../thread-inspector-navigation.test.tsx | 41 ++++++++++++++++++- .../threads/thread-inspector-navigation.ts | 38 +++++++++++++---- 3 files changed, 74 insertions(+), 15 deletions(-) diff --git a/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx b/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx index b916b49697fc5..1da0ec450a572 100644 --- a/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx @@ -3,7 +3,7 @@ import { sourceControlClients } from "@t3tools/client-runtime/source-control-cli import { resolveAutoFeatureBranchName } from "@t3tools/shared/git"; import * as Arr from "effect/Array"; import * as Result from "effect/Result"; -import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native"; +import { useNavigation, type StaticScreenProps } from "@react-navigation/native"; import { useGT, useMessages } from "gt-react-native"; import { useCallback, useMemo } from "react"; import { View } from "react-native"; @@ -20,6 +20,7 @@ import { type GitRepositoryRouteParams, } from "../../../state/thread-git-target"; import { vcsEnvironment } from "../../../state/vcs"; +import { useReturnToThread } from "../thread-inspector-navigation"; import { SheetActionButton } from "./gitSheetComponents"; type GitConfirmSheetProps = StaticScreenProps< @@ -38,6 +39,7 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { const gt = useGT(); const messages = useMessages(); const navigation = useNavigation(); + const returnToThread = useReturnToThread(); const repository = gitRepositoryTargetFromRoute(props.route.params); const gitState = useSelectedThreadGitState(repository); const gitActions = useSelectedThreadGitActions(repository); @@ -89,7 +91,7 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { const continuePendingAction = async () => { if (!canWriteSourceControl || !confirmAction) return; - navigation.dispatch(StackActions.replace("Thread", { environmentId, threadId })); + returnToThread({ environmentId, threadId }); await gitActions.onRunSelectedThreadGitAction({ action: confirmAction, ...(params.commitMessage ? { commitMessage: params.commitMessage } : {}), @@ -99,7 +101,7 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { const movePendingActionToFeatureBranch = useCallback(async () => { if (!canCreateFeatureBranch || !confirmAction) return; - navigation.dispatch(StackActions.replace("Thread", { environmentId, threadId })); + returnToThread({ environmentId, threadId }); if (includesCommit) { await gitActions.onRunSelectedThreadGitAction({ @@ -131,7 +133,7 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { gitState.selectedThreadBranches, includesCommit, params, - navigation, + returnToThread, environmentId, threadId, ]); diff --git a/apps/mobile/src/features/threads/thread-inspector-navigation.test.tsx b/apps/mobile/src/features/threads/thread-inspector-navigation.test.tsx index 404d28184d7b8..f2398d6e1fc90 100644 --- a/apps/mobile/src/features/threads/thread-inspector-navigation.test.tsx +++ b/apps/mobile/src/features/threads/thread-inspector-navigation.test.tsx @@ -29,7 +29,7 @@ vi.mock("@react-navigation/native", async () => { }; }); -import { useOpenThreadInspector } from "./thread-inspector-navigation"; +import { useOpenThreadInspector, useReturnToThread } from "./thread-inspector-navigation"; import { useOpenLinkedThread, useOpenLinkedThreadRead } from "./useOpenLinkedThread"; const requireNavigation = NodeModule.createRequire( @@ -45,7 +45,15 @@ function setup(fromAgents: boolean, fullscreen = false, inspectorSupported = tru (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; const router = StackRouter({}); const options = { - routeNames: ["Home", "Thread", "ThreadAgents", "ThreadInspectorFullscreen", "LinkedThread"], + routeNames: [ + "Home", + "Thread", + "ThreadAgents", + "ThreadInspectorFullscreen", + "LinkedThread", + "ThreadReview", + "GitConfirm", + ], routeParamList: {}, routeGetIdList: {}, }; @@ -70,14 +78,17 @@ function setup(fromAgents: boolean, fullscreen = false, inspectorSupported = tru let openInspector: ReturnType; let openLinkedThread: ReturnType; let openLinkedThreadRead: ReturnType; + let returnToThread: ReturnType; function Probe() { const open = useOpenThreadInspector(); const openLinked = useOpenLinkedThread(); const openLinkedRead = useOpenLinkedThreadRead(); + const returnTo = useReturnToThread(); useLayoutEffect(() => { openInspector = open; openLinkedThread = openLinked; openLinkedThreadRead = openLinkedRead; + returnToThread = returnTo; }); return null; } @@ -103,6 +114,9 @@ function setup(fromAgents: boolean, fullscreen = false, inspectorSupported = tru openLinkedRead(...input: Parameters) { act(() => openLinkedThreadRead(...input)); }, + returnTo(thread: Parameters[0]) { + act(() => returnToThread(thread)); + }, [Symbol.dispose]() { act(() => root.unmount()); }, @@ -190,6 +204,29 @@ it.each([ }, ); +it.each([ + { confirmFrom: "parent", routes: ["Home", "Thread"] }, + // A side thread's review, opened from the parent's inspector, sits above the parent's route. + { confirmFrom: "child", routes: ["Home", "Thread", "ThreadReview", "Thread"] }, +])( + "returns from a Git confirmation to the $confirmFrom thread without replacing another", + ({ confirmFrom, routes }) => { + using screen = setup(false); + const inspector = { type: "device", ...screen.source } as const; + screen.open(inspector); + const thread = { ...screen.source, threadId: confirmFrom }; + if (confirmFrom !== "parent") screen.dispatch(StackActions.push("ThreadReview", thread)); + screen.dispatch(StackActions.push("GitConfirm", thread)); + screen.returnTo(thread); + expect(screen.state.routes.map((route) => route.name)).toEqual(routes); + expect(screen.state.routes[1]).toMatchObject({ + key: screen.parentKey, + params: { ...screen.source, prompt: "retained prompt", inspector }, + }); + expect(screen.state.routes.at(-1)?.params).toMatchObject(thread); + }, +); + it("switches between subagents and devices in the same parent route", () => { using screen = setup(false); screen.open({ type: "thread", environmentId: screen.source.environmentId, threadId: "child" }); diff --git a/apps/mobile/src/features/threads/thread-inspector-navigation.ts b/apps/mobile/src/features/threads/thread-inspector-navigation.ts index 966dd1a92a632..04fc59ed636e1 100644 --- a/apps/mobile/src/features/threads/thread-inspector-navigation.ts +++ b/apps/mobile/src/features/threads/thread-inspector-navigation.ts @@ -41,15 +41,7 @@ export function useOpenThreadInspector() { if (presentation === "full-screen") return false; if (openInInspector) openInInspector(target); else { - const parent = navigation.getState()?.routes.findLast((route) => route.name === "Thread"); - if ( - !parent?.params || - !("environmentId" in parent.params) || - parent.params.environmentId !== source.environmentId || - !("threadId" in parent.params) || - parent.params.threadId !== source.threadId - ) - return false; + if (!isNearestThreadRoute(navigation.getState(), source)) return false; navigation.dispatch( StackActions.popTo("Thread", { ...source, inspector: target }, { merge: true }), ); @@ -57,3 +49,31 @@ export function useOpenThreadInspector() { return true; }; } + +/** Closes the screens above `thread`, or opens it when the nearest thread route is another one. */ +export function useReturnToThread() { + const navigation = useNavigation(); + return (thread: { readonly environmentId: string; readonly threadId: string }) => + navigation.dispatch( + isNearestThreadRoute(navigation.getState(), thread) + ? StackActions.popTo("Thread", thread, { merge: true }) + : StackActions.replace("Thread", thread), + ); +} + +// `Thread` has no `getId`, so `popTo("Thread")` lands on the nearest one whatever thread it shows. +function isNearestThreadRoute( + state: + | { readonly routes: ReadonlyArray<{ readonly name: string; readonly params?: object }> } + | undefined, + thread: { readonly environmentId: string; readonly threadId: string }, +) { + const params = state?.routes.findLast((route) => route.name === "Thread")?.params; + return ( + params !== undefined && + "environmentId" in params && + params.environmentId === thread.environmentId && + "threadId" in params && + params.threadId === thread.threadId + ); +} From 9c25b71395e36bba1e86f3f093348f0ad966495e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 05:31:49 -0800 Subject: [PATCH 012/139] =?UTF-8?q?fix(opencode):=20Usage=20=E2=86=92=20Li?= =?UTF-8?q?mits=20shows=20why=20OpenCode=20could=20not=20read=20usage=20(#?= =?UTF-8?q?40340)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/server/v2/OpenCode2Client.test.ts | 12 ++++++++++++ .../src/server/v2/usageLimits.ts | 19 +++++++++++++++---- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts b/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts index ff77d8ef72a2f..701ad57fe488a 100644 --- a/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts +++ b/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts @@ -467,6 +467,16 @@ describe("OpenCode2Client usage limits", () => { "unsupported", ], [503, {}, "probeFailed"], + [ + 503, + { + _tag: "ServiceUnavailableError", + message: + "OpenCode Console budgets are unavailable: StatusCode: non 2xx status code (401 GET https://opencode.ai/console/api/policies/current-budgets)", + service: "opencode", + }, + "probeFailed", + ], [401, {}, "probeFailed"], [200, { data: { workspace: {} } }, "probeFailed"], ] as const) { @@ -487,6 +497,8 @@ describe("OpenCode2Client usage limits", () => { else assert.strictEqual(result?.unavailable?.reason, reason); if ("data" in body && body.data === null) assert.include(result?.unavailable?.message ?? "", "signed in"); + if ("message" in body) + assert.include(result?.unavailable?.message ?? "", "OpenCode Console budgets"); } }), ); diff --git a/packages/provider-opencode/src/server/v2/usageLimits.ts b/packages/provider-opencode/src/server/v2/usageLimits.ts index dd28770b9c5c4..bdf678e424692 100644 --- a/packages/provider-opencode/src/server/v2/usageLimits.ts +++ b/packages/provider-opencode/src/server/v2/usageLimits.ts @@ -61,6 +61,9 @@ const Providers = Schema.Struct({ ), }); +const ErrorBody = Schema.Struct({ message: Schema.String }); +const probeFailedMessage = "OpenCode could not read workspace usage."; + const resetTime = (ms: number) => DateTime.formatIso(DateTime.makeUnsafe(ms)); const budgetPercent = (spent: number, limit: number) => limit <= 0 ? 100 : clampPercent((spent / limit) * 100); @@ -81,9 +84,17 @@ export const readServerUsageLimits = Effect.fn("OpenCode2Client.usageLimits")(fu response.headers["content-type"]?.split(";")[0]?.trim() === "text/html") ) return undefined; - const body = yield* HttpClientResponse.filterStatusOk(response).pipe( - Effect.flatMap(HttpClientResponse.schemaBodyJson(ResponseBody)), - ); + // OpenCode names the upstream cause, such as an expired Console login, in its error body. + if (response.status < 200 || response.status >= 300) + return makeUnavailableUsageLimits({ + checkedAt, + reason: "probeFailed", + message: yield* HttpClientResponse.schemaBodyJson(ErrorBody)(response).pipe( + Effect.map((error) => error.message.trim() || probeFailedMessage), + Effect.orElseSucceed(() => probeFailedMessage), + ), + }); + const body = yield* HttpClientResponse.schemaBodyJson(ResponseBody)(response); if (body.data === null) return makeUnavailableUsageLimits({ checkedAt, @@ -186,7 +197,7 @@ export const readServerUsageLimits = Effect.fn("OpenCode2Client.usageLimits")(fu makeUnavailableUsageLimits({ checkedAt, reason: "probeFailed", - message: "OpenCode could not read workspace usage.", + message: probeFailedMessage, }), ), ); From d3bb8f810898b939712aea7629e94073ae50c0f8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 05:56:16 -0800 Subject: [PATCH 013/139] perf(server): deleting a thread's worktree refreshes git status once, not twice (#40337) --- apps/server/src/ws.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index d96b91f30d62a..afa030d4d7e9c 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -3295,7 +3295,8 @@ export const layerWsRpc = ( Effect.flatMap((removed) => removed ? Effect.void : gitWorkflow.removeWorktree(input), ), - Effect.tap(() => refreshGitStatus(input.cwd)), + // No project-root refresh here: the client awaits vcs.refreshStatus right after, and a + // second refresh would queue behind this one and reread an unchanged repository. // Subscribers of the removed checkout learn it is no longer a repository. Effect.tap(() => vcsStatusBroadcaster From ece4964b8ea2ac15cf59658c1a2112d1e2bb95f5 Mon Sep 17 00:00:00 2001 From: Simone Date: Sat, 21 Nov 2026 14:56:29 +0100 Subject: [PATCH 014/139] fix(antigravity): accept null skill manifest lists (#40287) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../src/provider/Drivers/AntigravitySkills.test.ts | 10 +++++++++- .../src/provider/Drivers/AntigravitySkills.ts | 13 +++++-------- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts index 96dd2c5dbaa44..0033755bfe706 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts @@ -435,8 +435,16 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { yield* fileSystem.writeFileString( path.join(input.cwd, ".agents", "skills.json"), JSON.stringify({ + entries: null, + inherits: [{ path: "workspace-skills.json", include_only: null }], + }), + ); + yield* fileSystem.writeFileString( + path.join(input.cwd, "workspace-skills.json"), + JSON.stringify({ + inherits: null, entries: [ - { path: "tools/skills/deploy/SKILL.md" }, + { path: "tools/skills/deploy/SKILL.md", exclude: null }, { path: "tools/skills/internal/SKILL.md", exclude: ["internal"] }, ], }), diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.ts b/apps/server/src/provider/Drivers/AntigravitySkills.ts index 51fd5535c8226..f69b3d1c455be 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.ts @@ -48,14 +48,14 @@ const SkillFrontmatter = Schema.Struct({ const decodeSkillFrontmatter = Schema.decodeUnknownSync(SkillFrontmatter); const SkillConfigEntry = Schema.Struct({ path: Schema.String, - include_only: Schema.optional(Schema.Array(Schema.String)), - exclude: Schema.optional(Schema.Array(Schema.String)), + include_only: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))), + exclude: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))), }); const decodeSkillsConfig = Schema.decodeUnknownOption( Schema.fromJsonString( Schema.Struct({ - inherits: Schema.optional(Schema.Array(SkillConfigEntry)), - entries: Schema.optional(Schema.Array(SkillConfigEntry)), + inherits: Schema.optional(Schema.NullOr(Schema.Array(SkillConfigEntry))), + entries: Schema.optional(Schema.NullOr(Schema.Array(SkillConfigEntry))), }), ), ); @@ -289,10 +289,7 @@ function matchesSkillFilter(entry: string, filter: SkillEntryFilter): boolean { function narrowSkillFilter( parent: SkillEntryFilter, - entry: { - readonly include_only?: ReadonlyArray | undefined; - readonly exclude?: ReadonlyArray | undefined; - }, + entry: typeof SkillConfigEntry.Type, ): SkillEntryFilter { const includeGroups = entry.include_only && entry.include_only.length > 0 From e0f3ab9e78a72e86727b6664488f9a19a1e8fe7b Mon Sep 17 00:00:00 2001 From: panol <302941691@qq.com> Date: Sat, 21 Nov 2026 21:57:47 +0800 Subject: [PATCH 015/139] fix(mobile): text selection menu items follow the UI language (#40297) Co-authored-by: Julius Marminge --- apps/mobile/src/i18n/translations/de.json | 6 ++++-- apps/mobile/src/i18n/translations/en.json | 6 ++++-- apps/mobile/src/i18n/translations/es.json | 6 ++++-- apps/mobile/src/i18n/translations/fr.json | 6 ++++-- apps/mobile/src/i18n/translations/ja.json | 6 ++++-- apps/mobile/src/i18n/translations/ko.json | 6 ++++-- apps/mobile/src/i18n/translations/pt-BR.json | 6 ++++-- apps/mobile/src/i18n/translations/ru.json | 6 ++++-- apps/mobile/src/i18n/translations/sv.json | 6 ++++-- apps/mobile/src/i18n/translations/zh.json | 6 ++++-- apps/mobile/src/native/EnrichedMarkdownText.tsx | 17 +++++++++++++++++ 11 files changed, 57 insertions(+), 20 deletions(-) diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 8777f08e663ce..e0eb437599e38 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -1546,6 +1546,10 @@ "8f2e6a13eee27d59": "Überschriften", "29005b7a742cae1e": "Links", "728a49012344e673": "Bilder", + "a034d65164bb39de": "Kopieren", + "0165ef55eb6c8a99": "Als Markdown kopieren", + "439737cb6de2a5b3": "Bild-URL kopieren", + "d3d24474c922eef2": "{count} Bild-URLs kopieren", "f18f6d80b6bd08a0": "Modellreferenz kopieren", "d7a551536aa43f3e": "Modellreferenz teilen", "9f1b29c948772f0f": "Link öffnen", @@ -1553,7 +1557,6 @@ "d7dc565616d13a5c": "Link teilen", "51244cd196696a00": "Zitieren", "6cdca065884f77f2": "Kopieren", - "0165ef55eb6c8a99": "Als Markdown kopieren", "7c1923203049d602": "Code kopieren", "74d986aed0381cb0": "Der Diagramm-Renderer konnte nicht geladen werden.", "9cc6288e83305ca3": "Das Diagramm konnte nicht gerendert werden.", @@ -1862,7 +1865,6 @@ "1d0a7acef4a95536": "Akzeptieren", "255ae21697461ef6": "Übernimm die Steuerung, um zu antworten.", "d2a40ef08ef016ec": "{command} kopieren", - "a034d65164bb39de": "Kopieren", "e0cfab9ded209e81": "Neu verbinden", "b00379f06c304b6a": "Browser öffnen, {title}", "149eba5f977b0549": "Öffnet den Browser-Tab im Vollbild", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index dfe3a473fe248..bca87cee0884f 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -1546,6 +1546,10 @@ "8f2e6a13eee27d59": "Headings", "29005b7a742cae1e": "Links", "728a49012344e673": "Images", + "a034d65164bb39de": "Copy", + "0165ef55eb6c8a99": "Copy as Markdown", + "439737cb6de2a5b3": "Copy Image URL", + "d3d24474c922eef2": "Copy {count} Image URLs", "f18f6d80b6bd08a0": "Copy model reference", "d7a551536aa43f3e": "Share model reference", "9f1b29c948772f0f": "Open link", @@ -1553,7 +1557,6 @@ "d7dc565616d13a5c": "Share link", "51244cd196696a00": "Cite", "6cdca065884f77f2": "Copy", - "0165ef55eb6c8a99": "Copy as Markdown", "7c1923203049d602": "Copy code", "74d986aed0381cb0": "The diagram renderer failed to load.", "9cc6288e83305ca3": "The diagram could not be rendered.", @@ -1862,7 +1865,6 @@ "1d0a7acef4a95536": "Accept", "255ae21697461ef6": "Take control to respond.", "d2a40ef08ef016ec": "Copy {command}", - "a034d65164bb39de": "Copy", "e0cfab9ded209e81": "Reconnect", "b00379f06c304b6a": "Open browser, {title}", "149eba5f977b0549": "Opens the browser tab full screen", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 05f58a63227d3..3f73e995b2521 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -1546,6 +1546,10 @@ "8f2e6a13eee27d59": "Encabezados", "29005b7a742cae1e": "Enlaces", "728a49012344e673": "Imágenes", + "a034d65164bb39de": "Copiar", + "0165ef55eb6c8a99": "Copiar como Markdown", + "439737cb6de2a5b3": "Copiar URL de la imagen", + "d3d24474c922eef2": "Copiar {count} URL de imágenes", "f18f6d80b6bd08a0": "Copiar referencia del modelo", "d7a551536aa43f3e": "Compartir referencia del modelo", "9f1b29c948772f0f": "Abrir enlace", @@ -1553,7 +1557,6 @@ "d7dc565616d13a5c": "Compartir enlace", "51244cd196696a00": "Citar", "6cdca065884f77f2": "Copiar", - "0165ef55eb6c8a99": "Copiar como Markdown", "7c1923203049d602": "Copiar código", "74d986aed0381cb0": "No se pudo cargar el renderizador de diagramas.", "9cc6288e83305ca3": "No se pudo renderizar el diagrama.", @@ -1862,7 +1865,6 @@ "1d0a7acef4a95536": "Aceptar", "255ae21697461ef6": "Toma el control para responder.", "d2a40ef08ef016ec": "Copiar {command}", - "a034d65164bb39de": "Copiar", "e0cfab9ded209e81": "Volver a conectar", "b00379f06c304b6a": "Abrir navegador, {title}", "149eba5f977b0549": "Abre la pestaña del navegador a pantalla completa", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index f661c315215c0..3aff16728eeff 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -1546,6 +1546,10 @@ "8f2e6a13eee27d59": "Titres", "29005b7a742cae1e": "Liens", "728a49012344e673": "Images", + "a034d65164bb39de": "Copier", + "0165ef55eb6c8a99": "Copier en Markdown", + "439737cb6de2a5b3": "Copier l’URL de l’image", + "d3d24474c922eef2": "Copier {count} URL d’images", "f18f6d80b6bd08a0": "Copier la référence du modèle", "d7a551536aa43f3e": "Partager la référence du modèle", "9f1b29c948772f0f": "Ouvrir le lien", @@ -1553,7 +1557,6 @@ "d7dc565616d13a5c": "Partager le lien", "51244cd196696a00": "Citer", "6cdca065884f77f2": "Copier", - "0165ef55eb6c8a99": "Copier en Markdown", "7c1923203049d602": "Copier le code", "74d986aed0381cb0": "Le moteur de rendu des diagrammes n’a pas pu se charger.", "9cc6288e83305ca3": "Impossible d’afficher le diagramme.", @@ -1862,7 +1865,6 @@ "1d0a7acef4a95536": "Accepter", "255ae21697461ef6": "Prenez le contrôle pour répondre.", "d2a40ef08ef016ec": "Copier {command}", - "a034d65164bb39de": "Copier", "e0cfab9ded209e81": "Se reconnecter", "b00379f06c304b6a": "Ouvrir le navigateur, {title}", "149eba5f977b0549": "Ouvre l’onglet du navigateur en plein écran", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 56616809052d3..302318926d092 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -1546,6 +1546,10 @@ "8f2e6a13eee27d59": "見出し", "29005b7a742cae1e": "リンク", "728a49012344e673": "画像", + "a034d65164bb39de": "コピー", + "0165ef55eb6c8a99": "Markdown としてコピー", + "439737cb6de2a5b3": "画像URLをコピー", + "d3d24474c922eef2": "{count}件の画像URLをコピー", "f18f6d80b6bd08a0": "モデルの参照をコピー", "d7a551536aa43f3e": "モデルの参照を共有", "9f1b29c948772f0f": "リンクを開く", @@ -1553,7 +1557,6 @@ "d7dc565616d13a5c": "リンクを共有", "51244cd196696a00": "引用", "6cdca065884f77f2": "コピー", - "0165ef55eb6c8a99": "Markdown としてコピー", "7c1923203049d602": "コードをコピー", "74d986aed0381cb0": "図のレンダラーを読み込めませんでした。", "9cc6288e83305ca3": "図をレンダリングできませんでした。", @@ -1862,7 +1865,6 @@ "1d0a7acef4a95536": "承諾", "255ae21697461ef6": "応答するには操作権を取得してください。", "d2a40ef08ef016ec": "{command} をコピー", - "a034d65164bb39de": "コピー", "e0cfab9ded209e81": "再接続", "b00379f06c304b6a": "ブラウザーを開く、{title}", "149eba5f977b0549": "ブラウザータブを全画面で開きます", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 443285f8664c4..ec0ee0864e6ef 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -1546,6 +1546,10 @@ "8f2e6a13eee27d59": "제목", "29005b7a742cae1e": "링크", "728a49012344e673": "이미지", + "a034d65164bb39de": "복사", + "0165ef55eb6c8a99": "Markdown으로 복사", + "439737cb6de2a5b3": "이미지 URL 복사", + "d3d24474c922eef2": "이미지 URL {count}개 복사", "f18f6d80b6bd08a0": "모델 참조 복사", "d7a551536aa43f3e": "모델 참조 공유", "9f1b29c948772f0f": "링크 열기", @@ -1553,7 +1557,6 @@ "d7dc565616d13a5c": "링크 공유", "51244cd196696a00": "인용하기", "6cdca065884f77f2": "복사", - "0165ef55eb6c8a99": "Markdown으로 복사", "7c1923203049d602": "코드 복사", "74d986aed0381cb0": "다이어그램 렌더러를 불러오지 못했습니다.", "9cc6288e83305ca3": "다이어그램을 렌더링할 수 없습니다.", @@ -1862,7 +1865,6 @@ "1d0a7acef4a95536": "수락", "255ae21697461ef6": "응답하려면 제어하세요.", "d2a40ef08ef016ec": "{command} 복사", - "a034d65164bb39de": "복사", "e0cfab9ded209e81": "다시 연결", "b00379f06c304b6a": "브라우저 열기, {title}", "149eba5f977b0549": "브라우저 탭을 전체 화면으로 엽니다", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 33793cc553d34..56b52f85e6d01 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -1546,6 +1546,10 @@ "8f2e6a13eee27d59": "Títulos", "29005b7a742cae1e": "Links", "728a49012344e673": "Imagens", + "a034d65164bb39de": "Copiar", + "0165ef55eb6c8a99": "Copiar como Markdown", + "439737cb6de2a5b3": "Copiar URL da imagem", + "d3d24474c922eef2": "Copiar {count} URLs de imagens", "f18f6d80b6bd08a0": "Copiar referência do modelo", "d7a551536aa43f3e": "Compartilhar referência do modelo", "9f1b29c948772f0f": "Abrir link", @@ -1553,7 +1557,6 @@ "d7dc565616d13a5c": "Compartilhar link", "51244cd196696a00": "Citar", "6cdca065884f77f2": "Copiar", - "0165ef55eb6c8a99": "Copiar como Markdown", "7c1923203049d602": "Copiar código", "74d986aed0381cb0": "Falha ao carregar o renderizador de diagramas.", "9cc6288e83305ca3": "Não foi possível renderizar o diagrama.", @@ -1862,7 +1865,6 @@ "1d0a7acef4a95536": "Aceitar", "255ae21697461ef6": "Assuma o controle para responder.", "d2a40ef08ef016ec": "Copiar {command}", - "a034d65164bb39de": "Copiar", "e0cfab9ded209e81": "Reconectar", "b00379f06c304b6a": "Abrir navegador, {title}", "149eba5f977b0549": "Abre a aba do navegador em tela cheia", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index d0e2d9577a9ab..9b3b38bcf0234 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -1546,6 +1546,10 @@ "8f2e6a13eee27d59": "Заголовки", "29005b7a742cae1e": "Ссылки", "728a49012344e673": "Изображения", + "a034d65164bb39de": "Копировать", + "0165ef55eb6c8a99": "Копировать как Markdown", + "439737cb6de2a5b3": "Копировать URL изображения", + "d3d24474c922eef2": "Копировать URL изображений: {count}", "f18f6d80b6bd08a0": "Копировать ссылку на модель", "d7a551536aa43f3e": "Поделиться ссылкой на модель", "9f1b29c948772f0f": "Открыть ссылку", @@ -1553,7 +1557,6 @@ "d7dc565616d13a5c": "Поделиться ссылкой", "51244cd196696a00": "Цитировать", "6cdca065884f77f2": "Копировать", - "0165ef55eb6c8a99": "Копировать как Markdown", "7c1923203049d602": "Копировать код", "74d986aed0381cb0": "Не удалось загрузить отрисовщик диаграмм.", "9cc6288e83305ca3": "Не удалось отрисовать диаграмму.", @@ -1862,7 +1865,6 @@ "1d0a7acef4a95536": "Принять", "255ae21697461ef6": "Возьмите управление, чтобы ответить.", "d2a40ef08ef016ec": "Копировать {command}", - "a034d65164bb39de": "Копировать", "e0cfab9ded209e81": "Переподключить", "b00379f06c304b6a": "Открыть браузер, {title}", "149eba5f977b0549": "Открывает вкладку браузера на весь экран", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 7fd2f945cc033..5b94cd6efe6ea 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -1546,6 +1546,10 @@ "8f2e6a13eee27d59": "Rubriker", "29005b7a742cae1e": "Länkar", "728a49012344e673": "Bilder", + "a034d65164bb39de": "Kopiera", + "0165ef55eb6c8a99": "Kopiera som Markdown", + "439737cb6de2a5b3": "Kopiera bild-URL", + "d3d24474c922eef2": "Kopiera {count} bild-URL:er", "f18f6d80b6bd08a0": "Kopiera modellreferens", "d7a551536aa43f3e": "Dela modellreferens", "9f1b29c948772f0f": "Öppna länk", @@ -1553,7 +1557,6 @@ "d7dc565616d13a5c": "Dela länk", "51244cd196696a00": "Citera", "6cdca065884f77f2": "Kopiera", - "0165ef55eb6c8a99": "Kopiera som Markdown", "7c1923203049d602": "Kopiera kod", "74d986aed0381cb0": "Diagramrenderaren kunde inte läsas in.", "9cc6288e83305ca3": "Diagrammet kunde inte renderas.", @@ -1862,7 +1865,6 @@ "1d0a7acef4a95536": "Godkänn", "255ae21697461ef6": "Ta kontrollen för att svara.", "d2a40ef08ef016ec": "Kopiera {command}", - "a034d65164bb39de": "Kopiera", "e0cfab9ded209e81": "Återanslut", "b00379f06c304b6a": "Öppna webbläsaren, {title}", "149eba5f977b0549": "Öppnar webbläsarfliken i helskärm", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 54c72efe3b4fb..0478b5b378409 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -1547,6 +1547,10 @@ "8f2e6a13eee27d59": "标题", "29005b7a742cae1e": "链接", "728a49012344e673": "图片", + "a034d65164bb39de": "复制", + "0165ef55eb6c8a99": "复制为 Markdown", + "439737cb6de2a5b3": "复制图片 URL", + "d3d24474c922eef2": "复制 {count} 个图片 URL", "f18f6d80b6bd08a0": "复制模型引用", "d7a551536aa43f3e": "分享模型引用", "9f1b29c948772f0f": "打开链接", @@ -1554,7 +1558,6 @@ "d7dc565616d13a5c": "分享链接", "51244cd196696a00": "引用", "6cdca065884f77f2": "复制", - "0165ef55eb6c8a99": "复制为 Markdown", "7c1923203049d602": "复制代码", "74d986aed0381cb0": "图表渲染器加载失败。", "9cc6288e83305ca3": "无法渲染图表。", @@ -1863,7 +1866,6 @@ "1d0a7acef4a95536": "接受", "255ae21697461ef6": "接管控制后才能回应。", "d2a40ef08ef016ec": "复制 {command}", - "a034d65164bb39de": "复制", "e0cfab9ded209e81": "重新连接", "b00379f06c304b6a": "打开浏览器,{title}", "149eba5f977b0549": "全屏打开浏览器标签页", diff --git a/apps/mobile/src/native/EnrichedMarkdownText.tsx b/apps/mobile/src/native/EnrichedMarkdownText.tsx index 4ef351b39873b..ff542959413ec 100644 --- a/apps/mobile/src/native/EnrichedMarkdownText.tsx +++ b/apps/mobile/src/native/EnrichedMarkdownText.tsx @@ -22,6 +22,7 @@ import { type MarkdownImageBlock, type MarkdownLinkOccurrence, type MarkdownStyle, + type TextSelectionMenuConfig, } from "react-native-enriched-markdown"; import { codeFenceRenderer } from "./codeBlockMarkdown"; import { HighlightedCodeBlock } from "./HighlightedCodeBlock"; @@ -190,6 +191,7 @@ function codeBlockElement( mathRenderingEnabled: boolean, scheme: HighlightScheme, accessibilityLabels: AccessibilityLabels, + selectionMenuConfig: TextSelectionMenuConfig, ): ReactElement | undefined { const renderer = codeFenceRenderer(block.language, mathRenderingEnabled); if (renderer.kind === "mermaid") { @@ -210,6 +212,7 @@ function codeBlockElement( selectionColor={textStyle.selectionColor} selectionHandleColor={textStyle.selectionHandleColor} accessibilityLabels={accessibilityLabels} + selectionMenuConfig={selectionMenuConfig} /> ) : undefined; } @@ -254,6 +257,18 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) { }), [gt], ); + // The library's built-in selection menu items default to English labels. + const selectionMenuConfig = useMemo( + () => ({ + copy: { label: gt("Copy", { $context: "verb" }) }, + copyAsMarkdown: { label: gt("Copy as Markdown") }, + copyImageUrl: { + label: gt("Copy Image URL"), + pluralLabels: { other: gt("Copy {count} Image URLs", { count: "{count}" }) }, + }, + }), + [gt], + ); const { markdown, fileHrefs } = useMemo(() => { if (!fileEmbedLabel) { return { @@ -415,6 +430,7 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) { mathRenderingEnabled, themeAppearance, accessibilityLabels, + selectionMenuConfig, ), }; const resolveNativeImageSource = useRetryingImageSource(resolveImageSource); @@ -472,6 +488,7 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) { : undefined } selectionClipboard={selectionClipboard} + selectionMenuConfig={selectionMenuConfig} selectionColor={props.textStyle.selectionColor} selectionHandleColor={props.textStyle.selectionHandleColor} md4cFlags={{ From 997575be5f5dde8e5443a26ae4cfd4155fa27d87 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 06:06:28 -0800 Subject: [PATCH 016/139] perf(server): pull no longer scans the working tree twice (#40338) --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 50 ++++++++++++++++++++ apps/server/src/vcs/GitVcsDriverCore.ts | 35 ++++++++++++-- 2 files changed, 80 insertions(+), 5 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index e745669fda5c2..777d46e53d4c9 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -1630,6 +1630,56 @@ describe("pullCurrentBranch", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect("does not scan the working tree to pull", () => + Effect.gen(function* () { + const { cwd, initialBranch, remoteHead } = yield* cloneBehindRemote; + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const spawnedArgs: Array> = []; + const spawner = ChildProcessSpawner.make((command) => { + if (ChildProcess.isStandardCommand(command)) spawnedArgs.push(command.args.map(String)); + return delegate.spawn(command); + }); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + + const result = yield* driver.pullCurrentBranch(cwd); + + assert.deepEqual(result, { + status: "pulled", + refName: initialBranch, + upstreamRef: `origin/${initialBranch}`, + }); + assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), remoteHead); + // The status broadcast after a pull re-reads the working tree for the UI. + assert.deepEqual( + spawnedArgs.filter((args) => args.includes("status") || args.includes("--numstat")), + [], + ); + }).pipe(Effect.provide(layerTest)), + ); + + it.effect("pulls into an unborn branch that tracks an unfetched upstream", () => + Effect.gen(function* () { + const { remote, initialBranch, remoteHead } = yield* cloneBehindRemote; + const cwd = yield* makeTmpDir(); + yield* git(cwd, ["init", "--initial-branch", initialBranch]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["config", `branch.${initialBranch}.remote`, "origin"]); + yield* git(cwd, ["config", `branch.${initialBranch}.merge`, `refs/heads/${initialBranch}`]); + const driver = yield* makeGitVcsDriverCore(); + + const result = yield* driver.pullCurrentBranch(cwd); + + assert.deepEqual(result, { + status: "pulled", + refName: initialBranch, + upstreamRef: `origin/${initialBranch}`, + }); + assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), remoteHead); + }).pipe(Effect.provide(layerTest)), + ); + it.effect.each([false, true])( "pulls past an unrelated lock with custom fetch mapping=%s", (customMapping) => diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 7fe1dab187ac5..63d8ab594d607 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -3845,8 +3845,34 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const pullCurrentBranch: GitVcsDriver.GitVcsDriver["Service"]["pullCurrentBranch"] = Effect.fn( "pullCurrentBranch", )(function* (cwd) { - const details = yield* readStatusDetailsLocal(cwd); - const refName = details.branch; + const [refName, currentUpstreamRef] = yield* Effect.all( + [ + readCurrentBranch("GitVcsDriver.pullCurrentBranch.branch", cwd), + readCurrentUpstreamRef(cwd), + ], + { concurrency: 2 }, + ); + let upstreamRef = currentUpstreamRef; + // `@{upstream}` needs the tracking ref, which an unborn branch's first pull has not fetched. + if (upstreamRef === null && refName) { + const head = yield* executeGit( + "GitVcsDriver.pullCurrentBranch.head", + cwd, + ["rev-parse", "--verify", "--quiet", "HEAD"], + { allowNonZeroExit: true }, + ); + if (head.exitCode !== 0) { + const [configuredRemote, mergeRef] = yield* Effect.all([ + readConfigValue(cwd, `branch.${refName}.remote`), + readConfigValue(cwd, `branch.${refName}.merge`), + ]); + const mergeBranch = mergeRef?.replace(/^refs\/heads\//, ""); + if (configuredRemote && mergeBranch) { + upstreamRef = + configuredRemote === "." ? mergeBranch : `${configuredRemote}/${mergeBranch}`; + } + } + } if (!refName) { return yield* new GitCommandError({ ...gitCommandContext({ @@ -3857,7 +3883,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* detail: "Cannot pull from detached HEAD.", }); } - if (!details.hasUpstream) { + if (upstreamRef === null) { return yield* new GitCommandError({ ...gitCommandContext({ operation: "GitVcsDriver.pullCurrentBranch", @@ -3973,14 +3999,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* true, ).pipe(Effect.map((stdout) => stdout.trim())); - const refreshed = yield* readStatusDetailsLocal(cwd); return { status: beforeSha.length > 0 && beforeSha === afterSha ? ("skipped_up_to_date" as const) : ("pulled" as const), refName, - upstreamRef: refreshed.upstreamRef, + upstreamRef, }; }, Effect.scoped); From 755de001f25c54c9d6435bb23a83ffcd231e06a5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 06:22:17 -0800 Subject: [PATCH 017/139] fix(server): Antigravity Orchestrator usage prices at the base Gemini 4 rate (#40352) --- .../Drivers/antigravityUsageReader.test.ts | 12 ++++++++++++ .../provider/Drivers/antigravityUsageReader.ts | 16 ++++++++++++---- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts b/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts index d0def84f1efe0..88e076d98f208 100644 --- a/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts +++ b/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts @@ -383,6 +383,9 @@ describe("readAntigravityUsage", () => { "gemini-3-flash-agent", "gemini-3-flash", "gemini-default", + "gemini-pro-orchestrator-neon", + "gemini-4-hydrogen-orchestrator", + "gemini-pro-orchestrator-g1-pro", ].entries()) { yield* db.run("INSERT INTO gen_metadata VALUES (?, ?)", [ idx, @@ -393,6 +396,11 @@ describe("readAntigravityUsage", () => { new Uint8Array(protoBytes(9, protoNumber(2, 10 + idx))), ]); } + // Orchestrator (Neon), MODEL_PLACEHOLDER_M537, with no name in the metadata. + yield* db.run("INSERT INTO steps VALUES (?, ?)", [ + 20, + new Uint8Array(protoBytes(9, [...protoNumber(1, 1537), ...protoNumber(2, 30)])), + ]); }), ); const result = yield* readAntigravityUsage(dir, 0); @@ -405,6 +413,10 @@ describe("readAntigravityUsage", () => { ["gemini-3-flash-agent", "gemini-3.5-flash"], ["gemini-3-flash", "gemini-3-flash-preview"], ["gemini-default", undefined], + ["gemini-pro-orchestrator-neon", "gemini-4-neon"], + ["gemini-4-hydrogen-orchestrator", "gemini-4-hydrogen"], + ["gemini-pro-orchestrator-g1-pro", "gemini-4-argon"], + ["gemini-pro-orchestrator-neon", "gemini-4-neon"], ], ); }).pipe(Effect.provide(NodeServices.layer)), diff --git a/apps/server/src/provider/Drivers/antigravityUsageReader.ts b/apps/server/src/provider/Drivers/antigravityUsageReader.ts index 4a71c8ed2b056..5dff65928ad24 100644 --- a/apps/server/src/provider/Drivers/antigravityUsageReader.ts +++ b/apps/server/src/provider/Drivers/antigravityUsageReader.ts @@ -126,18 +126,26 @@ const MODEL_IDS: Record = { 1417: "gemini-4-argon", 1418: "gemini-4-argon", 1419: "gemini-4-argon", + 1537: "gemini-pro-orchestrator-neon", }; // Effort and routing variants share the base model's price. export const antigravityRateModel = (model: string) => { - const base = model.replace(/-(?:extra-low|low|medium|high|tiered|control|thinking|agent)$/, ""); + const base = model.replace( + /-(?:extra-low|low|medium|high|tiered|control|thinking|agent|orchestrator)$/, + "", + ); return /^gemini-3-flash-(?:agent(?:-[ab])?|[ab])$/.test(model) ? "gemini-3.5-flash" : model === "gemini-3.7-flash-safety-le" ? "gemini-3.7-flash" - : base === "gemini-3-flash" - ? "gemini-3-flash-preview" - : base; + : model === "gemini-pro-orchestrator-neon" + ? "gemini-4-neon" + : model === "gemini-pro-orchestrator-g1-pro" + ? "gemini-4-argon" + : base === "gemini-3-flash" + ? "gemini-3-flash-preview" + : base; }; function withRateModel(record: UsageRecord): UsageRecord { From dd941b9c3b581b4a04539255fb85f2b0cbc3fa57 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 06:36:07 -0800 Subject: [PATCH 018/139] fix(server): treat a branch rename as done when Git moved the ref but kept the config locked (#40361) --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 17 +++++++++++++++++ apps/server/src/vcs/GitVcsDriverCore.ts | 17 +++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 777d46e53d4c9..b25e0ff2a8f64 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -7907,6 +7907,23 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("reports a rename as done when Git moved the ref but kept the config locked", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + yield* git(cwd, ["checkout", "-b", "t3/abcd1234"]); + yield* writeTextFile(cwd, ".git/config.lock", ""); + const driver = yield* GitVcsDriver.GitVcsDriver; + + const renamed = yield* TestClock.withLive( + driver.renameBranch({ cwd, oldBranch: "t3/abcd1234", newBranch: "t3/fix-login" }), + ); + + assert.equal(renamed.branch, "t3/fix-login"); + assert.equal(yield* git(cwd, ["branch", "--show-current"]), "t3/fix-login"); + }), + ); + it.effect.each([false, true])( "cleans up links left by successful worktree removal, preserving ordinary files: %s", (keepFile) => diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 63d8ab594d607..4356de894f0b4 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -6661,6 +6661,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* timeoutMs: 10_000, fallbackErrorDetail: "git branch rename failed", }, + ).pipe( + // Git exits non-zero after moving the ref when it cannot rewrite the locked config. + Effect.catch((error) => + Effect.all( + [branchExists(input.cwd, input.oldBranch), branchExists(input.cwd, targetBranch)], + { concurrency: "unbounded" }, + ).pipe( + Effect.orElseSucceed(() => [true, false] as const), + Effect.flatMap(([oldExists, newExists]) => + !oldExists && newExists + ? Effect.logWarning( + "GitVcsDriver.renameBranch: renamed the branch but could not move its config entries", + ) + : Effect.fail(error), + ), + ), + ), ); return { branch: targetBranch }; From 27125d7d16829de92c2ede3d4cc905c30ed1ce33 Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Sat, 21 Nov 2026 16:59:54 +0200 Subject: [PATCH 019/139] fix(cli): thread --wait --json keeps a result a woken run submits (#40360) Co-authored-by: Julius Marminge --- apps/server/src/cli/thread.test.ts | 11 ++++++++++- apps/server/src/cli/thread.ts | 10 ++++++---- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/apps/server/src/cli/thread.test.ts b/apps/server/src/cli/thread.test.ts index b98314133da84..7231ea7f2b3e0 100644 --- a/apps/server/src/cli/thread.test.ts +++ b/apps/server/src/cli/thread.test.ts @@ -241,6 +241,8 @@ it.effect("--wait lasts until background work the agent waits on wakes it and th status: "completed", timedOut: false, resultRun: { runId: wakeRun, status: "completed" }, + // The wake run submits the result the first run owes, which the server stores there. + output: { head: "abc" }, }, ], // The wake run starts from a notification, which the messages view leaves out. @@ -256,7 +258,12 @@ it.effect("--wait lasts until background work the agent waits on wakes it and th { threadId, runId, timeoutMs: 15_000, untilDelegatedWorkSettled: true }, ], ); - assert.deepStrictEqual(outcome, { type: "ended", runId: wakeRun, status: "completed" }); + assert.deepStrictEqual(outcome, { + type: "ended", + runId: wakeRun, + status: "completed", + output: { head: "abc" }, + }); }), ); @@ -329,6 +336,7 @@ it.effect( status: "completed", timedOut: false, resultRun: { runId: sentRun, status: "failed" }, + output: { head: "abc" }, }, ], t3_thread_read: laterRunReads(sentRun, [{ runId: sentRun, type: "user_message" }]), @@ -338,6 +346,7 @@ it.effect( type: "ended", runId, status: "completed", + output: { head: "abc" }, }); }), ); diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index ab80f3e1fbb2d..8849f10c6a5ec 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -643,8 +643,10 @@ export const waitForRun = Effect.fn("cli.thread.waitForRun")(function* ( const waited = yield* waitSlice(WAIT_SLICE_MS, true); // `resultRun` is the thread's latest finished run, whoever sent it. const result = waited.timedOut ? undefined : waited.resultRun; + // A later run can submit the result the asked run owes, so read it again. + const settled = waited.output === undefined ? outcome : { ...outcome, output: waited.output }; const after = yield* runsAfter(tools, threadId, finalRunId); - if (after.sent) return outcome; + if (after.sent) return settled; if (!waited.timedOut) { if (result !== undefined && after.later.some((run) => run.runId === result.runId)) { // A run that work woke was not asked for the result; the run before it holds it. @@ -652,13 +654,13 @@ export const waitForRun = Effect.fn("cli.thread.waitForRun")(function* ( type: "ended", runId: result.runId, status: result.status, - ...(outcome.output === undefined ? {} : { output: outcome.output }), + ...(settled.output === undefined ? {} : { output: settled.output }), } satisfies WaitOutcome; } - if (!workOutlivedRun) return outcome; + if (!workOutlivedRun) return settled; if (after.later.some((run) => !TERMINAL_RUN_STATUSES.has(run.status))) continue; if (after.later.length === 0 && (yield* wakeRunRecorded)) continue; - return outcome; + return settled; } workOutlivedRun = true; const { thread } = yield* tools.call( From b4277089795299da077e784f9f3432b3cc1c1c7d Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:43:37 +0530 Subject: [PATCH 020/139] fix(issues): agents can file issues in any bound Linear team (#40299) Co-authored-by: Claude Opus 5.5 --- ...ettingsSourceControlDetailRouteScreens.tsx | 2 +- apps/mobile/src/i18n/translations/de.json | 2 +- apps/mobile/src/i18n/translations/en.json | 2 +- apps/mobile/src/i18n/translations/es.json | 2 +- apps/mobile/src/i18n/translations/fr.json | 2 +- apps/mobile/src/i18n/translations/ja.json | 2 +- apps/mobile/src/i18n/translations/ko.json | 2 +- apps/mobile/src/i18n/translations/pt-BR.json | 2 +- apps/mobile/src/i18n/translations/ru.json | 2 +- apps/mobile/src/i18n/translations/sv.json | 2 +- apps/mobile/src/i18n/translations/zh.json | 2 +- apps/server/src/issue/IssueService.test.ts | 7 +- apps/server/src/issue/IssueService.ts | 27 ++++++-- .../src/mcp/toolkits/issues/handlers.test.ts | 65 +++++++++++++++++++ .../src/mcp/toolkits/issues/handlers.ts | 14 ++-- apps/server/src/mcp/toolkits/issues/tools.ts | 5 ++ .../src/provider/agentContextBudget.json | 2 +- .../settings/IssueTrackerSettings.tsx | 2 +- apps/web/src/i18n/translations/de.json | 2 +- apps/web/src/i18n/translations/en.json | 2 +- apps/web/src/i18n/translations/es.json | 2 +- apps/web/src/i18n/translations/fr.json | 2 +- apps/web/src/i18n/translations/ja.json | 2 +- apps/web/src/i18n/translations/ko.json | 2 +- apps/web/src/i18n/translations/pt-BR.json | 2 +- apps/web/src/i18n/translations/ru.json | 2 +- apps/web/src/i18n/translations/sv.json | 2 +- apps/web/src/i18n/translations/zh.json | 2 +- docs/user/source-control.md | 2 +- evals/mcp-tool-use/cases/issues.ndjson | 2 + .../linear-settings-name-another-team.e2e.ts | 59 +++++++++++++++++ scripts/scenarios/start-app.ts | 4 ++ 32 files changed, 193 insertions(+), 38 deletions(-) create mode 100644 scripts/scenarios/linear-settings-name-another-team.e2e.ts diff --git a/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx b/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx index f368dcca2dfc3..957cf17a26178 100644 --- a/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx +++ b/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx @@ -199,7 +199,7 @@ export function SettingsIssueTrackerRouteScreen({ diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index e0eb437599e38..f538b87920412 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -3736,7 +3736,7 @@ "b725843fd45b74aa": "Anmeldedaten", "b239ba3ce2899a3e": "Oder verwende deine eigenen Anmeldedaten", "f0e6397ab4de588e": "Token", - "295392927d5c8a84": "Wähle für jedes Projekt ein oder mehrere {scope}s in {tracker}. Ihre Issues erscheinen neben denen des Repositorys, und Agenten legen neue Issues im ersten an.", + "ed83b25c71c98a20": "Wähle für jedes Projekt ein oder mehrere {scope}s in {tracker}. Ihre Issues erscheinen neben denen des Repositorys, und Agenten legen neue Issues im ersten an, sofern kein anderes verlangt wird.", "ce2136b36f87b655": "Verbinde diese Umgebung, um ihre Einstellungen zu ändern.", "a90a441fd0e08de7": "Diese Umgebung", "32fb83554cfd85b4": "Transkriptionsmodelle", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index bca87cee0884f..745201ad99094 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -3738,7 +3738,7 @@ "b725843fd45b74aa": "Credentials", "b239ba3ce2899a3e": "Or use your own credentials", "f0e6397ab4de588e": "Token", - "295392927d5c8a84": "Pick one or more {tracker} {scope}s for each project. Their issues list beside the repository's own, and agents file new issues in the first one.", + "ed83b25c71c98a20": "Pick one or more {tracker} {scope}s for each project. Their issues list beside the repository's own, and agents file new issues in the first one unless asked for another.", "ce2136b36f87b655": "Connect this environment to change its settings.", "a90a441fd0e08de7": "This environment", "32fb83554cfd85b4": "Transcription models", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 3f73e995b2521..fb134339cd3c4 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -3731,7 +3731,7 @@ "b725843fd45b74aa": "Credenciales", "b239ba3ce2899a3e": "O usa tus propias credenciales", "f0e6397ab4de588e": "Token", - "295392927d5c8a84": "Elige uno o más {scope}s de {tracker} para cada proyecto. Sus issues aparecen junto a las del repositorio, y los agentes crean issues nuevas en el primero.", + "ed83b25c71c98a20": "Elige uno o más {scope}s de {tracker} para cada proyecto. Sus issues aparecen junto a las del repositorio, y los agentes crean issues nuevas en el primero, salvo que se les pida otro.", "ce2136b36f87b655": "Conecta este entorno para cambiar sus ajustes.", "a90a441fd0e08de7": "Este entorno", "32fb83554cfd85b4": "Modelos de transcripción", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 3aff16728eeff..d6aef220df3a2 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -3731,7 +3731,7 @@ "b725843fd45b74aa": "Identifiants", "b239ba3ce2899a3e": "Ou utilisez vos propres identifiants", "f0e6397ab4de588e": "Jeton", - "295392927d5c8a84": "Choisissez un ou plusieurs {scope}s {tracker} pour chaque projet. Leurs tickets s'affichent à côté de ceux du dépôt, et les agents créent les nouveaux tickets dans le premier.", + "ed83b25c71c98a20": "Choisissez un ou plusieurs {scope}s {tracker} pour chaque projet. Leurs tickets s'affichent à côté de ceux du dépôt, et les agents créent les nouveaux tickets dans le premier, sauf si vous leur indiquez une autre destination.", "ce2136b36f87b655": "Connectez cet environnement pour modifier ses paramètres.", "a90a441fd0e08de7": "Cet environnement", "32fb83554cfd85b4": "Modèles de transcription", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 302318926d092..8cd9fba5c8332 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -3727,7 +3727,7 @@ "b725843fd45b74aa": "資格情報", "b239ba3ce2899a3e": "または自分の資格情報を使用", "f0e6397ab4de588e": "トークン", - "295392927d5c8a84": "各プロジェクトに {tracker} の {scope} を1つ以上選択します。その Issue はリポジトリ自身の Issue と並べて表示され、エージェントは最初の {scope} に新しい Issue を作成します。", + "ed83b25c71c98a20": "各プロジェクトに {tracker} の {scope} を1つ以上選択します。その Issue はリポジトリ自身の Issue と並べて表示され、エージェントは別の {scope} を指定されない限り、最初の {scope} に新しい Issue を作成します。", "ce2136b36f87b655": "設定を変更するには、この環境に接続してください。", "a90a441fd0e08de7": "この環境", "32fb83554cfd85b4": "文字起こしモデル", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index ec0ee0864e6ef..731eaeecaec22 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -3731,7 +3731,7 @@ "b725843fd45b74aa": "자격 증명", "b239ba3ce2899a3e": "또는 내 자격 증명 사용", "f0e6397ab4de588e": "토큰", - "295392927d5c8a84": "각 프로젝트에 {tracker} {scope}을(를) 하나 이상 선택하세요. 해당 이슈는 저장소 자체 이슈와 함께 표시되며, 에이전트는 첫 번째 {scope}에 새 이슈를 만듭니다.", + "ed83b25c71c98a20": "각 프로젝트에 {tracker} {scope}을(를) 하나 이상 선택하세요. 해당 이슈는 저장소 자체 이슈와 함께 표시되며, 에이전트는 다른 {scope}을(를) 지정받지 않으면 첫 번째 {scope}에 새 이슈를 만듭니다.", "ce2136b36f87b655": "설정을 변경하려면 이 환경에 연결하세요.", "a90a441fd0e08de7": "이 환경", "32fb83554cfd85b4": "받아쓰기 모델", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 56b52f85e6d01..2c4ee1bc64fc4 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -3731,7 +3731,7 @@ "b725843fd45b74aa": "Credenciais", "b239ba3ce2899a3e": "Ou use suas próprias credenciais", "f0e6397ab4de588e": "Token", - "295392927d5c8a84": "Escolha um ou mais {scope}s do {tracker} para cada projeto. As issues deles aparecem ao lado das do repositório, e os agentes criam novas issues no primeiro.", + "ed83b25c71c98a20": "Escolha um ou mais {scope}s do {tracker} para cada projeto. As issues deles aparecem ao lado das do repositório, e os agentes criam novas issues no primeiro, a menos que outro seja pedido.", "ce2136b36f87b655": "Conecte este ambiente para alterar as configurações dele.", "a90a441fd0e08de7": "Este ambiente", "32fb83554cfd85b4": "Modelos de transcrição", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index 9b3b38bcf0234..c4f78e560083b 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -3785,7 +3785,7 @@ "b725843fd45b74aa": "Учётные данные", "b239ba3ce2899a3e": "Или используйте свои учётные данные", "f0e6397ab4de588e": "Токен", - "295392927d5c8a84": "Выберите один или несколько {scope} в {tracker} для каждого проекта. Их issue показываются рядом с issue репозитория, а агенты создают новые issue в первом.", + "ed83b25c71c98a20": "Выберите один или несколько {scope} в {tracker} для каждого проекта. Их issue показываются рядом с issue репозитория, а агенты создают новые issue в первом, если вы не укажете, где их создать.", "ce2136b36f87b655": "Подключите это окружение, чтобы изменить его настройки.", "a90a441fd0e08de7": "Это окружение", "32fb83554cfd85b4": "Модели расшифровки", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 5b94cd6efe6ea..fa3a3dd6d039f 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -3737,7 +3737,7 @@ "b725843fd45b74aa": "Autentiseringsuppgifter", "b239ba3ce2899a3e": "Eller använd dina egna autentiseringsuppgifter", "f0e6397ab4de588e": "Token", - "295392927d5c8a84": "Välj en eller flera {scope} i {tracker} för varje projekt. Deras ärenden listas bredvid repots egna, och agenter skapar nya ärenden i den första.", + "ed83b25c71c98a20": "Välj en eller flera {scope} i {tracker} för varje projekt. Deras ärenden listas bredvid repots egna, och agenter skapar nya ärenden i det första om de inte ombeds välja ett annat.", "ce2136b36f87b655": "Anslut den här miljön för att ändra dess inställningar.", "a90a441fd0e08de7": "Den här miljön", "32fb83554cfd85b4": "Transkriberingsmodeller", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 0478b5b378409..f36e76805c298 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -3733,7 +3733,7 @@ "b725843fd45b74aa": "凭据", "b239ba3ce2899a3e": "或使用你自己的凭据", "f0e6397ab4de588e": "token", - "295392927d5c8a84": "为每个项目选择一个或多个 {tracker} {scope}。它们的 issue 会列在仓库自身的 issue 旁,智能体会在第一个中创建新 issue。", + "ed83b25c71c98a20": "为每个项目选择一个或多个 {tracker} {scope}。它们的 issue 会列在仓库自身的 issue 旁;除非另有指定,智能体会在第一个中创建新 issue。", "ce2136b36f87b655": "连接此环境以更改其设置。", "a90a441fd0e08de7": "此环境", "32fb83554cfd85b4": "转写模型", diff --git a/apps/server/src/issue/IssueService.test.ts b/apps/server/src/issue/IssueService.test.ts index a291d5bee11f7..e8308b8480d02 100644 --- a/apps/server/src/issue/IssueService.test.ts +++ b/apps/server/src/issue/IssueService.test.ts @@ -699,7 +699,12 @@ describe("IssueService with a standalone tracker", () => { writable: false, }); expect((yield* bound.projectScope("web" as ProjectId)).scope).toBe("ENG"); - expect((yield* bound.projectScope("web" as ProjectId, "ops-12")).scope).toBe("OPS"); + expect((yield* bound.projectScope("web" as ProjectId, { key: "ops-12" })).scope).toBe("OPS"); + expect(yield* bound.projectScope("web" as ProjectId, { scope: "ACME/Web" })).toMatchObject({ + tracker: GITHUB, + host: "github.com", + scope: "acme/web", + }); expect( yield* bound.detail({ projectId: "web" as ProjectId, diff --git a/apps/server/src/issue/IssueService.ts b/apps/server/src/issue/IssueService.ts index a4483e2224927..27499b240d655 100644 --- a/apps/server/src/issue/IssueService.ts +++ b/apps/server/src/issue/IssueService.ts @@ -158,10 +158,13 @@ export class IssueService extends Context.Service< readonly update: (input: IssueUpdateInput) => Effect.Effect; readonly setState: (input: IssueSetStateInput) => Effect.Effect; readonly react: (input: IssueReactionInput) => Effect.Effect; - /** The tracker and container a project's own issues live in, or the one `key` names. */ + /** + * The tracker and container a project's own issues live in: the bound `scope` when named, else + * the one `key`'s prefix names, else the project's default. + */ readonly projectScope: ( projectId: ProjectId, - key?: string, + select?: { readonly key?: string | undefined; readonly scope?: string | undefined }, ) => Effect.Effect; /** * Resolve through a matching project, preferring `preferredProjectId`; other scopes are read-only. @@ -678,14 +681,24 @@ const make = Effect.gen(function* () { const projectScope: IssueService["Service"]["projectScope"] = Effect.fn( "IssueService.projectScope", - )(function* (projectId, key) { + )(function* (projectId, select) { const { supported } = yield* listProjects({ projectId }); - const prefix = key?.toLowerCase(); + if (supported.length === 0) { + return yield* new IssueUnavailableError({ reason: "tracker-unsupported" }); + } + const named = select?.scope?.trim().toLowerCase(); + const prefix = select?.key?.toLowerCase(); const own = - supported.find((candidate) => prefix?.startsWith(`${candidate.scope.toLowerCase()}-`)) ?? - supported[0]; + named === undefined + ? (supported.find((candidate) => prefix?.startsWith(`${candidate.scope.toLowerCase()}-`)) ?? + supported[0]) + : supported.find((candidate) => candidate.scope.toLowerCase() === named); if (own === undefined) { - return yield* new IssueUnavailableError({ reason: "tracker-unsupported" }); + return yield* new IssueOperationError({ + operation: "scope", + reason: "not-found", + detail: `This project does not track ${select?.scope?.trim()}. Use one of: ${[...new Set(supported.map((candidate) => candidate.scope))].join(", ")}.`, + }); } return { projectId, tracker: own.tracker, host: own.host, scope: own.scope }; }); diff --git a/apps/server/src/mcp/toolkits/issues/handlers.test.ts b/apps/server/src/mcp/toolkits/issues/handlers.test.ts index 07f4b4e019204..143ba4a0c98a3 100644 --- a/apps/server/src/mcp/toolkits/issues/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/issues/handlers.test.ts @@ -278,6 +278,71 @@ describe("issue toolkit handlers", () => { }), ); + it.effect("files an issue in the bound Linear team an agent names", () => + Effect.gen(function* () { + const tracker = IssueTrackerKind.make("linear"); + const host = "linear.app"; + const filedIn = yield* Ref.make>([]); + const linear: StandaloneIssueTrackerApi = { + kind: tracker, + capabilities: detail.capabilities, + standalone: { + tracker, + displayName: "Linear", + host, + scopeNoun: "team", + credential: { label: "Personal API key", helpUrl: null }, + }, + parseIssueUrl: () => null, + probeCredential: () => Effect.succeed({ account: "user", scopes: [] }), + getViewer: () => Effect.succeed("user"), + listIssues: () => Effect.succeed({ items: [], nextCursor: null }), + getComments: () => Effect.succeed({ comments: [], nextCursor: null }), + getIssue: () => Effect.die("unused"), + create: ({ scope }) => + Ref.update(filedIn, (teams) => [...teams, scope]).pipe( + Effect.as({ + key: `${scope}-1`, + url: `https://linear.app/acme/issue/${scope}-1`, + displayKey: `${scope}-1`, + }), + ), + }; + const issueLayer = IssueService.layer.pipe( + Layer.provide( + Layer.mergeAll( + projectLayer, + Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({}), + Layer.mock(IssueTrackerBindings.IssueTrackerBindingsRepository)({ + list: Effect.succeed( + new Map([[PROJECT_ID, { tracker, scope: "ENG", additionalScopes: ["OPS"] }]]), + ), + }), + Layer.succeed( + IssueTrackerRegistry.IssueTrackerRegistry, + IssueTrackerRegistry.fromTrackers([linear]), + ), + ), + ), + ); + const harness = yield* makeHarness([], issueLayer); + + expect( + yield* harness.call("create_issue", { title: "Backup ran twice", scope: "ops" }), + ).toMatchObject({ tracker, scope: "OPS", key: "OPS-1" }); + expect(yield* harness.call("create_issue", { title: "Label typo" })).toMatchObject({ + scope: "ENG", + key: "ENG-1", + }); + const unbound = yield* harness + .call("create_issue", { title: "Flaky test", scope: "QA" }) + .pipe(Effect.flip); + expect(unbound).toMatchObject({ _tag: "IssueOperationError", reason: "not-found" }); + expect(unbound.message).toContain("Use one of: ENG, OPS."); + expect(yield* Ref.get(filedIn)).toEqual(["OPS", "ENG"]); + }), + ); + it.effect("refuses a credential without the issues capability", () => Effect.gen(function* () { const harness = yield* makeHarness(); diff --git a/apps/server/src/mcp/toolkits/issues/handlers.ts b/apps/server/src/mcp/toolkits/issues/handlers.ts index 6b835ffb564f9..b45b3d3dbd875 100644 --- a/apps/server/src/mcp/toolkits/issues/handlers.ts +++ b/apps/server/src/mcp/toolkits/issues/handlers.ts @@ -90,15 +90,17 @@ const make = Effect.gen(function* () { /** Where a key-only reference is read: the named project's tracker, or the caller's thread's. */ const requireProjectScope = Effect.fn("IssuesToolkit.requireProjectScope")(function* ( requested: ProjectId | undefined, - key?: string, + select?: { readonly key?: string | undefined; readonly scope?: string | undefined }, ) { // A named project skips the caller's thread, so the capability is checked here too. yield* McpInvocationContext.requireMcpCapability("issues"); const projectId = requested ?? (yield* callerThread())?.projectId; if (projectId === undefined) return yield* new IssueProjectRequiredError(); - return yield* issues - .projectScope(projectId, key) - .pipe(Effect.mapError(() => new IssueProjectNotFoundError({ projectId }))); + return yield* issues.projectScope(projectId, select).pipe( + Effect.catchTags({ + IssueUnavailableError: () => Effect.fail(new IssueProjectNotFoundError({ projectId })), + }), + ); }); /** @@ -116,7 +118,7 @@ const make = Effect.gen(function* () { return { ...resolved, url: input.url } satisfies ResolvedTarget; } if (input.key === undefined) return yield* new IssueTargetIncompleteError(); - const scope = yield* requireProjectScope(input.projectId, input.key); + const scope = yield* requireProjectScope(input.projectId, { key: input.key }); return { ...scope, key: input.key, @@ -231,7 +233,7 @@ const make = Effect.gen(function* () { ), create_issue: McpToolAccess.writesWithCapability((input) => Effect.gen(function* () { - const scope = yield* requireProjectScope(input.projectId); + const scope = yield* requireProjectScope(input.projectId, { scope: input.scope }); const created = yield* issues.create({ ...scope, title: input.title, diff --git a/apps/server/src/mcp/toolkits/issues/tools.ts b/apps/server/src/mcp/toolkits/issues/tools.ts index 20de86b1f9dea..6af757999134d 100644 --- a/apps/server/src/mcp/toolkits/issues/tools.ts +++ b/apps/server/src/mcp/toolkits/issues/tools.ts @@ -284,6 +284,11 @@ const CreateIssueTool = Tool.make("create_issue", { projectId: Schema.optional( ProjectId.annotate({ description: "Defaults to this thread's project." }), ), + scope: Schema.optional( + TrimmedNonEmptyString.annotate({ + description: "A bound team or repository, such as OPS. Defaults to the project's first.", + }), + ), title: TrimmedNonEmptyString.check(Schema.isMaxLength(1024)), body: Schema.optional(Schema.String.check(Schema.isMaxLength(65_536))), labels: Schema.optional(Schema.Array(TrimmedNonEmptyString).check(Schema.isMaxLength(50))), diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index e089e5a84218a..139eba175bc8a 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 59026 + "mcpToolListJsonBytes": 59052 } diff --git a/apps/web/src/components/settings/IssueTrackerSettings.tsx b/apps/web/src/components/settings/IssueTrackerSettings.tsx index 1bf3e2466f837..72423aaf4ef6e 100644 --- a/apps/web/src/components/settings/IssueTrackerSettings.tsx +++ b/apps/web/src/components/settings/IssueTrackerSettings.tsx @@ -297,7 +297,7 @@ function ProjectBindings({ diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 4f60fef9f6088..c7095b8536469 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -8695,7 +8695,7 @@ "58e0e226493150e7": "Issue-Tracker konnten nicht geladen werden", "77cfcbde543df32d": "Details zu {tracker} ein-/ausblenden", "0083f65885c60156": "{tracker} trennen", - "295392927d5c8a84": "Wähle für jedes Projekt ein oder mehrere {scope}s in {tracker}. Ihre Issues erscheinen neben denen des Repositorys, und Agenten legen neue Issues im ersten an.", + "ed83b25c71c98a20": "Wähle für jedes Projekt ein oder mehrere {scope}s in {tracker}. Ihre Issues erscheinen neben denen des Repositorys, und Agenten legen neue Issues im ersten an, sofern kein anderes verlangt wird.", "19c2d5e81ff8f89a": "{tracker} {scope} für {project}", "68e061510b765772": "Nicht zugeordnet", "a2d95d39d3398bda": "Anmeldedaten abgelehnt", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 6453de11f9da0..2ff8148bb7329 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -8703,7 +8703,7 @@ "58e0e226493150e7": "Could not load issue trackers", "77cfcbde543df32d": "Toggle {tracker} details", "0083f65885c60156": "Disconnect {tracker}", - "295392927d5c8a84": "Pick one or more {tracker} {scope}s for each project. Their issues list beside the repository's own, and agents file new issues in the first one.", + "ed83b25c71c98a20": "Pick one or more {tracker} {scope}s for each project. Their issues list beside the repository's own, and agents file new issues in the first one unless asked for another.", "19c2d5e81ff8f89a": "{tracker} {scope} for {project}", "68e061510b765772": "Not bound", "a2d95d39d3398bda": "Credential rejected", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index a73a02ec3bcc9..78c68c4c0dc2f 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -8693,7 +8693,7 @@ "58e0e226493150e7": "No se pudieron cargar los gestores de issues", "77cfcbde543df32d": "Mostrar u ocultar detalles de {tracker}", "0083f65885c60156": "Desconectar {tracker}", - "295392927d5c8a84": "Elige uno o más {scope}s de {tracker} para cada proyecto. Sus issues aparecen junto a las del repositorio, y los agentes crean issues nuevas en el primero.", + "ed83b25c71c98a20": "Elige uno o más {scope}s de {tracker} para cada proyecto. Sus issues aparecen junto a las del repositorio, y los agentes crean issues nuevas en el primero, salvo que se les pida otro.", "19c2d5e81ff8f89a": "{scope} de {tracker} para {project}", "68e061510b765772": "Sin vincular", "a2d95d39d3398bda": "Credencial rechazada", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 95ea50d6bf22d..873767a296ba5 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -8694,7 +8694,7 @@ "58e0e226493150e7": "Impossible de charger les gestionnaires de tickets", "77cfcbde543df32d": "Afficher ou masquer les détails de {tracker}", "0083f65885c60156": "Déconnecter {tracker}", - "295392927d5c8a84": "Choisissez un ou plusieurs {scope}s {tracker} pour chaque projet. Leurs tickets s'affichent à côté de ceux du dépôt, et les agents créent les nouveaux tickets dans le premier.", + "ed83b25c71c98a20": "Choisissez un ou plusieurs {scope}s {tracker} pour chaque projet. Leurs tickets s'affichent à côté de ceux du dépôt, et les agents créent les nouveaux tickets dans le premier, sauf si vous leur indiquez une autre destination.", "19c2d5e81ff8f89a": "{scope} {tracker} pour {project}", "68e061510b765772": "Non lié", "a2d95d39d3398bda": "Identifiant refusé", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 96bf9c7c7bf48..69ac82ad8a247 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -8651,7 +8651,7 @@ "58e0e226493150e7": "Issue トラッカーを読み込めませんでした", "77cfcbde543df32d": "{tracker} の詳細を切り替え", "0083f65885c60156": "{tracker} を切断", - "295392927d5c8a84": "各プロジェクトに {tracker} の {scope} を1つ以上選択します。その Issue はリポジトリ自身の Issue と並べて表示され、エージェントは最初の {scope} に新しい Issue を作成します。", + "ed83b25c71c98a20": "各プロジェクトに {tracker} の {scope} を1つ以上選択します。その Issue はリポジトリ自身の Issue と並べて表示され、エージェントは別の {scope} を指定されない限り、最初の {scope} に新しい Issue を作成します。", "19c2d5e81ff8f89a": "{project} の {tracker} {scope}", "68e061510b765772": "未バインド", "a2d95d39d3398bda": "資格情報が拒否されました", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index d7b1a7628ffc6..10782b2ca6166 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -8654,7 +8654,7 @@ "58e0e226493150e7": "이슈 트래커를 불러올 수 없습니다", "77cfcbde543df32d": "{tracker} 세부 정보 전환", "0083f65885c60156": "{tracker} 연결 끊기", - "295392927d5c8a84": "각 프로젝트에 {tracker} {scope}을(를) 하나 이상 선택하세요. 해당 이슈는 저장소 자체 이슈와 함께 표시되며, 에이전트는 첫 번째 {scope}에 새 이슈를 만듭니다.", + "ed83b25c71c98a20": "각 프로젝트에 {tracker} {scope}을(를) 하나 이상 선택하세요. 해당 이슈는 저장소 자체 이슈와 함께 표시되며, 에이전트는 다른 {scope}을(를) 지정받지 않으면 첫 번째 {scope}에 새 이슈를 만듭니다.", "19c2d5e81ff8f89a": "{project}의 {tracker} {scope}", "68e061510b765772": "바인딩되지 않음", "a2d95d39d3398bda": "자격 증명 거부됨", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5097324486fb8..5b2b9e2b9b381 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -8693,7 +8693,7 @@ "58e0e226493150e7": "Não foi possível carregar os rastreadores de issues", "77cfcbde543df32d": "Mostrar ou ocultar detalhes de {tracker}", "0083f65885c60156": "Desconectar {tracker}", - "295392927d5c8a84": "Escolha um ou mais {scope}s do {tracker} para cada projeto. As issues deles aparecem ao lado das do repositório, e os agentes criam novas issues no primeiro.", + "ed83b25c71c98a20": "Escolha um ou mais {scope}s do {tracker} para cada projeto. As issues deles aparecem ao lado das do repositório, e os agentes criam novas issues no primeiro, a menos que outro seja pedido.", "19c2d5e81ff8f89a": "{scope} do {tracker} para {project}", "68e061510b765772": "Não vinculado", "a2d95d39d3398bda": "Credencial recusada", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 4c19189200eb5..0ecadaba9ded1 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -8695,7 +8695,7 @@ "58e0e226493150e7": "Не удалось загрузить issue-трекеры", "77cfcbde543df32d": "Показать или скрыть подробности {tracker}", "0083f65885c60156": "Отключить {tracker}", - "295392927d5c8a84": "Выберите один или несколько {scope} в {tracker} для каждого проекта. Их issue показываются рядом с issue репозитория, а агенты создают новые issue в первом.", + "ed83b25c71c98a20": "Выберите один или несколько {scope} в {tracker} для каждого проекта. Их issue показываются рядом с issue репозитория, а агенты создают новые issue в первом, если вы не укажете, где их создать.", "19c2d5e81ff8f89a": "{tracker} {scope} для {project}", "68e061510b765772": "Не привязано", "a2d95d39d3398bda": "Учётные данные отклонены", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 7add0fa009b1d..1c01b1112768f 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -8701,7 +8701,7 @@ "58e0e226493150e7": "Kunde inte läsa in ärendehanterare", "77cfcbde543df32d": "Visa/dölj detaljer för {tracker}", "0083f65885c60156": "Koppla från {tracker}", - "295392927d5c8a84": "Välj en eller flera {scope} i {tracker} för varje projekt. Deras ärenden listas bredvid repots egna, och agenter skapar nya ärenden i den första.", + "ed83b25c71c98a20": "Välj en eller flera {scope} i {tracker} för varje projekt. Deras ärenden listas bredvid repots egna, och agenter skapar nya ärenden i det första om de inte ombeds välja ett annat.", "19c2d5e81ff8f89a": "{scope} i {tracker} för {project}", "68e061510b765772": "Inte kopplad", "a2d95d39d3398bda": "Autentiseringsuppgiften avvisades", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 5a5c7160230de..43790340d1167 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -8711,7 +8711,7 @@ "58e0e226493150e7": "无法加载 issue 跟踪器", "77cfcbde543df32d": "切换 {tracker} 详情", "0083f65885c60156": "断开 {tracker} 连接", - "295392927d5c8a84": "为每个项目选择一个或多个 {tracker} {scope}。它们的 issue 会列在仓库自身的 issue 旁,智能体会在第一个中创建新 issue。", + "ed83b25c71c98a20": "为每个项目选择一个或多个 {tracker} {scope}。它们的 issue 会列在仓库自身的 issue 旁;除非另有指定,智能体会在第一个中创建新 issue。", "19c2d5e81ff8f89a": "{project} 的 {tracker} {scope}", "68e061510b765772": "未绑定", "a2d95d39d3398bda": "凭据被拒绝", diff --git a/docs/user/source-control.md b/docs/user/source-control.md index c04060ba831a3..cb8d252b9ab37 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -412,7 +412,7 @@ To list Linear issues beside a project's, connect Linear with an API key under Settings → Source control & issues, then pick one or more teams for that project there. Pick another team at any time to add it; uncheck every team to unbind the project. Each team's issues appear in the Linear group of the issue list, sorted with the rest by last update, and -each can be loaded further on its own. Agents file new issues in the first team picked. +each can be loaded further on its own. Agents file new issues in the first team picked unless you name another bound team. Select an issue to open it beside the list: description, comments, state changes, linked pull requests, labels, assignees, and reactions. Linked pull requests open in the same panel. You can diff --git a/evals/mcp-tool-use/cases/issues.ndjson b/evals/mcp-tool-use/cases/issues.ndjson index b3c33cef640e9..16967ba5e17db 100644 --- a/evals/mcp-tool-use/cases/issues.ndjson +++ b/evals/mcp-tool-use/cases/issues.ndjson @@ -1,2 +1,4 @@ {"id":"work-on-issue-links-thread","area":"issues","kind":"bad","pattern":"Agent takes on a tracked issue without linking it to the thread","experience":"Agents linked pull requests but often left the issues they were working on unlinked.","privacy":"commit-safe","setup":{"role":"top","mocks":{"link_issue":{"projectId":"app","tracker":"github","host":"github.com","scope":"acme/app","key":"42","url":"https://github.com/acme/app/issues/42","alreadyLinked":false}},"world":{"repo":"acme/app","files":{"src/label.ts":"export const label = 'Setings';"},"issues":[{"url":"https://github.com/acme/app/issues/42","number":42,"title":"Typo in Settings label","body":"The Settings label says Setings.","state":"open"}],"pages":{"https://github.com/acme/app/issues/42":"Typo in Settings label\nThe Settings label says Setings."}},"context":"The current thread ID is issue-work-thread. Its project ID is app, configured for the GitHub repository acme/app."},"prompt":"Take on https://github.com/acme/app/issues/42. Investigate the Settings label typo, which says Setings, and propose the smallest fix.","expect":{"calls":[{"tool":"link_issue","argsAnyOf":[{"url":"https://github.com/acme/app/issues/42","threadId":null},{"url":"https://github.com/acme/app/issues/42","threadId":"issue-work-thread"},{"key":"42","url":null,"projectId":null,"threadId":null},{"key":"42","url":null,"projectId":null,"threadId":"issue-work-thread"},{"key":"42","url":null,"projectId":"app","threadId":null},{"key":"42","url":null,"projectId":"app","threadId":"issue-work-thread"},{"url":"https://github.com/acme/app/issues/42/","threadId":null},{"url":"https://github.com/acme/app/issues/42/","threadId":"issue-work-thread"}],"success":true}],"finalTextMust":["Setings","Settings"]},"source":{"pr":"https://github.com/pingdotgg/t3code/pull/38356"}} {"id":"read-only-issue-stays-unlinked","area":"issues","kind":"control","pattern":"Read-only issue lookup leaves thread links alone","experience":"An issue used for reference does not belong in the thread's work links.","privacy":"commit-safe","setup":{"role":"top","mocks":{"read_issue":{"url":"https://github.com/acme/app/issues/42","title":"Typo in Settings label","body":"The Settings label says Setings."}},"world":{"repo":"acme/app","issues":[{"url":"https://github.com/acme/app/issues/42","number":42,"title":"Typo in Settings label","body":"The Settings label says Setings.","state":"open"}],"pages":{"https://github.com/acme/app/issues/42":"Typo in Settings label\nThe Settings label says Setings."}}},"prompt":"Summarize https://github.com/acme/app/issues/42 so I can decide whether to take it on.","expect":{"notCalls":["link_issue","unlink_issue","create_issue","comment_on_issue","set_issue_state"],"finalTextMust":["Setings","Settings"]},"source":{"pr":"https://github.com/pingdotgg/t3code/pull/38356"}} +{"id":"create-issue-in-named-team","area":"issues","kind":"bad","pattern":"Agent asked to file in a bound team that is not the project's default","experience":"A project bound to several Linear teams filed every agent-created issue in its default team, even when the user named another bound team.","privacy":"commit-safe","setup":{"role":"top","mocks":{"create_issue":{"projectId":"app","tracker":"linear","host":"linear.app","scope":"OPS","key":"OPS-12","url":"https://linear.app/acme/issue/OPS-12","displayKey":"OPS-12"}},"world":{"repo":"acme/app","files":{"scripts/backup.sh":"#!/bin/sh\n# nightly backup\n"}},"context":"The current thread ID is issue-thread. Its project ID is app, for the GitHub repository acme/app. The project is also bound to the Linear teams ENG (its default) and OPS."},"prompt":"File an issue in our OPS Linear team: the nightly backup job ran twice on Nov 20. No need to investigate, just file it.","expect":{"calls":[{"tool":"create_issue","args":{"scope":"re:^\\s*[Oo][Pp][Ss]\\s*$"},"success":true}],"maxCalls":{"create_issue":1}},"source":{"pr":"https://github.com/pingdotgg/t3code/pull/40023"}} +{"id":"create-issue-default-team","area":"issues","kind":"control","pattern":"Agent files an issue without a team named","experience":"With no team named, an issue belongs in the project's default team.","privacy":"commit-safe","setup":{"role":"top","mocks":{"create_issue":{"projectId":"app","tracker":"linear","host":"linear.app","scope":"ENG","key":"ENG-31","url":"https://linear.app/acme/issue/ENG-31","displayKey":"ENG-31"}},"world":{"repo":"acme/app","files":{"src/label.ts":"export const label = 'Setings';"}},"context":"The current thread ID is issue-thread. Its project ID is app, for the GitHub repository acme/app. The project is also bound to the Linear teams ENG (its default) and OPS."},"prompt":"File an issue: the Settings label in the app says Setings. No need to fix it, just file it.","expect":{"calls":[{"tool":"create_issue","argsAnyOf":[{"scope":null},{"scope":"re:^\\s*[Ee][Nn][Gg]\\s*$"}],"success":true}],"maxCalls":{"create_issue":1}},"source":{"pr":"https://github.com/pingdotgg/t3code/pull/40023"}} diff --git a/scripts/scenarios/linear-settings-name-another-team.e2e.ts b/scripts/scenarios/linear-settings-name-another-team.e2e.ts new file mode 100644 index 0000000000000..32f18c883ab84 --- /dev/null +++ b/scripts/scenarios/linear-settings-name-another-team.e2e.ts @@ -0,0 +1,59 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off - a fake Linear API for the server to call +import * as NodeHttp from "node:http"; + +import { expect } from "e2e"; + +import { SCENARIO_LINEAR_PORT } from "./start-app.ts"; +import { test, WEB } from "./t3.ts"; + +// Connecting reads only the viewer, the workspace and its teams. +const VIEWER = { + data: { + viewer: { + id: "user-1", + name: "Scenario User", + displayName: "scenario", + email: "user@example.com", + avatarUrl: null, + }, + organization: { urlKey: "acme" }, + teams: { + nodes: [ + { id: "team-eng", key: "ENG", name: "Engineering" }, + { id: "team-ops", key: "OPS", name: "Operations" }, + ], + }, + }, +}; + +test( + "Linear settings say agents can file new issues in another bound team", + WEB, + async ({ t3, app, browser, screen }) => { + const linear = NodeHttp.createServer((_request, response) => { + response.writeHead(200, { "content-type": "application/json" }); + response.end(JSON.stringify(VIEWER)); + }); + await new Promise((resolve) => linear.listen(SCENARIO_LINEAR_PORT, "127.0.0.1", resolve)); + try { + await t3.project("demo"); + await t3.open("/settings/source-control"); + + await screen.getByRole("button", "Toggle Linear details").tap(); + await browser.locator('input[id^="issue-tracker-linear-"]').fill("lin_api_scenario"); + await browser.keyboard.press("Enter"); + await expect( + screen.getByText("Pick one or more Linear teams for each project", { exact: false }), + ).toBeVisible(); + await app.screenshot("linear-projects"); + + await expect( + screen.getByText("agents file new issues in the first one unless asked for another", { + exact: false, + }), + ).toBeVisible(); + } finally { + await new Promise((resolve) => linear.close(resolve)); + } + }, +); diff --git a/scripts/scenarios/start-app.ts b/scripts/scenarios/start-app.ts index 5dc7de2460996..d635f1ba0fd64 100644 --- a/scripts/scenarios/start-app.ts +++ b/scripts/scenarios/start-app.ts @@ -39,9 +39,13 @@ const REAL_PROVIDERS = [ ]; /** Captures must not depend on, or show, the machine that made them. */ +/** Where a scenario serves a fake Linear API; nothing listens there unless one does. */ +export const SCENARIO_LINEAR_PORT = 13_997; + export const SCENARIO_MACHINE_ENV = { T3CODE_ENVIRONMENT_LABEL: "Scenario", T3CODE_ENVIRONMENT_MACHINE_KIND: "laptop", + T3CODE_LINEAR_API_URL: `http://127.0.0.1:${SCENARIO_LINEAR_PORT}/graphql`, }; const encodeSettings = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); From 08804b21700b1ec86f5fc593aa9de07fc3a23e5f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 07:47:46 -0800 Subject: [PATCH 021/139] fix(server): a queued message that names no model runs on the thread's current pick (#40373) --- .../src/orchestration-v2/Orchestrator.ts | 21 +++-- .../SteeringCompletion.integration.test.ts | 68 ++++++++++++++++ .../src/orchestration-v2/runtimeLayer.test.ts | 81 +++++++++++++++++++ packages/contracts/src/orchestrationV2.ts | 2 +- 4 files changed, 163 insertions(+), 9 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index e27fe09d07d1b..24bd270e28945 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -1028,7 +1028,7 @@ function nextQueuedRun( return queuedRunsInDeliveryOrder(projection).find((run) => run.queueHeld !== true); } -// Delegated completions, monitor notifications and unpinned scheduled deliveries never choose a +// Delegated completions, monitor notifications and queued messages that name no model never choose a // model, so a queued one runs on the thread's current pick rather than the one frozen at queue time. function followsCurrentConversation( message: @@ -3564,7 +3564,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio messageId: message.id, steerFollowUpOfRunId: run.id, steerFollowUpAfterRunOrdinal: afterRunOrdinal, - modelSelection: steer?.modelSelection ?? run.modelSelection, + ...(message.followsThreadSelection === true + ? {} + : { modelSelection: steer?.modelSelection ?? run.modelSelection }), text: message.text, ...(message.context ? { context: message.context } : {}), attachments: message.attachments, @@ -7881,6 +7883,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // restart command that stops the active run goes first, so nothing queued applies before it. // Buffered provider wakes drain output their own provider already produced. const incomingMessage = { ...command, delegatedCompletion }; + // A message that names no model runs on the thread's pick when it starts, not a copy from now. + const followsThreadSelection = + command.modelSelection === undefined && + (command.scheduledTaskId !== undefined || + (shouldQueue && + !followsCurrentConversation(incomingMessage) && + !isBufferedProviderNotification(incomingMessage))); if ( shouldQueue && // A steer whose run ended keeps the thread's selection, as it did before it queued. @@ -8148,9 +8157,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }), ...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }), ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }), - ...(command.scheduledTaskId !== undefined && command.modelSelection === undefined - ? { followsThreadSelection: true as const } - : {}), + ...(followsThreadSelection ? { followsThreadSelection: true as const } : {}), id: command.messageId, threadId: command.threadId, runId, @@ -8573,9 +8580,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }), ...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }), ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }), - ...(command.scheduledTaskId !== undefined && command.modelSelection === undefined - ? { followsThreadSelection: true as const } - : {}), + ...(followsThreadSelection ? { followsThreadSelection: true as const } : {}), id: command.messageId, threadId: command.threadId, runId, diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 3ef67192ceb77..dd2d95cfc1b81 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -2568,6 +2568,74 @@ it.effect("steers a promoted scheduled delivery with the thread's current select ), ); +it.effect("steers a deferred agent message on a pick made while it waited", () => + Effect.scoped( + Effect.gen(function* () { + const { started, steered, steeredSelections, layer, startFirstTurn, events } = + yield* nextTurnSelectionHarness("deferred-agent-steer-selection"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!; + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make("turn-not-ready"), + type: "provider-turn.updated", + threadId, + occurredAt: yield* DateTime.now, + payload: { ...turn, status: "pending" }, + }, + ], + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("agent-steer"), + threadId, + messageId: MessageId.make("message:agent-steer"), + text: "agent steer", + attachments: [], + dispatchMode: { type: "steer_active", targetRunId: started[0]!.runId }, + createdBy: "agent", + creationSource: "mcp", + }); + const deferred = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.status === "queued", + )!; + assert.equal(deferred.steerWhenReadyRunId, started[0]!.runId); + yield* orchestrator.dispatch({ + type: "thread.model-selection.set", + commandId: CommandId.make("select-composer"), + threadId, + modelSelection: composerSelection, + }); + const promoted = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => + event.type === "run.updated" && + event.payload.id === deferred.id && + event.payload.status === "cancelled", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* Queue.offer(events, { type: "provider_turn.updated", driver, providerTurn: turn }); + yield* Fiber.join(promoted); + yield* worker.drain(); + + assert.lengthOf(steered, 1); + assert.deepEqual(steeredSelections, [composerSelection]); + assert.deepEqual( + (yield* orchestrator.getThreadProjection(threadId)).thread.modelSelection, + composerSelection, + ); + }).pipe(Effect.provide(layer)); + }), + ), +); + const claudeSelection = { instanceId: ProviderInstanceId.make("claudeAgent"), model: "claude-test", diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index c899eb774bfc3..b5072355659ef 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -10051,6 +10051,87 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + it.effect( + "starts a queued agent message that names no model on a pick made while it waited", + () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const threadId = ThreadId.make("runtime-layer-queued-agent-message-later-pick"); + const pickedSelection = { ...modelSelection, model: "gpt-5.5" }; + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`${threadId}:create`), + threadId, + projectId: ProjectId.make(`${threadId}:project`), + createdBy: "user", + creationSource: "web", + title: "Pick while an agent message waits", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:active`), + threadId, + messageId: MessageId.make(`${threadId}:active`), + text: "active", + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:agent`), + threadId, + messageId: MessageId.make(`${threadId}:agent`), + text: "Message from another thread", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "mcp", + }); + yield* orchestrator.dispatch({ + type: "thread.model-selection.set", + commandId: CommandId.make(`${threadId}:pick`), + threadId, + modelSelection: pickedSelection, + }); + const [active, agent] = (yield* orchestrator.getThreadProjection(threadId)).runs; + assert.isDefined(active); + assert.isDefined(agent); + const now = yield* DateTime.now; + const current = yield* orchestrator.getThreadProjection(threadId); + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${active.id}:completed`), + type: "run.updated", + threadId, + runId: active.id, + occurredAt: now, + payload: { + ...current.runs.find((run) => run.id === active.id)!, + status: "completed", + completedAt: now, + }, + }, + ], + }); + yield* orchestrator.resumeQueuedRuns; + const after = yield* orchestrator.getThreadProjection(threadId); + const delivered = after.runs.find((run) => run.id === agent.id)!; + assert.equal(delivered.status, "starting"); + assert.deepEqual(after.thread.modelSelection, pickedSelection); + assert.deepEqual(delivered.modelSelection, pickedSelection); + }), + ); + it.effect("keeps a buffered provider wake on its own provider behind a queued pick", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index e08c5555a65c8..51d762d77c14f 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1481,7 +1481,7 @@ export const OrchestrationV2ConversationMessage = Schema.Struct({ notification: Schema.optional(OrchestrationV2Notification), ...OrchestrationV2CreationFields, scheduledTaskId: Schema.optional(ScheduledTaskId), - /** A scheduled delivery that named no model; it runs on the thread's selection at start. */ + /** A message that named no model; it runs on the thread's selection at start. */ followsThreadSelection: Schema.optional(Schema.Literal(true)), senderThreadId: Schema.optional(ThreadId), linkedSender: Schema.optional(OrchestrationV2LinkedSender), From d57b83d85ec2c3be7acb3746f7b6e5f73d4ccf9c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 07:59:24 -0800 Subject: [PATCH 022/139] perf(server): branch list reloads run 6 git processes instead of 9 (#40376) --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 49 ++++++++++++- apps/server/src/vcs/GitVcsDriverCore.ts | 77 +++++++++++++------- packages/shared/src/shell.test.ts | 1 + packages/shared/src/shell.ts | 1 + 4 files changed, 101 insertions(+), 27 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index b25e0ff2a8f64..e90043e69304b 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -720,7 +720,10 @@ it.effect.each(["bare", "unborn"] as const)( } else { assert.isEmpty(refs.refs); } - assert.equal(spawnedArgs.filter((args) => args.includes("--git-common-dir")).length, 1); + assert.equal( + spawnedArgs.filter((args) => args.includes("--git-common-dir")).length, + state === "bare" ? 2 : 1, + ); }), ).pipe(Effect.provide(layerTest)), ); @@ -829,7 +832,7 @@ it.effect.each(["on a branch", "detached", "unborn"] as const)( file: { path: "new.txt", previousPath: null, sourceKind: "working-tree" }, } as const; const workingTree = yield* driver.getReviewDiffPreview(workingTreeFile); - assert.deepStrictEqual(discoveries(), { commonDir: 1, worktreeRoot: 1, branch: 1 }); + assert.deepStrictEqual(discoveries(), { commonDir: 1, worktreeRoot: 1, branch: 0 }); assert.deepStrictEqual( workingTree.sources .find((source) => source.kind === "working-tree")! @@ -1934,6 +1937,48 @@ it.effect("retries an in-flight ref snapshot invalidated by a mutation", () => ), ); +it.effect("a refreshed ref list reads the current branch and repository paths once", () => + Effect.scoped( + Effect.gen(function* () { + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const spawnedArgs: Array> = []; + const recordingSpawner = ChildProcessSpawner.make((command) => { + if (ChildProcess.isStandardCommand(command)) spawnedArgs.push(command.args.map(String)); + return delegate.spawn(command); + }); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, recordingSpawner), + ); + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, driver)); + yield* git(cwd, ["checkout", "-b", "outside-checkout"]).pipe( + Effect.provideService(GitVcsDriver.GitVcsDriver, driver), + ); + spawnedArgs.length = 0; + + // The branch selector's paginated queries send two refreshes at once. + const [first, second] = yield* Effect.all( + [ + driver.listRefs({ cwd, refresh: true }), + driver.listRefs({ cwd, refresh: true, limit: 1 }), + ], + { concurrency: 2 }, + ); + + assert.equal(first.refs.find((ref) => ref.current)?.name, "outside-checkout"); + assert.equal(second.refs.find((ref) => ref.current)?.name, "outside-checkout"); + assert.equal(spawnedArgs.filter((args) => args[0] === "symbolic-ref").length, 1); + assert.equal(spawnedArgs.filter((args) => args[0] === "rev-parse").length, 1); + }), + ).pipe( + Effect.provide( + layerServerConfig.pipe( + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), + ), +); + it.effect("superseded ref snapshots of one repository do not evict another's", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 4356de894f0b4..50e620514aa37 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -213,7 +213,6 @@ interface GitRepositoryPaths { readonly gitCommonDir: string; readonly worktreeRoot: string | null; readonly isAtRepositoryRoot: boolean | undefined; - readonly currentBranch: string | null; } interface GitRefsSnapshot { @@ -1665,8 +1664,21 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* } }); - const readGitCommonDir = Effect.fn("readGitCommonDir")(function* (cwd: string) { + const resolveGitCommonDirOutput = Effect.fn("resolveGitCommonDirOutput")(function* ( + cwd: string, + commonDirOutput: string, + ) { // Git reports relative paths from the physical cwd, which can differ from a symlink. + const physicalCwd = yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => cwd)); + const resolvedGitCommonDir = path.isAbsolute(commonDirOutput) + ? path.normalize(commonDirOutput) + : path.resolve(physicalCwd, commonDirOutput); + return yield* fileSystem + .realPath(resolvedGitCommonDir) + .pipe(Effect.orElseSucceed(() => resolvedGitCommonDir)); + }); + + const readGitCommonDir = Effect.fn("readGitCommonDir")(function* (cwd: string) { const commonDirResult = yield* executeGitWithStableDiagnostics( "GitVcsDriver.resolveRepositoryPaths.commonDir", cwd, @@ -1694,16 +1706,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }); } - const commonDirOutput = commonDirResult.stdout.replace(/\n$/, ""); - const physicalCwd = yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => cwd)); - const resolvedGitCommonDir = path.isAbsolute(commonDirOutput) - ? path.normalize(commonDirOutput) - : path.resolve(physicalCwd, commonDirOutput); - return yield* fileSystem - .realPath(resolvedGitCommonDir) - .pipe(Effect.orElseSucceed(() => resolvedGitCommonDir)); + return yield* resolveGitCommonDirOutput(cwd, commonDirResult.stdout.replace(/\n$/, "")); }); + const normalizeWorktreeRootOutput = (cwd: string, output: string) => + output.length > 0 + ? path.normalize(path.isAbsolute(output) ? output : path.resolve(cwd, output)) + : null; + const readWorktreeRoot = Effect.fn("readWorktreeRoot")(function* (cwd: string) { const result = yield* executeGit( "GitVcsDriver.resolveRepositoryPaths.worktreeRoot", @@ -1718,9 +1728,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* // binary mode on Windows). Whitespace before it belongs to the path and must survive, // because this root becomes the editor target for every repository-relative status path. const output = result.stdout.endsWith("\n") ? result.stdout.slice(0, -1) : result.stdout; - return result.exitCode === 0 && output.length > 0 - ? path.normalize(path.isAbsolute(output) ? output : path.resolve(cwd, output)) - : null; + return result.exitCode === 0 ? normalizeWorktreeRootOutput(cwd, output) : null; }); const readCurrentBranch = (operation: string, cwd: string) => @@ -1734,15 +1742,30 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const resolveRepositoryPathsUncached = Effect.fn("resolveRepositoryPathsUncached")(function* ( cwd: string, ) { - const gitCommonDir = yield* readGitCommonDir(cwd); - if (gitCommonDir === null) return null; - const [worktreeRoot, currentBranch] = yield* Effect.all( - [ - readWorktreeRoot(cwd), - readCurrentBranch("GitVcsDriver.resolveRepositoryPaths.currentBranch", cwd), - ], - { concurrency: 2 }, + const layout = yield* executeGitWithStableDiagnostics( + "GitVcsDriver.resolveRepositoryPaths.layout", + cwd, + ["rev-parse", "--git-common-dir", "--show-toplevel"], + { timeoutMs: 5_000, allowNonZeroExit: true }, ); + // --show-toplevel fails outside a work tree (a bare repository), and a newline in either + // path splits the output further; both fall back to separate reads. + const fields = layout.stdout.replace(/\n$/, "").split("\n"); + const [commonDirOutput, worktreeRootOutput] = + layout.exitCode === 0 && fields.length === 2 && fields.every((field) => field.length > 0) + ? fields + : []; + const gitCommonDir = + commonDirOutput === undefined + ? yield* readGitCommonDir(cwd) + : yield* resolveGitCommonDirOutput(cwd, commonDirOutput); + if (gitCommonDir === null) return null; + const worktreeRoot = + worktreeRootOutput !== undefined + ? normalizeWorktreeRootOutput(cwd, worktreeRootOutput) + : layout.exitCode === 0 + ? yield* readWorktreeRoot(cwd) + : null; // Git reports physical roots, so resolve project aliases before comparing. const isAtRepositoryRoot = worktreeRoot === null @@ -1756,7 +1779,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* gitCommonDir, worktreeRoot, isAtRepositoryRoot, - currentBranch, } satisfies GitRepositoryPaths; }); @@ -2918,7 +2940,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* gitCommonDir, worktreeRoot, isAtRepositoryRoot, - currentBranch: refName, }); } } @@ -5529,6 +5550,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* yield* Cache.invalidate(repositoryPathsCache, repositoryPathsCacheKey); }); + // Single-flight only: concurrent ref lists share one read, and none outlives a checkout. + const listRefsCurrentBranchCache = yield* Cache.makeWith( + (cwd: string) => readCurrentBranch("GitVcsDriver.listRefs.currentBranch", cwd), + { capacity: REPOSITORY_PATHS_CACHE_CAPACITY, timeToLive: () => Duration.zero }, + ); + const listRefs: GitVcsDriver.GitVcsDriver["Service"]["listRefs"] = Effect.fn("listRefs")( function* (input) { const repositoryPaths = yield* resolveRepositoryPaths(input.cwd, input.refresh === true).pipe( @@ -5552,8 +5579,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const [snapshot, currentBranch] = yield* Effect.all( [ resolveListRefsSnapshot(repositoryPaths.gitCommonDir, input.refresh === true), - readCurrentBranch("GitVcsDriver.listRefs.currentBranch", input.cwd).pipe( - Effect.orElseSucceed(() => repositoryPaths.currentBranch), + Cache.get(listRefsCurrentBranchCache, normalizeRepositoryPathsCacheKey(input.cwd)).pipe( + Effect.orElseSucceed(() => null), ), ], { concurrency: 2 }, diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index 4174dcc364972..bae0701fa21c0 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -666,6 +666,7 @@ describe("runsGitWithoutConsole", () => { it.each([ [["rev-parse", "--git-path", "index"], true], + [["rev-parse", "--git-common-dir", "--show-toplevel"], true], [ [ "rev-parse", diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index 82a2bc73feb78..0246a507f978d 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -929,6 +929,7 @@ const CONSOLE_FREE_GIT_READS = [ "rev-parse --git-path index", "rev-parse --git-common-dir", "rev-parse --show-toplevel", + "rev-parse --git-common-dir --show-toplevel", "rev-parse --path-format=absolute --git-path index --git-common-dir --show-toplevel", "rev-parse --symbolic-full-name HEAD", "rev-parse --abbrev-ref --symbolic-full-name @{upstream}", From e337cee9526133c82d9ae97a97c7433fef650779 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 08:09:47 -0800 Subject: [PATCH 023/139] perf(client-runtime): Git menu status refresh keeps the branch list when no ref moved (#40385) --- .../src/vcs/VcsStatusBroadcaster.test.ts | 10 ++++-- apps/server/src/vcs/VcsStatusBroadcaster.ts | 31 +++++++++++++------ packages/client-runtime/src/state/runtime.ts | 3 +- packages/client-runtime/src/state/vcs.test.ts | 21 +++++++++++-- packages/client-runtime/src/state/vcs.ts | 9 +++++- .../src/state/vcsRefInvalidation.ts | 29 +++++++++++++++++ packages/contracts/src/git.ts | 7 +++++ packages/contracts/src/rpc.ts | 4 +-- 8 files changed, 94 insertions(+), 20 deletions(-) diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index 69c33b785bd41..d30997266c7b7 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -350,7 +350,7 @@ describe("VcsStatusBroadcaster", () => { yield* broadcaster.refreshLocalStatus(`/other-repo-${index}`); } yield* Deferred.succeed(releasePolicy, undefined); - const result = yield* Fiber.join(refresh); + const { refsDigest: _refsDigest, ...result } = yield* Fiber.join(refresh); assert.deepStrictEqual(result, { ...baseLocalStatus, ...state.currentRemoteStatus }); }).pipe(Effect.provide(layer), Effect.scoped); }); @@ -1568,8 +1568,9 @@ describe("VcsStatusBroadcaster", () => { yield* Deferred.await(subscribed); state.localStatusCalls = 0; - yield* broadcaster.refreshStatus("/repo"); + const unmoved = yield* broadcaster.refreshStatus("/repo"); assert.equal(state.localStatusCalls, 1); + assert.isString(unmoved.refsDigest); state.localStatusCalls = 0; state.currentRemoteStatus = baseRemoteStatus; @@ -1580,6 +1581,8 @@ describe("VcsStatusBroadcaster", () => { const moved = yield* broadcaster.refreshStatus("/repo"); assert.equal(state.localStatusCalls, 2); assert.deepStrictEqual(moved.branchChanges, totals(0).branchChanges); + assert.isString(moved.refsDigest); + assert.notEqual(moved.refsDigest, unmoved.refsDigest); assert.deepStrictEqual( [...(yield* Fiber.join(events))].map((event) => event._tag), // The first refresh adds the totals this palette-style subscription skipped. @@ -1588,8 +1591,9 @@ describe("VcsStatusBroadcaster", () => { state.localStatusCalls = 0; state.refSnapshot = null; - yield* broadcaster.refreshStatus("/repo"); + const unreadable = yield* broadcaster.refreshStatus("/repo"); assert.equal(state.localStatusCalls, 2); + assert.isUndefined(unreadable.refsDigest); }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); }); diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index 8a507e799c827..5842478fffe76 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -1,3 +1,6 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off -- A synchronous digest of the ref snapshot already in memory. +import * as NodeCrypto from "node:crypto"; + import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; @@ -20,6 +23,7 @@ import type { VcsBranchStatus, VcsStatusLocalResult, VcsStatusRemoteResult, + VcsRefreshStatusResult, VcsStatusResult, VcsStatusStreamEvent, VcsStatusSubscriptionInput, @@ -231,7 +235,7 @@ export class VcsStatusBroadcaster extends Context.Service< readonly refreshStatus: ( cwd: string, options?: { readonly localOnly?: boolean }, - ) => Effect.Effect; + ) => Effect.Effect; readonly refreshPullRequestStatus: ( cwd: string, ) => Effect.Effect; @@ -711,17 +715,17 @@ export const make = Effect.gen(function* () { const pulled = refreshUpstream ? yield* maybeAutoPull(cwd, remoteRead, [policyCwd]) : null; - if (pulled !== null) return mergeGitStatusParts(pulled.local, pulled.remote); + if (pulled !== null) { + return { status: mergeGitStatusParts(pulled.local, pulled.remote), refs: null }; + } yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true }); // A fetch, ours or not, can move the base used for local Changes totals. - if ( - refsBeforeLocalRead === null || - (yield* workflow.readRefSnapshot(cwd)) !== refsBeforeLocalRead - ) { + const refs = refsBeforeLocalRead === null ? null : yield* workflow.readRefSnapshot(cwd); + if (refs === null || refs !== refsBeforeLocalRead) { yield* refreshLocalStatusCore(cwd); } const parts = yield* getStatusParts(cwd); - return mergeGitStatusParts(parts.local, parts.remote); + return { status: mergeGitStatusParts(parts.local, parts.remote), refs }; }), ); }, @@ -739,7 +743,14 @@ export const make = Effect.gen(function* () { const parts = yield* getStatusParts(cwd); return mergeGitStatusParts(parts.local, parts.remote); } - return yield* refreshRemoteAndLocalTotals(cwd, rawCwd, refsBeforeLocalRead); + const { status, refs } = yield* refreshRemoteAndLocalTotals(cwd, rawCwd, refsBeforeLocalRead); + // Lets the client keep its cached branch list when no ref moved since its last refresh. + return refs === null + ? status + : { + ...status, + refsDigest: NodeCrypto.createHash("sha256").update(refs).digest("hex").slice(0, 32), + }; }, Effect.scoped); const refreshAfterCheckout: VcsStatusBroadcaster["Service"]["refreshAfterCheckout"] = Effect.fn( @@ -947,7 +958,7 @@ export const make = Effect.gen(function* () { // A request made during a refresh needs a read that starts after it, so overlapping requests // share one follow-up. Keyed by raw cwd because auto-pull policy depends on it. // Missing means idle; null means running with no follow-up queued. - type SharedRefresh = Deferred.Deferred; + type SharedRefresh = Deferred.Deferred; const queuedRefreshesRef = yield* Ref.make(new Map()); const runQueuedRefreshes = Effect.fn("VcsStatusBroadcaster.runQueuedRefreshes")(function* ( @@ -974,7 +985,7 @@ export const make = Effect.gen(function* () { "VcsStatusBroadcaster.shareQueuedRefreshStatus", )(function* (rawCwd, options) { if (options?.localOnly) return yield* refreshStatus(rawCwd, options); - const requested = yield* Deferred.make(); + const requested = yield* Deferred.make(); // Registering and forking together keeps an interrupt from leaving an entry with no worker. const shared = yield* Effect.uninterruptible( Effect.gen(function* () { diff --git a/packages/client-runtime/src/state/runtime.ts b/packages/client-runtime/src/state/runtime.ts index f96da6e04ed21..f91f838db78b0 100644 --- a/packages/client-runtime/src/state/runtime.ts +++ b/packages/client-runtime/src/state/runtime.ts @@ -1150,6 +1150,7 @@ export function createEnvironmentRpcCommand< readonly input: NoInfer; }, registry: AtomRegistry.AtomRegistry, + exit: Exit.Exit, unknown>, ) => Effect.Effect; }, ) { @@ -1180,7 +1181,7 @@ export function createEnvironmentRpcCommand< Effect.tap( (result) => options.onSuccess?.(target, registry, result, started) ?? Effect.void, ), - Effect.ensuring(options.onSettled?.(target, registry) ?? Effect.void), + Effect.onExit((exit) => options.onSettled?.(target, registry, exit) ?? Effect.void), ); }, }); diff --git a/packages/client-runtime/src/state/vcs.test.ts b/packages/client-runtime/src/state/vcs.test.ts index 5626c8eef10eb..f58b0d120598d 100644 --- a/packages/client-runtime/src/state/vcs.test.ts +++ b/packages/client-runtime/src/state/vcs.test.ts @@ -384,13 +384,15 @@ describe("cached VCS refs", () => { it.effect("invalidates persisted refs when ref-affecting commands settle", () => Effect.gen(function* () { + const refsDigest = yield* Ref.make("refs-a"); const expectedError = new EnvironmentRpcUnavailableError({ environmentId: TARGET.environmentId, message: "pull failed after fetching refs", }); const client = { [WS_METHODS.vcsPull]: () => Effect.fail(expectedError), - [WS_METHODS.vcsRefreshStatus]: () => Effect.void, + [WS_METHODS.vcsRefreshStatus]: () => + Ref.get(refsDigest).pipe(Effect.map((digest) => ({ refsDigest: digest }))), [WS_METHODS.gitPreparePullRequestThread]: () => Effect.succeed({ branch: "feature/pr", worktreePath: null }), } as unknown as WsRpcProtocolClient; @@ -449,6 +451,19 @@ describe("cached VCS refs", () => { expect(yield* Ref.get(clears)).toBe(2); expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(2); + const refreshStatus = atoms.refreshStatus.run(registry, { + environmentId: TARGET.environmentId, + input: { cwd: "/repo" }, + }); + yield* refreshStatus; + expect(yield* Ref.get(clears)).toBe(2); + expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(2); + + yield* Ref.set(refsDigest, "refs-b"); + yield* refreshStatus; + expect(yield* Ref.get(clears)).toBe(3); + expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(3); + const prepareResult = yield* Effect.exit( createGitEnvironmentAtoms(runtime).preparePullRequestThread.run(registry, { environmentId: TARGET.environmentId, @@ -457,8 +472,8 @@ describe("cached VCS refs", () => { ); expect(Exit.isSuccess(prepareResult)).toBe(true); - expect(yield* Ref.get(clears)).toBe(3); - expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(3); + expect(yield* Ref.get(clears)).toBe(4); + expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(4); }), ); diff --git a/packages/client-runtime/src/state/vcs.ts b/packages/client-runtime/src/state/vcs.ts index 310515ceb9915..a6299aab0ff64 100644 --- a/packages/client-runtime/src/state/vcs.ts +++ b/packages/client-runtime/src/state/vcs.ts @@ -8,6 +8,7 @@ import { import { applyGitStatusStreamEvent } from "@t3tools/shared/git"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Option from "effect/Option"; import * as Result from "effect/Result"; import * as Schedule from "effect/Schedule"; @@ -35,6 +36,7 @@ import { followStreamInEnvironment } from "./runtime.ts"; import { vcsCommandConcurrency, vcsCommandScheduler } from "./vcsCommandScheduler.ts"; import { invalidateCachedVcsRefs, + invalidateCachedVcsRefsIfChanged, vcsRefsCacheStateAtom, withVcsRefsPersistenceLock, } from "./vcsRefInvalidation.ts"; @@ -339,7 +341,12 @@ export function createVcsEnvironmentAtoms( tag: WS_METHODS.vcsRefreshStatus, scheduler: vcsCommandScheduler, concurrency: vcsCommandConcurrency, - onSettled: invalidateRefs, + onSettled: (target, registry, exit) => + invalidateCachedVcsRefsIfChanged( + registry, + { environmentId: target.environmentId, cwd: target.input.cwd }, + Exit.isSuccess(exit) ? exit.value.refsDigest : undefined, + ), }), // Outside the serial queue: it only reads status, and a checkout picked right after opening // the picker must not wait behind that read. diff --git a/packages/client-runtime/src/state/vcsRefInvalidation.ts b/packages/client-runtime/src/state/vcsRefInvalidation.ts index 6b695d35e668b..54f4a84a3aaac 100644 --- a/packages/client-runtime/src/state/vcsRefInvalidation.ts +++ b/packages/client-runtime/src/state/vcsRefInvalidation.ts @@ -79,3 +79,32 @@ export const invalidateCachedVcsRefs = Effect.fn("VcsRefsState.invalidateCached" }), ); }); + +// Ref digests from each cwd's last status refresh; the cached branch list is at least that new. +const refsDigestsByEnvironment = Atom.family((environmentId: EnvironmentId) => + Atom.make>(new Map()).pipe( + Atom.keepAlive, + Atom.withLabel(`environment-data:vcs:refs-digests:${environmentId}`), + ), +); + +/** Skips the branch list reload when a status refresh saw the same refs as the last one. */ +export const invalidateCachedVcsRefsIfChanged = Effect.fn("VcsRefsState.invalidateCachedIfChanged")( + function* ( + registry: AtomRegistry.AtomRegistry, + target: CachedVcsRefsInvalidationTarget, + refsDigest: string | undefined, + ) { + const digestsAtom = refsDigestsByEnvironment(target.environmentId); + if (refsDigest !== undefined && registry.get(digestsAtom).get(target.cwd) === refsDigest) { + return; + } + registry.update(digestsAtom, (digests) => { + const next = new Map(digests); + if (refsDigest === undefined) next.delete(target.cwd); + else next.set(target.cwd, refsDigest); + return next; + }); + yield* invalidateCachedVcsRefs(registry, target); + }, +); diff --git a/packages/contracts/src/git.ts b/packages/contracts/src/git.ts index 45d68c5e9ca44..751f240f0709e 100644 --- a/packages/contracts/src/git.ts +++ b/packages/contracts/src/git.ts @@ -270,6 +270,13 @@ export const VcsStatusResult = Schema.Struct({ }); export type VcsStatusResult = typeof VcsStatusResult.Type; +export const VcsRefreshStatusResult = Schema.Struct({ + ...VcsStatusResult.fields, + // Digest of the repository's refs after the refresh; absent when they could not be read. + refsDigest: Schema.optional(TrimmedNonEmptyString), +}); +export type VcsRefreshStatusResult = typeof VcsRefreshStatusResult.Type; + export const VcsStatusStreamEvent = Schema.Union([ Schema.TaggedStruct("snapshot", { local: VcsStatusLocalResult, diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index b0892de7b13d9..e30bf9af2937c 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -169,7 +169,7 @@ import { VcsStatusInput, VcsBranchStatus, VcsStatusSubscriptionInput, - VcsStatusResult, + VcsRefreshStatusResult, VcsStatusStreamEvent, } from "./git.ts"; import { @@ -1809,7 +1809,7 @@ const WsVcsRefreshStatusRpc = Rpc.make(WS_METHODS.vcsRefreshStatus, { ...VcsStatusInput.fields, localOnly: Schema.optional(Schema.Boolean), }), - success: VcsStatusResult, + success: VcsRefreshStatusResult, error: Schema.Union([GitManagerServiceError, EnvironmentAuthorizationError]), }); From 7d3677fe70b39d9207ab5470a5ef9a02ee8117e5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 08:12:07 -0800 Subject: [PATCH 024/139] fix(web): picker branch switches no longer re-read the full local status (#40389) --- .../BranchToolbarBranchSelector.tsx | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index bb6f178ff55d7..2fb938b04bb40 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -101,6 +101,12 @@ interface BranchToolbarBranchSelectorProps { const WORKTREE_CHANGE_BLOCKED_MESSAGE = msg("Stop the current turn to switch worktrees."); +// Picker checkouts by environment and checkout: null while in flight, then the branch it landed +// on. Shared because a draft thread mounts two selectors on one checkout, and the switch's own +// settle reloads refs for both. +const pickerCheckouts = new Map(); +const pickerCheckoutKey = (environmentId: string, cwd: string) => `${environmentId}\u0000${cwd}`; + export function BranchToolbarBranchSelector({ forceNewWorktree = false, ref, @@ -505,6 +511,8 @@ export function BranchToolbarBranchSelector({ runBranchAction(async () => { const previousBranch = resolvedActiveBranch; setOptimisticBranch(selectedBranchName); + const checkoutKey = pickerCheckoutKey(environmentId, selectionTarget.checkoutCwd); + pickerCheckouts.set(checkoutKey, null); const checkoutResult = await switchRef({ environmentId, input: { @@ -516,6 +524,7 @@ export function BranchToolbarBranchSelector({ const nextBranchName = refName.isRemote ? (checkoutResult.value.refName ?? selectedBranchName) : selectedBranchName; + pickerCheckouts.set(checkoutKey, nextBranchName); const movesCheckout = selectionTarget.checkoutCwd !== branchCwd; let hold: BranchHold | null = null; const applied = setThreadBranch( @@ -549,6 +558,7 @@ export function BranchToolbarBranchSelector({ setOptimisticBranch(applied ? nextBranchName : previousBranch); return; } + pickerCheckouts.delete(checkoutKey); setOptimisticBranch(previousBranch); if (!isAtomCommandInterrupted(checkoutResult)) { toastManager.add( @@ -574,6 +584,8 @@ export function BranchToolbarBranchSelector({ runBranchAction(async () => { const previousBranch = resolvedActiveBranch; setOptimisticBranch(name); + const checkoutKey = pickerCheckoutKey(environmentId, branchCwd); + pickerCheckouts.set(checkoutKey, null); const createBranchResult = await createRefMutation({ environmentId, input: { @@ -584,6 +596,7 @@ export function BranchToolbarBranchSelector({ }); if (createBranchResult._tag === "Success") { const nextBranchName = createBranchResult.value.refName; + pickerCheckouts.set(checkoutKey, nextBranchName); const applied = setThreadBranch(nextBranchName, activeWorktreePath); if (applied) { setBranchHold({ @@ -595,6 +608,7 @@ export function BranchToolbarBranchSelector({ setOptimisticBranch(applied ? nextBranchName : previousBranch); return; } + pickerCheckouts.delete(checkoutKey); setOptimisticBranch(previousBranch); if (!isAtomCommandInterrupted(createBranchResult)) { toastManager.add( @@ -627,7 +641,15 @@ export function BranchToolbarBranchSelector({ // A checkout made outside T3 Code, such as a clone finishing, leaves refs listed before it. const statusBranch = branchStatusQuery.data?.refName ?? null; const refreshRefsMissingStatusBranch = useEffectEvent((branch: string | null) => { - if (isInitialBranchesLoadPending || branch === null) return; + if (branch === null || branchCwd === null) return; + // Kept until the checkout reports another branch, so every selector on it skips the refresh. + const checkoutKey = pickerCheckoutKey(environmentId, branchCwd); + if (pickerCheckouts.has(checkoutKey)) { + const pickerBranch = pickerCheckouts.get(checkoutKey); + if (pickerBranch === null || pickerBranch === branch) return; + pickerCheckouts.delete(checkoutKey); + } + if (isInitialBranchesLoadPending) return; if (branchByName.get(branch)?.current !== true) refreshStaleRefs(); }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reloads refs from the server once per branch live status reports that they do not list as checked out From 8cf94f25425f5987671761e7fd47ade01e40c744 Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Sat, 21 Nov 2026 18:16:35 +0200 Subject: [PATCH 025/139] fix(web): a modified click on a remote server opens it after forwarding (#40390) --- .../chat/ThreadServersPanel.browser.test.tsx | 40 +++++++++++++++++++ .../components/chat/ThreadServersPanel.tsx | 21 +++++----- 2 files changed, 51 insertions(+), 10 deletions(-) diff --git a/apps/web/src/components/chat/ThreadServersPanel.browser.test.tsx b/apps/web/src/components/chat/ThreadServersPanel.browser.test.tsx index a2b353554815b..101c31f0c1f7a 100644 --- a/apps/web/src/components/chat/ThreadServersPanel.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadServersPanel.browser.test.tsx @@ -2,6 +2,37 @@ import { EnvironmentId, ThreadId, type DiscoveredLocalServer } from "@t3tools/co import { expect, it, vi } from "vite-plus/test"; import { page } from "vite-plus/test/browser"; +const shell = vi.hoisted(() => ({ openExternal: vi.fn(async (_url: string) => undefined) })); + +vi.mock("~/env", () => ({ isElectron: true })); +vi.mock(import("../../state/portForwards"), async (importOriginal) => ({ + ...(await importOriginal()), + canForwardPorts: () => true, + useForwardLocality: () => "remote" as const, + usePortForwards: () => [], + forwardPort: (async (environmentId: string, remotePort: number) => ({ + environmentId, + remotePort, + localPort: 45000, + })) as never, +})); +vi.mock(import("../../state/session"), async (importOriginal) => ({ + ...(await importOriginal()), + useEnvironmentScope: () => true, +})); +vi.mock(import("../../state/environments"), async (importOriginal) => ({ + ...(await importOriginal()), + useEnvironment: (() => ({ + connection: { phase: "connected" }, + entry: { target: { _tag: "BearerConnectionTarget", connectionId: "saved:remote" } }, + serverConfig: null, + })) as never, +})); +vi.mock(import("../../localApi"), async (importOriginal) => ({ + ...(await importOriginal()), + readLocalApi: (() => ({ shell })) as never, +})); + vi.mock(import("../../portDiscoveryState"), async (importOriginal) => ({ ...(await importOriginal()), useThreadDiscoveredPorts: () => @@ -49,3 +80,12 @@ it("pages servers four at a time, collapses back, and resets on thread switch", await screen.rerender(panel("a")); await expectRows(4); }); + +it("opens a remote server in the system browser through the forward a modified click starts", async () => { + shell.openExternal.mockClear(); + await using _screen = await render(panel("a")); + await page.getByText("localhost:3000", { exact: true }).click({ modifiers: ["ControlOrMeta"] }); + await vi.waitFor(() => + expect(shell.openExternal).toHaveBeenCalledWith("http://localhost:45000/"), + ); +}); diff --git a/apps/web/src/components/chat/ThreadServersPanel.tsx b/apps/web/src/components/chat/ThreadServersPanel.tsx index 5f6f11636e806..e71a6be549a42 100644 --- a/apps/web/src/components/chat/ThreadServersPanel.tsx +++ b/apps/web/src/components/chat/ThreadServersPanel.tsx @@ -106,19 +106,20 @@ function ThreadServersList(props: ThreadServersPanelProps) { event.preventDefault(); // This machine's browser reaches another environment's loopback only through a forward. // Starting a forward runs the probe; only a confirmed local environment opens directly. - const url = - forwardable && locality !== "local" - ? await forwardPort(props.environmentId, server.port).then( - (forward) => forwardedUrl(forward, server.url), - (error: unknown) => { - reportFailure(gt("Could not forward port {port}", { port: server.port }), error); - return null; - }, - ) - : resolveExternalServerUrl(props.environmentId, server.url); + const forwarding = forwardable && locality !== "local"; + const url = forwarding + ? await forwardPort(props.environmentId, server.port).then( + (forward) => forwardedUrl(forward, server.url), + (error: unknown) => { + reportFailure(gt("Could not forward port {port}", { port: server.port }), error); + return null; + }, + ) + : resolveExternalServerUrl(props.environmentId, server.url); if (url === null) return; // Without a forward, a remote environment's localhost would open this machine's instead. if ( + !forwarding && locality !== "local" && tunnelsEnvironmentLoopback(environment?.entry.target) && isLoopbackHost(new URL(url).hostname) From 370b1fde77bec0c38c950e36663ae383b2562dcf Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 08:24:45 -0800 Subject: [PATCH 026/139] fix(server): a no-op fetch on Windows no longer re-resolves the base branch (#40388) --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 6 ++++++ apps/server/src/vcs/GitVcsDriverCore.ts | 18 ++++++++++++++---- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index e90043e69304b..27f4d4eceec59 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -967,8 +967,14 @@ it.effect("resolves a branch's base once while its refs and branch config are un }); assert.deepStrictEqual(reused.sources, withUntracked.sources); yield* (yield* FileSystem.FileSystem).remove(`${cwd}/untracked.txt`); + yield* driver.statusDetailsLocal(cwd); spawnedArgs.length = 0; + // Git for Windows' no-op `fetch --dry-run` touches a refs directory without moving a ref. + NodeFS.utimesSync(`${cwd}/.git/refs/heads`, 1_893_456_000, 1_893_456_000); + yield* driver.statusDetailsLocal(cwd); + assert.equal(lookups(), 0); + yield* git(cwd, ["config", "branch.feature/x.t3-merge-base-ref", "refs/heads/main"]); yield* driver.statusDetailsLocal(cwd); assert.equal(lookups(), 1); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 50e620514aa37..35105aeea90e4 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -2429,8 +2429,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }); // The effective config listing covers included, global, system and worktree config. Git writes - // packed-refs by rename and each loose ref by a rename in its directory, so those stats change - // whenever a ref could. Cost: one git process, plus a stat and listing per refs directory. + // packed-refs and each loose ref by rename, so their stats change whenever a ref could. Directory + // stats are left out: Git for Windows' no-op fetch touches refs/remotes/. + // Cost: one git process, a listing per refs directory and a stat per loose ref. const readBaseBranchInputsStamp = Effect.fn("GitVcsDriverCore.readBaseBranchInputsStamp")( function* (cwd: string, gitCommonDir: string) { const effectiveConfig = yield* executeGit( @@ -2463,16 +2464,25 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* path.join(gitCommonDir, "refs", "heads"), path.join(gitCommonDir, "refs", "remotes"), ]; + const looseRefs: Array = []; for (let index = 0; index < directories.length; index++) { const directory = directories[index]!; - tokens.push(`${directory}=${yield* statToken(directory)}`); const entries = yield* fileSystem .readDirectoryEntries(directory) .pipe(Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed([]))); for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) { - if (entry.type === "Directory") directories.push(path.join(directory, entry.name)); + const entryPath = path.join(directory, entry.name); + if (entry.type === "Directory") directories.push(entryPath); + else looseRefs.push(entryPath); } } + tokens.push( + ...(yield* Effect.forEach( + looseRefs, + (ref) => Effect.map(statToken(ref), (token) => `${ref}=${token}`), + { concurrency: 16 }, + )), + ); tokens.push(configHash); return tokens.join("\0"); }, From efea1aabe7a5657f5c78f71c12dd49f375886a78 Mon Sep 17 00:00:00 2001 From: Stevu <68607600+Abaans@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:32:02 +0500 Subject: [PATCH 027/139] fix(web): CSV preview rows keep their height during horizontal scroll (#40381) Co-authored-by: Abaan Co-authored-by: Julius Marminge --- .../AttachmentFilePreview.browser.test.tsx | 108 +++++- .../components/files/VirtualTablePreview.tsx | 340 +++++++++++++++++- 2 files changed, 430 insertions(+), 18 deletions(-) diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx index 16654ba72023c..add8d7368e2ab 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx @@ -72,7 +72,7 @@ vi.mock(import("./office/WordDocument"), async () => { }; }); -import { getClientSettings } from "~/hooks/useSettings"; +import { __setClientSettingsForTests, getClientSettings } from "~/hooks/useSettings"; import { AttachmentFilePreview } from "./AttachmentFilePreview"; import LargeTextViewer from "./LargeTextViewer"; import VirtualTablePreview from "./VirtualTablePreview"; @@ -840,6 +840,112 @@ describe("large text preview recovery", () => { expect(screen.container.textContent).toContain("C19"); }); + it("keeps row height and vertical position stable across horizontal scroll, fresh row arrays, resize, and typography changes", async () => { + const columns = 35; + const header = Array.from({ length: columns }, (_, i) => `Col ${i}`); + const forcedEightLines = Array.from({ length: 8 }, (_, i) => `L${i + 1}`).join("\n"); + const wrappedTwelveWords = Array.from({ length: 12 }, (_, i) => `segment${i + 1}`).join(" "); + const makeRows = () => [ + header, + ...Array.from({ length: 24 }, (_, rowIndex) => + Array.from({ length: columns }, (_, columnIndex) => { + if (rowIndex === 0) { + if (columnIndex >= 10 && columnIndex < 28) return forcedEightLines; + if (columnIndex === 34) return wrappedTwelveWords; + } + if (columnIndex === 33 && rowIndex % 3 === 1) return forcedEightLines; + // Wide lowercase glyphs that wrap without spaces or newlines. + if (rowIndex === 2 && columnIndex === 34) return "m".repeat(11); + return `r${rowIndex + 1}-c${columnIndex}`; + }), + ), + ]; + const view = (width: number) => ( +
    + (page === 0 ? makeRows() : undefined)} + /> +
    + ); + const previousSettings = getClientSettings(); + const previousRootFontSize = document.documentElement.style.fontSize; + try { + await using screen = await render(view(420)); + const horizontal = () => screen.container.querySelector('[role="table"]')!.parentElement!; + const vertical = () => screen.container.querySelector('[tabindex="0"]')!; + const row = (index: number) => + screen.container.querySelector(`[data-preview-row="${index}"]`)!; + + await vi.waitFor(() => { + expect(row(1)).not.toBeNull(); + expect(row(1).getBoundingClientRect().height).toBeGreaterThan(150); + }); + + const initialRow1Height = row(1).getBoundingClientRect().height; + const initialRow2Height = row(2).getBoundingClientRect().height; + const initialRow3Height = row(3).getBoundingClientRect().height; + const initialRow4Top = row(4).getBoundingClientRect().top; + + // Scroll to the far right where the word-wrapped column 34 mounts after 18 newline cells. + await act(() => { + horizontal().scrollLeft = horizontal().scrollWidth; + horizontal().dispatchEvent(new Event("scroll", { bubbles: true })); + }); + await vi.waitFor(() => expect(screen.container.textContent).toContain("segment12")); + + expect(Math.abs(row(1).getBoundingClientRect().height - initialRow1Height)).toBeLessThan(1); + expect(Math.abs(row(2).getBoundingClientRect().height - initialRow2Height)).toBeLessThan(1); + expect(row(3).getBoundingClientRect().height).toBeGreaterThan(40); + expect(Math.abs(row(3).getBoundingClientRect().height - initialRow3Height)).toBeLessThan(1); + expect(Math.abs(row(4).getBoundingClientRect().top - initialRow4Top)).toBeLessThan(1); + + // Scroll vertically into the table, then sweep horizontally back to the left edge. + await act(() => { + vertical().scrollTop = 120; + vertical().dispatchEvent(new Event("scroll", { bubbles: true })); + }); + await vi.waitFor(() => expect(row(5)).not.toBeNull()); + const scrolledRow5Top = row(5).getBoundingClientRect().top; + const scrolledRow5Height = row(5).getBoundingClientRect().height; + + await act(() => { + horizontal().scrollLeft = 0; + horizontal().dispatchEvent(new Event("scroll", { bubbles: true })); + }); + await vi.waitFor(() => expect(screen.container.textContent).toContain("r6-c0")); + + expect(Math.abs(row(5).getBoundingClientRect().height - scrolledRow5Height)).toBeLessThan(1); + expect(Math.abs(row(5).getBoundingClientRect().top - scrolledRow5Top)).toBeLessThan(1); + + // Widening the container widens each uniform column, reducing wrapped line count. + await screen.rerender(view(1600)); + await vi.waitFor(() => + expect(row(1).getBoundingClientRect().height).toBeLessThan(initialRow1Height), + ); + const widenedRow1Height = row(1).getBoundingClientRect().height; + + // Typography changes invalidate cached minimums even at the same container width. + await act(() => { + document.documentElement.style.fontSize = "20px"; + __setClientSettingsForTests({ + ...previousSettings, + fontSizeInterface: previousSettings.fontSizeInterface + 4, + }); + }); + await vi.waitFor(() => + expect(row(1).getBoundingClientRect().height).toBeGreaterThan(widenedRow1Height), + ); + } finally { + document.documentElement.style.fontSize = previousRootFontSize; + __setClientSettingsForTests(previousSettings); + } + }); + it("reveals and highlights requested source lines again for a new request", async () => { const view = (line: number, request: number, loaded = true) => (
    diff --git a/apps/web/src/components/files/VirtualTablePreview.tsx b/apps/web/src/components/files/VirtualTablePreview.tsx index 5154153807df1..229a6efb87329 100644 --- a/apps/web/src/components/files/VirtualTablePreview.tsx +++ b/apps/web/src/components/files/VirtualTablePreview.tsx @@ -1,5 +1,6 @@ /* oxlint-disable react/no-array-index-key -- Positions identify source rows and columns. */ import { useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from "react"; +import { useClientSettings } from "~/hooks/useSettings"; import { observeResize } from "~/lib/observeResize"; import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip"; import { PREVIEW_PAGE_ROWS } from "./largeTextProtocol"; @@ -72,6 +73,7 @@ export default function VirtualTablePreview(props: { ); const offset = (column: number) => offsets[column]!; const tableWidth = props.source ? "100%" : Math.max(width, offset(props.columns) + rowHeader); + const hasHorizontalOverflow = !props.source && offset(props.columns) + rowHeader > width; return (
    | undefined; rowHeader: number; firstColumn: number; viewportHeight: number; @@ -197,6 +201,7 @@ function RowPage( const row = rows?.[local]; const index = start + local; if (props.header && index === 0) return null; + const rowMinHeight = !props.source && row ? props.rowHeights?.get(index) : undefined; return (
    [0], "page">) { +function ScaledRows( + props: Omit[0], "page" | "rowHeights"> & { + hasHorizontalOverflow: boolean; + }, +) { const ref = useRef(null); const contentRef = useRef(null); + const rowProbeRef = useRef(null); + const rowHeightCacheRef = useRef<{ + key: string; + entries: Map; + }>({ key: "", entries: new Map() }); + const [rowHeights, setRowHeights] = useState<{ + key: string; + heights: ReadonlyMap; + }>({ key: "", heights: new Map() }); + const [, setRowMeasureTick] = useState(0); + const typographyKey = useClientSettings( + (settings) => `${settings.fontFamilySans}:${settings.fontSizeInterface}`, + ); const [layout, setLayout] = useState({ offset: 0, height: 0, rowHeight: 29 }); const [top, setTop] = useState(0); const handledReveal = useRef(null); @@ -347,6 +370,87 @@ function ScaledRows(props: Omit[0], "page">) { }, []); const page = Math.floor(first / PREVIEW_PAGE_ROWS); const visibleEnd = (first % PREVIEW_PAGE_ROWS) + Math.ceil(position.height / 29) + 1; + const sizesKey = `${props.sizes.join(",")}|${typographyKey}`; + const pageCount = Math.min( + Math.ceil(visibleEnd / PREVIEW_PAGE_ROWS), + Math.ceil(props.count / PREVIEW_PAGE_ROWS) - page, + ); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Measure mounted rows across all columns before paint so horizontal column virtualization keeps row heights and vertical scroll position stable. + useLayoutEffect(() => { + const probe = rowProbeRef.current; + if (!props.hasHorizontalOverflow || !probe) return; + const probeStyle = getComputedStyle(probe); + const cacheKey = `${sizesKey}|${probeStyle.font}`; + if (rowHeightCacheRef.current.key !== cacheKey) { + rowHeightCacheRef.current = { key: cacheKey, entries: new Map() }; + } + const cache = rowHeightCacheRef.current.entries; + const mountedIndices: number[] = []; + const uncached: Array<{ index: number; row: readonly string[] }> = []; + for (let pageOffset = 0; pageOffset < pageCount; pageOffset++) { + const currentPage = page + pageOffset; + const rows = props.getRows(currentPage); + if (!rows) continue; + const start = currentPage * PREVIEW_PAGE_ROWS; + const limit = visibleEnd - pageOffset * PREVIEW_PAGE_ROWS; + const count = Math.min(PREVIEW_PAGE_ROWS, props.count - start, limit); + for (let local = 0; local < count; local++) { + const index = start + local; + if (props.header && index === 0) continue; + const row = rows[local]; + if (!row) continue; + mountedIndices.push(index); + const existing = cache.get(index); + if (existing && (existing.row === row || sameRowCells(existing.row, row))) { + existing.row = row; + } else { + uncached.push({ index, row }); + } + } + } + let hasRemainingUncached = false; + if (uncached.length > 0) { + const fontSize = Number.parseFloat(probeStyle.fontSize) || 12; + const lineHeight = Number.parseFloat(probeStyle.lineHeight) || fontSize * 1.333; + const { measured, remaining } = measureRowsFullHeight( + probe, + uncached, + props.columns, + props.sizes, + fontSize, + lineHeight, + MAX_SYNC_SCAN_CHARS, + ); + hasRemainingUncached = remaining; + for (const [index, entry] of measured) cache.set(index, entry); + if (cache.size > MAX_CACHED_ROW_HEIGHTS) { + const keep = new Set(mountedIndices); + for (const key of cache.keys()) { + if (cache.size <= MAX_CACHED_ROW_HEIGHTS) break; + if (!keep.has(key)) cache.delete(key); + } + } + } + const next = new Map(); + for (const index of mountedIndices) { + const height = cache.get(index)?.height; + if (height && height > BASE_ROW_HEIGHT) next.set(index, height); + } + setRowHeights((old) => + old.key === cacheKey && sameRowHeightMap(old.heights, next) + ? old + : { key: cacheKey, heights: next }, + ); + if (hasRemainingUncached) { + const frameId = requestAnimationFrame(() => setRowMeasureTick((tick) => tick + 1)); + return () => cancelAnimationFrame(frameId); + } + return undefined; + }); + const activeRowHeights = + props.hasHorizontalOverflow && rowHeights.key.startsWith(`${sizesKey}|`) + ? rowHeights.heights + : undefined; // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Measure mounted row offsets and observe content resizes to position the virtual rows against the scroll track. useLayoutEffect(() => { if (atStart) return; @@ -462,6 +566,13 @@ function ScaledRows(props: Omit[0], "page">) { onScroll={(event) => setTop(event.currentTarget.scrollTop)} >
    + {!props.source ? ( +
    ); } +const BASE_ROW_HEIGHT = 29; +const CELL_HORIZONTAL_INSET = 25; +const CELL_VERTICAL_INSET = 13; +const MAX_MEASURED_CELLS_PER_ROW = 16; +// Wider than any common glyph, so estimates never undercount lines. +const MAX_GLYPH_WIDTH_EM = 1.35; +const MAX_CACHED_ROW_HEIGHTS = 512; +const MAX_SYNC_SCAN_CHARS = 128_000; +const PROBE_CELL_CLASS_NAME = + "box-border border-r border-b border-transparent px-3 py-1.5 whitespace-pre-wrap break-words tabular-nums"; + +interface CachedRowHeight { + row: readonly string[]; + height: number; +} + +interface RowCellCandidate { + readonly column: number; + readonly text: string; + readonly upperLines: number; +} + +/** Conservative greedy word-wrap upper bound on rendered lines without native text shaping. */ +function estimateUpperLines(text: string, innerWidth: number, fontSize: number): number { + const length = text.length; + let lines = 1; + let lineWidth = 0; + let wordWidth = 0; + for (let index = 0; index < length; index++) { + const code = text.charCodeAt(index); + if (code === 10 || code === 13) { + if (code === 13 && index + 1 < length && text.charCodeAt(index + 1) === 10) index++; + if (wordWidth > 0) { + if (lineWidth > 0 && lineWidth + wordWidth > innerWidth) lines++; + wordWidth = 0; + } + lines++; + lineWidth = 0; + continue; + } + if (code === 32 || code === 9) { + const spaceWidth = (code === 9 ? 4.5 : 0.38) * fontSize; + if (wordWidth > 0) { + if (lineWidth > 0 && lineWidth + wordWidth > innerWidth) { + lines++; + lineWidth = wordWidth; + } else { + lineWidth += wordWidth; + } + wordWidth = 0; + } + lineWidth += spaceWidth; + if (lineWidth > innerWidth) { + lines++; + lineWidth = 0; + } + continue; + } + const charWidth = MAX_GLYPH_WIDTH_EM * fontSize; + wordWidth += charWidth; + if (wordWidth > innerWidth) { + if (lineWidth > 0) { + lines++; + lineWidth = 0; + } + lines++; + wordWidth = charWidth; + } + } + if (wordWidth > 0 && lineWidth > 0 && lineWidth + wordWidth > innerWidth) lines++; + return lines; +} + +function collectRowHeightCandidates( + row: readonly string[], + columns: number, + sizes: readonly number[], + fontSize: number, +): { candidates: RowCellCandidate[]; scannedChars: number } { + const candidates: RowCellCandidate[] = []; + const limit = Math.min(columns, row.length); + const maxGlyphWidth = fontSize * MAX_GLYPH_WIDTH_EM; + let scannedChars = 0; + for (let column = 0; column < limit; column++) { + const text = row[column]; + if (!text) continue; + const width = sizes[column]; + if (!width) continue; + const innerWidth = Math.max(1, width - CELL_HORIZONTAL_INSET); + const hasControlWhitespace = text.includes("\n") || text.includes("\r") || text.includes("\t"); + if (!hasControlWhitespace && text.length * maxGlyphWidth <= innerWidth) continue; + scannedChars += text.length; + const upperLines = estimateUpperLines(text, innerWidth, fontSize); + if (!hasControlWhitespace && upperLines <= 1) continue; + candidates.push({ column, text, upperLines }); + } + if (candidates.length > MAX_MEASURED_CELLS_PER_ROW) { + candidates.sort((left, right) => right.upperLines - left.upperLines); + } + return { candidates, scannedChars }; +} + +function measureProbeEntries( + probe: HTMLElement, + entries: ReadonlyArray<{ index: number; column: number; text: string }>, + sizes: readonly number[], + results: Map, +): void { + if (entries.length === 0) return; + const fragment = document.createDocumentFragment(); + const nodes: Array<{ index: number; node: HTMLDivElement }> = []; + for (const entry of entries) { + const node = document.createElement("div"); + node.className = PROBE_CELL_CLASS_NAME; + node.style.width = `${sizes[entry.column]}px`; + node.textContent = entry.text; + fragment.append(node); + nodes.push({ index: entry.index, node }); + } + probe.replaceChildren(fragment); + for (const { index, node } of nodes) { + const height = node.getBoundingClientRect().height; + const current = results.get(index); + if (current && height > current.height) current.height = height; + } + probe.replaceChildren(); +} + +function measureRowsFullHeight( + probe: HTMLElement, + rows: ReadonlyArray<{ index: number; row: readonly string[] }>, + columns: number, + sizes: readonly number[], + fontSize: number, + lineHeight: number, + maxScanChars: number, +): { measured: Map; remaining: boolean } { + const measured = new Map(); + const firstPassEntries: Array<{ index: number; column: number; text: string }> = []; + const overflowRows: Array<{ index: number; candidates: RowCellCandidate[] }> = []; + let scannedChars = 0; + let remaining = false; + for (const { index, row } of rows) { + if (measured.size > 0 && scannedChars >= maxScanChars) { + remaining = true; + break; + } + const collected = collectRowHeightCandidates(row, columns, sizes, fontSize); + scannedChars += collected.scannedChars; + measured.set(index, { row, height: BASE_ROW_HEIGHT }); + const firstBatchCount = Math.min(collected.candidates.length, MAX_MEASURED_CELLS_PER_ROW); + for (let candidateIndex = 0; candidateIndex < firstBatchCount; candidateIndex++) { + const candidate = collected.candidates[candidateIndex]!; + firstPassEntries.push({ index, column: candidate.column, text: candidate.text }); + } + if (collected.candidates.length > MAX_MEASURED_CELLS_PER_ROW) { + overflowRows.push({ index, candidates: collected.candidates }); + } + } + measureProbeEntries(probe, firstPassEntries, sizes, measured); + if (overflowRows.length > 0) { + const secondPassEntries: Array<{ index: number; column: number; text: string }> = []; + for (const { index, candidates } of overflowRows) { + const bestHeight = measured.get(index)?.height ?? BASE_ROW_HEIGHT; + const measuredLines = Math.max( + 1, + Math.floor((bestHeight - CELL_VERTICAL_INSET + 0.5) / lineHeight), + ); + for ( + let candidateIndex = MAX_MEASURED_CELLS_PER_ROW; + candidateIndex < candidates.length; + candidateIndex++ + ) { + const candidate = candidates[candidateIndex]!; + if (candidate.upperLines <= measuredLines) break; + secondPassEntries.push({ index, column: candidate.column, text: candidate.text }); + } + } + measureProbeEntries(probe, secondPassEntries, sizes, measured); + } + return { measured, remaining }; +} + +function sameRowCells(left: readonly string[], right: readonly string[]): boolean { + if (left.length !== right.length) return false; + for (let index = 0; index < left.length; index++) { + if (left[index] !== right[index]) return false; + } + return true; +} + +function sameRowHeightMap( + left: ReadonlyMap, + right: ReadonlyMap, +): boolean { + if (left.size !== right.size) return false; + for (const [index, height] of left) { + if (right.get(index) !== height) return false; + } + return true; +} + function columnLabel(index: number): string { let label = ""; for (let value = index + 1; value > 0; value = Math.floor((value - 1) / 26)) From 1458a4241939b9ba17f78dc219205d1a3fc64557 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 08:53:18 -0800 Subject: [PATCH 028/139] fix(server): transcript cleanup failures tell the user why (#40424) --- apps/server/src/auth/http.ts | 13 ++++- apps/server/src/speech/http.test.ts | 60 +++++++++++++++++++++++ apps/server/src/speech/http.ts | 13 ++++- apps/web/src/speech/voiceInputSession.ts | 14 ++++-- packages/contracts/src/environmentHttp.ts | 2 + 5 files changed, 95 insertions(+), 7 deletions(-) diff --git a/apps/server/src/auth/http.ts b/apps/server/src/auth/http.ts index 86d7330887376..39952a385ba87 100644 --- a/apps/server/src/auth/http.ts +++ b/apps/server/src/auth/http.ts @@ -191,7 +191,11 @@ export const authenticateMediaRequest = export const failEnvironmentInternal = /* Request instrumentation already owns the span; keep this helper in that context. */ - Effect.fnUntraced(function* (reason: EnvironmentInternalErrorReason, error?: unknown) { + Effect.fnUntraced(function* ( + reason: EnvironmentInternalErrorReason, + error?: unknown, + detail?: string, + ) { const traceId = yield* currentEnvironmentTraceId; if (error !== undefined) { yield* Effect.logError("environment api operation failed", { @@ -200,7 +204,12 @@ export const failEnvironmentInternal = cause: error, }); } - return yield* new EnvironmentInternalError({ code: "internal_error", reason, traceId }); + return yield* new EnvironmentInternalError({ + code: "internal_error", + reason, + traceId, + ...(detail === undefined ? {} : { detail }), + }); }); // Plaintext LAN servers still need the cookie; TLS arrives through a proxy that sets X-Forwarded-Proto. diff --git a/apps/server/src/speech/http.test.ts b/apps/server/src/speech/http.test.ts index 770a1b5c94ca5..8bbf2d81bc065 100644 --- a/apps/server/src/speech/http.test.ts +++ b/apps/server/src/speech/http.test.ts @@ -12,6 +12,7 @@ import { CloudSpeechError, DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS, SPEECH_MAX_OPTIONS_BYTES, + TextGenerationError, DEFAULT_SERVER_SETTINGS, EnvironmentAuthenticatedAuth, EnvironmentAuthenticatedPrincipal, @@ -377,3 +378,62 @@ effectIt.effect.each([ }); }), ); + +effectIt.effect("tells the client why transcript cleanup failed", () => + Effect.gen(function* () { + const detail = "OpenCode returned invalid structured output."; + const failingCleanup = Layer.mergeAll( + dependencies, + Layer.succeed( + TextGeneration.TextGeneration, + TextGeneration.TextGeneration.of({ + generateCommitMessage: () => Effect.die("not used"), + generatePrContent: () => Effect.die("not used"), + generateBranchName: () => Effect.die("not used"), + generateThreadTitle: () => Effect.die("not used"), + generateReviewGuide: () => Effect.die("not used"), + generateTranscriptionPostProcessing: () => + Effect.fail( + new TextGenerationError({ + operation: "generateTranscriptionPostProcessing", + detail, + }), + ), + }), + ), + ); + const { handler, dispose } = HttpRouter.toWebHandler( + HttpApiBuilder.layer(HttpApi.make("environment").add(EnvironmentVoiceHttpApi)).pipe( + Layer.provide(speechHttpApiLayer), + Layer.provide(principal(AuthOrchestrationOperateScope)), + Layer.provide(Layer.mock(SpeechService.SpeechService)({})), + Layer.provide(failingCleanup), + // Cleanup makes a real temporary directory; the HTTP services only carry a no-op filesystem. + Layer.provide(NodeServices.layer), + Layer.provide(HttpServer.layerServices), + ), + { disableLogger: true }, + ); + yield* Effect.addFinalizer(() => Effect.promise(dispose)); + const context = yield* Layer.build(Layer.mergeAll(failingCleanup, NodeServices.layer)); + const response = yield* Effect.promise(() => + handler( + new Request("http://localhost/api/voice/post-process", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + options: { + speechCustomWords: [], + speechPostProcessingPrompt: { mode: "default", customInstructions: "" }, + }, + transcript: "um so hello world", + draft: { text: "", selection: { start: 0, end: 0 } }, + }), + }), + context, + ), + ); + expect(response.ok).toBe(false); + expect(yield* Effect.promise(() => response.text())).toContain(detail); + }), +); diff --git a/apps/server/src/speech/http.ts b/apps/server/src/speech/http.ts index 834118b332b05..09c3d4dc23faa 100644 --- a/apps/server/src/speech/http.ts +++ b/apps/server/src/speech/http.ts @@ -9,11 +9,13 @@ import { type EnvironmentSpeechModels, EnvironmentVoiceBodyLimit, SPEECH_MAX_OPTIONS_BYTES, + TextGenerationError, } from "@t3tools/contracts"; import * as ByteSize from "effect/ByteSize"; 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 HttpServerRequest from "effect/http/HttpServerRequest"; import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; @@ -29,6 +31,7 @@ import * as SpeechService from "./SpeechService.ts"; const MAX_TRANSCRIBE_BODY_BYTES = SpeechService.MAX_SPEECH_BYTES + SPEECH_MAX_OPTIONS_BYTES + 4; const parseAudio = Option.liftThrowable(decodeSpeechPcmRequest); +const isTextGenerationError = Schema.is(TextGenerationError); const bodyLimit = Layer.succeed(EnvironmentVoiceBodyLimit, (effect) => Effect.gen(function* () { @@ -233,7 +236,15 @@ export const speechHttpApiLayer = HttpApiBuilder.group( yield* guard(args.endpoint.name); return yield* postProcessing .process(args.payload) - .pipe(Effect.catch((error) => failEnvironmentInternal("internal_error", error))); + .pipe( + Effect.catch((error) => + failEnvironmentInternal( + "internal_error", + error, + isTextGenerationError(error.cause) ? error.cause.detail : undefined, + ), + ), + ); }), ); }), diff --git a/apps/web/src/speech/voiceInputSession.ts b/apps/web/src/speech/voiceInputSession.ts index f048b5653973c..f21285457aa15 100644 --- a/apps/web/src/speech/voiceInputSession.ts +++ b/apps/web/src/speech/voiceInputSession.ts @@ -19,8 +19,9 @@ import type { SpeechStreamText, SpeechTranscriptionOptions, } from "@t3tools/contracts"; -import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts"; +import { DEFAULT_CLIENT_SETTINGS, EnvironmentInternalError } from "@t3tools/contracts"; import { resolveSpeechVocabulary } from "@t3tools/shared/speech"; +import * as Schema from "effect/Schema"; import { useEffect, useSyncExternalStore } from "react"; import { toastManager } from "../components/ui/toast"; @@ -34,6 +35,8 @@ import { bindAudioGrant, readCleanupGrant } from "./voiceConsent"; import { msg } from "gt-react"; import { m } from "../i18n/messages"; +const isEnvironmentInternalError = Schema.is(EnvironmentInternalError); + export const IDLE_VOICE_STATE: VoiceInputState = { phase: "idle", error: null, errorAction: null }; type DraftInput = { @@ -220,12 +223,15 @@ export class VoiceInputSession { releaseRecording: async () => platform.cancelRecording(), deleteRecording: platform.deleteRecording, postProcess, - onPostProcessingError: () => + onPostProcessingError: (error) => { + const added = m(msg("The original transcript was added.")); + const detail = isEnvironmentInternalError(error) ? error.detail : undefined; toastManager.add({ type: "warning", title: m(msg("Transcript cleanup failed")), - description: m(msg("The original transcript was added.")), - }), + description: detail ? `${detail} ${added}` : added, + }); + }, readDraft: (): VoiceDraftSnapshot | null => { const target = this.target; const draft = target?.readDraft(); diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.ts index adda38304a6b2..9b5cd9a0cb5c1 100644 --- a/packages/contracts/src/environmentHttp.ts +++ b/packages/contracts/src/environmentHttp.ts @@ -257,6 +257,8 @@ export class EnvironmentInternalError extends Schema.TaggedError Date: Sat, 21 Nov 2026 08:59:16 -0800 Subject: [PATCH 029/139] fix(acp): Devin's terminal commands run under Git Bash on Windows, not cmd.exe (#40418) --- .../src/server/clientTerminals.ts | 26 +++++++++++++++++-- packages/shared/src/shell.test.ts | 19 ++++++++++++++ packages/shared/src/shell.ts | 14 ++++++++++ 3 files changed, 57 insertions(+), 2 deletions(-) diff --git a/packages/provider-acp/src/server/clientTerminals.ts b/packages/provider-acp/src/server/clientTerminals.ts index 2fda24d4e4fa5..c8371fb7020e8 100644 --- a/packages/provider-acp/src/server/clientTerminals.ts +++ b/packages/provider-acp/src/server/clientTerminals.ts @@ -13,6 +13,7 @@ import * as EffectAcpErrors from "effect-acp/errors"; import type * as EffectAcpSchema from "effect-acp/compat"; import * as NodeBuffer from "node:buffer"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { gitForWindowsBash, SpawnExecutableResolution } from "@t3tools/shared/shell"; const MAX_LIVE_TERMINALS = 16; const MAX_UNRELEASED_TERMINALS = 64; @@ -137,15 +138,27 @@ export interface AcpClientTerminalsOptions { function acpTerminalCommand(input: { readonly request: EffectAcpSchema.CreateTerminalRequest; readonly shellCommands?: boolean | undefined; + /** Windows only: the shell source runs here instead of Node's cmd.exe. */ + readonly posixShell: string | undefined; readonly defaultCwd: string; readonly environment: NodeJS.ProcessEnv; readonly forceKillAfter: Duration.Input; }) { - return ChildProcess.make(input.request.command, input.request.args ?? [], { + const options = { cwd: input.request.cwd ?? input.defaultCwd, env: input.environment, - shell: input.shellCommands === true && (input.request.args?.length ?? 0) === 0, forceKillAfter: input.forceKillAfter, + }; + const isShellSource = input.shellCommands === true && (input.request.args?.length ?? 0) === 0; + if (isShellSource && input.posixShell !== undefined) { + // Native tools write in the console code page and output is decoded as UTF-8. The spawner + // hides the window, so each terminal has its own console and the change stays inside it. + const source = `chcp.com 65001 >/dev/null 2>&1\n${input.request.command}`; + return ChildProcess.make(input.posixShell, ["-c", source], options); + } + return ChildProcess.make(input.request.command, input.request.args ?? [], { + ...options, + shell: isShellSource, }); } @@ -170,6 +183,7 @@ export const makeAcpClientTerminals = Effect.fn("makeAcpClientTerminals")(functi const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const forceKillAfter = options.forceKillAfter ?? "5 seconds"; const isWindows = yield* HostProcess.isWindows; + const resolveExecutable = yield* SpawnExecutableResolution; const creationPermit = yield* Semaphore.make(1); const terminals = new Map(); let nextTerminalNumber = 1; @@ -246,6 +260,13 @@ export const makeAcpClientTerminals = Effect.fn("makeAcpClientTerminals")(functi Object.entries(sessionEnvironment ?? {}), (request.env ?? []).map((variable) => [variable.name, variable.value] as const), ]); + // Agents that send shell source write bash; Node's shell on Windows is cmd.exe. + const gitExecutable = + isWindows && options.shellCommands === true + ? resolveExecutable("git", "win32", environment) + : undefined; + const posixShell = + gitExecutable === undefined ? undefined : gitForWindowsBash(gitExecutable); const terminalScope = yield* Scope.make(); const child = yield* restore( spawner @@ -253,6 +274,7 @@ export const makeAcpClientTerminals = Effect.fn("makeAcpClientTerminals")(functi acpTerminalCommand({ request, shellCommands: options.shellCommands, + posixShell, defaultCwd: options.defaultCwd, environment, forceKillAfter, diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index bae0701fa21c0..32ed8d2b46116 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -23,6 +23,7 @@ import { CommandAvailability, CommandResolutionCache, type CommandAvailabilityChecker, + gitForWindowsBash, isCommandAvailable, listLoginShellCandidates, mergePathEntries, @@ -758,6 +759,24 @@ describe("preferGitForWindowsBinary", () => { }); }); +describe("gitForWindowsBash", () => { + const bash = "C:\\Program Files\\Git\\bin\\bash.exe"; + const isBash = (filePath: string) => filePath === bash; + + it.each([ + "C:\\Program Files\\Git\\cmd\\git.exe", + "C:\\Program Files\\Git\\bin\\git.exe", + "C:\\Program Files\\Git\\mingw64\\bin\\git.exe", + ])("finds Git Bash from %s", (git) => { + expect(gitForWindowsBash(git, isBash)).toBe(bash); + }); + + it("finds nothing without a Git for Windows bash", () => { + expect(gitForWindowsBash("C:\\Users\\me\\scoop\\shims\\git.exe", isBash)).toBeUndefined(); + expect(gitForWindowsBash("C:\\Program Files\\Git\\cmd\\gitk.exe", () => true)).toBeUndefined(); + }); +}); + // Byte for byte what `npm install -g opencode-ai` writes as `opencode.cmd`. const NPM_OPENCODE_SHIM = [ "@ECHO off", diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index 0246a507f978d..05a1d5b14bd79 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -813,6 +813,20 @@ export function preferGitForWindowsBinary( return executable; } +/** Git for Windows' bash beside a git.exe from its install, never WSL's System32 bash.exe. */ +export function gitForWindowsBash( + gitExecutable: string, + isFile: (filePath: string) => boolean = isFileSync, +): string | undefined { + const path = NodePath.win32; + if (path.basename(gitExecutable).toLowerCase() !== "git.exe") return undefined; + // git.exe lives in \cmd, \bin, or \\bin. + const launcherRoot = path.dirname(path.dirname(gitExecutable)); + return [launcherRoot, path.dirname(launcherRoot)] + .map((root) => path.join(root, "bin", "bash.exe")) + .find(isFile); +} + // npm cmd-shim format for native executables. const NPM_EXECUTABLE_SHIM_PREFIX = [ "@ECHO off", From d4d54658f919d1b643566f579f6fabe109927628 Mon Sep 17 00:00:00 2001 From: Sungyong Cho Date: Sat, 21 Nov 2026 17:59:27 +0100 Subject: [PATCH 030/139] fix(server): a delegated task still reaches its parent when its first update fails (#37225) Co-authored-by: Julius Marminge --- .../DelegatedChildTerminalRetry.test.ts | 328 ++++++++++++++++++ .../src/orchestration-v2/Orchestrator.ts | 137 +++++--- 2 files changed, 421 insertions(+), 44 deletions(-) create mode 100644 apps/server/src/orchestration-v2/DelegatedChildTerminalRetry.test.ts diff --git a/apps/server/src/orchestration-v2/DelegatedChildTerminalRetry.test.ts b/apps/server/src/orchestration-v2/DelegatedChildTerminalRetry.test.ts new file mode 100644 index 0000000000000..b9c20c02b5afe --- /dev/null +++ b/apps/server/src/orchestration-v2/DelegatedChildTerminalRetry.test.ts @@ -0,0 +1,328 @@ +import { assert, it } from "@effect/vitest"; +import { + CommandId, + MessageId, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ProviderThreadId, + ProviderTurnId, + ThreadId, + type OrchestrationV2DomainEvent, +} from "@t3tools/contracts"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; + +import { ClaudeProviderCapabilitiesV2 } from "./Adapters/ClaudeAdapterV2.ts"; +import * as EffectWorker from "./EffectWorker.ts"; +import * as Orchestrator from "./Orchestrator.ts"; +import * as ProjectionStore from "./ProjectionStore.ts"; +import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; +import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts"; + +const driver = ProviderDriverKind.make("claudeAgent"); +const instanceId = ProviderInstanceId.make("claudeAgent"); +const modelSelection = { instanceId, model: "claude-test" }; +const parentThreadId = ThreadId.make("thread:delegated-terminal-retry-parent"); +const childError = "Failed to initialize session: No space left on device"; + +type ParentRead = { + readonly store: ProjectionStore.ProjectionStoreV2["Service"]; + readonly threadId: ThreadId; + readonly fields: ReadonlyArray; + readonly filter: Parameters[2]; +}; + +// The parent hears of a child only from the reaction to the child's terminal run. +// The injected failure stands in for a storage error, such as a full disk, and fails once. +const runDelegation = (input: { + readonly name: string; + readonly parentEndsFirst: boolean; + readonly failRead?: (read: ParentRead) => Effect.Effect; + readonly failChildRunMessage?: boolean; +}) => + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace(input.name); + let armed = false; + const turns: Array<{ + readonly turn: ProviderAdapter.ProviderAdapterV2TurnInput; + readonly events: Queue.Queue; + }> = []; + const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = { + instanceId, + driver, + getCapabilities: () => Effect.succeed(ClaudeProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }), + openSession: (session) => + Effect.gen(function* () { + const now = yield* DateTime.now; + const events = yield* Queue.unbounded(); + return { + instanceId, + driver, + providerSessionId: session.providerSessionId, + providerSession: { + id: session.providerSessionId, + driver, + providerInstanceId: instanceId, + status: "ready", + cwd, + model: modelSelection.model, + capabilities: ClaudeProviderCapabilitiesV2, + createdAt: now, + updatedAt: now, + lastError: null, + }, + events: Stream.fromQueue(events), + ensureThread: ({ threadId }) => + IdAllocator.isDelegatedTaskThread(threadId) + ? Effect.fail( + new ProviderAdapter.ProviderAdapterEnsureThreadError({ + driver, + threadId, + cause: new Error(childError), + }), + ) + : Effect.succeed({ + id: ProviderThreadId.make(`provider-thread:${threadId}`), + driver, + providerInstanceId: instanceId, + providerSessionId: session.providerSessionId, + appThreadId: threadId, + ownerNodeId: null, + nativeThreadRef: { driver, nativeId: `native:${threadId}`, strength: "strong" }, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: null, + lastRunOrdinal: null, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + }), + resumeThread: ({ providerThread }) => Effect.succeed(providerThread), + startTurn: (turn) => + Effect.gen(function* () { + turns.push({ turn, events }); + yield* Queue.offer(events, { + type: "provider_turn.updated", + driver, + providerTurn: { + id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`), + providerThreadId: turn.providerThread.id, + nodeId: turn.rootNodeId, + runAttemptId: turn.attemptId, + nativeTurnRef: null, + ordinal: turn.providerTurnOrdinal, + status: "running", + startedAt: now, + completedAt: null, + }, + }); + }), + steerTurn: () => Effect.die("unused"), + interruptTurn: () => Effect.void, + respondToRuntimeRequest: () => Effect.die("unused"), + readThreadSnapshot: () => Effect.die("unused"), + rollbackThread: () => Effect.die("unused"), + forkThread: () => Effect.die("unused"), + }; + }), + }; + const layerTest = ProviderReplayHarness.layerWithRegistry( + { name: input.name }, + ProviderAdapterRegistry.layerSingle(adapter), + { + runEffectWorker: false, + runContinuationWorker: true, + wrapProjectionStore: (store) => ({ + ...store, + getThreadRecords: (threadId, fields, filter) => + Effect.gen(function* () { + if ( + armed && + input.failRead !== undefined && + (yield* input.failRead({ store, threadId, fields, filter })) + ) { + armed = false; + return yield* new ProjectionStore.ProjectionStoreReadError({ threadId }); + } + return yield* store.getThreadRecords(threadId, fields, filter); + }), + getRunMessage: (threadId, runId) => { + if ( + !armed || + !input.failChildRunMessage || + !IdAllocator.isDelegatedTaskThread(threadId) + ) { + return store.getRunMessage(threadId, runId); + } + armed = false; + return Effect.fail(new ProjectionStore.ProjectionStoreReadError({ threadId })); + }, + }), + }, + ); + + return yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) => + orchestrator.streamDomainEvents.pipe( + Stream.filter(predicate), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create-parent"), + threadId: parentThreadId, + projectId: ProjectId.make("project:delegated-terminal-retry"), + title: "Parent", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + createdBy: "user", + creationSource: "web", + }); + const parentRunning = yield* watch( + (event) => event.type === "provider-turn.updated" && event.payload.status === "running", + ); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("start-parent"), + threadId: parentThreadId, + messageId: MessageId.make("message:start-parent"), + text: "Delegate a review", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + yield* worker.drain(); + yield* Fiber.join(parentRunning); + const parentRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs[0]!; + + yield* orchestrator.dispatch({ + type: "delegated_task.request", + commandId: CommandId.make("delegate"), + parentThreadId, + parentRunId: parentRun.id, + parentNodeId: parentRun.rootNodeId!, + task: "Review the change", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + completionWake: "always", + createdBy: "agent", + creationSource: "mcp", + }); + const task = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents[0]!; + const childThreadId = task.childThreadId!; + + const endParentTurn = Effect.gen(function* () { + const parentTurn = (yield* orchestrator.getThreadProjection(parentThreadId)) + .providerTurns[0]!; + const parentEvents = turns.find((entry) => entry.turn.threadId === parentThreadId)!.events; + const now = yield* DateTime.now; + yield* Queue.offer(parentEvents, { + type: "provider_turn.updated", + driver, + providerTurn: { ...parentTurn, status: "completed", completedAt: now }, + }); + yield* Queue.offer(parentEvents, { + type: "turn.terminal", + driver, + providerThreadId: parentTurn.providerThreadId, + providerTurnId: parentTurn.id, + runOrdinal: parentRun.ordinal, + status: "completed", + failure: null, + threadDisposition: "reusable", + }); + }); + + if (input.parentEndsFirst) { + const parentEnded = yield* watch( + (event) => + event.type === "run.updated" && + event.payload.id === parentRun.id && + event.payload.status !== "running", + ); + yield* endParentTurn; + yield* Fiber.join(parentEnded); + } + + armed = true; + const childFailed = yield* watch( + (event) => + event.type === "run.updated" && + event.payload.threadId === childThreadId && + event.payload.status === "failed", + ); + for (let attempt = 0; attempt < 5; attempt++) { + yield* worker.drain(); + yield* TestClock.adjust("1 second"); + } + yield* Fiber.join(childFailed); + + if (!input.parentEndsFirst) yield* endParentTurn; + for (let attempt = 0; attempt < 5; attempt++) { + yield* worker.drain(); + yield* TestClock.adjust("30 seconds"); + } + + assert.isFalse(armed, "the injected read failed once"); + const parent = yield* orchestrator.getThreadProjection(parentThreadId); + const settled = parent.subagents.find((row) => row.id === task.id); + assert.equal(settled?.status, "failed"); + assert.equal(settled?.result, childError); + assert.isTrue( + parent.messages.some( + (message) => message.delegatedCompletion?.taskIds.includes(task.id) === true, + ), + "the parent is woken with the child's failure", + ); + }).pipe(Effect.provide(layerTest)); + }); + +it.effect("a delegated child that fails to start reaches its parent after a failed read", () => + runDelegation({ + name: "delegated-child-terminal-retry", + parentEndsFirst: false, + // Only finalizing the parent's task reads its rows by child thread. + failRead: ({ filter }) => Effect.succeed(filter?.subagentChildThreadIds !== undefined), + }), +); + +it.effect("an idle parent is woken when its wake fails after the task settles", () => + runDelegation({ + name: "delegated-child-terminal-wake-retry", + parentEndsFirst: true, + failRead: ({ store, threadId, fields, filter }) => + threadId !== parentThreadId || fields.join() !== "runs" || filter?.runIds === undefined + ? Effect.succeed(false) + : store.getThreadRecords(parentThreadId, ["subagents"]).pipe( + Effect.map((records) => records.subagents.some((task) => task.result !== null)), + Effect.orDie, + ), + }), +); + +it.effect("a delegated child reaches its parent after its own delivery read fails", () => + runDelegation({ + name: "delegated-child-terminal-delivery-read", + parentEndsFirst: false, + failChildRunMessage: true, + }), +); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 24bd270e28945..dd69750a43496 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -101,14 +101,17 @@ import { } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; 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 Exit from "effect/Exit"; +import * as FiberSet from "effect/FiberSet"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as Result from "effect/Result"; +import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; @@ -979,6 +982,14 @@ function delegatedCompletionWakeDetail( .join("\n\n"); } +// Startup recovery settles whatever is still missed after this window. +const parentTaskSyncRetry = Schedule.exponential("1 second").pipe( + Schedule.modifyDelay(({ duration }) => + Effect.succeed(Duration.min(duration, Duration.seconds(30))), + ), + Schedule.upTo({ duration: Duration.hours(1) }), +); + function isTerminalDelegatedTaskStatus(status: OrchestrationV2Subagent["status"]): boolean { return ( status === "completed" || @@ -2142,6 +2153,23 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } }); + const offerChildTaskDeliveries = + /* This helper runs for individual orchestration events; the enclosing operation owns the span. */ + Effect.fnUntraced(function* (parentThreadId: ThreadId, childThreadId: ThreadId) { + // A task's wake lives on the run that requested it; the parent's other wakes are not this child's. + const { subagents } = yield* projectionStore.getThreadRecords(parentThreadId, ["subagents"], { + subagentChildThreadIds: [childThreadId], + }); + const parentRunIds = new Set( + subagents.flatMap((task) => + task.childThreadId === childThreadId && task.runId !== null ? [task.runId] : [], + ), + ); + for (const parentRunId of parentRunIds) { + yield* offerDelegatedCompletionDelivery(parentThreadId, parentRunId); + } + }); + /** Marks a wake the provider received delivered and reserves the next one for pending siblings. */ const acceptDelegatedCompletionDelivery = Effect.fn( "Orchestrator.acceptDelegatedCompletionDelivery", @@ -16462,6 +16490,57 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : dispatch; }); + const parentTaskSyncRetries = yield* FiberSet.make(); + const syncDelegatedParentTask = Effect.fn("Orchestrator.syncDelegatedParentTask")(function* ( + childThreadId: ThreadId, + options: { readonly syncRunId: RunId | undefined; readonly retry: boolean }, + ) { + const parentThreadId = yield* appOwnedSubagentParentThreadId(childThreadId); + if (parentThreadId === undefined) return; + const finalize = finalizeAppOwnedSubagent( + childThreadId, + options.syncRunId === undefined ? undefined : { syncRunId: options.syncRunId }, + ); + yield* threadDispatch.withLock( + parentThreadId, + // A failed attempt may have committed the result before offering its wake. + options.retry + ? offerChildTaskDeliveries(parentThreadId, childThreadId).pipe(Effect.andThen(finalize)) + : finalize, + ); + }); + // Only these reactions tell a parent about its child before a restart; a dropped one leaves its task running. + const updateDelegatedParentTask = Effect.fn("Orchestrator.updateDelegatedParentTask")(function* ( + childThreadId: ThreadId, + syncRunId?: RunId, + ) { + const context = { + threadId: childThreadId, + ...(syncRunId === undefined ? {} : { runId: syncRunId }), + }; + yield* syncDelegatedParentTask(childThreadId, { syncRunId, retry: false }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Retrying a delegated task update for its parent", { + ...context, + cause, + }).pipe( + Effect.andThen( + syncDelegatedParentTask(childThreadId, { syncRunId, retry: true }).pipe( + Effect.retry({ schedule: parentTaskSyncRetry }), + Effect.delay("1 second"), + Effect.catchCause((cause) => + Effect.logWarning("Failed to update a delegated task for its parent", { + ...context, + cause, + }), + ), + FiberSet.run(parentTaskSyncRetries), + ), + ), + ), + ), + ); + }); const handleRunUpdate = Effect.fn("Orchestrator.handleRunUpdate")( function* (stored: OrchestrationV2StoredEvent) { if (stored.event.type !== "run.updated") return; @@ -16483,10 +16562,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); } - yield* threadDispatch.withLock( - threadId, - finalizeDelegatedCompletionDelivery(threadId, run.id), - ); + yield* threadDispatch + .withLock(threadId, finalizeDelegatedCompletionDelivery(threadId, run.id)) + .pipe( + Effect.catchCause((cause) => + Effect.logWarning("Failed to settle a delegated completion delivery", { + threadId, + runId: run.id, + cause, + }), + ), + ); yield* threadDispatch .withLock( threadId, @@ -16515,13 +16601,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); } - const parentThreadId = yield* appOwnedSubagentParentThreadId(threadId); - if (parentThreadId !== undefined) { - yield* threadDispatch.withLock( - parentThreadId, - finalizeAppOwnedSubagent(threadId, { syncRunId: run.id }), - ); - } + yield* updateDelegatedParentTask(threadId, run.id); }, (effect, stored) => effect.pipe( @@ -16656,23 +16736,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ).pipe( Stream.filter(settlesChildWork), Stream.runForEach((stored) => - threadReactions.run( - stored.event.threadId, - Effect.gen(function* () { - const childThreadId = stored.event.threadId; - const parentThreadId = yield* appOwnedSubagentParentThreadId(childThreadId); - if (parentThreadId === undefined) return; - yield* threadDispatch.withLock(parentThreadId, finalizeAppOwnedSubagent(childThreadId)); - }).pipe( - Effect.catchCause((cause) => - Effect.logWarning("Failed to finalize a delegated child after its work settled", { - threadId: stored.event.threadId, - sequence: stored.sequence, - cause, - }), - ), - ), - ), + threadReactions.run(stored.event.threadId, updateDelegatedParentTask(stored.event.threadId)), ), Effect.forkScoped, ); @@ -16855,22 +16919,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio return; yield* threadDispatch.withLock( parentThreadId, - Effect.gen(function* () { - // A task's wake lives on the run that requested it; the parent's other wakes are not this child's. - const { subagents } = yield* projectionStore.getThreadRecords( - parentThreadId, - ["subagents"], - { subagentChildThreadIds: [threadId] }, - ); - const parentRunIds = new Set( - subagents.flatMap((task) => - task.childThreadId === threadId && task.runId !== null ? [task.runId] : [], - ), - ); - for (const parentRunId of parentRunIds) { - yield* offerDelegatedCompletionDelivery(parentThreadId, parentRunId); - } - }).pipe( + offerChildTaskDeliveries(parentThreadId, threadId).pipe( Effect.andThen( finalizeAppOwnedSubagent( threadId, From 3b15a01fca4bb76328e592e7706d3a888d16cf18 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 09:15:39 -0800 Subject: [PATCH 031/139] fix(server): worktree threads start when a checkout hook already linked a nested clone (#40419) --- apps/server/src/workspace/TaskFolders.test.ts | 58 +++++++++++++++++++ apps/server/src/workspace/TaskFolders.ts | 55 ++++++++++++------ 2 files changed, 95 insertions(+), 18 deletions(-) diff --git a/apps/server/src/workspace/TaskFolders.test.ts b/apps/server/src/workspace/TaskFolders.test.ts index 37fd360cf8b24..c156f190e0049 100644 --- a/apps/server/src/workspace/TaskFolders.test.ts +++ b/apps/server/src/workspace/TaskFolders.test.ts @@ -347,6 +347,64 @@ it.live("puts a clone the project ignores inside the project's worktree", () => ), ); +it.live("creates the task folder when the project's checkout hook already linked a clone", () => + withState((state) => + Effect.gen(function* () { + const { fileSystem, path, tmp, run, repository } = yield* fixture; + const project = yield* repository("p"); + yield* fileSystem.writeFileString(path.join(project, ".gitignore"), "vendor/\n"); + yield* run(project, "add", "."); + yield* run(project, "commit", "-m", "ignore vendor"); + const lib = yield* repository("p/vendor/lib"); + // Like many projects with vendored clones, a new worktree links them back to the checkout. + const hooks = path.join(tmp, "hooks"); + yield* fileSystem.makeDirectory(hooks); + yield* fileSystem.writeFileString( + path.join(hooks, "post-checkout"), + `#!/bin/sh\nmkdir -p vendor && ln -s "${lib}" vendor/lib\n`, + { mode: 0o755 }, + ); + yield* run(project, "config", "core.hooksPath", hooks); + state.workspaceRoot = project; + state.trackedFolders = tracked(lib); + + const created = yield* create("feature").pipe(Effect.exit); + + assert.isTrue(Exit.isSuccess(created), String(Exit.isFailure(created) && created.cause)); + }), + ), +); + +it.live("leaves a hook's link to an empty folder alone", () => + withState((state) => + Effect.gen(function* () { + const { fileSystem, path, tmp, run, repository } = yield* fixture; + const project = yield* repository("p"); + yield* fileSystem.writeFileString(path.join(project, ".gitignore"), "vendor/\n"); + yield* run(project, "add", "."); + yield* run(project, "commit", "-m", "ignore vendor"); + const lib = yield* repository("p/vendor/lib"); + const target = path.join(tmp, "empty"); + yield* fileSystem.makeDirectory(target); + const hooks = path.join(tmp, "hooks"); + yield* fileSystem.makeDirectory(hooks); + yield* fileSystem.writeFileString( + path.join(hooks, "post-checkout"), + `#!/bin/sh\nmkdir -p vendor && ln -s "${target}" vendor/lib\n`, + { mode: 0o755 }, + ); + yield* run(project, "config", "core.hooksPath", hooks); + state.workspaceRoot = project; + state.trackedFolders = tracked(lib); + + const created = yield* create("feature").pipe(Effect.exit); + + assert.isTrue(Exit.isSuccess(created), String(Exit.isFailure(created) && created.cause)); + assert.deepStrictEqual(yield* fileSystem.readDirectory(target), []); + }), + ), +); + it.live("treats a project folder inside a larger repository as plain", () => withState((state) => Effect.gen(function* () { diff --git a/apps/server/src/workspace/TaskFolders.ts b/apps/server/src/workspace/TaskFolders.ts index 3dd74d90d2d80..4911065118ce4 100644 --- a/apps/server/src/workspace/TaskFolders.ts +++ b/apps/server/src/workspace/TaskFolders.ts @@ -243,6 +243,16 @@ const make = Effect.gen(function* () { const exists = (target: string) => fileSystem.exists(target).pipe(Effect.orElseSucceed(() => false)); const isRepository = (folder: string) => exists(path.join(folder, ".git")); + const occupied = Effect.fnUntraced(function* (target: string) { + if (!(yield* exists(target))) return false; + const isDirectory = (yield* fileSystem.stat(target).pipe(Effect.option)).pipe( + Option.exists((info) => info.type === "Directory"), + ); + if (!isDirectory) return true; + return ( + (yield* fileSystem.readDirectory(target).pipe(Effect.orElseSucceed(() => [""]))).length > 0 + ); + }); const trackedFolders = (project: { readonly workspaceRoot: string; readonly trackedFolders: ReadonlyArray; @@ -855,6 +865,13 @@ const make = Effect.gen(function* () { baseBranch: string | undefined, ) { const worktreePath = mapped(taskFolder, repository.path); + // The project's own checkout (a post-checkout hook, say) already provided this repository. + // A link counts even to an empty folder: Git would write the worktree through it. + if ( + Option.isSome(yield* fileSystem.readLink(worktreePath).pipe(Effect.option)) || + (yield* occupied(worktreePath)) + ) + return null; yield* fileSystem.makeDirectory(path.dirname(worktreePath), { recursive: true }); const start = yield* repositoryStart(repository.path, startFromOrigin, baseBranch); yield* git.createWorktree({ @@ -1006,6 +1023,9 @@ const make = Effect.gen(function* () { } else { yield* linkFolder(taskPlan.projectRoot, empty.projectPath, taskPlan.trackedRepositories); } + let finished = 0; + // Whatever the project put at a skipped path also stands for the repositories inside it. + const skipped: string[] = []; // A repository inside another waits for the one that holds it. const levels = Map.groupBy( taskPlan.repositories, @@ -1021,21 +1041,28 @@ const make = Effect.gen(function* () { const exits = yield* Effect.forEach( levels.get(level)!, (repository) => - createRepositoryWorktree( - empty, - repository, - branch, - input.startFromOrigin, - input.baseBranch, + (skipped.some((outer) => isWithinRoot(path, repository.path, outer)) + ? Effect.succeed(null) + : createRepositoryWorktree( + empty, + repository, + branch, + input.startFromOrigin, + input.baseBranch, + ) ).pipe( Effect.tap((worktree) => Effect.suspend(() => { - created.push(worktree.repository); - repositoriesStartedFromOrigin ||= worktree.fromOrigin; + finished += 1; + if (worktree === null) skipped.push(repository.path); + else { + created.push(worktree.repository); + repositoriesStartedFromOrigin ||= worktree.fromOrigin; + } return ( input.onRepository?.({ name: repository.name, - done: created.length, + done: finished, total: taskPlan.repositories.length, }) ?? Effect.void ); @@ -1189,15 +1216,7 @@ const make = Effect.gen(function* () { path.relative(taskFolder.projectRoot, repositoryPath), ).pipe(Effect.mapError(fail("add-repository", "Could not prepare the folder"))) : true; - const occupied = - !opened || - ((yield* exists(worktreePath)) && - ((yield* fileSystem.stat(worktreePath).pipe(Effect.option)).pipe( - Option.exists((info) => info.type !== "Directory"), - ) || - (yield* fileSystem.readDirectory(worktreePath).pipe(Effect.orElseSucceed(() => [""]))) - .length > 0)); - if (occupied) + if (!opened || (yield* occupied(worktreePath))) return yield* refuse(`${worktreePath} already holds files, so no worktree can go there.`); // The link the worktree took the place of comes back when the worktree does not stay. const relink = wasLinked From 630f2e14440faa2a6a177cea1f280dae0a3ed9a8 Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Sat, 21 Nov 2026 19:31:32 +0200 Subject: [PATCH 032/139] fix(desktop): a forward moves off a port this machine serves on IPv6 loopback (#40423) Co-authored-by: Julius Marminge --- .../src/preview/LoopbackTunnel.test.ts | 76 +++++++++++-------- apps/desktop/src/preview/LoopbackTunnel.ts | 12 ++- 2 files changed, 56 insertions(+), 32 deletions(-) diff --git a/apps/desktop/src/preview/LoopbackTunnel.test.ts b/apps/desktop/src/preview/LoopbackTunnel.test.ts index fe83817c0d5e8..5b3cf08c9f728 100644 --- a/apps/desktop/src/preview/LoopbackTunnel.test.ts +++ b/apps/desktop/src/preview/LoopbackTunnel.test.ts @@ -2,6 +2,7 @@ import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem"; import * as NodeWS from "@effect/platform-node/NodeWS"; import { EnvironmentId } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as NetService from "@t3tools/shared/Net"; import { expect, it } from "@effect/vitest"; import * as NodeNet from "node:net"; import * as Context from "effect/Context"; @@ -30,20 +31,23 @@ const closeServer = (server: NodeNet.Server | NodeWS.WebSocketServer) => ); /** A local listener that must never see a connection: the reviewer's own localhost server. */ -const listenDecoy = Effect.acquireRelease( - Effect.promise( - () => - new Promise<{ server: NodeNet.Server; connections: () => number }>((resolve) => { - let connections = 0; - const server = NodeNet.createServer((socket) => { - connections++; - socket.destroy(); - }); - server.listen(0, "127.0.0.1", () => resolve({ server, connections: () => connections })); - }), - ), - ({ server }) => closeServer(server), -); +const listenDecoyOn = (host: string) => + Effect.acquireRelease( + Effect.promise( + () => + new Promise<{ server: NodeNet.Server; connections: () => number }>((resolve, reject) => { + let connections = 0; + const server = NodeNet.createServer((socket) => { + connections++; + socket.destroy(); + }); + server.once("error", reject); + server.listen(0, host, () => resolve({ server, connections: () => connections })); + }), + ), + ({ server }) => closeServer(server), + ); +const listenDecoy = listenDecoyOn("127.0.0.1"); /** Stands in for the environment's /api/preview/tunnel: echoes each frame behind a 0xee byte. */ const listenEndpoint = Effect.acquireRelease( @@ -101,6 +105,7 @@ const makeTunnel = ( }), NodeFileSystem.layer, SecureRandom.layerWebCrypto, + NetService.layer, host ?? Layer.empty, ), ), @@ -357,24 +362,33 @@ it.effect("forwards a port over the tunnel on the same local port until stopped" }), ); -it.effect("moves a forward to a free port when its own is taken here", () => - Effect.gen(function* () { - const decoy = yield* listenDecoy; - const endpoint = yield* listenEndpoint; - const remotePort = addressPort(decoy.server); - const tunnel = yield* makeTunnel( - `ws://127.0.0.1:${addressPort(endpoint.server)}/api/preview/tunnel`, - ); - const forward = yield* tunnel.forward({ - environmentId: EnvironmentId.make("remote"), - remotePort, - }); - expect(forward.localPort).not.toBe(remotePort); +const hasIpv6Loopback = await new Promise((resolve) => { + const probe = NodeNet.createServer(); + probe.once("error", () => resolve(false)); + probe.listen(0, "::1", () => probe.close(() => resolve(true))); +}); - expect(yield* exchange(forward.localPort, Uint8Array.of(6))).toEqual([0xee, 6]); - expect(endpoint.requests.at(-1)).toBe(`/api/preview/tunnel?port=${remotePort}`); - expect(decoy.connections()).toBe(0); - }), +// Vite listens on ::1 by default on macOS, and Node's default listen is ::. +it.effect.each(hasIpv6Loopback ? ["127.0.0.1", "::1", "::"] : ["127.0.0.1"])( + "moves a forward to a free port when its own is taken here on %s", + (host) => + Effect.gen(function* () { + const decoy = yield* listenDecoyOn(host); + const endpoint = yield* listenEndpoint; + const remotePort = addressPort(decoy.server); + const tunnel = yield* makeTunnel( + `ws://127.0.0.1:${addressPort(endpoint.server)}/api/preview/tunnel`, + ); + const forward = yield* tunnel.forward({ + environmentId: EnvironmentId.make("remote"), + remotePort, + }); + expect(forward.localPort).not.toBe(remotePort); + + expect(yield* exchange(forward.localPort, Uint8Array.of(6))).toEqual([0xee, 6]); + expect(endpoint.requests.at(-1)).toBe(`/api/preview/tunnel?port=${remotePort}`); + expect(decoy.connections()).toBe(0); + }), ); /** An environment on this machine: each tunnel connection dials the requested local port. */ diff --git a/apps/desktop/src/preview/LoopbackTunnel.ts b/apps/desktop/src/preview/LoopbackTunnel.ts index 1e06993fa54f0..f84dc3e5c38a2 100644 --- a/apps/desktop/src/preview/LoopbackTunnel.ts +++ b/apps/desktop/src/preview/LoopbackTunnel.ts @@ -11,6 +11,7 @@ import type { EnvironmentId, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as NetService from "@t3tools/shared/Net"; import type { NonEmptyReadonlyArray } from "effect/Array"; import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; @@ -314,6 +315,7 @@ const make = Effect.gen(function* () { const platform = yield* HostProcess.Platform; const userId = yield* HostProcess.UserId; const random = yield* SecureRandom.SecureRandom; + const net = yield* NetService.NetService; const listenerScope = yield* Effect.scope; const routing = yield* Semaphore.make(1); const forwarding = yield* Semaphore.make(1); @@ -503,6 +505,13 @@ const make = Effect.gen(function* () { }); }); + // `localhost` also names ::1, and a server here on ::1 or :: does not collide with the + // forward's 127.0.0.1 bind, so it would keep answering `localhost` in place of the forward. + const servedOverIpv6 = (port: number) => + Effect.forEach(["::1", "::"], (host) => net.canListenOnHost(port, host)).pipe( + Effect.map((free) => free.includes(false)), + ); + const forward: LoopbackTunnel["Service"]["forward"] = Effect.fn("LoopbackTunnel.forward")( function* ({ environmentId, remotePort }) { const existing = forwarded.get(forwardKey(environmentId, remotePort)); @@ -513,7 +522,8 @@ const make = Effect.gen(function* () { const scope = yield* Scope.fork(listenerScope); const bind = (port: number) => NodeSocketServer.make({ port, host: "127.0.0.1" }).pipe(Scope.provide(scope)); - const server = yield* bind(remotePort).pipe( + const preferredPort = (yield* servedOverIpv6(remotePort)) ? 0 : remotePort; + const server = yield* bind(preferredPort).pipe( // Taken here, or privileged: any free port still reaches the environment's. Effect.catch(() => bind(0)), Effect.onError(() => Scope.close(scope, Exit.void)), From 8ee2a8a9a087da2fea9f176023961bd5bc08455f Mon Sep 17 00:00:00 2001 From: Michel Liao <107891771+Michel-Liao@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:44:01 -0500 Subject: [PATCH 033/139] fix(web): RTF previews no longer join text across section and column breaks (#40437) Co-authored-by: Julius Marminge --- .../components/files/FilePreviewPanel.test.ts | 21 +++++++++++++++++++ .../files/extendedDocumentPreview.ts | 5 ++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts index c02a74868fb0a..c1d49b1d26f8d 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.ts +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -248,6 +248,27 @@ Third}`; ); }); + it("starts a new line at rich text section and column breaks", () => { + const result = openRtf( + bytes( + String.raw`{\rtf1\ansi\sectd\cols2\pard North quota: 120\column South quota: 240\page East quota: 360\sect\sectd\pard West quota: 480\par}`, + ), + ); + if (result.type !== "document") throw new Error("Expected document"); + expect(result.pages.map((page) => page.html)).toEqual([ + "

    North quota: 120
    South quota: 240

    ", + "

    East quota: 360
    West quota: 480

    ", + ]); + const written = openRtf( + bytes(String.raw`{\rtf1\ansi First\par\sect\sectd Second\par\column Third\page\sect Fourth}`), + ); + if (written.type !== "document") throw new Error("Expected document"); + expect(written.pages.map((page) => page.html)).toEqual([ + "

    First
    Second
    Third

    ", + "

    Fourth

    ", + ]); + }); + it("decodes declared rich text code pages for raw bytes and escaped byte runs", () => { const input = new TextEncoder().encode( String.raw`{\rtf1\ansi\ansicpg1251 A \'c0\par\ansicpg932\'82\'a0}`, diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index 429e2fc56a4db..a450123089718 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -736,7 +736,10 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { (!hidden() && (word === "par" || word === "line")) ) html += "
    "; - else { + // Writers usually end the paragraph before these breaks; a second break would add a blank line. + else if (!hidden() && (word === "sect" || word === "column")) { + if (html && !html.endsWith("
    ")) html += "
    "; + } else { const character = RTF_CHARACTERS.get(word!); if (character) emit(character); } From e2035934a67d13aa76f5f61f52c4448b4c91a545 Mon Sep 17 00:00:00 2001 From: Michel Liao <107891771+Michel-Liao@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:44:47 -0500 Subject: [PATCH 034/139] fix(azure-devops): project-less pull request URLs can be pasted to check out (#40436) Co-authored-by: Julius Marminge --- .../src/shared/definition.test.ts | 12 ++++++++++++ .../src/shared/definition.ts | 2 +- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/packages/source-control-azure-devops/src/shared/definition.test.ts b/packages/source-control-azure-devops/src/shared/definition.test.ts index f18b627a874be..9234546a8a5a8 100644 --- a/packages/source-control-azure-devops/src/shared/definition.test.ts +++ b/packages/source-control-azure-devops/src/shared/definition.test.ts @@ -54,6 +54,18 @@ describe("Azure DevOps change request URLs", () => { } }); + it("takes a pull request URL that leaves the project out as a checkout reference", () => { + for (const url of [ + "https://dev.azure.com/acme/_git/web/pullrequest/17", + "https://acme.visualstudio.com/_git/web/pullrequest/17", + ]) { + expect(definition.isChangeRequestReference(url), url).toBe(true); + } + expect( + definition.isChangeRequestReference("https://dev.azure.com/_git/web/pullrequest/17"), + ).toBe(false); + }); + it.each([ ["ssh.dev.azure.com", "v3/org/project/web"], ["org.visualstudio.com", "defaultcollection/project/_git/web"], diff --git a/packages/source-control-azure-devops/src/shared/definition.ts b/packages/source-control-azure-devops/src/shared/definition.ts index 78f1a4df45a8d..a32ba471a7b48 100644 --- a/packages/source-control-azure-devops/src/shared/definition.ts +++ b/packages/source-control-azure-devops/src/shared/definition.ts @@ -21,7 +21,7 @@ const WORK_ITEM_PATH = /^\/([^/]+\/[^/]+)\/_workitems\/edit\/(\d+)(?:\/|$)/u; const LEGACY_WORK_ITEM_PATH = /^\/([^/]+)\/_workitems\/edit\/(\d+)(?:\/|$)/u; 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\/(?:DefaultCollection\/)?[^/\s]+)\/_git\/[^/\s]+\/pullrequest\/(\d+)(?:[/?#].*)?$/i; + /^https:\/\/(?:dev\.azure\.com\/[^/\s]+(?:\/[^/\s]+)?|[^/\s]+\.visualstudio\.com(?:\/DefaultCollection)?(?:\/[^/\s]+)?)\/_git\/[^/\s]+\/pullrequest\/(\d+)(?:[/?#].*)?$/i; // `ssh.dev.azure.com` is the default SSH clone host (git@ssh.dev.azure.com:v3/org/project/repo), // so any `*.dev.azure.com` subdomain is Azure. Legacy hosts stay under `.visualstudio.com`, From 28b413fe12ce3501b4fbc0903f81c4ec50af11ac Mon Sep 17 00:00:00 2001 From: Mukul Ashwath Ram Date: Sat, 21 Nov 2026 12:55:04 -0500 Subject: [PATCH 035/139] fix(server): queued messages no longer wait out every timed-out checkpoint in a shared folder (#40411) Co-authored-by: ExSidius <17144735+ExSidius@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../CheckpointCaptureService.test.ts | 2 + .../CheckpointCaptureService.ts | 3 + .../CheckpointService.test.ts | 151 ++++++++++++++++++ .../src/orchestration-v2/CheckpointService.ts | 105 ++++++++---- 4 files changed, 231 insertions(+), 30 deletions(-) diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts index af276de7ff276..aa85cd675dc1a 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts @@ -311,6 +311,7 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { ), ) : Layer.mock(CheckpointService.CheckpointServiceV2)({ + capturesSoFar: () => Effect.succeed(0), repositoryScopes: () => Effect.succeed([]), materializeBaselineCheckpoint: () => Effect.die( @@ -892,6 +893,7 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { Layer.mergeAll( IdAllocator.layer, Layer.mock(CheckpointService.CheckpointServiceV2)({ + capturesSoFar: () => Effect.succeed(0), repositoryScopes: () => Effect.succeed([]), materializeBaselineCheckpoint: () => Effect.die("baseline materialization must be skipped when ordinal 0 is ready"), diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts index 119b5420be343..3dadd8618ed03 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts @@ -135,6 +135,8 @@ export const layer: Layer.Layer< }; // Each scope is checked on its own, so a retried capture fills only what is missing. const captureRoot = Effect.gen(function* () { + // Materializing a baseline waits on the folder's lock before the capture does. + const capturesBeforeLock = yield* checkpoints.capturesSoFar(scope.cwd); const threadStartCheckpoint = baselineOrdinalWithinScope === 0 || isPreserved(0) ? null : yield* materializeBaseline(0); const baselineCheckpoint = isPreserved(baselineOrdinalWithinScope) @@ -148,6 +150,7 @@ export const layer: Layer.Layer< appRunOrdinal: run.ordinal, capturedAt, forceMissing: sideChat, + capturesBeforeLock, ...excluded(scope), }); return { threadStartCheckpoint, baselineCheckpoint, checkpoint }; diff --git a/apps/server/src/orchestration-v2/CheckpointService.test.ts b/apps/server/src/orchestration-v2/CheckpointService.test.ts index 8887d391da176..0433208167a73 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.test.ts @@ -21,6 +21,7 @@ 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 Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as TestClock from "effect/testing/TestClock"; @@ -550,6 +551,156 @@ it.effect("backs off only baseline retries after repeated workspace capture time }), ); +it.effect("skips post-turn captures that waited out another capture's timeout in the folder", () => + Effect.gen(function* () { + const scopeFor = (name: string): OrchestrationV2CheckpointScope => ({ + id: CheckpointScopeId.make(`checkpoint-scope:shared-folder:${name}`), + threadId: ThreadId.make(`thread:shared-folder:${name}`), + runId: RunId.make(`run:shared-folder:${name}:1`), + nodeId: NodeId.make(`node:shared-folder:${name}:1`), + parentScopeId: null, + providerThreadId: ProviderThreadId.make(`provider-thread:shared-folder:${name}`), + kind: "root_run", + ordinalWithinParent: 0, + advancesAppRunCount: true, + cwd: "/repo/shared", + createdAt: DateTime.makeUnsafe("2026-07-28T00:00:00.000Z"), + }); + const attempts = yield* Ref.make(0); + // Outcomes for upcoming attempts; an attempt with none scripted times out. + const script = yield* Ref.make>([]); + const started = yield* Queue.unbounded(); + const layerTest = CheckpointService.layer.pipe( + Layer.provide( + Layer.mergeAll( + IdAllocator.layer, + layerNoTrackedFolders, + Layer.mock(CheckpointStore.CheckpointStore)({ + isGitRepository: () => Effect.succeed(true), + hasCheckpointRef: () => Effect.succeed(false), + resolveCleanHead: () => Effect.succeed(null), + captureCheckpoint: ({ cwd }) => + Effect.gen(function* () { + yield* Ref.update(attempts, (count) => count + 1); + yield* Queue.offer(started, undefined); + yield* Effect.sleep("30 seconds"); + const [next = "timeout", ...rest] = yield* Ref.get(script); + yield* Ref.set(script, rest); + if (next === "ready") return; + return yield* new VcsProcessTimeoutError({ + operation: "GitVcsDriver.checkpoints.captureCheckpoint", + command: "git", + cwd, + timeoutMs: 30_000, + }); + }), + }), + ), + ), + Layer.provideMerge(NodeCrypto.layer), + ); + yield* Effect.gen(function* () { + const checkpoints = yield* CheckpointService.CheckpointServiceV2; + const captureTurn = (scope: OrchestrationV2CheckpointScope) => + checkpoints + .capture({ + scope, + ordinalWithinScope: 1, + runId: scope.runId!, + nodeId: scope.nodeId!, + appRunOrdinal: 1, + capturedAt: scope.createdAt, + }) + .pipe(Effect.forkChild); + // A baseline's short budget running out says nothing about a post-turn capture. + const baseline = yield* checkpoints + .captureBaseline({ scope: scopeFor("baseline"), ordinalWithinScope: 0 }) + .pipe(Effect.result, Effect.forkChild); + yield* Queue.take(started); + const afterBaseline = yield* captureTurn(scopeFor("after-baseline")); + yield* TestClock.adjust("5 seconds"); + yield* Fiber.join(baseline); + yield* Queue.take(started); + yield* TestClock.adjust("30 seconds"); + assert.strictEqual((yield* Fiber.join(afterBaseline)).status, "error"); + assert.strictEqual(yield* Ref.get(attempts), 2); + + const first = yield* captureTurn(scopeFor("first")); + yield* Queue.take(started); + // Other threads in the same folder finish their turns while the first capture hangs. + const waiting = [ + yield* captureTurn(scopeFor("second")), + yield* captureTurn(scopeFor("third")), + ]; + const repository = scopeFor("repository"); + const repositoryWaiting = yield* checkpoints + .captureRepository({ + scope: repository, + runId: repository.runId!, + nodeId: repository.nodeId!, + ordinalWithinScope: 1, + capturedAt: repository.createdAt, + baselineCapturedAt: repository.createdAt, + baselineRecorded: true, + }) + .pipe(Effect.forkChild); + // A thread's root capture first materializes its baseline, which waits on the lock too. + const root = scopeFor("root"); + const rootWaiting = yield* Effect.gen(function* () { + const capturesBeforeLock = yield* checkpoints.capturesSoFar(root.cwd); + yield* checkpoints.materializeBaselineCheckpoint({ + scope: root, + ordinalWithinScope: 0, + nodeId: root.nodeId!, + capturedAt: root.createdAt, + }); + return yield* checkpoints.capture({ + scope: root, + ordinalWithinScope: 1, + runId: root.runId!, + nodeId: root.nodeId!, + appRunOrdinal: 1, + capturedAt: root.createdAt, + capturesBeforeLock, + }); + }).pipe(Effect.forkChild); + yield* TestClock.adjust("30 seconds"); + assert.strictEqual((yield* Fiber.join(first)).status, "error"); + // Room for every waiter to probe, so the count below is what fails without the fix. + yield* TestClock.adjust("120 seconds"); + for (const fiber of waiting) { + assert.strictEqual((yield* Fiber.join(fiber)).status, "error"); + } + const repositoryCaptured = yield* Fiber.join(repositoryWaiting); + assert.strictEqual(Option.getOrThrow(repositoryCaptured).checkpoint.status, "error"); + assert.strictEqual((yield* Fiber.join(rootWaiting)).status, "error"); + assert.strictEqual(yield* Ref.get(attempts), 3, "each waiter spent its own full timeout"); + + // A capture that starts after the timeout still probes for recovery. + const later = yield* captureTurn(scopeFor("later")); + yield* TestClock.adjust("30 seconds"); + assert.strictEqual((yield* Fiber.join(later)).status, "error"); + assert.strictEqual(yield* Ref.get(attempts), 4); + + // A success ahead in the queue does not hide a timeout that follows it. + yield* Ref.set(script, ["ready", "timeout"]); + const recovered = yield* captureTurn(scopeFor("recovered")); + const relapsed = yield* captureTurn(scopeFor("relapsed")); + const queuedBehind = yield* captureTurn(scopeFor("queued-behind")); + yield* TestClock.adjust("90 seconds"); + assert.deepEqual( + [ + (yield* Fiber.join(recovered)).status, + (yield* Fiber.join(relapsed)).status, + (yield* Fiber.join(queuedBehind)).status, + ], + ["ready", "error", "error"], + ); + assert.strictEqual(yield* Ref.get(attempts), 6, "the waiter probed after a later timeout"); + }).pipe(Effect.provide(layerTest)); + }), +); + it.effect("keeps the pre-rewind snapshot of a folder a failed rewind could not put back", () => { const targets = ["first", "second"].map((name) => ({ scope: { id: CheckpointScopeId.make(`checkpoint-scope:rewind:${name}`), cwd: `/repo/${name}` }, diff --git a/apps/server/src/orchestration-v2/CheckpointService.ts b/apps/server/src/orchestration-v2/CheckpointService.ts index d8a3da1f0c8ca..079ac88211870 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.ts @@ -220,7 +220,11 @@ export interface CheckpointServiceV2Shape { readonly capturedAt: DateTime.Utc; readonly forceMissing?: boolean; readonly excludePaths?: ReadonlyArray; + /** `capturesSoFar` from before an earlier wait on the folder's lock, when there was one. */ + readonly capturesBeforeLock?: number; }) => Effect.Effect; + /** How many captures have finished in a folder, for a caller that waits on it before `capture`. */ + readonly capturesSoFar: (cwd: string) => Effect.Effect; /** * A tracked repository's checkpoint for a run, with the baseline before it unless that is * already recorded. None when the run left the repository as it found it, which costs one @@ -388,19 +392,43 @@ export const layer: Layer.Layer< capacity: 128, lookup: () => Effect.succeed(0), }); + // Unlike the streak, a success never rewinds the count, so a waiter can order outcomes. A + // baseline running out of its short budget is not a post-turn capture timing out. + const lastCaptures = new Map(); + const noteCapture = (cwd: string, timedOut: boolean) => + Effect.sync(() => { + lastCaptures.set(cwd, { count: (lastCaptures.get(cwd)?.count ?? 0) + 1, timedOut }); + }); + const capturesSoFar = (cwd: string) => lastCaptures.get(cwd)?.count ?? 0; + const withCaptureLock = Effect.fn("CheckpointService.withCaptureLock")(function* ( + cwd: string, + capturesBeforeLock: number | undefined, + effect: (capturesBeforeLock: number) => Effect.Effect, + ) { + return yield* withWorkspaceLock(cwd, effect(capturesBeforeLock ?? capturesSoFar(cwd))); + }); // Both callers hold the workspace lock; post-turn captures always probe for recovery. const captureWorkspaceCheckpoint = Effect.fn("CheckpointService.captureWorkspaceCheckpoint")( function* (input: CheckpointStore.CaptureCheckpointInput, baseline = false) { const capture = checkpointStore.captureCheckpoint(input); yield* (baseline ? capture.pipe(Effect.timeout(BASELINE_CAPTURE_BUDGET)) : capture).pipe( - Effect.tap(() => Cache.invalidate(captureTimeouts, input.cwd)), + Effect.tap(() => + Effect.andThen( + Cache.invalidate(captureTimeouts, input.cwd), + noteCapture(input.cwd, false), + ), + ), Effect.tapError((error) => error._tag === "VcsProcessTimeoutError" || error._tag === "TimeoutError" ? Effect.gen(function* () { const previous = yield* Cache.get(captureTimeouts, input.cwd); yield* Cache.set(captureTimeouts, input.cwd, previous + 1); + yield* noteCapture(input.cwd, !baseline); }) - : Cache.invalidate(captureTimeouts, input.cwd), + : Effect.andThen( + Cache.invalidate(captureTimeouts, input.cwd), + noteCapture(input.cwd, false), + ), ), ); }, @@ -590,8 +618,7 @@ export const layer: Layer.Layer< readonly cleanHead?: string; }, ) => - withWorkspaceLock( - input.scope.cwd, + withCaptureLock(input.scope.cwd, input.capturesBeforeLock, (capturesBeforeLock) => Effect.gen(function* () { const checkpointId = yield* checkpointIdForScopeOrdinal(idAllocator, { scopeId: input.scope.id, @@ -634,32 +661,47 @@ export const layer: Layer.Layer< }; } - const captureStatus = yield* ( - input.cleanHead === undefined - ? captureWorkspaceCheckpoint({ - cwd: input.scope.cwd, - checkpointRef, - ...(input.ordinalWithinScope > 0 ? { previousCheckpointRef } : {}), - ...(input.excludePaths === undefined ? {} : { excludePaths: input.excludePaths }), - }) - : checkpointStore.captureHeadCheckpoint({ - cwd: input.scope.cwd, - checkpointRef, - head: input.cleanHead, - }) - ).pipe( - Effect.as("ready" as const), - Effect.catchTags({ - VcsUnsupportedOperationError: () => Effect.succeed("missing" as const), - }), - Effect.catch((cause) => - Effect.logWarning("orchestration V2 checkpoint capture failed", { - scopeId: input.scope.id, - checkpointRef, - cause: String(cause), - }).pipe(Effect.as("error" as const)), - ), - ); + // Threads sharing a folder queue on its lock. One that waited out another's timeout + // would only time out again while its own queued messages wait behind it. + const lastCapture = lastCaptures.get(input.scope.cwd); + const timedOutWhileWaiting = + input.cleanHead === undefined && + lastCapture !== undefined && + lastCapture.timedOut && + lastCapture.count > capturesBeforeLock; + const captureStatus = timedOutWhileWaiting + ? yield* Effect.logWarning( + "orchestration V2 checkpoint capture skipped after a capture timed out in its folder", + { scopeId: input.scope.id, checkpointRef }, + ).pipe(Effect.as("error" as const)) + : yield* ( + input.cleanHead === undefined + ? captureWorkspaceCheckpoint({ + cwd: input.scope.cwd, + checkpointRef, + ...(input.ordinalWithinScope > 0 ? { previousCheckpointRef } : {}), + ...(input.excludePaths === undefined + ? {} + : { excludePaths: input.excludePaths }), + }) + : checkpointStore.captureHeadCheckpoint({ + cwd: input.scope.cwd, + checkpointRef, + head: input.cleanHead, + }) + ).pipe( + Effect.as("ready" as const), + Effect.catchTags({ + VcsUnsupportedOperationError: () => Effect.succeed("missing" as const), + }), + Effect.catch((cause) => + Effect.logWarning("orchestration V2 checkpoint capture failed", { + scopeId: input.scope.id, + checkpointRef, + cause: String(cause), + }).pipe(Effect.as("error" as const)), + ), + ); if (captureStatus !== "ready") { return { @@ -966,6 +1008,7 @@ export const layer: Layer.Layer< )(function* (input) { const { cwd, id } = input.scope; const baselineOrdinal = input.ordinalWithinScope - 1; + const capturesBeforeLock = capturesSoFar(cwd); const start = yield* withWorkspaceLock( cwd, Effect.gen(function* () { @@ -1023,6 +1066,7 @@ export const layer: Layer.Layer< ordinalWithinScope: input.ordinalWithinScope, appRunOrdinal: null, capturedAt: input.capturedAt, + capturesBeforeLock, ...(input.excludePaths === undefined ? {} : { excludePaths: input.excludePaths }), ...(start.cleanHead === null ? {} : { cleanHead: start.cleanHead }), }); @@ -1135,6 +1179,7 @@ export const layer: Layer.Layer< captureBaseline, materializeBaselineCheckpoint, capture, + capturesSoFar: (cwd: string) => Effect.sync(() => capturesSoFar(cwd)), captureRepository, restore, deleteStaleRefs, From ac0032742b52b8cac5bbec416cb308df0dee913f Mon Sep 17 00:00:00 2001 From: Leon Date: Sat, 21 Nov 2026 19:03:57 +0100 Subject: [PATCH 036/139] fix(shell): non-ASCII Windows PATH entries survive the PowerShell environment probe (#37154) Co-authored-by: lowlyleon <183293296+lowlyleon@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../src/shell/DesktopShellEnvironment.test.ts | 9 +++++++++ .../src/shell/DesktopShellEnvironment.ts | 2 ++ packages/shared/src/shell.test.ts | 18 ++++++++++++++++++ packages/shared/src/shell.ts | 2 ++ 4 files changed, 31 insertions(+) diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts index 621c5c64178d2..dedd202acb1ee 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts @@ -983,11 +983,13 @@ describe("DesktopShellEnvironment", () => { USERPROFILE: "C:\\Users\\testuser", }; + const scripts: Array = []; const prepared = yield* runShellEnvironment({ env, platform: "win32", handler: (command) => { if (command._tag !== "StandardCommand") return ""; + scripts.push(String(command.args.at(-1))); const loadProfile = !command.args.includes("-NoProfile"); return loadProfile ? envOutput({ @@ -1021,6 +1023,13 @@ describe("DesktopShellEnvironment", () => { env.FNM_MULTISHELL_PATH, "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123", ); + assert.isNotEmpty(scripts); + for (const script of scripts) { + assert.include( + script, + "[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)", + ); + } }), ); diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.ts index 3c90d7bfcaff1..f9ab0d6c3a054 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts @@ -235,6 +235,8 @@ const logShellEnvironmentCommandError = ( const captureWindowsEnvironmentCommand = (names: ReadonlyArray) => [ "$ErrorActionPreference = 'Stop'", + // Redirected PowerShell output uses the console code page, which mangles non-ASCII paths. + "try { [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch {}", ...names.flatMap((name) => { return [ `Write-Output '${startMarker(name)}'`, diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index 32ed8d2b46116..d9950edc60cfb 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -415,6 +415,9 @@ describe("readEnvironmentFromWindowsShell", () => { expect.arrayContaining(["-NoLogo", "-NoProfile", "-NonInteractive", "-Command"]), { encoding: "utf8", timeout: 5000 }, ); + expect(execFile.mock.calls[0]?.[1].at(-1)).toContain( + "[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)", + ); }), ); @@ -441,6 +444,21 @@ describe("readEnvironmentFromWindowsShell", () => { }), ); + effectIt.effect.runIf(HostProcess.Platform.defaultValue() === "win32")( + "reads a non-ASCII value from the real shell", + () => + Effect.gen(function* () { + const name = "T3CODE_TEST_NON_ASCII_PATH"; + const value = "C:\\Users\\Jürgen\\Grüße"; + vi.stubEnv(name, value); + try { + expect(yield* readEnvironmentFromWindowsShell([name])).toEqual({ [name]: value }); + } finally { + vi.unstubAllEnvs(); + } + }), + ); + effectIt.effect("omits -NoProfile when loadProfile is enabled", () => Effect.gen(function* () { const execFile = vi.fn< diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index 05a1d5b14bd79..8ccb466775c1f 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -295,6 +295,8 @@ export function windowsEnvironmentValueCommand(name: string): string { function buildWindowsEnvironmentCaptureCommand(names: ReadonlyArray): string { return [ "$ErrorActionPreference = 'Stop'", + // Redirected PowerShell output uses the console code page, which mangles non-ASCII paths. + "try { [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch {}", ...names.flatMap((name) => { if (!SHELL_ENV_NAME_PATTERN.test(name)) { throw new Error(`Unsupported environment variable name: ${name}`); From 1cedd4b4ed729d8696821e018063a5bc2c5c6b49 Mon Sep 17 00:00:00 2001 From: Karchi <162874774+Gooder24@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:16:09 +0100 Subject: [PATCH 037/139] fix(web): scheduled task times follow the Time format setting (#37314) Co-authored-by: maria-rcks Co-authored-by: Julius Marminge --- .../chat/ThreadAutomationsPanel.tsx | 10 ++-- .../settings/ScheduledTasksSettings.tsx | 13 ++++- .../scheduledTasksSettings.logic.test.ts | 48 +++++++++++++++++-- .../settings/scheduledTasksSettings.logic.ts | 14 +++--- apps/web/src/timestampFormat.ts | 27 +++++++++++ 5 files changed, 95 insertions(+), 17 deletions(-) diff --git a/apps/web/src/components/chat/ThreadAutomationsPanel.tsx b/apps/web/src/components/chat/ThreadAutomationsPanel.tsx index 0a602227cad54..12989e3f4f607 100644 --- a/apps/web/src/components/chat/ThreadAutomationsPanel.tsx +++ b/apps/web/src/components/chat/ThreadAutomationsPanel.tsx @@ -12,12 +12,14 @@ import { type ScheduledTask, type ThreadId, } from "@t3tools/contracts"; +import type { TimestampFormat } from "@t3tools/contracts/settings"; import { isAtomCommandInterrupted, squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; import { ThreadDetailsSection } from "./ThreadDetailsSection"; +import { useClientSettings } from "../../hooks/useSettings"; import { cn } from "../../lib/utils"; import { ScheduledRelativeLabel } from "../settings/ScheduledTasksSettings"; import { scheduleLabel } from "../settings/scheduledTasksSettings.logic"; @@ -43,12 +45,13 @@ const STATUS_DOT_CLASS: Record = { function taskScheduleLine( task: ScheduledTask, + timestampFormat: TimestampFormat, timeZone: string | undefined, resolve: MessageResolver, ) { return ( <> - {scheduleLabel(task.schedule, timeZone, task.nextRunAt, resolve)} + {scheduleLabel(task.schedule, timestampFormat, timeZone, task.nextRunAt, resolve)} {task.blockedByPolicy !== undefined ? ( ` · ${task.blockedByPolicy}` ) : task.enabled && task.nextRunAt !== null ? ( @@ -87,6 +90,7 @@ export function ThreadAutomationsPanel(props: { const runTaskNow = useAtomCommand(serverEnvironment.runScheduledTaskNow, { label: "thread automation run now", }); + const timestampFormat = useClientSettings((settings) => settings.timestampFormat); const navigate = useNavigate(); const gt = useGT(); const m = useMessages(); @@ -198,13 +202,13 @@ export function ThreadAutomationsPanel(props: { {task.title}

    - {taskScheduleLine(task, tasksQuery.data?.timeZone, m)} + {taskScheduleLine(task, timestampFormat, tasksQuery.data?.timeZone, m)}

    {task.title}

    - {taskScheduleLine(task, tasksQuery.data?.timeZone, m)} + {taskScheduleLine(task, timestampFormat, tasksQuery.data?.timeZone, m)}

    diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.tsx index 471dcdf0fe0df..4f70815684faa 100644 --- a/apps/web/src/components/settings/ScheduledTasksSettings.tsx +++ b/apps/web/src/components/settings/ScheduledTasksSettings.tsx @@ -54,7 +54,7 @@ import { msg, T, useGT, useLocale, useMessages, Var } from "gt-react"; import { m, type MessageResolver } from "../../i18n/messages"; import { formatRelativeTime } from "../../timestampFormat"; -import { useEnvironmentSettings } from "../../hooks/useSettings"; +import { useClientSettings, useEnvironmentSettings } from "../../hooks/useSettings"; import { getCustomModelOptionsByInstance } from "../../modelSelection"; import { providerInstanceEntriesFor } from "../../providerInstances"; import { usePrimaryCloudLinkState } from "../../cloud/cloudLinkState"; @@ -795,6 +795,7 @@ function ScheduledTaskRow({ const canOperate = useAtomValue( serverEnvironment.upsertScheduledTask.permissionAtom(environmentId), ); + const timestampFormat = useClientSettings((settings) => settings.timestampFormat); const [busy, setBusy] = useState(false); const [deliveriesOpen, setDeliveriesOpen] = useState(false); const isWebhook = task.schedule.type === "webhook"; @@ -841,7 +842,15 @@ function ScheduledTaskRow({ status={
    - {scheduleLabel(task.schedule, timeZone, task.nextRunAt, messages, locale)} ·{" "} + {scheduleLabel( + task.schedule, + timestampFormat, + timeZone, + task.nextRunAt, + messages, + locale, + )}{" "} + ·{" "} {task.blockedByPolicy !== undefined ? ( task.blockedByPolicy ) : !task.enabled ? ( diff --git a/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts b/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts index d01b47078dbe2..2bbdd7867c3c7 100644 --- a/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts +++ b/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts @@ -424,11 +424,49 @@ it("rejects dedupe templates without a request placeholder", () => { expect(scheduleFromDraft({ ...draft, coalesceKey: "{{body.bad" })).toBeNull(); }); +// The host locale's clock for a wall time, so these pass in any locale (digits, day period, zero padding). +function clock(hour12: boolean, hour: number, minute: number) { + return new Intl.DateTimeFormat(undefined, { + hour: "numeric", + minute: "2-digit", + hour12, + timeZone: "UTC", + }).format(Date.UTC(2000, 0, 1, hour, minute)); +} + it("appends the server zone only to fixed-time schedule labels", () => { - expect(scheduleLabel({ type: "fixed_time", timeOfDay: "16:31" }, "Etc/UTC")).toBe( - "Daily at 16:31 UTC", + expect(scheduleLabel({ type: "fixed_time", timeOfDay: "16:31" }, "24-hour", "Etc/UTC")).toBe( + `Daily at ${clock(false, 16, 31)} UTC`, + ); + expect(scheduleLabel({ type: "fixed_time", timeOfDay: "09:00" }, "24-hour")).toBe( + `Daily at ${clock(false, 9, 0)}`, + ); + expect(scheduleLabel({ type: "interval", everyMs: 60_000 }, "24-hour", "Etc/UTC")).toBe( + "Every 1 min", ); - expect(scheduleLabel({ type: "fixed_time", timeOfDay: "09:00" })).toBe("Daily at 09:00"); - expect(scheduleLabel({ type: "interval", everyMs: 60_000 }, "Etc/UTC")).toBe("Every 1 min"); - expect(scheduleLabel({ type: "webhook", signature: null }, "Etc/UTC")).toBe("On webhook"); + expect(scheduleLabel({ type: "webhook", signature: null }, "24-hour", "Etc/UTC")).toBe( + "On webhook", + ); +}); + +it("shows schedule times in the Time format setting", () => { + const daily = { type: "fixed_time", timeOfDay: "17:30" } as const; + expect(scheduleLabel(daily, "24-hour")).toBe(`Daily at ${clock(false, 17, 30)}`); + expect(scheduleLabel(daily, "12-hour")).toBe(`Daily at ${clock(true, 17, 30)}`); + const midnight = scheduleLabel({ type: "fixed_time", timeOfDay: "0:05" }, "24-hour"); + expect(midnight).toBe(`Daily at ${clock(false, 0, 5)}`); + // An h24 clock would print midnight as 24:05 in both the label and the helper. + expect(midnight).not.toContain("24"); + + // A local wall time, so the label reads 17:30 in any host zone. + const runAt = new Date(2026, 10, 20, 17, 30); + const once = { type: "once", runAt: runAt.toISOString() } as const; + for (const hour12 of [false, true]) { + const dateTime = new Intl.DateTimeFormat(undefined, { + dateStyle: "medium", + timeStyle: "short", + hour12, + }).format(runAt); + expect(scheduleLabel(once, hour12 ? "12-hour" : "24-hour")).toBe(`Once, ${dateTime}`); + } }); diff --git a/apps/web/src/components/settings/scheduledTasksSettings.logic.ts b/apps/web/src/components/settings/scheduledTasksSettings.logic.ts index bbb5c146cb28a..6c7038f8ed191 100644 --- a/apps/web/src/components/settings/scheduledTasksSettings.logic.ts +++ b/apps/web/src/components/settings/scheduledTasksSettings.logic.ts @@ -24,6 +24,7 @@ import { type WebhookFilterDraft, } from "@t3tools/client-runtime/scheduled-task-webhook"; import { scheduleTimeZoneLabel } from "@t3tools/client-runtime/scheduled-task-time-zone"; +import type { TimestampFormat } from "@t3tools/contracts/settings"; import { msg } from "gt-react"; import { @@ -32,6 +33,7 @@ import { } from "@t3tools/shared/projectSettings"; import { getActiveLocale, m, type MessageResolver } from "../../i18n/messages"; import type { ProviderInstanceEntry } from "../../providerInstances"; +import { formatDateTimeTimestamp, formatTimeOfDay } from "../../timestampFormat"; import type { ResolvedSettingsScope } from "./settingsScope"; @@ -43,13 +45,9 @@ export function weekdayShortLabel(day: number, locale: string = getActiveLocale( ); } -const ONCE_FORMATTER = new Intl.DateTimeFormat(undefined, { - dateStyle: "medium", - timeStyle: "short", -}); - export function scheduleLabel( schedule: ScheduledTaskSchedule, + timestampFormat: TimestampFormat, timeZone?: string, runAt?: string | null, resolve: MessageResolver = m, @@ -57,7 +55,9 @@ export function scheduleLabel( ): string { if (schedule.type === "webhook") return resolve(msg("On webhook")); if (schedule.type === "once") { - return resolve(msg("Once, {time}", { time: ONCE_FORMATTER.format(new Date(schedule.runAt)) })); + return resolve( + msg("Once, {time}", { time: formatDateTimeTimestamp(schedule.runAt, timestampFormat) }), + ); } if (schedule.type === "interval") { const minutes = schedule.everyMs / 60_000; @@ -66,7 +66,7 @@ export function scheduleLabel( : resolve(msg("Every {seconds} sec", { seconds: Math.round(schedule.everyMs / 1000) })); } const weekdays = schedule.weekdays ?? []; - const time = schedule.timeOfDay; + const time = formatTimeOfDay(schedule.timeOfDay, timestampFormat); const zone = scheduleTimeZoneLabel(timeZone, runAt); if (weekdays.length === 0) { return zone === undefined diff --git a/apps/web/src/timestampFormat.ts b/apps/web/src/timestampFormat.ts index ac99534a5ca2f..836020c20bbec 100644 --- a/apps/web/src/timestampFormat.ts +++ b/apps/web/src/timestampFormat.ts @@ -181,6 +181,33 @@ export function formatShortTimestamp(isoDate: string, timestampFormat: Timestamp return formatTime(date, timestampFormat); } +const dateTimeFormatterCache = new Map(); + +export function formatDateTimeTimestamp(isoDate: string, timestampFormat: TimestampFormat): string { + const date = parseTimestampDate(isoDate); + if (!date) return ""; + let formatter = dateTimeFormatterCache.get(timestampFormat); + if (!formatter) { + formatter = new Intl.DateTimeFormat(timestampLocale, { + dateStyle: "medium", + timeStyle: "short", + ...(timestampFormat === "locale" ? {} : { hour12: timestampFormat === "12-hour" }), + }); + dateTimeFormatterCache.set(timestampFormat, formatter); + } + return formatter.format(date); +} + +/** A wall-clock `H:MM` or `HH:MM` that names no date or zone, such as a daily schedule's time. */ +export function formatTimeOfDay(timeOfDay: string, timestampFormat: TimestampFormat): string { + const match = /^(\d{1,2}):(\d{2})$/.exec(timeOfDay); + if (!match) return timeOfDay; + // Default-zone formatters run in UTC, so the host zone cannot shift the wall time. + return getTimestampFormatter(timestampFormat, false).format( + Date.UTC(2000, 0, 1, Number(match[1]), Number(match[2])), + ); +} + const numericDateOptions: Intl.DateTimeFormatOptions = { month: "numeric", day: "numeric" }; const numericDateWithYearOptions: Intl.DateTimeFormatOptions = { ...numericDateOptions, From e2fdfd2c3112ec738f31638765faee5b9312ffc7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 10:28:58 -0800 Subject: [PATCH 038/139] perf(client-runtime): opening the branch picker keeps the branch list when no ref moved (#40452) --- .../src/vcs/VcsStatusBroadcaster.test.ts | 5 +++- apps/server/src/vcs/VcsStatusBroadcaster.ts | 26 ++++++++++++------- packages/client-runtime/src/state/vcs.test.ts | 8 ++++++ packages/client-runtime/src/state/vcs.ts | 21 ++++++++++----- 4 files changed, 42 insertions(+), 18 deletions(-) diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index d30997266c7b7..9d8b2bf2117b3 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -717,7 +717,10 @@ describe("VcsStatusBroadcaster", () => { return Effect.gen(function* () { const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; const initial = yield* broadcaster.getStatus({ cwd: "/repo" }); - const refreshed = yield* broadcaster.refreshStatus("/repo", { localOnly: true }); + const { refsDigest, ...refreshed } = yield* broadcaster.refreshStatus("/repo", { + localOnly: true, + }); + assert.isString(refsDigest); assert.deepStrictEqual(refreshed, initial); assert.deepStrictEqual(yield* broadcaster.getStatus({ cwd: "/repo" }), refreshed); assert.equal(state.localInvalidationCalls, 1); diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index 5842478fffe76..92a83c0230f71 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -736,21 +736,27 @@ export const make = Effect.gen(function* () { )(function* (rawCwd, options) { const cwd = yield* withFileSystem(normalizeCwd(rawCwd)); yield* acquireBranchChangesDemand(cwd); - const refsBeforeLocalRead = options?.localOnly ? null : yield* workflow.readRefSnapshot(cwd); - yield* refreshLocalStatusCore(cwd); + // Lets the client keep its cached branch list when no ref moved since its last refresh. + const withRefsDigest = (status: VcsStatusResult, refs: string | null) => + refs === null + ? status + : { + ...status, + refsDigest: NodeCrypto.createHash("sha256").update(refs).digest("hex").slice(0, 32), + }; if (options?.localOnly) { + const [refs] = yield* Effect.all( + [workflow.readRefSnapshot(cwd), refreshLocalStatusCore(cwd)], + { concurrency: "unbounded" }, + ); // Never cache a remote here: readers take `value: null` as "read and found no PR". const parts = yield* getStatusParts(cwd); - return mergeGitStatusParts(parts.local, parts.remote); + return withRefsDigest(mergeGitStatusParts(parts.local, parts.remote), refs); } + const refsBeforeLocalRead = yield* workflow.readRefSnapshot(cwd); + yield* refreshLocalStatusCore(cwd); const { status, refs } = yield* refreshRemoteAndLocalTotals(cwd, rawCwd, refsBeforeLocalRead); - // Lets the client keep its cached branch list when no ref moved since its last refresh. - return refs === null - ? status - : { - ...status, - refsDigest: NodeCrypto.createHash("sha256").update(refs).digest("hex").slice(0, 32), - }; + return withRefsDigest(status, refs); }, Effect.scoped); const refreshAfterCheckout: VcsStatusBroadcaster["Service"]["refreshAfterCheckout"] = Effect.fn( diff --git a/packages/client-runtime/src/state/vcs.test.ts b/packages/client-runtime/src/state/vcs.test.ts index f58b0d120598d..edc005263b432 100644 --- a/packages/client-runtime/src/state/vcs.test.ts +++ b/packages/client-runtime/src/state/vcs.test.ts @@ -464,6 +464,13 @@ describe("cached VCS refs", () => { expect(yield* Ref.get(clears)).toBe(3); expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(3); + yield* atoms.refreshLocalStatusForPicker.run(registry, { + environmentId: TARGET.environmentId, + input: { cwd: "/repo", localOnly: true }, + }); + expect(yield* Ref.get(clears)).toBe(3); + expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(3); + const prepareResult = yield* Effect.exit( createGitEnvironmentAtoms(runtime).preparePullRequestThread.run(registry, { environmentId: TARGET.environmentId, @@ -485,6 +492,7 @@ describe("cached VCS refs", () => { [WS_METHODS.vcsRefreshStatus]: () => Deferred.succeed(refreshStarted, undefined).pipe( Effect.andThen(Deferred.await(releaseRefresh)), + Effect.as({}), ), [WS_METHODS.vcsSwitchRef]: () => Effect.succeed({ refName: "feature" }), } as unknown as WsRpcProtocolClient; diff --git a/packages/client-runtime/src/state/vcs.ts b/packages/client-runtime/src/state/vcs.ts index a6299aab0ff64..dab79e282a4d2 100644 --- a/packages/client-runtime/src/state/vcs.ts +++ b/packages/client-runtime/src/state/vcs.ts @@ -2,6 +2,7 @@ import { type EnvironmentId, type VcsListRefsInput, type VcsListRefsResult, + type VcsRefreshStatusResult, type VcsStatusResult, WS_METHODS, } from "@t3tools/contracts"; @@ -294,6 +295,17 @@ export function createVcsEnvironmentAtoms( cwd: target.input.cwd, }); + const invalidateRefsIfChanged = ( + target: { readonly environmentId: EnvironmentId; readonly input: { readonly cwd: string } }, + registry: AtomRegistry.AtomRegistry, + exit: Exit.Exit, + ) => + invalidateCachedVcsRefsIfChanged( + registry, + { environmentId: target.environmentId, cwd: target.input.cwd }, + Exit.isSuccess(exit) ? exit.value.refsDigest : undefined, + ); + return { listRefs, // An uncached read for decisions that must match the repository now, not @@ -341,19 +353,14 @@ export function createVcsEnvironmentAtoms( tag: WS_METHODS.vcsRefreshStatus, scheduler: vcsCommandScheduler, concurrency: vcsCommandConcurrency, - onSettled: (target, registry, exit) => - invalidateCachedVcsRefsIfChanged( - registry, - { environmentId: target.environmentId, cwd: target.input.cwd }, - Exit.isSuccess(exit) ? exit.value.refsDigest : undefined, - ), + onSettled: invalidateRefsIfChanged, }), // Outside the serial queue: it only reads status, and a checkout picked right after opening // the picker must not wait behind that read. refreshLocalStatusForPicker: createEnvironmentRpcCommand(runtime, { label: "environment-data:vcs:refresh-local-status-for-picker", tag: WS_METHODS.vcsRefreshStatus, - onSettled: invalidateRefs, + onSettled: invalidateRefsIfChanged, }), createWorktree: createEnvironmentRpcCommand(runtime, { label: "environment-data:vcs:create-worktree", From 194025ef11027c95b0d226a4d2bbdafb92279eab Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 10:31:19 -0800 Subject: [PATCH 039/139] perf(server): turn end reads upstream divergence once, not twice (#40450) --- apps/server/src/git/GitManager.ts | 10 +++- apps/server/src/git/GitWorkflowService.ts | 2 + .../src/vcs/VcsStatusBroadcaster.test.ts | 55 ++++++++++++++++--- apps/server/src/vcs/VcsStatusBroadcaster.ts | 17 +++++- 4 files changed, 71 insertions(+), 13 deletions(-) diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index dab6d4d20924e..543b5de5505f5 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -111,6 +111,8 @@ export interface GitLocalStatusOptions { export interface GitRemoteStatusOptions extends GitVcsDriver.GitRemoteStatusOptions { readonly refreshMissingPullRequest?: boolean; + /** Details the caller just read without fetching; used instead of reading them again. */ + readonly statusDetails?: GitVcsDriver.GitRemoteStatusDetails; } export type GitBranchPullRequest = NonNullable & { @@ -1603,9 +1605,11 @@ export const make = Effect.gen(function* () { cwd: string, options?: GitRemoteStatusOptions, ) { - const details = yield* gitCore - .statusDetailsRemote(cwd, options) - .pipe(Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(null))); + const details = + options?.statusDetails ?? + (yield* gitCore + .statusDetailsRemote(cwd, options) + .pipe(Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(null)))); if (details === null || !details.isRepo) { return null; } diff --git a/apps/server/src/git/GitWorkflowService.ts b/apps/server/src/git/GitWorkflowService.ts index f012a65bb0692..f0757fd7078fe 100644 --- a/apps/server/src/git/GitWorkflowService.ts +++ b/apps/server/src/git/GitWorkflowService.ts @@ -59,6 +59,7 @@ export class GitWorkflowService extends Context.Service< readonly refName: string; readonly aheadCount: number; readonly behindCount: number; + readonly details: GitVcsDriver.GitRemoteStatusDetails; } | null, GitManagerServiceError >; @@ -384,6 +385,7 @@ export const make = Effect.gen(function* () { refName: details.branch, aheadCount: details.aheadCount, behindCount: details.behindCount, + details, } : null; }), diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index 9d8b2bf2117b3..7c5dd63773848 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -78,6 +78,7 @@ function layerTestFor(state: { localInvalidationCalls: number; remoteInvalidationCalls: number; remoteStatusRefreshUpstreamValues?: Array; + remoteStatusReusedDetails?: Array; localStatusBranchChanges?: Array; refSnapshot?: string | null; remoteStatusError?: GitManagerError; @@ -144,15 +145,29 @@ function layerTestFor(state: { readRefSnapshot: () => Effect.sync(() => (state.refSnapshot === undefined ? "refs" : state.refSnapshot)), upstreamDivergence: () => - Effect.sync(() => - state.currentRemoteStatus?.hasUpstream && state.currentLocalStatus.refName !== null - ? { - refName: state.currentLocalStatus.refName, - aheadCount: (state.currentDivergence ?? state.currentRemoteStatus).aheadCount, - behindCount: (state.currentDivergence ?? state.currentRemoteStatus).behindCount, - } - : null, - ), + Effect.sync(() => { + const refName = state.currentLocalStatus.refName; + if (!state.currentRemoteStatus?.hasUpstream || refName === null) return null; + const { aheadCount, behindCount } = + state.currentDivergence ?? state.currentRemoteStatus; + return { + refName, + aheadCount, + behindCount, + details: { + isRepo: true, + hasPrimaryRemote: true, + defaultBranch: "main", + isDefaultBranch: false, + branch: refName, + upstreamRef: `origin/${refName}`, + hasUpstream: true, + aheadCount, + behindCount, + aheadOfDefaultCount: aheadCount, + }, + }; + }), remoteStatus: (_input, options) => Effect.suspend(() => { return (state.beforeRemoteStatus ?? Effect.void).pipe( @@ -160,6 +175,7 @@ function layerTestFor(state: { Effect.sync(() => { state.remoteStatusCalls += 1; state.remoteStatusRefreshUpstreamValues?.push(options?.refreshUpstream); + state.remoteStatusReusedDetails?.push(options?.statusDetails !== undefined); return state.currentRemoteStatus; }), ), @@ -794,6 +810,27 @@ describe("VcsStatusBroadcaster", () => { }, ); + it.effect("the turn-end PR lookup reuses the upstream read it follows, once", () => { + const state: Parameters[0] = { + currentLocalStatus: baseLocalStatus, + currentRemoteStatus: remoteStatusWithPr, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + remoteStatusReusedDetails: [], + }; + + return Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + yield* broadcaster.getStatus({ cwd: "/repo" }); + yield* broadcaster.refreshLocalStatus("/repo"); + yield* broadcaster.refreshPullRequestStatus("/repo"); + yield* broadcaster.refreshPullRequestStatus("/repo"); + assert.deepStrictEqual(state.remoteStatusReusedDetails, [false, true, false]); + }).pipe(Effect.provide(layerTestFor(state))); + }); + it.effect.each([0, 2])( "refreshes merge divergence while a lookup ends with %s commits behind", (behindAfterLookup) => { diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index 92a83c0230f71..156290ed0ca6a 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -37,6 +37,7 @@ import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; import * as GitWorkflowService from "../git/GitWorkflowService.ts"; import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; import * as ServerSettings from "../serverSettings.ts"; +import type * as GitVcsDriver from "./GitVcsDriver.ts"; import { VcsAutomaticFetchInterval } from "./VcsAutomaticFetchInterval.ts"; const VCS_STATUS_REFRESH_FAILURE_BASE_DELAY = Duration.seconds(30); @@ -330,6 +331,9 @@ export const make = Effect.gen(function* () { // A refresh that started after a request saw every change that request could mean, so queued // callers share it instead of each running git status again. const localRefreshRequests = new Map(); + // Upstream details the turn-end refreshLocalStatus just read, handed once to the PR lookup that + // follows it so the same no-fetch read is not repeated. Any remote write in between drops them. + const upstreamReads = new Map(); const localRefreshResults = new Map< string, { @@ -353,6 +357,7 @@ export const make = Effect.gen(function* () { // A queued caller can read git again. Keep the monotonic request counter so it cannot // mistake an older result for a later request. localRefreshResults.delete(candidate); + upstreamReads.delete(candidate); } return cache; }; @@ -449,6 +454,7 @@ export const make = Effect.gen(function* () { const updateCachedRemoteStatus = Effect.fn("VcsStatusBroadcaster.updateCachedRemoteStatus")( function* (cwd: string, remote: CachedRemoteStatus | null, options?: { publish?: boolean }) { + upstreamReads.delete(cwd); const [changed, value] = yield* Ref.modify(cacheRef, (cache) => { const previous = cache.get(cwd) ?? { local: null, remote: null }; const next = remote?.branch === previous.local?.value.refName ? remote : null; @@ -556,6 +562,7 @@ export const make = Effect.gen(function* () { "VcsStatusBroadcaster.refreshLocalStatus", )(function* (rawCwd) { const cwd = yield* withFileSystem(normalizeCwd(rawCwd)); + upstreamReads.delete(cwd); const local = yield* refreshLocalStatusCore(cwd); const cached = yield* getCachedStatus(cwd); // Divergence is local Git data; a slow forge lookup must not delay turn-end updates. @@ -577,6 +584,7 @@ export const make = Effect.gen(function* () { }, { publish: true }, ); + upstreamReads.set(cwd, divergence.details); } } return local; @@ -590,7 +598,11 @@ export const make = Effect.gen(function* () { // GitManager's remote TTL cache is keyed by cwd, not the checked-out branch. yield* workflow.invalidateRemoteStatus(cwd); const previousRemote = (yield* getCachedStatus(cwd))?.remote; - const remote = yield* workflow.remoteStatus({ cwd }, options); + const { statusDetails, ...remoteOptions } = options ?? {}; + const remote = yield* workflow.remoteStatus( + { cwd }, + statusDetails?.branch === branch ? { ...remoteOptions, statusDetails } : remoteOptions, + ); const latest = yield* getCachedStatus(cwd); // An overlapping turn refresh and fetch can both move divergence during the forge lookup. const refreshed = @@ -783,9 +795,12 @@ export const make = Effect.gen(function* () { const cached = yield* getCachedStatus(cwd); if (!cached || cached.remote?.value === null) return null; // Turn completion must update divergence even when background polling is paused. + const statusDetails = upstreamReads.get(cwd); + upstreamReads.delete(cwd); const remoteRead = yield* readRemoteStatus(cwd, { refreshUpstream: false, refreshMissingPullRequest: true, + ...(statusDetails ? { statusDetails } : {}), }); return yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true }); }), From 1ffa099e7fbf0037dbffb6fb72b7585c933be24a Mon Sep 17 00:00:00 2001 From: Michel Liao <107891771+Michel-Liao@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:52:14 -0500 Subject: [PATCH 040/139] fix(shared): file links whose title holds the other quote keep their folder labels (#40464) Co-authored-by: Julius Marminge --- packages/shared/src/markdownLinks.test.ts | 3 +++ packages/shared/src/markdownLinks.ts | 17 ++++++++++------- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/packages/shared/src/markdownLinks.test.ts b/packages/shared/src/markdownLinks.test.ts index 0a997aee79eac..a1f0af927636d 100644 --- a/packages/shared/src/markdownLinks.test.ts +++ b/packages/shared/src/markdownLinks.test.ts @@ -185,6 +185,9 @@ describe("extractMarkdownLinkHrefs", () => { ["/x/app/(a)/page.tsx", "/x/app/(b)/page.tsx"], ], ['[a](/tmp/a(1).txt "title") after', ["/tmp/a(1).txt"]], + [`[a](a.ts "it's a title") [b](b.ts 'a "quoted" title') [c](ok)`, ["a.ts", "b.ts", "ok"]], + [`[a](a.ts "mixed') [b](b.ts)`, ["b.ts"]], + [`[a](a.ts "it's\n\n[b](lib/a.ts)")`, ["lib/a.ts"]], ["[a](a(b(c))d) [b](ok)", ["a(b(c))d", "ok"]], ["[a](x\\)y) [b](x\\(y)", ["x\\)y", "x\\(y"]], ["[a](unclosed(paren) [b](ok)", ["ok"]], diff --git a/packages/shared/src/markdownLinks.ts b/packages/shared/src/markdownLinks.ts index 98df3952fb278..fe450406093b3 100644 --- a/packages/shared/src/markdownLinks.ts +++ b/packages/shared/src/markdownLinks.ts @@ -461,15 +461,18 @@ function markdownRunEndFinder(markdown: string, delimiter: RegExp) { } function markdownLinkTailScanner(markdown: string) { - const whitespaceEnd = markdownRunEndFinder(markdown, /\S/g); - const titleEnd = markdownRunEndFinder(markdown, /["']/g); - const titleWhitespaceEnd = markdownRunEndFinder(markdown, /\S/g); + // A blank line ends the paragraph, so no part of a link's tail runs past one. + const whitespaceEnd = markdownRunEndFinder(markdown, /\S|\n[ \t\r]*\n/g); + const doubleQuoteEnd = markdownRunEndFinder(markdown, /"|\n[ \t\r]*\n/g); + const singleQuoteEnd = markdownRunEndFinder(markdown, /'|\n[ \t\r]*\n/g); + const titleWhitespaceEnd = markdownRunEndFinder(markdown, /\S|\n[ \t\r]*\n/g); return (start: number) => { const end = whitespaceEnd(start); - if (markdown[end] === ")") return end + 1; - if (end === start || (markdown[end] !== '"' && markdown[end] !== "'")) return null; - const quoteEnd = titleEnd(end + 1); - if (quoteEnd === markdown.length) return null; + const quote = markdown[end]; + if (quote === ")") return end + 1; + if (end === start || (quote !== '"' && quote !== "'")) return null; + const quoteEnd = (quote === '"' ? doubleQuoteEnd : singleQuoteEnd)(end + 1); + if (markdown[quoteEnd] !== quote) return null; const close = titleWhitespaceEnd(quoteEnd + 1); return markdown[close] === ")" ? close + 1 : null; }; From a3001b33fe652ad7df9d9977384058bbac5a53f2 Mon Sep 17 00:00:00 2001 From: Michel Liao <107891771+Michel-Liao@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:56:04 -0500 Subject: [PATCH 041/139] fix(web): RTF previews break the line at TextEdit soft line breaks (#40468) Co-authored-by: Julius Marminge --- apps/web/src/components/files/FilePreviewPanel.test.ts | 8 +++++++- apps/web/src/components/files/extendedDocumentPreview.ts | 4 +++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts index c1d49b1d26f8d..4c9d8b0f9a676 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.ts +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -214,7 +214,7 @@ describe("document preview contents", () => { expect(html).not.toContain("https:"); }); - it("treats a backslash before a line break as a paragraph break, as TextEdit writes them", () => { + it("breaks lines at the paragraph and line breaks TextEdit writes", () => { const html = (rtf: string) => { const result = openRtf(bytes(rtf)); if (result.type !== "document") throw new Error("Expected document"); @@ -230,6 +230,12 @@ Third}`; ); expect(html(textEdit)).toEqual(expected); expect(html(textEdit.replaceAll("\n", "\r\n"))).toEqual(expected); + const lineBreak = html(String.raw`{\rtf1\ansi First line\line Second line}`); + expect(lineBreak).toEqual(["

    First line
    Second line

    "]); + expect(html(String.raw`{\rtf1\ansi First line\uc0\u8232 Second line}`)).toEqual(lineBreak); + expect(html(String.raw`{\rtf1\ansi First line\u8232?Second line{\deleted\u8232?}}`)).toEqual( + lineBreak, + ); }); it("preserves rich text page breaks and formatting without splitting hidden destinations", () => { diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index a450123089718..07a8713b08202 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -727,7 +727,9 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { else if (word === "uc") state.uc = Math.max(0, Math.min(10, arg)); else if (word === "u") { fallback = 0; - emit(String.fromCharCode(arg < 0 ? arg + 65536 : arg)); + // TextEdit writes a soft line break as U+2028, where Chromium does not break the line. + if (arg !== 0x2028) emit(String.fromCharCode(arg < 0 ? arg + 65536 : arg)); + else if (!hidden()) html += "
    "; fallback = state.uc; } else if (!hidden() && word === "page") finishPage(); else if (word === "cell") emit("\t", state.skip); From 9fdcd08835ebd15e134b6abb7e5a65031b1f1266 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 11:02:34 -0800 Subject: [PATCH 042/139] fix(mobile): scheduled task Time dialog closes after OK on Android (#40479) --- .../src/features/settings/SettingsScheduledTasksRouteScreen.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx index 8e15dad08ac23..e878f86581b4a 100644 --- a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx @@ -1228,6 +1228,7 @@ function TaskForm({ display={Platform.OS === "ios" ? "spinner" : "default"} onDismiss={() => setTimePickerOpen(false)} onValueChange={(_, selected) => { + if (Platform.OS === "android") setTimePickerOpen(false); const timeOfDay = `${String(selected.getHours()).padStart(2, "0")}:${String(selected.getMinutes()).padStart(2, "0")}`; setDraft((current) => ({ ...current, From fcf50973f3353cb401450c5cc6b4a177746150b7 Mon Sep 17 00:00:00 2001 From: Michel Liao <107891771+Michel-Liao@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:14:28 -0500 Subject: [PATCH 043/139] fix(server): RTF attachments no longer garble text set in a font's own character set (#40476) Co-authored-by: Julius Marminge --- .../server/src/provider/documentTextWorker.ts | 47 ++++++++++++++++--- .../src/provider/userInputAttachments.test.ts | 11 +++++ 2 files changed, 52 insertions(+), 6 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 9cec14dadd67e..b49b9a42378f3 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -416,10 +416,35 @@ function* notebook(source: string): Generator { } } +// Per-byte decoding only supports the single-byte \fcharset values. +const FONT_CODE_PAGES = new Map([ + [77, "macintosh"], + [161, "windows-1253"], + [162, "windows-1254"], + [163, "windows-1258"], + [177, "windows-1255"], + [178, "windows-1256"], + [186, "windows-1257"], + [204, "windows-1251"], + [222, "windows-874"], + [238, "windows-1250"], +]); + function* rtf(source: string): Generator { if (!source.startsWith("{\\rtf")) throw new Error("Invalid RTF document"); - let state = { skip: false, deleted: false, uc: 1, decoder: new TextDecoder("windows-1252") }; + let state = { + skip: false, + deleted: false, + uc: 1, + font: 0, + fontTable: false, + decoder: new TextDecoder("windows-1252"), + }; const stack: Array = []; + // A font's \fcharset, not the document code page, encodes the bytes written in that font. + const fonts = new Map(); + let defaultFont = 0; + const decoder = () => fonts.get(state.font) ?? state.decoder; const hidden = () => state.skip || state.deleted; const symbols = new Map([ ["endash", "–"], @@ -454,7 +479,7 @@ function* rtf(source: string): Generator { const word = /^([a-z]+)(-?\d+)? ?/i.exec(rest); if (hex) { if (fallback) fallback--; - else if (!hidden()) yield state.decoder.decode(Uint8Array.of(Number.parseInt(hex[1]!, 16))); + else if (!hidden()) yield decoder().decode(Uint8Array.of(Number.parseInt(hex[1]!, 16))); i += 3; } else if (word) { i += word[0].length; @@ -489,8 +514,20 @@ function* rtf(source: string): Generator { ].includes(control) ) state.skip = true; + if (control === "fonttbl") state.fontTable = true; + else if (control === "deff") state.font = defaultFont = value; + else if (control === "f") { + state.font = value; + if (state.fontTable) fonts.delete(value); + } else if (control === "fcharset" && state.fontTable) { + const codePage = FONT_CODE_PAGES.get(value); + if (codePage) fonts.set(state.font, new TextDecoder(codePage)); + } if (control === "deleted") state.deleted = value !== 0; - else if (control === "plain") state.deleted = false; + else if (control === "plain") { + state.deleted = false; + state.font = defaultFont; + } if (control === "mac" || (control === "ansicpg" && value === 10000)) state.decoder = new TextDecoder("macintosh"); else if (control === "ansicpg") { @@ -524,9 +561,7 @@ function* rtf(source: string): Generator { } else if (char !== "\n" && char !== "\r") { if (fallback) fallback--; else if (!hidden()) - yield char.charCodeAt(0) < 128 - ? char - : state.decoder.decode(Uint8Array.of(char.charCodeAt(0))); + yield char.charCodeAt(0) < 128 ? char : decoder().decode(Uint8Array.of(char.charCodeAt(0))); } } } diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 7bf24acb0b40a..26752022aab17 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -344,6 +344,17 @@ describe("question answer paths", () => { String.raw`{\rtf1\mac\ansicpg10000 Caf\'8e Cr\'8fme}`, "Café Crème", ], + [ + "font character set", + String.raw`{\rtf1\ansi\ansicpg1252\deff1{\fonttbl\f0\fnil\fcharset178 GeezaPro;\f1\fnil\fcharset0 LucidaGrande;} +\f0 \'e3\'e1\'c7\'cd\'d9\'c9\f1 : caf\'e9, \f0\plain\'c7a}`, + "ملاحظة: café, Ça", + ], + [ + "font character set outside the font table", + String.raw`{\rtf1\ansi{\fonttbl{\f0\fcharset178 A;}{\f0\fcharset0 B;}{\f1\fcharset0 C;}{\f2\fcharset178 D;}{\f2 E;}}{\stylesheet{\s0\f1\fcharset178 N;}}\f0 \'e3\f1\'e3\f2\'e3}`, + "ããã", + ], ["destination symbol", String.raw`{\rtf1\ansi\u945\*Z}`, "αZ"], ["multiple units", String.raw`{\rtf1\ansi\uc4\u945?\tab\'3f\~Z}`, "αZ"], ["binary unit", String.raw`{\rtf1\ansi\u945\bin3 abcZ}`, "αZ"], From f0ceeefc08af95ad00ae50a62e1ead5e89c8ebca Mon Sep 17 00:00:00 2001 From: Simone Date: Sat, 21 Nov 2026 20:31:20 +0100 Subject: [PATCH 044/139] fix(antigravity): match skill manifest filters literally (#40488) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../Drivers/AntigravitySkills.test.ts | 16 +-- .../src/provider/Drivers/AntigravitySkills.ts | 105 ++---------------- 2 files changed, 19 insertions(+), 102 deletions(-) diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts index 0033755bfe706..40d78ab16b05f 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts @@ -381,7 +381,7 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { path.join(sharedSkills, "yagni"), "---\nname: yagni\ndescription: Keep it simple.\n---\n", ); - yield* writeSkill( + const experimentalPath = yield* writeSkill( path.join(sharedSkills, "experimental-draft"), "---\nname: experimental-draft\n---\n", ); @@ -392,11 +392,7 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { "---\nname: linter\n---\n", ); yield* writeSkill(path.join(inheritedSkills, "skipped"), "---\nname: skipped\n---\n"); - // Backtracks exponentially under RegExp against the pattern below. - yield* writeSkill( - path.join(inheritedSkills, "a".repeat(40)), - "---\nname: backtrack\n---\n", - ); + yield* writeSkill(path.join(inheritedSkills, "lint-draft"), "---\nname: lint-draft\n---\n"); const projectSkills = path.join(input.cwd, "tools", "skills"); const projectPath = yield* writeSkill( @@ -425,7 +421,7 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { yield* fileSystem.writeFileString( path.join(globalConfigDir, "skills.json"), JSON.stringify({ - inherits: [{ path: inheritedConfigPath, include_only: ["linter", "(a*)*b"] }], + inherits: [{ path: inheritedConfigPath, include_only: ["linter", "lint-.*"] }], entries: [ { path: sharedSkills, exclude: ["experimental-.*"] }, { path: "~/tilde-skills" }, @@ -452,6 +448,12 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { assert.deepEqual(yield* discoverAntigravitySkills(input), [ { name: "deploy", path: projectPath, scope: "project", enabled: true }, + { + name: "experimental-draft", + path: experimentalPath, + scope: "user", + enabled: true, + }, { name: "linter", path: inheritedPath, scope: "user", enabled: true }, { name: "yagni", diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.ts b/apps/server/src/provider/Drivers/AntigravitySkills.ts index f69b3d1c455be..edbe5e34a7343 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.ts @@ -185,106 +185,21 @@ const readSkillFrontmatter = Effect.fn("readAntigravitySkill")(function* ( return bytes.toString("utf8", 0, frontmatterEnd); }); -type SkillPatternMatcher = (entry: string) => boolean; - interface SkillEntryFilter { - readonly includeGroups: ReadonlyArray>; - readonly excludePatterns: ReadonlyArray; + readonly includeGroups: ReadonlyArray>; + readonly excludeNames: ReadonlyArray; } const EMPTY_SKILL_FILTER: SkillEntryFilter = { includeGroups: [], - excludePatterns: [], + excludeNames: [], }; -interface SkillPatternToken { - readonly test: (character: string) => boolean; - readonly optional: boolean; - readonly repeats: boolean; -} - -/** Undefined for syntax outside literals, escapes, `.`, `[...]` and `* + ?`; such patterns match literally. */ -function parseSkillPattern(pattern: string): ReadonlyArray | undefined { - const characters = Array.from(pattern); - const tokens: Array = []; - let index = 0; - while (index < characters.length) { - const character = characters[index]!; - let test: (candidate: string) => boolean; - if (character === "\\") { - const escaped = characters[index + 1]; - if (escaped === undefined) return undefined; - if (/[dDwWsS]/.test(escaped)) { - const characterClass = new RegExp(`^\\${escaped}$`, "u"); - test = (candidate) => characterClass.test(candidate); - } else { - test = (candidate) => candidate === escaped; - } - index += 2; - } else if (character === "[") { - const close = characters.indexOf("]", index + 2); - if (close === -1) return undefined; - let characterClass: RegExp; - try { - characterClass = new RegExp(`^[${characters.slice(index + 1, close).join("")}]$`, "u"); - } catch { - return undefined; - } - test = (candidate) => characterClass.test(candidate); - index = close + 1; - } else if (character === ".") { - test = () => true; - index += 1; - } else if ("()|{}^$*+?".includes(character)) { - return undefined; - } else { - test = (candidate) => candidate === character; - index += 1; - } - const quantifier = characters[index]; - const optional = quantifier === "*" || quantifier === "?"; - const repeats = quantifier === "*" || quantifier === "+"; - if (optional || repeats) { - index += 1; - if (characters[index] === "?") index += 1; - } - tokens.push({ test, optional, repeats }); - } - return tokens; -} - -/** Manifests can come from an opened workspace, so matching runs as an NFA in linear time instead of RegExp. */ -function compileSkillPattern(pattern: string): SkillPatternMatcher { - const tokens = parseSkillPattern(pattern); - if (tokens === undefined) return (entry) => entry === pattern; - const close = (states: Set) => { - for (const state of states) { - if (state < tokens.length && tokens[state]!.optional) states.add(state + 1); - } - return states; - }; - return (entry) => { - let states = close(new Set([0])); - for (const character of entry) { - const next = new Set(); - for (const state of states) { - const token = tokens[state]; - if (!token?.test(character)) continue; - next.add(state + 1); - if (token.repeats) next.add(state); - } - if (next.size === 0) return false; - states = close(next); - } - return states.has(tokens.length); - }; -} - function matchesSkillFilter(entry: string, filter: SkillEntryFilter): boolean { for (const group of filter.includeGroups) { - if (!group.some((matches) => matches(entry))) return false; + if (!group.includes(entry)) return false; } - return !filter.excludePatterns.some((matches) => matches(entry)); + return !filter.excludeNames.includes(entry); } function narrowSkillFilter( @@ -293,13 +208,13 @@ function narrowSkillFilter( ): SkillEntryFilter { const includeGroups = entry.include_only && entry.include_only.length > 0 - ? [...parent.includeGroups, entry.include_only.map(compileSkillPattern)] + ? [...parent.includeGroups, entry.include_only] : parent.includeGroups; - const excludePatterns = + const excludeNames = entry.exclude && entry.exclude.length > 0 - ? [...parent.excludePatterns, ...entry.exclude.map(compileSkillPattern)] - : parent.excludePatterns; - return { includeGroups, excludePatterns }; + ? [...parent.excludeNames, ...entry.exclude] + : parent.excludeNames; + return { includeGroups, excludeNames }; } // agy does not expand ~, so a ~/ path stays relative to the config file. From e452042db8af83b6cbc503fa9c6612b30054372e Mon Sep 17 00:00:00 2001 From: phorrr Date: Sat, 21 Nov 2026 20:42:28 +0100 Subject: [PATCH 045/139] fix(contracts): older clients drop unknown values in RPC responses (#40490) Co-authored-by: x0r Co-authored-by: Julius Marminge --- packages/contracts/src/baseSchemas.test.ts | 15 +++++++++++++-- packages/contracts/src/baseSchemas.ts | 11 +++++++++-- packages/contracts/src/pullRequest.test.ts | 15 +++++++++++++-- 3 files changed, 35 insertions(+), 6 deletions(-) diff --git a/packages/contracts/src/baseSchemas.test.ts b/packages/contracts/src/baseSchemas.test.ts index ec5b5e31d75f7..beae3731400bc 100644 --- a/packages/contracts/src/baseSchemas.test.ts +++ b/packages/contracts/src/baseSchemas.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "@effect/vitest"; import * as DateTime from "effect/DateTime"; +import * as Exit from "effect/Exit"; import * as Schema from "effect/Schema"; import { @@ -22,13 +23,23 @@ const fromWire = (schema: S) => describe("ForwardCompatibleArray", () => { it("decodes elements through their own codec and drops ones it cannot read", () => { - const decoded = fromWire(ForwardCompatibleArray(Shape))([ + const shapes = ForwardCompatibleArray(Shape); + const exit = Schema.toCodecJson(Schema.Exit(shapes, Schema.Never, Schema.Never)); + const wire = [ { kind: "circle", radius: 1, at }, { kind: "triangle" }, { kind: "square", side: "wide" }, - ]); + ]; + const decoded = fromWire(shapes)(wire); expect(decoded).toHaveLength(1); expect(DateTime.isDateTime((decoded[0] as { at: unknown }).at)).toBe(true); + expect(Schema.decodeSync(exit)({ _tag: "Success", value: wire })).toEqual( + Exit.succeed(decoded), + ); + expect(Schema.encodeSync(exit)(Exit.succeed(decoded))).toEqual({ + _tag: "Success", + value: [wire[0]], + }); }); const Named = ForwardCompatibleArray(Schema.Struct({ name: TrimmedNonEmptyString })); diff --git a/packages/contracts/src/baseSchemas.ts b/packages/contracts/src/baseSchemas.ts index 7b000a4a22edc..30df0d53c537f 100644 --- a/packages/contracts/src/baseSchemas.ts +++ b/packages/contracts/src/baseSchemas.ts @@ -94,11 +94,18 @@ export const OmittedWhenNull = (value: Value) => { ); }; +const UnknownArrayElement = Schema.Unknown.pipe( + Schema.decodeTo(Schema.Undefined, { + decode: SchemaGetter.succeed(undefined), + encode: SchemaGetter.passthrough(), + }), +); + /** Prefer {@link ForwardCompatibleUnion} for tagged unions so malformed known members still fail. */ export const ForwardCompatibleArray = (element: Element) => + // Exit derives its wire codec from the encoded shape, which keeps the union but drops recovery middleware. Schema.Array( - Schema.UndefinedOr(element).pipe( - Schema.catchDecoding(() => Effect.succeedSome(undefined)), + Schema.Union([element, UnknownArrayElement]).pipe( Schema.catchEncoding(() => Effect.succeedSome(undefined)), ), ).pipe( diff --git a/packages/contracts/src/pullRequest.test.ts b/packages/contracts/src/pullRequest.test.ts index 91f22f20bfa5f..2e801b71970ef 100644 --- a/packages/contracts/src/pullRequest.test.ts +++ b/packages/contracts/src/pullRequest.test.ts @@ -1,14 +1,25 @@ import { SourceControlProviderKind } from "./sourceControl.ts"; +import * as Exit from "effect/Exit"; +import * as Rpc from "effect/rpc/Rpc"; import * as Schema from "effect/Schema"; import { describe, expect, it } from "vite-plus/test"; import { - PullRequestDetail, + type PullRequestDetail, PullRequestListResult, resolvePullRequestAuthorFilter, } from "./pullRequest.ts"; +import { WS_METHODS, WsRpcGroup } from "./rpc.ts"; -const decodeDetail = Schema.decodeUnknownSync(Schema.toCodecJson(PullRequestDetail)); +// Clients decode the detail inside the RPC's Exit, as the JSON serialization does. +const decodeDetailExit = Schema.decodeUnknownSync( + Schema.toCodecJson(Rpc.exitSchema(WsRpcGroup.requests.get(WS_METHODS.pullRequestsDetail)!)), +); +const decodeDetail = (value: unknown): PullRequestDetail => { + const exit = decodeDetailExit({ _tag: "Success", value }); + if (!Exit.isSuccess(exit)) throw new Error("expected a successful exit"); + return exit.value as PullRequestDetail; +}; const LIST_RESULT: PullRequestListResult = { viewers: { "github.com": "bilal", "gitlab.com": "bilal.hassan" }, From 10a5b5dca60159750132a7f07120e813fdb7b07c Mon Sep 17 00:00:00 2001 From: Michel Liao <107891771+Michel-Liao@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:47:25 -0500 Subject: [PATCH 046/139] fix(server): Word table cells wrapped in a content control reach the agent (#40496) Co-authored-by: Julius Marminge --- apps/server/src/provider/documentTextWorker.ts | 5 ++--- apps/server/src/provider/userInputAttachments.test.ts | 3 ++- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index b49b9a42378f3..8509b490cceee 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -256,9 +256,8 @@ function hasCellText(cell: XmlNode): boolean { function* table(node: XmlNode): Generator { let rowCount = 0; for (const row of all(node, ["tr", "table-row"])) { - const cells = children(row).filter((cell) => - ["tc", "table-cell", "covered-table-cell", "td", "th"].includes(cell.name), - ); + // Word nests a cell inside w:sdt when a content control wraps the whole cell. + const cells = [...all(row, ["tc", "table-cell", "covered-table-cell", "td", "th"])]; // ODS writers pad sheets with repeated empty rows and trailing cells. while (cells.length && !hasCellText(cells.at(-1)!)) cells.pop(); if (!cells.length) continue; diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 26752022aab17..556351b225bac 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -786,11 +786,12 @@ describe("question answer paths", () => { bounded: true, parts: { "word/document.xml": - 'Report & totalsNorth1234BeforeInnerAfterNeighbor', + 'Report & totalsNorth1234Annual reportDraftBeforeInnerAfterNeighbor', }, expected: [ "## Report & totals", "North\t12 34", + "Annual report\tDraft", "Before Inner After\tNeighbor\t\u2011\n\u2011", ], }, From db9efc5cf0fa181e0a913e750ed908b0814809f8 Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Sat, 21 Nov 2026 21:51:16 +0200 Subject: [PATCH 047/139] fix(server): a stop-on-settle action no longer holds back automatic settlement (#40489) Co-authored-by: Julius Marminge --- apps/server/src/terminal/Manager.test.ts | 6 ++++++ apps/server/src/terminal/Manager.ts | 3 ++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index c6f45a60ab75e..8af803db1fd8c 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -1003,12 +1003,18 @@ it.layer( { pid: 100, ppid: 9000, name: "zsh" }, { pid: 9001, ppid: 1, name: "zsh" }, { pid: 200, ppid: 9001, name: "node" }, + { pid: 9002, ppid: 1, name: "zsh" }, + { pid: 300, ppid: 9002, name: "node" }, ]), }).pipe(Effect.provide(layerWithHostPlatform("linux"))); yield* manager.open(openInput({ terminalId: "idle", threadId: "thread-idle" })); yield* manager.open(openInput({ terminalId: "dev-server", threadId: "thread-active" })); + yield* manager.open( + openInput({ terminalId: "managed-dev", threadId: "thread-managed", stopOnSettle: true }), + ); expect(yield* manager.hasActiveSubprocess({ threadId: "thread-none" })).toBe(false); + expect(yield* manager.hasActiveSubprocess({ threadId: "thread-managed" })).toBe(false); expect(yield* manager.hasActiveSubprocess({ threadId: "thread-idle" })).toBe(false); expect(yield* manager.hasActiveSubprocess({ threadId: "thread-active" })).toBe(true); }), diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 86ccc1d3e0dd2..fb19b6c7ad1d6 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -3968,9 +3968,10 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func const hasActiveSubprocess = Effect.fn("terminal.hasActiveSubprocess")(function* (input: { readonly threadId: string; }) { + // Settling closes stopOnSettle sessions, so their work must not hold settlement back. const running = (yield* sessionsForThread(input.threadId)).filter( (session): session is TerminalSessionState & { pid: number } => - session.status === "running" && Number.isInteger(session.pid), + session.status === "running" && Number.isInteger(session.pid) && !session.stopOnSettle, ); if (running.length === 0) return false; const { inspector } = yield* acquireSubprocessInspector( From bac86471fe75e5f344a524b60775a14da0e1dd33 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 12:10:15 -0800 Subject: [PATCH 048/139] fix(web): links inside a PDF are clickable in the in-app PDF viewer (#40507) --- .../components/files/BrowserDocumentFrame.tsx | 8 ++ .../src/components/files/FilePreviewPanel.tsx | 1 + .../files/PdfViewer.browser.test.tsx | 49 +++++++++- apps/web/src/components/files/PdfViewer.tsx | 90 ++++++++++++++++++- 4 files changed, 144 insertions(+), 4 deletions(-) diff --git a/apps/web/src/components/files/BrowserDocumentFrame.tsx b/apps/web/src/components/files/BrowserDocumentFrame.tsx index 024f8480a6d7f..3270556fb0ff4 100644 --- a/apps/web/src/components/files/BrowserDocumentFrame.tsx +++ b/apps/web/src/components/files/BrowserDocumentFrame.tsx @@ -85,6 +85,7 @@ function PdfDocument(props: { src: string; title: string; documentKey: string; + threadRef: ScopedThreadRef | undefined; actions?: ReactNode; }) { const [view, setView] = useState({ page: 0, offset: 0, zoom: null, left: 0 }); @@ -96,6 +97,7 @@ function PdfDocument(props: { positionKey={props.documentKey} initialView={view} onViewChange={setView} + threadRef={props.threadRef} actions={props.actions} /> ); @@ -108,9 +110,11 @@ function PdfDocumentRevision(props: { positionKey: string; initialView: PdfViewState; onViewChange: (view: PdfViewState) => void; + threadRef: ScopedThreadRef | undefined; actions?: ReactNode; }) { const [src] = useState(props.src); + const openLink = useOpenLink(props.threadRef); // The Electron shell does not enable PDF plugins. WebKit embeds on iOS // expose only the first page, even when pdfViewerEnabled reports support. const native = @@ -133,6 +137,9 @@ function PdfDocumentRevision(props: { positionKey={props.positionKey} initialView={props.initialView} onViewChange={props.onViewChange} + onOpenLink={(url, event) => { + void openLink(url, { event }).catch((cause: unknown) => console.error(cause)); + }} actions={props.actions} /> @@ -163,6 +170,7 @@ export function BrowserDocumentFrame(props: { documentKey={key} src={props.src} title={props.title} + threadRef={props.threadRef} actions={props.pdfActions} /> ) : props.htmlRender ? ( diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx index 13a74c131eea3..c020113815dfa 100644 --- a/apps/web/src/components/files/FilePreviewPanel.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.tsx @@ -350,6 +350,7 @@ export function WorkspaceBrowserPreview(props: { documentId={documentId} title={props.title} pdf={pdf} + threadRef={props.threadRef} pdfActions={ >", `<< /Type /Pages /Count ${pages.length} /Kids [${pages.map((_, index) => `${3 + index * 2} 0 R`).join(" ")}] >>`, - ...pages.flatMap(({ box, rotate, text }, index) => [ - `<< /Type /Page /Parent 2 0 R /MediaBox [${box}] /Rotate ${rotate} /Resources << /Font << /F1 ${fonts} 0 R /F2 ${fonts + 1} 0 R >> >> /Contents ${4 + index * 2} 0 R >>`, + ...pages.flatMap(({ box, rotate, text, annots = "" }, index) => [ + `<< /Type /Page /Parent 2 0 R /MediaBox [${box}] /Rotate ${rotate}${annots && ` /Annots [${annots}]`} /Resources << /Font << /F1 ${fonts} 0 R /F2 ${fonts + 1} 0 R >> >> /Contents ${4 + index * 2} 0 R >>`, `<< /Length ${text.length} >>\nstream\n${text}\nendstream`, ]), "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>", @@ -257,3 +257,46 @@ it("restores page, within-page offset and zoom after a remount", async () => { URL.revokeObjectURL(url); } }); + +it("follows a link to another page and exposes a web link", async () => { + const url = URL.createObjectURL( + testPdf([ + { + box: "0 0 612 792", + rotate: 0, + text: "BT /F1 24 Tf 30 700 Td (See p. 2) Tj 0 -60 Td (Website) Tj ET", + annots: [ + "<< /Type /Annot /Subtype /Link /Rect [30 690 200 730] /Border [0 0 0] /Dest [5 0 R /XYZ 0 792 0] >>", + "<< /Type /Annot /Subtype /Link /Rect [30 630 200 670] /Border [0 0 0] /A << /S /URI /URI (https://example.com/) >> >>", + ].join(" "), + }, + { box: "0 0 612 792", rotate: 0, text: "BT /F1 24 Tf 30 700 Td (Target) Tj ET" }, + ]), + ); + try { + await using screen = await render( +
    + +
    , + ); + await expect.element(screen.getByText("1 / 2 pages")).toBeVisible(); + const region = screen.getByRole("region", { name: "Linked PDF" }).element(); + const web = await vi.waitFor(() => { + const link = region.querySelector('a[href="https://example.com/"]'); + expect(link).not.toBeNull(); + return link!; + }); + expect(getComputedStyle(web).cursor).toBe("pointer"); + const internal = await vi.waitFor(() => { + const link = Array.from(region.querySelectorAll("a")).find( + (anchor) => anchor !== web, + ); + expect(link).toBeDefined(); + return link!; + }); + internal.click(); + await expect.element(screen.getByText("2 / 2 pages")).toBeVisible(); + } finally { + URL.revokeObjectURL(url); + } +}); diff --git a/apps/web/src/components/files/PdfViewer.tsx b/apps/web/src/components/files/PdfViewer.tsx index f81e23deab2b1..31faf628fbeb9 100644 --- a/apps/web/src/components/files/PdfViewer.tsx +++ b/apps/web/src/components/files/PdfViewer.tsx @@ -6,6 +6,7 @@ import { useRef, useState, type CSSProperties, + type MouseEvent, type ReactNode, } from "react"; import { TextLayer, type PDFDocumentProxy } from "pdfjs-dist"; @@ -42,6 +43,21 @@ type PdfPosition = PdfViewState & { width: number; ratios: readonly number[] }; // Thread switches unmount the preview; retain only the most recent documents. const positions = new Map(); +type PdfLink = { box: readonly [number, number, number, number] } & ( + | { url: string } + | { page: number } +); + +// Resolves a link annotation's destination, named or explicit, to a page index. +async function pdfLinkPage(pdf: PDFDocumentProxy, dest: unknown): Promise { + const explicit: unknown = typeof dest === "string" ? await pdf.getDestination(dest) : dest; + if (!Array.isArray(explicit)) return null; + const [ref] = explicit as unknown[]; + if (Number.isInteger(ref)) return ref as number; + if (typeof ref !== "object" || ref === null) return null; + return pdf.getPageIndex(ref as Parameters[0]); +} + export type PdfViewState = { page: number; offset: number; @@ -56,8 +72,11 @@ function PdfPage(props: { query: string; onSize: (index: number, ratio: number) => void; onError: (error: string) => void; + onPageLink: (index: number) => void; + onOpenLink: ((url: string, event: MouseEvent) => void) | undefined; }) { const gt = useGT(); + const [links, setLinks] = useState([]); const canvas = useRef(null); const text = useRef(null); const painted = useRef(null); @@ -112,7 +131,31 @@ function PdfPage(props: { buffer.width = 0; painted.current = pdf; }); - await Promise.all([shown, layer.render()]); + const linked = page.getAnnotations({ intent: "display" }).then(async (annotations) => { + const found: PdfLink[] = []; + for (const annotation of annotations) { + if (annotation.subtype !== "Link") continue; + const [x1, y1] = viewport.convertToViewportPoint(annotation.rect[0], annotation.rect[1]); + const [x2, y2] = viewport.convertToViewportPoint(annotation.rect[2], annotation.rect[3]); + const box = [ + Math.min(x1, x2) / viewport.width, + Math.min(y1, y2) / viewport.height, + Math.abs(x2 - x1) / viewport.width, + Math.abs(y2 - y1) / viewport.height, + ] as const; + if (typeof annotation.url === "string" && /^https?:\/\//i.test(annotation.url)) { + found.push({ box, url: annotation.url }); + continue; + } + const target = await pdfLinkPage(pdf, annotation.dest).catch(() => null); + if (target !== null && target >= 0 && target < pdf.numPages) + found.push({ box, page: target }); + } + if (!cancelled) setLinks(found); + }); + // A page whose annotations cannot be read still renders, without links. + const linkedOrNone = linked.catch(() => undefined); + await Promise.all([shown, layer.render(), linkedOrNone]); })().catch((cause: unknown) => { if (!cancelled) onError(thrownErrorMessage(cause, m) ?? m(msg("This PDF page could not render."))); @@ -151,6 +194,48 @@ function PdfPage(props: { className="block h-full w-full" />
    ))} From ba4f99ae43b0b5988bd00e729c6a55cadaa5fd2b Mon Sep 17 00:00:00 2001 From: Sean Kenneth Doherty Date: Sat, 21 Nov 2026 14:10:26 -0600 Subject: [PATCH 049/139] fix(web,mobile): Limits shows why a provider's limits are unavailable (#40481) Co-authored-by: Sean Kenneth Doherty <328402569+seankd3@users.noreply.github.com> Co-authored-by: Julius Marminge --- packages/shared/src/usageLimits.test.ts | 24 ++++++++++++++++++++++++ packages/shared/src/usageLimitsCopy.ts | 11 +++++++++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/packages/shared/src/usageLimits.test.ts b/packages/shared/src/usageLimits.test.ts index 6b553fe5f1555..0019c74e1d5cd 100644 --- a/packages/shared/src/usageLimits.test.ts +++ b/packages/shared/src/usageLimits.test.ts @@ -1889,6 +1889,30 @@ describe("external usage settings", () => { expect(collectLimitNotices(presentations)).toEqual(["Host · codex: Could not read limits."]); }); + it("shows the reason an account's limits are unsupported, but not a bare unsupported", () => { + const unsupported = (message?: string) => + provider({ + usageLimits: { + checkedAt: "2026-09-03T11:00:00.000Z", + windows: [], + unavailable: { reason: "unsupported", ...(message ? { message } : {}) }, + }, + }); + const notices = (limited: ServerProvider) => + collectLimitNotices( + new Map([ + [ + EnvironmentId.make("a"), + { entry: { target: { label: "Host" } }, serverConfig: { providers: [limited] } }, + ], + ]), + ); + expect(notices(unsupported("Sign in with Google to see Antigravity limits."))).toEqual([ + "codex: Sign in with Google to see Antigravity limits.", + ]); + expect(notices(unsupported())).toEqual([]); + }); + it("names a hub account whose read failed unless another environment read it", () => { const checkedAt = "2026-09-03T11:00:00.000Z"; const account = { diff --git a/packages/shared/src/usageLimitsCopy.ts b/packages/shared/src/usageLimitsCopy.ts index ea9eafaf55ce1..85f78e0f11f28 100644 --- a/packages/shared/src/usageLimitsCopy.ts +++ b/packages/shared/src/usageLimitsCopy.ts @@ -92,8 +92,15 @@ export function collectLimitNotices( for (const presentation of presentations.values()) { const environmentLabel = presentation.entry.target.label; for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) { - if (provider.usageLimits?.unavailable?.reason === "unsupported") continue; - const notice = provider.usageLimits ? limitsNotice(provider.usageLimits, resolve) : null; + const limits = provider.usageLimits; + // A bare unsupported means the account has no limits; an external usage link shows its message. + if ( + limits?.unavailable?.reason === "unsupported" && + (!limits.unavailable.message || limits.externalUsage) + ) { + continue; + } + const notice = limits ? limitsNotice(limits, resolve) : null; const name = provider.displayName?.trim() || String(provider.driver); if (notice) notices.add(`${label(environmentLabel, name)}: ${notice}`); } From c3fb01dc0535c0312b5ff8fa386fde5c8d675593 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 12:14:57 -0800 Subject: [PATCH 050/139] fix(server): preview snapshots no longer report an empty interactiveElements list (#40520) --- apps/server/src/mcp/McpHttpServer.test.ts | 57 +++---------------- apps/server/src/mcp/McpHttpServer.ts | 48 +++------------- apps/server/src/preview/ServerBrowser.test.ts | 1 - .../src/preview/ServerBrowserPage.test.ts | 18 +++++- apps/server/src/preview/ServerBrowserPage.ts | 6 +- .../mcp-tool-use/cases/browser-routing.ndjson | 26 ++++----- packages/contracts/src/previewAutomation.ts | 13 ----- 7 files changed, 48 insertions(+), 121 deletions(-) diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index e5d47410817f2..3842d1a4b3bf2 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -124,7 +124,6 @@ const snapshotResult = { title: "Example", loading: false, visibleText: "Example", - interactiveElements: [], accessibilityTree: {}, consoleEntries: [], networkEntries: [], @@ -421,18 +420,6 @@ it.effect.each([ url: "http://example.test/", loading: false, visibleText: "Save your changes", - interactiveElements: [ - { - tag: "button", - role: "button", - name: "Save", - selector: "#save", - x: 0, - y: 0, - width: 20, - height: 10, - }, - ], accessibilityTree: { role: "document", name: "Example" }, consoleEntries: [], networkEntries: [], @@ -482,7 +469,7 @@ it.effect.each([ expect(snapshot.isError).toBe(false); expect(snapshot.structuredContent).toEqual({ ...boundedMetadata, - omitted: ["accessibilityTree (use interactiveElements locators or preview_evaluate)"], + omitted: ["accessibilityTree (use preview_evaluate)"], }); const [identity, text, ...rest] = snapshot.content; expect(identity?.type === "text" ? decodeJsonText(identity.text) : null).toEqual({ @@ -492,7 +479,7 @@ it.effect.each([ expect(rest).toEqual([ { type: "text", - text: "Snapshot text was bounded. Omitted: accessibilityTree (use interactiveElements locators or preview_evaluate).", + text: "Snapshot text was bounded. Omitted: accessibilityTree (use preview_evaluate).", }, ...(images ? [ @@ -890,25 +877,9 @@ it.effect("keeps the snapshot text under the agent's output ceiling", () => Effect.scoped( Effect.gen(function* () { const pageText = "/Users/theo/Code/project\nClaude, Codex · 79 threads\n".repeat(600); - const element = (name: string, index: number) => ({ - tag: "div", - role: "presentation", - name, - selector: `div:nth-of-type(${index})`, - x: 0, - y: 0, - width: 10, - height: 10, - }); const oversized = { ...snapshotResult, visibleText: pageText, - interactiveElements: [ - element(pageText, 1), - element(pageText, 2), - element(pageText, 3), - element("Continue", 4), - ], accessibilityTree: { nodes: Array.from({ length: 2_000 }, (_, i) => ({ nodeId: `${i}` })) }, consoleEntries: Array.from({ length: 100 }, (_, i) => ({ level: "log", @@ -933,14 +904,10 @@ it.effect("keeps the snapshot text under the agent's output ceiling", () => const parsed = decodeJsonText(body) as { readonly accessibilityTree?: unknown; readonly visibleText: string; - readonly interactiveElements: ReadonlyArray<{ readonly name: string }>; readonly consoleEntries: ReadonlyArray<{ readonly text: string }>; }; expect(parsed.accessibilityTree).toBeUndefined(); expect(parsed.visibleText.length).toBeLessThanOrEqual(8_001); - expect(parsed.interactiveElements).toHaveLength(4); - expect(parsed.interactiveElements[0]?.name.length).toBeLessThanOrEqual(201); - expect(parsed.interactiveElements[3]?.name).toBe("Continue"); expect(parsed.consoleEntries).toHaveLength(40); expect(parsed.consoleEntries[0]?.text).toBe("entry 60"); expect(notice?.type === "text" ? notice.text : "").toContain("accessibilityTree"); @@ -960,7 +927,6 @@ it.effect("bounds the snapshot text even when nothing but logs and the title are const oversized = { ...snapshotResult, title: `t${"😀".repeat(35_000)}`, - interactiveElements: [], consoleEntries: [{ level: "log", text: `x${"😀".repeat(35_000)}`, timestamp: "t" }], }; yield* serveSnapshots("mcp-bounded-logs-client", oversized); @@ -992,19 +958,14 @@ it.effect("bounds the snapshot text even when nothing but logs and the title are it.effect("bounds page text made of wide characters before dropping locators", () => Effect.scoped( Effect.gen(function* () { + const accessibilityTree = Array.from( + { length: 20 }, + (_, i) => `- button "Button ${i}" [ref=t3-1-e${i}]`, + ).join("\n"); yield* serveSnapshots("mcp-wide-text-client", { ...snapshotResult, visibleText: "界".repeat(9_000), - interactiveElements: Array.from({ length: 20 }, (_, i) => ({ - tag: "button", - role: "button", - name: `Button ${i}`, - selector: `#button-${i}`, - x: 0, - y: 0, - width: 10, - height: 10, - })), + accessibilityTree, }); const snapshot = yield* callSnapshot({ includeImage: false }); @@ -1016,10 +977,10 @@ it.effect("bounds page text made of wide characters before dropping locators", ( ); const parsed = decodeJsonText(body) as { readonly visibleText: string; - readonly interactiveElements: ReadonlyArray; + readonly accessibilityTree: string; }; expect(parsed.visibleText).toMatch(/^界+…$/); - expect(parsed.interactiveElements).toHaveLength(20); + expect(parsed.accessibilityTree).toBe(accessibilityTree); expect(notice?.type === "text" ? notice.text : "").toContain( "visibleText after 4000 characters", ); diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index d7bea75493b73..4c9d9dca1081a 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -373,7 +373,6 @@ export const MAX_SNAPSHOT_TEXT_BYTES = 20_000; const MAX_SNAPSHOT_VISIBLE_TEXT_CHARS = 8_000; // Page text and the ARIA tree both shrink to this before either drops below it. const SNAPSHOT_TEXT_FLOOR_CHARS = 2_000; -const MAX_SNAPSHOT_ELEMENT_NAME_CHARS = 200; const MAX_SNAPSHOT_LOG_ENTRIES = 40; const MAX_SNAPSHOT_LOG_TEXT_CHARS = 500; const MAX_SNAPSHOT_IDENTIFIER_CHARS = 2_048; @@ -406,10 +405,6 @@ type SnapshotMetadata = { readonly url: string; readonly title: string; readonly visibleText: string; - readonly interactiveElements: ReadonlyArray<{ - readonly name: string; - readonly [key: string]: unknown; - }>; readonly consoleEntries: ReadonlyArray; readonly networkEntries: ReadonlyArray; readonly actionTimeline: ReadonlyArray; @@ -426,7 +421,7 @@ const boundSnapshotMetadata = (metadata: SnapshotMetadata) => { const { accessibilityTree, ...withoutTree } = metadata; const ariaTree = typeof accessibilityTree === "string" ? accessibilityTree : undefined; if (accessibilityTree !== undefined && ariaTree === undefined) { - omitted.push("accessibilityTree (use interactiveElements locators or preview_evaluate)"); + omitted.push("accessibilityTree (use preview_evaluate)"); } const tail = (entries: ReadonlyArray, label: string) => { if (entries.length > MAX_SNAPSHOT_LOG_ENTRIES) { @@ -444,41 +439,23 @@ const boundSnapshotMetadata = (metadata: SnapshotMetadata) => { ) { omitted.push(`url or title after ${MAX_SNAPSHOT_IDENTIFIER_CHARS} characters`); } - if ( - metadata.interactiveElements.some( - (element) => element.name.length > MAX_SNAPSHOT_ELEMENT_NAME_CHARS, - ) - ) { - omitted.push(`element names longer than ${MAX_SNAPSHOT_ELEMENT_NAME_CHARS} characters`); - } const bounded = { ...withoutTree, url: cutText(metadata.url, MAX_SNAPSHOT_IDENTIFIER_CHARS), title: cutText(metadata.title, MAX_SNAPSHOT_IDENTIFIER_CHARS), - interactiveElements: metadata.interactiveElements.map((element) => ({ - ...element, - name: cutText(element.name, MAX_SNAPSHOT_ELEMENT_NAME_CHARS), - })), consoleEntries: tail(metadata.consoleEntries, "console entries"), networkEntries: tail(metadata.networkEntries, "network entries"), actionTimeline: tail(metadata.actionTimeline, "action timeline entries"), }; // Per-field character caps can still exceed the total byte ceiling. - const shedOrder = [ - "actionTimeline", - "networkEntries", - "consoleEntries", - "interactiveElements", - ] as const; + const shedOrder = ["actionTimeline", "networkEntries", "consoleEntries"] as const; const lists: Record<(typeof shedOrder)[number], ReadonlyArray> = { - interactiveElements: bounded.interactiveElements, consoleEntries: bounded.consoleEntries, networkEntries: bounded.networkEntries, actionTimeline: bounded.actionTimeline, }; const dropped: Record<(typeof shedOrder)[number], number> = { - interactiveElements: 0, consoleEntries: 0, networkEntries: 0, actionTimeline: 0, @@ -493,22 +470,18 @@ const boundSnapshotMetadata = (metadata: SnapshotMetadata) => { }); let text = encodeJsonText(value()); while (utf8Length(text) > MAX_SNAPSHOT_TEXT_BYTES) { - // Logs shed first, oldest first. Below the floors, locator-bearing elements and tree go last. + // Logs shed first, oldest first. Below the floors, the locator-bearing tree goes last. const key = - shedOrder.find( - (candidate) => candidate !== "interactiveElements" && lists[candidate].length > 0, - ) ?? + shedOrder.find((candidate) => lists[candidate].length > 0) ?? (visibleTextChars > SNAPSHOT_TEXT_FLOOR_CHARS ? "visibleText" : ariaTreeChars > SNAPSHOT_TEXT_FLOOR_CHARS ? "accessibilityTree" : visibleTextChars > 0 ? "visibleText" - : lists.interactiveElements.length > 0 - ? "interactiveElements" - : ariaTreeChars > 0 - ? "accessibilityTree" - : undefined); + : ariaTreeChars > 0 + ? "accessibilityTree" + : undefined); if (key === undefined) break; if (key === "visibleText") { visibleTextChars = halveToFloor(visibleTextChars); @@ -517,12 +490,7 @@ const boundSnapshotMetadata = (metadata: SnapshotMetadata) => { } else { const keep = Math.floor(lists[key].length / 2); dropped[key] += lists[key].length - keep; - lists[key] = - keep === 0 - ? [] - : key === "interactiveElements" - ? lists[key].slice(0, keep) - : lists[key].slice(-keep); + lists[key] = keep === 0 ? [] : lists[key].slice(-keep); } text = encodeJsonText(value()); } diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.ts index 9d1460c9befd5..a15378ec3039c 100644 --- a/apps/server/src/preview/ServerBrowser.test.ts +++ b/apps/server/src/preview/ServerBrowser.test.ts @@ -235,7 +235,6 @@ function makeContext(onClose?: (context: BrowserContext) => void, initialUrl = " title: "test page", loading: false, visibleText: "delete", - interactiveElements: [], })), ariaSnapshot: vi.fn(async () => '- button "delete" [ref=e1]'), locator: vi.fn((): unknown => { diff --git a/apps/server/src/preview/ServerBrowserPage.test.ts b/apps/server/src/preview/ServerBrowserPage.test.ts index 79ccc4089aeee..9afe924dabc4c 100644 --- a/apps/server/src/preview/ServerBrowserPage.test.ts +++ b/apps/server/src/preview/ServerBrowserPage.test.ts @@ -61,7 +61,6 @@ describe("snapshot deadline diagnostics", () => { title: "", loading: false, visibleText: "", - interactiveElements: [], }), ariaSnapshot: async () => "", ...options.page, @@ -275,6 +274,23 @@ describe("server browser element refs", () => { }; const repeatedRows = `
      ${Array.from({ length: 5 }, (_, i) => `
    • row ${i + 1}
    • `).join("")}
    `; + it("does not report an empty interactiveElements list beside a tree full of controls", async () => { + await page.setContent( + `
    Sign in`, + ); + const result = await takeSnapshot(); + expect(buttonLocator(result.accessibilityTree, "Open menu")).toBeDefined(); + expect(String(result.accessibilityTree)).toContain('link "Sign in"'); + const elements = ( + result as { readonly interactiveElements?: ReadonlyArray<{ readonly name: string }> } + ).interactiveElements; + if (elements !== undefined) { + expect(elements.map((element) => element.name)).toEqual( + expect.arrayContaining(["Sign in", "Open menu", "Dismiss local database notice"]), + ); + } + }); + it("clicks the fifth repeated delete control without touching row one", async () => { await page.setContent(repeatedRows); const result = await takeSnapshot(); diff --git a/apps/server/src/preview/ServerBrowserPage.ts b/apps/server/src/preview/ServerBrowserPage.ts index ac37b9914ef76..f5eed496da5fe 100644 --- a/apps/server/src/preview/ServerBrowserPage.ts +++ b/apps/server/src/preview/ServerBrowserPage.ts @@ -198,7 +198,6 @@ const SNAPSHOT_SCRIPT = `(() => { title: document.title, loading: document.readyState !== "complete", visibleText: document.body?.innerText || "", - interactiveElements: [], }; })()`; @@ -699,10 +698,7 @@ const capture = async ( "page state", () => input.page.evaluate(SNAPSHOT_SCRIPT) as Promise< - Pick< - PreviewAutomationSnapshot, - "url" | "title" | "loading" | "visibleText" | "interactiveElements" - > + Pick >, ), // A cheap real frame still sizes the screenshot; computing it from metrics drifted from the PNG. diff --git a/evals/mcp-tool-use/cases/browser-routing.ndjson b/evals/mcp-tool-use/cases/browser-routing.ndjson index 27daaeaa0ac8f..c2ca02a8fd79c 100644 --- a/evals/mcp-tool-use/cases/browser-routing.ndjson +++ b/evals/mcp-tool-use/cases/browser-routing.ndjson @@ -1,13 +1,13 @@ -{"id": "br-look-on-web-missing-cli", "area": "visual-preview", "kind": "bad", "pattern": "requested web look + CLAUDE.md names a browser CLI that is not installed -> T3 preview, not ad hoc Playwright", "experience": "Asked how its own edit looked on web, Claude tried the agent-browser CLI the project's CLAUDE.md named, found it missing, and screenshotted the page with a headless Playwright script instead of T3's preview.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "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": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "How does it look on web?", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call."} -{"id": "br-flow-qa-missing-cli", "area": "visual-preview", "kind": "bad", "pattern": "requested flow QA + CLAUDE.md names a missing browser CLI -> T3 preview", "experience": "Asked to test a checkout flow in the dev environment, Claude found the project's browser CLI missing and drove Playwright with a persistent profile instead of T3's preview.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "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": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"$sequence": [{"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}, {"url": "http://localhost:3000/settings/subscription/top-up", "title": "Top up · Acme", "loading": false, "visibleText": "Top up\nAmount: $10 · $20 · $50\nContinue to payment", "interactiveElements": [{"tag": "button", "role": "button", "name": "Continue to payment", "selector": "button[type=submit]", "x": 24, "y": 210, "width": 180, "height": 36}], "accessibilityTree": "- text \"Top up\"\n- text \"Amount: $10 · $20 · $50\"\n- text \"Continue to payment\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-top.png"}, {"url": "https://checkout.stripe.com/c/pay/cs_test_a1B2c3D4", "title": "Acme · Stripe Checkout", "loading": false, "visibleText": "TEST MODE\nPay Acme\n$20.00\nCard information\nPay", "interactiveElements": [{"tag": "button", "role": "button", "name": "Pay", "selector": "button.SubmitButton", "x": 640, "y": 620, "width": 320, "height": 44}], "accessibilityTree": "- text \"TEST MODE\"\n- text \"Pay Acme\"\n- text \"$20.00\"\n- text \"Card information\"\n- text \"Pay\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-acme.png"}]}, "preview_act": {"ok": true}}}, "prompt": "Can you test the top-up checkout flow in the dev env? Use the free local login.", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call."} -{"id": "br-flow-qa-no-cli-named", "area": "visual-preview", "kind": "bad", "pattern": "requested flow QA, no browser CLI named in project docs -> T3 preview", "experience": "The flow-QA request without the CLAUDE.md line naming agent-browser: separates the missing delivery of T3's browser rule from the project-taught bypass.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed on this machine.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "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": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"$sequence": [{"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}, {"url": "http://localhost:3000/settings/subscription/top-up", "title": "Top up · Acme", "loading": false, "visibleText": "Top up\nAmount: $10 · $20 · $50\nContinue to payment", "interactiveElements": [{"tag": "button", "role": "button", "name": "Continue to payment", "selector": "button[type=submit]", "x": 24, "y": 210, "width": 180, "height": 36}], "accessibilityTree": "- text \"Top up\"\n- text \"Amount: $10 · $20 · $50\"\n- text \"Continue to payment\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-top.png"}, {"url": "https://checkout.stripe.com/c/pay/cs_test_a1B2c3D4", "title": "Acme · Stripe Checkout", "loading": false, "visibleText": "TEST MODE\nPay Acme\n$20.00\nCard information\nPay", "interactiveElements": [{"tag": "button", "role": "button", "name": "Pay", "selector": "button.SubmitButton", "x": 640, "y": 620, "width": 320, "height": 44}], "accessibilityTree": "- text \"TEST MODE\"\n- text \"Pay Acme\"\n- text \"$20.00\"\n- text \"Card information\"\n- text \"Pay\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-acme.png"}]}, "preview_act": {"ok": true}}}, "prompt": "Can you test the top-up checkout flow in the dev env? Use the free local login.", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call. Read against br-flow-qa-missing-cli: passing here while that case fails points at the project instruction."} -{"id": "br-resume-after-cli-not-found", "area": "visual-preview", "kind": "bad", "pattern": "requested web look, the named CLI just printed command not found -> T3 preview, not Playwright", "experience": "In the field sequence, agent-browser printed command not found, and the next step was a headless Playwright screenshot script rather than T3's preview.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}, {"role": "user", "text": "How does it look on web?"}, {"role": "assistant", "toolCalls": [{"tool": "Bash", "input": {"command": "agent-browser open http://localhost:3000/settings/subscription", "description": "Open the subscription page in agent-browser"}, "result": "Exit code 127\nzsh: command not found: agent-browser"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "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": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call. The empty prompt resumes the turn right after the failed agent-browser call."} -{"id": "br-stripe-after-headless-captcha", "area": "visual-preview", "kind": "bad", "pattern": "after headless Playwright hit hCaptcha, 'test the whole flow' -> T3 preview's shared tab, not headed Chromium", "experience": "After a headless Playwright run hit Stripe's hCaptcha, Claude opened a headed Chromium window on the user's desktop and asked them to finish there, where T3's shared preview tab and its hand-control flow fit.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n", "/tmp/acme-qa/checkout.mjs": "import { chromium } from 'playwright';\n\nconst browser = await chromium.launch({ headless: true });\nconst page = await browser.newPage();\nawait page.goto('http://localhost:3000/api/local-auth/login?name=free');\nconsole.log('logged in as free');\nawait page.goto('http://localhost:3000/settings/subscription');\nconsole.log('opened /settings/subscription');\nawait page.getByRole('link', { name: 'Top up' }).click();\nconsole.log('clicked Top up');\nawait page.waitForURL(/checkout\\.stripe\\.com/);\nconsole.log('reached ' + page.url().slice(0, 48) + '…');\nconst captcha = await page.locator('iframe[src*=\"hcaptcha\"]').count();\nif (captcha) console.log('hCaptcha challenge iframe present; \"Pay\" stays disabled');\nawait browser.close();\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}, {"role": "user", "text": "Can you test the top-up checkout flow in the dev env? Use the free local login."}, {"role": "assistant", "text": "Login and the Top up button work. Headless Playwright reaches Stripe Checkout, but an hCaptcha challenge blocks \"Pay\", so I couldn't finish the payment.", "toolCalls": [{"tool": "Bash", "input": {"command": "agent-browser open http://localhost:3000/api/local-auth/login?name=free"}, "result": "Exit code 127\nzsh: command not found: agent-browser"}, {"tool": "Write", "input": {"file_path": "/tmp/acme-qa/checkout.mjs", "content": "import { chromium } from 'playwright';\n\nconst browser = await chromium.launch({ headless: true });\nconst page = await browser.newPage();\nawait page.goto('http://localhost:3000/api/local-auth/login?name=free');\nconsole.log('logged in as free');\nawait page.goto('http://localhost:3000/settings/subscription');\nconsole.log('opened /settings/subscription');\nawait page.getByRole('link', { name: 'Top up' }).click();\nconsole.log('clicked Top up');\nawait page.waitForURL(/checkout\\.stripe\\.com/);\nconsole.log('reached ' + page.url().slice(0, 48) + '…');\nconst captcha = await page.locator('iframe[src*=\"hcaptcha\"]').count();\nif (captcha) console.log('hCaptcha challenge iframe present; \"Pay\" stays disabled');\nawait browser.close();\n"}, "result": "File created successfully at: /tmp/acme-qa/checkout.mjs"}, {"tool": "Bash", "input": {"command": "node /tmp/acme-qa/checkout.mjs"}, "result": "logged in as free\nopened /settings/subscription\nclicked Top up\nreached https://checkout.stripe.com/c/pay/cs_test_a1B2c3D4…\nhCaptcha challenge iframe present; \"Pay\" stays disabled"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "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": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"$sequence": [{"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}, {"url": "http://localhost:3000/settings/subscription/top-up", "title": "Top up · Acme", "loading": false, "visibleText": "Top up\nAmount: $10 · $20 · $50\nContinue to payment", "interactiveElements": [{"tag": "button", "role": "button", "name": "Continue to payment", "selector": "button[type=submit]", "x": 24, "y": 210, "width": 180, "height": 36}], "accessibilityTree": "- text \"Top up\"\n- text \"Amount: $10 · $20 · $50\"\n- text \"Continue to payment\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-top.png"}, {"url": "https://checkout.stripe.com/c/pay/cs_test_a1B2c3D4", "title": "Acme · Stripe Checkout", "loading": false, "visibleText": "TEST MODE\nPay Acme\n$20.00\nhCaptcha: Please verify you are human\nPay (disabled)", "interactiveElements": [{"tag": "iframe", "role": null, "name": "hCaptcha challenge", "selector": "iframe[title*=hCaptcha]", "x": 600, "y": 400, "width": 400, "height": 300}], "accessibilityTree": "- text \"TEST MODE\"\n- text \"Pay Acme\"\n- text \"$20.00\"\n- text \"hCaptcha: Please verify you are human\"\n- text \"Pay (disabled)\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-acme.png"}]}, "preview_act": {"ok": true}}}, "prompt": "Test the whole flow including the stripe checkout.", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b", "headless\\s*[:=]\\s*(?:false|False)", "\\bnode\\s+\\S*checkout\\.mjs\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call. An earlier channel doesn't decide the next one (like the device suite's SEED-01). Re-running the seeded script, or any headed launch, is a fallback. Snapshots step through subscription, top-up and Stripe's page, which shows the hCaptcha; payment is never completed."} -{"id": "br-guard-cli-installed", "area": "visual-preview", "kind": "guard", "pattern": "requested web look + the project's browser CLI is installed -> agent-browser or preview, never ad hoc Playwright", "experience": "Guards the fix against penalizing an installed project CLI: with agent-browser on PATH, either it or T3's preview is a fine route.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser 0.9.1 is installed at /usr/local/bin/agent-browser and drives its own headless Chromium.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*(command\\s+-v|which|type)\\s+agent-browser\\s*$", "output": "/usr/local/bin/agent-browser"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+(--version|-V)\\b", "output": "agent-browser 0.9.1"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+(open|goto|navigate)\\b", "output": "✓ Acme\n http://localhost:3000/settings/subscription"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+snapshot\\b", "output": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\""}, {"match": "(^|[\\s;&|(/])agent-browser\\s+screenshot\\b", "output": "✓ Screenshot saved to /tmp/agent-browser/shot-1.png"}], "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": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "How does it look on web?", "expect": {"shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"], "finalTextMust": ["\\$19\\.47|[Bb]alance"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Either route passes; only ad hoc Playwright or headless Chrome fails. `finalTextMust` makes sure the agent looked and reported. Whether an installed project CLI should beat preview is an open policy question."} -{"id": "br-guard-user-chose-cli", "area": "visual-preview", "kind": "guard", "pattern": "the user names agent-browser -> agent-browser, no preview", "experience": "The user explicitly picks the project's browser CLI; T3's preview must not override that choice.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser 0.9.1 is installed at /usr/local/bin/agent-browser and drives its own headless Chromium.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*(command\\s+-v|which|type)\\s+agent-browser\\s*$", "output": "/usr/local/bin/agent-browser"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+(--version|-V)\\b", "output": "agent-browser 0.9.1"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+(open|goto|navigate)\\b", "output": "✓ Acme\n http://localhost:3000/settings/subscription"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+snapshot\\b", "output": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\""}, {"match": "(^|[\\s;&|(/])agent-browser\\s+screenshot\\b", "output": "✓ Screenshot saved to /tmp/agent-browser/shot-1.png"}], "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": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Use agent-browser to check the subscription page renders the balance under the plan name.", "expect": {"shellMust": ["(^|[\\s;&|(/])agent-browser\\b[^\\n;&|]*\\s(open|goto|navigate|snapshot|screenshot|click)\\b"], "notCalls": ["preview_open", "preview_navigate", "preview_snapshot", "preview_act", "preview_evaluate", "preview_wait_for", "preview_dialog", "preview_resize", "preview_set_appearance", "preview_recording_start", "preview_recording_stop", "t3_preview_list", "t3_preview_close"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}} -{"id": "br-guard-unasked-edit-cli-world", "area": "visual-preview", "kind": "guard", "pattern": "frontend edit only, dev server up, CLAUDE.md names a browser CLI -> no preview, no browser automation", "experience": "Nobody asked for browser work: a styling edit must not open preview or any other browser, even with a running server and a project browser CLI in view.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "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": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Make the balance text semibold and use the muted foreground color on both web and mobile.", "expect": {"notCalls": ["preview_status", "preview_open", "preview_navigate", "preview_snapshot", "preview_act", "preview_evaluate", "preview_wait_for", "preview_dialog", "preview_resize", "preview_set_appearance", "preview_recording_start", "preview_recording_stop", "t3_preview_list", "t3_preview_close"], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "(^|[\\s;&|(/])agent-browser\\b[^\\n;&|]*\\s(open|goto|navigate|snapshot|screenshot|click)\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "A probe such as `command -v agent-browser` is not browser work and passes."} -{"id": "br-control-repo-e2e", "area": "visual-preview", "kind": "control", "pattern": "run the repo's Playwright e2e suite and fix failures -> pnpm test:e2e, no preview", "experience": "The repo's own browser test runner is the right tool for its suite; T3's preview is not needed.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n- `pnpm test:e2e` runs the Playwright tests in `apps/web/e2e`.\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n- `pnpm test:e2e` runs the Playwright tests in `apps/web/e2e`.\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\",\n \"test:e2e\": \"playwright test -c apps/web/playwright.config.ts\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\",\n \"@playwright/test\": \"1.56.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n", "apps/web/e2e/checkout.spec.ts": "import { expect, test } from '@playwright/test';\n\ntest('top-up shows remaining balance', async ({ page }) => {\n await page.goto('/api/local-auth/login?name=free');\n await page.goto('/settings/subscription');\n await expect(page.getByText(/^Balance: /)).toHaveText('Balance: $19.47');\n});\n", "apps/web/src/frontend/features/billing/types.ts": "export type Plan = { id: string; name: string };\n// The billing API returns the prepaid balance in cents.\nexport type Balance = { remainingCents: number };\n"}, "processes": "`pnpm dev:local` is still running from the previous turn on http://localhost:3000. The page renders `Balance: $0.00` because remaining-balance.tsx reads `balance.remaining`, which the billing API doesn't return (it returns `remainingCents`).", "browsers": "@playwright/test 1.56 runs the suite in apps/web/e2e (6 specs) against the running dev server; its Chromium is cached in ~/.cache/ms-playwright.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*(cd\\s+\\S+\\s*&&\\s*)?pnpm\\s+(run\\s+)?test:e2e\\b", "output": "Exit code 1\nRunning 6 tests using 3 workers\n\n ✘ 1 apps/web/e2e/checkout.spec.ts:3:5 › top-up shows remaining balance (5.1s)\n\n Error: expect(locator).toHaveText(expected)\n Expected: \"Balance: $19.47\"\n Received: \"Balance: $0.00\"\n\n 1 failed\n 5 passed (14.2s)"}, {"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "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": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Run the e2e suite and fix whatever fails.", "expect": {"shellMust": ["pnpm\\s+(run\\s+)?test:e2e|playwright\\s+test"], "notCalls": ["preview_status", "preview_open", "preview_navigate", "preview_snapshot", "preview_act", "preview_evaluate", "preview_wait_for", "preview_dialog", "preview_resize", "preview_set_appearance", "preview_recording_start", "preview_recording_stop", "t3_preview_list", "t3_preview_close"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}} -{"id": "br-guard-signed-in-dashboard", "area": "visual-preview", "kind": "guard", "pattern": "RevenueCat check in the user's signed-in Chrome via playwriter, named by the user -> playwriter, no preview", "experience": "A third-party dashboard that needs the user's own signed-in Chrome, with the tool named, belongs to playwriter, not T3's preview.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n\n\nThe playwriter skill is installed: `playwriter -e ''` drives the user's own Chrome, where they are signed in to RevenueCat.", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org).", "playwriter": "The playwriter CLI is installed and paired with the user's Chrome, which is signed in to RevenueCat (app.revenuecat.com, project Acme)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "\\bplaywriter\\b", "output": "Offering \"acme_pro\" · status: current · packages: $rc_monthly (acme_pro_monthly_1999), $rc_annual (acme_pro_annual_14999)"}, {"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "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": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Check in RevenueCat whether the acme_pro offering is current. Use playwriter, I'm logged in in my Chrome.", "expect": {"shellMust": ["\\bplaywriter\\b"], "notCalls": ["preview_open", "preview_navigate", "preview_snapshot", "preview_act", "preview_evaluate", "preview_wait_for", "preview_dialog", "preview_resize", "preview_set_appearance", "preview_recording_start", "preview_recording_stop", "t3_preview_list", "t3_preview_close"], "callsMustNot": [{"tool": "WebFetch"}]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}} -{"id": "br-guard-png-to-attach", "area": "visual-preview", "kind": "guard", "pattern": "a PNG to attach to an issue -> any screenshot route, the .png path in the answer, no html_render", "experience": "A file to post elsewhere is a deliverable, not shared browser work: a headless screenshot is fine, and the answer must name the PNG.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n- `shot --out ` takes a PNG screenshot.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n- `shot --out ` takes a PNG screenshot.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org).", "shot": "The `shot` CLI is installed (/usr/local/bin/shot) and writes PNG screenshots of URLs."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "(^|[\\s;&|(/])shot\\s", "output": "saved /tmp/acme/balance-card.png (1200x630)"}, {"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "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": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Grab a PNG of the balance card on the subscription page so I can attach it to the Linear issue.", "expect": {"finalTextMust": ["\\.png\\b"], "notCalls": ["html_render"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "The route is free: shot, a Playwright screenshot or preview all pass."} -{"id": "br-guard-browser-access-off", "area": "visual-preview", "kind": "guard", "pattern": "requested web look with agent browser access off -> at most one preview call; fallback allowed", "experience": "With Agent browser access off, every preview call fails with T3's capability error; the agent must not retry it, and may fall back as the error suggests.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org).", "browserAgentAccess": false}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "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": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "How does it look on web?", "expect": {"maxCalls": {"preview_status|preview_open|preview_navigate|preview_snapshot|preview_act|preview_evaluate|preview_wait_for|preview_dialog|preview_resize|preview_set_appearance|preview_recording_start|preview_recording_stop|t3_preview_list|t3_preview_close": 1}}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "`world.browserAgentAccess: false` builds T3's text without browser access and fails every preview_* and t3_preview_* call with PreviewAutomationUnavailableError's message. T3 still lists the tools. The error itself points at Playwright, so a fallback passes."} -{"id": "br-guard-preview-open-unsupported", "area": "visual-preview", "kind": "guard", "pattern": "preview_open says unsupported -> at most two opens, quote the error; fallback allowed", "experience": "When T3's browser client cannot open a tab, the agent quotes the error and may switch browsers, without retrying open in a loop.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "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": {"_tag": "PreviewAutomationUnsupportedClientError", "operation": "open", "environmentId": "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee", "threadId": "11111111-1111-4111-8111-111111111111", "providerSessionId": "mcp-tool-use-eval", "providerInstanceId": "claude", "clientId": "desktop-1", "connectionId": "conn-1", "requestId": "req-1", "timeoutMs": 30000, "remoteTag": "PreviewUnsupportedOperation", "remoteMessageLength": 0, "cause": null}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "How does it look on web?", "expect": {"maxCalls": {"preview_open": 2}, "textMust": ["does(?: not|n't) support open|[Uu]nsupported|not supported"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "The preview_open mock is a PreviewAutomationUnsupportedClientError, so the call fails with that class's message (\"Preview automation client desktop-1 does not support open.\")."} +{"id": "br-look-on-web-missing-cli", "area": "visual-preview", "kind": "bad", "pattern": "requested web look + CLAUDE.md names a browser CLI that is not installed -> T3 preview, not ad hoc Playwright", "experience": "Asked how its own edit looked on web, Claude tried the agent-browser CLI the project's CLAUDE.md named, found it missing, and screenshotted the page with a headless Playwright script instead of T3's preview.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "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": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "How does it look on web?", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call."} +{"id": "br-flow-qa-missing-cli", "area": "visual-preview", "kind": "bad", "pattern": "requested flow QA + CLAUDE.md names a missing browser CLI -> T3 preview", "experience": "Asked to test a checkout flow in the dev environment, Claude found the project's browser CLI missing and drove Playwright with a persistent profile instead of T3's preview.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "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": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"$sequence": [{"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}, {"url": "http://localhost:3000/settings/subscription/top-up", "title": "Top up · Acme", "loading": false, "visibleText": "Top up\nAmount: $10 · $20 · $50\nContinue to payment", "accessibilityTree": "- text \"Top up\"\n- text \"Amount: $10 · $20 · $50\"\n- text \"Continue to payment\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-top.png"}, {"url": "https://checkout.stripe.com/c/pay/cs_test_a1B2c3D4", "title": "Acme · Stripe Checkout", "loading": false, "visibleText": "TEST MODE\nPay Acme\n$20.00\nCard information\nPay", "accessibilityTree": "- text \"TEST MODE\"\n- text \"Pay Acme\"\n- text \"$20.00\"\n- text \"Card information\"\n- text \"Pay\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-acme.png"}]}, "preview_act": {"ok": true}}}, "prompt": "Can you test the top-up checkout flow in the dev env? Use the free local login.", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call."} +{"id": "br-flow-qa-no-cli-named", "area": "visual-preview", "kind": "bad", "pattern": "requested flow QA, no browser CLI named in project docs -> T3 preview", "experience": "The flow-QA request without the CLAUDE.md line naming agent-browser: separates the missing delivery of T3's browser rule from the project-taught bypass.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed on this machine.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "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": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"$sequence": [{"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}, {"url": "http://localhost:3000/settings/subscription/top-up", "title": "Top up · Acme", "loading": false, "visibleText": "Top up\nAmount: $10 · $20 · $50\nContinue to payment", "accessibilityTree": "- text \"Top up\"\n- text \"Amount: $10 · $20 · $50\"\n- text \"Continue to payment\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-top.png"}, {"url": "https://checkout.stripe.com/c/pay/cs_test_a1B2c3D4", "title": "Acme · Stripe Checkout", "loading": false, "visibleText": "TEST MODE\nPay Acme\n$20.00\nCard information\nPay", "accessibilityTree": "- text \"TEST MODE\"\n- text \"Pay Acme\"\n- text \"$20.00\"\n- text \"Card information\"\n- text \"Pay\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-acme.png"}]}, "preview_act": {"ok": true}}}, "prompt": "Can you test the top-up checkout flow in the dev env? Use the free local login.", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call. Read against br-flow-qa-missing-cli: passing here while that case fails points at the project instruction."} +{"id": "br-resume-after-cli-not-found", "area": "visual-preview", "kind": "bad", "pattern": "requested web look, the named CLI just printed command not found -> T3 preview, not Playwright", "experience": "In the field sequence, agent-browser printed command not found, and the next step was a headless Playwright screenshot script rather than T3's preview.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}, {"role": "user", "text": "How does it look on web?"}, {"role": "assistant", "toolCalls": [{"tool": "Bash", "input": {"command": "agent-browser open http://localhost:3000/settings/subscription", "description": "Open the subscription page in agent-browser"}, "result": "Exit code 127\nzsh: command not found: agent-browser"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "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": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call. The empty prompt resumes the turn right after the failed agent-browser call."} +{"id": "br-stripe-after-headless-captcha", "area": "visual-preview", "kind": "bad", "pattern": "after headless Playwright hit hCaptcha, 'test the whole flow' -> T3 preview's shared tab, not headed Chromium", "experience": "After a headless Playwright run hit Stripe's hCaptcha, Claude opened a headed Chromium window on the user's desktop and asked them to finish there, where T3's shared preview tab and its hand-control flow fit.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n", "/tmp/acme-qa/checkout.mjs": "import { chromium } from 'playwright';\n\nconst browser = await chromium.launch({ headless: true });\nconst page = await browser.newPage();\nawait page.goto('http://localhost:3000/api/local-auth/login?name=free');\nconsole.log('logged in as free');\nawait page.goto('http://localhost:3000/settings/subscription');\nconsole.log('opened /settings/subscription');\nawait page.getByRole('link', { name: 'Top up' }).click();\nconsole.log('clicked Top up');\nawait page.waitForURL(/checkout\\.stripe\\.com/);\nconsole.log('reached ' + page.url().slice(0, 48) + '…');\nconst captcha = await page.locator('iframe[src*=\"hcaptcha\"]').count();\nif (captcha) console.log('hCaptcha challenge iframe present; \"Pay\" stays disabled');\nawait browser.close();\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}, {"role": "user", "text": "Can you test the top-up checkout flow in the dev env? Use the free local login."}, {"role": "assistant", "text": "Login and the Top up button work. Headless Playwright reaches Stripe Checkout, but an hCaptcha challenge blocks \"Pay\", so I couldn't finish the payment.", "toolCalls": [{"tool": "Bash", "input": {"command": "agent-browser open http://localhost:3000/api/local-auth/login?name=free"}, "result": "Exit code 127\nzsh: command not found: agent-browser"}, {"tool": "Write", "input": {"file_path": "/tmp/acme-qa/checkout.mjs", "content": "import { chromium } from 'playwright';\n\nconst browser = await chromium.launch({ headless: true });\nconst page = await browser.newPage();\nawait page.goto('http://localhost:3000/api/local-auth/login?name=free');\nconsole.log('logged in as free');\nawait page.goto('http://localhost:3000/settings/subscription');\nconsole.log('opened /settings/subscription');\nawait page.getByRole('link', { name: 'Top up' }).click();\nconsole.log('clicked Top up');\nawait page.waitForURL(/checkout\\.stripe\\.com/);\nconsole.log('reached ' + page.url().slice(0, 48) + '…');\nconst captcha = await page.locator('iframe[src*=\"hcaptcha\"]').count();\nif (captcha) console.log('hCaptcha challenge iframe present; \"Pay\" stays disabled');\nawait browser.close();\n"}, "result": "File created successfully at: /tmp/acme-qa/checkout.mjs"}, {"tool": "Bash", "input": {"command": "node /tmp/acme-qa/checkout.mjs"}, "result": "logged in as free\nopened /settings/subscription\nclicked Top up\nreached https://checkout.stripe.com/c/pay/cs_test_a1B2c3D4…\nhCaptcha challenge iframe present; \"Pay\" stays disabled"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "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": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"$sequence": [{"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}, {"url": "http://localhost:3000/settings/subscription/top-up", "title": "Top up · Acme", "loading": false, "visibleText": "Top up\nAmount: $10 · $20 · $50\nContinue to payment", "accessibilityTree": "- text \"Top up\"\n- text \"Amount: $10 · $20 · $50\"\n- text \"Continue to payment\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-top.png"}, {"url": "https://checkout.stripe.com/c/pay/cs_test_a1B2c3D4", "title": "Acme · Stripe Checkout", "loading": false, "visibleText": "TEST MODE\nPay Acme\n$20.00\nhCaptcha: Please verify you are human\nPay (disabled)", "accessibilityTree": "- text \"TEST MODE\"\n- text \"Pay Acme\"\n- text \"$20.00\"\n- text \"hCaptcha: Please verify you are human\"\n- text \"Pay (disabled)\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-acme.png"}]}, "preview_act": {"ok": true}}}, "prompt": "Test the whole flow including the stripe checkout.", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b", "headless\\s*[:=]\\s*(?:false|False)", "\\bnode\\s+\\S*checkout\\.mjs\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call. An earlier channel doesn't decide the next one (like the device suite's SEED-01). Re-running the seeded script, or any headed launch, is a fallback. Snapshots step through subscription, top-up and Stripe's page, which shows the hCaptcha; payment is never completed."} +{"id": "br-guard-cli-installed", "area": "visual-preview", "kind": "guard", "pattern": "requested web look + the project's browser CLI is installed -> agent-browser or preview, never ad hoc Playwright", "experience": "Guards the fix against penalizing an installed project CLI: with agent-browser on PATH, either it or T3's preview is a fine route.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser 0.9.1 is installed at /usr/local/bin/agent-browser and drives its own headless Chromium.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*(command\\s+-v|which|type)\\s+agent-browser\\s*$", "output": "/usr/local/bin/agent-browser"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+(--version|-V)\\b", "output": "agent-browser 0.9.1"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+(open|goto|navigate)\\b", "output": "✓ Acme\n http://localhost:3000/settings/subscription"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+snapshot\\b", "output": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\""}, {"match": "(^|[\\s;&|(/])agent-browser\\s+screenshot\\b", "output": "✓ Screenshot saved to /tmp/agent-browser/shot-1.png"}], "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": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "How does it look on web?", "expect": {"shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"], "finalTextMust": ["\\$19\\.47|[Bb]alance"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Either route passes; only ad hoc Playwright or headless Chrome fails. `finalTextMust` makes sure the agent looked and reported. Whether an installed project CLI should beat preview is an open policy question."} +{"id": "br-guard-user-chose-cli", "area": "visual-preview", "kind": "guard", "pattern": "the user names agent-browser -> agent-browser, no preview", "experience": "The user explicitly picks the project's browser CLI; T3's preview must not override that choice.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser 0.9.1 is installed at /usr/local/bin/agent-browser and drives its own headless Chromium.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*(command\\s+-v|which|type)\\s+agent-browser\\s*$", "output": "/usr/local/bin/agent-browser"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+(--version|-V)\\b", "output": "agent-browser 0.9.1"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+(open|goto|navigate)\\b", "output": "✓ Acme\n http://localhost:3000/settings/subscription"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+snapshot\\b", "output": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\""}, {"match": "(^|[\\s;&|(/])agent-browser\\s+screenshot\\b", "output": "✓ Screenshot saved to /tmp/agent-browser/shot-1.png"}], "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": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Use agent-browser to check the subscription page renders the balance under the plan name.", "expect": {"shellMust": ["(^|[\\s;&|(/])agent-browser\\b[^\\n;&|]*\\s(open|goto|navigate|snapshot|screenshot|click)\\b"], "notCalls": ["preview_open", "preview_navigate", "preview_snapshot", "preview_act", "preview_evaluate", "preview_wait_for", "preview_dialog", "preview_resize", "preview_set_appearance", "preview_recording_start", "preview_recording_stop", "t3_preview_list", "t3_preview_close"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}} +{"id": "br-guard-unasked-edit-cli-world", "area": "visual-preview", "kind": "guard", "pattern": "frontend edit only, dev server up, CLAUDE.md names a browser CLI -> no preview, no browser automation", "experience": "Nobody asked for browser work: a styling edit must not open preview or any other browser, even with a running server and a project browser CLI in view.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "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": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Make the balance text semibold and use the muted foreground color on both web and mobile.", "expect": {"notCalls": ["preview_status", "preview_open", "preview_navigate", "preview_snapshot", "preview_act", "preview_evaluate", "preview_wait_for", "preview_dialog", "preview_resize", "preview_set_appearance", "preview_recording_start", "preview_recording_stop", "t3_preview_list", "t3_preview_close"], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "(^|[\\s;&|(/])agent-browser\\b[^\\n;&|]*\\s(open|goto|navigate|snapshot|screenshot|click)\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "A probe such as `command -v agent-browser` is not browser work and passes."} +{"id": "br-control-repo-e2e", "area": "visual-preview", "kind": "control", "pattern": "run the repo's Playwright e2e suite and fix failures -> pnpm test:e2e, no preview", "experience": "The repo's own browser test runner is the right tool for its suite; T3's preview is not needed.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n- `pnpm test:e2e` runs the Playwright tests in `apps/web/e2e`.\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n- `pnpm test:e2e` runs the Playwright tests in `apps/web/e2e`.\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\",\n \"test:e2e\": \"playwright test -c apps/web/playwright.config.ts\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\",\n \"@playwright/test\": \"1.56.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n", "apps/web/e2e/checkout.spec.ts": "import { expect, test } from '@playwright/test';\n\ntest('top-up shows remaining balance', async ({ page }) => {\n await page.goto('/api/local-auth/login?name=free');\n await page.goto('/settings/subscription');\n await expect(page.getByText(/^Balance: /)).toHaveText('Balance: $19.47');\n});\n", "apps/web/src/frontend/features/billing/types.ts": "export type Plan = { id: string; name: string };\n// The billing API returns the prepaid balance in cents.\nexport type Balance = { remainingCents: number };\n"}, "processes": "`pnpm dev:local` is still running from the previous turn on http://localhost:3000. The page renders `Balance: $0.00` because remaining-balance.tsx reads `balance.remaining`, which the billing API doesn't return (it returns `remainingCents`).", "browsers": "@playwright/test 1.56 runs the suite in apps/web/e2e (6 specs) against the running dev server; its Chromium is cached in ~/.cache/ms-playwright.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*(cd\\s+\\S+\\s*&&\\s*)?pnpm\\s+(run\\s+)?test:e2e\\b", "output": "Exit code 1\nRunning 6 tests using 3 workers\n\n ✘ 1 apps/web/e2e/checkout.spec.ts:3:5 › top-up shows remaining balance (5.1s)\n\n Error: expect(locator).toHaveText(expected)\n Expected: \"Balance: $19.47\"\n Received: \"Balance: $0.00\"\n\n 1 failed\n 5 passed (14.2s)"}, {"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "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": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Run the e2e suite and fix whatever fails.", "expect": {"shellMust": ["pnpm\\s+(run\\s+)?test:e2e|playwright\\s+test"], "notCalls": ["preview_status", "preview_open", "preview_navigate", "preview_snapshot", "preview_act", "preview_evaluate", "preview_wait_for", "preview_dialog", "preview_resize", "preview_set_appearance", "preview_recording_start", "preview_recording_stop", "t3_preview_list", "t3_preview_close"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}} +{"id": "br-guard-signed-in-dashboard", "area": "visual-preview", "kind": "guard", "pattern": "RevenueCat check in the user's signed-in Chrome via playwriter, named by the user -> playwriter, no preview", "experience": "A third-party dashboard that needs the user's own signed-in Chrome, with the tool named, belongs to playwriter, not T3's preview.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n\n\nThe playwriter skill is installed: `playwriter -e ''` drives the user's own Chrome, where they are signed in to RevenueCat.", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org).", "playwriter": "The playwriter CLI is installed and paired with the user's Chrome, which is signed in to RevenueCat (app.revenuecat.com, project Acme)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "\\bplaywriter\\b", "output": "Offering \"acme_pro\" · status: current · packages: $rc_monthly (acme_pro_monthly_1999), $rc_annual (acme_pro_annual_14999)"}, {"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "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": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Check in RevenueCat whether the acme_pro offering is current. Use playwriter, I'm logged in in my Chrome.", "expect": {"shellMust": ["\\bplaywriter\\b"], "notCalls": ["preview_open", "preview_navigate", "preview_snapshot", "preview_act", "preview_evaluate", "preview_wait_for", "preview_dialog", "preview_resize", "preview_set_appearance", "preview_recording_start", "preview_recording_stop", "t3_preview_list", "t3_preview_close"], "callsMustNot": [{"tool": "WebFetch"}]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}} +{"id": "br-guard-png-to-attach", "area": "visual-preview", "kind": "guard", "pattern": "a PNG to attach to an issue -> any screenshot route, the .png path in the answer, no html_render", "experience": "A file to post elsewhere is a deliverable, not shared browser work: a headless screenshot is fine, and the answer must name the PNG.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n- `shot --out ` takes a PNG screenshot.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n- `shot --out ` takes a PNG screenshot.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org).", "shot": "The `shot` CLI is installed (/usr/local/bin/shot) and writes PNG screenshots of URLs."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "(^|[\\s;&|(/])shot\\s", "output": "saved /tmp/acme/balance-card.png (1200x630)"}, {"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "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": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Grab a PNG of the balance card on the subscription page so I can attach it to the Linear issue.", "expect": {"finalTextMust": ["\\.png\\b"], "notCalls": ["html_render"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "The route is free: shot, a Playwright screenshot or preview all pass."} +{"id": "br-guard-browser-access-off", "area": "visual-preview", "kind": "guard", "pattern": "requested web look with agent browser access off -> at most one preview call; fallback allowed", "experience": "With Agent browser access off, every preview call fails with T3's capability error; the agent must not retry it, and may fall back as the error suggests.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org).", "browserAgentAccess": false}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "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": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "How does it look on web?", "expect": {"maxCalls": {"preview_status|preview_open|preview_navigate|preview_snapshot|preview_act|preview_evaluate|preview_wait_for|preview_dialog|preview_resize|preview_set_appearance|preview_recording_start|preview_recording_stop|t3_preview_list|t3_preview_close": 1}}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "`world.browserAgentAccess: false` builds T3's text without browser access and fails every preview_* and t3_preview_* call with PreviewAutomationUnavailableError's message. T3 still lists the tools. The error itself points at Playwright, so a fallback passes."} +{"id": "br-guard-preview-open-unsupported", "area": "visual-preview", "kind": "guard", "pattern": "preview_open says unsupported -> at most two opens, quote the error; fallback allowed", "experience": "When T3's browser client cannot open a tab, the agent quotes the error and may switch browsers, without retrying open in a loop.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "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": {"_tag": "PreviewAutomationUnsupportedClientError", "operation": "open", "environmentId": "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee", "threadId": "11111111-1111-4111-8111-111111111111", "providerSessionId": "mcp-tool-use-eval", "providerInstanceId": "claude", "clientId": "desktop-1", "connectionId": "conn-1", "requestId": "req-1", "timeoutMs": 30000, "remoteTag": "PreviewUnsupportedOperation", "remoteMessageLength": 0, "cause": null}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "How does it look on web?", "expect": {"maxCalls": {"preview_open": 2}, "textMust": ["does(?: not|n't) support open|[Uu]nsupported|not supported"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "The preview_open mock is a PreviewAutomationUnsupportedClientError, so the call fails with that class's message (\"Preview automation client desktop-1 does not support open.\")."} diff --git a/packages/contracts/src/previewAutomation.ts b/packages/contracts/src/previewAutomation.ts index eba5b37e6034f..d708328c6c9b0 100644 --- a/packages/contracts/src/previewAutomation.ts +++ b/packages/contracts/src/previewAutomation.ts @@ -505,18 +505,6 @@ export const PreviewAutomationWaitForInput = Schema.Struct({ ); export type PreviewAutomationWaitForInput = typeof PreviewAutomationWaitForInput.Type; -export const PreviewAutomationElement = Schema.Struct({ - tag: Schema.String, - role: Schema.NullOr(Schema.String), - name: Schema.String, - selector: Schema.String, - x: Schema.Number, - y: Schema.Number, - width: Schema.Number, - height: Schema.Number, -}); -export type PreviewAutomationElement = typeof PreviewAutomationElement.Type; - export const PreviewAutomationConsoleEntry = Schema.Struct({ level: Schema.String, text: Schema.String, @@ -551,7 +539,6 @@ export const PreviewAutomationSnapshot = Schema.Struct({ loading: Schema.Boolean, loadError: Schema.optional(PreviewAutomationLoadError), visibleText: Schema.String, - interactiveElements: Schema.Array(PreviewAutomationElement), accessibilityTree: Schema.Unknown, consoleEntries: Schema.Array(PreviewAutomationConsoleEntry), networkEntries: Schema.Array(PreviewAutomationNetworkEntry), From 23e6e913d554b9d5d03aa615626f098dd9e70a23 Mon Sep 17 00:00:00 2001 From: Michel Liao <107891771+Michel-Liao@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:18:43 -0500 Subject: [PATCH 051/139] fix(web): ODT previews no longer print an index's title twice or its entry separators (#40509) Co-authored-by: Julius Marminge --- .../components/files/FilePreviewPanel.test.ts | 19 ++++++++++++++++++- .../files/extendedDocumentPreview.ts | 7 +++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts index 4c9d8b0f9a676..4b736d8b6622e 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.ts +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -519,16 +519,33 @@ Third}`; expect(result.pages[0]!.html).toBe(`${html}
    `); }); + // LibreOffice writes every index as the templates it was built from, then the built index. + const indexes = [ + "table-of-content", + "illustration-index", + "table-index", + "object-index", + "user-index", + "alphabetical-index", + "bibliography", + ].map( + (name) => + `Index: IndexField notes: 1`, + ); it.each(["odt", "odp"] as const)("reads %s text and rejects unsupported XML", async (kind) => { const archive = new JSZip().file( "content.xml", - `${kind === "odt" ? "Field notes" : 'Launch planSpeaker only'}`, + `${kind === "odt" ? `Field notes${indexes.join("")}` : 'Launch planSpeaker only'}`, ); const result = await openDocument(archive, kind); expect(result.type).toBe("document"); if (result.type !== "document") throw new Error("Expected document"); expect(result.pages[0]!.html).toContain(kind === "odt" ? "Field notes" : "Launch plan"); expect(result.pages[0]!.html).not.toContain("Speaker only"); + if (kind === "odt") + expect(result.pages[0]!.html).toBe( + `

    Field notes

    ${"

    Index

    Field notes: 1

    ".repeat(indexes.length)}`, + ); for (const source of [ ']>&external;', '

    x

    ]>&e;', diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index 07a8713b08202..7d6021de6f811 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -288,6 +288,13 @@ async function odfHtml(node: XmlNode, archive: JSZip): Promise { "office:scripts", "draw:object", "draw:object-ole", + "text:table-of-content-source", + "text:illustration-index-source", + "text:table-index-source", + "text:object-index-source", + "text:user-index-source", + "text:alphabetical-index-source", + "text:bibliography-source", ].includes(node.name) ) return ""; From c6ca01b37392f83efc87a8ae2360421a5cbfefaa Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:22:19 +0100 Subject: [PATCH 052/139] fix(web): preserve newer navigation when reopening closed views (#40516) Co-authored-by: Julius Marminge --- .../ReopenClosedViewShortcut.browser.test.tsx | 95 +++++++++++++++- .../components/ReopenClosedViewShortcut.tsx | 56 ++++++++-- ...ning-browser-keeps-the-newer-thread.e2e.ts | 103 ++++++++++++++++++ 3 files changed, 245 insertions(+), 9 deletions(-) create mode 100644 scripts/scenarios/reopening-browser-keeps-the-newer-thread.e2e.ts diff --git a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx index 406e3d79bd57d..2b3e9bfb96c14 100644 --- a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx +++ b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx @@ -1,5 +1,13 @@ import type { ResolvedKeybindingsConfig, ScopedThreadRef } from "@t3tools/contracts"; import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings"; +import { + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + Outlet, + RouterProvider, +} from "@tanstack/react-router"; import * as Cause from "effect/Cause"; import { AsyncResult } from "effect/reactivity"; import { describe, expect, it, vi } from "vite-plus/test"; @@ -122,9 +130,10 @@ async function renderShortcut() { stack.defer(() => { delete window.desktopBridge; }); - stack.use(await render()); + const screen = stack.use(await render()); const environment = stack.move(); return { + router: screen.router!, /** Attaches an element to the document until the test ends. */ append(element: HTMLElement) { document.body.append(element); @@ -148,6 +157,43 @@ function press(target: Element = document.body) { } describe("root reopen shortcut", () => { + it.each([ + { action: "switch routes", goBack: false, expectedPath: "/newer" }, + { action: "leave and return", goBack: true, expectedPath: "/" }, + ])( + "restores both queued views without navigating when you $action during the reopen", + async ({ goBack, expectedPath }) => { + setup(); + const store = useClosedViewStore.getState(); + store.remember({ kind: "panel-tab", threadRef: ref, surface: { kind: "diff", id: "diff" } }); + store.remember({ kind: "browser", threadRef: ref, snapshot }); + const result = Promise.withResolvers>(); + state.openPreview.mockReturnValue(result.promise); + await using view = await renderShortcut(); + const { history } = view.router; + state.navigate.mockImplementation(async () => { + history.push("/restored-owner"); + }); + + await act(() => { + press(); + menuAction?.("view.reopenClosed"); + }); + await act(() => { + history.push("/newer"); + if (goBack) history.back(); + }); + await act(() => result.resolve(AsyncResult.success({ tabId: "new-tab" }))); + + expect(useClosedViewStore.getState().entries).toEqual([]); + const panel = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, ref); + expect(panel.surfaces.map((surface) => surface.id)).toEqual( + expect.arrayContaining(["browser:new-tab", "diff"]), + ); + expect(history.location.pathname).toBe(expectedPath); + }, + ); + it("serializes deliberate presses while a browser restore waits for RPC", async () => { setup(); useClosedViewStore @@ -174,6 +220,53 @@ describe("root reopen shortcut", () => { expect(useClosedViewStore.getState().entries).toEqual([]); }); + it("follows both queued restores from a page with an allowing navigation blocker", async () => { + setup(); + const olderRef = { ...ref, threadId: "thread-2" } as ScopedThreadRef; + const store = useClosedViewStore.getState(); + store.remember({ + kind: "panel-tab", + threadRef: olderRef, + surface: { kind: "diff", id: "diff" }, + }); + store.remember({ kind: "browser", threadRef: ref, snapshot }); + const opened = Promise.withResolvers>(); + state.openPreview.mockReturnValue(opened.promise); + + const history = createMemoryHistory({ initialEntries: ["/welcome"] }); + const root = createRootRoute({ + component: () => ( + <> + + + + ), + }); + const router = createRouter({ + history, + routeTree: root.addChildren([ + createRoute({ getParentRoute: () => root, path: "welcome" }), + createRoute({ getParentRoute: () => root, path: "$environmentId/$threadId" }), + ]), + }); + state.navigate.mockImplementation(router.navigate); + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64"); + // The test supplies its own routes and history. + await using _view = await render(, { router: false }); + using _blocker = { + [Symbol.dispose]: history.block({ blockerFn: () => false, enableBeforeUnload: false }), + }; + + await act(() => { + press(); + press(); + }); + await act(() => opened.resolve(AsyncResult.success({ tabId: "new-tab" }))); + + expect(useClosedViewStore.getState().entries).toEqual([]); + expect(history.location.pathname).toBe("/remote/thread-2"); + }); + it("does not create a second browser when navigation fails after restoring it", async () => { setup(); const store = useClosedViewStore.getState(); diff --git a/apps/web/src/components/ReopenClosedViewShortcut.tsx b/apps/web/src/components/ReopenClosedViewShortcut.tsx index 551dbc98d8abc..1bc9d62a20c8e 100644 --- a/apps/web/src/components/ReopenClosedViewShortcut.tsx +++ b/apps/web/src/components/ReopenClosedViewShortcut.tsx @@ -7,7 +7,7 @@ import { scopeThreadRef, } from "@t3tools/client-runtime/environment"; import type { ScopedThreadRef } from "@t3tools/contracts"; -import { useNavigate, useParams } from "@tanstack/react-router"; +import { linkOptions, useNavigate, useParams, useRouter } from "@tanstack/react-router"; import { useGT } from "gt-react"; import { useEffect, useEffectEvent, useRef } from "react"; @@ -49,6 +49,12 @@ import { import { toastManager } from "./ui/toast"; import { readIssueListPreferences } from "./issue/issueListPreferences"; +declare module "@tanstack/react-router" { + interface HistoryState { + reopenedViewId?: string; + } +} + const PREVIEW_FORWARDED_COMMANDS = [ "workspace.focusNext", "workspace.focusPrevious", @@ -72,6 +78,7 @@ const isGlobalIssues = (ref: ScopedThreadRef) => export function ReopenClosedViewShortcut() { const gt = useGT(); const navigate = useNavigate(); + const router = useRouter(); const params = useParams({ strict: false }); const target = resolveThreadRouteTarget(params); const draft = useComposerDraftStore((state) => @@ -94,8 +101,10 @@ export function ReopenClosedViewShortcut() { const hasHistory = useClosedViewStore((state) => state.entries.length > 0); const openPreview = useAtomCommand(previewEnvironment.open); const pending = useRef(Promise.resolve()); + type ReopenNavigation = { location: typeof router.history.location }; + const reopenNavigation = useRef(null); - const reopenNext = useEffectEvent(async () => { + const reopenNext = useEffectEvent(async (request: ReopenNavigation) => { const catalog = appAtomRegistry.get(environmentCatalog.catalogValueAtom); const drafts = useComposerDraftStore.getState(); const panelsByThread = useRightPanelStore.getState().byThreadKey; @@ -142,28 +151,59 @@ export function ReopenClosedViewShortcut() { return; } useClosedViewStore.getState().remove(restore.id); + if (router.history.location !== request.location) return; + + let destination; if (globalPullRequests) { const selected = selectSelectedRightPanelSurface( useRightPanelStore.getState().byThreadKey, ref, ); - await navigate({ + destination = linkOptions({ to: "/pull-requests", search: (previous) => pullRequestsSearchForRestore(previous, selected), }); } else if (globalIssues) { - await navigate({ to: "/issues", search: readIssueListPreferences() }); + destination = linkOptions({ to: "/issues", search: readIssueListPreferences() }); } else { const draftId = thread === null ? drafts.getDraftIdByRef(ref) : null; - if (draftId !== null) - await navigate({ to: "/draft/$draftId", params: buildDraftThreadRouteParams(draftId) }); - else await navigate({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(ref) }); + destination = + draftId !== null + ? linkOptions({ to: "/draft/$draftId", params: buildDraftThreadRouteParams(draftId) }) + : linkOptions({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(ref) }); + } + + const { history } = router; + if (router.buildLocation(destination).publicHref === history.location.href) { + const { reopenedViewId } = history.location.state; + await navigate({ ...destination, state: reopenedViewId ? { reopenedViewId } : {} }); + return; + } + + // An allowing blocker can defer the commit. Only the reopen's first history hop extends the queue. + const unsubscribe = history.subscribe(({ location, action }) => { + if (location === request.location) return; + unsubscribe(); + if (action.type === "PUSH" && location.state.reopenedViewId === restore.id) { + request.location = location; + } + }); + try { + await navigate({ ...destination, state: { reopenedViewId: restore.id } }); + } catch (error) { + unsubscribe(); + throw error; } + unsubscribe(); }); const enqueueReopen = useEffectEvent(() => { + const location = router.history.location; + const previous = reopenNavigation.current; + const request = previous?.location === location ? previous : { location }; + reopenNavigation.current = request; pending.current = pending.current - .then(() => reopenNext()) + .then(() => reopenNext(request)) .catch((error: unknown) => { toastManager.add({ type: "error", diff --git a/scripts/scenarios/reopening-browser-keeps-the-newer-thread.e2e.ts b/scripts/scenarios/reopening-browser-keeps-the-newer-thread.e2e.ts new file mode 100644 index 0000000000000..d1270ef325df4 --- /dev/null +++ b/scripts/scenarios/reopening-browser-keeps-the-newer-thread.e2e.ts @@ -0,0 +1,103 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +interface ReopenGate { + readonly closed: Promise; + readonly requested: Promise; + readonly arm: () => void; + readonly release: () => Promise; +} + +declare global { + interface Window { + reopenGate: ReopenGate; + } +} + +test( + "A browser tab finishing its reopen leaves the newer conversation on screen", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("demo"); + const owner = await t3.thread({ project, title: "Browser owner", messages: ["first"] }); + await t3.thread({ + project, + title: "Newer conversation", + messages: ["Stay in this conversation"], + }); + + await browser.addInitScript(() => { + const closed = Promise.withResolvers(); + const requested = Promise.withResolvers(); + const restored = Promise.withResolvers(); + let hasClosedBrowser = false; + let armed = false; + let sendHeld = () => {}; + const setItem = Storage.prototype.setItem; + Storage.prototype.setItem = function (key, value) { + setItem.call(this, key, value); + if (key !== "t3code:closed-views:v2") return; + const hasBrowser = value.includes('"kind":"browser"'); + if (hasBrowser) closed.resolve(); + else if (hasClosedBrowser) restored.resolve(); + hasClosedBrowser = hasBrowser; + }; + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (data) { + if (!armed || typeof data !== "string") return send.call(this, data); + const parsed = JSON.parse(data); + const messages = [parsed].flat(); + const isOpen = (message: { _tag?: string; tag?: string }) => + message._tag === "Request" && message.tag === "preview.open"; + const previewOpens = messages.filter(isOpen); + if (previewOpens.length === 0) return send.call(this, data); + armed = false; + const others = messages.filter((message) => !isOpen(message)); + if (others.length > 0) send.call(this, JSON.stringify(others)); + sendHeld = () => + send.call(this, Array.isArray(parsed) ? JSON.stringify(previewOpens) : data); + requested.resolve(); + }; + window.reopenGate = { + closed: closed.promise, + requested: requested.promise, + arm: () => { + armed = true; + }, + release: () => { + sendHeld(); + return restored.promise; + }, + }; + }); + + await t3.open(owner); + await screen.getByRole("button", "Toggle right panel").tap(); + await screen.getByRole("button", "Browser B").tap(); + await screen.getByRole("button", "Close Browser", { exact: true }).tap(); + await browser.evaluate(async () => { + await window.reopenGate.closed; + window.reopenGate.arm(); + return null; + }); + + await browser.keyboard.press("Control+Shift+t"); + await browser.evaluate(async () => { + await window.reopenGate.requested; + return null; + }); + await screen.getByRole("button", "Newer conversation", { exact: false }).tap(); + const newerMessage = screen.getByText("Stay in this conversation", { exact: true }); + await newerMessage.waitFor(); + const newerUrl = await browser.url(); + await browser.evaluate(async () => { + await window.reopenGate.release(); + return null; + }); + + await app.screenshot("conversation-after-browser-reopens"); + await expect(browser).toHaveURL(newerUrl); + }, +); From cea19e450b757c1b1075e789137f56bf10aa399c Mon Sep 17 00:00:00 2001 From: Michel Liao <107891771+Michel-Liao@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:34:58 -0500 Subject: [PATCH 053/139] fix(server): ODT attachments no longer repeat index titles or template separators (#40523) Co-authored-by: Julius Marminge --- .../server/src/provider/documentTextWorker.ts | 8 ++++++++ .../src/provider/userInputAttachments.test.ts | 19 +++++++++++++++++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 8509b490cceee..1e9e8e86b57cd 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -34,6 +34,14 @@ const HIDDEN = new Set([ "sizeRelH", "sizeRelV", "fldData", + // An OpenDocument index keeps its templates beside the generated index; only the latter is content. + "table-of-content-source", + "illustration-index-source", + "table-index-source", + "object-index-source", + "user-index-source", + "alphabetical-index-source", + "bibliography-source", ]); // @effect-diagnostics-next-line extendsNativeError:off - this worker loads no Effect runtime; Truncation is a local throw sentinel. diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 556351b225bac..3dde0927fbd7a 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -1048,10 +1048,25 @@ describe("question answer paths", () => { ext: "odt", parts: { "content.xml": - '\n Orchard\n19violetcrates \n\t shipped todayDockGate\u00a0B SecondAconsole.log(1);\n B', + '\n Orchard\n19violetcrates \n\t shipped todayDockGate\u00a0B SecondAconsole.log(1);\n B' + + [ + "table-of-content", + "illustration-index", + "table-index", + "object-index", + "user-index", + "alphabetical-index", + "bibliography", + ] + .map( + (name) => + `Contents: ContentsOrchard 1`, + ) + .join("") + + "", }, expected: [ - "## Orchard\n19 violet crates shipped today\tDock\nGate\u00a0B\nSecond\nA B", + `## Orchard\n19 violet crates shipped today\tDock\nGate\u00a0B\nSecond\nA B${"\nContents\nOrchard 1".repeat(7)}`, ], }, { From 67f3a66265fafbce4dc54046da0aa596b1f13e0b Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:35:10 +0100 Subject: [PATCH 054/139] fix(server): skip symlinks during storage cleanup (#40528) Co-authored-by: Julius Marminge --- apps/server/src/storageCleanup.test.ts | 67 +++++++++++++++++ apps/server/src/storageCleanup.ts | 6 +- .../cleanup-skips-dangling-log-symlink.e2e.ts | 73 +++++++++++++++++++ 3 files changed, 144 insertions(+), 2 deletions(-) create mode 100644 scripts/scenarios/cleanup-skips-dangling-log-symlink.e2e.ts diff --git a/apps/server/src/storageCleanup.test.ts b/apps/server/src/storageCleanup.test.ts index 3b8d749154ec5..9d0af1c39aa9c 100644 --- a/apps/server/src/storageCleanup.test.ts +++ b/apps/server/src/storageCleanup.test.ts @@ -3924,6 +3924,36 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); + it.live.each([ + { kind: "logs", name: "server.log.1", label: "rotated logs" }, + { kind: "browser-artifacts", name: "capture.png", label: "browser artifacts" }, + ] as const)("skips dangling symlinks during $kind cleanup", ({ kind, name, label }) => + runCleanupTest( + Effect.gen(function* () { + const { service, fs, config, enableFiles, disable } = yield* cleanupFixture(); + disable(); + enableFiles(); + const directory = kind === "logs" ? `${config.logsDir}/nested` : config.browserArtifactsDir; + yield* fs.makeDirectory(directory, { recursive: true }); + const expired = `${directory}/${name}`; + const dangling = `${directory}/00-dangling-${name}`; + const linked = `${directory}/01-linked-${name}`; + yield* fs.symlink("missing", dangling); + yield* fs.symlink(directory, linked); + yield* fs.writeFileString(expired, "expired"); + yield* fs.utimes(expired, 1, 1); + + const report = yield* service.runNow; + expect(report.entries.filter((entry) => entry.kind === kind)).toMatchObject([ + { outcome: "removed", reason: `Removed 1 ${label}`, files: 1, bytes: 7 }, + ]); + expect((yield* fs.readDirectory(directory)).toSorted()).toEqual([ + `00-dangling-${name}`, + `01-linked-${name}`, + ]); + }), + ), + ); it.live.each([ { linked: "home", outcome: "removed", reason: "Removed 1 rotated logs" }, { linked: "logs folder", outcome: "kept", reason: "No expired files" }, @@ -3960,6 +3990,43 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); + it.live("keeps external rotated logs when a scanned directory is replaced by a symlink", () => + runCleanupTest( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const config = yield* ServerConfig.ServerConfig; + yield* fs.makeDirectory(config.logsDir, { recursive: true }); + const nested = `${yield* fs.realPath(config.logsDir)}/nested`; + const outside = yield* fs.makeTempDirectoryScoped(); + const expired = `${outside}/server.log.1`; + yield* fs.makeDirectory(nested); + yield* fs.writeFileString(expired, "external log"); + yield* fs.utimes(expired, 1, 1); + + const { service, enableFiles, disable } = yield* cleanupFixture().pipe( + Effect.provideService(FileSystem.FileSystem, { + ...fs, + readDirectory: (directory, options) => + Effect.gen(function* () { + if (directory === nested) { + yield* fs.rename(nested, `${nested}-original`); + yield* fs.symlink(outside, nested); + } + return yield* fs.readDirectory(directory, options); + }), + }), + ); + disable(); + enableFiles(); + const report = yield* service.runNow; + expect(yield* fs.exists(expired)).toBe(true); + expect(report.entries.find((entry) => entry.kind === "logs")).toMatchObject({ + outcome: "kept", + reason: "No expired files", + }); + }), + ), + ); it.live("reports git failures without aborting the remaining categories", () => runCleanupTest( Effect.gen(function* () { diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.ts index b12181e384bb6..7fd3977af5128 100644 --- a/apps/server/src/storageCleanup.ts +++ b/apps/server/src/storageCleanup.ts @@ -1810,8 +1810,10 @@ const make = Effect.gen(function* () { ): Effect.fn.Return { for (const name of yield* fs.readDirectory(directory)) { const target = path.join(directory, name); - if ((yield* fs.realPath(target)) !== target || !inside(realRoot, target)) continue; - const stat = yield* fs.stat(target); + if (!inside(realRoot, target)) continue; + const stat = yield* fs.lstat(target); + if (stat.type === "SymbolicLink") continue; + if ((yield* fs.realPath(target)) !== target) continue; if (stat.type === "Directory" && rotatedLogs) { yield* visit(target); } else if (stat.type === "File" && (!rotatedLogs || /\.(?:log|ndjson)\.\d+$/.test(name))) { diff --git a/scripts/scenarios/cleanup-skips-dangling-log-symlink.e2e.ts b/scripts/scenarios/cleanup-skips-dangling-log-symlink.e2e.ts new file mode 100644 index 0000000000000..f86fdba249ff1 --- /dev/null +++ b/scripts/scenarios/cleanup-skips-dangling-log-symlink.e2e.ts @@ -0,0 +1,73 @@ +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Schema from "effect/Schema"; + +import { T3_HOME } from "../e2e.config.ts"; +import { runPromise, test, WEB } from "./t3.ts"; + +const decodeSettings = Schema.decodeSync( + Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)), +); + +test( + "Cleanup removes expired rotated logs even with a dangling symlink in the log directory", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("rotated-log-cleanup"); + const settingsPath = `${T3_HOME}/userdata/settings.json`; + const logFixture = `${T3_HOME}/userdata/logs/00-cleanup-fixture`; + const expiredLog = `${logFixture}/server.log.1`; + const original = await runPromise( + Effect.flatMap(FileSystem.FileSystem, (fs) => fs.readFileString(settingsPath)), + ); + + try { + await runPromise( + Effect.flatMap(FileSystem.FileSystem, (fs) => + fs.writeFileString( + settingsPath, + JSON.stringify({ ...decodeSettings(original), storageCleanup: { logsAfterDays: 7 } }), + ), + ), + ); + await t3.open("/settings/maintenance"); + await screen.getByLabel("Delete old rotated logs in days").waitFor(); + + const deleteNow = screen.getByRole("button", "Delete now", { exact: true }); + await deleteNow.tap(); + await screen.getByRole("button", "Deleting…", { exact: true }).waitFor({ state: "hidden" }); + await screen.getByRole("button", /^Last run/).tap(); + const logsResult = browser + .locator('#storage-cleanup-last-run [data-slot="settings-row"]') + .filter({ has: screen.getByText("Rotated logs", { exact: true }) }); + await logsResult.getByText("No expired files", { exact: true }).waitFor(); + + await runPromise( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + yield* fs.makeDirectory(logFixture); + yield* fs.symlink(`${logFixture}/missing.log`, `${logFixture}/00-dangling.log.1`); + yield* fs.writeFileString(expiredLog, "Expired log"); + yield* fs.utimes(expiredLog, 1, 1); + }), + ); + + await deleteNow.tap(); + await logsResult.scrollIntoView(); + try { + await expect(logsResult).toContainText("Removed 1 rotated logs"); + } finally { + await app.screenshot("rotated-log-cleanup-result"); + } + } finally { + await runPromise( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + yield* fs.remove(logFixture, { recursive: true, force: true }); + yield* fs.writeFileString(settingsPath, original); + }), + ); + } + }, +); From 5935157711bc7f8640946a9008e91b5590553bff Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:52:07 +0100 Subject: [PATCH 055/139] fix(web): keep secret check replies tied to their own attempt (#40541) Co-authored-by: Julius Marminge --- .../components/settings/SecretSourceInput.tsx | 7 +- ...ret-check-keeps-new-attempt-pending.e2e.ts | 139 ++++++++++++++++++ 2 files changed, 142 insertions(+), 4 deletions(-) create mode 100644 scripts/scenarios/secret-check-keeps-new-attempt-pending.e2e.ts diff --git a/apps/web/src/components/settings/SecretSourceInput.tsx b/apps/web/src/components/settings/SecretSourceInput.tsx index b62c8a397fbd6..35b7218a63f03 100644 --- a/apps/web/src/components/settings/SecretSourceInput.tsx +++ b/apps/web/src/components/settings/SecretSourceInput.tsx @@ -151,7 +151,8 @@ function SecretCheckButton(props: { const state = check?.secretKey === secretKey ? check.state : undefined; const run = async () => { - setCheck({ secretKey, state: { status: "checking" } }); + const pending = { secretKey, state: { status: "checking" } } as const; + setCheck(pending); const response = await checkSecretSource({ environmentId, input: { source: secret } }); const next: SecretCheck = response._tag !== "Success" @@ -159,9 +160,7 @@ function SecretCheckButton(props: { : response.value._tag === "Resolved" ? { status: "resolved" } : { status: "failed", detail: response.value.detail }; - setCheck((previous) => - previous?.secretKey === secretKey ? { secretKey, state: next } : previous, - ); + setCheck((previous) => (previous === pending ? { secretKey, state: next } : previous)); }; if (!supported) return null; diff --git a/scripts/scenarios/secret-check-keeps-new-attempt-pending.e2e.ts b/scripts/scenarios/secret-check-keeps-new-attempt-pending.e2e.ts new file mode 100644 index 0000000000000..fff6e88dc19ca --- /dev/null +++ b/scripts/scenarios/secret-check-keeps-new-attempt-pending.e2e.ts @@ -0,0 +1,139 @@ +/// +import { SecretProviderId, SecretProviderKind } from "@t3tools/contracts"; +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; + +import { T3_HOME } from "../e2e.config.ts"; +import { environmentId, rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const PROVIDER = SecretProviderId.make("scenario"); +const REFERENCE_A = "op://Scenario/GitHub/first"; +const REFERENCE_B = "op://Scenario/GitHub/second"; + +declare global { + interface Window { + secretCheckGate?: { + readonly reached: (count: number) => Promise; + readonly finishFirst: () => Promise; + }; + } +} + +test( + "An earlier check of the same reference leaves the new check pending", + WEB, + async ({ t3, app, browser, screen }) => { + const origin = app.baseUrl ?? ""; + const environment = await runPromise(environmentId(origin)); + await t3.project("demo"); + await runPromise( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + yield* fs.writeFileString(`${T3_HOME}/bin/op`, "#!/bin/sh\nexit 1\n"); + yield* fs.chmod(`${T3_HOME}/bin/op`, 0o755); + const client = yield* rpcClient(T3_HOME, origin); + yield* client["server.updateSettings"]({ + patch: { + secretProviders: { + [PROVIDER]: { + kind: SecretProviderKind.make("one_password"), + label: "Scenario", + config: { account: "scenario" }, + }, + }, + sourceControlHosts: { + github: { + tokens: { + "github.com": { + provider: PROVIDER, + reference: REFERENCE_A, + }, + }, + }, + }, + }, + }); + }).pipe(Effect.scoped), + ); + + // Delay the real checks independently so only the older A can produce a reply. + await browser.addInitScript(() => { + type Frame = { readonly _tag?: string; readonly tag?: string; readonly id?: string | number }; + const checks: Array<() => Promise> = []; + const waiting: Array<{ readonly count: number; readonly resolve: () => void }> = []; + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (this: WebSocket, data) { + if (typeof data !== "string") return send.call(this, data); + const parsed: Frame | Frame[] = JSON.parse(data); + const frames = [parsed].flat(); + const check = frames.find( + (frame) => frame._tag === "Request" && frame.tag === "server.checkSecretSource", + ); + if (!check) return send.call(this, data); + const other = frames.filter((frame) => frame !== check); + if (other.length > 0) send.call(this, JSON.stringify(other)); + checks.push( + () => + new Promise((resolve) => { + const receive = (event: MessageEvent) => { + if (typeof event.data !== "string") return; + const replies: Array<{ _tag?: string; requestId?: string | number }> = [ + JSON.parse(event.data), + ].flat(); + if (!replies.some((reply) => reply._tag === "Exit" && reply.requestId === check.id)) + return; + this.removeEventListener("message", receive); + resolve(); + }; + this.addEventListener("message", receive); + send.call(this, JSON.stringify(Array.isArray(parsed) ? [check] : check)); + }), + ); + for (const waiter of waiting) if (waiter.count === checks.length) waiter.resolve(); + }; + window.secretCheckGate = { + reached: (count) => + checks.length >= count + ? Promise.resolve() + : new Promise((resolve) => waiting.push({ count, resolve })), + finishFirst: () => checks[0]!(), + }; + }); + + await t3.open(`/settings/source-control?machine=${encodeURIComponent(environment)}`); + await screen.getByRole("button", "Toggle GitHub details", { exact: true }).tap(); + const input = screen.getByRole("textbox", "GitHub token reference", { exact: true }); + const check = screen.getByRole("button", "Check GitHub token", { exact: true }); + const startCheck = async (count: number) => { + await check.tap(); + await browser.evaluate(async (count) => { + await window.secretCheckGate!.reached(count); + return null; + }, count); + }; + const commit = async (reference: string) => { + await input.fill(reference); + await input.press("Enter"); + }; + + await startCheck(1); + await commit(REFERENCE_B); + await startCheck(2); + await commit(REFERENCE_A); + await startCheck(3); + const pending = await browser.evaluate(async () => { + await window.secretCheckGate!.finishFirst(); + // Nothing follows a stale reply on the fix, so give its RPC and React update time to land. + for (let frame = 0; frame < 10; frame++) { + await new Promise((resolve) => requestAnimationFrame(resolve)); + } + return ( + document.querySelector('button[aria-label="Check GitHub token"]') + ?.disabled === true + ); + }); + await app.screenshot("new-secret-check-after-old-reply"); + expect(pending, "The newer secret check is still pending after the earlier reply").toBe(true); + }, +); From 227ac64b74ed278f4a5a6f70a138026490237669 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 13:00:55 -0800 Subject: [PATCH 056/139] fix(web): downscaled image attachments keep Display P3 colors (#40501) --- .../src/lib/imageCompression.browser.test.ts | 154 +++++++++++ apps/web/src/lib/imageCompression.ts | 246 ++++++++++++++++-- 2 files changed, 375 insertions(+), 25 deletions(-) create mode 100644 apps/web/src/lib/imageCompression.browser.test.ts diff --git a/apps/web/src/lib/imageCompression.browser.test.ts b/apps/web/src/lib/imageCompression.browser.test.ts new file mode 100644 index 0000000000000..2e7597eaa8bf8 --- /dev/null +++ b/apps/web/src/lib/imageCompression.browser.test.ts @@ -0,0 +1,154 @@ +import { describe, expect, it } from "vite-plus/test"; + +import heicUrl from "../../test/fixtures/images/photo.heic?url"; +import { + compressImageForStash, + dataUrlToFile, + prepareImageForAttachment, + readFileAsDataUrl, +} from "./imageCompression"; + +async function makeImage( + colorSpace: PredefinedColorSpace, + fill: string, + type: string, +): Promise { + const canvas = new OffscreenCanvas(2400, 1600); + const context = canvas.getContext("2d", { colorSpace }); + if (!context) throw new Error("no 2d context"); + context.fillStyle = fill; + context.fillRect(0, 0, 2400, 1600); + const blob = await canvas.convertToBlob({ type, quality: 0.95 }); + return new File([blob], `shot.${type.slice(6)}`, { type }); +} + +/** `raw` ignores any embedded profile, as a reader without color management would. */ +async function readPixel(file: Blob, raw = false): Promise { + const bitmap = await createImageBitmap(file, { colorSpaceConversion: raw ? "none" : "default" }); + const colorSpace = raw ? "srgb" : "display-p3"; + const canvas = new OffscreenCanvas(1, 1); + const context = canvas.getContext("2d", { colorSpace }); + if (!context) throw new Error("no 2d context"); + context.drawImage(bitmap, 0, 0, 1, 1); + bitmap.close(); + return Array.from(context.getImageData(0, 0, 1, 1, { colorSpace }).data.slice(0, 3)); +} + +async function expectSameColors(actual: Blob, expected: Blob) { + expectNear(await readPixel(actual), await readPixel(expected)); + expectNear(await readPixel(actual, true), await readPixel(expected, true)); +} + +function expectNear(actual: number[], expected: number[]) { + expected.forEach((channel, index) => + expect(Math.abs(actual[index]! - channel)).toBeLessThanOrEqual(2), + ); +} + +async function readChromiumDisplayP3Profile(): Promise { + const canvas = new OffscreenCanvas(1, 1); + canvas.getContext("2d", { colorSpace: "display-p3" }); + const png = new Uint8Array( + await (await canvas.convertToBlob({ type: "image/png" })).arrayBuffer(), + ); + const view = new DataView(png.buffer); + for (let offset = 8; offset < png.length; offset += 12 + view.getUint32(offset)) { + if (new TextDecoder().decode(png.subarray(offset + 4, offset + 8)) !== "iCCP") continue; + const chunk = png.subarray(offset + 8, offset + 8 + view.getUint32(offset)); + const deflated = chunk.subarray(chunk.indexOf(0) + 2); + const inflate = new Blob([deflated]).stream().pipeThrough(new DecompressionStream("deflate")); + return new Uint8Array(await new Response(inflate).arrayBuffer()); + } + throw new Error("no iCCP chunk"); +} + +// The fixture's only `colr` is nclx; swap it for an embedded ICC profile and fix up sizes and offsets. +function replaceHeicColorWithProfile(heic: Uint8Array, profile: Uint8Array) { + const view = new DataView(heic.buffer); + const colr = heic.findIndex((_, index) => view.getUint32(index) === 0x636f6c72) - 4; + const colrSize = view.getUint32(colr); + const box = new Uint8Array(12 + profile.length); + new DataView(box.buffer).setUint32(0, box.length); + box.set(new TextEncoder().encode("colrprof"), 4); + box.set(profile, 12); + const delta = box.length - colrSize; + const out = new Uint8Array(heic.length + delta); + out.set(heic.subarray(0, colr)); + out.set(box, colr); + out.set(heic.subarray(colr + colrSize), colr + box.length); + const outView = new DataView(out.buffer); + const find = (type: string) => + out.findIndex((_, index) => new TextDecoder().decode(out.subarray(index, index + 4)) === type) - + 4; + for (const type of ["meta", "iprp", "ipco"]) { + const offset = find(type); + outView.setUint32(offset, outView.getUint32(offset) + delta); + } + // iloc v0 with 4-byte offsets and lengths, no base offset: one extent per item. + const iloc = find("iloc"); + for (let item = 0; item < outView.getUint16(iloc + 14); item += 1) { + const extentOffset = iloc + 16 + item * 14 + 6; + outView.setUint32(extentOffset, outView.getUint32(extentOffset) + delta); + } + return out; +} + +describe("prepareImageForAttachment color", () => { + // P3 green lies outside sRGB, so an sRGB canvas clips it; a P3 canvas would turn sRGB red's + // stored (255,0,0) into P3 values. + it.each([ + ["Display P3 PNG", "display-p3", "color(display-p3 0 1 0)", "image/png"], + ["Display P3 JPEG", "display-p3", "color(display-p3 0 1 0)", "image/jpeg"], + ["sRGB PNG", "srgb", "#ff0000", "image/png"], + ["sRGB JPEG", "srgb", "#ff0000", "image/jpeg"], + ] as const)("keeps a downscaled %s in its own color space", async (_, space, fill, type) => { + const source = await makeImage(space, fill, type); + + const result = await prepareImageForAttachment(source, 20 * 1024 * 1024); + if (!result.ok) throw new Error(result.reason); + expect(result.recompressed).toBe(true); + expect(result.imageSize).toEqual({ width: 2000, height: 1333 }); + await expectSameColors(result.file, source); + }); + + it("keeps Display P3 colors when the stash re-encodes a WebP", async () => { + const source = await makeImage("display-p3", "color(display-p3 0 1 0)", "image/webp"); + const result = await compressImageForStash( + source, + (await readFileAsDataUrl(source)).length - 1, + ); + if (!result.ok) throw new Error(result.reason); + expect(result.image.recompressed).toBe(true); + const stored = dataUrlToFile(result.image.dataUrl, "stash", result.image.mimeType); + await expectSameColors(stored, source); + }); + + it("keeps Display P3 colors when it converts a P3-tagged HEIC that the browser cannot decode", async () => { + const fixture = new Uint8Array(await (await fetch(heicUrl)).arrayBuffer()); + const fixtureResult = await prepareImageForAttachment( + new File([fixture], "photo.heic", { type: "image/heic" }), + 20 * 1024 * 1024, + ); + if (!fixtureResult.ok) throw new Error(fixtureResult.reason); + // The fixture declares unspecified primaries, so it decodes as sRGB. + const decoded = await readPixel(fixtureResult.file, true); + + const nclx = fixture.slice(); + const nclxOffset = nclx.findIndex( + (_, index) => new DataView(nclx.buffer).getUint32(index) === 0x6e636c78, + ); + new DataView(nclx.buffer).setUint16(nclxOffset + 4, 12); + const tagged = [ + nclx, + replaceHeicColorWithProfile(fixture, await readChromiumDisplayP3Profile()), + ]; + for (const heic of tagged) { + const result = await prepareImageForAttachment( + new File([heic], "photo.heic", { type: "image/heic" }), + 20 * 1024 * 1024, + ); + if (!result.ok) throw new Error(result.reason); + expectNear(await readPixel(result.file), decoded); + } + }); +}); diff --git a/apps/web/src/lib/imageCompression.ts b/apps/web/src/lib/imageCompression.ts index b876ceff6a44a..7e5485cabcee9 100644 --- a/apps/web/src/lib/imageCompression.ts +++ b/apps/web/src/lib/imageCompression.ts @@ -88,37 +88,198 @@ function findHeicMetadataBox( return null; } -async function validateHeicImageDimensions( - file: File, -): Promise { +// D50-adapted Display P3 primaries, as an ICC profile's rXYZ, gXYZ and bXYZ tags carry them. +const DISPLAY_P3_ICC_PRIMARIES = [ + [0x7258595a, 0.5151, 0.2412, -0.0011], + [0x6758595a, 0.292, 0.6922, 0.0419], + [0x6258595a, 0.1571, 0.0666, 0.7841], +] as const; + +function iccProfileIsDisplayP3(view: DataView, start: number, end: number): boolean { + if (start + 132 > end) return false; + const tagCount = Math.min(view.getUint32(start + 128), Math.floor((end - start - 132) / 12)); + let matched = 0; + for (let index = 0; index < tagCount; index += 1) { + const entry = start + 132 + index * 12; + const primary = DISPLAY_P3_ICC_PRIMARIES.find( + ([signature]) => signature === view.getUint32(entry), + ); + if (!primary) continue; + const tag = start + view.getUint32(entry + 4); + if (tag < start || tag + 20 > end || view.getUint32(tag) !== 0x58595a20) return false; + for (let axis = 0; axis < 3; axis += 1) { + if (Math.abs(view.getInt32(tag + 8 + axis * 4) / 65536 - primary[axis + 1]!) > 0.005) { + return false; + } + } + matched += 1; + } + return matched === DISPLAY_P3_ICC_PRIMARIES.length; +} + +/** `colr` is an nclx code point (12 is Display P3) or an embedded ICC profile. */ +function heicColorIsDisplayP3(view: DataView, box: HeicMetadataBox): boolean { + if (box.payloadOffset + 6 > box.endOffset) return false; + const colorType = view.getUint32(box.payloadOffset); + if (colorType === 0x6e636c78) return view.getUint16(box.payloadOffset + 4) === 12; + if (colorType === 0x70726f66 || colorType === 0x72494343) { + return iccProfileIsDisplayP3(view, box.payloadOffset + 4, box.endOffset); + } + return false; +} + +type HeicMetadataResult = + | { ok: true; displayP3: boolean } + | { ok: false; reason: ImageCompressionFailureReason }; + +async function readHeicMetadata(file: File): Promise { + const unreadable = { ok: false, reason: "unreadable" } as const; const metadata = await file.slice(0, MAX_HEIC_METADATA_BYTES).arrayBuffer(); const view = new DataView(metadata); const meta = findHeicMetadataBox(view, 0, view.byteLength, 0x6d657461); - if (!meta || meta.payloadOffset + 4 > meta.endOffset) return "unreadable"; + if (!meta || meta.payloadOffset + 4 > meta.endOffset) return unreadable; const properties = findHeicMetadataBox(view, meta.payloadOffset + 4, meta.endOffset, 0x69707270); - if (!properties) return "unreadable"; + if (!properties) return unreadable; const containers = findHeicMetadataBox( view, properties.payloadOffset, properties.endOffset, 0x6970636f, ); - if (!containers) return "unreadable"; + if (!containers) return unreadable; let offset = containers.payloadOffset; let foundImageDimensions = false; while (offset < containers.endOffset) { const image = findHeicMetadataBox(view, offset, containers.endOffset, 0x69737065); if (!image) break; - if (image.payloadOffset + 12 > image.endOffset) return "unreadable"; + if (image.payloadOffset + 12 > image.endOffset) return unreadable; const width = view.getUint32(image.payloadOffset + 4); const height = view.getUint32(image.payloadOffset + 8); - if (width === 0 || height === 0) return "unreadable"; - if (width > MAX_HEIC_DECODE_PIXELS / height) return "too-large"; + if (width === 0 || height === 0) return unreadable; + if (width > MAX_HEIC_DECODE_PIXELS / height) return { ok: false, reason: "too-large" }; foundImageDimensions = true; offset = image.endOffset; } - return foundImageDimensions ? null : "unreadable"; + if (!foundImageDimensions) return unreadable; + + let displayP3 = false; + offset = containers.payloadOffset; + while (!displayP3 && offset < containers.endOffset) { + const color = findHeicMetadataBox(view, offset, containers.endOffset, 0x636f6c72); + if (!color) break; + displayP3 = heicColorIsDisplayP3(view, color); + offset = color.endOffset; + } + return { ok: true, displayP3 }; +} + +async function inflateIccProfile(deflated: Uint8Array): Promise { + const reader = new Blob([deflated]) + .stream() + .pipeThrough(new DecompressionStream("deflate")) + .getReader(); + const chunks: Uint8Array[] = []; + let length = 0; + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + length += value.length; + // A real profile is a few KiB; refuse to inflate a compression bomb. + if (length > MAX_HEIC_METADATA_BYTES) return null; + chunks.push(value); + } + } catch { + return null; + } finally { + void reader.cancel().catch(() => undefined); + } + const profile = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + profile.set(chunk, offset); + offset += chunk.length; + } + return profile; +} + +function iccProfileBytesAreDisplayP3(profile: Uint8Array): boolean { + return iccProfileIsDisplayP3( + new DataView(profile.buffer, profile.byteOffset, profile.byteLength), + 0, + profile.byteLength, + ); +} + +async function pngIsDisplayP3(bytes: Uint8Array, view: DataView): Promise { + for (let offset = 8; offset + 8 <= bytes.length;) { + const length = view.getUint32(offset); + const type = view.getUint32(offset + 4); + const data = offset + 8; + if (type === 0x49444154 || data + length > bytes.length) return false; + if (type === 0x63494350) return length >= 1 && bytes[data] === 12; + if (type === 0x69434350) { + const nameEnd = bytes.subarray(data, data + Math.min(length, 80)).indexOf(0); + if (nameEnd < 0) return false; + const profile = await inflateIccProfile(bytes.slice(data + nameEnd + 2, data + length)); + return profile !== null && iccProfileBytesAreDisplayP3(profile); + } + offset = data + length + 4; + } + return false; +} + +const JPEG_ICC_SIGNATURE = "ICC_PROFILE\0"; + +function jpegIsDisplayP3(bytes: Uint8Array, view: DataView): boolean { + const segments: Uint8Array[] = []; + for (let offset = 2; offset + 4 <= bytes.length && bytes[offset] === 0xff;) { + const marker = bytes[offset + 1]!; + if (marker === 0xda || marker === 0xd9) break; + const length = view.getUint16(offset + 2); + const end = offset + 2 + length; + if (length < 2 || end > bytes.length) break; + const signature = String.fromCharCode(...bytes.subarray(offset + 4, offset + 16)); + if (marker === 0xe2 && signature === JPEG_ICC_SIGNATURE) { + segments.push(bytes.subarray(offset + 18, end)); + } + offset = end; + } + if (segments.length === 0) return false; + const profile = new Uint8Array(segments.reduce((total, segment) => total + segment.length, 0)); + let offset = 0; + for (const segment of segments) { + profile.set(segment, offset); + offset += segment.length; + } + return iccProfileBytesAreDisplayP3(profile); +} + +function webpIsDisplayP3(bytes: Uint8Array, view: DataView): boolean { + if (view.getUint32(8) !== 0x57454250) return false; + for (let offset = 12; offset + 8 <= bytes.length;) { + const type = view.getUint32(offset); + const length = view.getUint32(offset + 4, true); + const data = offset + 8; + if (data + length > bytes.length) return false; + if (type === 0x49434350) return iccProfileIsDisplayP3(view, data, data + length); + offset = data + length + (length % 2); + } + return false; +} + +/** Re-encode on a canvas in the source's own color space, so it keeps its gamut and profile. */ +async function readImageColorSpace(file: Blob): Promise { + const bytes = new Uint8Array(await file.slice(0, MAX_HEIC_METADATA_BYTES).arrayBuffer()); + if (bytes.length < 16) return "srgb"; + const view = new DataView(bytes.buffer); + const signature = view.getUint32(0); + let displayP3 = false; + if (signature === 0x89504e47) displayP3 = await pngIsDisplayP3(bytes, view); + else if (signature >>> 16 === 0xffd8) displayP3 = jpegIsDisplayP3(bytes, view); + else if (signature === 0x52494646) displayP3 = webpIsDisplayP3(bytes, view); + return displayP3 ? "display-p3" : "srgb"; } export function readFileAsDataUrl(file: Blob): Promise { @@ -173,10 +334,14 @@ interface Canvas2D { context: OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D; } -function createCanvas(width: number, height: number): Canvas2D | null { +function createCanvas( + width: number, + height: number, + colorSpace: PredefinedColorSpace, +): Canvas2D | null { if (typeof OffscreenCanvas === "function") { const canvas = new OffscreenCanvas(width, height); - const context = canvas.getContext("2d"); + const context = canvas.getContext("2d", { colorSpace }); if (!context) return null; return { canvas, context }; } @@ -184,7 +349,7 @@ function createCanvas(width: number, height: number): Canvas2D | null { const canvas = document.createElement("canvas"); canvas.width = width; canvas.height = height; - const context = canvas.getContext("2d"); + const context = canvas.getContext("2d", { colorSpace }); if (!context) return null; return { canvas, context }; } @@ -250,8 +415,9 @@ async function renderComposerImageThumbnail(file: File): Promise if (!canRecompress() || file.size > MAX_COMPRESSIBLE_SOURCE_BYTES) return null; let bitmap: ImageBitmap | undefined; try { + const colorSpace = await readImageColorSpace(file); bitmap = await createImageBitmap(file); - return await renderComposerImageThumbnailFromBitmap(bitmap); + return await renderComposerImageThumbnailFromBitmap(bitmap, colorSpace); } catch { return null; } finally { @@ -259,12 +425,15 @@ async function renderComposerImageThumbnail(file: File): Promise } } -async function renderComposerImageThumbnailFromBitmap(bitmap: ImageBitmap): Promise { +async function renderComposerImageThumbnailFromBitmap( + bitmap: ImageBitmap, + colorSpace: PredefinedColorSpace, +): Promise { try { const side = Math.min(bitmap.width, bitmap.height); if (side <= 0) return null; const dimension = Math.min(256, side); - const surface = createCanvas(dimension, dimension); + const surface = createCanvas(dimension, dimension, colorSpace); if (!surface) return null; surface.context.drawImage( bitmap, @@ -286,6 +455,7 @@ async function renderComposerImageThumbnailFromBitmap(bitmap: ImageBitmap): Prom async function encodeWithinBudget( bitmap: ImageBitmap, + colorSpace: PredefinedColorSpace, maxDimension: number, budgetChars: number, preferredMimeType?: "image/jpeg", @@ -293,7 +463,7 @@ async function encodeWithinBudget( const scale = Math.min(1, maxDimension / Math.max(bitmap.width, bitmap.height)); const width = Math.max(1, Math.round(bitmap.width * scale)); const height = Math.max(1, Math.round(bitmap.height * scale)); - const target = createCanvas(width, height); + const target = createCanvas(width, height, colorSpace); if (!target) return null; // Probe the codec before drawing; JPEG needs a white matte because it has no alpha. @@ -333,7 +503,9 @@ async function reencodeWithinBudget( } let bitmap: ImageBitmap; + let colorSpace: PredefinedColorSpace; try { + colorSpace = await readImageColorSpace(file); bitmap = await createImageBitmap(file); } catch { return { ok: false, reason: "unreadable" }; @@ -347,7 +519,13 @@ async function reencodeWithinBudget( const targetDimension = Math.max(1, Math.round(baseDimension * dimensionScale)); let encoded: Awaited>; try { - encoded = await encodeWithinBudget(bitmap, targetDimension, budgetChars, preferredMimeType); + encoded = await encodeWithinBudget( + bitmap, + colorSpace, + targetDimension, + budgetChars, + preferredMimeType, + ); } catch { encodeFailed = true; continue; @@ -415,7 +593,7 @@ async function fitImageToMaxEdge(file: File): Promise<{ file: File; imageSize: I bitmap = await createImageBitmap(file, { imageOrientation: "from-image" }); const imageSize = fitImageAttachmentSize(bitmap); if (!imageSize) return null; - const target = createCanvas(imageSize.width, imageSize.height); + const target = createCanvas(imageSize.width, imageSize.height, await readImageColorSpace(file)); if (!target) return null; target.context.imageSmoothingQuality = "high"; target.context.drawImage(bitmap, 0, 0, imageSize.width, imageSize.height); @@ -494,6 +672,17 @@ function prepareHeicImage(file: File) { return preparation; } +async function readPixelsAsDisplayP3( + bitmap: ImageBitmap, + { width, height }: ImageSize, +): Promise { + const raw = createCanvas(width, height, "srgb"); + if (!raw) return undefined; + raw.context.drawImage(bitmap, 0, 0, width, height); + const pixels = raw.context.getImageData(0, 0, width, height); + return createImageBitmap(new ImageData(pixels.data, width, height, { colorSpace: "display-p3" })); +} + async function convertHeicImage( file: File, onThumbnail: (src: string | null) => void, @@ -504,14 +693,13 @@ async function convertHeicImage( let bitmap: ImageBitmap | undefined; try { - const dimensionError = await validateHeicImageDimensions(file); - if (dimensionError) { - return { ok: false, reason: dimensionError }; - } + const metadata = await readHeicMetadata(file); + if (!metadata.ok) return metadata; bitmap = typeof createImageBitmap === "function" ? await createImageBitmap(file).catch(() => undefined) : undefined; + const decodedNatively = bitmap !== undefined; if (!bitmap) { const { heicTo } = await import("heic-to/csp"); bitmap = await heicTo({ blob: file, type: "bitmap" }); @@ -520,12 +708,20 @@ async function convertHeicImage( width: bitmap.width, height: bitmap.height, }; - const surface = createCanvas(imageSize.width, imageSize.height); + // heic-to ignores the color profile and hands back the raw Display P3 values as sRGB. + if (!decodedNatively && metadata.displayP3) { + const source = bitmap; + bitmap = await readPixelsAsDisplayP3(source, imageSize); + source.close(); + if (!bitmap) return { ok: false, reason: "unreadable" }; + } + const colorSpace = metadata.displayP3 ? "display-p3" : "srgb"; + const surface = createCanvas(imageSize.width, imageSize.height, colorSpace); if (!surface) return { ok: false, reason: "unreadable" }; surface.context.drawImage(bitmap, 0, 0, imageSize.width, imageSize.height); const [converted] = await Promise.all([ encodeCanvas(surface.canvas, QUALITY_STEPS[0], "image/jpeg"), - renderComposerImageThumbnailFromBitmap(bitmap).then(onThumbnail), + renderComposerImageThumbnailFromBitmap(bitmap, colorSpace).then(onThumbnail), ]); if (!converted) return { ok: false, reason: "unreadable" }; return { From 1a9a858d457340dfb7007b66171eec50a6f3f75e Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:01:48 +0100 Subject: [PATCH 057/139] fix(keybindings): preserve sibling shortcuts when editing an inherited rule (#40525) Co-authored-by: Julius Marminge --- apps/server/src/keybindings.test.ts | 142 +++++++++++++++++- apps/server/src/keybindings.ts | 55 +++++-- ...ng-default-shortcut-keeps-the-other.e2e.ts | 59 ++++++++ 3 files changed, 241 insertions(+), 15 deletions(-) create mode 100644 scripts/scenarios/editing-default-shortcut-keeps-the-other.e2e.ts diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts index c404fef75ad52..7e846811e1440 100644 --- a/apps/server/src/keybindings.test.ts +++ b/apps/server/src/keybindings.test.ts @@ -446,16 +446,154 @@ it.layer(NodeServices.layer)("keybindings", (it) => { }).pipe(Effect.provide(layerKeybindings())), ); - it.effect("unassigns a shortcut without restoring it on startup and can reassign it", () => + it.effect("preserves sibling shortcuts when editing an inherited shortcut", () => + Effect.gen(function* () { + const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; + const keybindings = yield* Keybindings.Keybindings; + const target = { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" } as const; + const sibling = { ...target, key: "mod+n" }; + const unrelated = { ...sibling, command: "threadPanel.toggle" } as const; + yield* writeKeybindingsConfig(keybindingsConfigPath, [unrelated]); + + const replacement = { ...target, key: "f8" }; + const saved = yield* keybindings.upsertKeybindingRule({ + ...replacement, + replace: { ...target, key: "Shift+Mod+O", when: "!(terminalFocus)" }, + }); + const relevant = (rule: (typeof saved.keybindings)[number]) => + rule.command === target.command || rule.command === unrelated.command; + const expected = SharedKeybindings.compileResolvedKeybindingsConfig([ + sibling, + unrelated, + replacement, + ]); + assert.deepEqual(saved.keybindings.filter(relevant), expected); + + yield* keybindings.syncDefaultKeybindingsOnStartup; + const snapshot = yield* keybindings.getSnapshot; + assert.deepEqual(snapshot.keybindings.filter(relevant), expected); + }).pipe(Effect.provide(layerKeybindings())), + ); + + it.effect("preserves sibling shortcuts when adding to an inherited command", () => + Effect.gen(function* () { + const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; + const keybindings = yield* Keybindings.Keybindings; + yield* writeKeybindingsConfig(keybindingsConfigPath, []); + + const added = { key: "f9", command: "chat.new" } as const; + const saved = yield* keybindings.upsertKeybindingRule(added); + assert.deepEqual( + saved.keybindings.filter((rule) => rule.command === added.command), + SharedKeybindings.compileResolvedKeybindingsConfig([ + { key: "mod+n", command: added.command, when: "!terminalFocus" }, + { key: "mod+shift+o", command: added.command, when: "!terminalFocus" }, + added, + ]), + ); + }).pipe(Effect.provide(layerKeybindings())), + ); + + it.effect("preserves sibling shortcuts by rejecting an edit that would evict saved rules", () => Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; + const keybindings = yield* Keybindings.Keybindings; + const original = JSON.stringify([ + { key: "f7", command: "terminal.new" }, + ...Array.from({ length: MAX_KEYBINDINGS_COUNT - 2 }, (_, index) => ({ + key: "f1", + command: `future.command-${index}`, + })), + ]); + yield* fs.writeFileString(keybindingsConfigPath, original); + + const target = { key: "mod+n", command: "chat.new", when: "!terminalFocus" } as const; + const result = yield* toDetailResult( + keybindings.upsertKeybindingRule({ ...target, key: "f8", replace: target }), + ); + assertFailure(result, "Not enough room to save this shortcut and its inherited shortcuts."); + assert.equal(yield* fs.readFileString(keybindingsConfigPath), original); + }).pipe(Effect.provide(layerKeybindings())), + ); + + it.effect("preserves sibling shortcuts only if visible within the binding limit", () => + Effect.gen(function* () { + const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; + const keybindings = yield* Keybindings.Keybindings; yield* writeKeybindingsConfig( keybindingsConfigPath, - Array.from({ length: MAX_KEYBINDINGS_COUNT }, (_, index) => ({ + Array.from({ length: 210 }, (_, index) => ({ key: "mod+alt+f1", command: `script.filler-${index}.run` as const, })), ); + + const target = { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" } as const; + const local = { ...target, key: "mod+shift+n", command: "chat.newLocal" } as const; + const relevant = (rule: { readonly command: KeybindingCommand }) => + rule.command === target.command || rule.command === local.command; + const before = yield* keybindings.getSnapshot; + assert.deepEqual( + before.keybindings.filter(relevant), + SharedKeybindings.compileResolvedKeybindingsConfig([target, local]), + ); + + const replacement = { ...target, key: "f8" }; + const saved = yield* keybindings.upsertKeybindingRule({ ...replacement, replace: target }); + assert.deepEqual( + saved.keybindings.filter(relevant), + SharedKeybindings.compileResolvedKeybindingsConfig([local, replacement]), + ); + }).pipe(Effect.provide(layerKeybindings())), + ); + + it.effect( + "preserves sibling shortcuts when an inherited edit target has since become hidden", + () => + Effect.gen(function* () { + const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; + const keybindings = yield* Keybindings.Keybindings; + yield* writeKeybindingsConfig( + keybindingsConfigPath, + Array.from({ length: 209 }, (_, index) => ({ + key: "mod+alt+f1", + command: `script.filler-${index}.run` as const, + })), + ); + + const target = { key: "mod+n", command: "chat.new", when: "!terminalFocus" } as const; + const sibling = { ...target, key: "mod+shift+o" }; + const isChatNew = (binding: { readonly command: KeybindingCommand }) => + binding.command === target.command; + const before = yield* keybindings.getSnapshot; + assert.deepEqual( + before.keybindings.filter(isChatNew), + SharedKeybindings.compileResolvedKeybindingsConfig([target, sibling]), + ); + + const afterUnrelatedSave = yield* keybindings.upsertKeybindingRule({ + key: "mod+alt+f1", + command: "script.extra.run", + }); + assert.deepEqual( + afterUnrelatedSave.keybindings.filter(isChatNew), + SharedKeybindings.compileResolvedKeybindingsConfig([sibling]), + ); + + const replacement = { ...target, key: "f8" }; + const saved = yield* keybindings.upsertKeybindingRule({ ...replacement, replace: target }); + assert.deepEqual( + saved.keybindings.filter(isChatNew), + SharedKeybindings.compileResolvedKeybindingsConfig([sibling, replacement]), + ); + }).pipe(Effect.provide(layerKeybindings())), + ); + + it.effect("unassigns a shortcut without restoring it on startup and can reassign it", () => + Effect.gen(function* () { + const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; + yield* writeKeybindingsConfig(keybindingsConfigPath, []); const keybindings = yield* Keybindings.Keybindings; const target = SharedKeybindings.DEFAULT_KEYBINDINGS.find( (rule) => rule.command === "composer.sendBackground", diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.ts index d3d0fa5cbebd6..d9a6a8dbf01d3 100644 --- a/apps/server/src/keybindings.ts +++ b/apps/server/src/keybindings.ts @@ -174,6 +174,7 @@ const decodeKeybindingRuleExit = Schema.decodeUnknownExit(KeybindingRule); const decodeResolvedKeybindingFromConfigExit = Schema.decodeExit(ResolvedKeybindingFromConfig); const decodeRawKeybindingsEntriesExit = Schema.decodeUnknownExit(RawKeybindingsEntries); const encodeRawKeybindingsEntriesPrettyJson = Schema.encodeEffect(RawKeybindingsEntriesPrettyJson); +const isSameResolvedKeybindingRule = Schema.toEquivalence(ResolvedKeybindingRule); export interface KeybindingsConfigState { readonly keybindings: ResolvedKeybindingsConfig; @@ -669,15 +670,34 @@ const make = Effect.gen(function* () { const customConfig = yield* loadWritableCustomKeybindingsConfig(); const rule = keybindingRuleFromInput(input); const replaceTarget = replaceTargetFromUpsertInput(input); - const siblingDefaults = - rule.when === "false" && - replaceTarget && - !customConfig.some(({ rule: entry }) => entry?.command === rule.command) - ? DEFAULT_KEYBINDINGS.filter( - (entry) => - entry.command === rule.command && !isSameKeybindingRule(entry, replaceTarget), - ).map((entry) => ({ value: entry, rule: entry })) - : []; + // A saved rule overrides every inherited default for its command. + let siblingDefaults: ReadonlyArray = []; + if ( + (!replaceTarget || + (replaceTarget.command === rule.command && + DEFAULT_KEYBINDINGS.some((entry) => isSameKeybindingRule(entry, replaceTarget)))) && + !customConfig.some(({ rule: entry }) => entry?.command === rule.command) && + decodeResolvedKeybindingFromConfigExit(rule)._tag === "Success" + ) { + const customRules = customConfig.flatMap(({ rule: entry }) => (entry ? [entry] : [])); + const visibleBindings = mergeWithDefaultKeybindings( + compileResolvedKeybindingsConfig(customRules), + ).filter((entry) => entry.command === rule.command); + siblingDefaults = DEFAULT_KEYBINDINGS.filter((entry) => { + if ( + entry.command !== rule.command || + (replaceTarget && isSameKeybindingRule(entry, replaceTarget)) || + isSameKeybindingRule(entry, rule) + ) { + return false; + } + const resolved = compileResolvedKeybindingRule(entry); + return ( + resolved && + visibleBindings.some((binding) => isSameResolvedKeybindingRule(binding, resolved)) + ); + }); + } const retainedConfig = customConfig.filter(({ rule: entry }) => { if (!entry) return true; return ( @@ -685,11 +705,20 @@ const make = Effect.gen(function* () { !isSameKeybindingRule(entry, rule) ); }); - const availableSlots = MAX_KEYBINDINGS_COUNT - siblingDefaults.length - 1; + const availableSlots = MAX_KEYBINDINGS_COUNT - 1; + if ( + siblingDefaults.length > 0 && + retainedConfig.length + siblingDefaults.length > availableSlots + ) { + return yield* new KeybindingsConfigError({ + configPath: keybindingsConfigPath, + detail: "Not enough room to save this shortcut and its inherited shortcuts.", + }); + } const nextConfig = [ ...siblingDefaults, - ...retainedConfig.slice(-availableSlots), - { value: rule, rule }, + ...retainedConfig.slice(-availableSlots).map(({ value }) => value), + rule, ]; if (retainedConfig.length > availableSlots) { yield* Effect.logWarning("truncating keybindings config to max entries", { @@ -697,7 +726,7 @@ const make = Effect.gen(function* () { maxEntries: MAX_KEYBINDINGS_COUNT, }); } - yield* writeConfigAtomically(nextConfig.map(({ value }) => value)); + yield* writeConfigAtomically(nextConfig); return yield* reloadAndEmit; }), ), diff --git a/scripts/scenarios/editing-default-shortcut-keeps-the-other.e2e.ts b/scripts/scenarios/editing-default-shortcut-keeps-the-other.e2e.ts new file mode 100644 index 0000000000000..f2c75d5c34d29 --- /dev/null +++ b/scripts/scenarios/editing-default-shortcut-keeps-the-other.e2e.ts @@ -0,0 +1,59 @@ +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; + +import { T3_HOME } from "../e2e.config.ts"; +import { runPromise, test, WEB } from "./t3.ts"; + +test( + "Editing one inherited shortcut keeps the other shortcut for the same command", + WEB, + async ({ t3, app, screen }) => { + await t3.project("inherited-shortcuts"); + const keybindingsPath = `${T3_HOME}/userdata/keybindings.json`; + const original = await runPromise( + Effect.flatMap(FileSystem.FileSystem, (fs) => fs.readFileString(keybindingsPath)), + ); + + try { + await runPromise( + Effect.flatMap(FileSystem.FileSystem, (fs) => + fs.writeFileString( + keybindingsPath, + '[{ "key": "enter", "command": "commandPalette.toggle", "when": "!rightPanelOpen" }]\n', + ), + ), + ); + await t3.open("/settings/keybindings"); + const search = screen.getByLabel("Search keybindings"); + await search.fill("Command Palette"); + await screen + .getByRole("button", "Edit shortcut for Command Palette: Toggle: Enter") + .waitFor(); + + await search.fill("Chat: New"); + const unchanged = screen.getByRole("button", "Edit shortcut for Chat: New: Ctrl+N", { + exact: true, + }); + await unchanged.waitFor(); + await screen.getByRole("button", "Edit shortcut for Chat: New: Ctrl+Shift+O").tap(); + await screen.getByRole("textbox", "Keybinding for Chat: New", { exact: true }).press("F8"); + await screen.getByRole("button", "Save", { exact: true }).tap(); + await screen + .getByRole("button", "Edit shortcut for Chat: New: F8", { exact: true }) + .waitFor(); + + try { + await expect(unchanged).toBeVisible(); + } finally { + await app.screenshot("chat-new-shortcuts-after-edit"); + } + } finally { + await runPromise( + Effect.flatMap(FileSystem.FileSystem, (fs) => + fs.writeFileString(keybindingsPath, original), + ), + ); + } + }, +); From 464e8f7e607a034d41b689e93cac727de7c49d89 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:14:51 +0100 Subject: [PATCH 058/139] fix: keep paged linked thread history when reopening the same snapshot (#40545) Co-authored-by: Julius Marminge --- .../client-runtime/src/linkedThread.test.ts | 79 ++++++- packages/client-runtime/src/linkedThread.ts | 202 ++++++++++++++---- .../src/state/orchestrationV2TestFixtures.ts | 37 ++++ .../src/state/peerLinks.test.ts | 124 ++++++++++- .../client-runtime/src/state/peerLinks.ts | 32 +-- .../src/state/threadHistoryMerge.test.ts | 7 +- .../src/state/threadHistoryMerge.ts | 5 + .../client-runtime/src/state/threadStream.ts | 18 +- 8 files changed, 445 insertions(+), 59 deletions(-) diff --git a/packages/client-runtime/src/linkedThread.test.ts b/packages/client-runtime/src/linkedThread.test.ts index 8b2d4e105e5b1..2004f514df4a4 100644 --- a/packages/client-runtime/src/linkedThread.test.ts +++ b/packages/client-runtime/src/linkedThread.test.ts @@ -20,7 +20,7 @@ import { LINKED_THREAD_RETRY_MS, type LinkedThreadView, } from "./linkedThread.ts"; -import { v2Now, v2Projection } from "./state/orchestrationV2TestFixtures.ts"; +import { v2MessageRow, v2Now, v2Projection } from "./state/orchestrationV2TestFixtures.ts"; const snapshot = ( snapshotSequence: number, @@ -163,6 +163,83 @@ it.effect("loads the turns before a snapshot's window once per request", () => }).pipe(Effect.scoped), ); +it.effect("brings back the turns a closed view had loaded when it opens again", () => + Effect.gen(function* () { + const older = v2MessageRow("Older", 1); + const recent = v2MessageRow("Recent", 2); + const latest = v2MessageRow("Latest", 3); + const window = ( + snapshotSequence: number, + historyCursor: string, + row: typeof recent, + ): OrchestrationV2ThreadStreamItem => ({ + kind: "snapshot", + snapshotSequence, + projection: { ...v2Projection, turnItems: [row.item], visibleTurnItems: [row] }, + historyCursor, + hasMoreHistory: true, + }); + const pages: Record> = { + "before-recent": { items: [older], nextCursor: "before-older" }, + "before-latest": { items: [recent], nextCursor: "before-recent" }, + }; + const asked: string[] = []; + const follow = ( + items: ReadonlyArray, + previous: LinkedThreadView | null, + ) => + Effect.gen(function* () { + const views = yield* Queue.unbounded(); + yield* followLinkedThread({ + items: Stream.fromIterable(items).pipe(Stream.concat(Stream.never)), + historyPage: (cursor) => + Effect.sync(() => { + asked.push(cursor); + return { ...pages[cursor]!, snapshotSequence: 3, hasMoreHistory: true }; + }), + previous, + }).pipe( + Stream.runForEach((view) => Queue.offer(views, view)), + Effect.forkScoped, + ); + return views; + }); + const settled = Effect.fnUntraced(function* (views: Queue.Queue) { + let view = yield* Queue.take(views); + while (view.history.loading) view = yield* Queue.take(views); + return view; + }); + const rows = (view: LinkedThreadView) => + view.thread.projection?.visibleTurnItems.map((row) => row.sourceItemId); + + const first = yield* follow([window(1, "before-recent", recent), retitled(2, "Renamed")], null); + (yield* Queue.take(first)).loadEarlier(); + yield* Queue.take(first); // Loading. + yield* Queue.take(first); // The earlier page. + const closed = yield* Queue.take(first); + expect([rows(closed), closed.thread.sequence]).toEqual([ + [older.sourceItemId, recent.sourceItemId], + 2, + ]); + + // Nothing changed while the view was closed: the rows it held are shown as they were. + const same = yield* settled(yield* follow([window(2, "before-recent", recent)], closed)); + expect([rows(same), same.thread.historyCursor]).toEqual([ + [older.sourceItemId, recent.sourceItemId], + "before-older", + ]); + expect(asked).toEqual(["before-recent"]); + + // The thread moved on: pages are read again until the oldest row it showed is back. + const moved = yield* settled(yield* follow([window(3, "before-latest", latest)], closed)); + expect([rows(moved), moved.thread.historyCursor]).toEqual([ + [older.sourceItemId, recent.sourceItemId, latest.sourceItemId], + "before-older", + ]); + expect(asked).toEqual(["before-recent", "before-latest", "before-recent"]); + }).pipe(Effect.scoped), +); + describe("connectLinkedEnvironment", () => { const lan = "http://192.168.1.20:3773"; const tailnet = "https://vm.tail.ts.net"; diff --git a/packages/client-runtime/src/linkedThread.ts b/packages/client-runtime/src/linkedThread.ts index 15364cddf54ea..69b179e08f671 100644 --- a/packages/client-runtime/src/linkedThread.ts +++ b/packages/client-runtime/src/linkedThread.ts @@ -1,5 +1,6 @@ import type { EnvironmentId, + OrchestrationV2ProjectedTurnItem, OrchestrationV2ThreadHistoryPage, OrchestrationV2ThreadProjection, OrchestrationV2ThreadStreamItem, @@ -8,6 +9,7 @@ import type { } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Queue from "effect/Queue"; +import * as Result from "effect/Result"; import * as Stream from "effect/Stream"; import { mFallback, msg } from "gt-i18n"; import type { MFunctionType } from "gt-i18n/types"; @@ -20,6 +22,7 @@ import { applyThreadHistoryPage, applyThreadStreamItem, initialThreadStreamState, + prependThreadHistory, type ThreadStreamState, } from "./state/threadStream.ts"; @@ -212,12 +215,38 @@ export function isLinkedThreadWorking(projection: OrchestrationV2ThreadProjectio /** How long a view waits before asking again for a thread whose environment did not answer. */ export const LINKED_THREAD_RETRY_MS = 15_000; +type HistoryAnchor = Pick; + +interface LinkedHistoryWindow { + readonly sequence: number; + readonly cursor: string; +} + +interface LinkedHistoryRequest { + readonly window: LinkedHistoryWindow; + readonly cursor: string; +} + +function includesHistoryAnchor(rows: ReadonlyArray, anchor: HistoryAnchor): boolean { + return rows.some( + (row) => + row.sourceThreadId === anchor.sourceThreadId && row.sourceItemId === anchor.sourceItemId, + ); +} + /** A linked thread as its view holds it: the thread's own stream, reduced as any thread's is. */ export interface LinkedThreadView { readonly thread: ThreadStreamState; /** Why the stream stopped, while the view waits to ask again; the next item clears it. */ readonly error: unknown; readonly history: { readonly loading: boolean; readonly failed: boolean }; + /** Pagination progress survives the temporary view that hides the cursor during reconnect. */ + readonly loadedHistory: { + readonly window: LinkedHistoryWindow; + readonly nextCursor: string | null; + /** The oldest row still to recover, even if a read fails or the view closes during backfill. */ + readonly restoreThrough: HistoryAnchor | null; + } | null; /** Loads the turns before the ones shown. Does nothing while a page loads or none is left. */ readonly loadEarlier: () => void; } @@ -233,7 +262,11 @@ export const keepLinkedThreadView = ( ): LinkedThreadView => next.thread.projection !== null || kept === null || kept.thread.projection === null ? next - : { ...next, thread: { ...kept.thread, historyCursor: null } }; + : { + ...next, + thread: { ...kept.thread, historyCursor: null }, + loadedHistory: kept.loadedHistory, + }; /** * Follows a linked environment's thread for as long as something consumes the result. The thread @@ -244,34 +277,100 @@ export const keepLinkedThreadView = ( export const followLinkedThread = (source: { readonly items: Stream.Stream; readonly historyPage: (cursor: string) => Effect.Effect; + readonly previous?: LinkedThreadView | null; }): Stream.Stream => Stream.unwrap( Effect.gen(function* () { - const requests = yield* Queue.unbounded(); + const requests = yield* Queue.unbounded(); let requested = false; - // Both halves below run one step at a time, so each reads the view the other left. + let previous = source.previous ?? null; + let snapshotWindow: LinkedHistoryWindow | null = null; + const requestPage = (window: LinkedHistoryWindow, cursor: string) => { + requested = true; + Queue.offerUnsafe(requests, { window, cursor }); + }; let view: LinkedThreadView = { thread: initialThreadStreamState, error: null, history: { loading: false, failed: false }, + loadedHistory: null, loadEarlier: () => { - if (requested || view.thread.historyCursor === null) return; - requested = true; - Queue.offerUnsafe(requests, undefined); + const cursor = view.thread.historyCursor; + if (requested || snapshotWindow === null || cursor === null) return; + requestPage(snapshotWindow, cursor); }, }; const show = (patch: Partial) => { view = { ...view, ...patch }; return view; }; - const attempt = (): Stream.Stream => + + const onItem = (item: OrchestrationV2ThreadStreamItem) => { + let thread = applyThreadStreamItem(view.thread, item); + if (item.kind !== "snapshot") return show({ thread, error: null }); + + const kept = view.thread.projection === null ? previous : view; + previous = null; + const loaded = kept?.loadedHistory; + const window = + thread.historyCursor === null + ? null + : { sequence: thread.sequence, cursor: thread.historyCursor }; + let loadedHistory: LinkedThreadView["loadedHistory"] = null; + if (window && kept?.thread.projection && loaded) { + // A live update can advance the revision and move the window without invalidating held rows. + if ( + kept.thread.sequence === window.sequence && + (window.sequence > loaded.window.sequence || window.cursor === loaded.window.cursor) + ) { + thread = prependThreadHistory( + thread, + { + items: kept.thread.projection.visibleTurnItems, + subagents: kept.thread.projection.subagents, + }, + loaded.nextCursor, + ); + loadedHistory = { ...loaded, window }; + } else if (window.sequence > kept.thread.sequence) { + const oldest = loaded.restoreThrough ?? kept.thread.projection.visibleTurnItems[0]; + if (oldest && !includesHistoryAnchor(item.projection.visibleTurnItems, oldest)) { + const { sourceThreadId, sourceItemId } = oldest; + loadedHistory = { + window, + nextCursor: window.cursor, + restoreThrough: { sourceThreadId, sourceItemId }, + }; + } + } + } + + snapshotWindow = window; + requested = false; + if (window && thread.historyCursor !== null && loadedHistory?.restoreThrough) { + requestPage(window, thread.historyCursor); + } else { + Queue.offerUnsafe(requests, null); + } + return show({ + thread, + loadedHistory, + history: { loading: requested, failed: false }, + error: null, + }); + }; + + const attempt = (): Stream.Stream< + | { readonly kind: "item"; readonly item: OrchestrationV2ThreadStreamItem } + | { readonly kind: "unreachable"; readonly error: E }, + E, + R + > => source.items.pipe( - Stream.map((item) => - show({ thread: applyThreadStreamItem(view.thread, item), error: null }), - ), + Stream.map((item) => ({ kind: "item" as const, item })), Stream.catch((error) => isLinkedThreadUnreachable(error) - ? Stream.make(show({ error })).pipe( + ? Stream.make({ kind: "unreachable" as const, error }).pipe( Stream.concat( Stream.unwrap(Effect.sleep(LINKED_THREAD_RETRY_MS).pipe(Effect.map(attempt))), ), @@ -279,38 +378,67 @@ export const followLinkedThread = (source: { : Stream.fail(error), ), ); + const earlier = Stream.fromQueue(requests).pipe( - Stream.flatMap(() => - Stream.suspend(() => { - const cursor = view.thread.historyCursor; - if (cursor === null) { - requested = false; - return Stream.empty; - } - return Stream.make(show({ history: { loading: true, failed: false } })).pipe( - Stream.concat( - Stream.fromEffect( - source.historyPage(cursor).pipe( - Effect.match({ - onSuccess: (page) => - show({ - thread: applyThreadHistoryPage(view.thread, cursor, page), - history: { loading: false, failed: false }, - }), - onFailure: () => show({ history: { loading: false, failed: true } }), - }), - Effect.ensuring( - Effect.sync(() => { - requested = false; - }), + Stream.switchMap((request) => + request === null + ? Stream.empty + : Stream.make({ kind: "loading" as const, request }).pipe( + Stream.concat( + Stream.fromEffect( + source.historyPage(request.cursor).pipe( + Effect.result, + Effect.map((page) => ({ kind: "page" as const, request, page })), ), ), ), ), - ); - }), ), ); - return Stream.merge(attempt(), earlier, { haltStrategy: "left" }); + + // Reduce snapshots, live items and history results in publication order. + return Stream.merge(attempt(), earlier, { haltStrategy: "left" }).pipe( + Stream.filterMap((update) => { + if (update.kind === "item") return Result.succeed(onItem(update.item)); + if (update.kind === "unreachable") return Result.succeed(show({ error: update.error })); + const { window, cursor } = update.request; + if (snapshotWindow !== window || view.thread.historyCursor !== cursor) { + return Result.failVoid; + } + if (update.kind === "loading") { + return view.history.loading + ? Result.failVoid + : Result.succeed(show({ history: { loading: true, failed: false } })); + } + requested = false; + const page = update.page; + if ( + Result.isFailure(page) || + page.success.snapshotSequence < window.sequence || + (page.success.hasMoreHistory && page.success.nextCursor === cursor) + ) { + return Result.succeed(show({ history: { loading: false, failed: true } })); + } + + const thread = applyThreadHistoryPage(view.thread, cursor, page.success); + let restoreThrough = view.loadedHistory?.restoreThrough ?? null; + const nextCursor = thread.historyCursor; + if ( + restoreThrough !== null && + (nextCursor === null || + includesHistoryAnchor(thread.projection?.visibleTurnItems ?? [], restoreThrough)) + ) { + restoreThrough = null; + } + if (restoreThrough !== null && nextCursor !== null) requestPage(window, nextCursor); + return Result.succeed( + show({ + thread, + loadedHistory: { window, nextCursor, restoreThrough }, + history: { loading: requested, failed: false }, + }), + ); + }), + ); }), ); diff --git a/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts b/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts index 550dc389a86bf..cf1ec01a4fc65 100644 --- a/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts +++ b/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts @@ -1,8 +1,11 @@ import { + MessageId, ProjectId, ProviderInstanceId, ThreadId, + TurnItemId, type OrchestrationProjectShell, + type OrchestrationV2ProjectedTurnItem, type OrchestrationV2ShellSnapshot, type OrchestrationV2ThreadProjection, type OrchestrationV2ThreadShell, @@ -101,6 +104,40 @@ export const v2Projection: OrchestrationV2ThreadProjection = { updatedAt: v2Now, }; +/** A completed user message row of `v2ThreadId`, identified by its text. */ +export function v2MessageRow(text: string, ordinal: number): OrchestrationV2ProjectedTurnItem { + const itemId = TurnItemId.make(text); + return { + position: 0, + visibility: "local", + sourceThreadId: v2ThreadId, + sourceItemId: itemId, + item: { + id: itemId, + threadId: v2ThreadId, + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal, + status: "completed", + title: null, + startedAt: v2Now, + completedAt: v2Now, + updatedAt: v2Now, + type: "user_message", + createdBy: "user", + creationSource: "web", + messageId: MessageId.make(text), + inputIntent: "turn_start", + text, + attachments: [], + }, + }; +} + export const v2ShellSnapshot: OrchestrationV2ShellSnapshot = { schemaVersion: 1, snapshotSequence: 0, diff --git a/packages/client-runtime/src/state/peerLinks.test.ts b/packages/client-runtime/src/state/peerLinks.test.ts index c1e4ae8acd9f9..75430e340fbff 100644 --- a/packages/client-runtime/src/state/peerLinks.test.ts +++ b/packages/client-runtime/src/state/peerLinks.test.ts @@ -1,8 +1,126 @@ -import { EnvironmentId, type PeerLinkSummary } from "@t3tools/contracts"; +import { + EnvironmentId, + WS_METHODS, + type OrchestrationV2ThreadHistoryPage, + type OrchestrationV2ThreadStreamItem, + type PeerLinkSummary, +} from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; import * as DateTime from "effect/DateTime"; -import { describe, expect, it } from "vite-plus/test"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; +import * as SubscriptionRef from "effect/SubscriptionRef"; +import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; -import { linkThroughRoutes } from "./peerLinks.ts"; +import { EnvironmentRegistry } from "../connection/registry.ts"; +import { EnvironmentSupervisor } from "../connection/supervisor.ts"; +import type { LinkedThreadView } from "../linkedThread.ts"; +import type { RpcSession } from "../rpc/session.ts"; +import { v2MessageRow, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts"; +import { createPeerLinkEnvironmentAtoms, linkThroughRoutes } from "./peerLinks.ts"; + +// regression: #40544 earlier messages vanished when a linked thread's view opened again +it.effect( + "keeps loaded messages when a linked thread's view opens again on the same snapshot", + () => + Effect.gen(function* () { + const recent = v2MessageRow("Recent message", 2); + const older = v2MessageRow("Earlier message", 1); + const snapshot = (historyCursor: string): OrchestrationV2ThreadStreamItem => ({ + kind: "snapshot", + snapshotSequence: 7, + projection: { ...v2Projection, turnItems: [recent.item], visibleTurnItems: [recent] }, + historyCursor, + hasMoreHistory: true, + }); + const subscriptions = yield* Queue.unbounded<{ + items: Queue.Queue; + stopped: Deferred.Deferred; + }>(); + const requested: string[] = []; + const client = { + [WS_METHODS.peerLinksSubscribeThread]: () => + Stream.unwrap( + Effect.gen(function* () { + const items = yield* Queue.unbounded(); + const stopped = yield* Deferred.make(); + yield* Effect.addFinalizer(() => Deferred.succeed(stopped, undefined)); + yield* Queue.offer(subscriptions, { items, stopped }); + return Stream.fromQueue(items); + }), + ), + [WS_METHODS.peerLinksThreadHistoryPage]: ({ cursor }: { cursor: string }) => + Effect.sync((): OrchestrationV2ThreadHistoryPage => { + requested.push(cursor); + return cursor === "before-recent" + ? { + snapshotSequence: 7, + items: [older], + nextCursor: "before-earlier", + hasMoreHistory: true, + } + : { snapshotSequence: 7, items: [], nextCursor: null, hasMoreHistory: false }; + }), + } as unknown as RpcSession["client"]; + const target = { + environmentId: EnvironmentId.make("via"), + input: { environmentId: EnvironmentId.make("linked"), threadId: v2ThreadId }, + }; + const supervisor = EnvironmentSupervisor.of({ + target: { environmentId: target.environmentId, label: "Via" }, + session: yield* SubscriptionRef.make(Option.some({ client })), + } as unknown as EnvironmentSupervisor["Service"]); + const environment = EnvironmentRegistry.of({ + followStream: (_id, stream) => + Stream.provideService(stream, EnvironmentSupervisor, supervisor), + } as Pick as EnvironmentRegistry["Service"]); + const links = createPeerLinkEnvironmentAtoms( + Atom.runtime(Layer.succeed(EnvironmentRegistry, environment)), + ); + const registry = yield* Effect.acquireRelease( + Effect.sync(() => AtomRegistry.make()), + (registry) => Effect.sync(() => registry.dispose()), + ); + const views = yield* Queue.unbounded(); + const open = () => + registry.subscribe(links.threadView(target), (result) => { + if (AsyncResult.isSuccess(result)) Queue.offerUnsafe(views, result.value); + }); + const visibleMessages = (view: LinkedThreadView) => + view.thread.projection?.visibleTurnItems.map((row) => row.sourceItemId); + + const unmount = open(); + const first = yield* Queue.take(subscriptions); + yield* Queue.offer(first.items, snapshot("before-recent")); + (yield* Queue.take(views)).loadEarlier(); + yield* Queue.take(views); // Loading. + expect(visibleMessages(yield* Queue.take(views))).toEqual([ + older.sourceItemId, + recent.sourceItemId, + ]); + unmount(); + yield* Deferred.await(first.stopped); + + open(); + const reopened = yield* Queue.take(subscriptions); + yield* Queue.offer(reopened.items, snapshot("before-recent")); + const resumed = yield* Queue.take(views); + expect(visibleMessages(resumed)).toEqual([older.sourceItemId, recent.sourceItemId]); + // Paging goes on from where the closed view stopped, without reading the same page again. + expect(resumed.thread.historyCursor).toBe("before-earlier"); + expect(requested).toEqual(["before-recent"]); + + // A snapshot of another window replaces the rows held for the old one. + yield* Queue.offer(reopened.items, snapshot("new-window")); + const refreshed = yield* Queue.take(views); + expect(visibleMessages(refreshed)).toEqual([recent.sourceItemId]); + expect(refreshed.thread.historyCursor).toBe("new-window"); + }).pipe(Effect.scoped), +); const now = DateTime.makeUnsafe("2026-11-20T00:00:00.000Z"); const id = (value: string) => EnvironmentId.make(value); diff --git a/packages/client-runtime/src/state/peerLinks.ts b/packages/client-runtime/src/state/peerLinks.ts index 543fd55887139..fd9d269bfd726 100644 --- a/packages/client-runtime/src/state/peerLinks.ts +++ b/packages/client-runtime/src/state/peerLinks.ts @@ -7,6 +7,7 @@ import { import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Stream from "effect/Stream"; import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity"; import type { EnvironmentRegistry } from "../connection/registry.ts"; @@ -19,7 +20,7 @@ import { request, subscribe } from "../rpc/client.ts"; import { createEnvironmentRpcCommand, createEnvironmentRpcQueryAtomFamily, - createEnvironmentSubscriptionAtomFamily, + followStreamInEnvironment, } from "./runtime.ts"; /** The environment a client reads through, and the linked environment's thread it reads. */ @@ -54,16 +55,6 @@ export function createPeerLinkEnvironmentAtoms( registry.refresh(list({ environmentId, input: {} })); registry.refresh(names({ environmentId, input: {} })); }); - const threadStream = createEnvironmentSubscriptionAtomFamily(runtime, { - label: "environment-data:peer-links:thread-stream", - idleTtlMs: 0, - subscribe: (input: PeerLinkThreadInput) => - followLinkedThread({ - items: subscribe(WS_METHODS.peerLinksSubscribeThread, input), - historyPage: (cursor) => - request(WS_METHODS.peerLinksThreadHistoryPage, { ...input, cursor }), - }), - }); /** * What a view of the thread last showed. It outlives the subscription for a while, so coming * back to the view shows the thread at once while the stream starts again. @@ -79,11 +70,26 @@ export function createPeerLinkEnvironmentAtoms( * last reader, which closes the stream at the linked environment too. */ const threadView = Atom.family((key: string) => { - const stream = threadStream(JSON.parse(key) as LinkedThreadViewTarget); + const { environmentId, input } = JSON.parse(key) as LinkedThreadViewTarget; + const kept = lastThreadView(key); + const stream = runtime + .atom(({ registry }) => + followStreamInEnvironment( + environmentId, + Stream.suspend(() => + followLinkedThread({ + items: subscribe(WS_METHODS.peerLinksSubscribeThread, input), + historyPage: (cursor) => + request(WS_METHODS.peerLinksThreadHistoryPage, { ...input, cursor }), + previous: registry.get(kept), + }), + ), + ), + ) + .pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-data:peer-links:thread-stream:${key}`)); return Atom.make((get) => { const live = get(stream); if (AsyncResult.isSuccess(live)) { - const kept = lastThreadView(key); get.set(kept, keepLinkedThreadView(get.once(kept), live.value)); } return live; diff --git a/packages/client-runtime/src/state/threadHistoryMerge.test.ts b/packages/client-runtime/src/state/threadHistoryMerge.test.ts index 9647f5e4ffc2c..e92852ee36db1 100644 --- a/packages/client-runtime/src/state/threadHistoryMerge.test.ts +++ b/packages/client-runtime/src/state/threadHistoryMerge.test.ts @@ -345,8 +345,11 @@ describe("threadHistoryMerge", () => { visibleTurnItems: [{ ...recent, position: 0 }], }; + // A row of the run that was never in the window, such as one paged in after a rollback. + const ran = { ...row(1), item: { ...row(1).item, runId } }; const merged = mergeOlderHistoryIntoProjection(coldOpen, [ { ...row(0), position: 0 }, + ran, { position: 1, visibility: "local", @@ -357,7 +360,9 @@ describe("threadHistoryMerge", () => { ]); expect(merged.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual( - status === "rolled_back" ? ["item-0", "item-5"] : ["item-0", "item-question", "item-5"], + status === "rolled_back" + ? ["item-0", "item-5"] + : ["item-0", "item-1", "item-question", "item-5"], ); expect(merged.turnItems).toContain(card); const pending = derivePendingThreadRequests(merged).userInputs; diff --git a/packages/client-runtime/src/state/threadHistoryMerge.ts b/packages/client-runtime/src/state/threadHistoryMerge.ts index 4af17f76e031c..a455d64a4726f 100644 --- a/packages/client-runtime/src/state/threadHistoryMerge.ts +++ b/packages/client-runtime/src/state/threadHistoryMerge.ts @@ -102,6 +102,9 @@ export function mergeOlderHistoryIntoProjection( const currentByKey = new Map( projection.visibleTurnItems.map((row) => [projectedItemKey(row), row]), ); + const rolledBackRuns = new Set( + projection.runs.filter((run) => run.status === "rolled_back").map((run) => run.id), + ); const turnItemById = new Map(projection.turnItems.map((item) => [String(item.id), item])); const pageKeys = new Set(); const page: OrchestrationV2ProjectedTurnItem[] = []; @@ -140,6 +143,8 @@ export function mergeOlderHistoryIntoProjection( continue; row = { ...row, item: currentItem }; } + // A rollback can arrive before a history page for rows outside the loaded window. + if (row.item.runId !== null && rolledBackRuns.has(row.item.runId)) continue; } pageKeys.add(key); page.push(row); diff --git a/packages/client-runtime/src/state/threadStream.ts b/packages/client-runtime/src/state/threadStream.ts index b723a99885aad..e03a1e610a094 100644 --- a/packages/client-runtime/src/state/threadStream.ts +++ b/packages/client-runtime/src/state/threadStream.ts @@ -82,13 +82,23 @@ export function applyThreadHistoryPage( page: OrchestrationV2ThreadHistoryPage, ): ThreadStreamState { // A snapshot since the request replaced the thread and its cursor. - if (state.projection === null || state.historyCursor !== cursor) return state; + if (state.historyCursor !== cursor) return state; + return prependThreadHistory(state, page, page.hasMoreHistory ? page.nextCursor : null); +} + +/** Adds older timeline rows and their subagent records, with the cursor that follows them. */ +export function prependThreadHistory( + state: ThreadStreamState, + history: Pick, + nextCursor: string | null, +): ThreadStreamState { + if (state.projection === null) return state; return { ...state, projection: mergeOlderSubagentsIntoProjection( - mergeOlderHistoryIntoProjection(state.projection, page.items), - page.subagents, + mergeOlderHistoryIntoProjection(state.projection, history.items), + history.subagents, ), - historyCursor: page.hasMoreHistory ? page.nextCursor : null, + historyCursor: nextCursor, }; } From da57ea2bf9ee829ade3b6c98cb7b402072fb1f15 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:16:24 +0100 Subject: [PATCH 059/139] fix(mobile): push clean default branches without a new commit (#40538) Co-authored-by: Julius Marminge --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 43 +++++++++++++++++++ apps/server/src/vcs/GitVcsDriverCore.ts | 8 +++- .../src/state/gitActions.test.ts | 17 ++++++++ .../client-runtime/src/state/gitActions.ts | 4 +- 4 files changed, 68 insertions(+), 4 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 27f4d4eceec59..0e9ab873cbb30 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -9720,6 +9720,49 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("publishes a new branch at the same commit as its local upstream", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const remote = yield* makeTmpDir("git-remote-"); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "-u", "origin", initialBranch]); + const remoteBase = yield* git(remote, [ + "--git-dir=.", + "rev-parse", + `refs/heads/${initialBranch}`, + ]); + yield* writeTextFile(cwd, "feature.txt", "feature\n"); + yield* git(cwd, ["add", "feature.txt"]); + const { commitSha } = yield* driver.commit(cwd, "Add feature", ""); + yield* git(cwd, ["config", "branch.autoSetupMerge", "always"]); + yield* driver.createRef({ cwd, refName: "feature/push" }); + yield* driver.switchRef({ cwd, refName: "feature/push" }); + assert.equal( + yield* git(cwd, ["rev-parse", "--symbolic-full-name", "@{upstream}"]), + `refs/heads/${initialBranch}`, + ); + + const pushed = yield* driver.pushCurrentBranch(cwd, null); + + assert.deepInclude(pushed, { + status: "pushed", + upstreamBranch: "origin/feature/push", + setUpstream: true, + }); + assert.equal( + yield* git(remote, ["--git-dir=.", "rev-parse", "refs/heads/feature/push"]), + commitSha, + ); + assert.equal( + yield* git(remote, ["--git-dir=.", "rev-parse", `refs/heads/${initialBranch}`]), + remoteBase, + ); + }), + ); + it.effect("republishes a branch whose upstream was deleted", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 35105aeea90e4..a6aab054d37dc 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -3733,8 +3733,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const destination = yield* resolvePushDestination(cwd, branch, details.hasUpstream); if (hasNoLocalDelta && details.hasUpstream) { if (!destination?.pushRemote) { - // The tracking ref reflects the fetch URL, so it says nothing about a separate push URL. - if (!destination || (yield* pushesOnlyToFetchUrl(cwd, destination.remoteName))) { + // A local upstream and a separate push URL both leave the publish destination unchecked. + if ( + !destination || + (destination.upstream?.remoteName !== "." && + (yield* pushesOnlyToFetchUrl(cwd, destination.remoteName))) + ) { return { status: "skipped_up_to_date" as const, branch, diff --git a/packages/client-runtime/src/state/gitActions.test.ts b/packages/client-runtime/src/state/gitActions.test.ts index 7418ed0df172b..7b1db4e9f5f47 100644 --- a/packages/client-runtime/src/state/gitActions.test.ts +++ b/packages/client-runtime/src/state/gitActions.test.ts @@ -88,6 +88,23 @@ describe("git action copy", () => { expect(resolveQuickAction({ ...pushed, isDefaultRef: true }, false, true).disabled).toBe(true); }); + it.each([ + { tracking: "with an upstream", hasUpstream: true }, + { tracking: "without an upstream", hasUpstream: false }, + ])("pushes existing commits from a clean default branch $tracking", ({ hasUpstream }) => { + const cleanDefaultBranch = status({ + refName: "main", + isDefaultRef: true, + hasUpstream, + aheadCount: 1, + }); + expect(resolveQuickAction(cleanDefaultBranch, false, true)).toMatchObject({ + disabled: false, + kind: "run_action", + action: "push", + }); + }); + it("names the host's change request in the default-branch dialog", () => { const input = { action: "commit_push_pr", branchName: "main", includesCommit: true } as const; expect( diff --git a/packages/client-runtime/src/state/gitActions.ts b/packages/client-runtime/src/state/gitActions.ts index ece720c47d3a2..c975e640aafee 100644 --- a/packages/client-runtime/src/state/gitActions.ts +++ b/packages/client-runtime/src/state/gitActions.ts @@ -238,7 +238,7 @@ export function resolveQuickAction( label: resolve(msg("Push", { $context: "verb, git action" })), disabled: false, kind: "run_action", - action: isDefaultBranch ? "commit_push" : "push", + action: "push", }; } return { @@ -272,7 +272,7 @@ export function resolveQuickAction( label: resolve(msg("Push", { $context: "verb, git action" })), disabled: false, kind: "run_action", - action: isDefaultBranch ? "commit_push" : "push", + action: "push", }; } return { From ffb42a0b7767374c59ff5a6665025abd47f0376c Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:33:15 +0100 Subject: [PATCH 060/139] fix(web): preserve browser history across open tabs (#40543) Co-authored-by: Grok 4.7 Co-authored-by: Julius Marminge --- .../src/browserHistoryStore.browser.test.ts | 302 +++++++++++++ apps/web/src/browserHistoryStore.ts | 427 +++++++++++++----- ...history-keeps-visits-from-both-tabs.e2e.ts | 76 ++++ 3 files changed, 693 insertions(+), 112 deletions(-) create mode 100644 apps/web/src/browserHistoryStore.browser.test.ts create mode 100644 scripts/scenarios/browser-history-keeps-visits-from-both-tabs.e2e.ts diff --git a/apps/web/src/browserHistoryStore.browser.test.ts b/apps/web/src/browserHistoryStore.browser.test.ts new file mode 100644 index 0000000000000..c0c22fc2558a4 --- /dev/null +++ b/apps/web/src/browserHistoryStore.browser.test.ts @@ -0,0 +1,302 @@ +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; + +import { resetBrowserHistoryForTests, useBrowserHistoryStore } from "./browserHistoryStore"; + +const storageKey = "t3code:browser-history:v1"; +const oldEntry = { url: "http://example.test/removed", lastVisitedAt: 1 }; +const otherEntry = { url: "http://example.test/other", lastVisitedAt: 2 }; +const page = { url: "http://localhost:3000/page", lastVisitedAt: 3, title: "Page" }; + +function storedHistory(): unknown { + return JSON.parse(localStorage.getItem(storageKey) ?? "null")?.state; +} + +function openHistoryFixture(disposables: DisposableStack) { + return new Promise((resolve, reject) => { + const request = indexedDB.open(storageKey, 1); + request.onupgradeneeded = () => request.result.createObjectStore("history"); + request.onsuccess = () => { + const db = request.result; + disposables.defer(() => db.close()); + resolve(db); + }; + request.onerror = () => reject(request.error); + }); +} + +function readHistoryFixture(db: IDBDatabase): Promise { + return new Promise((resolve, reject) => { + const request = db.transaction("history").objectStore("history").get(storageKey); + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error); + }); +} + +function writeHistoryFixture(db: IDBDatabase, state: unknown): Promise { + return new Promise((resolve, reject) => { + const transaction = db.transaction("history", "readwrite"); + transaction.objectStore("history").put(state, storageKey); + transaction.oncomplete = () => resolve(); + transaction.onabort = () => reject(transaction.error); + }); +} + +it.each([ + { + name: "records a visit without bringing back a deleted URL", + change: () => useBrowserHistoryStore.getState().recordVisit("a", "http://example.test/new", 4), + expected: { + byProjectKey: { + a: [{ url: "http://example.test/new", lastVisitedAt: 4 }, page], + b: [otherEntry], + }, + }, + }, + { + name: "titles the latest matching visit without changing its URL", + change: () => + useBrowserHistoryStore.getState().setTitleForUrl("a", "http://127.0.0.1:3000/page/", "New"), + expected: { byProjectKey: { a: [{ ...page, title: "New" }], b: [otherEntry] } }, + }, + { + name: "removes a visit added elsewhere without clearing the other project", + change: () => useBrowserHistoryStore.getState().removeUrl("a", page.url), + expected: { byProjectKey: { b: [otherEntry] } }, + }, + { + name: "registers a thread without replacing another tab's history", + change: () => + useBrowserHistoryStore.getState().registerThreadProject( + { + environmentId: EnvironmentId.make("env"), + threadId: ThreadId.make("thread"), + }, + "a", + ), + expected: { byProjectKey: { a: [page], b: [otherEntry] } }, + }, +])("$name", async ({ change, expected }) => { + await resetHistoryFixture(); + try { + using fixture = new DisposableStack(); + const db = await openHistoryFixture(fixture); + useBrowserHistoryStore.getState().recordVisit("a", oldEntry.url, oldEntry.lastVisitedAt); + await vi.waitFor(async () => + expect(await readHistoryFixture(db)).toMatchObject({ byProjectKey: { a: [oldEntry] } }), + ); + + // Another document has committed newer history that this store has not heard about. + await writeHistoryFixture(db, { + byProjectKey: { a: [page], b: [otherEntry] }, + projectKeyByThreadKey: {}, + }); + change(); + + await vi.waitFor(async () => { + const saved = await readHistoryFixture(db); + expect(saved).toHaveProperty("byProjectKey", expected.byProjectKey); + expect(saved).toHaveProperty( + "projectKeyByThreadKey", + useBrowserHistoryStore.getState().projectKeyByThreadKey, + ); + }); + await vi.waitFor(() => + expect(useBrowserHistoryStore.getState().byProjectKey).toEqual(expected.byProjectKey), + ); + } finally { + await resetHistoryFixture(); + } +}); + +it("refreshes the open history when another document adds a visit", async () => { + await resetHistoryFixture(); + try { + localStorage.setItem( + storageKey, + JSON.stringify({ state: { byProjectKey: { a: [page] } }, version: 1 }), + ); + + using documents = new DisposableStack(); + const otherStore = await openHistoryDocument(documents); + await vi.waitFor(() => expect(otherStore.getState().byProjectKey).toEqual({ a: [page] })); + otherStore.getState().recordVisit("a", page.url, page.lastVisitedAt); + + await vi.waitFor(() => + expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({ a: [page] }), + ); + } finally { + await resetHistoryFixture(); + } +}); + +it("bounds saved thread mappings while keeping live registrations", async () => { + await resetHistoryFixture(); + const mappings = Object.fromEntries( + Array.from({ length: 100 }, (_, index) => [`env:thread-${index}`, "a"]), + ); + + try { + using fixture = new DisposableStack(); + const db = await openHistoryFixture(fixture); + await writeHistoryFixture(db, { byProjectKey: { a: [page] }, projectKeyByThreadKey: mappings }); + const store = useBrowserHistoryStore.getState(); + const environmentId = EnvironmentId.make("env"); + store.registerThreadProject({ environmentId, threadId: ThreadId.make("thread-0") }, "a"); + store.registerThreadProject({ environmentId, threadId: ThreadId.make("pending") }, "b"); + const { "env:thread-0": _oldest, ...retained } = mappings; + await vi.waitFor(async () => + expect(await readHistoryFixture(db)).toHaveProperty("projectKeyByThreadKey", { + ...retained, + "env:pending": "b", + }), + ); + + store.removeUrl("a", page.url); + await vi.waitFor(async () => + expect(await readHistoryFixture(db)).toHaveProperty("projectKeyByThreadKey", { + "env:pending": "b", + }), + ); + expect(useBrowserHistoryStore.getState().projectKeyByThreadKey["env:thread-0"]).toBe("a"); + } finally { + await resetHistoryFixture(); + } +}); + +async function openHistoryDocument( + disposables: DisposableStack, + { withoutIndexedDB = false } = {}, +) { + const source = new URL(import.meta.url); + source.pathname = source.pathname.replace(/\.browser\.test\.ts$/, ".ts"); + source.search = ""; + const frame = document.createElement("iframe"); + disposables.defer(() => frame.remove()); + frame.srcdoc = `${withoutIndexedDB ? '' : ""} + `; + await new Promise((resolve) => { + frame.onload = () => resolve(); + document.body.append(frame); + }); + const store = ( + frame.contentWindow as (Window & { historyStore?: typeof useBrowserHistoryStore }) | null + )?.historyStore; + if (!store) throw new Error("The history document did not load."); + return store; +} + +function deleteHistoryDatabase() { + return new Promise((resolve, reject) => { + const request = indexedDB.deleteDatabase(storageKey); + request.onsuccess = () => resolve(); + request.onerror = () => reject(request.error); + }); +} + +async function resetHistoryFixture() { + localStorage.removeItem(storageKey); + await deleteHistoryDatabase(); + resetBrowserHistoryForTests(); +} + +it("moves the legacy snapshot into the shared database", async () => { + await resetHistoryFixture(); + localStorage.setItem( + storageKey, + JSON.stringify({ state: { byProjectKey: { a: [page] } }, version: 1 }), + ); + try { + using documents = new DisposableStack(); + const first = await openHistoryDocument(documents); + await vi.waitFor(() => expect(first.getState().byProjectKey).toEqual({ a: [page] })); + expect(localStorage.getItem(storageKey)).toBeNull(); + first.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); + await vi.waitFor(() => expect(first.getState().byProjectKey.b).toEqual([otherEntry])); + + const reopened = await openHistoryDocument(documents); + await vi.waitFor(() => + expect(reopened.getState().byProjectKey).toEqual({ a: [page], b: [otherEntry] }), + ); + } finally { + await resetHistoryFixture(); + } +}); + +it("persists new visits from an open document after its history database is deleted", async () => { + await resetHistoryFixture(); + localStorage.setItem( + storageKey, + JSON.stringify({ state: { byProjectKey: { a: [page] } }, version: 1 }), + ); + try { + using documents = new DisposableStack(); + const first = await openHistoryDocument(documents); + await vi.waitFor(() => expect(first.getState().byProjectKey).toEqual({ a: [page] })); + first.getState().removeUrl("a", page.url); + await vi.waitFor(() => expect(first.getState().byProjectKey).toEqual({})); + + await deleteHistoryDatabase(); + first.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); + await vi.waitFor(() => expect(first.getState().byProjectKey.b).toEqual([otherEntry])); + + const reopened = await openHistoryDocument(documents); + await vi.waitFor(() => expect(reopened.getState().byProjectKey).toEqual({ b: [otherEntry] })); + } finally { + await resetHistoryFixture(); + } +}); + +it("keeps overlapping visits from independent documents", async () => { + await resetHistoryFixture(); + localStorage.setItem( + storageKey, + JSON.stringify({ state: { byProjectKey: { a: [page] } }, version: 1 }), + ); + try { + using documents = new DisposableStack(); + const [first, second] = await Promise.all([ + openHistoryDocument(documents), + openHistoryDocument(documents), + ]); + first.getState().recordVisit("a", oldEntry.url, oldEntry.lastVisitedAt); + second.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); + const expected = { a: [page, oldEntry], b: [otherEntry] }; + await vi.waitFor(() => { + expect(first.getState().byProjectKey).toEqual(expected); + expect(second.getState().byProjectKey).toEqual(expected); + }); + + // A fresh document should read the committed visits even after the legacy seed is gone. + localStorage.removeItem(storageKey); + const reopened = await openHistoryDocument(documents); + await vi.waitFor(() => expect(reopened.getState().byProjectKey).toEqual(expected)); + } finally { + await resetHistoryFixture(); + } +}); + +it("keeps visits saved while IndexedDB could not open", async () => { + await resetHistoryFixture(); + try { + using documents = new DisposableStack(); + const db = await openHistoryFixture(documents); + await writeHistoryFixture(db, { byProjectKey: { a: [page] }, projectKeyByThreadKey: {} }); + const offline = await openHistoryDocument(documents, { withoutIndexedDB: true }); + offline.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); + await vi.waitFor(() => + expect(storedHistory()).toHaveProperty("byProjectKey", { b: [otherEntry] }), + ); + + const online = await openHistoryDocument(documents); + await vi.waitFor(() => + expect(online.getState().byProjectKey).toEqual({ a: [page], b: [otherEntry] }), + ); + expect(storedHistory()).toBeUndefined(); + } finally { + await resetHistoryFixture(); + } +}); diff --git a/apps/web/src/browserHistoryStore.ts b/apps/web/src/browserHistoryStore.ts index d5ccb0fcd621e..c6088b2abfca7 100644 --- a/apps/web/src/browserHistoryStore.ts +++ b/apps/web/src/browserHistoryStore.ts @@ -11,7 +11,6 @@ import { type ScopedThreadRef, } from "@t3tools/contracts"; import { create } from "zustand"; -import { createJSONStorage, persist } from "zustand/middleware"; import { useShallow } from "zustand/react/shallow"; import { normalizePreviewUrl } from "@t3tools/shared/preview"; @@ -40,7 +39,6 @@ import { isClientSettingsHydrated, useClientSettings, } from "./hooks/useSettings"; -import { resolveStorage } from "./lib/storage"; import { deriveLogicalProjectKeyFromSettings, derivePhysicalProjectKey, @@ -180,6 +178,7 @@ export function migratePersistedBrowserHistoryState(persistedState: unknown): { const BROWSER_HISTORY_STORAGE_KEY = "t3code:browser-history:v1"; +const MAX_PERSISTED_THREAD_MAPPINGS = 100; const PENDING_MAX_PER_THREAD = 10; const PENDING_MAX_THREADS = 20; @@ -199,7 +198,7 @@ interface BrowserHistoryStoreState { projectKey: string, url: string, title: string, - environmentHostname?: string | null, + options?: { environmentHostname?: string | null; onlyIfUntitled?: boolean }, ) => void; removeUrl: (projectKey: string, url: string) => void; registerThreadProject: (ref: ScopedThreadRef, projectKey: string) => void; @@ -221,100 +220,313 @@ function addPendingByThread( return next; } -export const useBrowserHistoryStore = create()( - persist( - (set, get) => ({ - byProjectKey: {}, - projectKeyByThreadKey: {}, - pendingVisitsByThreadKey: {}, - recordVisit: (projectKey, url, at, options) => { - const normalized = normalizeHistoryUrl(url); - if (!normalized) return; - set((state) => { - return { - byProjectKey: evictExcessProjects({ - ...state.byProjectKey, - [projectKey]: upsertHistoryEntry( - state.byProjectKey[projectKey] ?? [], - normalized, - at, - options, - ), - }), - }; - }); +type PersistedBrowserHistory = Pick< + BrowserHistoryStoreState, + "byProjectKey" | "projectKeyByThreadKey" +>; + +type UpdateHistory = (state: PersistedBrowserHistory) => PersistedBrowserHistory; + +function boundThreadMappings( + previous: PersistedBrowserHistory, + next: PersistedBrowserHistory, +): PersistedBrowserHistory { + return { + ...next, + projectKeyByThreadKey: Object.fromEntries( + Object.entries(next.projectKeyByThreadKey) + // Keep new registrations for empty projects, but drop projects that lost their history. + .filter( + ([, projectKey]) => + !Object.hasOwn(previous.byProjectKey, projectKey) || + Object.hasOwn(next.byProjectKey, projectKey), + ) + .slice(-MAX_PERSISTED_THREAD_MAPPINGS), + ), + }; +} + +const HISTORY_OBJECT_STORE = "history"; +const EMPTY_PERSISTED_HISTORY: PersistedBrowserHistory = { + byProjectKey: {}, + projectKeyByThreadKey: {}, +}; +let historyDatabase: Promise | undefined; +let historyChannel: BroadcastChannel | undefined; + +function readLegacyHistory( + missing: Missing = EMPTY_PERSISTED_HISTORY as Missing, +): PersistedBrowserHistory | Missing { + try { + const value = window.localStorage.getItem(BROWSER_HISTORY_STORAGE_KEY); + if (value === null) return missing; + const parsed: { state?: unknown } | null = JSON.parse(value); + return { + ...migratePersistedBrowserHistoryState(parsed?.state), + projectKeyByThreadKey: migratePersistedThreadProjectKeys(parsed?.state), + }; + } catch { + return EMPTY_PERSISTED_HISTORY; + } +} + +function retireLegacyHistory(): void { + try { + window.localStorage.removeItem(BROWSER_HISTORY_STORAGE_KEY); + } catch { + // The browser can deny access to localStorage independently of IndexedDB. + } +} + +// localStorage can gain visits after migration: from the fallback below, or a tab on an older build. +function mergeLegacyHistory( + saved: PersistedBrowserHistory, + legacy: PersistedBrowserHistory, +): PersistedBrowserHistory { + const byProjectKey = { ...saved.byProjectKey }; + for (const [projectKey, entries] of Object.entries(legacy.byProjectKey)) + byProjectKey[projectKey] = [...(byProjectKey[projectKey] ?? []), ...entries]; + return { + ...migratePersistedBrowserHistoryState({ byProjectKey }), + projectKeyByThreadKey: { ...legacy.projectKeyByThreadKey, ...saved.projectKeyByThreadKey }, + }; +} + +// Without IndexedDB, merge into the freshest localStorage snapshot so a reload keeps new visits. +function transactLegacyHistory(update: UpdateHistory, current: PersistedBrowserHistory) { + const previous = readLegacyHistory(current); + const next = update(previous); + if (next === previous) return previous; + const history = boundThreadMappings(previous, next); + try { + window.localStorage.setItem( + BROWSER_HISTORY_STORAGE_KEY, + JSON.stringify({ state: history, version: 1 }), + ); + } catch { + // History stays in memory when the browser denies both storage APIs. + } + return history; +} + +function invalidateHistoryDatabase(opening: Promise): void { + if (historyDatabase === opening) historyDatabase = undefined; +} + +function openHistoryDatabase() { + if (historyDatabase) return historyDatabase; + const opening = new Promise((resolve, reject) => { + const request = indexedDB.open(BROWSER_HISTORY_STORAGE_KEY, 1); + request.onupgradeneeded = () => request.result.createObjectStore(HISTORY_OBJECT_STORE); + request.onsuccess = () => { + const db = request.result; + db.onclose = () => invalidateHistoryDatabase(opening); + db.onversionchange = () => { + invalidateHistoryDatabase(opening); + db.close(); + }; + resolve(db); + }; + request.onerror = () => reject(request.error); + }); + historyDatabase = opening; + void opening.catch(() => invalidateHistoryDatabase(opening)); + return opening; +} + +async function transactIndexedHistory(update?: UpdateHistory, retry = true) { + const opening = openHistoryDatabase(); + const db = await opening; + let transaction: IDBTransaction; + try { + transaction = db.transaction(HISTORY_OBJECT_STORE, update ? "readwrite" : "readonly"); + } catch (error) { + if (error instanceof DOMException && error.name === "InvalidStateError") { + invalidateHistoryDatabase(opening); + if (retry) return transactIndexedHistory(update, false); + } + throw error; + } + + return new Promise<{ history: PersistedBrowserHistory; changed: boolean }>((resolve, reject) => { + const store = transaction.objectStore(HISTORY_OBJECT_STORE); + const request = store.get(BROWSER_HISTORY_STORAGE_KEY); + let history: PersistedBrowserHistory; + let changed = false; + request.onsuccess = () => { + const saved = request.result as PersistedBrowserHistory | undefined; + const legacy = update ? readLegacyHistory(null) : null; + const previous = + saved && legacy + ? mergeLegacyHistory(saved, legacy) + : (saved ?? legacy ?? EMPTY_PERSISTED_HISTORY); + const next = update?.(previous) ?? previous; + history = next === previous ? previous : boundThreadMappings(previous, next); + changed = history !== saved; + if (update && changed) store.put(history, BROWSER_HISTORY_STORAGE_KEY); + }; + transaction.oncomplete = () => { + // Keep the migration source until the IndexedDB snapshot has committed. + if (update) retireLegacyHistory(); + resolve({ history, changed }); + }; + transaction.onabort = () => reject(transaction.error); + }); +} + +export const useBrowserHistoryStore = create()((set, get) => { + const publish = ({ byProjectKey }: PersistedBrowserHistory) => { + if (byProjectKey !== get().byProjectKey) set({ byProjectKey }); + }; + const updateHistory = (update: UpdateHistory) => { + if (typeof window === "undefined") { + publish(update(get())); + return; + } + void transactIndexedHistory(update).then( + ({ history, changed }) => { + publish(history); + // oxlint-disable-next-line unicorn/require-post-message-target-origin -- BroadcastChannel is scoped to the origin + if (changed) historyChannel?.postMessage(null); }, - setTitleForUrl: (projectKey, url, title, environmentHostname) => { - const normalized = normalizeHistoryUrl(url); - const state = get(); + () => { + const { byProjectKey, projectKeyByThreadKey } = get(); + publish(transactLegacyHistory(update, { byProjectKey, projectKeyByThreadKey })); + }, + ); + }; + + return mergeBrowserHistoryState(undefined, { + byProjectKey: {}, + projectKeyByThreadKey: {}, + pendingVisitsByThreadKey: {}, + recordVisit: (projectKey, url, at, options) => { + const normalized = normalizeHistoryUrl(url); + if (!normalized) return; + updateHistory((state) => { + const entries = state.byProjectKey[projectKey] ?? []; + return { + ...state, + byProjectKey: evictExcessProjects({ + ...state.byProjectKey, + [projectKey]: upsertHistoryEntry(entries, normalized, at, { + ...options, + insertOrdered: options?.insertOrdered || (entries[0]?.lastVisitedAt ?? at) > at, + }), + }), + }; + }); + }, + setTitleForUrl: (projectKey, url, title, options) => { + const normalized = normalizeHistoryUrl(url); + const trimmed = title.trim().slice(0, BROWSER_HISTORY_MAX_TITLE_LENGTH); + if (!normalized || trimmed.length === 0) return; + const key = titleLookupKey(normalized, options?.environmentHostname); + updateHistory((state) => { const entries = state.byProjectKey[projectKey]; - const trimmed = title.trim().slice(0, BROWSER_HISTORY_MAX_TITLE_LENGTH); - if (!normalized || !entries || trimmed.length === 0) return; - const key = titleLookupKey(normalized, environmentHostname); - const index = entries.findIndex( - (candidate) => titleLookupKey(candidate.url, environmentHostname) === key, - ); - if (index === -1 || entries[index]?.title === trimmed) return; - set({ + const index = + entries?.findIndex( + (candidate) => titleLookupKey(candidate.url, options?.environmentHostname) === key, + ) ?? -1; + const entry = entries?.[index]; + if ( + !entries || + !entry || + entry.title === trimmed || + (entry.title && options?.onlyIfUntitled) + ) + return state; + return { + ...state, byProjectKey: { ...state.byProjectKey, - [projectKey]: entries.map((candidate, candidateIndex) => - candidateIndex === index ? { ...candidate, title: trimmed } : candidate, - ), + [projectKey]: entries.with(index, { ...entry, title: trimmed }), }, - }); - }, - removeUrl: (projectKey, url) => { - const normalized = normalizeHistoryUrl(url); - const state = get(); + }; + }); + }, + removeUrl: (projectKey, url) => { + const normalized = normalizeHistoryUrl(url); + if (!normalized) return; + updateHistory((state) => { const entries = state.byProjectKey[projectKey]; - if (!normalized || !entries) return; + if (!entries) return state; const next = entries.filter((candidate) => candidate.url !== normalized); - if (next.length === entries.length) return; - if (next.length === 0) { - const { [projectKey]: _removed, ...rest } = state.byProjectKey; - set({ byProjectKey: rest }); - return; - } - set({ byProjectKey: { ...state.byProjectKey, [projectKey]: next } }); - }, - registerThreadProject: (ref, projectKey) => { - const threadKey = scopedThreadKey(ref); - const state = get(); - const pendingVisits = state.pendingVisitsByThreadKey[threadKey]; - if (state.projectKeyByThreadKey[threadKey] === projectKey && !pendingVisits) return; - const nextPendingVisits = { ...state.pendingVisitsByThreadKey }; - delete nextPendingVisits[threadKey]; - set({ - projectKeyByThreadKey: { ...state.projectKeyByThreadKey, [threadKey]: projectKey }, - pendingVisitsByThreadKey: nextPendingVisits, + if (next.length === entries.length) return state; + const byProjectKey = { ...state.byProjectKey }; + if (next.length === 0) delete byProjectKey[projectKey]; + else byProjectKey[projectKey] = next; + return { ...state, byProjectKey }; + }); + }, + registerThreadProject: (ref, projectKey) => { + const threadKey = scopedThreadKey(ref); + const state = get(); + const pendingVisits = state.pendingVisitsByThreadKey[threadKey]; + if (state.projectKeyByThreadKey[threadKey] === projectKey && !pendingVisits) return; + const nextPendingVisits = { ...state.pendingVisitsByThreadKey }; + delete nextPendingVisits[threadKey]; + set({ + projectKeyByThreadKey: { ...state.projectKeyByThreadKey, [threadKey]: projectKey }, + pendingVisitsByThreadKey: nextPendingVisits, + }); + updateHistory((shared) => + shared.projectKeyByThreadKey[threadKey] === projectKey + ? shared + : { + ...shared, + projectKeyByThreadKey: { ...shared.projectKeyByThreadKey, [threadKey]: projectKey }, + }, + ); + for (const visit of pendingVisits ?? []) + get().recordVisit(projectKey, visit.url, visit.at, { + insertOrdered: true, + environmentHostname: visit.environmentHostname, + }); + if (pendingVisits) + recordPreviewTitles(ref, readThreadPreviewState(ref), { + urls: pendingVisits.map((visit) => visit.url), }); - for (const visit of pendingVisits ?? []) - get().recordVisit(projectKey, visit.url, visit.at, { - insertOrdered: true, - environmentHostname: visit.environmentHostname, - }); - if (pendingVisits) - recordPreviewTitles(ref, readThreadPreviewState(ref), { - urls: pendingVisits.map((visit) => visit.url), - }); - }, - }), - { - name: BROWSER_HISTORY_STORAGE_KEY, - version: 1, - storage: createJSONStorage(() => - resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined), - ), - partialize: (state) => ({ - byProjectKey: state.byProjectKey, - projectKeyByThreadKey: state.projectKeyByThreadKey, - }), - migrate: migratePersistedBrowserHistoryState, - merge: mergeBrowserHistoryState, }, - ), -); + }); +}); + +if (typeof window !== "undefined") { + try { + historyChannel = new BroadcastChannel(BROWSER_HISTORY_STORAGE_KEY); + } catch { + // History still persists when the browser cannot send change notifications. + } + if (historyChannel) { + historyChannel.onmessage = () => { + void transactIndexedHistory().then( + ({ history }) => useBrowserHistoryStore.setState({ byProjectKey: history.byProjectKey }), + () => undefined, + ); + }; + } + const hydrate = (history: PersistedBrowserHistory) => { + useBrowserHistoryStore.setState((state) => ({ + byProjectKey: history.byProjectKey, + projectKeyByThreadKey: { + ...migratePersistedThreadProjectKeys(history, history.byProjectKey), + ...state.projectKeyByThreadKey, + }, + })); + }; + void transactIndexedHistory((history) => history).then( + ({ history }) => hydrate(history), + () => hydrate(readLegacyHistory()), + ); + import.meta.hot?.dispose(() => { + historyChannel?.close(); + historyChannel = undefined; + void historyDatabase?.then( + (db) => db.close(), + () => undefined, + ); + }); +} export function mergeBrowserHistoryState( persistedState: unknown, @@ -331,19 +543,16 @@ export function mergeBrowserHistoryState( function migratePersistedThreadProjectKeys( persistedState: unknown, - byProjectKey: Record, + byProjectKey?: Record, ): Record { if (!persistedState || typeof persistedState !== "object") return {}; const raw = (persistedState as { projectKeyByThreadKey?: unknown }).projectKeyByThreadKey; if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {}; - return Object.fromEntries( - Object.entries(raw as Record) - .filter( - (entry): entry is [string, string] => - typeof entry[1] === "string" && entry[1] in byProjectKey, - ) - .slice(-100), + const entries = Object.entries(raw as Record).filter( + (entry): entry is [string, string] => + typeof entry[1] === "string" && (!byProjectKey || Object.hasOwn(byProjectKey, entry[1])), ); + return Object.fromEntries(entries.slice(-MAX_PERSISTED_THREAD_MAPPINGS)); } /** @@ -435,24 +644,14 @@ function recordPreviewTitles( ): void { const state = useBrowserHistoryStore.getState(); const projectKey = state.projectKeyByThreadKey[scopedThreadKey(ref)]; - if (!projectKey || !state.byProjectKey[projectKey]?.length) return; + if (!projectKey) return; const connection = readPreparedConnection(ref.environmentId); const environmentHostname = connection ? new URL(connection.httpBaseUrl).hostname : null; const titleKey = (url: string) => { const normalized = normalizeHistoryUrl(url); return normalized ? titleLookupKey(normalized, environmentHostname) : null; }; - const titled = new Set( - "urls" in only - ? state.byProjectKey[projectKey]?.flatMap((entry) => - entry.title ? [titleLookupKey(entry.url, environmentHostname)] : [], - ) - : [], - ); - const visitKeys = - "urls" in only - ? new Set(only.urls.map(titleKey).filter((key) => key !== null && !titled.has(key))) - : null; + const visitKeys = "urls" in only ? new Set(only.urls.map(titleKey)) : null; // Resizes and list reconciles replace a session without loading a new page. const settledAgain = (session: PreviewSessionSnapshot, previous?: PreviewSessionSnapshot) => previous?.navStatus._tag === "Success" && @@ -463,15 +662,20 @@ function recordPreviewTitles( "changedSince" in only ? !settledAgain(session, only.changedSince[session.tabId]) : (visitKeys?.has(titleKey(url)) ?? false); - // Tabs can share a URL; applying oldest first lets the newest settle win. + // A fill uses the newest eligible title first because it only sets an untitled entry. const sessions = Object.values(preview.sessions).toSorted((a, b) => - a.updatedAt.localeCompare(b.updatedAt), + "urls" in only + ? b.updatedAt.localeCompare(a.updatedAt) + : a.updatedAt.localeCompare(b.updatedAt), ); for (const session of sessions) { const status = session.navStatus; if (session.profileId === INCOGNITO_BROWSER_PROFILE_ID) continue; if (status._tag !== "Success" || !status.title || !include(session, status.url)) continue; - state.setTitleForUrl(projectKey, status.url, status.title, environmentHostname); + state.setTitleForUrl(projectKey, status.url, status.title, { + environmentHostname, + onlyIfUntitled: "urls" in only, + }); } } @@ -555,5 +759,4 @@ export function resetBrowserHistoryForTests(): void { projectKeyByThreadKey: {}, pendingVisitsByThreadKey: {}, }); - useBrowserHistoryStore.persist.clearStorage(); } diff --git a/scripts/scenarios/browser-history-keeps-visits-from-both-tabs.e2e.ts b/scripts/scenarios/browser-history-keeps-visits-from-both-tabs.e2e.ts new file mode 100644 index 0000000000000..738d7f8b9df00 --- /dev/null +++ b/scripts/scenarios/browser-history-keeps-visits-from-both-tabs.e2e.ts @@ -0,0 +1,76 @@ +/// +// @effect-diagnostics-next-line nodeBuiltinImport:off - fixture pages for the server's browser +import * as NodeHttp from "node:http"; + +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "Browser history keeps visits from both open tabs after a reload", + WEB, + async ({ t3, app, browser, screen }) => { + const server = NodeHttp.createServer((request, response) => { + const title = request.url === "/first" ? "First preview visit" : "Second preview visit"; + response.writeHead(200, { "content-type": "text/html" }); + response.end(`${title}

    ${title}

    `); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + try { + const address = server.address(); + if (address === null || typeof address === "string") throw new Error("No page port."); + const host = `127.0.0.1:${address.port}`; + const origin = `http://${host}`; + const project = await t3.project("demo"); + const first = await t3.thread({ project, title: "First browser", messages: ["first"] }); + const second = await t3.thread({ project, title: "Second browser", messages: ["second"] }); + const history = await t3.thread({ project, title: "History check", messages: ["third"] }); + await t3.open(first); + + // Load the second app before either visit, with an independent store and shared storage. + await browser.evaluate((threadId) => { + const frame = document.createElement("iframe"); + frame.id = "second-client"; + frame.src = location.pathname.replace(/[^/]+$/, threadId); + frame.style.cssText = + "position:fixed;inset:0;width:100%;height:100%;border:0;z-index:2147483647"; + document.body.append(frame); + return null; + }, second.threadId); + const other = browser.frameLocator("#second-client"); + await other.getByRole("button", "Toggle right panel").tap(); + await other.getByRole("button", "Browser B").tap(); + const otherAddress = other.getByRole("textbox", "Search or enter URL"); + await otherAddress.waitFor(); + await browser.evaluate(() => { + document.querySelector("#second-client")!.style.display = "none"; + return null; + }); + + await screen.getByRole("button", "Toggle right panel").tap(); + await screen.getByRole("button", "Browser B").tap(); + await screen.getByRole("textbox", "Search or enter URL").fill(`${origin}/first`); + await browser.keyboard.press("Enter"); + await screen.getByText("First preview visit", { exact: true }).waitFor(); + + await browser.evaluate(() => { + document.querySelector("#second-client")!.style.display = ""; + return null; + }); + await otherAddress.fill(`${origin}/second`); + await browser.keyboard.press("Enter"); + await other.getByText("Second preview visit", { exact: true }).waitFor(); + + const historyUrl = new URL(await browser.url()); + historyUrl.pathname = historyUrl.pathname.replace(/[^/]+$/, history.threadId); + await app.open(historyUrl.pathname); + await screen.getByRole("button", "Toggle right panel").tap(); + await screen.getByRole("button", "Browser B").tap(); + await screen.getByText(`${host}/second`, { exact: false }).waitFor(); + await app.screenshot("browser-history-after-both-visits"); + await expect(screen.getByText(`${host}/first`, { exact: false })).toBeVisible(); + } finally { + await new Promise((resolve) => server.close(resolve)); + } + }, +); From fd4284d8b23529ef82495e499b173ce32670968b Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:52:24 +0100 Subject: [PATCH 061/139] fix(vcs): refresh branch pickers after external worktree changes (#40556) Co-authored-by: Julius Marminge --- .../threads/NewTaskContextPickerScreens.tsx | 2 + .../git/GitBranchesSheet.occupancy.test.tsx | 5 +- .../threads/git/GitBranchesSheet.test.tsx | 1 + .../features/threads/git/GitBranchesSheet.tsx | 2 + .../threads/use-refresh-branches-on-focus.ts | 25 ++ apps/server/src/git/GitWorkflowService.ts | 4 +- apps/server/src/vcs/GitVcsDriver.ts | 6 +- apps/server/src/vcs/GitVcsDriverCore.test.ts | 223 +++++++++++++----- apps/server/src/vcs/GitVcsDriverCore.ts | 162 ++++++++----- .../src/vcs/VcsStatusBroadcaster.test.ts | 34 ++- apps/server/src/vcs/VcsStatusBroadcaster.ts | 14 +- .../BranchToolbarBranchSelector.tsx | 4 +- .../components/WorktreeBaseBranchPicker.tsx | 7 + packages/client-runtime/src/state/vcs.test.ts | 12 +- packages/client-runtime/src/state/vcs.ts | 3 + ...ranch-picker-sees-external-worktree.e2e.ts | 71 ++++++ 16 files changed, 439 insertions(+), 136 deletions(-) create mode 100644 apps/mobile/src/features/threads/use-refresh-branches-on-focus.ts create mode 100644 scripts/scenarios/branch-picker-sees-external-worktree.e2e.ts diff --git a/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx b/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx index 97a3ce45fab3a..a8cc689b7a5cf 100644 --- a/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx +++ b/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx @@ -36,6 +36,7 @@ import { cn } from "../../lib/cn"; import { useEnvironmentScope } from "../../state/session"; import { useAtomCommand } from "../../state/use-atom-command"; import { vcsEnvironment } from "../../state/vcs"; +import { useRefreshBranchesOnFocus } from "./use-refresh-branches-on-focus"; import { useSearchToolbarInset } from "../../components/ui/useBarInset"; import type { AppBarSearch } from "../../components/ui/AppBar"; import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider"; @@ -466,6 +467,7 @@ export function BranchPickerScreen(props: { const m = useMessages(); const navigation = useNavigation(); const insets = useSafeAreaInsets(); + useRefreshBranchesOnFocus(props.project?.environmentId, props.project?.workspaceRoot); const search: AppBarSearch = { value: props.query, onChangeText: props.onQueryChange, diff --git a/apps/mobile/src/features/threads/git/GitBranchesSheet.occupancy.test.tsx b/apps/mobile/src/features/threads/git/GitBranchesSheet.occupancy.test.tsx index 436fb4dd0b403..8653d859442f4 100644 --- a/apps/mobile/src/features/threads/git/GitBranchesSheet.occupancy.test.tsx +++ b/apps/mobile/src/features/threads/git/GitBranchesSheet.occupancy.test.tsx @@ -8,7 +8,10 @@ const checkout = vi.hoisted(() => ({ branches: [] as Array<{ name: string; worktreePath: string | null }>, })); -vi.mock("@react-navigation/native", () => ({ useNavigation: () => ({}) })); +vi.mock("@react-navigation/native", () => ({ + useFocusEffect: () => {}, + useNavigation: () => ({}), +})); vi.mock("../../../components/ui/SheetHeader", () => ({ SheetHeader: () => null })); vi.mock("../../../components/ui/FitSheet", () => ({ FitSheet: ({ children }: { children: ReactNode }) =>
    {children}
    , diff --git a/apps/mobile/src/features/threads/git/GitBranchesSheet.test.tsx b/apps/mobile/src/features/threads/git/GitBranchesSheet.test.tsx index 084dd7880fba1..f0ddc71fea15d 100644 --- a/apps/mobile/src/features/threads/git/GitBranchesSheet.test.tsx +++ b/apps/mobile/src/features/threads/git/GitBranchesSheet.test.tsx @@ -20,6 +20,7 @@ const state = vi.hoisted(() => ({ })); vi.mock("@react-navigation/native", () => ({ + useFocusEffect: () => {}, useNavigation: () => ({ goBack: () => state.goBackCalls++, isFocused: () => state.focused, diff --git a/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx b/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx index df1ad6649c8f7..618996c61500c 100644 --- a/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx @@ -14,6 +14,7 @@ import { useSelectedThreadGitActions } from "../../../state/use-selected-thread- import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state"; import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-worktree"; import { vcsEnvironment } from "../../../state/vcs"; +import { useRefreshBranchesOnFocus } from "../use-refresh-branches-on-focus"; import { SheetActionButton } from "./gitSheetComponents"; type GitBranchesSheetProps = StaticScreenProps<{ @@ -26,6 +27,7 @@ export function GitBranchesSheet(_props: GitBranchesSheetProps) { const navigation = useNavigation(); const { selectedThread } = useThreadSelection(); const { selectedThreadCwd } = useSelectedThreadWorktree(); + useRefreshBranchesOnFocus(selectedThread?.environmentId, selectedThreadCwd); const gitState = useSelectedThreadGitState(); const gitActions = useSelectedThreadGitActions(); const { canChangeThreadBranch } = gitActions; diff --git a/apps/mobile/src/features/threads/use-refresh-branches-on-focus.ts b/apps/mobile/src/features/threads/use-refresh-branches-on-focus.ts new file mode 100644 index 0000000000000..6366994b9641e --- /dev/null +++ b/apps/mobile/src/features/threads/use-refresh-branches-on-focus.ts @@ -0,0 +1,25 @@ +import { RegistryContext } from "@effect/atom-react"; +import { useFocusEffect } from "@react-navigation/native"; +import { runAtomCommand } from "@t3tools/client-runtime/state/runtime"; +import type { EnvironmentId } from "@t3tools/contracts"; +import { useCallback, useContext } from "react"; + +import { vcsEnvironment } from "../../state/vcs"; + +export function useRefreshBranchesOnFocus( + environmentId: EnvironmentId | undefined, + cwd: string | null | undefined, +) { + const registry = useContext(RegistryContext); + useFocusEffect( + useCallback(() => { + if (environmentId === undefined || !cwd) return; + void runAtomCommand( + registry, + vcsEnvironment.refreshLocalStatusForPicker, + { environmentId, input: { cwd } }, + { reportFailure: false }, + ); + }, [cwd, environmentId, registry]), + ); +} diff --git a/apps/server/src/git/GitWorkflowService.ts b/apps/server/src/git/GitWorkflowService.ts index f0757fd7078fe..4cf3e62d9a93f 100644 --- a/apps/server/src/git/GitWorkflowService.ts +++ b/apps/server/src/git/GitWorkflowService.ts @@ -69,7 +69,8 @@ export class GitWorkflowService extends Context.Service< ) => Effect.Effect; readonly invalidateLocalStatus: (cwd: string) => Effect.Effect; readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect; - readonly readRefSnapshot: (cwd: string) => Effect.Effect; + readonly readLocalStatusRefSnapshot: GitVcsDriver.GitVcsDriver["Service"]["readLocalStatusRefSnapshot"]; + readonly readRefSnapshot: GitVcsDriver.GitVcsDriver["Service"]["readRefSnapshot"]; readonly invalidateStatus: (cwd: string) => Effect.Effect; /** The checkout's own HEAD file, inside a linked worktree's admin directory when there is one. */ readonly headPath: (cwd: string) => Effect.Effect; @@ -398,6 +399,7 @@ export const make = Effect.gen(function* () { }), invalidateLocalStatus: gitManager.invalidateLocalStatus, invalidateRemoteStatus: gitManager.invalidateRemoteStatus, + readLocalStatusRefSnapshot: git.readLocalStatusRefSnapshot, readRefSnapshot: git.readRefSnapshot, invalidateStatus: gitManager.invalidateStatus, headPath: Effect.fn("GitWorkflowService.headPath")(function* (cwd) { diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index f341ebd987a6c..3a4dd7cedf10a 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -369,8 +369,10 @@ export class GitVcsDriver extends Context.Service< cwd: string, options?: GitRemoteStatusOptions, ) => Effect.Effect; - /** Refs, HEAD and shallow boundaries. Null when the snapshot cannot be read. */ - readonly readRefSnapshot: (cwd: string) => Effect.Effect; + /** Refs, HEAD and shallow boundaries. Null on read failure. */ + readonly readLocalStatusRefSnapshot: (cwd: string) => Effect.Effect; + /** Includes worktree paths. Accepts an existing local status ref snapshot to avoid re-reading refs. */ + readonly readRefSnapshot: (cwd: string, refs?: string) => Effect.Effect; readonly prepareCommitContext: ( cwd: string, filePaths?: readonly string[], diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 0e9ab873cbb30..d9a661c7b1237 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -302,7 +302,7 @@ const makeTmpDir = ( ): Effect.Effect => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; - return yield* fileSystem.makeTempDirectoryScoped({ prefix }); + return yield* fileSystem.realPath(yield* fileSystem.makeTempDirectoryScoped({ prefix })); }); const writeTextFile = ( @@ -1878,69 +1878,80 @@ describe("pullCurrentBranch", () => { ); }); -it.effect("retries an in-flight ref snapshot invalidated by a mutation", () => - Effect.scoped( - Effect.gen(function* () { - const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; - const firstWorktreeScanStarted = yield* Deferred.make(); - const firstRefScanCompleted = yield* Deferred.make(); - const releaseFirstWorktreeScan = yield* Deferred.make(); - const delayFirstWorktreeScan = yield* Ref.make(true); - const refScans = yield* Ref.make(0); - const coordinatingSpawner = ChildProcessSpawner.make((command) => - Effect.gen(function* () { - if (!ChildProcess.isStandardCommand(command)) { - return yield* Effect.die("expected a standard Git command"); - } - const isWorktreeScan = - command.args.includes("worktree") && command.args.includes("--porcelain"); - if (isWorktreeScan && (yield* Ref.getAndSet(delayFirstWorktreeScan, false))) { - yield* Deferred.succeed(firstWorktreeScanStarted, undefined); - yield* Deferred.await(releaseFirstWorktreeScan); - } - const handle = yield* delegate.spawn(command); - const isRefScan = - command.args.includes("for-each-ref") && - command.args.includes("refs/heads") && - command.args.includes("refs/remotes"); - if (!isRefScan) return handle; - const scan = yield* Ref.updateAndGet(refScans, (count) => count + 1); - return scan === 1 - ? ChildProcessSpawner.makeHandle({ - ...handle, - exitCode: handle.exitCode.pipe( - Effect.tap(() => Deferred.succeed(firstRefScanCompleted, undefined)), +it.effect.each(["a T3 branch creation", "an external worktree addition"] as const)( + "refreshes an in-flight ref snapshot after %s", + (mutation) => + Effect.scoped( + Effect.gen(function* () { + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const firstScanCompleted = yield* Deferred.make(); + const releaseOtherScans = yield* Deferred.make(); + const firstScan = yield* Ref.make(true); + const coordinatingSpawner = ChildProcessSpawner.make((command) => + Effect.gen(function* () { + if (!ChildProcess.isStandardCommand(command)) { + return yield* Effect.die("expected a standard Git command"); + } + const isWorktreeScan = + command.args.includes("worktree") && command.args.includes("--porcelain"); + const isRefScan = + command.args.includes("for-each-ref") && + command.args.includes("refs/heads") && + command.args.includes("refs/remotes"); + if (!isRefScan && (!isWorktreeScan || mutation === "a T3 branch creation")) { + return yield* delegate.spawn(command); + } + if (!(yield* Ref.getAndSet(firstScan, false))) { + yield* Deferred.await(releaseOtherScans); + return yield* delegate.spawn(command); + } + const handle = yield* delegate.spawn(command); + return ChildProcessSpawner.makeHandle({ + ...handle, + exitCode: handle.exitCode.pipe( + Effect.tap(() => + Deferred.succeed(firstScanCompleted, undefined).pipe( + Effect.andThen(Deferred.await(releaseOtherScans)), + ), ), - }) - : handle; - }), - ); - const driver = yield* makeGitVcsDriverCore().pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, coordinatingSpawner), - ); - const cwd = yield* makeTmpDir(); - yield* initRepoWithCommit(cwd).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, driver)); - - const inFlight = yield* driver - .listRefs({ cwd, refresh: true, limit: 100 }) - .pipe(Effect.forkChild({ startImmediately: true })); - yield* Deferred.await(firstWorktreeScanStarted); - yield* Deferred.await(firstRefScanCompleted); - - yield* driver.createRef({ cwd, refName: "feature/during-refresh" }); - yield* Deferred.succeed(releaseFirstWorktreeScan, undefined); + ), + }); + }), + ); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, coordinatingSpawner), + ); + const cwd = yield* makeTmpDir(); + const worktree = (yield* Path.Path).join(cwd, "linked checkout"); + const refName = "feature/during-refresh"; + yield* initRepoWithCommit(cwd).pipe( + Effect.provideService(GitVcsDriver.GitVcsDriver, driver), + ); + const list = driver.listRefs({ cwd, refresh: true, query: refName }); + const inFlight = yield* list.pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(firstScanCompleted); - const refs = yield* Fiber.join(inFlight); - assert.isTrue(refs.refs.some((ref) => ref.name === "feature/during-refresh")); - assert.equal(yield* Ref.get(refScans), 2); - }), - ).pipe( - Effect.provide( - layerServerConfig.pipe( - Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + if (mutation === "a T3 branch creation") { + yield* driver.createRef({ cwd, refName }); + yield* Deferred.succeed(releaseOtherScans, undefined); + assert.equal((yield* Fiber.join(inFlight)).refs[0]?.name, refName); + } else { + yield* git(cwd, ["worktree", "add", "-b", refName, worktree]).pipe( + Effect.provideService(GitVcsDriver.GitVcsDriver, driver), + ); + const refresh = yield* list.pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.succeed(releaseOtherScans, undefined); + assert.equal((yield* Fiber.join(refresh)).refs[0]?.worktreePath, worktree); + yield* Fiber.join(inFlight); + } + }), + ).pipe( + Effect.provide( + layerServerConfig.pipe( + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), ), ), - ), ); it.effect("a refreshed ref list reads the current branch and repository paths once", () => @@ -1985,6 +1996,40 @@ it.effect("a refreshed ref list reads the current branch and repository paths on ), ); +it.effect("keeps cached branch occupancy when Git cannot rescan worktrees", () => + Effect.scoped( + Effect.gen(function* () { + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + let failWorktreeScan = false; + const spawner = ChildProcessSpawner.make((command) => + failWorktreeScan && + ChildProcess.isStandardCommand(command) && + command.args.includes("worktree") && + command.args.includes("--porcelain") + ? Effect.fail( + PlatformError.systemError({ + _tag: "Unknown", + module: "ChildProcess", + method: "spawn", + }), + ) + : delegate.spawn(command), + ); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const list = driver.listRefs({ cwd, refresh: true, query: initialBranch }); + const cached = yield* list; + assert.equal(cached.refs[0]?.worktreePath, cwd); + + failWorktreeScan = true; + assert.deepEqual(yield* list, cached); + }).pipe(Effect.provide(layerTest)), + ), +); + it.effect("superseded ref snapshots of one repository do not evict another's", () => Effect.scoped( Effect.gen(function* () { @@ -2073,6 +2118,35 @@ it.effect("invalidates a ref snapshot when a mutation fails after changing Git", ), ); +it.effect("lists external worktree paths even within the ref snapshot refresh window", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const path = yield* Path.Path; + const worktree = path.join(cwd, "another checkout"); + const movedWorktree = path.join(cwd, "moved checkout"); + yield* initRepoWithCommit(cwd); + yield* git(cwd, ["branch", "feature"]); + const driver = yield* GitVcsDriver.GitVcsDriver; + const list = driver.listRefs({ cwd, refresh: true, query: "feature" }); + yield* list; + + yield* git(cwd, ["worktree", "add", worktree, "feature"]); + assert.equal((yield* list).refs[0]?.worktreePath, worktree); + yield* git(cwd, ["worktree", "move", worktree, movedWorktree]); + assert.equal((yield* list).refs[0]?.worktreePath, movedWorktree); + yield* git(cwd, ["worktree", "remove", movedWorktree]); + assert.isNull((yield* list).refs[0]?.worktreePath); + + yield* git(cwd, ["worktree", "add", "-b", "new-branch", worktree]); + const newBranchQuery = { cwd, query: "new-branch" }; + assert.equal( + (yield* driver.listRefs({ ...newBranchQuery, refresh: true })).refs[0]?.worktreePath, + worktree, + ); + assert.equal((yield* driver.listRefs(newBranchQuery)).refs[0]?.worktreePath, worktree); + }).pipe(Effect.provide(layerTest), Effect.scoped), +); + it.effect("marks the current branch when worktree metadata is unavailable", () => Effect.scoped( Effect.gen(function* () { @@ -5852,6 +5926,35 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("a ref snapshot detects which branches are checked out in other worktrees", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const worktree = (yield* Path.Path).join(cwd, "linked checkout"); + yield* initRepoWithCommit(cwd); + yield* git(cwd, ["branch", "feature"]); + yield* git(cwd, ["branch", "same-commit"]); + const driver = yield* GitVcsDriver.GitVcsDriver; + const snapshot = driver.readRefSnapshot(cwd); + const initial = yield* snapshot; + assert.isNotNull(initial); + + yield* git(cwd, ["worktree", "add", "--detach", worktree]); + assert.equal(yield* snapshot, initial); + yield* git(worktree, ["checkout", "feature"]); + const attached = yield* snapshot; + assert.isNotNull(attached); + assert.notEqual(attached, initial); + assert.equal(yield* snapshot, attached); + yield* git(worktree, ["checkout", "same-commit"]); + const switched = yield* snapshot; + assert.isNotNull(switched); + assert.notEqual(switched, attached); + assert.notEqual(switched, initial); + yield* git(cwd, ["worktree", "remove", worktree]); + assert.equal(yield* snapshot, initial); + }), + ); + it.effect("a ref snapshot detects branch identity, ref and ancestry changes", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index a6aab054d37dc..8f3e3e16ca12b 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -220,6 +220,7 @@ interface GitRefsSnapshot { readonly localBranches: ReadonlyArray; readonly remoteBranches: ReadonlyArray; readonly hasPrimaryRemote: boolean; + readonly worktreeStamp: string | null; } interface ExecuteGitOptions { @@ -1353,6 +1354,50 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return { ...lineResult, stdout: lineResult.stdout.replaceAll("\n", "\0") }; }); + const readWorktreeBranchPaths = Effect.fn("GitVcsDriver.readWorktreeBranchPaths")(function* ( + gitCommonDir: string, + ) { + const cwd = path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir; + const result = yield* executeWorktreeList( + "GitVcsDriver.readWorktreeBranchPaths", + cwd, + ["--git-dir", gitCommonDir], + { allowNonZeroExit: true, maxOutputBytes: 16 * 1024 * 1024 }, + ); + if (result.exitCode !== 0) return null; + + const entries = [...parseWorktreeBranchPaths(result.stdout)].map( + ([branchName, worktreePath]) => + [branchName, path.normalize(path.resolve(worktreePath))] as const, + ); + // Without core.worktree, Git reports a separate git dir as the main checkout. + const normalizedGitCommonDir = path.normalize(path.resolve(gitCommonDir)); + const existing = yield* Effect.filter( + entries, + ([, worktreePath]) => + worktreePath === normalizedGitCommonDir + ? Effect.succeed(false) + : fileSystem.stat(worktreePath).pipe( + Effect.as(true), + Effect.orElseSucceed(() => false), + ), + { concurrency: 16 }, + ); + return { + paths: new Map(existing), + stamp: existing + .map((entry) => JSON.stringify(entry)) + .sort() + .join("\n"), + }; + }); + + // Share overlapping reads without retaining occupancy across external Git commands. + const worktreeBranchPathsCache = yield* Cache.makeWith(readWorktreeBranchPaths, { + capacity: LIST_REFS_SNAPSHOT_CACHE_CAPACITY, + timeToLive: () => Duration.zero, + }); + const runGitStdoutWithOptions = ( operation: string, cwd: string, @@ -1960,12 +2005,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ), }); - const readRefSnapshot: GitVcsDriver.GitVcsDriver["Service"]["readRefSnapshot"] = Effect.fn( - "GitVcsDriver.readRefSnapshot", - )( - function* (cwd) { + const readLocalStatusRefSnapshot = Effect.fn("GitVcsDriver.readLocalStatusRefSnapshot")( + function* (cwd: string) { const result = yield* executeGit( - "GitVcsDriver.readRefSnapshot", + "GitVcsDriver.readLocalStatusRefSnapshot", cwd, ["show-ref", "--head"], { @@ -1975,7 +2018,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ); if (result.exitCode !== 0) return null; const symbolicHead = yield* executeGit( - "GitVcsDriver.readRefSnapshot", + "GitVcsDriver.readLocalStatusRefSnapshot", cwd, ["symbolic-ref", "--quiet", "HEAD"], { allowNonZeroExit: true }, @@ -1983,7 +2026,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* // Exit 1 means detached HEAD; other failures require a full status read. if (symbolicHead.exitCode !== 0 && symbolicHead.exitCode !== 1) return null; // Deepening a shallow clone changes ancestry without moving refs. - const shallowPath = path.join(yield* resolveGitCommonDir(cwd), "shallow"); + const gitCommonDir = yield* resolveGitCommonDir(cwd); + const shallowPath = path.join(gitCommonDir, "shallow"); const shallow = (yield* fileSystem.exists(shallowPath)) ? yield* fileSystem.readFileString(shallowPath) : ""; @@ -1992,6 +2036,22 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* Effect.orElseSucceed(() => null), ); + const readRefSnapshot: GitVcsDriver.GitVcsDriver["Service"]["readRefSnapshot"] = Effect.fn( + "GitVcsDriver.readRefSnapshot", + )( + function* (cwd, refs) { + const localRefs = refs ?? (yield* readLocalStatusRefSnapshot(cwd)); + if (localRefs === null) return null; + const gitCommonDir = yield* resolveGitCommonDir(cwd); + const worktrees = yield* Cache.get(worktreeBranchPathsCache, gitCommonDir).pipe( + Effect.timeoutOption(5_000), + Effect.map(Option.getOrNull), + ); + return worktrees === null ? null : `${localRefs}\0${worktrees.stamp}`; + }, + Effect.orElseSucceed(() => null), + ); + // Returns the upstream remote name it read, or undefined when it did not read one. const refreshStatusUpstreamIfStale = Effect.fn("refreshStatusUpstreamIfStale")(function* ( cwd: string, @@ -5306,7 +5366,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const fetchCwd = path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir; const gitDirArgs = ["--git-dir", gitCommonDir] as const; - const [refsResult, defaultRefResult, worktreeListResult, remoteNamesResult] = yield* Effect.all( + // Read occupancy first so a concurrent worktree addition changes the cached stamp. + const worktrees = yield* Cache.get(worktreeBranchPathsCache, gitCommonDir); + const [refsResult, defaultRefResult, remoteNamesResult] = yield* Effect.all( [ executeGitWithStableDiagnostics( "GitVcsDriver.listRefs.snapshotRefs", @@ -5340,11 +5402,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* allowNonZeroExit: true, }, ), - executeWorktreeList("GitVcsDriver.listRefs.worktreeList", fetchCwd, gitDirArgs, { - timeoutMs: 30_000, - allowNonZeroExit: true, - maxOutputBytes: 16 * 1024 * 1024, - }), executeGit("GitVcsDriver.listRefs.remoteNames", fetchCwd, [...gitDirArgs, "remote"], { timeoutMs: 5_000, allowNonZeroExit: true, @@ -5364,27 +5421,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* defaultRefResult.exitCode === 0 ? parseDefaultBranchFromRemoteHeadRef(defaultRefResult.stdout, "origin") : null; - const parsedWorktreeEntries = - worktreeListResult.exitCode === 0 - ? [...parseWorktreeBranchPaths(worktreeListResult.stdout)].map( - ([branchName, worktreePath]) => - [branchName, path.normalize(path.resolve(worktreePath))] as const, - ) - : []; - // Without `core.worktree`, Git reports a separate git dir as the main checkout. - const normalizedGitCommonDir = path.normalize(path.resolve(gitCommonDir)); - const existingWorktreeEntries = yield* Effect.filter( - parsedWorktreeEntries, - ([, worktreePath]) => - worktreePath === normalizedGitCommonDir - ? Effect.succeed(false) - : fileSystem.stat(worktreePath).pipe( - Effect.as(true), - Effect.orElseSucceed(() => false), - ), - { concurrency: 16 }, - ); - const worktreeMap = new Map(existingWorktreeEntries); const localBranches: Array<{ readonly ref: VcsRef; readonly lastCommit: number }> = []; const remoteBranches: Array<{ readonly ref: VcsRef; readonly lastCommit: number }> = []; @@ -5403,7 +5439,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* current: false, isRemote: false, isDefault: name === defaultBranch, - worktreePath: worktreeMap.get(name) ?? null, + worktreePath: worktrees?.paths.get(name) ?? null, ...(upstreamRef ? { upstreamRef } : {}), }, lastCommit, @@ -5441,6 +5477,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* localBranches: localBranches.toSorted(byRecencyThenName).map(({ ref }) => ref), remoteBranches: remoteBranches.toSorted(byRecencyThenName).map(({ ref }) => ref), hasPrimaryRemote: remoteNames.length > 0, + worktreeStamp: worktrees?.stamp ?? null, } satisfies GitRefsSnapshot; }); @@ -5517,6 +5554,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* Exit.isSuccess(exit) ? LIST_REFS_REFRESH_COALESCE_TTL : LIST_REFS_REFRESH_FAILURE_COOLDOWN, }, ); + const invalidateListRefsSnapshots = Effect.fn("GitVcsDriver.invalidateListRefsSnapshots")( + function* (gitCommonDir: string, generation: number) { + bumpListRefsGeneration(gitCommonDir); + yield* advanceListRefsEpoch(gitCommonDir); + yield* Cache.invalidate( + listRefsRefreshSnapshotCache, + new GitRefsRefreshCacheKey({ gitCommonDir, generation }), + ); + }, + ); const resolveListRefsSnapshot = Effect.fn("resolveListRefsSnapshot")(function* ( gitCommonDir: string, refresh: boolean, @@ -5524,17 +5571,28 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* while (true) { const generation = currentListRefsGeneration(gitCommonDir); const currentEpoch = listRefsEpochByCommonDir.get(gitCommonDir); - const snapshot = - refresh || currentEpoch === undefined - ? // Cache the entire snapshot read so slow scans stay single-flight beyond the coalescing TTL. - yield* Cache.get( - listRefsRefreshSnapshotCache, - new GitRefsRefreshCacheKey({ gitCommonDir, generation }), - ) - : yield* Cache.get( - listRefsSnapshotCache, - new GitRefsSnapshotCacheKey({ gitCommonDir, epoch: currentEpoch }), - ); + if (refresh || currentEpoch === undefined) { + const key = new GitRefsRefreshCacheKey({ gitCommonDir, generation }); + const cached = yield* Cache.getOption(listRefsRefreshSnapshotCache, key); + if (Option.isNone(cached)) { + const snapshot = yield* Cache.get(listRefsRefreshSnapshotCache, key); + if (currentListRefsGeneration(gitCommonDir) === generation) return snapshot; + continue; + } + // A joined load may have read occupancy before this refresh was requested. + const worktrees = yield* Cache.get(worktreeBranchPathsCache, gitCommonDir).pipe( + Effect.orElseSucceed(() => null), + ); + if (currentListRefsGeneration(gitCommonDir) !== generation) continue; + if (worktrees === null || cached.value.worktreeStamp === worktrees.stamp) + return cached.value; + yield* invalidateListRefsSnapshots(gitCommonDir, generation); + continue; + } + const snapshot = yield* Cache.get( + listRefsSnapshotCache, + new GitRefsSnapshotCacheKey({ gitCommonDir, epoch: currentEpoch }), + ); if (currentListRefsGeneration(gitCommonDir) === generation) { return snapshot; } @@ -5550,16 +5608,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ? (yield* Cache.get(repositoryPathsCache, repositoryPathsCacheKey))?.gitCommonDir : gitCommonDir; if (commonDir == null) return; - const previousGeneration = currentListRefsGeneration(commonDir); - bumpListRefsGeneration(commonDir); - yield* advanceListRefsEpoch(commonDir); - yield* Cache.invalidate( - listRefsRefreshSnapshotCache, - new GitRefsRefreshCacheKey({ - gitCommonDir: commonDir, - generation: previousGeneration, - }), - ); + yield* invalidateListRefsSnapshots(commonDir, currentListRefsGeneration(commonDir)); yield* Cache.invalidate(repositoryPathsRefreshCache, repositoryPathsCacheKey); yield* Cache.invalidate(repositoryPathsCache, repositoryPathsCacheKey); }); @@ -6980,6 +7029,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* statusDetails, statusDetailsLocal, statusDetailsRemote, + readLocalStatusRefSnapshot, readRefSnapshot, prepareCommitContext, commit: Effect.fnUntraced(function* (cwd, subject, body, options) { diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index 7c5dd63773848..455dadc1766ba 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -81,6 +81,7 @@ function layerTestFor(state: { remoteStatusReusedDetails?: Array; localStatusBranchChanges?: Array; refSnapshot?: string | null; + worktreeStamp?: string | null; remoteStatusError?: GitManagerError; backgroundWorkEnabled?: boolean; automaticFetchInterval?: Effect.Effect; @@ -142,8 +143,16 @@ function layerTestFor(state: { : (state.beforeCurrentBranch ?? Effect.void).pipe( Effect.andThen(Effect.sync(() => state.currentLocalStatus.refName)), ), - readRefSnapshot: () => + readLocalStatusRefSnapshot: () => Effect.sync(() => (state.refSnapshot === undefined ? "refs" : state.refSnapshot)), + readRefSnapshot: (_cwd, refs) => + Effect.sync(() => { + const localRefs = + refs ?? (state.refSnapshot === undefined ? "refs" : state.refSnapshot); + return localRefs === null || state.worktreeStamp === null + ? null + : `${localRefs}\0${state.worktreeStamp ?? ""}`; + }), upstreamDivergence: () => Effect.sync(() => { const refName = state.currentLocalStatus.refName; @@ -965,6 +974,7 @@ describe("VcsStatusBroadcaster", () => { Layer.mock(GitWorkflowService.GitWorkflowService)({ localStatus: () => Effect.succeed(localStatus), currentBranch: () => Effect.succeed(localStatus.refName), + readLocalStatusRefSnapshot: () => Effect.succeed("refs"), readRefSnapshot: () => Effect.succeed("refs"), remoteStatus: () => Effect.succeed(remoteStatus), invalidateLocalStatus: () => Effect.void, @@ -1062,6 +1072,7 @@ describe("VcsStatusBroadcaster", () => { Layer.mock(GitWorkflowService.GitWorkflowService)({ localStatus: () => Effect.succeed(baseLocalStatus), currentBranch: () => Effect.succeed(baseLocalStatus.refName), + readLocalStatusRefSnapshot: () => Effect.succeed("refs"), readRefSnapshot: () => Effect.succeed("refs"), remoteStatus: () => Effect.gen(function* () { @@ -1109,6 +1120,7 @@ describe("VcsStatusBroadcaster", () => { Layer.mock(GitWorkflowService.GitWorkflowService)({ localStatus: () => Effect.succeed(baseLocalStatus), currentBranch: () => Effect.succeed(baseLocalStatus.refName), + readLocalStatusRefSnapshot: () => Effect.succeed("refs"), readRefSnapshot: () => Effect.succeed("refs"), remoteStatus: () => Effect.gen(function* () { @@ -1163,6 +1175,7 @@ describe("VcsStatusBroadcaster", () => { return state.currentLocalStatus; }), currentBranch: () => Effect.succeed(state.currentLocalStatus.refName), + readLocalStatusRefSnapshot: () => Effect.succeed("refs"), readRefSnapshot: () => Effect.succeed("refs"), remoteStatus: () => Effect.suspend(() => { @@ -1553,6 +1566,7 @@ describe("VcsStatusBroadcaster", () => { }), currentBranch: () => Effect.succeed(baseLocalStatus.refName), invalidateRemoteStatus: () => Effect.void, + readLocalStatusRefSnapshot: () => Effect.sync(() => refSnapshot), readRefSnapshot: () => Effect.sync(() => refSnapshot), remoteStatus: () => Deferred.succeed(fetchStarted, undefined).pipe( @@ -1612,6 +1626,24 @@ describe("VcsStatusBroadcaster", () => { assert.equal(state.localStatusCalls, 1); assert.isString(unmoved.refsDigest); + state.localStatusCalls = 0; + state.beforeRemoteStatus = Effect.sync(() => { + state.worktreeStamp = "feature in /linked"; + }); + const worktreeChanged = yield* broadcaster.refreshStatus("/repo"); + assert.equal(state.localStatusCalls, 1); + assert.isString(worktreeChanged.refsDigest); + assert.notEqual(worktreeChanged.refsDigest, unmoved.refsDigest); + + state.localStatusCalls = 0; + state.beforeRemoteStatus = Effect.sync(() => { + state.worktreeStamp = null; + }); + const worktreesUnreadable = yield* broadcaster.refreshStatus("/repo"); + assert.equal(state.localStatusCalls, 1); + assert.isUndefined(worktreesUnreadable.refsDigest); + state.worktreeStamp = "feature in /linked"; + state.localStatusCalls = 0; state.currentRemoteStatus = baseRemoteStatus; state.beforeRemoteStatus = Effect.sync(() => { diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index 156290ed0ca6a..d1e9a9c5496c6 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -702,7 +702,7 @@ export const make = Effect.gen(function* () { if (refsAtLocalRead === undefined) { yield* refreshLocalStatusCore(cwd); } else { - const refs = yield* workflow.readRefSnapshot(cwd); + const refs = yield* workflow.readLocalStatusRefSnapshot(cwd); if (refs === null || refs !== (yield* Ref.get(refsAtLocalRead))) { yield* Ref.set(refsAtLocalRead, null); yield* refreshLocalStatusCore(cwd); @@ -732,7 +732,8 @@ export const make = Effect.gen(function* () { } yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true }); // A fetch, ours or not, can move the base used for local Changes totals. - const refs = refsBeforeLocalRead === null ? null : yield* workflow.readRefSnapshot(cwd); + const refs = + refsBeforeLocalRead === null ? null : yield* workflow.readLocalStatusRefSnapshot(cwd); if (refs === null || refs !== refsBeforeLocalRead) { yield* refreshLocalStatusCore(cwd); } @@ -748,7 +749,7 @@ export const make = Effect.gen(function* () { )(function* (rawCwd, options) { const cwd = yield* withFileSystem(normalizeCwd(rawCwd)); yield* acquireBranchChangesDemand(cwd); - // Lets the client keep its cached branch list when no ref moved since its last refresh. + // Lets the client keep its cached branch list when refs and worktree paths match its last refresh. const withRefsDigest = (status: VcsStatusResult, refs: string | null) => refs === null ? status @@ -765,10 +766,13 @@ export const make = Effect.gen(function* () { const parts = yield* getStatusParts(cwd); return withRefsDigest(mergeGitStatusParts(parts.local, parts.remote), refs); } - const refsBeforeLocalRead = yield* workflow.readRefSnapshot(cwd); + const refsBeforeLocalRead = yield* workflow.readLocalStatusRefSnapshot(cwd); yield* refreshLocalStatusCore(cwd); const { status, refs } = yield* refreshRemoteAndLocalTotals(cwd, rawCwd, refsBeforeLocalRead); - return withRefsDigest(status, refs); + return withRefsDigest( + status, + refs === null ? null : yield* workflow.readRefSnapshot(cwd, refs), + ); }, Effect.scoped); const refreshAfterCheckout: VcsStatusBroadcaster["Service"]["refreshAfterCheckout"] = Effect.fn( diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index 2fb938b04bb40..4bf062b27d93f 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -631,7 +631,7 @@ export function BranchToolbarBranchSelector({ if (branchCwd === null) return; void refreshLocalStatusForPicker({ environmentId, - input: { cwd: branchCwd, localOnly: true }, + input: { cwd: branchCwd }, }); }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- refs listed while the project was cloning are empty; reload them past the server's snapshot when the clone finishes @@ -685,7 +685,7 @@ export function BranchToolbarBranchSelector({ if (open && !isBranchMenuOpen && branchCwd !== null) { void refreshLocalStatusForPicker({ environmentId, - input: { cwd: branchCwd, localOnly: true }, + input: { cwd: branchCwd }, }); } if (!open) { diff --git a/apps/web/src/components/WorktreeBaseBranchPicker.tsx b/apps/web/src/components/WorktreeBaseBranchPicker.tsx index dd6520a11dab8..eb740a78e4233 100644 --- a/apps/web/src/components/WorktreeBaseBranchPicker.tsx +++ b/apps/web/src/components/WorktreeBaseBranchPicker.tsx @@ -5,6 +5,7 @@ import { useState } from "react"; import { usePaginatedBranches } from "../state/queries"; import { useEnvironmentQuery } from "../state/query"; +import { useAtomCommand } from "../state/use-atom-command"; import { vcsEnvironment } from "../state/vcs"; import { BranchPicker, BranchPickerRefItem } from "./BranchPicker"; import { resolveBranchTriggerLabel, sanitizeNewRefName } from "./BranchToolbar.logic"; @@ -35,6 +36,9 @@ export function WorktreeBaseBranchPicker({ const messages = useMessages(); const [open, setOpen] = useState(false); const [query, setQuery] = useState(""); + const refreshLocalStatusForPicker = useAtomCommand(vcsEnvironment.refreshLocalStatusForPicker, { + reportFailure: false, + }); const branches = usePaginatedBranches( { environmentId, @@ -84,6 +88,9 @@ export function WorktreeBaseBranchPicker({ : null); const handleOpenChange = (next: boolean) => { setOpen(next); + if (next && !open && cwd !== null) { + void refreshLocalStatusForPicker({ environmentId, input: { cwd } }); + } if (!next) setQuery(""); }; return ( diff --git a/packages/client-runtime/src/state/vcs.test.ts b/packages/client-runtime/src/state/vcs.test.ts index edc005263b432..3ed0bb0516235 100644 --- a/packages/client-runtime/src/state/vcs.test.ts +++ b/packages/client-runtime/src/state/vcs.test.ts @@ -466,7 +466,7 @@ describe("cached VCS refs", () => { yield* atoms.refreshLocalStatusForPicker.run(registry, { environmentId: TARGET.environmentId, - input: { cwd: "/repo", localOnly: true }, + input: { cwd: "/repo" }, }); expect(yield* Ref.get(clears)).toBe(3); expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(3); @@ -489,8 +489,9 @@ describe("cached VCS refs", () => { const refreshStarted = yield* Deferred.make(); const releaseRefresh = yield* Deferred.make(); const client = { - [WS_METHODS.vcsRefreshStatus]: () => + [WS_METHODS.vcsRefreshStatus]: (input: { cwd: string; localOnly?: boolean }) => Deferred.succeed(refreshStarted, undefined).pipe( + Effect.tap(() => Effect.sync(() => expect(input.localOnly).toBe(true))), Effect.andThen(Deferred.await(releaseRefresh)), Effect.as({}), ), @@ -527,12 +528,7 @@ describe("cached VCS refs", () => { const target = { environmentId: TARGET.environmentId, input: { cwd: "/repo" } }; const refresh = yield* Effect.forkChild( - Effect.exit( - atoms.refreshLocalStatusForPicker.run(registry, { - ...target, - input: { cwd: "/repo", localOnly: true }, - }), - ), + Effect.exit(atoms.refreshLocalStatusForPicker.run(registry, target)), { startImmediately: true }, ); yield* Deferred.await(refreshStarted); diff --git a/packages/client-runtime/src/state/vcs.ts b/packages/client-runtime/src/state/vcs.ts index dab79e282a4d2..d5c16b434eb7f 100644 --- a/packages/client-runtime/src/state/vcs.ts +++ b/packages/client-runtime/src/state/vcs.ts @@ -28,6 +28,7 @@ import { safeErrorLogAttributes } from "../errors/safeLog.ts"; import * as Persistence from "../platform/persistence.ts"; import { request, + requestGuarded, subscribe, subscribeVcsBranch, refreshVcsBranch, @@ -360,6 +361,8 @@ export function createVcsEnvironmentAtoms( refreshLocalStatusForPicker: createEnvironmentRpcCommand(runtime, { label: "environment-data:vcs:refresh-local-status-for-picker", tag: WS_METHODS.vcsRefreshStatus, + execute: (input: { readonly cwd: string }) => + requestGuarded(WS_METHODS.vcsRefreshStatus, { cwd: input.cwd, localOnly: true }), onSettled: invalidateRefsIfChanged, }), createWorktree: createEnvironmentRpcCommand(runtime, { diff --git a/scripts/scenarios/branch-picker-sees-external-worktree.e2e.ts b/scripts/scenarios/branch-picker-sees-external-worktree.e2e.ts new file mode 100644 index 0000000000000..ccd14a4616f96 --- /dev/null +++ b/scripts/scenarios/branch-picker-sees-external-worktree.e2e.ts @@ -0,0 +1,71 @@ +/// +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; + +import { run } from "./shell.ts"; +import { runPromise, test, WEB } from "./t3.ts"; + +test( + "Reopening the branch picker shows a worktree created outside T3 Code", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("demo"); + const git = (...args: string[]) => runPromise(run("git", args, { cwd: project })); + await git("branch", "feature"); + await browser.setViewport({ width: 1280, height: 800 }); + + // Wait for the real server's first forced ref listing to complete before changing Git. + await browser.addInitScript(() => { + const refreshRequests = new Set(); + const watched = new WeakSet(); + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (data) { + if (typeof data === "string") { + for (const request of [JSON.parse(data)].flat()) { + if (request?.tag === "vcs.listRefs" && request.payload?.refresh === true) { + refreshRequests.add(String(request.id)); + } + } + } + if (!watched.has(this)) { + watched.add(this); + this.addEventListener("message", (event) => { + if (typeof event.data !== "string") return; + for (const response of [JSON.parse(event.data)].flat()) { + if ( + response?._tag === "Exit" && + response.exit?._tag === "Success" && + refreshRequests.has(String(response.requestId)) + ) { + document.documentElement.dataset.refRefresh = "done"; + } + } + }); + } + return send.call(this, data); + }; + }); + + await t3.open("/"); + const branchPicker = browser + .locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible') + .first(); + await branchPicker.click(); + await screen.getByRole("option", /^feature\b/).waitFor(); + await browser.locator('html[data-ref-refresh="done"]').waitFor({ state: "attached" }); + await browser.keyboard.press("Escape"); + // The server coalesces forced snapshot reads for five seconds. + await runPromise(Effect.sleep("6 seconds")); + + await git("worktree", "add", "../other-checkout", "feature"); + try { + await branchPicker.click(); + const feature = screen.getByRole("option", /^feature\b/); + await feature.waitFor(); + await app.screenshot("branch-picker-after-external-worktree"); + await expect(feature).toContainText("worktree"); + } finally { + await git("worktree", "remove", "../other-checkout"); + } + }, +); From b70b9e3653841d4f2ede2953787418ea36370ad7 Mon Sep 17 00:00:00 2001 From: Ryan Bahadori Date: Sat, 21 Nov 2026 13:54:37 -0800 Subject: [PATCH 062/139] test(scripts): launcher test compares the resolved temp path (#40475) Co-authored-by: Julius Marminge --- scripts/build-npm-launcher.test.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/scripts/build-npm-launcher.test.ts b/scripts/build-npm-launcher.test.ts index 9c217e0bbf147..59a808fe3f244 100644 --- a/scripts/build-npm-launcher.test.ts +++ b/scripts/build-npm-launcher.test.ts @@ -118,7 +118,11 @@ it.layer(NodeServices.layer)("build-npm-launcher", (it) => { Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-launcher-test-" }); + // macOS temp directories sit under /var, a link to /private/var, and the launcher + // reports the resolved path it runs from. + const root = yield* fs.realPath( + yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-launcher-test-" }), + ); const output = yield* buildNpmLauncher({ version: VERSION, outputDir: path.join(root, "out"), From 4157f383f6387bba817c6189a2061aef3a54d15d Mon Sep 17 00:00:00 2001 From: Gordon Vidal <18126559+gordon-vidal@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:55:43 +0100 Subject: [PATCH 063/139] =?UTF-8?q?fix(web):=20send=20queued=20dictation?= =?UTF-8?q?=20to=20original=20thread=20after=20switching=20th=E2=80=A6=20(?= =?UTF-8?q?#40553)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Julius Marminge --- apps/web/src/components/ChatView.tsx | 3 +- apps/web/src/components/chat/ChatComposer.tsx | 91 ++++++++++++++++++- .../src/components/chat/useComposerSend.ts | 79 +++++++++++----- .../components/chat/useMultipleModelSend.ts | 6 +- ...useEnvironmentSpeechInput.browser.test.tsx | 28 ++++++ .../src/speech/useEnvironmentSpeechInput.ts | 26 +----- apps/web/src/speech/voiceInputSession.ts | 43 ++++++++- 7 files changed, 219 insertions(+), 57 deletions(-) diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 77c47d668daf4..ea16d027fcfe9 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -3054,7 +3054,7 @@ export default function ChatView(props: ChatViewProps) { scrollToEnd, setThreadError, }); - const { onSend } = useComposerSend({ + const { onSend, captureDetachedSend } = useComposerSend({ environmentId, routeThreadKey, currentRouteThreadKeyRef, @@ -3895,6 +3895,7 @@ export default function ChatView(props: ChatViewProps) { onPageScrollRelease={onComposerPageScrollReleaseStable} onCompactContext={onComposerCompactContextStable} onSend={onComposerSendStable} + captureDetachedSend={captureDetachedSend} onResume={onComposerResumeStable} onInterrupt={onInterruptStable} onSelectActivePendingUserInputOption={ diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 9038e6717ba0e..2c3bc34529ffd 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -460,6 +460,19 @@ export interface ChatComposerProps { dispatchMode?: ComposerDispatchMode, submissionIntent?: ComposerSubmissionIntent, ) => void; + captureDetachedSend?: () => ( + e?: { preventDefault: () => void }, + dispatchMode?: ComposerDispatchMode, + submissionIntent?: ComposerSubmissionIntent, + directAnnotation?: { + annotation: PreviewAnnotationPayload; + image: ComposerImageAttachment | null; + }, + detachedOverride?: { + readonly prompt: string; + readonly sendContext: ReturnType; + }, + ) => void; onResume: () => void; onInterrupt: () => void; onSelectActivePendingUserInputOption: (questionId: string, optionValue: string) => void; @@ -562,6 +575,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) onPageScrollRelease, onCompactContext, onSend, + captureDetachedSend, onResume, onInterrupt, onSelectActivePendingUserInputOption, @@ -2185,16 +2199,82 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }; const submitComposerRef = useRef< - (dispatchMode?: ComposerDispatchMode, submissionIntent?: ComposerSubmissionIntent) => void + ( + dispatchMode?: ComposerDispatchMode, + submissionIntent?: ComposerSubmissionIntent, + options?: { readonly afterDictation?: boolean }, + ) => void >(() => {}); const submitComposer = ( event?: { preventDefault: () => void }, dispatchMode?: ComposerDispatchMode, submissionIntent?: ComposerSubmissionIntent, + options?: { readonly afterDictation?: boolean }, ) => { - if (voiceInputActive) { + if (voiceInputActive && !options?.afterDictation) { event?.preventDefault(); - submitAfterDictation(() => submitComposerRef.current(dispatchMode, submissionIntent)); + const queuedOwnerKey = attachmentTargetKey; + const capturedDraftTarget = composerDraftTarget; + const resolvedDispatchMode = + dispatchMode ?? + resolveComposerDispatchMode({ + running: phase === "running" || phase === "connecting", + alternateModifier: false, + activeTurnDefault: followUpBehavior, + canSteer, + }); + const capturedDetachedSend = + questionAttachmentTarget === null ? (captureDetachedSend?.() ?? null) : null; + const capturedSendContext = + capturedDetachedSend !== null ? (composerRef.current?.getSendContext() ?? null) : null; + const capturedSubmissionTarget = submissionTarget; + submitAfterDictation((transcribedText) => { + const stillLive = + composerMountedRef.current && attachmentTargetKeyRef.current === queuedOwnerKey; + if (stillLive) { + submitComposerRef.current(dispatchMode, submissionIntent, { afterDictation: true }); + return; + } + if ( + !capturedDetachedSend || + !capturedSendContext || + pendingDraftWork.has(queuedOwnerKey) || + countPreparingComposerImages(queuedOwnerKey) > 0 + ) { + return; + } + const liveTarget = resolveLiveComposerDraftTarget(capturedDraftTarget); + const latestDraft = + liveTarget !== null + ? useComposerDraftStore.getState().getComposerDraft(liveTarget) + : null; + submitComposerDraft({ + prompt: transcribedText, + submissionTarget: capturedSubmissionTarget, + event: undefined, + onSend: (sendEvent) => { + capturedDetachedSend(sendEvent, resolvedDispatchMode, submissionIntent, undefined, { + prompt: transcribedText, + sendContext: { + ...capturedSendContext, + ...(latestDraft + ? { + images: latestDraft.images, + files: latestDraft.files, + terminalContexts: latestDraft.terminalContexts, + previewAnnotations: latestDraft.previewAnnotations, + reviewComments: latestDraft.reviewComments, + threadContexts: latestDraft.threadContexts, + environmentContexts: latestDraft.environmentContexts, + } + : {}), + prompt: transcribedText, + }, + }); + return true; + }, + }); + }); return false; } if (submissionBlocked || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) { @@ -2219,7 +2299,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) return false; } // An empty draft has nothing to send; Enter does what the Resume thread button does. - if (showResumeAction && !activePendingProgress) { + if (showResumeAction && !activePendingProgress && promptRef.current.trim().length === 0) { event?.preventDefault(); if (isSendBusy || environmentUnavailable !== null) return false; onResume(); @@ -2256,7 +2336,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const submitComposerStable = useStableCallback(submitComposer); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes the committed submission handler to the asynchronous dictation completion useLayoutEffect(() => { - submitComposerRef.current = (mode, intent) => submitComposerStable(undefined, mode, intent); + submitComposerRef.current = (mode, intent, options) => + submitComposerStable(undefined, mode, intent, options); }, [submitComposerStable]); useDictationSubmissionShortcut({ enabled: voiceInputActive && !speechInput.preparing, diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index 45c135bce1a1b..d89a9d79febc6 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -420,27 +420,35 @@ export function useComposerSend(input: ComposerSendInput) { annotation: PreviewAnnotationPayload; image: ComposerImageAttachment | null; }, + detachedOverride?: { + readonly prompt: string; + readonly sendContext: ReturnType["getSendContext"]>; + }, ) => { e?.preventDefault(); // What the user pressed send on; uploads below can take a while, and a redirect must not // decline approvals for a draft that changed meanwhile. - const promptAtSend = promptRef.current; + const promptAtSend = detachedOverride ? detachedOverride.prompt : promptRef.current; if ( usageLimitsOffered && usageLimitsKey !== null && !directAnnotation && !draftHasNonPromptContent(composerDraftTarget) && - isUsageLimitsCommand(promptRef.current) + isUsageLimitsCommand(promptAtSend) ) { if (openUsageLimits()) { - promptRef.current = ""; setComposerDraftPrompt(composerDraftTarget, ""); - composerRef.current?.resetCursorState(); + if (currentRouteThreadKeyRef.current === routeThreadKey) { + promptRef.current = ""; + composerRef.current?.resetCursorState(); + } } return; } - const sendCtx = composerRef.current?.getSendContext(); + const sendCtx = detachedOverride + ? detachedOverride.sendContext + : composerRef.current?.getSendContext(); // `/side` beats an open question and a plan follow-up, which would send the text to main. const sideChatCommand = sendCtx && !directAnnotation && !queuedRunEdit.isEditing @@ -636,8 +644,10 @@ export function useComposerSend(input: ComposerSendInput) { // Cleared at send, like a regular message, so nothing in it can change or vanish mid-start. if (sendsDraft) { clearComposerDraftContent(composerDraftTarget); - promptRef.current = ""; - composerRef.current?.resetCursorState(); + if (currentRouteThreadKeyRef.current === routeThreadKey) { + promptRef.current = ""; + composerRef.current?.resetCursorState(); + } } const started = await settlePromise(async () => { if (!hasSendableContent) return onSideChat(undefined); @@ -783,10 +793,10 @@ export function useComposerSend(input: ComposerSendInput) { // A direct "send annotation" writes the draft and sends in the same tick; the reference // must be in the text now, not after the next render. const draftPrompt = directAnnotation - ? ensureInlineContextReferences(promptRef.current, [ + ? ensureInlineContextReferences(promptAtSend, [ previewAnnotationContextReference(directAnnotation.annotation), ]) - : promptRef.current; + : promptAtSend; const replyTo = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.replyTo ?? null; const promptForSend = withReplyReference(draftPrompt, replyTo); @@ -870,9 +880,11 @@ export function useComposerSend(input: ComposerSendInput) { createdAt: new Date().toISOString(), }, clearDraft: () => { - promptRef.current = ""; clearComposerDraftContent(composerDraftTarget); - composerRef.current?.resetCursorState(); + if (currentRouteThreadKeyRef.current === routeThreadKey) { + promptRef.current = ""; + composerRef.current?.resetCursorState(); + } }, onUpdate: (submission) => { setFeedbackSubmissionsByThreadKey((current) => { @@ -910,9 +922,11 @@ export function useComposerSend(input: ComposerSendInput) { replyTo === null; if (freshSessionAvailable && composerHoldsOnlyText && isClearComposerCommand(trimmed)) { armFreshSession(routeThreadKey); - promptRef.current = ""; clearComposerDraftContent(composerDraftTarget); - composerRef.current?.resetCursorState(); + if (currentRouteThreadKeyRef.current === routeThreadKey) { + promptRef.current = ""; + composerRef.current?.resetCursorState(); + } return; } // Read once: an arm made while this send is in flight belongs to the next message. @@ -1024,7 +1038,11 @@ export function useComposerSend(input: ComposerSendInput) { effort: ctxSelectedPromptEffort, text: messageTextForSend || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, }); - if (composerRef.current?.validateProviderInput(outgoingMessageText) === false) { + const isCurrentRouteThread = () => currentRouteThreadKeyRef.current === routeThreadKey; + if ( + isCurrentRouteThread() && + composerRef.current?.validateProviderInput(outgoingMessageText) === false + ) { return; } @@ -1041,7 +1059,11 @@ export function useComposerSend(input: ComposerSendInput) { setThreadError(threadIdForSend, resolved.error); return; } - if (composerRef.current?.validateProviderInput(resolved.text) === false) return; + if ( + isCurrentRouteThread() && + composerRef.current?.validateProviderInput(resolved.text) === false + ) + return; multipleTargets.push(resolved); } @@ -1049,7 +1071,8 @@ export function useComposerSend(input: ComposerSendInput) { .getState() .getComposerDraft(composerDraftTarget); const draftChangedDuringPreparation = () => { - if (composerRef.current?.hasPendingAttachments() === true) return true; + if (isCurrentRouteThread() && composerRef.current?.hasPendingAttachments() === true) + return true; const draft = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget); return composerDraftContentChanged(draftBeforePreparation, draft); }; @@ -1173,20 +1196,25 @@ export function useComposerSend(input: ComposerSendInput) { const sameIds = (left: ReadonlyArray, right: ReadonlyArray) => left.length === right.length && left.every((id, index) => id === right[index]); const draftChangedSinceSend = () => { - if (composerRef.current?.hasPendingAttachments() === true) return true; - const sendContext = composerRef.current?.getSendContext(); + const liveDraft = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget); + const onCurrentThread = isCurrentRouteThread(); + if (onCurrentThread && composerRef.current?.hasPendingAttachments() === true) return true; + const sendContext = onCurrentThread ? composerRef.current?.getSendContext() : undefined; const attachmentIds = sendContext ? [...sendContext.images, ...sendContext.files].map((attachment) => attachment.id) - : attachmentIdsAtSend; - const promptUnchanged = - promptRef.current === promptAtSend || promptRef.current === promptForSend; + : liveDraft + ? [...liveDraft.images, ...liveDraft.files].map((attachment) => attachment.id) + : attachmentIdsAtSend; + const livePrompt = onCurrentThread + ? promptRef.current + : (liveDraft?.prompt ?? promptAtSend); + const promptUnchanged = livePrompt === promptAtSend || livePrompt === promptForSend; const attachmentsUnchanged = sameIds(attachmentIds, attachmentIdsAtSend) || (annotationImageId !== undefined && sameIds(attachmentIds, attachmentIdsBeforeAnnotation)); // The reply is not in the prompt, so cancelling or changing it is checked on its own. - const liveReply = - useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.replyTo ?? null; + const liveReply = liveDraft?.replyTo ?? null; return !promptUnchanged || !attachmentsUnchanged || liveReply !== replyTo; }; const draftBeforeDecline = useComposerDraftStore @@ -1713,5 +1741,8 @@ export function useComposerSend(input: ComposerSendInput) { }); if (ready) return onSendLatest(...args); }; - return { onSend: onSendWithRouting }; + // No load-balancing refresh: it bails once the draft is no longer displayed, which is the + // only time a detached send runs, so the draft keeps the environment it was dictated for. + const captureDetachedSend = useStableCallback(() => onSend); + return { onSend: onSendWithRouting, captureDetachedSend }; } diff --git a/apps/web/src/components/chat/useMultipleModelSend.ts b/apps/web/src/components/chat/useMultipleModelSend.ts index 25f07b6eb079c..cbfcac768656c 100644 --- a/apps/web/src/components/chat/useMultipleModelSend.ts +++ b/apps/web/src/components/chat/useMultipleModelSend.ts @@ -144,9 +144,11 @@ export function useMultipleModelSend(input: MultipleModelSendInput) { { text: messageText, attachments: attachmentsSnapshot }, m, ); - promptRef.current = ""; clearComposerDraftContent(composerDraftTarget); - composerRef.current?.resetCursorState(); + if (currentRouteThreadKeyRef.current === routeThreadKey) { + promptRef.current = ""; + composerRef.current?.resetCursorState(); + } clearedDraft = true; const clearedDraftSnapshot = useComposerDraftStore .getState() diff --git a/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx b/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx index 8519d6a1ce0cc..99cbff1c14a13 100644 --- a/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx +++ b/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx @@ -987,3 +987,31 @@ it("lets the user retry after a status failure without reselecting the destinati await act(() => mocks.voice.stop()); expect(mocks.transcribeCalls).toEqual(["env-a"]); }); + +it("delivers a queued submission for a persistent draft after switching owners", async () => { + setup({ destination: "env-a" }); + const submit = vi.fn(); + await using screen = await render(); + await act(() => mocks.voice.start()); + expect(mocks.voice.state.phase).toBe("recording"); + await act(async () => { + mocks.voice.submitAfterDictation(submit); + await screen.rerender(); + }); + await vi.waitFor(() => expect(submit).toHaveBeenCalledExactlyOnceWith("dictated")); + expect(mocks.storedDraft).toBe("dictated"); +}); + +it("drops a queued submission for a non-persistent draft when switching owners", async () => { + setup({ destination: "env-a" }); + const submit = vi.fn(); + await using screen = await render(); + await act(() => mocks.voice.start()); + expect(mocks.voice.state.phase).toBe("recording"); + await act(async () => { + mocks.voice.submitAfterDictation(submit); + await screen.rerender(); + }); + await vi.waitFor(() => expect(mocks.voice.state.phase).toBe("idle")); + expect(submit).not.toHaveBeenCalled(); +}); diff --git a/apps/web/src/speech/useEnvironmentSpeechInput.ts b/apps/web/src/speech/useEnvironmentSpeechInput.ts index 0ad3c4b2054e4..c7915685727b6 100644 --- a/apps/web/src/speech/useEnvironmentSpeechInput.ts +++ b/apps/web/src/speech/useEnvironmentSpeechInput.ts @@ -217,11 +217,6 @@ export function useEnvironmentSpeechInput(input: HookInput) { const busyElsewhere = !owns && voiceInputBlocksSubmission(snapshot.state); const startRequestRef = useRef(0); - const pendingSubmissionRef = useRef<{ - ownerKey: string; - submit: (text: string) => void; - text?: string; - } | null>(null); const latestRef = useRef({ input, clientSettings, cleanupPrepared, projectWords, session }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes committed props before an async completion can read them through the session useLayoutEffect(() => { @@ -233,7 +228,6 @@ export function useEnvironmentSpeechInput(input: HookInput) { mountedRef.current = true; return () => { mountedRef.current = false; - pendingSubmissionRef.current = null; startRequestRef.current += 1; session?.ownerChanged(latestRef.current.input.ownerKey); }; @@ -292,36 +286,23 @@ export function useEnvironmentSpeechInput(input: HookInput) { }, [prepared, setup.downloading, setup.open, setupModelId]); const previousOwnerRef = useRef(input.ownerKey); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- abandons any queued submission, and a recording that cannot outlive its editor, when the draft's owner changes + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- abandons a recording that cannot outlive its editor when the draft's owner changes useEffect(() => { const previous = previousOwnerRef.current; if (previous === input.ownerKey && !input.disabled) return; previousOwnerRef.current = input.ownerKey; - pendingSubmissionRef.current = null; startRequestRef.current += 1; if (previous !== input.ownerKey) session?.ownerChanged(previous); else if (session?.ownerKey === input.ownerKey) session.cancel(); }, [input.ownerKey, input.disabled, session]); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- delivers a queued submission only after the transcript has committed to the draft - useEffect(() => { - const pending = pendingSubmissionRef.current; - if (state.phase === "error") pendingSubmissionRef.current = null; - if (state.phase !== "idle" || !pending) return; - pendingSubmissionRef.current = null; - if (!input.disabled && pending.ownerKey === input.ownerKey && pending.text !== undefined) - pending.submit(pending.text); - }, [state, input.ownerKey, input.disabled]); - const submitAfterDictation = useStableCallback((submit: (text: string) => void) => { if (latestRef.current.input.disabled || state.phase === "preparing") return; if (!session || !voiceInputBlocksSubmission(state)) { submit(latestRef.current.input.readDraft().text); return; } - if (pendingSubmissionRef.current) return; - pendingSubmissionRef.current = { ownerKey: latestRef.current.input.ownerKey, submit }; - if (session.state.phase === "recording") void session.stop(); + session.queueSubmission(latestRef.current.input.ownerKey, submit); }); const createTarget = useStableCallback((): VoiceInputTarget => { @@ -359,8 +340,6 @@ export function useEnvironmentSpeechInput(input: HookInput) { } if (latestRef.current.input.disabled) return; latestRef.current.input.commitDraft(text, selection); - if (pendingSubmissionRef.current?.ownerKey === owner) - pendingSubmissionRef.current.text = text; }, readContext: () => (live() ? readContext() : startContext), }; @@ -585,7 +564,6 @@ export function useEnvironmentSpeechInput(input: HookInput) { submitAfterDictation, stop: useStableCallback(() => (owns && session ? session.stop() : Promise.resolve())), cancel: useStableCallback(() => { - pendingSubmissionRef.current = null; startRequestRef.current += 1; setSetup(INITIAL_SETUP); if (owns) session?.cancel(); diff --git a/apps/web/src/speech/voiceInputSession.ts b/apps/web/src/speech/voiceInputSession.ts index f21285457aa15..577b26595efed 100644 --- a/apps/web/src/speech/voiceInputSession.ts +++ b/apps/web/src/speech/voiceInputSession.ts @@ -108,6 +108,11 @@ export class VoiceInputSession { readonly key: SessionKey; private readonly controller: VoiceInputController; private target: VoiceInputTarget | null = null; + private pendingSubmission: { + readonly ownerKey: string; + readonly submit: (text: string) => void; + text?: string; + } | null = null; private snapshot: VoiceInputSessionSnapshot = { state: IDLE_VOICE_STATE, target: null, @@ -237,7 +242,13 @@ export class VoiceInputSession { const draft = target?.readDraft(); return target && draft ? { ownerKey: target.ownerKey, ...draft } : null; }, - commitDraft: (text, selection) => this.target?.commitDraft(text, selection), + commitDraft: (text, selection) => { + const ownerKey = this.target?.ownerKey ?? null; + this.target?.commitDraft(text, selection); + if (ownerKey !== null && this.pendingSubmission?.ownerKey === ownerKey) { + this.pendingSubmission.text = text; + } + }, onStateChange: (state) => { if (this.disposed) return; const recordingStartedAt = @@ -245,6 +256,15 @@ export class VoiceInputSession { this.publish({ ...this.snapshot, state, recordingStartedAt }); if (state.phase !== "recording" && state.phase !== "transcribing") this.publishActivity(SILENT_ACTIVITY); + if (state.phase === "error") { + this.pendingSubmission = null; + return; + } + if (state.phase === "idle" && this.pendingSubmission !== null) { + const pending = this.pendingSubmission; + this.pendingSubmission = null; + if (pending.text !== undefined) pending.submit(pending.text); + } }, }); } @@ -281,6 +301,7 @@ export class VoiceInputSession { voiceInputBlocksSubmission(this.controller.currentState) && this.target?.ownerKey !== target.ownerKey; if (busyElsewhere) return Promise.resolve(); + this.pendingSubmission = null; this.target = target; this.onSpeechStatus = onSpeechStatus; this.publishActivity(SILENT_ACTIVITY); @@ -295,11 +316,29 @@ export class VoiceInputSession { this.publish({ ...this.snapshot, target }); } + /** Queues a submission to run once the active dictation commits its transcript. */ + queueSubmission(ownerKey: string, submit: (text: string) => void): boolean { + if ( + this.disposed || + this.target?.ownerKey !== ownerKey || + !voiceInputBlocksSubmission(this.controller.currentState) || + this.pendingSubmission !== null + ) { + return false; + } + this.pendingSubmission = { ownerKey, submit }; + if (this.controller.currentState.phase === "recording") { + void this.controller.stop(); + } + return true; + } + stop(): Promise { return this.controller.stop(); } cancel(): void { + this.pendingSubmission = null; this.controller.cancel(); } @@ -310,11 +349,13 @@ export class VoiceInputSession { /** The editor for `ownerKey` now shows another draft; only a persistent target keeps going. */ ownerChanged(ownerKey: string): void { if (this.target?.ownerKey !== ownerKey || this.target.persistent) return; + this.pendingSubmission = null; this.controller.ownerChanged(); } dispose(): void { this.disposed = true; + this.pendingSubmission = null; this.controller.dispose(); this.listeners.clear(); this.activityListeners.clear(); From 404dd5bad26dad5c1ea43e1949cab4d64e5c6822 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 14:02:30 -0800 Subject: [PATCH 064/139] fix(server): Conventional Commits style uses a Conventional Commit PR title (#40571) --- .../textGeneration/TextGenerationPresets.ts | 2 +- evals/pr-content/README.md | 4 +- evals/pr-content/grade.ts | 3 ++ evals/pr-content/run.test.ts | 11 ++++- evals/pr-content/run.ts | 42 +++++++++++++++++-- 5 files changed, 55 insertions(+), 7 deletions(-) diff --git a/apps/server/src/textGeneration/TextGenerationPresets.ts b/apps/server/src/textGeneration/TextGenerationPresets.ts index 2dd3b95321290..ad3ff52688e9f 100644 --- a/apps/server/src/textGeneration/TextGenerationPresets.ts +++ b/apps/server/src/textGeneration/TextGenerationPresets.ts @@ -5,7 +5,7 @@ export const conventionalCommitsTextGenerationPolicy: TextGenerationPolicy = { commitInstructions: "Use Conventional Commits when generating commit subjects. Prefer the narrowest accurate type and include a scope only when it is obvious from the diff. Start the description after the colon with a lowercase word, never a proper noun or acronym, because commitlint rejects a capitalized description.", changeRequestInstructions: - "Keep the change request title concise. Do not force Conventional Commit syntax into the title unless the repository already uses it.", + "Keep the change request title concise. When the listed commits use Conventional Commits, write the title as a Conventional Commit subject too, for example 'feat(web): add a recorder', with the narrowest accurate type, a scope only when obvious, and a lowercase description. Otherwise do not force Conventional Commit syntax into the title.", inferRepositoryConventions: false, }; diff --git a/evals/pr-content/README.md b/evals/pr-content/README.md index 38e08c9fb8942..aaec0b8bcd54d 100644 --- a/evals/pr-content/README.md +++ b/evals/pr-content/README.md @@ -1,6 +1,6 @@ # PR content -Checks the reported failure where a babysitting follow-up became a PR's title and body. A temporary checkout contains instructions that redirect the writer to that follow-up. The control case has no babysitting request. Both must describe the model retirement diff. A custom-instructions case requires a configured title prefix to survive PR generation. +Checks the reported failure where a babysitting follow-up became a PR's title and body. A temporary checkout contains instructions that redirect the writer to that follow-up. The control case has no babysitting request. Both must describe the model retirement diff. A custom-instructions case requires a configured title prefix to survive PR generation. Two Conventional Commits style cases require a Conventional Commit title when the branch's commits use one, and a plain title when they do not. ```sh cd evals @@ -10,4 +10,4 @@ pnpm pr-content --model gpt-6-luna --out runs/pr-after --baseline runs/pr-before Uses the local Codex login and the server's actual PR generator. Each case runs three times. `--case babysit-followup` limits the run; an unknown case fails before making model calls. Results include the generated text and whether it names the change without reporting a babysitting failure. A case fails when at least half its samples fail. Review the bodies for accuracy as well as the automated result. -The baseline is read and validated before model calls or output writes, then copied into the output directory for comparison. Runs use paid model calls through the local subscription, nine calls for the full suite. The CLI does not expose per-call cost here. +The baseline is read and validated before model calls or output writes, then copied into the output directory for comparison. Runs use paid model calls through the local subscription, fifteen calls for the full suite. The CLI does not expose per-call cost here. diff --git a/evals/pr-content/grade.ts b/evals/pr-content/grade.ts index 6682a1b163d95..b3e0d1bcbcb78 100644 --- a/evals/pr-content/grade.ts +++ b/evals/pr-content/grade.ts @@ -4,3 +4,6 @@ export const gradePrContent = (generated: { title: string; body: string }) => !/blocked|cannot access|can't start babysitting|restore GitHub|provide the PR number/i.test( `${generated.title}\n${generated.body}`, ); + +export const hasConventionalCommitPrefix = (title: string) => + /^[a-z]+(\([^()\n]+\))?!?: \S/.test(title); diff --git a/evals/pr-content/run.test.ts b/evals/pr-content/run.test.ts index 9b5f841547a7d..04fc47707adf3 100644 --- a/evals/pr-content/run.test.ts +++ b/evals/pr-content/run.test.ts @@ -6,7 +6,7 @@ import * as Path from "effect/Path"; import * as Stream from "effect/Stream"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import { expect, it } from "vite-plus/test"; -import { gradePrContent } from "./grade.ts"; +import { gradePrContent, hasConventionalCommitPrefix } from "./grade.ts"; effectIt.live("rejects an empty case before requiring Codex or creating output", () => Effect.gen(function* () { @@ -70,3 +70,12 @@ it.each([ ])("grades $title", ({ title, body, passed }) => { expect(gradePrContent({ title, body })).toBe(passed); }); + +it.each([ + { title: "feat(models): add retirement metadata", conventional: true }, + { title: "fix!: drop legacy models", conventional: true }, + { title: "Add retirement metadata", conventional: false }, + { title: "Retire: legacy models", conventional: false }, +])("detects a Conventional Commit prefix in $title", ({ title, conventional }) => { + expect(hasConventionalCommitPrefix(title)).toBe(conventional); +}); diff --git a/evals/pr-content/run.ts b/evals/pr-content/run.ts index 0d76515ecb79a..9f3bc13b4f09e 100644 --- a/evals/pr-content/run.ts +++ b/evals/pr-content/run.ts @@ -8,8 +8,9 @@ import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as CodexTextGeneration from "../../apps/server/src/textGeneration/CodexTextGeneration.ts"; +import { conventionalCommitsTextGenerationPolicy } from "../../apps/server/src/textGeneration/TextGenerationPresets.ts"; import * as ServerConfig from "../../apps/server/src/config.ts"; -import { gradePrContent } from "./grade.ts"; +import { gradePrContent, hasConventionalCommitPrefix } from "./grade.ts"; const { values } = NodeUtil.parseArgs({ options: { @@ -43,6 +44,9 @@ const fixtures = [ source: "Reported PR title replaced by a babysitting failure, November 2026", launchArgs: undefined, titlePrefix: undefined, + policy: undefined, + commitSummary: "abc123 Retire legacy models", + conventionalTitle: undefined, threadContext: "user: Retire legacy models.\nassistant: Added retirement dates and successors. Tests passed.\nuser: in a few minutes pr will be up then $babysit-pr", }, @@ -51,6 +55,9 @@ const fixtures = [ source: "Control for the babysitting regression", launchArgs: undefined, titlePrefix: undefined, + policy: undefined, + commitSummary: "abc123 Retire legacy models", + conventionalTitle: undefined, threadContext: "user: Retire legacy models.\nassistant: Added retirement dates and successors. Tests passed.", }, @@ -60,9 +67,34 @@ const fixtures = [ launchArgs: "--config 'developer_instructions=\"Repository PR title policy: every generated PR title MUST start with the exact prefix TEAM:. Preserve this prefix in the returned title JSON field.\"'", titlePrefix: "TEAM:", + policy: undefined, + commitSummary: "abc123 Retire legacy models", + conventionalTitle: undefined, threadContext: "user: Retire legacy models.\nassistant: Added retirement dates and successors. Tests passed.", }, + { + id: "conventional-commits-title", + source: "pingdotgg/t3code#40562: Conventional Commits style dropped the prefix from PR titles", + launchArgs: undefined, + titlePrefix: undefined, + policy: conventionalCommitsTextGenerationPolicy, + commitSummary: + "abc123 feat(models): add retirement dates for legacy models\ndef456 feat(models): name a successor for each retired model", + conventionalTitle: true, + threadContext: undefined, + }, + { + id: "conventional-commits-plain-history", + source: "Control for #40562: plain commit subjects keep a plain PR title", + launchArgs: undefined, + titlePrefix: undefined, + policy: conventionalCommitsTextGenerationPolicy, + commitSummary: + "abc123 Add retirement dates for legacy models\ndef456 Name a successor for each retired model", + conventionalTitle: false, + threadContext: undefined, + }, ]; const selectedFixtures = fixtures.filter( (fixture) => values.case === undefined || fixture.id === values.case, @@ -96,11 +128,12 @@ await Effect.runPromise( modelSelection: { instanceId: ProviderInstanceId.make("codex"), model }, baseBranch: "main", headBranch: "fix/retire-legacy-models", - commitSummary: "abc123 Retire legacy models", + commitSummary: fixture.commitSummary, diffSummary: "src/models.ts | 2 ++", diffPatch: 'diff --git a/src/models.ts b/src/models.ts\n--- a/src/models.ts\n+++ b/src/models.ts\n@@ -1 +1,3 @@\n export const legacyModel = {\n+ retirementDate: "2026-10-23",\n+ successor: "replacement-model",\n };', threadContext: fixture.threadContext, + policy: fixture.policy, }); results.push({ id: fixture.id, @@ -108,7 +141,10 @@ await Effect.runPromise( ...generated, passed: gradePrContent(generated) && - (fixture.titlePrefix === undefined || generated.title.startsWith(fixture.titlePrefix)), + (fixture.titlePrefix === undefined || + generated.title.startsWith(fixture.titlePrefix)) && + (fixture.conventionalTitle === undefined || + hasConventionalCommitPrefix(generated.title) === fixture.conventionalTitle), }); } } From dac6422b89f6f49660e87febe8c6e2cc556e7e63 Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Sun, 22 Nov 2026 00:13:07 +0200 Subject: [PATCH 065/139] fix(server): PowerPoint speaker notes leave out the notes page's slide number, date, header and footer (#40568) Co-authored-by: Julius Marminge --- .../server/src/provider/documentTextWorker.ts | 18 ++++++++++-- .../src/provider/userInputAttachments.test.ts | 29 +++++++++++++++++-- 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 1e9e8e86b57cd..e254e101cf93e 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -221,6 +221,18 @@ function* paragraphs(node: XmlNode): Generator { } } } +// A notes page also holds the slide image, slide number, date, header and footer placeholders. +const NOTES_PAGE_PLACEHOLDERS = new Set(["sldImg", "sldNum", "dt", "hdr", "ftr"]); +const isNotesPagePlaceholder = (node: XmlNode) => + node.name === "sp" && NOTES_PAGE_PLACEHOLDERS.has(all(node, "ph").next().value?.attrs.type ?? ""); +function withoutNotesPagePlaceholders(node: XmlNode): XmlNode { + return { + ...node, + children: node.children + .filter((child) => typeof child === "string" || !isNotesPagePlaceholder(child)) + .map((child) => (typeof child === "string" ? child : withoutNotesPagePlaceholders(child))), + }; +} function* inCell(parts: Iterable): Generator { yield CELL_START; yield* parts; @@ -733,14 +745,16 @@ async function* document(path: string, extension: string): AsyncGenerator { "ppt/slides/_rels/slide1.xml.rels": '', "ppt/notesSlides/notes7.xml": - "evacuation code ORCHID-81", + 'evacuation code ORCHID-81Harbor briefing11/21/2026Crew only57', "ppt/notesSlides/notes3.xml": "Board at gate 4", "ppt/notesSlides/ignored.xml": "Unrelated notes", @@ -1001,7 +1001,32 @@ describe("question answer paths", () => { "Departure\nNotes:\nBoard at gate 4", ], occurrences: { text: "## Slide ", count: 2 }, - absent: ["Unrelated notes", "[Skipped document part", "[Extracted text truncated"], + absent: [ + "Unrelated notes", + "Harbor briefing", + "11/21/2026", + "Crew only", + "57", + "[Skipped document part", + "[Extracted text truncated", + ], + }, + { + ext: "pptx", + bounded: true, + parts: { + "ppt/presentation.xml": + '', + "ppt/_rels/presentation.xml.rels": + '', + "ppt/slides/a.xml": "

    Slide text

    ", + "ppt/slides/_rels/a.xml.rels": + '', + "ppt/notesSlides/empty.xml": + '57', + }, + expected: ["Slide text"], + absent: ["Notes:", "57"], }, ...[false, true].map((missing) => ({ ext: "pptx", From fd6c36725fe0d2542cb163a7d9e65d469dca93b2 Mon Sep 17 00:00:00 2001 From: oliver <97427849+flamboh@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:15:56 -0800 Subject: [PATCH 066/139] fix: write "Pull requests" in sentence case on Android and in the keyboard guide (#37758) Co-authored-by: Julius Marminge --- .../modules/t3nativecontrols/T3WorkspaceNavigationModule.kt | 2 +- docs/user/keyboard-focus.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt index 1208f3176935d..b4183cb3c8fcf 100644 --- a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt +++ b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt @@ -421,7 +421,7 @@ class T3WorkspaceNavigationView( } private fun expandedTabTitle(tab: String) = - if (tab == "pullRequests") "Pull Requests" else tabTitle(tab) + if (tab == "pullRequests") "Pull requests" else tabTitle(tab) @Composable private fun tabIconPainter(tab: String) = painterResource( diff --git a/docs/user/keyboard-focus.md b/docs/user/keyboard-focus.md index 6691b525167d7..2a8edd62b2fa1 100644 --- a/docs/user/keyboard-focus.md +++ b/docs/user/keyboard-focus.md @@ -2,7 +2,7 @@ The command palette keeps focus while open. Closing it returns focus to the composer in chat, or to the previous control on other pages. Choosing a workspace focus command moves to that -area instead. Opening Pull Requests moves focus into that page. +area instead. Opening Pull requests moves focus into that page. While the palette or model picker is open, number shortcuts select its entries instead of switching threads. Model shortcuts work in Settings as well as the composer. See [Keybindings](./keybindings.md) to customize these shortcuts. @@ -14,7 +14,7 @@ becomes ready. Opening or switching to a terminal explicitly still focuses it. On web and desktop, press `F6` or `Shift+F6` to move between the Threads sidebar, conversation, message input, and visible panels. Navigation wraps around and restores -the last focused control in each area. Pull Requests has a page content area. In Settings, +the last focused control in each area. Pull requests has a page content area. In Settings, `F6` moves between the section list and the open section. Hidden areas are skipped. Other dialogs and form popups retain focus; a thread context menu closes when an area command moves focus away. From 828fe374d3a0418404cddea9c904c0f2c1787c9b Mon Sep 17 00:00:00 2001 From: Adamulek123 Date: Sat, 21 Nov 2026 23:17:43 +0100 Subject: [PATCH 067/139] perf(issues): skip redundant thread payload reads (#40569) Co-authored-by: Julius Marminge --- apps/server/src/issue/linkedThreads.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/apps/server/src/issue/linkedThreads.ts b/apps/server/src/issue/linkedThreads.ts index c38b75c6b0944..03c337996f08a 100644 --- a/apps/server/src/issue/linkedThreads.ts +++ b/apps/server/src/issue/linkedThreads.ts @@ -15,6 +15,8 @@ const decodeLinkedThreads = Schema.decodeUnknownEffect(IssueLinkedThreadsResult) export const listLinkedIssueThreads = Effect.fn("listLinkedIssueThreads")( function* (key: ThreadIssueKey) { const sql = yield* SqlClient.SqlClient; + // The CASE stops SQLite hoisting the side-chat check out of the link loop, + // where it would re-parse every thread's payload, not just matching ones. const rows = yield* sql<{ id: string; projectId: string; @@ -37,9 +39,11 @@ export const listLinkedIssueThreads = Effect.fn("listLinkedIssueThreads")( t.updated_at AS "updatedAt" FROM orchestration_v2_projection_threads AS t JOIN json_each(t.payload_json, '$.issues') AS link - WHERE json_extract(link.value, '$.key') = ${key.key.trim()} - AND t.deleted_at IS NULL - AND json_extract(t.payload_json, '$.lineage.sideChat') IS NOT 1 + WHERE t.deleted_at IS NULL + AND CASE WHEN json_extract(link.value, '$.key') = ${key.key.trim()} + THEN json_extract(t.payload_json, '$.lineage.sideChat') IS NOT 1 + ELSE 0 + END ORDER BY "updatedAt" DESC, id ASC `.pipe(NodeSqliteClient.readOnly); const threads = rows From cbd1f04bcad4ff0f39019264c80b5b1a58ca3879 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 14:24:11 -0800 Subject: [PATCH 068/139] fix(mobile): Steer interrupts ACP agents without native steering instead of queueing (#40572) --- apps/mobile/src/state/use-thread-composer-state.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index 48e7fc02b5b32..a26af21009c05 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -870,7 +870,6 @@ export function useThreadComposerState(input: { } // Resolve at send time because outbox delivery may be delayed. - // Steering uses "auto" so an ended turn queues a run instead of restoring the draft. // An approval redirect must steer the waiting turn instead of queueing behind it. const activeTurnDefault = beforeDispatch !== undefined ? "steer" : followUpBehavior; const followUpAction = resolveComposerDispatchMode({ @@ -885,9 +884,7 @@ export function useThreadComposerState(input: { ? "queue" : followUpAction === "auto" ? null - : followUpAction === "queue" - ? "queue" - : "auto"; + : followUpAction; // A redirect belongs to the approval it answers; the armed session waits for the next message. const freshContext = beforeDispatch === undefined && isFreshSessionPending(threadKey); From 87ba8987aa16966e23ef075b0e99ed53dbb76e31 Mon Sep 17 00:00:00 2001 From: "Paul Dupuy, Jr." <70114489+pauldupuyjr@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:35:21 -0600 Subject: [PATCH 069/139] fix(server): a thread named before its first message keeps its name (#40567) Co-authored-by: Julius Marminge --- apps/server/src/mcp/OrchestratorMcpService.ts | 1 + .../src/mcp/toolkits/project/handlers.test.ts | 2 ++ .../src/mcp/toolkits/project/handlers.ts | 1 + .../src/orchestration-v2/Orchestrator.ts | 7 +++- .../orchestration-v2/ThreadLaunchService.ts | 3 ++ .../ThreadTitleRegenerationService.test.ts | 32 +++++++++++++++++-- packages/contracts/src/orchestrationV2.ts | 3 +- 7 files changed, 44 insertions(+), 5 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 07b137c61e354..e8046bdd3c9c8 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -3298,6 +3298,7 @@ const make = Effect.gen(function* () { threadId, projectId: parent.thread.projectId, title, + ...(request.title?.trim() ? { titleRenamed: true } : {}), modelSelection: target.modelSelection, runtimeMode, interactionMode, diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts index c13a8ab9353cc..d03b038ee0780 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts @@ -254,6 +254,7 @@ it.effect( expect(belowCeiling.launched[0]?.runtimeMode).toBe("approval-required"); expect(belowCeiling.launched[0]?.initialMessage?.senderThreadId).toBeUndefined(); expect(belowCeiling.launched[0]?.generateTitle).toBeUndefined(); + expect(belowCeiling.launched[0]?.titleRenamed).toBe(true); const titled = yield* launchWith("full-access", "full-access", { title: "Fix", @@ -261,6 +262,7 @@ it.effect( message: "Fix the bug", }); expect(titled.launched[0]).toMatchObject({ title: "Fix", generateTitle: true }); + expect(titled.launched[0]?.titleRenamed).toBeUndefined(); for (const message of [undefined, "", " \n "]) { const idleTitled = yield* launchWith("full-access", "full-access", { diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index 3966d48ccd090..76f53b43bdfdc 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -438,6 +438,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { projectId, title: input.title, ...(input.generateTitle === undefined ? {} : { generateTitle: input.generateTitle }), + ...(input.generateTitle === true ? {} : { titleRenamed: true }), modelSelection, runtimeMode: startedRuntimeMode, interactionMode, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index dd69750a43496..bcbe8a3656017 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -4040,6 +4040,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio id: command.threadId, projectId: command.projectId, title: command.title, + ...(command.titleRenamed === true ? { titleRenamed: true } : {}), providerInstanceId: command.modelSelection.instanceId, modelSelection: command.modelSelection, runtimeMode: command.runtimeMode, @@ -7428,7 +7429,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio !hasTitleSetBeforeFirstMessage(projection.thread, command.titleSeed); if ( !isNativeMaintenanceCommand(command) && - (seedsUntitledThread || (command.createdBy === "user" && (yield* onlyMaintenanceHistory))) + (seedsUntitledThread || + (command.createdBy === "user" && + // A draft opened by `/compact` is titled after it, so only a chosen title stays here. + projection.thread.titleRenamed !== true && + (yield* onlyMaintenanceHistory))) ) { const now = yield* DateTime.now; const thread: OrchestrationV2AppThread = { diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts index e0ae516a190b5..0382415179bfc 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts @@ -103,6 +103,8 @@ export interface ThreadLaunchInput { readonly projectId: ProjectId; readonly title: string; readonly generateTitle?: boolean; + /** The caller chose `title`, so a first message keeps it. */ + readonly titleRenamed?: boolean; readonly modelSelection: ModelSelection; readonly runtimeMode: RuntimeMode; readonly interactionMode: ProviderInteractionMode; @@ -1458,6 +1460,7 @@ const make = Effect.gen(function* () { threadId: candidateThreadId, projectId: input.projectId, title: input.title, + ...(input.titleRenamed === true ? { titleRenamed: true } : {}), modelSelection: input.modelSelection, runtimeMode: input.runtimeMode, interactionMode: input.interactionMode, diff --git a/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts b/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts index 20cd5aaa76236..1d39000ed3a9f 100644 --- a/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts @@ -343,9 +343,19 @@ describe("ThreadTitleRegenerationService", () => { const threads = yield* ThreadManagement.ThreadManagementService; const outbox = yield* EffectOutbox.EffectOutboxV2; // An MCP launch names the thread, or leaves a placeholder, and sends no message. - for (const [key, title, expectedTitle, generates] of [ - ["preset", "[API] #4821 — retry webhook deliveries after a timeout", undefined, false], - ["placeholder", placeholderThreadTitle("Parent", 0), seed, true], + for (const [key, title, titleRenamed, compactFirst, expectedTitle, generates] of [ + [ + "preset", + "[API] #4821 - retry webhook deliveries after a timeout", + false, + false, + undefined, + false, + ], + ["placeholder", placeholderThreadTitle("Parent", 0), false, false, seed, true], + ["named like a placeholder", "Release thread 2", true, false, undefined, false], + ["named, then compacted", "Release notes", true, true, undefined, false], + ["draft titled by its /compact", "/compact", false, true, seed, true], ] as const) { const threadId = ThreadId.make(`thread:title:${key}`); yield* threads.dispatch({ @@ -354,6 +364,7 @@ describe("ThreadTitleRegenerationService", () => { threadId, projectId, title, + ...(titleRenamed ? { titleRenamed } : {}), modelSelection, runtimeMode: "full-access", interactionMode: "default", @@ -362,6 +373,21 @@ describe("ThreadTitleRegenerationService", () => { createdBy: "agent", creationSource: "mcp", }); + if (compactFirst) { + yield* threads.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`command:title:${key}:compact`), + threadId, + messageId: MessageId.make(`command:title:${key}:compact:message`), + text: "/compact", + titleSeed: "/compact", + attachments: [], + modelSelection, + dispatchMode: { type: "defer_start" }, + createdBy: "user", + creationSource: "web", + }); + } const requestId = CommandId.make(`command:title:${key}:message`); yield* threads.dispatch({ type: "message.dispatch", diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 51d762d77c14f..2d5bc546d1800 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -538,7 +538,7 @@ export const OrchestrationV2AppThread = Schema.Struct({ ), ), lastTitleRegeneration: Schema.optional(Schema.NullOr(OrchestrationV2LastTitleRegeneration)), - /** Set by a rename until a generated title replaces it; absent reads as false. */ + /** Set by a rename or a naming launch until a generated title replaces it; absent reads false. */ titleRenamed: Schema.optional(Schema.Boolean), rollbackRequestId: Schema.optional(CommandId), rollbackFailure: Schema.optional( @@ -3244,6 +3244,7 @@ export const OrchestrationV2Command = Schema.Union([ threadId: ThreadId, projectId: ProjectId, title: TrimmedNonEmptyString, + titleRenamed: Schema.optional(Schema.Boolean), modelSelection: ModelSelection, runtimeMode: RuntimeMode, interactionMode: ProviderInteractionMode, From 7b21adbe7cd633813eeb8a9e3ec4961ec31f98a3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 14:35:39 -0800 Subject: [PATCH 070/139] fix(server): a merge no longer settles an unlinked thread on another thread's PR branch (#40564) --- .../ProjectionSettlement.test.ts | 8 +- .../src/orchestration-v2/ProjectionStore.ts | 5 +- .../ThreadSettlementService.test.ts | 107 ++++++++++++++++++ .../ThreadSettlementService.ts | 50 +++++++- 4 files changed, 165 insertions(+), 5 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts index 86a4c6c77375d..cb2fb0e87ada4 100644 --- a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts @@ -433,7 +433,7 @@ it.effect("sql: lists only active threads with pull request links, oldest first" const store = yield* ProjectionStore.ProjectionStoreV2; yield* createThread("no-links"); yield* createThread("empty-links", { pullRequests: [] }); - yield* createThread("archived-link", { + const archived = yield* createThread("archived-link", { archivedAt: old, pullRequests: [pullRequestLink(1)], }); @@ -459,6 +459,12 @@ it.effect("sql: lists only active threads with pull request links, oldest first" (yield* store.getThreadsWithPullRequests(open)).map((thread) => thread.id), [open], ); + assert.deepEqual( + (yield* store.getThreadsWithPullRequests(undefined, { includeArchived: true })).map( + (thread) => thread.id, + ), + [settled, archived, open], + ); }).pipe(Effect.provide(layerSql)), ); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index ba91ba94d2520..6c8308706b651 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -684,6 +684,7 @@ export interface ProjectionStoreV2Shape { ) => Effect.Effect, ProjectionStoreV2Error>; readonly getThreadsWithPullRequests: ( threadId?: ThreadId, + options?: { readonly includeArchived?: boolean }, ) => Effect.Effect, ProjectionStoreV2Error>; /** Titles of the given threads that exist, archived ones included. */ readonly getThreadLinkMetadata: ( @@ -8972,12 +8973,12 @@ export const layer: Layer.Layer = const getThreadsWithPullRequests: ProjectionStoreV2Shape["getThreadsWithPullRequests"] = Effect.fn("ProjectionStore.getThreadsWithPullRequests")( - function* (threadId) { + function* (threadId, options) { const rows = yield* sql` SELECT payload_json FROM orchestration_v2_projection_threads WHERE deleted_at IS NULL${threadId === undefined ? sql`` : sql` AND thread_id = ${threadId}`} - AND json_extract(payload_json, '$.archivedAt') IS NULL + ${options?.includeArchived === true ? sql`` : sql`AND json_extract(payload_json, '$.archivedAt') IS NULL`} AND json_array_length(payload_json, '$.pullRequests') > 0 ORDER BY updated_at ASC, thread_id ASC `; diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts index b20feef64eadd..0fee4a50ce34b 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts @@ -689,6 +689,16 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: listShells: () => Ref.get(snapshots).pipe(Effect.map((snapshot) => snapshot.projects)), }), Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getThreadsWithPullRequests: (_threadId, readOptions) => + Ref.get(snapshots).pipe( + Effect.map((snapshot) => + snapshot.threads + .filter( + (thread) => readOptions?.includeArchived === true || thread.archivedAt === null, + ) + .map((thread) => ({ ...thread, pullRequests: thread.pullRequests ?? [] })), + ), + ), ...options.projections, getSettlementCandidates: (threadId) => Ref.update(candidateReads, (reads) => [...reads, threadId]).pipe( @@ -2109,6 +2119,103 @@ describe("ThreadSettlementServiceV2 worker", () => { }).pipe(Effect.provide(fixture.layer)); }), ); + + it.effect("a merge does not settle a local thread on the branch of another thread's PR", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const mergedLink = { + ...persistedLink("open", DateTime.makeUnsafe("2026-08-20T00:00:00.000Z")), + snapshot: { + ...persistedLink("open", DateTime.makeUnsafe("2026-08-20T00:00:00.000Z")).snapshot!, + state: "merged" as const, + mergedAt: NOW, + }, + }; + const owner = makeThread("pr-owner", { branch: "feature", pullRequests: [mergedLink] }); + const sibling = makeThread("local-sibling", { + branch: "feature", + createdAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + }); + const cachedSibling = makeThread("cached-sibling", { + branch: "feature", + createdAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + branchPullRequest: { + projectId: PROJECT_ID, + repository: "owner/repository", + number: 42, + url: "https://example.test/owner/repository/pull/42", + }, + }); + const legacyOwner = makeThread("legacy-owner", { + branch: "feature", + createdAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + linkedPullRequest: cachedSibling.branchPullRequest, + }); + const fixture = yield* makeHarness({ + snapshot: makeSnapshot([owner, sibling, legacyOwner, cachedSibling]), + settings: { + ...DEFAULT_SERVER_SETTINGS, + sidebarAutoSettleOnMerge: true, + sidebarAutoSettleAfterDays: null, + }, + branchPullRequest: () => Effect.succeed(makeBranchPullRequest("merged")), + }); + + yield* Effect.gen(function* () { + const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2; + yield* startHarness(reactor, fixture.activation, fixture.snapshotReads); + yield* fixture.publishMerge; + yield* Queue.take(fixture.snapshotReads); + yield* reactor.drain; + + expect( + [ + ...new Set((yield* Ref.get(fixture.commands)).map((command) => command.threadId)), + ].toSorted(), + ).toEqual([legacyOwner.id, owner.id].toSorted()); + }).pipe(Effect.provide(fixture.layer)); + }), + ); + it.effect("an archived thread's pull request does not settle a local thread on its branch", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const link = persistedLink("open", DateTime.makeUnsafe("2026-08-20T00:00:00.000Z")); + const owner = makeThread("archived-owner", { + branch: "feature", + archivedAt: DateTime.makeUnsafe("2026-08-29T00:00:00.000Z"), + pullRequests: [ + { ...link, snapshot: { ...link.snapshot!, state: "merged", mergedAt: NOW } }, + ], + }); + const sibling = makeThread("local-sibling", { + branch: "feature", + createdAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + }); + const fixture = yield* makeHarness({ + snapshot: makeSnapshot([owner, sibling]), + settings: { + ...DEFAULT_SERVER_SETTINGS, + sidebarAutoSettleOnMerge: true, + sidebarAutoSettleAfterDays: null, + }, + branchPullRequest: () => Effect.succeed(makeBranchPullRequest("merged")), + }); + + yield* Effect.gen(function* () { + const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2; + yield* startHarness(reactor, fixture.activation, fixture.snapshotReads); + yield* fixture.publishMerge; + yield* Queue.take(fixture.snapshotReads); + yield* reactor.drain; + + expect(yield* Ref.get(fixture.commands)).toEqual([]); + }).pipe(Effect.provide(fixture.layer)); + }), + ); }); describe("ThreadSettlementServiceV2 terminals", () => { diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index 6f05e0fd3c40c..38616d48846de 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -35,6 +35,10 @@ import * as TerminalManager from "../terminal/Manager.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as ProjectStore from "./ProjectStore.ts"; import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; +import { + legacyThreadPullRequestKey, + threadPullRequestKeyOf, +} from "../sourceControl/threadPullRequests.ts"; import { makeNoPullRequestRechecks } from "./noPullRequestRechecks.ts"; import * as Orchestrator from "./Orchestrator.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; @@ -87,6 +91,20 @@ function pullRequestMatchesProject( ); } +function branchPullRequestKey(pullRequest: GitManager.GitBranchPullRequest): string | null { + const parsed = sourceControlDefinitions.parseChangeRequestUrl(pullRequest.url)?.link; + if (parsed !== undefined && parsed.number === pullRequest.number) { + return threadPullRequestKeyOf(parsed); + } + const separator = pullRequest.repositoryKey?.indexOf("/") ?? -1; + if (pullRequest.repositoryKey == null || separator <= 0) return null; + return threadPullRequestKeyOf({ + host: pullRequest.repositoryKey.slice(0, separator), + repository: pullRequest.repositoryKey.slice(separator + 1), + number: pullRequest.number, + }); +} + type SettlementPullRequestLink = NonNullable< ProjectionStore.ProjectionSettlementCandidate["pullRequests"] >[number]; @@ -481,7 +499,7 @@ export const make = Effect.gen(function* () { const reference = thread.linkedPullRequest ?? thread.branchPullRequest; if (reference != null) { return JSON.stringify([ - "linked", + thread.linkedPullRequest != null ? "linked" : "branch-reference", reference.projectId, reference.repository, reference.number, @@ -496,6 +514,22 @@ export const make = Effect.gen(function* () { ); }; const groups = Map.groupBy(lookupCandidates, lookupKey); + // A thread with no link of its own does not settle from a pull request another thread links, + // archived threads included. + const explicitlyLinked = new Set( + groups.size === 0 + ? [] + : (yield* projections.getThreadsWithPullRequests(undefined, { + includeArchived: true, + })).flatMap((thread) => + visibleThreadPullRequests(thread.pullRequests ?? []).map(threadPullRequestKeyOf), + ), + ); + const ownedByAnotherThread = (pullRequest: GitManager.GitBranchPullRequest | null) => { + if (pullRequest === null || pullRequest.state === "open") return false; + const key = branchPullRequestKey(pullRequest); + return key !== null && explicitlyLinked.has(key); + }; // wouldSettle and pullRequestFor run per lookup group; the git and pull request reads they make carry the spans. const wouldSettle = Effect.fnUntraced(function* ( @@ -524,6 +558,13 @@ export const make = Effect.gen(function* () { ) { const thread = group[0]!; const reference = thread.linkedPullRequest ?? thread.branchPullRequest; + if ( + thread.linkedPullRequest == null && + reference != null && + explicitlyLinked.has(threadPullRequestKeyOf(legacyThreadPullRequestKey(reference))) + ) { + return undefined; + } if (reference != null) { // Only matching PR links settle from this merge event; unrelated links require fresh lookup. const matchesMerge = @@ -601,9 +642,14 @@ export const make = Effect.gen(function* () { { refresh, confirmTerminal: false }, ); noPullRequestRechecks.record(key, nowMs, remembered !== null); + if (ownedByAnotherThread(remembered)) return undefined; if (refresh || remembered === null || remembered.state === "open") return remembered; if (!(yield* wouldSettle(group, remembered))) return undefined; - return yield* git.branchPullRequest({ cwd, branch: thread.branch }, { freshGitState: true }); + const fresh = yield* git.branchPullRequest( + { cwd, branch: thread.branch }, + { freshGitState: true }, + ); + return ownedByAnotherThread(fresh) ? undefined : fresh; }); // A merge, a shell close and a thread's own events read at once; only scheduled sweeps wait. From d3242f8ed1c2f40116d0bf14d5c7e5c0b9e1b8cd Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:41:55 +0100 Subject: [PATCH 071/139] fix(mobile): reuse gallery resources for workspace image taps (#40576) Co-authored-by: Julius Marminge --- .../src/features/threads/ThreadFeed.tsx | 23 ++-- .../threads/ThreadMarkdownImage.test.tsx | 58 +++++++++- .../features/threads/ThreadMarkdownImage.tsx | 1 + apps/mobile/src/lib/filePreview.test.ts | 101 +++++++++++++++--- 4 files changed, 153 insertions(+), 30 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 8a2a7e83a6698..53b773dc7f9c4 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -106,10 +106,7 @@ import { settlePromise, squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; -import { - classifyMarkdownImageSource, - markdownImageSourceFragment, -} from "@t3tools/client-runtime/markdown-images"; +import { classifyMarkdownImageSource } from "@t3tools/client-runtime/markdown-images"; import { contextCompactionTokenCounts, resolveViewedImageAsset, @@ -3743,20 +3740,20 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { /> ); } - if (imageSource._tag === "Blocked") { + if ( + media?.kind !== "image" || + !("resource" in media.source) || + media.source.resource._tag !== "media-file" + ) { return ; } return ( ); diff --git a/apps/mobile/src/features/threads/ThreadMarkdownImage.test.tsx b/apps/mobile/src/features/threads/ThreadMarkdownImage.test.tsx index 82f5cc62a7b68..2f2bffa336402 100644 --- a/apps/mobile/src/features/threads/ThreadMarkdownImage.test.tsx +++ b/apps/mobile/src/features/threads/ThreadMarkdownImage.test.tsx @@ -82,9 +82,6 @@ vi.mock("expo/fetch", () => ({ fetch: vi.fn() })); vi.mock("react-native-svg", () => ({ parse: vi.fn(), SvgAst: () => null })); vi.mock("@t3tools/client-runtime/state/assets", () => ({ MISSING_FILE_ACCESS_MESSAGE: "" })); vi.mock("../../components/ui/AppActivityIndicator", () => ({ AppActivityIndicator: () => null })); -vi.mock("../../components/ui/FilePreviewGallery", () => ({ - useFilePreviewGallery: () => (source: unknown) => source, -})); vi.mock("../../components/ui/AppText", () => ({ AppText: ({ children }: { children?: ReactNode }) => {children}, })); @@ -96,11 +93,64 @@ vi.mock("../../state/mediaActions", () => ({ useMediaActions: () => ({ actions: vi.mock("../../state/assets", () => ({ useAssetUrlState: vi.fn() })); import { RegistryContext } from "@effect/atom-react"; +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { AtomRegistry } from "effect/reactivity"; import { fetch } from "expo/fetch"; import { parse } from "react-native-svg"; -import { MarkdownImageAvailableWidthContext, ThreadMarkdownImageView } from "./ThreadMarkdownImage"; +import { FilePreviewGallery } from "../../components/ui/FilePreviewGallery"; +import type { FilePreviewSource } from "../../components/ui/FilePreviewModal.types"; +import { useAssetUrlState } from "../../state/assets"; +import { + MarkdownImageAvailableWidthContext, + ThreadMarkdownImage, + ThreadMarkdownImageView, +} from "./ThreadMarkdownImage"; + +it("keeps the tapped workspace image fragment on its gallery page", async () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const root = createRoot(document.createElement("div")); + const environmentId = EnvironmentId.make("environment-1"); + const threadId = ThreadId.make("thread-1"); + const resource = { _tag: "media-file", threadId, path: "/repo/./red.png" } as const; + const red = { kind: "image", environmentId, resource, srcFragment: "#detail" } as const; + const blue = { + kind: "image", + environmentId, + resource: { ...resource, path: "/repo/./blue.png" }, + } as const; + const openPreview = vi.fn<(source: FilePreviewSource) => void>(); + vi.mocked(useAssetUrlState).mockReturnValueOnce({ + _tag: "Success", + url: "https://example.test/red.png", + expiresAt: 0, + }); + try { + await act(async () => + root.render( + + + , + ), + ); + await act(async () => harness.pressable.onPress?.({ nativeEvent: {} })); + expect(openPreview).toHaveBeenCalledWith( + expect.objectContaining({ + resource, + srcFragment: "#detail", + gallery: [expect.objectContaining(red), blue], + }), + ); + } finally { + await act(async () => root.unmount()); + } +}); it("keeps the frame size when the same image reports a different decoded width", async () => { (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; diff --git a/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx b/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx index 8a7540625cc08..8e18d8445c85a 100644 --- a/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx +++ b/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx @@ -342,6 +342,7 @@ export function ThreadMarkdownImage(props: { gallery: undefined, environmentId: props.environmentId, resource: props.resource, + ...(props.srcFragment === undefined ? {} : { srcFragment: props.srcFragment }), }), ); }} diff --git a/apps/mobile/src/lib/filePreview.test.ts b/apps/mobile/src/lib/filePreview.test.ts index cd0bd8ae9890c..7c463ac0c3438 100644 --- a/apps/mobile/src/lib/filePreview.test.ts +++ b/apps/mobile/src/lib/filePreview.test.ts @@ -23,6 +23,7 @@ import { acquireAudioSession, activateAudioSession, releaseAudioSession } from " import { ThreadFeed } from "../features/threads/ThreadFeed"; import type { ThreadFeedEntry } from "./threadActivity"; import type { MarkdownImageRenderer } from "../native/SelectableMarkdownText"; +import type { FilePreviewItem, FilePreviewSource } from "../components/ui/FilePreviewModal.types"; const audio = vi.hoisted(() => ({ status: { @@ -203,12 +204,18 @@ vi.mock("../native/SelectableMarkdownText", () => ({ onLinkPress(href: string): void; renderImage?: MarkdownImageRenderer; }) => { - const embed = props.markdown.match(/!\[([^\]]*)\]\(([^)]+)\)/); + const embeds = [...props.markdown.matchAll(/!\[([^\]]*)\]\(([^)]+)\)/g)]; return createElement( "div", null, createElement("button", { onClick: () => props.onLinkPress("target.ts") }, props.markdown), - embed && props.renderImage?.({ href: embed[2]!, alt: embed[1]!, title: null }), + embeds.map(([, alt, href], index) => + createElement( + Fragment, + { key: index }, + props.renderImage?.({ href: href!, alt: alt!, title: null }), + ), + ), ); }, })); @@ -238,7 +245,9 @@ vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ top: 0, bottom: 0 }), })); vi.mock("expo-haptics", () => ({ selectionAsync: async () => {} })); -vi.mock("expo-image", () => ({})); +vi.mock("expo-image", () => ({ Image: () => null })); +vi.mock("expo/fetch", () => ({})); +vi.mock("react-native-svg", () => ({})); vi.mock("uniwind", () => ({})); vi.mock("../components/ui/Dialog", () => ({})); vi.mock("../components/ui/Sheet", () => ({ @@ -254,13 +263,19 @@ vi.mock("../components/ui/NativePresentation", () => ({ vi.mock("../components/ui/Menu", () => ({ Menu: ({ children }: { children?: ReactNode }) => children, })); -vi.mock("../components/ui/FilePreviewGallery", () => ({ - FilePreviewGallery: ({ children }: { children?: ReactNode }) => children, - useFilePreviewGallery: () => (source: unknown) => source, -})); +function previewPath(item: FilePreviewItem) { + return "resource" in item && "path" in item.resource ? item.resource.path : null; +} + vi.mock("../components/ui/FilePreviewModal", () => ({ - FilePreviewModal: (props: { source: { name: string } | null }) => - props.source ? createElement("div", { "data-file-preview": props.source.name }) : null, + FilePreviewModal: ({ source }: { source: FilePreviewSource | null }) => + source + ? createElement("div", { + "data-file-preview": source.name, + "data-selected-path": previewPath(source), + "data-gallery": JSON.stringify(source.gallery?.map(previewPath)), + }) + : null, })); vi.mock("../components/ui/VideoPreviewModal", () => ({ VideoPreviewModal: () => null })); vi.mock("../components/ComposerContextSheet", () => ({})); @@ -313,10 +328,6 @@ vi.mock("../features/layout/AdaptiveWorkspaceLayout", () => ({ })); vi.mock("../features/threads/thread-workflow-opening", () => ({ useWorkflowOpening: () => null })); vi.mock("../features/threads/useFileChipShare", () => ({ useFileChipShare: () => vi.fn() })); -vi.mock("../features/threads/ThreadMarkdownImage", async () => { - const { createContext } = await import("react"); - return { MarkdownImageAvailableWidthContext: createContext(390) }; -}); vi.mock("../features/threads/ZoomableImagePressable", async () => { const { Pressable } = await import("react-native"); return { ZoomableImagePressable: Pressable }; @@ -1408,6 +1419,70 @@ describe("inline file previews", () => { }); describe("ThreadFeed previews", () => { + it("opens a tapped workspace image on its own gallery page, in message order", async () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const threadId = ThreadId.make("thread-1"); + const messageId = MessageId.make("message-1"); + const timestamp = "2026-10-20T00:00:00.000Z"; + const container = document.createElement("div"); + const root = createRoot(container); + try { + await act(async () => + root.render( + createElement(ThreadFeed, { + environmentId: EnvironmentId.make("environment-1"), + threadId, + detailRef: null, + threadTitle: "preview", + workspaceRoot: "/repo", + feed: [ + { + type: "message", + id: messageId, + createdAt: timestamp, + message: { + id: messageId, + role: "assistant", + text: "![Red](./red.png)\n\n![Blue](./blue.png)", + attachments: [], + createdAt: timestamp, + updatedAt: timestamp, + runId: null, + streaming: false, + visibility: "local", + sourceThreadId: threadId, + }, + }, + ], + queuedMessages: [], + dispatchingMessageId: null, + onEditPendingMessage: null, + contentPresentation: { kind: "ready" }, + latestRun: null, + activeWorkStartedAt: null, + listRef: { current: null }, + freeze: { value: false } as Parameters[0]["freeze"], + contentInsetEndAdjustment: { value: 0 } as Parameters< + typeof ThreadFeed + >[0]["contentInsetEndAdjustment"], + anchorMessageId: null, + keyboardOffset: 0, + }), + ), + ); + await act(async () => + container.querySelector(`[aria-label="Red"]`)!.click(), + ); + const preview = container.querySelector("[data-file-preview]"); + expect(preview?.getAttribute("data-selected-path")).toBe("/repo/./red.png"); + expect(preview?.getAttribute("data-gallery")).toBe( + JSON.stringify(["/repo/./red.png", "/repo/./blue.png"]), + ); + } finally { + await act(async () => root.unmount()); + } + }); + it("does not commit an open preview over a different thread", async () => { (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; const environmentId = EnvironmentId.make("environment-1"); From 6247463bd3aa950cd309a6dfa2799d927e1c314c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 14:42:37 -0800 Subject: [PATCH 072/139] perf(server): turn-end git status reads the branch remote and remote URL once (#40533) --- apps/server/src/git/GitManager.test.ts | 54 ++++++++++++++++++ apps/server/src/git/GitManager.ts | 79 ++++++++++++++++++++++++-- 2 files changed, 127 insertions(+), 6 deletions(-) diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 064427a3727f5..94247273e1ca0 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -1100,6 +1100,60 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + it.effect("a turn-end status refresh reads the branch remote and remote URL once", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["checkout", "-b", "feature/turn-end"]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/turn-end"]); + const gitCommands: string[] = []; + const { manager } = yield* makeManager({ gitCommands }); + const count = (cmd: string) => gitCommands.filter((args) => args === cmd).length; + + // Turn end: local status, then the PR lookup for a branch that has no PR yet. + yield* manager.invalidateLocalStatus(repoDir); + yield* manager.localStatus({ cwd: repoDir }); + yield* manager.invalidateRemoteStatus(repoDir); + const remote = yield* manager.remoteStatus( + { cwd: repoDir }, + { refreshUpstream: false, refreshMissingPullRequest: true }, + ); + + expect(remote?.pr ?? null).toBeNull(); + expect(count("config --get branch.feature/turn-end.remote")).toBe(1); + expect(count("config --get-all remote.origin.url")).toBe(1); + + // The thread's PR backfill can reach the lookup before the status refresh does. + const backfillCommands: string[] = []; + const backfill = yield* makeManager({ gitCommands: backfillCommands }); + yield* backfill.manager.localStatus({ cwd: repoDir }); + yield* backfill.manager.branchPullRequest( + { cwd: repoDir, branch: "feature/turn-end" }, + { confirmTerminal: false }, + ); + yield* backfill.manager.remoteStatus( + { cwd: repoDir }, + { refreshUpstream: false, refreshMissingPullRequest: true }, + ); + expect( + backfillCommands.filter((args) => args === "config --get branch.feature/turn-end.remote") + .length, + ).toBe(1); + + // A fresh identity check reads git itself, not what local status just read. + yield* manager.invalidateLocalStatus(repoDir); + yield* manager.localStatus({ cwd: repoDir }); + gitCommands.length = 0; + yield* manager.branchPullRequest( + { cwd: repoDir, branch: "feature/turn-end" }, + { freshGitState: true }, + ); + expect(count("config --get-all remote.origin.url")).toBe(1); + }), + ); + it.effect("a git read in flight during a T3 git action does not outlive it", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index 543b5de5505f5..db62af1f79b69 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -220,6 +220,8 @@ const PR_LOOKUP_FAILURE_BASE_TTL = Duration.seconds(20); const PR_LOOKUP_FAILURE_MAX_TTL = Duration.minutes(15); const PR_LOOKUP_CACHE_CAPACITY = 2_048; const PR_LOOKUP_GIT_STATE_TTL = Duration.minutes(5); +// Turn end looks up the PR ~0.5 s after local status; older reads are read again. +const LOCAL_STATUS_GIT_READS_HANDOFF_TTL = Duration.seconds(5); const SETTLED_PR_LOOKUP_RECHECK_INTERVAL = Duration.minutes(15); // Shared by every background caller (backfill, settlement, cleanup), so startup discovery // cannot fill the git and forge process slots that foreground work also needs. @@ -1289,7 +1291,7 @@ export const make = Effect.gen(function* () { Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(nonRepositoryStatusDetails)), ); const hostingProvider = details.hasOriginRemote - ? yield* resolveHostingProvider(cwd, details.branch) + ? yield* resolveHostingProviderForLocalStatus(cwd, details.branch) : null; return { @@ -1333,7 +1335,30 @@ export const make = Effect.gen(function* () { cwd: string, ): shared is SharedPrLookupGitReads => shared !== null && shared.open && shared.cwd === cwd && prLookupEpoch(cwd) === shared.epoch; - const withPrLookupGitReads = (effect: Effect.Effect, cwd: string) => + // Branch remote and remote URLs that local status just read, reused by the PR lookups that + // follow it (turn end runs the status lookup and the thread's PR backfill) instead of reading again. + const localStatusGitReads = new Map< + string, + Pick + >(); + const recentLocalStatusGitReads = (cwd: string) => + Clock.currentTimeMillis.pipe( + Effect.map((now) => { + const handoff = localStatusGitReads.get(cwd); + if (handoff === undefined || handoff.epoch !== prLookupEpoch(cwd)) return undefined; + const isFresh = (entry: RememberedPrLookupValue) => + now - entry.readAtMs < Duration.toMillis(LOCAL_STATUS_GIT_READS_HANDOFF_TTL); + return { + configValues: new Map([...handoff.configValues].filter(([, entry]) => isFresh(entry))), + remoteUrls: new Map([...handoff.remoteUrls].filter(([, entry]) => isFresh(entry))), + }; + }), + ); + const openPrLookupGitReads = ( + effect: Effect.Effect, + cwd: string, + handoff: Pick | undefined, + ) => Effect.suspend(() => { const shared: SharedPrLookupGitReads = { open: true, @@ -1341,8 +1366,8 @@ export const make = Effect.gen(function* () { cwd, epoch: prLookupEpoch(cwd), remotes: undefined, - configValues: new Map(), - remoteUrls: new Map(), + configValues: handoff?.configValues ?? new Map(), + remoteUrls: handoff?.remoteUrls ?? new Map(), }; return effect.pipe( Effect.provideService(prLookupGitReads, shared), @@ -1357,9 +1382,15 @@ export const make = Effect.gen(function* () { ), ); }); + const withPrLookupGitReads = (effect: Effect.Effect, cwd: string) => + openPrLookupGitReads(effect, cwd, undefined); + const withRecentLocalStatusGitReads = (effect: Effect.Effect, cwd: string) => + Effect.flatMap(recentLocalStatusGitReads(cwd), (handoff) => + openPrLookupGitReads(effect, cwd, handoff), + ); const withActivePrLookupGitReads = (cwd: string, effect: Effect.Effect) => Effect.flatMap(prLookupGitReads, (shared) => - isActivePrLookupGitReads(shared, cwd) ? effect : withPrLookupGitReads(effect, cwd), + isActivePrLookupGitReads(shared, cwd) ? effect : withRecentLocalStatusGitReads(effect, cwd), ); const prLookupCacheKey = ( cwd: string, @@ -1781,6 +1812,32 @@ export const make = Effect.gen(function* () { .pipe(Effect.orElseSucceed(() => null)); return handle?.context?.provider ?? provider; }); + const resolveHostingProviderForLocalStatus = (cwd: string, branch: string | null) => + Effect.suspend(() => { + const reads: SharedPrLookupGitReads = { + open: true, + queriedProvider: false, + cwd, + epoch: prLookupEpoch(cwd), + remotes: undefined, + configValues: new Map(), + remoteUrls: new Map(), + }; + return resolveHostingProvider(cwd, branch).pipe( + Effect.provideService(prLookupGitReads, reads), + Effect.ensuring( + Effect.sync(() => { + reads.open = false; + localStatusGitReads.delete(cwd); + if (localStatusGitReads.size >= STATUS_RESULT_CACHE_CAPACITY) { + const oldestCwd = localStatusGitReads.keys().next().value; + if (oldestCwd !== undefined) localStatusGitReads.delete(oldestCwd); + } + localStatusGitReads.set(cwd, reads); + }), + ), + ); + }); const resolveRemoteRepositoryContext = Effect.fn("resolveRemoteRepositoryContext")(function* ( cwd: string, @@ -3093,6 +3150,16 @@ export const make = Effect.gen(function* () { ], { concurrency: "unbounded" }, ).pipe(Effect.map((parts) => parts.join("\u0000"))); + // A fresh identity check, which confirms terminal results, must read git itself. + const withBranchPullRequestGitReads = ( + effect: Effect.Effect, + cacheCwd: string, + _branch: string, + options: { readonly freshGitState: boolean }, + ) => + options.freshGitState + ? withPrLookupGitReads(effect, cacheCwd) + : withRecentLocalStatusGitReads(effect, cacheCwd); const lookupBranchPullRequest = Effect.fn("lookupBranchPullRequest")(function* ( cacheCwd: string, branch: string, @@ -3261,7 +3328,7 @@ export const make = Effect.gen(function* () { // Hosting CLIs may target upstream; the PR URL identifies its actual repository. repositoryKey: pullRequestRepositoryKey(latest.url), }; - }, withPrLookupGitReads); + }, withBranchPullRequestGitReads); const checkedOutPullRequestKey = (branch: string) => `branch.${branch}.t3-pull-request`; From 904e2671ca5351bd6f5bfcbeaee3f53c828e7333 Mon Sep 17 00:00:00 2001 From: Mike Olson Date: Sat, 21 Nov 2026 17:49:55 -0500 Subject: [PATCH 073/139] fix(web): Keep background announcements quiet for held or stopped runs (#40585) Co-authored-by: Julius Marminge --- .../components/BackgroundThreadAnnouncer.tsx | 3 +- .../backgroundThreadAnnouncement.test.ts | 70 +++++++++++++++++++ .../backgroundThreadAnnouncement.ts | 25 +++++++ 3 files changed, 97 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/BackgroundThreadAnnouncer.tsx b/apps/web/src/components/BackgroundThreadAnnouncer.tsx index 3176c8132eed9..649898cf2e5a5 100644 --- a/apps/web/src/components/BackgroundThreadAnnouncer.tsx +++ b/apps/web/src/components/BackgroundThreadAnnouncer.tsx @@ -14,6 +14,7 @@ import { type BackgroundThreadSnapshot, nextBackgroundThreadAnnouncement, resolveBackgroundThreadRequest, + resolveBackgroundThreadRunStatus, } from "./backgroundThreadAnnouncement"; const backgroundThreadLiveRegion = createLiveRegion(); @@ -51,7 +52,7 @@ export function startBackgroundThreadAnnouncements( title: thread.title, ...resolveBackgroundThreadRequest(thread), runId: thread.latestRun?.runId ?? null, - runStatus: thread.latestRun?.status ?? null, + runStatus: resolveBackgroundThreadRunStatus(thread), activeRunId: thread.runtime?.activeRunId ?? null, snoozed: effectiveSnoozed(thread, { now }), }); diff --git a/apps/web/src/components/backgroundThreadAnnouncement.test.ts b/apps/web/src/components/backgroundThreadAnnouncement.test.ts index b2b6195d8f288..51d3c693f9904 100644 --- a/apps/web/src/components/backgroundThreadAnnouncement.test.ts +++ b/apps/web/src/components/backgroundThreadAnnouncement.test.ts @@ -7,6 +7,7 @@ import { type BackgroundThreadSnapshot, nextBackgroundThreadAnnouncement, resolveBackgroundThreadRequest, + resolveBackgroundThreadRunStatus, } from "./backgroundThreadAnnouncement"; const firstRun = RunId.make("run-1"); @@ -187,3 +188,72 @@ describe("resolveBackgroundThreadRequest", () => { ).toEqual(["Needs approval: Fix login redirect"]); }); }); + +describe("resolveBackgroundThreadRunStatus", () => { + const threadStatus = (overrides?: { + readonly status?: "completed" | "failed" | "interrupted"; + readonly pendingBackgroundTasks?: ReadonlyArray<{ + readonly taskId: string; + readonly kind: "command" | "monitor" | "subagent" | "background_task"; + readonly awaited?: true; + }>; + readonly latestRunBackgroundWake?: boolean; + readonly latestRunStopRequested?: boolean; + }) => { + const pendingBackgroundTasks = overrides?.pendingBackgroundTasks ?? []; + return resolveBackgroundThreadRunStatus({ + latestRun: { status: overrides?.status ?? "completed" }, + pendingBackgroundTasks, + source: { + pendingBackgroundTasks, + latestRunBackgroundWake: overrides?.latestRunBackgroundWake ?? false, + latestRunStopRequested: overrides?.latestRunStopRequested ?? false, + }, + }); + }; + + it("suppresses Done while awaited background work or a monitor wake holds completion, or when stop was requested", () => { + const heldCases = [ + { latestRunStopRequested: true }, + { pendingBackgroundTasks: [{ taskId: "sub-1", kind: "subagent" as const }] }, + { + pendingBackgroundTasks: [ + { taskId: "cmd-1", kind: "command" as const, awaited: true as const }, + ], + }, + { + latestRunBackgroundWake: true, + pendingBackgroundTasks: [{ taskId: "mon-1", kind: "monitor" as const }], + }, + ]; + for (const input of heldCases) { + expect(threadStatus(input)).toBeNull(); + } + }); + + it("keeps Done for unawaited background work and keeps non-completed outcomes", () => { + expect( + threadStatus({ + pendingBackgroundTasks: [{ taskId: "cmd-1", kind: "command" }], + }), + ).toBe("completed"); + expect( + threadStatus({ + latestRunBackgroundWake: false, + pendingBackgroundTasks: [{ taskId: "mon-1", kind: "monitor" }], + }), + ).toBe("completed"); + expect( + threadStatus({ + status: "failed", + pendingBackgroundTasks: [{ taskId: "sub-1", kind: "subagent" }], + }), + ).toBe("failed"); + expect( + threadStatus({ + status: "interrupted", + latestRunStopRequested: true, + }), + ).toBe("interrupted"); + }); +}); diff --git a/apps/web/src/components/backgroundThreadAnnouncement.ts b/apps/web/src/components/backgroundThreadAnnouncement.ts index e1c52adb662ad..48a334543c447 100644 --- a/apps/web/src/components/backgroundThreadAnnouncement.ts +++ b/apps/web/src/components/backgroundThreadAnnouncement.ts @@ -1,4 +1,8 @@ import type { OrchestrationV2RunStatus, RunId } from "@t3tools/contracts"; +import { + backgroundWorkHoldsCompletion, + monitorHoldsWakeCompletion, +} from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import { msg } from "gt-react"; @@ -40,6 +44,27 @@ export function resolveBackgroundThreadRequest( return { request: null, requestId: null }; } +/** Suppresses Done announcements for stopped runs, awaited background work, and monitor wakes. */ +export function resolveBackgroundThreadRunStatus(thread: { + readonly latestRun: { readonly status: OrchestrationV2RunStatus } | null; + readonly pendingBackgroundTasks: SidebarThreadSummary["pendingBackgroundTasks"]; + readonly source: Pick< + SidebarThreadSummary["source"], + "latestRunBackgroundWake" | "latestRunStopRequested" | "pendingBackgroundTasks" + >; +}): OrchestrationV2RunStatus | null { + const status = thread.latestRun?.status ?? null; + if ( + status === "completed" && + (thread.source.latestRunStopRequested === true || + backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks) || + monitorHoldsWakeCompletion(thread.source)) + ) { + return null; + } + return status; +} + interface BackgroundThreadMemoryEntry { readonly request: BackgroundThreadSnapshot["request"]; readonly requestId: string | null; From a480167e0cefb12846efc87d9cb839eb550db11d Mon Sep 17 00:00:00 2001 From: Adamulek123 Date: Sat, 21 Nov 2026 23:56:05 +0100 Subject: [PATCH 074/139] perf(issues): reuse repository bindings when classifying markdown links (#40592) Co-authored-by: Julius Marminge --- packages/client-runtime/src/issueLinks.test.ts | 11 +++++++++++ packages/client-runtime/src/issueLinks.ts | 16 ++++++++++++++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/packages/client-runtime/src/issueLinks.test.ts b/packages/client-runtime/src/issueLinks.test.ts index 66909fad1f054..661dfe1a94cae 100644 --- a/packages/client-runtime/src/issueLinks.test.ts +++ b/packages/client-runtime/src/issueLinks.test.ts @@ -49,6 +49,17 @@ describe("resolveIssueLinkTarget", () => { expect(target?.ref).toMatchObject({ projectId: "fork", scope: "me/web", key: "3" }); }); + it("uses the current repository identity after a project changes repositories", () => { + const url = "https://github.com/acme/api/issues/7"; + const original = project("p1", "acme/api"); + const replacement = project("p1", "acme/mobile"); + const lender = project("p3", "acme/web"); + expect(resolveIssueLinkTarget({ url, projects: [lender, original] })?.ref.projectId).toBe("p1"); + expect(resolveIssueLinkTarget({ url, projects: [lender, replacement] })?.ref.projectId).toBe( + "p3", + ); + }); + it("prefers the project bound to the link's own port over one on the bare hostname", () => { const enterprise = (id: string, host: string) => ({ diff --git a/packages/client-runtime/src/issueLinks.ts b/packages/client-runtime/src/issueLinks.ts index 0b442d18c92b5..db06b1b0a218f 100644 --- a/packages/client-runtime/src/issueLinks.ts +++ b/packages/client-runtime/src/issueLinks.ts @@ -3,6 +3,7 @@ import { issueTrackerBindingScopes, type IssueRef, type IssueTrackerConnectionList, + type RepositoryIdentity, } from "@t3tools/contracts"; import { LINEAR_HOST, @@ -15,11 +16,22 @@ import type { EnvironmentProject } from "./state/shell.ts"; type LinkProject = Pick; +const issueBindingsByRepository = new WeakMap< + RepositoryIdentity, + ReturnType +>(); + /** The hosts and scopes a project's git-host tracker is bound to, the way the server resolves them. */ function projectIssueBindings(project: LinkProject) { - return sourceControlClients - .issueBindings(project.repositoryIdentity) + const identity = project.repositoryIdentity; + if (identity == null) return []; + const cached = issueBindingsByRepository.get(identity); + if (cached !== undefined) return cached; + const bindings = sourceControlClients + .issueBindings(identity) .map((binding) => ({ ...binding, scope: binding.scope.toLowerCase() })); + issueBindingsByRepository.set(identity, bindings); + return bindings; } function linkAuthority(url: string): string | null { From b5709bb8650904f5be0e4db561cb547364febe20 Mon Sep 17 00:00:00 2001 From: Adamulek123 Date: Sat, 21 Nov 2026 23:59:08 +0100 Subject: [PATCH 075/139] perf(issues): read only the selected project tracker binding (#40587) Co-authored-by: Julius Marminge --- apps/server/src/issue/IssueService.test.ts | 6 ++- apps/server/src/issue/IssueService.ts | 2 +- .../src/issue/IssueTrackerConnections.ts | 2 +- .../src/mcp/toolkits/issues/handlers.test.ts | 9 ++-- .../src/persistence/IssueTrackerBindings.ts | 45 ++++++++++--------- .../103_IssueTrackerAdditionalScopes.test.ts | 8 +++- 6 files changed, 43 insertions(+), 29 deletions(-) diff --git a/apps/server/src/issue/IssueService.test.ts b/apps/server/src/issue/IssueService.test.ts index e8308b8480d02..6291f304e6efc 100644 --- a/apps/server/src/issue/IssueService.test.ts +++ b/apps/server/src/issue/IssueService.test.ts @@ -156,7 +156,9 @@ function makeService(input: { readonly projects: ReadonlyArray; readonly trackers: ReadonlyArray; readonly bindings?: Record; - readonly readBindings?: IssueTrackerBindings.IssueTrackerBindingsRepository["Service"]["list"]; + readonly readBindings?: ReturnType< + IssueTrackerBindings.IssueTrackerBindingsRepository["Service"]["list"] + >; }) { return IssueService.IssueService.pipe( Effect.provide( @@ -164,7 +166,7 @@ function makeService(input: { Layer.provide( Layer.mergeAll( Layer.mock(IssueTrackerBindings.IssueTrackerBindingsRepository)({ - list: + list: () => input.readBindings ?? Effect.succeed( new Map( diff --git a/apps/server/src/issue/IssueService.ts b/apps/server/src/issue/IssueService.ts index 27499b240d655..049de0d757a1c 100644 --- a/apps/server/src/issue/IssueService.ts +++ b/apps/server/src/issue/IssueService.ts @@ -249,7 +249,7 @@ const make = Effect.gen(function* () { ); if (shells.length === 0) return []; // One read per listing, not per project, and never cached so Settings changes apply. - const bound = yield* bindings.list.pipe( + const bound = yield* bindings.list(filter.projectId).pipe( // A failed read is not an unbound project: that would list the git host's issues alone. Effect.mapError( (cause) => diff --git a/apps/server/src/issue/IssueTrackerConnections.ts b/apps/server/src/issue/IssueTrackerConnections.ts index 390cc9701e858..704116fc65326 100644 --- a/apps/server/src/issue/IssueTrackerConnections.ts +++ b/apps/server/src/issue/IssueTrackerConnections.ts @@ -113,7 +113,7 @@ const make = Effect.gen(function* () { const list: IssueTrackerConnections["Service"]["list"] = Effect.all({ trackers: Effect.forEach(registry.standalone, current, { concurrency: 4 }), - bindings: bindings.list.pipe( + bindings: bindings.list().pipe( Effect.map((bound) => Object.fromEntries(bound)), // No single tracker is at fault; the first registered one carries the report. Effect.mapError(secretFailure(anyTracker, "The project bindings could not be read.")), diff --git a/apps/server/src/mcp/toolkits/issues/handlers.test.ts b/apps/server/src/mcp/toolkits/issues/handlers.test.ts index 143ba4a0c98a3..5736b685b829b 100644 --- a/apps/server/src/mcp/toolkits/issues/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/issues/handlers.test.ts @@ -260,7 +260,7 @@ describe("issue toolkit handlers", () => { projectLayer, Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({}), Layer.mock(IssueTrackerBindings.IssueTrackerBindingsRepository)({ - list: Effect.succeed(new Map([[PROJECT_ID, { tracker, scope: "ENG" }]])), + list: () => Effect.succeed(new Map([[PROJECT_ID, { tracker, scope: "ENG" }]])), }), Layer.succeed( IssueTrackerRegistry.IssueTrackerRegistry, @@ -314,9 +314,10 @@ describe("issue toolkit handlers", () => { projectLayer, Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({}), Layer.mock(IssueTrackerBindings.IssueTrackerBindingsRepository)({ - list: Effect.succeed( - new Map([[PROJECT_ID, { tracker, scope: "ENG", additionalScopes: ["OPS"] }]]), - ), + list: () => + Effect.succeed( + new Map([[PROJECT_ID, { tracker, scope: "ENG", additionalScopes: ["OPS"] }]]), + ), }), Layer.succeed( IssueTrackerRegistry.IssueTrackerRegistry, diff --git a/apps/server/src/persistence/IssueTrackerBindings.ts b/apps/server/src/persistence/IssueTrackerBindings.ts index fbb0a398900d2..2f665b487e03f 100644 --- a/apps/server/src/persistence/IssueTrackerBindings.ts +++ b/apps/server/src/persistence/IssueTrackerBindings.ts @@ -26,7 +26,9 @@ const BindingRow = Schema.Struct({ export class IssueTrackerBindingsRepository extends Context.Service< IssueTrackerBindingsRepository, { - readonly list: Effect.Effect< + readonly list: ( + projectId?: ProjectId, + ) => Effect.Effect< ReadonlyMap, IssueTrackerBindingsRepositoryError >; @@ -56,32 +58,35 @@ function toSqlOrDecodeError(sqlOperation: string, decodeOperation: string) { const make = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; + const select = sql` + SELECT project_id AS "projectId", tracker AS "tracker", scope AS "scope", + additional_scopes AS "additionalScopes" + FROM issue_tracker_bindings + `; const listRows = SqlSchema.findAll({ - Request: Schema.Void, + Request: Schema.UndefinedOr(ProjectId), Result: BindingRow, - execute: () => - sql` - SELECT project_id AS "projectId", tracker AS "tracker", scope AS "scope", - additional_scopes AS "additionalScopes" - FROM issue_tracker_bindings - `, + execute: (projectId) => + projectId === undefined ? select : sql`${select} WHERE project_id = ${projectId}`, }); return IssueTrackerBindingsRepository.of({ - list: listRows(undefined).pipe( - Effect.map( - (rows) => - new Map( - rows.map( - ({ projectId, additionalScopes, ...binding }) => - [ - projectId, - additionalScopes.length === 0 ? binding : { ...binding, additionalScopes }, - ] as const, + list: Effect.fn("IssueTrackerBindingsRepository.list")((projectId?: ProjectId) => + listRows(projectId).pipe( + Effect.map( + (rows) => + new Map( + rows.map( + ({ projectId, additionalScopes, ...binding }) => + [ + projectId, + additionalScopes.length === 0 ? binding : { ...binding, additionalScopes }, + ] as const, + ), ), - ), + ), + Effect.mapError(toSqlOrDecodeError("listIssueTrackerBindings", "IssueTrackerBinding")), ), - Effect.mapError(toSqlOrDecodeError("listIssueTrackerBindings", "IssueTrackerBinding")), ), set: Effect.fn("IssueTrackerBindingsRepository.set")( function* (input) { diff --git a/apps/server/src/persistence/Migrations/103_IssueTrackerAdditionalScopes.test.ts b/apps/server/src/persistence/Migrations/103_IssueTrackerAdditionalScopes.test.ts index 3ea190f41d2ed..9e61347812e74 100644 --- a/apps/server/src/persistence/Migrations/103_IssueTrackerAdditionalScopes.test.ts +++ b/apps/server/src/persistence/Migrations/103_IssueTrackerAdditionalScopes.test.ts @@ -21,13 +21,19 @@ it.layer(NodeSqliteClient.layer({ filename: ":memory:" }))( ); const projectId = ProjectId.make("web"); const binding = { tracker: IssueTrackerKind.make("linear"), scope: "ENG" }; - const read = () => bindings.list.pipe(Effect.map((all) => all.get(projectId))); + const read = () => bindings.list(projectId).pipe(Effect.map((rows) => rows.get(projectId))); assert.deepStrictEqual(yield* read(), binding); const multi = { ...binding, additionalScopes: ["OPS", "DOCS"] }; yield* bindings.set({ projectId, binding: multi, updatedAt: "2026-11-21" }); assert.deepStrictEqual(yield* read(), multi); yield* bindings.set({ projectId, binding, updatedAt: "2026-11-21" }); assert.deepStrictEqual(yield* read(), binding); + yield* sql` + INSERT INTO issue_tracker_bindings (project_id, tracker, scope, updated_at, additional_scopes) + VALUES ('other', 'linear', 'OPS', '2026-11-21', 'invalid') + `; + assert.deepStrictEqual(yield* read(), binding); + assert.strictEqual((yield* Effect.result(bindings.list()))._tag, "Failure"); }), ); }, From 76bb5ec81b0f14e7db1ae29200b38d275f0cdf77 Mon Sep 17 00:00:00 2001 From: Adamulek123 Date: Sun, 22 Nov 2026 00:11:00 +0100 Subject: [PATCH 076/139] perf(issues): read only link metadata when linking GitHub issues (#40595) Co-authored-by: Julius Marminge --- apps/server/src/issue/IssueService.ts | 19 ++++++++ .../src/mcp/toolkits/issues/handlers.test.ts | 1 + .../src/mcp/toolkits/issues/handlers.ts | 10 ++-- .../src/server/IssueTracker.ts | 6 +++ .../src/server/GitHubIssueTracker.test.ts | 25 ++++++++++ .../src/server/GitHubIssueTracker.ts | 10 ++++ .../src/server/issues.graphql | 10 ++++ .../src/server/issues.graphql.ts | 48 ++++++++++++++++++- 8 files changed, 123 insertions(+), 6 deletions(-) diff --git a/apps/server/src/issue/IssueService.ts b/apps/server/src/issue/IssueService.ts index 049de0d757a1c..9b9b050ab6ad0 100644 --- a/apps/server/src/issue/IssueService.ts +++ b/apps/server/src/issue/IssueService.ts @@ -42,6 +42,7 @@ import { type IssueTrackerApi, type StandaloneIssueTrackerApi, type TrackerIssueDetail, + type TrackerIssueLink, } from "@t3tools/source-control-core/server/IssueTracker"; import { parseUrl } from "@t3tools/shared/url"; @@ -148,6 +149,7 @@ export class IssueService extends Context.Service< { readonly list: (input: IssueListInput) => Effect.Effect; readonly detail: (input: IssueRef) => Effect.Effect; + readonly linkMetadata: (input: IssueRef) => Effect.Effect; readonly comments: ( input: IssueCommentsPageInput, ) => Effect.Effect; @@ -524,6 +526,22 @@ const make = Effect.gen(function* () { ), ); + const linkMetadata: IssueService["Service"]["linkMetadata"] = (input) => + requireProject(input).pipe( + Effect.flatMap((project) => { + const read = project.api.getIssueLink ?? project.api.getIssue; + return read({ + cwd: project.project.workspaceRoot, + host: project.host, + scope: project.scope, + key: input.key, + }).pipe( + Effect.map(({ title, url, displayKey }) => ({ title, url, displayKey })), + Effect.mapError(toIssueError("detail")), + ); + }), + ); + const comments: IssueService["Service"]["comments"] = (input) => requireProject(input).pipe( Effect.flatMap((project) => @@ -796,6 +814,7 @@ const make = Effect.gen(function* () { return IssueService.of({ list, detail: traced("detail", detail), + linkMetadata: traced("linkMetadata", linkMetadata), comments: traced("comments", comments), templates: traced("templates", templates), candidates: interactive(traced("candidates", candidates)), diff --git a/apps/server/src/mcp/toolkits/issues/handlers.test.ts b/apps/server/src/mcp/toolkits/issues/handlers.test.ts index 5736b685b829b..9867324f7fc23 100644 --- a/apps/server/src/mcp/toolkits/issues/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/issues/handlers.test.ts @@ -158,6 +158,7 @@ const makeHarness = Effect.fn("makeIssuesToolkitHarness")(function* ( issueLayer ?? Layer.mock(IssueService.IssueService)({ detail: () => Effect.succeed(detail), + linkMetadata: () => Effect.succeed(detail), projectScope: (projectId) => Effect.succeed({ projectId, diff --git a/apps/server/src/mcp/toolkits/issues/handlers.ts b/apps/server/src/mcp/toolkits/issues/handlers.ts index b45b3d3dbd875..c09dbc356d61f 100644 --- a/apps/server/src/mcp/toolkits/issues/handlers.ts +++ b/apps/server/src/mcp/toolkits/issues/handlers.ts @@ -269,20 +269,20 @@ const make = Effect.gen(function* () { link_issue: writesThread((input) => Effect.gen(function* () { const thread = yield* requireThread(input.threadId); - const target = yield* resolveTarget({ + const target: ResolvedTarget = yield* resolveTarget({ ...input, projectId: input.projectId ?? thread.projectId, }); // Reading the issue proves it exists and names it for the thread's row. - const detail = yield* readIssue(target); - const url = target.url ?? detail.url; + const issue = target.issue ?? (yield* issues.linkMetadata(refOf(target))); + const url = target.url ?? issue.url; const { alreadyLinked } = yield* threadIssues .link({ threadId: thread.id, ref: refOf(target), url, - displayKey: detail.displayKey, - title: detail.title, + displayKey: issue.displayKey, + title: issue.title, source: "agent", }) .pipe(Effect.catchCause(linkFailure)); diff --git a/packages/source-control-core/src/server/IssueTracker.ts b/packages/source-control-core/src/server/IssueTracker.ts index b5894ed806363..eecbde1ed2267 100644 --- a/packages/source-control-core/src/server/IssueTracker.ts +++ b/packages/source-control-core/src/server/IssueTracker.ts @@ -73,6 +73,7 @@ export interface IssueTarget extends IssueScopeTarget { /** An issue as the tracker sees it, before the service attaches project context. */ export type TrackerIssueSummary = Omit; +export type TrackerIssueLink = Pick; export interface TrackerIssuePage { readonly items: ReadonlyArray; @@ -134,6 +135,11 @@ export interface IssueTrackerApi { /** The issue with its first page of conversation, in one read where the tracker allows. */ readonly getIssue: (input: IssueTarget) => Effect.Effect; + /** Confirms an issue exists and names it for a thread link. */ + readonly getIssueLink?: ( + input: IssueTarget, + ) => Effect.Effect; + /** One page of older comments past a cursor `getIssue` or a previous page handed over. */ readonly getComments: ( input: IssueTarget & { readonly cursor: string }, diff --git a/packages/source-control-github/src/server/GitHubIssueTracker.test.ts b/packages/source-control-github/src/server/GitHubIssueTracker.test.ts index 3ddcd024f8b35..c04145758f7b1 100644 --- a/packages/source-control-github/src/server/GitHubIssueTracker.test.ts +++ b/packages/source-control-github/src/server/GitHubIssueTracker.test.ts @@ -226,6 +226,31 @@ const decodeBody = Schema.decodeUnknownSync( ); describe("GitHubIssueTracker", () => { + it.effect("reads only the fields needed to link a GitHub issue and rejects missing issues", () => + Effect.gen(function* () { + const requests: unknown[] = []; + const target = { cwd: "/w", host: "github.com", scope: "acme/web", key: "42" }; + const url = "https://github.com/acme/web/issues/42"; + const found = yield* tracker((input) => requests.push(input), { + issue: { number: 42, title: "Fixture issue", url }, + }); + expect(yield* found.getIssueLink(target)).toEqual({ + displayKey: "#42", + title: "Fixture issue", + url, + }); + + const missing = yield* tracker((input) => requests.push(input), { issue: null }); + expect(yield* Effect.flip(missing.getIssueLink(target))).toMatchObject({ + reason: "not-found", + }); + expect(requests).toEqual([ + { owner: "acme", name: "web", number: 42 }, + { owner: "acme", name: "web", number: 42 }, + ]); + }), + ); + it.effect("writes an issue lifecycle without mutating pull requests or foreign comments", () => Effect.gen(function* () { const writes: unknown[] = []; diff --git a/packages/source-control-github/src/server/GitHubIssueTracker.ts b/packages/source-control-github/src/server/GitHubIssueTracker.ts index bf1c20abae4e3..b2cb38ff4d413 100644 --- a/packages/source-control-github/src/server/GitHubIssueTracker.ts +++ b/packages/source-control-github/src/server/GitHubIssueTracker.ts @@ -337,6 +337,16 @@ export const make = Effect.gen(function* () { }; }), + getIssueLink: Effect.fn("GitHubIssueTracker.getIssueLink")(function* (input) { + const { owner, name, number } = yield* issue(input, "getIssue"); + const result = yield* client + .IssueLinkMetadata({ owner, name, number }) + .pipe(graphql(input.host, "getIssue")); + const found = result.repository?.issue; + if (found == null) return yield* notFound("getIssue"); + return { displayKey: `#${found.number}`, title: found.title, url: found.url }; + }), + getComments: (input) => issue(input, "getComments").pipe( Effect.flatMap(({ owner, name, number }) => diff --git a/packages/source-control-github/src/server/issues.graphql b/packages/source-control-github/src/server/issues.graphql index 42dc67a98a123..18c8cee3536a2 100644 --- a/packages/source-control-github/src/server/issues.graphql +++ b/packages/source-control-github/src/server/issues.graphql @@ -270,6 +270,16 @@ query IssueComments($owner: String!, $name: String!, $number: Int!, $cursor: Str } } +query IssueLinkMetadata($owner: String!, $name: String!, $number: Int!) { + repository(owner: $owner, name: $name) { + issue(number: $number) { + number + title + url + } + } +} + query IssueNodeId($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { issue(number: $number) { diff --git a/packages/source-control-github/src/server/issues.graphql.ts b/packages/source-control-github/src/server/issues.graphql.ts index d99defc174a5c..9d059396d26a0 100644 --- a/packages/source-control-github/src/server/issues.graphql.ts +++ b/packages/source-control-github/src/server/issues.graphql.ts @@ -666,6 +666,52 @@ export declare namespace IssueComments { export type Result = typeof IssueComments.result.Type } +/** An Issue is a place to discuss ideas, enhancements, tasks, and bugs for a project. */ +export const IssueLinkMetadataRepositoryIssueIssue = Schema.Struct({ + /** Identifies the issue number. */ + number: Shared.Int, + /** Identifies the issue title. */ + title: Schema.String, + /** The HTTP URL for this issue */ + url: Shared.URI +}) +export interface IssueLinkMetadataRepositoryIssueIssue extends Schema.Struct.Type {} + +/** A repository contains the content for a project. */ +export const IssueLinkMetadataRepositoryRepository = Schema.Struct({ + /** Returns a single issue from the current repository by number. */ + issue: Schema.NullOr(IssueLinkMetadataRepositoryIssueIssue) +}) +export interface IssueLinkMetadataRepositoryRepository extends Schema.Struct.Type {} + +/** `query IssueLinkMetadata` */ +export const IssueLinkMetadata = GraphQL.query("IssueLinkMetadata", { + document: { + variables: [ + { name: "owner", body: "String!" }, + { name: "name", body: "String!" }, + { name: "number", body: "Int!" } + ], + selections: [ + { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){issue(number:$", "number", "){number title url}}"] } + ], + fragments: [] + }, + variables: { + owner: Schema.String, + name: Schema.String, + number: Shared.Int + }, + result: Schema.Struct({ + /** Lookup a given repository by the owner and repository name. */ + repository: Schema.NullOr(IssueLinkMetadataRepositoryRepository) + }) +}) +export declare namespace IssueLinkMetadata { + export type Variables = typeof IssueLinkMetadata.variables.Type + export type Result = typeof IssueLinkMetadata.result.Type +} + /** An Issue is a place to discuss ideas, enhancements, tasks, and bugs for a project. */ export const IssueNodeIdRepositoryIssueIssue = Schema.Struct({ /** The Node ID of the Issue object */ @@ -1038,4 +1084,4 @@ export declare namespace IssueCollections { } /** Every operation in issues.graphql. */ -export const IssuesGraphQLGroup = GraphQLGroup.make(IssueSearch, IssueDetail, IssueComments, IssueNodeId, IssueCommentScope, IssueCandidates, IssueTemplates, IssueViewer, IssueCollections) +export const IssuesGraphQLGroup = GraphQLGroup.make(IssueSearch, IssueDetail, IssueComments, IssueLinkMetadata, IssueNodeId, IssueCommentScope, IssueCandidates, IssueTemplates, IssueViewer, IssueCollections) From 10586f9e31834e21212cfbd1d743f2cb704375d8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 15:13:34 -0800 Subject: [PATCH 077/139] feat: read feature flags from one T3CODE_FEATURE_FLAGS service (#40594) Co-authored-by: Claude Opus 5.5 --- apps/desktop/src/app/DesktopApp.ts | 27 ++++++ .../backend/DesktopBackendConfiguration.ts | 3 +- .../src/shell/DesktopShellEnvironment.ts | 8 +- apps/mobile/app.config.ts | 3 - .../features/settings/CloudVoiceSection.tsx | 4 +- apps/server/src/os-jank.test.ts | 82 ++++++++++--------- apps/server/src/os-jank.ts | 6 +- apps/server/src/server.ts | 2 + .../SourceControlProviderRegistry.ts | 15 ++-- .../src/sourceControl/builtInDrivers.ts | 19 ++++- .../sourceControl/sourceControlDefinitions.ts | 15 ++-- apps/server/src/ws.test.ts | 2 + apps/server/src/ws.ts | 6 ++ .../src/components/chat/SecretRequestCard.tsx | 4 +- .../CloudVoiceConfiguration.browser.test.tsx | 5 +- .../settings/CloudVoiceConfiguration.tsx | 5 +- .../components/settings/SecretSourceInput.tsx | 6 +- ...ngsSidebarNav.composition.browser.test.tsx | 11 +-- .../settings/SettingsSidebarNav.tsx | 10 ++- .../settings/settingsSearch.test.ts | 31 +++++-- .../src/components/settings/settingsSearch.ts | 39 +++++---- .../useAvailableSettingsSearchItems.ts | 11 +++ apps/web/src/env.ts | 4 - .../web/src/routes/_chat.settings.secrets.tsx | 20 +++-- apps/web/src/vite-env.d.ts | 1 - apps/web/vite.config.ts | 2 - docs/user/source-control.md | 6 +- evals/thread-titles/run.ts | 2 + .../src/sourceControlClients.test.ts | 7 -- packages/client-runtime/src/state/server.ts | 9 ++ packages/contracts/src/resourceTelemetry.ts | 2 +- packages/contracts/src/server.ts | 8 ++ packages/shared/package.json | 4 + packages/shared/src/FeatureFlags.test.ts | 31 +++++++ packages/shared/src/FeatureFlags.ts | 61 ++++++++++++++ .../source-control-core/src/server/driver.ts | 4 +- .../src/registry.ts | 67 +++++++-------- .../scripts/measure-pr-preview.ts | 2 + .../src/server/GitHubAppSignIn.test.ts | 13 ++- .../src/server/GitHubAppSignIn.ts | 11 +-- .../src/server/GitHubRest.test.ts | 6 +- 41 files changed, 388 insertions(+), 186 deletions(-) create mode 100644 packages/shared/src/FeatureFlags.test.ts create mode 100644 packages/shared/src/FeatureFlags.ts diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts index 0ccce648bba61..ba09871ee1c5a 100644 --- a/apps/desktop/src/app/DesktopApp.ts +++ b/apps/desktop/src/app/DesktopApp.ts @@ -4,6 +4,7 @@ import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; import * as NetService from "@t3tools/shared/Net"; import * as SecureRandom from "effect/crypto/SecureRandom"; @@ -173,6 +174,31 @@ const stopAllPoolInstances = Effect.fn("desktop.app.stopAllPoolInstances")( ); // Spawns the local backend as soon as the protocol, IPC, and legacy storage that every window needs exist. +/** + * The server reads T3CODE_FEATURE_FLAGS once at start, from the value cached at the last + * discovery. When the login shell now sets different flags, restart it so they apply. + */ +const restartOnFeatureFlagChange = Effect.fn("desktop.restartOnFeatureFlagChange")(function* ( + backend: DesktopBackendManager.DesktopBackendInstance, +) { + const state = yield* DesktopState.DesktopState; + const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment; + let startedWith = (yield* HostProcess.Environment).T3CODE_FEATURE_FLAGS; + yield* shellEnvironment.updates.pipe( + Stream.filter((snapshot) => snapshot.discovered), + Stream.runForEach( + Effect.fnUntraced(function* (snapshot) { + const flags = snapshot.environment.T3CODE_FEATURE_FLAGS ?? undefined; + if (flags === startedWith || (yield* Ref.get(state.quitting))) return; + startedWith = flags; + yield* logBootstrapInfo("restarting backend for changed T3CODE_FEATURE_FLAGS"); + yield* backend.stop(); + yield* backend.start; + }), + ), + ); +}); + const startLocalBackend = Effect.gen(function* () { const state = yield* DesktopState.DesktopState; const environment = yield* DesktopEnvironment.DesktopEnvironment; @@ -268,6 +294,7 @@ const startLocalBackend = Effect.gen(function* () { } yield* primaryBackend.start; yield* logBootstrapInfo("bootstrap backend start requested"); + yield* Effect.forkScoped(restartOnFeatureFlagChange(primaryBackend)); // The renderer asks for this token first; minting it at readiness saves a round trip. yield* Effect.forkScoped( (yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth).getBearerToken.pipe( diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts index 9c12690f31351..5474583be9976 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -89,8 +89,7 @@ const WSL_FORWARDED_ENV_NAMES = [ "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "T3CODE_TELEMETRY_ENABLED", - "T3CODE_GITHUB_APP_CLIENT_ID", - "T3CODE_TANSTACK_SOURCE", + "T3CODE_FEATURE_FLAGS", // Otherwise the WSL server keeps exporting to endpoints from the bootstrap. "T3CODE_OTEL_SDK_DISABLED", "OTEL_SDK_DISABLED", diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.ts index f9ab0d6c3a054..620fd8f561fa8 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts @@ -123,8 +123,7 @@ const LOGIN_SHELL_ENV_NAMES = [ "SSL_CERT_DIR", "NODE_EXTRA_CA_CERTS", "T3CODE_TELEMETRY_ENABLED", - "T3CODE_GITHUB_APP_CLIENT_ID", - "T3CODE_TANSTACK_SOURCE", + "T3CODE_FEATURE_FLAGS", "T3CODE_RELEASE_BASE_URL", "__MISE_DIFF", "JAVA_HOME", @@ -555,8 +554,7 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix "JAVA_HOME", "PNPM_HOME", "T3CODE_TELEMETRY_ENABLED", - "T3CODE_GITHUB_APP_CLIENT_ID", - "T3CODE_TANSTACK_SOURCE", + "T3CODE_FEATURE_FLAGS", "T3CODE_RELEASE_BASE_URL", ] as const) { if (!config.env[name] && shellEnvironment[name]) { @@ -663,6 +661,8 @@ const CACHED_ENV_NAMES = [ "SSL_CERT_DIR", "NODE_EXTRA_CA_CERTS", "T3CODE_TELEMETRY_ENABLED", + // The server reads its flags once at start, before discovery can finish. + "T3CODE_FEATURE_FLAGS", ] as const; /** @public */ diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index 464f7ab9929b0..a868851d5c9da 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -471,9 +471,6 @@ const config: ExpoConfig = { ], extra: { appVariant: APP_VARIANT, - secretsFeatureEnabled: ["1", "true"].includes( - process.env.T3CODE_FEATURE_SECRETS?.trim().toLowerCase() ?? "", - ), iosPersonalTeamBuild: isIosPersonalTeamBuild, relay: { url: repoEnv.T3CODE_RELAY_URL ?? null, diff --git a/apps/mobile/src/features/settings/CloudVoiceSection.tsx b/apps/mobile/src/features/settings/CloudVoiceSection.tsx index dceb42d86e457..3e782d2457fa3 100644 --- a/apps/mobile/src/features/settings/CloudVoiceSection.tsx +++ b/apps/mobile/src/features/settings/CloudVoiceSection.tsx @@ -2,6 +2,7 @@ import { T, useGT, useMessages } from "gt-react-native"; import { useAtomRefresh, useAtomValue } from "@effect/atom-react"; import { cloudSpeechDisclosure } from "@t3tools/shared/speechCopy"; import { setCloudSpeechKey } from "@t3tools/client-runtime/voice-input"; +import { hasFeatureFlag } from "@t3tools/client-runtime/state/server"; import { configuredSecretSources, secretRequestReference, @@ -20,7 +21,6 @@ import { type VoiceTranscriptionDestination, } from "@t3tools/contracts"; import * as Schema from "effect/Schema"; -import Constants from "expo-constants"; import { AsyncResult } from "effect/reactivity"; import { type ReactNode, useState } from "react"; import { ScrollView, TextInput, View } from "react-native"; @@ -199,7 +199,7 @@ function CloudChoices({ environment, active, onClose }: Props & { onClose: () => const [model, setModel] = useState(""); const [sourceId, setSourceId] = useState(null); const sources = - Constants.expoConfig?.extra?.secretsFeatureEnabled === true && + hasFeatureFlag(environment.serverConfig, "secretProviders") && environment.serverConfig?.secretReferences ? configuredSecretSources(environment.serverConfig.settings.secretProviders, messages) : []; diff --git a/apps/server/src/os-jank.test.ts b/apps/server/src/os-jank.test.ts index 857adb2c8e5c3..46b3b6b1e9936 100644 --- a/apps/server/src/os-jank.test.ts +++ b/apps/server/src/os-jank.test.ts @@ -149,44 +149,52 @@ effectIt.effect("keeps mise's PATH record with the login shell PATH", () => ), ); -effectIt.effect("hydrates a missing JAVA_HOME from the login shell and keeps an explicit one", () => - Effect.acquireUseRelease( - Effect.sync(() => - vi - .spyOn(NodeChildProcess, "execFileSync") - .mockReturnValue( - [ - "__T3CODE_ENV_PATH_START__", - "/opt/homebrew/bin", - "__T3CODE_ENV_PATH_END__", - "__T3CODE_ENV_JAVA_HOME_START__", - "/opt/homebrew/opt/openjdk@17", - "__T3CODE_ENV_JAVA_HOME_END__", - ].join("\n"), - ), +effectIt.effect( + "hydrates missing JAVA_HOME and feature flags from the login shell and keeps explicit ones", + () => + Effect.acquireUseRelease( + Effect.sync(() => + vi + .spyOn(NodeChildProcess, "execFileSync") + .mockReturnValue( + [ + "__T3CODE_ENV_PATH_START__", + "/opt/homebrew/bin", + "__T3CODE_ENV_PATH_END__", + "__T3CODE_ENV_JAVA_HOME_START__", + "/opt/homebrew/opt/openjdk@17", + "__T3CODE_ENV_JAVA_HOME_END__", + "__T3CODE_ENV_T3CODE_FEATURE_FLAGS_START__", + "tanstack_source", + "__T3CODE_ENV_T3CODE_FEATURE_FLAGS_END__", + ].join("\n"), + ), + ), + () => + Effect.gen(function* () { + const missing: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" }; + const explicit: NodeJS.ProcessEnv = { + SHELL: "/bin/zsh", + PATH: "/usr/bin", + JAVA_HOME: "/custom/jdk", + T3CODE_FEATURE_FLAGS: "", + }; + + for (const env of [missing, explicit]) { + yield* fixPath().pipe( + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService(HostProcess.Environment, env), + Effect.provide(NodeServices.layer), + ); + } + + assert.equal(missing.JAVA_HOME, "/opt/homebrew/opt/openjdk@17"); + assert.equal(explicit.JAVA_HOME, "/custom/jdk"); + assert.equal(missing.T3CODE_FEATURE_FLAGS, "tanstack_source"); + assert.equal(explicit.T3CODE_FEATURE_FLAGS, ""); + }), + (probe) => Effect.sync(() => probe.mockRestore()), ), - () => - Effect.gen(function* () { - const missing: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" }; - const explicit: NodeJS.ProcessEnv = { - SHELL: "/bin/zsh", - PATH: "/usr/bin", - JAVA_HOME: "/custom/jdk", - }; - - for (const env of [missing, explicit]) { - yield* fixPath().pipe( - Effect.provideService(HostProcess.Platform, "darwin"), - Effect.provideService(HostProcess.Environment, env), - Effect.provide(NodeServices.layer), - ); - } - - assert.equal(missing.JAVA_HOME, "/opt/homebrew/opt/openjdk@17"); - assert.equal(explicit.JAVA_HOME, "/custom/jdk"); - }), - (probe) => Effect.sync(() => probe.mockRestore()), - ), ); effectIt.effect("replaces a Path-spelled Windows PATH instead of adding a second key", () => diff --git a/apps/server/src/os-jank.ts b/apps/server/src/os-jank.ts index bc6528f91a5be..dc0c90a787123 100644 --- a/apps/server/src/os-jank.ts +++ b/apps/server/src/os-jank.ts @@ -32,7 +32,7 @@ function logPathHydrationWarning(message: string, error?: unknown): void { // __MISE_DIFF is mise's record of the PATH entries it added. It must travel // with the shell's PATH, or `mise x` can rebuild PATH behind a same-named // wrapper (`exec mise x claude -- claude`) that then re-runs itself forever. -const LOGIN_SHELL_ENV_NAMES = ["PATH", "__MISE_DIFF", "JAVA_HOME"] as const; +const LOGIN_SHELL_ENV_NAMES = ["PATH", "__MISE_DIFF", "JAVA_HOME", "T3CODE_FEATURE_FLAGS"] as const; const LOGIN_SHELL_TIMEOUT = Duration.seconds(5); const SLOW_LOGIN_SHELL_TIMEOUT_MS = 20_000; @@ -64,6 +64,10 @@ function applyLoginShellEnvironment( if (!env.JAVA_HOME && shellEnvironment.JAVA_HOME) { env.JAVA_HOME = shellEnvironment.JAVA_HOME; } + // A headless server (systemd, launchd) reads no profile, yet flags belong where users export them. + if (env.T3CODE_FEATURE_FLAGS === undefined && shellEnvironment.T3CODE_FEATURE_FLAGS) { + env.T3CODE_FEATURE_FLAGS = shellEnvironment.T3CODE_FEATURE_FLAGS; + } } function hydratePosixPath(env: NodeJS.ProcessEnv, platform: NodeJS.Platform): void { diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 720834730e99b..d06186beb1988 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -17,6 +17,7 @@ import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { EnvironmentHttpApi, type RepositoryIdentity } from "@t3tools/contracts"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Cause from "effect/Cause"; import * as Duration from "effect/Duration"; @@ -1408,6 +1409,7 @@ const layerMakeServer = Layer.unwrap( Layer.provide(VcsProcess.layer), Layer.provideMerge(AgentScopeLive.layer), Layer.provideMerge(layerPlatformServices), + Layer.provideMerge(FeatureFlags.layer), Layer.provide(Layer.succeed(HostProcess.InvokedAs, invokedAs)), ); }), diff --git a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts index c6f823d61f3c6..06616a914b1e9 100644 --- a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts +++ b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts @@ -75,16 +75,11 @@ function unsupportedProvider( // Binding context does not create a second provider-operation span. return SourceControlProvider.SourceControlProvider.of({ kind, - // Unknown hosts have no readable change requests; return none to avoid poll warnings on every refresh. - listChangeRequests: (input) => - kind === "unknown" - ? Effect.succeed([]) - : new SourceControlProviderError({ - provider: kind, - operation: "listChangeRequests", - cwd: input.cwd, - detail: `No ${kind} source control provider is registered.`, - }), + // Unknown hosts, and hosts whose forge a feature flag leaves out, have no readable change + // requests; return none to avoid poll warnings on every refresh. + listChangeRequests: Effect.fn("SourceControlProviderRegistry.unsupported.listChangeRequests")( + () => Effect.succeed([]), + ), getChangeRequest: (input) => new SourceControlProviderError({ provider: kind, diff --git a/apps/server/src/sourceControl/builtInDrivers.ts b/apps/server/src/sourceControl/builtInDrivers.ts index 0e994dcac4a7f..33aa77ffefd8f 100644 --- a/apps/server/src/sourceControl/builtInDrivers.ts +++ b/apps/server/src/sourceControl/builtInDrivers.ts @@ -3,6 +3,7 @@ import type { SourceControlDriverInstance, } from "@t3tools/source-control-core/server/driver"; import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -21,9 +22,21 @@ export class SourceControlDrivers extends Context.Service< ReadonlyArray >()("t3/sourceControl/builtInDrivers/SourceControlDrivers") {} -const make = Effect.forEach(BUILT_IN_SOURCE_CONTROL_DRIVER_LIST, (driver) => - driver.make.pipe(Effect.map((instance) => ({ driver, instance }))), -); +/** Drivers offered only while their feature flag is on. */ +const FLAGGED_DRIVERS: Readonly> = { + "tanstack-source": "tanstackSource", +}; + +const make = Effect.gen(function* () { + const flags = yield* FeatureFlags.FeatureFlags; + const drivers = BUILT_IN_SOURCE_CONTROL_DRIVER_LIST.filter((driver) => { + const flag = FLAGGED_DRIVERS[driver.kind]; + return flag === undefined || flags[flag]; + }); + return yield* Effect.forEach(drivers, (driver) => + driver.make.pipe(Effect.map((instance) => ({ driver, instance }))), + ); +}); export const layer = Layer.effect(SourceControlDrivers, make).pipe( Layer.provideMerge(ServerSourceControlHost.layer), diff --git a/apps/server/src/sourceControl/sourceControlDefinitions.ts b/apps/server/src/sourceControl/sourceControlDefinitions.ts index c6a770a897f02..6dff3fe3c6962 100644 --- a/apps/server/src/sourceControl/sourceControlDefinitions.ts +++ b/apps/server/src/sourceControl/sourceControlDefinitions.ts @@ -1,7 +1,7 @@ import * as AzureDevOpsDriver from "@t3tools/source-control-azure-devops/server/driver"; import * as BitbucketDriver from "@t3tools/source-control-bitbucket/server/driver"; import * as CursorOriginDriver from "@t3tools/source-control-cursor-origin/server/driver"; -import { makeBuiltInSourceControlDefinitions } from "@t3tools/source-control-definitions/registry"; +import { builtInSourceControlDefinitions } from "@t3tools/source-control-definitions/registry"; import * as ForgejoDriver from "@t3tools/source-control-forgejo/server/driver"; import * as GitCafeDriver from "@t3tools/source-control-gitcafe/server/driver"; import * as GitHubDriver from "@t3tools/source-control-github/server/driver"; @@ -9,26 +9,21 @@ import * as GitLabDriver from "@t3tools/source-control-gitlab/server/driver"; import * as TanStackSourceDriver from "@t3tools/source-control-tanstack-source/server/driver"; /** - * TanStack Source is in private beta, so its forge exists only on a server started with - * `T3CODE_TANSTACK_SOURCE=1`. Read once at load: the registry below is a module constant. + * In the shared registry's order, which is the order hosts are listed and probed in. Feature + * flags leave some out; see `builtInDrivers.ts`. */ -const tanStackSourceEnabled = process.env.T3CODE_TANSTACK_SOURCE?.trim() === "1"; - -/** In the shared registry's order, which is the order hosts are listed and probed in. */ export const BUILT_IN_SOURCE_CONTROL_DRIVER_LIST = [ GitHubDriver.driver, CursorOriginDriver.driver, GitLabDriver.driver, GitCafeDriver.driver, - ...(tanStackSourceEnabled ? [TanStackSourceDriver.driver] : []), + TanStackSourceDriver.driver, ForgejoDriver.driver, BitbucketDriver.driver, AzureDevOpsDriver.driver, ]; -export const sourceControlDefinitions = makeBuiltInSourceControlDefinitions({ - tanStackSource: tanStackSourceEnabled, -}); +export const sourceControlDefinitions = builtInSourceControlDefinitions; /** A host CLI command that merges or closes a change request, such as `gh pr merge`. */ export const isChangeRequestCloseCommand = (command: string) => diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index e629af899c172..02ca5170d7ffd 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -165,6 +165,7 @@ import * as SecretCheck from "./secrets/SecretCheck.ts"; import * as ServerConfigModule from "./config.ts"; import * as Keybindings from "./keybindings.ts"; import { USAGE_LIMITS_COMMAND } from "@t3tools/shared/usageLimits"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import * as ServerSettings from "./serverSettings.ts"; import * as ManagedPolicy from "./policy/ManagedPolicy.ts"; @@ -906,6 +907,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(TaskFolders.TaskFolders)({}), Layer.mock(WorkspaceFileSystem.WorkspaceFileSystem)({}), Layer.mock(WorktreeSetupTracker.WorktreeSetupTracker)({}), + FeatureFlags.layerTest(), ); const layerConfigSources = Layer.mergeAll( diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index afa030d4d7e9c..90c264f5408ca 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -1,6 +1,7 @@ import { GitCommandError, OrchestrationDispatchCommandError } from "@t3tools/contracts"; // @effect-diagnostics-next-line nodeBuiltinImport:off -- A synchronous digest inside the pure provider mapping. import * as NodeCrypto from "node:crypto"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Context from "effect/Context"; import * as NodeHttpServerRequest from "@effect/platform-node/NodeHttpServerRequest"; @@ -1533,6 +1534,7 @@ export const layerWsRpc = ( const checkpointDiffQuery = yield* CheckpointDiffQuery.CheckpointDiffQuery; const nativeChildWork = yield* NativeChildWorkQuery.NativeChildWorkQuery; const keybindings = yield* Keybindings.Keybindings; + const featureFlags = yield* FeatureFlags.FeatureFlags; const environmentTheme = yield* EnvironmentTheme.EnvironmentThemeService; const externalLauncher = yield* ExternalLauncher.ExternalLauncher; const remoteOpenTargets = yield* RemoteOpenTargets.RemoteOpenTargets; @@ -1920,6 +1922,10 @@ export const layerWsRpc = ( secretProviderSettings: true, secretReferences: true, secretRequestReferences: true, + featureFlags: { + secretProviders: featureFlags.secretProviders, + tanstackSource: featureFlags.tanstackSource, + }, ...Option.match(scratchWorkspaceRoot, { onNone: () => ({}), onSome: (root) => ({ scratchWorkspaceRoot: root }), diff --git a/apps/web/src/components/chat/SecretRequestCard.tsx b/apps/web/src/components/chat/SecretRequestCard.tsx index d337e7a1b9b54..25c1fe59d5e6b 100644 --- a/apps/web/src/components/chat/SecretRequestCard.tsx +++ b/apps/web/src/components/chat/SecretRequestCard.tsx @@ -24,6 +24,7 @@ import type { SecretProviderId, } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; +import { hasFeatureFlag } from "@t3tools/client-runtime/state/server"; import { T, useGT, useMessages, Var } from "gt-react"; import { CheckIcon, @@ -36,7 +37,6 @@ import { } from "lucide-react"; import { useId, useRef, useState, type FormEvent } from "react"; -import { isSecretsFeatureEnabled } from "../../env"; import { serverEnvironment } from "../../state/server"; import { useAtomCommand } from "../../state/use-atom-command"; import { Button } from "../ui/button"; @@ -80,7 +80,7 @@ const NO_SOURCES: ReadonlyArray = []; function useSecretRequestSources(environmentId: EnvironmentId) { const config = useAtomValue(serverEnvironment.configValueAtom(environmentId)); const messages = useMessages(); - return isSecretsFeatureEnabled + return hasFeatureFlag(config, "secretProviders") ? secretRequestSources(config, config?.settings.secretProviders ?? {}, messages) : NO_SOURCES; } diff --git a/apps/web/src/components/settings/CloudVoiceConfiguration.browser.test.tsx b/apps/web/src/components/settings/CloudVoiceConfiguration.browser.test.tsx index b5eddbcc10df8..f859695e3360d 100644 --- a/apps/web/src/components/settings/CloudVoiceConfiguration.browser.test.tsx +++ b/apps/web/src/components/settings/CloudVoiceConfiguration.browser.test.tsx @@ -11,10 +11,6 @@ import { VoiceSettingsPanel } from "./VoiceSettingsPanel"; import { SettingsScopeProvider } from "./SettingsScopeContext"; vi.mock(import("../../state/session"), { spy: true }); -vi.mock("../../env", async (original) => ({ - ...(await original()), - isSecretsFeatureEnabled: true, -})); vi.mock("../../state/environments", async (importOriginal) => ({ ...(await importOriginal()), useEnvironments: () => ({ @@ -24,6 +20,7 @@ vi.mock("../../state/environments", async (importOriginal) => ({ label: "Laptop", connection: { phase: "available" }, serverConfig: { + featureFlags: { secretProviders: true }, secretReferences: true, settings: { secretProviders: { diff --git a/apps/web/src/components/settings/CloudVoiceConfiguration.tsx b/apps/web/src/components/settings/CloudVoiceConfiguration.tsx index 90c93009d4634..0a992f4f93b61 100644 --- a/apps/web/src/components/settings/CloudVoiceConfiguration.tsx +++ b/apps/web/src/components/settings/CloudVoiceConfiguration.tsx @@ -1,6 +1,7 @@ import { useAtomRefresh, useAtomValue } from "@effect/atom-react"; import { cloudSpeechDisclosure } from "@t3tools/shared/speechCopy"; import type { PreparedConnection } from "@t3tools/client-runtime/connection"; +import { hasFeatureFlag } from "@t3tools/client-runtime/state/server"; import { configuredSecretSources, secretRequestReference, @@ -31,7 +32,6 @@ import type { HttpClient } from "effect/http"; import { Atom, AsyncResult } from "effect/reactivity"; import { useId, useState } from "react"; import { T, useGT, useMessages, Var } from "gt-react"; -import { isSecretsFeatureEnabled } from "../../env"; import { inEnvironmentSpeechRuntime, runEnvironmentSpeech, @@ -194,7 +194,8 @@ export function CloudVoiceConfiguration({ const saved = AsyncResult.isSuccess(presence) ? presence.value?.[provider] : undefined; const existing = environment.serverConfig?.settings?.cloudSpeechCredentials?.[provider]; const sources = - isSecretsFeatureEnabled && environment.serverConfig?.secretReferences + hasFeatureFlag(environment.serverConfig, "secretProviders") && + environment.serverConfig?.secretReferences ? configuredSecretSources(environment.serverConfig.settings?.secretProviders ?? {}, messages) : []; const reference = diff --git a/apps/web/src/components/settings/SecretSourceInput.tsx b/apps/web/src/components/settings/SecretSourceInput.tsx index 35b7218a63f03..53263c226d2f0 100644 --- a/apps/web/src/components/settings/SecretSourceInput.tsx +++ b/apps/web/src/components/settings/SecretSourceInput.tsx @@ -7,6 +7,7 @@ import { } from "@t3tools/contracts"; import { builtInSecretProviderDefinitions } from "@t3tools/secret-provider-definitions/registry"; import { invalidSecretReferenceText } from "@t3tools/client-runtime/secret-request"; +import { hasFeatureFlag } from "@t3tools/client-runtime/state/server"; import { useAtomValue } from "@effect/atom-react"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; @@ -14,7 +15,6 @@ import { useGT, useMessages } from "gt-react"; import { AlertTriangleIcon, CheckIcon, KeyRoundIcon, RefreshCwIcon, 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"; @@ -42,9 +42,9 @@ export function useSecretSources(environmentId: EnvironmentId): ReadonlyArray settings.secretProviders); const supported = useAtomValue( serverEnvironment.configValueAtom(environmentId), - (config) => config?.secretReferences === true, + (config) => hasFeatureFlag(config, "secretProviders") && config?.secretReferences === true, ); - if (!isSecretsFeatureEnabled || !supported) return NO_SECRET_SOURCES; + if (!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 })); diff --git a/apps/web/src/components/settings/SettingsSidebarNav.composition.browser.test.tsx b/apps/web/src/components/settings/SettingsSidebarNav.composition.browser.test.tsx index 3457bc2467820..338c4ff0fa111 100644 --- a/apps/web/src/components/settings/SettingsSidebarNav.composition.browser.test.tsx +++ b/apps/web/src/components/settings/SettingsSidebarNav.composition.browser.test.tsx @@ -4,12 +4,13 @@ import { page, userEvent } from "vite-plus/test/browser"; import { act, render } from "../../../test/render"; import { SidebarProvider } from "../ui/sidebar"; import { SettingsSidebarNav } from "./SettingsSidebarNav"; -import { SETTINGS_NAV_GROUPS, SETTINGS_SECTION_LABELS } from "./settingsSearch"; +import { settingsNavGroups, SETTINGS_SECTION_LABELS } from "./settingsSearch"; vi.mock("./useAvailableSettingsSearchItems", () => ({ useAvailableSettingsSearchItems: () => [ { id: "theme", title: "Theme", to: "/settings/appearance" }, ], + useHasSecretProvidersEnvironment: () => false, })); it("ignores composing keys in the search", async () => { @@ -76,9 +77,9 @@ it("moves Tab through every settings section", async () => { await using _screen = await renderNav(); await userEvent.click(page.getByRole("combobox", { name: "Search settings" })); - const sections = SETTINGS_NAV_GROUPS.flatMap((group) => group.paths).map( - (to) => SETTINGS_SECTION_LABELS[to], - ); + const sections = settingsNavGroups(false) + .flatMap((group) => group.paths) + .map((to) => SETTINGS_SECTION_LABELS[to]); const tabbed: string[] = []; for (let step = 0; step < sections.length; step += 1) { await userEvent.tab(); @@ -103,7 +104,7 @@ it.each([1280, 390])("names each group by a heading outside it at %ipx wide", as ); } const groups = page.getByRole("group").elements(); - expect(groups).toHaveLength(SETTINGS_NAV_GROUPS.length); + expect(groups).toHaveLength(settingsNavGroups(false).length); for (const group of groups) { const first = group.querySelector("[data-settings-section]")?.textContent; const heading = document.getElementById(group.getAttribute("aria-labelledby") ?? ""); diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsx index 794574d9505b4..10bc07c123dd8 100644 --- a/apps/web/src/components/settings/SettingsSidebarNav.tsx +++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx @@ -53,13 +53,16 @@ import { scrollToSettingsTarget } from "./settingsLayout"; import { searchSettings, revealSettingsSearchTarget, - SETTINGS_NAV_GROUPS, + settingsNavGroups, SETTINGS_NAV_LABELS, SETTINGS_SECTION_LABELS, type SettingsPath, type SettingsSearchItem, } from "./settingsSearch"; -import { useAvailableSettingsSearchItems } from "./useAvailableSettingsSearchItems"; +import { + useAvailableSettingsSearchItems, + useHasSecretProvidersEnvironment, +} from "./useAvailableSettingsSearchItems"; import { handleSettingsSectionKeyDown } from "./settingsSectionNavigation"; import { workspaceAreaProps } from "../../lib/workspaceFocus"; @@ -143,6 +146,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) { const [compactSearchOpen, setCompactSearchOpen] = useState(false); const [activeResultIndex, setActiveResultIndex] = useState(0); const searchableItems = useAvailableSettingsSearchItems(); + const navGroups = settingsNavGroups(useHasSecretProvidersEnvironment()); const results = searchSettings(query, searchableItems, m); const isSearching = query.trim().length > 0; const hasResults = results.length > 0; @@ -379,7 +383,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) { )}
    - {SETTINGS_NAV_GROUPS.map((group, index) => ( + {navGroups.map((group, index) => (
    ({ - ...(await importOriginal()), - isSecretsFeatureEnabled: false, -})); - const ITEMS: ReadonlyArray = [ { id: "word-wrap", @@ -76,9 +71,27 @@ describe("searchSettings", () => { } }); - it("hides the Secrets page from nav and search while the secrets feature is disabled", () => { - expect(SETTINGS_NAV_GROUPS.flatMap((group) => group.paths)).not.toContain("/settings/secrets"); - expect(searchSettings("1password").map((item) => item.to)).not.toContain("/settings/secrets"); + it("shows the Secrets page in nav and search only when an environment enables secret providers", () => { + const availability = { + hasCloudPublicConfig: false, + hasEnvironment: true, + hasProviderSettingsEnvironment: true, + canManageLocalBackend: false, + isWslSettingsRowVisible: false, + hasThreadAutoSettlement: false, + }; + for (const enabled of [false, true]) { + const navPaths = settingsNavGroups(enabled).flatMap((group) => group.paths); + const searchPaths = searchSettings( + "1password", + filterAvailableSettingsSearchItems({ + ...availability, + hasSecretProvidersEnvironment: enabled, + }), + ).map((item) => item.to); + expect(navPaths.includes("/settings/secrets")).toBe(enabled); + expect(searchPaths.includes("/settings/secrets")).toBe(enabled); + } }); it("finds where subagents and side chats open by any of its names", () => { diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index e891af3db0434..d91d6da4a42d7 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -1,5 +1,5 @@ import { HOSTED_APP_CHANNEL } from "~/branding"; -import { isElectron, isSecretsFeatureEnabled } from "~/env"; +import { isElectron } from "~/env"; import { isMacPlatform, isWindowsPlatform, normalizeSearchText } from "~/lib/utils"; import { STATIC_KEYBINDING_COMMANDS, type KeybindingCommand } from "@t3tools/contracts"; import type { EnvironmentId } from "@t3tools/contracts"; @@ -61,7 +61,7 @@ export interface SettingsSearchItem { readonly macOnly?: boolean; readonly windowsOnly?: boolean; readonly releaseChannelOnly?: boolean; - readonly secretsFeatureOnly?: boolean; + readonly secretProvidersOnly?: boolean; readonly cloudOnly?: boolean; readonly environmentOnly?: boolean; readonly providerSettingsOnly?: boolean; @@ -91,6 +91,7 @@ export interface SettingsSearchAvailability { /** An environment without a provider allow-list, which hides text generators. */ readonly hasTextGeneratorsEnvironment?: boolean; readonly hasPrimaryEnvironment?: boolean; + readonly hasSecretProvidersEnvironment?: boolean; } export const SETTINGS_SECTION_LABELS: Readonly> = { @@ -128,12 +129,14 @@ export const SETTINGS_NAV_LABELS: Readonly> = { "/settings/access": msg("Sharing & access", { $context: "settings navigation item" }), }; -/** Sidebar order. A group with a hidden heading is set apart on screen by space alone. */ -export const SETTINGS_NAV_GROUPS: ReadonlyArray<{ +type SettingsNavGroup = { readonly heading: string; readonly headingHidden?: true; readonly paths: ReadonlyArray; -}> = [ +}; + +/** Sidebar order. A group with a hidden heading is set apart on screen by space alone. */ +const ALL_SETTINGS_NAV_GROUPS: ReadonlyArray = [ { heading: msg("Preferences"), headingHidden: true, @@ -163,11 +166,7 @@ export const SETTINGS_NAV_GROUPS: ReadonlyArray<{ }, { heading: msg("Connections"), - paths: [ - "/settings/connections", - "/settings/access", - ...(isSecretsFeatureEnabled ? (["/settings/secrets"] as const) : []), - ], + paths: ["/settings/connections", "/settings/access", "/settings/secrets"], }, { heading: msg("More"), @@ -176,6 +175,18 @@ export const SETTINGS_NAV_GROUPS: ReadonlyArray<{ }, ]; +const SETTINGS_NAV_GROUPS_WITHOUT_SECRETS = ALL_SETTINGS_NAV_GROUPS.map((group) => ({ + ...group, + paths: group.paths.filter((path) => path !== "/settings/secrets"), +})); + +/** Sidebar groups; Secrets shows only when some environment's server enables secret providers. */ +export function settingsNavGroups(hasSecretProvidersEnvironment: boolean) { + return hasSecretProvidersEnvironment + ? ALL_SETTINGS_NAV_GROUPS + : SETTINGS_NAV_GROUPS_WITHOUT_SECRETS; +} + export function keybindingSearchAnchorId(command: Command) { return `keybinding-${command}` as const; } @@ -1463,7 +1474,7 @@ export const SETTINGS_SEARCH_ITEMS = [ title: msg("Secret providers"), to: "/settings/secrets", searchTerms: [msg("1password vault credentials api key")], - secretsFeatureOnly: true, + secretProvidersOnly: true, }, { id: "secret-providers-add", @@ -1471,7 +1482,7 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/secrets", targetId: "secret-providers", searchTerms: [msg("new 1password vault op cli account")], - secretsFeatureOnly: true, + secretProvidersOnly: true, }, { id: "archive", @@ -1644,7 +1655,8 @@ export function filterAvailableSettingsSearchItems( (!item.peerLinksOnly || availability.hasPeerLinkHost === true) && (!item.fastWorktreeCheckoutOnly || availability.hasFastWorktreeCheckoutEnvironment === true) && - (!item.textGeneratorsOnly || availability.hasTextGeneratorsEnvironment === true), + (!item.textGeneratorsOnly || availability.hasTextGeneratorsEnvironment === true) && + (!item.secretProvidersOnly || availability.hasSecretProvidersEnvironment === true), ); } @@ -1657,7 +1669,6 @@ export function settingsForThisPlatform( (item) => (isElectron || item.desktopOnly !== true) && (!item.releaseChannelOnly || isElectron || HOSTED_APP_CHANNEL !== null) && - (!item.secretsFeatureOnly || isSecretsFeatureEnabled) && (!item.macOnly || isMacPlatform(platform)) && (!item.windowsOnly || isWindowsPlatform(platform)), ); diff --git a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts b/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts index e6d947935bd94..beb5e3c85c52c 100644 --- a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts +++ b/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts @@ -1,4 +1,5 @@ import { useMessages } from "gt-react"; +import { hasFeatureFlag } from "@t3tools/client-runtime/state/server"; import { AuthEnvironmentMaintainScope } from "@t3tools/contracts"; import { usePrimaryCloudLinkState } from "~/cloud/cloudLinkState"; @@ -17,6 +18,14 @@ import { getThreadAutoSettlementSearchAvailability, } from "./settingsSearch"; +/** Any environment whose server enables secret providers; gates the Secrets page, nav and search. */ +export function useHasSecretProvidersEnvironment() { + const { environments } = useEnvironments(); + return environments.some((environment) => + hasFeatureFlag(environment.serverConfig, "secretProviders"), + ); +} + export function useAvailableSettingsSearchItems() { const { environments } = useEnvironments(); // Explicit booleans keep flags out of the filter cache so environment updates do not rebuild the list. @@ -42,6 +51,7 @@ export function useAvailableSettingsSearchItems() { environment.serverConfig !== null && environment.serverConfig.managedPolicy?.limits?.providers?.allowedDrivers === undefined, ) === true; + const hasSecretProvidersEnvironment = useHasSecretProvidersEnvironment(); const hasThreadAutoSettlement = getThreadAutoSettlementSearchAvailability(environments).eligibleEnvironmentIds.length > 0; const primaryEnvironmentId = usePrimaryEnvironmentId(); @@ -75,5 +85,6 @@ export function useAvailableSettingsSearchItems() { hasFastWorktreeCheckoutEnvironment, hasTextGeneratorsEnvironment, hasPrimaryEnvironment: primaryEnvironmentId !== null, + hasSecretProvidersEnvironment, }); } diff --git a/apps/web/src/env.ts b/apps/web/src/env.ts index a0a28c5d7fd60..be2a563d736bd 100644 --- a/apps/web/src/env.ts +++ b/apps/web/src/env.ts @@ -1,6 +1,2 @@ // Preload installs desktopBridge before web code runs, so module-load detection is reliable. export const isElectron = typeof window !== "undefined" && window.desktopBridge !== undefined; - -export const isSecretsFeatureEnabled = ["1", "true"].includes( - import.meta.env.T3CODE_FEATURE_SECRETS?.trim().toLowerCase() ?? "", -); diff --git a/apps/web/src/routes/_chat.settings.secrets.tsx b/apps/web/src/routes/_chat.settings.secrets.tsx index d97e00fda19f7..e0031f4aeaf9a 100644 --- a/apps/web/src/routes/_chat.settings.secrets.tsx +++ b/apps/web/src/routes/_chat.settings.secrets.tsx @@ -1,11 +1,19 @@ -import { createFileRoute, redirect } from "@tanstack/react-router"; +import { createFileRoute, Navigate } from "@tanstack/react-router"; import { SecretsSettingsPanel } from "../components/settings/SecretsSettings"; -import { isSecretsFeatureEnabled } from "../env"; +import { useHasSecretProvidersEnvironment } from "../components/settings/useAvailableSettingsSearchItems"; +import { useEnvironments } from "../state/environments"; export const Route = createFileRoute("/_chat/settings/secrets")({ - beforeLoad: () => { - if (!isSecretsFeatureEnabled) throw redirect({ to: "/settings/general", replace: true }); - }, - component: SecretsSettingsPanel, + component: SecretsSettingsRoute, }); + +function SecretsSettingsRoute() { + const enabled = useHasSecretProvidersEnvironment(); + // Only redirect once every environment reported flags; one may enable them after another loads. + const { isReady, environments } = useEnvironments(); + const allReported = + isReady && environments.every((environment) => environment.serverConfig !== null); + if (!enabled && allReported) return ; + return ; +} diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.ts index 63f7cca9cbfc6..307b9c5d8284d 100644 --- a/apps/web/src/vite-env.d.ts +++ b/apps/web/src/vite-env.d.ts @@ -15,7 +15,6 @@ interface ImportMetaEnv { readonly VITE_RELAY_OTLP_TRACES_DATASET: string; readonly VITE_RELAY_OTLP_TRACES_TOKEN: string; readonly T3CODE_DESKTOP_UPDATE_REPOSITORY: string; - readonly T3CODE_FEATURE_SECRETS: string; readonly APP_VERSION: string; } diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 073fca7943d3e..005e828202bda 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -50,7 +50,6 @@ const configuredDesktopUpdateRepository = process.env.T3CODE_DESKTOP_UPDATE_REPOSITORY?.trim() || process.env.GITHUB_REPOSITORY?.trim() || ""; -const configuredFeatureSecrets = process.env.T3CODE_FEATURE_SECRETS?.trim() || ""; const configuredHostedAppUrl = (() => { const explicitHostedAppUrl = process.env.VITE_HOSTED_APP_URL?.trim(); if (explicitHostedAppUrl) { @@ -370,7 +369,6 @@ export default defineConfig(({ command }) => { "import.meta.env.T3CODE_DESKTOP_UPDATE_REPOSITORY": JSON.stringify( configuredDesktopUpdateRepository, ), - "import.meta.env.T3CODE_FEATURE_SECRETS": JSON.stringify(configuredFeatureSecrets), "import.meta.env.VITE_RELEASE_CHANNEL": JSON.stringify(configuredReleaseChannel), "import.meta.env.APP_VERSION": JSON.stringify(configuredAppVersion), }, diff --git a/docs/user/source-control.md b/docs/user/source-control.md index cb8d252b9ab37..fa193bf0e87a8 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -146,8 +146,10 @@ Merging a stack lands it through GitCafe, and updating a branch restacks the lay ### TanStack Source -TanStack Source is in private beta, so the server shows it only when started with -`T3CODE_TANSTACK_SOURCE=1` in its environment. Install its CLI and sign in: +TanStack Source is in private beta, so the server shows it only when its environment turns the flag +on: `export T3CODE_FEATURE_FLAGS=tanstack_source` in your shell profile, then restart T3 Code. Separate +several flags with commas. A value already set in the server's own environment, such as a service +definition, is used instead of the profile. Install its CLI and sign in: ```sh curl -fsSL https://source.tanstack.com/install | sh diff --git a/evals/thread-titles/run.ts b/evals/thread-titles/run.ts index d53571698b021..5c77f68752485 100644 --- a/evals/thread-titles/run.ts +++ b/evals/thread-titles/run.ts @@ -6,6 +6,7 @@ import * as FetchHttpClient from "effect/http/FetchHttpClient"; import * as NodePlatformCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { CodexSettings, ProviderInstanceId } from "@t3tools/contracts"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Duration from "effect/Duration"; @@ -153,6 +154,7 @@ await Effect.runPromise( ProcessRunner.layer, SourceControlProviderRegistry.layer.pipe( Layer.provide(SourceControlBuiltInDrivers.layer), + Layer.provide(FeatureFlags.layer), Layer.provide(ServerSettings.layerTest()), Layer.provide(VcsDriverRegistry.layer.pipe(Layer.provide(VcsProjectConfig.layer))), Layer.provide(GitVcsDriver.layer), diff --git a/packages/client-runtime/src/sourceControlClients.test.ts b/packages/client-runtime/src/sourceControlClients.test.ts index 684b26ddf5e36..1f2cbfbc3a4d7 100644 --- a/packages/client-runtime/src/sourceControlClients.test.ts +++ b/packages/client-runtime/src/sourceControlClients.test.ts @@ -1,5 +1,4 @@ import { ProjectId, SourceControlProviderKind } from "@t3tools/contracts"; -import { makeBuiltInSourceControlDefinitions } from "@t3tools/source-control-definitions/registry"; import { describe, expect, it } from "vite-plus/test"; import { appSignInTargetForRemote, sourceControlClients } from "./sourceControlClients.ts"; @@ -50,12 +49,6 @@ describe("sourceControlClients.parseChangeRequestUrl", () => { expect(sourceControlClients.parseChangeRequestUrl(url)?.link.repositoryUrl).toBe( "https://source.tanstack.com/@TanStack/router", ); - // A server without the beta reads no TanStack Source host at all. - const without = makeBuiltInSourceControlDefinitions({ tanStackSource: false }); - expect(without.find(SourceControlProviderKind.make("tanstack-source"))).toBeUndefined(); - expect(without.recognizeRemote("https://source.tanstack.com/@TanStack/router.git")?.kind).toBe( - "unknown", - ); }); it("reads a Cursor Origin pull request under Origin's git host, not as GitHub's /pull/", () => { diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts index 3179f0c149e4b..222c12e6ba3e3 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -12,6 +12,7 @@ import { type ProviderInstanceId, type ServerConfig, type ServerConfigStreamEvent, + type ServerFeatureFlags, type ServerLifecycleWelcomePayload, type ServerLifecycleStreamReadyEvent, type ServerProviderWorkspaceSnapshot, @@ -832,6 +833,14 @@ function serverWelcomeStateChanges(environmentId: EnvironmentId) { ); } +/** Whether an environment's server turned on a feature flag; unset flags and unloaded configs are off. */ +export function hasFeatureFlag( + config: Pick | null | undefined, + flag: keyof ServerFeatureFlags, +): boolean { + return config?.featureFlags?.[flag] === true; +} + export function resolveServerConfigValue( projection: ServerConfigProjection | null, initialConfig: ServerConfig | null, diff --git a/packages/contracts/src/resourceTelemetry.ts b/packages/contracts/src/resourceTelemetry.ts index f3800089f5c20..24ac9d1bf3874 100644 --- a/packages/contracts/src/resourceTelemetry.ts +++ b/packages/contracts/src/resourceTelemetry.ts @@ -320,7 +320,7 @@ export const ShellEnvironmentPatch = Schema.Struct({ SSL_CERT_DIR: Schema.optionalKey(Schema.NullOr(Schema.String)), NODE_EXTRA_CA_CERTS: Schema.optionalKey(Schema.NullOr(Schema.String)), T3CODE_TELEMETRY_ENABLED: Schema.optionalKey(Schema.NullOr(Schema.String)), - T3CODE_GITHUB_APP_CLIENT_ID: Schema.optionalKey(Schema.NullOr(Schema.String)), + T3CODE_FEATURE_FLAGS: Schema.optionalKey(Schema.NullOr(Schema.String)), T3CODE_RELEASE_BASE_URL: Schema.optionalKey(Schema.NullOr(Schema.String)), __MISE_DIFF: Schema.optionalKey(Schema.NullOr(Schema.String)), JAVA_HOME: Schema.optionalKey(Schema.NullOr(Schema.String)), diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index afd870ef97cc7..1e70426001495 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -700,6 +700,13 @@ export const ServerEventLoopStall = Schema.Struct({ }); export type ServerEventLoopStall = typeof ServerEventLoopStall.Type; +/** The boolean `T3CODE_FEATURE_FLAGS` a server started with. Unset flags are off. */ +export const ServerFeatureFlags = Schema.Struct({ + secretProviders: Schema.optionalKey(Schema.Boolean), + tanstackSource: Schema.optionalKey(Schema.Boolean), +}); +export type ServerFeatureFlags = typeof ServerFeatureFlags.Type; + export const ServerConfig = Schema.Struct({ environment: ExecutionEnvironmentDescriptor, auth: ServerAuthDescriptor, @@ -737,6 +744,7 @@ export const ServerConfig = Schema.Struct({ threadSnapshotPagination: Schema.optionalKey(Schema.Boolean), threadFind: Schema.optionalKey(Schema.Boolean), threadFindProgressive: Schema.optionalKey(Schema.Boolean), + featureFlags: Schema.optionalKey(ServerFeatureFlags), /** 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. */ diff --git a/packages/shared/package.json b/packages/shared/package.json index e0529dbbdefa8..daa396dd07043 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -371,6 +371,10 @@ "types": "./src/managedPolicyFile.ts", "import": "./src/managedPolicyFile.ts" }, + "./FeatureFlags": { + "types": "./src/FeatureFlags.ts", + "import": "./src/FeatureFlags.ts" + }, "./HostProcess": { "types": "./src/HostProcess.ts", "import": "./src/HostProcess.ts" diff --git a/packages/shared/src/FeatureFlags.test.ts b/packages/shared/src/FeatureFlags.test.ts new file mode 100644 index 0000000000000..7a5962131e35c --- /dev/null +++ b/packages/shared/src/FeatureFlags.test.ts @@ -0,0 +1,31 @@ +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import * as FeatureFlags from "./FeatureFlags.ts"; + +it.effect("resolves T3CODE_FEATURE_FLAGS lists", () => + Effect.gen(function* () { + const cases: ReadonlyArray< + readonly [string | undefined, Partial] + > = [ + [undefined, {}], + [" tanstack_source , secret_providers=1 ", { tanstackSource: true, secretProviders: true }], + [ + "tanstack_source=0,github_app_client_id=Iv23=x", + { githubAppClientId: Option.some("Iv23=x") }, + ], + ["tanstack_source,typo_flag", { tanstackSource: true }], + // One bad value turns every flag off rather than failing startup. + ["tanstack_source,secret_providers=maybe", {}], + ]; + for (const [list, expected] of cases) { + assert.deepStrictEqual(yield* FeatureFlags.resolve(list), { + secretProviders: false, + tanstackSource: false, + githubAppClientId: Option.none(), + ...expected, + }); + } + }), +); diff --git a/packages/shared/src/FeatureFlags.ts b/packages/shared/src/FeatureFlags.ts new file mode 100644 index 0000000000000..7cc13e3420a48 --- /dev/null +++ b/packages/shared/src/FeatureFlags.ts @@ -0,0 +1,61 @@ +import * as Config from "effect/Config"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as HostProcess from "./HostProcess.ts"; + +/** + * One comma-separated list, such as `tanstack_source,github_app_client_id=Iv23…`. A bare name + * turns a flag on. Read once when the server starts; changing it takes a restart. + */ +const VARIABLE = "T3CODE_FEATURE_FLAGS"; + +const config = Config.all({ + secretProviders: Config.Boolean("secret_providers").pipe(Config.withDefault(false)), + tanstackSource: Config.Boolean("tanstack_source").pipe(Config.withDefault(false)), + /** The public client ID of the T3 Code for GitHub app; unset turns its sign-in off. */ + githubAppClientId: Config.option(Config.String("github_app_client_id")), +}); + +export type FeatureFlagValues = Config.Success; + +export class FeatureFlags extends Context.Service()( + "@t3tools/shared/FeatureFlags", +) {} + +/** The `name=value` pairs of a flags list, with a bare name read as `true`. */ +function parseList(list: string | undefined): Record { + const record: Record = {}; + for (const entry of (list ?? "").split(",")) { + const separator = entry.indexOf("="); + const name = (separator === -1 ? entry : entry.slice(0, separator)).trim(); + if (name === "") continue; + record[name] = separator === -1 ? "true" : entry.slice(separator + 1).trim(); + } + return record; +} + +const parse = (record: Record) => config.parse(ConfigProvider.fromUnknown(record)); + +export const resolve = Effect.fn("FeatureFlags.resolve")(function* (list: string | undefined) { + return yield* parse(parseList(list)).pipe( + Effect.catch((error) => + Effect.logWarning(`Ignoring invalid ${VARIABLE}; every flag is off.`, error).pipe( + Effect.andThen(parse({})), + ), + ), + ); +}); + +export const layer = Layer.effect( + FeatureFlags, + Effect.flatMap(HostProcess.Environment, (env) => resolve(env[VARIABLE])), +); + +export const layerTest = (values: Partial = {}) => + Layer.effect( + FeatureFlags, + Effect.map(resolve(undefined), (defaults) => ({ ...defaults, ...values })), + ); diff --git a/packages/source-control-core/src/server/driver.ts b/packages/source-control-core/src/server/driver.ts index 7f86d0fff3b9e..fcf737fe2181d 100644 --- a/packages/source-control-core/src/server/driver.ts +++ b/packages/source-control-core/src/server/driver.ts @@ -11,6 +11,7 @@ import type * as FileSystem from "effect/FileSystem"; import type { HttpClient, HttpClientError, HttpClientResponse } from "effect/http"; import * as Layer from "effect/Layer"; import type * as Scope from "effect/Scope"; +import type * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import type { SourceControlDefinition } from "../shared/definition.ts"; @@ -80,7 +81,8 @@ export type SourceControlDriverServices = | SourceControlRateLimit.SourceControlRateLimit | HttpClient.HttpClient | FileSystem.FileSystem - | Digest.Digest; + | Digest.Digest + | FeatureFlags.FeatureFlags; export interface SourceControlDriver { readonly kind: SourceControlProviderKind; diff --git a/packages/source-control-definitions/src/registry.ts b/packages/source-control-definitions/src/registry.ts index 46bc9c5b0abd4..90f14961c0d57 100644 --- a/packages/source-control-definitions/src/registry.ts +++ b/packages/source-control-definitions/src/registry.ts @@ -13,42 +13,35 @@ export { canonicalizePullRequestUrl as canonicalizeGitCafePullRequestUrl } from /** * GitHub comes first as the client default for unknown hosts. GitCafe, TanStack Source and Origin * claim URLs first: GitHub and Forgejo accept the same routes on any hostname. TanStack Source is a - * private beta a server may leave out; clients always know it, for a server that has it. + * private beta: every reader knows its URLs, and only a server with its flag on offers the forge. */ -export function makeBuiltInSourceControlDefinitions(options: { readonly tanStackSource: boolean }) { - const tanStackSource = options.tanStackSource ? [TanStackSource.definition] : []; - return makeSourceControlDefinitionRegistry( - [ - GitHub.definition, - CursorOrigin.definition, - GitLab.definition, - GitCafe.definition, - ...tanStackSource, - Forgejo.definition, - Bitbucket.definition, - AzureDevOps.definition, +export const builtInSourceControlDefinitions = makeSourceControlDefinitionRegistry( + [ + GitHub.definition, + CursorOrigin.definition, + GitLab.definition, + GitCafe.definition, + TanStackSource.definition, + Forgejo.definition, + Bitbucket.definition, + AzureDevOps.definition, + ], + { + claimChangeRequestUrlsFirst: [ + GitCafe.definition.kind, + TanStackSource.definition.kind, + CursorOrigin.definition.kind, + AzureDevOps.definition.kind, ], - { - claimChangeRequestUrlsFirst: [ - GitCafe.definition.kind, - ...tanStackSource.map((definition) => definition.kind), - CursorOrigin.definition.kind, - AzureDevOps.definition.kind, - ], - recognizeRemotesIn: [ - GitCafe.definition.kind, - ...tanStackSource.map((definition) => definition.kind), - CursorOrigin.definition.kind, - Forgejo.definition.kind, - GitHub.definition.kind, - GitLab.definition.kind, - AzureDevOps.definition.kind, - Bitbucket.definition.kind, - ], - }, - ); -} - -export const builtInSourceControlDefinitions = makeBuiltInSourceControlDefinitions({ - tanStackSource: true, -}); + recognizeRemotesIn: [ + GitCafe.definition.kind, + TanStackSource.definition.kind, + CursorOrigin.definition.kind, + Forgejo.definition.kind, + GitHub.definition.kind, + GitLab.definition.kind, + AzureDevOps.definition.kind, + Bitbucket.definition.kind, + ], + }, +); diff --git a/packages/source-control-github/scripts/measure-pr-preview.ts b/packages/source-control-github/scripts/measure-pr-preview.ts index 5047dcb281b1e..551245c5600ee 100644 --- a/packages/source-control-github/scripts/measure-pr-preview.ts +++ b/packages/source-control-github/scripts/measure-pr-preview.ts @@ -21,6 +21,7 @@ import * as GitHubAppAccess from "../src/server/GitHubAppAccess.ts"; import * as GitHubPullRequestApi from "../src/server/GitHubPullRequestApi.ts"; import * as GitHubPullRequestProvider from "../src/server/GitHubPullRequestProvider.ts"; import * as GitHubRest from "../src/server/GitHubRest.ts"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; const repeatsFlag = process.argv.find((arg) => arg.startsWith("--repeats=")); const repeats = repeatsFlag === undefined ? 1 : Number(repeatsFlag.slice("--repeats=".length)); @@ -119,6 +120,7 @@ const services = GitHubPullRequestApi.layer.pipe( Layer.provideMerge(SourceControlRateLimit.layer), Layer.provideMerge(measuredHttp), Layer.provideMerge(sourceControlHost), + Layer.provideMerge(FeatureFlags.layer), ); const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); diff --git a/packages/source-control-github/src/server/GitHubAppSignIn.test.ts b/packages/source-control-github/src/server/GitHubAppSignIn.test.ts index 1d8652f06495f..f212386f61942 100644 --- a/packages/source-control-github/src/server/GitHubAppSignIn.test.ts +++ b/packages/source-control-github/src/server/GitHubAppSignIn.test.ts @@ -15,6 +15,7 @@ import { DEFAULT_SERVER_SETTINGS, ServerSettingsError } from "@t3tools/contracts import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit"; import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings"; import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost"; @@ -54,6 +55,8 @@ function harness(options: { readonly settingsWritesFail?: boolean; /** Holds a request open until it completes, to interleave other work with it. */ readonly gate?: (sent: Sent) => Effect.Effect; + /** Defaults to a configured app; null runs without one. */ + readonly clientId?: string | null; }) { const requests: Array = []; const http = HttpClient.make((request) => { @@ -114,6 +117,13 @@ function harness(options: { Layer.provideMerge(SourceControlRateLimit.layer), Layer.provideMerge(options.settingsWritesFail === true ? failingWrites : host), Layer.provide(NodeCrypto.layer), + Layer.provide( + FeatureFlags.layerTest({ + githubAppClientId: Option.fromNullishOr( + options.clientId === undefined ? "Iv-test-client" : options.clientId, + ), + }), + ), Layer.provide(FileSystem.layerNoop({})), Layer.provide(Layer.succeed(HttpClient.HttpClient, http)), ); @@ -157,7 +167,6 @@ const installedOn = (sent: Sent): Reply => beforeEach(() => { for (const name of ["GH_TOKEN", "GITHUB_TOKEN"]) vi.stubEnv(name, ""); - vi.stubEnv(GitHubAppSignIn.CLIENT_ID_VARIABLE, "Iv-test-client"); }); afterEach(() => { vi.unstubAllEnvs(); @@ -267,8 +276,8 @@ describe("GitHubAppSignIn", () => { }); it.effect("does nothing with the app when the server has no client ID", () => { - vi.stubEnv(GitHubAppSignIn.CLIENT_ID_VARIABLE, ""); const { layer, requests } = harness({ + clientId: null, signIns: { "github.com": session() }, handle: () => ({ body: { login: "octocat" } }), }); diff --git a/packages/source-control-github/src/server/GitHubAppSignIn.ts b/packages/source-control-github/src/server/GitHubAppSignIn.ts index 28bde65ed84a8..843e14ce00687 100644 --- a/packages/source-control-github/src/server/GitHubAppSignIn.ts +++ b/packages/source-control-github/src/server/GitHubAppSignIn.ts @@ -19,16 +19,10 @@ import * as Schema from "effect/Schema"; import * as Schedule from "effect/Schedule"; import * as Semaphore from "effect/Semaphore"; import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; -import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import * as GitHubClient from "../shared/definition.ts"; -/** - * The public client ID of the T3 Code for GitHub app, which the device flow needs (no secret). - * Unset turns the app sign-in off: no app tokens, no sign-in, nothing for clients to show. - */ -export const CLIENT_ID_VARIABLE = "T3CODE_GITHUB_APP_CLIENT_ID"; - const KIND = SourceControlProviderKind.make("github"); const REQUEST_TIMEOUT = Duration.seconds(15); // Refresh ahead of expiry so a token never lapses between the check and a long request. @@ -107,7 +101,8 @@ const signInError = (host: string, reason: SourceControlSignInFailure, detail: s export const make = Effect.gen(function* () { const sourceControlHost = yield* SourceControlHost.SourceControlHost; const httpClient = yield* HttpClient.HttpClient; - const clientId = (yield* HostProcess.Environment)[CLIENT_ID_VARIABLE]?.trim() ?? ""; + // Unset turns the app sign-in off: no app tokens, no sign-in, nothing for clients to show. + const clientId = Option.getOrElse((yield* FeatureFlags.FeatureFlags).githubAppClientId, () => ""); const enabled = clientId !== ""; const scope = yield* Effect.scope; const refreshLock = yield* Semaphore.make(1); diff --git a/packages/source-control-github/src/server/GitHubRest.test.ts b/packages/source-control-github/src/server/GitHubRest.test.ts index 460bfbc16d82c..9d82bee19752c 100644 --- a/packages/source-control-github/src/server/GitHubRest.test.ts +++ b/packages/source-control-github/src/server/GitHubRest.test.ts @@ -8,6 +8,7 @@ import * as NodeFSP from "node:fs/promises"; import * as NodeOS from "node:os"; // @effect-diagnostics-next-line nodeBuiltinImport:off -- Keep the native socket path within the temporary directory. import * as NodePath from "node:path"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -360,7 +361,10 @@ describe("GitHubRest", () => { const media = yield* instance.fetchMedia!({ url: mediaUrl, headers: {} }); expect(media?.status).toBe(401); expect(directRequests).toEqual([mediaUrl]); - }).pipe(Effect.provide(layer), Effect.provideService(HostProcess.Environment, {})); + }).pipe( + Effect.provide(layer.pipe(Layer.provideMerge(FeatureFlags.layerTest()))), + Effect.provideService(HostProcess.Environment, {}), + ); }), ); From 63fa4c892eb89bb4b8fe43b6cc9d02999980d208 Mon Sep 17 00:00:00 2001 From: Navid Nadali Date: Sat, 21 Nov 2026 23:33:37 +0000 Subject: [PATCH 078/139] fix(mcp): a child's async question no longer keeps its parent polling (#40604) Co-authored-by: Julius Marminge --- .../src/mcp/OrchestratorMcpService.test.ts | 22 +++++++++++++++---- apps/server/src/mcp/OrchestratorMcpService.ts | 5 ++++- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index 2dad1fe68ee6d..4a5935d427879 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -617,7 +617,7 @@ describe("OrchestratorMcpService", () => { const childThreadId = ThreadId.make("thread:mcp-next-child"); const taskId = NodeId.make("node:mcp-next-task"); let finished = false; - let pendingRequest = false; + let pendingRequest: "live" | "message" | null = null; const parentProjection = () => ({ thread: { id: parentThreadId }, @@ -652,7 +652,16 @@ describe("OrchestratorMcpService", () => { subagents: [], providerThreads: [], providerTurns: [], - runtimeRequests: pendingRequest ? [{ status: "pending" }] : [], + runtimeRequests: + pendingRequest === null + ? [] + : [ + { + kind: "user_input", + status: "pending", + responseCapability: { type: pendingRequest }, + }, + ], nodes: [], turnItems: [], }) as unknown as OrchestrationV2ThreadProjection; @@ -705,11 +714,16 @@ describe("OrchestratorMcpService", () => { assert.equal(waiting.next, ORCHESTRATOR_MCP_RUNNING_TASK_NEXT); // A child waiting on a question or approval needs an answer, not a wake. - pendingRequest = true; + pendingRequest = "live"; const asking = yield* service.waitForThread(scope, { threadId: childThreadId }); assert.isTrue(asking.timedOut); assert.notProperty(asking, "next"); - pendingRequest = false; + + // A question answered by message does not stop the child. + pendingRequest = "message"; + const working = yield* service.waitForThread(scope, { threadId: childThreadId }); + assert.equal(working.next, ORCHESTRATOR_MCP_RUNNING_TASK_NEXT); + pendingRequest = null; finished = true; const completed = yield* service.taskStatus(scope, taskId); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index e8046bdd3c9c8..5f0c95a55ffee 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -3734,7 +3734,10 @@ const make = Effect.gen(function* () { .pipe(Effect.mapError(threadManagementFailure))).runtimeRequests : []; const wakesCaller = - ownedTask && !childRequests.some((request) => request.status === "pending"); + ownedTask && + !childRequests.some( + (request) => request.status === "pending" && request.responseCapability.type === "live", + ); return { threadId: input.threadId, runId: result.run?.id ?? null, From 2ea1c51f188bd3ac684e2aa1cfd0d05c9ca43d8c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 16:10:21 -0800 Subject: [PATCH 079/139] fix(acp): a late session update no longer marks a stopped thread active (#40629) --- .../server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts | 2 ++ packages/provider-acp/src/server/adapter.ts | 4 ++++ 2 files changed, 6 insertions(+) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index d79257944c8e9..348c2f38b0190 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -11857,6 +11857,8 @@ describe("AcpAdapterV2", () => { assert.deepInclude(late.providerThread.contextUsage, { usedTokens: 13101 }); // With no run left to receive it, only a session-scoped update reaches the projection. assert.isTrue(late.sessionScoped); + // It is written straight to the projection, so it must not revive the settled turn. + assert.equal(late.providerThread.status, "idle"); }).pipe(Effect.provide(layerTest), Effect.scoped), ); diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index a712d40629e60..e214a51586f4c 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -5792,6 +5792,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const now = yield* DateTime.now; const providerThread: OrchestrationV2ProviderThread = { ...knownProviderThread, + // The settled turn's snapshot is still cached as active; no turn runs now. + ...(context === null && knownProviderThread.status === "active" + ? { status: "idle" as const } + : {}), contextUsage: (yield* Ref.get(contextUsageBySessionId)).get(notification.sessionId) ?? knownProviderThread.contextUsage ?? From 76b421864ba9334991940440ccea979585189604 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 16:10:52 -0800 Subject: [PATCH 080/139] fix(web): Ctrl+click in the composer no longer outlines the whole line (#40628) --- apps/web/package.json | 1 + ...ComposerPromptEditorTiptap.input.browser.test.tsx | 12 ++++++++++++ .../src/components/ComposerPromptEditorTiptap.tsx | 4 ++++ pnpm-lock.yaml | 3 +++ 4 files changed, 20 insertions(+) diff --git a/apps/web/package.json b/apps/web/package.json index 9e6f0f475b3d0..21ac8caba0b1e 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -51,6 +51,7 @@ "@tiptap/extension-horizontal-rule": "^3.31.3", "@tiptap/extension-italic": "^3.31.3", "@tiptap/extension-list": "^3.31.3", + "@tiptap/extension-paragraph": "^3.31.3", "@tiptap/extension-strike": "^3.31.3", "@tiptap/extension-task-item": "^3.31.3", "@tiptap/extension-task-list": "^3.31.3", diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx index ca1db10dbdc10..d69c06751b527 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx @@ -677,6 +677,18 @@ it("reopens a long draft scrolled to its caret without taking focus", async () = expect(caret.bottom).toBeLessThanOrEqual(scroller.getBoundingClientRect().bottom - 48 + 1); }); +it("does not outline the line under a click made with the node-select modifier held", async () => { + await using screen = await mountEditor("ship it"); + const { editor } = screen; + const paragraph = editor.view.dom.querySelector("p")!; + const mod = isMacPlatform(navigator.platform) ? "Meta" : "Control"; + await userEvent.keyboard(`{${mod}>}`); + await userEvent.click(paragraph); + await userEvent.keyboard(`{/${mod}}`); + await vi.waitFor(() => expect(document.activeElement).toBe(editor.view.dom)); + expect(getComputedStyle(paragraph).outlineStyle).toBe("none"); +}); + describe("Markdown markers around styled text", () => { it.each([ { keys: "{Backspace}", expected: "**** after" }, diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 9b758ee8b6777..ab43b514ed3d9 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -14,6 +14,7 @@ import { type TiptapEditorHTMLElement, } from "@tiptap/core"; import { ReactNodeViewRenderer, NodeViewWrapper, type NodeViewProps } from "@tiptap/react"; +import { Paragraph } from "@tiptap/extension-paragraph"; import StarterKit from "@tiptap/starter-kit"; import { useGT } from "gt-react"; import { newlineInCode, splitBlockKeepMarks } from "@tiptap/pm/commands"; @@ -876,7 +877,10 @@ function createComposerExtensions(richText: boolean) { italic: false, bold: false, strike: false, + paragraph: false, }), + // Ctrl/Cmd+click would node-select and outline the whole line (Wispr Flow holds Ctrl to dictate). + Paragraph.extend({ selectable: false }), ComposerUndoGroupingExtension, ComposerTextDirectionExtension, ComposerMentionExtension, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 62cbee3b4d8f8..635da4aed6a90 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1158,6 +1158,9 @@ importers: '@tiptap/extension-list': specifier: ^3.31.3 version: 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3) + '@tiptap/extension-paragraph': + specifier: ^3.31.3 + version: 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3)) '@tiptap/extension-strike': specifier: ^3.31.3 version: 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3)) From b5a0352bfd1ba193f0e0795b1501082bcb35c65f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 16:12:04 -0800 Subject: [PATCH 081/139] fix(server): log when a settle script is skipped because its worktree is gone (#40627) Co-authored-by: Kevin Flores <101906409+kevincommits@users.noreply.github.com> --- .../ThreadSettlementService.test.ts | 42 +++++++++++++++++-- .../ThreadSettlementService.ts | 18 +++++++- 2 files changed, 56 insertions(+), 4 deletions(-) diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts index 0fee4a50ce34b..07bb2d64d80a5 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts @@ -28,6 +28,8 @@ 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 Logger from "effect/Logger"; +import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as PlatformError from "effect/PlatformError"; import * as PubSub from "effect/PubSub"; @@ -687,6 +689,12 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: const layerDependencies = Layer.mergeAll( Layer.mock(ProjectStore.ProjectStoreV2)({ listShells: () => Ref.get(snapshots).pipe(Effect.map((snapshot) => snapshot.projects)), + getShell: (projectId) => + Ref.get(snapshots).pipe( + Effect.map((snapshot) => + Option.fromNullishOr(snapshot.projects.find((project) => project.id === projectId)), + ), + ), }), Layer.mock(ProjectionStore.ProjectionStoreV2)({ getThreadsWithPullRequests: (_threadId, readOptions) => @@ -2248,12 +2256,29 @@ describe("ThreadSettlementServiceV2 terminals", () => { it.effect("runs the settle script in the thread's own worktree", () => Effect.gen(function* () { + const warnings: string[] = []; + const logger = Logger.make(({ logLevel, message }) => { + if (logLevel === "Warn") warnings.push(JSON.stringify(message)); + }); const shared = appThread("shared-checkout-thread", "settled"); const missing = appThread("removed-worktree-thread", "settled", "/worktrees/removed"); const worktree = appThread("worktree-thread", "settled", "/worktrees/thread"); + const scriptless = makeProject(ProjectId.make("scriptless-project")); + const missingScriptless = { + ...appThread("removed-worktree-scriptless-thread", "settled", "/worktrees/scriptless"), + projectId: scriptless.id, + }; + const teardown = { + id: "teardown", + name: "Teardown", + command: "docker compose down", + icon: "configure", + runOnWorktreeCreate: false, + runOnSettle: true, + } as const; const fixture = yield* makeHarness({ - snapshot: makeSnapshot([]), - currentThreads: [shared, missing, worktree], + snapshot: makeSnapshot([], [{ ...makeProject(), scripts: [teardown] }, scriptless]), + currentThreads: [shared, missing, missingScriptless, worktree], existingWorktreePaths: ["/worktrees/thread"], }); @@ -2262,12 +2287,23 @@ describe("ThreadSettlementServiceV2 terminals", () => { yield* startHarness(service, fixture.activation, fixture.snapshotReads); yield* fixture.publishEvent(settledEvent(shared)); yield* fixture.publishEvent(settledEvent(missing)); + yield* fixture.publishEvent(settledEvent(missingScriptless)); yield* fixture.publishEvent(settledEvent(worktree)); const run = yield* Queue.take(fixture.scriptRuns); assert.strictEqual(run.threadId, worktree.id); assert.strictEqual(run.worktreePath, "/worktrees/thread"); assert.strictEqual(run.trigger, "settle"); - }).pipe(Effect.provide(fixture.layer)); + // A removed worktree skips a configured settle script; the log is its only trace. + assert.strictEqual(warnings.length, 1); + assert.include(warnings[0], missing.id); + assert.include(warnings[0], "/worktrees/removed"); + }).pipe( + Effect.provide( + fixture.layer.pipe( + Layer.provideMerge(Logger.layer([logger], { mergeWithExisting: false })), + ), + ), + ); }), ); diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index 38616d48846de..ef0894f3ecbeb 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -3,6 +3,7 @@ import { isPullRequestWatchTask, turnItemUpdateCanEndBackgroundWork, } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; +import { resolveProjectScripts, settleProjectScript } from "@t3tools/shared/projectScripts"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; import { @@ -20,6 +21,7 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as FiberSet from "effect/FiberSet"; import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schedule from "effect/Schedule"; import * as Semaphore from "effect/Semaphore"; @@ -758,7 +760,21 @@ export const make = Effect.gen(function* () { if (settled.deletedAt !== null || settled.settledOverride !== "settled") return; yield* terminals.closeOnSettle({ threadId }); const worktreePath = settled.worktreePath; - if (worktreePath === null || !(yield* fileSystem.exists(worktreePath))) return; + if (worktreePath === null) return; + if (!(yield* fileSystem.exists(worktreePath))) { + // A settle script that tears something down would otherwise be skipped with no trace. + const project = Option.getOrUndefined(yield* projectStore.getShell(settled.projectId)); + if ( + project !== undefined && + settleProjectScript(resolveProjectScripts(yield* settingsService.getSettings, project)) + ) { + yield* Effect.logWarning( + "settle script skipped: the thread's worktree no longer exists", + { threadId, worktreePath }, + ); + } + return; + } // Recheck after closing and worktree I/O; only live, settled threads may run scripts. const thread = yield* projections.getThread(threadId); if (thread.deletedAt !== null || thread.settledOverride !== "settled") return; From a9447cedbdfe8690303cc29aa298e801d753abfb Mon Sep 17 00:00:00 2001 From: Matthew Feroz <136640686+MatthewFeroz@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:21:48 -0500 Subject: [PATCH 082/139] fix(web): Cite button appears as fast after a double-click as after a drag (#33221) Co-authored-by: shivam <91240327+shivamhwp@users.noreply.github.com> --- .../chat/AssistantSelectionToolbar.tsx | 1 + .../src/lib/selectionActions.browser.test.ts | 48 +++++++++++++++++++ apps/web/src/lib/selectionActions.ts | 12 ++++- 3 files changed, 59 insertions(+), 2 deletions(-) create mode 100644 apps/web/src/lib/selectionActions.browser.test.ts diff --git a/apps/web/src/components/chat/AssistantSelectionToolbar.tsx b/apps/web/src/components/chat/AssistantSelectionToolbar.tsx index 0772a864c021e..afb51240b625e 100644 --- a/apps/web/src/components/chat/AssistantSelectionToolbar.tsx +++ b/apps/web/src/components/chat/AssistantSelectionToolbar.tsx @@ -143,6 +143,7 @@ export function AssistantSelectionToolbar({ element: viewport, getActionElement: () => toolbarRef.current, restoreAfterScroll: true, + immediateMultiClick: true, onSelection: update, onDismiss: clear, }); diff --git a/apps/web/src/lib/selectionActions.browser.test.ts b/apps/web/src/lib/selectionActions.browser.test.ts new file mode 100644 index 0000000000000..de5b70908fbb6 --- /dev/null +++ b/apps/web/src/lib/selectionActions.browser.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it, vi } from "vite-plus/test"; + +import { fakeTimers } from "../../test/render"; +import { observeSelectionActions, SELECTION_MULTI_CLICK_INTERVAL_MS } from "./selectionActions"; + +describe("observeSelectionActions", () => { + it.each([ + { immediateMultiClick: false, nextFrame: [], afterInterval: [[{ x: 40, y: 12 }]] }, + { immediateMultiClick: true, nextFrame: [[null]], afterInterval: [[null]] }, + ])( + "double-click with immediateMultiClick=$immediateMultiClick", + ({ immediateMultiClick, nextFrame, afterInterval }) => { + using stack = new DisposableStack(); + const element = stack.adopt(document.body.appendChild(document.createElement("div")), (e) => + e.remove(), + ); + stack.use(fakeTimers()); + const onSelection = vi.fn(); + const actions = observeSelectionActions({ + element, + immediateMultiClick, + onSelection, + onDismiss: () => {}, + }); + stack.defer(() => actions.dispose()); + + element.dispatchEvent( + new PointerEvent("pointerdown", { bubbles: true, isPrimary: true, button: 0 }), + ); + element.dispatchEvent( + new MouseEvent("mouseup", { + bubbles: true, + button: 0, + detail: 2, + clientX: 40, + clientY: 12, + }), + ); + + vi.advanceTimersByTime(20); + expect(onSelection.mock.calls).toEqual(nextFrame); + vi.advanceTimersByTime(SELECTION_MULTI_CLICK_INTERVAL_MS - 21); + expect(onSelection.mock.calls).toEqual(nextFrame); + vi.advanceTimersByTime(50); + expect(onSelection.mock.calls).toEqual(afterInterval); + }, + ); +}); diff --git a/apps/web/src/lib/selectionActions.ts b/apps/web/src/lib/selectionActions.ts index 9303602097543..2c219000290c3 100644 --- a/apps/web/src/lib/selectionActions.ts +++ b/apps/web/src/lib/selectionActions.ts @@ -47,12 +47,19 @@ export function observeSelectionActions({ element, getActionElement, restoreAfterScroll = false, + immediateMultiClick = false, onSelection, onDismiss, }: { element: HTMLElement; getActionElement?: () => HTMLElement | null; restoreAfterScroll?: boolean; + /** + * Show double- and triple-click selections at once instead of waiting out the multi-click + * interval. Their pointer is withheld so the action anchors below the selection, clear of + * the spot where a following click lands. + */ + immediateMultiClick?: boolean; onSelection: (pointer: SelectionActionPoint | null) => void; onDismiss: (reason: "interaction" | "cancel") => void; }) { @@ -132,8 +139,9 @@ export function observeSelectionActions({ pointerDown = false; if (!gestureActive) return; gestureActive = false; - pointer = { x: event.clientX, y: event.clientY }; - schedule(event.detail >= 2 ? SELECTION_MULTI_CLICK_INTERVAL_MS : 0); + const multiClick = event.detail >= 2; + pointer = multiClick && immediateMultiClick ? null : { x: event.clientX, y: event.clientY }; + schedule(multiClick && !immediateMultiClick ? SELECTION_MULTI_CLICK_INTERVAL_MS : 0); }; const onKeyDown = (event: KeyboardEvent) => { if (isActionTarget(event.target) && event.key !== "Escape") return; From 67bf1e693a387b3bbbe5c305174617ebc6387974 Mon Sep 17 00:00:00 2001 From: RibatTRW Date: Sun, 22 Nov 2026 08:33:40 +0800 Subject: [PATCH 083/139] fix(desktop): AppImage t3 serve stops cleanly under systemd (#40624) --- apps/desktop/src/app/DesktopCliShim.test.ts | 27 ++++++++++++++------- apps/desktop/src/app/DesktopCliShim.ts | 27 ++++++++++++++++++--- 2 files changed, 42 insertions(+), 12 deletions(-) diff --git a/apps/desktop/src/app/DesktopCliShim.test.ts b/apps/desktop/src/app/DesktopCliShim.test.ts index 3e8b4967dfde5..929148fdbb32f 100644 --- a/apps/desktop/src/app/DesktopCliShim.test.ts +++ b/apps/desktop/src/app/DesktopCliShim.test.ts @@ -69,7 +69,7 @@ const fakeAppImage = (canMount = true, app = REPORTER) => { // Stays up after a signal until the test lets it finish, like a server shutting down. const SLOW_SERVER = [ "#!/bin/sh", - "trap 'echo stopping >&3; read go; echo stopped >&3; exit 0' TERM HUP", + "trap 'echo stopping >&3; read go; echo \"stopped $go\" >&3; exit 7' TERM HUP", "echo ready", "while :; do sleep 0.05; done", "", @@ -101,9 +101,16 @@ const lines = (stream: NodeJS.ReadableStream) => { }; describe("renderCliShim", () => { - it.skipIf(!hasSetsid).each(["SIGTERM", "SIGHUP"] as const)( - "keeps the AppImage mounted until the server exits after %s to the process group", - async (signal) => { + // Ctrl-C, an SSH hangup, or a supervisor signals the process group. systemd's default KillMode + // also signals the mounter, and KillMode=mixed signals only the launcher. + it.skipIf(!hasSetsid).each([ + ["SIGTERM", "the process group"], + ["SIGHUP", "the process group"], + ["SIGTERM", "every process"], + ["SIGTERM", "the launcher"], + ] as const)( + "keeps the AppImage mounted until the server exits after %s to %s", + async (signal, target) => { const { root, shim } = fakeAppImage(true, SLOW_SERVER); const child = NodeChildProcess.spawn(shim, [], { detached: true, @@ -114,12 +121,12 @@ describe("renderCliShim", () => { try { const stdout = lines(child.stdout!); const events = lines(child.stdio[3] as NodeJS.ReadableStream); - const exited = new Promise((resolve) => child.on("close", resolve)); + const exited = new Promise((resolve) => child.on("close", resolve)); await stdout.until((line) => line === "ready"); mounter = Number(NodeFS.readFileSync(NodePath.join(root, "mounter.pid"), "utf8")); - // Ctrl-C in a terminal, a closed SSH session, or a service manager signals the whole group. - process.kill(-child.pid!, signal); + process.kill(target === "the launcher" ? child.pid! : -child.pid!, signal); + if (target === "every process") process.kill(mounter, signal); // The shell runs pending traps in ascending signal number, and WINCH outnumbers TERM and // HUP, so a mounter that also got the group signal unmounts before it answers this probe. process.kill(mounter, "SIGWINCH"); @@ -128,8 +135,8 @@ describe("renderCliShim", () => { await events.until((line) => line === "stopping"); child.stdin!.end("go\n"); - await exited; - expect(events.seen.slice(-2)).toEqual(["stopped", "unmounted"]); + expect(await exited).toBe(7); + expect(events.seen.slice(-2)).toEqual(["stopped go", "unmounted"]); } finally { for (const pid of [-child.pid!, mounter]) { if (pid === undefined) continue; @@ -156,6 +163,8 @@ describe("renderCliShim", () => { const result = run(shim, ["--version"]); expect(result.status).toBe(3); expect(result.stdout).toContain(`appimage=${appImage}`); + const closedStdin = NodeChildProcess.spawnSync("sh", ["-c", '"$0" --version <&-', shim]); + expect(closedStdin.status).toBe(3); }); it("keeps the install's T3 home under sudo, unless one is set", () => { diff --git a/apps/desktop/src/app/DesktopCliShim.ts b/apps/desktop/src/app/DesktopCliShim.ts index 217f3b327dc9e..0f7e605da6b36 100644 --- a/apps/desktop/src/app/DesktopCliShim.ts +++ b/apps/desktop/src/app/DesktopCliShim.ts @@ -91,11 +91,15 @@ export const renderCliShim = (input: { // Extract-and-run would make the runtime start the app instead of mounting it. "unset APPIMAGE_EXTRACT_AND_RUN", // Its own session keeps a group signal (Ctrl-C, SSH hangup) from unmounting it under the - // running server; the traps unmount it after. Without setsid the extract fallback runs. + // running server, and ignoring TERM survives a stop sent to every process (systemd's default). + // Without setsid the extract fallback runs. "work=$(mktemp -d) || exit 1", + "trap '' TERM", 'setsid "$app" --appimage-mount >"$work/mount" 2>/dev/null &', "mounter=$!", - `trap 'kill "$mounter" 2>/dev/null; rm -rf "$work"' EXIT`, + // It unmounts itself on TERM, which it now ignores, so the trap unmounts it. Lazily, like the + // runtime: the server's own children may still be exiting. + `trap '[ -z "$mount" ] || fusermount3 -uz "$mount" 2>/dev/null || fusermount -uz "$mount" 2>/dev/null; kill -HUP "$mounter" 2>/dev/null; rm -rf "$work"' EXIT`, "trap 'exit 130' INT TERM HUP", "mount=", 'while kill -0 "$mounter" 2>/dev/null; do', @@ -111,7 +115,24 @@ export const renderCliShim = (input: { "fi", // The runtime sets this when it launches the app; the CLI skips its path-keyed compile cache on it. 'export APPIMAGE="$app"', - run("$mount"), + // The shell must outlive the CLI to unmount, so it forwards TERM and HUP; the terminal sends + // Ctrl-C to the CLI directly. A background child would read /dev/null, so pass stdin on fd 9. + // With stdin closed, `exec 9<&0` would end the shell; `command` makes it a normal error. + "{ command exec 9<&0; } 2>/dev/null || exec 9/dev/null' TERM`, + `trap 'kill -HUP "$cli" 2>/dev/null' HUP`, + "trap '' INT", + "status=0", + 'wait "$cli" || status=$?', + // A trapped signal interrupts wait; wait again for the CLI's own exit status. + 'while kill -0 "$cli" 2>/dev/null; do', + " status=0", + ' wait "$cli" || status=$?', + "done", + 'exit "$status"', "", ].join("\n"); }; From 047fb5b1627c67d3f7a9d7e70c10af2536551b7e Mon Sep 17 00:00:00 2001 From: Alex Southwell Date: Sun, 22 Nov 2026 11:36:35 +1100 Subject: [PATCH 084/139] fix(relay): iOS notifications no longer cut an emoji in half at the title limit (#29830) Co-authored-by: Claude Opus 5.5 Co-authored-by: shivam <91240327+shivamhwp@users.noreply.github.com> --- infra/relay/src/agentActivity/ApnsClient.test.ts | 4 +++- infra/relay/src/agentActivity/agentActivityPayloads.ts | 7 ++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/infra/relay/src/agentActivity/ApnsClient.test.ts b/infra/relay/src/agentActivity/ApnsClient.test.ts index 81e76b0391aae..f06c751982710 100644 --- a/infra/relay/src/agentActivity/ApnsClient.test.ts +++ b/infra/relay/src/agentActivity/ApnsClient.test.ts @@ -151,7 +151,7 @@ describe("ApnsClient", () => { const environmentId = "é".repeat(191); const threadId = "t".repeat(512); const notification = sanitizeApnsNotificationPayload({ - title: "界".repeat(120), + title: "😀".repeat(120), body: "界".repeat(120), environmentId, threadId, @@ -159,6 +159,8 @@ describe("ApnsClient", () => { }); const request = apns.makePushNotificationRequest({ token: "push-token", notification }); + expect(notification.title).toBe(`${"😀".repeat(58)}...`); + expect( new TextEncoder().encode(JSON.stringify(request.payload)).byteLength, ).toBeLessThanOrEqual(4096); diff --git a/infra/relay/src/agentActivity/agentActivityPayloads.ts b/infra/relay/src/agentActivity/agentActivityPayloads.ts index 4195c81171803..2dd8be5870b9b 100644 --- a/infra/relay/src/agentActivity/agentActivityPayloads.ts +++ b/infra/relay/src/agentActivity/agentActivityPayloads.ts @@ -52,7 +52,12 @@ export function truncateText(value: string, maxLength: number): string { if (trimmed.length <= maxLength) { return trimmed; } - return trimmed.slice(0, maxLength - 3).trimEnd() + "..."; + return ( + trimmed + .slice(0, maxLength - 3) + .replace(/[\uD800-\uDBFF]$/, "") + .trimEnd() + "..." + ); } function sanitizeDeepLink(value: string): string { From 5028eb10a4851ba3943c3bd2291137598727d286 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 17:06:34 -0800 Subject: [PATCH 085/139] perf(shared): Windows command lookups reuse PATH listings across requests (#40634) Co-authored-by: Mostafa El Ayoubi <20224923+MostafaElAyoubi@users.noreply.github.com> --- apps/desktop/src/ipc/methods/window.test.ts | 56 ++++----- apps/desktop/src/ipc/methods/window.ts | 4 +- apps/server/src/process/externalLauncher.ts | 8 +- packages/shared/src/shell.test.ts | 93 +++++++++++++-- packages/shared/src/shell.ts | 124 +++++++++++++++++--- 5 files changed, 218 insertions(+), 67 deletions(-) diff --git a/apps/desktop/src/ipc/methods/window.test.ts b/apps/desktop/src/ipc/methods/window.test.ts index b256025eff844..9c50501a1bdfd 100644 --- a/apps/desktop/src/ipc/methods/window.test.ts +++ b/apps/desktop/src/ipc/methods/window.test.ts @@ -4,6 +4,7 @@ import type { ManagedPolicyLimits } from "@t3tools/contracts"; import { EDITORS, REMOTE_CAPABLE_EDITOR_IDS } from "@t3tools/contracts"; import { resolveEditorCommand } from "@t3tools/shared/editor"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { makePathDirectoryListings, PathDirectoryListings } from "@t3tools/shared/shell"; import { ManagedPolicyFileError } from "@t3tools/shared/managedPolicyFile"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; @@ -11,6 +12,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import { vi } from "vite-plus/test"; import type * as Electron from "electron"; @@ -550,6 +552,7 @@ it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( ); describe("probeRemoteEditors PATH scan", () => { + const FIXTURE_MTIME = 1_767_225_600; const platform = HostProcess.Platform.defaultValue(); const launcherName = (command: string) => (platform === "win32" ? `${command}.cmd` : command); @@ -570,6 +573,9 @@ describe("probeRemoteEditors PATH scan", () => { yield* fs.writeFileString(file, "#!/bin/sh\n"); if (platform !== "win32") yield* fs.chmod(file, 0o755); } + // A listing of a directory changed moments ago is not kept, so age them past that window. + for (const dir of dirs) yield* fs.utimes(dir, FIXTURE_MTIME, FIXTURE_MTIME); + yield* TestClock.setTime((FIXTURE_MTIME + 60) * 1000); return { root, env: { @@ -581,19 +587,15 @@ describe("probeRemoteEditors PATH scan", () => { }; }); - const countingFileSystem = (counter: { stat: number; reads: Map }) => + const countingFileSystem = (reads: Map) => Layer.effect( FileSystem.FileSystem, Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; return FileSystem.FileSystem.of({ ...fs, - stat: (target) => { - counter.stat += 1; - return fs.stat(target); - }, readDirectory: (target, options) => { - counter.reads.set(target, (counter.reads.get(target) ?? 0) + 1); + reads.set(target, (reads.get(target) ?? 0) + 1); return fs.readDirectory(target, options); }, }); @@ -612,44 +614,38 @@ describe("probeRemoteEditors PATH scan", () => { return available; }); - it.effect("reads each PATH directory once instead of stat-ing every candidate per editor", () => + it.effect("finds the editors a serial scan finds, listing each PATH directory at most once", () => Effect.gen(function* () { const { env: baseEnv } = yield* makeFakePath(); const delimiter = platform === "win32" ? ";" : ":"; - const uncachedCounter = { stat: 0, reads: new Map() }; - const cachedCounter = { stat: 0, reads: new Map() }; - const uncachedEnv = { ...baseEnv, PATH: `${baseEnv.PATH}${delimiter}${baseEnv.HOME}x1` }; - const cachedEnv = { ...baseEnv, PATH: `${baseEnv.PATH}${delimiter}${baseEnv.HOME}x2` }; - const uncached = yield* serialReference(uncachedEnv).pipe( - Effect.provide(countingFileSystem(uncachedCounter)), + const reads = new Map(); + // Distinct PATH values keep one scan from answering the other out of the resolution cache. + const serialEnv = { ...baseEnv, PATH: `${baseEnv.PATH}${delimiter}${baseEnv.HOME}x1` }; + const probeEnv = { ...baseEnv, PATH: `${baseEnv.PATH}${delimiter}${baseEnv.HOME}x2` }; + const serial = yield* serialReference(serialEnv).pipe( + Effect.provideServiceEffect(PathDirectoryListings, makePathDirectoryListings), ); - const cached = yield* probeRemoteEditors + const probed = yield* probeRemoteEditors .handler(undefined) .pipe( - Effect.provideService(HostProcess.Environment, cachedEnv), + Effect.provideService(HostProcess.Environment, probeEnv), Effect.provideService(HostProcess.Platform, platform), - Effect.provide(countingFileSystem(cachedCounter)), + Effect.provide(countingFileSystem(reads)), + Effect.provideServiceEffect(PathDirectoryListings, makePathDirectoryListings), ); // The host can add editors from app folders the fixture can't redirect (e.g. /Applications). const fixtureEditors = ["cursor", "vscode", "zed", "webstorm"]; assert.deepStrictEqual( - uncached.filter((id) => fixtureEditors.includes(id)), + serial.filter((id) => fixtureEditors.includes(id)), fixtureEditors, ); - assert.deepStrictEqual(cached, uncached); - assert.isAbove(uncachedCounter.stat, 0); - // On every platform the probe lists each PATH directory at most once. Only PATH entries count: - // resolveEditorCommand also reads app folders such as /Applications on macOS. - const pathReads = cachedEnv.PATH.split(delimiter) + assert.deepStrictEqual(probed, serial); + // Only PATH entries count: resolveEditorCommand also reads app folders such as /Applications + // on macOS. PATH directories are listed on Windows only, once even for concurrent probes. + const pathReads = probeEnv.PATH.split(delimiter) .filter((entry) => entry.length > 0) - .map((entry) => cachedCounter.reads.get(entry) ?? 0); - assert.isAbove(Math.max(...pathReads), 0); - assert.isAtMost(Math.max(...pathReads), 1); - // Without the listings, Windows stats every PATH entry x PATHEXT candidate for each editor; - // elsewhere there is no PATHEXT, so the stat count is about the same either way. - if (platform === "win32") { - assert.isBelow(cachedCounter.stat, uncachedCounter.stat / 2); - } + .map((entry) => reads.get(entry) ?? 0); + assert.strictEqual(Math.max(...pathReads), platform === "win32" ? 1 : 0); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); }); diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index abf4ec929a7b7..c6ad0bef18c81 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -17,7 +17,6 @@ import { } from "@t3tools/contracts"; import { PROJECT_FAVICON_EXTENSIONS } from "@t3tools/shared/projectFavicon"; import { resolveEditorCommand } from "@t3tools/shared/editor"; -import { withPathDirectoryListings } from "@t3tools/shared/shell"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { isRelayTracingEnabled } from "@t3tools/shared/otelEnvironment"; import * as FileSystem from "effect/FileSystem"; @@ -446,7 +445,6 @@ export const probeRemoteEditors = DesktopIpc.makeIpcMethod({ result: Schema.Array(EditorId), handler: Effect.fn("desktop.ipc.window.probeRemoteEditors")(function* () { const env = yield* HostProcess.Environment; - // Shared listings stop each editor re-stating every PATH entry x PATHEXT candidate on Windows. const resolved = yield* Effect.forEach( REMOTE_CAPABLE_EDITOR_IDS, (editorId) => { @@ -456,7 +454,7 @@ export const probeRemoteEditors = DesktopIpc.makeIpcMethod({ : Effect.succeed(false); }, { concurrency: REMOTE_EDITOR_PROBE_CONCURRENCY }, - ).pipe(withPathDirectoryListings); + ); return REMOTE_CAPABLE_EDITOR_IDS.filter((_, index) => resolved[index]); }), }); diff --git a/apps/server/src/process/externalLauncher.ts b/apps/server/src/process/externalLauncher.ts index caa6664a1ba80..4c0d006332ff7 100644 --- a/apps/server/src/process/externalLauncher.ts +++ b/apps/server/src/process/externalLauncher.ts @@ -15,11 +15,7 @@ import { } from "@t3tools/contracts"; import { resolveEditorCommand } from "@t3tools/shared/editor"; import * as HostProcess from "@t3tools/shared/HostProcess"; -import { - isCommandAvailable, - resolveSpawnCommand, - withPathDirectoryListings, -} from "@t3tools/shared/shell"; +import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell"; import * as Config from "effect/Config"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; @@ -503,7 +499,7 @@ const readEditorEnv = Effect.fn("externalLauncher.readEditorEnv")(function* () { const resolveAvailableEditors = Effect.fn("externalLauncher.resolveAvailableEditors")(function* () { const platform = yield* HostProcess.Platform; const env = yield* readEditorEnv(); - return yield* buildAvailableEditors(platform, env).pipe(withPathDirectoryListings); + return yield* buildAvailableEditors(platform, env); }); const resolveFileManagerRevealKind = Effect.fn("externalLauncher.resolveFileManagerRevealKind")( diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index d9950edc60cfb..08731a41c19ef 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -22,6 +22,8 @@ import { pathSetupCommand, CommandAvailability, CommandResolutionCache, + makePathDirectoryListings, + PathDirectoryListings, type CommandAvailabilityChecker, gitForWindowsBash, isCommandAvailable, @@ -39,7 +41,6 @@ import { windowsEnvironmentValueCommand, SpawnExecutableResolution, WindowsShellEnvironment, - withPathDirectoryListings, type WindowsShellEnvironmentReader, XcodeGitLocation, } from "./shell.ts"; @@ -591,7 +592,8 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { stat: (filePath) => Effect.sync(() => { probed.push(filePath); - return { type: "Directory" } as FileSystem.File.Info; + // No mtime, so no listing: every candidate is probed directly. + return { type: "Directory", mtime: Option.none() } as FileSystem.File.Info; }), }), ), @@ -609,7 +611,7 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { }); // Windows PATH directories can be case-sensitive; preserve both spellings. - expect(probed).toHaveLength(8); + expect(probed.filter((file) => file.includes("definitely-not-installed"))).toHaveLength(8); }), ); @@ -635,7 +637,7 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { ...fs, stat: (filePath) => fs.stat( - filePath === executable || filePath === decoy + [cwd, executable, decoy].includes(filePath) ? filePath : path.join(cwd, "missing"), ), @@ -646,38 +648,111 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { }), ); - it.effect("probes only listed PATH names and relists a directory that changes", () => + // Seconds; the tests below run their clock a minute later, past the window in which a listing is not kept. + const AGED_MTIME = 4_102_444_800; + const afterAgedMtime = TestClock.setTime((AGED_MTIME + 60) * 1000); + + it.effect("reuses PATH listings across lookups until a directory changes", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const first = yield* fs.makeTempDirectoryScoped(); const second = yield* fs.makeTempDirectoryScoped(); yield* fs.writeFileString(path.join(first, "cursor.CMD"), ""); + yield* fs.writeFileString(path.join(first, "MyToolLongName.cmd"), ""); yield* fs.writeFileString(path.join(second, "cursor.EXE"), ""); + yield* fs.utimes(first, AGED_MTIME, AGED_MTIME); + yield* fs.utimes(second, AGED_MTIME, AGED_MTIME); + yield* afterAgedMtime; const env = { PATH: `${first};${second}`, PATHEXT: ".EXE;.CMD" }; + // Windows resolves an 8.3 alias that a directory listing never names. + const alias = path.join(first, "MYTOOL~1.CMD"); const probed: Array = []; + const listed: Array = []; yield* Effect.gen(function* () { expect(yield* resolveCommandPath("cursor", { env })).toBe(path.join(first, "cursor.CMD")); expect(yield* isCommandAvailable("absent", { env })).toBe(false); + expect(yield* isCommandAvailable("also-absent", { env })).toBe(false); + expect(yield* resolveCommandPath("MYTOOL~1", { env })).toBe(alias); + expect(listed).toEqual([first, second]); yield* fs.writeFileString(path.join(second, "late.EXE"), ""); - yield* fs.utimes(second, 4_102_444_800, 4_102_444_800); + yield* fs.utimes(second, AGED_MTIME + 30, AGED_MTIME + 30); expect(yield* resolveCommandPath("late", { env })).toBe(path.join(second, "late.EXE")); + expect(listed).toEqual([first, second, second]); }).pipe( - withPathDirectoryListings, Effect.provideService(FileSystem.FileSystem, { ...fs, stat: (file) => { if (file !== first && file !== second) probed.push(file); - return fs.stat(file); + return fs.stat(file === alias ? path.join(first, "MyToolLongName.cmd") : file); + }, + readDirectory: (directory, options) => { + listed.push(directory); + return fs.readDirectory(directory, options); + }, + }), + ); + expect(probed).toEqual([ + path.join(first, "cursor.CMD"), + path.join(first, "MYTOOL~1.EXE"), + path.join(first, "MYTOOL~1.exe"), + alias, + path.join(second, "late.EXE"), + ]); + }).pipe( + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService(CommandResolutionCache, new Map()), + Effect.provideServiceEffect(PathDirectoryListings, makePathDirectoryListings), + ), + ); + + it.effect("does not keep the listing of a PATH directory that changed moments ago", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const directory = yield* fs.makeTempDirectoryScoped(); + yield* fs.utimes(directory, AGED_MTIME + 59, AGED_MTIME + 59); + yield* afterAgedMtime; + const env = { PATH: directory, PATHEXT: ".CMD" }; + let listings = 0; + yield* Effect.gen(function* () { + expect(yield* isCommandAvailable("absent", { env })).toBe(false); + expect(yield* isCommandAvailable("also-absent", { env })).toBe(false); + }).pipe( + Effect.provideService(FileSystem.FileSystem, { + ...fs, + readDirectory: (target, options) => { + listings += 1; + return fs.readDirectory(target, options); }, }), ); - expect(probed).toEqual([path.join(first, "cursor.CMD"), path.join(second, "late.EXE")]); + expect(listings).toBe(2); }).pipe( Effect.provideService(HostProcess.Platform, "win32"), Effect.provideService(CommandResolutionCache, new Map()), + Effect.provideServiceEffect(PathDirectoryListings, makePathDirectoryListings), ), ); + + // A POSIX directory joined with win32 separators names nothing, so this needs a Windows host. + it.effect.skipIf(HostProcess.Platform.defaultValue() !== "win32")( + "relists a changed PATH directory in the synchronous spawn resolver", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped(); + yield* fs.writeFileString(path.join(directory, "cursor.CMD"), ""); + yield* fs.utimes(directory, 946_684_800, 946_684_800); + const env = { PATH: directory, PATHEXT: ".EXE;.CMD" }; + const resolveExecutable = yield* SpawnExecutableResolution; + expect(resolveExecutable("cursor", "win32", env)).toBe(path.join(directory, "cursor.CMD")); + expect(resolveExecutable("late", "win32", env)).toBeUndefined(); + yield* fs.writeFileString(path.join(directory, "late.EXE"), ""); + yield* fs.utimes(directory, 946_684_830, 946_684_830); + expect(resolveExecutable("late", "win32", env)).toBe(path.join(directory, "late.EXE")); + }), + ); }); describe("runsGitWithoutConsole", () => { diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index 8ccb466775c1f..ffcc1110fe381 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -7,6 +7,7 @@ import * as Cache from "effect/Cache"; import * as Clock from "effect/Clock"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; @@ -108,7 +109,12 @@ function resolveSpawnExecutableWithNode( for (const pathEntry of (readEnvPath(env) ?? "").split(pathDelimiterForPlatform(platform))) { const normalizedPathEntry = normalizePathEntry(pathEntry, platform); if (normalizedPathEntry.length === 0) continue; + const names = + platform === "win32" + ? listPathDirectorySync(normalizedPathEntry, path.isAbsolute) + : undefined; for (const candidate of candidates) { + if (isAbsentFromListing(names, candidate)) continue; const candidatePath = path.join(normalizedPathEntry, candidate); if (isExecutable(candidatePath)) return candidatePath; } @@ -578,7 +584,38 @@ export const CommandResolutionCache = Context.Reference | undefined; + readonly reusable: boolean; +} + +const PATH_DIRECTORY_LISTINGS_MAX_ENTRIES = 1024; +// A directory changed within a coarse filesystem's timestamp step (FAT: 2 s) can change again +// without moving its mtime, so its listing serves the lookups waiting on it but is not kept. +const PATH_DIRECTORY_SETTLE_MS = 2_000; +const NO_DIRECTORY_NAMES: ReadonlySet = new Set(); + +// A listing only speaks for names Windows matches by ASCII case folding. It omits 8.3 aliases +// (`~`), Windows trims a trailing dot, and other characters fold differently than in JS. +const LISTED_NAME_PATTERN = /^[\w.+-]*[\w+-]$/; + +function isAbsentFromListing(names: ReadonlySet | undefined, candidate: string): boolean { + return ( + names !== undefined && + LISTED_NAME_PATTERN.test(candidate) && + !names.has(candidate.toLowerCase()) + ); +} + +// The listing must start after the mtime's timestamp step has passed, and a relative entry +// names another directory once the working directory changes. +function isReusableListing( + directory: string, + modified: number, + listedAtMs: number, + isAbsolute: (path: string) => boolean, +): boolean { + return isAbsolute(directory) && listedAtMs - modified >= PATH_DIRECTORY_SETTLE_MS; } const directoryMtime = (directory: string) => @@ -592,29 +629,77 @@ const directoryMtime = (directory: string) => // Timestamp before reading so concurrent additions change the next mtime check; missing listings fall back to direct probes. const listPathDirectory = Effect.fnUntraced(function* ( directory: string, -): Effect.fn.Return { +): Effect.fn.Return { + const path = yield* Path.Path; const modified = yield* directoryMtime(directory); - if (modified == null) return { modified, names: modified === null ? new Set() : undefined }; + if (modified === null) { + return { modified, names: NO_DIRECTORY_NAMES, reusable: path.isAbsolute(directory) }; + } + if (modified === undefined) return { modified, names: undefined, reusable: false }; + const listedAtMs = yield* Clock.currentTimeMillis; const entries = yield* FileSystem.FileSystem.use((fileSystem) => fileSystem.readDirectory(directory), ).pipe(Effect.orElseSucceed(() => undefined)); - return { modified, names: entries && new Set(entries.map((entry) => entry.toLowerCase())) }; + return { + modified, + names: entries && new Set(entries.map((entry) => entry.toLowerCase())), + reusable: + entries !== undefined && isReusableListing(directory, modified, listedAtMs, path.isAbsolute), + }; }); -const PathDirectoryListings = Context.Reference< - Cache.Cache | undefined ->("@t3tools/shared/shell/PathDirectoryListings", { defaultValue: () => undefined }); - -export const withPathDirectoryListings = - /* Directory reads are cached inside one shell operation; a span for each lookup adds noise. */ - Effect.fnUntraced(function* (effect: Effect.Effect) { - const listings = yield* Cache.make({ - capacity: 1024, - lookup: listPathDirectory, - requireServicesAt: "lookup", - }); - return yield* effect.pipe(Effect.provideService(PathDirectoryListings, listings)); - }); +export const makePathDirectoryListings = Cache.makeWith(listPathDirectory, { + capacity: PATH_DIRECTORY_LISTINGS_MAX_ENTRIES, + timeToLive: (exit) => + Exit.isSuccess(exit) && exit.value.reusable ? Duration.infinity : Duration.zero, + requireServicesAt: "lookup", +}); + +/** Windows PATH directory listings for the process; each use rechecks the directory's mtime. */ +export const PathDirectoryListings = Context.Reference( + "@t3tools/shared/shell/PathDirectoryListings", + { defaultValue: () => Effect.runSync(makePathDirectoryListings) }, +); + +const syncPathDirectoryListings = new Map< + string, + { readonly modified: number; readonly names: ReadonlySet } +>(); + +// The synchronous resolver's counterpart of `PathDirectoryListings`, under the same rules. +function listPathDirectorySync( + directory: string, + isAbsolute: (path: string) => boolean, +): ReadonlySet | undefined { + let modified: number; + try { + const stats = NodeFS.statSync(directory); + if (!stats.isDirectory()) return undefined; + modified = stats.mtimeMs; + } catch (error) { + return (error as NodeJS.ErrnoException).code === "ENOENT" ? NO_DIRECTORY_NAMES : undefined; + } + const cached = syncPathDirectoryListings.get(directory); + if (cached?.modified === modified) return cached.names; + syncPathDirectoryListings.delete(directory); + // This resolver runs outside Effect, so it has no Clock to read. + // @effect-diagnostics-next-line globalDate:off + const listedAtMs = Date.now(); + let names: ReadonlySet; + try { + names = new Set(NodeFS.readdirSync(directory).map((entry) => entry.toLowerCase())); + } catch { + return undefined; + } + if (isReusableListing(directory, modified, listedAtMs, isAbsolute)) { + if (syncPathDirectoryListings.size >= PATH_DIRECTORY_LISTINGS_MAX_ENTRIES) { + const oldest = syncPathDirectoryListings.keys().next().value; + if (oldest !== undefined) syncPathDirectoryListings.delete(oldest); + } + syncPathDirectoryListings.set(directory, { modified, names }); + } + return names; +} // An injected resolver or locator may answer differently for the same search, so its // entries are kept apart from every other resolver's. @@ -685,7 +770,8 @@ const findOnPath = Effect.fnUntraced(function* ( pathEntries.push(pathEntry); } - const listings = yield* PathDirectoryListings; + // Only Windows multiplies the candidates per directory; elsewhere a listing saves no probe. + const listings = platform === "win32" ? yield* PathDirectoryListings : undefined; const matches: string[] = []; for (const pathEntry of pathEntries) { let listing = listings && (yield* Cache.get(listings, pathEntry)); @@ -694,7 +780,7 @@ const findOnPath = Effect.fnUntraced(function* ( listing = yield* Cache.get(listings, pathEntry); } for (const candidate of commandCandidates) { - if (listing?.names && !listing.names.has(candidate.toLowerCase())) continue; + if (isAbsentFromListing(listing?.names, candidate)) continue; const candidatePath = path.join(pathEntry, candidate); if (yield* isExecutableFile(candidatePath, platform, windowsPathExtensions)) { matches.push(candidatePath); From 83edd5e722e11a469c3ec72684eab71b0236d9aa Mon Sep 17 00:00:00 2001 From: Navid Nadali Date: Sun, 22 Nov 2026 01:07:59 +0000 Subject: [PATCH 086/139] fix(mcp): t3_thread_wait no longer has parents poll a task's first run (#40633) Co-authored-by: Julius Marminge --- .../src/mcp/OrchestratorMcpService.test.ts | 24 +++++++++++++++---- apps/server/src/mcp/OrchestratorMcpService.ts | 9 +++++-- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index 4a5935d427879..ccd41144a5ea8 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -617,6 +617,7 @@ describe("OrchestratorMcpService", () => { const childThreadId = ThreadId.make("thread:mcp-next-child"); const taskId = NodeId.make("node:mcp-next-task"); let finished = false; + let firstRun = false; let pendingRequest: "live" | "message" | null = null; const parentProjection = () => ({ @@ -640,12 +641,17 @@ describe("OrchestratorMcpService", () => { const childRun = () => ({ id: RunId.make("run:mcp-next-child"), ordinal: 1, - status: finished ? ("completed" as const) : ("running" as const), - delegatedTaskId: taskId, + status: finished && !firstRun ? ("completed" as const) : ("running" as const), + // A task's first run is untagged; the child's fork node names the task. + ...(firstRun ? {} : { delegatedTaskId: taskId }), }); const childProjection = () => ({ - thread: { id: childThreadId, title: "Child task" }, + thread: { + id: childThreadId, + title: "Child task", + forkedFrom: { type: "node", nodeId: taskId }, + }, runs: [childRun()], contextTransfers: [], messages: [], @@ -677,7 +683,7 @@ describe("OrchestratorMcpService", () => { Effect.succeed({ threadId: childThreadId, run: childRun() as unknown as OrchestrationV2ThreadProjection["runs"][number], - timedOut: !finished, + timedOut: !finished || firstRun, }), dispatch: () => Effect.succeed({} as never), }), @@ -725,7 +731,17 @@ describe("OrchestratorMcpService", () => { assert.equal(working.next, ORCHESTRATOR_MCP_RUNNING_TASK_NEXT); pendingRequest = null; + firstRun = true; + const first = yield* service.waitForThread(scope, { threadId: childThreadId }); + assert.equal(first.next, ORCHESTRATOR_MCP_RUNNING_TASK_NEXT); + + // An untagged run after the task has its result is no longer that task. finished = true; + const followUp = yield* service.waitForThread(scope, { threadId: childThreadId }); + assert.isTrue(followUp.timedOut); + assert.notProperty(followUp, "next"); + firstRun = false; + const completed = yield* service.taskStatus(scope, taskId); assert.equal(completed.status, "completed"); assert.notProperty(completed, "next"); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 5f0c95a55ffee..4062c509812c4 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -3713,7 +3713,11 @@ const make = Effect.gen(function* () { }) .pipe(Effect.mapError(threadManagementFailure)); const status = result.run === null ? "idle" : runOutcome(result.run); - const taskId = result.run?.delegatedTaskId; + // A task's first run carries no task id; the child's untagged runs continue that task + // until it has a result. + const taskId = + result.run?.delegatedTaskId ?? + (target.thread.forkedFrom?.type === "node" ? target.thread.forkedFrom.nodeId : undefined); const ownedTask = result.timedOut && status !== "waiting" && @@ -3725,7 +3729,8 @@ const make = Effect.gen(function* () { task.origin === "app_owned" && task.threadId === parent.thread.id && task.childThreadId === input.threadId && - task.completionDelivery?.state !== "disposed", + task.completionDelivery?.state !== "disposed" && + (result.run?.delegatedTaskId !== undefined || task.result === null), ); // A child waiting on a question or approval needs an answer, not a wake. const childRequests = ownedTask From 15d945faef4c14099ba3d82bcdb84e91b5a3c3cd Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 17:20:02 -0800 Subject: [PATCH 087/139] fix(server): reveal no longer opens Explorer's default folder for a missing file (#40637) --- .../src/process/externalLauncher.test.ts | 55 +++++++++++++++++-- apps/server/src/process/externalLauncher.ts | 9 +++ packages/contracts/src/editor.ts | 13 +++++ 3 files changed, 72 insertions(+), 5 deletions(-) diff --git a/apps/server/src/process/externalLauncher.test.ts b/apps/server/src/process/externalLauncher.test.ts index 8ce873733d443..827d52bbda230 100644 --- a/apps/server/src/process/externalLauncher.test.ts +++ b/apps/server/src/process/externalLauncher.test.ts @@ -65,6 +65,7 @@ const layerTest = (input: { readonly onSpawn?: (command: ChildProcess.StandardCommand) => void; readonly onUnref?: () => void; readonly spawnResult?: (command: ChildProcess.StandardCommand) => MockSpawnResult | undefined; + readonly existingPaths?: ReadonlyArray; }) => { const layerSpawner = Layer.succeed( ChildProcessSpawner.ChildProcessSpawner, @@ -92,6 +93,17 @@ const layerTest = (input: { NodeServices.layer, layerSpawner, input.path ? Layer.succeed(Path.Path, input.path) : Layer.empty, + // Reveal fixtures name paths that do not exist on the test host. + Layer.effect( + FileSystem.FileSystem, + Effect.map(FileSystem.FileSystem, (fileSystem) => ({ + ...fileSystem, + exists: (path: string) => + input.existingPaths?.includes(path) + ? Effect.succeed(true) + : fileSystem.exists(path), + })), + ).pipe(Layer.provide(NodeServices.layer)), ), ), ), @@ -571,6 +583,7 @@ for (const [replacement, verb, handler, target, expected] of [ layerTest({ platform: "win32", env: { PATH: "C:\\Windows", PATHEXT: ".EXE" }, + existingPaths: [target], onSpawn: (command) => { spawned = command; }, @@ -605,16 +618,13 @@ it.effect.skipIf(windowsHost)( yield* fileSystem.chmod(filePath, 0o755); } + const target = "/home/t3/workspace [draft]/author's ‘$media/clip|draft.mp4"; let spawned: ChildProcess.StandardCommand | undefined; const result = yield* Effect.gen(function* () { const launcher = yield* ExternalLauncher.ExternalLauncher; const kind = yield* launcher.resolveFileManagerRevealKind(); const editors = yield* launcher.resolveAvailableEditors(); - yield* launcher.launchEditor({ - editor: "file-manager", - cwd: "/home/t3/workspace [draft]/author's ‘$media/clip|draft.mp4", - reveal: true, - }); + yield* launcher.launchEditor({ editor: "file-manager", cwd: target, reveal: true }); return { kind, editors }; }).pipe( Effect.provide( @@ -625,6 +635,7 @@ it.effect.skipIf(windowsHost)( WSL_DISTRO_NAME: "Ubuntu-24.04", WSL_INTEROP: "/run/WSL/1_interop", }, + existingPaths: [target], onSpawn: (command) => { spawned = command; }, @@ -687,6 +698,7 @@ it.effect.each([ layerTest({ platform: "win32", env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD", SYSTEMROOT: "C:\\Windows" }, + existingPaths: ["C:/Users/t3/my project/a,b.ts"], onSpawn: (command) => spawned.push(command), spawnResult: (command) => (command.command.endsWith("reg.exe") ? registry : undefined), }), @@ -718,6 +730,38 @@ it.effect.each([ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); +// Explorer answers /select of a missing path by opening its default folder, not the parent. +it.effect("does not ask Explorer to select a file that does not exist", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); + yield* fileSystem.writeFileString(path.join(binDir, "explorer.EXE"), ""); + const missing = path.join(binDir, "CLAUDE.md"); + const verbatim: Array]> = []; + yield* Effect.gen(function* () { + const launcher = yield* ExternalLauncher.ExternalLauncher; + yield* launcher + .launchEditor({ editor: "file-manager", cwd: missing, reveal: true }) + .pipe(Effect.exit); + }).pipe( + Effect.provideService(WindowsVerbatimSpawn, (command, args) => + Effect.sync(() => verbatim.push([command, args])), + ), + Effect.provide( + layerTest({ + platform: "win32", + env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD", SYSTEMROOT: "C:\\Windows" }, + spawnResult: (command) => + command.command.endsWith("reg.exe") ? { stdout: STOCK_FOLDER_VERB } : undefined, + }), + ), + ); + + assert.deepEqual(verbatim, []); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + for (const wsl of [false, true]) { it.effect.skipIf(windowsHost)( "selects a file over D-Bus on " + (wsl ? "WSLg without interop PowerShell" : "Linux"), @@ -747,6 +791,7 @@ for (const wsl of [false, true]) { ? { WSL_DISTRO_NAME: "Ubuntu-24.04", WSL_INTEROP: "/run/WSL/1_interop" } : {}), }, + existingPaths: [target], onSpawn: (command) => spawnedCommands.push(command), spawnResult: (command) => command.command === "xdg-mime" diff --git a/apps/server/src/process/externalLauncher.ts b/apps/server/src/process/externalLauncher.ts index 4c0d006332ff7..b5ffaf82fcc10 100644 --- a/apps/server/src/process/externalLauncher.ts +++ b/apps/server/src/process/externalLauncher.ts @@ -6,6 +6,7 @@ import { ExternalLauncherBrowserSpawnError, ExternalLauncherCommandNotFoundError, ExternalLauncherEditorSpawnError, + ExternalLauncherRevealTargetMissingError, ExternalLauncherUnknownEditorError, ExternalLauncherUnsupportedEditorError, ExternalLauncherUnsupportedTargetError, @@ -36,6 +37,7 @@ export { ExternalLauncherBrowserSpawnError, ExternalLauncherCommandNotFoundError, ExternalLauncherEditorSpawnError, + ExternalLauncherRevealTargetMissingError, ExternalLauncherUnknownEditorError, ExternalLauncherUnsupportedEditorError, ExternalLauncherUnsupportedTargetError, @@ -590,6 +592,13 @@ const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* ( } if (input.reveal === true) { + // Explorer answers /select of a missing path by opening its default folder, not the parent. + const exists = yield* (yield* FileSystem.FileSystem) + .exists(target) + .pipe(Effect.orElseSucceed(() => true)); + if (!exists) { + return yield* new ExternalLauncherRevealTargetMissingError({ editor: editorDef.id, target }); + } return yield* resolveFileManagerRevealLaunch(target, platform, env, command); } diff --git a/packages/contracts/src/editor.ts b/packages/contracts/src/editor.ts index 146007499d440..98a9c852b2554 100644 --- a/packages/contracts/src/editor.ts +++ b/packages/contracts/src/editor.ts @@ -305,6 +305,18 @@ export class ExternalLauncherUnsupportedTargetError extends Schema.TaggedError()( + "ExternalLauncherRevealTargetMissingError", + { + editor: EditorId, + target: Schema.String, + }, +) { + override get message(): string { + return `No file or folder exists at ${this.target}`; + } +} + const ExternalLauncherSpawnFields = { command: Schema.String, args: Schema.Array(Schema.String), @@ -341,6 +353,7 @@ export const ExternalLauncherError = Schema.Union([ ExternalLauncherUnsupportedEditorError, ExternalLauncherCommandNotFoundError, ExternalLauncherUnsupportedTargetError, + ExternalLauncherRevealTargetMissingError, ExternalLauncherBrowserSpawnError, ExternalLauncherEditorSpawnError, ]); From 90f0bac1913a379bf421576d6c051c5f3b83f2cc Mon Sep 17 00:00:00 2001 From: Navid Nadali Date: Sun, 22 Nov 2026 02:07:57 +0000 Subject: [PATCH 088/139] fix(server): a steer that missed its turn keeps its place in the queue (#40622) Co-authored-by: Julius Marminge --- .../src/orchestration-v2/EffectWorker.ts | 3 +- .../src/orchestration-v2/Orchestrator.ts | 11 +- .../SteeringCompletion.integration.test.ts | 181 +++++++++++------- 3 files changed, 115 insertions(+), 80 deletions(-) diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.ts index c637446d78827..6c805cfc4592f 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.ts @@ -390,8 +390,7 @@ export const layerExecutor: Layer.Layer< threadId: effect.threadId, messageId: message.id, ...(error.steerDeclined ? { steerFollowUpOfRunId: run.id } : {}), - ...(error.steerDeclined && - effect.request.steerFollowUpAfterRunOrdinal !== undefined + ...(effect.request.steerFollowUpAfterRunOrdinal !== undefined ? { steerFollowUpAfterRunOrdinal: effect.request.steerFollowUpAfterRunOrdinal, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index bcbe8a3656017..4f1d2d671060e 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -8073,10 +8073,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio command.creationSource === "provider" && !(yield* stopReachedRun(command, command.threadId, activeRun.id)); let steerFollowUpQueuePosition: number | undefined; - if ( - command.steerFollowUpOfRunId !== undefined && - command.steerFollowUpAfterRunOrdinal !== undefined - ) { + if (command.steerFollowUpAfterRunOrdinal !== undefined) { const afterRunOrdinal = command.steerFollowUpAfterRunOrdinal; const steerOrdinal = projection.turnItems.find( @@ -8237,7 +8234,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio runId: queued.id, providerInstanceId: queued.providerInstanceId, occurredAt: now, - payload: { ...queued, queuePosition: (queued.queuePosition ?? queued.ordinal) + 1 }, + payload: { + ...queued, + ...(heldRunsToRelease.includes(queued) ? { queueHeld: false } : {}), + queuePosition: (queued.queuePosition ?? queued.ordinal) + 1, + }, }); } } diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index dd2d95cfc1b81..04257d91bc9a7 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -1363,81 +1363,116 @@ it.effect("restarts the turn for an image when native steering takes text only", }), ); -it.effect("starts a steer that missed the turn on the saved next-turn selection", () => - Effect.gen(function* () { - const { events, started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness( - "steering-selection-follow-up", - ); - yield* Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; - const threadId = yield* startFirstTurn; - const first = started[0]!; - yield* orchestrator.dispatch({ - type: "message.dispatch", - commandId: CommandId.make("steer"), - threadId, - messageId: MessageId.make("message:steer"), - text: "late steer", - attachments: [], - modelSelection: composerSelection, - dispatchMode: { type: "steer_active", targetRunId: first.runId }, - createdBy: "user", - creationSource: "web", - }); - const settled = yield* orchestrator.streamDomainEvents.pipe( - Stream.filter( - (event) => - event.type === "run.updated" && - event.payload.id === first.runId && - event.payload.status === "waiting", - ), - Stream.take(1), - Stream.runDrain, - Effect.forkScoped, +it.effect.each(["complete", "stop-before-end"] as const)( + "starts a steer that missed the turn in its place on the saved next-turn selection: %s", + (timing) => + Effect.gen(function* () { + const { events, started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness( + `steering-selection-follow-up-${timing}`, ); - const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!; - yield* Queue.offer(events, { - type: "provider_turn.updated", - driver, - providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now }, - }); - yield* Queue.offer(events, { - type: "turn.terminal", - driver, - providerThreadId: turn.providerThreadId, - providerTurnId: turn.id, - runOrdinal: first.runOrdinal, - status: "completed", - failure: null, - threadDisposition: "reusable", - }); - yield* Fiber.join(settled); - yield* worker.drain(); - yield* orchestrator.resumeQueuedRuns; - yield* worker.drain(); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + const first = started[0]!; + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("steer"), + threadId, + messageId: MessageId.make("message:steer"), + text: "late steer", + attachments: [], + modelSelection: composerSelection, + dispatchMode: { type: "steer_active", targetRunId: first.runId }, + createdBy: "user", + creationSource: "web", + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("queued-later"), + threadId, + messageId: MessageId.make("message:queued-later"), + text: "queued later", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "user", + creationSource: "web", + }); + if (timing === "stop-before-end") { + yield* orchestrator.dispatch({ + type: "run.interrupt", + commandId: CommandId.make("stop"), + threadId, + runId: first.runId, + holdQueue: true, + }); + } + const settled = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => + event.type === "run.updated" && + event.payload.id === first.runId && + event.payload.status === "waiting", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!; + yield* Queue.offer(events, { + type: "provider_turn.updated", + driver, + providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now }, + }); + yield* Queue.offer(events, { + type: "turn.terminal", + driver, + providerThreadId: turn.providerThreadId, + providerTurnId: turn.id, + runOrdinal: first.runOrdinal, + status: "completed", + failure: null, + threadDisposition: "reusable", + }); + yield* Fiber.join(settled); + yield* worker.drain(); + if (timing === "stop-before-end") { + const queued = (yield* orchestrator.getThreadProjection(threadId)).runs + .filter((run) => run.status === "queued") + .toSorted((left, right) => (left.queuePosition ?? 0) - (right.queuePosition ?? 0)); + assert.deepEqual( + queued.map((run) => [run.userMessageId, run.queueHeld === true]), + [ + [MessageId.make("message:steer"), false], + [MessageId.make("message:queued-later"), false], + ], + ); + return; + } + yield* orchestrator.resumeQueuedRuns; + yield* worker.drain(); - const projection = yield* orchestrator.getThreadProjection(threadId); - assert.deepEqual(steered, []); - assert.equal(started.length, 2); - assert.equal(started[1]?.message.messageId, MessageId.make("message:steer")); - assert.deepEqual(started[1]?.modelSelection, composerSelection); - assert.deepEqual(projection.thread.modelSelection, composerSelection); - const message = projection.turnItems.find( - (item) => - item.type === "user_message" && item.messageId === MessageId.make("message:steer"), - ); - assert.equal(message?.runId, started[1]!.runId); - assert.isAbove( - message!.ordinal, - Math.max( - ...projection.turnItems - .filter((item) => item.runId === first.runId) - .map((item) => item.ordinal), - ), - ); - }).pipe(Effect.provide(layer)); - }), + const projection = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual(steered, []); + assert.equal(started.length, 2); + assert.equal(started[1]?.message.messageId, MessageId.make("message:steer")); + assert.deepEqual(started[1]?.modelSelection, composerSelection); + assert.deepEqual(projection.thread.modelSelection, composerSelection); + const message = projection.turnItems.find( + (item) => + item.type === "user_message" && item.messageId === MessageId.make("message:steer"), + ); + assert.equal(message?.runId, started[1]!.runId); + assert.isAbove( + message!.ordinal, + Math.max( + ...projection.turnItems + .filter((item) => item.runId === first.runId) + .map((item) => item.ordinal), + ), + ); + }).pipe(Effect.provide(layer)); + }), ); const declinedSteerTimings = [ From 3f08098c99711edc1f201ce53b3ffceb09a6ea3f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 19:08:53 -0800 Subject: [PATCH 089/139] fix(web): wrapped prompt suggestion no longer overlaps the composer toolbar (#40654) --- apps/web/src/components/ComposerPromptEditorTiptap.tsx | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index ab43b514ed3d9..c3fb7fad73ff8 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -1924,12 +1924,13 @@ function ComposerPromptEditorTiptapInner(
    { if ( event.key === "Control" || @@ -1974,7 +1975,7 @@ function ComposerPromptEditorTiptapInner( {isEmpty && contextRecords.size === 0 && placeholder ? (
    From 571b8697da2179883609fbdbc585c91b6f200a80 Mon Sep 17 00:00:00 2001 From: Guilherme Brasil Date: Sat, 21 Nov 2026 22:43:37 -0500 Subject: [PATCH 090/139] fix(server): refuse ref switches while a thread works in the shared checkout (#38271) Co-authored-by: Julius Marminge --- .../src/git/sharedCheckoutGuard.test.ts | 167 ++++++++++++++++++ apps/server/src/git/sharedCheckoutGuard.ts | 101 +++++++++++ apps/server/src/ws.ts | 36 ++-- docs/user/thread-sidebar.md | 3 +- 4 files changed, 292 insertions(+), 15 deletions(-) create mode 100644 apps/server/src/git/sharedCheckoutGuard.test.ts create mode 100644 apps/server/src/git/sharedCheckoutGuard.ts diff --git a/apps/server/src/git/sharedCheckoutGuard.test.ts b/apps/server/src/git/sharedCheckoutGuard.test.ts new file mode 100644 index 0000000000000..1723b29c10bb8 --- /dev/null +++ b/apps/server/src/git/sharedCheckoutGuard.test.ts @@ -0,0 +1,167 @@ +import { ProjectId, ThreadId } from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import * as GitWorkflowService from "./GitWorkflowService.ts"; +import { assertCheckoutIdle, busyThreadsInCheckout } from "./sharedCheckoutGuard.ts"; + +const projectId = ProjectId.make("project-a"); +const otherProjectId = ProjectId.make("project-b"); +const nestedProjectId = ProjectId.make("project-nested"); +const childRepositoryProjectId = ProjectId.make("project-child-repository"); + +const thread = ( + title: string, + overrides: { + readonly projectId?: ProjectId; + readonly worktreePath?: string | null; + readonly activityRunStatus?: "preparing" | "starting" | "running" | "waiting" | null; + readonly archived?: boolean; + } = {}, +) => ({ + archived: overrides.archived ?? false, + id: ThreadId.make(title), + title, + projectId: overrides.projectId ?? projectId, + worktreePath: overrides.worktreePath ?? null, + activityRunStatus: + overrides.activityRunStatus === undefined ? "running" : overrides.activityRunStatus, +}); + +describe("busyThreadsInCheckout", () => { + it("finds running local threads in the project root checkout", () => { + const busy = busyThreadsInCheckout({ + checkoutPaths: ["/repo"], + projectIds: new Set([projectId]), + threads: [ + thread("local running"), + thread("local idle", { activityRunStatus: null }), + thread("worktree running", { worktreePath: "/worktrees/a" }), + thread("other project", { projectId: otherProjectId }), + ], + }); + + expect(busy.map(({ title }) => title)).toEqual(["local running"]); + }); + + it("finds running threads that share a worktree", () => { + const busy = busyThreadsInCheckout({ + checkoutPaths: ["/worktrees/a"], + projectIds: new Set(), + threads: [ + thread("same worktree", { worktreePath: "/worktrees/a", activityRunStatus: "waiting" }), + thread("other worktree", { worktreePath: "/worktrees/b" }), + thread("local running"), + ], + }); + + expect(busy.map(({ title }) => title)).toEqual(["same worktree"]); + }); +}); + +describe("assertCheckoutIdle", () => { + const guardLayer = (input: { + readonly repositoryRoot: string; + readonly threads: ReadonlyArray>; + readonly failWorktreeLookup?: boolean; + }) => + Layer.mergeAll( + Layer.mock(GitWorkflowService.GitWorkflowService)({ + repositoryRoot: (cwd) => + Effect.succeed(cwd.startsWith("/repo/child") ? "/repo/child" : input.repositoryRoot), + }), + Layer.mock(ProjectService.ProjectService)({ + snapshot: Effect.succeed({ + projects: [ + { id: projectId, workspaceRoot: "/repo" }, + { id: nestedProjectId, workspaceRoot: "/repo/packages/app" }, + { id: childRepositoryProjectId, workspaceRoot: "/repo/child" }, + { id: otherProjectId, workspaceRoot: "/other" }, + ], + } as never), + }), + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getShellSnapshot: (options) => + options?.worktreePath !== undefined && input.failWorktreeLookup + ? Effect.fail("worktree lookup failed" as never) + : Effect.succeed( + (() => { + const matching = input.threads.filter( + (candidate) => + (options?.projectId === undefined || + candidate.projectId === options.projectId) && + (options?.worktreePath === undefined || + candidate.worktreePath === options.worktreePath), + ); + return { + threads: matching.filter((candidate) => !candidate.archived), + archivedThreads: matching.filter((candidate) => candidate.archived), + } as never; + })(), + ), + }), + ); + + it.effect("refuses a switch from a subdirectory of a busy checkout", () => + Effect.gen(function* () { + const error = yield* assertCheckoutIdle("test", "/repo/src").pipe( + Effect.flip, + Effect.provide(guardLayer({ repositoryRoot: "/repo", threads: [thread("local running")] })), + ); + expect(error.detail).toContain("'local running'"); + }), + ); + + it.effect("keeps a busy thread when another lookup fails", () => + Effect.gen(function* () { + const error = yield* assertCheckoutIdle("test", "/repo").pipe( + Effect.flip, + Effect.provide( + guardLayer({ + repositoryRoot: "/repo", + threads: [thread("local running")], + failWorktreeLookup: true, + }), + ), + ); + expect(error.detail).toContain("'local running'"); + }), + ); + + it.effect("refuses a switch while a nested project or archived thread is working", () => + Effect.gen(function* () { + const error = yield* assertCheckoutIdle("test", "/repo").pipe( + Effect.flip, + Effect.provide( + guardLayer({ + repositoryRoot: "/repo", + threads: [ + thread("nested running", { projectId: nestedProjectId }), + thread("archived running", { archived: true }), + thread("other running", { projectId: otherProjectId }), + thread("child repository running", { projectId: childRepositoryProjectId }), + ], + }), + ), + ); + // Exactly these two: a third busy thread would read "and 1 more". + expect(error.detail).toMatch( + /^'(nested|archived) running' and '(nested|archived) running' are still working/, + ); + }), + ); + + it.effect("allows a switch when no thread is working", () => + assertCheckoutIdle("test", "/repo").pipe( + Effect.provide( + guardLayer({ + repositoryRoot: "/repo", + threads: [thread("local idle", { activityRunStatus: null })], + }), + ), + ), + ); +}); diff --git a/apps/server/src/git/sharedCheckoutGuard.ts b/apps/server/src/git/sharedCheckoutGuard.ts new file mode 100644 index 0000000000000..442ef14dc71e9 --- /dev/null +++ b/apps/server/src/git/sharedCheckoutGuard.ts @@ -0,0 +1,101 @@ +import { + GitCommandError, + type OrchestrationV2ThreadShell, + type ProjectId, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; + +import * as GitWorkflowService from "./GitWorkflowService.ts"; +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import * as ProjectService from "../project/ProjectService.ts"; + +type CheckoutThread = Pick< + OrchestrationV2ThreadShell, + "id" | "title" | "projectId" | "worktreePath" | "activityRunStatus" +>; + +/** Threads with an active run whose working directory is one of `checkoutPaths`. */ +export function busyThreadsInCheckout(input: { + readonly checkoutPaths: ReadonlyArray; + readonly projectIds: ReadonlySet; + readonly threads: ReadonlyArray; +}): ReadonlyArray { + return input.threads.filter( + (thread) => + (thread.activityRunStatus ?? null) !== null && + (thread.worktreePath === null + ? input.projectIds.has(thread.projectId) + : input.checkoutPaths.includes(thread.worktreePath)), + ); +} + +function describeBusyCheckout(titles: ReadonlyArray): string { + const quoted = titles.map((title) => `'${title}'`); + const names = + quoted.length <= 2 + ? quoted.join(" and ") + : `${quoted.slice(0, 2).join(", ")} and ${quoted.length - 2} more`; + return `${names} ${quoted.length === 1 ? "is" : "are"} still working in this checkout. Wait for ${quoted.length === 1 ? "it" : "them"} to finish, or use a worktree for a separate branch.`; +} + +/** Switching a shared checkout's ref moves every thread working in it, mid-turn included. */ +export const assertCheckoutIdle = Effect.fn("sharedCheckoutGuard.assertCheckoutIdle")(function* ( + operation: string, + cwd: string, +) { + const gitWorkflow = yield* GitWorkflowService.GitWorkflowService; + const projectService = yield* ProjectService.ProjectService; + const threadManagement = yield* ThreadManagementService.ThreadManagementService; + // `git checkout` from a subdirectory moves the whole checkout; records may hold either spelling. + const root = yield* gitWorkflow.repositoryRoot(cwd).pipe(Effect.orElseSucceed(() => null)); + const checkoutPaths = [...new Set([cwd, ...(root === null ? [] : [root])])]; + const projects = yield* projectService.snapshot.pipe( + Effect.map((snapshot) => snapshot.projects), + Effect.orElseSucceed(() => []), + ); + // A project rooted inside the checkout shares it, as in a monorepo package, unless it is its + // own repository nested there. + const nested = yield* Effect.forEach( + projects.filter( + ({ workspaceRoot }) => + root !== null && + !checkoutPaths.includes(workspaceRoot) && + workspaceRoot.startsWith(`${root}/`), + ), + (project) => + gitWorkflow.repositoryRoot(project.workspaceRoot).pipe( + Effect.map((projectRoot) => (projectRoot === root ? [project] : [])), + Effect.orElseSucceed(() => []), + ), + { concurrency: "unbounded" }, + ); + const projectIds = new Set( + [ + ...projects.filter(({ workspaceRoot }) => checkoutPaths.includes(workspaceRoot)), + ...nested.flat(), + ].map(({ id }) => id), + ); + // Archiving does not stop a run, so archived threads can still be working. Each lookup fails + // open on its own, so one failure keeps what the others found. + const snapshots = yield* Effect.forEach( + [ + ...checkoutPaths.map((worktreePath) => threadManagement.getShellSnapshot({ worktreePath })), + ...[...projectIds].map((projectId) => threadManagement.getShellSnapshot({ projectId })), + ], + (snapshot) => snapshot.pipe(Effect.orElseSucceed(() => ({ threads: [], archivedThreads: [] }))), + { concurrency: "unbounded" }, + ); + const busy = busyThreadsInCheckout({ + checkoutPaths, + projectIds, + threads: snapshots.flatMap((snapshot) => [...snapshot.threads, ...snapshot.archivedThreads]), + }); + const titles = [...new Map(busy.map((thread) => [thread.id, thread.title])).values()]; + if (titles.length === 0) return; + return yield* new GitCommandError({ + operation, + command: "git checkout", + cwd, + detail: describeBusyCheckout(titles), + }); +}); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 90c264f5408ca..ddd07fcfad656 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -224,6 +224,7 @@ import * as WorkspacePaths from "./workspace/WorkspacePaths.ts"; import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts"; import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts"; import * as GitWorkflowService from "./git/GitWorkflowService.ts"; +import { assertCheckoutIdle } from "./git/sharedCheckoutGuard.ts"; import { refreshPushedPullRequests } from "./git/refreshPushedPullRequests.ts"; import { linkCreatedPullRequest } from "./git/linkCreatedPullRequest.ts"; import * as ReviewService from "./review/ReviewService.ts"; @@ -3264,9 +3265,13 @@ export const layerWsRpc = ( ), [WS_METHODS.gitResolvePullRequest]: (input) => gitWorkflow.resolvePullRequest(input), [WS_METHODS.gitPreparePullRequestThread]: (input) => - gitWorkflow - .preparePullRequestThread(input) - .pipe(Effect.tap(() => refreshGitStatus(input.cwd))), + (input.mode === "local" + ? assertCheckoutIdle("GitWorkflowService.preparePullRequestThread", input.cwd) + : Effect.void + ).pipe( + Effect.andThen(gitWorkflow.preparePullRequestThread(input)), + Effect.tap(() => refreshGitStatus(input.cwd)), + ), [WS_METHODS.vcsListRefs]: (input) => gitWorkflow.listRefs(input), [WS_METHODS.vcsCreateWorktree]: (input) => // A project that tracks repositories gets a task folder, as its new worktree threads do. @@ -3311,19 +3316,22 @@ export const layerWsRpc = ( ), ), [WS_METHODS.vcsCreateRef]: (input) => - gitWorkflow - .createRef(input) - .pipe( - Effect.tap(() => - input.switchRef - ? vcsStatusBroadcaster.refreshAfterCheckout(input.cwd) - : refreshGitStatus(input.cwd), - ), + (input.switchRef + ? assertCheckoutIdle("GitWorkflowService.createRef", input.cwd) + : Effect.void + ).pipe( + Effect.andThen(gitWorkflow.createRef(input)), + Effect.tap(() => + input.switchRef + ? vcsStatusBroadcaster.refreshAfterCheckout(input.cwd) + : refreshGitStatus(input.cwd), ), + ), [WS_METHODS.vcsSwitchRef]: (input) => - gitWorkflow - .switchRef(input) - .pipe(Effect.tap(() => vcsStatusBroadcaster.refreshAfterCheckout(input.cwd))), + assertCheckoutIdle("GitWorkflowService.switchRef", input.cwd).pipe( + Effect.andThen(gitWorkflow.switchRef(input)), + Effect.tap(() => vcsStatusBroadcaster.refreshAfterCheckout(input.cwd)), + ), [WS_METHODS.vcsInit]: (input) => vcsProvisioning.initRepository(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), [WS_METHODS.reviewGetBranchCommits]: (input) => review.getBranchCommits(input), diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index f58f35feb45f5..9bbf3194a9d59 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -1,7 +1,8 @@ # Working with threads Use a new thread for a separate task. Choose **New worktree** when its code changes -need a separate branch and working directory. +need a separate branch and working directory. Threads in the same checkout share its +branch, so T3 Code refuses a branch switch there while one of them is working. ## Start a thread From c7a9fba06bdb143bd380e610487a46c9e96f35cc Mon Sep 17 00:00:00 2001 From: TheGuyWithHAT Date: Sun, 22 Nov 2026 04:45:59 +0100 Subject: [PATCH 091/139] fix(server): label speaker notes in OpenDocument attachments (#38542) Co-authored-by: Geezy Co-authored-by: Julius Marminge --- .../server/src/provider/documentTextWorker.ts | 20 ++++++++++++++++--- .../src/provider/userInputAttachments.test.ts | 15 ++++++++++++-- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index e254e101cf93e..3dd649811f330 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -115,7 +115,10 @@ function xml(source: string, extension: string): XmlNode { if (odf && (node.name === "p" || node.name === "h")) collapseOdfWhitespace(node); if ( (extension === ".docx" && node.name === "del") || - (odf && node.name === "annotation" && parent.name !== "semantics") + (odf && node.name === "annotation" && parent.name !== "semantics") || + (extension === ".odp" && + node.name === "page-thumbnail" && + stack.some((ancestor) => ancestor.name === "notes")) ) { parent.children.pop(); return; @@ -621,8 +624,19 @@ async function* document(path: string, extension: string): AsyncGenerator child.name === "notes"); + yield* paragraphs({ + ...part, + children: part.children.filter((child) => child !== notes), + }); + if (notes && hasCellText(notes)) { + yield "\nNotes:\n"; + yield* paragraphs(notes); + } } } } else if (extension === ".xlsx") { diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index b107188136a3d..72f7e52a3cd41 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -1139,9 +1139,20 @@ describe("question answer paths", () => { ext: "odp", parts: { "content.xml": - "\n First\n\t slide Second", + "" + + "\n First\n\t slide " + + "Overview" + + "Speaker only" + + "Second" + + "Slide previewThumbnail metadata" + + "" + + "Third" + + '' + + "", }, - expected: ["## Slide 1\nFirst slide\n\n## Slide 2\nSecond"], + expected: [ + "## Slide 1\nFirst slide\nOverview\nNotes:\nSpeaker only\n\n## Slide 2\nSecond\n\n## Slide 3\nThird\n\nNotes:\n42", + ], }, { ext: "ods", From f9b19a7f855b7e10f057cab6b4bc17ea43188623 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 20:14:30 -0800 Subject: [PATCH 092/139] fix(server): folder discovery skips the walk when t3.json ignores the whole project (#40664) --- .../src/workspace/WorkspaceFolders.test.ts | 37 +++++++++++++++++++ apps/server/src/workspace/WorkspaceFolders.ts | 12 +++--- 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/apps/server/src/workspace/WorkspaceFolders.test.ts b/apps/server/src/workspace/WorkspaceFolders.test.ts index 61dac26a8c044..4c5b33bbf7776 100644 --- a/apps/server/src/workspace/WorkspaceFolders.test.ts +++ b/apps/server/src/workspace/WorkspaceFolders.test.ts @@ -193,6 +193,43 @@ it.layer(NodeServices.layer)("WorkspaceFolders", (it) => { }), ); + it.effect("does not walk a project's folders when t3.json ignores the whole project", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const workspaceRoot = yield* makeTempDir; + for (const folder of ["api/.git", "src/web/.git", "notes"]) { + yield* fileSystem.makeDirectory(path.join(workspaceRoot, folder), { recursive: true }); + } + yield* fileSystem.writeFileString( + path.join(workspaceRoot, "t3.json"), + JSON.stringify({ ignoreRepositories: ["."] }), + ); + const probed: Array = []; + const counting = FileSystem.FileSystem.of({ + ...fileSystem, + readDirectory: (target, options) => { + probed.push(target); + return fileSystem.readDirectory(target, options); + }, + stat: (target) => { + probed.push(target); + return fileSystem.stat(target); + }, + }); + + const found = yield* WorkspaceFolders.discoverFolders(workspaceRoot).pipe( + Effect.provideService(FileSystem.FileSystem, counting), + ); + + assert.deepEqual(found, []); + assert.deepEqual( + probed.filter((target) => target !== workspaceRoot), + [], + ); + }), + ); + it.effect("keeps the folders someone added when a project holds more than fit", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/server/src/workspace/WorkspaceFolders.ts b/apps/server/src/workspace/WorkspaceFolders.ts index 776f90ea6e5b0..9b21fd3fbcc62 100644 --- a/apps/server/src/workspace/WorkspaceFolders.ts +++ b/apps/server/src/workspace/WorkspaceFolders.ts @@ -276,11 +276,7 @@ export const discoverFolders = Effect.fn("WorkspaceFolders.discover")(function* const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const { realPath, ownsHistory } = yield* folderProbes; - // Uncapped: the folders outside the project are dropped below, and must not use up the room. - const scan = yield* scanFolders({ workspaceRoot }, Number.POSITIVE_INFINITY).pipe(Effect.option); - if (Option.isNone(scan)) return []; - const root = scan.value.workspaceRoot; - const realRoot = yield* realPath(root); + const root = path.resolve(expandHomePath(workspaceRoot.trim(), yield* HostProcess.HomeDirectory)); const ignored = ( parseT3ProjectFile( yield* fileSystem @@ -288,6 +284,12 @@ export const discoverFolders = Effect.fn("WorkspaceFolders.discover")(function* .pipe(Effect.orElseSucceed(() => "")), )?.ignoreRepositories ?? [] ).map((entry) => path.resolve(root, entry)); + // Everything the scan could find would be dropped, so skip the walk. + if (ignored.some((entry) => isWithinRoot(path, root, entry))) return []; + // Uncapped: the folders outside the project are dropped below, and must not use up the room. + const scan = yield* scanFolders({ workspaceRoot }, Number.POSITIVE_INFINITY).pipe(Effect.option); + if (Option.isNone(scan)) return []; + const realRoot = yield* realPath(root); const inside = yield* Effect.filter( scan.value.folders.filter( (folder) => From 28a420060b321ce3317f8529a5db5138af97c189 Mon Sep 17 00:00:00 2001 From: Sudharsan <126713117+Sidreyas@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:06:26 +0530 Subject: [PATCH 093/139] fix(server): checkpoint repository scopes walk the project folder once per turn (#40671) Co-authored-by: Julius Marminge --- .../src/orchestration-v2/CheckpointService.ts | 9 ++++---- .../src/workspace/WorkspaceFolders.test.ts | 22 +++++++++++-------- apps/server/src/workspace/WorkspaceFolders.ts | 5 +++-- 3 files changed, 21 insertions(+), 15 deletions(-) diff --git a/apps/server/src/orchestration-v2/CheckpointService.ts b/apps/server/src/orchestration-v2/CheckpointService.ts index 079ac88211870..ec3e872d61c2b 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.ts @@ -924,10 +924,11 @@ export const layer: Layer.Layer< const repositoryScopesIfReadable: CheckpointServiceV2Shape["repositoryScopesIfReadable"] = Effect.fn("CheckpointService.repositoryScopes")( function* (input) { - const [workspace, submodules] = yield* Effect.all([ - workspaceFolders.forThread(input), - workspaceFolders.submodules(input), - ]); + const workspace = yield* workspaceFolders.forThread(input); + const submodules = yield* workspaceFolders.submodules({ + ...input, + folders: workspace.folders, + }); return yield* Effect.forEach( [...workspace.folders.filter((folder) => folder.isGitRepository), ...submodules], (folder) => diff --git a/apps/server/src/workspace/WorkspaceFolders.test.ts b/apps/server/src/workspace/WorkspaceFolders.test.ts index 4c5b33bbf7776..3a02d202be891 100644 --- a/apps/server/src/workspace/WorkspaceFolders.test.ts +++ b/apps/server/src/workspace/WorkspaceFolders.test.ts @@ -330,17 +330,21 @@ it.layer(NodeServices.layer)("WorkspaceFolders", (it) => { folders: [], extraRoots: [], }); - assert.deepEqual(yield* workspaceFolders.submodules({ projectId, worktreePath: null }), [ - { name: "lib", path: path.join(workspaceRoot, "vendor", "lib"), isGitRepository: true }, - { - name: "deep", - path: path.join(workspaceRoot, "vendor", "lib", "deep"), - isGitRepository: true, - }, - ]); + const { folders } = yield* workspaceFolders.forThread({ projectId, worktreePath: null }); + assert.deepEqual( + yield* workspaceFolders.submodules({ projectId, worktreePath: null, folders }), + [ + { name: "lib", path: path.join(workspaceRoot, "vendor", "lib"), isGitRepository: true }, + { + name: "deep", + path: path.join(workspaceRoot, "vendor", "lib", "deep"), + isGitRepository: true, + }, + ], + ); // A worktree reaches its own submodules, named by where the project folder has them. assert.deepEqual( - yield* workspaceFolders.submodules({ projectId, worktreePath: worktree }), + yield* workspaceFolders.submodules({ projectId, worktreePath: worktree, folders: [] }), [ { name: "lib", diff --git a/apps/server/src/workspace/WorkspaceFolders.ts b/apps/server/src/workspace/WorkspaceFolders.ts index 9b21fd3fbcc62..0824c647ce360 100644 --- a/apps/server/src/workspace/WorkspaceFolders.ts +++ b/apps/server/src/workspace/WorkspaceFolders.ts @@ -64,6 +64,8 @@ export class WorkspaceFolders extends Context.Service< readonly submodules: (input: { readonly projectId: ProjectId; readonly worktreePath: string | null; + /** The thread's `forThread` folders; passed in so the project is walked once. */ + readonly folders: ReadonlyArray; }) => Effect.Effect, WorkspaceFoldersError>; readonly list: ( input: WorkspaceListFoldersInput, @@ -508,7 +510,6 @@ const make = Effect.gen(function* () { const submodules: WorkspaceFolders["Service"]["submodules"] = Effect.fn( "WorkspaceFolders.submodules", )(function* (input) { - const { folders } = yield* forThread(input); // A worktree can outlive its project record; its submodules are then named by where they are. const projectRoot = yield* readProject(input.projectId).pipe( Effect.map((project) => path.resolve(project.workspaceRoot)), @@ -520,7 +521,7 @@ const make = Effect.gen(function* () { const identity = Option.getOrElse(projectRoot, () => root); return yield* submodulesOf([ { path: root, identity }, - ...folders.flatMap((folder) => + ...input.folders.flatMap((folder) => folder.isGitRepository ? [{ path: folder.path, identity: folder.repositoryPath ?? folder.path }] : [], From c5fa33b27e45ca48fea7b4e12337b8560845f3db Mon Sep 17 00:00:00 2001 From: MIT-Consulting Date: Sun, 22 Nov 2026 00:42:40 -0500 Subject: [PATCH 094/139] fix(server,cursor): preserve inline handoff when a failed Cursor turn drops its prompt (#40670) Co-authored-by: Julius Marminge --- .../ContextHandoffDelivery.ts | 10 +- .../src/orchestration-v2/Orchestrator.ts | 5 +- .../ProviderTurnStartService.ts | 103 +++++++--- .../orchestration-v2/RestartBackgroundNote.ts | 35 ++-- .../RunExecutionService.test.ts | 48 +++++ .../orchestration-v2/RunExecutionService.ts | 192 ++++++++++++------ .../ProviderSwitch.integration.test.ts | 169 +++++++++++++++ packages/contracts/src/orchestrationV2.ts | 8 + .../src/server/ProviderAdapter.ts | 4 + .../src/server/adapter.test.ts | 143 +++++++++++++ .../provider-cursor/src/server/adapter.ts | 14 ++ .../orchestrationV2ManualContinuation.test.ts | 12 ++ .../src/orchestrationV2ManualContinuation.ts | 10 +- 13 files changed, 634 insertions(+), 119 deletions(-) diff --git a/apps/server/src/orchestration-v2/ContextHandoffDelivery.ts b/apps/server/src/orchestration-v2/ContextHandoffDelivery.ts index 5211da2faf169..72471eb8cf944 100644 --- a/apps/server/src/orchestration-v2/ContextHandoffDelivery.ts +++ b/apps/server/src/orchestration-v2/ContextHandoffDelivery.ts @@ -37,7 +37,7 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH handoff.delivery.status === "pending", ); if (pending.length === 0 || (input.deferInline && input.inject === undefined)) - return { context: "", delivered: Effect.void, unsent: Effect.void }; + return { context: "", delivered: Effect.void, unsent: Effect.void, inlineHandoffs: [] }; const budget = typeof input.budget === "number" ? input.budget : yield* input.budget; let coverage = pending .map( @@ -76,7 +76,8 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH budget, }); if (historyCost(selected.messages, selected.context) > budget) { - if (input.deferInline) return { context: "", delivered: Effect.void, unsent: Effect.void }; + if (input.deferInline) + return { context: "", delivered: Effect.void, unsent: Effect.void, inlineHandoffs: [] }; return yield* new ContextHandoffBudgetError(); } const omittedItemIds = new Set(selected.omittedItemIds); @@ -127,7 +128,7 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH }); if (injected) { yield* persist("injected"); - return { context: "", delivered: Effect.void, unsent: Effect.void }; + return { context: "", delivered: Effect.void, unsent: Effect.void, inlineHandoffs: [] }; } } else { yield* persist("pending"); @@ -135,12 +136,13 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH if (input.deferInline) { // Compaction cannot carry inline transcripts; retain for the next turn if native injection is unsupported. yield* Effect.forEach(pending, input.persist, { discard: true }); - return { context: "", delivered: Effect.void, unsent: Effect.void }; + return { context: "", delivered: Effect.void, unsent: Effect.void, inlineHandoffs: [] }; } return { context: renderHistory(selected.messages, selected.context), delivered: persist("inline"), unsent: Effect.forEach(pending, input.persist, { discard: true }), + inlineHandoffs: pending, }; }, ); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 4f1d2d671060e..995ff63b25747 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -28,6 +28,7 @@ import { CommandId, type GuestMessageId, isCompactionCommandMessage, + isDeliveredProviderTurn, isOrchestrationV2WorkActive, isProviderNativeSubagentThread, MessageId, @@ -1599,7 +1600,9 @@ function lastDeliveredRunForProviderThread( isHandoffSourceRun(run) && run.providerThreadId === providerThreadId && (run.status === "completed" || - projection.providerTurns.some((turn) => turn.runAttemptId === run.activeAttemptId)), + projection.providerTurns.some( + (turn) => turn.runAttemptId === run.activeAttemptId && isDeliveredProviderTurn(turn), + )), ); } diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index e47e88eda09a0..8e35271ce5aa9 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -16,6 +16,7 @@ import { type OrchestrationV2ThreadProjection, type OrchestrationV2TurnItem, isCompactionCommandMessage, + isDeliveredProviderTurn, parseGoalCommand, RunId, RunAttemptId, @@ -32,6 +33,7 @@ import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Predicate from "effect/Predicate"; import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; import * as ServerConfig from "../config.ts"; import { @@ -173,7 +175,9 @@ const nativeSessionMissesKeptTurns = ( ): boolean => { const nativeId = providerThread.nativeThreadRef?.nativeId; if (nativeId === undefined) return false; - const acceptedAttemptIds = new Set(projection.providerTurns.map((turn) => turn.runAttemptId)); + const acceptedAttemptIds = new Set( + projection.providerTurns.filter(isDeliveredProviderTurn).map((turn) => turn.runAttemptId), + ); const accepted = projection.attempts.filter((attempt) => acceptedAttemptIds.has(attempt.id)); const runsById = new Map(projection.runs.map((source) => [source.id, source])); const ordinalOf = (attempt: OrchestrationV2RunAttempt) => @@ -1087,7 +1091,12 @@ export const layer: Layer.Layer< ...settledHandoffs.flatMap((handoff) => handoff.delivery?.omittedItemIds ?? []), ]); const deliveredAttemptIds = new Set( - projection.providerTurns.map((turn) => turn.runAttemptId), + projection.providerTurns.filter(isDeliveredProviderTurn).map((turn) => turn.runAttemptId), + ); + const droppedAttemptIds = new Set( + projection.providerTurns + .filter((turn) => !isDeliveredProviderTurn(turn)) + .map((turn) => turn.runAttemptId), ); const acceptedAttempts = projection.attempts.filter( (source) => @@ -1159,7 +1168,9 @@ export const layer: Layer.Layer< (source) => source.ordinal < run.ordinal && source.providerThreadId === providerThread.id && - (source.status === "failed" || source.status === "interrupted") && + (source.status === "failed" || + source.status === "interrupted" || + (source.status === "cancelled" && droppedAttemptIds.has(source.activeAttemptId))) && !deliveredAttemptIds.has(source.activeAttemptId), ); const missedRunIds = new Set(missedRuns.map((source) => source.id)); @@ -1536,7 +1547,9 @@ export const layer: Layer.Layer< const rejectedHistory = yield* Effect.gen(function* () { if (session.driver !== "codex") return false; const acceptedAttemptIds = new Set( - projection.providerTurns.map((turn) => turn.runAttemptId), + projection.providerTurns + .filter(isDeliveredProviderTurn) + .map((turn) => turn.runAttemptId), ); const previous = projection.runs.findLast( (source) => @@ -1605,7 +1618,9 @@ export const layer: Layer.Layer< // Dispatch prepares no import handoff for a session import: its history is in the native session. const importedNativeSession = projection.thread.historyOrigin === "v1_import" && - !projection.providerTurns.some((turn) => turn.providerThreadId === providerThread.id) && + !projection.providerTurns.some( + (turn) => turn.providerThreadId === providerThread.id && isDeliveredProviderTurn(turn), + ) && !projection.contextHandoffs.some( (handoff) => handoff.toProviderThreadId === providerThread.id && @@ -2025,6 +2040,10 @@ export const layer: Layer.Layer< ], }); }); + let inlineDeliveredHandoffs: ReadonlyArray = []; + let promptDroppedOnTerminal = false; + const inlineDeliveryLock = yield* Semaphore.make(1); + const retryHandoffIds = new Set(retryHandoff.handoffs.map((handoff) => handoff.id)); const startWithHandoffs = Effect.fn("ProviderTurnStartService.startWithHandoffs")( function* (turnInput: Parameters[0], compact = false) { const delivery = yield* deliverContextHandoffs({ @@ -2051,6 +2070,15 @@ export const layer: Layer.Layer< sideChatHandoff === undefined || compact || goalCommand ? "" : sideChatHandoff.summaryText; + // Record inline handoffs before startTurn so an immediate dropped terminal can restore them. + inlineDeliveredHandoffs = [ + ...delivery.inlineHandoffs.map((handoff) => + retryHandoffIds.has(handoff.id) + ? { ...handoff, status: "superseded" as const } + : handoff, + ), + ...(sideChatContext === "" || sideChatHandoff === undefined ? [] : [sideChatHandoff]), + ]; const context = [delivery.context, sideChatContext, restartNote] .filter((part) => part !== "") .join("\n\n"); @@ -2101,31 +2129,39 @@ export const layer: Layer.Layer< : Effect.void, ), ); - // After provider acceptance, failed delivery bookkeeping must not stop live ingestion. - const nativeThreadId = runningProviderThread.nativeThreadRef?.nativeId; - yield* Effect.forEach( - [ - delivery.delivered, - ...(sideChatContext === "" || sideChatHandoff === undefined || nativeThreadId == null - ? [] - : [ - persistHandoff({ - ...sideChatHandoff, - toProviderThreadId: runningProviderThread.id, - delivery: { nativeThreadId, status: "inline" as const, itemIds: [] }, - }), - ]), - ], - (record) => - record.pipe( - Effect.catchCause(() => - Effect.logWarning("Failed to record accepted context handoff delivery", { - runId: run.id, - deliveryStatus: "pending", - }), - ), - ), - { discard: true }, + // Serialize acceptance writes against dropped-terminal restoration so neither overwrites the other. + yield* inlineDeliveryLock.withPermits(1)( + Effect.gen(function* () { + if (promptDroppedOnTerminal) return; + // After provider acceptance, failed delivery bookkeeping must not stop live ingestion. + const nativeThreadId = runningProviderThread.nativeThreadRef?.nativeId; + yield* Effect.forEach( + [ + delivery.delivered, + ...(sideChatContext === "" || + sideChatHandoff === undefined || + nativeThreadId == null + ? [] + : [ + persistHandoff({ + ...sideChatHandoff, + toProviderThreadId: runningProviderThread.id, + delivery: { nativeThreadId, status: "inline" as const, itemIds: [] }, + }), + ]), + ], + (record) => + record.pipe( + Effect.catchCause(() => + Effect.logWarning("Failed to record accepted context handoff delivery", { + runId: run.id, + deliveryStatus: "pending", + }), + ), + ), + { discard: true }, + ); + }), ); }, Effect.mapError((cause) => @@ -2186,6 +2222,13 @@ export const layer: Layer.Layer< hasUnpairedRunInterruptRequest: runControls.hasUnpairedRunInterruptRequest, loadRunInterruptReason: runControls.loadRunInterruptReason, hasWorkspaceMoved: runControls.hasWorkspaceMoved, + loadDroppedInlineHandoffs: () => + inlineDeliveryLock.withPermits(1)( + Effect.sync(() => { + promptDroppedOnTerminal = true; + return inlineDeliveredHandoffs; + }), + ), loadUnsettledWork: runControls.loadUnsettledWork, message: { messageId: message.id, diff --git a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts index ceaf2fd5de54b..58918bdef612d 100644 --- a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts +++ b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts @@ -1,14 +1,15 @@ -import type { - NodeId, - OrchestrationV2ConversationMessage, - OrchestrationV2PendingBackgroundTask, - OrchestrationV2ProviderThread, - OrchestrationV2ProviderTurn, - OrchestrationV2RestartCancelledBackgroundWork, - OrchestrationV2Run, - OrchestrationV2RunAttempt, - OrchestrationV2Subagent, - OrchestrationV2TurnItem, +import { + isDeliveredProviderTurn, + type NodeId, + type OrchestrationV2ConversationMessage, + type OrchestrationV2PendingBackgroundTask, + type OrchestrationV2ProviderThread, + type OrchestrationV2ProviderTurn, + type OrchestrationV2RestartCancelledBackgroundWork, + type OrchestrationV2Run, + type OrchestrationV2RunAttempt, + type OrchestrationV2Subagent, + type OrchestrationV2TurnItem, } from "@t3tools/contracts"; import { subagentHoldsCompletion } from "@t3tools/provider-core/server/subagentProjection"; import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; @@ -151,7 +152,7 @@ export function restartCancelledBackgroundWorkNote( type ProviderTurnState = Pick< OrchestrationV2ProviderTurn, - "runAttemptId" | "providerThreadId" | "status" + "runAttemptId" | "providerThreadId" | "status" | "promptDropped" >; export function isRestartNoteSource( @@ -307,12 +308,14 @@ export function delegatedTaskResultRun( /** The provider never accepted this continuation's prompt, so starting it again repeats nothing. */ export function continuationFailedBeforePrompt( run: Pick, - providerTurns: ReadonlyArray>, + providerTurns: ReadonlyArray>, ): boolean { return ( run.status === "failed" && run.restartContinuationOfRunId !== undefined && - !providerTurns.some((turn) => turn.runAttemptId === run.activeAttemptId) + !providerTurns.some( + (turn) => turn.runAttemptId === run.activeAttemptId && isDeliveredProviderTurn(turn), + ) ); } @@ -323,7 +326,9 @@ export function continuationStartRetryDelayMs( run: OrchestrationV2Run, projection: { readonly runs: ReadonlyArray; - readonly providerTurns: ReadonlyArray>; + readonly providerTurns: ReadonlyArray< + Pick + >; readonly turnItems: Parameters[1]; }, ): number | undefined { diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.ts index a23a3fdf87bff..1d13620b75623 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts @@ -8,6 +8,7 @@ import { NodeId, type OrchestrationV2AppThread, type OrchestrationV2CheckpointScope, + type OrchestrationV2ContextHandoff, type OrchestrationV2DomainEvent, type OrchestrationV2ExecutionNode, type OrchestrationV2PendingBackgroundTask, @@ -3702,6 +3703,49 @@ it.effect.each([ }), ); +it.effect("restores dropped inline handoffs when ingestion fails before the terminal", () => + Effect.gen(function* () { + const key = "dropped-turn-ingest-error"; + const ids = backgroundScenarioIds(key); + const handoff = { id: `handoff:${key}` } as unknown as OrchestrationV2ContextHandoff; + const { finalEvents } = yield* captureRootRunTermination({ + key, + shouldFinalizeRun: () => Effect.succeed(true), + loadDroppedInlineHandoffs: () => Effect.succeed([handoff]), + events: () => + Stream.make({ + type: "provider_turn.updated" as const, + driver, + threadId: ids.threadId, + providerTurn: { + id: ids.rootProviderTurnId, + providerThreadId: ids.providerThreadId, + runAttemptId: ids.attemptId, + ordinal: 1, + status: "failed", + promptDropped: true, + } as OrchestrationV2ProviderTurn, + }), + ingestNormalized: ({ event }) => + event.type === "provider_turn.updated" + ? Effect.fail( + new ProviderEventIngestor.ProviderEventPublishError({ + providerSessionId: ProviderSessionId.make(`session:${key}`), + eventCount: 1, + cause: new Error("SQLITE_FULL: database or disk is full"), + }), + ) + : Effect.succeed([]), + }); + assert.deepEqual( + finalEvents.flatMap((event) => + event.type === "context-handoff.updated" ? [event.payload.id] : [], + ), + [handoff.id], + ); + }), +); + it.effect("does not interrupt a provider when ingestion fails before the root turn is known", () => Effect.gen(function* () { const interrupts = yield* Ref.make(0); @@ -3989,6 +4033,7 @@ function captureRootRunTermination(input: { readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect; readonly hasWorkspaceMoved?: () => Effect.Effect; readonly loadRunInterruptReason?: () => Effect.Effect; + readonly loadDroppedInlineHandoffs?: RunExecutionService.RunExecutionServiceV2StartRootRunInput["loadDroppedInlineHandoffs"]; readonly hasPendingBackgroundWorkForThread?: ProviderAdapter.ProviderAdapterV2SessionRuntime["hasPendingBackgroundWorkForThread"]; readonly seedOpenSubagent?: boolean; readonly events?: ( @@ -4235,6 +4280,9 @@ function captureRootRunTermination(input: { ...(input.hasWorkspaceMoved === undefined ? {} : { hasWorkspaceMoved: input.hasWorkspaceMoved }), + ...(input.loadDroppedInlineHandoffs === undefined + ? {} + : { loadDroppedInlineHandoffs: input.loadDroppedInlineHandoffs }), message: { messageId: MessageId.make(`message:${input.key}`), text: input.messageText ?? "interrupt projection", diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index 1bc83f639d5ae..34cc31f98fa09 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -9,6 +9,7 @@ import { type NodeId, type OrchestrationV2AppThread, type OrchestrationV2CheckpointScope, + type OrchestrationV2ContextHandoff, type OrchestrationV2DomainEvent, type OrchestrationV2ExecutionNode, type OrchestrationV2ProviderFailure, @@ -658,6 +659,11 @@ export interface RunExecutionServiceV2StartRootRunInput { readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect; readonly loadRunInterruptReason?: () => Effect.Effect; readonly hasWorkspaceMoved?: () => Effect.Effect; + /** Restores inline context handoffs if the provider drops this turn's prompt before persisting it. */ + readonly loadDroppedInlineHandoffs?: () => Effect.Effect< + ReadonlyArray, + never + >; /** * Stored rows of a thread's unsettled work. Work a dead runtime left is ended from these, since * Stop may have settled it after the snapshots this run holds. @@ -736,6 +742,7 @@ export const layer: Layer.Layer< readonly abandonedProviderTurn?: OrchestrationV2ProviderTurn; // Stored root tool calls still open when the provider runtime was lost; nothing else ends them. readonly lostToolCalls?: ReadonlyArray; + readonly restoredHandoffs?: ReadonlyArray; readonly terminal: ProviderTerminalEvent; readonly completedAt?: DateTime.Utc; readonly failureItemPersisted: boolean; @@ -752,24 +759,35 @@ export const layer: Layer.Layer< status: input.terminal.status, completedAt, }; + const allocateEventId = () => idAllocator.allocate.event({ threadId: input.run.threadId }); + const buildRestoredHandoffEvents = () => + input.terminal.promptDropped === true && + input.restoredHandoffs !== undefined && + input.restoredHandoffs.length > 0 + ? Effect.forEach(input.restoredHandoffs, (handoff) => + Effect.map(allocateEventId(), (id) => ({ + id, + type: "context-handoff.updated" as const, + threadId: input.run.threadId, + runId: input.run.id, + providerInstanceId: input.run.providerInstanceId, + occurredAt: completedAt, + payload: { ...handoff, updatedAt: completedAt }, + })), + ) + : Effect.succeed([]); const shouldFinalizeRun = input.shouldFinalizeRun === undefined ? true : yield* input.shouldFinalizeRun(); if (!shouldFinalizeRun) { - if (input.terminal.status === "interrupted") { - const hasUnpairedRequest = - input.hasUnpairedRunInterruptRequest === undefined - ? false - : yield* input.hasUnpairedRunInterruptRequest(); - if (hasUnpairedRequest) { - const reason = - input.loadRunInterruptReason === undefined - ? undefined - : yield* input.loadRunInterruptReason(); - yield* eventSink.writeWithEffects({ - effects: [], - events: [ + const restoredHandoffEvents = yield* buildRestoredHandoffEvents(); + const unpairedInterruptEvents = + input.terminal.status === "interrupted" && + (input.hasUnpairedRunInterruptRequest === undefined + ? false + : yield* input.hasUnpairedRunInterruptRequest()) + ? [ { - id: yield* idAllocator.allocate.event({ threadId: input.run.threadId }), + id: yield* allocateEventId(), type: "turn-item.updated" as const, threadId: input.run.threadId, runId: input.run.id, @@ -781,18 +799,25 @@ export const layer: Layer.Layer< run: input.run, rootNode: input.rootNode, providerThread: input.providerThread, - reason, + reason: + input.loadRunInterruptReason === undefined + ? undefined + : yield* input.loadRunInterruptReason(), completedAt, }), }, - ], - }); - yield* input.refreshAfterTurn; - } + ] + : []; + const earlyEvents = [...unpairedInterruptEvents, ...restoredHandoffEvents]; + if (earlyEvents.length > 0) { + yield* eventSink.writeWithEffects({ + effects: [], + events: earlyEvents, + }); + yield* input.refreshAfterTurn; } return false; } - const allocateEventId = () => idAllocator.allocate.event({ threadId: input.run.threadId }); const reason = input.terminal.status === "interrupted" ? ((input.loadRunInterruptReason === undefined @@ -839,6 +864,7 @@ export const layer: Layer.Layer< status: finalProviderThreadStatus(input.terminal.threadDisposition), updatedAt: completedAt, }; + const restoredHandoffEvents = yield* buildRestoredHandoffEvents(); const runEventId = yield* allocateEventId(); const nodeEventId = yield* allocateEventId(); const providerThreadEventId = yield* allocateEventId(); @@ -1005,6 +1031,7 @@ export const layer: Layer.Layer< occurredAt: completedAt, payload: finalizedProviderThread, }, + ...restoredHandoffEvents, ], } satisfies Parameters[0]; if (input.writeIfRunCurrent !== undefined) { @@ -1031,6 +1058,13 @@ export const layer: Layer.Layer< effects: finalization.effects, }); if (!result.committed) { + if (restoredHandoffEvents.length > 0) { + yield* eventSink.writeWithEffects({ + effects: [], + events: restoredHandoffEvents, + }); + yield* input.refreshAfterTurn; + } return false; } } else { @@ -1275,44 +1309,55 @@ export const layer: Layer.Layer< } const providerThread = yield* Ref.get(latestProviderThread); const openSubagents = yield* Ref.get(openRunOwnedSubagents); - const writeTerminal = (settledTerminal: ProviderTerminalEvent) => - writeFinalRunEvents({ - run: input.run, - rootNode: input.rootNode, - checkpointScope: input.checkpointScope, - providerThread, - attempt: input.attempt, - ...(input.shouldFinalizeRun === undefined - ? {} - : { - shouldFinalizeRun: input.shouldFinalizeRun, - // Stop may commit between the ownership read and this - // terminal write. Gate the events and checkpoint together. - writeIfRunCurrent: { - activeAttemptId: input.attempt.id, - expectedStatus: "running" as const, - unlessInterruptRequested: settledTerminal !== terminal, - }, - }), - ...(input.hasUnpairedRunInterruptRequest === undefined - ? {} - : { - hasUnpairedRunInterruptRequest: input.hasUnpairedRunInterruptRequest, - }), - ...(input.loadRunInterruptReason === undefined - ? {} - : { loadRunInterruptReason: input.loadRunInterruptReason }), - openRunOwnedSubagents: openSubagents, - openRunOwnedSubagentsTerminal: terminal, - ...(abandonedProviderTurn === undefined ? {} : { abandonedProviderTurn }), - terminal: settledTerminal, - failureItemPersisted: settledTerminal.status === "failed", - refreshAfterTurn, - }).pipe( - Effect.mapError( - (cause) => new RunExecutionIngestError({ runId: input.run.id, cause }), + const writeTerminal = Effect.fnUntraced( + function* (settledTerminal: ProviderTerminalEvent) { + const restoredHandoffs = + settledTerminal.promptDropped === true && + input.loadDroppedInlineHandoffs !== undefined + ? yield* input.loadDroppedInlineHandoffs() + : undefined; + return yield* writeFinalRunEvents({ + run: input.run, + rootNode: input.rootNode, + checkpointScope: input.checkpointScope, + providerThread, + attempt: input.attempt, + ...(input.shouldFinalizeRun === undefined + ? {} + : { + shouldFinalizeRun: input.shouldFinalizeRun, + // Stop may commit between the ownership read and this + // terminal write. Gate the events and checkpoint together. + writeIfRunCurrent: { + activeAttemptId: input.attempt.id, + expectedStatus: "running" as const, + unlessInterruptRequested: settledTerminal !== terminal, + }, + }), + ...(input.hasUnpairedRunInterruptRequest === undefined + ? {} + : { + hasUnpairedRunInterruptRequest: input.hasUnpairedRunInterruptRequest, + }), + ...(input.loadRunInterruptReason === undefined + ? {} + : { loadRunInterruptReason: input.loadRunInterruptReason }), + openRunOwnedSubagents: openSubagents, + openRunOwnedSubagentsTerminal: terminal, + ...(abandonedProviderTurn === undefined ? {} : { abandonedProviderTurn }), + ...(restoredHandoffs === undefined ? {} : { restoredHandoffs }), + terminal: settledTerminal, + failureItemPersisted: settledTerminal.status === "failed", + refreshAfterTurn, + }); + }, + (effect) => + effect.pipe( + Effect.mapError( + (cause) => new RunExecutionIngestError({ runId: input.run.id, cause }), + ), ), - ); + ); // A workspace handoff detaches the session and stops the turn that asked // for it: the run completes, while its native subagents still settle // as interrupted. The completed write refuses in the same transaction @@ -2116,6 +2161,13 @@ export const layer: Layer.Layer< : null; const latestItemOrdinal = yield* Ref.get(latestTurnItemOrdinal); const openSubagents = yield* Ref.get(openRunOwnedSubagents); + const droppedPrompt = + (yield* Ref.get(terminalEvent))?.promptDropped === true || + rootProviderTurn?.promptDropped === true; + const recoveredHandoffs = + droppedPrompt && input.loadDroppedInlineHandoffs !== undefined + ? yield* input.loadDroppedInlineHandoffs() + : undefined; const lostToolCalls = runtimeLost ? yield* loadLostRootToolCalls.pipe( Effect.catchCauseIf( @@ -2141,18 +2193,24 @@ export const layer: Layer.Layer< }, openRunOwnedSubagents: openSubagents, ...(abandonedProviderTurn === null ? {} : { abandonedProviderTurn }), + ...(recoveredHandoffs === undefined + ? {} + : { restoredHandoffs: recoveredHandoffs }), lostToolCalls, completedAt, - terminal: makeFailedTerminalEvent( - makeProviderFailure({ - cause: squashed, - message: - knownProviderFailureMessage(squashed) ?? - userFacingDatabaseErrorMessage(squashed), - class: "unknown", - }), - latestItemOrdinal + 1, - ), + terminal: { + ...makeFailedTerminalEvent( + makeProviderFailure({ + cause: squashed, + message: + knownProviderFailureMessage(squashed) ?? + userFacingDatabaseErrorMessage(squashed), + class: "unknown", + }), + latestItemOrdinal + 1, + ), + ...(droppedPrompt ? { promptDropped: true as const } : {}), + }, failureItemPersisted: false, refreshAfterTurn, }).pipe( 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 ee048c2100592..ddf9259622599 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -118,6 +118,7 @@ function makeTestAdapter(input: { readonly failure?: ReturnType; readonly rejectedNativeThreads?: Ref.Ref>; readonly failedRunOrdinals?: ReadonlySet; + readonly promptDroppedRunOrdinals?: ReadonlySet; readonly brokenRunOrdinals?: ReadonlySet; readonly interruptedRunOrdinals?: ReadonlySet; readonly cancelledRunOrdinals?: ReadonlySet; @@ -410,6 +411,9 @@ function makeTestAdapter(input: { status: terminalStatus, startedAt: eventTime, completedAt: eventTime, + ...(input.promptDroppedRunOrdinals?.has(turnInput.runOrdinal) + ? { promptDropped: true as const } + : {}), }, }, { @@ -462,6 +466,9 @@ function makeTestAdapter(input: { threadDisposition: input.brokenRunOrdinals?.has(turnInput.runOrdinal) ? "broken" : "reusable", + ...(input.promptDroppedRunOrdinals?.has(turnInput.runOrdinal) + ? { promptDropped: true as const } + : {}), }, ]; const reportedUsage = input.tokenUsageByRunOrdinal?.[turnInput.runOrdinal]; @@ -6400,4 +6407,166 @@ describe("orchestration v2 provider switching", () => { ); }), ); + + it.effect.each([ + "same-provider-retry", + "cancelled-dropped", + "switch-away-and-return", + "persisted-failure", + ] as const)("handles an inline context handoff after a failed returning turn (%s)", (variant) => + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace(`dropped-handoff-${variant}`); + const capturedTurns = yield* Ref.make>([]); + const dropped = variant !== "persisted-failure"; + const cancelled = variant === "cancelled-dropped"; + const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([ + makeTestAdapter({ + instanceId: CODEX_MODEL_SELECTION.instanceId, + driver: CODEX_DRIVER, + capabilities: CodexProviderCapabilitiesV2, + modelSelection: CODEX_MODEL_SELECTION, + responseByRunOrdinal: { + 1: "Morning Codex summary.", + 3: "", + 4: "Recovered Codex answer.", + 5: "Recovered Codex after round-trip.", + }, + capturedTurns, + ...(cancelled + ? { cancelledRunOrdinals: new Set([3]) } + : { failedRunOrdinals: new Set([3]) }), + ...(dropped ? { promptDroppedRunOrdinals: new Set([3]) } : {}), + }), + makeTestAdapter({ + instanceId: CLAUDE_MODEL_SELECTION.instanceId, + driver: CLAUDE_DRIVER, + capabilities: ClaudeProviderCapabilitiesV2, + modelSelection: CLAUDE_MODEL_SELECTION, + responseByRunOrdinal: { + 2: "Afternoon Claude shipped b63 live draft.", + 4: "Extra Claude turn after dropped handoff.", + }, + capturedTurns, + }), + ]); + + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const testThreadId = ThreadId.make(`thread:dropped-handoff:${variant}`); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`command:dropped-handoff:${variant}:create`), + threadId: testThreadId, + projectId, + title: `Dropped handoff ${variant}`, + modelSelection: CODEX_MODEL_SELECTION, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + }); + let step = 0; + const send = (text: string, modelSelection: ModelSelection) => + Effect.gen(function* () { + step += 1; + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`command:dropped-handoff:${variant}:msg-${step}`), + threadId: testThreadId, + messageId: MessageId.make(`message:dropped-handoff:${variant}:${step}`), + text, + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + }); + yield* worker.drain(); + yield* waitForIdle(testThreadId); + yield* worker.drain(); + return yield* orchestrator.getThreadProjection(testThreadId); + }); + + // Run 1: establish native session on Codex. + yield* send("Morning task", CODEX_MODEL_SELECTION); + // Run 2: switch to Claude and do real work. + yield* send("Build live draft b63", CLAUDE_MODEL_SELECTION); + // Run 3: switch back to Codex (delta handoff covering run 2); fails. + const afterRun3 = yield* send("Resume after failure", CODEX_MODEL_SELECTION); + const run3 = afterRun3.runs.find((run) => run.ordinal === 3)!; + assert.equal(run3.status, cancelled ? "cancelled" : "failed"); + const run3Handoff = afterRun3.contextHandoffs.find( + (handoff) => handoff.targetRunId === run3.id, + ); + assert.isDefined(run3Handoff); + assert.deepEqual(run3Handoff?.coveredRunOrdinals, { from: 2, to: 2 }); + + if (dropped) { + assert.isUndefined( + run3Handoff?.delivery, + "dropping the failed prompt must clear inline handoff delivery", + ); + const run3Turn = afterRun3.providerTurns.find( + (turn) => turn.runAttemptId === run3.activeAttemptId, + ); + assert.equal(run3Turn?.promptDropped, true); + } else { + assert.equal(run3Handoff?.delivery?.status, "inline"); + } + + if (variant === "same-provider-retry" || variant === "cancelled-dropped") { + // Run 4: stay on Codex; must re-deliver run 2's handoff. + const afterRun4 = yield* send("Resume", CODEX_MODEL_SELECTION); + const turns = yield* Ref.get(capturedTurns); + const run4Turn = turns.at(-1)!; + assert.include(run4Turn.text, "Afternoon Claude shipped b63 live draft."); + assert.include(run4Turn.text, "Resume after failure"); + assert.include(run4Turn.text, "User message:\nResume"); + const updatedHandoff = afterRun4.contextHandoffs.find( + (handoff) => handoff.id === run3Handoff!.id, + ); + assert.equal(updatedHandoff?.delivery?.status, "inline"); + } else if (variant === "switch-away-and-return") { + // Run 4: bounce back to Claude, then Run 5: return to Codex. + yield* send("Continue on Claude", CLAUDE_MODEL_SELECTION); + const afterRun5 = yield* send("Back to Codex", CODEX_MODEL_SELECTION); + const run5 = afterRun5.runs.find((run) => run.ordinal === 5)!; + const run5Handoff = afterRun5.contextHandoffs.find( + (handoff) => handoff.targetRunId === run5.id, + ); + assert.isDefined(run5Handoff); + assert.deepEqual(run5Handoff?.coveredRunOrdinals, { from: 2, to: 4 }); + const run5Turn = (yield* Ref.get(capturedTurns)).at(-1)!; + assert.include(run5Turn.text, "Afternoon Claude shipped b63 live draft."); + assert.include(run5Turn.text, "Extra Claude turn after dropped handoff."); + } else { + // Control: run 3 persisted its prompt before failing, so run 4 must not re-send run 2. + yield* send("Resume", CODEX_MODEL_SELECTION); + const run4Turn = (yield* Ref.get(capturedTurns)).at(-1)!; + assert.notInclude(run4Turn.text, "Afternoon Claude shipped b63 live draft."); + } + }).pipe( + Effect.provide( + ProviderReplayHarness.layerWithRegistry( + { + name: `dropped-handoff-${variant}`, + runtimePolicyOverride: { + cwd, + approvalPolicy: "never", + sandboxPolicy: { + type: "readOnly", + access: { type: "fullAccess" }, + networkAccess: false, + }, + }, + }, + layerRegistry, + ), + ), + ); + }), + ); }); diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 2d5bc546d1800..8b05c12e17871 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1334,9 +1334,17 @@ export const OrchestrationV2ProviderTurn = Schema.Struct({ turnTokenUsage: Schema.optional(TurnTokenUsage), /** The model the provider reported running this turn's root agent, which can differ from the requested one. */ model: Schema.optional(TrimmedNonEmptyString), + /** True when the provider dropped this turn's request before persisting it to native history. */ + promptDropped: Schema.optional(Schema.Literal(true)), }); export type OrchestrationV2ProviderTurn = typeof OrchestrationV2ProviderTurn.Type; +export function isDeliveredProviderTurn( + turn: Pick, +): boolean { + return turn.promptDropped !== true; +} + /** Codex goals can span multiple native turns within one attempt. */ export function latestProviderTurnForAttempt< Turn extends Pick, diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index 18ebf74baa1c7..c0bf5156acb97 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -202,6 +202,8 @@ export const ProviderAdapterV2Event = Schema.Union([ failure: Schema.Null, reason: Schema.optional(Schema.String), threadDisposition: Schema.Literals(["reusable", "broken"]), + /** The provider dropped this turn's request before persisting it to native history. */ + promptDropped: Schema.optional(Schema.Literal(true)), retainedRuntimeRequestIds: Schema.optional(Schema.Array(RuntimeRequestId)), }), Schema.Struct({ @@ -216,6 +218,8 @@ export const ProviderAdapterV2Event = Schema.Union([ retry: Schema.optional(OrchestrationV2ProviderRetry), retryStartedAt: Schema.optional(Schema.DateTimeUtc), threadDisposition: Schema.Literals(["reusable", "broken"]), + /** The provider dropped this turn's request before persisting it to native history. */ + promptDropped: Schema.optional(Schema.Literal(true)), /** Child turns outlive root failure and report their own terminals; otherwise open children settle. */ childTurnsContinue: Schema.optional(Schema.Literal(true)), retainedRuntimeRequestIds: Schema.optional(Schema.Array(RuntimeRequestId)), diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts index 5c0a1940d671c..dfa1ac4865269 100644 --- a/packages/provider-cursor/src/server/adapter.test.ts +++ b/packages/provider-cursor/src/server/adapter.test.ts @@ -756,6 +756,149 @@ describe("CursorAdapterV2", () => { ), ); + it.effect("marks failed turns as promptDropped only when Cursor did not checkpoint the run", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const workspace = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "cursor-v2-dropped-", + }); + const checkpointedRuns = new Set(); + let sendCalls = 0; + const instanceId = ProviderInstanceId.make("cursor"); + const threadId = ThreadId.make("cursor-dropped-thread"); + const modelSelection = { instanceId, model: "gemini-4-neon" }; + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: workspace, + }); + const adapter = yield* makeCursorAdapterV2({ + instanceId, + environment: { HOME: workspace }, + }).pipe( + Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, { + assertComplete: Effect.void, + open: () => + Effect.succeed({ + agentId: "native-cursor-dropped", + listMessages: Effect.succeed([]), + close: Effect.void, + runCheckpointed: (runId) => + Effect.succeed(runId !== undefined && checkpointedRuns.has(runId)), + send: () => + Effect.sync(() => { + sendCalls += 1; + const runId = `native-cursor-run-${sendCalls}`; + return { + agentId: "native-cursor-dropped", + runId, + cancel: Effect.void, + wait: Effect.succeed({ + id: runId, + status: "error" as const, + error: { + message: + 'AI Model Not Found Invalid parameters for registry model: "gemini-4-neon"', + }, + }), + }; + }), + }), + textGenerate: () => Effect.die("unused"), + }), + Effect.provide(TestProviderHost.layer({ cwd: workspace })), + ); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("cursor-dropped-session"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + const appThread = { + id: threadId, + projectId: ProjectId.make("cursor-dropped-project"), + createdBy: "user" as const, + creationSource: "web" as const, + title: "Cursor dropped prompt", + providerInstanceId: instanceId, + modelSelection, + runtimeMode: "full-access" as const, + interactionMode: "default" as const, + branch: null, + worktreePath: null, + activeProviderThreadId: providerThread.id, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }; + const runFailed = (ordinal: number) => + Effect.gen(function* () { + yield* runtime.startTurn({ + threadId, + providerThread, + modelSelection, + runtimePolicy, + runId: RunId.make(`cursor-dropped-run-${ordinal}`), + runOrdinal: ordinal, + providerTurnOrdinal: ordinal, + attemptId: RunAttemptId.make(`cursor-dropped-attempt-${ordinal}`), + rootNodeId: NodeId.make(`cursor-dropped-root-${ordinal}`), + appThread, + message: { + messageId: MessageId.make(`cursor-dropped-message-${ordinal}`), + createdBy: "user", + creationSource: "web", + text: "Resume", + attachments: [], + }, + }); + const events = yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ); + const terminal = events.find((event) => event.type === "turn.terminal"); + const turn = events.findLast( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.completedAt !== null, + ); + return { + terminal: terminal?.type === "turn.terminal" ? terminal : undefined, + turn: turn?.type === "provider_turn.updated" ? turn.providerTurn : undefined, + }; + }); + + // Uncheckpointed failure: Cursor never persisted the prompt. + const uncheckpointed = yield* runFailed(1); + assert.equal(uncheckpointed.terminal?.status, "failed"); + assert.equal(uncheckpointed.terminal?.promptDropped, true); + assert.equal(uncheckpointed.turn?.promptDropped, true); + + // Checkpointed failure: Cursor kept the run's prompt in its store. + checkpointedRuns.add("native-cursor-run-2"); + const checkpointed = yield* runFailed(2); + assert.equal(checkpointed.terminal?.status, "failed"); + assert.isUndefined(checkpointed.terminal?.promptDropped); + assert.isUndefined(checkpointed.turn?.promptDropped); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer), + ), + ), + ); + it.effect("sends T3 instructions to each Cursor conversation that lacks them", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index 7aadadaf9ddd4..b4dd1033c2a9f 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -2510,6 +2510,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( readonly status: OrchestrationV2ProviderTurn["status"]; readonly completedAt: DateTime.Utc | null; readonly tokenUsage?: OrchestrationV2ProviderTurn["tokenUsage"]; + readonly promptDropped?: true; }): OrchestrationV2ProviderTurn => ({ id: input.context.providerTurnId, providerThreadId: input.context.input.providerThread.id, @@ -2525,6 +2526,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( startedAt: input.context.startedAt, completedAt: input.completedAt, ...(input.tokenUsage === undefined ? {} : { tokenUsage: input.tokenUsage }), + ...(input.promptDropped === true ? { promptDropped: true as const } : {}), ...(input.completedAt === null || input.context.usage === undefined ? {} : { @@ -2590,6 +2592,15 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( }).pipe(Effect.as(undefined)), ), ); + // Cursor only keeps a run in conversation history once it saves its first checkpoint. + const promptDropped = + (input.status === "failed" || input.status === "cancelled") && + !input.context.compacted && + input.context.prompt !== undefined && + !(yield* ( + input.context.session.runCheckpointed?.(input.context.run.runId) ?? + Effect.succeed(false) + ).pipe(Effect.orElseSucceed(() => false))); yield* emitProviderEvent({ type: "provider_turn.updated", driver: CursorAgentSdk.CURSOR_PROVIDER, @@ -2597,6 +2608,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( context: input.context, status: input.status, completedAt, + ...(promptDropped ? { promptDropped: true as const } : {}), ...(contextUsage === undefined ? {} : { @@ -2633,6 +2645,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( status: input.status, failure: input.failure ?? makeProviderFailure({ class: "provider_error" }), threadDisposition, + ...(promptDropped ? { promptDropped: true as const } : {}), } : { type: "turn.terminal", @@ -2643,6 +2656,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( status: input.status, failure: null, threadDisposition, + ...(promptDropped ? { promptDropped: true as const } : {}), }, ); if (input.context.runtimeInstructions !== undefined) { diff --git a/packages/shared/src/orchestrationV2ManualContinuation.test.ts b/packages/shared/src/orchestrationV2ManualContinuation.test.ts index 137bf6cd8f205..e7670749f6c5a 100644 --- a/packages/shared/src/orchestrationV2ManualContinuation.test.ts +++ b/packages/shared/src/orchestrationV2ManualContinuation.test.ts @@ -108,4 +108,16 @@ describe("unsentManualContinuationSource", () => { unsentManualContinuationSource(run("c", "a" as RunId), projection([a, b], [], [])), ).toBeUndefined(); }); + + it("treats a turn with promptDropped as unsent", () => { + const source = run("src"); + const a1 = attempt("a1", "src", 1); + const dropped = { ...turn("a1"), promptDropped: true as const }; + expect( + unsentManualContinuationSource( + run("r2", "src" as RunId), + projection([source], [a1], [dropped]), + ), + ).toBe(source); + }); }); diff --git a/packages/shared/src/orchestrationV2ManualContinuation.ts b/packages/shared/src/orchestrationV2ManualContinuation.ts index 3fb6c8d5a1866..ad64b63483e14 100644 --- a/packages/shared/src/orchestrationV2ManualContinuation.ts +++ b/packages/shared/src/orchestrationV2ManualContinuation.ts @@ -1,4 +1,8 @@ -import type { OrchestrationV2Run, OrchestrationV2ThreadProjection } from "@t3tools/contracts"; +import { + isDeliveredProviderTurn, + type OrchestrationV2Run, + type OrchestrationV2ThreadProjection, +} from "@t3tools/contracts"; export function unsentManualContinuationSource( run: Pick | undefined, @@ -7,7 +11,9 @@ export function unsentManualContinuationSource( let sourceId = run?.manualContinuationOfRunId; if (sourceId === undefined) return undefined; const runs = new Map(projection.runs.map((source) => [source.id, source])); - const acceptedAttempts = new Set(projection.providerTurns.map((turn) => turn.runAttemptId)); + const acceptedAttempts = new Set( + projection.providerTurns.filter(isDeliveredProviderTurn).map((turn) => turn.runAttemptId), + ); const latestAttempt = ( runId: OrchestrationV2Run["id"], matches: (attempt: (typeof projection.attempts)[number]) => boolean, From 0fb6ac6e65cced6201247705b304170010e37a78 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 21:47:07 -0800 Subject: [PATCH 095/139] perf(web): Markdown renders with Words as static islands under one shared tooltip; remark leaves the web app (#27866) Co-authored-by: Claude Opus 5.5 Co-authored-by: Yash Singh Co-authored-by: Cursor Co-authored-by: Gemini 4 Neon Co-authored-by: Noah Sigel --- .pnpmfile.cjs | 26 +- .../pull-requests/PullRequestDescription.tsx | 4 +- .../pull-requests/PullRequestMarkdown.tsx | 8 +- .../pullRequestAutolinks.test.ts | 2 +- .../pullRequestDescriptionContent.test.ts | 4 +- .../usePullRequestDescription.ts | 2 +- apps/mobile/src/lib/composerContext.test.ts | 13 +- apps/mobile/src/lib/composerContext.ts | 10 +- .../src/native/T3ComposerEditor.ios.tsx | 4 +- .../src/native/T3ComposerEditor.native.tsx | 4 +- apps/web/deps/README.md | 15 + .../deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz | Bin 0 -> 219310 bytes apps/web/package.json | 13 +- .../components/ChatMarkdown.browser.test.tsx | 99 +- apps/web/src/components/ChatMarkdown.tsx | 495 ++++--- .../chat/ChatMarkdownMedia.browser.test.tsx | 13 +- .../chat/MarkdownCodeBlock.logic.ts | 10 +- .../src/components/chat/MarkdownCodeBlock.tsx | 122 +- .../src/components/chat/MarkdownDetails.tsx | 39 + .../src/components/chat/MarkdownFileLink.tsx | 135 +- .../chat/MarkdownMath.browser.test.tsx | 36 - apps/web/src/components/chat/MarkdownMath.tsx | 81 -- .../components/chat/MathTypeset.logic.test.ts | 30 - .../src/components/chat/MathTypeset.logic.ts | 39 - apps/web/src/components/chat/MathTypeset.tsx | 49 - .../chat/MessagesTimeline.browser.test.tsx | 64 +- .../components/chat/MessagesTimeline.logic.ts | 2 +- .../components/chat/TimelineAssistantRows.tsx | 2 +- .../chat/TimelineUserMessageRow.tsx | 12 +- .../chat/TimelineWorkEntryRow.logic.ts | 74 +- .../components/chat/TimelineWorkEntryRow.tsx | 8 +- .../components/chat/TimelineWorkGroupRows.tsx | 10 +- .../components/chat/markdownIslands.test.ts | 50 + .../src/components/chat/markdownIslands.ts | 214 +++ .../components/chat/markdownRenderer.test.tsx | 85 +- .../src/components/chat/markdownRenderer.ts | 76 +- ....test.tsx => markdownStreamBlocks.test.ts} | 33 +- .../components/chat/markdownSyntaxGates.ts | 204 --- .../components/chat/markdownTextDirection.ts | 33 +- .../components/chat/threadFindHighlights.ts | 2 +- .../components/chat/timelineMinimapItems.ts | 64 +- .../src/components/files/FilePreviewPanel.tsx | 2 +- .../src/components/files/NotebookPreview.tsx | 23 +- .../pullRequest/PullRequestDetailPanel.tsx | 4 +- .../PullRequestMarkdown.browser.test.tsx | 2 +- .../pullRequest/PullRequestMarkdown.tsx | 6 +- .../pullRequest/PullRequestSummaryTab.tsx | 2 +- .../pullRequestDetail.logic.test.ts | 9 + .../pullRequest/pullRequestDetail.logic.ts | 31 +- .../pullRequestMarkdown.logic.test.ts | 86 +- .../pullRequest/pullRequestMarkdown.logic.ts | 154 +- .../src/components/settings/settingsSearch.ts | 1 + apps/web/src/components/ui/shared-tooltip.tsx | 262 ++++ .../components/ui/tooltip.browser.test.tsx | 131 +- apps/web/src/components/ui/tooltip.tsx | 28 +- apps/web/src/composer-editor-mentions.ts | 5 +- apps/web/src/composer-rich-text-doc.ts | 3 +- apps/web/src/i18n/translations/de.json | 5 - apps/web/src/i18n/translations/en.json | 5 - apps/web/src/i18n/translations/es.json | 5 - apps/web/src/i18n/translations/fr.json | 5 - apps/web/src/i18n/translations/ja.json | 5 - apps/web/src/i18n/translations/ko.json | 5 - apps/web/src/i18n/translations/pt-BR.json | 5 - apps/web/src/i18n/translations/ru.json | 5 - apps/web/src/i18n/translations/sv.json | 5 - apps/web/src/i18n/translations/zh.json | 5 - apps/web/src/index.css | 13 +- apps/web/src/markdown-clipboard.test.ts | 128 +- apps/web/src/markdown-clipboard.ts | 4 +- apps/web/src/markdown-incremental.test.tsx | 135 -- apps/web/src/markdown-incremental.ts | 98 -- apps/web/src/markdown-links.ts | 39 + apps/web/src/markdown/markdownText.ts | 68 + apps/web/src/markdown/wordsHast.test.ts | 403 +++++ apps/web/src/markdown/wordsHast.ts | 1296 +++++++++++++++++ packages/client-runtime/package.json | 12 +- .../src/pullRequestMarkdown.test.ts | 80 +- .../client-runtime/src/pullRequestMarkdown.ts | 71 +- .../src/pullRequestReferences.ts | 30 + packages/shared/package.json | 19 + packages/shared/src/assistantInsights.ts | 3 + packages/shared/src/codexArtifactTemplates.ts | 26 + .../shared/src/codexMarkdownDirectives.ts | 26 - .../shared/src/composerInlineTokens.test.ts | 18 +- packages/shared/src/composerInlineTokens.ts | 15 +- .../shared/src/markdownGithubAlerts.test.ts | 19 +- packages/shared/src/markdownHast.ts | 211 +++ packages/shared/src/markdownLinks.ts | 3 + .../src/markdownListIndentation.test.ts | 23 +- packages/shared/src/markdownPipeline.ts | 212 +-- packages/shared/src/markdownTaskEdits.ts | 28 + packages/shared/src/markdownTaskList.test.ts | 3 +- packages/shared/src/markdownTaskList.ts | 31 +- packages/shared/src/markdownWindowsPaths.ts | 4 +- packages/shared/src/textDirection.ts | 4 +- packages/shared/src/threadFindBlockTags.ts | 38 + packages/shared/src/threadFindText.ts | 47 +- pnpm-lock.yaml | 109 +- scripts/check-changed.ts | 3 +- scripts/release-smoke.ts | 11 +- 101 files changed, 3959 insertions(+), 2256 deletions(-) create mode 100644 apps/web/deps/README.md create mode 100644 apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz delete mode 100644 apps/web/src/components/chat/MarkdownMath.browser.test.tsx delete mode 100644 apps/web/src/components/chat/MarkdownMath.tsx delete mode 100644 apps/web/src/components/chat/MathTypeset.logic.test.ts delete mode 100644 apps/web/src/components/chat/MathTypeset.logic.ts delete mode 100644 apps/web/src/components/chat/MathTypeset.tsx create mode 100644 apps/web/src/components/chat/markdownIslands.test.ts create mode 100644 apps/web/src/components/chat/markdownIslands.ts rename apps/web/src/components/chat/{markdownStreamBlocks.test.tsx => markdownStreamBlocks.test.ts} (81%) delete mode 100644 apps/web/src/components/chat/markdownSyntaxGates.ts create mode 100644 apps/web/src/components/ui/shared-tooltip.tsx delete mode 100644 apps/web/src/markdown-incremental.test.tsx delete mode 100644 apps/web/src/markdown-incremental.ts create mode 100644 apps/web/src/markdown/markdownText.ts create mode 100644 apps/web/src/markdown/wordsHast.test.ts create mode 100644 apps/web/src/markdown/wordsHast.ts create mode 100644 packages/client-runtime/src/pullRequestReferences.ts create mode 100644 packages/shared/src/assistantInsights.ts rename apps/web/src/markdownGithubAlerts.test.tsx => packages/shared/src/markdownGithubAlerts.test.ts (70%) create mode 100644 packages/shared/src/markdownHast.ts rename apps/web/src/markdownListIndentation.test.tsx => packages/shared/src/markdownListIndentation.test.ts (72%) create mode 100644 packages/shared/src/markdownTaskEdits.ts create mode 100644 packages/shared/src/threadFindBlockTags.ts diff --git a/.pnpmfile.cjs b/.pnpmfile.cjs index 87a153f7b030d..8e79fceda4142 100644 --- a/.pnpmfile.cjs +++ b/.pnpmfile.cjs @@ -1,16 +1,22 @@ const fs = require("node:fs"); const path = require("node:path"); -// Our forks ship as tarballs in apps/mobile/deps. A pnpm patch on one is a second source of -// truth that the next tarball silently drops, so changes go to the fork (apps/mobile/deps/README.md). +// Our forks ship as tarballs in apps/mobile/deps and apps/web/deps. A pnpm patch on one is a +// second source of truth that the next tarball silently drops, so changes go to the fork (see +// the README beside each tarball). +const FORK_APPS = ["apps/mobile", "apps/web"]; + function forkTarballPatches(patchedDependencies) { - const manifestPath = path.join(__dirname, "apps/mobile/package.json"); - // Release staging installs a partial workspace without the mobile app. - if (!patchedDependencies || !fs.existsSync(manifestPath)) return []; - const { dependencies = {} } = JSON.parse(fs.readFileSync(manifestPath, "utf8")); - const forks = Object.keys(dependencies).filter((name) => - String(dependencies[name]).startsWith("file:deps/"), - ); + if (!patchedDependencies) return []; + const forks = FORK_APPS.flatMap((app) => { + const manifestPath = path.join(__dirname, app, "package.json"); + // Release staging installs a partial workspace without every app. + if (!fs.existsSync(manifestPath)) return []; + const { dependencies = {} } = JSON.parse(fs.readFileSync(manifestPath, "utf8")); + return Object.keys(dependencies).filter((name) => + String(dependencies[name]).startsWith("file:deps/"), + ); + }); return Object.keys(patchedDependencies).filter((key) => forks.some((name) => key === name || key.startsWith(`${name}@`)), ); @@ -23,7 +29,7 @@ module.exports = { if (forkPatches.length > 0) { throw new Error( `pnpm-workspace.yaml patches ${forkPatches.join(", ")}, which ships as a fork tarball in ` + - "apps/mobile/deps. Change the fork and replace the tarball instead (apps/mobile/deps/README.md).", + "an app's deps directory. Change the fork and replace the tarball instead (deps/README.md).", ); } // Windows installs need Linux x64 glibc binaries because WSL shares node_modules. diff --git a/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx b/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx index 3251cb8773f03..f0604d6b4ceb6 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx @@ -10,7 +10,7 @@ import { useContext, useMemo, useState, type ComponentProps, type ReactNode } fr import { Platform, Pressable, ScrollView, StyleSheet, View } from "react-native"; import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg"; import { pullRequestImageSource } from "./pullRequestMediaSource"; -import { parseMarkdownDocument } from "../../lib/markdownDocument"; +import { markdownReferenceDefinitions, parseMarkdownDocument } from "../../lib/markdownDocument"; import { SymbolView } from "../../components/ui/AppSymbol"; import { AppText as Text } from "../../components/ui/AppText"; import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; @@ -44,7 +44,7 @@ export function PullRequestDescription(props: { const document = parseMarkdownDocument(props.markdown); const content = pullRequestDescriptionContent( document, - splitPullRequestBody(props.markdown), + splitPullRequestBody(props.markdown, markdownReferenceDefinitions), messages, ); return { diff --git a/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx b/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx index 3654cfd87bb42..c1852a6ee2601 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx @@ -17,7 +17,7 @@ import { createContext, useContext, useMemo, useState } from "react"; import { changeRequestReferenceAutolinker, resolveChangeRequestMediaUrl, -} from "@t3tools/client-runtime/pull-request-markdown"; +} from "@t3tools/client-runtime/pull-request-references"; import { sourceControlClients, type ReferenceAutolink, @@ -28,6 +28,7 @@ import { useOpenPullRequest } from "../../native/useOpenPullRequest"; import { SelectableMarkdownText } from "../../native/SelectableMarkdownText"; import { useMarkdownPreviewStyles } from "../files/FileMarkdownPreview"; import { markdownImageSources } from "../../lib/markdownImageSources"; +import { markdownReferenceDefinitions } from "../../lib/markdownDocument"; import { FilePreviewGallery, useFilePreviewGallery } from "../../components/ui/FilePreviewGallery"; import { pullRequestImageSource } from "./pullRequestMediaSource"; import { @@ -124,7 +125,10 @@ export function PullRequestMarkdown(props: { }) { const mediaContext = useContext(PullRequestMediaContext); const changeRequestUrl = useContext(ChangeRequestUrlContext); - const segments = useMemo(() => splitPullRequestBody(props.markdown), [props.markdown]); + const segments = useMemo( + () => splitPullRequestBody(props.markdown, markdownReferenceDefinitions), + [props.markdown], + ); const [undoneTicks, setUndoneTicks] = useState(0); const gallery: FilePreviewItem[] = markdownImageSources( props.imageGroupMarkdown ?? props.markdown, diff --git a/apps/mobile/src/features/pull-requests/pullRequestAutolinks.test.ts b/apps/mobile/src/features/pull-requests/pullRequestAutolinks.test.ts index 6500a79885a8d..7acb1640694f7 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestAutolinks.test.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestAutolinks.test.ts @@ -1,4 +1,4 @@ -import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-markdown"; +import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-references"; import { describe, expect, it } from "vite-plus/test"; import { nativePullRequestMarkdown } from "./pullRequestAutolinks"; diff --git a/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts b/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts index 6d6a1bfe4b624..74e21d39018ee 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vite-plus/test"; -import type { MarkdownNode } from "../../lib/markdownDocument"; +import { markdownReferenceDefinitions, type MarkdownNode } from "../../lib/markdownDocument"; import { splitPullRequestBody } from "@t3tools/client-runtime/pull-request-markdown"; import { pullRequestDescriptionContent } from "./pullRequestDescriptionContent"; @@ -15,6 +15,7 @@ describe("PR attachments", () => { } as MarkdownNode; const media = splitPullRequestBody( `${uri}\n\nhttps://drop.example.com/demo.mp4\n\nhttps://github.com/user-attachments/assets/123-abc`, + markdownReferenceDefinitions, ); expect(pullRequestDescriptionContent(document, media).attachments).toEqual([ { uri, caption: "Screenshot", kind: "image" }, @@ -30,6 +31,7 @@ describe("PR attachments", () => { it("collects videos from a before/after table", () => { const media = splitPullRequestBody( "\n\n\n
    BeforeAfter
    \n\nhttps://drop.example.com/before.mp4\n\n\n\nhttps://drop.example.com/after.mp4\n\n
    ", + markdownReferenceDefinitions, ); expect( pullRequestDescriptionContent({ type: "root" } as MarkdownNode, media).attachments, diff --git a/apps/mobile/src/features/pull-requests/usePullRequestDescription.ts b/apps/mobile/src/features/pull-requests/usePullRequestDescription.ts index 105f4a1095009..5758e6b2ee84a 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestDescription.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestDescription.ts @@ -8,7 +8,7 @@ import { } from "@t3tools/client-runtime/pull-request-editing"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import type { PullRequestDetail } from "@t3tools/contracts"; -import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList"; +import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskEdits"; import { AsyncResult } from "effect/reactivity"; import { useGT } from "gt-react-native"; import { useRef, useState } from "react"; diff --git a/apps/mobile/src/lib/composerContext.test.ts b/apps/mobile/src/lib/composerContext.test.ts index e2a5a015c61af..255666ebcf0b2 100644 --- a/apps/mobile/src/lib/composerContext.test.ts +++ b/apps/mobile/src/lib/composerContext.test.ts @@ -8,6 +8,7 @@ import { type ServerProviderSkill, } from "@t3tools/contracts"; import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens"; +import { markdownMathRanges } from "@t3tools/shared/markdownMath"; import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations"; import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, @@ -167,7 +168,7 @@ describe("mobile composer context", () => { const modelTokens = (text: string) => composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), new Set(), collectComposerModelTokens(text, known), ) @@ -256,7 +257,7 @@ describe("mobile composer context", () => { const skills = [babysit, disabled, agentOnly]; const tokens = composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), composerSkillLabels(skills), ); expect(tokens.map((token) => token.source)).toEqual([ @@ -271,14 +272,14 @@ describe("mobile composer context", () => { expect( composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), composerSkillLabels([]), ).map((token) => token.type), ).toEqual(["mention", "context", "context", "citation", "citation"]); expect( composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), composerSkillLabels([{ ...babysit, name: "HOME" }]), ) .filter((token) => token.type === "skill") @@ -292,7 +293,7 @@ describe("mobile composer context", () => { expect( composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), composerSkillLabels(promoted), ) .filter((token) => token.type === "skill") @@ -301,7 +302,7 @@ describe("mobile composer context", () => { expect( composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), composerSkillLabels(skills), ) .filter((token) => token.type === "skill") diff --git a/apps/mobile/src/lib/composerContext.ts b/apps/mobile/src/lib/composerContext.ts index 754774c4f1306..219a61108fd51 100644 --- a/apps/mobile/src/lib/composerContext.ts +++ b/apps/mobile/src/lib/composerContext.ts @@ -40,6 +40,7 @@ import { composerMathRanges, type ComposerInlineToken, } from "@t3tools/shared/composerInlineTokens"; +import { markdownMathRanges } from "@t3tools/shared/markdownMath"; const isMessageContext = Schema.is(OrchestrationMessageContext); const decodeMessageContext = Schema.decodeUnknownOption(OrchestrationMessageContext); @@ -73,7 +74,7 @@ export function composerMentionPath(source: string, context?: OrchestrationMessa const record = context?.records.find((entry) => entry.contextId === reference.contextId); return record?.kind === "mention" && "path" in record ? record.path : null; } - const token = collectComposerInlineTokens(`${source} `)[0]; + const token = collectComposerInlineTokens(`${source} `, { findMath: markdownMathRanges })[0]; return token?.type === "mention" && token.source === source ? token.value : null; } @@ -222,7 +223,12 @@ export function composerContextEditorTokens( !references.some((ref) => token.start < ref.end && token.end > ref.start) && !citations.some((ref) => token.start < ref.end && token.end > ref.start), ); - const taken = [...inlineTokens, ...references, ...citations, ...composerMathRanges(text)]; + const taken = [ + ...inlineTokens, + ...references, + ...citations, + ...composerMathRanges(text, markdownMathRanges), + ]; const models = modelTokens.filter( (mention) => !taken.some((range) => mention.start < range.end && mention.end > range.start), ); diff --git a/apps/mobile/src/native/T3ComposerEditor.ios.tsx b/apps/mobile/src/native/T3ComposerEditor.ios.tsx index ef57536abe95f..7e8eba1d01b28 100644 --- a/apps/mobile/src/native/T3ComposerEditor.ios.tsx +++ b/apps/mobile/src/native/T3ComposerEditor.ios.tsx @@ -1,6 +1,7 @@ import { PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES } from "@t3tools/client-runtime/text-paste"; import { PROVIDER_SEND_TURN_MAX_INPUT_CHARS } from "@t3tools/contracts"; import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens"; +import { markdownMathRanges } from "@t3tools/shared/markdownMath"; import { composerContextEditorTokens, composerSkillLabels } from "../lib/composerContext"; import { useComposerModelTokens } from "./useComposerModelTokens"; import { requireNativeView } from "expo"; @@ -169,11 +170,12 @@ export function ComposerEditor({ // an abandoned render from leaking a trailing token into the next one. const [confirmedTokens, setConfirmedTokens] = useState(() => ({ value: props.value, - tokens: collectComposerInlineTokens(props.value), + tokens: collectComposerInlineTokens(props.value, { findMath: markdownMathRanges }), })); let tokens = confirmedTokens.tokens; if (confirmedTokens.value !== props.value) { tokens = collectComposerInlineTokens(props.value, { + findMath: markdownMathRanges, preserveTrailingFrom: confirmedTokens.tokens, }); setConfirmedTokens({ value: props.value, tokens }); diff --git a/apps/mobile/src/native/T3ComposerEditor.native.tsx b/apps/mobile/src/native/T3ComposerEditor.native.tsx index 28f47c3b758ab..4a0f57e411020 100644 --- a/apps/mobile/src/native/T3ComposerEditor.native.tsx +++ b/apps/mobile/src/native/T3ComposerEditor.native.tsx @@ -1,6 +1,7 @@ import { PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES } from "@t3tools/client-runtime/text-paste"; import { PROVIDER_SEND_TURN_MAX_INPUT_CHARS } from "@t3tools/contracts"; import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens"; +import { markdownMathRanges } from "@t3tools/shared/markdownMath"; import { composerContextEditorTokens, composerSkillLabels } from "../lib/composerContext"; import { DEFAULT_COMPOSER_ENTER_BEHAVIOR } from "../lib/composerEnterBehavior"; import { useComposerModelTokens } from "./useComposerModelTokens"; @@ -156,11 +157,12 @@ export function ComposerEditor({ // an abandoned render from leaking a trailing token into the next one. const [confirmedTokens, setConfirmedTokens] = useState(() => ({ value: props.value, - tokens: collectComposerInlineTokens(props.value), + tokens: collectComposerInlineTokens(props.value, { findMath: markdownMathRanges }), })); let tokens = confirmedTokens.tokens; if (confirmedTokens.value !== props.value) { tokens = collectComposerInlineTokens(props.value, { + findMath: markdownMathRanges, preserveTrailingFrom: confirmedTokens.tokens, }); setConfirmedTokens({ value: props.value, tokens }); diff --git a/apps/web/deps/README.md b/apps/web/deps/README.md new file mode 100644 index 0000000000000..26750d308c195 --- /dev/null +++ b/apps/web/deps/README.md @@ -0,0 +1,15 @@ +The Words tarball comes from the [`fork/t3-words` branch](https://github.com/pingdotgg/pierre/tree/fork/t3-words) of our fork of [pierrecomputer/pierre](https://github.com/pierrecomputer/pierre). Its `t3-fork.json` records the source commit and the upstream base. The fork adds opt-in options, all off by default so default output stays byte-identical to upstream: + +- `singleTilde: false`: only `~~` strikes. +- `windowsPaths`: backslashes in Windows drive paths stay. +- `codeMeta`: code fence info after the language becomes `data-meta`. +- `sourcePositions`: `data-sourcepos` byte ranges on list items, links, images, code blocks, math and directives. +- `directives`: the named remark-directive text and leaf directives. +- `escapeHtml`: raw HTML renders as escaped text. +- `leadingWhitespace`: spaces typed at the start of paragraph lines show, in `data-leading-whitespace` spans. +- `texDelimiters`: with `math`, `\(…\)` and `\[…\]` are math, as T3's llm-math reads them. +- `autolinkBoundaries`: end ASCII bare URLs before CJK/Arabic punctuation and keep trailing `_`/`~` when not closing emphasis. + +To replace it, commit the change on `fork/t3-words`, bump `packages/words/package.json` to the next `0.2.2-t3.N` and update `t3-fork.json`'s `source`, then run `moon run words:build` (or `node scripts/build.ts && tsdown`) and `npm pack` in `packages/words`. Name the archive with the first eight characters of the source commit, such as `pierre-words-0.2.2-t3.4-7c04b7f1.tgz`, update the path in `apps/web/package.json`, and run `vp i`. + +Change it through the fork, never with a pnpm patch: the next tarball would drop the patch without a trace. diff --git a/apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz b/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0QGF*~YtfZD%T&AYOO4c!!VBnQ*-RNKJor6k$CZ(<`>o`Wn zgQxr8b%%pY;iImXaTvOxB#xe=7B4l7c|X%9ErWY>OZvQ%5%YQYg~fGt*8B``v*u@k zgMewMQ;yB6$l;WwcGt^=U$pOW!yGue-_3?O;Pshj*D`SfBdt1Wz3f<7wa!6AJGNz> zC^rP_97Lqgyv0O(i^z5CO9aGxH%y=HbtR=G5^Bb6Pj0A7x-?~L=c@H`S!rph+>nEA z-9mS44RxmCq&#}e7#R+6%ji*$rA{|>en0wF*B^^qmfGDgisWAinHz$iOHmx{yh1q= z%C)FCj-_>F9o4Rv>l_Z1FVfwLQn{f{%a~aw%*orO_kThA4Rv;3GQ1$G(8Go3)@Xj}1m`Tw+YEjtKio1-m~3Kk>bbG}!>Bf>y%nx_)nqe*K^xzfz( xwYqImg?t*iHj+@gPJ`e`A_vv&Xh literal 0 HcmV?d00001 diff --git a/apps/web/package.json b/apps/web/package.json index 21ac8caba0b1e..a60eb801260cf 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -34,6 +34,7 @@ "@noble/hashes": "catalog:", "@pierre/diffs": "catalog:", "@pierre/trees": "1.0.0-beta.6", + "@pierre/words": "file:deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz", "@t3tools/client-runtime": "workspace:*", "@t3tools/contracts": "workspace:*", "@t3tools/provider-core": "workspace:*", @@ -74,24 +75,16 @@ "jszip": "3.10.1", "katex": "^0.18.2", "lucide-react": "^0.564.0", - "mdast-util-from-markdown": "^2.0.3", - "micromark-util-combine-extensions": "^2.0.1", "pdfjs-dist": "6.4.299", "pele": "catalog:", + "property-information": "^7.2.0", "react": "catalog:", "react-dom": "catalog:", - "react-markdown": "^10.1.0", - "remark-gfm": "catalog:", - "remark-math": "6.0.0", - "remark-parse": "catalog:", - "remark-rehype": "catalog:", "saxes": "6.0.0", "sql.js": "1.15.0", "tailwind-merge": "^3.4.0", "tiff": "7.1.3", - "unified": "catalog:", "use-sync-external-store": "^1.6.0", - "vfile": "^6.0.3", "zustand": "^5.0.11" }, "devDependencies": { @@ -103,7 +96,6 @@ "@types/compression": "^1.8.1", "@types/culori": "^4.0.1", "@types/hast": "^3.0.4", - "@types/mdast": "^4.0.4", "@types/react": "catalog:", "@types/react-dom": "catalog:", "@types/sql.js": "1.4.11", @@ -113,7 +105,6 @@ "@vitest/browser-playwright": "5.0.5", "compression": "^1.8.2", "gt": "2.27.0", - "micromark-util-types": "catalog:", "oxc-transform-react": "~0.152.0", "playwright": "1.64.1", "tailwindcss": "^4.0.0", diff --git a/apps/web/src/components/ChatMarkdown.browser.test.tsx b/apps/web/src/components/ChatMarkdown.browser.test.tsx index 0586a724b0c56..faca71b4a101f 100644 --- a/apps/web/src/components/ChatMarkdown.browser.test.tsx +++ b/apps/web/src/components/ChatMarkdown.browser.test.tsx @@ -2,7 +2,6 @@ import { MISSING_FILE_ACCESS_MESSAGE } from "@t3tools/client-runtime/state/asset import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { AsyncResult } from "effect/reactivity"; import { type ReactElement } from "react"; -import remarkGfm from "remark-gfm"; import { describe, expect, it, vi } from "vite-plus/test"; import { commands, page, userEvent } from "vite-plus/test/browser"; @@ -15,11 +14,8 @@ import { selectActiveRightPanelSurface, useRightPanelStore, } from "../rightPanelStore"; -import { - CHAT_USER_MARKDOWN_REMARK_PLUGINS, - remarkEnableOrderedListNumbers, -} from "@t3tools/shared/markdownPipeline"; -import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList"; +import type { MarkdownExtensions } from "../markdown/wordsHast"; +import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskEdits"; import { HostImageUrlContext } from "./chat/hostImageUrl"; import { getSyntaxHighlighterPromise } from "~/lib/syntaxHighlighting"; @@ -28,14 +24,14 @@ const { workspaceSearch, filesystemMetadata } = vi.hoisted(() => ({ filesystemMetadata: vi.fn(), })); const parsedSources = vi.hoisted(() => [] as string[]); -vi.mock(import("mdast-util-from-markdown"), async (original) => { +vi.mock(import("../markdown/wordsHast"), async (original) => { const actual = await original(); return { ...actual, - fromMarkdown: ((source: string, ...rest: never[]) => { - parsedSources.push(String(source)); - return (actual.fromMarkdown as (...args: unknown[]) => unknown)(source, ...rest); - }) as typeof actual.fromMarkdown, + wordsHast: (source, options) => { + parsedSources.push(source); + return actual.wordsHast(source, options); + }, }; }); @@ -188,7 +184,7 @@ function buttonsLabelled(container: HTMLElement, label: string) { ); } -const SOURCE_NUMBER_PLUGINS = [remarkEnableOrderedListNumbers]; +const USER_MESSAGE = { userMessage: true }; it("keeps decimal markers in nested user lists while documents keep their counter styles", async () => { setup(); @@ -201,7 +197,7 @@ it("keeps decimal markers in nested user lists while documents keep their counte cwd={undefined} text={text} className="user-message-markdown" - extraRemarkPlugins={SOURCE_NUMBER_PLUGINS} + extensions={USER_MESSAGE} />

    @@ -312,36 +308,24 @@ it("reuses the parse of a streaming reply's finished blocks when it remounts", a expect(parsedSources.filter((source) => source.includes("Finished block"))).toHaveLength(1); }); -it("reuses the parse of a remounted message that has stable extra plugins", async () => { +it("reuses the parse of a remounted message that has stable extensions", async () => { setup(); - const parsed = vi.fn(); - const countingPlugins = [() => () => void parsed()]; - const message = ( - - ); + const extensions = { userMessage: true }; + const message = ; { await using first = await render( - , + , ); await first.rerender(message); } await using screen = await render(message); await expect.element(screen.getByText("Cached text")).toBeVisible(); - expect(parsed).toHaveBeenCalledTimes(1); - const changed = vi.fn(); + const parses = () => parsedSources.filter((source) => source === "Cached text").length; + expect(parses()).toBe(1); await screen.rerender( - () => void changed()]} - />, + , ); - expect(changed).toHaveBeenCalledTimes(1); + expect(parses()).toBe(2); }); it("highlights a code block's own source when an earlier block of the same length was cached", async () => { @@ -399,6 +383,45 @@ describe("ChatMarkdown external link labels", () => { }); }); +describe("ChatMarkdown link tooltips", () => { + it("shows each link's address on one shared tooltip as the pointer moves between links", async () => { + setup(); + await using screen = await render( + , + ); + await userEvent.hover(screen.getByRole("link", { name: /First/ })); + await expect.element(page.getByText("https://example.com/a")).toBeVisible(); + await userEvent.hover(screen.getByRole("link", { name: /Second/ })); + await expect.element(page.getByText("https://example.org/b")).toBeVisible(); + expect(document.querySelectorAll('[data-slot="tooltip-popup"]')).toHaveLength(1); + }); +}); + +describe("ChatMarkdown details", () => { + it("opens collapsed details by click, and by keyboard without losing focus", async () => { + setup(); + await using screen = await render( + First\n\nHidden one\n\n\n\n
    Second\n\nHidden two\n\n
    " + } + />, + ); + await userEvent.click(screen.getByRole("button", { name: "First" })); + await expect.element(screen.getByText("Hidden one")).toBeVisible(); + await userEvent.tab(); + const second = screen.getByRole("button", { name: "Second" }); + await expect.element(second).toHaveFocus(); + await userEvent.keyboard("{Enter}"); + await expect.element(screen.getByText("Hidden two")).toBeVisible(); + await expect.element(screen.getByRole("button", { name: "Second" })).toHaveFocus(); + }); +}); + describe("ChatMarkdown streaming", () => { it("runs only a complete single-line shell block after a click", async () => { setup(); @@ -802,12 +825,12 @@ describe("ChatMarkdown copy", () => { "copies and selects user lines the same whether their typed indentation shows: $text", async (copy) => { setup(); - const copied = async (extraRemarkPlugins: typeof CHAT_USER_MARKDOWN_REMARK_PLUGINS) => { + const copied = async (extensions: MarkdownExtensions) => { await using screen = await renderText(copy.text, { className: "user-message-markdown", lineBreaks: true, parseRawHtml: false, - extraRemarkPlugins, + extensions, }); const range = document.createRange(); range.selectNodeContents(screen.container); @@ -824,9 +847,9 @@ describe("ChatMarkdown copy", () => { // A drag or anything else that reads the selection gets its text, not the copy payload. return { payload: chatMarkdownClipboardPayload(selection), selected: selection.toString() }; }; - const shown = await copied(CHAT_USER_MARKDOWN_REMARK_PLUGINS); + const shown = await copied({ userMessage: true, leadingWhitespace: true }); // The user pipeline as it was before typed indentation was shown. - expect(shown).toEqual(await copied([[remarkGfm, { singleTilde: false }]])); + expect(shown).toEqual(await copied({ userMessage: true })); }, ); @@ -885,7 +908,7 @@ describe("ChatMarkdown copy", () => { setup(); await using screen = await renderText( source, - userMessage ? { extraRemarkPlugins: SOURCE_NUMBER_PLUGINS } : {}, + userMessage ? { extensions: USER_MESSAGE } : {}, ); const itemText = (shown: string) => [...screen.container.querySelectorAll("li")] diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 8c0d14520871d..979d1858cafc1 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -13,7 +13,7 @@ import { extractMarkdownLinkHrefs, inlineCodeFilePathCandidate, } from "@t3tools/shared/markdownLinks"; -import { taskListMarkerOffset } from "@t3tools/shared/markdownTaskList"; +import { taskListMarkerOffset } from "@t3tools/shared/markdownTaskEdits"; import { isHostPath, resolveWorkspaceFilePath } from "@t3tools/shared/path"; import { usePullRequestLinking } from "~/hooks/usePullRequestLinking"; import { @@ -21,14 +21,7 @@ import { AuthOrchestrationOperateScope, SOURCE_CONTROL_MEDIA_ASSET, } from "@t3tools/contracts"; -import { - CHAT_MARKDOWN_REMARK_PLUGINS, - CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, - CHAT_MARKDOWN_REHYPE_PLUGINS, - chatMarkdownImageSource, - decodeMarkdownLinkEscapes, - remarkAssistantInsights, -} from "@t3tools/shared/markdownPipeline"; +import { chatMarkdownImageSource } from "@t3tools/shared/markdownHast"; import { useAtomValue } from "@effect/atom-react"; import { COMPOSER_CONTEXT_CLIPBOARD_MIME, @@ -94,27 +87,17 @@ import React, { useState, type ReactNode, } from "react"; -import type { - Components, - ExtraProps as ReactMarkdownExtraProps, - Options as ReactMarkdownOptions, -} from "react-markdown"; -import { createIncrementalMarkdownPlugin } from "../markdown-incremental"; -import type { Pluggable, PluggableList } from "unified"; -import { defaultUrlTransform } from "react-markdown"; import { parseAssistantCitationHref } from "@t3tools/shared/assistantCitations"; import { parseComposerContextHref } from "@t3tools/shared/composerContextReferences"; import { parseThreadLinkHref } from "@t3tools/shared/threadLinks"; import { AssistantCitationEmbed } from "./chat/AssistantCitationChip"; import { MarkdownThreadLink } from "./chat/MarkdownThreadLink"; -import { mathKind } from "@t3tools/shared/markdownMath"; -import remarkMath from "remark-math"; +import { artifactTemplateFromHastProperties } from "@t3tools/shared/codexArtifactTemplates"; import { - artifactTemplateFromHastProperties, + decodeMarkdownLinkEscapes, renderCodexInlineDirectivesAsMarkdown, -} from "@t3tools/shared/codexMarkdownDirectives"; +} from "../markdown/markdownText"; import { renderSkillInlineMarkdownChildren } from "./chat/SkillInlineText"; -import { MarkdownMath } from "./chat/MarkdownMath"; import { resolveMarkdownMediaPreview, type ExpandedImagePreview, @@ -131,7 +114,7 @@ import { resolveExternalWebLinkHost, showExternalLinkContextMenu, } from "./chat/externalLinkContextMenu"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; +import { SharedTooltipProvider, SharedTooltipTrigger } from "./ui/shared-tooltip"; import { Button } from "./ui/button"; import { stackedThreadToast, toastManager } from "./ui/toast"; import { recordVisitForThread } from "../browserHistoryStore"; @@ -214,6 +197,15 @@ import { PullRequestLinkPreview } from "./pullRequest/PullRequestLinkPreview"; import { IssueLinkPreview, IssueLinkPreviewFallback } from "./issue/IssueLinkPreview"; import { MarkdownCodeBlock, SuspenseShikiCodeBlock } from "./chat/MarkdownCodeBlock"; import { createMarkdownRenderer } from "./chat/markdownRenderer"; +import type { MarkdownExtensions, WordsHastOptions } from "../markdown/wordsHast"; +import { + type MarkdownIslandOptions, + renderHastWithIslands, + withProperties, +} from "./chat/markdownIslands"; +import type { Element as HastElement } from "hast"; +import { matchInlineSkills } from "@t3tools/shared/inlineSkills"; +import { collectComposerModelMentions } from "@t3tools/client-runtime/composer-model-mentions"; import { splitMarkdownBlocks } from "./chat/markdownStreamBlocks"; import { MarkdownMermaidCodeBlock } from "./chat/MarkdownMermaidCodeBlock"; import { MarkdownTable } from "./chat/MarkdownTable"; @@ -230,9 +222,7 @@ import { import { MarkdownExternalLinkContent } from "./chat/MarkdownExternalLink"; import { MarkdownFileLink } from "./chat/MarkdownFileLink"; import { canUseMarkdownFileShellActions } from "./chat/MarkdownFileLink.logic"; -import { rehypeChipPunctuation } from "./chat/markdownChipPunctuation"; -import { handleMarkdownFragmentClick, rehypeHeadingIds } from "./chat/markdownFragments"; -import { rehypeTextDirection } from "./chat/markdownTextDirection"; +import { handleMarkdownFragmentClick } from "./chat/markdownFragments"; import { hastHasText, hastPlainTextDeep, plainHastText } from "./chat/markdownHast.logic"; import { extractCodeBlock, @@ -268,8 +258,8 @@ interface ChatMarkdownProps { imageBaseDir?: string | undefined; workspaceMutationId?: string | null | undefined; onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined; - /** Keep one list per configuration (a module constant): it keys the shared parse cache. */ - extraRemarkPlugins?: NonNullable; + /** Keep one object per configuration (a module constant): it keys the shared parse cache. */ + extensions?: MarkdownExtensions | undefined; renderContextReference?: ((reference: ChatMarkdownContextReference) => ReactNode) | undefined; /** Loads media a source control host keeps behind a credential through the server, which holds `cwd`'s; without it a private repository's uploads load unauthenticated and 404. */ @@ -289,7 +279,7 @@ export interface ChatMarkdownContextReference { } const EMPTY_MARKDOWN_SKILLS: ReadonlyArray = []; -const EMPTY_REMARK_PLUGINS: NonNullable = []; +const NO_EXTENSIONS: MarkdownExtensions = {}; const ARTIFACT_TEMPLATE_ICON_BY_KIND = { document: FileTextIcon, @@ -423,19 +413,29 @@ function normalizeMarkdownLinkHrefKey(href: string): string { : rewrittenHref; } -// Heading ids are added after sanitizing, which would prefix them a second time. -const CHAT_MARKDOWN_RENDER_REHYPE_PLUGINS = [ - ...CHAT_MARKDOWN_REHYPE_PLUGINS, - rehypeHeadingIds, - rehypeTextDirection, - rehypeChipPunctuation, -] satisfies NonNullable; +/** A component per element, with the hast node it renders, as react-markdown typed them. */ +type MarkdownComponents = { + [Tag in keyof React.JSX.IntrinsicElements]?: React.ComponentType< + React.JSX.IntrinsicElements[Tag] & { node?: HastElement | undefined } + >; +}; -const CHAT_MARKDOWN_LITERAL_HTML_REHYPE_PLUGINS = [ - rehypeHeadingIds, - rehypeTextDirection, - rehypeChipPunctuation, -] satisfies NonNullable; +// react-markdown's defaultUrlTransform: relative URLs, and absolute ones with a safe protocol. +const SAFE_PROTOCOL = /^(?:https?|ircs?|mailto|xmpp)$/i; +function safeUrl(value: string): string { + const colon = value.indexOf(":"); + const before = (character: string) => { + const at = value.indexOf(character); + return at !== -1 && colon > at; + }; + return colon === -1 || + before("/") || + before("?") || + before("#") || + SAFE_PROTOCOL.test(value.slice(0, colon)) + ? value + : ""; +} function markdownUrlTransform(href: string) { if (parseAssistantCitationHref(href)) return href; @@ -443,7 +443,7 @@ function markdownUrlTransform(href: string) { if (parseThreadLinkHref(href)) return href; if (isWindowsDrivePathHref(href)) return href; if (isLocalEditorFileHref(href)) return href; - return rewriteMarkdownFileUriHref(href) ?? defaultUrlTransform(href); + return rewriteMarkdownFileUriHref(href) ?? safeUrl(href); } const NO_MARKDOWN_EDITORS: ReadonlyArray = []; @@ -486,11 +486,16 @@ const markdownServerConfigFieldsAtom = Atom.family((environmentId: EnvironmentId }).pipe(Atom.withLabel("markdown-server-config-fields")), ); -function fileLinkSourcesKey( +interface BlockFileLinkSources { + readonly hrefs: ReadonlyArray; + readonly spans: ReadonlyArray; +} + +function blockFileLinkSources( text: string, cwd: string | undefined, imageBaseDir: string | undefined, -): string { +): BlockFileLinkSources { const hrefs = extractMarkdownLinkHrefs(renderCodexInlineDirectivesAsMarkdown(text)) .filter((href) => !parseComposerContextHref(href)) .map(decodeMarkdownLinkEscapes) @@ -499,7 +504,47 @@ function fileLinkSourcesKey( const spans = extractInlineCodeSpans(text).filter((span) => resolveInlineCodeFileLinkMeta(span, cwd, imageBaseDir ?? cwd), ); - return JSON.stringify([[...new Set(hrefs)], [...new Set(spans)]]); + return { hrefs, spans }; +} + +// Links and code spans never cross blocks: a streamed reply rescans only its open last block. +const MAX_CACHED_BLOCK_CHARS = 2_000_000; +const finishedBlockFileLinkSources = new Map(); +let cachedBlockChars = 0; + +function fileLinkSourcesKey( + text: string, + cwd: string | undefined, + imageBaseDir: string | undefined, + streamingBlocks: ReadonlyArray | null, +): string { + if (!streamingBlocks) { + const { hrefs, spans } = blockFileLinkSources(text, cwd, imageBaseDir); + return JSON.stringify([[...new Set(hrefs)], [...new Set(spans)]]); + } + const config = `${cwd ?? ""}\u0000${imageBaseDir ?? ""}\u0000`; + const hrefs = new Set(); + const spans = new Set(); + const last = streamingBlocks.length - 1; + for (const [index, block] of streamingBlocks.entries()) { + // The last block still grows; caching each of its prefixes would only fill the cache. + const key = config + block; + let sources = index === last ? undefined : finishedBlockFileLinkSources.get(key); + if (!sources) { + sources = blockFileLinkSources(block, cwd, imageBaseDir); + if (index !== last) { + if (cachedBlockChars + key.length > MAX_CACHED_BLOCK_CHARS) { + finishedBlockFileLinkSources.clear(); + cachedBlockChars = 0; + } + finishedBlockFileLinkSources.set(key, sources); + cachedBlockChars += key.length; + } + } + for (const href of sources.hrefs) hrefs.add(href); + for (const span of sources.spans) spans.add(span); + } + return JSON.stringify([[...hrefs], [...spans]]); } function resolveFileLinkSources( @@ -525,27 +570,30 @@ function resolveFileLinkSources( return { markdownFileLinkMetaByHref, inlineCodeFileLinkMetaByText, fileLinkParentSuffixByPath }; } -function useChatMarkdownState({ - text, - inline = false, - cwd, - agentDirectories, - threadRef, - pullRequestPanelRef, - environmentId: explicitEnvironmentId, - onTaskListChange, - isStreaming = false, - skills = EMPTY_MARKDOWN_SKILLS, - onUseArtifactTemplate, - onRunShellCommand, - imageBaseDir, - workspaceMutationId, - onImageExpand, - renderContextReference, - headingLevelOffset = 0, - sourceControlMedia = false, - sourceControlMediaRepository, -}: ChatMarkdownProps) { +function useChatMarkdownState( + { + text, + inline = false, + cwd, + agentDirectories, + threadRef, + pullRequestPanelRef, + environmentId: explicitEnvironmentId, + onTaskListChange, + isStreaming = false, + skills = EMPTY_MARKDOWN_SKILLS, + onUseArtifactTemplate, + onRunShellCommand, + imageBaseDir, + workspaceMutationId, + onImageExpand, + renderContextReference, + headingLevelOffset = 0, + sourceControlMedia = false, + sourceControlMediaRepository, + }: ChatMarkdownProps, + streamingBlocks: ReadonlyArray | null, +) { const gt = useGT(); const messages = useMessages(); const resolvedTheme = useRenderedAppearance(); @@ -743,7 +791,7 @@ function useChatMarkdownState({ // 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 fileLinksKey = `${fileLinkSourcesKey(text, cwd, imageBaseDir, isStreaming ? (streamingBlocks ?? splitMarkdownBlocks(text) ?? [text]) : null)}`; const { markdownFileLinkMetaByHref, inlineCodeFileLinkMetaByText, fileLinkParentSuffixByPath } = resolveFileLinkSources(fileLinksKey, cwd, imageBaseDir); const resolveThreadPullRequest = ( @@ -1087,7 +1135,7 @@ function markdownHeadingRenderer(level: 1 | 2 | 3 | 4 | 5 | 6) { return function MarkdownHeading({ node: _node, ...props - }: ComponentProps & ReactMarkdownExtraProps) { + }: ComponentProps & { node?: HastElement | undefined }) { const { headingLevelOffset } = use(ChatMarkdownRendererContext); return ( ; } - return ( - - - {href} - - ); + return ; } const label = nodeToPlainText(children); @@ -1533,18 +1576,9 @@ const CHAT_MARKDOWN_COMPONENTS = { ); }, code: function MarkdownCode({ node, children, className, ...props }) { - const { cwd, imageBaseDir, inlineCodeFileLinkMetaByText, fileLinkChip, mathEnabled, inline } = - use(ChatMarkdownRendererContext); - const math = mathEnabled ? mathKind(className) : null; - if (math) { - return ( - - ); - } + const { cwd, imageBaseDir, inlineCodeFileLinkMetaByText, fileLinkChip } = use( + ChatMarkdownRendererContext, + ); if (node?.properties?.dataInlineCode != null) { const codeText = nodeToPlainText(children); const fileLinkMeta = @@ -1769,15 +1803,9 @@ const CHAT_MARKDOWN_COMPONENTS = { }, pre: function MarkdownPre({ node, children, ...props }) { const gt = useGT(); - const { - resolvedTheme, - diffThemeName, - expandMedia, - isStreaming, - onRunShellCommand, - inline, - mathEnabled, - } = use(ChatMarkdownRendererContext); + const { resolvedTheme, diffThemeName, expandMedia, isStreaming, onRunShellCommand } = use( + ChatMarkdownRendererContext, + ); const text = use(ChatMarkdownTextContext); const codeBlock = extractCodeBlock(children); if (!codeBlock) { @@ -1785,15 +1813,6 @@ const CHAT_MARKDOWN_COMPONENTS = { } const language = extractFenceLanguage(codeBlock.className); - if ( - mathEnabled && - language === "math" && - (!isStreaming || - mathKind(codeBlock.className) === "display" || - isClosedCodeFence(node, text, codeBlock.code)) - ) { - return ; - } const fenceTitle = extractFenceTitle(extractPreCodeMeta(node)); const highlightedCode = ( ); }, -} satisfies Components; - -const REMARK_MATH: Pluggable = [remarkMath, { singleDollarTextMath: true }]; -// Shared lists, so every message with the same options shares a processor and its cache. -const CHAT_MARKDOWN_REMARK_PLUGIN_SETS = { - plain: CHAT_MARKDOWN_REMARK_PLUGINS, - breaks: CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, - math: [REMARK_MATH, ...CHAT_MARKDOWN_REMARK_PLUGINS], - mathBreaks: [REMARK_MATH, ...CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS], -} satisfies Record; - -const combinedPlugins = new WeakMap>(); +} satisfies MarkdownComponents; -// One combined list per pair, so a stable extra list shares a renderer and its parse cache. -const INSIGHT_REMARK_PLUGINS: PluggableList = [remarkAssistantInsights]; +const markdownOptions = new WeakMap>(); -function withExtraPlugins(shared: PluggableList, extra: PluggableList): PluggableList { - if (extra.length === 0) return shared; - let byShared = combinedPlugins.get(extra); - if (!byShared) combinedPlugins.set(extra, (byShared = new WeakMap())); - let combined = byShared.get(shared); - if (!combined) byShared.set(shared, (combined = [...shared, ...extra])); - return combined; +/** One options object per configuration, so equal messages share a renderer and its cache. */ +function wordsOptions( + extensions: MarkdownExtensions, + flags: Omit, +): WordsHastOptions { + let byFlags = markdownOptions.get(extensions); + if (!byFlags) markdownOptions.set(extensions, (byFlags = new Map())); + const key = `${+flags.math}${+flags.breaks}${+flags.escapeHtml}${+flags.insights}`; + let options = byFlags.get(key); + if (!options) byFlags.set(key, (options = { ...flags, extensions })); + return options; } const markdownRenderers = new WeakMap< - PluggableList, - WeakMap> + WordsHastOptions, + ReturnType >(); -function markdownRenderer(remarkPlugins: PluggableList, rehypePlugins: PluggableList) { - let byRehype = markdownRenderers.get(remarkPlugins); - if (!byRehype) markdownRenderers.set(remarkPlugins, (byRehype = new WeakMap())); - let renderer = byRehype.get(rehypePlugins); +function markdownRenderer(markdown: WordsHastOptions) { + let renderer = markdownRenderers.get(markdown); if (!renderer) { renderer = createMarkdownRenderer({ - remarkPlugins, - rehypePlugins, + markdown, components: CHAT_MARKDOWN_COMPONENTS, urlTransform: markdownUrlTransform, }); - byRehype.set(rehypePlugins, renderer); + markdownRenderers.set(markdown, renderer); } return renderer; } +type ChatMarkdownComponentState = ReturnType["componentState"]; + +function hastClassName(node: HastElement): string | undefined { + const { className } = node.properties; + return Array.isArray(className) ? className.join(" ") : (className as string | undefined); +} + +// Paragraphs and list items turn skill and model mentions in their text into chips, except in +// code and links, as SkillInlineText does. +function hastTextHasChip(node: HastElement, skills: ReadonlyArray): boolean { + return node.children.some((child) => + child.type === "text" + ? (skills.length > 0 && !matchInlineSkills(child.value, skills).next().done) || + collectComposerModelMentions(child.value).length > 0 + : child.type === "element" && + child.tagName !== "code" && + child.tagName !== "a" && + hastTextHasChip(child, skills), + ); +} + +const HEADING_LEVELS: Record = { h1: 1, h2: 2, h3: 3, h4: 4, h5: 5, h6: 6 }; + +const markdownIslandOptionsByState = new WeakMap< + ChatMarkdownComponentState, + MarkdownIslandOptions +>(); + +/** Which elements need CHAT_MARKDOWN_COMPONENTS, and what the others' components add. */ +function markdownIslandOptions(state: ChatMarkdownComponentState): MarkdownIslandOptions { + const cached = markdownIslandOptionsByState.get(state); + if (cached) return cached; + const { + cwd, + headingLevelOffset, + imageBaseDir, + inlineCodeFileLinkMetaByText, + onTaskListChange, + skills, + } = state; + const options: MarkdownIslandOptions = { + components: CHAT_MARKDOWN_COMPONENTS, + variant: String(headingLevelOffset), + isIsland: (node) => { + switch (node.tagName) { + case "a": + case "img": + case "pre": + case "details": + case "table": + return true; + case "blockquote": + return GITHUB_ALERT_PRESENTATIONS[String(node.properties.dataAlert ?? "")] !== undefined; + case "div": + return artifactTemplateFromHastProperties(node.properties) !== null; + case "input": + return node.properties.type === "checkbox" && onTaskListChange !== undefined; + case "code": { + if (node.properties.dataInlineCode == null) return false; + const codeText = hastPlainTextDeep(node); + return ( + (inlineCodeFileLinkMetaByText.get(codeText.trim()) ?? + resolveInlineCodeFileLinkMeta(codeText, cwd, imageBaseDir ?? cwd)) != null + ); + } + case "p": + case "li": + return hastTextHasChip(node, skills); + default: + return false; + } + }, + staticElement: (node) => { + const level = HEADING_LEVELS[node.tagName]; + if (level !== undefined) { + return headingLevelOffset > 0 + ? withProperties(node, { ariaLevel: Math.min(level + headingLevelOffset, 6) }) + : node; + } + switch (node.tagName) { + case "ol": { + const itemValues = node.children.flatMap((child) => + child.type === "element" && child.tagName === "li" ? [child.properties.value] : [], + ); + const gutter = orderedListGutterStyle(itemValues, node.properties.start); + if (!gutter) return node; + const authored = typeof node.properties.style === "string" ? node.properties.style : ""; + return withProperties(node, { + style: `${authored}${authored ? ";" : ""}--list-gutter:${gutter["--list-gutter"]}`, + }); + } + case "li": + return hastClassName(node)?.includes("task-list-item") + ? withProperties(node, { dataListItemOffset: node.position?.start.offset }) + : node; + case "input": + return node.properties.type === "checkbox" + ? withProperties(node, { readOnly: true }) + : node; + default: + return node; + } + }, + }; + markdownIslandOptionsByState.set(state, options); + return options; +} + const MarkdownSource = memo(function MarkdownSource({ text, - remarkPlugins, - rehypePlugins, - shared, + markdown, cache, }: { text: string; - remarkPlugins: PluggableList; - rehypePlugins: PluggableList; - /** The plugins are one of the shared sets. */ - shared: boolean; + markdown: WordsHastOptions; /** The text will not change again; streamed text would only fill the cache with prefixes. */ cache: boolean; }) { - // Per-instance plugins, such as the incremental parser, set up their state on every render. - const render = shared - ? markdownRenderer(remarkPlugins, rehypePlugins) - : createMarkdownRenderer({ - remarkPlugins, - rehypePlugins, - components: CHAT_MARKDOWN_COMPONENTS, - urlTransform: markdownUrlTransform, - }); - const element = render(text); + const render = markdownRenderer(markdown); + const entry = render.parse(text); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Caching during render would make React Compiler rebuild the element when `cache` flips. useEffect(() => { - if (shared && cache) render.remember(text, element); - }, [render, text, element, shared, cache]); - return {element}; + if (cache) render.remember(text, entry); + }, [render, text, entry, cache]); + const islandState = use(ChatMarkdownRendererContext); + return ( + + {islandState + ? renderHastWithIslands(entry.tree, markdownIslandOptions(islandState)) + : render.element(entry)} + + ); }); function ChatMarkdown({ @@ -1935,51 +2045,28 @@ function ChatMarkdown({ inline = false, lineBreaks = false, parseRawHtml = true, - extraRemarkPlugins = EMPTY_REMARK_PLUGINS, + extensions = NO_EXTENSIONS, renderInsights = false, ...props }: ChatMarkdownProps) { - const { componentState, handleCopy, markdownRef, localMediaPreview, closeLocalMediaPreview } = - useChatMarkdownState({ text, inline, ...props }); - const hasInsights = renderInsights && text.includes("★ Insight"); - // Streaming re-renders only the last block; offsets for task edits need the whole text. + // Streaming re-renders only the last block; offsets for task edits, and extensions that read + // the whole message, need the whole text. const streamingBlocks = - props.isStreaming === true && - !inline && - extraRemarkPlugins.length === 0 && - !props.onTaskListChange - ? splitMarkdownBlocks(text) + props.isStreaming === true && !inline && extensions === NO_EXTENSIONS && !props.onTaskListChange + ? (splitMarkdownBlocks(text) ?? [text]) : null; - const incrementalParsing = - props.isStreaming === true && - !hasInsights && - streamingBlocks === null && - extraRemarkPlugins.length === 0 && - /(?:^|\n) {0,3}(?:`{3}|~{3})/.test(text); + const { componentState, handleCopy, markdownRef, localMediaPreview, closeLocalMediaPreview } = + useChatMarkdownState({ text, inline, ...props }, streamingBlocks); const Root = inline ? "span" : "div"; const bindMarkdownRef = (node: HTMLElement | null) => { markdownRef.current = node; }; - const sharedRemarkPlugins = - CHAT_MARKDOWN_REMARK_PLUGIN_SETS[ - componentState.mathEnabled - ? lineBreaks - ? "mathBreaks" - : "math" - : lineBreaks - ? "breaks" - : "plain" - ]; - // The incremental parser keeps per-instance state, so its output is not shared. - const uncachedPlugins = incrementalParsing; - const remarkPlugins = incrementalParsing - ? [...sharedRemarkPlugins, ...extraRemarkPlugins, createIncrementalMarkdownPlugin()] - : withExtraPlugins( - hasInsights - ? withExtraPlugins(INSIGHT_REMARK_PLUGINS, sharedRemarkPlugins) - : sharedRemarkPlugins, - extraRemarkPlugins, - ); + const markdown = wordsOptions(extensions, { + math: componentState.mathEnabled, + breaks: lineBreaks, + escapeHtml: !parseRawHtml, + insights: renderInsights && text.includes("★ Insight"), + }); const blocks = streamingBlocks ?? [text]; return ( @@ -1995,22 +2082,18 @@ function ChatMarkdown({ onCopy={handleCopy} > - {blocks.map((source, index) => ( - - ))} + + {blocks.map((source, index) => ( + + ))} + {localMediaPreview ? ( diff --git a/apps/web/src/components/chat/ChatMarkdownMedia.browser.test.tsx b/apps/web/src/components/chat/ChatMarkdownMedia.browser.test.tsx index db46999708043..04a4d9fd76f84 100644 --- a/apps/web/src/components/chat/ChatMarkdownMedia.browser.test.tsx +++ b/apps/web/src/components/chat/ChatMarkdownMedia.browser.test.tsx @@ -1,7 +1,6 @@ import type { PreparedConnection } from "@t3tools/client-runtime/connection"; import { EnvironmentId, ThreadId } from "@t3tools/contracts"; -import remarkParse from "remark-parse"; -import { unified } from "unified"; +import { markdownTree } from "~/markdown/wordsHast"; import { describe, expect, it, vi } from "vite-plus/test"; import { render } from "../../../test/render"; @@ -91,9 +90,13 @@ describe("markdownImageCopy", () => { it("copies an image whose path has a space as Markdown that is still that image", () => { // Raw HTML and sources reach the copy with the space unencoded. const copied = markdownImageCopy("Shot", "/work/my shot.png", undefined); - const [block] = unified().use(remarkParse).parse(copied).children; + const [block] = markdownTree(copied).children; const images = - block?.type === "paragraph" ? block.children.filter((node) => node.type === "image") : []; - expect(images.map((image) => decodeURI(image.url))).toEqual(["/work/my shot.png"]); + block?.type === "element" && block.tagName === "p" + ? block.children.filter((node) => node.type === "element" && node.tagName === "img") + : []; + expect( + images.map((image) => image.type === "element" && decodeURI(String(image.properties.src))), + ).toEqual(["/work/my shot.png"]); }); }); diff --git a/apps/web/src/components/chat/MarkdownCodeBlock.logic.ts b/apps/web/src/components/chat/MarkdownCodeBlock.logic.ts index fcee475c2886a..0a45cd6ac5659 100644 --- a/apps/web/src/components/chat/MarkdownCodeBlock.logic.ts +++ b/apps/web/src/components/chat/MarkdownCodeBlock.logic.ts @@ -1,5 +1,5 @@ import { Children, isValidElement, type ReactNode } from "react"; -import type { ExtraProps as ReactMarkdownExtraProps } from "react-markdown"; +import type { Element } from "hast"; import type { DiffThemeName } from "../../lib/diffRendering"; @@ -44,11 +44,7 @@ export function extractPreCodeMeta(node: unknown): string | undefined { return typeof meta === "string" && meta.trim().length > 0 ? meta.trim() : undefined; } -export function isClosedCodeFence( - node: ReactMarkdownExtraProps["node"], - text: string, - code: string, -): boolean { +export function isClosedCodeFence(node: Element | undefined, text: string, code: string): boolean { const start = node?.position?.start.offset; const end = node?.position?.end.offset; if (start === undefined || end === undefined) return false; @@ -98,7 +94,7 @@ export function extractCodeBlock( return null; } // With a custom `code` component the child's type is that component, not - // the "code" tag — the hast node react-markdown attaches still names it. + // the "code" tag — the hast node the renderer passes still names it. if (onlyChild.type !== "code" && onlyChild.props.node?.tagName !== "code") { return null; } diff --git a/apps/web/src/components/chat/MarkdownCodeBlock.tsx b/apps/web/src/components/chat/MarkdownCodeBlock.tsx index d6c8a7aaba2eb..726c34cbf029e 100644 --- a/apps/web/src/components/chat/MarkdownCodeBlock.tsx +++ b/apps/web/src/components/chat/MarkdownCodeBlock.tsx @@ -1,4 +1,4 @@ -import { T, useGT } from "gt-react"; +import { useGT } from "gt-react"; import { PlayIcon, WrapTextIcon, CheckIcon, CopyIcon } from "lucide-react"; import { toHtml } from "hast-util-to-html"; import React, { use, useEffect, useState, type ReactNode } from "react"; @@ -18,7 +18,7 @@ import { syntheticFileNameForLanguageId, } from "../../pierre-icons"; import { Button } from "../ui/button"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; import { HighlightedCodeLines } from "./HighlightedCodeLines"; import { createHighlightCacheKey, @@ -115,19 +115,17 @@ function MarkdownCodeBlockTitleContent({ return {language}; } return ( - - - } - > - - - {language} - + + } + > + + ); } @@ -187,22 +185,20 @@ export function MarkdownCodeBlock({ const handleCopy = () => copyToClipboard(code.endsWith("\n") ? code.slice(0, -1) : code); const copyButton = ( - - - } - > - {copied ? : } - - {copyLabel} - + + } + > + {copied ? : } + ); if (diagram) { @@ -231,43 +227,37 @@ export function MarkdownCodeBlock({ aria-label={gt("Code block actions")} > {canWrap ? ( - - setWrapOverride(!wrapped)} - aria-label={wrapLabel} - /> - } - > - - - {wrapLabel} - + setWrapOverride(!wrapped)} + aria-label={wrapLabel} + /> + } + > + + ) : null} {canRun ? ( - - onRunShellCommand(command)} - aria-label={gt("Run in terminal")} - /> - } - > - - - - Run in terminal - - + onRunShellCommand(command)} + aria-label={gt("Run in terminal")} + /> + } + > + + ) : null} {viewToggle} {copyButton} diff --git a/apps/web/src/components/chat/MarkdownDetails.tsx b/apps/web/src/components/chat/MarkdownDetails.tsx index 5ec510c3a4306..b6fa2b1d8d1f1 100644 --- a/apps/web/src/components/chat/MarkdownDetails.tsx +++ b/apps/web/src/components/chat/MarkdownDetails.tsx @@ -1,5 +1,6 @@ import { useGT } from "gt-react"; import { ChevronRightIcon } from "lucide-react"; +import { flushSync } from "react-dom"; import { Children, isValidElement, @@ -12,6 +13,11 @@ import { import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible"; import { findRevealRef, MarkdownFindContext } from "./markdownFindContext"; +const focusOnMount = (element: HTMLElement | null) => { + if (element && element.ownerDocument.activeElement === element.ownerDocument.body) + element.focus(); +}; + export function MarkdownDetails({ children, open = false, @@ -19,6 +25,7 @@ export function MarkdownDetails({ }: Pick, "children" | "open" | "dir">) { const gt = useGT(); const [isOpen, setIsOpen] = useState(open); + const [armed, setArmed] = useState<"hover" | "focus" | null>(null); const searching = use(MarkdownFindContext); const expanded = isOpen; const revealForFind = () => setIsOpen(true); @@ -36,6 +43,36 @@ export function MarkdownDetails({ : gt("Details", { $context: "fallback title of a collapsible section" }); const content = childNodes.filter((_, index) => index !== summaryIndex); + // Most details stay closed: mount Base UI on hover or focus, before the first click. + if (!armed && !expanded && !searching) { + return ( +
    +
    + +
    +
    + ); + } + return (
    - } - className={MARKDOWN_FILE_LINK_CLASS_NAME} - data-markdown-copy={copyMarkdown} - onClick={(event) => { - event.preventDefault(); - event.stopPropagation(); - if (onOpen && shouldOpenMarkdownFileLinkInEditor(event)) { - handleOpenInEditor(); - return; - } - if (useBrowserPrimaryAction) { - handleOpenInBrowser(); - return; - } - handleOpenInFilePreview(); - }} - onContextMenu={handleContextMenu} - > - - ) : undefined - } - path={iconPath} - environmentId={environmentId} - label={label} - theme={theme} - /> - - ) : ( - } - aria-label={gt("File options for {label}", { label })} - aria-haspopup="menu" - className={cn(MARKDOWN_FILE_LINK_CLASS_NAME, "select-text")} - data-markdown-copy={copyMarkdown} - onClick={handleContextMenu} - onContextMenu={handleContextMenu} - > - - ) : undefined - } - path={iconPath} - environmentId={environmentId} - label={label} - theme={theme} - /> - - ) + const tooltipContent = ( + + ); + const sharedTooltip = useSharedTooltip({ + render: () => tooltipContent, + contentKey: `${iconPath}\u0000${targetPath}`, + variant: "code", + }); + const chip = hasPrimaryAction ? ( + } + className={MARKDOWN_FILE_LINK_CLASS_NAME} + data-markdown-copy={copyMarkdown} + onClick={(event) => { + event.preventDefault(); + event.stopPropagation(); + if (onOpen && shouldOpenMarkdownFileLinkInEditor(event)) { + handleOpenInEditor(); + return; + } + if (useBrowserPrimaryAction) { + handleOpenInBrowser(); + return; } + handleOpenInFilePreview(); + }} + onContextMenu={handleContextMenu} + > + : undefined + } + path={iconPath} + environmentId={environmentId} + label={label} + theme={theme} + /> + + ) : ( + } + aria-label={gt("File options for {label}", { label })} + aria-haspopup="menu" + className={cn(MARKDOWN_FILE_LINK_CLASS_NAME, "select-text")} + data-markdown-copy={copyMarkdown} + onClick={handleContextMenu} + onContextMenu={handleContextMenu} + > + : undefined + } + path={iconPath} + environmentId={environmentId} + label={label} + theme={theme} /> + + ); + if (sharedTooltip) return withSharedTooltip(chip, sharedTooltip); + return ( + + - + {tooltipContent} ); diff --git a/apps/web/src/components/chat/MarkdownMath.browser.test.tsx b/apps/web/src/components/chat/MarkdownMath.browser.test.tsx deleted file mode 100644 index ec5b38541ddc4..0000000000000 --- a/apps/web/src/components/chat/MarkdownMath.browser.test.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import { expect, it } from "vite-plus/test"; -import { userEvent } from "vite-plus/test/browser"; - -import { render } from "../../../test/render"; -import "../../index.css"; - -import { MarkdownMath } from "./MarkdownMath"; - -it("keeps keyboard scrolling available as a streamed equation outgrows its viewport", async () => { - const equation = (tex: string, width = 180) => ( -
    - - - -
    - ); - await using screen = await render(equation("x")); - await screen.getByRole("button", { name: "Before equation" }).click(); - await userEvent.keyboard("{Tab}"); - await expect.element(screen.getByRole("button", { name: "After equation" })).toHaveFocus(); - - await screen.rerender(equation("x_1 + x_2 + x_3 + x_4 + x_5 + x_6 + x_7 + x_8")); - const scroller = screen.getByLabelText("Scroll display equation"); - await expect.element(scroller).toHaveAttribute("tabindex", "0"); - await screen.getByRole("button", { name: "Before equation" }).click(); - await userEvent.keyboard("{Tab}"); - await expect.element(scroller).toHaveFocus(); - await userEvent.keyboard("{ArrowRight}"); - await expect.element(scroller).not.toHaveProperty("scrollLeft", 0); - - await screen.rerender(equation("x_1 + x_2 + x_3 + x_4 + x_5 + x_6 + x_7 + x_8", 1000)); - await expect.element(screen.getByLabelText("Scroll display equation")).not.toBeInTheDocument(); - await screen.getByRole("button", { name: "Before equation" }).click(); - await userEvent.keyboard("{Tab}"); - await expect.element(screen.getByRole("button", { name: "After equation" })).toHaveFocus(); -}); diff --git a/apps/web/src/components/chat/MarkdownMath.tsx b/apps/web/src/components/chat/MarkdownMath.tsx deleted file mode 100644 index 8070d64ac3c18..0000000000000 --- a/apps/web/src/components/chat/MarkdownMath.tsx +++ /dev/null @@ -1,81 +0,0 @@ -import { useGT } from "gt-react"; -import { lazy, memo, Suspense, useLayoutEffect, useRef, useState } from "react"; - -import { observeResize } from "../../lib/observeResize"; - -import { RenderErrorBoundary } from "../RenderErrorBoundary"; - -const MathTypeset = lazy(() => import("./MathTypeset")); - -/** - * One formula from `remark-math`. Shows its TeX until KaTeX loads, and - * keeps showing it when KaTeX cannot parse it, such as mid-stream. Copying - * any part of a formula copies its whole TeX source. - */ -export const MarkdownMath = memo(function MarkdownMath(props: { - tex: string; - display: boolean; - focusable?: boolean; -}) { - const gt = useGT(); - const viewportRef = useRef(null); - const contentRef = useRef(null); - const [overflows, setOverflows] = useState(false); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- observes formula DOM width to make overflowing equations keyboard scrollable - useLayoutEffect(() => { - const viewport = viewportRef.current; - const content = contentRef.current; - if (!viewport || !content || props.focusable === false) return; - const measure = () => setOverflows(viewport.scrollWidth > viewport.clientWidth); - measure(); - // Typesetting and streamed TeX can change content width without resizing the viewport. - return observeResize([viewport, content], measure); - }, [props.focusable]); - const scrollable = props.focusable !== false && overflows; - const tex = props.tex.trim(); - const source = props.display ? `\\[\n${tex}\n\\]` : `\\(${tex}\\)`; - const fallback = {source}; - return ( - - - - - - - - - - - - ); -}); diff --git a/apps/web/src/components/chat/MathTypeset.logic.test.ts b/apps/web/src/components/chat/MathTypeset.logic.test.ts deleted file mode 100644 index 634f5146475ac..0000000000000 --- a/apps/web/src/components/chat/MathTypeset.logic.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import katex from "katex"; -import { describe, expect, it } from "vite-plus/test"; - -import { escapeLiteralPercents } from "./MathTypeset.logic"; - -describe("escapeLiteralPercents", () => { - it.each([ - ["\\text{3.18% yield}", "\\text{3.18\\% yield}"], - ["\\text{100%% yield}", "\\text{100\\%\\% yield}"], - ["6\\% + 2\\%", "6\\% + 2\\%"], - ["x\\\\%", "x\\\\\\%"], - ["x % note\n+ 1", "x % note\n+ 1"], - ["% note\n\\text{2%}", "% note\n\\text{2\\%}"], - ["x &= 1 % +9%\n\\text{2%}", "x &= 1 % +9%\n\\text{2\\%}"], - ["\\verb|50%|+\\text{2%}", "\\verb|50%|+\\text{2\\%}"], - ["\\verb*%a%b%+c%", "\\verb*%a%b\\%+c\\%"], - ["\\verb|50%+\\text{2%}", "\\verb|50%+\\text{2%}"], - ])("repairs %j", (tex, expected) => { - expect(escapeLiteralPercents(tex)).toBe(expected); - }); - - it("lets the reported multiline equation typeset", () => { - const tex = - "R_e=\\underbrace{\\frac{1.0176}{32}}_{\\text{3.18% dividend yield}}\n+\\underbrace{6\\%}_{\\text{growth}}\n=\\boxed{9.18\\%}"; - expect(() => katex.renderToString(tex, { throwOnError: true })).toThrow(); - expect(() => - katex.renderToString(escapeLiteralPercents(tex), { throwOnError: true }), - ).not.toThrow(); - }); -}); diff --git a/apps/web/src/components/chat/MathTypeset.logic.ts b/apps/web/src/components/chat/MathTypeset.logic.ts deleted file mode 100644 index 04111ab4a70b4..0000000000000 --- a/apps/web/src/components/chat/MathTypeset.logic.ts +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Escapes each `%` written right after other text, as in `\text{3.18% yield}`. - * A `%` at a line start or after whitespace stays a comment. Skips escapes and - * `\verb` like KaTeX's lexer, in one linear pass. - */ -export function escapeLiteralPercents(tex: string): string { - let repaired = ""; - let copied = 0; - let index = 0; - while (index < tex.length) { - const char = tex[index]; - if (char === "\\") { - if (tex.startsWith("\\verb", index)) { - const starred = tex[index + 5] === "*"; - const delimiter = tex[index + (starred ? 6 : 5)]; - if (delimiter !== undefined && (starred || !/[*a-zA-Z]/.test(delimiter))) { - const bodyStart = index + (starred ? 7 : 6); - let close = bodyStart; - while (close < tex.length && ![delimiter, "\n", "\r"].includes(tex[close]!)) close++; - // KaTeX rejects a \verb that does not close on its own line. - if (tex[close] !== delimiter) return tex; - index = close + 1; - continue; - } - } - // A control symbol such as `\%` or `\\` is two characters. - index += 2; - } else if (char === "%" && index > 0 && !/\s/.test(tex[index - 1]!)) { - repaired += `${tex.slice(copied, index)}\\%`; - copied = ++index; - } else if (char === "%") { - const newline = tex.indexOf("\n", index); - index = newline === -1 ? tex.length : newline + 1; - } else { - index++; - } - } - return copied === 0 ? tex : repaired + tex.slice(copied); -} diff --git a/apps/web/src/components/chat/MathTypeset.tsx b/apps/web/src/components/chat/MathTypeset.tsx deleted file mode 100644 index 16d3dba409ee6..0000000000000 --- a/apps/web/src/components/chat/MathTypeset.tsx +++ /dev/null @@ -1,49 +0,0 @@ -import katex from "katex"; -import "katex/dist/katex.min.css"; -import type { ReactNode } from "react"; - -import { LRUCache } from "../../lib/lruCache"; -import { escapeLiteralPercents } from "./MathTypeset.logic"; - -// Virtualized threads remount messages while scrolling; cached markup keeps -// that from typesetting the same formulas again. "" records a parse error. -const typesetCache = new LRUCache(1000, 4 * 1024 * 1024); - -function typeset(tex: string, display: boolean): string { - const key = `${display ? "display" : "inline"}:${tex}`; - const cached = typesetCache.get(key); - if (cached !== null) return cached; - const options = { - displayMode: display, - output: "htmlAndMathml" as const, - throwOnError: true, - // No \href, \url, \htmlClass, or other commands that emit active HTML. - trust: false, - strict: "ignore" as const, - maxSize: 20, - maxExpand: 1000, - }; - let html = ""; - try { - html = katex.renderToString(tex, options); - } catch { - const repaired = escapeLiteralPercents(tex); - if (repaired !== tex) { - try { - html = katex.renderToString(repaired, options); - } catch { - // Unfinished or unsupported TeX stays readable as its source. - } - } - } - typesetCache.set(key, html, (key.length + html.length) * 2); - return html; -} - -/** KaTeX lives in this lazily loaded chunk, so it is only fetched once a formula renders. */ -export default function MathTypeset(props: { tex: string; display: boolean; fallback: ReactNode }) { - const html = typeset(props.tex, props.display); - if (!html) return props.fallback; - // KaTeX escapes the TeX it renders, and `trust: false` keeps it from emitting links or attributes. - return ; -} diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index 2e7721dddea18..d15a26ca43db0 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -44,11 +44,10 @@ import { type PendingApproval, deriveTimelineEntriesFromVisibleTurnItems, } from "../../session-logic"; -import type { Root } from "mdast"; import { ViewedImagesTimelineRow } from "./TimelineWorkEntryRow"; -import { remarkThoughtPreview, THOUGHT_PREVIEW_MAX_LENGTH } from "./TimelineWorkEntryRow.logic"; +import { THOUGHT_PREVIEW_MAX_LENGTH, thoughtPreviewMarkdown } from "./TimelineWorkEntryRow.logic"; +import { wordsHast } from "~/markdown/wordsHast"; import { TimelineRowCtx } from "./timelineRowContext"; -import { parseMarkdownWithMath } from "@t3tools/shared/markdownMath"; import { searchableMessageSegments } from "@t3tools/shared/threadFindText"; import { countThreadSearchOccurrences } from "@t3tools/shared/threadSearch"; import { collectThreadFindRanges } from "./threadFindHighlights"; @@ -2128,49 +2127,22 @@ describe("compact reasoning math", () => { ["hard \nbreak\\\nagain", [["text", "hard break again"]]], ["
    only html
    ", [["text", "Reasoning"]]], ])("keeps formulas while flattening compact reasoning previews: %j", (source, expected) => { - const tree = parseMarkdownWithMath(source); - remarkThoughtPreview("Reasoning")(tree); - expect(tree.children.map((node) => [node.type, "value" in node ? node.value : null])).toEqual( - expected, - ); - }); - - it("stops reading the tree once the preview is full", () => { - const beyondCap = (): string => { - throw new Error("read beyond cap"); - }; - const head = "x".repeat(THOUGHT_PREVIEW_MAX_LENGTH - 2); - const tree: Root = { - type: "root", - children: [ - { - type: "paragraph", - children: [ - { type: "text", value: head }, - { type: "strong", children: [{ type: "text", value: "yz beyond" }] }, - { - type: "inlineMath", - get value() { - return beyondCap(); - }, - }, - ], - }, - { - type: "paragraph", - children: [ - { - type: "text", - get value() { - return beyondCap(); - }, - }, - ], - }, - ], - }; - remarkThoughtPreview("Reasoning")(tree); - expect(tree.children).toEqual([{ type: "text", value: `${head}yz` }]); + const tree = wordsHast(source, { + math: true, + breaks: false, + escapeHtml: false, + insights: false, + extensions: thoughtPreviewMarkdown("Reasoning"), + }); + expect( + tree.children.map((node) => + node.type === "text" + ? ["text", node.value] + : node.type === "element" && node.children[0]?.type === "element" + ? ["inlineMath", String(node.children[0].properties.ariaLabel).trim()] + : [node.type, null], + ), + ).toEqual(expected); }); }); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 124062303e0cf..b00a48185b9db 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -14,7 +14,7 @@ import { IDLE_COMPACTION_TITLES, } from "@t3tools/client-runtime/user-message"; import type { HandoffTimelineRun } from "@t3tools/client-runtime/handoff"; -import { renderCodexDirectivesForCopy } from "@t3tools/shared/codexMarkdownDirectives"; +import { renderCodexDirectivesForCopy } from "~/markdown/markdownText"; import { commandDisplayText, commandProgramName, diff --git a/apps/web/src/components/chat/TimelineAssistantRows.tsx b/apps/web/src/components/chat/TimelineAssistantRows.tsx index 7ab6e361494ee..72fcf79013e87 100644 --- a/apps/web/src/components/chat/TimelineAssistantRows.tsx +++ b/apps/web/src/components/chat/TimelineAssistantRows.tsx @@ -1,4 +1,4 @@ -import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/markdownPipeline"; +import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/assistantInsights"; import { MessageId, type RunId, type TurnItemId } from "@t3tools/contracts"; import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows"; import { agentWorkingDirectories } from "@t3tools/client-runtime/workspace-basename-lookup"; diff --git a/apps/web/src/components/chat/TimelineUserMessageRow.tsx b/apps/web/src/components/chat/TimelineUserMessageRow.tsx index 88cdd61b58cc5..cd99aad44d080 100644 --- a/apps/web/src/components/chat/TimelineUserMessageRow.tsx +++ b/apps/web/src/components/chat/TimelineUserMessageRow.tsx @@ -1,10 +1,7 @@ import { copySnapshot as copySnapshotToClipboard } from "./copySnapshot"; import { InlineAudioPreview } from "../files/InlineAudioPreview"; import { filePreviewKind } from "@t3tools/shared/filePreview"; -import { - CHAT_USER_MARKDOWN_REMARK_PLUGINS, - remarkEnableOrderedListNumbers, -} from "@t3tools/shared/markdownPipeline"; +import type { MarkdownExtensions } from "~/markdown/wordsHast"; import { T, useGT, useMessages, Var } from "gt-react"; import { findRevealRef } from "./markdownFindContext"; import { @@ -1284,10 +1281,7 @@ const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(prop ); }); -const USER_MESSAGE_REMARK_PLUGINS = [ - ...CHAT_USER_MARKDOWN_REMARK_PLUGINS, - remarkEnableOrderedListNumbers, -]; +const USER_MESSAGE_MARKDOWN: MarkdownExtensions = { userMessage: true, leadingWhitespace: true }; const UserMessageBody = memo(function UserMessageBody(props: { text: string; @@ -1308,7 +1302,7 @@ const UserMessageBody = memo(function UserMessageBody(props: { className="text-message-foreground user-message-markdown" lineBreaks parseRawHtml={false} - extraRemarkPlugins={USER_MESSAGE_REMARK_PLUGINS} + extensions={USER_MESSAGE_MARKDOWN} renderContextReference={props.renderContextReference} headingLevelOffset={MESSAGE_HEADING_LEVEL} /> diff --git a/apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts b/apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts index dc279ea8cb164..894f58f45edb4 100644 --- a/apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts +++ b/apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts @@ -1,6 +1,5 @@ import { msg } from "gt-react"; -import type { PluggableList } from "unified"; -import type { Root, RootContent } from "mdast"; +import type { MarkdownExtensions } from "~/markdown/wordsHast"; import { resolveWorkEntryToolPresentation, toolGroupAction, @@ -209,67 +208,14 @@ export function workEntryIconName(workEntry: TimelineWorkEntry): WorkEntryIconNa export const THOUGHT_PREVIEW_SOURCE_MAX_LENGTH = 8_192; export const THOUGHT_PREVIEW_MAX_LENGTH = 2_048; -/** Compact reasoning keeps formulas while flattening other Markdown into label text. */ -export function remarkThoughtPreview(fallback: string) { - return (tree: Root) => { - const children: RootContent[] = []; - let remaining = THOUGHT_PREVIEW_MAX_LENGTH; - let fragments: string[] = []; - const flush = () => { - if (fragments.length === 0) return; - children.push({ type: "text", value: fragments.join("").replace(/\s+/g, " ") }); - fragments = []; - }; - const take = (value: string) => { - const text = value.slice(0, remaining); - remaining = text.length < value.length ? 0 : remaining - text.length; - // A cut here or at the source limit must not leave half a surrogate pair. - return text.replace(/[\uD800-\uDBFF]$/, ""); - }; - const append = (value: string) => { - fragments.push(take(value)); - }; - const visit = (node: Root | RootContent) => { - if (remaining === 0 || node.type === "html" || node.type === "definition") return; - if (node.type === "math" || node.type === "inlineMath") { - flush(); - const value = take(node.value); - children.push({ - type: "inlineMath", - value, - position: node.position, - data: { - hName: "code", - hProperties: { className: ["language-math", "math-inline"] }, - hChildren: [{ type: "text", value }], - }, - }); - } else if ("alt" in node) append(node.alt ?? ""); - else if ("value" in node) append(node.value); - else if ("children" in node) { - for (const [index, child] of node.children.entries()) { - if (remaining === 0) break; - if ( - index && - ["root", "blockquote", "list", "listItem", "table", "tableRow"].includes(node.type) - ) - append(" "); - visit(child); - } - } else if (node.type === "break") append(" "); - }; - visit(tree); - flush(); - const first = children[0]; - const last = children.at(-1); - if (first?.type === "text") first.value = first.value.trimStart(); - if (last?.type === "text") last.value = last.value.trimEnd(); - tree.children = children.some((child) => child.type !== "text" || child.value) - ? children - : [{ type: "text", value: fallback }]; - }; -} +const thoughtPreviews = new Map(); -export function thoughtPreviewPlugins(fallback: string): PluggableList { - return [[remarkThoughtPreview, fallback]]; +/** Compact reasoning keeps formulas while flattening other Markdown into label text. */ +export function thoughtPreviewMarkdown(fallback: string): MarkdownExtensions { + let extensions = thoughtPreviews.get(fallback); + if (!extensions) { + extensions = { preview: { fallback, maxLength: THOUGHT_PREVIEW_MAX_LENGTH } }; + thoughtPreviews.set(fallback, extensions); + } + return extensions; } diff --git a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx index 8e7f03618e59d..4cd6fc0e8dee6 100644 --- a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx +++ b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx @@ -73,7 +73,7 @@ import { workEntryRawCommand, buildToolCallExpandedBody, workEntryIconName, - thoughtPreviewPlugins, + thoughtPreviewMarkdown, THOUGHT_PREVIEW_SOURCE_MAX_LENGTH, } from "./TimelineWorkEntryRow.logic"; @@ -590,10 +590,10 @@ function WorkEntryLogRow(props: WorkEntryRowProps) { )} cwd={ctx.markdownCwd} parseRawHtml={false} - extraRemarkPlugins={ + extensions={ workEntry.toolLifecycleStatus === "inProgress" - ? thoughtPreviewPlugins(gt("Thinking")) - : thoughtPreviewPlugins(gt("Thought")) + ? thoughtPreviewMarkdown(gt("Thinking")) + : thoughtPreviewMarkdown(gt("Thought")) } /> ) : threadLabel ? ( diff --git a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx index 745a7aff68fdf..c67c76bf4cca3 100644 --- a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx +++ b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx @@ -56,7 +56,7 @@ import { SimpleWorkEntryRow, } from "./TimelineWorkEntryRow"; import { - thoughtPreviewPlugins, + thoughtPreviewMarkdown, THOUGHT_PREVIEW_SOURCE_MAX_LENGTH, toolGroupSummaryIconName, workEntryIconName, @@ -640,7 +640,7 @@ export function LiveWorkEntryTimelineRow({ text={thoughtLine} cwd={ctx.markdownCwd} parseRawHtml={false} - extraRemarkPlugins={thoughtPreviewPlugins(gt("Thought"))} + extensions={thoughtPreviewMarkdown(gt("Thought"))} />
    } @@ -661,10 +661,10 @@ export function LiveWorkEntryTimelineRow({ text={(row.entry.detail ?? label).slice(0, THOUGHT_PREVIEW_SOURCE_MAX_LENGTH)} cwd={ctx.markdownCwd} parseRawHtml={false} - extraRemarkPlugins={ + extensions={ row.active - ? thoughtPreviewPlugins(gt("Thinking")) - : thoughtPreviewPlugins(gt("Thought")) + ? thoughtPreviewMarkdown(gt("Thinking")) + : thoughtPreviewMarkdown(gt("Thought")) } /> ) : threadLabel ? ( diff --git a/apps/web/src/components/chat/markdownIslands.test.ts b/apps/web/src/components/chat/markdownIslands.test.ts new file mode 100644 index 0000000000000..f328c9ea51251 --- /dev/null +++ b/apps/web/src/components/chat/markdownIslands.test.ts @@ -0,0 +1,50 @@ +import type { Root } from "hast"; +import { renderToStaticMarkup } from "react-dom/server"; +import { createElement, Fragment } from "react"; +import { describe, expect, it } from "vite-plus/test"; + +import { renderHastWithIslands } from "./markdownIslands"; + +describe("renderHastWithIslands", () => { + it("writes SVG attributes by their SVG names in static HTML", () => { + const tree: Root = { + type: "root", + children: [ + { + type: "element", + tagName: "p", + properties: {}, + children: [ + { + type: "element", + tagName: "svg", + properties: { viewBox: "0 0 1 1" }, + children: [ + { + type: "element", + tagName: "text", + properties: { fontSize: "700", strokeWidth: "2" }, + children: [{ type: "text", value: "x" }], + }, + ], + }, + ], + }, + ], + }; + const html = renderToStaticMarkup( + createElement( + Fragment, + null, + renderHastWithIslands(tree, { + components: {}, + variant: "", + isIsland: () => false, + staticElement: (node) => node, + }), + ), + ); + expect(html).toContain('x'); + expect(html).toContain('viewBox="0 0 1 1"'); + }); +}); diff --git a/apps/web/src/components/chat/markdownIslands.ts b/apps/web/src/components/chat/markdownIslands.ts new file mode 100644 index 0000000000000..8c434daf099ce --- /dev/null +++ b/apps/web/src/components/chat/markdownIslands.ts @@ -0,0 +1,214 @@ +import type { Element, ElementContent, Properties, Root, RootContent } from "hast"; +import { find, html as htmlSchema, svg as svgSchema } from "property-information"; +import { toJsxRuntime, type Components } from "hast-util-to-jsx-runtime"; +import { createElement, Fragment as ReactFragment, type ReactNode } from "react"; +import { Fragment, jsx, jsxs } from "react/jsx-runtime"; + +export interface MarkdownIslandOptions { + readonly components: Partial; + /** Elements that need their React component; everything else renders as static HTML. */ + readonly isIsland: (node: Element) => boolean; + /** What a static element's component would have added, or the node itself when nothing. */ + readonly staticElement: (node: Element) => Element; + /** Separates static HTML that `staticElement` renders differently, such as a heading offset. */ + readonly variant: string; +} + +const VOID_ELEMENTS = new Set( + "area base br col embed hr img input link meta source track wbr".split(" "), +); + +const jsxOptions = (components: Partial) => + ({ + Fragment, + components, + ignoreInvalidStyle: true, + jsx, + jsxs, + passKeys: true, + passNode: true, + }) as const; + +// Static HTML depends only on the cached, immutable tree and the variant. +const innerHtmlCache = new WeakMap(); + +function transformStatic( + node: ElementContent, + staticElement: MarkdownIslandOptions["staticElement"], +): ElementContent { + if (node.type !== "element") return node; + const element = staticElement(node); + let children: ElementContent[] | undefined; + for (let index = 0; index < element.children.length; index++) { + const child = element.children[index]!; + const next = transformStatic(child, staticElement); + if (next !== child) { + children ??= element.children.slice(); + children[index] = next; + } + } + return children ? { ...element, children } : element; +} + +function innerHtml(node: Element, options: MarkdownIslandOptions): string { + const cached = innerHtmlCache.get(node); + if (cached?.variant === options.variant) return cached.html; + let html = ""; + for (const child of node.children) { + html += serialize(transformStatic(child, options.staticElement)); + } + innerHtmlCache.set(node, { variant: options.variant, html }); + return html; +} + +interface AttributeInfo { + readonly name: string; + readonly boolean: boolean; + readonly separator: string; +} + +const attributeInfo = new Map(); + +// SVG names its attributes differently (`fontSize` is `font-size`), so its lookups key apart. +function infoFor(property: string, inSvg: boolean): AttributeInfo { + const key = inSvg ? `svg:${property}` : property; + let info = attributeInfo.get(key); + if (!info) { + const found = find(inSvg ? svgSchema : htmlSchema, property); + info = { + name: found.attribute, + boolean: found.boolean || found.overloadedBoolean, + separator: found.commaSeparated ? ", " : " ", + }; + attributeInfo.set(key, info); + } + return info; +} + +const escapeText = (value: string) => + value.includes("&") || value.includes("<") || value.includes(">") + ? value.replace(/&/g, "&").replace(//g, ">") + : value; +const escapeAttribute = (value: string) => + value.includes("&") || value.includes('"') + ? value.replace(/&/g, "&").replace(/"/g, """) + : value; + +/** HTML for the elements and text this pipeline builds; the DOM matches hast-util-to-html's. */ +function serialize(node: ElementContent, inSvg = false): string { + if (node.type === "text") return escapeText(node.value); + if (node.type !== "element") return ""; + const svg = inSvg || node.tagName === "svg"; + let html = `<${node.tagName}`; + const { properties } = node; + for (const key in properties) { + const value = properties[key]; + if (value === null || value === undefined || value === false || Number.isNaN(value)) continue; + const info = infoFor(key, svg); + if (info.boolean && value) { + html += ` ${info.name}`; + continue; + } + const text = Array.isArray(value) + ? value.join(info.separator) + : value === true + ? "" + : String(value); + html += ` ${info.name}="${escapeAttribute(text)}"`; + } + html += ">"; + if (VOID_ELEMENTS.has(node.tagName)) return html; + for (const child of node.children) html += serialize(child, svg); + return `${html}`; +} + +/** React props for an element, converted as hast-util-to-jsx-runtime converts them. */ +function shallowProps(node: Element, components: Partial): Record { + const element = toJsxRuntime( + { ...node, children: [] }, + { ...jsxOptions(components), components: {}, passNode: false }, + ) as { props: Record }; + const { children: _children, ...props } = element.props; + return props; +} + +interface Plan { + readonly islands: Set; + /** Elements with an island somewhere below them. */ + readonly ancestors: Set; +} + +function renderContent( + node: RootContent, + key: number, + options: MarkdownIslandOptions, + plan: Plan, +): ReactNode { + if (node.type === "text") return node.value; + if (node.type !== "element") return null; + if (plan.islands.has(node)) { + return createElement( + ReactFragment, + { key }, + toJsxRuntime(node, jsxOptions(options.components)), + ); + } + const element = options.staticElement(node); + const props: Record = { ...shallowProps(element, options.components), key }; + if (plan.ancestors.has(node)) { + return createElement( + element.tagName, + props, + ...element.children.map((child, index) => renderContent(child, index, options, plan)), + ); + } + if (element.children.length > 0 && !VOID_ELEMENTS.has(element.tagName)) { + props.dangerouslySetInnerHTML = { __html: innerHtml(node, options) }; + } + return createElement(element.tagName, props); +} + +/** + * Renders a hast tree with React only on the path to elements that need a component: subtrees + * without one become static HTML, which the browser builds without React reconciling each node. + */ +export function renderHastWithIslands(tree: Root, options: MarkdownIslandOptions): ReactNode { + // The same elements again let React skip the block; islands still follow their context. + let signature = options.variant; + const plan: Plan = { islands: new Set(), ancestors: new Set() }; + const visit = (node: Root | Element): boolean => { + let below = false; + for (const child of node.children) { + if (child.type !== "element") continue; + const island = options.isIsland(child); + signature += island ? "1" : "0"; + if (island) { + plan.islands.add(child); + below = true; + continue; + } + if (visit(child)) { + plan.ancestors.add(child); + below = true; + } + } + return below; + }; + visit(tree); + const cached = renderedTrees.get(tree); + if (cached?.signature === signature && cached.components === options.components) { + return cached.node; + } + const node = tree.children.map((child, index) => renderContent(child, index, options, plan)); + renderedTrees.set(tree, { signature, components: options.components, node }); + return node; +} + +const renderedTrees = new WeakMap< + Root, + { signature: string; components: Partial; node: ReactNode } +>(); + +export function withProperties(node: Element, properties: Properties): Element { + return { ...node, properties: { ...node.properties, ...properties } }; +} diff --git a/apps/web/src/components/chat/markdownRenderer.test.tsx b/apps/web/src/components/chat/markdownRenderer.test.tsx index f15fe49584aea..a9a60c545b37b 100644 --- a/apps/web/src/components/chat/markdownRenderer.test.tsx +++ b/apps/web/src/components/chat/markdownRenderer.test.tsx @@ -1,88 +1,41 @@ -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 { createIncrementalMarkdownPlugin } from "../../markdown-incremental"; import { createMarkdownRenderer } from "./markdownRenderer"; // Visible in the markup, so every URL attribute must pass through it. const urlTransform = (url: string) => `${url}#seen`; describe("createMarkdownRenderer", () => { - const render = createMarkdownRenderer({ - remarkPlugins: CHAT_MARKDOWN_REMARK_PLUGINS, - rehypePlugins: CHAT_MARKDOWN_REHYPE_PLUGINS, + const renderer = createMarkdownRenderer({ + markdown: { math: false, breaks: false, escapeHtml: false, insights: false, extensions: {} }, components: {}, urlTransform, }); + const render = (text: string) => renderer.element(renderer.parse(text)); + const renderAndRemember = (text: string) => { + const entry = renderer.parse(text); + renderer.remember(text, entry); + return renderer.element(entry); + }; - it.each([ - '# Title\n\nText with `code`, **bold**, [a link](https://example.com "t") and https://bare.example.com.', - "![shot](./shot.png) and [file](file:///C:/repo/a.ts) and [bad](javascript:alert(1))", - "
    More\n\nHidden bold \n\n
    ", - "| a | b |\n| - | - |\n|
    | [x](#frag) |\n\n- [ ] task\n- [x] done", - '```ts title="a.ts"\nconst a = 1;\n```\n\n> [!WARNING]\n> careful
    bare', - "Footnote[^1] and ~~strike~~\n\n[^1]: the note", - // Each GFM construct the parser skips when its text cannot match, next to one that can. - "Mail me@example.com, see www.example.com and HTTPS://example.com/a, not [x](https://y.z).", - "a.b-c_d+e@x.io and @user\n\n`me@x.io` ", - "A table without pipes\n:--", - "> | quoted |\n> | - |\n> | body |\n\n- [ ] open\n- [X] done", - "Escaped www\\.example.com and me@example.com", - "\ufeffA byte order mark\n\n| a |\n| - |\n| b |", - "> - | a |\r\n> | - |\r\n> | me@x.io |\r\n\n-\t[ ] tab\n\n ~~lazy~~", - ])("renders what react-markdown renders: %j", (source) => { - const expected = renderToStaticMarkup( - - {source} - , + it("passes every URL attribute through the transform", () => { + const html = renderToStaticMarkup( + render('![shot](./shot.png) and [a link](https://example.com "t") and '), ); - const element = render(source); - expect(renderToStaticMarkup(element)).toBe(expected); - render.remember(source, element); - expect(render(source)).toBe(element); + expect(html).toContain('src="./shot.png#seen"'); + expect(html).toContain('href="https://example.com#seen"'); + expect(html).toContain('src="b.png#seen"'); }); - it("renders what react-markdown renders while a reply streams through the incremental parser", () => { - const reply = - "```ts\nconst a = 1;\n```\n\n| a | b |\n| - | - |\n| me@x.io | www.x.io |\n\nDone ~~now~~."; - // As ChatMarkdown streams: one incremental plugin for the reply, a fresh renderer per update. - const incremental = createIncrementalMarkdownPlugin(); - for (let end = 1; end <= reply.length; end++) { - const source = reply.slice(0, end); - const streamed = createMarkdownRenderer({ - remarkPlugins: [...CHAT_MARKDOWN_REMARK_PLUGINS, incremental], - rehypePlugins: CHAT_MARKDOWN_REHYPE_PLUGINS, - components: {}, - urlTransform, - })(source); - expect(renderToStaticMarkup(streamed)).toBe( - renderToStaticMarkup( - - {source} - , - ), - ); - } + it("reuses a remembered message's element", () => { + const element = renderAndRemember("# Title\n\nText with `code` and **bold**."); + expect(render("# Title\n\nText with `code` and **bold**.")).toBe(element); }); it("keeps cached messages when one far larger than the cache is rendered", () => { - const element = render("Kept *message*"); - render.remember("Kept *message*", element); - const large = "x".repeat(600_000); - render.remember(large, render(large)); + const element = renderAndRemember("Kept *message*"); + renderAndRemember("x".repeat(600_000)); expect(render("Kept *message*")).toBe(element); }); }); diff --git a/apps/web/src/components/chat/markdownRenderer.ts b/apps/web/src/components/chat/markdownRenderer.ts index 9637d68e8f158..c2aa499a9583d 100644 --- a/apps/web/src/components/chat/markdownRenderer.ts +++ b/apps/web/src/components/chat/markdownRenderer.ts @@ -3,18 +3,13 @@ import { toJsxRuntime, type Components } from "hast-util-to-jsx-runtime"; import { urlAttributes } from "html-url-attributes"; import type { ReactElement } from "react"; import { Fragment, jsx, jsxs } from "react/jsx-runtime"; -import remarkParse from "remark-parse"; -import remarkRehype from "remark-rehype"; -import { type PluggableList, unified } from "unified"; -import { VFile } from "vfile"; -import { remarkParseWithoutUnusedSyntax } from "./markdownSyntaxGates"; +import { wordsHast, type WordsHastOptions } from "../../markdown/wordsHast"; export type MarkdownUrlTransform = (url: string, key: string, node: Element) => string; interface MarkdownRendererOptions { - readonly remarkPlugins: PluggableList; - readonly rehypePlugins: PluggableList; + readonly markdown: WordsHastOptions; readonly components: Partial; readonly urlTransform: MarkdownUrlTransform; } @@ -23,7 +18,11 @@ interface MarkdownRendererOptions { // reuses one instead of parsing again. Parsing is most of the cost of rendering markdown. // An element and the hast it keeps hold about 20 bytes per source character, so ~10 MB. const MAX_CACHED_CHARS = 500_000; -const rendered = new Map(); +interface Rendered { + readonly tree: Root; + element?: ReactElement; +} +const rendered = new Map(); let cachedChars = 0; let nextRendererId = 0; @@ -31,10 +30,10 @@ let nextRendererId = 0; const ENTRY_OVERHEAD_CHARS = 200; const entrySize = (key: string) => key.length + ENTRY_OVERHEAD_CHARS; -function remember(key: string, element: ReactElement) { +function remember(key: string, entry: Rendered) { // One huge message would otherwise evict everything else. if (entrySize(key) > MAX_CACHED_CHARS / 4) return; - rendered.set(key, element); + rendered.set(key, entry); cachedChars += entrySize(key); for (const oldest of rendered.keys()) { if (cachedChars <= MAX_CACHED_CHARS) break; @@ -43,32 +42,18 @@ function remember(key: string, element: ReactElement) { } } -/** Renders markdown as react-markdown does, with one processor per plugin set. */ +/** Renders markdown with Words, keeping one parse cache per option set. */ export function createMarkdownRenderer({ - remarkPlugins, - rehypePlugins, + markdown, components, urlTransform, }: MarkdownRendererOptions) { - const processor = unified() - .use(remarkParse) - .use(remarkParseWithoutUnusedSyntax) - .use(remarkPlugins) - .use(remarkRehype, { allowDangerousHtml: true }) - .use(rehypePlugins) - .freeze(); const keyPrefix = `${nextRendererId++}\u0000`; - // Literal raw HTML that survived the rehype plugins, and URL attributes, as react-markdown treats them. + // URL attributes, as react-markdown transformed them. const prepare = (node: Nodes) => { if (!("children" in node)) return; - const { children } = node; - for (let index = 0; index < children.length; index++) { - const child = children[index]!; - if (child.type === "raw") { - children[index] = { type: "text", value: child.value }; - continue; - } + for (const child of node.children) { if (child.type !== "element") continue; const { properties } = child; for (const key in properties) { @@ -82,7 +67,7 @@ export function createMarkdownRenderer({ } }; - const render = (text: string): ReactElement => { + const parse = (text: string): Rendered => { const key = keyPrefix + text; const cached = rendered.get(key); if (cached !== undefined) { @@ -91,24 +76,27 @@ export function createMarkdownRenderer({ rendered.set(key, cached); return cached; } - const file = new VFile(text); - const tree = processor.runSync(processor.parse(file), file) as Root; + const tree = wordsHast(text, markdown); prepare(tree); - return toJsxRuntime(tree, { - Fragment, - components, - ignoreInvalidStyle: true, - jsx, - jsxs, - passKeys: true, - passNode: true, - }); + return { tree }; }; - return Object.assign(render, { - remember(text: string, element: ReactElement) { + return { + /** A cached entry, or a fresh one that `remember` can keep. Cached trees are shared, so callers must not change them. */ + parse, + element: (entry: Rendered): ReactElement => + (entry.element ??= toJsxRuntime(entry.tree, { + Fragment, + components, + ignoreInvalidStyle: true, + jsx, + jsxs, + passKeys: true, + passNode: true, + })), + remember(text: string, entry: Rendered) { const key = keyPrefix + text; - if (!rendered.has(key)) remember(key, element); + if (!rendered.has(key)) remember(key, entry); }, - }); + }; } diff --git a/apps/web/src/components/chat/markdownStreamBlocks.test.tsx b/apps/web/src/components/chat/markdownStreamBlocks.test.ts similarity index 81% rename from apps/web/src/components/chat/markdownStreamBlocks.test.tsx rename to apps/web/src/components/chat/markdownStreamBlocks.test.ts index 38ecff7666508..b89940489ec32 100644 --- a/apps/web/src/components/chat/markdownStreamBlocks.test.tsx +++ b/apps/web/src/components/chat/markdownStreamBlocks.test.ts @@ -1,32 +1,19 @@ -import { - CHAT_MARKDOWN_REHYPE_PLUGINS, - CHAT_MARKDOWN_REMARK_PLUGINS, - remarkAssistantInsights, -} from "@t3tools/shared/markdownPipeline"; -import { renderToStaticMarkup } from "react-dom/server"; -import ReactMarkdown from "react-markdown"; -import remarkMath from "remark-math"; -import type { PluggableList } from "unified"; +import { toHtml } from "hast-util-to-html"; import { describe, expect, it } from "vite-plus/test"; +import { wordsHast } from "~/markdown/wordsHast"; import { splitMarkdownBlocks } from "./markdownStreamBlocks"; -import { rehypeHeadingIds } from "./markdownFragments"; - -const MATH_PLUGINS: PluggableList = [[remarkMath, { singleDollarTextMath: true }]]; // Whitespace between top-level blocks collapses in the rendered message. const renderMarkdown = (source: string, math = false) => - renderToStaticMarkup( - - {source} - , + toHtml( + wordsHast(source, { + math, + breaks: false, + escapeHtml: false, + insights: source.includes("★ Insight"), + extensions: {}, + }), ) .replace(/>\s+<") .trim(); diff --git a/apps/web/src/components/chat/markdownSyntaxGates.ts b/apps/web/src/components/chat/markdownSyntaxGates.ts deleted file mode 100644 index 57587a51b9d13..0000000000000 --- a/apps/web/src/components/chat/markdownSyntaxGates.ts +++ /dev/null @@ -1,204 +0,0 @@ -import type { Nodes as MdastNodes } from "mdast"; -import { - type Extension as MdastExtension, - fromMarkdown, - type Options as FromMarkdownOptions, - type Transform, -} from "mdast-util-from-markdown"; -import { combineExtensions } from "micromark-util-combine-extensions"; -import type { Construct, Extension, TokenizeContext } from "micromark-util-types"; -import type { Processor } from "unified"; - -// A table needs a delimiter row: dashes with a `|` or `:`, after any `>` or indent. -// One character class per pattern: overlapping ones backtrack quadratically on a run of dashes. -const DELIMITER_LINE = /^[ \t>|:-]+$/gm; -const isDelimiterRow = (line: string) => line.includes("-") && /[|:]/.test(line); -const NEXT_LINE = /[^\r\n]*(?:\r\n?|\n)([^\r\n]*)/y; - -function hasDelimiterRow(text: string) { - for (const [line] of text.matchAll(DELIMITER_LINE)) if (isDelimiterRow(line)) return true; - return false; -} -const PROTOCOL = /https?:\/\//iy; -const WWW = /www\./iy; -const EMAIL_ATEXT = /[\w+.-]*@/y; - -const matchesAt = (pattern: RegExp, text: string, offset: number) => { - pattern.lastIndex = offset; - return pattern.test(text); -}; - -interface Gate { - readonly names: ReadonlyArray; - /** False when the construct cannot match anywhere in the text. */ - readonly inText: (text: string) => boolean; - /** False when it cannot start at this offset, which keeps micromark from trying it there. */ - readonly at?: (context: TokenizeContext, text: string, offset: number) => boolean; -} - -// micromark tries these at every candidate character: email autolinks at every word, tables -// at every line. That is most of what GFM adds to a parse, and most texts cannot match them. -const GATES: ReadonlyArray = [ - { - names: ["emailAutolink"], - inText: (text) => text.includes("@"), - at: (_, text, offset) => matchesAt(EMAIL_ATEXT, text, offset), - }, - { - names: ["protocolAutolink"], - inText: (text) => /https?:\/\//i.test(text), - at: (_, text, offset) => matchesAt(PROTOCOL, text, offset), - }, - { - names: ["wwwAutolink"], - inText: (text) => /www\./i.test(text), - at: (_, text, offset) => matchesAt(WWW, text, offset), - }, - { - names: ["table"], - inText: hasDelimiterRow, - at: (context, text, offset) => { - NEXT_LINE.lastIndex = offset; - const nextLine = NEXT_LINE.exec(text)?.[1]; - return (nextLine !== undefined && hasDelimiterRow(nextLine)) || continuesTable(context); - }, - }, - { names: ["strikethrough"], inText: (text) => text.includes("~") }, - { - names: ["gfmFootnoteCall", "gfmPotentialFootnoteCall", "gfmFootnoteDefinition"], - inText: (text) => text.includes("[^"), - }, - { names: ["tasklistCheck"], inText: (text) => /\[[\sxX]\]/.test(text) }, -]; - -// A body row follows the head or another row. Mirrors `start` in micromark-extension-gfm-table's -// lib/syntax.js: recheck it when that package changes. -function continuesTable({ events }: TokenizeContext) { - let index = events.length - 1; - while (index > -1 && /^(?:lineEnding|linePrefix)$/.test(events[index]![1].type)) index--; - // The table extension's token types are not in micromark's map unless its types are loaded. - const tail: string | undefined = events[index]?.[1].type; - return tail === "tableHead" || tail === "tableRow"; -} - -let parsing = ""; -const gated = new WeakMap(); - -function gatedConstruct(construct: Construct, gate: Gate): Construct { - const at = gate.at; - if (!at) return construct; - let wrapped = gated.get(construct); - if (!wrapped) { - const { previous, tokenize } = construct; - wrapped = { - ...construct, - tokenize(effects, ok, nok) { - return at(this, parsing, this.now().offset) ? tokenize.call(this, effects, ok, nok) : nok; - }, - ...(previous && { - previous(code) { - return previous.call(this, code) && at(this, parsing, this.now().offset); - }, - }), - }; - gated.set(construct, wrapped); - } - return wrapped; -} - -type ConstructMap = Record; - -function gateExtension(extension: Extension, absent: ReadonlySet): Extension { - const gateOf = (name: string | undefined) => - GATES.find((gate) => name && gate.names.includes(name)); - const result: Record = {}; - for (const [field, value] of Object.entries(extension)) { - if (field === "disable" || field === "attentionMarkers" || !value) { - result[field] = value; - continue; - } - const map: ConstructMap = {}; - for (const [code, entry] of Object.entries(value as ConstructMap)) { - const kept = (Array.isArray(entry) ? entry : [entry]).flatMap((construct) => { - const gate = construct && gateOf(construct.name); - if (!construct || !gate) return construct ? [construct] : []; - return absent.has(gate) ? [] : [gatedConstruct(construct, gate)]; - }); - if (kept.length > 0) map[code] = Array.isArray(entry) ? kept : kept[0]; - } - result[field] = map; - } - return result as Extension; -} - -type MdastExtensions = NonNullable; - -// Merged once, as mdast-util-from-markdown merges them on every call: lists in order, handlers by key. -function mergeMdastExtensions(extensions: MdastExtensions): MdastExtension { - const merged = { - canContainEols: [] as string[], - enter: {}, - exit: {}, - transforms: [] as Transform[], - }; - for (const extension of extensions.flat()) { - merged.canContainEols.push(...(extension.canContainEols ?? [])); - Object.assign(merged.enter, extension.enter); - Object.assign(merged.exit, extension.exit); - // GFM looks for autolink literals again in the decoded text outside links, so `www\.x.io` - // links too. Most texts have URLs only in link destinations and code, where it finds nothing. - for (const transform of extension.transforms ?? []) { - merged.transforms.push( - extension.enter?.literalAutolink - ? (tree) => (hasAutolinkText(tree) ? transform(tree) : undefined) - : transform, - ); - } - } - return merged; -} - -const AUTOLINK_TEXT = /@|https?:\/\/|www\./i; - -function hasAutolinkText(node: MdastNodes): boolean { - if (node.type === "text") return AUTOLINK_TEXT.test(node.value); - if (node.type === "link" || node.type === "linkReference" || !("children" in node)) return false; - return node.children.some(hasAutolinkText); -} - -/** - * Parses as remark-parse does, without the syntax extension constructs that cannot match the - * text. Same tree, in about half the time. - */ -function attachParserWithoutUnusedSyntax(this: Processor) { - const data = this.data(); - const byMask = new Map(); - let mdastExtensions: MdastExtension[] | undefined; - this.parser = (document) => { - let mask = 0; - GATES.forEach((gate, index) => { - if (!gate.inText(document)) mask |= 1 << index; - }); - let extensions = byMask.get(mask); - if (!extensions) { - const absent = new Set(GATES.filter((_, index) => mask & (1 << index))); - extensions = [ - combineExtensions( - (data.micromarkExtensions ?? []).map((extension) => gateExtension(extension, absent)), - ), - ]; - byMask.set(mask, extensions); - } - mdastExtensions ??= [mergeMdastExtensions(data.fromMarkdownExtensions ?? [])]; - const outer = parsing; - // Gates read micromark offsets, which skip a leading byte order mark. - parsing = document.charCodeAt(0) === 0xfeff ? document.slice(1) : document; - try { - return fromMarkdown(document, { ...data.settings, extensions, mdastExtensions }); - } finally { - parsing = outer; - } - }; -} - -export const remarkParseWithoutUnusedSyntax = attachParserWithoutUnusedSyntax; diff --git a/apps/web/src/components/chat/markdownTextDirection.ts b/apps/web/src/components/chat/markdownTextDirection.ts index ffdbde76c1148..a4c78d3342754 100644 --- a/apps/web/src/components/chat/markdownTextDirection.ts +++ b/apps/web/src/components/chat/markdownTextDirection.ts @@ -1,4 +1,4 @@ -import { textDirection } from "~/textDirection"; +import { LETTER, RTL_LETTER, textDirection } from "~/textDirection"; type HastNode = { type?: string; @@ -57,11 +57,32 @@ function isolateInlineCode(node: HastNode): void { */ export function rehypeTextDirection() { return (tree: HastNode) => { - for (const block of tree.children ?? []) { - if (block.type !== "element" || block.tagName === "pre") continue; - const dir = textDirection(proseText(block)); - if (dir) block.properties = { ...block.properties, dir }; - } + blockTextDirections(tree); isolateInlineCode(tree); }; } + +/** Each top-level block's direction, from its prose; an RTL letter decides as textDirection does. */ +function blockTextDirections(tree: HastNode) { + for (const block of tree.children ?? []) { + if (block.type !== "element" || block.tagName === "pre") continue; + const dir = scriptOf(block) === "rtl" ? textDirection(proseText(block)) : scriptOf(block); + if (dir) block.properties = { ...block.properties, dir }; + } +} + +/** "rtl" when any prose letter is right-to-left; otherwise what textDirection would say. */ +function scriptOf(node: HastNode): "rtl" | "ltr" | undefined { + let found: "ltr" | undefined; + const visit = (current: HastNode): boolean => { + if (current.type === "text") { + const value = current.value ?? ""; + if (RTL_LETTER.test(value)) return true; + if (!found && LETTER.test(value)) found = "ltr"; + return false; + } + if (current.tagName === "code") return false; + return (current.children ?? []).some(visit); + }; + return visit(node) ? "rtl" : found; +} diff --git a/apps/web/src/components/chat/threadFindHighlights.ts b/apps/web/src/components/chat/threadFindHighlights.ts index c8ce0b31b9c9e..fe6a3ba5d3056 100644 --- a/apps/web/src/components/chat/threadFindHighlights.ts +++ b/apps/web/src/components/chat/threadFindHighlights.ts @@ -1,6 +1,6 @@ import { findThreadSearchOccurrences } from "@t3tools/shared/threadSearch"; import { useEffect, useEffectEvent, useRef } from "react"; -import { THREAD_FIND_BLOCK_TAGS } from "@t3tools/shared/threadFindText"; +import { THREAD_FIND_BLOCK_TAGS } from "@t3tools/shared/threadFindBlockTags"; import { observeResize } from "~/lib/observeResize"; diff --git a/apps/web/src/components/chat/timelineMinimapItems.ts b/apps/web/src/components/chat/timelineMinimapItems.ts index 151a02d88175e..57f6229c99526 100644 --- a/apps/web/src/components/chat/timelineMinimapItems.ts +++ b/apps/web/src/components/chat/timelineMinimapItems.ts @@ -4,10 +4,9 @@ import { isAttachmentOnlyBootstrapPrompt, replaceComposerContextReferences, } from "@t3tools/shared/composerContextReferences"; -import type { Nodes } from "mdast"; -import remarkGfm from "remark-gfm"; -import remarkParse from "remark-parse"; -import { unified } from "unified"; +import type { Nodes } from "hast"; + +import { markdownTree } from "~/markdown/wordsHast"; import type { MessagesTimelineRow } from "./MessagesTimeline.logic"; @@ -58,50 +57,49 @@ function resolveFinalAssistantTextForTurn( return finalAssistantText; } -const markdownPreviewParser = unified().use(remarkParse).use(remarkGfm).freeze(); - -const INLINE_PARENT_TYPES = new Set([ - "paragraph", - "heading", - "tableCell", - "emphasis", +// Elements whose children run together; every other element is separated by a space. +const INLINE_PARENTS = new Set([ + "p", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "td", + "th", + "em", "strong", - "delete", - "link", - "linkReference", + "del", + "a", + "code", + "span", + "sup", + "sub", ]); function markdownNodeText(node: Nodes): string { - if (node.type === "html") { - return node.value - .replace(/|$)/g, "") - .replace(/<\/?([a-z][\w-]*)(?:[^"'<>]|"[^"]*"|'[^']*')*>/gi, (_, tag: string) => - /^(?:address|article|aside|blockquote|br|dd|details|div|dl|dt|figcaption|figure|footer|h[1-6]|header|hr|li|main|nav|ol|p|pre|section|summary|table|tbody|td|th|thead|tr|ul)$/i.test( - tag, - ) - ? " " - : "", - ); - } - if (node.type === "break") return " "; - if ("value" in node) return node.value; - if (node.type === "image" || node.type === "imageReference") return node.alt ?? ""; - if (!("children" in node)) return ""; - const separator = INLINE_PARENT_TYPES.has(node.type) ? "" : " "; + if (node.type === "text") return node.value; + if (node.type === "element" && node.tagName === "br") return " "; + if (node.type === "element" && node.tagName === "img") return String(node.properties.alt ?? ""); + if (node.type !== "element" && node.type !== "root") return ""; + const separator = node.type === "element" && INLINE_PARENTS.has(node.tagName) ? "" : " "; const text = node.children.map(markdownNodeText).join(separator); // A thread autolink's only text is its URL. - return node.type === "link" && parseThreadLinkHref(text) !== null ? "a thread" : text; + return node.type === "element" && node.tagName === "a" && parseThreadLinkHref(text) !== null + ? "a thread" + : text; } /** Markdown as one line of the text it renders, without markup or link targets. */ export function markdownPlainText(markdown: string): string { - return markdownNodeText(markdownPreviewParser.parse(markdown)).replace(/\s+/g, " ").trim(); + return markdownNodeText(markdownTree(markdown)).replace(/\s+/g, " ").trim(); } // The tooltip shows a few lines; bound parsing work for long messages and streaming responses. function markdownMinimapPreview(markdown: string | null) { if (markdown === null) return null; - const compact = markdownNodeText(markdownPreviewParser.parse(markdown.slice(0, 1_500))) + const compact = markdownNodeText(markdownTree(markdown.slice(0, 1_500))) .replace(/\s+/g, " ") .trim(); return compact.length > 0 ? compact : null; diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx index c020113815dfa..2c27cfb8d80d1 100644 --- a/apps/web/src/components/files/FilePreviewPanel.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.tsx @@ -132,7 +132,7 @@ import { shouldShowFileExplorer, workspaceAssetResource, } from "./filePreviewMode"; -import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList"; +import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskEdits"; import { changeFileSaveSession, useFileSaveSession } from "./fileSaveSessions"; import { revisionedQuery } from "~/state/revisionedQuery"; import { diff --git a/apps/web/src/components/files/NotebookPreview.tsx b/apps/web/src/components/files/NotebookPreview.tsx index 35d0203818850..c2104ad2ddec6 100644 --- a/apps/web/src/components/files/NotebookPreview.tsx +++ b/apps/web/src/components/files/NotebookPreview.tsx @@ -2,8 +2,8 @@ import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments"; import { T, useGT, useMessages } from "gt-react"; import { useEffect, useRef, useState } from "react"; -import type { Root, RootContent } from "mdast"; import ChatMarkdown from "~/components/ChatMarkdown"; +import type { MarkdownExtensions } from "~/markdown/wordsHast"; import { Button } from "~/components/ui/button"; import ReadOnlySourcePreview from "./ReadOnlySourcePreview"; import DocumentPages from "./DocumentPages"; @@ -11,24 +11,7 @@ import { FileSurfaceNotice } from "./fileSurfaceChrome"; import type { OfficeWorkerResult } from "./officePreviewProtocol"; // Saved notebooks must not load URLs or turn authored links into app actions. -function inertNotebookMarkdown() { - function clean(nodes: RootContent[]): RootContent[] { - return nodes.flatMap((node): RootContent[] => { - if (node.type === "html" || node.type === "definition") return []; - if (node.type === "image" || node.type === "imageReference") - return [{ type: "text", value: node.alt ?? "" }]; - if (node.type === "link" || node.type === "linkReference") return clean(node.children); - if (node.type === "inlineCode") return [{ type: "text", value: node.value }]; - if (node.type === "code" && node.lang === "mermaid") return [{ ...node, lang: "text" }]; - if ("children" in node) node.children = clean(node.children) as typeof node.children; - return [node]; - }); - } - return (tree: Root) => { - tree.children = clean(tree.children) as Root["children"]; - }; -} -const NOTEBOOK_PLUGINS = [inertNotebookMarkdown]; +const NOTEBOOK_MARKDOWN: MarkdownExtensions = { inert: true }; function NotebookSource(props: { readonly name: string; readonly text: string }) { const [height, setHeight] = useState(Math.min(360, props.text.split("\n").length * 20 + 16)); @@ -129,7 +112,7 @@ export default function NotebookPreview(props: { text={cell.source} cwd={undefined} parseRawHtml={false} - extraRemarkPlugins={NOTEBOOK_PLUGINS} + extensions={NOTEBOOK_MARKDOWN} className="px-4 py-3" /> ) : cell.source.trim() ? ( diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index 1e0fa7680c405..cbf9de56dbbb2 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -112,7 +112,7 @@ import { PullRequestsUnavailableState } from "./PullRequestsUnavailableState"; import type { PullRequestAgentSelectionInput } from "./PullRequestCodeTab"; import { openOnHostLabel } from "./pullRequestLinkContextMenu"; import { PullRequestMarkdownContext } from "./PullRequestMarkdown"; -import { pullRequestMarkdownPlugins } from "./pullRequestMarkdown.logic"; +import { pullRequestMarkdownExtensions } from "./pullRequestMarkdown.logic"; import { PullRequestComposer } from "./PullRequestComposer"; import { PullRequestSummaryTab } from "./PullRequestSummaryTab"; import { PullRequestTimelineTab } from "./PullRequestTimelineTab"; @@ -298,7 +298,7 @@ function pullRequestMarkdownContext( threadRef: ScopedThreadRef | null, ) { return { - remarkPlugins: pullRequestMarkdownPlugins(detail), + extensions: pullRequestMarkdownExtensions(detail), lineBreaks: sourceControlClients.find(detail?.provider ?? "")?.hardLineBreaks ?? false, threadRef, repository: detail?.repository ?? null, diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdown.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdown.browser.test.tsx index fae5270d27123..f1cd6b6ba6708 100644 --- a/apps/web/src/components/pullRequest/PullRequestMarkdown.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestMarkdown.browser.test.tsx @@ -24,7 +24,7 @@ async function renderBody( ) { const { repository = null, text = "first line\nsecond line", ...props } = options; const context = { - remarkPlugins: [], + extensions: {}, lineBreaks: sourceControlClients.get(host).hardLineBreaks ?? false, threadRef: null, repository, diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx index 071e8dbe45d17..82012eae8f0a7 100644 --- a/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx +++ b/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx @@ -9,7 +9,7 @@ import { type ScopedThreadRef, } from "@t3tools/contracts"; import { createContext, useContext } from "react"; -import type { PluggableList } from "unified"; +import type { MarkdownExtensions } from "~/markdown/wordsHast"; import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls"; import { cn } from "~/lib/utils"; @@ -21,7 +21,7 @@ import { splitPullRequestBody, type PullRequestBodySegment } from "./pullRequest export const PullRequestMarkdownContext = createContext<{ /** Stable per repository, so comments share one renderer and its parse cache. */ - remarkPlugins: PluggableList; + extensions: MarkdownExtensions; lineBreaks: boolean; threadRef: ScopedThreadRef | null; /** The change request's `owner/name`, which can differ from the checkout the body renders in. */ @@ -129,7 +129,7 @@ function PullRequestBodySegmentView({ threadRef={threadRef} pullRequestPanelRef={threadRef ?? listPanelRef} environmentId={environmentId} - {...(context ? { extraRemarkPlugins: context.remarkPlugins } : {})} + {...(context ? { extensions: context.extensions } : {})} lineBreaks={lineBreaks} sourceControlMedia sourceControlMediaRepository={repository} diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx index dd4cf2f811c72..1f409d282ecc3 100644 --- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx @@ -87,7 +87,7 @@ import { startDescriptionSave, type DescriptionDraft, } from "@t3tools/client-runtime/pull-request-editing"; -import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList"; +import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskEdits"; import { PullRequestMarkdown } from "./PullRequestMarkdown"; import { PullRequestCommentBody } from "./PullRequestCommentBody"; import { PullRequestMoreReplies } from "./PullRequestMoreReplies"; diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts index 4f25b26f3276e..3d0ae22b15017 100644 --- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts @@ -1280,6 +1280,15 @@ describe("adding a remark to the chat", () => { }); expect(context?.text).toBe("octocat: This leaks the token.\n\n```html\n\n```"); + // A stray backtick before the comment opens no code span across the paragraphs. + const stray = buildPullRequestCommentContext(pullRequest, { + kind: "comment", + comment: remark( + "c2", + "Avoid `foo.\n\n\nSee `bar` and `` a ` ``.", + ), + }); + expect(stray?.text).toBe("octocat: Avoid `foo.\n\nSee `bar` and `` a ` ``."); }); it("keeps comments inside a quoted fence as code", () => { diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts index 238038730b93f..d98ec3ff114ec 100644 --- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts @@ -5,8 +5,9 @@ import { resolvePullRequestReviewAnchor, } from "@t3tools/shared/pullRequestAnchor"; import { stripInlineContextReferences } from "~/lib/composerContextReferences"; -import type { Nodes as MdastNodes } from "mdast"; -import { fromMarkdown } from "mdast-util-from-markdown"; +import type { Nodes } from "hast"; + +import { markdownHtmlComments, markdownTree } from "~/markdown/wordsHast"; import { sourceControlClients, type ChangeRequestTerminology, @@ -693,27 +694,18 @@ export function pagePullRequestConversationItems( function readableBody(raw: string): string | null { if (visibleBody(raw) === null) return null; const body = raw.replace(/\r\n?/gu, "\n"); - const cuts: Array<[number, number]> = []; - const visit = (node: MdastNodes) => { - if (node.type === "html" && node.position?.start.offset !== undefined) { - cuts.push([node.position.start.offset, node.position.end.offset ?? body.length]); - } - if ("children" in node) for (const child of node.children) visit(child); - }; - visit(fromMarkdown(body)); let readable = ""; let from = 0; - for (const [start, end] of cuts) { + for (const { start, end } of markdownHtmlComments(body)) { + // A comment opened inside another one ends with it. + if (start < from) continue; readable += body.slice(from, start); - // An HTML block can carry markup around its comment; only the comment itself is hidden. - const html = body.slice(start, end).replace(/|$)/gu, ""); // A line that was all comment is dropped rather than left as a blank one. const ownLine = /(?:^|\n)[ \t>]*$/u.test(readable) && /^[ \t]*(?:\n|$)/u.test(body.slice(end)); - if (ownLine && html.trim() === "") { + if (ownLine) { readable = readable.replace(/[ \t>]*$/u, ""); from = end + (/^[ \t]*\n/u.exec(body.slice(end))?.[0].length ?? 0); } else { - readable += html; from = end; } } @@ -740,11 +732,12 @@ const LINK_EXCERPT_LENGTH = 280; /** The words of a markdown body, without markup, HTML or images, for a short preview. */ function markdownExcerpt(body: string): string | null { const words: string[] = []; - const visit = (node: MdastNodes) => { - if (node.type === "text" || node.type === "inlineCode") words.push(node.value); - if (node.type !== "code" && "children" in node) for (const child of node.children) visit(child); + const visit = (node: Nodes) => { + if (node.type === "text") words.push(node.value); + if (node.type === "element" && node.tagName === "pre") return; + if ("children" in node) for (const child of node.children) visit(child); }; - visit(fromMarkdown(body)); + visit(markdownTree(body, { skipHtml: true })); // GitHub's alert marker (`> [!NOTE]`) parses as text but reads as markup. const text = words .join(" ") diff --git a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts index 1655427b2d4e9..7c4ffac84b8a5 100644 --- a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts @@ -1,45 +1,44 @@ -import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-markdown"; -import remarkParse from "remark-parse"; -import { unified } from "unified"; +import type { Element, Root } from "hast"; import { describe, expect, it } from "vite-plus/test"; +import { wordsHast } from "~/markdown/wordsHast"; import { pullRequestCommentPreview, - pullRequestMarkdownPlugins, - remarkPullRequestAutolinks, + pullRequestMarkdownExtensions, } from "./pullRequestMarkdown.logic"; -type Node = { - type: string; - value?: string; - url?: string; - data?: { hProperties?: Record }; - children?: Node[]; -}; - function links(markdown: string) { - const autolinks = changeRequestReferenceAutolinker({ + const extensions = pullRequestMarkdownExtensions({ provider: "github", url: "https://github.com/team/repo/pull/8", - })!; - const tree = unified().use(remarkParse).parse(markdown) as Node; - remarkPullRequestAutolinks({ autolinks })(tree as never); - const found: Array<[string | undefined, string | undefined, unknown]> = []; - const visit = (node: Node) => { - if (node.type === "link") { - found.push([ - node.children?.[0]?.value, - node.url, - node.data?.hProperties?.["dataPullRequestAutolink"], - ]); + }); + const tree = wordsHast(markdown, { + math: false, + breaks: false, + escapeHtml: false, + insights: false, + extensions, + }); + const found: Array<[string, unknown, unknown]> = []; + const visit = (node: Root | Element) => { + for (const child of node.children) { + if (child.type !== "element") continue; + if (child.tagName === "a") { + const label = child.children[0]; + found.push([ + label?.type === "text" ? label.value : "", + child.properties.href, + child.properties.dataPullRequestAutolink, + ]); + } + visit(child); } - node.children?.forEach(visit); }; visit(tree); return found; } -describe("remarkPullRequestAutolinks", () => { +describe("pullRequestMarkdownExtensions", () => { it("links the host's references in prose and leaves links and code alone", () => { expect(links("Fixes #12 in **abcdef1**. [#13](https://example.com) `#14`")).toEqual([ ["#12", "https://github.com/team/repo/issues/12", "reference"], @@ -47,22 +46,25 @@ describe("remarkPullRequestAutolinks", () => { ["#13", "https://example.com", undefined], ]); }); -}); - -describe("pullRequestMarkdownPlugins", () => { it("renders GitHub emoji shortcodes in prose and leaves code literal", () => { - const processor = unified() - .use(remarkParse) - .use( - pullRequestMarkdownPlugins({ - provider: "github", - url: "https://github.com/team/repo/pull/8", - }), - ); - const tree = processor.runSync(processor.parse("Ship it :tada: :+1: `:tada:`")) as Node; - const text = (node: Node): string => - (node.type === "inlineCode" ? `\`${node.value}\`` : (node.value ?? "")) + - (node.children ?? []).map(text).join(""); + const extensions = pullRequestMarkdownExtensions({ + provider: "github", + url: "https://github.com/team/repo/pull/8", + }); + const tree = wordsHast("Ship it :tada: :+1: `:tada:`", { + math: false, + breaks: false, + escapeHtml: false, + insights: false, + extensions, + }); + const text = (node: Root | Element | Root["children"][number]): string => { + if (node.type === "text") return node.value; + if (node.type === "element" && node.tagName === "code") { + return `\`${node.children.map(text).join("")}\``; + } + return "children" in node ? node.children.map(text).join("") : ""; + }; expect(text(tree)).toBe("Ship it 🎉 👍 `:tada:`"); }); }); diff --git a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts index 21f3574838e06..560b6ee03fd37 100644 --- a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts @@ -1,130 +1,63 @@ -import { - changeRequestReferenceAutolinker, - expandGithubEmojiAliases, - resolveChangeRequestMediaUrl, -} from "@t3tools/client-runtime/pull-request-markdown"; -import { - sourceControlClients, - type ReferenceAutolink, -} from "@t3tools/client-runtime/source-control-clients"; -import { - CHAT_MARKDOWN_REHYPE_PLUGINS, - CHAT_MARKDOWN_REMARK_PLUGINS, -} from "@t3tools/shared/markdownPipeline"; +import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-references"; +import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import type { Nodes } from "hast"; -import remarkParse from "remark-parse"; -import remarkRehype from "remark-rehype"; -import { unified, type PluggableList } from "unified"; -export { - splitPullRequestBody, +import { + splitPullRequestBody as splitBody, type PullRequestBodySegment, } from "@t3tools/client-runtime/pull-request-markdown"; +import { + markdownReferenceDefinitions, + wordsHast, + type MarkdownExtensions, +} from "~/markdown/wordsHast"; -type MarkdownNode = { - type: string; - value?: string; - children?: MarkdownNode[]; - url?: string; - data?: unknown; -}; - -const AUTOLINK_IGNORED_TYPES = new Set(["link", "linkReference"]); - -export function remarkPullRequestAutolinks(options: { - readonly autolinks: (text: string) => ReadonlyArray; -}) { - const visit = (node: MarkdownNode): void => { - const children = node.children; - if (children === undefined) return; - for (let index = 0; index < children.length; index += 1) { - const child = children[index]!; - if (AUTOLINK_IGNORED_TYPES.has(child.type)) continue; - if (child.type !== "text" || child.value === undefined) { - visit(child); - continue; - } - const value = child.value; - const links = options.autolinks(value); - if (links.length === 0) continue; - const replacements: MarkdownNode[] = []; - let start = 0; - for (const link of links) { - if (start < link.index) { - replacements.push({ type: "text", value: value.slice(start, link.index) }); - } - replacements.push({ - type: "link", - url: link.url, - data: { hProperties: { dataPullRequestAutolink: link.kind } }, - children: [{ type: "text", value: link.label }], - }); - start = link.index + link.text.length; - } - if (start < value.length) replacements.push({ type: "text", value: value.slice(start) }); - children.splice(index, 1, ...replacements); - index += replacements.length - 1; - } - }; - return (tree: MarkdownNode) => visit(tree); -} +export type { PullRequestBodySegment }; -function remarkChangeRequestMediaUrls(options: { readonly changeRequestUrl: string }) { - const visit = (node: MarkdownNode): void => { - if ((node.type === "image" || node.type === "definition") && node.url !== undefined) { - node.url = resolveChangeRequestMediaUrl(node.url, options.changeRequestUrl); - } - node.children?.forEach(visit); - }; - return (tree: MarkdownNode) => visit(tree); +export function splitPullRequestBody(body: string): ReadonlyArray { + return splitBody(body, markdownReferenceDefinitions); } -/** GitHub renders `:alias:` emoji in prose; code keeps them, being `inlineCode`/`code`, not `text`. */ -function remarkGithubEmoji() { - const visit = (node: MarkdownNode): void => { - if (node.type === "text" && node.value !== undefined) - node.value = expandGithubEmojiAliases(node.value); - node.children?.forEach(visit); - }; - return (tree: MarkdownNode) => visit(tree); -} - -const NO_PLUGINS: PluggableList = []; -const markdownPlugins = new Map(); +const NO_EXTENSIONS: MarkdownExtensions = {}; +const markdownExtensions = new Map(); /** - * One plugin list per repository, so every comment of a pull request shares one markdown + * One extension object per repository, so every comment of a pull request shares one markdown * renderer and its parse cache instead of parsing again on each render. */ -export function pullRequestMarkdownPlugins( +export function pullRequestMarkdownExtensions( changeRequest: { readonly provider: string; readonly url: string } | null, -): PluggableList { - if (changeRequest === null) return NO_PLUGINS; +): MarkdownExtensions { + if (changeRequest === null) return NO_EXTENSIONS; const repositoryUrl = sourceControlClients.parseChangeRequestUrl(changeRequest.url)?.link .repositoryUrl; - if (repositoryUrl === undefined) return NO_PLUGINS; + if (repositoryUrl === undefined) return NO_EXTENSIONS; const key = `${changeRequest.provider}\u0000${repositoryUrl}`; - let plugins = markdownPlugins.get(key); - if (plugins === undefined) { - const autolinks = changeRequestReferenceAutolinker(changeRequest); - plugins = [[remarkChangeRequestMediaUrls, { changeRequestUrl: repositoryUrl }]]; - if (changeRequest.provider === "github") plugins.push(remarkGithubEmoji); - if (autolinks) plugins.push([remarkPullRequestAutolinks, { autolinks }]); - markdownPlugins.set(key, plugins); + let extensions = markdownExtensions.get(key); + if (extensions === undefined) { + extensions = { + changeRequest: { + repositoryUrl, + autolinks: changeRequestReferenceAutolinker(changeRequest), + }, + githubEmoji: changeRequest.provider === "github", + }; + markdownExtensions.set(key, extensions); } - return plugins; + return extensions; } -const commentPreviewProcessor = (plugins: PluggableList) => - unified() - .use(remarkParse) - .use(CHAT_MARKDOWN_REMARK_PLUGINS) - .use(plugins) - .use(remarkRehype, { allowDangerousHtml: true }) - .use(CHAT_MARKDOWN_REHYPE_PLUGINS) - .freeze(); -const commentPreview = commentPreviewProcessor(NO_PLUGINS); -const githubCommentPreview = commentPreviewProcessor([remarkGithubEmoji]); +const PREVIEW_MARKDOWN = { + math: false, + breaks: false, + escapeHtml: false, + insights: false, + extensions: NO_EXTENSIONS, +}; +const GITHUB_PREVIEW_MARKDOWN = { + ...PREVIEW_MARKDOWN, + extensions: { githubEmoji: true }, +}; const PREVIEW_BLOCK_TAGS = new Set([ "blockquote", @@ -164,7 +97,6 @@ function commentPreviewText(node: Nodes): string { } export function pullRequestCommentPreview(body: string, provider: string): string { - const processor = provider === "github" ? githubCommentPreview : commentPreview; - const tree = processor.runSync(processor.parse(body), body); - return commentPreviewText(tree).replace(/\s+/gu, " ").trim(); + const options = provider === "github" ? GITHUB_PREVIEW_MARKDOWN : PREVIEW_MARKDOWN; + return commentPreviewText(wordsHast(body, options)).replace(/\s+/gu, " ").trim(); } diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index d91d6da4a42d7..4252fccc9c7d0 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -512,6 +512,7 @@ export const SETTINGS_SEARCH_ITEMS = [ targetId: "boring-sidebar", searchTerms: [msg("beta boring sidebar folder rows multiline branch pull request details")], }, + { id: "tool-call-visibility", title: msg("Tool calls in chat"), diff --git a/apps/web/src/components/ui/shared-tooltip.tsx b/apps/web/src/components/ui/shared-tooltip.tsx new file mode 100644 index 0000000000000..0858fa656e6bb --- /dev/null +++ b/apps/web/src/components/ui/shared-tooltip.tsx @@ -0,0 +1,262 @@ +import { + cloneElement, + createContext, + use, + useEffect, + useId, + useRef, + useState, + type FocusEvent, + type PointerEvent, + type ReactElement, + type ReactNode, +} from "react"; + +import { Tooltip, TooltipPopup, TooltipTrigger, useTooltipScrollTracker } from "./tooltip"; + +// Base UI's tooltip timing: open after a rest, reopen at once right after another closed. +const OPEN_DELAY_MS = 600; +const REOPEN_WINDOW_MS = 400; +// Time to travel from the trigger into a hoverable popup. +const CLOSE_GRACE_MS = 100; + +interface SharedTooltipContent { + readonly render: () => ReactNode; + /** Comparable key that changes whenever `render()` output changes while open. */ + readonly contentKey?: unknown; + readonly side?: "top" | "bottom" | "left" | "right"; + readonly variant?: "default" | "glass" | "code"; +} + +interface SharedTooltipState extends SharedTooltipContent { + readonly anchor: HTMLElement; + readonly open: boolean; +} + +interface SharedTooltipApi { + show(anchor: HTMLElement, content: SharedTooltipContent, immediate: boolean): void; + refresh(anchor: HTMLElement, content: SharedTooltipContent): void; + hide(anchor: HTMLElement): void; + /** A press closes it at once, as Base UI's closeOnClick does. */ + dismiss(anchor: HTMLElement): void; + holdOpen(): void; +} + +function setAriaDescribedBy(element: HTMLElement, id: string, present: boolean) { + const tokens = (element.getAttribute("aria-describedby") ?? "").split(/\s+/).filter(Boolean); + const next = present + ? tokens.includes(id) + ? tokens + : [...tokens, id] + : tokens.filter((token) => token !== id); + if (next.length > 0) element.setAttribute("aria-describedby", next.join(" ")); + else element.removeAttribute("aria-describedby"); +} + +const SharedTooltipContext = createContext(null); + +/** + * One tooltip for many triggers: a long message would otherwise mount a Base UI tooltip per + * link and file chip, and almost none of them are ever hovered. + */ +export function SharedTooltipProvider({ children }: { children: ReactNode }) { + const popupId = useId(); + const [state, setState] = useState(null); + const timer = useRef | null>(null); + const pending = useRef(null); + const lastClosedAt = useRef(0); + const current = useRef(null); + + const commit = (next: SharedTooltipState | null) => { + current.current = next; + setState(next); + }; + const clearTimer = () => { + if (timer.current !== null) clearTimeout(timer.current); + timer.current = null; + pending.current = null; + }; + const [api] = useState(() => ({ + show(anchor, content, immediate) { + clearTimer(); + const open = current.current?.open === true; + const reopen = performance.now() - lastClosedAt.current < REOPEN_WINDOW_MS; + if (immediate || open || reopen) { + commit({ ...content, anchor, open: true }); + return; + } + pending.current = { ...content, anchor, open: true }; + timer.current = setTimeout(() => { + const next = pending.current; + pending.current = null; + if (next) commit(next); + }, OPEN_DELAY_MS); + }, + refresh(anchor, content) { + if (pending.current?.anchor === anchor) { + pending.current = { ...pending.current, ...content }; + } + const active = current.current; + if (!active || active.anchor !== anchor) return; + if ( + active.contentKey === content.contentKey && + active.side === content.side && + active.variant === content.variant + ) { + return; + } + commit({ ...active, ...content }); + }, + hide(anchor) { + if (current.current && current.current.anchor !== anchor) { + clearTimer(); + return; + } + clearTimer(); + timer.current = setTimeout(() => { + if (current.current?.open) lastClosedAt.current = performance.now(); + if (current.current) commit({ ...current.current, open: false }); + }, CLOSE_GRACE_MS); + }, + dismiss(anchor) { + clearTimer(); + if (current.current?.anchor !== anchor) return; + if (current.current.open) lastClosedAt.current = 0; + commit({ ...current.current, open: false }); + }, + holdOpen() { + clearTimer(); + }, + })); + + const activeAnchor = state?.open ? state.anchor : null; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- links the active trigger DOM element to the shared tooltip popup via aria-describedby + useEffect(() => { + if (!activeAnchor) return; + setAriaDescribedBy(activeAnchor, popupId, true); + return () => setAriaDescribedBy(activeAnchor, popupId, false); + }, [activeAnchor, popupId]); + + return ( + + {children} + {state ? ( + { + if (!open) api.hide(state.anchor); + }} + > + api.holdOpen()} + onMouseLeave={() => api.hide(state.anchor)} + > + {state.render()} + + + ) : null} + + ); +} + +export interface SharedTooltipTriggerProps { + onPointerEnter: (event: PointerEvent) => void; + onPointerLeave: (event: PointerEvent) => void; + onFocus: (event: FocusEvent) => void; + onBlur: (event: FocusEvent) => void; + onPointerDown: (event: PointerEvent) => void; +} + +/** Props that show `content` on the shared tooltip, or null outside a SharedTooltipProvider. */ +export function useSharedTooltip(content: SharedTooltipContent): SharedTooltipTriggerProps | null { + const api = use(SharedTooltipContext); + const scrollTracker = useTooltipScrollTracker(); + const anchorRef = useRef(null); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- refreshes an open shared tooltip when its trigger's label changes + useEffect(() => { + if (api && anchorRef.current) api.refresh(anchorRef.current, content); + }, [api, content]); + if (!api) return null; + return { + // Touch never opens it, as Base UI's mouseOnly trigger; taps also send compatibility mouse events. + onPointerEnter: (event) => { + if (event.pointerType === "touch") return; + const trigger = event.currentTarget; + anchorRef.current = trigger; + api.show(trigger, content, false); + // Scrolling the timeline closes it, as it does a TooltipTrigger's. + scrollTracker?.hover(trigger, api, () => api.dismiss(trigger)); + }, + onPointerLeave: (event) => api.hide(event.currentTarget), + // Keyboard focus shows it at once, as Base UI does. + onFocus: (event) => { + if (event.currentTarget.matches(":focus-visible")) { + anchorRef.current = event.currentTarget; + api.show(event.currentTarget, content, true); + } + }, + onBlur: (event) => api.hide(event.currentTarget), + onPointerDown: (event) => api.dismiss(event.currentTarget), + }; +} + +type Handlers = Partial void>>; + +/** The trigger's own handlers run first, then the shared tooltip's. */ +export function withSharedTooltip( + element: ReactElement, + tooltip: SharedTooltipTriggerProps, + children?: ReactNode, +): ReactElement { + const own = element.props as Handlers; + const merged: Record void> = {}; + for (const key of Object.keys(tooltip) as Array) { + const shared = tooltip[key] as (event: never) => void; + const mine = own[key]; + merged[key] = mine + ? (event) => { + mine(event); + shared(event); + } + : shared; + } + return children === undefined + ? cloneElement(element, merged as Partial) + : cloneElement(element, merged as Partial, children); +} + +/** A tooltip on `render`: the shared one inside a SharedTooltipProvider, Base UI's otherwise. */ +export function SharedTooltipTrigger({ + render, + children, + label, + side = "top", + variant, +}: { + render: ReactElement; + children?: ReactNode; + label: ReactNode; + side?: SharedTooltipContent["side"]; + variant?: SharedTooltipContent["variant"]; +}) { + const tooltip = useSharedTooltip({ + render: () => label, + contentKey: label, + side, + ...(variant ? { variant } : {}), + }); + if (tooltip) return withSharedTooltip(render, tooltip, children); + return ( + + {children} + + {label} + + + ); +} diff --git a/apps/web/src/components/ui/tooltip.browser.test.tsx b/apps/web/src/components/ui/tooltip.browser.test.tsx index 24d76784e8a5a..bcb62ee2fdaf0 100644 --- a/apps/web/src/components/ui/tooltip.browser.test.tsx +++ b/apps/web/src/components/ui/tooltip.browser.test.tsx @@ -3,41 +3,114 @@ import { page, userEvent } from "vite-plus/test/browser"; import "~/index.css"; import { render } from "../../../test/render"; +import { SharedTooltipProvider, SharedTooltipTrigger } from "./shared-tooltip"; import { Tooltip, TooltipPopup, TooltipScrollDismissArea, TooltipTrigger } from "./tooltip"; +function TimelineAction({ shared }: { shared: boolean }) { + if (shared) { + return ( + + }> + Timeline action + + + ); + } + return ( + + Timeline action + Description + + ); +} + it.each([ - { focus: "mouse", keptOpen: false }, - { focus: "keyboard", keptOpen: true }, -])("scrolling with a $focus-focused hovered trigger keeps it open: $keptOpen", async (c) => { - const onScroll = vi.fn(); + { shared: false, focus: "mouse", keptOpen: false }, + { shared: false, focus: "keyboard", keptOpen: true }, + { shared: true, focus: "mouse", keptOpen: false }, + { shared: true, focus: "keyboard", keptOpen: true }, +])( + "scrolling with a $focus-focused hovered trigger (shared: $shared) keeps it open: $keptOpen", + async (c) => { + const onScroll = vi.fn(); + await using screen = await render( + + +
    + , + ); + const trigger = screen.getByRole("button", { name: "Timeline action" }); + if (c.focus === "mouse") { + // A press closes the tooltip; hovering again reopens it with mouse focus kept. + await userEvent.click(trigger); + await userEvent.unhover(trigger); + } else { + await userEvent.keyboard("{Tab}"); + } + await userEvent.hover(trigger); + await expect.element(trigger).toHaveFocus(); + await expect.element(page.getByText("Description")).toBeVisible(); + + // One pixel keeps the pointer over the trigger, so only the scroll can close it. + screen.getByTestId("timeline").element().scrollTop = 1; + await vi.waitFor(() => expect(onScroll).toHaveBeenCalledOnce()); + + if (c.keptOpen) await expect.element(page.getByText("Description")).toBeVisible(); + else await expect.element(page.getByText("Description")).not.toBeInTheDocument(); + }, +); + +it("refreshes an open shared tooltip's label and links aria-describedby on focus", async () => { await using screen = await render( - - - Timeline action - Description - -
    - , + + }> + Copy + + , ); - const trigger = screen.getByRole("button", { name: "Timeline action" }); - if (c.focus === "mouse") { - // A press closes the tooltip; hovering again reopens it with mouse focus kept. - await userEvent.click(trigger); - await userEvent.unhover(trigger); - } else { - await userEvent.keyboard("{Tab}"); - } - await userEvent.hover(trigger); + const trigger = screen.getByRole("button", { name: "Copy" }); + await userEvent.keyboard("{Tab}"); await expect.element(trigger).toHaveFocus(); - await expect.element(page.getByText("Description")).toBeVisible(); + const popup = page.getByText("Copy code"); + await expect.element(popup).toBeVisible(); + const popupId = trigger.element().getAttribute("aria-describedby"); + expect(popupId).toBeTruthy(); + expect(document.getElementById(popupId!)?.textContent).toBe("Copy code"); - screen.getByTestId("timeline").element().scrollTop = 20; - await vi.waitFor(() => expect(onScroll).toHaveBeenCalledOnce()); + await screen.rerender( + + }> + Copy + + , + ); + await expect.element(page.getByText("Copied")).toBeVisible(); + + await userEvent.keyboard("{Tab}"); + await vi.waitFor(() => expect(trigger.element().getAttribute("aria-describedby")).toBeNull()); +}); - if (c.keptOpen) await expect.element(page.getByText("Description")).toBeVisible(); - else await expect.element(page.getByText("Description")).not.toBeInTheDocument(); +it("refreshes a pending shared tooltip if its label changes during the open delay", async () => { + await using screen = await render( + + }> + Copy + + , + ); + const trigger = screen.getByRole("button", { name: "Copy" }); + await userEvent.hover(trigger); + await screen.rerender( + + }> + Copy + + , + ); + await expect.element(page.getByText("Copy code")).toBeVisible(); + expect(page.getByText("Copied").query()).toBeNull(); }); diff --git a/apps/web/src/components/ui/tooltip.tsx b/apps/web/src/components/ui/tooltip.tsx index 577aa48da87fa..e47a6b8d13afe 100644 --- a/apps/web/src/components/ui/tooltip.tsx +++ b/apps/web/src/components/ui/tooltip.tsx @@ -21,13 +21,13 @@ type TooltipActionsRef = RefObject; // The compiler freezes context values; update hovered tooltips through calls instead of shared ref writes. function createTooltipHoverTracker() { - let hovered: { trigger: HTMLElement; actionsRef: TooltipActionsRef } | null = null; + let hovered: { trigger: HTMLElement; owner: object; close: () => void } | null = null; return { - hover(trigger: HTMLElement, actionsRef: TooltipActionsRef) { - hovered = { trigger, actionsRef }; + hover(trigger: HTMLElement, owner: object, close: () => void) { + hovered = { trigger, owner, close }; }, - release(actionsRef: TooltipActionsRef) { - if (hovered?.actionsRef === actionsRef) hovered = null; + release(owner: object) { + if (hovered?.owner === owner) hovered = null; }, dismissUnfocused() { const tooltip = hovered; @@ -37,8 +37,7 @@ function createTooltipHoverTracker() { return; } hovered = null; - // Base UI also cancels delayed hover opens through this action. - tooltip.actionsRef.current?.close(); + tooltip.close(); }, }; } @@ -96,7 +95,8 @@ function TooltipTrigger(props: TooltipPrimitive.Trigger.Props) { {...props} onMouseEnter={(event) => { props.onMouseEnter?.(event); - tracker.hover(event.currentTarget, actionsRef); + // Base UI also cancels delayed hover opens through this action. + tracker.hover(event.currentTarget, actionsRef, () => actionsRef.current?.close()); }} /> ); @@ -161,4 +161,14 @@ function TooltipPopup({ ); } -export { TooltipProvider, Tooltip, TooltipTrigger, TooltipPopup, TooltipScrollDismissArea }; +/** The enclosing TooltipScrollDismissArea's tracker, for triggers that bypass TooltipTrigger. */ +const useTooltipScrollTracker = () => use(TooltipScrollContext); + +export { + TooltipProvider, + Tooltip, + TooltipTrigger, + TooltipPopup, + TooltipScrollDismissArea, + useTooltipScrollTracker, +}; diff --git a/apps/web/src/composer-editor-mentions.ts b/apps/web/src/composer-editor-mentions.ts index 7f3e93b821488..6608d3b2a0439 100644 --- a/apps/web/src/composer-editor-mentions.ts +++ b/apps/web/src/composer-editor-mentions.ts @@ -7,6 +7,7 @@ import { composerMathRanges, type ComposerInlineToken, } from "@t3tools/shared/composerInlineTokens"; +import { markdownMathRanges } from "~/markdown/wordsHast"; export type ComposerPromptSegment = | { @@ -89,7 +90,7 @@ function collectModelTokens(text: string, inlineTokens: ReadonlyArray !taken.some((range) => mention.start < range.end && mention.end > range.start), @@ -98,7 +99,7 @@ function collectModelTokens(text: string, inlineTokens: ReadonlyArray = []; for (const formula of formulas) { diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index c7095b8536469..92a2fa11cf7f2 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -3694,7 +3694,6 @@ "7c1923203049d602": "Code kopieren", "637817e4ff79c90e": "Aktionen für Codeblock", "ebf3a2b1e314aa5f": "Im Terminal ausführen", - "fe219642547fa0bf": "Im Terminal ausführen", "122a8512abc51180": "Details", "58c38c65c2783c5d": "Vollständiger Pfad", "f37e7d36b51c5b28": "Relativen Pfad kopieren", @@ -3706,10 +3705,6 @@ "4967584e8d0fb1c2": "Medienvorschau", "67589dd912eacb7c": "Im integrierten Browser öffnen", "a3c98d4c4b24cecb": "Dateioptionen für {label}", - "b4fe8a076e9fd2f8": "Abgesetzte Formel", - "085d1407e8c92cce": "Formel im Text", - "a2ef393fa7b48ae8": "Abgesetzte Formel scrollen", - "e94685ea5642e088": "Formel im Text scrollen", "3a04583c8500e23d": "Diagramm anzeigen", "16d64f650840fe06": "Code anzeigen", "6d329f7d3a50c7e7": "Tabelle kopieren", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 2ff8148bb7329..b174085c87c95 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -3693,7 +3693,6 @@ "7c1923203049d602": "Copy code", "637817e4ff79c90e": "Code block actions", "ebf3a2b1e314aa5f": "Run in terminal", - "fe219642547fa0bf": "Run in terminal", "122a8512abc51180": "Details", "58c38c65c2783c5d": "Full path", "f37e7d36b51c5b28": "Copy relative path", @@ -3705,10 +3704,6 @@ "4967584e8d0fb1c2": "Preview media", "67589dd912eacb7c": "Open in integrated browser", "a3c98d4c4b24cecb": "File options for {label}", - "b4fe8a076e9fd2f8": "Display equation", - "085d1407e8c92cce": "Inline equation", - "a2ef393fa7b48ae8": "Scroll display equation", - "e94685ea5642e088": "Scroll inline equation", "3a04583c8500e23d": "Show diagram", "16d64f650840fe06": "Show code", "6d329f7d3a50c7e7": "Copy table", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 78c68c4c0dc2f..b12f6e7f0dc32 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -3693,7 +3693,6 @@ "7c1923203049d602": "Copiar código", "637817e4ff79c90e": "Acciones del bloque de código", "ebf3a2b1e314aa5f": "Ejecutar en la terminal", - "fe219642547fa0bf": "Ejecutar en la terminal", "122a8512abc51180": "Detalles", "58c38c65c2783c5d": "Ruta completa", "f37e7d36b51c5b28": "Copiar ruta relativa", @@ -3705,10 +3704,6 @@ "4967584e8d0fb1c2": "Vista previa del contenido", "67589dd912eacb7c": "Abrir en el navegador integrado", "a3c98d4c4b24cecb": "Opciones de archivo de {label}", - "b4fe8a076e9fd2f8": "Ecuación en bloque", - "085d1407e8c92cce": "Ecuación en línea", - "a2ef393fa7b48ae8": "Desplazar la ecuación en bloque", - "e94685ea5642e088": "Desplazar la ecuación en línea", "3a04583c8500e23d": "Mostrar diagrama", "16d64f650840fe06": "Mostrar código", "6d329f7d3a50c7e7": "Copiar tabla", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 873767a296ba5..c5f7562a38e7d 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -3693,7 +3693,6 @@ "7c1923203049d602": "Copier le code", "637817e4ff79c90e": "Actions du bloc de code", "ebf3a2b1e314aa5f": "Exécuter dans le terminal", - "fe219642547fa0bf": "Exécuter dans le terminal", "122a8512abc51180": "Détails", "58c38c65c2783c5d": "Chemin complet", "f37e7d36b51c5b28": "Copier le chemin relatif", @@ -3705,10 +3704,6 @@ "4967584e8d0fb1c2": "Aperçu du média", "67589dd912eacb7c": "Ouvrir dans le navigateur intégré", "a3c98d4c4b24cecb": "Options du fichier {label}", - "b4fe8a076e9fd2f8": "Équation en bloc", - "085d1407e8c92cce": "Équation en ligne", - "a2ef393fa7b48ae8": "Faire défiler l’équation en bloc", - "e94685ea5642e088": "Faire défiler l’équation en ligne", "3a04583c8500e23d": "Afficher le diagramme", "16d64f650840fe06": "Afficher le code", "6d329f7d3a50c7e7": "Copier le tableau", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 69ac82ad8a247..a0a71c4814184 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -3688,7 +3688,6 @@ "7c1923203049d602": "コードをコピー", "637817e4ff79c90e": "コードブロックの操作", "ebf3a2b1e314aa5f": "ターミナルで実行", - "fe219642547fa0bf": "ターミナルで実行", "122a8512abc51180": "詳細", "58c38c65c2783c5d": "フルパス", "f37e7d36b51c5b28": "相対パスをコピー", @@ -3700,10 +3699,6 @@ "4967584e8d0fb1c2": "メディアをプレビュー", "67589dd912eacb7c": "統合ブラウザーで開く", "a3c98d4c4b24cecb": "{label} のファイルオプション", - "b4fe8a076e9fd2f8": "ディスプレイ数式", - "085d1407e8c92cce": "インライン数式", - "a2ef393fa7b48ae8": "ディスプレイ数式をスクロール", - "e94685ea5642e088": "インライン数式をスクロール", "3a04583c8500e23d": "図を表示", "16d64f650840fe06": "コードを表示", "6d329f7d3a50c7e7": "表をコピー", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 10782b2ca6166..ba0da8c82495a 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -3688,7 +3688,6 @@ "7c1923203049d602": "코드 복사", "637817e4ff79c90e": "코드 블록 작업", "ebf3a2b1e314aa5f": "터미널에서 실행", - "fe219642547fa0bf": "터미널에서 실행", "122a8512abc51180": "세부 정보", "58c38c65c2783c5d": "전체 경로", "f37e7d36b51c5b28": "상대 경로 복사", @@ -3700,10 +3699,6 @@ "4967584e8d0fb1c2": "미디어 미리 보기", "67589dd912eacb7c": "통합 브라우저에서 열기", "a3c98d4c4b24cecb": "{label} 파일 옵션", - "b4fe8a076e9fd2f8": "블록 수식", - "085d1407e8c92cce": "인라인 수식", - "a2ef393fa7b48ae8": "블록 수식 스크롤", - "e94685ea5642e088": "인라인 수식 스크롤", "3a04583c8500e23d": "다이어그램 표시", "16d64f650840fe06": "코드 표시", "6d329f7d3a50c7e7": "표 복사", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5b2b9e2b9b381..66d4f0b457e35 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -3693,7 +3693,6 @@ "7c1923203049d602": "Copiar código", "637817e4ff79c90e": "Ações do bloco de código", "ebf3a2b1e314aa5f": "Executar no terminal", - "fe219642547fa0bf": "Executar no terminal", "122a8512abc51180": "Detalhes", "58c38c65c2783c5d": "Caminho completo", "f37e7d36b51c5b28": "Copiar caminho relativo", @@ -3705,10 +3704,6 @@ "4967584e8d0fb1c2": "Pré-visualizar mídia", "67589dd912eacb7c": "Abrir no navegador integrado", "a3c98d4c4b24cecb": "Opções do arquivo {label}", - "b4fe8a076e9fd2f8": "Equação em destaque", - "085d1407e8c92cce": "Equação em linha", - "a2ef393fa7b48ae8": "Rolar a equação em destaque", - "e94685ea5642e088": "Rolar a equação em linha", "3a04583c8500e23d": "Mostrar diagrama", "16d64f650840fe06": "Mostrar código", "6d329f7d3a50c7e7": "Copiar tabela", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 0ecadaba9ded1..879d2684c207f 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -3693,7 +3693,6 @@ "7c1923203049d602": "Копировать код", "637817e4ff79c90e": "Действия с блоком кода", "ebf3a2b1e314aa5f": "Выполнить в терминале", - "fe219642547fa0bf": "Выполнить в терминале", "122a8512abc51180": "Подробности", "58c38c65c2783c5d": "Полный путь", "f37e7d36b51c5b28": "Копировать относительный путь", @@ -3705,10 +3704,6 @@ "4967584e8d0fb1c2": "Предпросмотр медиа", "67589dd912eacb7c": "Открыть во встроенном браузере", "a3c98d4c4b24cecb": "Параметры файла {label}", - "b4fe8a076e9fd2f8": "Формула в отдельной строке", - "085d1407e8c92cce": "Формула в строке", - "a2ef393fa7b48ae8": "Прокрутить формулу", - "e94685ea5642e088": "Прокрутить формулу в строке", "3a04583c8500e23d": "Показать диаграмму", "16d64f650840fe06": "Показать код", "6d329f7d3a50c7e7": "Копировать таблицу", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 1c01b1112768f..3de08f6ce6252 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -3693,7 +3693,6 @@ "7c1923203049d602": "Kopiera kod", "637817e4ff79c90e": "Åtgärder för kodblock", "ebf3a2b1e314aa5f": "Kör i terminalen", - "fe219642547fa0bf": "Kör i terminalen", "122a8512abc51180": "Detaljer", "58c38c65c2783c5d": "Fullständig sökväg", "f37e7d36b51c5b28": "Kopiera relativ sökväg", @@ -3705,10 +3704,6 @@ "4967584e8d0fb1c2": "Förhandsvisa media", "67589dd912eacb7c": "Öppna i den integrerade webbläsaren", "a3c98d4c4b24cecb": "Filalternativ för {label}", - "b4fe8a076e9fd2f8": "Fristående ekvation", - "085d1407e8c92cce": "Ekvation i texten", - "a2ef393fa7b48ae8": "Rulla fristående ekvation", - "e94685ea5642e088": "Rulla ekvation i texten", "3a04583c8500e23d": "Visa diagram", "16d64f650840fe06": "Visa kod", "6d329f7d3a50c7e7": "Kopiera tabell", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 43790340d1167..0193a3db09720 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -3698,7 +3698,6 @@ "7c1923203049d602": "复制代码", "637817e4ff79c90e": "代码块操作", "ebf3a2b1e314aa5f": "在终端中运行", - "fe219642547fa0bf": "在终端中运行", "122a8512abc51180": "详情", "58c38c65c2783c5d": "完整路径", "f37e7d36b51c5b28": "复制相对路径", @@ -3710,10 +3709,6 @@ "4967584e8d0fb1c2": "预览媒体", "67589dd912eacb7c": "在内置浏览器中打开", "a3c98d4c4b24cecb": "{label} 的文件选项", - "b4fe8a076e9fd2f8": "独立公式", - "085d1407e8c92cce": "行内公式", - "a2ef393fa7b48ae8": "滚动查看独立公式", - "e94685ea5642e088": "滚动查看行内公式", "3a04583c8500e23d": "显示图表", "16d64f650840fe06": "显示代码", "6d329f7d3a50c7e7": "复制表格", diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 4ba107059f2b7..2b19b90cc28e3 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -1887,10 +1887,6 @@ code { margin: 0.65rem 0; } -.chat-markdown-math-display .katex-display { - margin: 0; -} - :is(.chat-markdown, .composer-tiptap) h1, :is(.chat-markdown, .composer-tiptap) h2, :is(.chat-markdown, .composer-tiptap) h3, @@ -2312,6 +2308,15 @@ code { overflow-wrap: break-word; } +.chat-markdown [data-markdown-math] { + font-weight: normal; + font-style: normal; +} + +.chat-markdown [data-markdown-math] > svg { + font-size: 1.21em; +} + /* Formula cells keep their natural width and scroll with the table. */ .chat-markdown :is(th, td):has([data-markdown-math]) { max-width: none; diff --git a/apps/web/src/markdown-clipboard.test.ts b/apps/web/src/markdown-clipboard.test.ts index 1b0aa804a8437..7a50785c726c7 100644 --- a/apps/web/src/markdown-clipboard.test.ts +++ b/apps/web/src/markdown-clipboard.test.ts @@ -11,19 +11,27 @@ import { collectAssistantCitations, serializeAssistantCitation, } from "@t3tools/shared/assistantCitations"; -import { markdownMathRanges, parseMarkdownWithMath } from "@t3tools/shared/markdownMath"; +import type { Element as HastElement, ElementContent, Root } from "hast"; -import { unified } from "unified"; -import remarkParse from "remark-parse"; -import { - CHAT_MARKDOWN_REMARK_PLUGINS, - CHAT_USER_MARKDOWN_REMARK_PLUGINS, -} from "@t3tools/shared/markdownPipeline"; +import { markdownTree } from "./markdown/wordsHast"; -const userMarkdown = unified() - .use(remarkParse) - .use(CHAT_MARKDOWN_REMARK_PLUGINS) - .use(CHAT_USER_MARKDOWN_REMARK_PLUGINS); +// Copied Markdown read back as the chat reads it, to check it says what was copied. +const elementsOf = (node: Root | HastElement) => + (node.children as ElementContent[]).filter( + (child): child is HastElement => child.type === "element", + ); +const textOf = (node: ElementContent): string => + node.type === "text" + ? node.value + : node.type === "element" + ? node.children.map(textOf).join("") + : ""; +const readBack = (markdown: string, options?: Parameters[1]) => + elementsOf(markdownTree(markdown, options))[0]!; +// A user message's reading: a single `~` stays text. +const readUserBack = (markdown: string) => readBack(markdown, { singleTilde: false }); +const inline = (node: ElementContent) => + node.type === "element" ? [node.tagName, textOf(node)] : [node.type, textOf(node)]; const TEXT_NODE = 3; const ELEMENT_NODE = 1; @@ -223,10 +231,10 @@ describe("serializeRenderedMarkdownFragment", () => { new FakeText(" here."), ), ); - const paragraph = parseMarkdownWithMath(serializeRenderedMarkdownFragment(asNode(container))) - .children[0]; - if (paragraph?.type !== "paragraph") throw new Error("Expected a paragraph"); - expect(paragraph.children.find((child) => child.type === "inlineCode")?.value).toBe(value); + const paragraph = readBack(serializeRenderedMarkdownFragment(asNode(container))); + const code = elementsOf(paragraph).find((child) => child.tagName === "code"); + expect(paragraph.tagName).toBe("p"); + expect(code && textOf(code)).toBe(value); }); it.each([ @@ -238,28 +246,24 @@ describe("serializeRenderedMarkdownFragment", () => { String.raw`before\ after\ end`, ])("copies prose that parses back unchanged: %s", (value) => { const container = new FakeElement("DIV").append(new FakeText(value)); - const paragraph = userMarkdown.parse(serializeRenderedMarkdownFragment(asNode(container))) - .children[0]; - expect(paragraph).toMatchObject({ type: "paragraph", children: [{ type: "text", value }] }); + const paragraph = readUserBack(serializeRenderedMarkdownFragment(asNode(container))); + expect(paragraph.tagName).toBe("p"); + expect(paragraph.children.map(inline)).toEqual([["text", value]]); }); it.each([ - ["*", "EM", "word", "emphasis"], - ["\\", "CODE", "value", "inlineCode"], - ])("keeps a text edge %j beside %s", (edge, tag, value, type) => { + ["*", "EM", "word"], + ["\\", "CODE", "value"], + ])("keeps a text edge %j beside %s", (edge, tag, value) => { const container = new FakeElement("DIV").append( new FakeText(edge), new FakeElement(tag).append(new FakeText(value)), ); - const paragraph = userMarkdown.parse(serializeRenderedMarkdownFragment(asNode(container))) - .children[0]; - expect(paragraph).toMatchObject({ - type: "paragraph", - children: [ - { type: "text", value: edge }, - type === "inlineCode" ? { type, value } : { type, children: [{ type: "text", value }] }, - ], - }); + const paragraph = readUserBack(serializeRenderedMarkdownFragment(asNode(container))); + expect(paragraph.children.map(inline)).toEqual([ + ["text", edge], + [tag.toLowerCase(), value], + ]); }); it("copies email links with their address and drops in-app destinations", () => { @@ -288,10 +292,10 @@ describe("serializeRenderedMarkdownFragment", () => { expect(copied).toBe( "Write to support@example.com, [Support](mailto:support@example.com?subject=Help), [Support](mailto:support@example.com?subject=Help\\)) or the thread.", ); - const paragraph = parseMarkdownWithMath(copied).children[0]; - if (paragraph?.type !== "paragraph") throw new Error("Expected a paragraph"); expect( - paragraph.children.filter((child) => child.type === "link").map((link) => link.url), + elementsOf(readBack(copied)) + .filter((child) => child.tagName === "a") + .map((link) => link.properties.href), ).toEqual([ "mailto:support@example.com", "mailto:support@example.com?subject=Help", @@ -312,12 +316,14 @@ describe("serializeRenderedMarkdownFragment", () => { ])("keeps the link label and destination: %s", (label, href) => { const anchor = new FakeElement("A", [], { href }).append(new FakeText(label)); const container = new FakeElement("DIV").append(anchor); - const paragraph = userMarkdown.parse(serializeRenderedMarkdownFragment(asNode(container))) - .children[0]; - if (paragraph?.type !== "paragraph") throw new Error("Expected a paragraph"); - expect(paragraph.children).toMatchObject([ - { type: "link", url: href, children: [{ type: "text", value: label }] }, - ]); + const paragraph = readUserBack(serializeRenderedMarkdownFragment(asNode(container))); + expect( + paragraph.children.map((child) => + child.type === "element" + ? [child.tagName, decodeURI(String(child.properties.href)), textOf(child)] + : [child.type, textOf(child)], + ), + ).toEqual([["a", href, label]]); }); it("copies alert and insight callouts as their Markdown instead of the rendered label", () => { @@ -484,31 +490,25 @@ describe("copying rendered Markdown tables", () => { ); const markdown = serializeTableElementToMarkdown(table as unknown as Element); - const tree = parseMarkdownWithMath(markdown); - const parsed = tree.children[0]; - if (parsed?.type !== "table") throw new Error("Expected a table"); - expect(parsed.children.map((row) => row.children.length)).toEqual([2, 2, 2, 2, 2]); - expect(markdownMathRanges(markdown, tree).map((formula) => formula.tex)).toEqual([ - "|x|", - "\\|x\\|", - "|y|", - "|z|", - ]); - expect(parsed.children[1]?.children[1]?.children).toMatchObject([ - { type: "text", value: "*a* | ~~b~~" }, - ]); - expect(parsed.children[4]?.children[1]?.children).toMatchObject([ - { type: "text", value: "> c | d" }, - ]); - const [, , codeRow, linkRow] = parsed.children; - expect(codeRow?.children[1]?.children[0]).toMatchObject({ - type: "inlineCode", - value: "\\(c|d\\)", - }); - expect(linkRow?.children[0]?.children[0]).toMatchObject({ - type: "link", - url: "https://example.com/?q=a|b", - }); + const parsed = readBack(markdown, { math: true }); + expect(parsed.tagName).toBe("table"); + const rows = elementsOf(parsed).flatMap((section) => elementsOf(section)); + const cells = rows.map((row) => elementsOf(row)); + expect(cells.map((row) => row.length)).toEqual([2, 2, 2, 2, 2]); + const formulas: string[] = []; + const visit = (node: HastElement) => { + if (node.tagName === "svg") formulas.push(String(node.properties.ariaLabel)); + else elementsOf(node).forEach(visit); + }; + visit(parsed); + expect(formulas).toEqual(["|x|", "\\|x\\|", "|y|", "|z|"]); + expect(textOf(cells[1]![1]!)).toBe("*a* | ~~b~~"); + expect(textOf(cells[4]![1]!).trim()).toBe("> c | d"); + expect(inline(cells[2]![1]!.children[0]!)).toEqual(["code", "\\(c|d\\)"]); + const link = cells[3]![0]!.children[0]!; + expect(link.type === "element" && decodeURI(String(link.properties.href))).toBe( + "https://example.com/?q=a|b", + ); }); it("copies code and diagrams in cells without markers or unescaped pipes", () => { diff --git a/apps/web/src/markdown-clipboard.ts b/apps/web/src/markdown-clipboard.ts index 7421dbadd4bae..39ef90b2ec19a 100644 --- a/apps/web/src/markdown-clipboard.ts +++ b/apps/web/src/markdown-clipboard.ts @@ -1,4 +1,4 @@ -import { UNFINISHED_DRIVE_PATH } from "@t3tools/shared/markdownWindowsPaths"; +import { UNFINISHED_DRIVE_PATH } from "@t3tools/shared/markdownLinks"; const SKIPPED_TAGS = new Set(["BUTTON", "INPUT", "SCRIPT", "STYLE", "TEMPLATE"]); const SKIPPED_CLASS_NAMES = ["select-none", "sr-only"]; @@ -428,7 +428,7 @@ export function serializeTableElementToMarkdown(table: Element): string { return serializeTable(table).replaceAll(CODE_BOUNDARY, "").trim(); } -// The wrapper MarkdownMath puts on every formula it renders. The sanitizer drops +// The wrapper wordsHast puts on every formula it renders. The sanitizer drops // the attribute from authored HTML. const MATH_SELECTOR = "[data-markdown-math]"; diff --git a/apps/web/src/markdown-incremental.test.tsx b/apps/web/src/markdown-incremental.test.tsx deleted file mode 100644 index 3682deb281fa9..0000000000000 --- a/apps/web/src/markdown-incremental.test.tsx +++ /dev/null @@ -1,135 +0,0 @@ -import { CHAT_MARKDOWN_REHYPE_PLUGINS } from "@t3tools/shared/markdownPipeline"; -import type { Root } from "mdast"; -import { renderToStaticMarkup } from "react-dom/server"; -import ReactMarkdown from "react-markdown"; -import remarkGfm from "remark-gfm"; -import type { Plugin } from "unified"; -import { describe, expect, it } from "vite-plus/test"; - -import { remarkCodexDirectives } from "@t3tools/shared/codexMarkdownDirectives"; -import { remarkGithubAlerts } from "@t3tools/shared/markdownGithubAlerts"; -import { createIncrementalMarkdownPlugin } from "./markdown-incremental"; -import { remarkNormalizeListItemIndentation } from "@t3tools/shared/markdownListIndentation"; - -function render(source: string, incremental?: Plugin<[], Root>, parsedSources?: string[]) { - let tree: Root | undefined; - const observeParsing: Plugin<[], Root> = function () { - const original = this.parser; - if (original) { - this.parser = (text, file) => { - parsedSources?.push(text); - return original(text, file); - }; - } - }; - const capture: Plugin<[], Root> = () => (root) => { - tree = structuredClone(root); - }; - const html = renderToStaticMarkup( - - {source} - , - ); - return { html, tree }; -} - -const prefix = "# Before\n\n```ts\nconst values = [1, 2];\n```\n\n"; - -describe("incremental Markdown parsing", () => { - it("keeps the document prefix cached when list recovery parses contain fences", () => { - const source = - prefix + - "- first block\n\n ```ts\n const nested = 1;\n ```\n\n tail"; - const incremental = createIncrementalMarkdownPlugin(); - const parsedSources: string[] = []; - expect(render(source, incremental, parsedSources)).toEqual(render(source)); - parsedSources.length = 0; - const next = source + " more"; - expect(render(next, incremental, parsedSources)).toEqual(render(next)); - expect(parsedSources).not.toContain(next); - expect(parsedSources.some((text) => text.startsWith("t3-markdown-inline-prefix:"))).toBe(true); - }); - - it.each([ - "a\n===\n\nb\n---\n", - "- first\n\n continued\n\n- next\n", - "> quoted\n>\n> ```js\n> abc\n> ```\n\nend", - "
    \nhello\n\n
    \n\nend", - "[ref]\n\n[ref]: /later", - "a[^x]\n\n[^x]: note", - "a | b\n--|--\na | b\n", - "```\na\n```\n\nnext\n\n~~~\nb\n~~~\n\nmore", - "\n\n\tcode\n\nmore", - "text *bold*", - "> [!NOTE]\n> alert\n\n- [ ] task", - "\uFEFFtext after a byte-order mark", - ])("preserves the parse tree, positions, and HTML while streaming %j", (tail) => { - const source = prefix + tail; - const incremental = createIncrementalMarkdownPlugin(); - for (let end = 0; end <= source.length; end++) { - const text = source.slice(0, end); - expect(render(text, incremental), `prefix ${end}`).toEqual(render(text)); - } - }); - - it.each(["\r\n", "\r"])("preserves partial %j line endings", (newline) => { - const source = (prefix + "next\n\n```\nlast\n```\n\nend").replaceAll("\n", newline); - const incremental = createIncrementalMarkdownPlugin(); - for (let end = 0; end <= source.length; end++) { - const text = source.slice(0, end); - expect(render(text, incremental)).toEqual(render(text)); - } - }); - - it("updates earlier references when definitions arrive after the cached prefix", () => { - const before = "[later] and footnote[^note]\n\n" + prefix; - const incremental = createIncrementalMarkdownPlugin(); - for (const tail of ["text", "[later]: /target", "[later]: /target\n\n[^note]: a note"]) { - expect(render(before + tail, incremental)).toEqual(render(before + tail)); - } - }); - - it("handles edits, replacements, and repeated renders without leaking transformed nodes", () => { - const incremental = createIncrementalMarkdownPlugin(); - const documents = [ - prefix + "- first\n - second", - prefix + "> [!NOTE]\n> transformed alert", - prefix + "plain text", - "replacement without fences", - prefix.replace("Before", "Edited") + "edited prefix", - prefix + "plain text", - prefix + "plain text", - ]; - for (const document of documents) { - expect(render(document, incremental)).toEqual(render(document)); - } - }); - - it("does not freeze unclosed, nested, indented, or mismatched fences", () => { - const prefixes = [ - "```\nopen\n\n", - "````\n```\n\n", - "> ```\n> code\n> ```\n\n", - "- ```\n code\n ```\n\n", - " ```\n code\n ```\n\n", - " $y$', + { ...ASSISTANT, math: true }, + ), + ); + expect(html).not.toMatch(/onload|javascript|position| ReadonlyArray) | null; + }; + /** Expand GitHub `:alias:` emoji shortcodes in prose outside code. */ + readonly githubEmoji?: boolean; +} + +export interface WordsHastOptions { + /** `$…$`, `$$…$$` and `math` code blocks render as SVG. */ + readonly math: boolean; + /** Soft line breaks render as `
    `, as remark-breaks does. */ + readonly breaks: boolean; + /** Raw HTML shows as the text it was written as. */ + readonly escapeHtml: boolean; + /** `★ Insight ───` blocks render as insight callouts. */ + readonly insights: boolean; + readonly extensions: MarkdownExtensions; +} + +const CODEX_DIRECTIVES = ["codex-file-citation", "codex-followup", "artifact-template"]; + +const VOID = new Set("area base br col embed hr img input link meta source track wbr".split(" ")); + +const TAG = + /<(\/?)([a-zA-Z][\w:-]*)((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*)\s*(\/?)>|)|]*>|<\?[\s\S]*?\?>/g; +const ATTRIBUTE = /([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g; + +// Start tags an HTML parser closes an open `

    ` for, and the elements that scope that search. +const CLOSES_PARAGRAPH = new Set( + "address article aside blockquote center details dialog dir div dl fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 header hgroup hr li listing main menu nav ol p plaintext pre search section summary table ul xmp dd dt".split( + " ", + ), +); +const PARAGRAPH_SCOPE = new Set([ + "applet", + "caption", + "table", + "td", + "th", + "marquee", + "object", + "template", + "button", +]); + +type RenderOptions = Omit; + +const decoder = new TextDecoder(); +const encoder = new TextEncoder(); + +function renderToHtml(markdown: string, options: RenderOptions): Uint8Array { + try { + return wordsRenderToHtml(markdown, options); + } catch { + return encoder.encode( + `

    ${markdown.replaceAll("&", "&").replaceAll("<", "<").replaceAll("\n", "
    ")}

    `, + ); + } +} + +const decode = (value: string) => (value.includes("&") ? decodeHTML(value) : value); + +function properties(source: string | undefined, inSvg: boolean): Element["properties"] { + const result: Element["properties"] = {}; + if (!source) return result; + for (const match of source.matchAll(ATTRIBUTE)) { + const name = match[1]!; + const info = find(inSvg ? svgSchema : htmlSchema, inSvg ? name : name.toLowerCase()); + const raw = match[2] ?? match[3] ?? match[4]; + if (raw === undefined) { + result[info.property] = info.boolean || info.overloadedBoolean ? true : ""; + continue; + } + // Attribute values decode as attributes: `©=` in a query stays as written. + const value = raw.includes("&") ? decodeHTMLAttribute(raw) : raw; + result[info.property] = + info.spaceSeparated || info.commaSeparated + ? value.split(info.commaSeparated ? "," : /\s+/).filter(Boolean) + : info.boolean + ? true + : value; + } + return result; +} + +interface Tokenized { + readonly root: Root; + /** Elements with a `data-sourcepos`, which raw HTML can write too. */ + readonly positioned: Element[]; +} + +/** + * Hast for Words' HTML. Its own markup is well formed; raw HTML closes where its end tags say, + * and is sanitized afterwards, so a misnested tag can only change structure, never safety. + */ +function tokenize(html: string, offsetOf: (byte: number) => number): Tokenized { + const root: Root = { type: "root", children: [] }; + const positioned: Element[] = []; + const stack: Array = [root]; + let svgDepth = 0; + let last = 0; + // rehypePreserveBareAnchorPlaceholders: an `
    ` with no attributes that never closes is text. + const anchors: Array<{ element: Element; parent: Root | Element; tag: string } | null> = []; + const text = (end: number) => { + if (end <= last) return; + const parent = stack.at(-1)!; + const value = decode(html.slice(last, end)); + const previous = parent.children.at(-1); + if (previous?.type === "text") previous.value += value; + else parent.children.push({ type: "text", value } as Text); + }; + for (const match of html.matchAll(TAG)) { + text(match.index); + last = match.index + match[0].length; + const tagName = match[2]?.toLowerCase(); + if (!tagName) continue; + if (match[1]) { + if (tagName === "a") anchors.pop(); + if (tagName === "p" && openParagraph(stack) < 0) { + // A stray `

    ` is an empty paragraph to an HTML parser. + (stack.at(-1)!.children as ElementContent[]).push({ + type: "element", + tagName: "p", + properties: {}, + children: [], + }); + continue; + } + const at = stack.findLastIndex((node) => node.type === "element" && node.tagName === tagName); + if (at > 0) { + for (let index = at; index < stack.length; index++) { + if ((stack[index] as Element).tagName === "svg") svgDepth--; + } + stack.length = at; + } + continue; + } + const inSvg = svgDepth > 0 || tagName === "svg"; + if (!inSvg && CLOSES_PARAGRAPH.has(tagName)) { + const paragraph = openParagraph(stack); + if (paragraph > 0) stack.length = paragraph; + } + const element: Element = { + type: "element", + tagName: inSvg ? match[2]! : tagName, + properties: properties(match[3], inSvg), + children: [], + }; + const sourcepos = element.properties.dataSourcepos; + if (typeof sourcepos === "string") { + delete element.properties.dataSourcepos; + const [start, end] = sourcepos.split("-").map((byte) => offsetOf(Number(byte))); + element.position = { + start: { line: 1, column: start! + 1, offset: start! }, + end: { line: 1, column: end! + 1, offset: end! }, + }; + positioned.push(element); + } + const parent = stack.at(-1)!; + (parent.children as ElementContent[]).push(element); + if (tagName === "a") { + anchors.push(match[3]?.trim() ? null : { element, parent, tag: match[0] }); + } + // The HTML parser ignores `/>` on elements that are not void, such as `
    `. + if (!VOID.has(tagName) && (!match[4] || !inSvg)) { + stack.push(element); + if (tagName === "svg") svgDepth++; + } + } + text(html.length); + for (const anchor of anchors) { + if (!anchor) continue; + const siblings = anchor.parent.children as ElementContent[]; + const at = siblings.indexOf(anchor.element); + if (at >= 0) + siblings.splice(at, 1, { type: "text", value: anchor.tag }, ...anchor.element.children); + } + normalizeRawTables(root); + // Words ends each block with a newline; hast from remark has none after the last. + const end = root.children.at(-1); + if (end?.type === "text") { + end.value = end.value.replace(/\n$/, ""); + if (end.value.trim() === "") root.children.pop(); + } + return { root, positioned }; +} + +const positionKey = (node: Element) => + `${node.tagName.toLowerCase()}:${node.position!.start.offset}-${node.position!.end.offset}`; + +/** + * Words' HTML for `markdown` as hast. A position marks what Words generated, so raw HTML that + * writes its own `data-sourcepos` keeps none: Words' elements are those it also writes with raw + * HTML escaped, and a range claimed more often than that is trusted for none of its claimants. + */ +function parse(markdown: string, options: RenderOptions): Root { + const offsetOf = utf16Offsets(markdown); + const render = (escapeHtml?: true) => + tokenize( + decoder.decode( + renderToHtml(markdown, { + ...options, + ...(escapeHtml ? { escapeHtml } : {}), + sourcePositions: true, + }), + ), + offsetOf, + ); + const { root, positioned } = render(); + if (options.escapeHtml || options.skipHtml || !/data-sourcepos/i.test(markdown)) return root; + const generated = new Map(); + for (const node of render(true).positioned) { + const key = positionKey(node); + generated.set(key, (generated.get(key) ?? 0) + 1); + } + const claimed = new Map(); + for (const node of positioned) { + const key = positionKey(node); + claimed.set(key, (claimed.get(key) ?? 0) + 1); + } + for (const node of positioned) { + const key = positionKey(node); + if (claimed.get(key)! > (generated.get(key) ?? 0)) delete node.position; + } + return root; +} + +/** The stack index of the `

    ` an HTML parser would close, or -1 when none is in scope. */ +function openParagraph(stack: ReadonlyArray): number { + for (let index = stack.length - 1; index > 0; index--) { + const tagName = (stack[index] as Element).tagName; + if (tagName === "p") return index; + if (PARAGRAPH_SCOPE.has(tagName)) return -1; + } + return -1; +} + +/** parse5 puts a raw HTML table's rows in a ``; Words' own tables start with ``. */ +function normalizeRawTables(node: Root | Element) { + for (const child of node.children) { + if (child.type === "element") normalizeRawTables(child); + } + if (node.type !== "element" || node.tagName !== "table") return; + const first = node.children.findIndex((child) => isElement(child, "tr")); + if (first < 0) return; + node.children = [ + ...node.children.slice(0, first), + { type: "element", tagName: "tbody", properties: {}, children: node.children.slice(first) }, + ]; +} + +// Words leaves these raw in Markdown destinations, where micromark percent-encodes them. +const UNSAFE_URL_CHARACTERS = /[\\[\]`{}|^"<> ]/g; +const normalizeUri = (value: string) => + value.replace(UNSAFE_URL_CHARACTERS, (character) => encodeURIComponent(character)); + +const windowsPath = (url: string) => { + const path = url.replace(/%5C/gi, "\\"); + return /^[A-Za-z]:[\\/]/.test(path) ? path : undefined; +}; + +const isElement = (node: unknown, tagName?: string): node is Element => + (node as Element | undefined)?.type === "element" && + (tagName === undefined || (node as Element).tagName === tagName); + +const isElementNode = (node: ElementContent): node is Element => node.type === "element"; + +const isMarkdownImage = (node: unknown): boolean => + (isElement(node, "img") && node.position !== undefined) || + (isElement(node, "a") && + node.position !== undefined && + node.children.length === 1 && + isMarkdownImage(node.children[0])); + +const BREAK: ElementContent = { type: "element", tagName: "br", properties: {}, children: [] }; + +// Words' math: these elements and presentation attributes, and no links or handlers. +const MATH_ELEMENTS = new Set(["svg", "g", "text", "tspan", "rect", "path"]); +const MATH_PROPERTIES = new Set([ + "xmlns", + "width", + "height", + "viewBox", + "fill", + "fontFamily", + "fontSize", + "fontStyle", + "fontWeight", + "role", + "ariaLabel", + "x", + "y", + "dx", + "dy", + "d", + "transform", + "stroke", + "strokeWidth", + "textAnchor", +]); +const MATH_STYLE = /^(?:display|vertical-align|overflow|margin|white-space)$/; + +function sanitizeMath(node: Element): Element | null { + if (!MATH_ELEMENTS.has(node.tagName)) return null; + const properties: Element["properties"] = {}; + for (const [key, value] of Object.entries(node.properties)) { + if (MATH_PROPERTIES.has(key)) properties[key] = value; + } + if (typeof node.properties.style === "string") { + const style = node.properties.style + .split(";") + .filter((rule) => MATH_STYLE.test(rule.split(":")[0]!.trim())) + .join(";"); + if (style) properties.style = style; + } + const children: ElementContent[] = []; + for (const child of node.children) { + if (child.type === "text") children.push(child); + else if (child.type === "element") { + const clean = sanitizeMath(child); + if (clean) children.push(clean); + } + } + return { ...node, properties, children }; +} + +interface Walk { + /** Words' hast for more Markdown, rendered with the same options; `indent` as leadingWhitespace's. */ + readonly render: (markdown: string, indent: number) => Root; + readonly source: string; + readonly options: WordsHastOptions; + readonly math: Map; + /** A per-render id prefix for math placeholders, which authored ids cannot share. */ + readonly mathKey: string; + /** What insightSource opened each insight block with, when it opened any. */ + readonly insightMarker: RegExp | null; +} + +/** UTF-16 offsets for the UTF-8 byte offsets in Words' `data-sourcepos`. */ +function utf16Offsets(source: string): (byte: number) => number { + if (!/[^\x00-\x7f]/.test(source)) return (byte) => byte; + const offsets: number[] = []; + for (let index = 0; index < source.length; index++) { + const code = source.codePointAt(index)!; + const bytes = code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4; + for (let byte = 0; byte < bytes; byte++) offsets.push(index); + if (code >= 0x10000) index++; + } + offsets.push(source.length); + return (byte) => offsets[byte] ?? source.length; +} + +const sourceOf = (node: Element, source: string) => + node.position ? source.slice(node.position.start.offset, node.position.end.offset) : ""; + +const textOf = (node: ElementContent): string => + node.type === "text" + ? node.value + : node.type === "element" + ? node.children.map(textOf).join("") + : ""; + +/** A directive's attributes, as strings; anything else Words would never write reads as none. */ +function directiveAttributes(node: Element): Record { + let parsed: unknown; + try { + parsed = JSON.parse(String(node.properties.dataAttributes ?? "{}")); + } catch { + return {}; + } + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {}; + return Object.fromEntries( + Object.entries(parsed).filter( + (entry): entry is [string, string] => typeof entry[1] === "string", + ), + ); +} + +/** remarkCodexDirectives: what a directive Words parsed becomes, as the remark plugin builds it. */ +function codexDirective(node: Element, walk: Walk, inLink: boolean): ElementContent { + const name = node.properties.dataDirective; + const attributes = directiveAttributes(node); + const asText = (): ElementContent => { + const value: ElementContent = { type: "text", value: sourceOf(node, walk.source) }; + return node.tagName === "div" + ? { type: "element", tagName: "p", properties: {}, children: [value] } + : value; + }; + if (name === "codex-file-citation") { + const citation = resolveCodexFileCitationLink(attributes); + if (!citation || inLink) return asText(); + return { + type: "element", + tagName: "a", + properties: { href: citation.href }, + children: [{ type: "text", value: citation.label }], + ...(node.position ? { position: node.position } : {}), + }; + } + if (name === "codex-followup") { + if (!attributes.prompt?.trim() || !node.children.map(textOf).join("").trim()) return asText(); + return { type: "element", tagName: "span", properties: {}, children: node.children }; + } + const template = resolveCodexArtifactTemplate(attributes); + if (!template) return asText(); + return { + type: "element", + tagName: "div", + properties: { + dataCodexArtifactTemplate: "true", + dataArtifactKind: template.artifactKind, + dataDisplayName: template.displayName, + ...(template.galleryKind === undefined ? {} : { dataGalleryKind: template.galleryKind }), + dataSkillDirectory: template.skillDirectory, + dataSkillName: template.skillName, + }, + children: [], + }; +} + +const INLINE_PREFIX = "t3-markdown-inline-prefix:"; + +function stripPositions(node: ElementContent) { + delete node.position; + if (node.type === "element") node.children.forEach(stripPositions); +} + +/** + * remarkNormalizeListItemIndentation: four spaces after a list marker make indented code, but + * agents mean wide indentation, so code starting on the marker's line is Markdown again. True + * when it recovered the item, whose children it then has transformed. + */ +function recoverIndentedCode( + item: Element, + list: Root | Element, + walk: Walk, + inLink: boolean, + inCode: boolean, +): boolean { + const code = item.children.find((child) => child.type === "element"); + const start = code?.position?.start.offset; + const itemStart = item.position?.start.offset; + if (!isElement(code, "pre") || start === undefined || itemStart === undefined) return false; + const value = textOf(code); + if (!/^[\t ]/.test(value)) return false; + if (walk.source.slice(itemStart, start).includes("\n") || /[`~]/.test(walk.source[start]!)) { + return false; + } + // The trimmed first line sets where the item's content starts. + const indent = [.../^[\t ]*/.exec(value)![0]].reduce( + (column, character) => (character === "\t" ? (Math.floor(column / 4) + 1) * 4 : column + 1), + 0, + ); + // The prefix keeps block syntax at the start, such as `#`, from opening a block. + const source = `${INLINE_PREFIX}${value.trim()}`; + const recovered = walk.render(source, indent); + const paragraph = recovered.children.find((child) => child.type === "element"); + const first = isElement(paragraph, "p") ? paragraph.children[0] : undefined; + if (first?.type !== "text" || !first.value.startsWith(INLINE_PREFIX)) return false; + first.value = first.value.slice(INLINE_PREFIX.length); + if (first.value === "") paragraph!.children.shift(); + transform(recovered, { ...walk, source }, inLink, inCode); + transform(item, walk, inLink, inCode); + let blocks = recovered.children.filter( + (child) => !(child.type === "text" && child.value.trim() === ""), + ) as ElementContent[]; + // Their positions point into `source`, not the message. + blocks.forEach(stripPositions); + let at = item.children.indexOf(code); + let remove = 1; + if (!isLooseList(list, walk.source)) { + // A tight item shows its text bare, as remark-rehype unwraps its paragraphs. + blocks = blocks.flatMap((block, index) => [ + ...(index > 0 ? [{ type: "text", value: "\n" } as Text] : []), + ...(isElement(block, "p") ? block.children : [block]), + ]); + const isBlank = (node: ElementContent | undefined) => + node?.type === "text" && node.value.trim() === ""; + if (at === 1 && isBlank(item.children[0])) [at, remove] = [0, 2]; + if (at + remove === item.children.length - 1 && isBlank(item.children.at(-1))) remove++; + } + item.children.splice(at, remove, ...blocks); + return true; +} + +/** remark-rehype's listLoose: a blank line between items, or an item Words wrote as paragraphs. */ +function isLooseList(list: Root | Element, source: string): boolean { + const items = (list.children as ElementContent[]).filter((child): child is Element => + isElement(child, "li"), + ); + return items.some( + (item, index) => + item.children.some((child) => isElement(child, "p")) || + (index > 0 && + /\n[ \t>]*\n/.test( + source.slice( + items[index - 1]!.position?.end.offset ?? 0, + item.position?.start.offset ?? 0, + ), + )), + ); +} + +const WRITTEN_NUMBER = /[ \t]*(\d{1,9})[.)]/y; + +function keepListNumbers(list: Element, source: string) { + let expected = Number(list.properties.start ?? 1); + for (const item of list.children) { + if (!isElement(item, "li")) continue; + const offset = item.position?.start.offset; + WRITTEN_NUMBER.lastIndex = offset ?? 0; + const digits = offset === undefined ? undefined : WRITTEN_NUMBER.exec(source)?.[1]; + const value = digits === undefined ? expected : Number(digits); + if (value !== expected) item.properties.value = String(value); + expected = value + 1; + } +} + +/** What the chat's remark plugins add that Words does not. */ +const link = (href: string, label: string, properties: Element["properties"] = {}): Element => ({ + type: "element", + tagName: "a", + properties: { href, ...properties }, + children: [{ type: "text", value: label }], +}); + +/** Links in text: absolute file paths (remarkLinkAbsoluteFilePaths), then a change request's references. */ +function linkText(value: string, walk: Walk): ElementContent[] | null { + let parts: ElementContent[] = []; + let offset = 0; + for (const { index, path } of absoluteFilePathMatches(value)) { + if (index > offset) parts.push({ type: "text", value: value.slice(offset, index) }); + parts.push(link(path, path)); + offset = index + path.length; + } + if (offset < value.length) parts.push({ type: "text", value: value.slice(offset) }); + const autolinks = walk.options.extensions.changeRequest?.autolinks; + if (autolinks) { + parts = parts.flatMap((part) => { + if (part.type !== "text") return [part]; + const found = autolinks(part.value); + if (found.length === 0) return [part]; + const linked: ElementContent[] = []; + let start = 0; + for (const reference of found) { + if (start < reference.index) { + linked.push({ type: "text", value: part.value.slice(start, reference.index) }); + } + linked.push( + link(reference.url, reference.label, { dataPullRequestAutolink: reference.kind }), + ); + start = reference.index + reference.text.length; + } + if (start < part.value.length) linked.push({ type: "text", value: part.value.slice(start) }); + return linked; + }); + } + return parts.length === 1 && parts[0]!.type === "text" ? null : parts; +} + +function transform(node: Root | Element, walk: Walk, inLink: boolean, inCode: boolean) { + const children = node.children as ElementContent[]; + for (let index = 0; index < children.length; index++) { + const child = children[index]!; + if (child.type === "text") { + if (inCode) continue; + if (walk.options.extensions.githubEmoji && child.value.includes(":")) { + child.value = expandGithubEmojiAliases(child.value); + } + if (inLink) continue; + const parts = linkText(child.value, walk); + if (!parts) continue; + children.splice(index, 1, ...parts); + index += parts.length - 1; + continue; + } + if (child.type !== "element") continue; + // Words gives what it generates a source position; raw HTML that copies its attributes has none. + if (child.properties.dataDirective !== undefined && child.position) { + children[index] = codexDirective(child, walk, inLink); + index--; + continue; + } + const { tagName, properties: props } = child; + if (tagName === "svg") { + // Sanitizing drops SVG, so math waits under a placeholder until after it. + const clean = walk.options.math && child.position ? sanitizeMath(child) : null; + if (clean) { + const key = `${walk.mathKey}-${walk.math.size}`; + walk.math.set(key, clean); + children[index] = { + type: "element", + tagName: "span", + properties: { id: key }, + children: [], + }; + } + continue; + } + if (tagName === "a" && props.dataFootnoteRef !== undefined) { + // remark-rehype's footnote markup, before rehype-sanitize prefixes ids again. + props.href = `#user-content-${String(props.href).slice(1)}`; + props.id = `user-content-${String(props.id)}`; + props.ariaDescribedBy = ["footnote-label"]; + } else if (tagName === "a" && props.dataFootnoteBackref !== undefined) { + const { href, ariaLabel } = props; + child.properties = { + href: `#user-content-${String(href).slice(1)}`, + dataFootnoteBackref: "", + ariaLabel, + className: ["data-footnote-backref"], + }; + } else if (tagName === "li" && typeof props.id === "string" && props.id.startsWith("fn-")) { + props.id = `user-content-${props.id}`; + } else if (tagName === "section" && props.dataFootnotes !== undefined) { + child.properties = { dataFootnotes: "", className: ["footnotes"] }; + child.children.unshift({ + type: "element", + tagName: "h2", + properties: { className: ["sr-only"], id: "footnote-label" }, + children: [{ type: "text", value: "Footnotes" }], + }); + } else if (tagName === "a" && typeof props.href === "string") { + // remarkNormalizeLinksAndTagInlineCode: a Windows drive path links as a file URL. + const path = windowsPath(props.href); + props.href = path ? `file:///${path.replaceAll("\\", "/")}` : normalizeUri(props.href); + } else if (tagName === "img" && typeof props.src === "string") { + const changeRequest = walk.options.extensions.changeRequest; + const src = changeRequest + ? resolveChangeRequestMediaUrl(props.src, changeRequest.repositoryUrl) + : props.src; + props.src = windowsPath(src) ?? normalizeUri(src); + } else if (tagName === "code" && isElement(node, "pre")) { + if (props.dataMeta !== undefined) { + props.dataCodeMeta = props.dataMeta; + delete props.dataMeta; + } + } else if (tagName === "code" && !inLink) { + props.dataInlineCode = ""; + } else if (tagName === "ol" && walk.options.extensions.userMessage) { + keepListNumbers(child, walk.source); + } else if (tagName === "li") { + const firstBlock = child.children.find(isElementNode); + if (isElement(firstBlock, "pre") && recoverIndentedCode(child, node, walk, inLink, inCode)) { + continue; + } + // Tight items put the checkbox directly in `

  • `, loose ones inside its first `

    `. + const checkbox = isElement(child.children[0], "input") + ? child.children[0] + : isElement(firstBlock, "p") && isElement(firstBlock.children[0], "input") + ? firstBlock.children[0] + : undefined; + if (checkbox) { + props.className = ["task-list-item"]; + const { checked } = checkbox.properties; + checkbox.properties = { type: "checkbox", checked, disabled: true }; + if (node.type === "element") node.properties.className = ["contains-task-list"]; + } + breakLines(child, walk.options.breaks); + } else if (tagName === "p") { + breakLines(child, walk.options.breaks); + } else if (tagName === "blockquote") { + // remarkGithubAlerts + const paragraph = child.children.find((item) => item.type === "element"); + const first = isElement(paragraph, "p") ? paragraph.children[0] : undefined; + const text = first?.type === "text" ? first.value : ""; + const insight = walk.insightMarker?.exec(text); + const alert = GITHUB_ALERT_MARKER.exec(text); + // An alert marker followed by more inline content on its line is text, as remarkGithubAlerts reads it. + const match = insight + ? ([insight[0], "insight"] as const) + : alert && (alert[0].endsWith("\n") || (paragraph as Element).children.length === 1) + ? alert + : null; + if (match && first?.type === "text" && isElement(paragraph, "p")) { + first.value = first.value.slice(match[0].length); + if (first.value === "") paragraph.children.shift(); + if (paragraph.children.length === 0) { + const at = child.children.indexOf(paragraph); + const next = child.children[at + 1]; + // The line ending after it goes too, as remark leaves none for a removed paragraph. + const blank = next?.type === "text" && next.value.trim() === "" ? 2 : 1; + child.children.splice(at, blank); + } + props.dataAlert = match[1]!.toLowerCase(); + } + } + transform( + child, + walk, + inLink || tagName === "a", + inCode || tagName === "code" || tagName === "pre", + ); + } +} + +/** + * remark-breaks puts a `
    ` before every soft line ending, and remarkBreakAroundImageLines + * before those next to a Markdown image. Both keep the line ending after it. + */ +/** A Markdown image alone on its line: nothing but a line ending (or the paragraph's edge) around it. */ +function imageOwnsLine(items: ElementContent[], at: number): boolean { + if (!isMarkdownImage(items[at])) return false; + const before = items[at - 1]; + const after = items[at + 1]; + const startsLine = + before === undefined || + (before.type === "text" && /\n[ \t]*$/.test(before.value)) || + isElement(before, "br"); + const endsLine = after === undefined || (after.type === "text" && /^[ \t]*\n/.test(after.value)); + return startsLine && endsLine; +} + +const isBlockElement = (node: ElementContent | undefined) => + node?.type === "element" && CLOSES_PARAGRAPH.has(node.tagName); + +function breakLines(paragraph: Element, breaks: boolean) { + const items = paragraph.children; + for (let at = 0; at < items.length; at++) { + const item = items[at]!; + if ( + item.type === "element" && + breaks && + item.tagName !== "code" && + !CLOSES_PARAGRAPH.has(item.tagName) + ) { + breakLines(item, breaks); + } + if (item.type !== "text" || !item.value.includes("\n")) continue; + const afterImage = imageOwnsLine(items, at - 1); + const beforeImage = imageOwnsLine(items, at + 1); + const afterBlock = isBlockElement(items[at - 1]) || (at === 0 && paragraph.tagName === "li"); + const beforeBlock = + isBlockElement(items[at + 1]) || (at === items.length - 1 && paragraph.tagName === "li"); + const lines = item.value.split("\n"); + const parts: ElementContent[] = []; + lines.forEach((line, index) => { + // A hard break's own line ending follows its
    , and adds no second one; + // structural line endings around a list item's block children stay breaks between blocks. + const afterHardBreak = index === 1 && isElement(items[at - 1], "br"); + const blockBoundary = + (index === 1 && lines[0] === "" && afterBlock) || + (index === lines.length - 1 && line === "" && beforeBlock); + const breaksHere = + index > 0 && + !afterHardBreak && + !blockBoundary && + (breaks || (index === 1 && afterImage) || (index === lines.length - 1 && beforeImage)); + if (index > 0) { + if (breaksHere) { + const previous = parts.at(-1); + if (previous?.type === "text") previous.value = previous.value.replace(/[ \t]+$/, ""); + parts.push(BREAK); + } + parts.push({ type: "text", value: `\n${line}` }); + } else if (line) { + parts.push({ type: "text", value: line }); + } + }); + // Rejoin text that did not break, so the tree matches remark's text nodes. + const merged: ElementContent[] = []; + for (const part of parts) { + const previous = merged.at(-1); + if (part.type === "text" && previous?.type === "text") previous.value += part.value; + else merged.push(part); + } + items.splice(at, 1, ...merged); + at += merged.length - 1; + } +} + +/** + * The wrapper copying reads (markdown-clipboard's MATH_SELECTOR): the formula's TeX, as the source + * Words drew it from, so copying any part of a formula copies the whole of it. + */ +// A formula wider than its block scrolls, with room for the glyphs that reach past its box; in a +// table it keeps its width and the table scrolls. +const MATH_SCROLL = [ + "max-w-full", + "overflow-x-auto", + "overflow-y-hidden", + "px-0.5", + "py-0.75", + "in-[.chat-markdown-table-container]:max-w-none", + "in-[.chat-markdown-table-container]:overflow-visible", +]; + +function mathWrapper(svg: Element): Element { + const tex = String(svg.properties.ariaLabel ?? "").trim(); + const display = /display:\s*block/.test(String(svg.properties.style ?? "")); + return { + type: "element", + tagName: "span", + properties: display + ? { + className: ["chat-markdown-math-display", "block", ...MATH_SCROLL], + dataMarkdownMath: "display", + dataMarkdownCopy: `\\[\n${tex}\n\\]\n\n`, + } + : { + className: ["inline-block", "align-middle", ...MATH_SCROLL], + dataMarkdownMath: "inline", + dataMarkdownCopy: `\\(${tex}\\)`, + }, + children: [svg], + }; +} + +function restoreMath(node: Root | Element, math: Map) { + const children = node.children as ElementContent[]; + for (let index = 0; index < children.length; index++) { + const child = children[index]!; + if (child.type !== "element") continue; + const id = child.properties.id; + const svg = typeof id === "string" ? math.get(id.replace(/^user-content-/, "")) : undefined; + if (svg) children[index] = mathWrapper(svg); + else restoreMath(child, math); + } +} + +const addHeadingIds = rehypeHeadingIds(); +const addTextDirection = rehypeTextDirection(); +const preserveImageSourceMeta = rehypePreserveImageSourceMeta(); +const normalizeLocalEditorLinks = rehypeNormalizeLocalEditorLinks(); +const groupChipPunctuation = rehypeChipPunctuation(); + +const INSIGHT_OPENING = /^( {0,3})(`?)★ Insight[ \t]+─{3,}\2[ \t]*$/u; +const INSIGHT_CLOSING = /^( {0,3})(`?)─{3,}\2[ \t]*$/u; + +interface InsightSource { + readonly source: string; + readonly tree: Root; + readonly marker: RegExp; + /** The offset in the message for an offset in `source`. */ + readonly toOriginal: (offset: number) => number; +} + +/** + * remarkAssistantInsights: a `★ Insight ───` line opens a quoted insight block, which a `───` line + * at the same indentation closes; the end of the text closes one that never does. Lines in code + * neither open nor close one, and an opening Words does not read as a quote's first line, as in + * an HTML block or a quote's lazy line, stays text. + */ +function insightSource(text: string, options: RenderOptions): InsightSource | null { + if (!text.includes("★ Insight")) return null; + const code: Array = []; + const findCode = (node: Root | Element) => { + for (const child of node.children) { + if (child.type !== "element") continue; + if (child.tagName === "pre" && child.position) { + code.push([child.position.start.offset!, child.position.end.offset!]); + } else findCode(child); + } + }; + findCode(parse(text, options)); + const nonce = Math.random().toString(36).slice(2); + const marker = new RegExp(String.raw`^\[!T3-INSIGHT-${nonce}-(\d+)\](?:\r?\n)?`); + const anywhere = new RegExp(String.raw`\[!T3-INSIGHT-${nonce}-(\d+)\]`, "g"); + const lines = text.split(/(?<=\n)/u); + const skipped = new Set(); + for (;;) { + // Each line's offset in the message and in the source, and how much longer it got. + const offsets: Array<{ original: number; source: number; length: number; delta: number }> = []; + let original = 0; + let rewritten = 0; + let opened = 0; + let indent: string | undefined; + const source = lines + .map((line, lineIndex) => { + const value = line.replace(/[\r\n]+$/u, ""); + const ending = line.slice(value.length); + const inCode = code.some(([start, end]) => original >= start && original < end); + let output = line; + if (indent === undefined) { + const opening = inCode ? null : INSIGHT_OPENING.exec(value); + if (opening && !skipped.has(lineIndex)) { + indent = opening[1] ?? ""; + opened++; + output = `> [!T3-INSIGHT-${nonce}-${lineIndex}]${ending}`; + } + } else { + const closing = inCode ? null : INSIGHT_CLOSING.exec(value); + if (closing && closing[1] === indent) { + indent = undefined; + output = ending; + } else output = `> ${line}`; + } + offsets.push({ + original, + source: rewritten, + length: line.length, + delta: output.length - line.length, + }); + original += line.length; + rewritten += output.length; + return output; + }) + .join(""); + if (opened === 0) return null; + const tree = parse(source, options); + let stranded = false; + const visit = (node: Root | Element, quoteStart: Text | undefined) => { + for (const child of node.children) { + if (child.type === "text") { + for (const found of child.value.matchAll(anywhere)) { + if (child === quoteStart && found.index === 0) continue; + skipped.add(Number(found[1])); + stranded = true; + } + } else if (child.type === "element") { + const paragraph = + child.tagName === "blockquote" ? child.children.find(isElementNode) : undefined; + const first = isElement(paragraph, "p") ? paragraph.children[0] : undefined; + visit(child, first?.type === "text" ? first : quoteStart); + } + } + }; + visit(tree, undefined); + if (stranded) continue; + return { + source, + tree, + marker, + toOriginal: (offset) => { + const line = offsets.findLast((entry) => entry.source <= offset) ?? offsets[0]!; + return ( + line.original + Math.min(Math.max(offset - line.source - line.delta, 0), line.length) + ); + }, + }; + } +} + +/** Positions that point into an insight's rewritten source, moved back into the message. */ +function restorePositions(node: Root | Element, toOriginal: (offset: number) => number) { + for (const child of node.children) { + if (child.type !== "element") continue; + if (child.position) { + const start = toOriginal(child.position.start.offset!); + const end = toOriginal(child.position.end.offset!); + child.position = { + start: { line: 1, column: start + 1, offset: start }, + end: { line: 1, column: end + 1, offset: end }, + }; + } + restorePositions(child, toOriginal); + } +} + +const PREVIEW_SEPARATED = new Set([ + "blockquote", + "ul", + "ol", + "li", + "table", + "thead", + "tbody", + "tr", +]); + +/** remarkThoughtPreview: the message as one line of text, keeping math, cut at `maxLength`. */ +function flattenPreview(tree: Root, preview: NonNullable): Root { + const children: ElementContent[] = []; + let remaining = preview.maxLength; + let fragments: string[] = []; + const flush = () => { + if (fragments.length === 0) return; + children.push({ type: "text", value: fragments.join("").replace(/\s+/g, " ") }); + fragments = []; + }; + const take = (value: string) => { + const text = value.slice(0, remaining); + remaining = text.length < value.length ? 0 : remaining - text.length; + // A cut must not leave half a surrogate pair. + return text.replace(/[\uD800-\uDBFF]$/, ""); + }; + const visit = (node: Root | ElementContent) => { + if (remaining === 0) return; + if (node.type === "text") { + fragments.push(take(node.value)); + return; + } + if (node.type === "element" && node.properties.dataMarkdownMath !== undefined) { + flush(); + // One line has no room for display math, which a preview shows inline. + const svg = node.children[0]; + children.push( + node.properties.dataMarkdownMath === "display" && svg?.type === "element" + ? mathWrapper({ + ...svg, + properties: { + ...svg.properties, + style: "display:inline;vertical-align:middle;overflow:visible", + }, + }) + : node, + ); + return; + } + if (node.type === "element" && node.tagName === "img") { + fragments.push(take(String(node.properties.alt ?? ""))); + return; + } + if (node.type === "element" && node.tagName === "br") { + fragments.push(take(" ")); + return; + } + if (node.type !== "root" && node.type !== "element") return; + const separates = node.type === "root" || PREVIEW_SEPARATED.has(node.tagName); + let first = true; + for (const child of node.children as ElementContent[]) { + if (remaining === 0) break; + if (child.type === "text" && child.value.trim() === "" && separates) continue; + if (!first && separates) fragments.push(take(" ")); + first = false; + visit(child); + } + }; + visit(tree); + flush(); + const head = children[0]; + const tail = children.at(-1); + if (head?.type === "text") head.value = head.value.trimStart(); + if (tail?.type === "text") tail.value = tail.value.trimEnd(); + const visible = children.some((child) => child.type !== "text" || child.value); + return { + type: "root", + children: visible ? children : [{ type: "text", value: preview.fallback }], + }; +} + +/** Links become their text, images their alt text, inline code plain text, Mermaid plain code. */ +function makeInert(node: Root | Element) { + const children = node.children as ElementContent[]; + for (let index = 0; index < children.length; index++) { + const child = children[index]!; + if (child.type !== "element") continue; + if (child.tagName === "a") { + children.splice(index, 1, ...child.children); + index--; + continue; + } + if (child.tagName === "img") { + children[index] = { type: "text", value: String(child.properties.alt ?? "") }; + continue; + } + if (child.tagName === "code" && child.properties.dataInlineCode !== undefined) { + children[index] = { type: "text", value: textOf(child) }; + continue; + } + if ( + child.tagName === "code" && + String(child.properties.className ?? "").includes("language-mermaid") + ) { + child.properties.className = ["language-text"]; + } + makeInert(child); + } +} + +/** ChatMarkdown's sanitized hast for `text`, rendered by Words. */ +export function wordsHast(text: string, options: WordsHastOptions): Root { + const { extensions } = options; + const renderOptions: RenderOptions = { + math: options.math, + // llm-math's `\(…\)` and `\[…\]`, which agents write as often as `$`. + texDelimiters: options.math, + autolinkBoundaries: true, + singleTilde: !extensions.userMessage, + leadingWhitespace: extensions.leadingWhitespace === true, + windowsPaths: true, + codeMeta: true, + directives: CODEX_DIRECTIVES, + // Previews and inert Markdown drop raw HTML, as their remark plugins dropped html nodes. + ...(extensions.preview || extensions.inert + ? { skipHtml: true } + : { escapeHtml: options.escapeHtml }), + }; + const insights = options.insights ? insightSource(text, renderOptions) : null; + const source = insights?.source ?? text; + const tree = insights?.tree ?? parse(source, renderOptions); + const walk: Walk = { + render: (markdown, indent) => + parse(markdown, { + ...renderOptions, + leadingWhitespace: extensions.leadingWhitespace === true && { indent }, + }), + source, + options, + math: new Map(), + mathKey: `t3-math-${Math.random().toString(36).slice(2)}`, + insightMarker: insights?.marker ?? null, + }; + transform(tree, walk, false, false); + preserveImageSourceMeta(tree as never); + normalizeLocalEditorLinks(tree as never); + const hast = sanitizeChatHast(tree); + if (walk.math.size > 0) restoreMath(hast, walk.math); + if (insights) restorePositions(hast, insights.toOriginal); + if (extensions.inert) makeInert(hast); + if (extensions.preview) return flattenPreview(hast, extensions.preview); + addHeadingIds(hast); + addTextDirection(hast as never); + groupChipPunctuation(hast as never); + return hast; +} + +export interface CodexDirectiveSource { + readonly name: string; + readonly attributes: Record; + /** UTF-16 offsets of the whole directive in the source. */ + readonly start: number; + readonly end: number; + /** The label's text as written. */ + readonly label: string; + /** Inside a link, where a file citation stays text. */ + readonly inLink: boolean; +} + +/** The Codex directives in `markdown`, as Words reads them. */ +export function codexDirectiveSources(markdown: string): CodexDirectiveSource[] { + const found: CodexDirectiveSource[] = []; + const visit = (node: Root | Element, inLink: boolean) => { + for (const child of node.children) { + if (child.type !== "element") continue; + const name = child.properties.dataDirective; + if (typeof name === "string" && child.position) { + const { start, end } = child.position; + found.push({ + name, + attributes: directiveAttributes(child), + start: start.offset!, + end: end.offset!, + label: directiveLabel(markdown.slice(start.offset, end.offset)), + inLink, + }); + } + visit(child, inLink || child.tagName === "a"); + } + }; + visit( + parse(markdown, { + windowsPaths: true, + autolinkBoundaries: true, + directives: CODEX_DIRECTIVES, + }), + false, + ); + return found; +} + +/** The label of a directive as written, `:name[label]{…}`: brackets nest in it, and `\` escapes. */ +function directiveLabel(written: string): string { + const open = written.indexOf("["); + if (open < 0) return ""; + let depth = 0; + for (let index = open; index < written.length; index++) { + const character = written[index]; + if (character === "\\") index++; + else if (character === "[") depth++; + else if (character === "]" && --depth === 0) return written.slice(open + 1, index); + } + return ""; +} + +/** + * Words' HTML for `markdown` as hast, unsanitized and without the chat's additions. Code blocks, + * links, list items and math carry source positions. + */ +export function markdownTree( + markdown: string, + options: { skipHtml?: boolean; singleTilde?: boolean; math?: boolean } = {}, +): Root { + return parse(markdown, { + windowsPaths: true, + autolinkBoundaries: true, + skipHtml: options.skipHtml === true, + singleTilde: options.singleTilde !== false, + math: options.math === true, + texDelimiters: options.math === true, + }); +} + +/** The formulas Words reads in `text`, as source offsets, for editors that keep math as source. */ +export function markdownMathRanges(text: string): Array<{ start: number; end: number }> { + if (!/[$\\]|(?:`{3,}|~{3,})[ \t]*math\b/.test(text)) return []; + const ranges: Array<{ start: number; end: number }> = []; + const visit = (node: Root | Element) => { + for (const child of node.children) { + if (child.type !== "element") continue; + if (child.tagName === "svg") { + if (child.position) { + ranges.push({ start: child.position.start.offset!, end: child.position.end.offset! }); + } + continue; + } + visit(child); + } + }; + visit(parse(text, { math: true, texDelimiters: true })); + return ranges; +} + +/** The HTML comments Words reads as raw HTML in `markdown`, not as code or text, as source offsets. */ +export function markdownHtmlComments(markdown: string): Array<{ start: number; end: number }> { + const openers = [...markdown.matchAll(/", start + 4); + return { start, end: close < 0 ? markdown.length : close + 3 }; + }); +} + +/** + * The first definition of each label in `markdown`, as one line of Markdown. Words decides which + * `[label]:` text defines one: each label is looked up again after the text. + */ +export function markdownReferenceDefinitions(markdown: string): string[] { + const labels = new Map(); + for (const match of markdown.matchAll(/\[((?:[^\\[\]]|\\.){1,999})\]:/g)) { + const key = match[1]!.replace(/\s+/g, " ").trim().toLowerCase(); + // `[^1]:` is a footnote. + if (key !== "" && !key.startsWith("^") && !labels.has(key)) labels.set(key, match[1]!); + } + if (labels.size === 0) return []; + let probe = `${markdown}\n\n`; + const lookups = new Map(); + for (const label of labels.values()) { + lookups.set(probe.length, label); + probe += `[${label}]\n\n`; + } + const definitions: string[] = []; + const visit = (node: Root | Element) => { + for (const child of node.children) { + if (child.type !== "element") continue; + const label = lookups.get(child.position?.start.offset ?? -1); + if (child.tagName === "a" && label !== undefined) { + const href = String(child.properties.href ?? "").replace(/[<>\\\n]/g, encodeURIComponent); + const title = child.properties.title; + definitions.push( + `[${label}]: <${href}>${typeof title === "string" ? ` "${title.replace(/\s+/g, " ").replace(/["\\]/g, "\\$&")}"` : ""}`, + ); + } else visit(child); + } + }; + visit(parse(probe, { windowsPaths: true })); + return definitions; +} diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index fee70319c71de..92fad6b57ac9d 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -654,6 +654,10 @@ "./provider-instance-ids": { "types": "./src/providerInstanceIds.ts", "default": "./src/providerInstanceIds.ts" + }, + "./pull-request-references": { + "types": "./src/pullRequestReferences.ts", + "default": "./src/pullRequestReferences.ts" } }, "scripts": { @@ -680,16 +684,16 @@ "effect": "catalog:", "gt-i18n": "1.0.40", "jszip": "3.10.1", - "remark-gfm": "catalog:", - "remark-parse": "catalog:", "three": "0.180.0", - "unbash": "^5.0.0", - "unified": "catalog:" + "unbash": "^5.0.0" }, "devDependencies": { "@effect/vitest": "catalog:", "@types/mdast": "^4.0.4", "@types/three": "0.180.0", + "remark-gfm": "catalog:", + "remark-parse": "catalog:", + "unified": "catalog:", "vite-plus": "catalog:" } } diff --git a/packages/client-runtime/src/pullRequestMarkdown.test.ts b/packages/client-runtime/src/pullRequestMarkdown.test.ts index d4f19173758ec..7d9d162d76a05 100644 --- a/packages/client-runtime/src/pullRequestMarkdown.test.ts +++ b/packages/client-runtime/src/pullRequestMarkdown.test.ts @@ -4,19 +4,39 @@ import remarkParse from "remark-parse"; import { unified } from "unified"; import { describe, expect, it } from "vite-plus/test"; +import { splitPullRequestBody, type PullRequestBodySegment } from "./pullRequestMarkdown.ts"; import { changeRequestReferenceAutolinker, resolveChangeRequestMediaUrl, - splitPullRequestBody, - type PullRequestBodySegment, -} from "./pullRequestMarkdown.ts"; +} from "./pullRequestReferences.ts"; + +const definitionParser = unified().use(remarkParse).use(remarkGfm); + +// The finder a client passes: each first definition, joined onto one line out of its quote. +const split = (body: string) => + splitPullRequestBody(body, (markdown) => { + const definitions = new Map(); + const visit = (node: Root | RootContent, quotes: number) => { + if (node.type === "definition" && !definitions.has(node.identifier)) { + const wrap = new RegExp(`(?:\\r\\n|\\r|\\n)(?:[ \\t]*>){0,${quotes}}[ \\t]*`, "gu"); + const source = markdown.slice(node.position?.start.offset, node.position?.end.offset); + definitions.set(node.identifier, source.replace(wrap, " ")); + } + if ("children" in node) { + for (const child of node.children) + visit(child, quotes + (node.type === "blockquote" ? 1 : 0)); + } + }; + visit(definitionParser.parse(markdown), 0); + return [...definitions.values()]; + }); describe("pull request body segmentation", () => { // GitHub writes a dropped image into the body as an `` tag, so a bare attachment link on // its own line is the shape it uses for a video — every one sampled in the wild was one. it("lifts a dropped video out and keeps the prose around it", () => { expect( - splitPullRequestBody( + split( "Before\n\nhttps://github.com/user-attachments/assets/2f8c1a90-1b2c-4d5e-8f90-abcdef123456\n\nAfter", ), ).toEqual([ @@ -43,7 +63,7 @@ describe("pull request body segmentation", () => { ? segment.rows.flat().flatMap((cell) => prose(cell.segments)) : [], ); - const runs = prose(splitPullRequestBody(body)); + const runs = prose(split(body)); expect(runs.map((segment) => segment.text)).toEqual([ "- [ ] Before", " - [ ] code\n- [x] After", @@ -59,9 +79,7 @@ describe("pull request body segmentation", () => { it("reads the source out of a video tag, including a multi-line one", () => { expect( - splitPullRequestBody( - '', - ), + split(''), ).toEqual([ { id: "attachment:0", @@ -75,21 +93,21 @@ describe("pull request body segmentation", () => { it("leaves the img tag GitHub writes for a dropped image as markdown", () => { const body = 'image'; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("leaves an ordinary link alone, whether it is bare or written as markdown", () => { const body = "https://example.com/page\n\n[the docs](https://example.com/docs)"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("never lifts a link inside fenced code out of it", () => { const body = "```\nhttps://example.com/demo.mp4\n```"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); @@ -97,14 +115,14 @@ describe("pull request body segmentation", () => { // GitHub keeps CRLF in a body written in its web editor. it("recognizes fences in a body with CRLF line endings", () => { const body = "```\r\nhttps://example.com/demo.mp4\r\n```"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("closes a CRLF fence, so a video after it still lifts out", () => { const code = '```html\r\n\r\n```'; - expect(splitPullRequestBody(`${code}\r\n\r\nhttps://example.com/demo.mp4\r\n`)).toEqual([ + expect(split(`${code}\r\n\r\nhttps://example.com/demo.mp4\r\n`)).toEqual([ { id: "markdown:0", kind: "markdown", text: code, sourceOffset: 0 }, { id: "attachment:1", @@ -117,21 +135,21 @@ describe("pull request body segmentation", () => { it("does not let a different fence marker close an open fence", () => { const body = "```\n~~~\nhttps://example.com/demo.mp4\n```"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("keeps a video tag that shares its line with prose as markdown", () => { const body = 'Before after'; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("treats an info-string fence as a nested opener, not a close", () => { const body = "```\n```javascript\nhttps://example.com/demo.mp4\n```"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); @@ -139,9 +157,7 @@ describe("pull request body segmentation", () => { it("does not open a fence on a line of inline triple-backtick code", () => { const code = "```\nhttps://example.com/b.png\n```"; expect( - splitPullRequestBody( - `\`\`\`npm test\`\`\` passes.\n\nhttps://example.com/demo.mp4\n\n${code}`, - ), + split(`\`\`\`npm test\`\`\` passes.\n\nhttps://example.com/demo.mp4\n\n${code}`), ).toEqual([ { id: "markdown:0", kind: "markdown", text: "```npm test``` passes.", sourceOffset: 0 }, { @@ -153,14 +169,14 @@ describe("pull request body segmentation", () => { { id: "markdown:2", kind: "markdown", text: code, sourceOffset: 54 }, ]); const multilineSpan = "```foo`\nhttps://example.com/demo.mp4\nbar```"; - expect(splitPullRequestBody(multilineSpan)).toEqual([ + expect(split(multilineSpan)).toEqual([ { id: "markdown:0", kind: "markdown", text: multilineSpan, sourceOffset: 0 }, ]); }); it("leaves an indented code line alone even when it is only a video link", () => { const body = " https://example.com/demo.mp4"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); @@ -169,14 +185,14 @@ describe("pull request body segmentation", () => { const body = ['

    ");
         expect(html).toContain("
  • for (const step of rest.steps) {
  • "); expect(html).toContain("
  • if (step.request.body) {
  • "); - expect(html).toContain("
  • step.request.body = "<redacted>";
  • "); + expect(html).toContain('
  • step.request.body = "";
  • '); }); it("preserves every recovered block separated by blank lines", () => { diff --git a/packages/shared/src/markdownPipeline.ts b/packages/shared/src/markdownPipeline.ts index 53b49a03762a3..6bb022f532942 100644 --- a/packages/shared/src/markdownPipeline.ts +++ b/packages/shared/src/markdownPipeline.ts @@ -1,4 +1,3 @@ -import { isLocalEditorFileUrl, LOCAL_FILE_LINK_SCHEMES } from "@t3tools/contracts"; import type { Heading, Link, @@ -15,7 +14,7 @@ import remarkParse from "remark-parse"; import remarkRehype from "remark-rehype"; import { find, html } from "property-information"; import rehypeRaw from "rehype-raw"; -import rehypeSanitize, { defaultSchema } from "rehype-sanitize"; +import rehypeSanitize from "rehype-sanitize"; import remarkBreaks from "remark-breaks"; import remarkGfm from "remark-gfm"; import { remarkGithubAlerts } from "./markdownGithubAlerts.ts"; @@ -25,17 +24,18 @@ import { remarkEnableLeadingWhitespace, remarkKeepLeadingWhitespace, } from "./markdownLeadingWhitespace.ts"; -import { - CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES, - remarkCodexDirectives, -} from "./codexMarkdownDirectives.ts"; -import { - absoluteFilePathMatches, - isWindowsDrivePathHref, - normalizeMarkdownLinkDestination, -} from "./markdownLinks.ts"; +import { remarkCodexDirectives } from "./codexMarkdownDirectives.ts"; +import { absoluteFilePathMatches } from "./markdownLinks.ts"; import { isWindowsAbsolutePath } from "./path.ts"; -import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts"; +import { + CHAT_MARKDOWN_SANITIZE_SCHEMA, + chatMarkdownImageSource, + rehypeNormalizeLocalEditorLinks, + rehypePreserveImageSourceMeta, + type ChatMarkdownImageProperties, +} from "./markdownHast.ts"; + +export { chatMarkdownImageSource, type ChatMarkdownImageProperties }; export { remarkEnableOrderedListNumbers } from "./markdownOrderedListNumbers.ts"; @@ -47,44 +47,6 @@ type MarkdownImageHastNode = { children?: MarkdownImageHastNode[]; }; -function meaningfulHastChildren(node: MarkdownImageHastNode): MarkdownImageHastNode[] { - return (node.children ?? []).filter( - (child) => !(child.type === "text" && (child as { value?: string }).value?.trim() === ""), - ); -} - -const STANDALONE_IMAGE_BLOCKS = new Set([ - "p", - "div", - "li", - "td", - "th", - "figure", - "center", - "blockquote", -]); - -function soleImageDescendant(node: MarkdownImageHastNode): MarkdownImageHastNode | undefined { - const children = meaningfulHastChildren(node); - if (children.length !== 1) return undefined; - const only = children[0]; - if (only?.type !== "element") return undefined; - if (only.tagName === "img") return only; - return only.tagName === "a" || only.tagName === "strong" || only.tagName === "em" - ? soleImageDescendant(only) - : undefined; -} - -function markStandaloneImages(node: MarkdownImageHastNode) { - if (node.type === "root" || (node.tagName && STANDALONE_IMAGE_BLOCKS.has(node.tagName))) { - const image = soleImageDescendant(node); - if (image) image.properties = { ...image.properties, dataStandalone: true }; - } - node.children?.forEach((child) => { - if (child.type === "element") markStandaloneImages(child); - }); -} - // Whole tags, attributes, and comments, so closing-anchor text inside them never counts as a tag. const RAW_HTML_TAG_PATTERN = /|$)|<\/?[A-Za-z](?:[^"'<>]|"[^"]*"|'[^']*')*>/g; @@ -133,121 +95,6 @@ function rehypePreserveBareAnchorPlaceholders() { }; } -const COLOR_SCHEME_MEDIA = /^\(\s*prefers-color-scheme\s*:\s*(dark|light)\s*\)$/i; - -/** - * The renderer resolves an ``'s `src` (workspace files, host media) but never a ``'s - * `srcset`, which would load unresolved whenever its media matched. A color-scheme source moves - * onto the `` for the renderer to pick by theme; every source is then dropped. - */ -function moveColorSchemeSourcesToImage(picture: MarkdownImageHastNode) { - if (!picture.children) return; - const image = picture.children.find((child) => child.tagName === "img"); - for (const source of picture.children) { - if (source.tagName !== "source" || !image) continue; - const media = source.properties?.media; - const scheme = typeof media === "string" ? COLOR_SCHEME_MEDIA.exec(media)?.[1] : undefined; - const srcSet = source.properties?.srcSet; - const candidate = Array.isArray(srcSet) ? srcSet[0] : srcSet; - // A candidate's URL runs to the first space (a descriptor such as `2x` may follow). - const url = - typeof candidate === "string" ? candidate.trim().split(/\s/, 1)[0]?.replace(/,+$/, "") : ""; - const key = scheme?.toLowerCase() === "dark" ? "dataDarkSrc" : "dataLightSrc"; - // As in a browser, the first source that matches a scheme is the one shown. - if (scheme && url && image.properties?.[key] === undefined) { - // The sanitizer reads a drive letter as a protocol; as a file URL it resolves to the same path. - const value = isWindowsDrivePathHref(url) ? `file:///${url.replaceAll("\\", "/")}` : url; - image.properties = { ...image.properties, [key]: value }; - } - } - picture.children = picture.children.filter((child) => child.tagName !== "source"); -} - -function rehypePreserveImageSourceMeta() { - return (tree: MarkdownImageHastNode) => { - const visit = (node: MarkdownImageHastNode) => { - const src = node.properties?.src; - const title = node.properties?.title; - if (node.type === "element" && node.tagName === "picture") { - moveColorSchemeSourcesToImage(node); - } - if (node.type === "element" && node.tagName === "img") { - node.properties = { - ...node.properties, - ...(typeof src === "string" && isWindowsDrivePathHref(src) ? { dataLocalSrc: src } : {}), - ...(typeof title === "string" ? { dataMarkdownTitle: title } : {}), - }; - } - node.children?.forEach(visit); - }; - - visit(tree); - markStandaloneImages(tree); - }; -} - -const IMAGE_SRC_PROTOCOLS = [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"]; - -// The sanitizer compares schemes case-sensitively, so lowercase accepted editor links first. -function rehypeNormalizeLocalEditorLinks() { - return (tree: MarkdownImageHastNode) => { - const visit = (node: MarkdownImageHastNode) => { - const href = node.properties?.href; - if (node.type === "element" && node.tagName === "a" && typeof href === "string") { - try { - const url = new URL(href); - if (isLocalEditorFileUrl(url)) node.properties = { ...node.properties, href: url.href }; - } catch { - // Not an absolute URL; the sanitizer decides. - } - } - node.children?.forEach(visit); - }; - - visit(tree); - }; -} - -const CHAT_MARKDOWN_SANITIZE_SCHEMA = { - ...defaultSchema, - attributes: { - ...defaultSchema.attributes, - "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"), - // Fence languages plus the two math classes the web chat's math plugin emits. - code: [ - ["className", /^language-./, "math-inline", "math-display"], - "dataCodeMeta", - "dataInlineCode", - ], - blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"], - div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES], - a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"], - img: [ - ...(defaultSchema.attributes?.img ?? []), - "dataDarkSrc", - "dataLightSrc", - "dataLocalSrc", - "dataMarkdownTitle", - "dataStandalone", - ], - }, - protocols: { - ...defaultSchema.protocols, - href: [ - ...(defaultSchema.protocols?.href ?? []), - "file", - "t3-citation", - "t3-context", - THREAD_LINK_PROTOCOL, - // Scheme only: the renderer's URL transform checks the rest of the link shape. - ...LOCAL_FILE_LINK_SCHEMES, - ], - src: IMAGE_SRC_PROTOCOLS, - dataDarkSrc: IMAGE_SRC_PROTOCOLS, - dataLightSrc: IMAGE_SRC_PROTOCOLS, - }, -} satisfies Parameters[0]; - export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [ remarkGfm, remarkEndAutolinksAtScriptPunctuation, @@ -752,10 +599,6 @@ function remarkNormalizeLinksAndTagInlineCode() { }; } -export function shouldPreserveAssistantLineBreaks(text: string): boolean { - return /^★ Insight(?:\s|─)/mu.test(text); -} - export function remarkAssistantInsights(this: Processor) { return (tree: Root, file: { value: unknown }) => { const source = String(file.value); @@ -840,37 +683,6 @@ const imageSourceProcessor = unified() .use(remarkRehype, { allowDangerousHtml: true }) .use(CHAT_MARKDOWN_REHYPE_PLUGINS); -export type ChatMarkdownImageProperties = { - readonly src?: unknown; - readonly dataLocalSrc?: unknown; - readonly dataDarkSrc?: unknown; - readonly dataLightSrc?: unknown; -}; - -/** Keep the authored path for file links and normalize Windows separators for classification. */ -export function chatMarkdownImageSource( - properties?: ChatMarkdownImageProperties, - theme?: "dark" | "light", -) { - const themeSrc = - theme === undefined - ? undefined - : properties?.[theme === "dark" ? "dataDarkSrc" : "dataLightSrc"]; - const localSrc = typeof themeSrc === "string" ? undefined : properties?.dataLocalSrc; - const source = - typeof themeSrc === "string" - ? themeSrc - : typeof localSrc === "string" - ? localSrc - : properties?.src; - if (typeof source !== "string") return null; - const authoredSrc = normalizeMarkdownLinkDestination(source); - return { - authoredSrc, - classifiedSrc: typeof localSrc === "string" ? authoredSrc.replaceAll("\\", "/") : authoredSrc, - }; -} - interface ImageSourceNode { readonly type: string; readonly tagName?: string; diff --git a/packages/shared/src/markdownTaskEdits.ts b/packages/shared/src/markdownTaskEdits.ts new file mode 100644 index 0000000000000..2f33428613147 --- /dev/null +++ b/packages/shared/src/markdownTaskEdits.ts @@ -0,0 +1,28 @@ +/** Offset of the `[ ]` marker on the first line of the list item starting at `listItemStart`. */ +export function taskListMarkerOffset(markdown: string, listItemStart: number): number | null { + const firstLineEnd = markdown.indexOf("\n", listItemStart); + const firstLine = markdown.slice( + listItemStart, + firstLineEnd === -1 ? markdown.length : firstLineEnd, + ); + const match = firstLine.match(/^(?:\s*(?:[-+*]|\d+[.)])\s+)(\[[ xX]\])/); + if (!match?.[1]) return null; + return listItemStart + firstLine.indexOf(match[1]); +} + +export function setMarkdownTaskChecked( + markdown: string, + markerOffset: number, + checked: boolean, +): string { + if ( + markerOffset < 0 || + markdown[markerOffset] !== "[" || + !/[ xX]/.test(markdown[markerOffset + 1] ?? "") || + markdown[markerOffset + 2] !== "]" + ) { + return markdown; + } + + return `${markdown.slice(0, markerOffset + 1)}${checked ? "x" : " "}${markdown.slice(markerOffset + 2)}`; +} diff --git a/packages/shared/src/markdownTaskList.test.ts b/packages/shared/src/markdownTaskList.test.ts index 5e00a3926fa54..7f7519ce49ee5 100644 --- a/packages/shared/src/markdownTaskList.test.ts +++ b/packages/shared/src/markdownTaskList.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vite-plus/test"; -import { markdownTaskMarkerOffset, setMarkdownTaskChecked } from "./markdownTaskList.ts"; +import { markdownTaskMarkerOffset } from "./markdownTaskList.ts"; +import { setMarkdownTaskChecked } from "./markdownTaskEdits.ts"; describe("setMarkdownTaskChecked", () => { const markdown = "- [ ] First\n- [x] Second\n"; diff --git a/packages/shared/src/markdownTaskList.ts b/packages/shared/src/markdownTaskList.ts index fb02f757992b9..a4d18895505c6 100644 --- a/packages/shared/src/markdownTaskList.ts +++ b/packages/shared/src/markdownTaskList.ts @@ -3,36 +3,9 @@ import remarkGfm from "remark-gfm"; import remarkParse from "remark-parse"; import { unified } from "unified"; -const parser = unified().use(remarkParse).use(remarkGfm); - -/** Offset of the `[ ]` marker on the first line of the list item starting at `listItemStart`. */ -export function taskListMarkerOffset(markdown: string, listItemStart: number): number | null { - const firstLineEnd = markdown.indexOf("\n", listItemStart); - const firstLine = markdown.slice( - listItemStart, - firstLineEnd === -1 ? markdown.length : firstLineEnd, - ); - const match = firstLine.match(/^(?:\s*(?:[-+*]|\d+[.)])\s+)(\[[ xX]\])/); - if (!match?.[1]) return null; - return listItemStart + firstLine.indexOf(match[1]); -} - -export function setMarkdownTaskChecked( - markdown: string, - markerOffset: number, - checked: boolean, -): string { - if ( - markerOffset < 0 || - markdown[markerOffset] !== "[" || - !/[ xX]/.test(markdown[markerOffset + 1] ?? "") || - markdown[markerOffset + 2] !== "]" - ) { - return markdown; - } +import { taskListMarkerOffset } from "./markdownTaskEdits.ts"; - return `${markdown.slice(0, markerOffset + 1)}${checked ? "x" : " "}${markdown.slice(markerOffset + 2)}`; -} +const parser = unified().use(remarkParse).use(remarkGfm); /** Hard breaks as U+2028, as iOS draws them; soft breaks stay "\n". */ function plainText(node: Nodes): string { diff --git a/packages/shared/src/markdownWindowsPaths.ts b/packages/shared/src/markdownWindowsPaths.ts index c4c04490a2140..d7c827c8dba8c 100644 --- a/packages/shared/src/markdownWindowsPaths.ts +++ b/packages/shared/src/markdownWindowsPaths.ts @@ -1,5 +1,6 @@ import type { Processor } from "unified"; import { decodeString } from "micromark-util-decode-string"; +import { UNFINISHED_DRIVE_PATH } from "./markdownLinks.ts"; import { isWindowsAbsolutePath } from "./path.ts"; interface DestinationCompileContext { @@ -18,9 +19,6 @@ function keepWindowsPathDestination(this: DestinationCompileContext, token: unkn : decoded; } -// A drive path that has not reached whitespace yet: `C:`, `C:\Users\me`, `C:/work`. -export const UNFINISHED_DRIVE_PATH = /(?:^|\W)[A-Za-z]:(?:[\\/]\S*)?$/; - interface EscapeCompileContext { readonly stack: ReadonlyArray<{ readonly type: string; diff --git a/packages/shared/src/textDirection.ts b/packages/shared/src/textDirection.ts index 0d4a7d88fd837..1efe672108cad 100644 --- a/packages/shared/src/textDirection.ts +++ b/packages/shared/src/textDirection.ts @@ -2,8 +2,8 @@ export type TextDirection = "ltr" | "rtl"; // Hebrew through Arabic Extended-A, their presentation forms, and the // supplementary right-to-left blocks. -const RTL_LETTER = /[֐-ࣿיִ-﷿ﹰ-\u{10800}-\u{10FFF}\u{1E800}-\u{1EFFF}]/u; -const LETTER = /\p{L}/u; +export const RTL_LETTER = /[֐-ࣿיִ-﷿ﹰ-\u{10800}-\u{10FFF}\u{1E800}-\u{1EFFF}]/u; +export const LETTER = /\p{L}/u; const SENTENCE_END = /(?<=[.!?؟])(?=0.5.1' + react: ^18.3.1 || ^19.0.0 + peerDependenciesMeta: + '@pierre/highlights': + optional: true + react: + optional: true + '@pinojs/redact@0.4.0': resolution: {integrity: sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==} @@ -11629,12 +11623,6 @@ packages: react-is@19.2.7: resolution: {integrity: sha512-kZFnouyVv7eP/Phmrlo9FK+zcAdriZJvzxXHF1Sl1P377WSGe2G/JxVolhTrB/jeV47lKImhNUsijjHAAbcl/A==} - react-markdown@10.1.0: - resolution: {integrity: sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==} - peerDependencies: - '@types/react': '>=18' - react: '>=18' - react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz: resolution: {integrity: sha512-TdP2nTxn8W4jPJ5EU+9Ctgf6aOncENP/kMa9aEZpJDmWNLXkxPpcugHMWyZJt2o5WDYE4SPi0V6zV6mOl3+8cA==, tarball: file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz} version: 1.2.0-t3.18 @@ -16556,6 +16544,11 @@ snapshots: - '@shikijs/themes' - shiki + '@pierre/words@file:apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz(@pierre/highlights@0.5.1)(react@19.3.0)': + optionalDependencies: + '@pierre/highlights': 0.5.1 + react: 19.3.0 + '@pinojs/redact@0.4.0': {} '@polka/url@1.0.0-next.29': {} @@ -22531,24 +22524,6 @@ snapshots: react-is@19.2.7: {} - react-markdown@10.1.0(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1): - dependencies: - '@types/hast': 3.0.5 - '@types/mdast': 4.0.4 - '@types/react': 19.3.0 - devlop: 1.1.0 - hast-util-to-jsx-runtime: 2.3.6(supports-color@8.1.1) - html-url-attributes: 3.0.1 - mdast-util-to-hast: 13.2.1(patch_hash=57ea46c73aea3c876ab8d351fe0482ddd081dcb4a0610576e399dbe5eb59d2b1) - react: 19.3.0 - remark-parse: 11.0.0(supports-color@8.1.1) - remark-rehype: 11.1.2 - unified: 11.0.5 - unist-util-visit: 5.1.0 - vfile: 6.0.3 - transitivePeerDependencies: - - supports-color - react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz(katex@0.16.47)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@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): dependencies: react: 19.3.0 diff --git a/scripts/check-changed.ts b/scripts/check-changed.ts index 135ff4ed201f7..d5881661f4cdc 100644 --- a/scripts/check-changed.ts +++ b/scripts/check-changed.ts @@ -433,6 +433,7 @@ const checkChanged = Effect.fn("checkChanged")(function* (input: { file === ".pnpmfile.cjs" || file.startsWith("patches/") || file.startsWith("apps/mobile/deps/") || + file.startsWith("apps/web/deps/") || path.basename(file) === "package.json", ); @@ -479,7 +480,7 @@ const checkChanged = Effect.fn("checkChanged")(function* (input: { if (yield* fs.exists(inRoot(manifest))) yield* copy(manifest); } } - for (const extra of ["apps/mobile/deps", "patches", ".pnpmfile.cjs"]) { + for (const extra of ["apps/mobile/deps", "apps/web/deps", "patches", ".pnpmfile.cjs"]) { if (yield* fs.exists(inRoot(extra))) yield* copy(extra); } const result = yield* vp(["install", "--lockfile-only", "--ignore-scripts"], temp); diff --git a/scripts/release-smoke.ts b/scripts/release-smoke.ts index 3c58be4cbabbf..e7acbf1e76ff1 100644 --- a/scripts/release-smoke.ts +++ b/scripts/release-smoke.ts @@ -68,11 +68,12 @@ function copyWorkspaceManifestFixture(targetRoot: string): void { NodeFS.cpSync(sourcePath, destinationPath); } - const mobileDependencies = NodePath.resolve(repoRoot, "apps/mobile/deps"); - if (NodeFS.existsSync(mobileDependencies)) { - NodeFS.cpSync(mobileDependencies, NodePath.resolve(targetRoot, "apps/mobile/deps"), { - recursive: true, - }); + // Fork tarballs that file: dependencies install from. + for (const forks of ["apps/mobile/deps", "apps/web/deps"]) { + const source = NodePath.resolve(repoRoot, forks); + if (NodeFS.existsSync(source)) { + NodeFS.cpSync(source, NodePath.resolve(targetRoot, forks), { recursive: true }); + } } const patchesDirectory = NodePath.resolve(repoRoot, "patches"); From c1fbdf6cdbe1e16379beebf8658b12a0b8a84f70 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 21:53:58 -0800 Subject: [PATCH 096/139] fix(web): pasting text copied from Word inserts the text instead of an image (#40686) --- apps/web/src/components/chat/ChatComposer.tsx | 10 ++++- .../chat/composerAttachmentFiles.test.ts | 18 +++++++- .../chat/composerAttachmentFiles.ts | 44 +++++++++++++------ 3 files changed, 56 insertions(+), 16 deletions(-) diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 2c3bc34529ffd..6d4487adef153 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -133,6 +133,7 @@ import { fileAttachmentCapabilityBlockReason, fileAttachmentStagingLimit, isPreviewableComposerVideo, + isImageOnlyClipboardHtml, shouldHandleComposerAttachmentPaste, } from "./composerAttachmentFiles"; import { @@ -2918,7 +2919,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) (!pastedContext && activeThreadId && files.length > 0 && - shouldHandleComposerAttachmentPaste({ files, plainText, bypassAutoAttachment })) + shouldHandleComposerAttachmentPaste({ + files, + plainText, + bypassAutoAttachment, + htmlIsOnlyImage: + plainText.length > 0 && + isImageOnlyClipboardHtml(event.clipboardData.getData("text/html")), + })) ) { event.preventDefault(); event.stopPropagation(); diff --git a/apps/web/src/components/chat/composerAttachmentFiles.test.ts b/apps/web/src/components/chat/composerAttachmentFiles.test.ts index 2a487b1f237de..f842566d7cd60 100644 --- a/apps/web/src/components/chat/composerAttachmentFiles.test.ts +++ b/apps/web/src/components/chat/composerAttachmentFiles.test.ts @@ -121,10 +121,26 @@ describe("composer attachment files", () => { ).toBe(true); }); - it("leaves an image-and-text clipboard to the text path under Paste as Text", () => { + it("leaves a Word image-and-text clipboard to the text path, with or without Paste as Text", () => { const image = new File(["png"], "image.png", { type: "image/png" }); const input = { files: [image], plainText: "Hello from Word", bypassAutoAttachment: true }; expect(shouldHandleComposerAttachmentPaste(input)).toBe(false); + // A plain paste of the same Word clipboard keeps the text too. + expect(shouldHandleComposerAttachmentPaste({ ...input, bypassAutoAttachment: false })).toBe( + false, + ); + // Firefox's Copy Image adds the image URL as text and only an as HTML; the image attaches. + expect( + shouldHandleComposerAttachmentPaste({ + files: [image], + plainText: "https://example.com/image.png", + htmlIsOnlyImage: true, + }), + ).toBe(true); + // Finder adds a copied file's name as text. + expect(shouldHandleComposerAttachmentPaste({ files: [image], plainText: "image.png" })).toBe( + true, + ); }); it("preserves text when the clipboard also includes generic image files", () => { diff --git a/apps/web/src/components/chat/composerAttachmentFiles.ts b/apps/web/src/components/chat/composerAttachmentFiles.ts index 041db7193d2e2..191c5841185ff 100644 --- a/apps/web/src/components/chat/composerAttachmentFiles.ts +++ b/apps/web/src/components/chat/composerAttachmentFiles.ts @@ -239,30 +239,46 @@ export function attachmentsToReleaseOnUploadCapabilityLoss( ); } +function isOnlyFileNames(text: string, files: ReadonlyArray): boolean { + const names = new Set(files.map((file) => file.name)); + return text + .split(/\r?\n/) + .filter((line) => line.length > 0) + .every((line) => names.has(line)); +} + +/** A browser's Copy Image puts only an in text/html; rich text sources put the text there. */ +export function isImageOnlyClipboardHtml(html: string): boolean { + if (html.length === 0) return false; + const body = new DOMParser().parseFromString(html, "text/html").body; + return body.querySelector("img") !== null && (body.textContent ?? "").trim().length === 0; +} + export function shouldHandleComposerAttachmentPaste(input: { readonly files: ReadonlyArray; readonly plainText: string; readonly bypassAutoAttachment?: boolean; + readonly htmlIsOnlyImage?: boolean; }): boolean { // Paste as Text keeps the text even when the source also put an image of it on the clipboard. if (input.bypassAutoAttachment && input.plainText.length > 0) return false; if ( - input.files.some((file) => { - if (isDngFile(file)) return true; - const classification = classifyComposerAttachmentFile(file); - return ( - classification === "image" || - classification === "unsupported-image" || - isSvgAttachment({ name: file.name, mimeType: file.type }) - ); - }) + input.files.some( + (file) => isDngFile(file) || isSvgAttachment({ name: file.name, mimeType: file.type }), + ) ) { return true; } - - if (input.plainText.length > 0) { - return false; + const hasImage = input.files.some((file) => { + const classification = classifyComposerAttachmentFile(file); + return classification === "image" || classification === "unsupported-image"; + }); + if (input.plainText.length === 0) { + return hasImage || input.files.some((file) => classifyComposerAttachmentFile(file) === "file"); } - - return input.files.some((file) => classifyComposerAttachmentFile(file) === "file"); + // Rich text sources (Word, Pages) add a picture of the text. Copy Image adds the image URL as + // text beside an , and a Finder copy adds the file names. + return ( + hasImage && (input.htmlIsOnlyImage === true || isOnlyFileNames(input.plainText, input.files)) + ); } From 3b3f8808f43cd67a82e19cbdc5cfcefa7f8d56d4 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sun, 22 Nov 2026 00:03:48 -0600 Subject: [PATCH 097/139] fix(web): wait for image uploads before sending (#40672) Co-authored-by: Cursor Co-authored-by: Julius Marminge Co-authored-by: Claude Opus 5.5 --- .../src/components/ChatView.browser.test.tsx | 103 ++++++++++++++++++ apps/web/src/components/ChatView.tsx | 24 +++- apps/web/src/components/chat/ChatComposer.tsx | 91 ++++++++++++---- .../chat/ComposerFooterControls.tsx | 2 + .../chat/ComposerHeldSendBanner.tsx | 50 +++++++++ .../chat/ComposerPrimaryActions.tsx | 30 +++-- .../chat/preparingComposerImages.test.ts | 58 ++++++++++ .../chat/preparingComposerImages.ts | 90 +++++++++++++++ .../chat/useComposerAttachmentIntake.ts | 34 +++--- .../components/chat/useComposerSelection.ts | 6 + .../src/components/chat/useComposerSend.ts | 36 +++++- apps/web/src/i18n/translations/de.json | 20 ++-- apps/web/src/i18n/translations/en.json | 20 ++-- apps/web/src/i18n/translations/es.json | 20 ++-- apps/web/src/i18n/translations/fr.json | 20 ++-- apps/web/src/i18n/translations/ja.json | 20 ++-- apps/web/src/i18n/translations/ko.json | 20 ++-- apps/web/src/i18n/translations/pt-BR.json | 20 ++-- apps/web/src/i18n/translations/ru.json | 20 ++-- apps/web/src/i18n/translations/sv.json | 20 ++-- apps/web/src/i18n/translations/zh.json | 20 ++-- 21 files changed, 594 insertions(+), 130 deletions(-) create mode 100644 apps/web/src/components/chat/ComposerHeldSendBanner.tsx create mode 100644 apps/web/src/components/chat/preparingComposerImages.test.ts diff --git a/apps/web/src/components/ChatView.browser.test.tsx b/apps/web/src/components/ChatView.browser.test.tsx index ae6628ba6733c..cfd06a8864e0d 100644 --- a/apps/web/src/components/ChatView.browser.test.tsx +++ b/apps/web/src/components/ChatView.browser.test.tsx @@ -112,6 +112,19 @@ vi.mock("../../../../packages/client-runtime/src/connection/driver.ts", async (i return { ...actual, layer: Layer.succeed(actual.ConnectionDriver, fakeDriver) }; }); +// Null runs the real compression; a test sets it to hold an image in preparation. +const compression = vi.hoisted(() => ({ gate: null as Promise | null })); +vi.mock(import("~/lib/imageCompression"), async (original) => { + const actual = await original(); + return { + ...actual, + prepareImageForAttachment: async (...args) => { + await compression.gate; + return actual.prepareImageForAttachment(...args); + }, + }; +}); + vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({ ...(await original()), trackRpcRequestSent: () => {}, @@ -438,6 +451,96 @@ it("an interrupted image-only first send of a new thread says it may not have be expect(page.getByText("Copy message", { exact: true }).query()).toBeNull(); }); +it.each(["new", "existing"] as const)( + "Enter while an image compresses shows a cancellable banner, cancels on edit or Esc, and still sends after leaving a %s thread", + async (kind) => { + const thread = threadWithHistory(`upload-wait-${kind}`, 1); + const other = threadWithHistory(`upload-wait-other-${kind}`, 1); + using _environment = installFakeEnvironment(kind === "existing" ? [thread, other] : [other], { + acceptCommands: true, + }); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + const draftId = DraftId.make(`draft-upload-wait-${kind}`); + if (kind === "new") { + useComposerDraftStore + .getState() + .setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, { + threadId: thread.id, + }); + } + using launch = holdRpc(ORCHESTRATION_V2_WS_METHODS.launchThread, Effect.interrupt); + const router = getRouter( + createMemoryHistory({ + initialEntries: [kind === "new" ? `/draft/${draftId}` : `/${ENVIRONMENT_ID}/${thread.id}`], + }), + ); + await router.load(); + await using _app = await render(, { + // AppRoot brings its own router. + router: false, + }); + const compressed = Promise.withResolvers(); + compression.gate = compressed.promise; + using _compression = { [Symbol.dispose]: () => (compression.gate = null) }; + using _uploads = acceptAttachmentUploads(); + const editor = page.getByTestId("composer-editor"); + await expect.element(editor).toBeVisible(); + await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible(); + + await userEvent.click(editor); + const clipboardData = new DataTransfer(); + clipboardData.items.add(new File([PNG], "shot.png", { type: "image/png" })); + editor + .element() + .dispatchEvent( + new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }), + ); + + // Enter arms the send and shows the banner plus a disabled spinner button. + await userEvent.keyboard("check image{Enter}"); + await expect.element(page.getByText("Sending once image is ready")).toBeVisible(); + const waitingButton = page.getByRole("button", { name: "Sending when ready", exact: true }); + await expect.element(waitingButton).toBeDisabled(); + await expect.element(waitingButton).toHaveAttribute("aria-busy", "true"); + + // Typing disarms the queued send and keeps the edit. + await userEvent.keyboard(" now"); + await expect.element(page.getByText("Sending once image is ready")).not.toBeInTheDocument(); + await expect.element(editor).toHaveTextContent("check image now"); + + // Enter arms again; Esc cancels cleanly. + await userEvent.keyboard("{Enter}"); + await expect.element(page.getByText("Sending once image is ready")).toBeVisible(); + await userEvent.keyboard("{Escape}"); + await expect.element(page.getByText("Sending once image is ready")).not.toBeInTheDocument(); + + // Enter arms again; leaving the thread still sends once the image is ready. + await userEvent.keyboard("{Enter}"); + await expect.element(page.getByText("Sending once image is ready")).toBeVisible(); + await router.navigate({ to: `/${ENVIRONMENT_ID}/${other.id}` }); + await expect.element(page.getByText(`Answer 0 for upload-wait-other-${kind}.`)).toBeVisible(); + + compressed.resolve(); + await vi.waitFor(() => { + if (kind === "new") { + expect(launch.calls).toHaveLength(1); + } else { + expect(dispatchedCommands()).toContainEqual( + expect.objectContaining({ + type: "message.dispatch", + threadId: thread.id, + attachments: [expect.objectContaining({ type: "image", id: "upload-1" })], + }), + ); + } + }); + launch.release(); + }, +); + it("opens the thread actions menu for an older settled thread the shell leaves out", async () => { const thread = { ...threadWithHistory("older-settled", 1), olderSettled: true as const }; using _environment = installFakeEnvironment([thread]); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index ea16d027fcfe9..254bbd4eb9e42 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -59,7 +59,9 @@ import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; import type { UsageLimitSourceSnapshots } from "@t3tools/contracts"; import { feedbackBannerItem } from "./chat/ComposerFeedback"; import { freshSessionBannerItem } from "./chat/ComposerFreshSession"; +import { heldComposerSendBannerItem } from "./chat/ComposerHeldSendBanner"; import { armFreshSession, disarmFreshSession, useFreshSessionArmed } from "./chat/freshSessionArms"; +import { cancelHeldComposerSend, useComposerSendHeld } from "./chat/preparingComposerImages"; import { useUsageLimitsPanel } from "./chat/useUsageLimitsPanel"; import { useWorktreeSetup } from "./chat/useWorktreeSetup"; import { useChatShortcuts } from "./chat/useChatShortcuts"; @@ -253,6 +255,7 @@ import { type ComposerFileAttachment, type ComposerImageAttachment, type DraftThreadEnvMode, + composerTargetKey, useComposerDraftStore, DraftId, } from "../composerDraftStore"; @@ -2658,7 +2661,16 @@ export default function ChatView(props: ChatViewProps) { // While a question or approval owns the composer, its text answers that, not the agent. const freshSessionCommandAvailable = freshSessionAvailable && activePendingApproval === null && pendingUserInputs.length === 0; - const toggleKeepFullHistory = () => setKeepFullHistory(routeThreadKey, !keepFullHistory); + const composerDraftTargetKey = composerTargetKey(composerDraftTarget); + const composerSendHeld = useComposerSendHeld(composerDraftTargetKey); + const cancelHeldSendStable = useStableCallback(() => { + cancelHeldComposerSend(composerDraftTargetKey); + focusComposerStable(); + }); + const toggleKeepFullHistory = () => { + cancelHeldComposerSend(composerDraftTargetKey); + setKeepFullHistory(routeThreadKey, !keepFullHistory); + }; const toggleKeepFullHistoryStable = useStableCallback(toggleKeepFullHistory); const armFreshSessionStable = useStableCallback(() => armFreshSession(routeThreadKey)); const handleRestoreThreadBranch = () => { @@ -2769,6 +2781,14 @@ export default function ChatView(props: ChatViewProps) { freshSessionPending && activePendingApproval === null ? [freshSessionBannerItem(() => disarmFreshSession(routeThreadKey), messages)] : []; + const heldSendItems = composerSendHeld + ? [ + heldComposerSendBannerItem( + { draftTarget: composerDraftTarget, onCancel: cancelHeldSendStable }, + messages, + ), + ] + : []; if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) { return [ ...feedbackBannerItems, @@ -2778,6 +2798,7 @@ export default function ChatView(props: ChatViewProps) { ...usageLimitsItems, ...projectCloneItems, ...freshSessionItems, + ...heldSendItems, ...systemComposerBannerItems, ]; } @@ -2789,6 +2810,7 @@ export default function ChatView(props: ChatViewProps) { ...usageLimitsItems, ...projectCloneItems, ...freshSessionItems, + ...heldSendItems, ...systemComposerBannerItems, branchMismatchBannerItem( { diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 6d4487adef153..6fb651c3471f6 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -252,6 +252,7 @@ import { useNavigate } from "@tanstack/react-router"; import { assistantCitationLabel } from "@t3tools/shared/assistantCitations"; import { assistantCitationNavigation } from "../../lib/assistantCitationNavigation"; import { Button } from "../ui/button"; +import { Spinner } from "../ui/spinner"; import { useManagedPolicy } from "../../state/managedPolicy"; import { hasProviderSetup } from "./ProviderStatusBanner"; import { type AppModelOption, getAppModelOptionsForInstance } from "../../modelSelection"; @@ -286,10 +287,13 @@ import { useComposerStash } from "./useComposerStash"; import { useComposerContextImport } from "./useComposerContextImport"; import { useComposerAttachmentIntake } from "./useComposerAttachmentIntake"; import { + cancelHeldComposerSend, countPreparingComposerImages, + useComposerSendHeld, usePreparingComposerImages, useSubmitAfterPreparingImages, } from "./preparingComposerImages"; +import { HELD_COMPOSER_SEND_BANNER_ID } from "./ComposerHeldSendBanner"; import { ComposerControlsBar } from "./ComposerControlsBar"; import { composerCommandKeyHandler } from "./composerCommandKey"; import { promptSuggestionToAccept, usePromptSuggestion } from "./usePromptSuggestion"; @@ -729,8 +733,18 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) uncommittedSnapShotIds, standaloneComposerImages, } = useComposerImageGroups(attachmentDraftTarget, composerImages, composerPreviewAnnotations); - const preparingComposerImages = usePreparingComposerImages(attachmentTargetKey).filter( - (image) => !image.hidden, + const allPreparingComposerImages = usePreparingComposerImages(attachmentTargetKey); + const preparingComposerImages = allPreparingComposerImages.filter((image) => !image.hidden); + // A message send waits for these itself; an answer waits in the composer below. + const messageHasPreparingImages = + questionAttachmentTarget === null && allPreparingComposerImages.length > 0; + const composerSendHeld = useComposerSendHeld(composerDraftTargetKey); + const cancelHeldSend = () => cancelHeldComposerSend(composerDraftTargetKey); + const handleMultipleModelSelectionsChangeStable = useStableCallback( + (next: React.SetStateAction | null>) => { + cancelHeldSend(); + setMultipleModelSelections(next); + }, ); const nonPersistedComposerImageIds = attachmentDraft.nonPersistedImageIds; const uploadsByImageId = useAttachmentUploadStore((state) => state.uploadsByImageId); @@ -1267,21 +1281,28 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) isComplete: Boolean(activePendingResolvedAnswers), } : null; + const hasMessageToSend = composerSendState.hasSendableContent || messageHasPreparingImages; const showResumeAction = - canResume && !composerDraftHasUserContent(composerDraft) && !isEditingQueuedMessage; + canResume && + !composerDraftHasUserContent(composerDraft) && + !messageHasPreparingImages && + !isEditingQueuedMessage; const collapsedComposerPrimaryActionDisabled = phase === "running" || isSendBusy || + composerSendHeld || isSendDisabled || noProviderAvailable || projectSelectionRequired || environmentUnavailable !== null || - (!composerSendState.hasSendableContent && !showResumeAction); - const collapsedComposerPrimaryActionLabel = showResumeAction - ? gt("Resume thread") - : props.resumeCompactionTokens !== null && !props.keepFullHistory - ? gt("Open composer to compact and send") - : gt("Send message"); + (!hasMessageToSend && !showResumeAction); + const collapsedComposerPrimaryActionLabel = composerSendHeld + ? gt("Sending when ready") + : showResumeAction + ? gt("Resume thread") + : props.resumeCompactionTokens !== null && !props.keepFullHistory + ? gt("Open composer to compact and send") + : gt("Send message"); const showMobilePendingAnswerActions = isMobileViewport && !isComposerCollapsedMobile && pendingPrimaryAction !== null; @@ -2196,7 +2217,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) if (activePendingProgress) { return activePendingProgress.isLastQuestion && Boolean(activePendingResolvedAnswers); } - return composerSendState.hasSendableContent; + return hasMessageToSend; }; const submitComposerRef = useRef< @@ -2282,9 +2303,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) event?.preventDefault(); return false; } - // Sending now would leave a still-compressing image out of the turn, so wait for it. + if (composerSendHeld) { + event?.preventDefault(); + return false; + } + // Sending now would leave a still-compressing image out of the answer, so wait for it. if ( activeThreadId && + questionAttachmentTarget && submitAfterPreparingImages(() => submitComposerRef.current(dispatchMode, submissionIntent)) ) { event?.preventDefault(); @@ -2467,8 +2493,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ? promptSuggestion : null; - const onComposerCommandKey = (key: string, event: KeyboardEvent, isTaskItem?: boolean) => - composerCommandKeyHandler({ + const onComposerCommandKey = (key: string, event: KeyboardEvent, isTaskItem?: boolean) => { + if (key === "Escape" && composerSendHeld && !event.isComposing) { + cancelHeldSend(); + return true; + } + return composerCommandKeyHandler({ keybindings, getShortcutContext, sendShortcut: settings.sendShortcut, @@ -2507,6 +2537,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) promptSuggestion: offeredPromptSuggestion, dismissPromptSuggestion, })(key, event, isTaskItem); + }; const { stashQueue, @@ -2615,7 +2646,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) isSendBusy={isSendBusy} multipleModelsEnabled={routeKind === "draft" && supportsMultipleModels} multipleModelSelections={multipleModelSelections} - onMultipleModelSelectionsChange={setMultipleModelSelections} + onMultipleModelSelectionsChange={handleMultipleModelSelectionsChangeStable} selectedModelSelection={selectedModelSelection} onProviderModelSelect={onProviderModelSelect} activeThreadModelSelection={activeThreadModelSelection} @@ -2713,7 +2744,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const shelfItems = hasBlockingComposerTopDrawer ? bannerItems.filter( (item) => - item.group === "environment" && (item.variant === "error" || item.variant === "warning"), + item.id === HELD_COMPOSER_SEND_BANNER_ID || + (item.group === "environment" && + (item.variant === "error" || item.variant === "warning")), ) : bannerItems; @@ -3518,6 +3551,17 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
    { + if ( + event.key === "Escape" && + composerSendHeld && + !event.defaultPrevented && + !event.nativeEvent.isComposing + ) { + event.preventDefault(); + cancelHeldSend(); + } + }} onFocusCapture={(event) => { const activeElement = event.target; if ( @@ -3652,7 +3696,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) canOperateThread={canOperateThread} canInterrupt={canInterrupt} runId={activeThread?.runtime?.activeRunId ?? null} - hasSendableContent={composerSendState.hasSendableContent} + hasSendableContent={hasMessageToSend} isEditingQueuedMessage={isEditingQueuedMessage} onInterrupt={handleInterruptPrimaryActionStable} > @@ -3662,6 +3706,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) className="flex size-8 shrink-0 items-center justify-center rounded-full bg-message-action text-message-action-foreground hover:bg-message-action-hover disabled:opacity-64" disabled={collapsedComposerPrimaryActionDisabled} aria-label={collapsedComposerPrimaryActionLabel} + aria-busy={composerSendHeld || isSendBusy || undefined} onPointerDown={(event) => event.preventDefault()} onClick={(event) => { event.stopPropagation(); @@ -3671,7 +3716,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) else submitComposer(); }} > - {showResumeAction ? ( + {composerSendHeld || isSendBusy ? ( +
  • + {links.length ? ( + + ) : null} ); } @@ -161,6 +246,7 @@ export default function PdfViewer(props: { positionKey?: string; initialView?: PdfViewState; onViewChange?: (view: PdfViewState) => void; + onOpenLink?: (url: string, event: MouseEvent) => void; actions?: ReactNode; }) { const gt = useGT(); @@ -527,6 +613,8 @@ export default function PdfViewer(props: { query={query} onSize={onSize} onError={setError} + onPageLink={showPage} + onOpenLink={props.onOpenLink} />