From d0a754daeaa972101881befe74a6f99e24e25da7 Mon Sep 17 00:00:00 2001 From: Alex Vallone <39172404+amv146@users.noreply.github.com> Date: Wed, 18 Nov 2026 01:45:01 -0800 Subject: [PATCH 001/183] fix(server): label Copilot rg calls as file searches (#38512) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../Adapters/AcpRegistryAdapterV2.test.ts | 10 +++++----- .../provider-acp-registry/src/server/copilotAcp.ts | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts index 495f16646a61d..1931b1a87b0d2 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts @@ -1997,9 +1997,9 @@ describe("AcpRegistryAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); - // Copilot flattens MCP titles and reports kind "read" for MCP calls and glob; its native - // tool.execution_start event carries the real identity. - it.effect("keeps Copilot's MCP and search tool identity instead of calling them file reads", () => + // Copilot flattens MCP titles and reports kind "read" for MCP calls and glob ("other" for rg); + // its native tool.execution_start event carries the real identity. + it.effect.each(["glob", "rg"])("keeps Copilot's MCP and %s identity", (toolName) => Effect.gen(function* () { const sessionId = "copilot-session"; const executionStart = (data: Record) => ({ @@ -2058,7 +2058,7 @@ describe("AcpRegistryAdapterV2", () => { }), executionStart({ toolCallId: "native-search", - toolName: "glob", + toolName, toolTitle: "Finding files", arguments: { pattern: "*.ts", paths: ["/workspace"] }, }), @@ -2066,7 +2066,7 @@ describe("AcpRegistryAdapterV2", () => { sessionUpdate: "tool_call", toolCallId: "native-search", title: "Finding files matching *.ts", - kind: "read", + kind: toolName === "rg" ? "other" : "read", status: "completed", rawInput: { pattern: "*.ts", paths: ["/workspace"] }, locations: [{ path: "/workspace" }], diff --git a/packages/provider-acp-registry/src/server/copilotAcp.ts b/packages/provider-acp-registry/src/server/copilotAcp.ts index 7b5027147c073..44723c79dc1d5 100644 --- a/packages/provider-acp-registry/src/server/copilotAcp.ts +++ b/packages/provider-acp-registry/src/server/copilotAcp.ts @@ -69,7 +69,7 @@ type CopilotToolIdentity = | { readonly kind: "mcp"; readonly server: string; readonly tool: string } | { readonly kind: "search" }; -const COPILOT_SEARCH_TOOLS = new Set(["glob", "grep"]); +const COPILOT_SEARCH_TOOLS = new Set(["glob", "grep", "rg"]); interface CopilotSessionAttribution { delta: { readonly kind: string; readonly text: string; readonly task?: string } | undefined; From 75514dfa551f155532385cfed1d55408a9bfc5bc Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Wed, 18 Nov 2026 03:51:22 -0600 Subject: [PATCH 002/183] fix(web): keep Ready pending label until its request finishes (#38517) Co-authored-by: Julius Marminge Co-authored-by: Claude Opus 5.5 --- .../chat/ThreadDetailsPrRow.browser.test.tsx | 76 ++++++++++++++++--- .../components/chat/ThreadDetailsPrRow.tsx | 7 +- .../usePullRequestActions.browser.test.tsx | 24 ++++-- .../pullRequest/usePullRequestActions.ts | 18 +++-- 4 files changed, 101 insertions(+), 24 deletions(-) diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx index 0c33baf1a2e4c..3abae88a711b5 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx @@ -1,3 +1,4 @@ +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; import { EnvironmentId, IssueTrackerKind, @@ -12,6 +13,7 @@ import { AsyncResult } from "effect/reactivity"; import { expect, it, vi } from "vite-plus/test"; const state = vi.hoisted(() => ({ + isDraft: false, status: "success" as PullRequestCheck["status"], extraStatus: null as PullRequestCheck["status"] | null, mergeMethods: ["merge"] as Array<"merge" | "squash" | "rebase">, @@ -26,6 +28,10 @@ const state = vi.hoisted(() => ({ projectMergeMethods: {} as Record, })); +vi.mock(import("~/state/use-atom-command"), () => ({ + useAtomCommand: (() => state.perform) as never, +})); + vi.mock(import("~/state/entities"), async (importOriginal) => ({ ...(await importOriginal()), // Rows render a pull request only with a project, so this does not reach tests that pass none. @@ -47,7 +53,7 @@ const queryData = () => ({ number: 1, title: "Test PR", state: "open", - isDraft: false, + isDraft: state.isDraft, mergeability: "mergeable", headBranch: "feature", baseBranch: "main", @@ -60,8 +66,8 @@ const queryData = () => ({ description: null, url: null, })), - capabilities: { actions: ["merge"], mergeMethods: state.mergeMethods }, - viewerPermissions: { actions: ["merge"] }, + capabilities: { actions: ["merge", "ready"], mergeMethods: state.mergeMethods }, + viewerPermissions: { actions: ["merge", "ready"] }, mergeCapabilities: { merge: state.mergeMethods.includes("merge"), squash: state.mergeMethods.includes("squash"), @@ -87,7 +93,6 @@ vi.mock(import("~/state/query"), async (importOriginal) => ({ })); vi.mock(import("../pullRequest/usePullRequestActions"), async (importOriginal) => ({ ...(await importOriginal()), - usePullRequestActionRunner: () => ({ actionPending: false, perform: state.perform }), usePullRequestDefaultMergeMethodResolver: ((_environmentId: unknown, projectId: unknown) => () => state.projectMergeMethods[String(projectId)]) as never, })); @@ -139,6 +144,9 @@ const repositoryProject = { environmentId: EnvironmentId.make("environment"), title: "repo", workspaceRoot: "/work/repo", + defaultModelSelection: null, + createdAt: "2026-11-18T00:00:00.000Z", + updatedAt: "2026-11-18T00:00:00.000Z", scripts: [], repositoryIdentity: { canonicalKey: "github.com/owner/repo", @@ -152,7 +160,7 @@ const repositoryProject = { name: "repo", displayName: "owner/repo", }, -}; +} satisfies EnvironmentProject; const clickButton = async (scope: ParentNode, label: string) => await act(async () => { @@ -173,7 +181,7 @@ it("merges with the last selected merge method", async () => { pr={null} number={1} status={null} - project={null} + project={repositoryProject} label="Test PR" onOpen={vi.fn()} />, @@ -189,7 +197,11 @@ it("merges with the last selected merge method", async () => { const dialog = document.querySelector('[role="alertdialog"]')!; expect(dialog.textContent).toContain("using squash"); await clickMerge(dialog); - expect(state.perform).toHaveBeenCalledWith("merge", "squash"); + expect(state.perform).toHaveBeenCalledWith( + expect.objectContaining({ + input: expect.objectContaining({ action: "merge", mergeMethod: "squash" }), + }), + ); }); it("requires a new merge click after passing checks become pending and pass again", async () => { @@ -201,7 +213,7 @@ it("requires a new merge click after passing checks become pending and pass agai pr={null} number={1} status={null} - project={null} + project={repositoryProject} label="Test PR" onOpen={vi.fn()} /> @@ -233,7 +245,7 @@ it("requires a new merge click after passing checks become pending and pass agai }); async function setup() { - state.perform.mockReset(); + state.perform.mockReset().mockResolvedValue({ _tag: "Success", value: undefined }); state.checkoutError = null; state.newThread.mockReset().mockResolvedValue({ draftId: DraftId.make("new-draft"), @@ -243,6 +255,7 @@ async function setup() { state.addToast.mockReset().mockReturnValue("checkout-toast"); state.updateToast.mockReset(); + state.isDraft = false; state.status = "success"; state.extraStatus = null; state.mergeMethods = ["merge"]; @@ -264,7 +277,7 @@ it("adds the failing checks to a given composer instead of opening a new thread" pr={null} number={1} status={null} - project={null} + project={repositoryProject} label="Test PR" onOpen={vi.fn()} composerTarget={threadRef} @@ -402,3 +415,46 @@ it("names a linked issue row by its kind, number and title, not its URL", async expect(name).toContain("#123"); expect(name).toContain("Sidebar flickers on resize"); }); + +it("keeps Ready pending when refreshed detail becomes mergeable before the action settles", async () => { + await using screen = await setup(); + const row = () => ( + + ); + let finish!: (result: { _tag: "Success"; value: undefined }) => void; + const result = new Promise<{ _tag: "Success"; value: undefined }>((resolve) => { + finish = resolve; + }); + state.perform.mockReturnValueOnce(result); + state.isDraft = true; + await screen.rerender(row()); + await clickButton(screen.container, "Ready"); + expect(state.perform).toHaveBeenCalledWith( + expect.objectContaining({ + input: expect.objectContaining({ + projectId: repositoryProject.id, + repository: "owner/repo", + number: 1, + action: "ready", + }), + }), + ); + await expect.element(screen.getByRole("button", { name: "Marking..." })).toBeDisabled(); + + state.isDraft = false; + await screen.rerender(row()); + await expect.element(screen.getByRole("button", { name: "Marking..." })).toBeDisabled(); + await act(async () => { + finish({ _tag: "Success", value: undefined }); + await result; + }); + await expect.element(screen.getByRole("button", { name: "Merge", exact: true })).toBeEnabled(); +}); diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx index 843bb3b037ca4..3b7836b32293d 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx @@ -166,7 +166,7 @@ export function ThreadDetailsPrRow({ checks: detail?.checks ?? [], }); - const { actionPending, perform } = usePullRequestActionRunner({ + const { actionPending, pendingAction, perform } = usePullRequestActionRunner({ environmentId, reference, terminology, @@ -183,7 +183,10 @@ export function ThreadDetailsPrRow({ ); const [confirmingMerge, setConfirmingMerge] = useState(false); - const rowAction = resolveThreadPanelPullRequestAction(detail); + const rowAction = + pendingAction === "ready" || pendingAction === "merge" + ? pendingAction + : resolveThreadPanelPullRequestAction(detail); if (confirmingMerge && rowAction !== "merge") { setConfirmingMerge(false); } diff --git a/apps/web/src/components/pullRequest/usePullRequestActions.browser.test.tsx b/apps/web/src/components/pullRequest/usePullRequestActions.browser.test.tsx index 018a5012fbf30..79089c0a858c6 100644 --- a/apps/web/src/components/pullRequest/usePullRequestActions.browser.test.tsx +++ b/apps/web/src/components/pullRequest/usePullRequestActions.browser.test.tsx @@ -32,19 +32,26 @@ function deferred() { } function MergeButton({ reference }: { reference: PullRequestRef }) { - const { actionPending, perform } = usePullRequestActionRunner({ + const { actionPending, pendingAction, perform } = usePullRequestActionRunner({ environmentId: EnvironmentId.make("environment"), reference, terminology: sourceControlClients.get(undefined).changeRequest, }); return ( ); } +function setup() { + state.runAction.mockReset(); + state.newThread.mockReset(); + state.prepareThread.mockReset(); +} + it("keeps pending merges with their pull request when navigating between threads", async () => { + setup(); const first: PullRequestRef = { projectId: ProjectId.make("project"), repository: "owner/repo", @@ -54,7 +61,6 @@ it("keeps pending merges with their pull request when navigating between threads const firstResult = deferred<{ _tag: "Success"; value: void }>(); const secondResult = deferred<{ _tag: "Success"; value: void }>(); state.runAction - .mockReset() .mockReturnValueOnce(firstResult.promise) .mockReturnValueOnce(secondResult.promise); await using screen = await render(); @@ -62,6 +68,14 @@ it("keeps pending merges with their pull request when navigating between threads await userEvent.click(button); await expect.element(button).toHaveTextContent("Merging..."); + await screen.rerender( + , + ); + await expect.element(button).toHaveTextContent("Merge"); + await expect.element(button).toBeEnabled(); + await screen.rerender(); + await expect.element(button).toHaveTextContent("Merging..."); + await expect.element(button).toBeDisabled(); await screen.rerender(); await expect.element(button).toHaveTextContent("Merge"); await expect.element(button).toBeEnabled(); @@ -102,6 +116,7 @@ function FixChecksButton() { } it("stops a pull request handoff when its loading toast is dismissed", async () => { + setup(); const prepared = deferred<{ _tag: "Success"; value: { @@ -112,10 +127,9 @@ it("stops a pull request handoff when its loading toast is dismissed", async () }; }>(); state.newThread - .mockReset() .mockResolvedValueOnce({ draftId: "draft-1", threadId: ThreadId.make("thread-1") }) .mockResolvedValueOnce({ draftId: "draft-2", threadId: ThreadId.make("thread-1") }); - state.prepareThread.mockReset().mockReturnValueOnce(prepared.promise); + state.prepareThread.mockReturnValueOnce(prepared.promise); await using screen = await render( diff --git a/apps/web/src/components/pullRequest/usePullRequestActions.ts b/apps/web/src/components/pullRequest/usePullRequestActions.ts index 5b7210ae32b96..f7885e098d3c3 100644 --- a/apps/web/src/components/pullRequest/usePullRequestActions.ts +++ b/apps/web/src/components/pullRequest/usePullRequestActions.ts @@ -201,23 +201,27 @@ export function usePullRequestActionRunner({ const runAction = useAtomCommand(pullRequestEnvironment.runAction, { reportFailure: false, }); - const pendingRef = useRef(new Set()); - const [pendingKeys, setPendingKeys] = useState>(() => new Set()); + const pendingRef = useRef(new Map()); + const [pendingActions, setPendingActions] = useState>( + () => new Map(), + ); const actionKey = reference === null ? null : JSON.stringify([ environmentId, + reference.projectId, reference.host ?? null, reference.repository, reference.number, ]); - const actionPending = actionKey !== null && pendingKeys.has(actionKey); + const pendingAction = actionKey === null ? null : (pendingActions.get(actionKey) ?? null); + const actionPending = pendingAction !== null; const perform = async (action: PullRequestAction, method?: PullRequestMergeMethod) => { if (actionKey === null || reference === null || pendingRef.current.has(actionKey)) return; - pendingRef.current.add(actionKey); - setPendingKeys(new Set(pendingRef.current)); + pendingRef.current.set(actionKey, action); + setPendingActions(new Map(pendingRef.current)); const result = await runAction({ environmentId, input: { @@ -227,7 +231,7 @@ export function usePullRequestActionRunner({ }, }); pendingRef.current.delete(actionKey); - setPendingKeys(new Set(pendingRef.current)); + setPendingActions(new Map(pendingRef.current)); if (result._tag === "Failure") { toastManager.add({ type: "error", @@ -246,7 +250,7 @@ export function usePullRequestActionRunner({ onSuccess?.(action, result.value); }; - return { actionPending, perform }; + return { actionPending, pendingAction, perform }; } export function usePullRequestCloseBatch( From 1c41c5ed898434f97dae7815f57b0914c9aeb0b5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 01:53:22 -0800 Subject: [PATCH 003/183] fix(azure-devops): issue lists reuse each project's states and survive a refresh while loading (#38508) --- apps/web/src/components/issue/IssuesPage.tsx | 8 +++++- .../server/AzureDevOpsIssueTracker.test.ts | 13 +++++++--- .../src/server/AzureDevOpsIssueTracker.ts | 26 +++++++++++++++---- 3 files changed, 38 insertions(+), 9 deletions(-) diff --git a/apps/web/src/components/issue/IssuesPage.tsx b/apps/web/src/components/issue/IssuesPage.tsx index 307aca3741398..bd8627a2e6689 100644 --- a/apps/web/src/components/issue/IssuesPage.tsx +++ b/apps/web/src/components/issue/IssuesPage.tsx @@ -216,7 +216,13 @@ export function IssuesPage() { input: listInput, })); const list = useIssueList(targets); - useLiveRefresh(list.refresh, { key: JSON.stringify(targets) }); + // Refreshing a list still loading would cancel it and start over, losing the scopes already read. + useLiveRefresh( + () => { + if (!list.isPending) list.refresh(); + }, + { key: JSON.stringify(targets) }, + ); const [pages, setPages] = useState>(new Map()); const held = holdIssuePages(list.answers, pages); diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.test.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.test.ts index 5bd495bca73ee..cc6a1d18cd28f 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.test.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.test.ts @@ -219,6 +219,7 @@ describe("AzureDevOpsIssueTracker", () => { const fs = yield* FileSystem.FileSystem; const bodies: string[] = []; const hydrated: string[] = []; + let typeReads = 0; const api = yield* AzureDevOpsIssueTracker.make.pipe( Effect.provide( Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({ @@ -238,6 +239,7 @@ describe("AzureDevOpsIssueTracker", () => { ); } if (resource !== "wiql" && resource !== "workitemsbatch") { + if (resource === "workitemtypes") typeReads += 1; return Effect.succeed(TestSourceControlHost.processOutput(answer(args))); } return fs.readFileString(args[args.indexOf("--in-file") + 1]!).pipe( @@ -260,7 +262,7 @@ describe("AzureDevOpsIssueTracker", () => { }), ), ); - const page = yield* api.listIssues({ + const list = api.listIssues({ cwd: "/w", host: "dev.azure.com", scope: "acme/Web App", @@ -273,11 +275,16 @@ describe("AzureDevOpsIssueTracker", () => { limit: 2, cursor: "2026-07-01T00:00:00Z|7", }); + const page = yield* list; + yield* list; // The rows come back in WIQL's order, and the cursor is the last one of the page. - expect(hydrated).toEqual(["9,7"]); + expect(hydrated).toEqual(["9,7", "9,7"]); expect(page.items.map((item) => item.key)).toEqual(["9", "7"]); expect(page.nextCursor).toBe("2026-07-01T00:00:00Z|7"); - expect(bodies).toHaveLength(1); + // Each `az` call costs seconds, so a second list reuses the project's states. + expect(typeReads).toBe(1); + expect(bodies).toHaveLength(2); + expect(bodies[1]).toBe(bodies[0]); expect(bodies[0]).toContain("AND [System.State] NOT IN ('shipped')"); const { query } = JSON.parse(bodies[0]!) as { query: string }; // Mentions cannot be asked for over REST, so the filter sends no clause for them. diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.ts index 5a6f4c7c38ef9..84212c9ff0ecd 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.ts @@ -3,7 +3,10 @@ * scope is `organization/project` and every call names the organization. Listing is a WIQL * query paged by a `(changedDate, id)` keyset cursor, because WIQL has no offset. */ +import * as Cache from "effect/Cache"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; @@ -67,6 +70,7 @@ const VIEWER_PERMISSIONS: IssueViewerPermissions = { const REST_API_VERSION = "7.1"; const PAGE_SIZE = 100; +const CLOSED_STATES_TTL = Duration.minutes(10); /** Updates are read a page per `az` process, oldest first, so a long history is bounded. */ const UPDATE_PAGE_LIMIT = 5; /** Linked pull requests are read one `az` process each, so a work item's links are bounded. */ @@ -356,8 +360,19 @@ export const make: Effect.Effect< decode: decodeAs(decodeTypes), }).pipe(Effect.map((types) => types.value)); - const closedStates = (input: Parameters[0]) => - workItemTypes(input).pipe(Effect.map(closedStateNames)); + // Each `az` call costs seconds of startup, and a project's states rarely change. + const listClosedStates = yield* Cache.makeWith( + (key: string) => { + const [cwd, organization, project] = JSON.parse(key) as [string, string, string]; + return workItemTypes({ cwd, organization, project, operation: "listIssues" }).pipe( + Effect.map(closedStateNames), + ); + }, + { + capacity: 256, + timeToLive: (exit) => (Exit.isSuccess(exit) ? CLOSED_STATES_TTL : Duration.zero), + }, + ); const workItem = (input: { readonly cwd: string; @@ -599,9 +614,10 @@ export const make: Effect.Effect< const dateField = created ? "[System.CreatedDate]" : "[System.ChangedDate]"; return yield* scoped("listIssues", input).pipe( Effect.flatMap((scope) => - closedStates({ ...scope, cwd: input.cwd, operation: "listIssues" }).pipe( - Effect.map((closed) => ({ scope, closed })), - ), + Cache.get( + listClosedStates, + JSON.stringify([input.cwd, scope.organization, scope.project]), + ).pipe(Effect.map((closed) => ({ scope, closed }))), ), Effect.flatMap(({ scope, closed }) => invokeWithBody({ From fe1f1a5732d8a72f435ee4981bef303d88d7dc7f Mon Sep 17 00:00:00 2001 From: Ian Rowe <87292868+ianrowe12@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:08:25 -0500 Subject: [PATCH 004/183] fix(acp): Devin terminals no longer inherit the launching thread's T3 MCP credentials (#26652) Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks --- .../src/server/clientTerminals.test.ts | 45 ++++++++++++++++--- .../src/server/clientTerminals.ts | 41 ++++++++++++----- 2 files changed, 69 insertions(+), 17 deletions(-) diff --git a/packages/provider-acp/src/server/clientTerminals.test.ts b/packages/provider-acp/src/server/clientTerminals.test.ts index 22f8bb9ce3dde..87a96999cd1bf 100644 --- a/packages/provider-acp/src/server/clientTerminals.test.ts +++ b/packages/provider-acp/src/server/clientTerminals.test.ts @@ -99,28 +99,59 @@ describe("AcpClientTerminals", () => { it.live("resolves terminal environment from the requesting ACP session", () => Effect.gen(function* () { + const inheritedEnvironment = yield* HostProcess.Environment; const terminals = yield* makeAcpClientTerminals({ defaultCwd: process.cwd(), - environmentForSession: (sessionId) => ({ - T3_TEST_ACP_SESSION_TOKEN: sessionId === "session-a" ? "token-a" : "token-b", - }), + environmentForSession: (sessionId) => + sessionId === "unknown" + ? undefined + : { + T3_ACP_MCP_AUTHORIZATION: sessionId === "session-a" ? "token-a" : "token-b", + T3CODE_THREAD_ID: sessionId, + }, }); yield* Effect.addFinalizer(() => terminals.disposeAll); + inheritedEnvironment.T3_TEST_INHERITED = "refreshed"; for (const [sessionId, expected] of [ - ["session-a", "token-a"], - ["session-b", "token-b"], + ["session-a", "token-a||session-a|refreshed|T3_TEST_OVERRIDE=request"], + ["session-b", "token-b||session-b|refreshed|T3_TEST_OVERRIDE=request"], + ["unknown", "|||refreshed|T3_TEST_OVERRIDE=inherited"], ] as const) { const created = yield* terminals.create({ sessionId, command: process.execPath, - args: ["-e", "process.stdout.write(process.env.T3_TEST_ACP_SESSION_TOKEN ?? '')"], + args: [ + "-e", + "const env = process.env; process.stdout.write([env.T3_ACP_MCP_AUTHORIZATION ?? '', env.t3_Acp_Mcp_Endpoint ?? '', env.T3CODE_THREAD_ID ?? '', env.T3_TEST_INHERITED, ...Object.keys(env).filter((name) => name.toUpperCase() === 'T3_TEST_OVERRIDE').map((name) => name + '=' + env[name])].join('|'))", + ], + ...(sessionId === "unknown" + ? {} + : { + env: [ + { name: "T3_TEST_OVERRIDE", value: "first" }, + { name: "t3_Test_Override", value: "second" }, + { name: "T3_TEST_OVERRIDE", value: "request" }, + ], + }), }); yield* terminals.waitForExit({ sessionId, terminalId: created.terminalId }); const output = yield* terminals.output({ sessionId, terminalId: created.terminalId }); expect(output.output).toBe(expected); } - }).pipe(Effect.provide(NodeServices.layer)), + }).pipe( + Effect.provideService(HostProcess.Environment, { + ...process.env, + T3_ACP_MCP_AUTHORIZATION: "launching-thread-token", + t3_Acp_Mcp_Endpoint: "launching-thread-endpoint", + T3CODE_THREAD_ID: "launching-thread", + T3_TEST_INHERITED: "kept", + T3_TEST_OVERRIDE: "inherited", + }), + // Exercise Windows' case-insensitive variable names on every OS. + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provide(NodeServices.layer), + ), ); it.live("runs Devin shell source with arguments, pipes, and session fallback variables", () => diff --git a/packages/provider-acp/src/server/clientTerminals.ts b/packages/provider-acp/src/server/clientTerminals.ts index 77d8767904bb5..2fda24d4e4fa5 100644 --- a/packages/provider-acp/src/server/clientTerminals.ts +++ b/packages/provider-acp/src/server/clientTerminals.ts @@ -12,6 +12,7 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; 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"; const MAX_LIVE_TERMINALS = 16; const MAX_UNRELEASED_TERMINALS = 64; @@ -137,22 +138,38 @@ function acpTerminalCommand(input: { readonly request: EffectAcpSchema.CreateTerminalRequest; readonly shellCommands?: boolean | undefined; readonly defaultCwd: string; - readonly environment?: NodeJS.ProcessEnv | undefined; + readonly environment: NodeJS.ProcessEnv; readonly forceKillAfter: Duration.Input; }) { return ChildProcess.make(input.request.command, input.request.args ?? [], { cwd: input.request.cwd ?? input.defaultCwd, - ...(input.environment === undefined ? {} : { env: input.environment }), + env: input.environment, shell: input.shellCommands === true && (input.request.args?.length ?? 0) === 0, forceKillAfter: input.forceKillAfter, }); } +// Windows variable names are case-insensitive and Node passes only one spelling to the child, +// so a later layer's `Path` must replace an earlier `PATH` rather than sit beside it. +function mergeEnvironments( + isWindows: boolean, + layers: ReadonlyArray>, +) { + const variables = new Map(); + for (const layer of layers) { + for (const [name, value] of layer) { + variables.set(isWindows ? name.toUpperCase() : name, [name, value]); + } + } + return Object.fromEntries(variables.values()); +} + export const makeAcpClientTerminals = Effect.fn("makeAcpClientTerminals")(function* ( options: AcpClientTerminalsOptions, ): Effect.fn.Return { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const forceKillAfter = options.forceKillAfter ?? "5 seconds"; + const isWindows = yield* HostProcess.isWindows; const creationPermit = yield* Semaphore.make(1); const terminals = new Map(); let nextTerminalNumber = 1; @@ -215,16 +232,20 @@ export const makeAcpClientTerminals = Effect.fn("makeAcpClientTerminals")(functi `ACP terminal/create exceeded the limit of ${MAX_LIVE_TERMINALS} concurrent terminals.`, ); } - const requestEnvironment = Object.fromEntries( - (request.env ?? []).map((variable) => [variable.name, variable.value] as const), + // Thread credentials and identity must come from the requesting session. + const inheritedEnvironment = Object.fromEntries( + Object.entries(options.environment ?? (yield* HostProcess.Environment)).filter( + ([name]) => + !name.toUpperCase().startsWith("T3_ACP_MCP_") && + name.toUpperCase() !== "T3CODE_THREAD_ID", + ), ); const sessionEnvironment = options.environmentForSession?.(request.sessionId); - const environment = - options.environment === undefined && - sessionEnvironment === undefined && - (request.env?.length ?? 0) === 0 - ? undefined - : { ...options.environment, ...sessionEnvironment, ...requestEnvironment }; + const environment = mergeEnvironments(isWindows, [ + Object.entries(inheritedEnvironment), + Object.entries(sessionEnvironment ?? {}), + (request.env ?? []).map((variable) => [variable.name, variable.value] as const), + ]); const terminalScope = yield* Scope.make(); const child = yield* restore( spawner From 0d405f664a2720a73ad2491529597317c6bd5945 Mon Sep 17 00:00:00 2001 From: Fuksss Date: Wed, 18 Nov 2026 11:13:28 +0100 Subject: [PATCH 005/183] fix(web): a ~\ home path opens as a read-only home file, not as a project file (#38510) Co-authored-by: Julius Marminge --- apps/web/src/components/files/filePath.test.ts | 5 +++++ apps/web/src/components/files/filePath.ts | 4 +++- packages/client-runtime/src/operations/projects.ts | 11 ++++++++--- packages/shared/src/path.test.ts | 1 + packages/shared/src/path.ts | 13 +++++++++---- 5 files changed, 26 insertions(+), 8 deletions(-) diff --git a/apps/web/src/components/files/filePath.test.ts b/apps/web/src/components/files/filePath.test.ts index fbe6a67ece922..00a3247dc6508 100644 --- a/apps/web/src/components/files/filePath.test.ts +++ b/apps/web/src/components/files/filePath.test.ts @@ -33,6 +33,11 @@ describe("fileBreadcrumbs", () => { { label: ".claude", path: "~/.claude", kind: "directory" }, { label: "CLAUDE.md", path: "~/.claude/CLAUDE.md", kind: "file" }, ]); + expect(fileBreadcrumbs("t3code", "~\\.claude/CLAUDE.md")).toEqual([ + { label: "~", path: "~/", kind: "directory" }, + { label: ".claude", path: "~/.claude", kind: "directory" }, + { label: "CLAUDE.md", path: "~/.claude/CLAUDE.md", kind: "file" }, + ]); expect(isListableHostFolder("~/")).toBe(true); expect(isListableHostFolder("~/.claude")).toBe(true); }); diff --git a/apps/web/src/components/files/filePath.ts b/apps/web/src/components/files/filePath.ts index facefbb173016..b7a9d2784d973 100644 --- a/apps/web/src/components/files/filePath.ts +++ b/apps/web/src/components/files/filePath.ts @@ -16,7 +16,9 @@ export function fileBreadcrumbs(projectName: string, relativePath: string): File const windowsPath = isWindowsAbsolutePath(relativePath); const separator = windowsPath ? "\\" : "/"; // `\` is a legal filename character outside Windows paths. - const parts = relativePath.split(windowsPath ? /[\\/]/ : "/").filter(Boolean); + // The server reads `~\` as home; the rest keeps the usual relative-path spelling. + const homePath = relativePath.startsWith("~\\") ? `~/${relativePath.slice(2)}` : relativePath; + const parts = homePath.split(windowsPath ? /[\\/]/ : "/").filter(Boolean); const root = relativePath.startsWith("\\\\") ? "\\\\" : relativePath.startsWith("/") ? "/" : ""; return [ ...(hostPath ? [] : [{ label: projectName, path: "", kind: "project" as const }]), diff --git a/packages/client-runtime/src/operations/projects.ts b/packages/client-runtime/src/operations/projects.ts index 92532a6a90579..c56fa973c4501 100644 --- a/packages/client-runtime/src/operations/projects.ts +++ b/packages/client-runtime/src/operations/projects.ts @@ -11,7 +11,7 @@ import type { } from "@t3tools/contracts"; import { SourceControlProviderKind } from "@t3tools/contracts"; import { cloneUrlRepositoryPath } from "@t3tools/shared/cloneUrl"; -import { isExplicitRelativePath, isHostPath, newProjectFolderName } from "@t3tools/shared/path"; +import { isAbsolutePath, isExplicitRelativePath, newProjectFolderName } from "@t3tools/shared/path"; import * as Arr from "effect/Array"; import * as Option from "effect/Option"; import * as Order from "effect/Order"; @@ -222,8 +222,13 @@ export function buildAddProjectRemoteSourceReadiness( export function getAddProjectInitialQuery(baseDirectory: string | null | undefined): string { const trimmed = baseDirectory?.trim() ?? ""; if (trimmed.length === 0) return "~/"; - // A bare relative setting such as `Desktop/dev` means a folder under home. - const isAnchored = trimmed === "~" || isHostPath(trimmed) || isExplicitRelativePath(trimmed); + // A bare relative setting such as `Desktop/dev` means a folder under home. The browser + // navigates `~/` but not `~\` home paths. + const isAnchored = + trimmed === "~" || + isAbsolutePath(trimmed) || + trimmed.startsWith("~/") || + isExplicitRelativePath(trimmed); return ensureBrowseDirectoryPath(isAnchored ? trimmed : `~/${trimmed}`); } diff --git a/packages/shared/src/path.test.ts b/packages/shared/src/path.test.ts index 514f92b8f54e0..9a9647c1bcd4b 100644 --- a/packages/shared/src/path.test.ts +++ b/packages/shared/src/path.test.ts @@ -59,6 +59,7 @@ describe("resolvePastedPath", () => { ["over a selection", "/Users/me/old", "'/Users/me/My Code'", "/Users/me/My Code"], ["after a prefilled folder", "~/", "~/'/Users/me/My Code'", "/Users/me/My Code"], ["plain, after a prefilled folder", "~/", "~//Users/me/code", "/Users/me/code"], + ["backslash home, after a folder", "~/", "~/~\\folder\\ child", "~/~\\folder\\ child"], ["after a Windows folder", "C:\\Users\\", 'C:\\Users\\"D:\\My Code"', "D:\\My Code"], ["a shell's quoted apostrophe", "", "'/Users/me/Bob'\\''s Work'", "/Users/me/Bob's Work"], ["after a clone destination", "~/code/repo", "~/code/repo'/a b'", "/a b"], diff --git a/packages/shared/src/path.ts b/packages/shared/src/path.ts index 45b49b200091c..e4351b97b2626 100644 --- a/packages/shared/src/path.ts +++ b/packages/shared/src/path.ts @@ -134,15 +134,20 @@ export function isAbsolutePath(value: string): boolean { return value.startsWith("/") || isWindowsAbsolutePath(value); } -/** Home-relative host paths are expanded by the destination server. */ +/** Both ~/ and ~\ home prefixes are expanded by the destination server. */ export function isHostPath(value: string): boolean { - return isAbsolutePath(value) || value.startsWith("~/"); + return isAbsolutePath(value) || value.startsWith("~/") || value.startsWith("~\\"); } // Finder and Explorer copy a path ready for a shell: `'/a b'`, `/a\'s\ b`, or `"C:\a b"`. const QUOTED_PATH_AT_END = /(?:'((?:[^']|'\\'')+)'|"([^"]+)")\s*$/; const SHELL_ESCAPE = /\\([\s'"\\()[\]{}<>|&;$`!*?#~^=])/g; +// Folder browsers only navigate `~/` home paths, so a pasted `~\` path is not a replacement. +function isPastedFolderPath(value: string): boolean { + return isAbsolutePath(value) || value.startsWith("~/"); +} + /** * What a folder box holds after a change. A full path pasted into it replaces the box, even after * the text already there, because `~/'/a b'` would create that nested folder. @@ -157,13 +162,13 @@ export function resolvePastedPath(previous: string, next: string): string { // Text before the quote that wasn't in the box is a search, not a folder to paste after. if (match && previous.startsWith(next.slice(0, match.index).trimEnd())) { const quoted = match[1]?.replaceAll("'\\''", "'") ?? match[2] ?? ""; - if (isHostPath(quoted)) return quoted; + if (isPastedFolderPath(quoted)) return quoted; } // Without a trailing separator, `/a` then `/a/b` is a longer path, not one pasted after a folder. const afterFolder = /[/\\]$/.test(previous) && next.startsWith(previous); const path = afterFolder ? next.slice(previous.length) : next; - if (!isHostPath(path)) return next; + if (!isPastedFolderPath(path)) return next; // `\` separates folders in Windows paths, so it only escapes in `/` and `~/` paths. return isWindowsAbsolutePath(path) ? path : path.replace(SHELL_ESCAPE, "$1"); } From e6265a926e0e61109611201605bf68d9f0a9d6fa Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 02:22:46 -0800 Subject: [PATCH 006/183] fix(web): thread jump hints re-check when a modifier changes while the hold is already met (#38545) --- apps/web/src/components/Sidebar.logic.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 8c9af1ed0508b..5cb2a044093a0 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -723,12 +723,15 @@ const threadJumpModifierHold = createModifierHoldStore(THREAD_JUMP_HINT_SHOW_DEL function subscribeToThreadJumpHintInputs(listener: () => void): () => void { const unsubscribeHold = threadJumpModifierHold.subscribe(listener); + // The snapshot reads the modifiers; the hold stays silent when it is true across a change. + const unsubscribeModifiers = shortcutModifierStore.subscribe(listener); const unsubscribeFocus = subscribeToTerminalFocusChanges(listener); const unsubscribeTerminals = useTerminalUiStateStore.subscribe(listener); const unsubscribeRightPanels = useRightPanelStore.subscribe(listener); const unsubscribeModelPicker = subscribeToModelPickerVisibility(listener); return () => { unsubscribeHold(); + unsubscribeModifiers(); unsubscribeFocus(); unsubscribeTerminals(); unsubscribeRightPanels(); From 3babab1497ddd82dfd90a0d53ad4d16ebae41063 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 02:31:50 -0800 Subject: [PATCH 007/183] fix(server): Changes base follows the remote a plain recorded base branch tracks (#38543) --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 40 ++++++++++++++++++++ apps/server/src/vcs/GitVcsDriverCore.ts | 4 ++ 2 files changed, 44 insertions(+) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index f4eb10810503e..bbd61b5010fde 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -4420,6 +4420,46 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("compares a plain recorded base with the remote that base branch tracks", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const fork = yield* makeTmpDir(); + const upstream = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(cwd, ["branch", "-M", "main"]); + yield* git(fork, ["init", "--bare"]); + yield* git(upstream, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", fork]); + yield* git(cwd, ["remote", "add", "upstream", upstream]); + yield* git(cwd, ["push", "origin", "main"]); + yield* writeTextFile(cwd, "upstream.txt", "unrelated upstream work\n"); + yield* git(cwd, ["add", "upstream.txt"]); + yield* git(cwd, ["commit", "-m", "upstream work"]); + yield* git(cwd, ["push", "-u", "upstream", "main"]); + yield* git(cwd, ["checkout", "-b", "feature/from-local-main"]); + yield* git(cwd, ["config", "branch.feature/from-local-main.t3-merge-base", "main"]); + yield* writeTextFile(cwd, "feature.txt", "intended branch change\n"); + yield* git(cwd, ["add", "feature.txt"]); + yield* git(cwd, ["commit", "-m", "feature work"]); + + const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); + assert.deepStrictEqual(status.branchChanges, { + baseRef: "upstream/main", + insertions: 1, + deletions: 0, + }); + assert.strictEqual(status.aheadCount, 1); + const preview = yield* driver.getReviewDiffPreview({ cwd }); + const changes = preview.sources.find((source) => source.kind === "branch-range")!; + assert.strictEqual(changes.baseRef, "upstream/main"); + assert.deepStrictEqual( + changes.files?.map((file) => file.path), + ["feature.txt"], + ); + }), + ); + it.effect("does not guess a Changes base for a branch renamed during the status read", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 0d6ef4631327d..25c7b4505e25f 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -2158,6 +2158,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return { baseRef: comparisonRef, comparisonRef }; } if (configuredBase !== null) return configuredBase; + if (configuredBaseBranch.length > 0 && configuredBaseBranch !== refName) { + const trackedBase = yield* resolveTrackedRemoteBaseRef(cwd, configuredBaseBranch); + if (trackedBase !== null) return trackedBase; + } const primaryRemoteName = yield* resolvePrimaryRemoteName(cwd).pipe( Effect.orElseSucceed(() => null), From 2d558c4dad93f59cd03b5c3c9b3372555a503c84 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:35:00 +0100 Subject: [PATCH 008/183] fix(web): the issue viewer shows why a refresh failed (#38537) Co-authored-by: Julius Marminge --- .../src/components/issue/IssueDetailPanel.tsx | 10 ++ apps/web/src/i18n/translations/de.json | 1 + apps/web/src/i18n/translations/en.json | 1 + apps/web/src/i18n/translations/es.json | 1 + apps/web/src/i18n/translations/fr.json | 1 + apps/web/src/i18n/translations/ja.json | 1 + apps/web/src/i18n/translations/ko.json | 1 + apps/web/src/i18n/translations/pt-BR.json | 1 + apps/web/src/i18n/translations/ru.json | 1 + apps/web/src/i18n/translations/sv.json | 1 + apps/web/src/i18n/translations/zh.json | 1 + .../issues-shows-failed-refresh.e2e.ts | 125 ++++++++++++++++++ 12 files changed, 145 insertions(+) create mode 100644 scripts/scenarios/issues-shows-failed-refresh.e2e.ts diff --git a/apps/web/src/components/issue/IssueDetailPanel.tsx b/apps/web/src/components/issue/IssueDetailPanel.tsx index d7d98e26e04fc..20a9d7aa93cf8 100644 --- a/apps/web/src/components/issue/IssueDetailPanel.tsx +++ b/apps/web/src/components/issue/IssueDetailPanel.tsx @@ -50,6 +50,7 @@ import { threadEnvironment } from "~/state/threads"; import { useAtomCommand } from "~/state/use-atom-command"; import { formatRelativeTimeLabel } from "~/timestampFormat"; +import { Alert, AlertDescription, AlertTitle } from "../ui/alert"; import { Button, InlineButton } from "../ui/button"; import { Input } from "../ui/input"; import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu"; @@ -667,6 +668,15 @@ export function IssueDetailPanel({ + {detailQuery.error !== null && !detailQuery.isPending ? ( +
+ + {gt("Could not refresh this issue")} + {detailQuery.error} + +
+ ) : null} + {editing === "title" ? (
+import type { IssueDetail, IssueRef } from "@t3tools/contracts"; +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "A failed issue refresh tells the reader what went wrong", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("demo"); + await browser.addInitScript(() => { + let rateLimited = false; + Object.assign(window, { + armIssueRefreshFailure: () => { + rateLimited = true; + }, + }); + const refresh = new Promise((resolve) => { + Object.assign(window, { releaseIssueRefresh: () => resolve() }); + }); + // The first issue read succeeds; the refresh then hits GitHub's rate limit. + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (data) { + const request: { _tag: string; id: string; tag: string; payload: IssueRef } | null = + typeof data === "string" ? JSON.parse(data) : null; + if (request?._tag !== "Request" || request.tag !== "issues.detail") + return send.call(this, data); + const reply = (exit: unknown) => + this.dispatchEvent( + new MessageEvent("message", { + data: JSON.stringify({ _tag: "Exit", requestId: request.id, exit }), + }), + ); + if (rateLimited) { + void refresh.then(() => + reply({ + _tag: "Failure", + cause: [ + { + _tag: "Fail", + error: { + _tag: "IssueOperationError", + operation: "detail", + detail: "GitHub API rate limit exceeded.", + reason: "rate-limited", + }, + }, + ], + }), + ); + return; + } + const { projectId, tracker, scope, key } = request.payload; + const detail: IssueDetail = { + projectId, + tracker, + scope, + key, + host: "github.com", + displayKey: "#42", + projectTitle: "demo", + title: "Issue before the rate limit", + body: "The details from the last successful read.", + url: "https://github.com/example/demo/issues/42", + author: null, + state: { category: "open", name: "Open" }, + createdAt: "2026-10-01T00:00:00.000Z", + updatedAt: "2026-10-01T00:00:00.000Z", + closedAt: null, + assignees: [], + labels: [], + commentCount: 0, + writable: false, + capabilities: { + create: false, + edit: false, + comment: false, + labels: false, + assignees: false, + reactions: false, + templates: false, + linkedPullRequests: false, + events: false, + search: true, + }, + viewerPermissions: { + setState: false, + comment: false, + edit: false, + labels: false, + assignees: false, + }, + states: [], + viewer: null, + comments: [], + commentsCursor: null, + events: [], + linkedPullRequests: [], + }; + queueMicrotask(() => reply({ _tag: "Success", value: detail })); + }; + }); + + await t3.open("/issues?selectedProjectId=demo&tracker=github&scope=example/demo&key=42"); + await screen.getByText("Issue before the rate limit", { exact: true }).waitFor(); + await browser.evaluate(() => { + (window as unknown as { armIssueRefreshFailure: () => void }).armIssueRefreshFailure(); + return null; + }); + await screen.getByRole("button", "Refresh issue", { exact: true }).tap(); + const refreshing = browser.locator('button[aria-label="Refresh issue"]:disabled'); + await refreshing.waitFor(); + await browser.evaluate(() => { + (window as unknown as { releaseIssueRefresh: () => void }).releaseIssueRefresh(); + return null; + }); + await refreshing.waitFor({ state: "hidden" }); + await app.screenshot("after-failed-refresh"); + await expect( + screen.getByText("GitHub API rate limit exceeded.", { exact: false }), + ).toBeVisible(); + await expect(screen.getByText("Issue before the rate limit", { exact: true })).toBeVisible(); + }, +); From 03822a83126be699c806e5e90f54c6e93cbbbabf Mon Sep 17 00:00:00 2001 From: Fuksss Date: Wed, 18 Nov 2026 11:47:20 +0100 Subject: [PATCH 009/183] =?UTF-8?q?fix(shared):=20Latin=20letters=20such?= =?UTF-8?q?=20as=20=C5=82,=20=C3=B8,=20=C3=BE=20and=20=C4=B1=20no=20longer?= =?UTF-8?q?=20split=20words=20in=20generated=20folder=20and=20branch=20nam?= =?UTF-8?q?es=20(#38540)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Julius Marminge --- packages/shared/src/git.test.ts | 3 +++ packages/shared/src/path.test.ts | 2 ++ packages/shared/src/path.ts | 39 ++++++++++++++++++++++++++++---- 3 files changed, 39 insertions(+), 5 deletions(-) diff --git a/packages/shared/src/git.test.ts b/packages/shared/src/git.test.ts index a11230586ba11..e454a989fb7b6 100644 --- a/packages/shared/src/git.test.ts +++ b/packages/shared/src/git.test.ts @@ -369,6 +369,9 @@ describe("sanitizeFeatureBranchName", () => { "feature/grosse-der-strasse-korrigieren", ); expect(sanitizeFeatureBranchName("fix/Đặt tên")).toBe("fix/dat-ten"); + expect(sanitizeFeatureBranchName("Napraw błąd w żółtym przycisku")).toBe( + "feature/napraw-blad-w-zoltym-przycisku", + ); }); }); diff --git a/packages/shared/src/path.test.ts b/packages/shared/src/path.test.ts index 9a9647c1bcd4b..4cb41a56752cc 100644 --- a/packages/shared/src/path.test.ts +++ b/packages/shared/src/path.test.ts @@ -31,6 +31,8 @@ describe("path helpers", () => { expect(newProjectFolderName(" Café & Crème! ")).toBe("cafe-creme"); expect(newProjectFolderName("Đặt tên dự án")).toBe("dat-ten-du-an"); expect(newProjectFolderName("Straßenbahn GROẞ")).toBe("strassenbahn-gross"); + expect(newProjectFolderName("Łódź sklep")).toBe("lodz-sklep"); + expect(newProjectFolderName("Øl på Þingvellir ı")).toBe("ol-pa-thingvellir-i"); expect(newProjectFolderName("../../etc")).toBe("etc"); expect(newProjectFolderName("🎱🎱")).toBe("project"); expect(newProjectFolderName(`${"a".repeat(63)} b`)).toBe("a".repeat(63)); diff --git a/packages/shared/src/path.ts b/packages/shared/src/path.ts index e4351b97b2626..de320595d704a 100644 --- a/packages/shared/src/path.ts +++ b/packages/shared/src/path.ts @@ -63,15 +63,44 @@ export function normalizeProjectPathForComparison(value: string): string { // Windows refuses these as file names, with or without an extension. const WINDOWS_RESERVED_NAME = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/; +// Latin letters NFKD leaves whole (ł, ø, ß) or splits with a spacing mark (Ŀ, ʼn). +const LATIN_FOLDS: Record = { + Ŀ: "L", + ŀ: "l", + ʼn: "'n", + Đ: "D", + đ: "d", + Ð: "D", + ð: "d", + ß: "ss", + ẞ: "SS", + Ł: "L", + ł: "l", + Ø: "O", + ø: "o", + Æ: "AE", + æ: "ae", + Œ: "OE", + œ: "oe", + Þ: "TH", + þ: "th", + Ħ: "H", + ħ: "h", + ı: "i", + ĸ: "q", + Ŋ: "N", + ŋ: "n", + Ŧ: "T", + ŧ: "t", +}; +const LATIN_FOLD_PATTERN = new RegExp(`[${Object.keys(LATIN_FOLDS).join("")}]`, "g"); + /** Folds accented Latin letters to ASCII ("tìm" -> "tim"); other scripts pass through. */ export function foldLatinDiacritics(text: string): string { return text + .replace(LATIN_FOLD_PATTERN, (letter) => LATIN_FOLDS[letter] ?? letter) .normalize("NFKD") - .replace(/[\u0300-\u036f]/g, "") - .replace(/đ/g, "d") // d-with-stroke and sharp s have no Unicode decomposition - .replace(/Đ/g, "D") - .replace(/ß/g, "ss") - .replace(/ẞ/g, "SS"); + .replace(/[\u0300-\u036f]/g, ""); } export function newProjectFolderName(name: string): string { From 0c6d0ee862cf84fe107e3085c03edc63485eee8b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 02:58:22 -0800 Subject: [PATCH 010/183] fix(server): steering a running turn carries MCP app model context (#38554) --- apps/server/src/mcpApps/McpAppModelContext.ts | 23 ++ .../Adapters/ClaudeAdapterV2.test.ts | 36 ++- .../Adapters/ClaudeAdapterV2.ts | 35 ++- .../Adapters/CodexAdapterV2.test.ts | 91 ++++++ .../Adapters/CodexAdapterV2.ts | 29 +- .../ProjectionControlReads.test.ts | 5 +- .../ProviderTurnControlService.test.ts | 291 ++++++++++++------ .../ProviderTurnControlService.ts | 8 + .../orchestration-v2/RunExecutionService.ts | 19 +- .../src/orchestration-v2/runtimeLayer.ts | 7 +- .../testkit/ProviderReplayHarness.ts | 7 +- .../src/server/ProviderAdapter.ts | 2 + 12 files changed, 422 insertions(+), 131 deletions(-) diff --git a/apps/server/src/mcpApps/McpAppModelContext.ts b/apps/server/src/mcpApps/McpAppModelContext.ts index 8dc16e67564a0..017e10ae3bf5b 100644 --- a/apps/server/src/mcpApps/McpAppModelContext.ts +++ b/apps/server/src/mcpApps/McpAppModelContext.ts @@ -38,6 +38,29 @@ export class McpAppModelContext extends Context.Service< } >()("t3/mcpApps/McpAppModelContext") {} +/** The thread's notes as a provider turn or steer sends them; a failed read sends none. */ +export const forProvider = Effect.fn("McpAppModelContext.forProvider")(function* ( + modelContext: McpAppModelContext["Service"], + threadId: ThreadId, +) { + const entries = yield* modelContext + .forThread(threadId) + .pipe( + Effect.catch((cause) => + Effect.logWarning("Failed to read MCP app model context.", { cause }).pipe( + Effect.as([] as ReadonlyArray), + ), + ), + ); + return entries.map((entry) => ({ + // The item id alone is unique and needs no escaping; server and + // tool names are free text that would break the tag Codex wraps + // the context in. + key: `mcp_app_${entry.itemId.replace(/[^\w.-]/g, "_")}`, + text: entry.text, + })); +}); + export const layer = Layer.effect( McpAppModelContext, Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 5e855f3431203..a0e186c4f7d45 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -6860,10 +6860,34 @@ describe("ClaudeAdapterV2 background wake turns", () => { }), appContext: [{ key: "mcp_app_item-1", text: note }], }); + return lastOffered(); + }); + const lastOffered = () => { const content = harness.offeredMessages.at(-1)?.message.content; return typeof content === "string" ? content : (content ?? []).map((block) => (block.type === "text" ? block.text : "")).join("\n"); + }; + const steer = Effect.fnUntraced(function* (ordinal: number, note: string) { + const attemptId = `mcp-app-context-${ordinal}`; + yield* harness.runtime.steerTurn({ + threadId: harness.threadId, + runId: RunId.make(`run-${attemptId}`), + providerThread: harness.providerThread, + providerTurnId: (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({ + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeTurnId: `turn:${attemptId}`, + }), + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make(`steer-${attemptId}-${harness.offeredMessages.length}`), + text: "What did the app report now?", + attachments: [], + }, + appContext: [{ key: "mcp_app_item-1", text: note }], + }); + return lastOffered(); }); const finishTurn = Effect.fnUntraced(function* (ordinal: number) { yield* harness.offerAndWait( @@ -6886,8 +6910,14 @@ describe("ClaudeAdapterV2 background wake turns", () => { yield* finishTurn(1); // Already in Claude's history: resending it every turn would only grow the context. assert.notInclude(yield* runTurn(2, "Created Jira issue PROJ-42"), "PROJ-42"); + // regression: #38541 a note the app changes mid-turn rides on the next steer, once. + assert.notInclude(yield* steer(2, "Created Jira issue PROJ-42"), "PROJ-42"); + assert.include(yield* steer(2, "Created Jira issue PROJ-44"), "PROJ-44"); + assert.notInclude(yield* steer(2, "Created Jira issue PROJ-44"), "PROJ-44"); yield* finishTurn(2); - assert.include(yield* runTurn(3, "Created Jira issue PROJ-43"), "PROJ-43"); + assert.notInclude(yield* runTurn(3, "Created Jira issue PROJ-44"), "PROJ-44"); + yield* finishTurn(3); + assert.include(yield* runTurn(4, "Created Jira issue PROJ-43"), "PROJ-43"); yield* harness.offerAndWait( claudeSdkFrame({ type: "system", @@ -6897,9 +6927,9 @@ describe("ClaudeAdapterV2 background wake turns", () => { session_id: WAKE_NATIVE_SESSION, }), ); - yield* finishTurn(3); + yield* finishTurn(4); // Compaction summarizes the note away, so the next turn carries it again. - assert.include(yield* runTurn(4, "Created Jira issue PROJ-43"), "PROJ-43"); + assert.include(yield* runTurn(5, "Created Jira issue PROJ-43"), "PROJ-43"); }).pipe( Effect.provide( Layer.mergeAll( diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 6d6cc1fee8c95..2974c1a81ab2b 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -13787,7 +13787,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( existing.openedPermissionMode === currentTurn.queryPolicy.permissionMode) ? steerSelection : undefined; - const userMessage = yield* makeClaudeUserMessageWithAttachments({ + const steerMessage = yield* makeClaudeUserMessageWithAttachments({ text: applyClaudePromptEffortPrefix( turnInput.message.text, ( @@ -13806,6 +13806,27 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), Effect.provideService(Path.Path, path), ); + // Notes this turn's prompt or an earlier steer already carried are not sent again. + const appContext = turnInput.appContext ?? []; + const seenAppContext = + currentTurn.appContextOffered ?? deliveredAppContext.get(existing.nativeThreadId); + const userMessage = withClaudeAppContext( + steerMessage, + appContext.filter((entry) => seenAppContext?.get(entry.key) !== entry.text), + pdfReservation, + ); + // `offer` may call this twice; a second call must not restore notes compaction cleared. + let offerCommitted = false; + const commitOffer = () => { + if (offerCommitted) return; + offerCommitted = true; + pdfReservation.commit(); + if (userMessage !== steerMessage) { + currentTurn.appContextOffered = new Map( + appContext.map((entry) => [entry.key, entry.text]), + ); + } + }; yield* backgroundForegroundSubagents(existing, backgroundDeadline); if (liveSteerSelection !== undefined) { yield* applySelectionLive(existing, liveSteerSelection); @@ -13839,16 +13860,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }); yield* emitSteerStatus(currentTurn, messageId, "pending"); yield* Effect.uninterruptibleMask((restore) => - restore( - existing.query.offer(userMessage, () => { - pdfReservation.commit(); - }), - ).pipe( - Effect.tap(() => - Effect.sync(() => { - pdfReservation.commit(); - }), - ), + restore(existing.query.offer(userMessage, commitOffer)).pipe( + Effect.tap(() => Effect.sync(commitOffer)), ), ).pipe( Effect.onError(() => diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index a7448dbb09740..fd5f89b86a0c1 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -1915,6 +1915,97 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + // regression: #38541 an MCP app note that changes mid-turn reaches the next steer, once. + it.effect("steers carry MCP app notes Codex has not been sent", () => + Effect.gen(function* () { + const nativeThreadId = "steer-app-context-thread"; + const nativeTurnId = "steer-app-context-turn"; + const note = "Pressed: blue"; + const steerFrame = (id: number, input: ReadonlyArray) => + [ + { + type: "expect_outbound", + label: "turn/steer", + frame: { + id, + method: "turn/steer", + params: { + threadId: nativeThreadId, + expectedTurnId: nativeTurnId, + input: input.map((text) => ({ type: "text", text })), + }, + }, + }, + { type: "emit_inbound", frame: { id, result: { turnId: nativeTurnId } } }, + ] as const; + const harness = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ + scenario: "steer-app-context", + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Work." }), + ...steerFrame(4, [note, "What did the app report?"]), + ...steerFrame(5, ["And now?"]), + { + type: "emit_inbound", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), + }, + }, + }, + ], + }), + ); + const turnInput = makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("steer-app-context-attempt"), + text: "Work.", + }); + yield* harness.runtime.startTurn(turnInput); + yield* harness.until(() => + harness.events.some( + (event) => + event.type === "provider_turn.updated" && + event.providerTurn.nativeTurnRef?.nativeId === nativeTurnId, + ), + ); + const providerTurnId = harness.events.flatMap((event) => + event.type === "provider_turn.updated" ? [event.providerTurn.id] : [], + )[0]; + assert.isDefined(providerTurnId); + if (providerTurnId === undefined) return; + const appContext = [{ key: "mcp_app_item-1", text: "Pressed: blue" }]; + yield* harness.runtime.steerTurn({ + ...turnInput, + providerTurnId, + appContext, + message: { ...turnInput.message, text: "What did the app report?" }, + }); + yield* harness.runtime.steerTurn({ + ...turnInput, + providerTurnId, + appContext, + message: { ...turnInput.message, text: "And now?" }, + }); + yield* harness.firstTerminal; + assert.equal(harness.terminalEvents()[0]?.status, "completed"); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("a speed change with no message updates Codex's next-turn settings", () => Effect.gen(function* () { const nativeThreadId = "picker-tier-thread"; diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 8c138e4a0ffd0..fdd7c22e6ecca 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -8150,11 +8150,38 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( yield* applyServiceTier(threadId, turnInput.modelSelection); const codexInput = yield* toCodexInput(turnInput); + // turn/steer takes no additionalContext, so notes the thread has not been sent go + // as quoted user input, the way restoreAdditionalContext resends them. + const sentContext = (yield* Ref.get(additionalContextByThread)).get(threadId); + const unsentNotes = (turnInput.appContext ?? []).filter( + (entry) => sentContext?.[entry.key]?.value !== entry.text, + ); yield* client.request("turn/steer", { expectedTurnId: activeTurn.nativeTurnId, - input: codexInput, + input: [ + ...unsentNotes.map((entry) => ({ + type: "text" as const, + text: `${entry.text}`, + })), + ...codexInput, + ], threadId, }); + if (unsentNotes.length > 0) { + yield* Ref.update(additionalContextByThread, (current) => { + const next = new Map(current); + next.set(threadId, { + ...current.get(threadId), + ...Object.fromEntries( + unsentNotes.map((entry) => [ + entry.key, + { kind: "untrusted" as const, value: entry.text }, + ]), + ), + }); + return next; + }); + } }, (effect, turnInput) => effect.pipe( diff --git a/apps/server/src/orchestration-v2/ProjectionControlReads.test.ts b/apps/server/src/orchestration-v2/ProjectionControlReads.test.ts index 988fc7b494fb3..effdf81357d50 100644 --- a/apps/server/src/orchestration-v2/ProjectionControlReads.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionControlReads.test.ts @@ -24,6 +24,7 @@ import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import * as SqlClient from "effect/sql/SqlClient"; +import * as McpAppModelContext from "../mcpApps/McpAppModelContext.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as EventSink from "./EventSink.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; @@ -393,7 +394,9 @@ it.effect.each(storageCases)( }).pipe( Effect.provide( Layer.merge(ProviderTurnControlService.layer, RuntimeRequestService.layer).pipe( - Layer.provide(Layer.merge(layerSessions, layerEvents)), + Layer.provide( + Layer.mergeAll(layerSessions, layerEvents, McpAppModelContext.layerEmpty), + ), ), ), ); diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts index 48eacd6bbd18f..3b5beb4850e3c 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts @@ -1,8 +1,10 @@ import { assert, it } from "@effect/vitest"; import { + MessageId, type ModelSelection, NodeId, type OrchestrationV2ProviderThread, + type OrchestrationV2Run, type OrchestrationV2ThreadProjection, ProjectId, ProviderDriverKind, @@ -23,6 +25,7 @@ import * as Ref from "effect/Ref"; import * as Stream from "effect/Stream"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import * as McpAppModelContext from "../mcpApps/McpAppModelContext.ts"; import * as EventSink from "./EventSink.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; @@ -123,6 +126,102 @@ function makeProjection(input: { }; } +function layerProjectionStore( + getProviderControlContext: ProjectionStore.ProjectionStoreV2["Service"]["getProviderControlContext"], +) { + return Layer.succeed( + ProjectionStore.ProjectionStoreV2, + ProjectionStore.ProjectionStoreV2.of({ + apply: () => Effect.void, + getLimitRecoveryCandidates: () => Effect.die("unused getLimitRecoveryCandidates"), + getLimitRecoveryWakeAt: () => Effect.die("unused getLimitRecoveryWakeAt"), + getOpenRemoteDelegatedTasks: Effect.die("unused getOpenRemoteDelegatedTasks"), + getAgentAwarenessSnapshot: () => Effect.die("unused awareness snapshot"), + getShellSnapshot: () => Effect.die("unused getShellSnapshot"), + listActiveSubagentThreadIds: () => Effect.die("unused listActiveSubagentThreadIds"), + countThreads: () => Effect.die("unused countThreads"), + listActiveShellIndex: () => Effect.die("unused listActiveShellIndex"), + listActiveThreads: () => Effect.die("unused listActiveThreads"), + listOlderSettledThreads: () => Effect.die("unused listOlderSettledThreads"), + readShellSnapshot: () => Effect.die("unused readShellSnapshot"), + getThreadShell: () => Effect.die("unused getThreadShell"), + getThreadTitles: () => Effect.die("unused getThreadTitles"), + getThreadLinkMetadata: () => Effect.die("unused getThreadLinkMetadata"), + findGuestShareThreadId: () => Effect.die("unused findGuestShareThreadId"), + getThread: () => Effect.die("unused getThread"), + findThread: () => Effect.die("unused findThread"), + getSettlementCandidates: () => Effect.die("unused getSettlementCandidates"), + getThreadsWithPullRequests: () => Effect.die("unused getThreadsWithPullRequests"), + getThreadWorktreePaths: () => Effect.die("unused getThreadWorktreePaths"), + getThreadProjection: () => Effect.die("control effects must not load transcript"), + getTurnStartContext: () => Effect.die("unused"), + getTurnStartHistory: () => Effect.die("unused"), + getRuntimeRecoveryProjection: () => Effect.die("unused getRuntimeRecoveryProjection"), + getPlan: () => Effect.die("unused"), + hasUnpairedRunInterruptRequest: () => Effect.die("unused interrupt read"), + hasRunInterruptRequest: () => Effect.die("unused stop read"), + getRunProviderRecords: () => Effect.die("unused run provider read"), + getThreadAttachmentIds: () => Effect.die("Unused attachment lookup"), + searchThread: () => Effect.die("unused"), + searchThreadStream: () => Stream.empty, + getThreadHistoryPage: () => Effect.die("unused"), + getTimelinePage: () => Effect.die("Unused timeline read"), + getMessageCount: () => Effect.die("unused message count"), + getTranscriptByteFloor: () => Effect.die("unused transcript byte floor"), + hasPendingDelegatedCompletion: () => Effect.die("unused hasPendingDelegatedCompletion"), + getSubagentCount: () => Effect.die("unused subagent count"), + getRunCount: () => Effect.die("unused run count"), + listAppOwnedChildThreadIds: () => Effect.die("unused listAppOwnedChildThreadIds"), + getNextTurnItemOrdinal: () => Effect.die("unused ordinal read"), + getTurnItem: () => Effect.die("unused turn item read"), + getMessagesById: () => Effect.die("unused getMessagesById"), + getThreadRecords: () => Effect.die("unused record read"), + getRuntimeRequest: () => Effect.die("unused getRuntimeRequest"), + getRunningTurnContext: () => Effect.die("unused getRunningTurnContext"), + getThreadProviderContext: () => Effect.die("unused getThreadProviderContext"), + getRuntimeResponseContext: () => Effect.die("unused getRuntimeResponseContext"), + getPendingNativeUserInputs: () => Effect.die("unused getPendingNativeUserInputs"), + getProviderControlContext, + getCheckpointContext: () => Effect.die("not used"), + getCheckpointRollbackContext: () => Effect.die("unused rollback context"), + getCheckpointCaptureContext: () => Effect.die("not used"), + getRunMessage: () => Effect.die("not used"), + getRun: () => Effect.die("not used"), + isNodeStored: () => Effect.die("not used"), + canStartQueuedRun: () => Effect.die("not used"), + getHeldQueuedRuns: () => Effect.die("not used"), + getRecoveryThreadIds: () => Effect.die("unused getRecoveryThreadIds"), + getUnreadableThreadIds: () => Effect.die("unused getUnreadableThreadIds"), + getThreadSnapshot: () => Effect.die("unused getThreadSnapshot"), + getThreadSnapshotWindow: () => Effect.die("unused getThreadSnapshotWindow"), + getPullRequestSnapshot: () => Effect.die("unused getPullRequestSnapshot"), + }), + ); +} + +function layerSessions( + liveSessionId: ProviderSessionId, + runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime, +) { + return Layer.succeed( + ProviderSessionManager.ProviderSessionManagerV2, + ProviderSessionManager.ProviderSessionManagerV2.of({ + shutdown: Effect.void, + open: () => Effect.die("unused open"), + get: (providerSessionId) => + Effect.succeed(providerSessionId === liveSessionId ? Option.some(runtime) : Option.none()), + isLive: (providerSessionId) => Effect.succeed(providerSessionId === liveSessionId), + close: () => Effect.void, + closeInstance: () => Effect.void, + release: () => Effect.void, + detach: () => Effect.void, + otherWorkingThreads: () => Effect.succeed([]), + releaseUnlessBusy: () => Effect.succeed(true), + subscribePromptSuggestion: () => Stream.empty, + }), + ); +} + it.effect( "interrupts the historical session only for the exact committed restart replacement", () => @@ -206,112 +305,27 @@ it.effect( rollbackThread: () => Effect.die("unused rollbackThread"), forkThread: () => Effect.die("unused forkThread"), }; - const layerProjection = Layer.succeed( - ProjectionStore.ProjectionStoreV2, - ProjectionStore.ProjectionStoreV2.of({ - apply: () => Effect.void, - getLimitRecoveryCandidates: () => Effect.die("unused getLimitRecoveryCandidates"), - getLimitRecoveryWakeAt: () => Effect.die("unused getLimitRecoveryWakeAt"), - getOpenRemoteDelegatedTasks: Effect.die("unused getOpenRemoteDelegatedTasks"), - getAgentAwarenessSnapshot: () => Effect.die("unused awareness snapshot"), - getShellSnapshot: () => Effect.die("unused getShellSnapshot"), - listActiveSubagentThreadIds: () => Effect.die("unused listActiveSubagentThreadIds"), - countThreads: () => Effect.die("unused countThreads"), - listActiveShellIndex: () => Effect.die("unused listActiveShellIndex"), - listActiveThreads: () => Effect.die("unused listActiveThreads"), - listOlderSettledThreads: () => Effect.die("unused listOlderSettledThreads"), - readShellSnapshot: () => Effect.die("unused readShellSnapshot"), - getThreadShell: () => Effect.die("unused getThreadShell"), - getThreadTitles: () => Effect.die("unused getThreadTitles"), - getThreadLinkMetadata: () => Effect.die("unused getThreadLinkMetadata"), - findGuestShareThreadId: () => Effect.die("unused findGuestShareThreadId"), - getThread: () => Ref.get(projection).pipe(Effect.map((state) => state.thread)), - findThread: () => Effect.die("unused findThread"), - getSettlementCandidates: () => Effect.die("unused getSettlementCandidates"), - getThreadsWithPullRequests: () => Effect.die("unused getThreadsWithPullRequests"), - getThreadWorktreePaths: () => Effect.die("unused getThreadWorktreePaths"), - getThreadProjection: () => Effect.die("control effects must not load transcript"), - getTurnStartContext: () => Effect.die("unused"), - getTurnStartHistory: () => Effect.die("unused"), - getRuntimeRecoveryProjection: () => Effect.die("unused getRuntimeRecoveryProjection"), - getPlan: () => Effect.die("unused"), - hasUnpairedRunInterruptRequest: () => Effect.die("unused interrupt read"), - hasRunInterruptRequest: () => Effect.die("unused stop read"), - getRunProviderRecords: () => Effect.die("unused run provider read"), - getThreadAttachmentIds: () => Effect.die("Unused attachment lookup"), - searchThread: () => Effect.die("unused"), - searchThreadStream: () => Stream.empty, - getThreadHistoryPage: () => Effect.die("unused"), - getTimelinePage: () => Effect.die("Unused timeline read"), - getMessageCount: () => Effect.die("unused message count"), - getTranscriptByteFloor: () => Effect.die("unused transcript byte floor"), - hasPendingDelegatedCompletion: () => Effect.die("unused hasPendingDelegatedCompletion"), - getSubagentCount: () => Effect.die("unused subagent count"), - getRunCount: () => Effect.die("unused run count"), - listAppOwnedChildThreadIds: () => Effect.die("unused listAppOwnedChildThreadIds"), - getNextTurnItemOrdinal: () => Effect.die("unused ordinal read"), - getTurnItem: () => Effect.die("unused turn item read"), - getMessagesById: () => Effect.die("unused getMessagesById"), - getThreadRecords: () => Effect.die("unused record read"), - getRuntimeRequest: () => Effect.die("unused getRuntimeRequest"), - getRunningTurnContext: () => Effect.die("unused getRunningTurnContext"), - getThreadProviderContext: () => Effect.die("unused getThreadProviderContext"), - getRuntimeResponseContext: () => Effect.die("unused getRuntimeResponseContext"), - getPendingNativeUserInputs: () => Effect.die("unused getPendingNativeUserInputs"), - getProviderControlContext: (_threadId, target) => - Ref.get(projection).pipe( - Effect.map((current) => ({ - providerThread: current.providerThreads.find( - (thread) => thread.id === target.providerThreadId, - ), - providerTurn: current.providerTurns.find( - (turn) => turn.id === target.providerTurnId, - ), - attempt: current.attempts.find((attempt) => attempt.id === target.attemptId), - message: undefined, - run: undefined, - })), - ), - getCheckpointContext: () => Effect.die("not used"), - getCheckpointRollbackContext: () => Effect.die("unused rollback context"), - getCheckpointCaptureContext: () => Effect.die("not used"), - getRunMessage: () => Effect.die("not used"), - getRun: () => Effect.die("not used"), - isNodeStored: () => Effect.die("not used"), - canStartQueuedRun: () => Effect.die("not used"), - getHeldQueuedRuns: () => Effect.die("not used"), - getRecoveryThreadIds: () => Effect.die("unused getRecoveryThreadIds"), - getUnreadableThreadIds: () => Effect.die("unused getUnreadableThreadIds"), - getThreadSnapshot: () => Effect.die("unused getThreadSnapshot"), - getThreadSnapshotWindow: () => Effect.die("unused getThreadSnapshotWindow"), - getPullRequestSnapshot: () => Effect.die("unused getPullRequestSnapshot"), - }), - ); - const layerSessionManager = Layer.succeed( - ProviderSessionManager.ProviderSessionManagerV2, - ProviderSessionManager.ProviderSessionManagerV2.of({ - shutdown: Effect.void, - open: () => Effect.die("unused open"), - get: (providerSessionId) => - Effect.succeed( - providerSessionId === oldSessionId ? Option.some(runtime) : Option.none(), + const layerProjection = layerProjectionStore((_threadId, target) => + Ref.get(projection).pipe( + Effect.map((current) => ({ + providerThread: current.providerThreads.find( + (thread) => thread.id === target.providerThreadId, ), - isLive: (providerSessionId) => Effect.succeed(providerSessionId === oldSessionId), - close: () => Effect.void, - closeInstance: () => Effect.void, - release: () => Effect.void, - detach: () => Effect.void, - otherWorkingThreads: () => Effect.succeed([]), - releaseUnlessBusy: () => Effect.succeed(true), - subscribePromptSuggestion: () => Stream.empty, - }), + providerTurn: current.providerTurns.find((turn) => turn.id === target.providerTurnId), + attempt: current.attempts.find((attempt) => attempt.id === target.attemptId), + message: undefined, + run: undefined, + })), + ), ); + const layerSessionManager = layerSessions(oldSessionId, runtime); const layerControl = ProviderTurnControlService.layer.pipe( Layer.provide( Layer.mergeAll( layerProjection, layerSessionManager, Layer.mock(EventSink.EventSinkV2)({}), + McpAppModelContext.layerEmpty, ), ), ); @@ -362,3 +376,84 @@ it.effect( assert.equal(interrupted?.nativeThreadRef?.nativeId, "native-thread:restart-session"); }), ); + +it.effect("steers a running turn with the thread's MCP app model context", () => + Effect.gen(function* () { + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread:steer-app-context"); + const sessionId = ProviderSessionId.make("provider-session:steer-app-context"); + const providerTurnId = ProviderTurnId.make("provider-turn:steer-app-context"); + const attemptId = RunAttemptId.make("run-attempt:steer-app-context"); + const providerThread = { + id: ProviderThreadId.make("provider-thread:steer-app-context"), + driver, + providerInstanceId, + providerSessionId: sessionId, + } as OrchestrationV2ProviderThread; + const projection = makeProjection({ now, threadId, providerThread, providerTurnId, attemptId }); + const steered: Array = []; + const runtime = { + instanceId: providerInstanceId, + driver, + providerSessionId: sessionId, + steerTurn: (input: ProviderAdapter.ProviderAdapterV2SteerInput) => + Effect.sync(() => void steered.push(input)), + } as unknown as ProviderAdapter.ProviderAdapterV2SessionRuntime; + const layerControl = ProviderTurnControlService.layer.pipe( + Layer.provide( + Layer.mergeAll( + layerProjectionStore(() => + Effect.succeed({ + providerThread, + providerTurn: projection.providerTurns[0], + attempt: projection.attempts[0], + message: { + id: MessageId.make("message:steer-app-context"), + text: "What did the app report?", + attachments: [], + createdBy: "user", + creationSource: "web", + } as unknown as NonNullable< + ProjectionStore.ProjectionProviderControlContext["message"] + >, + run: { + id: RunId.make("run:steer-app-context"), + status: "running", + activeAttemptId: attemptId, + } as OrchestrationV2Run, + }), + ), + layerSessions(sessionId, runtime), + Layer.mock(EventSink.EventSinkV2)({}), + Layer.mock(McpAppModelContext.McpAppModelContext)({ + forThread: () => + Effect.succeed([ + { + itemId: "turn-item:call-1", + server: "tools", + tool: "picker", + text: "Pressed: blue", + }, + ]), + }), + ), + ), + ); + + yield* Effect.gen(function* () { + const control = yield* ProviderTurnControlService.ProviderTurnControlServiceV2; + yield* control.steer({ + threadId, + providerSessionId: sessionId, + providerThreadId: providerThread.id, + providerTurnId, + messageId: MessageId.make("message:steer-app-context"), + }); + }).pipe(Effect.provide(layerControl)); + + assert.equal(steered.length, 1); + assert.deepEqual("appContext" in steered[0]! ? steered[0].appContext : undefined, [ + { key: "mcp_app_turn-item_call-1", text: "Pressed: blue" }, + ]); + }), +); diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts index f9727734bf870..25df164788e76 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts @@ -18,6 +18,7 @@ import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as McpAppModelContext from "../mcpApps/McpAppModelContext.ts"; import * as EventSink from "./EventSink.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; import * as ProviderSessionManager from "./ProviderSessionManager.ts"; @@ -113,6 +114,7 @@ export const layer: Layer.Layer< ProviderTurnControlServiceV2, never, | EventSink.EventSinkV2 + | McpAppModelContext.McpAppModelContext | ProjectionStore.ProjectionStoreV2 | ProviderSessionManager.ProviderSessionManagerV2 > = Layer.effect( @@ -121,6 +123,7 @@ export const layer: Layer.Layer< const eventSink = yield* EventSink.EventSinkV2; const projections = yield* ProjectionStore.ProjectionStoreV2; const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2; + const mcpAppModelContext = yield* McpAppModelContext.McpAppModelContext; const load = Effect.fn("ProviderTurnControlService.load")(function* (input: { readonly threadId: ThreadId; @@ -444,6 +447,10 @@ export const layer: Layer.Layer< cause: "The persisted steering message or target run is missing.", }); } + const appContext = yield* McpAppModelContext.forProvider( + mcpAppModelContext, + input.threadId, + ); yield* loaded.session.value .steerTurn({ threadId: input.threadId, @@ -453,6 +460,7 @@ export const layer: Layer.Layer< ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }), + ...(appContext.length === 0 ? {} : { appContext }), message: { messageId: message.id, text: projectComposerContextForProvider({ diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index 113e0866b1402..f1d21f4a6bad5 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -2200,21 +2200,10 @@ export const layer: Layer.Layer< }), ); yield* touchMcpCredential; - const appContext = (yield* mcpAppModelContext - .forThread(input.run.threadId) - .pipe( - Effect.catch((cause) => - Effect.logWarning("Failed to read MCP app model context.", { cause }).pipe( - Effect.as([]), - ), - ), - )).map((entry) => ({ - // The item id alone is unique and needs no escaping; server and - // tool names are free text that would break the tag Codex wraps - // the context in. - key: `mcp_app_${entry.itemId.replace(/[^\w.-]/g, "_")}`, - text: entry.text, - })); + const appContext = yield* McpAppModelContext.forProvider( + mcpAppModelContext, + input.run.threadId, + ); const turnInput = { appThread: input.appThread, threadId: input.run.threadId, diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index 4f834535cc2d2..da06fd60e9000 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -184,7 +184,12 @@ const layerProviderTurnStartServiceProvided = ProviderTurnStartService.layer.pip const layerProviderTurnControlServiceProvided = ProviderTurnControlService.layer.pipe( Layer.provide( - Layer.mergeAll(layerEventSink, ProjectionStore.layer, layerProviderSessionManagerProvided), + Layer.mergeAll( + layerEventSink, + McpAppModelContext.layer, + ProjectionStore.layer, + layerProviderSessionManagerProvided, + ), ), ); const layerRuntimeRequestServiceProvided = RuntimeRequestService.layer.pipe( diff --git a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts index 0ba9137e45dbc..1e69421513a8b 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts @@ -454,7 +454,12 @@ export function layerWithRegistry( ); const layerProviderTurnControlServiceProvided = ProviderTurnControlService.layer.pipe( Layer.provide( - Layer.mergeAll(layerEventSinkProvided, layerStores, layerProviderSessionManagerProvided), + Layer.mergeAll( + layerEventSinkProvided, + McpAppModelContext.layerEmpty, + layerStores, + layerProviderSessionManagerProvided, + ), ), ); const layerRuntimeRequestServiceProvided = RuntimeRequestService.layer.pipe( diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index ff879ef0f723f..8fc0749c51859 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -587,6 +587,8 @@ export interface ProviderAdapterV2SteerInput { readonly message: ProviderAdapterV2TurnMessage; /** The selection sent with the message when it differs from the running turn's. */ readonly modelSelection?: ModelSelection; + /** The thread's MCP app notes; the adapter sends those the agent has not seen yet. */ + readonly appContext?: ProviderAdapterV2TurnInput["appContext"]; } export interface ProviderAdapterV2InterruptInput { From 3088d266654acbce33ea42a894b48f76aea264bd Mon Sep 17 00:00:00 2001 From: Tristan Knight Date: Wed, 18 Nov 2026 11:03:25 +0000 Subject: [PATCH 011/183] fix(web): thread details rows no longer show stray scrollbars on touch screens (#38546) Co-authored-by: Julius Marminge --- apps/web/src/components/chat/ThreadDetailsControl.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/chat/ThreadDetailsControl.tsx b/apps/web/src/components/chat/ThreadDetailsControl.tsx index 78f22ea5bec98..b2f1ce0cfe12e 100644 --- a/apps/web/src/components/chat/ThreadDetailsControl.tsx +++ b/apps/web/src/components/chat/ThreadDetailsControl.tsx @@ -53,8 +53,9 @@ export function ThreadDetailsControl({ props: mergeProps<"button">( { type: render ? undefined : "button", + // The touch target stays centered within the panel's 32px rows; spilling past them makes scrolling lists overflow. className: cn( - "relative inline-flex shrink-0 cursor-pointer items-center whitespace-nowrap border outline-none transition-[box-shadow,scale] [&:not([aria-haspopup]):not(:disabled):not([aria-disabled=true])]:will-change-[scale] [&:active:not([aria-haspopup])]:scale-[0.97] focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background pointer-coarse:after:absolute pointer-coarse:after:size-full pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 disabled:pointer-events-none disabled:opacity-64 aria-disabled:cursor-not-allowed aria-disabled:opacity-64 [&_svg]:shrink-0", + "relative inline-flex shrink-0 cursor-pointer items-center whitespace-nowrap border outline-none transition-[box-shadow,scale] [&:not([aria-haspopup]):not(:disabled):not([aria-disabled=true])]:will-change-[scale] [&:active:not([aria-haspopup])]:scale-[0.97] focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background pointer-coarse:after:absolute pointer-coarse:after:top-1/2 pointer-coarse:after:left-1/2 pointer-coarse:after:size-full pointer-coarse:after:min-h-8 pointer-coarse:after:min-w-8 pointer-coarse:after:-translate-x-1/2 pointer-coarse:after:-translate-y-1/2 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 disabled:pointer-events-none disabled:opacity-64 aria-disabled:cursor-not-allowed aria-disabled:opacity-64 [&_svg]:shrink-0", parts[part], multiline && "h-auto min-h-8 py-1.5 disabled:opacity-100 sm:h-auto", tone === "muted" && "text-muted-foreground hover:text-foreground/80", From 373ec12be606753c298a3a70c89fc035c210ddae Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 03:07:43 -0800 Subject: [PATCH 012/183] fix(web): very wide or tall lone images in user messages show the whole image (#38558) --- apps/web/src/components/chat/TimelineUserMessageRow.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/src/components/chat/TimelineUserMessageRow.tsx b/apps/web/src/components/chat/TimelineUserMessageRow.tsx index d62c03fe68239..6fc9ccc790e62 100644 --- a/apps/web/src/components/chat/TimelineUserMessageRow.tsx +++ b/apps/web/src/components/chat/TimelineUserMessageRow.tsx @@ -803,7 +803,7 @@ function UserTimelineRow({ row }: { row: Extract From 5552f0aa74b1cdc0606b86374d4312c42e3b117a Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:12:42 +0100 Subject: [PATCH 013/183] fix(mobile): a retried document upload keeps its tile and shows progress (#38553) Co-authored-by: Julius Marminge --- .../src/features/threads/ThreadComposer.tsx | 4 +- apps/mobile/src/lib/composerImages.test.ts | 23 +++++-- apps/mobile/src/lib/composerImages.ts | 22 ++++--- .../src/state/attachmentUploads.test.ts | 24 +++++-- .../src/state/attachmentUploads.ts | 63 ++++++++++++------- 5 files changed, 91 insertions(+), 45 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index 19ca8397aa64e..1d4f06c4f5c4b 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -323,9 +323,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps const uploadStates = useAtomValue(composerAttachmentUploadsAtom); const stripAttachments = composerStripAttachments( draftAttachments, - (attachment) => - uploadStates[composerAttachmentUploadKey(props.environmentId, attachment.id)]?.status === - "failed", + (attachment) => uploadStates[composerAttachmentUploadKey(props.environmentId, attachment.id)], ); const attachmentsUploading = props.connectionState === "connected" && diff --git a/apps/mobile/src/lib/composerImages.test.ts b/apps/mobile/src/lib/composerImages.test.ts index 367c6cf3896eb..d7830b8ed3466 100644 --- a/apps/mobile/src/lib/composerImages.test.ts +++ b/apps/mobile/src/lib/composerImages.test.ts @@ -3,6 +3,7 @@ import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, } from "@t3tools/contracts"; +import type { ComposerAttachmentUploadState } from "./composerAttachmentUploadQueue"; const files = new Map< string, @@ -333,15 +334,25 @@ describe("composerStripAttachments", () => { it("keeps media beside a document rather than dropping the whole strip", async () => { const { composerStripAttachments } = await import("./composerImages"); expect( - composerStripAttachments([doc, image, video] as never, () => false).map((a) => a.id), + composerStripAttachments([doc, image, video] as never, () => ({ + status: "uploading", + progress: 0.5, + })).map((a) => a.id), ).toEqual(["img-1", "vid-1"]); }); - it("shows a document whose upload failed, so it can be retried", async () => { + it("shows a document whose upload failed until its retry finishes", async () => { const { composerStripAttachments } = await import("./composerImages"); - expect( - composerStripAttachments([doc, image] as never, (a) => a.id === "doc-1").map((a) => a.id), - ).toEqual(["doc-1", "img-1"]); + const strip = (upload: ComposerAttachmentUploadState) => + composerStripAttachments([doc, image] as never, (a) => + a.id === "doc-1" ? upload : undefined, + ).map((a) => a.id); + expect(strip({ status: "failed", reason: "Service unavailable" })).toEqual(["doc-1", "img-1"]); + expect(strip({ status: "uploading", progress: 0.4, retrying: true })).toEqual([ + "doc-1", + "img-1", + ]); + expect(strip({ status: "ready" })).toEqual(["img-1"]); }); it("keeps oversized document-picked images visible while sending them as files", async () => { @@ -356,7 +367,7 @@ describe("composerStripAttachments", () => { sizeBytes: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1, }; - expect(composerStripAttachments([oversizedImage], () => false)).toEqual([oversizedImage]); + expect(composerStripAttachments([oversizedImage], () => undefined)).toEqual([oversizedImage]); expect(isComposerImageAttachment(oversizedImage)).toBe(false); }); }); diff --git a/apps/mobile/src/lib/composerImages.ts b/apps/mobile/src/lib/composerImages.ts index 3ca64eef41fe8..18546bb63bdc4 100644 --- a/apps/mobile/src/lib/composerImages.ts +++ b/apps/mobile/src/lib/composerImages.ts @@ -12,6 +12,7 @@ import { type PastedTextAttachmentSource, type UploadChatImageAttachment, } from "@t3tools/contracts"; +import type { AttachmentUploadStatus } from "@t3tools/client-runtime/state/attachment-uploads"; import type { DocumentPickerResult } from "expo-document-picker"; import { msg } from "gt-react-native"; import { m } from "../i18n/messages"; @@ -82,19 +83,26 @@ export type DraftComposerAttachment = DraftComposerImageAttachment | DraftCompos /** * Non-media attachments require chip references; missing references mean lost draft files. - * A chip cannot retry an upload, so a document whose upload failed joins the strip. + * A chip cannot retry an upload or show its progress, so a document whose upload failed joins + * the strip until its retry finishes. */ export function composerStripAttachments( attachments: ReadonlyArray, - uploadFailed: (attachment: DraftComposerAttachment) => boolean, + uploadStatus: (attachment: DraftComposerAttachment) => AttachmentUploadStatus | undefined, ): ReadonlyArray { - return attachments.filter( - (attachment) => + return attachments.filter((attachment) => { + if ( attachment.type === "image" || imageMimeType(attachment) !== null || - videoMimeType(attachment) !== null || - uploadFailed(attachment), - ); + videoMimeType(attachment) !== null + ) { + return true; + } + const upload = uploadStatus(attachment); + return ( + upload?.status === "failed" || (upload?.status === "uploading" && upload.retrying === true) + ); + }); } /** Promote legacy document-picked images only when their originals fit the image contract. */ diff --git a/packages/client-runtime/src/state/attachmentUploads.test.ts b/packages/client-runtime/src/state/attachmentUploads.test.ts index 53df58ba9bdb3..0c6d31666065c 100644 --- a/packages/client-runtime/src/state/attachmentUploads.test.ts +++ b/packages/client-runtime/src/state/attachmentUploads.test.ts @@ -210,8 +210,16 @@ describe("attachment upload registry", () => { reason: "Server unavailable", }); expect(progress).toEqual([0, 0.1, 1]); - upload.mockImplementationOnce(async () => "uploaded"); + upload.mockImplementationOnce(async (_request, _signal, report) => { + report(0.5); + return "uploaded"; + }); queue.retry(uploadKey(environmentId, "file")); + expect(states[uploadKey(environmentId, "file")]).toEqual({ + status: "uploading", + progress: 0.5, + retrying: true, + }); await queue.settled(); expect(states[uploadKey(environmentId, "file")]).toEqual({ status: "ready" }); queue.dispose(); @@ -251,18 +259,24 @@ describe("attachment upload registry", () => { ); it.effect("restarts a failed upload when a send joins it instead of rejoining the failure", () => Effect.gen(function* () { + const replacement = Promise.withResolvers(); const upload = vi .fn() .mockRejectedValueOnce(new Error("Server unavailable")) - .mockResolvedValue("uploaded-2"); + .mockImplementationOnce(() => replacement.promise); const queue = createQueue({ upload, onChange: () => {} }); const local = request("photo"); - queue.sync([local]); + const key = uploadKey(environmentId, local.attachment.id); + const release = queue.hold(local); yield* Effect.promise(() => queue.settled()); - expect(queue.status(uploadKey(environmentId, "photo"))?.status).toBe("failed"); + expect(queue.status(key)?.status).toBe("failed"); - expect(yield* queue.upload(local)).toBe("uploaded-2"); + const sent = yield* Effect.forkChild(queue.upload(local), { startImmediately: true }); + expect(queue.status(key)).toEqual({ status: "uploading", progress: 0, retrying: true }); + replacement.resolve("uploaded-2"); + expect(yield* Fiber.join(sent)).toBe("uploaded-2"); expect(upload).toHaveBeenCalledTimes(2); + release(); queue.dispose(); }), ); diff --git a/packages/client-runtime/src/state/attachmentUploads.ts b/packages/client-runtime/src/state/attachmentUploads.ts index 9571186aabf3c..42134c4d91d7d 100644 --- a/packages/client-runtime/src/state/attachmentUploads.ts +++ b/packages/client-runtime/src/state/attachmentUploads.ts @@ -29,17 +29,23 @@ export function attachmentUploadError(cause: unknown): AttachmentUploadError { } export type AttachmentUploadStatus = - | { readonly status: "uploading"; readonly progress: number } + /** `retrying` marks an upload started again after it failed. */ + | { readonly status: "uploading"; readonly progress: number; readonly retrying?: true } | { readonly status: "ready" } | { readonly status: "failed"; readonly reason: string }; -/** Equal by key; the request rides along for the upload. */ +const uploading = (progress: number, retry: boolean): AttachmentUploadStatus => + retry ? { status: "uploading", progress, retrying: true } : { status: "uploading", progress }; + +/** Equal by id; the request and retry flag only matter when starting a transfer. */ class UploadKey implements Equal.Equal { readonly id: string; readonly request: Request | null; - constructor(id: string, request: Request | null) { + readonly retry: boolean; + constructor(id: string, request: Request | null, retry = false) { this.id = id; this.request = request; + this.retry = retry; } [Equal.symbol](that: unknown): boolean { return that instanceof UploadKey && that.id === this.id; @@ -78,7 +84,8 @@ export function createAttachmentUploadRegistry(options: { previous === status || (previous?.status === "uploading" && status?.status === "uploading" && - previous.progress === status.progress) + previous.progress === status.progress && + previous.retrying === status.retrying) ) return; const next = { ...statuses }; @@ -109,13 +116,14 @@ export function createAttachmentUploadRegistry(options: { const request = key.request!; return Effect.suspend(() => { if (statuses[key.id]?.status !== "uploading") { - setOwnStatus(owner, key.id, { status: "uploading", progress: 0 }); + setOwnStatus(owner, key.id, uploading(0, key.retry)); } return options.upload(request, (progress) => - setOwnStatus(owner, key.id, { - status: "uploading", - progress: Math.floor(Math.max(0, Math.min(1, progress)) * 20) / 20, - }), + setOwnStatus( + owner, + key.id, + uploading(Math.floor(Math.max(0, Math.min(1, progress)) * 20) / 20, key.retry), + ), ); }).pipe( Semaphore.withPermits(permitsFor(options.environmentId(request)), 1), @@ -134,7 +142,7 @@ export function createAttachmentUploadRegistry(options: { lookup: Effect.fn("AttachmentUploads.lookup")(function* (key: UploadKey) { const owner = {}; owners.set(key.id, owner); - setStatus(key.id, { status: "uploading", progress: 0 }); + setStatus(key.id, uploading(0, key.retry)); yield* Effect.addFinalizer(() => Effect.sync(() => { setOwnStatus(owner, key.id, undefined); @@ -154,14 +162,11 @@ export function createAttachmentUploadRegistry(options: { }), ), ); - const keyOf = (request: Request) => new UploadKey(options.key(request), request); - let disposed = false; - /** Keeps the request's upload running until the returned release is called. */ - function hold(request: Request): () => void { + function holdUpload(key: UploadKey): () => void { if (disposed) return () => {}; const holder = Scope.makeUnsafe(); - Effect.runSync(Scope.provide(holder)(RcMap.get(uploads, keyOf(request)))); + Effect.runSync(Scope.provide(holder)(RcMap.get(uploads, key))); let released = false; return () => { if (released) return; @@ -172,8 +177,7 @@ export function createAttachmentUploadRegistry(options: { const synced = new Map void>(); let requested: ReadonlyArray = []; - /** Holds exactly these uploads; anything no longer requested and held nowhere else stops. */ - function sync(requests: ReadonlyArray) { + function syncUploads(requests: ReadonlyArray, retryKey?: string) { if (disposed) return; requested = requests; const keys = new Map(requests.map((request) => [options.key(request), request])); @@ -183,7 +187,7 @@ export function createAttachmentUploadRegistry(options: { release(); } for (const [id, request] of keys) { - if (!synced.has(id)) synced.set(id, hold(request)); + if (!synced.has(id)) synced.set(id, holdUpload(new UploadKey(id, request, id === retryKey))); } } @@ -192,17 +196,24 @@ export function createAttachmentUploadRegistry(options: { Effect.runSync(RcMap.invalidate(uploads, new UploadKey(key, null))); } - /** Drops the key's upload and starts it again for whatever `sync` holds. */ + /** Drops the key's upload and replaces it if `sync` holds it. */ function restart(key: string) { + const retry = statuses[key]?.status === "failed"; invalidate(key); synced.get(key)?.(); synced.delete(key); - sync(requested); + syncUploads(requested, retry ? key : undefined); } return { - hold, - sync, + /** Keeps the request's upload running until the returned release is called. */ + hold(request: Request): () => void { + return holdUpload(new UploadKey(options.key(request), request)); + }, + /** Holds exactly these uploads; anything no longer requested and held nowhere else stops. */ + sync(requests: ReadonlyArray) { + syncUploads(requests); + }, invalidate, restart, /** @@ -213,8 +224,12 @@ export function createAttachmentUploadRegistry(options: { return Effect.suspend(() => { if (disposed) return Effect.fail(attachmentUploadError(new Error("Upload cancelled."))); const key = options.key(request); - if (statuses[key]?.status === "failed") restart(key); - return RcMap.get(uploads, keyOf(request)).pipe(Effect.flatMap(Fiber.join), Effect.scoped); + const retry = statuses[key]?.status === "failed"; + if (retry) restart(key); + return RcMap.get(uploads, new UploadKey(key, request, retry)).pipe( + Effect.flatMap(Fiber.join), + Effect.scoped, + ); }); }, /** Starts a failed upload that `sync` holds again. */ From 6a29d58d147522f85112c0c7149f2f9032cd955f Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:19:37 +0100 Subject: [PATCH 014/183] fix(client-runtime): closed issue searches no longer build up in memory (#38493) Co-authored-by: Grok 4.7 Co-authored-by: Julius Marminge --- .../client-runtime/src/state/issues.test.ts | 82 +++++++++++++++++++ packages/client-runtime/src/state/issues.ts | 17 ++-- 2 files changed, 91 insertions(+), 8 deletions(-) diff --git a/packages/client-runtime/src/state/issues.test.ts b/packages/client-runtime/src/state/issues.test.ts index 53fb953c0acb3..7c52da1c5004b 100644 --- a/packages/client-runtime/src/state/issues.test.ts +++ b/packages/client-runtime/src/state/issues.test.ts @@ -1,3 +1,7 @@ +// @effect-diagnostics nodeBuiltinImport:off - The retention test forces garbage collection in Node. +import * as NodeTimersPromises from "node:timers/promises"; +import * as NodeV8 from "node:v8"; +import * as NodeVM from "node:vm"; import { EnvironmentId, IssueTrackerKind, @@ -5,6 +9,7 @@ import { type IssueComment, type IssueCommentsPage, type IssueListEntry, + type IssueListResult, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; @@ -13,8 +18,10 @@ import { describe, expect, it } from "vite-plus/test"; import { createIssueCommentPager, createMergedIssueCandidatesAtoms, + createMergedIssueListAtoms, issueEntryKey, mergeIssueListPage, + type IssueListTarget, } from "./issues.ts"; function entry(overrides: Partial & { key: string }): IssueListEntry { @@ -169,3 +176,78 @@ describe("createMergedIssueCandidatesAtoms", () => { } }); }); + +describe("createMergedIssueListAtoms", () => { + const answer: IssueListResult = { + viewers: {}, + trackers: [], + entries: [], + errors: [], + nextCursors: {}, + }; + + it("refreshes the open listings of the environment written to", () => { + const reads = new Map(); + const lists = new Map>>(); + const listings = createMergedIssueListAtoms((target) => { + const key = `${target.environmentId}:${target.input.query}`; + const existing = lists.get(key); + if (existing !== undefined) return existing; + const atom = Atom.make(() => { + reads.set(key, (reads.get(key) ?? 0) + 1); + return AsyncResult.success(answer); + }); + lists.set(key, atom); + return atom; + }, String); + const registry = AtomRegistry.make(); + const written = EnvironmentId.make("written"); + const other = EnvironmentId.make("other"); + try { + const listing = listings.atom([ + { environmentId: written, input: { state: "open", query: "bug" } }, + { environmentId: other, input: { state: "open", query: "bug" } }, + ]); + registry.mount(listing); + + listings.refreshEnvironment(registry, written); + registry.get(listing); + expect(Object.fromEntries(reads)).toEqual({ "written:bug": 2, "other:bug": 1 }); + } finally { + registry.dispose(); + } + }); + + it("releases historical search targets when the list closes", async () => { + NodeV8.setFlagsFromString("--expose-gc"); + const gc = NodeVM.runInNewContext("gc") as () => void; + const listings = createMergedIssueListAtoms( + () => Atom.make(AsyncResult.success(answer)), + String, + ); + const registry = AtomRegistry.make(); + const environmentId = EnvironmentId.make("environment"); + try { + const historical = ["search-one", "search-two", "search-three"].map((query) => { + const targets = [ + { environmentId, input: { state: "open", query } }, + ] satisfies IssueListTarget[]; + const close = registry.mount(listings.atom(targets)); + close(); + return new WeakRef(targets); + }); + // Let the registry remove all three unmounted queries and the WeakRefs leave their creation job. + // oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- a zero-delay macrotask boundary, not a wait for time + await NodeTimersPromises.setImmediate(); + gc(); + + listings.refreshEnvironment(registry, environmentId); + expect( + historical.filter((target) => target.deref() !== undefined).length, + "historical issue searches retained after closing", + ).toBe(0); + } finally { + registry.dispose(); + } + }); +}); diff --git a/packages/client-runtime/src/state/issues.ts b/packages/client-runtime/src/state/issues.ts index 3175602dfaa42..237610fe281d4 100644 --- a/packages/client-runtime/src/state/issues.ts +++ b/packages/client-runtime/src/state/issues.ts @@ -300,21 +300,22 @@ export function createMergedIssueListAtoms( ) => { for (const target of targets) registry.refresh(list(target)); }; - // Every listing asked for, so a write made elsewhere can refresh the ones still shown. - const asked = new Map>(); + // The targets behind each listing atom, so a write made elsewhere can refresh the ones still + // shown. Weak, so a closed search goes with its atom once the registry drops it. + const targetsOf = new WeakMap, ReadonlyArray>(); return { atom: (targets: ReadonlyArray) => { if (targets.length === 0) return empty; - const key = JSON.stringify(targets); - asked.set(key, targets); - return family(key); + const atom = family(JSON.stringify(targets)); + targetsOf.set(atom, targets); + return atom; }, refresh, /** Refreshes each listing of `environmentId` that something still reads. */ refreshEnvironment: (registry: AtomRegistry.AtomRegistry, environmentId: EnvironmentId) => { - const live = new Set(registry.getNodes().keys()); - for (const [key, targets] of asked) { - if (!live.has(family(key))) continue; + for (const node of registry.getNodes().values()) { + const targets = targetsOf.get(node.atom); + if (targets === undefined) continue; refresh( registry, targets.filter((target) => target.environmentId === environmentId), From 018ca6d58ec968479e287c2769bb9b2b8c44c29f Mon Sep 17 00:00:00 2001 From: amtiyo <134780061+amtiYo@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:41:20 +0100 Subject: [PATCH 015/183] fix(acp-registry): each Mistral Vibe model shows its own thinking levels (#38556) Co-authored-by: Julius Marminge --- .../src/server/driver.test.ts | 80 +++++++++++++++++++ .../provider-acp-registry/src/server/probe.ts | 7 +- .../provider-acp/src/server/sessionConfig.ts | 10 ++- 3 files changed, 93 insertions(+), 4 deletions(-) diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 2f9352bbdbfe0..684eb21d7456b 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -416,6 +416,86 @@ describe("acpRegistrySnapshotReadiness", () => { ]); }); + it("keeps each Mistral Vibe model's own thinking levels", () => { + const provider = buildCheckedAcpRegistrySnapshot({ + ...identity, + settings: decodeSettings({ agentId: "mistral-vibe" }), + checkedAt: "2026-11-18T10:00:00.000Z", + inspection: { + status: "ready", + agentId: "mistral-vibe", + version: "3.1.1", + distribution: "binary", + }, + probe: { + probe: { + instanceId: identity.instanceId, + ready: true, + icon: null, + authMethods: [], + models: [], + currentModelId: null, + configOptions: [], + sessionManagement: noSessionManagement, + }, + slashCommands: [], + skills: [], + }, + }); + // Mistral Vibe 3.1.1 sends its levels under category "thinking", for the session's model only. + const vibeSession = (model: string, levels: ReadonlyArray) => + normalizeAcpRegistryLiveConfiguration([ + { + id: "model", + name: "Model", + category: "model", + type: "select", + currentValue: model, + options: ["mistral-large-4-0-3", "mistral-medium-3.5"].map((value) => ({ + value, + name: value, + })), + }, + { + id: "thinking", + name: "Thinking", + category: "thinking", + type: "select", + currentValue: "high", + options: levels.map((value) => ({ value, name: value })), + }, + ]); + const thinking = (levels: ReadonlyArray) => ({ + id: "thinking", + label: "Thinking", + type: "select", + options: levels.map((id) => ({ id, label: id })), + currentValue: "high", + role: "reasoning", + }); + const descriptors = (snapshot: typeof provider) => + snapshot.models.map((model) => [model.slug, model.capabilities?.optionDescriptors ?? []]); + + const onLarge = applyAcpRegistryLiveConfiguration( + provider, + vibeSession("mistral-large-4-0-3", ["low", "medium", "high"]), + [], + ); + expect(descriptors(onLarge)).toEqual([ + ["mistral-large-4-0-3", [thinking(["low", "medium", "high"])]], + ["mistral-medium-3.5", []], + ]); + const onMedium = applyAcpRegistryLiveConfiguration( + onLarge, + vibeSession("mistral-medium-3.5", ["off", "high"]), + [], + ); + expect(descriptors(onMedium)).toEqual([ + ["mistral-large-4-0-3", [thinking(["low", "medium", "high"])]], + ["mistral-medium-3.5", [thinking(["off", "high"])]], + ]); + }); + it("projects discovery without claiming authentication when no login methods are advertised", () => { const snapshot = buildCheckedAcpRegistrySnapshot({ ...identity, diff --git a/packages/provider-acp-registry/src/server/probe.ts b/packages/provider-acp-registry/src/server/probe.ts index e1689a405a8bc..c012f38d195df 100644 --- a/packages/provider-acp-registry/src/server/probe.ts +++ b/packages/provider-acp-registry/src/server/probe.ts @@ -33,6 +33,7 @@ import { import { acpProviderOptionDescriptors, flattenSelectChoices, + isAcpThoughtLevelOption, } from "@t3tools/provider-acp/server/sessionConfig"; import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts"; import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; @@ -234,7 +235,9 @@ export function normalizeAcpRegistryLiveConfiguration( currentModelId === undefined ? null : (boundedOpaqueValue(currentModelId, MAX_ID_LENGTH) ?? null); - const effortOption = configOptions.find((option) => option.category === "thought_level"); + const effortOption = + configOptions.find((option) => option.category === "thought_level") ?? + configOptions.find(isAcpThoughtLevelOption); const models = normalizeModels(candidates, boundedCurrentModelId).map((model) => { const reasoningEffort = advertisedReasoningEffort( effortOption, @@ -245,7 +248,7 @@ export function normalizeAcpRegistryLiveConfiguration( const descriptors = acpProviderOptionDescriptors({ configOptions, modeState }); const modelOptionIds = new Set( configOptions - .filter((option) => option.category === "thought_level" || option.category === "model_config") + .filter((option) => isAcpThoughtLevelOption(option) || option.category === "model_config") .map((option) => option.id), ); return { diff --git a/packages/provider-acp/src/server/sessionConfig.ts b/packages/provider-acp/src/server/sessionConfig.ts index b79fdaebe245d..af8ee0eec0f33 100644 --- a/packages/provider-acp/src/server/sessionConfig.ts +++ b/packages/provider-acp/src/server/sessionConfig.ts @@ -22,6 +22,11 @@ const boundedOpaqueValue = (value: string, maximumLength: number): string | unde const choiceId = (value: string): string | undefined => value === "" ? ACP_EMPTY_OPTION_VALUE : boundedOpaqueValue(value, MAX_TEXT_LENGTH); +/** Mistral Vibe 3.1 sends its reasoning level under `thinking`, a category ACP reserves but never defined. */ +export const isAcpThoughtLevelOption = (option: EffectAcpSchema.SessionConfigOption): boolean => + option.category === "thought_level" || + (option.category === "thinking" && option.type === "select"); + export function flattenSelectChoices( options: EffectAcpSchema.SessionConfigSelectOptions, ): ReadonlyArray { @@ -91,7 +96,8 @@ export function acpProviderOptionDescriptors(input: { continue; } if (option.category === "mode") hasModeCategory = true; - if (option.category === "thought_level") { + const isThoughtLevel = isAcpThoughtLevelOption(option); + if (isThoughtLevel) { mirroredModeChoiceSets.push(new Set(choices.map((choice) => choice.id))); } const currentValue = choiceId(option.currentValue); @@ -102,7 +108,7 @@ export function acpProviderOptionDescriptors(input: { ...(currentValue && choices.some((choice) => choice.id === currentValue) ? { currentValue } : {}), - ...(option.category === "thought_level" ? { role: "reasoning" as const } : {}), + ...(isThoughtLevel ? { role: "reasoning" as const } : {}), }); if (descriptors.length === MAX_OPTION_DESCRIPTORS) return descriptors; } From 52f0f8afb8cde93389479b6bd8dd8d44a17946dd Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 03:46:54 -0800 Subject: [PATCH 016/183] fix(server): Cursor history on large accounts loads in pieces and keeps what was read (#38567) --- apps/server/src/usage/UsageService.test.ts | 74 +++++++++++++- .../src/server/CursorUsageAccounts.ts | 96 ++++++++++++------- .../src/server/accountCache.test.ts | 7 +- .../src/server/accountCache.ts | 52 +++++++--- 4 files changed, 171 insertions(+), 58 deletions(-) diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts index 9a7f7ab82c8f1..0a9b9611eea06 100644 --- a/apps/server/src/usage/UsageService.test.ts +++ b/apps/server/src/usage/UsageService.test.ts @@ -1967,7 +1967,7 @@ describe("UsageService", () => { const sources = yield* Fiber.join(wider); assert.deepStrictEqual(cursor.state.calls, [ { sinceMs: input.retentionCutoffMs, untilMs: CURSOR_NOW }, - { sinceMs: 0, untilMs: CURSOR_NOW }, + { sinceMs: 0, untilMs: input.retentionCutoffMs }, ]); assert.strictEqual(sources[0]?.status, "ok"); assert.deepStrictEqual( @@ -2077,6 +2077,78 @@ describe("UsageService", () => { }), ); + it.effect("loads Cursor history that cannot be read in one request within the deadline", () => + Effect.gen(function* () { + const { settings, home } = yield* setup; + yield* TestClock.setTime(CURSOR_NOW); + const cursor = makeFakeCursor(); + cursor.state.events = [ + { timestampMs: CURSOR_NOW - 40 * HOUR_MS, outputTokens: 7 }, + { timestampMs: CURSOR_NOW - 3 * HOUR_MS, outputTokens: 5 }, + ]; + // A large account: a window wider than half a day has too many pages for the read deadlines. + const read: CursorAccountReader.CursorAccountReader["Service"]["read"] = ( + credential, + sinceMs, + untilMs, + ) => + untilMs - sinceMs > 12 * HOUR_MS + ? Effect.succeed({ + accountKey: cursor.state.accountKey, + records: [], + missing: false, + error: "Cursor account usage could not be read.", + }) + : cursor.read(credential, sinceMs, untilMs); + yield* Effect.gen(function* () { + const service = yield* makeWithCursor(read); + let summary = yield* service.readSummary({ ...WINDOW, awaitRefresh: true }); + for (let attempt = 1; attempt < 10 && totalOutputTokens(summary) < 12; attempt++) { + yield* TestClock.adjust("2 minutes"); + summary = yield* service.readSummary({ ...WINDOW, awaitRefresh: true }); + } + assert.strictEqual(totalOutputTokens(summary), 12); + + // Failed reads during an outage narrow the span; it widens back once reads work again. + cursor.state.error = "Cursor account usage could not be read."; + for (let attempt = 0; attempt < 20; attempt++) { + yield* TestClock.adjust("2 minutes"); + yield* service.readSummary({ ...WINDOW, awaitRefresh: true }); + } + cursor.state.error = null; + yield* TestClock.adjust("10 hours"); + cursor.state.events.push({ timestampMs: CURSOR_NOW + 10 * HOUR_MS, outputTokens: 3 }); + const callsBeforeRecovery = cursor.state.calls.length; + summary = yield* service.readSummary({ ...WINDOW, awaitRefresh: true }); + assert.strictEqual(totalOutputTokens(summary), 15); + assert.isBelow(cursor.state.calls.length - callsBeforeRecovery, 20); + }).pipe( + Effect.provide( + layerService({ + prefix: "usage-service-cursor-large-account", + home, + settings, + platform: "darwin", + environment: {}, + secretStore: { + get: () => + Effect.succeedSome( + new TextEncoder().encode( + encodeUnknownJsonString({ + version: 1, + backendUrl: "https://api2.cursor.sh", + apiKey: "large-account-key", + createdAtMs: 0, + }), + ), + ), + }, + }), + ), + ); + }), + ); + it.effect("keeps a new Cursor key's refresh visible beside a failing key", () => Effect.gen(function* () { const { settings, home } = yield* setup; diff --git a/packages/provider-cursor/src/server/CursorUsageAccounts.ts b/packages/provider-cursor/src/server/CursorUsageAccounts.ts index 088a59ca285ed..7bea5ce83290a 100644 --- a/packages/provider-cursor/src/server/CursorUsageAccounts.ts +++ b/packages/provider-cursor/src/server/CursorUsageAccounts.ts @@ -18,6 +18,7 @@ import * as Semaphore from "effect/Semaphore"; import { CURSOR_ACCOUNT_CACHE_FILE_NAME, CURSOR_ACCOUNT_TTL_MS, + CURSOR_MIN_FETCH_SPAN_MS, cursorFetchRange, decodeCursorAccountCaches, encodeCursorAccountCaches, @@ -64,6 +65,8 @@ const make = Effect.gen(function* () { /** Failed refreshes share the cache TTL to prevent repeated requests; null means no login. */ const failures = new Map(); const refreshes = new Map>(); + /** Widest range the next read asks for, narrowed after failures until the cache is complete. */ + const fetchSpans = new Map(); const ensureLoaded = yield* Effect.cached( fileSystem.readFileString(cachePath).pipe( @@ -111,45 +114,64 @@ const make = Effect.gen(function* () { retentionStartMs: number, ) { const nowMs = yield* Clock.currentTimeMillis; - const fetchMissing = (cache: CursorAccountCache | undefined) => { - const range = cursorFetchRange(cache, retentionStartMs, nowMs); - return accountReader - .read(credential, range.sinceMs, range.untilMs) - .pipe(Effect.map((result) => ({ range, result }))); - }; - let base = caches.get(credentialKey); - let fetched = yield* fetchMissing(base); - if ( - base !== undefined && - fetched.result.accountKey !== null && - fetched.result.accountKey !== base.accountKey - ) { - caches.delete(credentialKey); - cacheDirty = true; - base = undefined; - fetched = yield* fetchMissing(base); - } - const { range, result } = fetched; - if (result.missing || result.error !== null || result.accountKey === null) { - failures.set(credentialKey, { - atMs: nowMs, - error: result.missing || result.error !== null ? result.error : CURSOR_ACCOUNT_READ_ERROR, - }); + let checkedAccount = false; + let span = fetchSpans.get(credentialKey) ?? Number.POSITIVE_INFINITY; + // Widen after each success so a span narrowed by earlier failures recovers in a few reads. + let widening = true; + let widened = false; + for (;;) { + const base = caches.get(credentialKey); + const range = cursorFetchRange(base, retentionStartMs, nowMs, span); + const result = yield* accountReader.read(credential, range.sinceMs, range.untilMs); + if ( + !checkedAccount && + base !== undefined && + result.accountKey !== null && + result.accountKey !== base.accountKey + ) { + caches.delete(credentialKey); + cacheDirty = true; + checkedAccount = true; + continue; + } + checkedAccount = true; + if (result.missing || result.error !== null || result.accountKey === null) { + // A large account's full history can outlast the read deadlines; try a narrower range. + span = Math.max(CURSOR_MIN_FETCH_SPAN_MS, (range.untilMs - range.sinceMs) / 2); + fetchSpans.set(credentialKey, span); + if (widened) { + // The span before widening just worked: keep going with it instead of failing. + widened = false; + widening = false; + continue; + } + failures.set(credentialKey, { + atMs: nowMs, + error: result.missing || result.error !== null ? result.error : CURSOR_ACCOUNT_READ_ERROR, + }); + yield* schedulePersist; + return; + } + const merged = mergeCursorFetch( + base, + result.accountKey, + range, + result.records, + nowMs, + retentionStartMs, + ); + caches.set(credentialKey, merged.cache); + failures.delete(credentialKey); + if (merged.changed) cacheDirty = true; yield* schedulePersist; - return; + if (merged.cache.sinceMs <= retentionStartMs && merged.cache.untilMs >= nowMs) break; + widened = widening && Number.isFinite(span); + if (widened) { + span *= 2; + fetchSpans.set(credentialKey, span); + } } - const merged = mergeCursorFetch( - base, - result.accountKey, - range, - result.records, - nowMs, - retentionStartMs, - ); - caches.set(credentialKey, merged.cache); - failures.delete(credentialKey); - if (merged.changed) cacheDirty = true; - yield* schedulePersist; + fetchSpans.delete(credentialKey); }, refreshLock.withPermit); const startRefresh = ( diff --git a/packages/provider-cursor/src/server/accountCache.test.ts b/packages/provider-cursor/src/server/accountCache.test.ts index f14e68efe19be..af509912c1c1a 100644 --- a/packages/provider-cursor/src/server/accountCache.test.ts +++ b/packages/provider-cursor/src/server/accountCache.test.ts @@ -23,7 +23,7 @@ const record = (timestampMs: number): UsageRecord => ({ }); describe("cursorAccountCache", () => { - it("refetches everything once the cache no longer reaches the retention start", () => { + it("reads only the history the cache is missing", () => { const cache = { accountKey: "a", sinceMs: 0, @@ -35,10 +35,7 @@ describe("cursorAccountCache", () => { const narrow = { ...cache, sinceMs: DAY_MS }; assert.isFalse(isCursorCacheFresh(narrow, 10 * DAY_MS, 0)); const widenedRange = cursorFetchRange(narrow, 0, 10 * DAY_MS); - assert.deepStrictEqual(widenedRange, { - sinceMs: 0, - untilMs: 10 * DAY_MS, - }); + assert.deepStrictEqual(widenedRange, { sinceMs: 0, untilMs: DAY_MS }); const widened = mergeCursorFetch(narrow, "a", widenedRange, cache.records, 10 * DAY_MS, 0); assert.isTrue(isCursorCacheFresh(widened.cache, 10 * DAY_MS, 0)); assert.deepStrictEqual(cursorFetchRange(widened.cache, 0, 11 * DAY_MS), { diff --git a/packages/provider-cursor/src/server/accountCache.ts b/packages/provider-cursor/src/server/accountCache.ts index 3d36083626bef..da65677781add 100644 --- a/packages/provider-cursor/src/server/accountCache.ts +++ b/packages/provider-cursor/src/server/accountCache.ts @@ -34,16 +34,31 @@ export function isCursorCacheFresh( ); } +/** Narrowest read a refresh falls back to after failed reads of wider ranges. */ +export const CURSOR_MIN_FETCH_SPAN_MS = 60 * 1000; + +/** + * The next range to read, at most `maxSpanMs` wide unless it only tops up a complete cache: + * the newest history first, then older history down to the retention start. + */ export function cursorFetchRange( cache: CursorAccountCache | undefined, retentionStartMs: number, nowMs: number, + maxSpanMs = Number.POSITIVE_INFINITY, ): CursorFetchRange { - return cache === undefined || - cache.sinceMs > retentionStartMs || - cache.untilMs - REFETCH_OVERLAP_MS < retentionStartMs - ? { sinceMs: retentionStartMs, untilMs: nowMs } - : { sinceMs: cache.untilMs - REFETCH_OVERLAP_MS, untilMs: nowMs }; + if (cache === undefined || cache.untilMs - REFETCH_OVERLAP_MS < retentionStartMs) { + return { sinceMs: Math.max(retentionStartMs, nowMs - maxSpanMs), untilMs: nowMs }; + } + if (cache.untilMs < nowMs || cache.sinceMs <= retentionStartMs) { + // Overlap at most half the span so a narrow read still moves forward. + const sinceMs = cache.untilMs - Math.min(REFETCH_OVERLAP_MS, maxSpanMs / 2); + return { sinceMs, untilMs: Math.min(nowMs, sinceMs + maxSpanMs) }; + } + return { + sinceMs: Math.max(retentionStartMs, cache.sinceMs - maxSpanMs), + untilMs: cache.sinceMs, + }; } export function mergeCursorFetch( @@ -56,7 +71,12 @@ export function mergeCursorFetch( ) { const inRange = (record: UsageRecord) => record.timestampMs >= range.sinceMs && record.timestampMs <= range.untilMs; - const previous = cache?.records ?? []; + const base = + cache !== undefined && range.sinceMs <= cache.untilMs && range.untilMs >= cache.sinceMs + ? cache + : undefined; + const older = base !== undefined && range.untilMs <= base.sinceMs; + const previous = base?.records ?? []; const added = fetched.filter(inRange); const replacedKeys = new Set(); let pruned = false; @@ -65,22 +85,24 @@ export function mergeCursorFetch( else if (record.timestampMs < retentionStartMs) pruned = true; } const changed = - cache === undefined || - cache.sinceMs > retentionStartMs || + base === undefined || + base.sinceMs > retentionStartMs || pruned || replacedKeys.size !== added.length || added.some((record) => !replacedKeys.has(record.dedupeKey)); - const records = !changed - ? previous - : previous - .filter((record) => !inRange(record) && record.timestampMs >= retentionStartMs) - .concat(added); + let records = previous; + if (changed) { + const kept = previous.filter( + (record) => !inRange(record) && record.timestampMs >= retentionStartMs, + ); + records = older ? added.concat(kept) : kept.concat(added); + } return { changed, cache: { accountKey, - sinceMs: retentionStartMs, - untilMs: range.untilMs, + sinceMs: Math.max(retentionStartMs, Math.min(base?.sinceMs ?? range.sinceMs, range.sinceMs)), + untilMs: older ? base.untilMs : range.untilMs, fetchedAtMs: nowMs, records, } satisfies CursorAccountCache, From 759a173e1576d1d78fb04d16580fdf9641c80c30 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:56:28 +0100 Subject: [PATCH 017/183] fix(web): idle numbered terminals show their name in the app language (#38565) Co-authored-by: Julius Marminge --- packages/shared/src/terminalLabels.test.ts | 21 ++++++++++ packages/shared/src/terminalLabelsCopy.ts | 15 ++++--- ...dle-terminal-label-follows-language.e2e.ts | 42 +++++++++++++++++++ 3 files changed, 73 insertions(+), 5 deletions(-) create mode 100644 scripts/scenarios/idle-terminal-label-follows-language.e2e.ts diff --git a/packages/shared/src/terminalLabels.test.ts b/packages/shared/src/terminalLabels.test.ts index 00f9db0b0990b..0281081a50acc 100644 --- a/packages/shared/src/terminalLabels.test.ts +++ b/packages/shared/src/terminalLabels.test.ts @@ -2,11 +2,32 @@ import { describe, expect, it } from "vite-plus/test"; import { DEFAULT_TERMINAL_ID, TerminalOpenInput } from "@t3tools/contracts"; import * as Schema from "effect/Schema"; +import { mFallback } from "gt-i18n"; +import type { MFunctionType } from "gt-i18n/types"; import { getTerminalLabel, nextTerminalId } from "./terminalLabels.ts"; +import { resolveTerminalSessionLabel } from "./terminalLabelsCopy.ts"; const decodeTerminalOpen = Schema.decodeUnknownSync(TerminalOpenInput); +const japanese: MFunctionType = (encodedMsg, options) => { + const english = mFallback(encodedMsg, options); + return ( + typeof english === "string" ? english.replace("Terminal", "ターミナル") : english + ) as typeof english; +}; + +describe("resolveTerminalSessionLabel", () => { + it("translates the idle default and keeps process names", () => { + const resolve = (label: string, hasRunningSubprocess: boolean) => + resolveTerminalSessionLabel("term-2", { label, hasRunningSubprocess }, japanese); + expect(resolve("Terminal 2", false)).toBe("ターミナル 2"); + expect(resolve(" ", false)).toBe("ターミナル 2"); + expect(resolve("sleep", true)).toBe("sleep"); + expect(resolve("Terminal 2", true)).toBe("Terminal 2"); + }); +}); + describe("nextTerminalId", () => { it("skips over taken term-N slots", () => { expect(nextTerminalId([DEFAULT_TERMINAL_ID, "term-2", "term-3"])).toBe("term-4"); diff --git a/packages/shared/src/terminalLabelsCopy.ts b/packages/shared/src/terminalLabelsCopy.ts index f1d6c4aa88c30..bddcff9942c99 100644 --- a/packages/shared/src/terminalLabelsCopy.ts +++ b/packages/shared/src/terminalLabelsCopy.ts @@ -2,7 +2,7 @@ import type { TerminalSummary } from "@t3tools/contracts"; import { mFallback, msg } from "gt-i18n"; import type { MFunctionType } from "gt-i18n/types"; -import { terminalNumber } from "./terminalLabels.ts"; +import { getTerminalLabel as getServerTerminalLabel, terminalNumber } from "./terminalLabels.ts"; /** @public */ export function getTerminalLabel(terminalId: string, resolve: MFunctionType = mFallback): string { @@ -10,12 +10,17 @@ export function getTerminalLabel(terminalId: string, resolve: MFunctionType = mF return numericSuffix ? resolve(msg("Terminal {number}", { number: numericSuffix })) : terminalId; } -/** @public */ +/** + * The server sends the running process name, or its English idle default, which is shown translated. + * @public + */ export function resolveTerminalSessionLabel( terminalId: string, - summary: Pick | null | undefined, + summary: Pick | null | undefined, resolve: MFunctionType = mFallback, ): string { - const trimmed = summary?.label?.trim(); - return trimmed && trimmed.length > 0 ? trimmed : getTerminalLabel(terminalId, resolve); + const trimmed = summary?.label.trim(); + const isIdleDefault = + !summary?.hasRunningSubprocess && trimmed === getServerTerminalLabel(terminalId); + return trimmed && !isIdleDefault ? trimmed : getTerminalLabel(terminalId, resolve); } diff --git a/scripts/scenarios/idle-terminal-label-follows-language.e2e.ts b/scripts/scenarios/idle-terminal-label-follows-language.e2e.ts new file mode 100644 index 0000000000000..9d4f3ea2c916f --- /dev/null +++ b/scripts/scenarios/idle-terminal-label-follows-language.e2e.ts @@ -0,0 +1,42 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "An idle numbered terminal shows its name in the app's language after switching threads", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("demo"); + const thread = await t3.thread({ project, title: "Terminal work", messages: ["Start"] }); + await t3.thread({ project, title: "Other work", messages: ["Start"] }); + + await t3.open("/settings/general"); + await screen.getByLabel("Language", { exact: true }).tap(); + await screen.getByText("日本語", { exact: true }).tap(); + await screen.getByLabel("言語", { exact: true }).waitFor(); + + await t3.open(thread); + const drawerToggle = screen.getByRole("button", "ターミナルドロワーの切り替え"); + await drawerToggle.tap(); + const input = browser.locator('[aria-label="ターミナルの入力"][data-workspace-focus-default]'); + await input.waitFor(); + await screen.getByRole("button", /^新しいターミナル(?: \(|$)/).tap(); + const secondTerminal = screen.getByRole("button", /^(?:Terminal 2|ターミナル 2)$/); + await secondTerminal.waitFor(); + await screen.getByRole("button", "Other work", { exact: false }).tap(); + await screen.getByRole("button", "Terminal work", { exact: false }).tap(); + + // Wait for a real process label so the idle assertion reads server metadata, not the fallback + // shown while the second terminal is opening. + await secondTerminal.tap(); + await input.focus(); + await browser.keyboard.type("sleep 60\n"); + await screen.getByRole("button", "sleep", { exact: true }).waitFor({ timeout: 40_000 }); + await input.focus(); + await browser.keyboard.press("Control+C"); + await secondTerminal.waitFor({ timeout: 40_000 }); + + await app.screenshot("idle-terminal-after-switch"); + await expect(secondTerminal).toHaveText("ターミナル 2"); + }, +); From 2c4622efb429dfe68c9dc1ef3cd08668803f874b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 04:06:13 -0800 Subject: [PATCH 018/183] fix(server): the first message on an imported conversation sends its history once (#38575) --- .../Adapters/ClaudeAdapterV2.test.ts | 9 + .../Adapters/ClaudeAdapterV2.ts | 11 +- .../src/orchestration-v2/Orchestrator.ts | 4 +- .../ProviderTurnStartService.ts | 10 + .../ProviderSwitch.integration.test.ts | 218 ++++++++++++++++++ .../src/server/ProviderAdapter.ts | 2 + 6 files changed, 250 insertions(+), 4 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index a0e186c4f7d45..33b1bebed3c0b 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -1880,6 +1880,15 @@ describe("ClaudeAdapterV2 resumeThread", () => { }, }); assert.equal(missing.nativeThreadRef?.nativeId, "native-thread-missing"); + + // An imported session's history lives only in its transcript. + const missingImport = yield* Effect.flip( + runtime.resumeThread({ + providerThread: { ...missing, id: providerThread.id }, + importedNativeSession: true, + }), + ); + assert.equal(missingImport._tag, "ProviderAdapterResumeThreadError"); }), ).pipe( Effect.provide( diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 2974c1a81ab2b..21d3a93ba3340 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -14078,7 +14078,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ), ), resumeThread: Effect.fn("ClaudeAdapterV2.resumeThread")( - function* (threadInput: { readonly providerThread: OrchestrationV2ProviderThread }) { + function* (threadInput: { + readonly providerThread: OrchestrationV2ProviderThread; + readonly importedNativeSession?: boolean; + }) { const nativeThreadId = threadInput.providerThread.nativeThreadRef?.nativeId; if (nativeThreadId !== undefined && nativeThreadId !== null) { const recordedTitle = threadInput.providerThread.nativeMetadata?.title; @@ -14102,7 +14105,11 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const transcript = yield* claudeTranscriptState(nativeThreadId).pipe( Effect.orElseSucceed(() => "missing" as const), ); - if (transcript === "empty") { + // Opening a missing imported session would start an empty one under its id. + if ( + transcript === "empty" || + (transcript === "missing" && threadInput.importedNativeSession === true) + ) { return yield* new ProviderAdapter.ProviderAdapterProtocolError({ driver: CLAUDE_PROVIDER, detail: `Claude session ${nativeThreadId} has no conversation to resume.`, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 819aa90c03b98..6b1fe8567b8e6 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -8087,8 +8087,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); const legacyImportHandoff = shouldPrepareLegacyImportHandoff({ hasNativeHistory: - activeProviderThread?.driver === "acpRegistry" && - activeProviderThread.nativeThreadRef !== null, + activeProviderThread !== undefined && activeProviderThread.nativeThreadRef !== null, historyOrigin: projection.thread.historyOrigin, hasCompletedRun: latestCompletedRun !== undefined, legacyImportItemCount: legacyImportItems.length, @@ -8797,6 +8796,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const legacyImportRecoveryHandoff = isProviderSwitch && !canResumeAcrossInstances && + ensuredProviderThread.nativeThreadRef === null && latestCompletedRun === undefined && legacyImportItems.length > 0 ? yield* contextHandoffService diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 28f8f474cd6ab..bb5701d337d0d 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -1420,6 +1420,15 @@ export const layer: Layer.Layer< const nativeSessionLacksKeptTurns = !session.providerSession.capabilities.checkpointing.providerCanRollbackConversation && nativeSessionMissesKeptTurns(projection, providerThread, run); + // 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.contextHandoffs.some( + (handoff) => + handoff.toProviderThreadId === providerThread.id && + handoff.strategy === "manual_context", + ); const resumed = yield* Effect.result( uncertainDelivery || nativeSessionLacksKeptTurns ? Effect.fail( @@ -1438,6 +1447,7 @@ export const layer: Layer.Layer< threadId: projection.thread.id, modelSelection: run.modelSelection, runtimePolicy: resolvedRuntimePolicy, + importedNativeSession, }), ); if (resumed._tag === "Success") { 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 a05636033eb8b..bbef6f3fac48c 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -1390,6 +1390,224 @@ describe("orchestration v2 provider switching", () => { }), ); + const importedNativeSessionScenario = ( + scenario: "first-send" | "after-failed-switch" | "resume-fails", + ) => + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace(`imported-native-session-${scenario}`); + const capturedTurns = yield* Ref.make>([]); + const claudeOrdinal = scenario === "after-failed-switch" ? 2 : 1; + const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([ + makeTestAdapter({ + instanceId: CLAUDE_MODEL_SELECTION.instanceId, + driver: CLAUDE_DRIVER, + capabilities: ClaudeProviderCapabilitiesV2, + modelSelection: CLAUDE_MODEL_SELECTION, + responseByRunOrdinal: { [claudeOrdinal]: "PELICAN" }, + capturedTurns, + failResume: scenario === "resume-fails", + }), + makeTestAdapter({ + instanceId: CODEX_MODEL_SELECTION.instanceId, + driver: CODEX_DRIVER, + capabilities: CodexProviderCapabilitiesV2, + modelSelection: CODEX_MODEL_SELECTION, + responseByRunOrdinal: {}, + capturedTurns, + failedRunOrdinals: new Set([1]), + }), + ]); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("imported-native:create"), + threadId, + projectId, + createdBy: "system", + creationSource: "server", + title: "Imported Claude Code session", + modelSelection: CLAUDE_MODEL_SELECTION, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + // The rows AgentSessionImporter writes: imported messages without a run, + // bound to the strong native session they came from. + const created = yield* orchestrator.getThreadProjection(threadId); + const at = created.thread.createdAt; + const providerThread: OrchestrationV2ProviderThread = { + id: ProviderThreadId.make("provider-thread:imported-native"), + driver: CLAUDE_DRIVER, + providerInstanceId: CLAUDE_MODEL_SELECTION.instanceId, + providerSessionId: null, + appThreadId: threadId, + ownerNodeId: null, + nativeThreadRef: { + driver: CLAUDE_DRIVER, + nativeId: "native-session", + strength: "strong", + }, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: null, + lastRunOrdinal: null, + handoffIds: [], + forkedFrom: null, + createdAt: at, + updatedAt: at, + }; + const common = { + threadId, + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + status: "completed" as const, + title: null, + startedAt: at, + completedAt: at, + updatedAt: at, + }; + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make("imported-native:thread"), + type: "thread.metadata-updated", + threadId, + providerInstanceId: CLAUDE_MODEL_SELECTION.instanceId, + occurredAt: at, + payload: { + ...created.thread, + historyOrigin: "v1_import", + activeProviderThreadId: providerThread.id, + }, + }, + { + id: EventId.make("imported-native:user"), + type: "turn-item.updated", + threadId, + occurredAt: at, + payload: { + ...common, + id: TurnItemId.make("imported-native:user"), + ordinal: 1, + createdBy: "user", + creationSource: "server", + type: "user_message", + messageId: MessageId.make("imported-native:user"), + inputIntent: "turn_start", + text: "Remember the code word PELICAN.", + attachments: [], + }, + }, + { + id: EventId.make("imported-native:assistant"), + type: "turn-item.updated", + threadId, + occurredAt: at, + payload: { + ...common, + id: TurnItemId.make("imported-native:assistant"), + ordinal: 2, + type: "assistant_message", + messageId: MessageId.make("imported-native:assistant"), + text: "OK", + streaming: false, + }, + }, + { + id: EventId.make("imported-native:provider-thread"), + type: "provider-thread.updated", + threadId, + driver: CLAUDE_DRIVER, + providerInstanceId: CLAUDE_MODEL_SELECTION.instanceId, + occurredAt: at, + payload: providerThread, + }, + ], + }); + const send = (ordinal: number, modelSelection: ModelSelection) => + Effect.gen(function* () { + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`imported-native:${ordinal}`), + threadId, + messageId: MessageId.make(`imported-native:${ordinal}`), + createdBy: "user", + creationSource: "web", + text: "What was the code word?", + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + }); + yield* orchestrator.streamStoredEvents.pipe( + Stream.filter( + ({ event }) => + event.type === "run.updated" && + event.payload.ordinal === ordinal && + (event.payload.status === "completed" || event.payload.status === "failed"), + ), + Stream.runHead, + ); + yield* worker.drain(); + }); + if (scenario === "after-failed-switch") yield* send(1, CODEX_MODEL_SELECTION); + yield* send(claudeOrdinal, CLAUDE_MODEL_SELECTION); + + const projection = yield* orchestrator.getThreadProjection(threadId); + assert.equal(projection.runs.at(-1)?.status, "completed"); + const claudeTurn = (yield* Ref.get(capturedTurns)).findLast( + (turn) => turn.driver === CLAUDE_DRIVER, + ); + const importHandoffTargets = projection.contextHandoffs + .filter((handoff) => handoff.strategy === "manual_context") + .map((handoff) => handoff.toProviderThreadId); + if (scenario === "resume-fails") { + // The replacement session is empty, so the recovery summary carries the import. + assert.notEqual(claudeTurn?.nativeThreadId, "native-session"); + assert.deepEqual( + projection.contextHandoffs.map((handoff) => handoff.strategy), + ["full_thread_summary"], + ); + assert.include(claudeTurn?.text ?? "", "Remember the code word PELICAN."); + return; + } + assert.equal(claudeTurn?.nativeThreadId, "native-session"); + assert.notInclude(importHandoffTargets, providerThread.id); + assert.lengthOf(importHandoffTargets, scenario === "after-failed-switch" ? 1 : 0); + if (scenario === "first-send") assert.deepEqual(projection.contextHandoffs, []); + assert.notInclude(claudeTurn?.text ?? "", "Remember the code word PELICAN."); + }).pipe( + Effect.provide( + ProviderReplayHarness.layerWithRegistry( + { + name: `imported-native-session-${scenario}`, + runtimePolicyOverride: { + cwd, + approvalPolicy: "never", + sandboxPolicy: { type: "readOnly" }, + }, + }, + layerRegistry, + ), + ), + ); + }); + it.live("resumes an imported native session without resending its history", () => + importedNativeSessionScenario("first-send"), + ); + it.live("returns to an imported native session without resending its history", () => + importedNativeSessionScenario("after-failed-switch"), + ); + it.live("recovers an imported native session's history when its resume fails", () => + importedNativeSessionScenario("resume-fails"), + ); + it.live.each(["native", "legacy"] as const)( "starts a replacement native thread as new after the resume fallback with %s attempts", (attempts) => diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index 8fc0749c51859..62fe110dd5245 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -734,6 +734,8 @@ export interface ProviderAdapterV2SessionRuntime { readonly threadId?: ThreadId; readonly modelSelection?: ModelSelection; readonly runtimePolicy?: ProviderAdapterV2RuntimePolicy; + /** The native session is the only copy of the thread's imported history: fail when it is gone. */ + readonly importedNativeSession?: boolean; }) => Effect.Effect; /** False means the native protocol explicitly does not support history injection. */ readonly injectHistory?: ( From 66bc6145fe2b117a842d2172d3806474c2b16488 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 04:23:10 -0800 Subject: [PATCH 019/183] fix(pi): worktree handoff no longer leaves Pi threads Waiting (#38582) --- packages/provider-pi/src/server/adapter.test.ts | 8 ++++++++ packages/provider-pi/src/server/adapter.ts | 1 + 2 files changed, 9 insertions(+) diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index d4a5f5ff206c8..4af5beda8e381 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -1070,6 +1070,14 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + // Session release interrupts open tool calls, such as a worktree handoff's, only with this flag. + it.effect("declares that its tool calls end with its process", () => + Effect.gen(function* () { + const { runtime } = yield* openRuntime(yield* makeFakePi); + assert.isTrue(runtime.backgroundTasksEndWithProcess); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect("keeps native image bytes and the saved path in the prompt", () => Effect.gen(function* () { const host = yield* ProviderHost.ProviderHost; diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index d4dac26c9a4e4..313b7f030cd45 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -3323,6 +3323,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return sessionEntity; }, events: Stream.fromQueue(events), + backgroundTasksEndWithProcess: true, hasPendingBackgroundWork: Effect.sync(() => pendingWake !== null), hasPendingBackgroundWorkForThread: (providerThread) => Effect.sync( From 9431a9479faf0ae89a4e5cdbb061ce5f478b15c7 Mon Sep 17 00:00:00 2001 From: Alex Date: Wed, 18 Nov 2026 04:23:29 -0800 Subject: [PATCH 020/183] fix(mobile): use the shared rounded frame for issue details (#38491) Co-authored-by: Julius Marminge --- .../src/features/issues/IssueRouteScreen.tsx | 257 +++++++++--------- 1 file changed, 131 insertions(+), 126 deletions(-) diff --git a/apps/mobile/src/features/issues/IssueRouteScreen.tsx b/apps/mobile/src/features/issues/IssueRouteScreen.tsx index 9f6ae1a7aaa7a..1833b0d765850 100644 --- a/apps/mobile/src/features/issues/IssueRouteScreen.tsx +++ b/apps/mobile/src/features/issues/IssueRouteScreen.tsx @@ -27,6 +27,7 @@ import { Chip } from "../../components/ui/Chip"; import { EmptyState } from "../../components/ui/EmptyState"; import { Menu } from "../../components/ui/Menu"; import { RefreshControl } from "../../components/ui/RefreshControl"; +import { ScreenContent } from "../../components/ui/ScreenContent"; import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic"; import { useComposerBottomInset } from "../../components/ComposerSurface"; import { ANDROID_READING_MAX_WIDTH, CHAT_CONTENT_MAX_WIDTH } from "../../lib/layout"; @@ -542,138 +543,142 @@ function IssueRoute({ params }: { readonly params: IssueParams }) { }, ]} /> - {!usesNativeWorkspaceColumns ? : null} - {/* Not a bare marker: Android wraps a refreshable scroll view, which the marker rejects. */} - void pager.refresh(registry, pullRefresh.onRefresh)} - /> - } - contentContainerStyle={{ - paddingHorizontal: 16, - paddingTop: 8, - paddingBottom: showComposer ? composerHeight + 16 : 24, - }} - > - {!issue ? ( - detailQuery.error && !detailQuery.isPending ? ( - + {!usesNativeWorkspaceColumns ? ( + + ) : null} + {/* Not a bare marker: Android wraps a refreshable scroll view, which the marker rejects. */} + void pager.refresh(registry, pullRefresh.onRefresh)} /> + } + contentContainerStyle={{ + paddingHorizontal: 16, + paddingTop: 8, + paddingBottom: showComposer ? composerHeight + 16 : 24, + }} + > + {!issue ? ( + detailQuery.error && !detailQuery.isPending ? ( + + ) : ( + + ) ) : ( - - ) - ) : ( - - navigation.navigate("IssueLabels", identity)} - onEditAssignees={() => navigation.navigate("IssueAssignees", identity)} - /> - {error || (detail && detailQuery.error) ? ( - - {error ?? detailQuery.error} - - ) : null} - {!detail ? ( - detailQuery.error && !detailQuery.isPending ? ( - + + navigation.navigate("IssueLabels", identity)} + onEditAssignees={() => navigation.navigate("IssueAssignees", identity)} + /> + {error || (detail && detailQuery.error) ? ( + + {error ?? detailQuery.error} + + ) : null} + {!detail ? ( + detailQuery.error && !detailQuery.isPending ? ( + + ) : ( + + ) ) : ( - - ) - ) : ( - <> - - ) : undefined - } - /> - {detail.linkedPullRequests.length > 0 ? ( - - ) : null} - - - {detail.commentCount > 0 - ? gt( - "{count, plural, one {Activity · {count} comment} other {Activity · {count} comments}}", - { count: detail.commentCount }, - ) - : gt("Activity")} - - {nextCursor !== null ? ( - ; + await using screen = await render(opener, { router: "/" }); + const openerButton = screen.getByRole("button", { name: "Open usage" }); + (openerButton.element() as HTMLElement).focus(); + + await screen.rerender( + <> + {opener} + +

Usage

+
+ , + ); + await expect.element(page.getByRole("dialog", { name: "Usage" })).toHaveFocus(); + await userEvent.keyboard("{Escape}"); + + await expect.element(page.getByRole("dialog", { name: "Usage" })).not.toBeInTheDocument(); + await expect.element(openerButton).toHaveFocus(); + }); + it("stays open when Esc belongs to a modal outside Base UI", async () => { await using _screen = await render( diff --git a/apps/web/src/components/AppRouteModal.tsx b/apps/web/src/components/AppRouteModal.tsx index 7b0b3d38daf0f..1414b198afdc4 100644 --- a/apps/web/src/components/AppRouteModal.tsx +++ b/apps/web/src/components/AppRouteModal.tsx @@ -3,7 +3,9 @@ import { T, useGT } from "gt-react"; import { XIcon } from "lucide-react"; import { useRef, useState, type CSSProperties, type ReactNode } from "react"; +import { getCommandPaletteOpener } from "../commandPaletteStore"; import { useNativeTitlebarHeight } from "../lib/windowControlsOverlay"; +import { requestWorkspaceFocus } from "../lib/workspaceFocus"; import { useCloseAppModal } from "./sidebar/mainAppLocation"; import { GlobalVoiceInputIndicator } from "./chat/GlobalVoiceInputIndicator"; import { Button } from "./ui/button"; @@ -21,8 +23,14 @@ export function AppRouteModal({ label, children }: { label: string; children: Re // Text selection that ends on the backdrop is not a dismissal. const backdropPressRef = useRef(false); // Focus the surface, not its first control: no stray focus ring, no phone keyboard. - // On close, leave focus alone; returning it to the opener paints a focus ring. + // On close, return focus to the opener only after a keyboard close; after a pointer close it + // would paint a focus ring. const popupRef = useRef(null); + const [opener] = useState( + () => + getCommandPaletteOpener() ?? + (document.activeElement instanceof HTMLElement ? document.activeElement : null), + ); // Clear the native window controls (macOS traffic lights, the Windows and Linux caption // buttons). Below sm the modal fills the window and leaves that strip empty; up to lg its // 1.5rem inset is shorter than the strip. @@ -79,7 +87,16 @@ export function AppRouteModal({ label, children }: { label: string; children: Re { + if (closeType !== "keyboard" || !opener?.isConnected) return false; + if (!opener.closest("[inert]")) return opener; + // The thread behind the modal stays inert until the route closes, so its area + // takes focus once it is usable again. + const area = opener.closest("[data-workspace-area]"); + if (area?.dataset.workspaceArea) + requestWorkspaceFocus({ area: area.dataset.workspaceArea }); + return false; + }} aria-label={label} data-slot="dialog-popup" data-app-modal="" From f1d64aa0b6dea2c5473bd5f45d62d8ebb6d7a133 Mon Sep 17 00:00:00 2001 From: Bilal Bakr <62337003+Bil0000@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:00:16 +0300 Subject: [PATCH 047/183] fix(azure-devops): legacy and project-less remotes list their work items (#38263) Co-authored-by: Claude Opus 5.5 Co-authored-by: Julius Marminge Co-authored-by: shivam <91240327+shivamhwp@users.noreply.github.com> --- apps/server/src/issue/IssueService.test.ts | 33 ++++++++++++++++ apps/server/src/issue/IssueService.ts | 9 +++-- packages/client-runtime/src/issueLinks.ts | 4 +- .../src/shared/definition.test.ts | 29 +++++++++++++- .../src/shared/definition.ts | 38 +++++++++++++------ .../src/shared/definition.ts | 9 ++++- 6 files changed, 103 insertions(+), 19 deletions(-) diff --git a/apps/server/src/issue/IssueService.test.ts b/apps/server/src/issue/IssueService.test.ts index 2e260451de2d7..e4f61ff49b82b 100644 --- a/apps/server/src/issue/IssueService.test.ts +++ b/apps/server/src/issue/IssueService.test.ts @@ -293,6 +293,39 @@ describe("IssueService", () => { }), ); + it.effect("resolves both legacy Azure work item URLs through the bound project", () => + Effect.gen(function* () { + const tracker = IssueTrackerKind.make("azure-devops"); + const host = "acme.visualstudio.com"; + const service = yield* makeService({ + projects: [ + project({ id: "api", repository: "Api/_git/api", provider: tracker, host }), + project({ + id: "web", + repository: "DefaultCollection/Web/_git/web", + provider: tracker, + host, + }), + ], + trackers: [fakeTracker({ kind: tracker })], + }); + for (const path of ["Web", "DefaultCollection/Web"]) { + const ref = yield* service.resolveUrl( + `https://${host}/${path}/_workitems/edit/9`, + "api" as ProjectId, + ); + expect(ref).toEqual({ + projectId: "web", + tracker, + host, + scope: "DefaultCollection/Web", + key: "9", + writable: true, + }); + } + }), + ); + it.effect("sends writes as interactive requests and reads as background ones", () => Effect.gen(function* () { const interactive: Array = []; diff --git a/apps/server/src/issue/IssueService.ts b/apps/server/src/issue/IssueService.ts index bf3d301f73708..fbf869e562001 100644 --- a/apps/server/src/issue/IssueService.ts +++ b/apps/server/src/issue/IssueService.ts @@ -704,9 +704,12 @@ const make = Effect.gen(function* () { const onTracker = onAuthority.length > 0 ? onAuthority : onHost; const preferFirst = (projects: ReadonlyArray) => projects.find((project) => project.project.id === preferredProjectId) ?? projects[0]; - const own = preferFirst( - onTracker.filter((project) => project.scope.toLowerCase() === link.scope.toLowerCase()), - ); + const scope = link.scope.toLowerCase(); + const own = + preferFirst(onTracker.filter((project) => project.scope.toLowerCase() === scope)) ?? + preferFirst( + onTracker.filter((project) => project.scope.toLowerCase() === gitHost?.link.scopeAlias), + ); const lender = own ?? preferFirst(onTracker); if (lender === undefined) { return yield* new IssueUnavailableError({ reason: "tracker-unsupported" }); diff --git a/packages/client-runtime/src/issueLinks.ts b/packages/client-runtime/src/issueLinks.ts index 3509bbbf33ed5..44da23d9d85bf 100644 --- a/packages/client-runtime/src/issueLinks.ts +++ b/packages/client-runtime/src/issueLinks.ts @@ -78,7 +78,9 @@ export function resolveIssueLinkTarget(input: { const preferFirst = (candidates: typeof bound) => candidates.find((candidate) => candidate.project.id === input.preferredProjectId) ?? candidates[0]; - const own = preferFirst(bound.filter((candidate) => candidate.binding.scope === link.scope)); + const own = + preferFirst(bound.filter((candidate) => candidate.binding.scope === link.scope)) ?? + preferFirst(bound.filter((candidate) => candidate.binding.scope === link.scopeAlias)); const lender = own ?? preferFirst(bound); if (lender === undefined) return null; return { 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 8a10c457f66c3..f18b627a874be 100644 --- a/packages/source-control-azure-devops/src/shared/definition.test.ts +++ b/packages/source-control-azure-devops/src/shared/definition.test.ts @@ -260,14 +260,39 @@ describe("Azure DevOps issue scope", () => { definition.issueScope?.({ provider: kind, displayName: "acme/Web%20App/_git/web" }), ).toBe("acme/Web App"); expect(definition.issueScope?.({ provider: kind, displayName: "web" })).toBeNull(); - // One segment before `_git` is a different thing on each kind of host, so it is not placed. + // One segment before `_git` is a different thing on each kind of host, so it needs the host. expect(definition.issueScope?.({ provider: kind, displayName: "acme/_git/web" })).toBeNull(); + const scopeOn = (canonicalKey: string, displayName: string) => + definition.issueScope?.({ provider: kind, canonicalKey, displayName }); + expect(scopeOn("dev.azure.com/acme/_git/web", "acme/_git/Web")).toBe("acme/Web"); + expect(scopeOn("acme.visualstudio.com/web/_git/web", "Web%20App/_git/web")).toBe("Web App"); + expect(scopeOn("acme.visualstudio.com/_git/web", "_git/Web")).toBe("Web"); + // Its work items are at `acme.visualstudio.com/Web/_workitems/...`, without the collection. + expect( + scopeOn("acme.visualstudio.com/defaultcollection/_git/web", "DefaultCollection/_git/Web"), + ).toBe("Web"); + expect(scopeOn("dev.azure.com/_git/web", "_git/web")).toBeNull(); // A legacy host keeps the organization in its name, and so does its work item URL. expect( definition.parseIssueUrl?.( new URL("https://acme.visualstudio.com/Web%20App/_workitems/edit/9"), ), - ).toEqual({ host: "acme.visualstudio.com", scope: "web app", key: "9" }); + ).toEqual({ + host: "acme.visualstudio.com", + scope: "web app", + scopeAlias: "defaultcollection/web app", + key: "9", + }); + expect( + definition.parseIssueUrl?.( + new URL("https://acme.visualstudio.com/DefaultCollection/Web%20App/_workitems/edit/9"), + ), + ).toEqual({ + host: "acme.visualstudio.com", + scope: "defaultcollection/web app", + scopeAlias: "web app", + key: "9", + }); expect( definition.parseIssueUrl?.(new URL("https://dev.azure.com/acme/_workitems/edit/9")), ).toBeNull(); diff --git a/packages/source-control-azure-devops/src/shared/definition.ts b/packages/source-control-azure-devops/src/shared/definition.ts index 38490a062c76b..78f1a4df45a8d 100644 --- a/packages/source-control-azure-devops/src/shared/definition.ts +++ b/packages/source-control-azure-devops/src/shared/definition.ts @@ -124,14 +124,18 @@ export const definition = defineSourceControl({ }, // A project named with spaces arrives percent-encoded; the binding it is matched against is not. parseIssueUrl: (url) => { + const legacy = url.hostname.toLowerCase().endsWith(".visualstudio.com"); const link = parseIssuePath(url, WORK_ITEM_PATH) ?? - (url.hostname.toLowerCase().endsWith(".visualstudio.com") - ? parseIssuePath(url, LEGACY_WORK_ITEM_PATH) - : null); - return link === null - ? null - : { ...link, scope: link.scope.split("/").map(decodeUrlPathSegment).join("/").toLowerCase() }; + (legacy ? parseIssuePath(url, LEGACY_WORK_ITEM_PATH) : null); + if (link === null) return null; + const scope = link.scope.split("/").map(decodeUrlPathSegment).join("/").toLowerCase(); + if (!legacy) return { ...link, scope }; + // On legacy hosts the default collection is optional in a work item URL. + const scopeAlias = + /^defaultcollection\/([^/]+)$/u.exec(scope)?.[1] ?? + (scope.includes("/") ? undefined : `defaultcollection/${scope}`); + return { ...link, scope, ...(scopeAlias === undefined ? {} : { scopeAlias }) }; }, changeRequestUrlFromReferenceAutolink: () => null, changeRequestActions: new Set([ @@ -170,13 +174,25 @@ export const definition = defineSourceControl({ return name ? decodeUrlPathSegment(name) : null; }, // Work items belong to the project: `organization/project` out of the remote's - // `organization/project/_git/repository`. A shorter path is not placed: `acme/_git/web` is a - // project named after its repository on dev.azure.com and a bare project on a legacy host, and - // nothing here says which host the remote is on. + // `organization/project/_git/repository`. A shorter path depends on the host: `acme/_git/web` + // is a project named after its repository on dev.azure.com and a bare project on a legacy host. issueScope: (identity) => { - const segments = (identity.displayName ?? "").split("/").filter((part) => part !== ""); + const segments = (identity.displayName ?? "") + .split("/") + .filter((part) => part !== "") + .map(decodeUrlPathSegment); const at = segments.indexOf("_git"); - return at === 2 ? segments.slice(0, at).map(decodeUrlPathSegment).join("/") : null; + if (at === 2) return segments.slice(0, at).join("/"); + const repository = segments[at + 1]; + if ((at !== 0 && at !== 1) || repository === undefined) return null; + const host = identity.canonicalKey?.split("/", 1)[0]?.toLowerCase() ?? ""; + const legacy = host.endsWith(".visualstudio.com"); + const [first = ""] = segments; + if (at === 0) return legacy ? repository : null; + if (host === "dev.azure.com") return `${first}/${repository}`; + if (!legacy) return null; + // Work item URLs on a legacy host leave the collection out. + return first.toLowerCase() === "defaultcollection" ? repository : first; }, repositoryKeyFromRemote, canonicalRepositoryKey, diff --git a/packages/source-control-core/src/shared/definition.ts b/packages/source-control-core/src/shared/definition.ts index acd85f0c877a7..d9fe29114a96c 100644 --- a/packages/source-control-core/src/shared/definition.ts +++ b/packages/source-control-core/src/shared/definition.ts @@ -39,6 +39,8 @@ export interface ChangeRequestLink { export interface IssueLink { readonly host: string; readonly scope: string; + /** An equivalent binding scope when the provider allows another spelling in URLs. */ + readonly scopeAlias?: string; readonly key: string; } @@ -94,6 +96,9 @@ export type RepositorySelectorIdentity = Pick< "provider" | "displayName" | "owner" | "name" >; +export type IssueScopeIdentity = RepositorySelectorIdentity & + Partial>; + /** A git remote's host, as `recognizeRemote` reads it. */ export interface GitRemoteHost { /** Trimmed. */ @@ -362,7 +367,7 @@ export interface SourceControlDefinition { * The container the project's issues live in, where that is not its repository: Azure DevOps * keeps work items per project. Null when the repository cannot be placed. */ - readonly issueScope?: (identity: RepositorySelectorIdentity) => string | null; + readonly issueScope?: (identity: IssueScopeIdentity) => string | null; /** * The key of a remote's lower case `host/path`, `.git` suffix kept, for a host that spells it * apart from `normalizeGitRemoteUrl`: over SSH and the web, or with `.git` as part of the name. @@ -699,7 +704,7 @@ export interface SourceControlDefinitionRegistry { identity: RepositorySelectorIdentity | null | undefined, ) => string | null; /** Where the project's issues live: the host's `issueScope`, else its repository. */ - readonly issueScope: (identity: RepositorySelectorIdentity | null | undefined) => string | null; + readonly issueScope: (identity: IssueScopeIdentity | null | undefined) => string | null; readonly changeRequestHost: ( identity: ChangeRequestHostIdentity, kind: Kind, From 75cae42febdbedc2bd39430a1d6f017e38f6bfe0 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 13:08:49 -0800 Subject: [PATCH 048/183] fix(server): live-status thread lists build shells only for threads that may be live (#38733) --- .../src/mcp/OrchestratorMcpService.test.ts | 37 +++++++++++++++++++ apps/server/src/mcp/OrchestratorMcpService.ts | 22 +++++++++++ 2 files changed, 59 insertions(+) diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index 802f3dfd761e3..0bbb8a65327d0 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -6,6 +6,7 @@ import { ContextTransferId, EnvironmentId, GitCommandError, + isLiveSubagentShell, MessageId, NodeId, ORCHESTRATOR_MCP_RUNNING_TASK_NEXT, @@ -4861,6 +4862,18 @@ describe("OrchestratorMcpService thread list", () => { { taskId: "sleep-600", kind: "command" as const, awaited: true as const }, ], }, + { + ...shell("thread:c-settled", "project:c", false), + settledOverride: "settled" as const, + settledAt: DateTime.makeUnsafe("2026-01-02T00:00:00Z"), + }, + { + ...shell("thread:c-awaiting-command", "project:c", false), + activityRunStatus: null, + pendingBackgroundTasks: [ + { taskId: "sleep-600", kind: "command" as const, awaited: true as const }, + ], + }, ]; const shellRequests: Array> = []; const service = layerOrchestratorService.pipe( @@ -4875,6 +4888,14 @@ describe("OrchestratorMcpService thread list", () => { (thread) => input.projectId === undefined || thread.projectId === input.projectId, ), ), + listActiveShellIndex: () => + Effect.succeed( + shells.map((thread) => ({ + ...thread, + mayBeLive: isLiveSubagentShell(thread), + hasRemoteTasks: false, + })), + ), getShellSnapshot: (options) => { const threadIds = options?.threadIds ?? shells.map((thread) => thread.id); shellRequests.push(threadIds); @@ -4979,6 +5000,22 @@ describe("OrchestratorMcpService thread list", () => { }).pipe(Effect.provide(service)), ); + it.effect("skips building shells for settled threads when every status filter is live", () => + Effect.gen(function* () { + const mcp = yield* OrchestratorMcpService.OrchestratorMcpService; + shellRequests.length = 0; + const listed = yield* mcp.listThreads(client, { + projectId: ProjectId.make("project:c"), + statuses: ["preparing", "queued", "starting", "running", "waiting"], + }); + assert.deepStrictEqual( + listed.threads.map((thread) => thread.threadId), + ["thread:c-awaiting-command"], + ); + assert.notInclude(shellRequests.flat(), ThreadId.make("thread:c-settled")); + }).pipe(Effect.provide(service)), + ); + it.effect("builds shells only for the threads on the page", () => Effect.gen(function* () { const mcp = yield* OrchestratorMcpService.OrchestratorMcpService; diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 95e269c64c97f..8dcd025c82481 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -934,6 +934,14 @@ function threadStatus( return backgroundWorkHoldsCompletion(pendingBackgroundTasks ?? []) ? "waiting" : settledStatus; } +const LIVE_LISTED_THREAD_STATUSES: ReadonlySet = new Set([ + "queued", + "preparing", + "starting", + "running", + "waiting", +]); + function listedThreadStatus(shell: OrchestrationV2ThreadShell) { return threadStatus(shell.activityRunStatus, shell.status, shell.pendingBackgroundTasks); } @@ -3280,7 +3288,21 @@ const make = Effect.gen(function* () { ? null : new Set(input.statuses); const titleContains = input.titleContains?.toLocaleLowerCase(); + // A live status needs a source the index's mayBeLive covers, so a live-only filter + // skips building shells for every thread that cannot match. + const mayBeLiveIds = + statuses !== null && + [...statuses].every((status) => LIVE_LISTED_THREAD_STATUSES.has(status)) + ? new Set( + (yield* threadManagement + .listActiveShellIndex() + .pipe(Effect.mapError(listFailure))).flatMap((entry) => + entry.mayBeLive ? [entry.id] : [], + ), + ) + : null; const candidates = projectThreads + .filter((thread) => mayBeLiveIds === null || mayBeLiveIds.has(thread.id)) .filter( (thread) => input.settled === undefined || threadSettlement(thread).settled === input.settled, From 68ea2220c12cef2fad673d87d731c828e73a6e4d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 13:14:28 -0800 Subject: [PATCH 049/183] fix(server): managed Antigravity and Codex runtimes prune old versions (#38740) Co-authored-by: Claude Opus 5.5 --- .../provider/AntigravityInstallation.test.ts | 7 +++- .../src/provider/AntigravityInstallation.ts | 20 ++++++++++ .../src/provider/CodexInstallation.test.ts | 6 +++ apps/server/src/provider/CodexInstallation.ts | 40 ++++++++++++++++--- 4 files changed, 65 insertions(+), 8 deletions(-) diff --git a/apps/server/src/provider/AntigravityInstallation.test.ts b/apps/server/src/provider/AntigravityInstallation.test.ts index 41b3675ff9364..5635522eab4a6 100644 --- a/apps/server/src/provider/AntigravityInstallation.test.ts +++ b/apps/server/src/provider/AntigravityInstallation.test.ts @@ -595,7 +595,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Antigravity inst expect(yield* fs.readFileString(selected.executablePath)).toBe(serverContents); expect(yield* fs.readFileString(selected.harnessPath!)).toBe(harnessContents); expect(yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).toEqual( - expect.arrayContaining([previousReleaseId, (yield* releaseAsset()).sha256]), + [(yield* releaseAsset()).sha256], ); expect(requests).toEqual([(yield* releaseAsset()).url]); }), @@ -1217,7 +1217,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Antigravity inst Effect.gen(function* () { const manifestEntered = yield* Deferred.make(); const releaseManifest = yield* Deferred.make(); - const { installation, fs, stagingReleased } = yield* makeHarness({ + const { installation, fs, baseDir, stagingReleased } = yield* makeHarness({ native: true, platform: "win32", archive: Buffer.from(serverContents), @@ -1242,6 +1242,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Antigravity inst expect(yield* fs.readFileString(oldExecutable.executablePath)).toBe(serverContents); expect(yield* installation.remove().pipe(Effect.flip)).toMatchObject({ operation: "remove" }); yield* Scope.close(processScope, Exit.void); + yield* makeHarness({ native: true, platform: "win32", baseDir }); + expect(yield* fs.exists(oldExecutable.managedVersionDirectory!)).toBe(false); + expect(yield* fs.readFileString(current.executablePath)).toBe(serverContents); yield* installation.remove(); expect(yield* fs.exists(installation.managedDirectory)).toBe(false); }), diff --git a/apps/server/src/provider/AntigravityInstallation.ts b/apps/server/src/provider/AntigravityInstallation.ts index b7c61d7a0bcfa..5a33552ac4263 100644 --- a/apps/server/src/provider/AntigravityInstallation.ts +++ b/apps/server/src/provider/AntigravityInstallation.ts @@ -540,6 +540,22 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma }), ); + // Each update lands in its own directory. Best effort: a busy gate means a session is + // resolving, so the next start or update finishes the cleanup. + const pruneInactiveReleases = Effect.gen(function* () { + const active = yield* readRecord(activePath, ActiveRelease); + for (const entry of yield* fs.readDirectory(versionsDirectory)) { + if (entry === active.releaseId || !/^[a-f0-9]{64}$/u.test(entry)) continue; + const directory = path.join(versionsDirectory, entry); + if (leases.has(directory)) continue; + yield* fs.remove(directory, { recursive: true, force: true }).pipe(Effect.ignore); + } + }).pipe( + gate.withPermitsIfAvailable(1), + Effect.ignore, + Effect.withSpan("AntigravityInstallation.pruneInactiveReleases"), + ); + const install = Effect.fn("AntigravityInstallation.install")( function* (asset: AntigravityReleaseAsset | AntigravityCliReleaseAsset) { yield* ensureEligible(asset.version); @@ -585,6 +601,7 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma mode: 0o600, }); yield* fs.rename(pointerPath, activePath); + yield* pruneInactiveReleases; yield* SubscriptionRef.update( state, (current) => @@ -1170,6 +1187,9 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma ), ); + // A startup install prunes when it activates; pruning now could delete the release it is verifying. + if (!isRunning(yield* SubscriptionRef.get(state))) yield* pruneInactiveReleases; + return AntigravityInstallation.of({ managedDirectory, resolve, diff --git a/apps/server/src/provider/CodexInstallation.test.ts b/apps/server/src/provider/CodexInstallation.test.ts index 59f19b822012c..a000aacb103d3 100644 --- a/apps/server/src/provider/CodexInstallation.test.ts +++ b/apps/server/src/provider/CodexInstallation.test.ts @@ -629,6 +629,8 @@ it.effect("updates a managed install to OpenAI's newest release and never downgr version: upstreamVersion, }); + const sessionScope = yield* Scope.make(); + const previous = yield* h.installation.acquire().pipe(Scope.provide(sessionScope)); yield* h.installation.start; expect(yield* terminalState(h.installation)).toMatchObject({ phase: "succeeded", @@ -636,9 +638,13 @@ it.effect("updates a managed install to OpenAI's newest release and never downgr version: upstreamVersion, }); expect((yield* h.installation.resolve()).version).toBe(upstreamVersion); + // The running session keeps its release until the next start prunes it. + expect(yield* h.fs.exists(previous.managedVersionDirectory!)).toBe(true); + yield* Scope.close(sessionScope, Exit.void); // Without upstream information the older pin is not offered as a reinstall. const restarted = yield* makeHarness({ baseDir: h.baseDir }); + expect(yield* h.fs.exists(previous.managedVersionDirectory!)).toBe(false); expect(yield* restarted.installation.state).toMatchObject({ installedVersion: upstreamVersion, version: upstreamVersion, diff --git a/apps/server/src/provider/CodexInstallation.ts b/apps/server/src/provider/CodexInstallation.ts index 7a9c80ebbf007..87660f0c41800 100644 --- a/apps/server/src/provider/CodexInstallation.ts +++ b/apps/server/src/provider/CodexInstallation.ts @@ -201,7 +201,7 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function const executableName = platform === "win32" ? "codex.exe" : "codex"; const gate = yield* Semaphore.make(1); const updateCheckGate = yield* Semaphore.make(1); - let leases = 0; + const leases = new Map(); let running: { readonly operationId: string; readonly fiber: Fiber.Fiber } | undefined; let upstream: CodexReleaseAsset | null = null; let upstreamCheckedAt: number | null = null; @@ -393,16 +393,20 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function return yield* Effect.acquireRelease( gate.withPermit( resolve().pipe( - Effect.tap(() => + Effect.tap((executable) => Effect.sync(() => { - leases += 1; + const key = executable.managedVersionDirectory ?? executable.executablePath; + leases.set(key, (leases.get(key) ?? 0) + 1); }), ), ), ), - () => + (executable) => Effect.sync(() => { - leases -= 1; + const key = executable.managedVersionDirectory ?? executable.executablePath; + const remaining = (leases.get(key) ?? 1) - 1; + if (remaining > 0) leases.set(key, remaining); + else leases.delete(key); }), ); }); @@ -566,6 +570,26 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function }, Effect.mapError(wrapFailure("verify", "The downloaded Codex runtime could not start.")), ); + // Each update lands in its own directory. Best effort: a busy gate means a session is + // resolving, so the next start or update finishes the cleanup. + const pruneInactiveReleases = Effect.gen(function* () { + const active = yield* readRecord(activePath, ActiveRelease); + for (const entry of yield* fs.readDirectory(managedDirectory)) { + if ( + entry === active.version || + Option.isNone(yield* decodeVersion(entry).pipe(Effect.option)) + ) + continue; + const directory = path.join(managedDirectory, entry); + if (leases.has(directory)) continue; + yield* fs.remove(directory, { recursive: true, force: true }).pipe(Effect.ignore); + } + }).pipe( + gate.withPermitsIfAvailable(1), + Effect.ignore, + Effect.withSpan("CodexInstallation.pruneInactiveReleases"), + ); + const install = Effect.fn("CodexInstallation.install")( function* (release: CodexReleaseAsset) { const ensureEligible = Effect.fn("CodexInstallation.ensureEligible")(function* () { @@ -594,6 +618,7 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function }); yield* ensureEligible(); yield* fs.rename(pointer, activePath); + yield* pruneInactiveReleases; yield* SubscriptionRef.update( state, (current) => @@ -872,7 +897,7 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function function* (protectedBinaryPaths: ReadonlyArray = []) { yield* gate.withPermit( Effect.gen(function* () { - if (isRunning(yield* SubscriptionRef.get(state)) || leases > 0) { + if (isRunning(yield* SubscriptionRef.get(state)) || leases.size > 0) { return yield* installationError( "remove", "Stop Codex sessions and sign-in flows before removing its managed runtime.", @@ -977,6 +1002,9 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function ), ); + // A startup install prunes when it activates; pruning now could delete the release it is verifying. + if (!isRunning(yield* SubscriptionRef.get(state))) yield* pruneInactiveReleases; + return CodexInstallation.of({ managedDirectory, resolve, From 34b12bea8e7f0c1b721ad3be7c13a78b630030da Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 13:17:01 -0800 Subject: [PATCH 050/183] fix(relay): finish unlinking when the DNS record is already gone (#38741) --- .../ManagedEndpointProvider.test.ts | 77 ++++++++++--------- .../environments/ManagedEndpointProvider.ts | 7 +- 2 files changed, 46 insertions(+), 38 deletions(-) diff --git a/infra/relay/src/environments/ManagedEndpointProvider.test.ts b/infra/relay/src/environments/ManagedEndpointProvider.test.ts index 3e360d8f62160..0b22b764e911f 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.test.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.test.ts @@ -1623,45 +1623,48 @@ describe("ManagedEndpointProvider", () => { }).pipe(Effect.provide(layer)); }); - it.effect("treats already deleted remote resources as successfully deprovisioned", () => { - const allocationCalls: AllocationCall[] = []; - const notFound = { _tag: "NotFound" } as const; - const tunnelClient = ManagedEndpointProvider.ManagedEndpointTunnelClient.of({ - ...makeTunnelClient(), - delete: () => - Effect.fail( - new ManagedEndpointProvider.ManagedEndpointTunnelClientError({ - operation: "delete", - tunnelId: "tunnel-id", - cause: notFound, - }), - ), - }); - const dnsClient = ManagedEndpointProvider.ManagedEndpointDnsClient.of({ - ...makeDnsClient(), - deleteRecord: () => - Effect.fail( - new ManagedEndpointProvider.ManagedEndpointDnsClientError({ - operation: "delete-record", - dnsRecordId: "created-record-id", - cause: notFound, - }), - ), - }); - const layer = layerProvider(tunnelClient, dnsClient, makeAllocations(allocationCalls)); - - return Effect.gen(function* () { - const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider; - const key = { userId: "user_ABC", environmentId: "env_ABC" } as const; - yield* provider.provision({ - ...key, - origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, + it.effect.each(["NotFound", "RecordNotFound"])( + "treats deleted remote resources as deprovisioned (%s)", + (dnsErrorTag) => { + const allocationCalls: AllocationCall[] = []; + const notFound = { _tag: "NotFound" } as const; + const tunnelClient = ManagedEndpointProvider.ManagedEndpointTunnelClient.of({ + ...makeTunnelClient(), + delete: () => + Effect.fail( + new ManagedEndpointProvider.ManagedEndpointTunnelClientError({ + operation: "delete", + tunnelId: "tunnel-id", + cause: notFound, + }), + ), }); - yield* provider.deprovision(key); + const dnsClient = ManagedEndpointProvider.ManagedEndpointDnsClient.of({ + ...makeDnsClient(), + deleteRecord: () => + Effect.fail( + new ManagedEndpointProvider.ManagedEndpointDnsClientError({ + operation: "delete-record", + dnsRecordId: "created-record-id", + cause: { _tag: dnsErrorTag }, + }), + ), + }); + const layer = layerProvider(tunnelClient, dnsClient, makeAllocations(allocationCalls)); - expect(allocationCalls.map((call) => call.operation)).toContain("removeClaimed"); - }).pipe(Effect.provide(layer)); - }); + return Effect.gen(function* () { + const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider; + const key = { userId: "user_ABC", environmentId: "env_ABC" } as const; + yield* provider.provision({ + ...key, + origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, + }); + yield* provider.deprovision(key); + + expect(allocationCalls.map((call) => call.operation)).toContain("removeClaimed"); + }).pipe(Effect.provide(layer)); + }, + ); it.effect("scopes managed endpoint resources by user", () => { const tunnelCalls: TunnelCall[] = []; diff --git a/infra/relay/src/environments/ManagedEndpointProvider.ts b/infra/relay/src/environments/ManagedEndpointProvider.ts index 188ad0e7b7148..75813c0608b3b 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.ts @@ -392,7 +392,12 @@ function isManagedEndpointNotFound(cause: unknown): boolean { if (typeof cause !== "object" || cause === null) { return false; } - if ("_tag" in cause && (cause._tag === "NotFound" || cause._tag === "TunnelNotFound")) { + if ( + "_tag" in cause && + (cause._tag === "NotFound" || + cause._tag === "TunnelNotFound" || + cause._tag === "RecordNotFound") + ) { return true; } if ("status" in cause && cause.status === 404) { From 7da318e2d563b4e3c51edde06d435b5c4ec2eb9e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 13:18:37 -0800 Subject: [PATCH 051/183] fix(relay): revoke the previous link when switching accounts (#37820) --- .../src/agentActivity/ApnsDeliveries.test.ts | 145 +++++++++--------- .../environments/EnvironmentLinker.test.ts | 2 + .../src/environments/EnvironmentLinker.ts | 30 +++- .../src/environments/EnvironmentLinks.test.ts | 19 +++ .../src/environments/EnvironmentLinks.ts | 94 +++++++----- 5 files changed, 178 insertions(+), 112 deletions(-) diff --git a/infra/relay/src/agentActivity/ApnsDeliveries.test.ts b/infra/relay/src/agentActivity/ApnsDeliveries.test.ts index 7e6c09a4ffa14..5f52f2576b47a 100644 --- a/infra/relay/src/agentActivity/ApnsDeliveries.test.ts +++ b/infra/relay/src/agentActivity/ApnsDeliveries.test.ts @@ -931,79 +931,84 @@ describe("ApnsDeliveries", () => { ); }); - it.effect("skips a queued Done Live Activity update after the thread resumes working", () => { - const attempts: Array = []; - let executeCount = 0; - const completedAt = "1970-01-01T00:00:01.000Z"; - const completedAggregate: RelayAgentActivityAggregateState = { - ...aggregate, - activeCount: 0, - updatedAt: completedAt, - activities: [ - { - ...aggregate.activities[0]!, - phase: "completed", - status: "Done", - updatedAt: completedAt, - }, - ], - }; - const payload = makeApnsDeliveryJobPayload({ - kind: "live_activity_update", - userId: target.user_id, - deviceId: target.device_id, - token: target.activity_push_token ?? "activity-token", - aggregate: completedAggregate, - alert: { title: "Thread", body: "Done: Project" }, - createdAt: completedAt, - expiresAt: "1970-01-01T00:10:00.000Z", - jobId: "job-update-superseded-by-running", - }); - const signed = signApnsDeliveryJob({ - secret: config.apnsDeliveryJobSigningSecret, - payload, - }); - const execute = (request: HttpClientRequest.HttpClientRequest) => - Effect.sync(() => { - executeCount += 1; - return HttpClientResponse.fromWeb(request, new Response("", { status: 200 })); + it.effect.each([true, false])( + "skips a queued Done update that is no longer visible (thread resumed: %s)", + (resumed) => { + const attempts: Array = []; + let executeCount = 0; + const completedAt = "1970-01-01T00:00:01.000Z"; + const completedAggregate: RelayAgentActivityAggregateState = { + ...aggregate, + activeCount: 0, + updatedAt: completedAt, + activities: [ + { + ...aggregate.activities[0]!, + phase: "completed", + status: "Done", + updatedAt: completedAt, + }, + ], + }; + const payload = makeApnsDeliveryJobPayload({ + kind: "live_activity_update", + userId: target.user_id, + deviceId: target.device_id, + token: target.activity_push_token ?? "activity-token", + aggregate: completedAggregate, + alert: { title: "Thread", body: "Done: Project" }, + createdAt: completedAt, + expiresAt: "1970-01-01T00:10:00.000Z", + jobId: "job-update-superseded-by-running", + }); + const signed = signApnsDeliveryJob({ + secret: config.apnsDeliveryJobSigningSecret, + payload, }); + const execute = (request: HttpClientRequest.HttpClientRequest) => + Effect.sync(() => { + executeCount += 1; + return HttpClientResponse.fromWeb(request, new Response("", { status: 200 })); + }); - return Effect.gen(function* () { - const deliveries = yield* ApnsDeliveries.ApnsDeliveries; - const result = yield* deliveries.processSignedJob(yield* signed); + return Effect.gen(function* () { + const deliveries = yield* ApnsDeliveries.ApnsDeliveries; + const result = yield* deliveries.processSignedJob(yield* signed); - expect(result).toMatchObject({ - kind: "live_activity_update", - ok: true, - apnsStatus: null, - apnsReason: "Stale APNs delivery job skipped.", - }); - expect(executeCount).toBe(0); - expect(attempts).toMatchObject([ - { - sourceJobId: "job-update-superseded-by-running", - apnsReason: "Stale agent activity state skipped.", - }, - ]); - }).pipe( - Effect.provide( - layerFor({ - attempts, - activityStates: [ - { - ...state, - phase: "running", - headline: "Running", - updatedAt: "1970-01-01T00:00:02.000Z", - }, - ], - config: signingConfig, - execute, - }), - ), - ); - }); + expect(result).toMatchObject({ + kind: "live_activity_update", + ok: true, + apnsStatus: null, + apnsReason: "Stale APNs delivery job skipped.", + }); + expect(executeCount).toBe(0); + expect(attempts).toMatchObject([ + { + sourceJobId: "job-update-superseded-by-running", + apnsReason: "Stale agent activity state skipped.", + }, + ]); + }).pipe( + Effect.provide( + layerFor({ + attempts, + activityStates: resumed + ? [ + { + ...state, + phase: "running", + headline: "Running", + updatedAt: "1970-01-01T00:00:02.000Z", + }, + ] + : [], + config: signingConfig, + execute, + }), + ), + ); + }, + ); it.effect("retries an in-flight device's jobs without cancelling other devices", () => { const attempts: Array = []; diff --git a/infra/relay/src/environments/EnvironmentLinker.test.ts b/infra/relay/src/environments/EnvironmentLinker.test.ts index b770b52d22f4e..871764da0123c 100644 --- a/infra/relay/src/environments/EnvironmentLinker.test.ts +++ b/infra/relay/src/environments/EnvironmentLinker.test.ts @@ -17,6 +17,7 @@ import * as Schema from "effect/Schema"; import * as CloudMintSigner from "../auth/CloudMintSigner.ts"; import * as DpopProofs from "../auth/DpopProofs.ts"; import * as RelayTokens from "../auth/RelayTokens.ts"; +import * as RelayDb from "../db.ts"; import * as EnvironmentCredentials from "./EnvironmentCredentials.ts"; import * as EnvironmentLinks from "./EnvironmentLinks.ts"; import * as RelayConfiguration from "../Config.ts"; @@ -119,6 +120,7 @@ function layerTest(input?: { Layer.provide( Layer.mergeAll( RelayConfiguration.layer(config), + Layer.succeed(RelayDb.RelayTransactions, { withTransaction: (effect) => effect }), Layer.succeed(DpopProofs.DpopProofReplay, { verifyAndConsume: () => Effect.die("unexpected DPoP proof verification"), consume: input?.consume ?? (() => Effect.succeed(true)), diff --git a/infra/relay/src/environments/EnvironmentLinker.ts b/infra/relay/src/environments/EnvironmentLinker.ts index 6a58f6ab4f378..c0acd41c36c2e 100644 --- a/infra/relay/src/environments/EnvironmentLinker.ts +++ b/infra/relay/src/environments/EnvironmentLinker.ts @@ -15,9 +15,11 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; +import * as SqlError from "effect/sql/SqlError"; import * as DpopProofs from "../auth/DpopProofs.ts"; import * as RelayTokens from "../auth/RelayTokens.ts"; +import * as RelayDb from "../db.ts"; import * as EnvironmentCredentials from "./EnvironmentCredentials.ts"; import * as EnvironmentLinks from "./EnvironmentLinks.ts"; import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts"; @@ -138,6 +140,7 @@ function isLoopbackManagedTunnelOrigin( const make = Effect.gen(function* () { const links = yield* EnvironmentLinks.EnvironmentLinks; + const transactions = yield* RelayDb.RelayTransactions; const credentials = yield* EnvironmentCredentials.EnvironmentCredentials; const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider; const proofReplay = yield* DpopProofs.DpopProofReplay; @@ -322,11 +325,28 @@ const make = Effect.gen(function* () { stage: "validate_endpoint", }); } - yield* links.upsert({ ...input, proof: verified, endpoint }); - const environmentCredential = yield* credentials.create({ - environmentId: verified.environmentId, - environmentPublicKey: verified.environmentPublicKey, - }); + const environmentCredential = yield* transactions + .withTransaction( + links.upsert({ ...input, proof: verified, endpoint }).pipe( + Effect.andThen( + credentials.create({ + environmentId: verified.environmentId, + environmentPublicKey: verified.environmentPublicKey, + }), + ), + ), + ) + .pipe( + Effect.mapError((cause) => + SqlError.isSqlError(cause) + ? new EnvironmentLinks.EnvironmentLinkUpsertPersistenceError({ + userId: input.userId, + environmentId: verified.environmentId, + cause, + }) + : cause, + ), + ); return { environmentId: verified.environmentId, endpoint, diff --git a/infra/relay/src/environments/EnvironmentLinks.test.ts b/infra/relay/src/environments/EnvironmentLinks.test.ts index 263e3bf11560c..52ceb63e87280 100644 --- a/infra/relay/src/environments/EnvironmentLinks.test.ts +++ b/infra/relay/src/environments/EnvironmentLinks.test.ts @@ -10,7 +10,20 @@ import * as EnvironmentLinks from "./EnvironmentLinks.ts"; describe("EnvironmentLinks", () => { it.effect("carries the webhook-hold opt-in over only from links with the same key", () => { const inserted: Array> = []; + const revoked: Array<{ values: Record; condition: unknown }> = []; const fakeDb = { + $client: { + withTransaction: (effect: Effect.Effect) => effect, + }, + execute: () => Effect.void, + update: () => ({ + set: (values: Record) => ({ + where: (condition: unknown) => + Effect.sync(() => { + revoked.push({ values, condition }); + }), + }), + }), insert: () => ({ values: (values: Record) => { inserted.push(values); @@ -38,6 +51,12 @@ describe("EnvironmentLinks", () => { const query = new PgDialect().sqlToQuery(inserted[0]?.holdWebhooksWhileOffline as never); expect(query.sql).toContain("environment_public_key"); expect(query.params).toEqual(["env-1", "public-key-1"]); + expect(revoked).toHaveLength(1); + expect(revoked[0]?.values.revokedAt).toEqual(inserted[0]?.updatedAt); + const priorLinks = new PgDialect().sqlToQuery(revoked[0]?.condition as never); + expect(priorLinks.sql).toContain('"user_id" <>'); + expect(priorLinks.sql).toContain('"revoked_at" is null'); + expect(priorLinks.params).toEqual(["env-1", "public-key-1", "user-1"]); }).pipe( Effect.provide( EnvironmentLinks.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb))), diff --git a/infra/relay/src/environments/EnvironmentLinks.ts b/infra/relay/src/environments/EnvironmentLinks.ts index b7b38f202a1a5..46fcd717a217c 100644 --- a/infra/relay/src/environments/EnvironmentLinks.ts +++ b/infra/relay/src/environments/EnvironmentLinks.ts @@ -9,7 +9,7 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; -import { and, eq, isNull, or, sql } from "drizzle-orm"; +import { and, eq, isNull, ne, or, sql } from "drizzle-orm"; import * as RelayDb from "../db.ts"; import { relayEnvironmentLinks } from "../persistence/schema.ts"; @@ -187,42 +187,62 @@ const make = Effect.gen(function* () { AND other.hold_webhooks_while_offline )`; const { endpoint } = input; - yield* db - .insert(relayEnvironmentLinks) - .values({ - userId: input.userId, - environmentId, - holdWebhooksWhileOffline: inheritedHoldWebhooks, - environmentLabel: proof.descriptor.label, - environmentPublicKey: proof.environmentPublicKey, - endpointHttpBaseUrl: endpoint.httpBaseUrl, - endpointWsBaseUrl: endpoint.wsBaseUrl, - endpointProviderKind: endpoint.providerKind, - notificationsEnabled: request.notificationsEnabled, - liveActivitiesEnabled: request.liveActivitiesEnabled, - managedTunnelsEnabled: request.managedTunnelsEnabled, - createdByDeviceId: request.deviceId ?? null, - revokedAt: null, - createdAt: now, - updatedAt: now, - }) - .onConflictDoUpdate({ - target: [relayEnvironmentLinks.userId, relayEnvironmentLinks.environmentId], - set: { - environmentPublicKey: proof.environmentPublicKey, - environmentLabel: proof.descriptor.label, - endpointHttpBaseUrl: endpoint.httpBaseUrl, - endpointWsBaseUrl: endpoint.wsBaseUrl, - endpointProviderKind: endpoint.providerKind, - notificationsEnabled: request.notificationsEnabled, - liveActivitiesEnabled: request.liveActivitiesEnabled, - managedTunnelsEnabled: request.managedTunnelsEnabled, - createdByDeviceId: request.deviceId ?? null, - revokedAt: null, - updatedAt: now, - holdWebhooksWhileOffline: inheritedHoldWebhooks, - }, - }) + yield* db.$client + .withTransaction( + Effect.gen(function* () { + // Serialize account switches for the same proven environment identity. + yield* db.execute( + sql`select pg_advisory_xact_lock(hashtext(${environmentId}), hashtext(${proof.environmentPublicKey}))`, + ); + yield* db + .insert(relayEnvironmentLinks) + .values({ + userId: input.userId, + environmentId, + holdWebhooksWhileOffline: inheritedHoldWebhooks, + environmentLabel: proof.descriptor.label, + environmentPublicKey: proof.environmentPublicKey, + endpointHttpBaseUrl: endpoint.httpBaseUrl, + endpointWsBaseUrl: endpoint.wsBaseUrl, + endpointProviderKind: endpoint.providerKind, + notificationsEnabled: request.notificationsEnabled, + liveActivitiesEnabled: request.liveActivitiesEnabled, + managedTunnelsEnabled: request.managedTunnelsEnabled, + createdByDeviceId: request.deviceId ?? null, + revokedAt: null, + createdAt: now, + updatedAt: now, + }) + .onConflictDoUpdate({ + target: [relayEnvironmentLinks.userId, relayEnvironmentLinks.environmentId], + set: { + environmentPublicKey: proof.environmentPublicKey, + environmentLabel: proof.descriptor.label, + endpointHttpBaseUrl: endpoint.httpBaseUrl, + endpointWsBaseUrl: endpoint.wsBaseUrl, + endpointProviderKind: endpoint.providerKind, + notificationsEnabled: request.notificationsEnabled, + liveActivitiesEnabled: request.liveActivitiesEnabled, + managedTunnelsEnabled: request.managedTunnelsEnabled, + createdByDeviceId: request.deviceId ?? null, + revokedAt: null, + updatedAt: now, + holdWebhooksWhileOffline: inheritedHoldWebhooks, + }, + }); + yield* db + .update(relayEnvironmentLinks) + .set({ revokedAt: now, updatedAt: now }) + .where( + and( + eq(relayEnvironmentLinks.environmentId, environmentId), + eq(relayEnvironmentLinks.environmentPublicKey, proof.environmentPublicKey), + ne(relayEnvironmentLinks.userId, input.userId), + isNull(relayEnvironmentLinks.revokedAt), + ), + ); + }), + ) .pipe( Effect.mapError( (cause) => From e48d6f31817ad12975af2ffd341ae2b1b961d247 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 13:32:15 -0800 Subject: [PATCH 052/183] fix(web): PDFs in the desktop file panel can be saved again (#38749) --- .../components/files/BrowserDocumentFrame.tsx | 14 +++++- .../src/components/files/FilePreviewPanel.tsx | 50 +++++++++++++++++++ apps/web/src/components/files/PdfViewer.tsx | 3 ++ 3 files changed, 66 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/files/BrowserDocumentFrame.tsx b/apps/web/src/components/files/BrowserDocumentFrame.tsx index bfa699cf252b4..1cd0e0417d7f0 100644 --- a/apps/web/src/components/files/BrowserDocumentFrame.tsx +++ b/apps/web/src/components/files/BrowserDocumentFrame.tsx @@ -28,6 +28,7 @@ import { } from "@t3tools/shared/keybindings"; import { lazy, + type ReactNode, Suspense, useEffect, useEffectEvent, @@ -79,7 +80,12 @@ export const isPdfPreviewFile = (path: string): boolean => const PdfViewer = lazy(() => import("./PdfViewer")); // The document stays mounted while each revision gets a fresh PDF.js document. -function PdfDocument(props: { src: string; title: string; documentKey: string }) { +function PdfDocument(props: { + src: string; + title: string; + documentKey: string; + actions?: ReactNode; +}) { const [view, setView] = useState({ page: 0, offset: 0, zoom: null, left: 0 }); return ( ); } @@ -100,6 +107,7 @@ function PdfDocumentRevision(props: { positionKey: string; initialView: PdfViewState; onViewChange: (view: PdfViewState) => void; + actions?: ReactNode; }) { const [src] = useState(props.src); // The Electron shell does not enable PDF plugins. WebKit embeds on iOS @@ -124,6 +132,7 @@ function PdfDocumentRevision(props: { positionKey={props.positionKey} initialView={props.initialView} onViewChange={props.onViewChange} + actions={props.actions} /> ); @@ -143,6 +152,8 @@ export function BrowserDocumentFrame(props: { readonly documentKey?: string | undefined; /** Resource identity without its revision, so PDF reloads can retain the reading position. */ readonly documentId?: string | undefined; + /** Toolbar actions for the in-app PDF viewer; Chromium's own viewer brings its own. */ + readonly pdfActions?: ReactNode; }) { const key = props.documentKey ?? props.src; return props.pdf ? ( @@ -151,6 +162,7 @@ export function BrowserDocumentFrame(props: { documentKey={key} src={props.src} title={props.title} + actions={props.pdfActions} /> ) : props.htmlRender ? ( + } /> ); } +function WorkspacePdfSaveAction(props: { + readonly environmentId: EnvironmentId; + readonly resource: AssetResource; + readonly name: string; +}) { + const gt = useGT(); + const [saving, setSaving] = useState(false); + const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, props.resource); + return ( + { + setSaving(true); + void (async () => { + const url = await refreshAssetUrl(); + if (!url) throw new Error(gt("Reconnect to the environment and try again.")); + const response = await fetch(url); + if (!response.ok) throw new Error(gt("The file could not be loaded. Try again.")); + // Blob downloads keep desktop's custom app scheme from navigating to an external browser. + const downloadUrl = URL.createObjectURL(await response.blob()); + setTimeout(() => URL.revokeObjectURL(downloadUrl), 30_000); + const anchor = document.createElement("a"); + anchor.href = downloadUrl; + anchor.download = props.name.split(/[\\/]/).at(-1) || props.name; + anchor.click(); + })() + .catch((cause: unknown) => + toastManager.add({ + type: "error", + title: gt("Could not save file"), + description: thrownErrorMessage(cause, m) ?? gt("Please try again."), + }), + ) + .finally(() => setSaving(false)); + }} + > + + + ); +} + function WorkspaceVideoPreview(props: { readonly environmentId: EnvironmentId; readonly threadRef: ScopedThreadRef; diff --git a/apps/web/src/components/files/PdfViewer.tsx b/apps/web/src/components/files/PdfViewer.tsx index e5872d123bba3..c3e9025eccfd7 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 ReactNode, } from "react"; import { TextLayer, type PDFDocumentProxy } from "pdfjs-dist"; import { msg, useGT } from "gt-react"; @@ -144,6 +145,7 @@ export default function PdfViewer(props: { positionKey?: string; initialView?: PdfViewState; onViewChange?: (view: PdfViewState) => void; + actions?: ReactNode; }) { const gt = useGT(); const [savedPosition] = useState(() => @@ -448,6 +450,7 @@ export default function PdfViewer(props: { ) : null} + {props.actions} diff --git a/apps/web/src/components/ChatView.browser.test.tsx b/apps/web/src/components/ChatView.browser.test.tsx index 8c1ddf1d84122..22523b2683144 100644 --- a/apps/web/src/components/ChatView.browser.test.tsx +++ b/apps/web/src/components/ChatView.browser.test.tsx @@ -2,10 +2,14 @@ import { createMemoryHistory } from "@tanstack/react-router"; import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment"; import { EnvironmentId, + IssueTrackerKind, ORCHESTRATION_V2_WS_METHODS, RunId, ThreadId, WS_METHODS, + type IssueDetail, + type IssueRef, + type ThreadIssueLink, } from "@t3tools/contracts"; import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings"; import { @@ -24,6 +28,7 @@ import "~/components/ChatView"; import { DraftId, useComposerDraftStore } from "~/composerDraftStore"; import { selectThreadDiffPanelSelection, useDiffPanelStore } from "~/diffPanelStore"; import { __setClientSettingsForTests } from "~/hooks/useSettings"; +import stylesheet from "~/index.css?inline"; import { environmentContextRecord } from "~/lib/composerContextRecords"; import { startWorkspaceFocus } from "~/lib/workspaceFocus"; import { usePromptStashStore } from "~/promptStashStore"; @@ -109,6 +114,121 @@ vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({ trackRpcRequestSent: () => {}, })); +it("opens a linked Linear issue from an inactive thread's sidebar badge", async () => { + const style = document.createElement("style"); + style.textContent = stylesheet; + document.head.append(style); + using _style = { [Symbol.dispose]: () => style.remove() }; + const first = threadWithHistory("issue-first", 1); + const linked = threadWithHistory("issue-linked", 1); + const issueRef = { + projectId: PROJECT_ID, + tracker: IssueTrackerKind.make("linear"), + host: "linear.app", + scope: "WEB", + key: "WEB-123", + } satisfies IssueRef; + const issue: ThreadIssueLink = { + ...issueRef, + url: "https://linear.app/example/issue/WEB-123/add-keyboard-support", + source: "manual", + linkedAt: "2026-01-01T00:00:00.000Z", + displayKey: issueRef.key, + title: "Add keyboard support", + }; + using _environment = installFakeEnvironment([first, { ...linked, issues: [issue] }]); + const liveTitle = "Add keyboard shortcuts to the sidebar"; + using _detail = answerRpc(WS_METHODS.issuesDetail, (input: IssueRef) => { + expect(input).toEqual(issueRef); + return Effect.succeed({ + ...issue, + title: liveTitle, + author: { login: "sam", name: null, avatarUrl: null }, + state: { category: "open", name: "Open" }, + createdAt: issue.linkedAt, + updatedAt: issue.linkedAt, + closedAt: null, + assignees: [], + labels: [], + commentCount: 3, + projectTitle: "render", + writable: false, + capabilities: { + create: false, + edit: false, + comment: false, + labels: false, + assignees: false, + reactions: false, + templates: false, + linkedPullRequests: false, + events: false, + search: false, + }, + viewerPermissions: { + setState: false, + comment: false, + edit: false, + labels: false, + assignees: false, + }, + states: [], + viewer: null, + body: "", + comments: [], + commentsCursor: null, + events: [], + linkedPullRequests: [], + } satisfies IssueDetail); + }); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + await page.viewport(1400, 900); + const router = getRouter( + createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${first.id}`] }), + ); + await router.load(); + await using _app = await render(, { + // AppRoot brings its own router. + router: false, + }); + const badge = page.getByRole("button", { + name: `Issue ${issue.displayKey}: ${issue.title}, Open`, + }); + await expect.element(badge).toBeVisible(); + expect(badge.element().querySelector("svg")).toHaveClass(/text-emerald-600/); + await userEvent.hover(badge); + const issueName = `Issue ${issue.displayKey}: ${liveTitle}`; + const previewLink = page.getByRole("link", { name: issueName }); + await userEvent.hover(previewLink.getByText("sam", { exact: true })); + await expect.element(previewLink).toBeVisible(); + const contextMenu = new MouseEvent("contextmenu", { bubbles: true, cancelable: true }); + await act(() => previewLink.element().dispatchEvent(contextMenu)); + expect(contextMenu.defaultPrevented).toBe(false); + await userEvent.click(badge); + const issueRow = page + .getByRole("region", { name: "Linked issues" }) + .getByRole("link", { name: issueName }); + await expect.element(issueRow.getByRole("img", { name: "Open" })).toBeVisible(); + await expect.element(issueRow.getByRole("img", { name: "3 comments" })).toBeVisible(); + await expect.element(issueRow.getByRole("img", { name: "Linear" })).toBeVisible(); + await expect.element(issueRow.getByText(issue.scope, { exact: true })).toBeVisible(); + await userEvent.click(issueRow); + expect(router.history.location.pathname).toBe(`/${ENVIRONMENT_ID}/${linked.id}`); + await expect.element(page.getByRole("heading", { name: liveTitle })).toBeVisible(); + await act(() => useRightPanelStore.getState().close(scopeThreadRef(ENVIRONMENT_ID, linked.id))); + await expect + .element( + page.getByRole("region", { name: "Thread details" }).getByRole("link", { + name: issueName, + exact: true, + }), + ) + .toBeVisible(); +}); + it("a machine chip stashed in one thread restores with its machine in another", async () => { const other = threadWithHistory("thread-stash-restore", 1); const asking = threadWithQuestion("thread-stash-question", "Which file should change?"); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index bceb3d9eb0788..a731a5798e191 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -2014,6 +2014,9 @@ export default function ChatView(props: ChatViewProps) { const visiblePullRequestCount = visiblePullRequests.length; const pullRequestsSurfaceAvailable = isServerThread && supportsThreadPullRequests && visiblePullRequestCount > 0; + const linkedItemsSurfaceAvailable = + pullRequestsSurfaceAvailable || + (isServerThread && (activeThreadShell?.issues?.length ?? 0) > 0); const { state: deviceState, loaded: deviceStateLoaded } = useDeviceState( activeThreadRef?.environmentId ?? null, ); @@ -2441,7 +2444,7 @@ export default function ChatView(props: ChatViewProps) { canMaximizeRightPanel, rightPanelMaximized, supportsPullRequests, - pullRequestsSurfaceAvailable, + pullRequestsSurfaceAvailable: linkedItemsSurfaceAvailable, gitCwd, activeProjectCwd, onDiffPanelOpen, @@ -4083,7 +4086,7 @@ export default function ChatView(props: ChatViewProps) { diffAvailable={isServerThread && isGitRepo} filesAvailable={activeProject !== null} pullRequestAvailable={pullRequestSurfaceAvailable} - pullRequestsAvailable={pullRequestsSurfaceAvailable} + pullRequestsAvailable={linkedItemsSurfaceAvailable} deviceAvailable={activeThreadRef !== null} sideChatAvailable={sideChat.available} sideChatDisabledReason={sideChatDisabledReason} diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 8bf3fe9f16789..a7a86ca21752e 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -1508,9 +1508,11 @@ function OpenCommandPaletteDialog(props: { actionItems.push({ kind: "action", value: "action:open-thread-pull-requests", - searchTerms: ["pull requests", "linked", "stack", "prs"], - title: gt("Show linked pull requests"), - disabled: visibleThreadPullRequests(activeThread.pullRequests).length === 0, + searchTerms: ["pull requests", "issues", "linked", "stack", "prs"], + title: gt("Show linked items"), + disabled: + visibleThreadPullRequests(activeThread.pullRequests).length === 0 && + !activeThread.issues?.length, icon: , run: async () => { useRightPanelStore.getState().open(threadRef, "pull-requests"); diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index f481c0426ae3b..2ce8f22f63f5e 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -185,7 +185,7 @@ const SURFACE_DISABLED_REASONS = { files: msg("Files are only available when a project is open."), diff: msg("Diff is only available for server threads in Git repositories."), pullRequest: msg("This thread's branch has no pull request yet."), - pullRequests: msg("No linked pull requests are available for this thread."), + pullRequests: msg("This thread has no linked items."), device: msg("Devices are only available from a thread."), sideChat: msg("Side chats start after the first message."), } as const; @@ -210,7 +210,7 @@ const SURFACE_UNAVAILABLE_HINTS = { files: msg("Available when a project is open."), diff: msg("Available for Git repositories."), pullRequest: msg("No pull request on this branch yet."), - pullRequests: msg("No linked pull requests available."), + pullRequests: msg("No linked items available."), device: msg("Available from a thread."), sideChat: msg("Available after the first message."), } as const; @@ -391,7 +391,7 @@ function RightPanelEmptyState(props: { onClick: props.onAddPullRequest, }, { - label: msg("Linked pull requests"), + label: msg("Linked items"), icon: PullRequestGlyph.link, shortcut: "L", available: props.pullRequestsAvailable, @@ -606,7 +606,7 @@ function surfaceTitle( case "pull-request": return `#${surface.number}`; case "pull-requests": - return resolve(msg("Pull requests")); + return resolve(msg("Linked items")); case "issue": // A git host numbers its issues; a tracker with keys of its own, such as Linear, names them. return /^\d+$/.test(surface.key) ? `#${surface.key}` : surface.key; @@ -1210,7 +1210,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) { onClick: props.onAddPullRequest, }, { - label: msg("Linked pull requests"), + label: msg("Linked items"), icon: PullRequestGlyph.link, shortcut: "L", available: props.pullRequestsAvailable, diff --git a/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx b/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx index 375d1a04aae35..bb3a5e2d54d3d 100644 --- a/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx +++ b/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx @@ -1,45 +1,167 @@ -import { threadIssueKeyOf, type ThreadIssueLink } from "@t3tools/contracts"; +import { threadIssueKeyOf, type ScopedThreadRef, type ThreadIssueLink } from "@t3tools/contracts"; import { useGT } from "gt-react"; -import type { MouseEvent as ReactMouseEvent } from "react"; +import { MessageSquareIcon } from "lucide-react"; +import type { MouseEvent } from "react"; import { cn } from "~/lib/utils"; +import { useRightPanelStore } from "~/rightPanelStore"; +import { useServerConfigs } from "~/state/entities"; +import { useLinkedIssueDetail } from "~/state/issues"; -import { IssueGlyph } from "../issue/issuePresentation"; -import { ThreadDetailsControl } from "./ThreadDetailsControl"; import { - THREAD_DETAILS_PANEL_ICON_CLASS, - THREAD_DETAILS_PANEL_LABEL_CLASS, -} from "./threadDetailsPanelStyles"; + IssueGlyph, + issueStatePresentation, + issueTrackerPresentation, +} from "../issue/issuePresentation"; +import { + PULL_REQUEST_ROW_CLASS, + PULL_REQUEST_ROW_NUMBER_CLASS, + PullRequestRowLines, +} from "../pullRequest/PullRequestListRow"; +import { PullRequestActorLabel } from "../pullRequest/pullRequestPresentation"; +import { ThreadDetailsControl } from "./ThreadDetailsControl"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; -/** - * The thread details panel's issue rows, one per linked issue, beside the pull request rows. A - * row names the issue as it was when linked and opens it in the right panel, which reads its - * live state. - */ -export function ThreadDetailsIssueRows({ - links, - onOpenLink, +function LinkedIssueRow({ + link, + threadRef, + compact, + mountScope, + onOpen, }: { - links: ReadonlyArray; - onOpenLink: (event: ReactMouseEvent, link: ThreadIssueLink) => void; + link: ThreadIssueLink; + threadRef: ScopedThreadRef; + compact: boolean; + mountScope: "thread-details" | "linked-items" | "sidebar-tooltip"; + onOpen: (() => void) | undefined; }) { const gt = useGT(); - if (links.length === 0) return null; - return ( + const configs = useServerConfigs(); + const detail = useLinkedIssueDetail(threadRef.environmentId, link, mountScope); + const trackerPresentation = issueTrackerPresentation(link.tracker); + const state = detail === null ? null : issueStatePresentation(detail.state); + const Icon = state?.Icon ?? IssueGlyph.issue; + const title = detail?.title ?? link.title; + const anchorProps = { + href: link.url, + target: "_blank", + rel: "noopener noreferrer", + "aria-label": gt("Issue {key}: {title}", { key: link.displayKey, title }), + onClick: (event: MouseEvent) => { + event.stopPropagation(); + if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; + if (configs.get(threadRef.environmentId)?.environment.capabilities.issues !== true) return; + event.preventDefault(); + useRightPanelStore.getState().openIssue(threadRef, link); + onOpen?.(); + }, + }; + const glyph = ( + + ); + const comments = + detail !== null && detail.commentCount > 0 ? ( + + + {detail.commentCount} + + ) : null; + const trackerIcon = ( + + ); + const lines = ( <> - {links.map((link) => ( - onOpenLink(event, link)} - > - - - {link.displayKey}: {link.title} - - - ))} + {glyph} + {link.displayKey}} + title={title} + status={comments} + meta={ + <> + {detail?.author ? ( + + ) : null} + {trackerIcon} + {link.scope} + + } + updatedAt={detail?.updatedAt ?? link.linkedAt} + /> ); + return compact ? ( +
+ + } />} + > + {glyph} + {title} + + +
{lines}
+
+
+
+ {link.displayKey} + {trackerIcon} + {comments} +
+
+ ) : ( + + {lines} + + ); +} + +export function ThreadDetailsIssueRows({ + links, + threadRef, + compact = true, + mountScope = "thread-details", + onOpen, +}: { + links: ReadonlyArray; + threadRef: ScopedThreadRef; + compact?: boolean; + mountScope?: "thread-details" | "linked-items" | "sidebar-tooltip"; + onOpen?: () => void; +}) { + return links.map((link) => ( + + )); } diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx index 3abae88a711b5..5fb1be8665fa7 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx @@ -1,3 +1,4 @@ +import { ThreadDetailsIssueRows } from "./ThreadDetailsIssueRows"; import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; import { EnvironmentId, @@ -13,6 +14,7 @@ import { AsyncResult } from "effect/reactivity"; import { expect, it, vi } from "vite-plus/test"; const state = vi.hoisted(() => ({ + issuesSupported: false, isDraft: false, status: "success" as PullRequestCheck["status"], extraStatus: null as PullRequestCheck["status"] | null, @@ -39,13 +41,15 @@ vi.mock(import("~/state/entities"), async (importOriginal) => ({ new Map([ [ EnvironmentId.make("environment"), - { environment: { capabilities: { pullRequests: true } } }, + { environment: { capabilities: { pullRequests: true, issues: state.issuesSupported } } }, ], ])) as never, useProjects: (() => state.projects) as never, useQuietThreadShell: ((ref: unknown) => ref === null ? null : { branch: null, pullRequests: state.pullRequests }) as never, })); +vi.mock(import("~/state/issues"), () => ({ useLinkedIssueDetail: () => null })); + const queryData = () => ({ projectId: ProjectId.make("project"), workspaceRoot: "/workspace", @@ -125,7 +129,6 @@ import { act, render as renderUi } from "../../../test/render"; import { useComposerDraftStore } from "~/composerDraftStore"; import { useUiStateStore } from "~/uiStateStore"; import { ThreadDetailsPrRow } from "./ThreadDetailsPrRow"; -import { ThreadDetailsIssueRows } from "./ThreadDetailsIssueRows"; import { ThreadDetailsThreadPrRows } from "./ThreadDetailsPrRows"; const threadRef: ScopedThreadRef = { @@ -255,6 +258,7 @@ async function setup() { state.addToast.mockReset().mockReturnValue("checkout-toast"); state.updateToast.mockReset(); + state.issuesSupported = false; state.isDraft = false; state.status = "success"; state.extraStatus = null; @@ -402,18 +406,26 @@ it("names a linked issue row by its kind, number and title, not its URL", async title: "Sidebar flickers on resize", }, ]} - onOpenLink={vi.fn()} + threadRef={{ + environmentId: EnvironmentId.make("environment"), + threadId: ThreadId.make("thread"), + }} />, ); }); - const row = [...screen.container.querySelectorAll("button")].find((button) => - button.textContent?.includes("Sidebar flickers on resize"), + const row = [...screen.container.querySelectorAll("a")].find((anchor) => + anchor.textContent?.includes("Sidebar flickers on resize"), )!; const name = row.getAttribute("aria-label") ?? row.textContent ?? ""; expect(name).not.toContain("https://"); expect(name).toMatch(/issue/i); expect(name).toContain("#123"); expect(name).toContain("Sidebar flickers on resize"); + const externalClick = new MouseEvent("click", { bubbles: true, cancelable: true }); + await act(async () => { + row.dispatchEvent(externalClick); + }); + expect(externalClick.defaultPrevented).toBe(false); }); it("keeps Ready pending when refreshed detail becomes mergeable before the action settles", async () => { diff --git a/apps/web/src/components/pullRequest/ThreadPullRequestsPanel.tsx b/apps/web/src/components/pullRequest/ThreadPullRequestsPanel.tsx index 98cf920f9de9f..95185c23ae263 100644 --- a/apps/web/src/components/pullRequest/ThreadPullRequestsPanel.tsx +++ b/apps/web/src/components/pullRequest/ThreadPullRequestsPanel.tsx @@ -40,6 +40,7 @@ import { PullRequestsUnavailableState } from "./PullRequestsUnavailableState"; import { threadEnvironment } from "~/state/threads"; import { useAtomCommand } from "~/state/use-atom-command"; import { RelativeTime } from "~/components/RelativeTime"; +import { ThreadDetailsIssueRows } from "../chat/ThreadDetailsIssueRows"; import { Button } from "../ui/button"; import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu"; import { MiddleTruncate } from "../ui/middle-truncate"; @@ -408,8 +409,8 @@ export function ThreadPullRequestsPanel({ threadRef }: { threadRef: ScopedThread if (configs.get(threadRef.environmentId) === undefined) { return ( ); } @@ -419,6 +420,7 @@ export function ThreadPullRequestsPanel({ threadRef }: { threadRef: ScopedThread function EnabledThreadPullRequestsPanel({ threadRef }: { threadRef: ScopedThreadRef }) { const gt = useGT(); const thread = useThreadShell(threadRef); + const issues = thread?.issues ?? []; const projects = useProjects(); const environmentProjects = projects .filter((project) => project.environmentId === threadRef.environmentId) @@ -508,7 +510,7 @@ function EnabledThreadPullRequestsPanel({ threadRef }: { threadRef: ScopedThread primaryEnvironmentId, }; - if (linkCount === 0) { + if (linkCount === 0 && issues.length === 0) { return (
@@ -538,6 +540,28 @@ function EnabledThreadPullRequestsPanel({ threadRef }: { threadRef: ScopedThread data={lines} keyExtractor={lineKey} extraData={rowInputs} + ListHeaderComponent={ + issues.length > 0 ? ( + <> +
+

+ Issues +

+ +
+ {linkCount > 0 ? ( +

+ Pull requests +

+ ) : null} + + ) : null + } renderItem={({ item: line }) => (
- {gt( - "{openCount, plural, one {{openCount} open} other {{openCount} open}} · {linkCount, plural, one {{linkCount} linked} other {{linkCount} linked}}", - { openCount, linkCount }, - )} + {linkCount > 0 + ? gt( + "{openCount, plural, one {{openCount} open} other {{openCount} open}} · {linkCount, plural, one {{linkCount} linked} other {{linkCount} linked}}", + { openCount, linkCount }, + ) + : null} {lastSynced ? ( <> {" · "} @@ -580,7 +606,7 @@ function EnabledThreadPullRequestsPanel({ threadRef }: { threadRef: ScopedThread
diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsx index bcde10957a94f..f3505bd2c66bf 100644 --- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx @@ -78,6 +78,7 @@ import { useThreadSelectionStore } from "../../threadSelectionStore"; import { useNowMinute } from "../../hooks/useNowMinute"; import { useNowSecond } from "../../hooks/useNowSecond"; import { vcsEnvironment, vcsBranchRevalidation } from "../../state/vcs"; +import { useLinkedIssueDetail } from "../../state/issues"; import { useEnvironmentQuery } from "../../state/query"; import { readEnvironmentScope, useEnvironmentScope } from "../../state/session"; import { formatRelativeTime, parseTimestampDate } from "../../timestampFormat"; @@ -129,6 +130,8 @@ import { MiddleTruncate } from "../ui/middle-truncate"; import { ActivityShimmerOverlay } from "../chat/TimelineRowParts"; import { observeVisibleAnimation } from "~/lib/visibleAnimation"; import { useThreadHasUnsentDraft } from "../../composerDraftStore"; +import { ThreadDetailsIssueRows } from "../chat/ThreadDetailsIssueRows"; +import { IssueGlyph, issueStatePresentation } from "../issue/issuePresentation"; // The fields thread rows show. Provider status pushes refresh `checkedAt`, // status and auth on every provider; leaving those out keeps each @@ -1112,7 +1115,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP const prBadgeShape = supportsMultiplePullRequests ? resolveThreadPullRequestBadge(thread.pullRequests) : null; - const handlePrListClick = () => { + const openLinkedItems = () => { useRightPanelStore.getState().open(threadRef, "pull-requests"); if (!props.isRouteThread) onThreadActivate(threadRef); }; @@ -1125,10 +1128,72 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP number={pr?.number ?? currentLinkedPr?.number} url={pr?.url ?? currentLinkedPr?.url} status={prStatus} - onOpenList={handlePrListClick} + onOpenList={openLinkedItems} onOpenPullRequest={handlePrClick} /> ) : null; + const firstIssue = thread.issues?.[0]; + const issueCount = thread.issues?.length ?? 0; + const issueDetail = useLinkedIssueDetail( + thread.environmentId, + leaseLiveStatus && issueCount === 1 ? firstIssue : undefined, + "sidebar", + ); + const issueStatus = issueDetail === null ? null : issueStatePresentation(issueDetail.state); + const IssueIcon = issueStatus?.Icon ?? IssueGlyph.issue; + const issueLabel = + issueCount === 1 && firstIssue + ? issueStatus + ? gt("Issue {key}: {title}, {state}", { + key: firstIssue.displayKey, + title: firstIssue.title, + state: issueStatus.label, + }) + : gt("Issue {key}: {title}", { key: firstIssue.displayKey, title: firstIssue.title }) + : gt("{count, plural, one {{count} linked issue} other {{count} linked issues}}", { + count: issueCount, + }); + const issueBadge = firstIssue ? ( + + event.stopPropagation()} + onClick={(event) => { + event.stopPropagation(); + openLinkedItems(); + }} + /> + } + > + + + {issueCount === 1 ? firstIssue.displayKey : issueCount} + + + event.stopPropagation()} + > +
+ { + if (!props.isRouteThread) onThreadActivate(threadRef); + }} + /> +
+
+
+ ) : null; const terminalStatusIcon = ( +{formatDiffCount(diff.insertions)}{" "} @@ -1319,6 +1386,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP {multiline ? titleLineIcons : null} {pinIndicator} {multiline ? null : terminalStatusIcon} + {multiline ? null : issueBadge} {isRegeneratingTitle ? ( Regenerating title diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 7cd1b127f65d2..123d585ffbb73 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -1707,7 +1707,7 @@ "9e9201570bcc2be8": "PR-Link kopieren", "a1fcc064a5cece14": "Thread kopieren", "2eb493c9e7a5fe9a": "Pull Request mit Thread verknüpfen", - "bf066df32c752202": "Verknüpfte Pull Requests anzeigen", + "abbbacfec60327d7": "Verknüpfte Elemente anzeigen", "67f5b13c3c7bcd40": "Mit Gast teilen", "82da5b8b340217ac": "Agentensitzung neu starten", "963d099509eabcd6": "Die Agentensitzung wird neu gestartet", @@ -2257,13 +2257,13 @@ "a3aa1e49af278d41": "Dateien sind nur verfügbar, wenn ein Projekt geöffnet ist.", "87ea6995ea1e7aa4": "Diffs sind nur für Server-Threads in Git-Repositorys verfügbar.", "4a87cae01ccde544": "Der Branch dieses Threads hat noch keinen Pull Request.", - "0051e6585d7ea014": "Für diesen Thread sind keine verknüpften Pull Requests verfügbar.", + "32535dba0b9af642": "Dieser Thread hat keine verknüpften Elemente.", "07080dead70f4cc5": "Geräte sind nur aus einem Thread verfügbar.", "a4bf49b31758ff7e": "Nur in der Desktop-App verfügbar.", "e917841cb66f9af1": "Verfügbar, wenn ein Projekt geöffnet ist.", "14c15fad0c2ee0c8": "Verfügbar für Git-Repositorys.", "9176276c78f3893f": "Noch kein Pull Request auf diesem Branch.", - "713aa4c9c08f042b": "Keine verknüpften Pull Requests verfügbar.", + "52ce9db6fb62a59f": "Keine verknüpften Elemente verfügbar.", "e5d6f41e4fe4efd6": "Aus einem Thread verfügbar.", "0ebc2bb883a8e283": "Nach der ersten Nachricht verfügbar.", "84d0ff8fb9846057": "Tab-Ton einschalten", @@ -2273,11 +2273,11 @@ "cba3e832ece50257": "Dateien", "83ac3423d6dfc4a7": "Diff", "da16af47eff38ae9": "Pull Request", + "ad3929f0103925d7": "Verknüpfte Elemente", "ac0de2a59d9c8860": "Gerät", "1354df9fb7278843": "Einen iOS-Simulator oder Android-Emulator ansehen.", "4bcfa3b976a421cf": "Nebenchat", "fdcd9643e2e63b15": "Stelle eine Nebenfrage, während dieser Thread weiterarbeitet.", - "13087312bc6a0b45": "Pull Requests", "314cfeebf191ba0d": "Genehmigung nötig", "4e5b7363441a3831": "Eingabe nötig", "97af4e74a5f95e5e": "läuft", @@ -3296,6 +3296,7 @@ "249192edde7f4932": "Sprachen durchsuchen", "71d8b593668d2106": "Keine passenden Sprachen.", "326bc17df66a7f05": "Dateien und Ordner", + "13087312bc6a0b45": "Pull Requests", "0e83c3bf28f8958e": "Befehle", "75d18dac06f4f037": "Skills", "05340d7dfcc34edf": "App", @@ -3981,6 +3982,7 @@ ], "e58a1d884fa1d8f2": "Thread-Details", "02d9667ff2c8e0b8": "Issue {key}: {title}", + "4276743ee60a3c62": "{count, plural, one {{count} Kommentar} other {{count} Kommentare}}", "42f634397f3960aa": "In Thread-Details anzeigen", "e3738ef0423ddfe7": "Auf Standard zurücksetzen", "ae10d34e11064fec": "Versionskontrolle", @@ -6720,7 +6722,6 @@ "c0257180840458bc": "{count, plural, =1 {Aufgelöste Unterhaltung} other {{count} aufgelöste Unterhaltungen}}", "9e65f6bc12538296": "Aufgelöst", "d74fc95719fe5478": "Offen", - "4276743ee60a3c62": "{count, plural, one {{count} Kommentar} other {{count} Kommentare}}", "79ae43d8b6d1cce4": "Kommentar bearbeiten", "1eadc7b869a55c68": "Weitere Kommentare laden", "3f9bc820dffd099f": "Antwort", @@ -6978,13 +6979,15 @@ "ed09d936d8ba9792": "Beobachtung beenden", "af6adbd67cef13b1": "Auf Änderungen beobachten", "13eb3e529a3e9bff": "Aus dem Thread entfernen", - "93cebe7fdcc9821e": "Verknüpfte Pull Requests nicht verfügbar", - "47c92b77099a6346": "Diese Umgebung unterstützt nicht mehrere verknüpfte Pull Requests.", + "b872b70a1387351a": "Verknüpfte Elemente nicht verfügbar", + "ff700a2d719110d8": "Die Umgebung des Threads ist nicht verfügbar.", + "b935e8d2dad4d8ba": "Verknüpfte Issues", "e18c90152452a50e": "{openCount, plural, one {{openCount} offen} other {{openCount} offen}} · {linkCount, plural, one {{linkCount} verknüpft} other {{linkCount} verknüpft}}", "106c1bf3308a8c33": "Beobachtet: Der Agent wird geweckt, wenn Checks fertig sind, jemand kommentiert oder der Branch Konflikte hat", "15a560968264b0ed": "Öffnen", "a4e0e1e0bad3dcd8": "Keine verknüpften Pull Requests", "973b668999e33451": "Pull Requests, die der Agent aus diesem Thread öffnet, landen hier. Verknüpfe selbst einen über URL oder Nummer.", + "24303a7d08e18647": "Issues", "f034c05267f161ce": [ "synchronisiert", " ", @@ -6994,7 +6997,7 @@ "v": "v" } ], - "74da2dae824a4573": "Verknüpfen", + "7d160729d1afcd58": "Pull Request verknüpfen", "2b82c15cd4dc73c6": "Angesehene Dateien konnten nicht aktualisiert werden", "f85cd11cb736771c": "Ausgecheckt, aber nicht auf dem neuesten Commit bestätigt", "406f2d0ee4df0b37": "{term, select, mr {Dieser Checkout konnte nicht als auf dem neuesten Commit des Merge Requests bestätigt werden, daher kann sein Code abweichen. Lokale Commits oder nicht committete Arbeit halten einen Checkout an seiner Stelle.} cr {Dieser Checkout konnte nicht als auf dem neuesten Commit der Änderungsanfrage bestätigt werden, daher kann sein Code abweichen. Lokale Commits oder nicht committete Arbeit halten einen Checkout an seiner Stelle.} other {Dieser Checkout konnte nicht als auf dem neuesten Commit des Pull Requests bestätigt werden, daher kann sein Code abweichen. Lokale Commits oder nicht committete Arbeit halten einen Checkout an seiner Stelle.}}", @@ -11633,6 +11636,8 @@ "37ffec8201f153c1": "Fehlgeschlagen", "984b361806ce8d25": "Aufgeweckt", "c6e8abc00ae470d2": "Fertig", + "f31a95961de19433": "Issue {key}: {title}, {state}", + "2dd9d295c882ef65": "{count, plural, one {{count} verknüpftes Issue} other {{count} verknüpfte Issues}}", "8cf699ae75fd8067": "Angeheftet", "be451f475c514b37": "Aufgeweckt-Hinweis schließen", "e9ced65134f2f36c": "Thread jetzt aufwecken", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 4754afcb4269e..e511620865bdf 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -1708,7 +1708,7 @@ "9e9201570bcc2be8": "Copy PR link", "a1fcc064a5cece14": "Copy thread", "2eb493c9e7a5fe9a": "Link pull request to thread", - "bf066df32c752202": "Show linked pull requests", + "abbbacfec60327d7": "Show linked items", "67f5b13c3c7bcd40": "Share with guest", "82da5b8b340217ac": "Restart agent session", "963d099509eabcd6": "Agent session will restart", @@ -2257,13 +2257,13 @@ "a3aa1e49af278d41": "Files are only available when a project is open.", "87ea6995ea1e7aa4": "Diff is only available for server threads in Git repositories.", "4a87cae01ccde544": "This thread's branch has no pull request yet.", - "0051e6585d7ea014": "No linked pull requests are available for this thread.", + "32535dba0b9af642": "This thread has no linked items.", "07080dead70f4cc5": "Devices are only available from a thread.", "a4bf49b31758ff7e": "Only available in the desktop app.", "e917841cb66f9af1": "Available when a project is open.", "14c15fad0c2ee0c8": "Available for Git repositories.", "9176276c78f3893f": "No pull request on this branch yet.", - "713aa4c9c08f042b": "No linked pull requests available.", + "52ce9db6fb62a59f": "No linked items available.", "e5d6f41e4fe4efd6": "Available from a thread.", "0ebc2bb883a8e283": "Available after the first message.", "84d0ff8fb9846057": "Unmute tab", @@ -2273,11 +2273,11 @@ "cba3e832ece50257": "Files", "83ac3423d6dfc4a7": "Diff", "da16af47eff38ae9": "Pull request", + "ad3929f0103925d7": "Linked items", "ac0de2a59d9c8860": "Device", "1354df9fb7278843": "Watch an iOS Simulator or Android Emulator.", "4bcfa3b976a421cf": "Side chat", "fdcd9643e2e63b15": "Ask a side question while this thread keeps working.", - "13087312bc6a0b45": "Pull requests", "314cfeebf191ba0d": "needs approval", "4e5b7363441a3831": "needs input", "97af4e74a5f95e5e": "running", @@ -3295,6 +3295,7 @@ "249192edde7f4932": "Search languages", "71d8b593668d2106": "No matching languages.", "326bc17df66a7f05": "Files and folders", + "13087312bc6a0b45": "Pull requests", "0e83c3bf28f8958e": "Commands", "75d18dac06f4f037": "Skills", "05340d7dfcc34edf": "App", @@ -3979,6 +3980,7 @@ ], "e58a1d884fa1d8f2": "Thread details", "02d9667ff2c8e0b8": "Issue {key}: {title}", + "4276743ee60a3c62": "{count, plural, one {{count} comment} other {{count} comments}}", "42f634397f3960aa": "Show in thread details", "e3738ef0423ddfe7": "Reset to default", "ae10d34e11064fec": "Version Control", @@ -6726,7 +6728,6 @@ "c0257180840458bc": "{count, plural, =1 {Resolved conversation} other {{count} resolved conversations}}", "9e65f6bc12538296": "Resolved", "d74fc95719fe5478": "Open", - "4276743ee60a3c62": "{count, plural, one {{count} comment} other {{count} comments}}", "79ae43d8b6d1cce4": "Edit comment", "1eadc7b869a55c68": "Load more comments", "3f9bc820dffd099f": "Reply", @@ -6986,13 +6987,15 @@ "ed09d936d8ba9792": "Stop watching", "af6adbd67cef13b1": "Watch for changes", "13eb3e529a3e9bff": "Dismiss from thread", - "93cebe7fdcc9821e": "Linked pull requests unavailable", - "47c92b77099a6346": "This environment does not support multiple linked pull requests.", + "b872b70a1387351a": "Linked items unavailable", + "ff700a2d719110d8": "The thread's environment is not available.", + "b935e8d2dad4d8ba": "Linked issues", "e18c90152452a50e": "{openCount, plural, one {{openCount} open} other {{openCount} open}} · {linkCount, plural, one {{linkCount} linked} other {{linkCount} linked}}", "106c1bf3308a8c33": "Watching: the agent wakes when checks finish, someone comments, or the branch conflicts", "15a560968264b0ed": "Open", "a4e0e1e0bad3dcd8": "No linked pull requests", "973b668999e33451": "Pull requests the agent opens from this thread land here. Link one yourself from a URL or a number.", + "24303a7d08e18647": "Issues", "f034c05267f161ce": [ "synced", " ", @@ -7002,7 +7005,7 @@ "v": "v" } ], - "74da2dae824a4573": "Link", + "7d160729d1afcd58": "Link pull request", "2b82c15cd4dc73c6": "Could not update viewed files", "f85cd11cb736771c": "Checked out, but not confirmed on the latest commit", "406f2d0ee4df0b37": "This checkout could not be confirmed at the {term, select, mr {merge request} cr {change request} other {pull request}}'s latest commit, so its code may differ. Local commits or uncommitted work keep a checkout where it is.", @@ -11641,6 +11644,8 @@ "37ffec8201f153c1": "Failed", "984b361806ce8d25": "Woke", "c6e8abc00ae470d2": "Done", + "f31a95961de19433": "Issue {key}: {title}, {state}", + "2dd9d295c882ef65": "{count, plural, one {{count} linked issue} other {{count} linked issues}}", "8cf699ae75fd8067": "Pinned", "be451f475c514b37": "Dismiss Woke notification", "e9ced65134f2f36c": "Wake thread now", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index bace8792e3fad..30323ec49044a 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -1708,7 +1708,7 @@ "9e9201570bcc2be8": "Copiar enlace de la PR", "a1fcc064a5cece14": "Copiar hilo", "2eb493c9e7a5fe9a": "Vincular una pull request al hilo", - "bf066df32c752202": "Mostrar pull requests vinculadas", + "abbbacfec60327d7": "Mostrar elementos vinculados", "67f5b13c3c7bcd40": "Compartir con un invitado", "82da5b8b340217ac": "Reiniciar sesión del agente", "963d099509eabcd6": "La sesión del agente se reiniciará", @@ -2257,13 +2257,13 @@ "a3aa1e49af278d41": "Los archivos solo están disponibles cuando hay un proyecto abierto.", "87ea6995ea1e7aa4": "El diff solo está disponible para hilos del servidor en repositorios Git.", "4a87cae01ccde544": "La rama de este hilo aún no tiene ninguna pull request.", - "0051e6585d7ea014": "No hay pull requests vinculadas disponibles para este hilo.", + "32535dba0b9af642": "Este hilo no tiene elementos vinculados.", "07080dead70f4cc5": "Los dispositivos solo están disponibles desde un hilo.", "a4bf49b31758ff7e": "Solo disponible en la app de escritorio.", "e917841cb66f9af1": "Disponible cuando hay un proyecto abierto.", "14c15fad0c2ee0c8": "Disponible para repositorios Git.", "9176276c78f3893f": "Aún no hay ninguna pull request en esta rama.", - "713aa4c9c08f042b": "No hay pull requests vinculadas disponibles.", + "52ce9db6fb62a59f": "No hay elementos vinculados disponibles.", "e5d6f41e4fe4efd6": "Disponible desde un hilo.", "0ebc2bb883a8e283": "Disponible después del primer mensaje.", "84d0ff8fb9846057": "Activar sonido de la pestaña", @@ -2273,11 +2273,11 @@ "cba3e832ece50257": "Archivos", "83ac3423d6dfc4a7": "Diff", "da16af47eff38ae9": "Pull request", + "ad3929f0103925d7": "Elementos vinculados", "ac0de2a59d9c8860": "Dispositivo", "1354df9fb7278843": "Mira un simulador de iOS o un emulador de Android.", "4bcfa3b976a421cf": "Chat lateral", "fdcd9643e2e63b15": "Haz una pregunta aparte mientras este hilo sigue trabajando.", - "13087312bc6a0b45": "Pull requests", "314cfeebf191ba0d": "necesita aprobación", "4e5b7363441a3831": "necesita respuesta", "97af4e74a5f95e5e": "en curso", @@ -3295,6 +3295,7 @@ "249192edde7f4932": "Buscar lenguajes", "71d8b593668d2106": "No hay lenguajes que coincidan.", "326bc17df66a7f05": "Archivos y carpetas", + "13087312bc6a0b45": "Pull requests", "0e83c3bf28f8958e": "Comandos", "75d18dac06f4f037": "Skills", "05340d7dfcc34edf": "App", @@ -3977,6 +3978,7 @@ ], "e58a1d884fa1d8f2": "Detalles del hilo", "02d9667ff2c8e0b8": "Issue {key}: {title}", + "4276743ee60a3c62": "{count, plural, one {{count} comentario} other {{count} comentarios}}", "42f634397f3960aa": "Mostrar en los detalles del hilo", "e3738ef0423ddfe7": "Restablecer al valor predeterminado", "ae10d34e11064fec": "Control de versiones", @@ -6719,7 +6721,6 @@ "c0257180840458bc": "{count, plural, =1 {Conversación resuelta} other {{count} conversaciones resueltas}}", "9e65f6bc12538296": "Resuelta", "d74fc95719fe5478": "Abierta", - "4276743ee60a3c62": "{count, plural, one {{count} comentario} other {{count} comentarios}}", "79ae43d8b6d1cce4": "Editar comentario", "1eadc7b869a55c68": "Cargar más comentarios", "3f9bc820dffd099f": "Responder", @@ -6979,13 +6980,15 @@ "ed09d936d8ba9792": "Dejar de seguir", "af6adbd67cef13b1": "Seguir los cambios", "13eb3e529a3e9bff": "Descartar del hilo", - "93cebe7fdcc9821e": "Pull requests vinculadas no disponibles", - "47c92b77099a6346": "Este entorno no admite varias pull requests vinculadas.", + "b872b70a1387351a": "Elementos vinculados no disponibles", + "ff700a2d719110d8": "El entorno del hilo no está disponible.", + "b935e8d2dad4d8ba": "Issues vinculadas", "e18c90152452a50e": "{openCount, plural, one {{openCount} abierta} other {{openCount} abiertas}} · {linkCount, plural, one {{linkCount} vinculada} other {{linkCount} vinculadas}}", "106c1bf3308a8c33": "Siguiendo: el agente se activa cuando terminan las comprobaciones, alguien comenta o la rama tiene conflictos", "15a560968264b0ed": "Abrir", "a4e0e1e0bad3dcd8": "No hay pull requests vinculadas", "973b668999e33451": "Aquí llegan las pull requests que el agente abre desde este hilo. Vincula una tú mismo desde una URL o un número.", + "24303a7d08e18647": "Issues", "f034c05267f161ce": [ "sincronizado", " ", @@ -6995,7 +6998,7 @@ "v": "v" } ], - "74da2dae824a4573": "Vincular", + "7d160729d1afcd58": "Vincular pull request", "2b82c15cd4dc73c6": "No se pudieron actualizar los archivos vistos", "f85cd11cb736771c": "Checkout hecho, pero no confirmado en el último commit", "406f2d0ee4df0b37": "No se pudo confirmar que este checkout esté en el último commit de la {term, select, mr {merge request} cr {solicitud de cambios} other {pull request}}, así que su código puede ser distinto. Los commits locales o el trabajo sin commit mantienen el checkout donde está.", @@ -11626,6 +11629,8 @@ "37ffec8201f153c1": "Falló", "984b361806ce8d25": "Reactivado", "c6e8abc00ae470d2": "Hecho", + "f31a95961de19433": "Incidencia {key}: {title}, {state}", + "2dd9d295c882ef65": "{count, plural, one {{count} incidencia vinculada} other {{count} incidencias vinculadas}}", "8cf699ae75fd8067": "Fijados", "be451f475c514b37": "Descartar notificación de reactivación", "e9ced65134f2f36c": "Reactivar hilo ahora", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index a658ad17a447a..35343414c7e76 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -1708,7 +1708,7 @@ "9e9201570bcc2be8": "Copier le lien de la PR", "a1fcc064a5cece14": "Copier le fil", "2eb493c9e7a5fe9a": "Associer une pull request au fil", - "bf066df32c752202": "Afficher les pull requests associées", + "abbbacfec60327d7": "Afficher les éléments associés", "67f5b13c3c7bcd40": "Partager avec un invité", "82da5b8b340217ac": "Redémarrer la session de l’agent", "963d099509eabcd6": "La session de l’agent va redémarrer", @@ -2257,13 +2257,13 @@ "a3aa1e49af278d41": "Les fichiers ne sont disponibles que lorsqu’un projet est ouvert.", "87ea6995ea1e7aa4": "Le diff n’est disponible que pour les fils de serveur dans des dépôts Git.", "4a87cae01ccde544": "La branche de ce fil n’a pas encore de pull request.", - "0051e6585d7ea014": "Aucune pull request associée n’est disponible pour ce fil.", + "32535dba0b9af642": "Ce fil n’a aucun élément associé.", "07080dead70f4cc5": "Les appareils ne sont disponibles que depuis un fil.", "a4bf49b31758ff7e": "Disponible uniquement dans l’app desktop.", "e917841cb66f9af1": "Disponible lorsqu’un projet est ouvert.", "14c15fad0c2ee0c8": "Disponible pour les dépôts Git.", "9176276c78f3893f": "Pas encore de pull request sur cette branche.", - "713aa4c9c08f042b": "Aucune pull request associée disponible.", + "52ce9db6fb62a59f": "Aucun élément associé disponible.", "e5d6f41e4fe4efd6": "Disponible depuis un fil.", "0ebc2bb883a8e283": "Disponible après le premier message.", "84d0ff8fb9846057": "Réactiver le son de l’onglet", @@ -2273,11 +2273,11 @@ "cba3e832ece50257": "Fichiers", "83ac3423d6dfc4a7": "Diff", "da16af47eff38ae9": "Pull request", + "ad3929f0103925d7": "Éléments associés", "ac0de2a59d9c8860": "Appareil", "1354df9fb7278843": "Regardez un simulateur iOS ou un émulateur Android.", "4bcfa3b976a421cf": "Discussion annexe", "fdcd9643e2e63b15": "Posez une question annexe pendant que ce fil continue de travailler.", - "13087312bc6a0b45": "Pull requests", "314cfeebf191ba0d": "approbation requise", "4e5b7363441a3831": "réponse requise", "97af4e74a5f95e5e": "en cours", @@ -3295,6 +3295,7 @@ "249192edde7f4932": "Rechercher un langage", "71d8b593668d2106": "Aucun langage correspondant.", "326bc17df66a7f05": "Fichiers et dossiers", + "13087312bc6a0b45": "Pull requests", "0e83c3bf28f8958e": "Commandes", "75d18dac06f4f037": "Skills", "05340d7dfcc34edf": "App", @@ -3978,6 +3979,7 @@ ], "e58a1d884fa1d8f2": "Détails du fil", "02d9667ff2c8e0b8": "Ticket {key} : {title}", + "4276743ee60a3c62": "{count, plural, one {{count} commentaire} other {{count} commentaires}}", "42f634397f3960aa": "Afficher dans les détails du fil", "e3738ef0423ddfe7": "Rétablir la valeur par défaut", "ae10d34e11064fec": "Gestion de versions", @@ -6720,7 +6722,6 @@ "c0257180840458bc": "{count, plural, =1 {Conversation résolue} other {{count} conversations résolues}}", "9e65f6bc12538296": "Résolue", "d74fc95719fe5478": "Ouverte", - "4276743ee60a3c62": "{count, plural, one {{count} commentaire} other {{count} commentaires}}", "79ae43d8b6d1cce4": "Modifier le commentaire", "1eadc7b869a55c68": "Charger plus de commentaires", "3f9bc820dffd099f": "Répondre", @@ -6980,13 +6981,15 @@ "ed09d936d8ba9792": "Arrêter la surveillance", "af6adbd67cef13b1": "Surveiller les changements", "13eb3e529a3e9bff": "Écarter du fil", - "93cebe7fdcc9821e": "Pull requests associées indisponibles", - "47c92b77099a6346": "Cet environnement ne prend pas en charge plusieurs pull requests associées.", + "b872b70a1387351a": "Éléments associés indisponibles", + "ff700a2d719110d8": "L’environnement du fil n’est pas disponible.", + "b935e8d2dad4d8ba": "Tickets associés", "e18c90152452a50e": "{openCount, plural, one {{openCount} ouverte} other {{openCount} ouvertes}} · {linkCount, plural, one {{linkCount} associée} other {{linkCount} associées}}", "106c1bf3308a8c33": "Surveillance : l’agent se réveille quand les checks se terminent, que quelqu’un commente ou que la branche entre en conflit", "15a560968264b0ed": "Ouvrir", "a4e0e1e0bad3dcd8": "Aucune pull request associée", "973b668999e33451": "Les pull requests que l’agent ouvre depuis ce fil arrivent ici. Associez-en une vous-même à partir d’une URL ou d’un numéro.", + "24303a7d08e18647": "Tickets", "f034c05267f161ce": [ "synchronisé", " ", @@ -6996,7 +6999,7 @@ "v": "v" } ], - "74da2dae824a4573": "Associer", + "7d160729d1afcd58": "Associer une pull request", "2b82c15cd4dc73c6": "Impossible de mettre à jour les fichiers vus", "f85cd11cb736771c": "Récupérée, mais non confirmée sur le dernier commit", "406f2d0ee4df0b37": "Cette extraction n’a pas pu être confirmée sur le dernier commit de la {term, select, mr {merge request} cr {demande de modification} other {pull request}}, son code peut donc différer. Les commits locaux ou le travail non commité maintiennent une extraction là où elle est.", @@ -11631,6 +11634,8 @@ "37ffec8201f153c1": "Échec", "984b361806ce8d25": "Réveillé", "c6e8abc00ae470d2": "Terminé", + "f31a95961de19433": "Ticket {key} : {title}, {state}", + "2dd9d295c882ef65": "{count, plural, one {{count} ticket lié} other {{count} tickets liés}}", "8cf699ae75fd8067": "Épinglés", "be451f475c514b37": "Ignorer la notification Réveillé", "e9ced65134f2f36c": "Réveiller le fil maintenant", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 0472298922416..299344ab78c4a 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -1707,7 +1707,7 @@ "9e9201570bcc2be8": "PR のリンクをコピー", "a1fcc064a5cece14": "スレッドをコピー", "2eb493c9e7a5fe9a": "プルリクエストをスレッドにリンク", - "bf066df32c752202": "リンクされたプルリクエストを表示", + "abbbacfec60327d7": "リンクされた項目を表示", "67f5b13c3c7bcd40": "ゲストと共有", "82da5b8b340217ac": "エージェントのセッションを再起動", "963d099509eabcd6": "エージェントのセッションが再起動されます", @@ -2255,13 +2255,13 @@ "a3aa1e49af278d41": "ファイルはプロジェクトが開いているときのみ利用できます。", "87ea6995ea1e7aa4": "差分は Git リポジトリ内のサーバースレッドでのみ利用できます。", "4a87cae01ccde544": "このスレッドのブランチにはまだプルリクエストがありません。", - "0051e6585d7ea014": "このスレッドにリンクされたプルリクエストはありません。", + "32535dba0b9af642": "このスレッドにリンクされた項目はありません。", "07080dead70f4cc5": "デバイスはスレッドからのみ利用できます。", "a4bf49b31758ff7e": "デスクトップアプリでのみ利用できます。", "e917841cb66f9af1": "プロジェクトが開いているときに利用できます。", "14c15fad0c2ee0c8": "Git リポジトリで利用できます。", "9176276c78f3893f": "このブランチにはまだプルリクエストがありません。", - "713aa4c9c08f042b": "リンクされたプルリクエストはありません。", + "52ce9db6fb62a59f": "リンクされた項目はありません。", "e5d6f41e4fe4efd6": "スレッドから利用できます。", "0ebc2bb883a8e283": "最初のメッセージの後に利用できます。", "84d0ff8fb9846057": "タブのミュートを解除", @@ -2271,11 +2271,11 @@ "cba3e832ece50257": "ファイル", "83ac3423d6dfc4a7": "差分", "da16af47eff38ae9": "プルリクエスト", + "ad3929f0103925d7": "リンクされた項目", "ac0de2a59d9c8860": "デバイス", "1354df9fb7278843": "iOS シミュレーターまたは Android エミュレーターを表示します。", "4bcfa3b976a421cf": "サイドチャット", "fdcd9643e2e63b15": "このスレッドの作業を続けたまま、別の質問をします。", - "13087312bc6a0b45": "プルリクエスト", "314cfeebf191ba0d": "承認が必要", "4e5b7363441a3831": "入力が必要", "97af4e74a5f95e5e": "実行中", @@ -3291,6 +3291,7 @@ "249192edde7f4932": "言語を検索", "71d8b593668d2106": "一致する言語はありません。", "326bc17df66a7f05": "ファイルとフォルダー", + "13087312bc6a0b45": "プルリクエスト", "0e83c3bf28f8958e": "コマンド", "75d18dac06f4f037": "スキル", "05340d7dfcc34edf": "アプリ", @@ -3968,6 +3969,7 @@ ], "e58a1d884fa1d8f2": "スレッドの詳細", "02d9667ff2c8e0b8": "Issue {key}: {title}", + "4276743ee60a3c62": "{count, plural, other {{count} 件のコメント}}", "42f634397f3960aa": "スレッドの詳細に表示", "e3738ef0423ddfe7": "デフォルトにリセット", "ae10d34e11064fec": "バージョン管理", @@ -6688,7 +6690,6 @@ "c0257180840458bc": "{count, plural, =1 {解決済みの会話} other {{count} 件の解決済みの会話}}", "9e65f6bc12538296": "解決済み", "d74fc95719fe5478": "未解決", - "4276743ee60a3c62": "{count, plural, other {{count} 件のコメント}}", "79ae43d8b6d1cce4": "コメントを編集", "1eadc7b869a55c68": "さらにコメントを読み込む", "3f9bc820dffd099f": "返信", @@ -6946,13 +6947,15 @@ "ed09d936d8ba9792": "ウォッチを解除", "af6adbd67cef13b1": "変更を監視", "13eb3e529a3e9bff": "スレッドから除外", - "93cebe7fdcc9821e": "リンクされたプルリクエストを利用できません", - "47c92b77099a6346": "この環境は複数のプルリクエストのリンクをサポートしていません。", + "b872b70a1387351a": "リンクされた項目を利用できません", + "ff700a2d719110d8": "スレッドの環境を利用できません。", + "b935e8d2dad4d8ba": "リンクされた Issue", "e18c90152452a50e": "{openCount, plural, other {{openCount} 件オープン}} · {linkCount, plural, other {{linkCount} 件リンク済み}}", "106c1bf3308a8c33": "監視中: チェックの完了、コメントの追加、ブランチの競合が発生するとエージェントが起動します", "15a560968264b0ed": "開く", "a4e0e1e0bad3dcd8": "リンクされたプルリクエストはありません", "973b668999e33451": "このスレッドからエージェントが作成したプルリクエストがここに表示されます。URL や番号から自分でリンクすることもできます。", + "24303a7d08e18647": "Issue", "f034c05267f161ce": [ "同期:", " ", @@ -6962,7 +6965,7 @@ "v": "v" } ], - "74da2dae824a4573": "リンク", + "7d160729d1afcd58": "プルリクエストをリンク", "2b82c15cd4dc73c6": "確認済みのファイルを更新できませんでした", "f85cd11cb736771c": "チェックアウトしましたが、最新のコミットであることを確認できませんでした", "406f2d0ee4df0b37": "{term, select, mr {このチェックアウトがマージリクエストの最新コミットであることを確認できなかったため、コードが異なる可能性があります。ローカルのコミットや未コミットの作業がある場合、チェックアウトはそのまま維持されます。} cr {このチェックアウトが変更リクエストの最新コミットであることを確認できなかったため、コードが異なる可能性があります。ローカルのコミットや未コミットの作業がある場合、チェックアウトはそのまま維持されます。} other {このチェックアウトがプルリクエストの最新コミットであることを確認できなかったため、コードが異なる可能性があります。ローカルのコミットや未コミットの作業がある場合、チェックアウトはそのまま維持されます。}}", @@ -11581,6 +11584,8 @@ "37ffec8201f153c1": "失敗", "984b361806ce8d25": "再開", "c6e8abc00ae470d2": "完了", + "f31a95961de19433": "課題 {key}: {title}、{state}", + "2dd9d295c882ef65": "{count, plural, other {{count} 件のリンクされた課題}}", "8cf699ae75fd8067": "ピン留め済み", "be451f475c514b37": "再開の通知を閉じる", "e9ced65134f2f36c": "スレッドを今すぐ再開", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 8fc59766937af..7075e686c1df8 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -1707,7 +1707,7 @@ "9e9201570bcc2be8": "PR 링크 복사", "a1fcc064a5cece14": "스레드 복사", "2eb493c9e7a5fe9a": "스레드에 풀 리퀘스트 연결", - "bf066df32c752202": "연결된 풀 리퀘스트 표시", + "abbbacfec60327d7": "연결된 항목 표시", "67f5b13c3c7bcd40": "게스트와 공유", "82da5b8b340217ac": "에이전트 세션 다시 시작", "963d099509eabcd6": "에이전트 세션이 다시 시작됩니다", @@ -2256,13 +2256,13 @@ "a3aa1e49af278d41": "파일은 프로젝트가 열려 있을 때만 사용할 수 있습니다.", "87ea6995ea1e7aa4": "변경 사항은 Git 저장소의 서버 스레드에서만 사용할 수 있습니다.", "4a87cae01ccde544": "이 스레드의 브랜치에 아직 풀 리퀘스트가 없습니다.", - "0051e6585d7ea014": "이 스레드에 연결된 풀 리퀘스트가 없습니다.", + "32535dba0b9af642": "이 스레드에 연결된 항목이 없습니다.", "07080dead70f4cc5": "기기는 스레드에서만 사용할 수 있습니다.", "a4bf49b31758ff7e": "데스크톱 앱에서만 사용할 수 있습니다.", "e917841cb66f9af1": "프로젝트가 열려 있을 때 사용할 수 있습니다.", "14c15fad0c2ee0c8": "Git 저장소에서 사용할 수 있습니다.", "9176276c78f3893f": "이 브랜치에 아직 풀 리퀘스트가 없습니다.", - "713aa4c9c08f042b": "연결된 풀 리퀘스트가 없습니다.", + "52ce9db6fb62a59f": "연결된 항목이 없습니다.", "e5d6f41e4fe4efd6": "스레드에서 사용할 수 있습니다.", "0ebc2bb883a8e283": "첫 메시지 후에 사용할 수 있습니다.", "84d0ff8fb9846057": "탭 음소거 해제", @@ -2272,11 +2272,11 @@ "cba3e832ece50257": "파일", "83ac3423d6dfc4a7": "변경 사항", "da16af47eff38ae9": "풀 리퀘스트", + "ad3929f0103925d7": "연결된 항목", "ac0de2a59d9c8860": "기기", "1354df9fb7278843": "iOS 시뮬레이터나 Android 에뮬레이터를 봅니다.", "4bcfa3b976a421cf": "사이드 채팅", "fdcd9643e2e63b15": "이 스레드가 계속 작업하는 동안 곁가지 질문을 하세요.", - "13087312bc6a0b45": "풀 리퀘스트", "314cfeebf191ba0d": "승인 필요", "4e5b7363441a3831": "입력 필요", "97af4e74a5f95e5e": "실행 중", @@ -3291,6 +3291,7 @@ "249192edde7f4932": "언어 검색", "71d8b593668d2106": "일치하는 언어가 없습니다.", "326bc17df66a7f05": "파일 및 폴더", + "13087312bc6a0b45": "풀 리퀘스트", "0e83c3bf28f8958e": "명령", "75d18dac06f4f037": "스킬", "05340d7dfcc34edf": "앱", @@ -3966,6 +3967,7 @@ ], "e58a1d884fa1d8f2": "스레드 세부 정보", "02d9667ff2c8e0b8": "이슈 {key}: {title}", + "4276743ee60a3c62": "{count, plural, other {댓글 {count}개}}", "42f634397f3960aa": "스레드 세부 정보에 표시", "e3738ef0423ddfe7": "기본값으로 재설정", "ae10d34e11064fec": "버전 관리", @@ -6692,7 +6694,6 @@ "c0257180840458bc": "{count, plural, =1 {해결된 대화} other {해결된 대화 {count}개}}", "9e65f6bc12538296": "해결됨", "d74fc95719fe5478": "열림", - "4276743ee60a3c62": "{count, plural, other {댓글 {count}개}}", "79ae43d8b6d1cce4": "댓글 편집", "1eadc7b869a55c68": "댓글 더 불러오기", "3f9bc820dffd099f": "답글", @@ -6949,13 +6950,15 @@ "ed09d936d8ba9792": "지켜보기 중지", "af6adbd67cef13b1": "변경 사항 지켜보기", "13eb3e529a3e9bff": "스레드에서 제외", - "93cebe7fdcc9821e": "연결된 풀 리퀘스트를 사용할 수 없음", - "47c92b77099a6346": "이 환경은 여러 풀 리퀘스트 연결을 지원하지 않습니다.", + "b872b70a1387351a": "연결된 항목을 사용할 수 없음", + "ff700a2d719110d8": "스레드의 환경을 사용할 수 없습니다.", + "b935e8d2dad4d8ba": "연결된 이슈", "e18c90152452a50e": "{openCount, plural, other {{openCount}개 열림}} · {linkCount, plural, other {{linkCount}개 연결됨}}", "106c1bf3308a8c33": "지켜보는 중: 검사가 끝나거나, 누군가 댓글을 달거나, 브랜치가 충돌하면 에이전트가 깨어납니다", "15a560968264b0ed": "열기", "a4e0e1e0bad3dcd8": "연결된 풀 리퀘스트 없음", "973b668999e33451": "에이전트가 이 스레드에서 연 풀 리퀘스트가 여기에 표시됩니다. URL이나 번호로 직접 연결할 수도 있습니다.", + "24303a7d08e18647": "이슈", "f034c05267f161ce": [ { "i": 1, @@ -6965,7 +6968,7 @@ " ", "동기화됨" ], - "74da2dae824a4573": "연결", + "7d160729d1afcd58": "풀 리퀘스트 연결", "2b82c15cd4dc73c6": "확인한 파일을 업데이트할 수 없습니다", "f85cd11cb736771c": "체크아웃했지만 최신 커밋인지 확인되지 않음", "406f2d0ee4df0b37": "이 체크아웃이 {term, select, mr {병합 요청의} cr {변경 요청의} other {풀 리퀘스트의}} 최신 커밋인지 확인할 수 없어 코드가 다를 수 있습니다. 로컬 커밋이나 커밋하지 않은 작업이 있으면 체크아웃이 현재 위치에 유지됩니다.", @@ -11578,6 +11581,8 @@ "37ffec8201f153c1": "실패", "984b361806ce8d25": "깨어남", "c6e8abc00ae470d2": "완료", + "f31a95961de19433": "이슈 {key}: {title}, {state}", + "2dd9d295c882ef65": "{count, plural, other {연결된 이슈 {count}개}}", "8cf699ae75fd8067": "고정됨", "be451f475c514b37": "깨어남 알림 닫기", "e9ced65134f2f36c": "지금 스레드 깨우기", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 75d7b6c3eaf07..f319ee85e554f 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -1708,7 +1708,7 @@ "9e9201570bcc2be8": "Copiar link do PR", "a1fcc064a5cece14": "Copiar thread", "2eb493c9e7a5fe9a": "Vincular pull request à thread", - "bf066df32c752202": "Mostrar pull requests vinculados", + "abbbacfec60327d7": "Mostrar itens vinculados", "67f5b13c3c7bcd40": "Compartilhar com convidado", "82da5b8b340217ac": "Reiniciar a sessão do agente", "963d099509eabcd6": "A sessão do agente será reiniciada", @@ -2257,13 +2257,13 @@ "a3aa1e49af278d41": "Os arquivos só estão disponíveis com um projeto aberto.", "87ea6995ea1e7aa4": "O diff só está disponível para threads do servidor em repositórios Git.", "4a87cae01ccde544": "O branch desta thread ainda não tem pull request.", - "0051e6585d7ea014": "Nenhum pull request vinculado disponível para esta thread.", + "32535dba0b9af642": "Esta thread não tem itens vinculados.", "07080dead70f4cc5": "Os dispositivos só estão disponíveis a partir de uma thread.", "a4bf49b31758ff7e": "Disponível só no app para desktop.", "e917841cb66f9af1": "Disponível com um projeto aberto.", "14c15fad0c2ee0c8": "Disponível para repositórios Git.", "9176276c78f3893f": "Ainda não há pull request neste branch.", - "713aa4c9c08f042b": "Nenhum pull request vinculado disponível.", + "52ce9db6fb62a59f": "Nenhum item vinculado disponível.", "e5d6f41e4fe4efd6": "Disponível a partir de uma thread.", "0ebc2bb883a8e283": "Disponível após a primeira mensagem.", "84d0ff8fb9846057": "Ativar som da aba", @@ -2273,11 +2273,11 @@ "cba3e832ece50257": "Arquivos", "83ac3423d6dfc4a7": "Diff", "da16af47eff38ae9": "Pull request", + "ad3929f0103925d7": "Itens vinculados", "ac0de2a59d9c8860": "Dispositivo", "1354df9fb7278843": "Acompanhe um iOS Simulator ou Android Emulator.", "4bcfa3b976a421cf": "Chat paralelo", "fdcd9643e2e63b15": "Faça uma pergunta paralela enquanto esta thread continua trabalhando.", - "13087312bc6a0b45": "Pull requests", "314cfeebf191ba0d": "precisa de aprovação", "4e5b7363441a3831": "precisa de resposta", "97af4e74a5f95e5e": "em execução", @@ -3295,6 +3295,7 @@ "249192edde7f4932": "Pesquisar linguagens", "71d8b593668d2106": "Nenhuma linguagem correspondente.", "326bc17df66a7f05": "Arquivos e pastas", + "13087312bc6a0b45": "Pull requests", "0e83c3bf28f8958e": "Comandos", "75d18dac06f4f037": "Skills", "05340d7dfcc34edf": "App", @@ -3978,6 +3979,7 @@ ], "e58a1d884fa1d8f2": "Detalhes da thread", "02d9667ff2c8e0b8": "Issue {key}: {title}", + "4276743ee60a3c62": "{count, plural, one {{count} comentário} other {{count} comentários}}", "42f634397f3960aa": "Mostrar nos detalhes da thread", "e3738ef0423ddfe7": "Redefinir para o padrão", "ae10d34e11064fec": "Controle de versão", @@ -6719,7 +6721,6 @@ "c0257180840458bc": "{count, plural, =1 {Discussão resolvida} other {{count} discussões resolvidas}}", "9e65f6bc12538296": "Resolvida", "d74fc95719fe5478": "Aberta", - "4276743ee60a3c62": "{count, plural, one {{count} comentário} other {{count} comentários}}", "79ae43d8b6d1cce4": "Editar comentário", "1eadc7b869a55c68": "Carregar mais comentários", "3f9bc820dffd099f": "Resposta", @@ -6979,13 +6980,15 @@ "ed09d936d8ba9792": "Parar de acompanhar", "af6adbd67cef13b1": "Acompanhar alterações", "13eb3e529a3e9bff": "Dispensar da thread", - "93cebe7fdcc9821e": "Pull requests vinculados indisponíveis", - "47c92b77099a6346": "Este ambiente não permite vários pull requests vinculados.", + "b872b70a1387351a": "Itens vinculados indisponíveis", + "ff700a2d719110d8": "O ambiente da thread não está disponível.", + "b935e8d2dad4d8ba": "Issues vinculadas", "e18c90152452a50e": "{openCount, plural, one {{openCount} aberto} other {{openCount} abertos}} · {linkCount, plural, one {{linkCount} vinculado} other {{linkCount} vinculados}}", "106c1bf3308a8c33": "Acompanhando: o agente é ativado quando as verificações terminam, alguém comenta ou o branch entra em conflito", "15a560968264b0ed": "Abrir", "a4e0e1e0bad3dcd8": "Nenhum pull request vinculado", "973b668999e33451": "Os pull requests que o agente abrir a partir desta thread aparecem aqui. Vincule um você mesmo por URL ou número.", + "24303a7d08e18647": "Issues", "f034c05267f161ce": [ "sincronizado", " ", @@ -6995,7 +6998,7 @@ "v": "v" } ], - "74da2dae824a4573": "Vincular", + "7d160729d1afcd58": "Vincular pull request", "2b82c15cd4dc73c6": "Não foi possível atualizar os arquivos vistos", "f85cd11cb736771c": "Checkout feito, mas não confirmado no commit mais recente", "406f2d0ee4df0b37": "Não foi possível confirmar este checkout no commit mais recente {term, select, mr {do merge request} cr {da solicitação de alteração} other {do pull request}}, então o código pode ser diferente. Commits locais ou trabalho sem commit mantêm um checkout onde ele está.", @@ -11630,6 +11633,8 @@ "37ffec8201f153c1": "Falhou", "984b361806ce8d25": "Despertou", "c6e8abc00ae470d2": "Pronta", + "f31a95961de19433": "Issue {key}: {title}, {state}", + "2dd9d295c882ef65": "{count, plural, one {{count} issue vinculada} other {{count} issues vinculadas}}", "8cf699ae75fd8067": "Fixadas", "be451f475c514b37": "Dispensar notificação de despertar", "e9ced65134f2f36c": "Despertar thread agora", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 9eedde5b11474..e43665a09699f 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -1708,7 +1708,7 @@ "9e9201570bcc2be8": "Копировать ссылку на PR", "a1fcc064a5cece14": "Копировать тред", "2eb493c9e7a5fe9a": "Привязать пул-реквест к треду", - "bf066df32c752202": "Показать привязанные пул-реквесты", + "abbbacfec60327d7": "Показать привязанные элементы", "67f5b13c3c7bcd40": "Поделиться с гостем", "82da5b8b340217ac": "Перезапустить сеанс агента", "963d099509eabcd6": "Сеанс агента будет перезапущен", @@ -2257,13 +2257,13 @@ "a3aa1e49af278d41": "Файлы доступны, только когда открыт проект.", "87ea6995ea1e7aa4": "Дифф доступен только для серверных тредов в Git-репозиториях.", "4a87cae01ccde544": "У ветки этого треда пока нет пул-реквеста.", - "0051e6585d7ea014": "Для этого треда нет привязанных пул-реквестов.", + "32535dba0b9af642": "У этого треда нет привязанных элементов.", "07080dead70f4cc5": "Устройства доступны только из треда.", "a4bf49b31758ff7e": "Доступно только в десктопном приложении.", "e917841cb66f9af1": "Доступно, когда открыт проект.", "14c15fad0c2ee0c8": "Доступно для Git-репозиториев.", "9176276c78f3893f": "В этой ветке пока нет пул-реквеста.", - "713aa4c9c08f042b": "Нет привязанных пул-реквестов.", + "52ce9db6fb62a59f": "Нет привязанных элементов.", "e5d6f41e4fe4efd6": "Доступно из треда.", "0ebc2bb883a8e283": "Доступно после первого сообщения.", "84d0ff8fb9846057": "Включить звук вкладки", @@ -2273,11 +2273,11 @@ "cba3e832ece50257": "Файлы", "83ac3423d6dfc4a7": "Дифф", "da16af47eff38ae9": "Пул-реквест", + "ad3929f0103925d7": "Привязанные элементы", "ac0de2a59d9c8860": "Устройство", "1354df9fb7278843": "Смотрите на iOS Simulator или Android Emulator.", "4bcfa3b976a421cf": "Боковой чат", "fdcd9643e2e63b15": "Задайте побочный вопрос, пока тред продолжает работу.", - "13087312bc6a0b45": "Пул-реквесты", "314cfeebf191ba0d": "нужно подтверждение", "4e5b7363441a3831": "нужен ввод", "97af4e74a5f95e5e": "выполняется", @@ -3295,6 +3295,7 @@ "249192edde7f4932": "Поиск языков", "71d8b593668d2106": "Нет подходящих языков.", "326bc17df66a7f05": "Файлы и папки", + "13087312bc6a0b45": "Пул-реквесты", "0e83c3bf28f8958e": "Команды", "75d18dac06f4f037": "Навыки", "05340d7dfcc34edf": "Приложение", @@ -3978,6 +3979,7 @@ ], "e58a1d884fa1d8f2": "Сведения о треде", "02d9667ff2c8e0b8": "Issue {key}: {title}", + "4276743ee60a3c62": "{count, plural, one {{count} комментарий} few {{count} комментария} many {{count} комментариев} other {{count} комментария}}", "42f634397f3960aa": "Показывать в сведениях о треде", "e3738ef0423ddfe7": "Сбросить по умолчанию", "ae10d34e11064fec": "Контроль версий", @@ -6719,7 +6721,6 @@ "c0257180840458bc": "{count, plural, =1 {Решённое обсуждение} one {{count} решённое обсуждение} few {{count} решённых обсуждения} many {{count} решённых обсуждений} other {{count} решённого обсуждения}}", "9e65f6bc12538296": "Решено", "d74fc95719fe5478": "Открыто", - "4276743ee60a3c62": "{count, plural, one {{count} комментарий} few {{count} комментария} many {{count} комментариев} other {{count} комментария}}", "79ae43d8b6d1cce4": "Изменить комментарий", "1eadc7b869a55c68": "Загрузить ещё комментарии", "3f9bc820dffd099f": "Ответ", @@ -6979,13 +6980,15 @@ "ed09d936d8ba9792": "Прекратить отслеживание", "af6adbd67cef13b1": "Отслеживать изменения", "13eb3e529a3e9bff": "Убрать из треда", - "93cebe7fdcc9821e": "Привязанные пул-реквесты недоступны", - "47c92b77099a6346": "Это окружение не поддерживает несколько привязанных пул-реквестов.", + "b872b70a1387351a": "Привязанные элементы недоступны", + "ff700a2d719110d8": "Окружение треда недоступно.", + "b935e8d2dad4d8ba": "Привязанные issues", "e18c90152452a50e": "{openCount, plural, one {{openCount} открыт} few {{openCount} открыто} many {{openCount} открыто} other {{openCount} открыто}} · {linkCount, plural, one {{linkCount} привязан} few {{linkCount} привязано} many {{linkCount} привязано} other {{linkCount} привязано}}", "106c1bf3308a8c33": "Отслеживается: агент проснётся, когда завершатся проверки, кто-то оставит комментарий или в ветке появится конфликт", "15a560968264b0ed": "Открыть", "a4e0e1e0bad3dcd8": "Нет привязанных пул-реквестов", "973b668999e33451": "Сюда попадают пул-реквесты, которые агент открывает из этого треда. Привяжите пул-реквест сами по URL или номеру.", + "24303a7d08e18647": "Issues", "f034c05267f161ce": [ "синхронизировано", " ", @@ -6995,7 +6998,7 @@ "v": "v" } ], - "74da2dae824a4573": "Привязать", + "7d160729d1afcd58": "Привязать пул-реквест", "2b82c15cd4dc73c6": "Не удалось обновить просмотренные файлы", "f85cd11cb736771c": "Переключено, но не подтверждено на последнем коммите", "406f2d0ee4df0b37": "{term, select, mr {Не удалось подтвердить, что этот checkout на последнем коммите мерж-реквеста, поэтому код может отличаться. Локальные коммиты или незакоммиченная работа оставляют checkout на месте.} cr {Не удалось подтвердить, что этот checkout на последнем коммите запроса на изменение, поэтому код может отличаться. Локальные коммиты или незакоммиченная работа оставляют checkout на месте.} other {Не удалось подтвердить, что этот checkout на последнем коммите пул-реквеста, поэтому код может отличаться. Локальные коммиты или незакоммиченная работа оставляют checkout на месте.}}", @@ -11631,6 +11634,8 @@ "37ffec8201f153c1": "Ошибка", "984b361806ce8d25": "Проснулся", "c6e8abc00ae470d2": "Готово", + "f31a95961de19433": "Задача {key}: {title}, {state}", + "2dd9d295c882ef65": "{count, plural, one {{count} связанная задача} few {{count} связанные задачи} many {{count} связанных задач} other {{count} связанной задачи}}", "8cf699ae75fd8067": "Закреплённые", "be451f475c514b37": "Скрыть уведомление о пробуждении", "e9ced65134f2f36c": "Разбудить тред сейчас", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 0b84b622d8ef4..d6a796b8b4cfa 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -1708,7 +1708,7 @@ "9e9201570bcc2be8": "Kopiera PR-länk", "a1fcc064a5cece14": "Kopiera tråd", "2eb493c9e7a5fe9a": "Länka pull request till tråd", - "bf066df32c752202": "Visa länkade pull requests", + "abbbacfec60327d7": "Visa länkade objekt", "67f5b13c3c7bcd40": "Dela med gäst", "82da5b8b340217ac": "Starta om agentsessionen", "963d099509eabcd6": "Agentsessionen startas om", @@ -2257,13 +2257,13 @@ "a3aa1e49af278d41": "Filer är bara tillgängliga när ett projekt är öppet.", "87ea6995ea1e7aa4": "Diff är bara tillgänglig för servertrådar i Git-repon.", "4a87cae01ccde544": "Den här trådens gren har ingen pull request än.", - "0051e6585d7ea014": "Inga länkade pull requests är tillgängliga för den här tråden.", + "32535dba0b9af642": "Den här tråden har inga länkade objekt.", "07080dead70f4cc5": "Enheter är bara tillgängliga från en tråd.", "a4bf49b31758ff7e": "Finns bara i skrivbordsappen.", "e917841cb66f9af1": "Tillgängligt när ett projekt är öppet.", "14c15fad0c2ee0c8": "Tillgängligt för Git-repon.", "9176276c78f3893f": "Ingen pull request på den här grenen än.", - "713aa4c9c08f042b": "Inga länkade pull requests tillgängliga.", + "52ce9db6fb62a59f": "Inga länkade objekt tillgängliga.", "e5d6f41e4fe4efd6": "Tillgängligt från en tråd.", "0ebc2bb883a8e283": "Tillgängligt efter det första meddelandet.", "84d0ff8fb9846057": "Slå på ljudet för fliken", @@ -2273,11 +2273,11 @@ "cba3e832ece50257": "Filer", "83ac3423d6dfc4a7": "Diff", "da16af47eff38ae9": "Pull request", + "ad3929f0103925d7": "Länkade objekt", "ac0de2a59d9c8860": "Enhet", "1354df9fb7278843": "Titta på en iOS-simulator eller Android-emulator.", "4bcfa3b976a421cf": "Sidochatt", "fdcd9643e2e63b15": "Ställ en sidofråga medan tråden fortsätter arbeta.", - "13087312bc6a0b45": "Pull requests", "314cfeebf191ba0d": "behöver godkännande", "4e5b7363441a3831": "behöver input", "97af4e74a5f95e5e": "körs", @@ -3295,6 +3295,7 @@ "249192edde7f4932": "Sök språk", "71d8b593668d2106": "Inga matchande språk.", "326bc17df66a7f05": "Filer och mappar", + "13087312bc6a0b45": "Pull requests", "0e83c3bf28f8958e": "Kommandon", "75d18dac06f4f037": "Färdigheter", "05340d7dfcc34edf": "App", @@ -3978,6 +3979,7 @@ ], "e58a1d884fa1d8f2": "Tråddetaljer", "02d9667ff2c8e0b8": "Ärende {key}: {title}", + "4276743ee60a3c62": "{count, plural, one {{count} kommentar} other {{count} kommentarer}}", "42f634397f3960aa": "Visa i tråddetaljer", "e3738ef0423ddfe7": "Återställ till standard", "ae10d34e11064fec": "Versionshantering", @@ -6725,7 +6727,6 @@ "c0257180840458bc": "{count, plural, =1 {Löst konversation} other {{count} lösta konversationer}}", "9e65f6bc12538296": "Löst", "d74fc95719fe5478": "Öppen", - "4276743ee60a3c62": "{count, plural, one {{count} kommentar} other {{count} kommentarer}}", "79ae43d8b6d1cce4": "Redigera kommentar", "1eadc7b869a55c68": "Läs in fler kommentarer", "3f9bc820dffd099f": "Svar", @@ -6985,13 +6986,15 @@ "ed09d936d8ba9792": "Sluta bevaka", "af6adbd67cef13b1": "Bevaka ändringar", "13eb3e529a3e9bff": "Avfärda från tråden", - "93cebe7fdcc9821e": "Länkade pull requests är inte tillgängliga", - "47c92b77099a6346": "Den här miljön stöder inte flera länkade pull requests.", + "b872b70a1387351a": "Länkade objekt är inte tillgängliga", + "ff700a2d719110d8": "Trådens miljö är inte tillgänglig.", + "b935e8d2dad4d8ba": "Länkade ärenden", "e18c90152452a50e": "{openCount, plural, one {{openCount} öppen} other {{openCount} öppna}} · {linkCount, plural, one {{linkCount} länkad} other {{linkCount} länkade}}", "106c1bf3308a8c33": "Bevakar: agenten vaknar när kontrollerna är klara, någon kommenterar eller grenen får konflikter", "15a560968264b0ed": "Öppna", "a4e0e1e0bad3dcd8": "Inga länkade pull requests", "973b668999e33451": "Pull requests som agenten öppnar från den här tråden hamnar här. Länka en själv från en URL eller ett nummer.", + "24303a7d08e18647": "Ärenden", "f034c05267f161ce": [ "synkad", " ", @@ -7001,7 +7004,7 @@ "v": "v" } ], - "74da2dae824a4573": "Länka", + "7d160729d1afcd58": "Länka pull request", "2b82c15cd4dc73c6": "Kunde inte uppdatera visade filer", "f85cd11cb736771c": "Utcheckad, men inte bekräftad på den senaste commiten", "406f2d0ee4df0b37": "Den här utcheckningen kunde inte bekräftas på den senaste commiten i {term, select, mr {merge requesten} cr {ändringsbegäran} other {pull requesten}}, så koden kan skilja sig. Lokala commits eller ocommittat arbete håller kvar en utcheckning där den är.", @@ -11639,6 +11642,8 @@ "37ffec8201f153c1": "Misslyckades", "984b361806ce8d25": "Väckt", "c6e8abc00ae470d2": "Klar", + "f31a95961de19433": "Ärende {key}: {title}, {state}", + "2dd9d295c882ef65": "{count, plural, one {{count} länkat ärende} other {{count} länkade ärenden}}", "8cf699ae75fd8067": "Fäst", "be451f475c514b37": "Stäng aviseringen Väckt", "e9ced65134f2f36c": "Väck tråden nu", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 5a8e6e2c6782f..d6e5cd9a62713 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -1708,7 +1708,7 @@ "9e9201570bcc2be8": "复制 PR 链接", "a1fcc064a5cece14": "复制会话", "2eb493c9e7a5fe9a": "为会话关联 PR", - "bf066df32c752202": "显示已关联的 PR", + "abbbacfec60327d7": "显示已关联项", "67f5b13c3c7bcd40": "与访客共享", "82da5b8b340217ac": "重启智能体会话", "963d099509eabcd6": "智能体会话将重启", @@ -2261,13 +2261,13 @@ "a3aa1e49af278d41": "打开项目后才能使用文件面板。", "87ea6995ea1e7aa4": "差异仅在 Git 仓库的服务器会话中可用。", "4a87cae01ccde544": "此会话的分支尚无 pull request。", - "0051e6585d7ea014": "此会话没有可用的已关联 pull request。", + "32535dba0b9af642": "此会话没有已关联项。", "07080dead70f4cc5": "设备仅在会话中可用。", "a4bf49b31758ff7e": "仅桌面应用可用。", "e917841cb66f9af1": "打开项目后可用。", "14c15fad0c2ee0c8": "仅适用于 Git 仓库。", "9176276c78f3893f": "此分支尚无 pull request。", - "713aa4c9c08f042b": "没有可用的已关联 pull request。", + "52ce9db6fb62a59f": "没有可用的已关联项。", "e5d6f41e4fe4efd6": "在会话中可用。", "0ebc2bb883a8e283": "发送第一条消息后可用。", "84d0ff8fb9846057": "取消标签静音", @@ -2277,11 +2277,11 @@ "cba3e832ece50257": "文件", "83ac3423d6dfc4a7": "差异", "da16af47eff38ae9": "PR", + "ad3929f0103925d7": "已关联项", "ac0de2a59d9c8860": "设备", "1354df9fb7278843": "查看 iOS 模拟器或 Android 模拟器。", "4bcfa3b976a421cf": "侧聊", "fdcd9643e2e63b15": "在会话继续运行的同时追问一个旁支问题。", - "13087312bc6a0b45": "PR", "314cfeebf191ba0d": "待批准", "4e5b7363441a3831": "待输入", "97af4e74a5f95e5e": "运行中", @@ -3300,6 +3300,7 @@ "249192edde7f4932": "搜索语言", "71d8b593668d2106": "没有匹配的语言。", "326bc17df66a7f05": "文件和文件夹", + "13087312bc6a0b45": "PR", "0e83c3bf28f8958e": "命令", "75d18dac06f4f037": "技能", "05340d7dfcc34edf": "应用", @@ -3983,6 +3984,7 @@ ], "e58a1d884fa1d8f2": "会话详情", "02d9667ff2c8e0b8": "issue {key}:{title}", + "4276743ee60a3c62": "{count, plural, other {{count} 条评论}}", "42f634397f3960aa": "在会话详情中显示", "e3738ef0423ddfe7": "恢复默认值", "ae10d34e11064fec": "版本控制", @@ -6733,7 +6735,6 @@ "c0257180840458bc": "{count, plural, =1 {已解决的对话} other {{count} 个已解决的对话}}", "9e65f6bc12538296": "已解决", "d74fc95719fe5478": "未解决", - "4276743ee60a3c62": "{count, plural, other {{count} 条评论}}", "79ae43d8b6d1cce4": "编辑评论", "1eadc7b869a55c68": "加载更多评论", "3f9bc820dffd099f": "回复", @@ -6994,13 +6995,15 @@ "ed09d936d8ba9792": "停止关注", "af6adbd67cef13b1": "关注更改", "13eb3e529a3e9bff": "从会话中忽略", - "93cebe7fdcc9821e": "已关联的 PR 不可用", - "47c92b77099a6346": "此环境不支持关联多个 pull request。", + "b872b70a1387351a": "已关联项不可用", + "ff700a2d719110d8": "此会话的环境不可用。", + "b935e8d2dad4d8ba": "已关联的 issue", "e18c90152452a50e": "{openCount, plural, other {{openCount} 个开放}} · {linkCount, plural, other {{linkCount} 个已关联}}", "106c1bf3308a8c33": "关注中:检查完成、有人评论或分支出现冲突时,智能体会被唤醒", "15a560968264b0ed": "打开", "a4e0e1e0bad3dcd8": "没有已关联的 PR", "973b668999e33451": "智能体从本会话打开的 pull request 会显示在这里。你也可以通过 URL 或编号自行关联。", + "24303a7d08e18647": "issue", "f034c05267f161ce": [ "同步于", " ", @@ -7010,7 +7013,7 @@ "v": "v" } ], - "74da2dae824a4573": "关联", + "7d160729d1afcd58": "关联 PR", "2b82c15cd4dc73c6": "无法更新已查看的文件", "f85cd11cb736771c": "已检出,但未确认是否为最新提交", "406f2d0ee4df0b37": "无法确认此工作副本位于该 {term, select, mr {merge request} cr {change request} other {pull request}} 的最新提交,因此其代码可能不同。本地提交或未提交的工作会使工作副本保持在原位置。", @@ -11655,6 +11658,8 @@ "37ffec8201f153c1": "失败", "984b361806ce8d25": "已唤醒", "c6e8abc00ae470d2": "完成", + "f31a95961de19433": "议题 {key}:{title},{state}", + "2dd9d295c882ef65": "{count, plural, other {{count} 个关联议题}}", "8cf699ae75fd8067": "已置顶", "be451f475c514b37": "忽略已唤醒通知", "e9ced65134f2f36c": "立即唤醒会话", diff --git a/apps/web/src/state/issues.ts b/apps/web/src/state/issues.ts index 1d384d7f9e9a1..16679aa25f1c7 100644 --- a/apps/web/src/state/issues.ts +++ b/apps/web/src/state/issues.ts @@ -7,16 +7,37 @@ import { type MergedIssueList, } from "@t3tools/client-runtime/state/issues"; import { useAtomValue } from "@effect/atom-react"; -import type { EnvironmentId } from "@t3tools/contracts"; +import type { EnvironmentId, ThreadIssueLink } from "@t3tools/contracts"; import { connectionAtomRuntime } from "../connection/runtime"; import { appAtomRegistry } from "../rpc/atomRegistry"; -import { formatEnvironmentQueryError } from "./query"; +import { useServerConfigs } from "./entities"; +import { formatEnvironmentQueryError, useEnvironmentQuery } from "./query"; export type { IssueListTarget }; export const issueEnvironment = createIssueEnvironmentAtoms(connectionAtomRuntime); +export function useLinkedIssueDetail( + environmentId: EnvironmentId, + link: ThreadIssueLink | undefined, + mountScope?: "sidebar" | "thread-details" | "linked-items" | "sidebar-tooltip", +) { + const configs = useServerConfigs(); + const input = link && { + projectId: link.projectId, + tracker: link.tracker, + host: link.host, + scope: link.scope, + key: link.key, + }; + return useEnvironmentQuery( + input && configs.get(environmentId)?.environment.capabilities.issues === true + ? issueEnvironment.detail({ environmentId, input }, mountScope) + : null, + ).data; +} + const mergedIssueLists = createMergedIssueListAtoms( issueEnvironment.list, formatEnvironmentQueryError, diff --git a/apps/web/test/fakeEnvironment.ts b/apps/web/test/fakeEnvironment.ts index 00cae2abfc567..3146de25b1c45 100644 --- a/apps/web/test/fakeEnvironment.ts +++ b/apps/web/test/fakeEnvironment.ts @@ -103,9 +103,15 @@ export const CLAUDE_PROVIDER = { }; const decodeServerConfig = Schema.decodeUnknownSync(ServerConfig); -const makeServerConfig = (providers: ReadonlyArray): ServerConfig => ({ +const makeServerConfig = ( + providers: ReadonlyArray, + supportsIssues = false, +): ServerConfig => ({ ...decodeServerConfig({ - environment: descriptor, + environment: { + ...descriptor, + capabilities: { ...descriptor.capabilities, issues: supportsIssues }, + }, auth, cwd: "/workspace/render", keybindingsConfigPath: "/workspace/.t3/keybindings.json", @@ -229,6 +235,7 @@ export interface FakeThread { readonly modelSelection?: ModelSelection; /** The first is the thread's active provider thread. */ readonly providerThreads?: ReadonlyArray; + readonly issues?: OrchestrationV2ThreadShell["issues"]; readonly runs: ReadonlyArray; readonly items: ReadonlyArray; readonly runtimeRequests?: OrchestrationV2ThreadProjection["runtimeRequests"]; @@ -316,6 +323,7 @@ function shellOf(thread: FakeThread): OrchestrationV2ThreadShell { branch: "main", worktreePath: null, activeProviderThreadId: thread.providerThreads?.[0]?.id ?? null, + ...(thread.issues === undefined ? {} : { issues: thread.issues }), lineage: { rootThreadId: thread.sideChatOf ?? thread.id, parentThreadId: thread.sideChatOf ?? null, @@ -599,7 +607,10 @@ export function installFakeEnvironment( ): Disposable { threads = fixtures; baseServerConfig = { - ...makeServerConfig(options?.providers ?? [CODEX_PROVIDER]), + ...makeServerConfig( + options?.providers ?? [CODEX_PROVIDER], + fixtures.some((thread) => (thread.issues?.length ?? 0) > 0), + ), keybindings: options?.keybindings ?? DEFAULT_RESOLVED_KEYBINDINGS, }; dispatched = []; diff --git a/docs/user/source-control.md b/docs/user/source-control.md index 5acbac0e22be4..b498a098276c1 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -312,7 +312,7 @@ and their marks follow the same rules as on web and desktop. ## Linked pull requests A thread can hold several pull requests, including reviews from another repository on the same host. -Use **Link pull request** in the command palette or **Linked pull requests** panel, or right-click a +Use **Link pull request** in the command palette or **Linked items** panel, or right-click a pull request link in the conversation. Creating a pull request from Git actions links it automatically, and so does an agent creating one with `gh pr create` or `glab mr create`. Agents can link other pull requests with the `link_pull_request` tool. @@ -322,10 +322,10 @@ on the Pull requests page, **Link to thread** lets you search for an active thre also lists the threads that link to it, including archived threads, so you can return to their context. Thread badges show a stack's layer count or the current review number with a count of additional -links. Clicking a badge with more than one review opens the **Linked pull requests** panel. On mobile, the Git overview lists linked reviews and their stacks; tap a review to open it. +links. Clicking a badge with more than one review opens the **Linked items** panel. On mobile, the Git overview lists linked reviews and their stacks; tap a review to open it. Linking and unlinking are available in the web and desktop clients. -The **Linked pull requests** panel lists every review and groups stacks. Unlink a review from its +The **Linked items** panel lists every review and groups stacks. Unlink a review from its row menu. An unlinked stack layer stays out of later syncs. Open linked reviews refresh on the server; closed reviews refresh periodically so reopening one on the host is detected. Merged reviews refresh when requested. Settling a thread refreshes its open and closed reviews once; after that they stop refreshing until you unsettle it. With **Auto-settle merged threads** enabled, a thread can settle after every linked @@ -343,7 +343,7 @@ failed reads in a row, or when you press Stop on the thread. A rate limit only p Settling or archiving a thread also ends all its watches. Unsettle the thread before starting a new watch. Watching a pull request again does not repeat check or conflict news its last watch already reported; unlinking the pull request clears that. Subagents cannot watch pull requests; the thread that delegated to them does. To start or stop -it yourself, use the row menu in the **Linked pull requests** panel. In the thread details card, a +it yourself, use the row menu in the **Linked items** panel. In the thread details card, a watched pull request shows an eye; click it to stop watching. A watched thread counts as working while the pull request still has checks running, so it stays in @@ -377,8 +377,9 @@ allow it. An issue read through a project that does not own its repository is sh An issue can be kept with a thread the way a pull request can: open it beside the thread (issue links in the conversation open there) and use **Link to this thread** in its header; **Unlink** -undoes it. Linked issues are listed in the thread's details beside its pull requests. Agents link the -issues they work on with the `link_issue` tool. +undoes it. Click the issue badge in the thread sidebar to see its issues and pull requests in +**Linked items**. Select an issue there to open it beside the thread. Agents link the issues they +work on with the `link_issue` tool. Writing to a tracker over a remote connection requires the `source-control:write` scope. diff --git a/packages/client-runtime/src/state/runtime.test.ts b/packages/client-runtime/src/state/runtime.test.ts index 97b5750872986..59093d2d9dbdc 100644 --- a/packages/client-runtime/src/state/runtime.test.ts +++ b/packages/client-runtime/src/state/runtime.test.ts @@ -1240,7 +1240,7 @@ describe("environment query lifecycle", () => { }), ); - it.effect("refetches when mounted again after its stale time, while still cached", () => + it.effect("refetches a stale query on remount while another view keeps the cache live", () => Effect.gen(function* () { let now = 0; using _now = vi.spyOn(Date, "now").mockImplementation(() => now); @@ -1254,6 +1254,11 @@ describe("environment query lifecycle", () => { ); const registry = AtomRegistry.make(); yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose())); + const sidebar = harness.family( + { environmentId: QUERY_ENVIRONMENT.environmentId, input: undefined }, + "sidebar", + ); + registry.mount(sidebar); const read = readEnvironmentQuery(registry, harness.atom); const remount = Effect.gen(function* () { const unmount = registry.mount(harness.atom); @@ -1275,6 +1280,7 @@ describe("environment query lifecycle", () => { // Past the stale time, well inside the default 5 minute idle TTL. now = 61_000; expect(yield* remount).toBe("after edit"); + expect(yield* readEnvironmentQuery(registry, sidebar)).toBe("after edit"); expect(fetches).toBe(2); }), ); diff --git a/packages/client-runtime/src/state/runtime.ts b/packages/client-runtime/src/state/runtime.ts index baca378f5b11f..ac55aba2da28c 100644 --- a/packages/client-runtime/src/state/runtime.ts +++ b/packages/client-runtime/src/state/runtime.ts @@ -713,15 +713,14 @@ export function createEnvironmentQueryAtomFamily( | AtomRegistry.AtomRegistry | R >, -): (target: { - readonly environmentId: EnvironmentIdType; - readonly input: Input; -}) => Atom.Atom> { +): ( + target: { readonly environmentId: EnvironmentIdType; readonly input: Input }, + mountScope?: string, +) => Atom.Atom> { const connectionAtom = environmentConnectionAtoms(runtime); // `Atom.family` holds members weakly and the mounted layer has no TTL, so each member lives // as long as its cache: keyed weakly, this lets both go once the cache's TTL ends. - const membersByCache = new WeakMap, Atom.Atom>(); - const family = Atom.family((key: string) => { + const cacheFamily = Atom.family((key: string) => { const target = parseEnvironmentRpcKey(key); const idleTtlMs = options.idleTtlMs ?? 5 * 60_000; const queryAtom = runtime @@ -865,19 +864,31 @@ export function createEnvironmentQueryAtomFamily( ? queryAtom : queryAtom.pipe(refreshEveryUntilFinal(options.refreshIntervalMs, isFinal)); const refreshTrigger = options.refreshTrigger?.(target); - const cache = ( + return ( refreshTrigger === undefined ? intervalQuery : intervalQuery.pipe(refreshOnSignalWhileRead(refreshTrigger, isFinal)) ).pipe(Atom.setIdleTTL(idleTtlMs)); + }); + type QueryAtom = ReturnType; + const membersByCache = new WeakMap>(); + return (target, mountScope) => { + const key = environmentRpcKey(target); + const cache = cacheFamily(key); + let members = membersByCache.get(cache); + if (members === undefined) { + members = new Map(); + membersByCache.set(cache, members); + } + const existing = members.get(mountScope); + if (existing !== undefined) return existing; const member = cache.pipe( revalidateOnMount(options.staleTimeMs ?? 30_000), - Atom.withLabel(`${options.label}:${key}`), + Atom.withLabel(`${options.label}:${key}${mountScope === undefined ? "" : `:${mountScope}`}`), ); - membersByCache.set(cache, member); + members.set(mountScope, member); return member; - }); - return (target) => family(environmentRpcKey(target)); + }; } export function createEnvironmentSubscriptionAtomFamily( From b4239c4b231a90866b98bb49af1eb4e140462868 Mon Sep 17 00:00:00 2001 From: Jake Leventhal Date: Wed, 18 Nov 2026 19:24:19 -0500 Subject: [PATCH 065/183] feat(mobile): share a thread with a guest from the mobile app (#29391) Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks Co-authored-by: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> --- apps/mobile/src/Stack.tsx | 5 + .../src/features/keyboard/CommandPalette.tsx | 12 + .../layout/workspace-overlay-routes.ts | 1 + .../features/threads/ThreadGuestShareBar.tsx | 4 +- .../threads/ThreadGuestShareSheet.test.tsx | 190 +++++++++++++ .../threads/ThreadGuestShareSheet.tsx | 265 ++++++++++++++++++ .../threads/guestShareAvailability.test.ts | 29 ++ .../threads/guestShareAvailability.ts | 17 ++ .../features/threads/thread-list-v2-items.tsx | 15 + .../features/threads/useCanShareWithGuest.ts | 17 ++ apps/mobile/src/i18n/translations/de.json | 18 ++ apps/mobile/src/i18n/translations/en.json | 18 ++ apps/mobile/src/i18n/translations/es.json | 18 ++ apps/mobile/src/i18n/translations/fr.json | 18 ++ apps/mobile/src/i18n/translations/ja.json | 18 ++ apps/mobile/src/i18n/translations/ko.json | 18 ++ apps/mobile/src/i18n/translations/pt-BR.json | 18 ++ apps/mobile/src/i18n/translations/ru.json | 18 ++ apps/mobile/src/i18n/translations/sv.json | 18 ++ apps/mobile/src/i18n/translations/zh.json | 18 ++ apps/mobile/vite.config.ts | 1 + .../src/orchestration-v2/GuestShare.test.ts | 13 + .../src/orchestration-v2/GuestShareDecider.ts | 3 + docs/user/guest-links.md | 5 +- 24 files changed, 753 insertions(+), 4 deletions(-) create mode 100644 apps/mobile/src/features/threads/ThreadGuestShareSheet.test.tsx create mode 100644 apps/mobile/src/features/threads/ThreadGuestShareSheet.tsx create mode 100644 apps/mobile/src/features/threads/guestShareAvailability.test.ts create mode 100644 apps/mobile/src/features/threads/guestShareAvailability.ts create mode 100644 apps/mobile/src/features/threads/useCanShareWithGuest.ts diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index ca77e1e641d7f..36dff4292681f 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -68,6 +68,7 @@ import { GitConfirmSheet } from "./features/threads/git/GitConfirmSheet"; import { GitOverviewSheet } from "./features/threads/git/GitOverviewSheet"; import { ThreadPullRequestsSheet } from "./features/threads/ThreadPullRequestsSheet"; import { ThreadAgentsSheet } from "./features/threads/ThreadAgentsSheet"; +import { ThreadGuestShareSheet } from "./features/threads/ThreadGuestShareSheet"; import { ThreadBackgroundWorkSheet } from "./features/threads/ThreadBackgroundWorkSheet"; import { ThreadQueueSheet } from "./features/threads/ThreadQueueControl"; import { @@ -777,6 +778,10 @@ const RootStackConfig = createWorkspaceStackNavigator({ screen: ThreadAgentsSheet, options: sheetRoute({ detent: 0.5, androidMaxDetent: 0.9 }), }), + ThreadGuestShare: createNativeStackScreen({ + screen: ThreadGuestShareSheet, + options: sheetRoute({ detent: 0.5 }), + }), GitOverview: createNativeStackScreen({ screen: GitOverviewSheet, linking: `${THREAD_LINKING_PREFIX}/git`, diff --git a/apps/mobile/src/features/keyboard/CommandPalette.tsx b/apps/mobile/src/features/keyboard/CommandPalette.tsx index c2fb56359b86f..4be1c5d9032e8 100644 --- a/apps/mobile/src/features/keyboard/CommandPalette.tsx +++ b/apps/mobile/src/features/keyboard/CommandPalette.tsx @@ -54,6 +54,7 @@ import { } from "../../state/entities"; import { useThreadSearch } from "../../state/queries"; import { requestThreadMessageJump } from "../threads/threadMessageJump"; +import { useCanShareWithGuest } from "../threads/useCanShareWithGuest"; import { threadEnvironment } from "../../state/threads"; import { useAtomCommand } from "../../state/use-atom-command"; import { serverEnvironment } from "../../state/server"; @@ -290,6 +291,7 @@ export function CommandPalette(props: { useAtomValue(serverEnvironment.prepareTriage.permissionAtom(triageEnvironmentId)) && triageEnvironmentId !== null && serverConfigs.get(triageEnvironmentId)?.environment.capabilities.triage === true; + const canShareWithGuest = useCanShareWithGuest(activeThreadRef?.environmentId ?? null); const contentMatchByKey = new Map( search.matches .filter((match) => match.source === "user" || match.source === "assistant") @@ -411,6 +413,15 @@ export function CommandPalette(props: { run: () => runCommand(command), })), ); + if (canShareWithGuest) { + actions.push({ + key: "shareWithGuest", + kind: "action", + title: gt("Share with guest"), + searchTerms: ["share", "guest", "invite", "link", "teammate"], + run: () => navigation.navigate("ThreadGuestShare", activeThreadRef), + }); + } } const openProjects = projects.filter((project) => project.archivedAt == null); const projectItems: CommandPaletteItem[] = [ @@ -488,6 +499,7 @@ export function CommandPalette(props: { activeThreadRef, environments.length, canTriage, + canShareWithGuest, navigation, projects, runCommand, diff --git a/apps/mobile/src/features/layout/workspace-overlay-routes.ts b/apps/mobile/src/features/layout/workspace-overlay-routes.ts index 0e8a009995063..592e5ce4eb6ea 100644 --- a/apps/mobile/src/features/layout/workspace-overlay-routes.ts +++ b/apps/mobile/src/features/layout/workspace-overlay-routes.ts @@ -29,6 +29,7 @@ const LISTED_OVERLAY_ROUTES: ReadonlySet = new Set([ "SettingsWaitlist", "ThreadAgents", "ThreadBackgroundWork", + "ThreadGuestShare", "ThreadPullRequests", "ThreadQueue", "ThreadReviewComment", diff --git a/apps/mobile/src/features/threads/ThreadGuestShareBar.tsx b/apps/mobile/src/features/threads/ThreadGuestShareBar.tsx index 035312a22f5a2..16a23b253be9c 100644 --- a/apps/mobile/src/features/threads/ThreadGuestShareBar.tsx +++ b/apps/mobile/src/features/threads/ThreadGuestShareBar.tsx @@ -57,8 +57,8 @@ function alertOnFailure(failureTitle: string, result: AtomCommandResult ({ + Slot: ({ children }: { children?: ReactNode }) => children, + created: { + share: undefined as ThreadGuestShare | null | undefined, + updatedAt: "1970-01-01T00:00:00.000Z", + command: vi.fn(), + }, + sharing: { messages: [] as Array<{ status: "pending" | "dismissed" }> }, +})); + +vi.mock("react-native", () => ({ + Platform: { OS: "ios" }, + ScrollView: Slot, + View: Slot, + Share: {}, +})); +vi.mock("@react-navigation/native", () => ({ + useNavigation: () => ({ goBack: () => {} }), + usePreventRemove: () => {}, +})); +vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ bottom: 0 }) })); +vi.mock("@effect/atom-react", () => ({ + useAtomValue: (atom: { value: unknown }, select?: (value: unknown) => unknown) => + select + ? select(atom.value) + : atom.value === "thread" + ? { projection: { thread: { updatedAt: DateTime.makeUnsafe(created.updatedAt) } } } + : atom.value, +})); +vi.mock("../../state/server", () => ({ + serverEnvironment: { createGuestShare: { permissionAtom: () => ({ value: true }) } }, + environmentServerConfigsAtom: {}, +})); +vi.mock("../../state/threads", () => ({ + environmentThreadDetails: { + threadAtom: () => ({ value: "thread" }), + statusAtom: () => ({ value: "ready" }), + errorAtom: () => ({ value: null }), + }, +})); +vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => created.command })); +vi.mock("./ThreadGuestShareBar", () => ({ + useThreadGuestShare: () => + created.share !== undefined + ? created.share + : { + guestName: null, + expiresAt: "1970-01-01T00:00:01.000Z", + messages: sharing.messages, + }, +})); +vi.mock("../../components/ui/AppText", () => ({ AppText: Slot })); +vi.mock("../../components/ui/Button", () => ({ + Button: ({ + label, + disabled, + onPress, + }: { + label: string; + disabled?: boolean; + onPress?: () => void; + }) => ( + + ), +})); +vi.mock("../../components/ui/AppSymbol", () => ({ SymbolView: () => null })); +vi.mock("../../components/ui/AppBar", () => ({ AppBar: () => null })); +vi.mock("../../components/ui/SheetHeader", () => ({ SheetHeader: () => null })); +vi.mock("../../components/ui/ScreenContent", () => ({ ScreenContent: Slot })); +vi.mock("../../components/ui/Dialog", () => ({})); +vi.mock("../../native/StackHeader", () => ({ NativeStackScreenOptions: () => null })); +vi.mock("../../lib/copyTextWithHaptic", () => ({ tryCopyTextWithHaptic: () => true })); + +import { ThreadGuestShareSheet } from "./ThreadGuestShareSheet"; + +it("stops treating a retained guest link as active when it expires", async () => { + sharing.messages = []; + created.share = undefined; + vi.useFakeTimers(); + vi.setSystemTime(0); + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + const container = document.createElement("div"); + const root = createRoot(container); + const renderSheet = () => + root.render( + , + ); + try { + await act(renderSheet); + expect(container.textContent).toContain("A guest link is active."); + expect(container.querySelector("button")?.textContent).toBe("Create new link"); + + await act(() => vi.advanceTimersByTimeAsync(1000)); + + expect(container.textContent).not.toContain("A guest link is active."); + expect(container.querySelector("button")?.textContent).toBe("Create link"); + sharing.messages = [{ status: "pending" }]; + await act(renderSheet); + expect(container.querySelector("button")?.disabled).toBe(true); + expect(container.textContent).toContain("Send or dismiss pending guest messages"); + + sharing.messages = [{ status: "dismissed" }]; + await act(renderSheet); + expect(container.querySelector("button")?.disabled).toBe(false); + } finally { + act(() => root.unmount()); + vi.useRealTimers(); + vi.unstubAllGlobals(); + } +}); + +it.each(["expired", "stopped", "replaced", "redeemed"] as const)( + "hides a created link after it is %s, while keeping it through projection catch-up", + async (change) => { + created.share = undefined; + created.updatedAt = "1970-01-01T00:00:00.000Z"; + sharing.messages = []; + const share: ThreadGuestShare = { + id: GuestShareId.make("created"), + host: "env.t3.test", + createdAt: "1970-01-01T00:00:00.100Z", + expiresAt: "1970-01-01T00:00:01.000Z", + guestName: null, + messages: [], + }; + const url = "https://env.t3.test/guest#invite"; + created.command.mockResolvedValue({ _tag: "Success", value: { url, share } }); + vi.useFakeTimers(); + vi.setSystemTime(0); + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + const container = document.createElement("div"); + const root = createRoot(container); + const renderSheet = () => + root.render( + , + ); + try { + await act(renderSheet); + await act(async () => container.querySelector("button")!.click()); + expect(container.textContent).toContain(url); + created.share = share; + created.updatedAt = share.createdAt; + await act(renderSheet); + expect(container.textContent).toContain(url); + expect(container.textContent).toContain("Copy"); + if (change === "expired") { + await act(() => vi.advanceTimersByTimeAsync(1000)); + } else { + created.updatedAt = "1970-01-01T00:00:00.200Z"; + created.share = + change === "redeemed" + ? { ...share, guestName: "Sam" } + : { ...share, id: GuestShareId.make("other") }; + if (change === "stopped") created.share = null; + await act(renderSheet); + } + expect(container.textContent).not.toContain(url); + expect(container.textContent).not.toContain("Copy"); + expect(container.textContent).not.toContain("Share"); + } finally { + act(() => root.unmount()); + vi.useRealTimers(); + vi.unstubAllGlobals(); + created.command.mockReset(); + created.share = undefined; + } + }, +); diff --git a/apps/mobile/src/features/threads/ThreadGuestShareSheet.tsx b/apps/mobile/src/features/threads/ThreadGuestShareSheet.tsx new file mode 100644 index 0000000000000..d719183079f6b --- /dev/null +++ b/apps/mobile/src/features/threads/ThreadGuestShareSheet.tsx @@ -0,0 +1,265 @@ +import { useAtomValue } from "@effect/atom-react"; +import { useNavigation, usePreventRemove, type StaticScreenProps } from "@react-navigation/native"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import type { EnvironmentId, ThreadGuestShare, ThreadId } from "@t3tools/contracts"; +import { msg, T, useGT, useMessages } from "gt-react-native"; +import * as DateTime from "effect/DateTime"; +import { useMemo, useState } from "react"; +import { Platform, ScrollView, Share, View } from "react-native"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; + +import { AppBar } from "../../components/ui/AppBar"; +import { SymbolView } from "../../components/ui/AppSymbol"; +import { AppText as Text } from "../../components/ui/AppText"; +import { Button } from "../../components/ui/Button"; +import * as Dialog from "../../components/ui/Dialog"; +import { ScreenContent } from "../../components/ui/ScreenContent"; +import { SheetHeader } from "../../components/ui/SheetHeader"; +import { useDeadlinePassed } from "../../lib/clock"; +import { tryCopyTextWithHaptic } from "../../lib/copyTextWithHaptic"; +import { NativeStackScreenOptions } from "../../native/StackHeader"; +import { serverEnvironment } from "../../state/server"; +import { environmentThreadDetails } from "../../state/threads"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { useThreadGuestShare } from "./ThreadGuestShareBar"; + +const TITLE = msg("Share with guest"); +const COPY_FEEDBACK_DURATION_MS = 1200; +const PENDING_MESSAGES_NOTICE = msg( + "Send or dismiss pending guest messages in the thread before creating a new link.", +); + +type CreateState = + | { readonly status: "idle" } + | { readonly status: "creating" } + | { readonly status: "created"; readonly url: string; readonly share: ThreadGuestShare } + | { readonly status: "failed"; readonly message: string }; + +type GuestShareTarget = { readonly environmentId: EnvironmentId; readonly threadId: ThreadId }; + +export function ThreadGuestShareSheet({ route }: StaticScreenProps) { + const gt = useGT(); + const m = useMessages(); + const navigation = useNavigation(); + const insets = useSafeAreaInsets(); + const { environmentId, threadId } = route.params; + const threadRef = useMemo( + () => scopeThreadRef(environmentId, threadId), + [environmentId, threadId], + ); + const guestShare = useThreadGuestShare(threadRef); + const shareExpired = useDeadlinePassed( + guestShare === null ? null : Date.parse(guestShare.expiresAt), + ); + const activeShare = shareExpired ? null : guestShare; + const hasPendingMessages = + guestShare?.messages.some((message) => message.status === "pending") ?? false; + // From the thread list the detail loads only now; until it does, an active link is unknown and a + // new link would end it without the warning. + const thread = useAtomValue(environmentThreadDetails.threadAtom(threadRef)); + const threadLoaded = thread !== null; + const threadDeleted = useAtomValue( + environmentThreadDetails.statusAtom(threadRef), + (status) => status === "deleted", + ); + const threadLoadError = useAtomValue(environmentThreadDetails.errorAtom(threadRef)); + const canCreate = useAtomValue(serverEnvironment.createGuestShare.permissionAtom(environmentId)); + const createGuestShare = useAtomCommand(serverEnvironment.createGuestShare, { + reportFailure: false, + }); + const [state, setState] = useState({ status: "idle" }); + const [copiedAtMs, setCopiedAtMs] = useState(null); + const copyFeedbackEnded = useDeadlinePassed( + copiedAtMs === null ? null : copiedAtMs + COPY_FEEDBACK_DURATION_MS, + ); + const copied = copiedAtMs !== null && !copyFeedbackEnded; + const creating = state.status === "creating"; + const close = () => navigation.goBack(); + // The link is shown only once, so any dismiss mid-request (swipe, header, Android back) would lose it. + usePreventRemove(creating, () => {}); + + const create = async () => { + if (hasPendingMessages) { + Dialog.alert(gt("Guest messages are waiting"), m(PENDING_MESSAGES_NOTICE)); + return; + } + setState({ status: "creating" }); + const result = await createGuestShare({ environmentId, input: { threadId } }); + if (result._tag === "Success") { + setState({ status: "created", url: result.value.url, share: result.value.share }); + return; + } + if (isAtomCommandInterrupted(result)) { + setState({ status: "idle" }); + return; + } + const error = squashAtomCommandFailure(result); + setState({ + status: "failed", + message: error instanceof Error ? error.message : gt("Could not create a guest link."), + }); + }; + + const copy = async (url: string) => { + if (!(await tryCopyTextWithHaptic(url, { target: "guest link" }))) { + Dialog.alert(gt("Could not copy"), gt("Try again.")); + return; + } + setCopiedAtMs(Date.now()); + }; + + const share = (url: string) => { + // Android ignores `url`; iOS turns a `message` URL into plain text instead of a link preview. + Share.share(Platform.OS === "ios" ? { url } : { message: url }).catch((cause: unknown) => { + console.error("Failed to share guest link.", cause); + Dialog.alert(gt("Could not share the link"), gt("Copy it instead.")); + }); + }; + + const createdShareExpired = useDeadlinePassed( + state.status === "created" ? Date.parse(state.share.expiresAt) : null, + ); + const createdLink = + state.status === "created" && + !createdShareExpired && + !threadDeleted && + (thread === null || + DateTime.toEpochMillis(thread.projection.thread.updatedAt) < + Date.parse(state.share.createdAt) || + (activeShare?.id === state.share.id && activeShare.guestName === null)) + ? state + : null; + + const content = ( + + {createdLink !== null ? ( + <> + + + + {createdLink.url} + + + + Send it to one person. It works once and expires in 24 hours. + + + + + diff --git a/apps/web/src/state/issues.ts b/apps/web/src/state/issues.ts index 16679aa25f1c7..c92bf81154a12 100644 --- a/apps/web/src/state/issues.ts +++ b/apps/web/src/state/issues.ts @@ -46,9 +46,13 @@ const mergedIssueLists = createMergedIssueListAtoms( /** The same listing read across every connected environment, as the pull-request page does. */ export function useIssueList( targets: ReadonlyArray, -): MergedIssueList & { readonly refresh: () => void } { +): MergedIssueList & { readonly refresh: () => void; readonly retry: () => void } { const view = useAtomValue(mergedIssueLists.atom(targets)); - return { ...view, refresh: () => mergedIssueLists.refresh(appAtomRegistry, targets) }; + return { + ...view, + refresh: () => mergedIssueLists.refresh(appAtomRegistry, targets), + retry: () => mergedIssueLists.retry(appAtomRegistry, targets), + }; } /** After a write made beside the list, such as a state change in the detail panel. */ diff --git a/packages/client-runtime/src/state/issues.test.ts b/packages/client-runtime/src/state/issues.test.ts index 7c52da1c5004b..587280be65912 100644 --- a/packages/client-runtime/src/state/issues.test.ts +++ b/packages/client-runtime/src/state/issues.test.ts @@ -218,6 +218,39 @@ describe("createMergedIssueListAtoms", () => { } }); + it("retries only failed environments, leaving one still loading to finish", () => { + const registry = AtomRegistry.make(); + const targets = ["slow", "flaky"].map((environmentId) => ({ + environmentId: EnvironmentId.make(environmentId), + input: { state: "open" as const }, + })); + const requests: string[] = []; + const lists = Atom.family((environmentId: string) => + Atom.make( + Effect.suspend(() => { + requests.push(environmentId); + return environmentId === "flaky" ? Effect.fail("Tracker unavailable") : Effect.never; + }), + ), + ); + const listings = createMergedIssueListAtoms( + (target) => lists(target.environmentId), + () => "Tracker unavailable", + ); + const view = listings.atom(targets); + const unmount = registry.mount(view); + try { + expect(registry.get(view)).toMatchObject({ error: "Tracker unavailable", isPending: true }); + + listings.retry(registry, targets); + + expect(requests).toEqual(["slow", "flaky", "flaky"]); + } finally { + unmount(); + registry.dispose(); + } + }); + it("releases historical search targets when the list closes", async () => { NodeV8.setFlagsFromString("--expose-gc"); const gc = NodeVM.runInNewContext("gc") as () => void; diff --git a/packages/client-runtime/src/state/issues.ts b/packages/client-runtime/src/state/issues.ts index ac87ed088f6ff..b48ec184a7c7e 100644 --- a/packages/client-runtime/src/state/issues.ts +++ b/packages/client-runtime/src/state/issues.ts @@ -281,10 +281,23 @@ export interface MergedIssueList { const NO_ISSUE_LISTS: MergedIssueList = { answers: [], error: null, isPending: false }; +function refreshFailed( + registry: AtomRegistry.AtomRegistry, + targets: ReadonlyArray, + query: (target: Target) => Atom.Atom>, +) { + for (const target of targets) { + const atom = query(target); + const result = registry.get(atom); + if (result._tag === "Failure" && !result.waiting) registry.refresh(atom); + } +} + /** * One listing read across every environment at once: React cannot subscribe to a list of atoms * whose length changes, so the fan-out lives in one derived atom keyed by the targets. An - * environment that fails contributes nothing rather than blanking the list. + * environment that fails contributes nothing rather than blanking the list. Retry reloads only + * the environments that failed, so a read still in flight elsewhere is not restarted. */ export function createMergedIssueListAtoms( list: (target: IssueListTarget) => Atom.Atom>, @@ -323,6 +336,8 @@ export function createMergedIssueListAtoms( return atom; }, refresh, + retry: (registry: AtomRegistry.AtomRegistry, targets: ReadonlyArray) => + refreshFailed(registry, targets, list), /** Refreshes each listing of `environmentId` that something still reads. */ refreshEnvironment: (registry: AtomRegistry.AtomRegistry, environmentId: EnvironmentId) => { for (const node of registry.getNodes().values()) { @@ -401,12 +416,7 @@ export function createMergedIssueCandidatesAtoms( return { atom: (targets: ReadonlyArray) => targets.length === 0 ? empty : family(JSON.stringify(targets)), - retry: (registry: AtomRegistry.AtomRegistry, targets: ReadonlyArray) => { - for (const target of targets) { - const atom = candidates(target); - const result = registry.get(atom); - if (result._tag === "Failure" && !result.waiting) registry.refresh(atom); - } - }, + retry: (registry: AtomRegistry.AtomRegistry, targets: ReadonlyArray) => + refreshFailed(registry, targets, candidates), }; } diff --git a/scripts/scenarios/issues-retry-keeps-pending-environment.e2e.ts b/scripts/scenarios/issues-retry-keeps-pending-environment.e2e.ts new file mode 100644 index 0000000000000..8cf489e4ca6c2 --- /dev/null +++ b/scripts/scenarios/issues-retry-keeps-pending-environment.e2e.ts @@ -0,0 +1,153 @@ +/// +import type { IssueListResult } from "@t3tools/contracts"; +import { expect } from "e2e"; + +import { SECOND_HOME, startSecondServer } from "./second-server.ts"; +import { makeState, test, WEB } from "./t3.ts"; + +test( + "Retrying a failed environment keeps the Issues refresh already in progress", + WEB, + async ({ t3, app, screen, browser }) => { + await t3.project("demo"); + const server = startSecondServer(app.baseUrl ?? ""); + try { + const { host, token } = await server.ready; + await makeState(SECOND_HOME).state.project("remote-demo"); + await browser.addInitScript((remoteHost) => { + const { promise: slowRead, resolve: release } = Promise.withResolvers(); + let refreshing = false; + let primaryRefreshStarted = false; + let remoteRefreshStarted = false; + Object.assign(window, { + armIssuesRefresh: () => { + refreshing = true; + }, + releaseSlowIssuesRead: release, + }); + const date = "2026-10-01T00:00:00.000Z"; + const tracker = "github" as IssueListResult["trackers"][number]["tracker"]; + const list = (title: string, remote: boolean): IssueListResult => { + const key = remote ? "2" : "1"; + return { + entries: [ + { + tracker, + host: "github.com", + scope: "example/demo", + key, + displayKey: "#" + key, + title, + projectId: (remote + ? "remote-demo" + : "demo") as IssueListResult["entries"][number]["projectId"], + projectTitle: remote ? "remote-demo" : "demo", + url: "https://github.com/example/demo/issues/" + key, + author: null, + state: { category: "open", name: "Open" }, + createdAt: date, + updatedAt: date, + closedAt: null, + assignees: [], + labels: [], + commentCount: 0, + }, + ], + errors: [], + nextCursors: {}, + viewers: {}, + trackers: [ + { + tracker, + host: "github.com", + projectCount: 1, + capabilities: null, + configured: true, + detail: null, + }, + ], + }; + }; + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (data) { + const request: { _tag: string; id: string; tag: string } | null = + typeof data === "string" ? JSON.parse(data) : null; + if (request?._tag !== "Request" || request.tag !== "issues.list") + return send.call(this, data); + const remote = new URL(this.url).host === remoteHost; + const reply = (exit: unknown) => + this.dispatchEvent( + new MessageEvent("message", { + data: JSON.stringify({ _tag: "Exit", requestId: request.id, exit }), + }), + ); + const success = (title: string) => reply({ _tag: "Success", value: list(title, remote) }); + + if (!refreshing) { + queueMicrotask(() => + success(remote ? "Issue from the linked environment" : "Before refresh"), + ); + } else if (remote && !remoteRefreshStarted) { + remoteRefreshStarted = true; + queueMicrotask(() => + reply({ + _tag: "Failure", + cause: [ + { + _tag: "Fail", + error: { + _tag: "IssueOperationError", + operation: "list", + detail: "The linked environment could not list issues.", + }, + }, + ], + }), + ); + } else if (remote) { + queueMicrotask(() => success("Issues recovered on the linked environment")); + } else if (!primaryRefreshStarted) { + primaryRefreshStarted = true; + // Only the original slow read is allowed to finish. Restarting it strands its result. + void slowRead.then(() => success("Updated issue from the slow environment")); + } + }; + }, new URL(host).host); + + await t3.open("/settings/connections"); + await screen.getByRole("button", "Add environment").tap(); + const dialog = screen.getByRole("dialog"); + await dialog.getByPlaceholder("backend.example.com").fill(host); + await dialog.getByPlaceholder("PAIRCODE").fill(token); + await dialog.getByRole("button", "Add environment").tap(); + await screen.getByRole("button", "More actions for Scenario").waitFor({ timeout: 60_000 }); + await app.open("/issues"); + + await screen.getByText("Before refresh", { exact: true }).waitFor({ timeout: 60_000 }); + await screen.getByText("Issue from the linked environment", { exact: true }).waitFor(); + await browser.evaluate(() => { + (window as unknown as { armIssuesRefresh: () => void }).armIssuesRefresh(); + return null; + }); + await screen.getByRole("button", "Refresh issues", { exact: true }).tap(); + await screen.getByText(/Showing the issues that loaded/).waitFor(); + await screen.getByRole("button", "Retry", { exact: true }).tap(); + await screen + .getByText("Issues recovered on the linked environment", { exact: true }) + .waitFor(); + await browser.evaluate(() => { + (window as unknown as { releaseSlowIssuesRead: () => void }).releaseSlowIssuesRead(); + return null; + }); + try { + await expect( + screen.getByText("Updated issue from the slow environment", { exact: true }), + ).toBeVisible(); + } finally { + await app.screenshot("partial-issues-after-retry"); + } + } finally { + await server.stop(); + } + }, +); From 6ea01d4cbecb37ec59476aa5c87945b9fce61fad Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:35:11 +0100 Subject: [PATCH 081/183] fix(web): No project folder follows the app language (#38649) Co-authored-by: Julius Marminge --- apps/web/src/hooks/useSidebarProjectGroups.ts | 20 +++-- apps/web/src/sidebarProjectGrouping.ts | 37 ++++---- .../scratch-folder-follows-language.e2e.ts | 90 +++++++++++++++++++ 3 files changed, 125 insertions(+), 22 deletions(-) create mode 100644 scripts/scenarios/scratch-folder-follows-language.e2e.ts diff --git a/apps/web/src/hooks/useSidebarProjectGroups.ts b/apps/web/src/hooks/useSidebarProjectGroups.ts index 88210360d2a7f..7a0036d35786d 100644 --- a/apps/web/src/hooks/useSidebarProjectGroups.ts +++ b/apps/web/src/hooks/useSidebarProjectGroups.ts @@ -1,3 +1,5 @@ +import { useMessages } from "gt-react"; + import { orderItemsByPreferredIds, sortSidebarV2ProjectGroups } from "../components/Sidebar.logic"; import { getProjectOrderKey, @@ -20,6 +22,7 @@ export function useSidebarProjectGroups() { const groupingSettings = useClientSettings(selectProjectGroupingSettings); const environments = useEnvironmentIdentities(); const primaryEnvironmentId = usePrimaryEnvironmentId(); + const resolve = useMessages(); const orderedProjects = orderItemsByPreferredIds({ items: projects, preferredIds: projectOrder, @@ -32,12 +35,15 @@ export function useSidebarProjectGroups() { const labels = new Map( environments.map((environment) => [environment.environmentId, environment.label] as const), ); - const unsortedGroups = buildSidebarProjectSnapshots({ - projects: sortOrder === "manual" ? orderedProjects : projects, - groupScratchProjects: true, - settings: groupingSettings, - primaryEnvironmentId, - resolveEnvironmentLabel: (environmentId) => labels.get(environmentId) ?? null, - }); + const unsortedGroups = buildSidebarProjectSnapshots( + { + projects: sortOrder === "manual" ? orderedProjects : projects, + groupScratchProjects: true, + settings: groupingSettings, + primaryEnvironmentId, + resolveEnvironmentLabel: (environmentId) => labels.get(environmentId) ?? null, + }, + resolve, + ); return sortSidebarV2ProjectGroups(unsortedGroups, threads, sortOrder, delegatedUnderParent); } diff --git a/apps/web/src/sidebarProjectGrouping.ts b/apps/web/src/sidebarProjectGrouping.ts index 8209922a2c60e..b8931f32051d1 100644 --- a/apps/web/src/sidebarProjectGrouping.ts +++ b/apps/web/src/sidebarProjectGrouping.ts @@ -11,6 +11,7 @@ import { } from "@t3tools/client-runtime/state/project-grouping"; import { msg } from "gt-react"; +import { m, type MessageResolver } from "./i18n/messages"; import type { Project } from "./types"; export const PROJECT_GROUPING_MODE_LABELS: Record = { @@ -139,21 +140,27 @@ export function buildPhysicalToLogicalProjectKeyMap(input: { return mapping; } -export function buildSidebarProjectSnapshots(input: { - projects: ReadonlyArray; - settings: ProjectGroupingSettings; - groupScratchProjects?: boolean; - primaryEnvironmentId: EnvironmentId | null; - resolveEnvironmentLabel: (environmentId: EnvironmentId) => string | null; - isDesktopLocalEnvironment?: (environmentId: EnvironmentId) => boolean; - isWslEnvironment?: (environmentId: EnvironmentId) => boolean; -}): SidebarProjectSnapshot[] { - return buildProjectGroups({ - projects: input.projects, - groupScratchProjects: input.groupScratchProjects ?? false, - settings: input.settings, - preferredEnvironmentId: input.primaryEnvironmentId, - }).map((group): SidebarProjectSnapshot => { +export function buildSidebarProjectSnapshots( + input: { + projects: ReadonlyArray; + settings: ProjectGroupingSettings; + groupScratchProjects?: boolean; + primaryEnvironmentId: EnvironmentId | null; + resolveEnvironmentLabel: (environmentId: EnvironmentId) => string | null; + isDesktopLocalEnvironment?: (environmentId: EnvironmentId) => boolean; + isWslEnvironment?: (environmentId: EnvironmentId) => boolean; + }, + resolve: MessageResolver = m, +): SidebarProjectSnapshot[] { + return buildProjectGroups( + { + projects: input.projects, + groupScratchProjects: input.groupScratchProjects ?? false, + settings: input.settings, + preferredEnvironmentId: input.primaryEnvironmentId, + }, + resolve, + ).map((group): SidebarProjectSnapshot => { const members = group.members.map( ({ physicalProjectKey, project }): SidebarProjectGroupMember => ({ ...project, diff --git a/scripts/scenarios/scratch-folder-follows-language.e2e.ts b/scripts/scenarios/scratch-folder-follows-language.e2e.ts new file mode 100644 index 0000000000000..986aa1ddb7454 --- /dev/null +++ b/scripts/scenarios/scratch-folder-follows-language.e2e.ts @@ -0,0 +1,90 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "The project folder for threads without a project follows the app language", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("scenario-scratch"); + const thread = await t3.thread({ project, title: "Scratch work", messages: ["Start"] }); + + // The scenario home is inside a Git checkout, where the server disables native scratch. + // Advertise the seeded workspace as scratch while leaving the real project and thread in place. + await browser.addInitScript((scratchWorkspaceRoot) => { + const configRequests = new WeakMap(); + 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 === "Request" && request.tag === "subscribeServerConfig") { + configRequests.set(this, String(request.id)); + } + } + } + return send.call(this, data); + }; + const addEventListener = WebSocket.prototype.addEventListener; + WebSocket.prototype.addEventListener = function ( + this: WebSocket, + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions, + ) { + if (type !== "message" || typeof listener !== "function") { + return addEventListener.call(this, type, listener, options); + } + return addEventListener.call( + this, + type, + (event: Event) => { + const data = (event as MessageEvent).data; + if (typeof data !== "string") return listener.call(this, event); + const parsed = JSON.parse(data); + let changed = false; + for (const message of [parsed].flat()) { + if ( + message?._tag !== "Chunk" || + String(message.requestId) !== configRequests.get(this) + ) + continue; + for (const value of message.values) { + if (value.type === "snapshot") { + value.config.scratchWorkspaceRoot = scratchWorkspaceRoot; + changed = true; + } + } + } + return listener.call( + this, + changed ? new MessageEvent("message", { data: JSON.stringify(parsed) }) : event, + ); + }, + options, + ); + } as typeof WebSocket.prototype.addEventListener; + }, project); + + await t3.open("/settings/labs"); + await screen.getByLabel("Boring sidebar (group by project)", { exact: true }).tap(); + await screen.getByLabel("Two-line folder rows", { exact: true }).waitFor(); + + await t3.open("/settings/general"); + const openFolder = screen.getByTestId("sidebar-project-folder"); + await expect(openFolder).toContainText("No project", { timeout: 60_000 }); + await screen.getByLabel("Language", { exact: true }).tap(); + await screen.getByText("日本語", { exact: true }).tap(); + await screen.getByLabel("言語", { exact: true }).waitFor(); + // Settings leaves the sidebar mounted. Keep this failure through the capture after reopening. + await expect.soft(openFolder).toContainText("プロジェクトなし"); + + await t3.open(thread); + const folder = screen.getByTestId("sidebar-project-folder"); + await folder.getByText(/^(?:No project|プロジェクトなし)$/, { exact: true }).waitFor({ + timeout: 60_000, + }); + await app.screenshot("scratch-folder-in-japanese"); + await expect(folder).toContainText("プロジェクトなし"); + }, +); From 66235c7f2a92677b8356a61ecaca6e5a7a96ebb8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 18:38:27 -0800 Subject: [PATCH 082/183] fix(server): messages after a fresh session no longer return to a pre-clear session woken by background work (#38824) --- .../src/orchestration-v2/Orchestrator.ts | 8 +- .../ProviderSwitch.integration.test.ts | 128 ++++++++++++++++++ 2 files changed, 134 insertions(+), 2 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 5c370c32c8223..a95481da7dfd6 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -1375,7 +1375,7 @@ function appendContextHandoffId( return handoffId === null ? handoffIds : Array.from(new Set([...handoffIds, handoffId])); } -/** The provider thread a message continues: the active one, unless a fresh-session schedule run started it. */ +/** The provider thread a message continues: the active one, unless a fresh-session schedule run started it or it predates the latest fresh start. */ function conversationProviderThread( projection: Pick< OrchestrationV2ThreadProjection, @@ -1391,8 +1391,12 @@ function conversationProviderThread( const active = projection.providerThreads.find( (candidate) => candidate.id === projection.thread.activeProviderThreadId, ); - if (active === undefined || !startedByScheduledFreshRun(active)) return active; + if (active === undefined) return active; const boundary = contextBoundaryOrdinal(projection); + // A pre-clear session that is still alive (background work) can become active again on its updates. + if (!startedByScheduledFreshRun(active) && !providerThreadPredatesBoundary(active, boundary)) { + return active; + } return ( projection.providerThreads .filter( 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 9929688d88e23..e1b92b61cb5a1 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -4643,6 +4643,134 @@ describe("orchestration v2 provider switching", () => { }), ); + it.live( + "keeps the post-clear conversation when the pre-clear session's background task settles", + () => + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace("fresh-context-old-session-wake"); + const capturedTurns = yield* Ref.make>([]); + const backgroundWork = yield* Ref.make(false); + const started = yield* Deferred.make(); + const release = yield* Deferred.make(); + const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([ + makeTestAdapter({ + instanceId: CLAUDE_MODEL_SELECTION.instanceId, + driver: CLAUDE_DRIVER, + capabilities: ClaudeProviderCapabilitiesV2, + modelSelection: CLAUDE_MODEL_SELECTION, + responseByRunOrdinal: {}, + capturedTurns, + backgroundWork, + nativeThreadGeneration: yield* Ref.make(0), + holdFirstTurn: started, + releaseFirstTurn: release, + }), + ]); + const threadId = ThreadId.make("thread:fresh-context-old-session-wake"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const eventSink = yield* EventSink.EventSinkV2; + const dispatch = (name: string, freshContext = false) => + orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`command:fresh-context-old-session-wake:${name}`), + threadId, + messageId: MessageId.make(`message:fresh-context-old-session-wake:${name}`), + text: name, + attachments: [], + modelSelection: CLAUDE_MODEL_SELECTION, + dispatchMode: { type: "queue_after_active" }, + ...(freshContext ? { freshContext: true } : {}), + }); + const send = (name: string) => + Effect.gen(function* () { + yield* dispatch(name); + yield* worker.drain(); + yield* waitForIdle(threadId); + }); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("command:fresh-context-old-session-wake:create"), + threadId, + projectId: ProjectId.make("project:fresh-context-old-session-wake"), + title: "Fresh context with an old session's background task", + modelSelection: CLAUDE_MODEL_SELECTION, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + }); + yield* dispatch("before-clear"); + yield* Deferred.await(started); + // Queued behind a running turn, the fresh run starts without waiting for its background work. + yield* dispatch("after-clear", true); + // The turn ends with a run_in_background command still running in its session. + yield* Ref.set(backgroundWork, true); + yield* Deferred.succeed(release, undefined); + yield* worker.drain(); + yield* waitForIdle(threadId); + yield* send("after-clear-reply"); + const turns = () => Ref.get(capturedTurns); + const turnFor = (all: ReadonlyArray, name: string) => + all.find((turn) => turn.text.endsWith(name))!; + const oldProviderThreadId = turnFor(yield* turns(), "before-clear").providerThreadId; + assert.notEqual( + turnFor(yield* turns(), "after-clear").providerThreadId, + oldProviderThreadId, + ); + assert.equal( + turnFor(yield* turns(), "after-clear-reply").nativeThreadId, + turnFor(yield* turns(), "after-clear").nativeThreadId, + ); + // The old Claude session reports its background task settled, as on task_notification. + const oldProviderThread = (yield* orchestrator.getThreadProjection( + threadId, + )).providerThreads.find((providerThread) => providerThread.id === oldProviderThreadId)!; + const settledAt = yield* DateTime.now; + yield* eventSink.write({ + events: [ + { + id: EventId.make("event:fresh-context-old-session-wake:old-session-settled"), + type: "provider-thread.updated", + threadId, + occurredAt: settledAt, + payload: { ...oldProviderThread, pendingBackgroundTasks: [], updatedAt: settledAt }, + }, + ], + }); + yield* send("next-user-message"); + const all = yield* turns(); + assert.equal( + turnFor(all, "next-user-message").nativeThreadId, + turnFor(all, "after-clear").nativeThreadId, + ); + }).pipe( + Effect.provide( + ProviderReplayHarness.layerWithRegistry( + { + name: "fresh-context-old-session-wake", + runtimePolicyOverride: { + cwd, + approvalPolicy: "never", + sandboxPolicy: { + type: "readOnly", + access: { type: "fullAccess" }, + networkAccess: false, + }, + }, + }, + layerRegistry, + ), + ), + ); + }), + ); + it.live("keeps the thread a queued fresh run reserved for that run", () => Effect.gen(function* () { const cwd = yield* checkpointWorkspace("fresh-context-reserved"); From 410109da5d846c17a40eadb5f92b2df6206b7f6a Mon Sep 17 00:00:00 2001 From: Navid Nadali Date: Thu, 19 Nov 2026 02:41:25 +0000 Subject: [PATCH 083/183] fix(testing): test git commands stay out of the outer repository (#38804) Co-authored-by: Julius Marminge --- .github/scripts/ci-changes.cjs | 2 +- apps/desktop/vite.config.ts | 6 +- apps/mobile/vite.config.ts | 6 +- apps/web/vite.config.ts | 1 + packages/client-runtime/vite.config.ts | 6 +- packages/provider-testing/package.json | 5 +- .../src/replayWorkspace.test.ts | 83 +++++++++++++++++++ .../provider-testing/src/replayWorkspace.ts | 7 +- packages/shared/package.json | 4 + packages/shared/src/testing/gitEnv.test.ts | 27 ++++++ packages/shared/src/testing/gitEnv.ts | 10 +++ .../shared/src/testing/gitRepositoryEnv.ts | 24 ++++++ pnpm-lock.yaml | 6 ++ scripts/check-changed.test.ts | 2 + vite.config.ts | 1 + 15 files changed, 184 insertions(+), 6 deletions(-) create mode 100644 packages/provider-testing/src/replayWorkspace.test.ts create mode 100644 packages/shared/src/testing/gitEnv.test.ts create mode 100644 packages/shared/src/testing/gitEnv.ts create mode 100644 packages/shared/src/testing/gitRepositoryEnv.ts diff --git a/.github/scripts/ci-changes.cjs b/.github/scripts/ci-changes.cjs index 7b7332903ed9f..f9c8174f854f2 100644 --- a/.github/scripts/ci-changes.cjs +++ b/.github/scripts/ci-changes.cjs @@ -14,7 +14,7 @@ const INERT = [ // Shared test setup and vendored mobile dependencies affect every package. const RUNS_EVERYTHING = [ - /^packages\/shared\/src\/(HostProcess|testing\/(longTempDir|providerEnv))\.ts$/, + /^packages\/shared\/src\/(HostProcess|testing\/(longTempDir|providerEnv|gitEnv|gitRepositoryEnv))\.ts$/, /^apps\/mobile\/deps\//, ]; diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts index 3e6fd9531106b..f4e04317e4924 100644 --- a/apps/desktop/vite.config.ts +++ b/apps/desktop/vite.config.ts @@ -177,6 +177,7 @@ export default defineConfig({ setupFiles: [ "../../packages/shared/src/testing/longTempDir.ts", "../../packages/shared/src/testing/providerEnv.ts", + "../../packages/shared/src/testing/gitEnv.ts", ], }, }, @@ -187,7 +188,10 @@ export default defineConfig({ include: domTests, // Guest preloads run in the page; these tests drive them against a DOM. environment: "jsdom", - setupFiles: ["../../packages/shared/src/testing/providerEnv.ts"], + setupFiles: [ + "../../packages/shared/src/testing/providerEnv.ts", + "../../packages/shared/src/testing/gitEnv.ts", + ], }, }, ], diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts index 0ed29995b982a..05261f9cb1848 100644 --- a/apps/mobile/vite.config.ts +++ b/apps/mobile/vite.config.ts @@ -116,6 +116,7 @@ export default defineConfig({ setupFiles: [ "../../packages/shared/src/testing/longTempDir.ts", "../../packages/shared/src/testing/providerEnv.ts", + "../../packages/shared/src/testing/gitEnv.ts", ], }, }, @@ -164,7 +165,10 @@ export default defineConfig({ include: reactTests, // Native components mock React Native and render through react-dom in these tests. environment: "jsdom", - setupFiles: ["../../packages/shared/src/testing/providerEnv.ts"], + setupFiles: [ + "../../packages/shared/src/testing/providerEnv.ts", + "../../packages/shared/src/testing/gitEnv.ts", + ], }, }, ], diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 1916d2dd54fc0..073fca7943d3e 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -96,6 +96,7 @@ const unitTestProject = { setupFiles: [ "../../packages/shared/src/testing/longTempDir.ts", "../../packages/shared/src/testing/providerEnv.ts", + "../../packages/shared/src/testing/gitEnv.ts", ], }, } satisfies TestProjectInlineConfiguration; diff --git a/packages/client-runtime/vite.config.ts b/packages/client-runtime/vite.config.ts index dbb29b7a4ef6c..18cae2d8d8c95 100644 --- a/packages/client-runtime/vite.config.ts +++ b/packages/client-runtime/vite.config.ts @@ -5,6 +5,10 @@ export default defineConfig({ test: { environment: "node", include: ["src/**/*.test.ts"], - setupFiles: ["../shared/src/testing/longTempDir.ts", "../shared/src/testing/providerEnv.ts"], + setupFiles: [ + "../shared/src/testing/longTempDir.ts", + "../shared/src/testing/providerEnv.ts", + "../shared/src/testing/gitEnv.ts", + ], }, }); diff --git a/packages/provider-testing/package.json b/packages/provider-testing/package.json index 1f0e3e02fd922..b2da89012680c 100644 --- a/packages/provider-testing/package.json +++ b/packages/provider-testing/package.json @@ -25,6 +25,7 @@ } }, "scripts": { + "test": "vp test run --config ../../vite.config.ts --dir .", "typecheck": "effect-tsgo tsrs --noEmit" }, "dependencies": { @@ -35,6 +36,8 @@ "effect": "catalog:" }, "devDependencies": { - "@types/node": "catalog:" + "@effect/vitest": "catalog:", + "@types/node": "catalog:", + "vite-plus": "catalog:" } } diff --git a/packages/provider-testing/src/replayWorkspace.test.ts b/packages/provider-testing/src/replayWorkspace.test.ts new file mode 100644 index 0000000000000..6c952542c4ea6 --- /dev/null +++ b/packages/provider-testing/src/replayWorkspace.test.ts @@ -0,0 +1,83 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as ChildProcess from "effect/process/ChildProcess"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import { vi } from "vite-plus/test"; + +import { checkpointWorkspace } from "./replayWorkspace.ts"; + +const git = (cwd: string, args: ReadonlyArray) => + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + return yield* spawner.string(ChildProcess.make("git", args, { cwd })); + }); + +const repositoryState = (repo: string, worktree: string, worktreeIndex: string) => + Effect.gen(function* () { + return { + config: yield* git(repo, ["config", "--local", "--list"]), + refs: yield* git(repo, ["for-each-ref"]), + worktrees: yield* git(repo, ["worktree", "list", "--porcelain"]), + worktreeHead: yield* git(worktree, ["rev-parse", "HEAD"]), + worktreeIndex: yield* git(repo, ["hash-object", "--no-filters", worktreeIndex]), + }; + }); + +it.layer(NodeServices.layer)("checkpointWorkspace", (it) => { + // `git bisect run` and `git rebase --exec` export GIT_DIR to what they run, and hooks add + // GIT_INDEX_FILE. In a linked worktree both are absolute paths into the shared repository. + it.effect.each([ + { runner: "git bisect run", selectors: ["GIT_DIR"] }, + { runner: "a git hook", selectors: ["GIT_DIR", "GIT_INDEX_FILE"] }, + ])("keeps to its own repository when run under $runner", ({ selectors }) => + Effect.gen(function* () { + yield* Effect.addFinalizer(() => Effect.sync(() => vi.unstubAllEnvs())); + // These commits use the contributor's global config, which must not require a signing key. + vi.stubEnv("GIT_CONFIG_COUNT", "1"); + vi.stubEnv("GIT_CONFIG_KEY_0", "commit.gpgsign"); + vi.stubEnv("GIT_CONFIG_VALUE_0", "false"); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-replay-workspace-decoy-" }); + const repo = path.join(root, "repo"); + const worktree = path.join(root, "worktree"); + yield* fs.makeDirectory(repo); + yield* git(repo, ["init"]); + yield* git(repo, [ + "-c", + "user.name=Decoy", + "-c", + "user.email=decoy@example.com", + "commit", + "--allow-empty", + "-m", + "decoy", + ]); + yield* git(repo, ["worktree", "add", "--detach", worktree]); + const worktreeGitDir = (yield* git(worktree, ["rev-parse", "--absolute-git-dir"])).trim(); + const worktreeIndex = path.join(worktreeGitDir, "index"); + const before = yield* repositoryState(repo, worktree, worktreeIndex); + + const inherited: Record = { + GIT_DIR: worktreeGitDir, + GIT_INDEX_FILE: worktreeIndex, + }; + for (const name of selectors) vi.stubEnv(name, inherited[name]); + const workspace = yield* checkpointWorkspace("decoy-guard", { "src/a.txt": "a\n" }); + vi.unstubAllEnvs(); + + assert.deepStrictEqual(yield* repositoryState(repo, worktree, worktreeIndex), before); + assert.strictEqual( + yield* git(workspace, ["log", "--format=%s%x00%an", "-1"]), + "initial\u0000T3 Code Test\n", + ); + assert.strictEqual( + (yield* git(workspace, ["ls-files"])).trim().split("\n").join(","), + "README.md,src/a.txt", + ); + }), + ); +}); diff --git a/packages/provider-testing/src/replayWorkspace.ts b/packages/provider-testing/src/replayWorkspace.ts index 4216ebaedc53f..1b60b685c788a 100644 --- a/packages/provider-testing/src/replayWorkspace.ts +++ b/packages/provider-testing/src/replayWorkspace.ts @@ -6,6 +6,8 @@ import * as PlatformError from "effect/PlatformError"; import * as Schema from "effect/Schema"; import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { unsetInheritedGitRepositoryEnv } from "@t3tools/shared/testing/gitRepositoryEnv"; class ReplayFixtureGitCommandError extends Schema.TaggedError()( "ReplayFixtureGitCommandError", @@ -29,7 +31,10 @@ function runGit( > { return Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const exitCode = yield* spawner.exitCode(ChildProcess.make("git", args, { cwd })); + const env = unsetInheritedGitRepositoryEnv(process.env, yield* HostProcess.Platform); + const exitCode = yield* spawner.exitCode( + ChildProcess.make("git", args, { cwd, env, extendEnv: true }), + ); if (Number(exitCode) !== 0) { return yield* new ReplayFixtureGitCommandError({ command: `git ${args.join(" ")}`, diff --git a/packages/shared/package.json b/packages/shared/package.json index 781d1a4e125e1..68a0b589f8809 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -375,6 +375,10 @@ "types": "./src/HostProcess.ts", "import": "./src/HostProcess.ts" }, + "./testing/gitRepositoryEnv": { + "types": "./src/testing/gitRepositoryEnv.ts", + "import": "./src/testing/gitRepositoryEnv.ts" + }, "./testing/longTempDir": { "types": "./src/testing/longTempDir.ts", "import": "./src/testing/longTempDir.ts" diff --git a/packages/shared/src/testing/gitEnv.test.ts b/packages/shared/src/testing/gitEnv.test.ts new file mode 100644 index 0000000000000..370a5147279f4 --- /dev/null +++ b/packages/shared/src/testing/gitEnv.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it, onTestFinished, vi } from "vite-plus/test"; + +import { unsetInheritedGitRepositoryEnv } from "./gitRepositoryEnv.ts"; + +describe("git test setup", () => { + it("starts tests without the repository selectors git exported to the run", async () => { + onTestFinished(() => { + vi.unstubAllEnvs(); + }); + vi.stubEnv("GIT_DIR", "/repo/.git/worktrees/wt"); + vi.stubEnv("GIT_INDEX_FILE", "/repo/.git/worktrees/wt/index"); + vi.stubEnv("GIT_EDITOR", "true"); + + vi.resetModules(); + await import("./gitEnv.ts"); + + expect(process.env).not.toHaveProperty("GIT_DIR"); + expect(process.env).not.toHaveProperty("GIT_INDEX_FILE"); + expect(process.env.GIT_EDITOR).toBe("true"); + }); + + it("unsets a selector under the spelling Windows passed it in", () => { + const inherited = { Git_Dir: "C:\\repo\\.git", GIT_EDITOR: "true", PATH: "C:\\bin" }; + expect(Object.keys(unsetInheritedGitRepositoryEnv(inherited, "win32"))).toEqual(["Git_Dir"]); + expect(Object.keys(unsetInheritedGitRepositoryEnv(inherited, "linux"))).toEqual([]); + }); +}); diff --git a/packages/shared/src/testing/gitEnv.ts b/packages/shared/src/testing/gitEnv.ts new file mode 100644 index 0000000000000..9fa63ab9312f2 --- /dev/null +++ b/packages/shared/src/testing/gitEnv.ts @@ -0,0 +1,10 @@ +import * as HostProcess from "../HostProcess.ts"; +import { unsetInheritedGitRepositoryEnv } from "./gitRepositoryEnv.ts"; + +// A test run started from `git bisect run`, `git rebase --exec` or a hook inherits GIT_DIR. Every git +// command a test or the code under test starts would then write into that repository. +for (const name of Object.keys( + unsetInheritedGitRepositoryEnv(process.env, HostProcess.Platform.defaultValue()), +)) { + delete process.env[name]; +} diff --git a/packages/shared/src/testing/gitRepositoryEnv.ts b/packages/shared/src/testing/gitRepositoryEnv.ts new file mode 100644 index 0000000000000..630f81d9ebb4b --- /dev/null +++ b/packages/shared/src/testing/gitRepositoryEnv.ts @@ -0,0 +1,24 @@ +// Mirrors the server's set in apps/server/src/vcs/VcsProcess.ts, which shared cannot import. +const REPOSITORY_SELECTORS = new Set([ + "GIT_DIR", + "GIT_WORK_TREE", + "GIT_COMMON_DIR", + "GIT_INDEX_FILE", + "GIT_OBJECT_DIRECTORY", + "GIT_ALTERNATE_OBJECT_DIRECTORIES", +]); + +/** + * `git bisect run`, `git rebase --exec` and hooks export GIT_DIR (hooks also GIT_INDEX_FILE) to what + * they run, so a fixture's git commands would work on that repository instead of the one in their + * cwd. Spread the result into a child's env to unset them under the spelling they were inherited as. + */ +export const unsetInheritedGitRepositoryEnv = ( + inherited: NodeJS.ProcessEnv, + platform: NodeJS.Platform, +): Record => + Object.fromEntries( + Object.keys(inherited) + .filter((name) => REPOSITORY_SELECTORS.has(platform === "win32" ? name.toUpperCase() : name)) + .map((name) => [name, undefined]), + ); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index af0be20508e16..3d44f4e0d55ec 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2060,9 +2060,15 @@ importers: specifier: 4.1.3 version: 4.1.3 devDependencies: + '@effect/vitest': + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.3)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 + vite-plus: + specifier: 1.4.0 + version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) packages/secret-provider-core: dependencies: diff --git a/scripts/check-changed.test.ts b/scripts/check-changed.test.ts index 37bcc389fc229..5874eef8de515 100644 --- a/scripts/check-changed.test.ts +++ b/scripts/check-changed.test.ts @@ -228,6 +228,8 @@ describe("check:changed", () => { it.each([ "packages/shared/src/testing/longTempDir.ts", "packages/shared/src/testing/providerEnv.ts", + "packages/shared/src/testing/gitEnv.ts", + "packages/shared/src/testing/gitRepositoryEnv.ts", ])("tests every package when the shared test setup file %s changes", (file) => { assert.strictEqual(decide([file], readWorkspace(), false).outputs.test_packages, ""); }); diff --git a/vite.config.ts b/vite.config.ts index fce0242597545..7533acd18b177 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -149,6 +149,7 @@ export default defineConfig({ NodeURL.fileURLToPath( new URL("./packages/shared/src/testing/providerEnv.ts", import.meta.url), ), + NodeURL.fileURLToPath(new URL("./packages/shared/src/testing/gitEnv.ts", import.meta.url)), ], ...(isRepoRootTestRun ? { From eb46038e3aea160fc8e21ab3f7b0aeb0fbf11773 Mon Sep 17 00:00:00 2001 From: Noah Sigel <30538387+nsigel@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:48:24 -0800 Subject: [PATCH 084/183] fix(web): Background work details show a subagent as Waiting, like the line above (#38763) Co-authored-by: Julius Marminge --- .../BackgroundWorkDetails.browser.test.tsx | 32 +++++++++++++++++++ .../components/chat/BackgroundWorkDetails.tsx | 3 +- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/chat/BackgroundWorkDetails.browser.test.tsx b/apps/web/src/components/chat/BackgroundWorkDetails.browser.test.tsx index 01311a60ecf4f..d5d5d62d3c2ab 100644 --- a/apps/web/src/components/chat/BackgroundWorkDetails.browser.test.tsx +++ b/apps/web/src/components/chat/BackgroundWorkDetails.browser.test.tsx @@ -95,3 +95,35 @@ it("opens full command details for short labels and keeps pending tasks current" await page.getByRole("button", { name: "Close", exact: true }).click(); await expect.element(page.getByRole("dialog")).not.toBeInTheDocument(); }); + +it("gives a subagent the same status as the background work line", async () => { + await using screen = await render( + undefined, + onOpenThread: () => undefined, + })} + />, + ); + await expect.element(page.getByText("Waiting · Review refactor diffs")).toBeVisible(); + await screen.getByRole("button", { name: "Details", exact: true }).click(); + await expect + .element(page.getByRole("dialog").getByText("Waiting", { exact: true })) + .toBeVisible(); +}); diff --git a/apps/web/src/components/chat/BackgroundWorkDetails.tsx b/apps/web/src/components/chat/BackgroundWorkDetails.tsx index 8679275e9de68..72ca70c2b16e1 100644 --- a/apps/web/src/components/chat/BackgroundWorkDetails.tsx +++ b/apps/web/src/components/chat/BackgroundWorkDetails.tsx @@ -4,6 +4,7 @@ import type { ThreadId, } from "@t3tools/contracts"; import type { ThreadStructure } from "@t3tools/client-runtime/state/shell"; +import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import { T, useGT } from "gt-react"; import { useState } from "react"; @@ -79,7 +80,7 @@ export function BackgroundWorkDetails(props: {

{title}

- {task.awaited + {backgroundWorkHoldsCompletion([task]) ? gt("Waiting", { $context: "status of background work" }) : gt("Running", { $context: "status of background work" })} From 38e946455a64ed3a4cc22c14679ae41d49424c54 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:48:36 +0100 Subject: [PATCH 085/183] fix(mobile): unavailable thread links are labeled in the app language (#38651) Co-authored-by: Julius Marminge --- apps/mobile/src/state/entities.ts | 19 ++++++++----- packages/shared/src/threadLinks.test.ts | 13 ++++++++- packages/shared/src/threadLinks.ts | 37 ------------------------- packages/shared/src/threadLinksCopy.ts | 34 +++++++++++++++++++++-- 4 files changed, 56 insertions(+), 47 deletions(-) diff --git a/apps/mobile/src/state/entities.ts b/apps/mobile/src/state/entities.ts index 11d3a5b0254a6..9ca7f1d64496f 100644 --- a/apps/mobile/src/state/entities.ts +++ b/apps/mobile/src/state/entities.ts @@ -20,11 +20,11 @@ import { guessThreadLinkRef, hasThreadLinks, parseThreadLinkHref, - relabelThreadLinks, threadLinkCandidates, threadLinkRefs, type ThreadLink, } from "@t3tools/shared/threadLinks"; +import { relabelThreadLinks } from "@t3tools/shared/threadLinksCopy"; import * as Schema from "effect/Schema"; import { AsyncResult, Atom } from "effect/reactivity"; import { msg, useMessages } from "gt-react-native"; @@ -246,12 +246,17 @@ export function useLiveThreadLinkLabels(markdown: string, environmentId: Environ ? threadLinkTitlesAtom(JSON.stringify(threadLinkRefs(markdown, environmentId).map(threadKey))) : EMPTY_THREAD_LINK_TITLES_ATOM, ); - return relabelThreadLinks(markdown, environmentId, (ref) => { - const title = titles.get(threadKey(ref)); - return title === FALLBACK_THREAD_TITLE - ? resolve(msg("Thread", { $context: "fallback title of a linked thread" })) - : title; - }); + return relabelThreadLinks( + markdown, + environmentId, + (ref) => { + const title = titles.get(threadKey(ref)); + return title === FALLBACK_THREAD_TITLE + ? resolve(msg("Thread", { $context: "fallback title of a linked thread" })) + : title; + }, + resolve, + ); } /** Keyed reads; every thread is read only to place a v1 link its message's environment lacks. */ diff --git a/packages/shared/src/threadLinks.test.ts b/packages/shared/src/threadLinks.test.ts index 1fcd14f1d5e30..0dae53ac87d9d 100644 --- a/packages/shared/src/threadLinks.test.ts +++ b/packages/shared/src/threadLinks.test.ts @@ -1,5 +1,7 @@ import { describe, expect, it, vi } from "vite-plus/test"; import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts"; +import { mFallback } from "gt-i18n"; +import type { MFunctionType } from "gt-i18n/types"; import { formatHostedThreadLink, @@ -7,10 +9,10 @@ import { guessThreadLinkRef, hostedThreadLink, parseThreadLinkHref, - relabelThreadLinks, threadLinkCandidates, threadLinkRefs, } from "./threadLinks.ts"; +import { relabelThreadLinks } from "./threadLinksCopy.ts"; const ref = (environmentId: string, threadId = "chat-1") => ({ environmentId: EnvironmentId.make(environmentId), @@ -22,6 +24,12 @@ const titlesIn = (titles: Record>) => ({ environmentId, threadId }: ScopedThreadRef) => titles[environmentId]?.[threadId]; +const japanese: MFunctionType = (encodedMsg, options) => { + const english = mFallback(encodedMsg, options); + return ( + english === "Thread no longer available" ? "スレッドは利用できなくなりました" : english + ) as typeof english; +}; describe("thread link destinations", () => { it("names a v1 link's thread in the message's environment, as written and then decoded", () => { @@ -140,6 +148,9 @@ describe("thread links", () => { expect(relabelThreadLinks("[Old](t3-thread://v1/t1)", local, () => undefined)).toBe( "[Old](t3-thread://v1/t1)", ); + expect(relabelThreadLinks("See ", local, () => undefined, japanese)).toBe( + "See スレッドは利用できなくなりました", + ); }); it("leaves links inside code spans and fences as written", () => { diff --git a/packages/shared/src/threadLinks.ts b/packages/shared/src/threadLinks.ts index 9c063938ab128..d564e4bb54730 100644 --- a/packages/shared/src/threadLinks.ts +++ b/packages/shared/src/threadLinks.ts @@ -179,12 +179,6 @@ export function threadLinkRefs( return [...refs.values()]; } -function unknownThreadLinkLabel(link: ThreadLink, messageEnvironmentId: EnvironmentId): string { - return link.environmentId === null || link.environmentId === messageEnvironmentId - ? "Thread no longer available" - : "Thread on another machine"; -} - /** Rewrites each link outside code `replace` answers for. `label` is a Markdown link's own text. */ export function replaceThreadLinks( markdown: string, @@ -200,34 +194,3 @@ export function replaceThreadLinks( return (link && replace(link, groups.label)) ?? source; }); } - -/** - * Writes each link with its thread's current title, a hosted link as a v2 link. A link `title` - * cannot resolve becomes plain text, its written label or a neutral one, except a labeled v1 - * link, which may open elsewhere. - */ -export function relabelThreadLinks( - markdown: string, - messageEnvironmentId: EnvironmentId, - title: (ref: ScopedThreadRef) => string | undefined, -): string { - return replaceThreadLinks(markdown, (written, label) => { - const environmentId = written.environmentId ?? messageEnvironmentId; - const decoded = percentDecodedThreadLinkId(written.threadId); - const threadId = - title({ environmentId, threadId: written.threadId }) === undefined && - decoded !== null && - title({ environmentId, threadId: decoded }) !== undefined - ? decoded - : written.threadId; - const current = title({ environmentId, threadId }); - if (current === undefined) { - if (label !== undefined && written.environmentId === null) return undefined; - return label?.trim() || unknownThreadLinkLabel(written, messageEnvironmentId); - } - return formatThreadLink( - { environmentId: written.environmentId, threadId }, - current.trim() || label || threadId, - ); - }); -} diff --git a/packages/shared/src/threadLinksCopy.ts b/packages/shared/src/threadLinksCopy.ts index e776f68f72b64..3b7480992b7e4 100644 --- a/packages/shared/src/threadLinksCopy.ts +++ b/packages/shared/src/threadLinksCopy.ts @@ -1,8 +1,13 @@ -import type { EnvironmentId } from "@t3tools/contracts"; +import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts"; import { mFallback, msg } from "gt-i18n"; import type { MFunctionType } from "gt-i18n/types"; -import type { ThreadLink } from "./threadLinks.ts"; +import { + formatThreadLink, + replaceThreadLinks, + threadLinkCandidates, + type ThreadLink, +} from "./threadLinks.ts"; /** @public */ export function unknownThreadLinkLabel( @@ -14,3 +19,28 @@ export function unknownThreadLinkLabel( ? resolve(msg("Thread no longer available")) : resolve(msg("Thread on another machine")); } + +/** + * Writes each link with its thread's current title, a hosted link as a v2 link. A link `title` + * cannot resolve becomes plain text, its written label or a neutral one, except a labeled v1 + * link, which may open elsewhere. + */ +export function relabelThreadLinks( + markdown: string, + messageEnvironmentId: EnvironmentId, + title: (ref: ScopedThreadRef) => string | undefined, + resolve: MFunctionType = mFallback, +): string { + return replaceThreadLinks(markdown, (written, label) => { + for (const ref of threadLinkCandidates(written, messageEnvironmentId)) { + const current = title(ref); + if (current === undefined) continue; + return formatThreadLink( + { environmentId: written.environmentId, threadId: ref.threadId }, + current.trim() || label || ref.threadId, + ); + } + if (label !== undefined && written.environmentId === null) return undefined; + return label?.trim() || unknownThreadLinkLabel(written, messageEnvironmentId, resolve); + }); +} From 6845207825728928bc439442f10aa9df1307eb1c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 18:49:33 -0800 Subject: [PATCH 086/183] feat(server): pairing-link sessions renew with the device's DPoP key (#37980) (#38859) --- .../environments/ManagedEndpointProvider.ts | 12 ++++++--- .../src/environments/ManagedEndpointReaper.ts | 26 ++++++++++++------- 2 files changed, 24 insertions(+), 14 deletions(-) diff --git a/infra/relay/src/environments/ManagedEndpointProvider.ts b/infra/relay/src/environments/ManagedEndpointProvider.ts index 75813c0608b3b..b2946c980358e 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.ts @@ -242,7 +242,10 @@ export class ManagedEndpointTunnelClient extends Context.Service< readonly get: ( tunnelId: string, ) => Effect.Effect; - readonly list: (request: ManagedEndpointTunnelListRequest) => Effect.Effect< + readonly list: ( + request: ManagedEndpointTunnelListRequest, + options?: { readonly timeout?: Duration.Input }, + ) => Effect.Effect< { readonly result: ReadonlyArray; readonly resultInfo?: { @@ -504,6 +507,7 @@ const makeCloudflareApiGate = (alchemyRuntimeContext: Alchemy.BaseRuntimeContext }); return ( call: Effect.Effect, + timeout: Duration.Input = "8 seconds", ): Effect.Effect => Effect.gen(function* () { const now = yield* Clock.currentTimeMillis; @@ -522,7 +526,7 @@ const makeCloudflareApiGate = (alchemyRuntimeContext: Alchemy.BaseRuntimeContext } return yield* call.pipe( Effect.provideService(CloudflareRetry.Retry, withoutRateLimitRetries), - Effect.timeout("8 seconds"), + Effect.timeout(timeout), Effect.tapError((cause) => isCloudflareRateLimited(cause) ? recordRateLimit(cause) : Effect.void, ), @@ -1607,8 +1611,8 @@ export const layerCloudflareBindings = ( }), ), ), - list: (request) => - gate(tunnelClient.list(request)).pipe( + list: (request, options) => + gate(tunnelClient.list(request), options?.timeout).pipe( Effect.mapError( (cause) => new ManagedEndpointTunnelClientError({ diff --git a/infra/relay/src/environments/ManagedEndpointReaper.ts b/infra/relay/src/environments/ManagedEndpointReaper.ts index f800dd8c070d0..71442b536d007 100644 --- a/infra/relay/src/environments/ManagedEndpointReaper.ts +++ b/infra/relay/src/environments/ManagedEndpointReaper.ts @@ -17,8 +17,11 @@ const MANAGED_ENDPOINT_GRACE_PERIOD_MINUTES = 5; // Never-connected tunnels may still be pairing; allow an hour. const MANAGED_ENDPOINT_INACTIVE_GRACE_PERIOD_MINUTES = 60; const MANAGED_ENDPOINT_SWEEP_PAGE_SIZE = 100; -export const MANAGED_ENDPOINT_SWEEP_ATTEMPT_LIMIT = 250; +// Down tunnels arrive at ~66k/day, about what 250 per sweep removed; the delete budget caps a sweep below this. +export const MANAGED_ENDPOINT_SWEEP_ATTEMPT_LIMIT = 500; const MANAGED_ENDPOINT_SWEEP_LIST_REQUEST_LIMIT = 10; +// Cloudflare's filtered list over a large backlog can outlast the 8 s limit request paths use. +const MANAGED_ENDPOINT_SWEEP_LIST_TIMEOUT = "30 seconds"; const MANAGED_ENDPOINT_LEGACY_AGE_BUCKET_DAYS = [7, 30, 90] as const; // Hosts without recovery cannot replace deleted tunnels; allow a longer absence. const MANAGED_ENDPOINT_LEGACY_GRACE_PERIOD_DAYS = 7; @@ -197,15 +200,18 @@ const make = Effect.gen(function* () { const cutoffIso = DateTime.formatIso(cutoff); const listPage = (page: number) => { listRequests += 1; - return tunnels.list({ - isDeleted: false, - includePrefix: prefix, - status, - existedAt: cutoffIso, - ...(status === "down" ? { wasInactiveAt: cutoffIso } : {}), - page, - perPage: MANAGED_ENDPOINT_SWEEP_PAGE_SIZE, - }); + return tunnels.list( + { + isDeleted: false, + includePrefix: prefix, + status, + existedAt: cutoffIso, + ...(status === "down" ? { wasInactiveAt: cutoffIso } : {}), + page, + perPage: MANAGED_ENDPOINT_SWEEP_PAGE_SIZE, + }, + { timeout: MANAGED_ENDPOINT_SWEEP_LIST_TIMEOUT }, + ); }; const first = yield* listPage(1); const totalCount = From 7bae751d89c9f950b174edb7a276ba5fcbacda33 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:50:16 +0100 Subject: [PATCH 087/183] fix(server): Hermes keeps its background reply when launched through a wrapper (#38659) Co-authored-by: Julius Marminge --- .../Adapters/AcpRegistryAdapterV2.test.ts | 119 +++++++++++++--- .../src/server/adapter.ts | 15 +- packages/provider-acp/src/server/adapter.ts | 45 ++++-- ...rmes-wrapper-keeps-background-reply.e2e.ts | 130 ++++++++++++++++++ 4 files changed, 270 insertions(+), 39 deletions(-) create mode 100644 scripts/scenarios/hermes-wrapper-keeps-background-reply.e2e.ts diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts index 7de5357aa76e8..1c84345c729fa 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts @@ -211,21 +211,38 @@ const openClaudeReplaySession = Effect.fn("openClaudeReplaySession")(function* ( replayGate?: ProviderReplayGate, continuationEnabled = true, agentId: string | Record = "claude-acp", + replacementEntries?: ReadonlyArray, ) { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const replayDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-lifecycle-" }); - const transcript = yield* decodeAcpReplayTranscript( - { - provider: ACP_REGISTRY_PROVIDER, - protocol: "acp.ndjson-jsonrpc", - version: "1", - scenario: "claude-lifecycle", - entries: entries as never, - }, - ACP_REGISTRY_PROVIDER, + const scriptPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-replay-agent.ts", import.meta.url), ); + const makeReplay = Effect.fn("openClaudeReplaySession.makeReplay")(function* ( + entries: ReadonlyArray, + name: string, + ) { + const transcript = yield* decodeAcpReplayTranscript( + { + provider: ACP_REGISTRY_PROVIDER, + protocol: "acp.ndjson-jsonrpc", + version: "1", + scenario: name, + entries: entries as never, + }, + ACP_REGISTRY_PROVIDER, + ); + return makeAcpReplayRuntime({ + transcript, + statusPath: path.join(replayDir, `${name}.json`), + scriptPath, + childProcessSpawner, + fileSystem, + ...(replayGate === undefined ? {} : { replayGate }), + }); + }); const offers: Array = []; const offered = yield* Queue.unbounded(); const continuationRequests = { @@ -239,16 +256,12 @@ const openClaudeReplaySession = Effect.fn("openClaudeReplaySession")(function* ( let onTermination: NonNullable< AcpSessionRuntime.AcpSessionRuntimeOptions["onTermination"] > = () => Effect.die("Runtime has not started"); - const replayRuntime = makeAcpReplayRuntime({ - transcript, - statusPath: path.join(replayDir, "status.json"), - scriptPath: yield* path.fromFileUrl( - new URL("../../../scripts/acp-replay-agent.ts", import.meta.url), - ), - childProcessSpawner, - fileSystem, - ...(replayGate === undefined ? {} : { replayGate }), - }); + const replayRuntime = yield* makeReplay(entries, "claude-lifecycle"); + const replacementRuntime = + replacementEntries === undefined + ? replayRuntime + : yield* makeReplay(replacementEntries, "replacement"); + let started = false; const adapterOptions = { selfInvocation: yield* resolveSelfInvocation(), instanceId, @@ -259,7 +272,9 @@ const openClaudeReplaySession = Effect.fn("openClaudeReplaySession")(function* ( ...(continuationEnabled ? { continuationRequests } : {}), makeRuntime: (runtimeInput: Parameters[0]) => { onTermination = runtimeInput.onTermination; - return replayRuntime({ + const replay = started ? replacementRuntime : replayRuntime; + started = true; + return replay({ ...runtimeInput, protocolLogging: { logIncoming: false, @@ -2001,7 +2016,10 @@ describe("AcpRegistryAdapterV2", () => { ); // regression: #38599 Hermes replies on its own when a background process it started exits - it.effect("does not drop Hermes' reply after a background process finishes", () => + it.effect.each([ + { launch: "hermes acp", commandPath: "hermes", commandArgs: ["acp"] }, + { launch: "a wrapper", commandPath: "node", commandArgs: ["hermes-acp.mjs"] }, + ])("does not drop Hermes' reply after a background process finishes ($launch)", (launch) => Effect.gen(function* () { const gate = makeProviderReplayGate(["process-exit"]); const sessionId = "hermes-session"; @@ -2061,7 +2079,7 @@ describe("AcpRegistryAdapterV2", () => { ], gate, true, - { source: "local", commandPath: "hermes", commandArgs: ["acp"] }, + { source: "local", commandPath: launch.commandPath, commandArgs: launch.commandArgs }, ); yield* session.runtime.startTurn(session.turnInput(1)); const foreground = yield* session.until((event) => event.type === "turn.terminal"); @@ -2078,6 +2096,63 @@ describe("AcpRegistryAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect("protects Hermes background work when a wrapper launches it on replacement", () => + Effect.gen(function* () { + const gate = makeProviderReplayGate(["process-exit"]); + const request = (method: string) => ({ + type: "expect_outbound", + frame: { kind: "request", method, params: "" }, + }); + const respond = (method: string, result: object) => ({ + type: "emit_inbound", + frame: { kind: "response", method, result }, + }); + const open = (sessionId: string, name: string) => [ + request("initialize"), + respond("initialize", { protocolVersion: 1, agentInfo: { name, version: "1.0.0" } }), + request("session/new"), + respond("session/new", { sessionId }), + ]; + const sessionId = "hermes-replacement"; + const session = yield* openClaudeReplaySession( + open("initial-session", "generic-agent"), + gate, + true, + { source: "local", commandPath: "node", commandArgs: ["agent-wrapper.mjs"] }, + [ + ...open(sessionId, "hermes-agent"), + request("session/prompt"), + respond("session/prompt", { stopReason: "end_turn" }), + { + ...claudeFrames.update(sessionId, { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Background command finished" }, + }), + label: "process-exit", + }, + ], + ); + const { threadId, modelSelection, runtimePolicy } = session.turnInput(1); + const replaceThread = { + threadId, + modelSelection, + runtimePolicy, + forceNewNativeThread: true, + }; + const pendingWork = session.runtime.hasPendingBackgroundWork ?? Effect.succeed(false); + assert.isFalse(yield* pendingWork); + const providerThread = yield* session.runtime.ensureThread(replaceThread); + yield* session.runtime.startTurn({ ...session.turnInput(1), providerThread }); + assert.equal((yield* session.terminal).status, "completed"); + + gate.release("process-exit"); + yield* Queue.take(session.offered); + assert.isTrue(yield* pendingWork); + const error = yield* session.runtime.ensureThread(replaceThread).pipe(Effect.flip); + assert.include(String(error.cause), "background work is active"); + }).pipe(Effect.provide(layerTest)), + ); + // Copilot flattens MCP titles and reports kind "read" for MCP calls and glob ("other" for rg); // its native tool.execution_start event carries the real identity. it.effect.each(["glob", "rg"])("keeps Copilot's MCP and %s identity", (toolName) => diff --git a/packages/provider-acp-registry/src/server/adapter.ts b/packages/provider-acp-registry/src/server/adapter.ts index d730cbd5e6b1d..8f133f619cea3 100644 --- a/packages/provider-acp-registry/src/server/adapter.ts +++ b/packages/provider-acp-registry/src/server/adapter.ts @@ -182,6 +182,10 @@ function makeAcpRegistryRuntime( }); } +const isHermes = ( + initializeResult: AcpSessionRuntime.AcpSessionRuntimeStartResult["initializeResult"], +) => initializeResult.agentInfo?.name === "hermes-agent"; + export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(function* ( options: AcpRegistryAdapterV2Options, ) { @@ -212,10 +216,6 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu registryAgentId === "kimi-code" || (options.settings.source === "local" && /^kimi(\.exe|\.cmd)?$/i.test(options.settings.commandPath.split(/[\\/]/).pop() ?? "")); - // Hermes Agent is not in the public registry; local installs run `hermes acp`. - const isHermes = - options.settings.source === "local" && - /^hermes(\.exe|\.cmd)?$/i.test(options.settings.commandPath.split(/[\\/]/).pop() ?? ""); const isClaude = registryAgentId === "claude-acp" || (options.settings.source === "local" && @@ -289,9 +289,10 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu : {}), // Hermes replies on the root session when a background process it started exits; no // prompt response follows, so the continuation ends on the deferred-finalize debounce. - ...(isHermes - ? { enablePostSettleContinuation: true, deferFinalizeForBackgroundWork: true } - : {}), + // Hermes is not in the public registry and may run through a wrapper, so only its + // initialize reply identifies it. + enablePostSettleContinuation: isHermes, + deferFinalizeForBackgroundWork: isHermes, ...(isDevin ? { clientCapabilitiesMeta: { diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 8ededca9258c0..23883850a8765 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -585,7 +585,7 @@ export interface AcpAdapterV2Flavor { readonly isProviderWakeNotification?: ( notification: EffectAcpSchema.SessionNotification, ) => boolean; - readonly deferFinalizeForBackgroundWork?: boolean; + readonly deferFinalizeForBackgroundWork?: AcpNegotiatedFlag; readonly assertComplete?: Effect.Effect; /** Interrupt the local prompt fiber before `session/cancel` (Grok wedged prompts). */ readonly interruptPromptOnCancel?: boolean; @@ -617,7 +617,7 @@ export interface AcpAdapterV2Flavor { readonly restartRuntimeOnEveryInterrupt?: boolean; readonly terminateRuntimeProcessGroupOnInterrupt?: boolean; readonly preserveRuntimeOnSettledInterrupt?: boolean; - readonly enablePostSettleContinuation?: boolean; + readonly enablePostSettleContinuation?: AcpNegotiatedFlag; /** Settle on native idle after the accepted user echo, only on negotiated ACP v2. */ readonly followAgentWorkState?: boolean; /** @@ -635,6 +635,19 @@ export interface AcpAdapterV2Flavor { ) => boolean; } +/** + * A flavor flag that is either fixed, or read from the agent's `initialize` result for + * agents identified only there, such as one launched through a wrapper command. + */ +type AcpNegotiatedFlag = + | boolean + | ((initializeResult: EffectAcpSchema.InitializeResponse) => boolean); + +const readNegotiatedFlag = ( + flag: AcpNegotiatedFlag | undefined, + initializeResult: EffectAcpSchema.InitializeResponse, +) => (typeof flag === "function" ? flag(initializeResult) : flag === true); + function acpSupportsImagePrompts(input: { readonly flavorSupportsImagePrompts?: boolean | undefined; readonly negotiatedImage?: boolean | undefined; @@ -1849,8 +1862,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); const driver = flavor.driver; const continuationRequests = options.continuationRequests; - const postSettleContinuationEnabled = - flavor.enablePostSettleContinuation === true && continuationRequests !== undefined; const readCapabilities = Effect.gen(function* () { if (flavor.supportsNativeGoals === undefined) return flavor.capabilities; @@ -2057,6 +2068,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }; let pendingStopCloseTurn: ActiveAcpTurn | null = null; let followsAgentWorkState = false; + let postSettleContinuationEnabled = false; + let defersFinalizeForBackgroundWork = false; let agentWork: Extract< EffectAcpSchema.SessionUpdate, { sessionUpdate: "state_update" } @@ -2097,6 +2110,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( flavor.followAgentWorkState === true && continuationRequests !== undefined && setup.initializeResult.protocolVersion === 2; + postSettleContinuationEnabled = + continuationRequests !== undefined && + readNegotiatedFlag(flavor.enablePostSettleContinuation, setup.initializeResult); + defersFinalizeForBackgroundWork = readNegotiatedFlag( + flavor.deferFinalizeForBackgroundWork, + setup.initializeResult, + ); agentWork = null; rootForegroundWork = undefined; agentRequests.clear(); @@ -4053,7 +4073,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const rearmDeferredFinalize = /* Provider events include streaming deltas; avoid a span for each update. */ Effect.fnUntraced(function* (context: ActiveAcpTurn) { - if (!flavor.deferFinalizeForBackgroundWork) return; + if (!defersFinalizeForBackgroundWork) return; if (!context.promptSettled || context.finalized) return; if (hasDeferredBackgroundWork(context)) return; yield* scheduleDeferredFinalize(context); @@ -8290,7 +8310,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); scheduleDeferredFinalize = Effect.fn("scheduleDeferredFinalize")(function* (context) { - if (!flavor.deferFinalizeForBackgroundWork) return; + if (!defersFinalizeForBackgroundWork) return; if (!context.promptSettled || context.finalized || context.interrupted) return; if (hasDeferredBackgroundWork(context)) return; context.backgroundFinalizeGeneration += 1; @@ -8877,7 +8897,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( context.promptSettled = true; context.promptSettledStatus = "completed"; if (drainedWakeCount === 0) { - if (continuationWasRequested && flavor.deferFinalizeForBackgroundWork === true) { + if (continuationWasRequested && defersFinalizeForBackgroundWork) { if (hasDeferredBackgroundWork(context)) { yield* rearmDeferredFinalize(context); } else { @@ -9006,7 +9026,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ? "interrupted" : "cancelled" : "completed"; - if (flavor.deferFinalizeForBackgroundWork === true && !context.interrupted) { + if (defersFinalizeForBackgroundWork && !context.interrupted) { context.promptSettled = true; context.promptSettledStatus = status; for (const [taskId, completion] of context.backgroundCommands) { @@ -9027,7 +9047,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return; } if ( - flavor.deferFinalizeForBackgroundWork === true && + defersFinalizeForBackgroundWork && !context.interrupted && hasDeferredBackgroundWork(context) ) { @@ -9173,6 +9193,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }), ); + // A replacement agent can negotiate capabilities the initial agent did not have. + const canReportBackgroundWork = + continuationRequests !== undefined && + (flavor.followAgentWorkState === true || Boolean(flavor.enablePostSettleContinuation)); const sessionRuntime: ProviderAdapter.ProviderAdapterV2SessionRuntime = { instanceId: options.instanceId, driver, @@ -9190,9 +9214,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( : flavor.getModelContextWindow?.(selection, session); }, }), - ...(postSettleContinuationEnabled || followsAgentWorkState + ...(canReportBackgroundWork ? { hasPendingBackgroundWork: Effect.gen(function* () { + if (!postSettleContinuationEnabled && !followsAgentWorkState) return false; const rootSessionId = yield* Ref.get(activeSessionId); if ( followsAgentWorkState && diff --git a/scripts/scenarios/hermes-wrapper-keeps-background-reply.e2e.ts b/scripts/scenarios/hermes-wrapper-keeps-background-reply.e2e.ts new file mode 100644 index 0000000000000..b697853dac928 --- /dev/null +++ b/scripts/scenarios/hermes-wrapper-keeps-background-reply.e2e.ts @@ -0,0 +1,130 @@ +// @effect-diagnostics nodeBuiltinImport:off -- The scenario stages a local ACP executable and its wake gate. +import * as NodeFSP from "node:fs/promises"; +import * as NodePath from "node:path"; + +import { expect } from "e2e"; + +import { T3_HOME } from "../e2e.config.ts"; +import { makeState, runPromise, test, WEB } from "./t3.ts"; + +const COMPLETION = "The background command printed DONE."; +const ACP = ` +import { unwatchFile, watchFile } from "node:fs"; +import { createInterface } from "node:readline"; + +const sessionId = "hermes-scenario"; +const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n"); +const respond = (id, result) => send({ id, result }); +const chunk = (text) => send({ + method: "session/update", + params: { sessionId, update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } } }, +}); +for await (const line of createInterface({ input: process.stdin })) { + const { id, method } = JSON.parse(line); + if (id === undefined) continue; + if (method === "initialize") { + respond(id, { + protocolVersion: 1, + agentInfo: { name: "hermes-agent", version: "0.23.1" }, + agentCapabilities: { loadSession: true }, + authMethods: [], + }); + } else if (method === "session/new") { + respond(id, { sessionId }); + } else if (method === "session/prompt") { + chunk("Started it in the background."); + respond(id, { stopReason: "end_turn" }); + // Hermes sends the follow-up on the root session, without another prompt response. + const gate = process.argv[2]; + watchFile(gate, { interval: 100 }, (stat) => { + if (stat.nlink === 0) return; + unwatchFile(gate); + chunk(${JSON.stringify(COMPLETION)}); + }); + } else { + send({ id, error: { code: -32601, message: "Method not found" } }); + } +} +`; + +test( + "Hermes sends its background completion reply when launched through a wrapper", + WEB, + async ({ t3, app, screen }) => { + const project = await t3.project("demo"); + const script = NodePath.join(project, "hermes-acp.mjs"); + const gate = NodePath.join(project, "process-exited"); + const settingsPath = NodePath.join(T3_HOME, "userdata/settings.json"); + const originalSettings = await NodeFSP.readFile(settingsPath, "utf8"); + const settings = JSON.parse(originalSettings); + await NodeFSP.writeFile(script, ACP); + settings.providerInstances["hermes-wrapper"] = { + driver: "acpRegistry", + displayName: "Hermes Agent", + enabled: true, + config: { + source: "local", + commandPath: process.execPath, + commandArgs: [script, gate], + }, + }; + try { + await NodeFSP.writeFile(settingsPath, JSON.stringify(settings)); + const { cli } = makeState(T3_HOME); + // The watcher reloads settings asynchronously. Retry only before a thread was created. + let threadId: string | undefined; + for (let attempt = 0; attempt < 8 && threadId === undefined; attempt++) { + const started = await runPromise( + cli( + [ + "thread", + "start", + project, + "Start a background command that reports DONE when it exits.", + "--title", + "Hermes background reply", + "--provider", + "hermes-wrapper", + "--model", + "default", + "--wait", + "--json", + ], + [0, 1], + ), + ); + if (!started.stdout.includes("threadId")) continue; + const result = JSON.parse(started.stdout) as { + threadId: string; + status: string; + reply: string | null; + }; + if ( + result.status !== "completed" || + !result.reply?.includes("Started it in the background.") + ) { + throw new Error( + `Hermes foreground turn did not complete: ${started.stdout} ${started.stderr}`, + ); + } + threadId = result.threadId; + } + if (threadId === undefined) throw new Error("Could not start the Hermes foreground turn."); + + await t3.open({ threadId }); + await screen + .getByText("Started it in the background.", { exact: true }) + .waitFor({ timeout: 60_000 }); + await NodeFSP.writeFile(gate, ""); + try { + await expect(screen.getByText(COMPLETION, { exact: true })).toBeVisible({ + timeout: 15_000, + }); + } finally { + await app.screenshot("hermes-background-reply"); + } + } finally { + await NodeFSP.writeFile(settingsPath, originalSettings); + } + }, +); From b6d6717df6229db4eec6366135a82f0cc0684283 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 18:51:09 -0800 Subject: [PATCH 088/183] fix(pi): teardown returns once the Pi process group exits (#38845) --- .../provider-pi/src/server/adapter.test.ts | 46 +++++++++++++++++++ packages/provider-pi/src/server/rpc.ts | 21 ++++++++- 2 files changed, 65 insertions(+), 2 deletions(-) diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 4af5beda8e381..50501dcc9cce1 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -20,6 +20,7 @@ import { type OrchestrationV2ProviderTurn, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; +import * as PlatformError from "effect/PlatformError"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; @@ -7182,4 +7183,49 @@ process.stdout.write('{"type":"ready"}\\n'); assert.deepEqual(cues, ["SIGTERM"]); }).pipe(Effect.provide(NodeServices.layer)), ); + + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "returns once the pi process group exits instead of waiting out the grace", + () => + Effect.gen(function* () { + const realSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const childExit = yield* Deferred.make< + ChildProcessSpawner.ExitCode, + PlatformError.PlatformError + >(); + const spawner = ChildProcessSpawner.make((command) => + realSpawner + .spawn(command) + .pipe( + Effect.tap((handle) => + handle.exitCode.pipe(Deferred.into(childExit), Effect.forkDetach), + ), + ), + ); + const scope = yield* Scope.make(); + const connection = yield* makePiRpcConnection({ + command: process.execPath, + args: [ + "-e", + 'process.on("SIGTERM",()=>process.exit(0));process.stdin.resume();' + + 'process.stdout.write(\'{"type":"ready"}\\n\');', + ], + cwd: undefined, + env: {}, + }).pipe( + Scope.provide(scope), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + assert.equal((yield* Queue.take(connection.events))["type"], "ready"); + + const closing = yield* Scope.close(scope, Exit.void).pipe(Effect.forkChild); + yield* Deferred.await(childExit); + yield* TestClock.adjust(Duration.millis(999)); + const closedBeforeGrace = closing.pollUnsafe() !== undefined; + + yield* TestClock.adjust(Duration.seconds(1)); + yield* Fiber.join(closing); + assert.isTrue(closedBeforeGrace); + }).pipe(Effect.provide(NodeServices.layer)), + ); }); diff --git a/packages/provider-pi/src/server/rpc.ts b/packages/provider-pi/src/server/rpc.ts index 9b016051a1501..3cdb2058f1cf3 100644 --- a/packages/provider-pi/src/server/rpc.ts +++ b/packages/provider-pi/src/server/rpc.ts @@ -105,6 +105,7 @@ export interface PiRpcConnection { const DEFAULT_REQUEST_TIMEOUT_MS = 30_000; const TERMINATION_GRACE = Duration.seconds(1); +const TERMINATION_POLL_INTERVAL = Duration.millis(20); interface PendingPiRequest { readonly deferred: Deferred.Deferred; @@ -196,10 +197,14 @@ function parsePiRecord(line: string): PiRpcRecord | undefined { const terminatePiProcess = Effect.fn("PiRpc.terminatePiProcess")(function* ( kill: (signal: NodeJS.Signals) => boolean, hasExited: () => boolean, + groupGone: () => boolean, ) { if (hasExited()) return; if (!kill("SIGTERM")) return; - yield* Effect.sleep(TERMINATION_GRACE); + yield* Effect.sleep(TERMINATION_POLL_INTERVAL).pipe( + Effect.repeat({ until: groupGone }), + Effect.timeoutOption(TERMINATION_GRACE), + ); if (hasExited()) return; kill("SIGKILL"); }); @@ -253,6 +258,16 @@ export const makePiRpcConnection = Effect.fnUntraced(function* (options: PiRpcSp } }; + // EPERM means a group member is still alive, so only ESRCH ends the SIGTERM grace early. + const processGroupGone = (): boolean => { + try { + signalProcessGroup(Number(child.pid), 0); + return false; + } catch (cause) { + return (cause as NodeJS.ErrnoException | undefined)?.code === "ESRCH"; + } + }; + // Windows process.kill leaves extension children and pipes alive; taskkill /T reaps the tree. const terminateWindowsTree = Effect.gen(function* () { if (hasExited()) return; @@ -263,7 +278,9 @@ export const makePiRpcConnection = Effect.fnUntraced(function* (options: PiRpcSp }).pipe(Effect.scoped, Effect.ignore); const terminateProcess = - platform === "win32" ? terminateWindowsTree : terminatePiProcess(killProcessGroup, hasExited); + platform === "win32" + ? terminateWindowsTree + : terminatePiProcess(killProcessGroup, hasExited, processGroupGone); // Register teardown immediately after spawn so interrupted setup cannot leak a detached process. yield* Scope.addFinalizer(scope, terminateProcess.pipe(Effect.ignore, Effect.uninterruptible)); From 5b265f8eb7db05df055b2e882d4c10d332076d6b Mon Sep 17 00:00:00 2001 From: regexboi <125159586+regexboi@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:51:21 -0500 Subject: [PATCH 089/183] fix(desktop): pnpm global commands find their bin directory (#38801) Co-authored-by: Julius Marminge --- apps/desktop/src/shell/DesktopShellEnvironment.test.ts | 6 ++++++ apps/desktop/src/shell/DesktopShellEnvironment.ts | 3 +++ packages/contracts/src/resourceTelemetry.ts | 1 + 3 files changed, 10 insertions(+) diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts index f082020a5dec1..a9a754919c7d7 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts @@ -231,12 +231,14 @@ describe("DesktopShellEnvironment", () => { __MISE_DIFF: "old-mise", SSH_AUTH_SOCK: "/old-session.sock", JAVA_HOME: "/old/java", + PNPM_HOME: "/old/pnpm", SSL_CERT_FILE: "/old/cert.pem", }), }); const cachePath = `${stateDir}/shell-environment-cache.json`; const cached = yield* fs.readFileString(cachePath).pipe(Effect.flatMap(decodeCache)); assert.equal(cached.environment.PATH, "/old/bin:/usr/bin"); + assert.equal(cached.environment.PNPM_HOME, "/old/pnpm"); assert.notProperty(cached.environment, "SSH_AUTH_SOCK"); const started = yield* Deferred.make(); const release = yield* Deferred.make(); @@ -285,6 +287,7 @@ describe("DesktopShellEnvironment", () => { assert.equal(env.PATH, "/fresh/bin:/launcher/bin"); assert.equal(env.__MISE_DIFF, "fresh-mise"); assert.isUndefined(env.JAVA_HOME); + assert.isUndefined(env.PNPM_HOME); assert.isUndefined(env.SSL_CERT_FILE); const fresh = yield* Stream.runHead(service.updates); assert.isTrue(Option.isSome(fresh)); @@ -298,6 +301,7 @@ describe("DesktopShellEnvironment", () => { const refreshed = yield* fs.readFileString(cachePath).pipe(Effect.flatMap(decodeCache)); assert.equal(refreshed.environment.PATH, "/fresh/bin:/launcher/bin"); assert.notProperty(refreshed.environment, "JAVA_HOME"); + assert.notProperty(refreshed.environment, "PNPM_HOME"); assert.notProperty(refreshed.environment, "SSL_CERT_FILE"); }).pipe(Effect.provide(NodeServices.layer)), ); @@ -352,6 +356,7 @@ describe("DesktopShellEnvironment", () => { PATH: "/cached/bin", __MISE_DIFF: "cached-mise", JAVA_HOME: "/cached/java", + PNPM_HOME: "/cached/pnpm", NODE_EXTRA_CA_CERTS: "/cached/ca.pem", SSL_CERT_FILE: "/cached/cert.pem", SSL_CERT_DIR: "/cached/certs", @@ -392,6 +397,7 @@ describe("DesktopShellEnvironment", () => { assert.equal(env.PATH, "/cached/bin:/usr/bin"); assert.equal(env.__MISE_DIFF, "cached-mise"); assert.equal(env.JAVA_HOME, "/launcher/java"); + assert.equal(env.PNPM_HOME, "/cached/pnpm"); assert.equal(env.NODE_EXTRA_CA_CERTS, "/launcher/ca.pem"); assert.equal(env.SSL_CERT_FILE, ""); assert.equal(env.SSL_CERT_DIR, "/cached/certs"); diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.ts index 6d84b87e6fcc6..ab370227804b1 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts @@ -127,6 +127,7 @@ const LOGIN_SHELL_ENV_NAMES = [ "T3CODE_RELEASE_BASE_URL", "__MISE_DIFF", "JAVA_HOME", + "PNPM_HOME", ] as const; const WINDOWS_PROFILE_ENV_NAMES = ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"] as const; const LOCALE_ENV_NAMES = ["LANG", "LC_ALL", "LC_CTYPE"] as const; @@ -549,6 +550,7 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix "SSL_CERT_DIR", "NODE_EXTRA_CA_CERTS", "JAVA_HOME", + "PNPM_HOME", "T3CODE_TELEMETRY_ENABLED", "T3CODE_GITHUB_APP_CLIENT_ID", "T3CODE_RELEASE_BASE_URL", @@ -652,6 +654,7 @@ const CACHED_ENV_NAMES = [ "HOMEBREW_CELLAR", "HOMEBREW_REPOSITORY", "JAVA_HOME", + "PNPM_HOME", "SSL_CERT_FILE", "SSL_CERT_DIR", "NODE_EXTRA_CA_CERTS", diff --git a/packages/contracts/src/resourceTelemetry.ts b/packages/contracts/src/resourceTelemetry.ts index ff6fdc25997e4..f3800089f5c20 100644 --- a/packages/contracts/src/resourceTelemetry.ts +++ b/packages/contracts/src/resourceTelemetry.ts @@ -324,6 +324,7 @@ export const ShellEnvironmentPatch = Schema.Struct({ 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)), + PNPM_HOME: Schema.optionalKey(Schema.NullOr(Schema.String)), FNM_DIR: Schema.optionalKey(Schema.NullOr(Schema.String)), FNM_MULTISHELL_PATH: Schema.optionalKey(Schema.NullOr(Schema.String)), }); From 8729bdd42c6a6d0b0ea715ed29a1760875d4ecda Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 18:53:28 -0800 Subject: [PATCH 090/183] feat(server): pairing-link sessions renew with the device's DPoP key (#37980) (#38860) --- docs/operations/relay-observability.md | 7 ++++--- infra/relay/src/monitoring.ts | 8 +++++--- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/docs/operations/relay-observability.md b/docs/operations/relay-observability.md index 55a6eb7fd017c..b6d131b913728 100644 --- a/docs/operations/relay-observability.md +++ b/docs/operations/relay-observability.md @@ -153,9 +153,10 @@ was about 2,100). **Traffic dropped.** The Worker is down, a deploy broke it, or spans stopped reaching Axiom. Check `https://relay.t3.codes/health` first. -**Tunnel cleanup stopped / tunnel deletions failing.** Warnings for the five-minute reaper that deletes -idle Cloudflare tunnels. "Stopped" counts sweeps that finished, so it also fires when every sweep -fails; a sweep fails when listing tunnels does, usually behind Cloudflare 429s. Idle tunnels are +**Tunnel cleanup stopped / tunnel deletions failing.** Monitors for the five-minute reaper that deletes +idle Cloudflare tunnels. "Stopped" pages after two hours without a finished sweep, so it also fires +when every sweep fails; a sweep fails when listing tunnels does, behind Cloudflare 429s or listings +that outlast the sweep's list timeout. "Deletions failing" is a warning. Idle tunnels are billed until the reaper catches up, which the "Idle tunnels in Cloudflare" chart shows. A failed sweep records no counts, so while sweeps fail the chart stops at the last good one; check the tunnel list in the Cloudflare dashboard for current numbers. For failed diff --git a/infra/relay/src/monitoring.ts b/infra/relay/src/monitoring.ts index bdf7f8a68a983..ff7295f018d90 100644 --- a/infra/relay/src/monitoring.ts +++ b/infra/relay/src/monitoring.ts @@ -181,15 +181,17 @@ const relayMonitors: ReadonlyArray = [ }, { id: "RelayTunnelCleanupStoppedMonitor", - severity: "warn", + // Pages because nothing else surfaces it: unnoticed, it ran 2026-11-15..18 while 27k+ idle tunnels piled up. + severity: "page", name: "T3 Connect relay: tunnel cleanup stopped", description: - "Tunnel cleanup sweeps that finished in 30 min. Healthy: 6. The cron is not running, or every sweep fails, as during the 2026-10-19 Cloudflare 429s when listing tunnels timed out. Idle tunnels pile up and are billed meanwhile.", + "Tunnel cleanup sweeps that finished in 2 h. Healthy: 24. The cron is not running, or every sweep fails, as during the 2026-10-19 Cloudflare 429s and from 2026-11-15 when listing tunnels timed out. Idle tunnels pile up and are billed meanwhile.", query: (dataset) => `['${dataset}']\n| where ${SWEEP} and error != true\n| summarize sweeps = count()`, operator: "Below", threshold: 1, - rangeMinutes: 30, + rangeMinutes: 120, + intervalMinutes: 15, triggerFromNRuns: 2, alertOnNoData: true, }, From 523a98447eaa1167ba4affe2270768e25f7565c2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 18:59:57 -0800 Subject: [PATCH 091/183] fix(web): files under "Also in this stop" in a review guide can be commented on (#38858) --- .../pullRequest/guide/GuideExcerpt.tsx | 147 +++++++++++------- .../pullRequest/guide/GuideFileDiff.tsx | 93 ++++++++++- .../pullRequest/guide/GuideStop.tsx | 7 +- 3 files changed, 187 insertions(+), 60 deletions(-) diff --git a/apps/web/src/components/pullRequest/guide/GuideExcerpt.tsx b/apps/web/src/components/pullRequest/guide/GuideExcerpt.tsx index 9d828fcbe5b82..40455ccc1adaf 100644 --- a/apps/web/src/components/pullRequest/guide/GuideExcerpt.tsx +++ b/apps/web/src/components/pullRequest/guide/GuideExcerpt.tsx @@ -73,7 +73,7 @@ interface ExcerptAnnotation { readonly draft: boolean; } -interface ExcerptDraft { +export interface CommentDraft { readonly range: SelectedLineRange; readonly position: PullRequestReviewPosition; readonly startPosition?: PullRequestReviewPosition; @@ -117,7 +117,7 @@ export function GuideExcerpt({ onOpenFile: (path: string) => void; }) { // Keep selections outside ExcerptDiff to survive head reloads. - const [draft, setDraft] = useState(null); + const [draft, setDraft] = useState(null); const slice = excerptSlice(file, excerpt); return ( @@ -178,8 +178,8 @@ function ExcerptDiff({ excerpt: PullRequestReviewGuideExcerpt; file: FileDiffMetadata; slice: ExcerptSlice; - draft: ExcerptDraft | null; - setDraft: (draft: ExcerptDraft | null) => void; + draft: CommentDraft | null; + setDraft: (draft: CommentDraft | null) => void; loadDiffFiles: FileDiffContentsLoader; notes: ReadonlyArray; commenting: ExcerptCommenting | null; @@ -235,29 +235,11 @@ function ExcerptDiff({ })(); const beginComment = (range: SelectedLineRange | null) => { - if (range === null) return; - const anchor = resolveDiffReviewAnchor(file, range, commenting?.rangeComments === true); - if (anchor === null) return; - setDraft({ range, ...anchor }); + const next = commentDraftFor(file, range, commenting); + if (next !== null) setDraft(next); }; const gt = useGT(); const interactive = commenting !== null && draft === null; - const onAskAgent = commenting?.onAskAgent ?? null; - const askAgent = (request: string) => { - if (draft === null || onAskAgent === null) return; - const comment = buildDiffReviewComment({ - id: `pull-request-guide:${diffReviewSelectionId(excerpt.path, draft.range)}`, - sectionId: `pull-request-guide:${excerpt.path}`, - // oxlint-disable-next-line t3code/no-untranslated-copy -- context title sent to the agent - sectionTitle: "Review guide", - filePath: excerpt.path, - fileDiff: file, - range: draft.range, - text: request, - }); - setDraft(null); - if (comment !== null) onAskAgent(comment, request); - }; const options = { diffStyle: "unified" as const, @@ -303,40 +285,12 @@ function ExcerptDiff({ /> ))} {annotation.metadata.draft && draft !== null && commenting !== null ? ( - askAgent(text), - }, - } - : {})} - onCancel={() => setDraft(null)} - onComment={(body) => { - if (!commenting.canComment) { - askAgent(body); - return; - } - commenting.onComment({ - path: excerpt.path, - oldPath: previousPathOf(file, excerpt.path), - position: draft.position, - startPosition: draft.startPosition, - body, - }); - setDraft(null); - }} + setDraft(null)} /> ) : null}
@@ -379,3 +333,80 @@ function previousPathOf(file: FileDiffMetadata, path: string): string | null { const previous = resolveFileDiffPreviousPath(file); return previous === path ? null : previous; } + +export function commentDraftFor( + file: FileDiffMetadata, + range: SelectedLineRange | null, + commenting: ExcerptCommenting | null, +): CommentDraft | null { + if (range === null || commenting === null) return null; + const anchor = resolveDiffReviewAnchor(file, range, commenting.rangeComments); + return anchor === null ? null : { range, ...anchor }; +} + +export function GuideCommentDraft({ + path, + file, + draft, + commenting, + onClose, +}: { + path: string; + file: FileDiffMetadata; + draft: CommentDraft; + commenting: ExcerptCommenting; + onClose: () => void; +}) { + const gt = useGT(); + const onAskAgent = commenting.onAskAgent; + const askAgent = (request: string) => { + if (onAskAgent === null) return; + const comment = buildDiffReviewComment({ + id: `pull-request-guide:${diffReviewSelectionId(path, draft.range)}`, + sectionId: `pull-request-guide:${path}`, + // oxlint-disable-next-line t3code/no-untranslated-copy -- context title sent to the agent + sectionTitle: "Review guide", + filePath: path, + fileDiff: file, + range: draft.range, + text: request, + }); + onClose(); + if (comment !== null) onAskAgent(comment, request); + }; + return ( + askAgent(text), + }, + } + : {})} + onCancel={onClose} + onComment={(body) => { + if (!commenting.canComment) { + askAgent(body); + return; + } + commenting.onComment({ + path, + oldPath: previousPathOf(file, path), + position: draft.position, + startPosition: draft.startPosition, + body, + }); + onClose(); + }} + /> + ); +} diff --git a/apps/web/src/components/pullRequest/guide/GuideFileDiff.tsx b/apps/web/src/components/pullRequest/guide/GuideFileDiff.tsx index e53c87ba2255f..e14d4a0b4e737 100644 --- a/apps/web/src/components/pullRequest/guide/GuideFileDiff.tsx +++ b/apps/web/src/components/pullRequest/guide/GuideFileDiff.tsx @@ -1,27 +1,89 @@ import { cloneFileDiffMetadata, + type DiffLineAnnotation, type FileDiffContentsLoader, type FileDiffMetadata, + type SelectedLineRange, } from "@pierre/diffs"; import { FileDiff } from "@pierre/diffs/react"; +import { useState } from "react"; import { useRenderedAppearance } from "~/hooks/useTheme"; import { resolveDiffThemeName } from "~/lib/diffRendering"; import { PREFERRED_HIGHLIGHTER } from "~/lib/syntaxHighlighting"; import { DIFF_VIEW_UNSAFE_CSS } from "../../diffs/StyledDiffCodeView"; +import { + getReviewPositionAnchor, + PendingReviewCommentCard, + toViewerSide, +} from "../PullRequestReviewAnnotation"; +import type { PendingReviewComment } from "../pullRequestReviewStore"; +import { + commentDraftFor, + GuideCommentDraft, + type CommentDraft, + type ExcerptCommenting, +} from "./GuideExcerpt"; + +interface FileAnnotation { + readonly pending: ReadonlyArray; + readonly draft: boolean; +} export function GuideFileDiff({ + path, file, + commenting, loadDiffFiles, }: { + path: string; file: FileDiffMetadata; + commenting: ExcerptCommenting | null; loadDiffFiles: FileDiffContentsLoader; }) { const resolvedTheme = useRenderedAppearance(); + const [draft, setDraft] = useState(null); // Loading the unchanged lines rewrites the diff it is given; the excerpts read the same file // as a patch, so this view expands a copy of its own. const expandable = cloneFileDiffMetadata(file); + + const annotations = (() => { + const groups = new Map>(); + const update = ( + side: "additions" | "deletions", + line: number, + change: (metadata: FileAnnotation) => FileAnnotation, + ) => { + const key = `${side}:${line}`; + const group = groups.get(key) ?? { + side, + lineNumber: line, + metadata: { pending: [], draft: false }, + }; + groups.set(key, { ...group, metadata: change(group.metadata) }); + }; + for (const comment of commenting?.pending ?? []) { + if (comment.path !== path) continue; + const anchor = getReviewPositionAnchor(comment.position); + update(toViewerSide(anchor.side), anchor.line, (metadata) => ({ + ...metadata, + pending: [...metadata.pending, comment], + })); + } + if (draft !== null) { + const anchor = getReviewPositionAnchor(draft.position); + update(toViewerSide(anchor.side), anchor.line, (metadata) => ({ ...metadata, draft: true })); + } + return [...groups.values()]; + })(); + + const beginComment = (range: SelectedLineRange | null) => { + const next = commentDraftFor(file, range, commenting); + if (next !== null) setDraft(next); + }; + const interactive = commenting !== null && draft === null; + const options = { diffStyle: "unified" as const, lineDiffType: "none" as const, @@ -31,11 +93,40 @@ export function GuideFileDiff({ themeType: resolvedTheme, preferredHighlighter: PREFERRED_HIGHLIGHTER, unsafeCSS: DIFF_VIEW_UNSAFE_CSS, + enableGutterUtility: interactive, + enableLineSelection: interactive, + onGutterUtilityClick: beginComment, + onLineSelectionEnd: beginComment, loadDiffFiles, }; return (
- + + fileDiff={expandable} + options={options} + lineAnnotations={annotations} + selectedLines={draft?.range ?? null} + renderAnnotation={(annotation) => ( +
+ {annotation.metadata.pending.map((comment) => ( + commenting?.onRemove(comment.id)} + /> + ))} + {annotation.metadata.draft && draft !== null && commenting !== null ? ( + setDraft(null)} + /> + ) : null} +
+ )} + />
); } diff --git a/apps/web/src/components/pullRequest/guide/GuideStop.tsx b/apps/web/src/components/pullRequest/guide/GuideStop.tsx index 1c09d2883793e..206541769dc3a 100644 --- a/apps/web/src/components/pullRequest/guide/GuideStop.tsx +++ b/apps/web/src/components/pullRequest/guide/GuideStop.tsx @@ -218,7 +218,12 @@ export function GuideStop({ {diff !== undefined ? ( - + ) : (

{diffLoading From 12be92d034f3889cfecac077c6bb655632d9074c Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Wed, 18 Nov 2026 19:04:54 -0800 Subject: [PATCH 092/183] fix(server): Antigravity threads keep going after a background command finishes (#38864) agy ends its prompt while a backgrounded command still runs. When the command finishes, agy starts a reply by itself with no prompt open. T3 Code dropped that output and failed its permission request, so the thread looked stopped. The built-in Antigravity adapter and the registry agy path now continue in a new run, and wait for the reply's closing usage_update instead of the 3 s debounce. T3 tool titles with the "Run mcp_t3-code_" form are recognized again, so html_render pages show. Takes over #36138, #37485, #30083 and part of #35073. Co-authored-by: Denis Bolba Co-authored-by: drstrangerujn <343873859@qq.com> Co-authored-by: Vedanta-krit das (Alex Vedmedenko) Co-authored-by: Julius Marminge Co-Authored-By: Claude Fable 5.2 --- .../Adapters/AcpRegistryAdapterV2.test.ts | 187 +++++++++++++- .../Adapters/AntigravityAdapterV2.test.ts | 242 +++++++++++++++++- .../Adapters/AntigravityAdapterV2.ts | 6 + .../src/server/adapter.ts | 12 +- packages/provider-acp/src/server/adapter.ts | 69 ++++- .../src/server/runtimeModel.test.ts | 11 +- .../provider-acp/src/server/runtimeModel.ts | 18 +- 7 files changed, 524 insertions(+), 21 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts index 1c84345c729fa..a532f2ced7704 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts @@ -212,6 +212,7 @@ const openClaudeReplaySession = Effect.fn("openClaudeReplaySession")(function* ( continuationEnabled = true, agentId: string | Record = "claude-acp", replacementEntries?: ReadonlyArray, + runtimeMode: "approval-required" | "full-access" = "approval-required", ) { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -292,7 +293,6 @@ const openClaudeReplaySession = Effect.fn("openClaudeReplaySession")(function* ( ); const threadId = ThreadId.make("thread-claude-lifecycle"); const modelSelection = { instanceId, model: "default" } as const; - const runtimeMode = "approval-required"; const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ runtimeMode, interactionMode: "default", @@ -452,6 +452,191 @@ const claudeUnrelatedChildren = [ ]; describe("AcpRegistryAdapterV2", () => { + it.effect.each([ + { commandPath: "/root/.local/bin/agy", offers: 1 }, + { commandPath: "C:\\tools\\agy.exe", offers: 1 }, + { commandPath: "/opt/bin/other-agent", offers: 0 }, + ])("continues late output only for agy ($commandPath)", ({ commandPath, offers }) => + Effect.gen(function* () { + const gate = makeProviderReplayGate(["wake"]); + const update = (sessionUpdate: Record) => + claudeFrames.update(CLAUDE_ROOT_SESSION, sessionUpdate); + const session = yield* openClaudeReplaySession( + [ + { + type: "expect_outbound", + frame: { kind: "request", method: "initialize", params: "" }, + }, + { + type: "emit_inbound", + frame: { + kind: "response", + method: "initialize", + result: { + protocolVersion: 1, + agentInfo: { name: "Antigravity ACP Server", version: "1.5.9" }, + agentCapabilities: { loadSession: true }, + authMethods: [], + }, + }, + }, + claudeFrames.open[2], + claudeFrames.open[3], + claudeFrames.prompt(1)[0], + { + type: "emit_inbound", + frame: { + kind: "response", + method: "session/prompt", + result: { stopReason: "end_turn" }, + }, + }, + { + ...update({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Background work finished." }, + }), + label: "wake", + }, + // agy ends each reply with usage_update; this one ends before the continuation run starts. + update({ sessionUpdate: "usage_update", used: 100, size: 1000 }), + claudeMarker("late output received"), + ], + gate, + true, + { source: "local", commandPath, commandArgs: ["acp"] }, + ); + yield* session.runtime.startTurn(session.turnInput(1)); + assert.equal((yield* session.terminal).status, "completed"); + gate.release("wake"); + yield* session.throughMarker("late output received"); + assert.lengthOf(session.offers, offers, "late output must only wake agy"); + if (offers === 0) return; + yield* session.offers[0]!.dispatchIfCurrent!(Effect.void); + yield* session.runtime.startTurn(session.turnInput(2, { continuation: true })); + yield* TestClock.adjust("3 seconds"); + const continued = yield* session.until((event) => event.type === "turn.terminal"); + assert.include(JSON.stringify(continued), "Background work finished."); + const terminal = continued.at(-1)!; + if (terminal.type !== "turn.terminal") throw new Error("Missing continuation terminal"); + assert.equal(terminal.status, "completed"); + }).pipe(Effect.provide(layerTest)), + ); + + it.effect.each(["approval-required", "full-access"] as const)( + "continues an agy permission request after the prompt settles (%s)", + (runtimeMode) => + Effect.gen(function* () { + const gate = makeProviderReplayGate(["wake", "reply"]); + const session = yield* openClaudeReplaySession( + [ + { + type: "expect_outbound", + frame: { kind: "request", method: "initialize", params: "" }, + }, + { + type: "emit_inbound", + frame: { + kind: "response", + method: "initialize", + result: { + protocolVersion: 1, + agentInfo: { name: "Antigravity ACP Server", version: "1.5.9" }, + agentCapabilities: { loadSession: true }, + authMethods: [], + }, + }, + }, + claudeFrames.open[2], + claudeFrames.open[3], + claudeFrames.prompt(1)[0], + { + type: "emit_inbound", + frame: { + kind: "response", + method: "session/prompt", + result: { stopReason: "end_turn" }, + }, + }, + { + type: "emit_inbound", + label: "wake", + frame: { + kind: "request", + method: "session/request_permission", + params: { + sessionId: CLAUDE_ROOT_SESSION, + toolCall: { + toolCallId: "late-command", + title: "Run command", + kind: "execute", + status: "pending", + }, + options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }], + }, + }, + }, + claudeMarker("late permission received"), + { + type: "expect_outbound", + frame: { + kind: "response", + method: "session/request_permission", + result: { outcome: { outcome: "selected", optionId: "allow" } }, + }, + }, + { + ...claudeFrames.update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Command approved." }, + }), + label: "reply", + }, + claudeFrames.update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "usage_update", + used: 100, + size: 1000, + }), + ], + gate, + true, + { source: "local", commandPath: "/root/.local/bin/agy", commandArgs: ["acp"] }, + undefined, + runtimeMode, + ); + yield* session.runtime.startTurn(session.turnInput(1)); + assert.equal((yield* session.terminal).status, "completed"); + gate.release("wake"); + yield* session.throughMarker("late permission received"); + assert.lengthOf(session.offers, 1, "a permission request must offer a continuation"); + yield* session.offers[0]!.dispatchIfCurrent!(Effect.void); + yield* session.runtime.startTurn(session.turnInput(2, { continuation: true })); + if (runtimeMode === "approval-required") { + const events = yield* session.until( + (event) => + event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending", + ); + const request = events.at(-1)!; + if (request.type !== "runtime_request.updated") throw new Error("Missing approval"); + yield* TestClock.adjust("5 seconds"); + yield* session.runtime.respondToRuntimeRequest({ + requestId: request.runtimeRequest.id, + decision: "accept", + }); + } + // The model can be silent longer than the finalize debounce before it goes on. + yield* TestClock.adjust("10 seconds"); + gate.release("reply"); + const output = yield* session.until( + (event) => event.type === "message.updated" && event.message.text === "Command approved.", + ); + assert.isTrue(output.some((event) => event.type === "message.updated")); + assert.isFalse(output.some((event) => event.type === "turn.terminal")); + yield* TestClock.adjust("3 seconds"); + assert.equal((yield* session.terminal).status, "completed"); + }).pipe(Effect.provide(layerTest)), + ); + it("preserves and sanitizes structured ACP errors without exposing arbitrary defects", () => { const limit = new EffectAcpErrors.AcpRequestError({ code: -31001, diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index b281ecc16ab84..5e3a971dba1c9 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -23,9 +23,11 @@ import * as FileSystem from "effect/FileSystem"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; +import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Stream from "effect/Stream"; import { ChildProcessSpawner } from "effect/process"; +import * as TestClock from "effect/testing/TestClock"; import type * as EffectAcpSchema from "effect-acp/compat"; import * as EffectAcpErrors from "effect-acp/errors"; @@ -38,6 +40,7 @@ import { normalizeAntigravitySessionUpdate } from "../../provider/acp/Antigravit import { ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE } from "../../provider/antigravityAuthSupport.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; import { makeAntigravityAcpAdapterFlavor, makeAntigravityAdapterV2, @@ -614,6 +617,11 @@ describe("AntigravityAdapterV2 html_render pages", () => { const report = { html: `${rows.join("")}
`, title: "Revenue", height: 240 }; const failed = { ...report, html: "

Revenue

" }; const errored = { ...report, html: "

Revenue error

" }; + const telemetry = { + html: `
    ${rows.join("").replaceAll("tr", "li")}
`, + title: "Telemetry", + height: 411, + }; const adapter = yield* makeAntigravityAdapterV2({ instanceId, selfInvocation: yield* resolveSelfInvocation(), @@ -730,6 +738,21 @@ describe("AntigravityAdapterV2 html_render pages", () => { status: "completed", rawOutput: "Summary of published", }); + // agy 1.5.8 titles the call with its MCP name and completes without any output. + yield* send({ + sessionUpdate: "tool_call", + toolCallId: "agy-1.5.8", + title: "Run mcp_t3-code_html_render", + kind: "other", + status: "in_progress", + rawInput: { ...telemetry, toolSummary: "Render telemetry" }, + }); + yield* mcpSessions.recordHtmlRender(threadId, telemetry, page("agy-1.5.8")); + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId: "agy-1.5.8", + status: "completed", + }); return { stopReason: "end_turn" as const }; }), })), @@ -855,7 +878,7 @@ describe("AntigravityAdapterV2 html_render pages", () => { ), [page("report"), page("report"), page("replacement"), page("replacement")], ); - for (const name of ["failed-retry", "error-retry"]) { + for (const name of ["failed-retry", "error-retry", "agy-1.5.8"]) { assert.deepEqual(tool(name), { status: "completed", toolName: "t3-code.html_render", @@ -866,6 +889,223 @@ describe("AntigravityAdapterV2 html_render pages", () => { assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, report), undefined); assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, failed), undefined); assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, errored), undefined); + assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, telemetry), undefined); + }).pipe(Effect.provide(layerSession)), + ); +}); + +describe("AntigravityAdapterV2 work after the prompt ends", () => { + // Frames as agy 1.5.11 sent them for `run_command` with `WaitMsBeforeAsync`: the prompt returns + // end_turn, the command finishes later, and the agent replies with no prompt open. + it.effect("continues in one run when a finished background command wakes the agent", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const path = yield* Path.Path; + const crypto = yield* SecureRandom.SecureRandom; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdate: Parameters[0] | undefined; + let requestPermission: Parameters[0] | undefined; + const send = (update: EffectAcpSchema.SessionUpdate) => + sessionUpdate === undefined + ? Effect.die("the adapter must handle session updates") + : sessionUpdate( + normalizeAntigravitySessionUpdate({ sessionId: "mock-session-1", update }), + ); + const command = { + toolCallId: "call_fetch", + kind: "execute", + title: "node fetch_throughput.mjs", + rawInput: { CommandLine: "node fetch_throughput.mjs", WaitMsBeforeAsync: 10000 }, + } as const; + const usage = { sessionUpdate: "usage_update", used: 9000, size: 1048576 } as const; + const offers: Array = []; + const instanceId = ProviderInstanceId.make("antigravity-wake-test"); + const threadId = ThreadId.make("thread-antigravity-wake"); + const adapter = yield* makeAntigravityAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + continuationRequests: { offer: (request) => Effect.sync(() => void offers.push(request)) }, + makeRuntime: (input) => + makeAntigravityAcpRuntime({ + ...input, + childProcessSpawner, + spawn: { + command: process.execPath, + args: [mockAgentPath], + cwd: input.cwd, + env: { T3_ACP_ANTIGRAVITY: "1" }, + }, + }).pipe( + Effect.provideService(SecureRandom.SecureRandom, crypto), + Effect.map((runtime): RuntimeService => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdate = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + handleRequestPermission: (handler) => + Effect.sync(() => { + requestPermission = handler; + }).pipe(Effect.andThen(runtime.handleRequestPermission(handler))), + prompt: () => + Effect.gen(function* () { + yield* send({ sessionUpdate: "tool_call", ...command, status: "in_progress" }); + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "I'll render once the fetch finishes." }, + }); + yield* send(usage); + return { stopReason: "end_turn" as const }; + }), + })), + ), + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "gemini-test-low" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-antigravity-wake"), + modelSelection, + runtimePolicy, + }); + const events = yield* Queue.unbounded(); + yield* session.events.pipe( + Stream.runForEach((event) => Queue.offer(events, event)), + Effect.forkScoped, + ); + const throughTerminal = Effect.gen(function* () { + const seen: Array = []; + while (true) { + const event = yield* Queue.take(events); + seen.push(event); + if (event.type === "turn.terminal") return seen; + } + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + const startTurn = (ordinal: number, continuation: boolean) => + session.startTurn({ + appThread: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make("project-antigravity-wake"), + title: "Antigravity wake", + providerInstanceId: instanceId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + 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, + }, + threadId, + runId: RunId.make(`run-antigravity-wake-${ordinal}`), + runOrdinal: ordinal, + providerTurnOrdinal: ordinal, + attemptId: RunAttemptId.make(`attempt-antigravity-wake-${ordinal}`), + rootNodeId: NodeId.make(`node-antigravity-wake-${ordinal}`), + providerThread, + message: { + ...(continuation + ? { createdBy: "agent" as const, creationSource: "provider" as const } + : { createdBy: "user" as const, creationSource: "web" as const }), + messageId: MessageId.make(`message-antigravity-wake-${ordinal}`), + text: "chart the throughput", + attachments: [], + }, + modelSelection, + runtimePolicy, + }); + + yield* startTurn(1, false); + const promptTerminal = (yield* throughTerminal).at(-1); + assert.equal(promptTerminal?.type === "turn.terminal" && promptTerminal.status, "completed"); + + yield* send({ + sessionUpdate: "tool_call_update", + ...command, + status: "completed", + rawOutput: { output: "Command exited with code 0.", exit_code: 0 }, + }); + assert.lengthOf(offers, 1, "the finished command must wake the thread"); + // The agent can ask before the app has started the continuation run. + const followUp = { toolCallId: "call_analyze", kind: "execute", title: "node analyze.mjs" }; + const permission = yield* Effect.suspend(() => + requestPermission === undefined + ? Effect.die("the adapter must handle permission requests") + : requestPermission( + { + sessionId: "mock-session-1", + toolCall: { ...followUp, status: "pending" }, + options: [ + { optionId: "allow", name: "Allow", kind: "allow_once" }, + { optionId: "deny", name: "Deny", kind: "reject_once" }, + ], + }, + { requestId: "permission-1", method: "session/request_permission" }, + ), + ).pipe(Effect.forkScoped({ startImmediately: true })); + yield* offers[0]!.dispatchIfCurrent!(Effect.void); + yield* startTurn(2, true); + assert.deepEqual(yield* Fiber.join(permission), { + outcome: { outcome: "selected", optionId: "allow" }, + }); + + // The model took 6.7 s to answer the finished command; the run must outlast that silence. + yield* TestClock.adjust("10 seconds"); + yield* send({ sessionUpdate: "tool_call", ...followUp, status: "completed" }); + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Here is the chart." }, + }); + yield* TestClock.adjust("10 seconds"); + yield* send(usage); + yield* TestClock.adjust("3 seconds"); + const continued = yield* throughTerminal; + const continuedTerminal = continued.at(-1); + assert.equal( + continuedTerminal?.type === "turn.terminal" && continuedTerminal.status, + "completed", + ); + assert.isTrue( + continued.some( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "assistant_message" && + event.turnItem.runId === RunId.make("run-antigravity-wake-2"), + ), + "the reply belongs to the continuation run", + ); + const finished = continued.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === command.toolCallId, + ); + assert.equal(finished?.type === "turn_item.updated" && finished.turnItem.status, "completed"); + assert.lengthOf(offers, 1, "one wake is one run"); }).pipe(Effect.provide(layerSession)), ); }); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 8566cbb83f9e9..b91f1a452679d 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -242,6 +242,12 @@ export function makeAntigravityAcpAdapterFlavor( ), // Loading history replays tool calls; resume avoids replay. subagentsIdleOnTurnCompletion: true, + // A finished background command or timer wakes the agent with no prompt open: it streams a + // reply and asks for permissions, and no prompt response ever ends that reply. + enablePostSettleContinuation: true, + deferFinalizeForBackgroundWork: true, + wakeOnDetachedRequest: true, + replyEndsWithUsageUpdate: true, ...(options.onSessionEvent === undefined ? {} : { onSessionEvent: options.onSessionEvent }), applyModelSelection: Effect.fn("AntigravityAdapterV2.applyModelSelection")(function* ({ runtime, diff --git a/packages/provider-acp-registry/src/server/adapter.ts b/packages/provider-acp-registry/src/server/adapter.ts index 8f133f619cea3..ce5a2b94531c4 100644 --- a/packages/provider-acp-registry/src/server/adapter.ts +++ b/packages/provider-acp-registry/src/server/adapter.ts @@ -197,6 +197,9 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu const startupKey = options.settings.source === "local" ? `local:${options.instanceId}` : registryAgentId; const isDevin = registryAgentId === "devin"; + const isAntigravityCli = + options.settings.source === "local" && + /^agy(\.exe|\.cmd)?$/i.test(options.settings.commandPath.split(/[\\/]/).pop() ?? ""); const isOmp = options.settings.source === "local" && /^omp(\.exe|\.cmd)?$/i.test(options.settings.commandPath.split(/[\\/]/).pop() ?? ""); @@ -252,6 +255,7 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu : AcpProviderCapabilitiesV2, customModels: readCustomModelEntries(options.settings.customModels).map((entry) => entry.slug), compactViaAdvertisedCommand: true, + ...(isAntigravityCli ? { wakeOnDetachedRequest: true, replyEndsWithUsageUpdate: true } : {}), promptFailure: (cause) => acpRegistryPromptFailure(registryAgentId, cause), ...(registryAgentId === "factory-droid" ? { extractElicitationForm: extractDroidElicitationForm } @@ -290,9 +294,11 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu // Hermes replies on the root session when a background process it started exits; no // prompt response follows, so the continuation ends on the deferred-finalize debounce. // Hermes is not in the public registry and may run through a wrapper, so only its - // initialize reply identifies it. - enablePostSettleContinuation: isHermes, - deferFinalizeForBackgroundWork: isHermes, + // initialize reply identifies it. agy does the same and is known by its command. + enablePostSettleContinuation: (initializeResult) => + isAntigravityCli || isHermes(initializeResult), + deferFinalizeForBackgroundWork: (initializeResult) => + isAntigravityCli || isHermes(initializeResult), ...(isDevin ? { clientCapabilitiesMeta: { diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 23883850a8765..7402b5ec9b0eb 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -143,6 +143,8 @@ export const ACP_PROTOCOL = "acp.ndjson-jsonrpc" as const; // Grok summaries can trail hydrated tools by over two seconds; shorter waits split the wake. const ACP_DEFERRED_FINALIZE_DEBOUNCE: Duration.Input = "3000 millis"; +// A model can stay silent this long before the first token of a reply the agent started itself. +const ACP_OPEN_REPLY_QUIET_LIMIT: Duration.Input = "2 minutes"; const ACP_BUSY_PROMPT_RETRY_INTERVAL: Duration.Input = "1 second"; // pi-agent-core agents (oh-my-pi) end a turn while background work runs and reject @@ -586,6 +588,11 @@ export interface AcpAdapterV2Flavor { notification: EffectAcpSchema.SessionNotification, ) => boolean; readonly deferFinalizeForBackgroundWork?: AcpNegotiatedFlag; + /** + * Every model reply ends with `usage_update`, also the ones the agent starts with no prompt + * open. A turn that ends on the deferred finalize waits for it instead of the short debounce. + */ + readonly replyEndsWithUsageUpdate?: boolean; readonly assertComplete?: Effect.Effect; /** Interrupt the local prompt fiber before `session/cancel` (Grok wedged prompts). */ readonly interruptPromptOnCancel?: boolean; @@ -618,6 +625,8 @@ export interface AcpAdapterV2Flavor { readonly terminateRuntimeProcessGroupOnInterrupt?: boolean; readonly preserveRuntimeOnSettledInterrupt?: boolean; readonly enablePostSettleContinuation?: AcpNegotiatedFlag; + /** A native request after prompt settlement starts a continuation before it is handled. */ + readonly wakeOnDetachedRequest?: boolean; /** Settle on native idle after the accepted user echo, only on negotiated ACP v2. */ readonly followAgentWorkState?: boolean; /** @@ -1554,6 +1563,8 @@ interface ActiveAcpTurn { readonly promptStarted: Deferred.Deferred; promptUsage: EffectAcpSchema.Usage | undefined; backgroundFinalizeGeneration: number; + /** `replyEndsWithUsageUpdate`: output arrived and its closing `usage_update` has not. */ + replyOpen: boolean; /** The agent's own id for this turn's prompt, from `forkFromTurn.nativeTurnId`. */ nativePromptId: string | undefined; /** Clock millis of the prompt's last progress, for `promptInactivityTimeout`. */ @@ -4041,6 +4052,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( /Monitor\s+["']?[0-9a-f-]{8,}/i.test(text) && /ended/i.test(text); const hasDeferredBackgroundWork = (context: ActiveAcpTurn): boolean => { + if (flavor.wakeOnDetachedRequest && agentRequests.size > 0) return true; if (context.awaitingBackgroundHydration.size > 0) return true; if (context.pendingInjectedReport.size > 0) return true; for (const [taskId, toolCallId] of context.toolCallIdsByBackgroundTaskId) { @@ -4052,6 +4064,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const status = toolStatus(tool.status); if (status === "pending" || status === "running") return true; } + // finalizeTurn idles these subagents, so waiting on them would never settle. + if (flavor.subagentsIdleOnTurnCompletion === true) return false; for (const subagent of context.subagents.values()) { if (acpSubagentStatusBlocksTurnSettlement(subagent.task.status)) { return true; @@ -5318,7 +5332,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); const awaitRequestTurn = Effect.fnUntraced(function* (generation: number) { - if (!followsAgentWorkState) return true; + if ( + !followsAgentWorkState && + !(postSettleContinuationEnabled && flavor.wakeOnDetachedRequest) + ) + return true; while (true) { const waiting = yield* runRuntimeCallbackAtGeneration( generation, @@ -5341,7 +5359,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( (generation: number) => (effect: Effect.Effect) => Effect.suspend(() => - !followsAgentWorkState + !followsAgentWorkState && + !(postSettleContinuationEnabled && flavor.wakeOnDetachedRequest) ? effect : Effect.acquireUseRelease( runRuntimeCallbackAtGeneration( @@ -5360,6 +5379,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (Option.isSome(token)) agentRequests.delete(token.value); const context = yield* Ref.get(activeTurn); if (context !== null) yield* settleIdleWork(context); + if (context !== null && flavor.wakeOnDetachedRequest) { + // The agent goes on with its reply once the request is answered. + if (flavor.replyEndsWithUsageUpdate === true) context.replyOpen = true; + yield* rearmDeferredFinalize(context); + } }), ).pipe(Effect.asVoid), ), @@ -5379,6 +5403,24 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return; if (yield* projectAgentTerminalUpdate(notification, context)) return; if (yield* projectDetachedBackgroundCommand(notification, context)) return; + if (flavor.replyEndsWithUsageUpdate === true) { + if (context === null) { + // A reply can end before its continuation run starts; replay its end with its output. + if ( + update.sessionUpdate === "usage_update" && + (yield* Ref.get(wakeBuffer)).length > 0 + ) { + yield* Ref.update(wakeBuffer, (current) => [...current, notification]); + } + } else if (context.nativeThreadId === notification.sessionId) { + if (update.sessionUpdate === "usage_update") { + context.replyOpen = false; + yield* rearmDeferredFinalize(context); + } else if (acpRootSessionUpdateIngestsOutput(notification)) { + context.replyOpen = true; + } + } + } if ( update.sessionUpdate === "usage_update" || update.sessionUpdate === "session_info_update" @@ -6924,6 +6966,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } yield* targetRuntime.handleRequestPermission((nativeParams, requestContext) => Effect.gen(function* () { + if ( + postSettleContinuationEnabled && + flavor.wakeOnDetachedRequest && + nativeParams.sessionId !== (yield* Ref.get(activeSessionId)) + ) { + return { outcome: { outcome: "cancelled" } } as const; + } const trackedTurn = yield* Ref.get(activeTurn); const params = trackedTurn !== null && nativeParams.sessionId === (yield* Ref.get(activeSessionId)) @@ -6961,7 +7010,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy, request: EffectAcpSchema.RequestPermissionRequest = params, ) => (flavor.permissionDisposition ?? acpPermissionDisposition)(policy, request); - if (followsAgentWorkState && dispositionFor(latestRuntimePolicy) === "ask") { + if ( + (followsAgentWorkState && dispositionFor(latestRuntimePolicy) === "ask") || + (postSettleContinuationEnabled && flavor.wakeOnDetachedRequest) + ) { if (!(yield* awaitRequestTurn(handlerGeneration))) return { outcome: { outcome: "cancelled" } } as const; } @@ -8315,8 +8367,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (hasDeferredBackgroundWork(context)) return; context.backgroundFinalizeGeneration += 1; const generation = context.backgroundFinalizeGeneration; + const debounce = context.replyOpen + ? ACP_OPEN_REPLY_QUIET_LIMIT + : ACP_DEFERRED_FINALIZE_DEBOUNCE; yield* Effect.gen(function* () { - yield* Effect.sleep(ACP_DEFERRED_FINALIZE_DEBOUNCE); + yield* Effect.sleep(debounce); if ( context.finalized || context.interrupted || @@ -8328,10 +8383,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const status = context.promptSettledStatus ?? "completed"; yield* finalizeTurn(context, status); }).pipe(Effect.forkIn(sessionScope), Effect.asVoid); - yield* ( - options.testHooks?.onDeferredFinalizeScheduled?.(ACP_DEFERRED_FINALIZE_DEBOUNCE) ?? - Effect.void - ); + yield* options.testHooks?.onDeferredFinalizeScheduled?.(debounce) ?? Effect.void; }); const promptInactivityPaused = Effect.fn("AcpAdapterV2.promptInactivityPaused")(function* ( @@ -8769,6 +8821,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( promptStarted, promptUsage: undefined, backgroundFinalizeGeneration: 0, + replyOpen: false, nativePromptId: undefined, lastProgressAt: 0, inactivityWatchdog: undefined, diff --git a/packages/provider-acp/src/server/runtimeModel.test.ts b/packages/provider-acp/src/server/runtimeModel.test.ts index b41c95f6466b6..4fb77c4c3cc6c 100644 --- a/packages/provider-acp/src/server/runtimeModel.test.ts +++ b/packages/provider-acp/src/server/runtimeModel.test.ts @@ -1395,6 +1395,10 @@ describe("extractMcpToolCallIdentity", () => { // Kimi retitles with partial JSON and middle-truncates args over 50 characters. 'delegate_task: {"mode":"async","task":"Ru', 'delegate_task: {"mode":"async","task":"Ru...cho child-result-42\'"}', + // Antigravity: "Running " before agy 1.5.8, "Run mcp__" since, "?" on prompts. + "Running delegate_task", + "Run mcp_t3-code_delegate_task", + "Run mcp_t3-code_delegate_task?", ]) { const toolCall = toolCallFromUpdate({ sessionUpdate: "tool_call", @@ -1612,7 +1616,12 @@ describe("extractMcpToolCallIdentity", () => { }); it("does not brand path-like or unknown-tool titles", () => { - for (const title of ["t3-code/README.md", "t3-code_not_a_real_tool"]) { + for (const title of [ + "t3-code/README.md", + "t3-code_not_a_real_tool", + "Run mcp_t3-code_not_a_real_tool", + "Run manage_task", + ]) { const toolCall = toolCallFromUpdate({ sessionUpdate: "tool_call", toolCallId: "path-1", diff --git a/packages/provider-acp/src/server/runtimeModel.ts b/packages/provider-acp/src/server/runtimeModel.ts index 3b936a30b766f..eaf352695e5c0 100644 --- a/packages/provider-acp/src/server/runtimeModel.ts +++ b/packages/provider-acp/src/server/runtimeModel.ts @@ -1088,11 +1088,14 @@ const T3_MCP_TITLE_SUFFIX_CALL = /^(?[A-Za-z0-9][A-Za-z0-9_.-]*?)(?: \(t3[-_ ]?code MCP Server\)(?::|$)|[-_.]t3[-_ ]?code$)/i; /** - * glm and Kimi use bare names; Antigravity uses "Running ". Kimi appends - * streamed JSON arguments. Require a name or JSON opening brace so built-ins - * titled ": " cannot impersonate an inventory entry. + * glm and Kimi use bare names. Kimi appends streamed JSON arguments. Require a + * name or JSON opening brace so built-ins titled ": " cannot + * impersonate an inventory entry. */ -const T3_MCP_BARE_TITLE_CALL = /^(?:Running )?(?[A-Za-z0-9_]+)(?::\s*\{|$)/; +const T3_MCP_BARE_TITLE_CALL = /^(?[A-Za-z0-9_]+)(?::\s*\{|$)/; + +// Antigravity titles calls "Running " or, from agy 1.5.8, "Run mcp__"; prompts end in "?". +const ANTIGRAVITY_TOOL_TITLE = /^Run(?:ning)? (?[^\s?]+)\??$/; /** ACP lacks typed MCP calls; recognize provider metadata and terminal fallback commands. */ export function extractMcpToolCallIdentity( @@ -1185,10 +1188,11 @@ export function extractMcpToolCallIdentity( } if (qualified?.[1] && qualified[2] && !/^t3[-_ ]?code$/i.test(qualified[1])) return { server: qualified[1], tool: qualified[2] }; + const name = ANTIGRAVITY_TOOL_TITLE.exec(trimmed)?.groups?.name ?? trimmed; const match = - T3_MCP_TITLE_CALL.exec(trimmed) ?? - T3_MCP_TITLE_SUFFIX_CALL.exec(trimmed) ?? - T3_MCP_BARE_TITLE_CALL.exec(trimmed); + T3_MCP_TITLE_CALL.exec(name) ?? + T3_MCP_TITLE_SUFFIX_CALL.exec(name) ?? + T3_MCP_BARE_TITLE_CALL.exec(name); const candidateTool = match?.groups?.tool; if (candidateTool !== undefined && T3_MCP_TOOL_NAMES.has(candidateTool)) { return { server: "t3-code", tool: candidateTool }; From 528687d2260ca0c132c6d634bcb15fc94c4604c6 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 19:09:19 -0800 Subject: [PATCH 093/183] fix(acp-registry): inherited NPM_CONFIG_PREFIX no longer overrides the managed npm prefix on Windows (#38839) --- .../src/server/AcpRegistrySupport.test.ts | 50 +++++++++++++++++++ .../src/server/AcpRegistrySupport.ts | 13 ++++- 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index 453855e58b662..db1deda3355ea 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -561,6 +561,56 @@ describe("AcpRegistrySupport", () => { ); }); + it.effect("gives Windows npm commands only the managed prefix spelling", () => { + const agent = makeAgent({ npx: { package: "@example/acp@1.2.3" } }); + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-windows-npm-prefix-", + }); + const toolchain = yield* makeFakeNpmToolchain(cacheDir); + const environment = { ...toolchain.environment, NPM_CONFIG_PREFIX: "C:\\inherited-npm" }; + const realSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const npmEnvironments: Array> = []; + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }).pipe( + Effect.provideService(HostProcess.Environment, environment), + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService(SpawnExecutableResolution, (command) => + command === "npm" ? toolchain.npmPath : undefined, + ), + Effect.provideService( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make((command) => { + if (command._tag === "StandardCommand" && command.command === toolchain.npmPath) { + npmEnvironments.push({ ...command.options.env }); + } + return realSpawner.spawn(command); + }), + ), + ); + + yield* resolver.resolve(settings(), "C:\\workspace", environment).pipe(Effect.ignore); + + expect(npmEnvironments.length).toBeGreaterThan(0); + for (const env of npmEnvironments) { + expect(Object.keys(env).filter((key) => key.toLowerCase() === "npm_config_prefix")).toEqual( + ["npm_config_prefix"], + ); + } + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => + Effect.succeed(HttpClientResponse.fromWeb(request, new Response(makeRegistry(agent)))), + ), + ), + ); + }); + it.effect("keeps only the end of a failed install's output in its error", () => { const agent = makeAgent({ npx: { package: "@example/acp@1.2.3" } }); return Effect.gen(function* () { diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index 051334750a49c..370331ef5b890 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -312,6 +312,17 @@ function readEnvironmentPath( ); } +// Windows env keys are case-insensitive, and an inherited NPM_CONFIG_PREFIX would win over ours. +function withoutNpmPrefix( + environment: NodeJS.ProcessEnv, + platform: NodeJS.Platform, +): NodeJS.ProcessEnv { + if (platform !== "win32") return environment; + return Object.fromEntries( + Object.entries(environment).filter(([key]) => key.toLowerCase() !== "npm_config_prefix"), + ); +} + function withPreferredPath( environment: NodeJS.ProcessEnv, directory: string, @@ -1250,7 +1261,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ); const packageEnvironment = distribution === "npx" - ? { ...environment, npm_config_prefix: packageRoot } + ? { ...withoutNpmPrefix(environment, platform), npm_config_prefix: packageRoot } : { ...environment, UV_TOOL_DIR: packageRoot, From 4c679a21e73f998832d2c32f9e16078aca28e2c5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 19:10:30 -0800 Subject: [PATCH 094/183] fix(web): page scripts in inline HTML renders no longer scroll the chat (#38832) Co-authored-by: StudioEtc --- .../src/components/chat/HtmlRenderFrame.tsx | 1 + .../BrowserDocumentFrame.browser.test.tsx | 98 +++++++++++++++++++ .../components/files/BrowserDocumentFrame.tsx | 8 +- .../src/components/guest/GuestHtmlRender.tsx | 6 +- packages/shared/src/htmlRender.ts | 13 ++- 5 files changed, 122 insertions(+), 4 deletions(-) diff --git a/apps/web/src/components/chat/HtmlRenderFrame.tsx b/apps/web/src/components/chat/HtmlRenderFrame.tsx index 8191e5fad6186..d3741a6f06e8d 100644 --- a/apps/web/src/components/chat/HtmlRenderFrame.tsx +++ b/apps/web/src/components/chat/HtmlRenderFrame.tsx @@ -92,6 +92,7 @@ export function HtmlRenderFrame(props: { title={title} threadRef={props.threadRef} className="block size-full" + containScroll onContentHeight={(height) => { rememberContentHeight(attachmentId, height); setContentHeight(height); diff --git a/apps/web/src/components/files/BrowserDocumentFrame.browser.test.tsx b/apps/web/src/components/files/BrowserDocumentFrame.browser.test.tsx index 40c84cc69fde6..34b450dbce87f 100644 --- a/apps/web/src/components/files/BrowserDocumentFrame.browser.test.tsx +++ b/apps/web/src/components/files/BrowserDocumentFrame.browser.test.tsx @@ -118,6 +118,104 @@ it("keeps the chat in place when a label far from its hidden radio is clicked", expect(scroller.scrollTop).toBe(scrollTop); }); +const scrollIntoViewPage = injectHtmlRenderBootstrap(` + +
+
+

Deep

+
+`); + +// Inline chat frames are fitted and contained; the expanded view keeps native scrolling, since +// its dialog scroller is how the page's own navigation reaches a section. +it.each([ + { name: "a fitted inline frame", containScroll: true, fitted: true }, + { name: "a fitted expanded frame", containScroll: false, fitted: true }, + { name: "a capped inline frame", containScroll: true, fitted: false }, +])( + "scrolls only what it should when a page script scrolls into view in $name", + async (frameCase) => { + const src = URL.createObjectURL(new Blob([scrollIntoViewPage], { type: "text/html" })); + using _url = { [Symbol.dispose]: () => URL.revokeObjectURL(src) }; + const scroller = document.createElement("div"); + scroller.style.cssText = "height: 400px; overflow: auto; width: 728px;"; + const scrolled = vi.fn(); + const messages = new AbortController(); + using _messages = { [Symbol.dispose]: () => messages.abort() }; + window.addEventListener( + "message", + (event) => { + if (event.data?.type === "scrolled") scrolled(event.data); + }, + { signal: messages.signal }, + ); + const contentHeight = vi.fn((height: number) => { + if (frameCase.fitted) scroller.style.setProperty("--content-height", `${height}px`); + }); + await using screen = await render( + <> + +
+ +
+ , + { container: scroller }, + ); + + const frame = screen.getByTitle("Index").element() as HTMLIFrameElement; + await vi.waitFor(() => expect(contentHeight).toHaveBeenCalled()); + if (frameCase.fitted) { + await vi.waitFor(() => expect(frame.getBoundingClientRect().height).toBeGreaterThan(1400)); + } + scroller.scrollTop = scroller.scrollHeight; + const scrollTop = scroller.scrollTop; + + frame.contentWindow?.postMessage({ type: "scroll-into-view", id: "deep" }, "*"); + await vi.waitFor(() => + expect(scrolled).toHaveBeenCalledWith(expect.objectContaining({ id: "deep" })), + ); + const deep = scrolled.mock.lastCall?.[0]; + // Every scroller inside the page moves, as the browser would: the clipped card, its panel, + // and in a capped frame the page itself. + expect(deep.card).toBeGreaterThan(0); + expect(deep.panel).toBeGreaterThan(0); + if (!frameCase.fitted) expect(deep.page).toBeGreaterThan(0); + expect(scroller.scrollTop).toBe(scrollTop); + + frame.contentWindow?.postMessage({ type: "scroll-into-view", id: "top" }, "*"); + await vi.waitFor(() => + expect(scrolled).toHaveBeenCalledWith(expect.objectContaining({ id: "top" })), + ); + if (frameCase.containScroll) expect(scroller.scrollTop).toBe(scrollTop); + else expect(scroller.scrollTop).toBeLessThan(scrollTop); + }, +); + it("keeps the first and last selected card rings inside the fitted renderer frame", async () => { const html = injectHtmlRenderBootstrap(`
Date: Wed, 18 Nov 2026 15:41:06 -0600 Subject: [PATCH 053/183] perf(server): batch provider commits without blocking unrelated writes (#38544) Co-authored-by: Julius Marminge Co-authored-by: Claude Opus 5.5 Co-authored-by: Cursor --- apps/server/src/orchestration-v2/EventSink.ts | 99 +++++-- .../FoundationPersistence.test.ts | 263 ++++++++++++++++-- .../src/orchestration-v2/ProjectionStore.ts | 58 +++- .../ProviderCommitBatch.test.ts | 59 ++++ .../orchestration-v2/ProviderCommitBatch.ts | 243 +++++++++------- packages/shared/src/nodeSqliteClient.test.ts | 55 ++++ packages/shared/src/nodeSqliteClient.ts | 45 ++- 7 files changed, 672 insertions(+), 150 deletions(-) diff --git a/apps/server/src/orchestration-v2/EventSink.ts b/apps/server/src/orchestration-v2/EventSink.ts index fff4fd3e3db76..cad0aff3afb19 100644 --- a/apps/server/src/orchestration-v2/EventSink.ts +++ b/apps/server/src/orchestration-v2/EventSink.ts @@ -72,12 +72,22 @@ export type EventSinkV2Error = typeof EventSinkV2Error.Type; interface ProviderBatchPublication { readonly publish: Array>; + readonly projection: ProjectionStore.ProviderBatchProjection; + /** The projection high-water mark, recorded once before the batch commits. */ + projectedSequence: number | undefined; eventCount: number; } const CurrentProviderBatch = Context.Reference( "t3/orchestration-v2/EventSink/CurrentProviderBatch", { defaultValue: () => undefined }, ); +// Projecting `provider-thread.updated` also rewrites its app thread's row. +const projectedThreadIds = (events: ReadonlyArray) => + events.flatMap((event) => + event.type === "provider-thread.updated" && event.payload.appThreadId !== null + ? [event.threadId, event.payload.appThreadId] + : [event.threadId], + ); export interface EventSinkV2Shape { /** Items that are not provider snapshots, such as a consumer's own control items, never batch. */ @@ -409,6 +419,30 @@ const layerBase: Layer.Layer< ); }; + // The enclosing write or commit span already traces this projection bookkeeping. + const recordProjectedSequence = Effect.fnUntraced(function* (sequence: number) { + const now = DateTime.formatIso(yield* DateTime.now); + yield* sql` + INSERT INTO orchestration_v2_projection_metadata ( + projection_name, + schema_version, + last_sequence, + updated_at + ) + VALUES ( + 'thread-projections', + ${ProjectionStore.ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION}, + ${sequence}, + ${now} + ) + ON CONFLICT(projection_name) + DO UPDATE SET + schema_version = excluded.schema_version, + last_sequence = excluded.last_sequence, + updated_at = excluded.updated_at + `; + }); + const applyStoredEvents = /* This helper runs for individual orchestration events; the enclosing operation owns the span. */ Effect.fnUntraced(function* (storedEvents: ReadonlyArray) { @@ -417,26 +451,9 @@ const layerBase: Layer.Layer< }); const sequence = storedEvents.at(-1)?.sequence; if (sequence !== undefined) { - const now = DateTime.formatIso(yield* DateTime.now); - yield* sql` - INSERT INTO orchestration_v2_projection_metadata ( - projection_name, - schema_version, - last_sequence, - updated_at - ) - VALUES ( - 'thread-projections', - ${ProjectionStore.ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION}, - ${sequence}, - ${now} - ) - ON CONFLICT(projection_name) - DO UPDATE SET - schema_version = excluded.schema_version, - last_sequence = excluded.last_sequence, - updated_at = excluded.updated_at - `; + const batch = yield* CurrentProviderBatch; + if (batch !== undefined) batch.projectedSequence = sequence; + else yield* recordProjectedSequence(sequence); } // Read lineage here, on the connection this transaction holds; see makeRunOutcomeRecorder. return yield* runOutcomes.prepare(storedEvents); @@ -476,6 +493,7 @@ const layerBase: Layer.Layer< const batch = yield* CurrentProviderBatch; if (batch !== undefined) batch.eventCount += input.events.length; const { committed } = yield* commitThenPublish( + projectedThreadIds(input.events), Effect.gen(function* () { // Check ownership in the same transaction that claims the native session. const imported = input.unlessNativeThreadOwned; @@ -530,6 +548,7 @@ const layerBase: Layer.Layer< }); return yield* commitThenPublish( + [input.threadId, ...projectedThreadIds(input.events)], Effect.gen(function* () { const rows = yield* sql<{ readonly status: string; @@ -611,6 +630,7 @@ const layerBase: Layer.Layer< }); return yield* commitThenPublish( + projectedThreadIds(input.events), Effect.gen(function* () { const rows = yield* sql<{ readonly active_attempt_id: string | null; @@ -664,6 +684,7 @@ const layerBase: Layer.Layer< events: ReadonlyArray, ) => commitThenPublish( + projectedThreadIds(events), Effect.gen(function* () { const rows = yield* readStoredPayload; if (rows[0]?.payload_json !== expectedJson) { @@ -764,6 +785,7 @@ const layerBase: Layer.Layer< input: Parameters[0], ) { const result = yield* commitThenPublish( + [input.threadId, ...projectedThreadIds(input.events)], Effect.gen(function* () { const reserved = yield* commandReceipts.insertIfAbsent({ commandId: input.commandId, @@ -909,6 +931,7 @@ const layerBase: Layer.Layer< const commitProjectCommandEffect = Effect.fn("orchestrationV2.EventSink.commitProjectCommand")( function* (input: Parameters[0]) { const result = yield* commitThenPublish( + [], Effect.gen(function* () { const reserved: CommandReceiptStore.ProjectCommandReceiptV2 = { commandId: input.commandId, @@ -1037,7 +1060,9 @@ const layerBase: Layer.Layer< ); }; + // Waits only for queued provider snapshots of `threadIds`, the threads this write touches. const commitThenPublish = ( + threadIds: ReadonlyArray, transaction: Effect.Effect, publish: (committed: A) => Effect.Effect, ) => @@ -1046,7 +1071,7 @@ const layerBase: Layer.Layer< ? Effect.flatMap(Effect.serviceOption(sql.transactionService), (existing) => Option.isSome(existing) ? commitThenPublishNow(transaction, publish) - : coordinator.barrier(commitThenPublishNow(transaction, publish)), + : coordinator.barrier(commitThenPublishNow(transaction, publish), threadIds), ) : transaction.pipe( Effect.tap((committed) => @@ -1061,12 +1086,33 @@ const layerBase: Layer.Layer< "orchestrationV2.EventSink.providerBatch", )(function* (effect: Effect.Effect) { if ((yield* CurrentProviderBatch) !== undefined) return yield* effect; - const batch: ProviderBatchPublication = { publish: [], eventCount: 0 }; + const batch: ProviderBatchPublication = { + publish: [], + eventCount: 0, + projection: { nodeReads: new Map(), threadTouches: new Map() }, + projectedSequence: undefined, + }; let started = false; const result = yield* commitThenPublishNow( Effect.sync(() => { started = true; - }).pipe(Effect.andThen(Effect.provideService(effect, CurrentProviderBatch, batch))), + }).pipe( + Effect.andThen( + effect.pipe( + Effect.provideService(CurrentProviderBatch, batch), + Effect.provideService(ProjectionStore.ProviderBatchProjectionState, batch.projection), + Effect.tap(() => + ProjectionStore.writeThreadTouches(sql, batch.projection.threadTouches).pipe( + Effect.andThen( + batch.projectedSequence === undefined + ? Effect.void + : recordProjectedSequence(batch.projectedSequence), + ), + ), + ), + ), + ), + ), () => Effect.forEach(batch.publish, (publish) => publish, { discard: true }), ).pipe( // Normalization mutates run-local state, so only retry before its transaction body starts. @@ -1105,12 +1151,19 @@ const layerBase: Layer.Layer< const batch = yield* CurrentProviderBatch; const publicationCount = batch?.publish.length ?? 0; const eventCount = batch?.eventCount ?? 0; + const projectedSequence = batch?.projectedSequence; + const threadTouches = new Map(batch?.projection.threadTouches); return yield* sql.withTransaction(work).pipe( Effect.onError(() => Effect.sync(() => { if (batch !== undefined) { batch.publish.length = publicationCount; batch.eventCount = eventCount; + batch.projectedSequence = projectedSequence; + batch.projection.nodeReads.clear(); + batch.projection.threadTouches.clear(); + for (const [threadId, updatedAt] of threadTouches) + batch.projection.threadTouches.set(threadId, updatedAt); } }), ), diff --git a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts index 14f443aa8cb62..1fbab4085b283 100644 --- a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts +++ b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts @@ -419,6 +419,209 @@ it.effect( }).pipe(Effect.provide(Layer.fresh(layerTest))), ); +function nodeComparisonEvent(thread: OrchestrationV2AppThread, now: DateTime.Utc) { + const nodeId = NodeId.make(`node:${thread.id}`); + return { + id: EventId.make(`node-cache:${thread.id}`), + type: "node.updated", + threadId: thread.id, + occurredAt: now, + payload: { + id: nodeId, + threadId: thread.id, + runId: null, + parentNodeId: null, + rootNodeId: nodeId, + kind: "assistant_message", + status: "running", + countsForRun: false, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + runtimeRequestId: null, + checkpointScopeId: null, + startedAt: now, + completedAt: null, + }, + } satisfies OrchestrationV2DomainEvent; +} + +it.effect("commits other threads' writes ahead of a thread's queued provider snapshots", () => + Effect.gen(function* () { + const sink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + const [busy, independent] = ["busy", "independent"].map((id) => + makeThread(ThreadId.make(id), now), + ); + yield* sink.write({ + events: [busy!, independent!].map((thread) => + threadCreatedEvent({ id: `created:${thread.id}`, thread, now }), + ), + }); + const highWater = yield* sink.latestSequence(); + const busyNode = nodeComparisonEvent(busy!, now); + const snapshot = { + type: "node.updated" as const, + driver: providerDriver, + node: busyNode.payload, + }; + const started = yield* Deferred.make(); + const release = yield* Deferred.make(); + const pulled = yield* Deferred.make(); + let writes = 0; + let pulls = 0; + const input = yield* Queue.unbounded(); + const provider = yield* sink + .consumeProviderEvents( + Stream.fromQueue(input).pipe( + Stream.take(3), + Stream.tap(() => (++pulls === 3 ? Deferred.succeed(pulled, undefined) : Effect.void)), + ), + () => + Effect.gen(function* () { + const id = EventId.make(`busy-provider-${++writes}`); + yield* sink.write({ events: [{ ...busyNode, id }] }); + if (writes > 1) return; + yield* Deferred.succeed(started, undefined); + yield* Deferred.await(release); + }), + Effect.succeed(false), + Effect.succeed(true), + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Queue.offer(input, snapshot); + yield* Deferred.await(started); + yield* Queue.offerAll(input, [snapshot, snapshot]); + yield* Deferred.await(pulled); + yield* TestClock.adjust(0); + const writeTo = (event: OrchestrationV2DomainEvent, id: string) => + sink + .write({ events: [{ ...event, id: EventId.make(id) }] }) + .pipe(Effect.forkScoped({ startImmediately: true })); + const sameThread = yield* writeTo(busyNode, "busy-command"); + const otherThread = yield* writeTo(nodeComparisonEvent(independent!, now), "independent"); + const childOfBusy = yield* writeTo( + { + id: EventId.make("unused"), + type: "provider-thread.updated", + threadId: independent!.id, + driver: providerDriver, + providerInstanceId, + occurredAt: now, + payload: { + id: ProviderThreadId.make("provider-thread:busy-child"), + driver: providerDriver, + providerInstanceId, + providerSessionId: null, + appThreadId: busy!.id, + ownerNodeId: null, + nativeThreadRef: null, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: 1, + lastRunOrdinal: 1, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + }, + }, + "busy-child", + ); + yield* TestClock.adjust(0); + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(provider); + yield* Fiber.join(sameThread); + yield* Fiber.join(otherThread); + yield* Fiber.join(childOfBusy); + const store = yield* EventStore.EventStoreV2; + const events = yield* store.read({ afterSequence: highWater }).pipe(Stream.runCollect); + assert.deepEqual( + events.map((stored) => stored.event.id), + [ + "busy-provider-1", + "independent", + "busy-provider-2", + "busy-provider-3", + "busy-command", + "busy-child", + ], + ); + }).pipe(Effect.scoped, Effect.provide(Layer.fresh(layerTest))), +); + +it.effect( + "reuses node comparisons and writes thread bookkeeping once per provider transaction", + () => + Effect.gen(function* () { + const sink = yield* EventSink.EventSinkV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const sql = yield* SqlClient.SqlClient; + const now = yield* DateTime.now; + const thread = makeThread(ThreadId.make("node-comparison-cache"), now); + yield* sink.write({ + events: [threadCreatedEvent({ id: "node-cache-created", thread, now })], + }); + const event = nodeComparisonEvent(thread, now); + const statements = { nodeReads: 0, threadTouches: 0, highWaterWrites: 0 }; + const observe: Statement.Transformer = (statement) => { + const text = statement.compile()[0]; + if ( + text.includes("SELECT payload_json FROM orchestration_v2_projection_nodes WHERE node_id") + ) + statements.nodeReads++; + if (text.includes("UPDATE orchestration_v2_projection_threads")) statements.threadTouches++; + if (text.includes("INSERT INTO orchestration_v2_projection_metadata")) + statements.highWaterWrites++; + return Effect.succeed(statement); + }; + const lastOccurredAt = DateTime.add(now, { minutes: 3 }); + yield* sink + .withProviderBatch( + Effect.gen(function* () { + for (let n = 0; n < 21; n++) + assert.isFalse(yield* projections.isNodeStored(event.payload)); + assert.equal(statements.nodeReads, 1); + yield* sink.write({ events: [event] }); + assert.isTrue(yield* projections.isNodeStored(event.payload)); + for (const minutes of [1, 2, 3]) { + yield* sink.write({ + events: [ + { + ...event, + id: EventId.make(`node-cache-touch:${minutes}`), + occurredAt: DateTime.add(now, { minutes }), + }, + ], + }); + } + assert.deepEqual([statements.threadTouches, statements.highWaterWrites], [0, 0]); + }), + ) + .pipe(Effect.provideService(Statement.CurrentTransformer, observe)); + assert.deepEqual([statements.threadTouches, statements.highWaterWrites], [1, 1]); + assert.deepEqual( + DateTime.toEpochMillis((yield* projections.getThread(thread.id)).updatedAt), + DateTime.toEpochMillis(lastOccurredAt), + ); + assert.deepEqual( + yield* sql`SELECT last_sequence FROM orchestration_v2_projection_metadata + WHERE projection_name = 'thread-projections'`, + [{ last_sequence: yield* sink.latestSequence() }], + ); + const completed = { ...event.payload, status: "completed" as const, completedAt: now }; + yield* sink.write({ + events: [{ ...event, id: EventId.make("node-cache-completed"), payload: completed }], + }); + yield* sink.withProviderBatch( + Effect.gen(function* () { + assert.isFalse(yield* projections.isNodeStored(event.payload)); + assert.isTrue(yield* projections.isNodeStored(completed)); + }), + ); + }).pipe(Effect.scoped, Effect.provide(Layer.fresh(layerTest))), +); + it.effect.each( (["none", "duplicate", "after-write"] as const).flatMap((failure) => [1, 10].map((streams) => ({ failure, streams })), @@ -427,7 +630,7 @@ it.effect.each( "shares the writer and isolates failure=$failure across $streams independent consumers", ({ failure, streams }) => { const rollback = failure !== "none"; - const failedIndex = streams - 1; + const failedIndex = failure === "after-write" ? 0 : streams - 1; const jobError = { _tag: "InvalidUpdate" } as const; const writes: number[] = []; const tracer = Tracer.make({ @@ -455,6 +658,8 @@ it.effect.each( threadCreatedEvent({ id: `created:${index}`, thread, now }), ), }); + const node = nodeComparisonEvent(threads[0]!, now); + yield* sink.write({ events: [node] }); const highWater = yield* sink.latestSequence(); const store = yield* EventStore.EventStoreV2; const publications = yield* Queue.unbounded(); @@ -465,7 +670,7 @@ it.effect.each( const pulled = yield* Deferred.make(); let arrivals = 0; const inputs = yield* Effect.forEach(threads, () => - Queue.unbounded(), + Queue.unbounded(), ); const consumers = yield* Effect.forEach(inputs, (input, index) => sink @@ -477,8 +682,11 @@ it.effect.each( ), (raw) => raw.type === "message.updated" - ? sink - .write({ + ? Effect.gen(function* () { + if (failure === "after-write" && index !== failedIndex) { + assert.isTrue(yield* projections.isNodeStored(node.payload)); + } + yield* sink.write({ events: [ { id: EventId.make( @@ -487,19 +695,29 @@ it.effect.each( : `shared-event:${index}`, ), threadId: raw.message.threadId, - occurredAt: now, + occurredAt: DateTime.add(now, { minutes: index + 1 }), type: "message.updated", payload: raw.message, }, + ...(failure === "after-write" && index === failedIndex + ? [ + { + ...node, + id: EventId.make("rolled-back-node"), + occurredAt: DateTime.add(now, { hours: 1 }), + payload: { + ...node.payload, + status: "completed" as const, + completedAt: now, + }, + }, + ] + : []), ], - }) - .pipe( - Effect.andThen( - failure === "after-write" && index === failedIndex - ? Effect.fail(jobError) - : Effect.void, - ), - ) + }); + if (failure === "after-write" && index === failedIndex) + return yield* Effect.fail(jobError); + }) : Effect.void, Effect.succeed(false), Effect.succeed(true), @@ -527,10 +745,10 @@ it.effect.each( }); } yield* Deferred.await(pulled); - yield* TestClock.adjust(0); - yield* sink.write({ events: [] }); + yield* Effect.forEach(inputs, Queue.end, { discard: true }); + const exits = yield* Effect.forEach(consumers, Fiber.join); if (rollback) { - const exit = yield* Fiber.join(consumers[failedIndex]!); + const exit = exits[failedIndex]!; assert.isTrue(Exit.isFailure(exit)); if (failure === "after-write" && Exit.isFailure(exit)) assert.strictEqual(Cause.squash(exit.cause), jobError); @@ -544,10 +762,21 @@ it.effect.each( assert.equal(yield* Queue.size(publications), 0); assert.deepEqual(writes, rollback && streams === 1 ? [] : [streams - (rollback ? 1 : 0)]); assert.equal(yield* sink.latestSequence(), highWater + streams - (rollback ? 1 : 0)); + const sql = yield* SqlClient.SqlClient; + assert.deepEqual( + yield* sql`SELECT last_sequence FROM orchestration_v2_projection_metadata + WHERE projection_name = 'thread-projections'`, + [{ last_sequence: yield* sink.latestSequence() }], + ); for (let index = 0; index < threads.length; index++) { + const failed = rollback && index === failedIndex; assert.lengthOf( (yield* projections.getThreadRecords(threads[index]!.id, ["messages"])).messages, - rollback && index === failedIndex ? 0 : 1, + failed ? 0 : 1, + ); + assert.equal( + DateTime.toEpochMillis((yield* projections.getThread(threads[index]!.id)).updatedAt), + DateTime.toEpochMillis(failed ? now : DateTime.add(now, { minutes: index + 1 })), ); } }).pipe( diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 5bc4ca7c99fd8..bee84d714103a 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -838,6 +838,34 @@ export class ProjectionStoreV2 extends Context.Service; + /** Thread `updated_at` bumps, written once by `writeThreadTouches` before the batch commits. */ + readonly threadTouches: Map; +} +export class ProviderBatchProjectionState extends Context.Reference< + ProviderBatchProjection | undefined +>("t3/orchestration-v2/ProjectionStore/ProviderBatchProjectionState", { + defaultValue: () => undefined, +}) {} + +// Runs per projected event or once per batch; the projection or batch commit span traces it. +export const writeThreadTouches = Effect.fnUntraced(function* ( + sql: SqlClient.SqlClient, + touches: ReadonlyMap, +) { + for (const [threadId, updatedAt] of touches) { + yield* sql` + UPDATE orchestration_v2_projection_threads + SET + updated_at = ${updatedAt}, + payload_json = json_set(payload_json, '$.updatedAt', ${updatedAt}) + WHERE thread_id = ${threadId} + `; + } +}); + export const ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION = 2; function upsertById(items: ReadonlyArray, next: T): Array { @@ -2347,6 +2375,23 @@ export const layer: Layer.Layer = for (const [key, cached] of timelineIndexes) { if (cached.index.threadIds.includes(event.threadId)) timelineIndexes.delete(key); } + const batch = yield* ProviderBatchProjectionState; + // These rewrite the thread row from what they read, so a deferred bump must land first. + const rewrittenThreadId = event.type.startsWith("thread.") + ? event.threadId + : event.type === "provider-thread.updated" + ? event.payload.appThreadId + : null; + const deferredUpdatedAt = + rewrittenThreadId === null ? undefined : batch?.threadTouches.get(rewrittenThreadId); + if ( + batch !== undefined && + rewrittenThreadId !== null && + deferredUpdatedAt !== undefined + ) { + batch.threadTouches.delete(rewrittenThreadId); + yield* writeThreadTouches(sql, new Map([[rewrittenThreadId, deferredUpdatedAt]])); + } switch (event.type) { case "thread.pull-request-link-updated": { const thread = yield* getThread(event.threadId); @@ -2593,6 +2638,7 @@ export const layer: Layer.Layer = completed_at = excluded.completed_at, payload_json = excluded.payload_json `; + batch?.nodeReads.set(event.payload.id, payloadJson); break; } case "subagent.updated": { @@ -3234,13 +3280,8 @@ export const layer: Layer.Layer = event.type !== "thread.guest-share-updated" ) { const updatedAt = yield* encodeThreadUpdatedAt(event.occurredAt); - yield* sql` - UPDATE orchestration_v2_projection_threads - SET - updated_at = ${updatedAt}, - payload_json = json_set(payload_json, '$.updatedAt', ${updatedAt}) - WHERE thread_id = ${event.threadId} - `; + if (batch !== undefined) batch.threadTouches.set(event.threadId, updatedAt); + else yield* writeThreadTouches(sql, new Map([[event.threadId, updatedAt]])); } }, (effect, event) => @@ -5818,9 +5859,12 @@ export const layer: Layer.Layer = )( function* (node) { const payloadJson = yield* encodeNodePayload(node); + const cache = (yield* ProviderBatchProjectionState)?.nodeReads; + if (cache?.has(node.id)) return cache.get(node.id) === payloadJson; const rows = yield* sql` SELECT payload_json FROM orchestration_v2_projection_nodes WHERE node_id = ${node.id} `; + cache?.set(node.id, rows[0]?.payload_json); return rows[0]?.payload_json === payloadJson; }, (effect, node) => effect.pipe(Effect.mapError(controlReadError(node.threadId))), diff --git a/apps/server/src/orchestration-v2/ProviderCommitBatch.test.ts b/apps/server/src/orchestration-v2/ProviderCommitBatch.test.ts index dd159a2ff14e7..2e88f2272dd14 100644 --- a/apps/server/src/orchestration-v2/ProviderCommitBatch.test.ts +++ b/apps/server/src/orchestration-v2/ProviderCommitBatch.test.ts @@ -404,6 +404,65 @@ it.effect.each([false, true])( }), ); +it.effect.each(["none", "writer", "snapshots"] as const)( + "runs another stream's control during a busy commit; splits slow backlogs for a write waiting on %s", + (waitingOn) => + Effect.gen(function* () { + const started = yield* Deferred.make(); + const release = yield* Deferred.make(); + let first = true; + const recorder = yield* recordBatches( + Effect.gen(function* () { + if (!first) return; + first = false; + yield* Deferred.succeed(started, undefined); + yield* Deferred.await(release); + }), + ); + const leading = yield* recorder + .consume(Stream.make(event(-1)), recorder.process, Effect.succeed(false)) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(started); + yield* recorder.consume(Stream.make(control), recorder.process, Effect.succeed(true)); + assert.deepEqual(yield* Queue.takeAll(recorder.output), [[control]]); + + const pulled = yield* Deferred.make(); + const backlog = [event(0), event(1), event(2)]; + const slow = yield* recorder + .consume( + Stream.fromArray(backlog).pipe( + Stream.tap((raw) => + raw === backlog.at(-1) ? Deferred.succeed(pulled, undefined) : Effect.void, + ), + ), + (raw) => recorder.process(raw).pipe(Effect.andThen(TestClock.adjust("100 millis"))), + Effect.succeed(false), + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(pulled); + yield* TestClock.adjust(0); + // An unrelated write stands in for one waiting on the writer the batch holds. + const writerFree = yield* Deferred.make(); + const write = yield* recorder + .barrier( + waitingOn === "writer" ? Deferred.await(writerFree) : Effect.void, + waitingOn === "snapshots" ? ["single-thread"] : ["other-thread"], + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(leading); + yield* Fiber.join(slow); + yield* Deferred.succeed(writerFree, undefined); + yield* Fiber.join(write); + assert.deepEqual( + yield* Queue.takeAll(recorder.output), + waitingOn === "none" + ? [[event(-1)], backlog] + : [[event(-1)], ...backlog.map((raw) => [raw])], + ); + }), +); + it.effect.each(["failure", "stop"] as const)( "flushes the prefix and respects a source %s barrier", (mode) => diff --git a/apps/server/src/orchestration-v2/ProviderCommitBatch.ts b/apps/server/src/orchestration-v2/ProviderCommitBatch.ts index 1a6ca8d28a609..9117653682f31 100644 --- a/apps/server/src/orchestration-v2/ProviderCommitBatch.ts +++ b/apps/server/src/orchestration-v2/ProviderCommitBatch.ts @@ -11,6 +11,8 @@ import * as Stream from "effect/Stream"; const MAX_EVENTS = 64; const MAX_BYTES = 1024 * 1024; +// While another write waits, a shared transaction stops taking jobs after this long. +const MAX_HOLD_NANOS = 100_000_000n; const encodeQueue = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); export const enabled = Config.Boolean("T3CODE_PROVIDER_COMMIT_BATCHING").pipe( @@ -18,11 +20,28 @@ export const enabled = Config.Boolean("T3CODE_PROVIDER_COMMIT_BATCHING").pipe( Effect.orDie, ); -const isSnapshot = (event: { readonly type: string }) => +type Snapshot = + | { readonly type: "node.updated"; readonly node: { readonly threadId: string } } + | { readonly type: "message.updated"; readonly message: { readonly threadId: string } } + | { readonly type: "turn_item.updated"; readonly turnItem: { readonly threadId: string } } + | { readonly type: "plan.updated"; readonly plan: { readonly threadId: string } }; +const isSnapshot = (event: { readonly type: string }): event is Snapshot => event.type === "node.updated" || event.type === "message.updated" || event.type === "turn_item.updated" || event.type === "plan.updated"; +const snapshotThreadId = (event: Snapshot) => { + switch (event.type) { + case "node.updated": + return event.node.threadId; + case "message.updated": + return event.message.threadId; + case "turn_item.updated": + return event.turnItem.threadId; + case "plan.updated": + return event.plan.threadId; + } +}; export class CommitBatchError extends Schema.TaggedError()("CommitBatchError", { cause: Schema.Defect(), @@ -31,8 +50,8 @@ export const isCommitBatchError = Schema.is(CommitBatchError); interface Job { readonly owner: { active: boolean }; + readonly threadId: string; readonly queuedAt: number; - readonly snapshot: boolean; readonly bytes: number; readonly execute: Effect.Effect; readonly settle: ( @@ -40,11 +59,11 @@ interface Job { preserveFailure: boolean, ) => Effect.Effect; readonly cancel: Effect.Effect; + readonly settled: Effect.Effect; } interface Batch { readonly events: ReadonlyArray; - readonly bytes: number; - readonly reason: "ready" | "limit" | "control"; + readonly reason: "ready" | "limit"; } function collect(queue: Queue.Queue) { @@ -54,20 +73,15 @@ function collect(queue: Queue.Queue) { let events: Array = []; let bytes = 0; const flush = (reason: Batch["reason"]) => { - if (events.length > 0) batches.push({ events, bytes, reason }); + if (events.length > 0) batches.push({ events, reason }); events = []; bytes = 0; }; for (const job of ready) { - if (!job.snapshot) { - flush("control"); - batches.push({ events: [job], bytes: 0, reason: "control" }); - } else { - if (events.length > 0 && bytes + job.bytes > MAX_BYTES) flush("limit"); - events.push(job); - bytes += job.bytes; - if (events.length >= MAX_EVENTS || bytes >= MAX_BYTES) flush("limit"); - } + if (events.length > 0 && bytes + job.bytes > MAX_BYTES) flush("limit"); + events.push(job); + bytes += job.bytes; + if (events.length >= MAX_EVENTS || bytes >= MAX_BYTES) flush("limit"); } flush("ready"); return Stream.fromArray(batches); @@ -92,6 +106,8 @@ export const make = Effect.fn("ProviderCommitBatch.make")(function* ( const queue = yield* Queue.bounded(MAX_EVENTS); const pending = new Set(); let closed = false; + // Writes in `barrier` that have not finished; they wait on the batch or the writer it holds. + let waitingWriters = 0; const shutdown = Effect.gen(function* () { closed = true; yield* Queue.shutdown(queue); @@ -102,7 +118,7 @@ export const make = Effect.fn("ProviderCommitBatch.make")(function* ( const enqueue = Effect.fnUntraced(function* ( effect: Effect.Effect, token: { active: boolean }, - snapshot: boolean, + threadId: string, bytes: number, ) { const caller = yield* Effect.context(); @@ -111,8 +127,8 @@ export const make = Effect.fn("ProviderCommitBatch.make")(function* ( let result: A; const job: Job = { owner: token, + threadId, queuedAt: yield* Clock.currentTimeMillis, - snapshot, bytes, execute: effect.pipe( Effect.tapCause((cause) => @@ -146,6 +162,7 @@ export const make = Effect.fn("ProviderCommitBatch.make")(function* ( pending.delete(job); yield* Deferred.interrupt(reply); }), + settled: Deferred.await(reply).pipe(Effect.exit, Effect.asVoid), }; yield* Effect.uninterruptibleMask((restore) => Effect.gen(function* () { @@ -158,77 +175,111 @@ export const make = Effect.fn("ProviderCommitBatch.make")(function* ( ); return Deferred.await(reply); }); + // Commits a prefix of `jobs` in one transaction and returns how many it took. + const commitPrefix = (jobs: ReadonlyArray, reason: Batch["reason"]) => + Effect.uninterruptibleMask((restore) => + Effect.gen(function* () { + const outcomes = new Map>(); + let taken = 0; + const work = Effect.gen(function* () { + // A retried transaction runs this again from the first job. + outcomes.clear(); + taken = 0; + const startedAt = yield* Clock.monotonicTimeNanos; + for (const job of jobs) { + if ( + taken > 0 && + waitingWriters > 0 && + (yield* Clock.monotonicTimeNanos) - startedAt >= MAX_HOLD_NANOS + ) + return; + taken++; + if (!job.owner.active) { + yield* job.cancel; + continue; + } + const outcome = yield* (jobs.length > 1 ? isolate(job.execute) : job.execute).pipe( + Effect.exit, + ); + outcomes.set(job, outcome); + if (Exit.isFailure(outcome)) { + job.owner.active = false; + if (jobs.length === 1) return yield* Effect.failCause(outcome.cause); + } + } + }); + const exit = yield* restore( + commit(work).pipe(Effect.provideService(CurrentWorker, yield* Effect.fiberId)), + ).pipe(Effect.exit); + const committed = taken === 0 ? jobs : jobs.slice(0, taken); + yield* Effect.annotateCurrentSpan({ + "orchestration_v2.work_item_count": committed.length, + "orchestration_v2.deferred_work_item_count": jobs.length - committed.length, + "orchestration_v2.consumer_count": new Set(committed.map((job) => job.owner)).size, + "orchestration_v2.raw_json_bytes": committed.reduce((bytes, job) => bytes + job.bytes, 0), + "orchestration_v2.batch_flush_reason": reason, + "orchestration_v2.backlog_batching": true, + "orchestration_v2.batch_wait_ms": + (yield* Clock.currentTimeMillis) - Math.min(...committed.map((job) => job.queuedAt)), + }); + for (const job of committed) { + const outcome = outcomes.get(job) ?? Exit.void; + yield* job.settle( + Exit.isSuccess(exit) ? outcome : exit, + Exit.isSuccess(exit) || + (Exit.isFailure(exit) && + Exit.isFailure(outcome) && + Cause.squash(exit.cause) === Cause.squash(outcome.cause)), + ); + } + return committed.length; + }), + ).pipe(Effect.withSpan("orchestrationV2.ProviderCommitBatch.flush")); if (enabled) { yield* collect(queue).pipe( - Stream.runForEach((batch) => - Effect.uninterruptibleMask((restore) => - Effect.gen(function* () { - const jobs = batch.events.filter((job) => job.owner.active); - for (const job of batch.events) if (!job.owner.active) yield* job.cancel; + Stream.runForEach( + Effect.fnUntraced(function* (batch: Batch) { + let jobs = batch.events; + while (jobs.length > 0) { + for (const job of jobs) if (!job.owner.active) yield* job.cancel; + jobs = jobs.filter((job) => job.owner.active); if (jobs.length === 0) return; - yield* Effect.annotateCurrentSpan({ - "orchestration_v2.work_item_count": jobs.length, - "orchestration_v2.consumer_count": new Set(jobs.map((job) => job.owner)).size, - "orchestration_v2.raw_json_bytes": batch.bytes, - "orchestration_v2.batch_flush_reason": batch.reason, - "orchestration_v2.backlog_batching": true, - "orchestration_v2.batch_wait_ms": - (yield* Clock.currentTimeMillis) - Math.min(...jobs.map((job) => job.queuedAt)), - }); - const outcomes = new Map>(); - const work = Effect.forEach( - jobs, - (job) => - Effect.gen(function* () { - if (!job.owner.active) return yield* job.cancel; - const outcome = yield* ( - jobs.length > 1 && job.bytes > 0 ? isolate(job.execute) : job.execute - ).pipe(Effect.exit); - outcomes.set(job, outcome); - if (Exit.isFailure(outcome)) { - job.owner.active = false; - if (jobs.length === 1) return yield* Effect.failCause(outcome.cause); - } - }), - { discard: true }, - ); - const exit = yield* restore( - (jobs.every((job) => job.bytes === 0) ? work : commit(work)).pipe( - Effect.provideService(CurrentWorker, yield* Effect.fiberId), - ), - ).pipe(Effect.exit); - for (const job of jobs) { - const outcome = outcomes.get(job) ?? Exit.void; - yield* job.settle( - Exit.isSuccess(exit) ? outcome : exit, - Exit.isSuccess(exit) || - (Exit.isFailure(exit) && - Exit.isFailure(outcome) && - Cause.squash(exit.cause) === Cause.squash(outcome.cause)), - ); - } - }), - ).pipe(Effect.withSpan("orchestrationV2.ProviderCommitBatch.flush")), + jobs = jobs.slice(yield* commitPrefix(jobs, batch.reason)); + } + }), ), Effect.ensuring(shutdown), Effect.forkScoped, ); } - const barrier = Effect.fnUntraced(function* (effect: Effect.Effect) { + /** + * Runs `effect` after queued snapshots for `threadIds` commit; omitted, after every queued + * snapshot. Other threads' snapshots never delay it. + */ + const barrier = Effect.fnUntraced(function* ( + effect: Effect.Effect, + threadIds?: ReadonlyArray, + ) { if (closed) return yield* Effect.interrupt; - if (!enabled || pending.size === 0 || (yield* CurrentWorker) === (yield* Effect.fiberId)) - return yield* effect; - const token = { active: true }; - return yield* enqueue(Effect.exit(effect), token, false, 0).pipe( - Effect.flatten, - Effect.orDie, - Effect.flatten, - Effect.ensuring( - Effect.sync(() => { - token.active = false; + if (!enabled || (yield* CurrentWorker) === (yield* Effect.fiberId)) return yield* effect; + return yield* Effect.uninterruptibleMask((restore) => { + waitingWriters++; + return restore( + Effect.gen(function* () { + for (const job of Array.from(pending)) { + if (threadIds === undefined || threadIds.includes(job.threadId)) yield* job.settled; + } + if (closed) return yield* Effect.interrupt; + return yield* effect; }), - ), - ); + ).pipe( + Effect.ensuring( + Effect.sync(() => { + waitingWriters--; + }), + ), + ); + }); }); const consume = Effect.fnUntraced(function* ( source: Stream.Stream, @@ -249,29 +300,31 @@ export const make = Effect.fn("ProviderCommitBatch.make")(function* ( Stream.concat(Stream.succeed({ _tag: "End" as const })), ); let resume: Effect.Effect = Effect.void; + // Replies run in order, so EOF, failures and controls follow this stream's earlier snapshots + // without waiting for other streams' work. yield* signals.pipe( Stream.mapEffect((signal) => Effect.gen(function* () { yield* resume; const processed = yield* Deferred.make(); - const event = signal._tag === "Event" ? signal.event : undefined; - // EOF only acknowledges prior work; it can share a commit with other consumers. - const snapshot = - signal._tag === "End" || - (event !== undefined && isSnapshot(event) && (yield* canBatch)); - const bytes = - snapshot && event !== undefined ? Buffer.byteLength(yield* encodeQueue(event)) : 0; - const work: Effect.Effect = - signal._tag === "Failure" - ? Effect.failCause(signal.cause) - : event === undefined - ? Effect.succeed(true) - : process(event).pipe(Effect.as(false)); - const reply = snapshot - ? yield* enqueue(work, token, true, bytes) - : (yield* enqueue(Effect.void, token, false, 0)).pipe(Effect.andThen(work)); - if (!snapshot) resume = Deferred.await(processed); - return { reply, processed, check: !snapshot }; + let reply: Effect.Effect; + let check = false; + if (signal._tag === "End") reply = Effect.succeed(true); + else if (signal._tag === "Failure") reply = Effect.failCause(signal.cause); + else if (isSnapshot(signal.event) && (yield* canBatch)) { + const bytes = Buffer.byteLength(yield* encodeQueue(signal.event)); + reply = yield* enqueue( + process(signal.event).pipe(Effect.as(false)), + token, + snapshotThreadId(signal.event), + bytes, + ); + } else { + reply = process(signal.event).pipe(Effect.as(false)); + check = true; + resume = Deferred.await(processed); + } + return { reply, processed, check }; }), ), Stream.buffer({ capacity: MAX_EVENTS }), diff --git a/packages/shared/src/nodeSqliteClient.test.ts b/packages/shared/src/nodeSqliteClient.test.ts index 5c7b086642a42..24910bc0bf9cf 100644 --- a/packages/shared/src/nodeSqliteClient.test.ts +++ b/packages/shared/src/nodeSqliteClient.test.ts @@ -230,6 +230,61 @@ it.effect.each([false, true])("batches worker results without losing rows (reade }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); +it.effect("coalesces savepoints with queries and preserves nested rollback", () => + Effect.gen(function* () { + const { filename } = yield* makeTempDatabase; + yield* Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const worker = startedWorkers.filter((entry) => !checkpointWorkers.includes(entry)).at(-1)!; + using messages = vi.spyOn(worker, "postMessage"); + yield* sql.withTransaction( + Effect.forEach(Array.from({ length: 53 }), () => sql.withTransaction(Effect.void)), + ); + assert.equal(messages.mock.calls.length, 2); + + yield* sql.withTransaction( + Effect.gen(function* () { + yield* sql`UPDATE counters SET value = 1 WHERE id = 1`; + const failure = yield* sql + .withTransaction( + sql`UPDATE counters SET value = 2 WHERE id = 1`.pipe( + Effect.andThen(Effect.fail("bad update")), + ), + ) + .pipe(Effect.flip); + assert.equal(failure, "bad update"); + const sent = messages.mock.calls.length; + assert.equal( + yield* sql.withTransaction(Effect.fail("empty update")).pipe(Effect.flip), + "empty update", + ); + assert.equal(messages.mock.calls.length, sent); + assert.deepEqual(yield* sql`SELECT value FROM counters WHERE id = 1`, [{ value: 1 }]); + assert.deepEqual(messages.mock.calls.at(-1)?.[0].savepoints, []); + yield* sql.withTransaction( + sql + .withTransaction( + sql`UPDATE counters SET value = 3 WHERE id = 1`.pipe( + Effect.andThen(Effect.fail("nested update")), + ), + ) + .pipe(Effect.flip), + ); + assert.deepEqual(yield* sql`SELECT value FROM counters WHERE id = 1`, [{ value: 1 }]); + + yield* sql.withTransaction(sql`UPDATE counters SET value = 4 WHERE id = 1`); + yield* sql`UPDATE counters SET value = 5 WHERE id = 1`; + const unsent = yield* sql + .withTransaction(sql.unsafe("SELECT ?", [Symbol("uncloneable")])) + .pipe(Effect.exit); + assert.isTrue(Exit.isFailure(unsent)); + }), + ); + assert.deepEqual(yield* sql`SELECT value FROM counters WHERE id = 1`, [{ value: 5 }]); + }).pipe(Effect.provide(SqliteClient.layer({ filename, writerWorker: true }))); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + it.effect("reuses a worker query after an iterator constraint failure", () => Effect.gen(function* () { const { filename } = yield* makeTempDatabase; diff --git a/packages/shared/src/nodeSqliteClient.ts b/packages/shared/src/nodeSqliteClient.ts index 51e47c4bb5530..da521a7c6036d 100644 --- a/packages/shared/src/nodeSqliteClient.ts +++ b/packages/shared/src/nodeSqliteClient.ts @@ -247,11 +247,13 @@ parentPort.on("message", (request) => { parentPort.close(); return; } - const { id, sql, params, cached, values, raw, safeIntegers, received } = request; + const { id, sql, params, cached, values, raw, safeIntegers, received, savepoints } = request; let operation = "open"; let iterator; try { if (db === undefined) throw new Error("database connection is unavailable"); + operation = "execute"; + for (const savepoint of savepoints) db.exec(savepoint); operation = "prepare"; const statement = prepare(sql, cached); operation = "execute"; @@ -370,6 +372,8 @@ const makeWorkerConnection = Effect.fnUntraced(function* (options: { } | undefined; let nextRequestId = 0; + // Materialize nested savepoints with the next statement; empty jobs need no worker round trip. + const pendingSavepoints: string[] = []; // A replacement writer would lose the pragmas callers set on it, such as foreign_keys. let writerStopped: string | undefined; @@ -467,8 +471,18 @@ const makeWorkerConnection = Effect.fnUntraced(function* (options: { }); if (pending.size === 1) worker.ref(); const cached = input.cached && !hasLargeBinding(input.params); + const message = { + id, + safeIntegers, + ...input, + cached, + received, + savepoints: [...pendingSavepoints], + }; // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin. - worker.postMessage({ id, safeIntegers, ...input, cached, received }); + worker.postMessage(message); + // An unsent savepoint must stay queued, or its rollback would target an older sibling's. + pendingSavepoints.length = 0; }); // A posted write runs to the end, as it did on the event loop; the caller and its lock // must not move on while the worker is still applying it. Reads stay cancellable. @@ -492,12 +506,27 @@ const makeWorkerConnection = Effect.fnUntraced(function* (options: { executeUnprepared(sql, params, rowTransform) { // Read snapshots need deferred BEGIN; readonly connections reject IMMEDIATE and EXCLUSIVE. const statement = readOnly && /^\s*BEGIN\b/i.test(sql) ? "BEGIN" : sql; - const effect = request({ - sql: statement, - params: params ?? [], - cached: false, - values: false, - raw: false, + const effect = Effect.suspend(() => { + if (!readOnly && /^SAVEPOINT effect_sql_\d+$/.test(statement)) { + pendingSavepoints.push(statement); + return Effect.succeed([]); + } + const rollback = /^ROLLBACK TO SAVEPOINT (effect_sql_\d+)$/.exec(statement); + if (rollback !== null) { + const pending = pendingSavepoints.lastIndexOf(`SAVEPOINT ${rollback[1]}`); + if (pending !== -1) { + pendingSavepoints.splice(pending); + return Effect.succeed([]); + } + } + if (statement === "COMMIT" || statement === "ROLLBACK") pendingSavepoints.length = 0; + return request({ + sql: statement, + params: params ?? [], + cached: false, + values: false, + raw: false, + }); }); return rowTransform ? Effect.map(effect, rowTransform) : effect; }, From 6d1381f04c3655dfddb5ea38521a9a76bfe1184c Mon Sep 17 00:00:00 2001 From: Srijan Dubey <87586713+Srijan-D@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:15:39 +0530 Subject: [PATCH 054/183] fix(server): a fork renamed before its first message keeps that name (#38683) Co-authored-by: Julius Marminge --- .../src/orchestration-v2/Orchestrator.ts | 9 ++- .../src/orchestration-v2/ThreadForkService.ts | 3 +- .../ThreadTitleRegenerationService.test.ts | 79 +++++++++++++++++++ packages/contracts/src/orchestrationV2.ts | 2 + .../src/server/subagentProjection.ts | 1 + .../renamed-fork-keeps-its-name.e2e.ts | 36 +++++++++ 6 files changed, 126 insertions(+), 4 deletions(-) create mode 100644 scripts/scenarios/renamed-fork-keeps-its-name.e2e.ts diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 6b1fe8567b8e6..f4d74ee618955 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -733,11 +733,12 @@ function pendingThreadTitleGenerationEffect( // Clients seed a new thread with its first message, and empty threads start as "New thread" or // an agent's placeholder. Any other title on a thread without messages was chosen on purpose. -// Forks and side chats are titled from their source history instead. +// A fork or side chat starts with a title its first message replaces, so only a rename keeps it. function hasTitleSetBeforeFirstMessage( thread: OrchestrationV2AppThread, titleSeed: string | undefined, ): boolean { + if (thread.titleRenamed === true) return true; const title = thread.title.trim(); return ( thread.forkedFrom === null && @@ -4831,7 +4832,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }; return { ...thread, - ...(command.title === undefined ? {} : { title: command.title }), + ...(command.title === undefined ? {} : { title: command.title, titleRenamed: true }), ...(command.limitRecovery === undefined ? {} : { limitRecovery }), ...(command.limitRecovery !== undefined && limitRecovery?.snooze === true && @@ -5158,7 +5159,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio return thread.titleRegeneration?.requestId === command.requestId ? { ...thread, - ...(command.title === undefined ? {} : { title: command.title }), + ...(command.title === undefined + ? {} + : { title: command.title, titleRenamed: false }), ...(command.outcome === undefined ? {} : { diff --git a/apps/server/src/orchestration-v2/ThreadForkService.ts b/apps/server/src/orchestration-v2/ThreadForkService.ts index 1dc6d1eaf4a54..e3e523e372bd0 100644 --- a/apps/server/src/orchestration-v2/ThreadForkService.ts +++ b/apps/server/src/orchestration-v2/ThreadForkService.ts @@ -111,8 +111,9 @@ export const layer: Layer.Layer = Layer.succeed( creationSource: input.creationSource, id: input.targetThreadId, title: input.title ?? `${input.sourceProjection.thread.title} fork`, - // The source's title job completes only on the source thread. + // The source's title job and rename stay with the source thread. titleRegeneration: null, + titleRenamed: false, activeProviderThreadId: null, lineage: { parentThreadId: input.sourceProjection.thread.id, diff --git a/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts b/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts index cd4e4df9ff1a3..268c2ccb7e822 100644 --- a/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts @@ -390,6 +390,85 @@ describe("ThreadTitleRegenerationService", () => { }), ); + it.effect("keeps a fork's own rename when its first message arrives", () => + Effect.gen(function* () { + const seed = "Try SQLite instead"; + const harness = makeHarness(); + yield* Effect.gen(function* () { + const threads = yield* ThreadManagement.ThreadManagementService; + const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService; + const outbox = yield* EffectOutbox.EffectOutboxV2; + const prefix = "thread:title:renamed-fork"; + const { sourceThreadId, forkRunId, forkThreadId } = yield* forkSeededSource(prefix); + const rename = (key: string, threadId: ThreadId, title: string) => + threads.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make(`${prefix}:${key}:rename`), + threadId, + title, + }); + const fork = (key: string) => + Effect.gen(function* () { + const targetThreadId = ThreadId.make(`${prefix}:${key}`); + yield* threads.dispatch({ + type: "thread.fork", + commandId: CommandId.make(`${prefix}:${key}:fork`), + sourceThreadId, + targetThreadId, + sourcePoint: { type: "run", runId: forkRunId }, + createdBy: "user", + creationSource: "web", + }); + return targetThreadId; + }); + yield* rename("renamed", forkThreadId, "Storage migration notes"); + yield* rename("source", sourceThreadId, "Renamed source"); + const forkOfRenamedSource = yield* fork("fork-of-renamed-source"); + const regenerated = yield* fork("regenerated"); + yield* rename("regenerated", regenerated, "Scratch name"); + yield* titleRegeneration.execute({ + threadId: regenerated, + requestId: yield* armRegeneration({ + command: `${prefix}:regenerated:regenerate`, + threadId: regenerated, + }), + kind: { type: "regenerate" }, + }); + + for (const [key, threadId, expectedTitle, generates] of [ + ["renamed", forkThreadId, "Storage migration notes", false], + ["fork of a renamed source", forkOfRenamedSource, seed, true], + ["renamed, then regenerated", regenerated, seed, true], + ] as const) { + const requestId = CommandId.make(`${prefix}:${key}:message`); + yield* threads.dispatch({ + type: "message.dispatch", + commandId: requestId, + threadId, + messageId: MessageId.make(`${prefix}:${key}:message:message`), + text: seed, + titleSeed: seed, + attachments: [], + modelSelection, + dispatchMode: { type: "defer_start" }, + createdBy: "user", + creationSource: "web", + }); + + const settled = yield* threads.getThreadProjection(threadId); + assert.equal(settled.thread.title, expectedTitle, key); + assert.equal( + (yield* outbox.listByCommandId(requestId)).some( + (effect) => effect.request.type === "thread-title.generate", + ), + generates, + key, + ); + } + }).pipe(Effect.provide(harness.layer)); + }), + ); + it.effect( "titles an image-only first message without sending bootstrap text to the title model", () => diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 1a440bca2ad70..48ccf7c3f1641 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -532,6 +532,8 @@ 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. */ + titleRenamed: Schema.optional(Schema.Boolean), rollbackRequestId: Schema.optional(CommandId), rollbackFailure: Schema.optional( Schema.NullOr( diff --git a/packages/provider-core/src/server/subagentProjection.ts b/packages/provider-core/src/server/subagentProjection.ts index db992693547d6..88b124bf5fb79 100644 --- a/packages/provider-core/src/server/subagentProjection.ts +++ b/packages/provider-core/src/server/subagentProjection.ts @@ -71,6 +71,7 @@ export function makeSubagentChildThread(input: { id: input.childThreadId, title: input.title, titleRegeneration: null, + titleRenamed: false, linkedPullRequest: null, pullRequests: [], historyOrigin: undefined, diff --git a/scripts/scenarios/renamed-fork-keeps-its-name.e2e.ts b/scripts/scenarios/renamed-fork-keeps-its-name.e2e.ts new file mode 100644 index 0000000000000..f8719f24781ab --- /dev/null +++ b/scripts/scenarios/renamed-fork-keeps-its-name.e2e.ts @@ -0,0 +1,36 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "A fork renamed before its first message keeps that name", + WEB, + async ({ t3, app, screen }) => { + const project = await t3.project("demo"); + const thread = await t3.thread({ project, title: "Earlier work", messages: ["first"] }); + await t3.open(thread); + + await expect(screen.getByText("first fixture turn complete", { exact: false })).toBeVisible(); + await screen.getByRole("button", "Fork from this response").first().tap(); + const forkActions = screen.getByRole("button", "Thread actions for Earlier work fork"); + await expect(forkActions).toBeVisible(); + + await forkActions.tap(); + await screen.getByRole("menuitem", "Rename thread").tap(); + const title = screen.getByRole("textbox", "Thread title"); + await title.fill("Storage notes"); + await title.press("Enter"); + const renamedActions = screen.getByRole("button", "Thread actions for Storage notes"); + await expect(renamedActions).toBeVisible(); + + const composer = screen.getByRole("textbox"); + await composer.pressSequentially("Try SQLite instead"); + await composer.press("Enter"); + // The fork shows its source's reply too, so the second one is the fork's own. + await expect( + screen.getByText("first fixture turn complete", { exact: false }).nth(1), + ).toBeVisible(); + await app.screenshot("after-first-message"); + await expect(renamedActions).toBeVisible(); + }, +); From f9a3c38c50586977a375d93de77250cddfc8f039 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:17:08 +0530 Subject: [PATCH 055/183] fix(antigravity): recover threads after a lost thinking signature (#28889) Co-authored-by: PR Batch Tester Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks Co-authored-by: Julius Marminge --- .../Adapters/AcpAdapterV2.test.ts | 95 ++++++++++- .../src/orchestration-v2/Orchestrator.ts | 5 +- .../ProviderTurnStartService.test.ts | 18 +- .../ProviderTurnStartService.ts | 23 ++- .../ProviderSwitch.integration.test.ts | 156 ++++++++++++++++-- .../acp/AntigravityTurnOutcome.test.ts | 65 +++++--- .../provider/acp/AntigravityTurnOutcome.ts | 67 +++++--- .../src/server/adapter.ts | 16 +- packages/provider-acp/src/server/adapter.ts | 36 +++- 9 files changed, 401 insertions(+), 80 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 52123f19ef059..930c94a530d2a 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -1336,6 +1336,10 @@ describe("AcpAdapterV2", () => { ); it.live("fails an end_turn the outcome check rejects and restarts before the next turn", () => Effect.gen(function* () { + const checking = yield* Deferred.make(); + const releaseCheck = yield* Deferred.make(); + const cancelled = yield* Deferred.make(); + const idAllocator = yield* IdAllocator.IdAllocatorV2; const instanceId = ProviderInstanceId.make("acp-test-prompt-outcome"); const threadId = ThreadId.make("thread-acp-prompt-outcome"); const quota = { @@ -1345,6 +1349,12 @@ describe("AcpAdapterV2", () => { retryable: true, resetAt: "2030-01-01T00:00:00.000Z", } as const; + const poisoned = { + class: "provider_error", + message: "Saved history is unusable.", + code: "INVALID_THINKING_SIGNATURE", + retryable: true, + } as const; // The runtime ordinal of each prompt, and the session each check watched. const promptRuntimes: Array = []; const promptTexts: Array = []; @@ -1358,14 +1368,27 @@ describe("AcpAdapterV2", () => { watchPromptOutcome: (sessionId) => Effect.sync(() => { watchedSessions.push(sessionId); - const failed = watchedSessions.length === 1; - return () => Effect.succeed(failed ? quota : undefined); + const outcome = + watchedSessions.length === 1 + ? { failure: quota, threadDisposition: "reusable" as const } + : watchedSessions.length >= 3 + ? { failure: poisoned, threadDisposition: "broken" as const } + : undefined; + const interrupted = watchedSessions.length === 4; + return () => + interrupted + ? Deferred.succeed(checking, undefined).pipe( + Effect.andThen(Deferred.await(releaseCheck)), + Effect.as(outcome), + ) + : Effect.succeed(outcome); }), makeRuntime: makeMockRuntime({ childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner, mockAgentPath: yield* bundledMockAgentPath, wrapRuntime: (runtime, runtimeOrdinal) => ({ ...runtime, + cancel: Deferred.succeed(cancelled, undefined).pipe(Effect.asVoid), prompt: (payload) => Effect.sync(() => { promptRuntimes.push(runtimeOrdinal); @@ -1409,19 +1432,20 @@ describe("AcpAdapterV2", () => { ordinal, }), ); - const events = yield* runtime.events.pipe( - Stream.takeUntil((event) => event.type === "turn.terminal"), - Stream.runCollect, + return Array.from( + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), ); - return events.at(-1); }); - const failed = yield* runTurn(1); + const failed = (yield* runTurn(1)).at(-1); if (failed?.type !== "turn.terminal" || failed.status !== "failed") { return assert.fail("expected a failed terminal"); } assert.deepEqual(failed.failure, quota); - const completed = yield* runTurn(2); + const completed = (yield* runTurn(2)).at(-1); assert.equal(completed?.type === "turn.terminal" ? completed.status : null, "completed"); assert.deepEqual(promptRuntimes, [1, 2], "the next turn runs on a fresh runtime"); // The fresh runtime has no record of what reached the agent, so it sends T3's notes again. @@ -1429,6 +1453,61 @@ describe("AcpAdapterV2", () => { assert.include(promptTexts[1] ?? "", "T3 Code interaction mode: Default"); assert.equal(watchedSessions.length, 2); assert.equal(watchedSessions[0], watchedSessions[1]); + + // Poisoned native history marks the thread broken; its persisted error row is never resumed. + const poisonedEvents = yield* runTurn(3); + const broken = poisonedEvents.at(-1); + if (broken?.type !== "turn.terminal" || broken.status !== "failed") { + return assert.fail("expected a failed terminal"); + } + assert.deepEqual(broken.failure, poisoned); + assert.equal(broken.threadDisposition, "broken"); + const brokenThread = poisonedEvents.findLast( + (event) => event.type === "provider_thread.updated", + ); + assert.equal( + brokenThread?.type === "provider_thread.updated" + ? brokenThread.providerThread.status + : null, + "error", + ); + const resumed = yield* Effect.result( + runtime.resumeThread({ + threadId, + providerThread: { ...providerThread, status: "error" }, + modelSelection, + runtimePolicy, + }), + ); + assert.equal( + resumed._tag === "Failure" ? resumed.failure._tag : null, + "ProviderAdapterResumeThreadError", + ); + + const turn = yield* Effect.forkChild(runTurn(4)); + yield* Deferred.await(checking); + const stop = yield* Effect.forkChild( + runtime.interruptTurn({ + providerThread, + providerTurnId: idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, `${watchedSessions[3]}:turn:4`), + }), + }), + ); + yield* Deferred.await(cancelled); + yield* Deferred.succeed(releaseCheck, undefined); + const interruptedEvents = yield* Fiber.join(turn); + yield* Fiber.join(stop); + const interrupted = interruptedEvents.at(-1); + assert.equal( + interrupted?.type === "turn.terminal" ? interrupted.status : null, + "interrupted", + ); + assert.equal( + interrupted?.type === "turn.terminal" ? interrupted.threadDisposition : null, + "broken", + ); }).pipe(Effect.provide(layerTest)), ); it.live("retains returned usage when Stop finalizes before the prompt callback", () => diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index f4d74ee618955..f13155f1447a3 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -2722,6 +2722,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const deliveryProviderThread = canResumeAcrossInstances ? { ...queuedProviderThread, + status: activeProviderThread.status, nativeThreadRef: activeProviderThread.nativeThreadRef, nativeConversationHeadRef: activeProviderThread.nativeConversationHeadRef, nativeMetadata: activeProviderThread.nativeMetadata, @@ -2913,7 +2914,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const providerThread: OrchestrationV2ProviderThread = { ...deliveryProviderThread, providerSessionId, - status: "not_loaded", + status: deliveryProviderThread.status === "error" ? "error" : "not_loaded", firstRunOrdinal: queuedProviderThread.firstRunOrdinal ?? ordinal, lastRunOrdinal: ordinal, handoffIds: appendContextHandoffId( @@ -8815,7 +8816,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : null; const providerThread: OrchestrationV2ProviderThread = { ...ensuredProviderThread, - status: "active", + status: ensuredProviderThread.status === "error" ? "error" : "active", firstRunOrdinal: ensuredProviderThread.firstRunOrdinal ?? ordinal, lastRunOrdinal: ordinal, handoffIds: [ diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index d12e6fd1e8bdb..66fc7c97c7fa1 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -2986,11 +2986,20 @@ effectIt.effect("does not mistake a failed state read for a superseded run", () }), ); -effectIt.effect( - "signs out the existing native provider before opening the newly selected provider", - () => +effectIt.effect.each(["not_loaded", "error"] as const)( + "signs out the existing native provider before opening the newly selected provider with status %s", + (providerThreadStatus) => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "/logout", previousNativeSession: true }); + const initial = harness.projection(); + harness.setProjection({ + ...initial, + providerThreads: initial.providerThreads.map((thread) => + thread.id === "new-provider-thread" + ? { ...thread, status: providerThreadStatus } + : thread, + ), + }); yield* harness.start; yield* harness.start; @@ -3016,6 +3025,9 @@ effectIt.effect( ]); expect(projection.providerTurns).toEqual([]); expect(projection.checkpoints).toEqual([]); + expect( + projection.providerThreads.find((thread) => thread.id === "new-provider-thread")?.status, + ).toBe(providerThreadStatus); }), ); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index bb5701d337d0d..43c5e663f90d1 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -686,7 +686,12 @@ export const layer: Layer.Layer< }, providerThreadUpdate: { ...providerThread, - status: providerThread.nativeThreadRef === null ? "not_loaded" : "idle", + status: + providerThread.status === "error" + ? "error" + : providerThread.nativeThreadRef === null + ? "not_loaded" + : "idle", updatedAt: now, }, }); @@ -842,6 +847,12 @@ export const layer: Layer.Layer< run, checkpointScope, }); + const brokenNativeThread = providerThread.status === "error"; + // Opened without the broken native id, a session that was not live starts fresh. + const opensFreshSession = + brokenNativeThread && + providerThread.nativeThreadRef !== null && + !(yield* providerSessions.isLive(providerSessionId)); const sessionResult = yield* Effect.result( providerSessions.open({ threadId: projection.thread.id, @@ -851,7 +862,7 @@ export const layer: Layer.Layer< ...(existingSessionProjection === undefined ? {} : { resumeFromSession: existingSessionProjection }), - ...(providerThread.nativeThreadRef?.nativeId == null + ...(providerThread.nativeThreadRef?.nativeId == null || brokenNativeThread ? {} : { initialNativeThreadId: providerThread.nativeThreadRef.nativeId }), ...(providerThread.nativeMetadata?.itemIdentityVersion === undefined @@ -1158,6 +1169,7 @@ export const layer: Layer.Layer< const createdAt = yield* DateTime.now; const history = yield* projectionStore.getTurnStartHistory(input.threadId); const boundary = contextBoundaryOrdinal({ runs: projection.runs, turnItems: history }); + const from = Math.max(1, boundary); const handoff = yield* contextHandoffService.prepareProviderHandoff({ threadId: projection.thread.id, targetRunId: run.id, @@ -1166,7 +1178,7 @@ export const layer: Layer.Layer< toProviderThreadId: providerThread.id, fromProviderInstanceId: providerThread.providerInstanceId, toProviderInstanceId: run.providerInstanceId, - coveredRunOrdinals: { from: 1, to: Math.max(1, run.ordinal - 1) }, + coveredRunOrdinals: { from, to: Math.max(from, run.ordinal - 1) }, strategy: "full_thread_summary", runs: projection.runs, items: [ @@ -1536,7 +1548,10 @@ export const layer: Layer.Layer< providerSessionId, // Clear the native ref to force a fresh session while preserving row identity. existingProviderThread: { ...providerThread, nativeThreadRef: null }, - forceNewNativeThread: true, + // A fresh session that never loaded the broken history needs no replacement. + ...(opensFreshSession && resumed._tag === "Failure" + ? {} + : { forceNewNativeThread: true }), }), ); if (replacement === undefined) return undefined; 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 bbef6f3fac48c..9929688d88e23 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -58,6 +58,7 @@ import * as EffectOutbox from "../EffectOutbox.ts"; import * as ProjectionReplay from "./ProjectionReplay.ts"; import * as ProjectionStore from "../ProjectionStore.ts"; import * as ProviderAdapterRegistry from "../ProviderAdapterRegistry.ts"; +import * as ProviderSessionManager from "../ProviderSessionManager.ts"; import { makeProviderFailure } from "@t3tools/provider-core/server/failure"; import { CLAUDE_MODEL_SELECTION, @@ -116,6 +117,7 @@ function makeTestAdapter(input: { >; readonly failure?: ReturnType; readonly failedRunOrdinals?: ReadonlySet; + readonly brokenRunOrdinals?: ReadonlySet; readonly interruptedRunOrdinals?: ReadonlySet; readonly cancelledRunOrdinals?: ReadonlySet; readonly holdRunOrdinal?: number; @@ -132,6 +134,8 @@ function makeTestAdapter(input: { readonly backgroundTasksEndWithProcess?: true; readonly backgroundWork?: Ref.Ref; readonly closedSessions?: Ref.Ref>; + /** Like ACP: opening resumes the initial native id, and forcing a new thread restarts the runtime. */ + readonly runtimeStarts?: Ref.Ref>; // ACP cannot truncate, so its rollback answers with a fresh, empty native session. readonly rollback?: "truncates" | "replaces_native_thread"; }): ProviderAdapter.ProviderAdapterV2["Service"] { @@ -144,6 +148,12 @@ function makeTestAdapter(input: { Effect.gen(function* () { if (input.holdOpenSession !== undefined) yield* Deferred.await(input.holdOpenSession); const events = yield* PubSub.unbounded(); + if (input.runtimeStarts !== undefined) { + yield* Ref.update(input.runtimeStarts, (starts) => [ + ...starts, + sessionInput.initialNativeThreadId ?? "new", + ]); + } if (input.closedSessions !== undefined) { const closedSessions = input.closedSessions; yield* Effect.addFinalizer(() => @@ -197,6 +207,9 @@ function makeTestAdapter(input: { }), ensureThread: (threadInput) => Effect.gen(function* () { + if (threadInput.forceNewNativeThread && input.runtimeStarts !== undefined) { + yield* Ref.update(input.runtimeStarts, (starts) => [...starts, "replacement"]); + } const createdAt = yield* DateTime.now; const generation = input.nativeThreadGeneration === undefined @@ -229,6 +242,7 @@ function makeTestAdapter(input: { resumeThread: ({ providerThread }) => Effect.gen(function* () { if ( + (input.brokenRunOrdinals !== undefined && providerThread.status === "error") || input.failResume || (input.failResumeOnce !== undefined && (yield* Ref.getAndSet(input.failResumeOnce, false))) @@ -427,7 +441,9 @@ function makeTestAdapter(input: { }), } : { status: terminalStatus, failure: null }), - threadDisposition: "reusable", + threadDisposition: input.brokenRunOrdinals?.has(turnInput.runOrdinal) + ? "broken" + : "reusable", }, ]; const reportedUsage = input.tokenUsageByRunOrdinal?.[turnInput.runOrdinal]; @@ -443,6 +459,17 @@ function makeTestAdapter(input: { }, }); } + if (input.brokenRunOrdinals?.has(turnInput.runOrdinal)) { + yield* PubSub.publish(events, { + type: "provider_thread.updated", + driver: input.driver, + providerThread: { + ...turnInput.providerThread, + status: "error", + updatedAt: eventTime, + }, + }); + } for (const event of providerEvents) { yield* PubSub.publish(events, event); } @@ -2307,7 +2334,8 @@ describe("orchestration v2 provider switching", () => { it.live.each( ( [ - ["failed", false, false, false], + ["failed", false, false, false, false], + ["failed", false, false, false, true], ["failed", true, true, true], ["interrupted", false, true, false], ["interrupted", true, false, true], @@ -2315,13 +2343,13 @@ describe("orchestration v2 provider switching", () => { ["cancelled", true, true, false], ] as const ).map( - ([status, queued, returning, native]) => + ([status, queued, returning, native, broken]) => [ - `${status} context ${queued ? "through the queue" : "immediately"} to ${returning ? "a returning" : "a new"} provider via ${native ? "native history" : "text"}`, - { status, queued, returning, native }, + `${status}${broken ? " broken" : ""} context ${queued ? "through the queue" : "immediately"} to ${returning ? "a returning" : "a new"} provider via ${native ? "native history" : "text"}`, + { status, queued, returning, native, broken }, ] as const, ), - )("hands off %s", ([, { status, queued, returning, native }]) => + )("hands off %s", ([, { status, queued, returning, native, broken }]) => Effect.gen(function* () { const cwd = yield* checkpointWorkspace(`handoff-${status}-${queued}-${returning}`); const capturedTurns = yield* Ref.make>([]); @@ -2331,6 +2359,7 @@ describe("orchestration v2 provider switching", () => { const sourceOrdinal = returning ? 2 : 1; const sourceSelection = returning ? CLAUDE_MODEL_SELECTION : CODEX_MODEL_SELECTION; const targetSelection = returning ? CODEX_MODEL_SELECTION : CLAUDE_MODEL_SELECTION; + const generation = yield* Ref.make(0); const originalPrompt = "Keep the release marker violet and preserve the existing API."; const partialResponse = "I checked the API and found the release configuration."; const layerRegistry = ProviderAdapterRegistry.layerFromAdapters( @@ -2353,6 +2382,12 @@ describe("orchestration v2 provider switching", () => { ...(modelSelection.instanceId === sourceSelection.instanceId ? { failedRunOrdinals: new Set(status === "failed" ? [sourceOrdinal] : []), + ...(broken + ? { + brokenRunOrdinals: new Set([sourceOrdinal]), + nativeThreadGeneration: generation, + } + : {}), interruptedRunOrdinals: new Set(status === "interrupted" ? [sourceOrdinal] : []), cancelledRunOrdinals: new Set(status === "cancelled" ? [sourceOrdinal] : []), holdRunOrdinal: sourceOrdinal, @@ -2466,8 +2501,17 @@ describe("orchestration v2 provider switching", () => { yield* dispatch("back", "Finish the remaining work", sourceSelection); yield* waitForRun(sourceOrdinal + 2, "completed"); const back = (yield* Ref.get(capturedTurns)).at(-1)!; - assert.notInclude(back.text, originalPrompt); - assert.notInclude(back.text, partialResponse); + if (broken) { + const source = (yield* Ref.get(capturedTurns)).find( + (turn) => turn.modelSelection.instanceId === sourceSelection.instanceId, + )!; + assert.notEqual(back.nativeThreadId, source.nativeThreadId); + assert.include(back.text, originalPrompt); + assert.include(back.text, partialResponse); + } else { + assert.notInclude(back.text, originalPrompt); + assert.notInclude(back.text, partialResponse); + } }).pipe( Effect.provide( ProviderReplayHarness.layerWithRegistry( @@ -4129,15 +4173,23 @@ describe("orchestration v2 provider switching", () => { }), ); - it.live.each(["immediately", "behind a running turn"] as const)( + it.live.each([ + "immediately", + "behind a running turn", + "and recovers it after it breaks", + "and recovers it after it breaks and the server restarts", + ] as const)( "starts a fresh provider session %s and never hands earlier runs to a later provider", (variant) => Effect.gen(function* () { - const queued = variant !== "immediately"; - const key = queued ? "queued" : "immediate"; + const queued = variant === "behind a running turn"; + const restarted = variant === "and recovers it after it breaks and the server restarts"; + const broken = restarted || variant === "and recovers it after it breaks"; + const key = queued ? "queued" : restarted ? "restarted" : broken ? "broken" : "immediate"; const cwd = yield* checkpointWorkspace(`fresh-context-${key}`); const capturedTurns = yield* Ref.make>([]); const closedSessions = yield* Ref.make>([]); + const runtimeStarts = yield* Ref.make>([]); // A queued start has nobody to refuse, so a busy session must stay up. const backgroundWork = yield* Ref.make(queued); const started = yield* Deferred.make(); @@ -4151,11 +4203,18 @@ describe("orchestration v2 provider switching", () => { responseByRunOrdinal: {}, capturedTurns, closedSessions, + runtimeStarts, backgroundWork, nativeThreadGeneration: yield* Ref.make(0), ...(queued ? { holdFirstTurn: started, releaseFirstTurn: release, holdRunOrdinal: 2 } : {}), + ...(broken + ? { + failedRunOrdinals: new Set([3]), + brokenRunOrdinals: new Set([3]), + } + : {}), }), makeTestAdapter({ instanceId: CODEX_MODEL_SELECTION.instanceId, @@ -4249,6 +4308,22 @@ describe("orchestration v2 provider switching", () => { // Claude hosts one native thread per session, so an idle old one is closed. assert.deepEqual(yield* Ref.get(closedSessions), queued ? [] : [firstSession.id]); yield* Ref.set(backgroundWork, false); + let startsBeforeRecovery = 0; + if (broken) { + if (restarted) { + const brokenProjection = yield* orchestrator.getThreadProjection(freshThreadId); + const brokenThread = brokenProjection.providerThreads.find( + (thread) => thread.id === brokenProjection.thread.activeProviderThreadId, + )!; + assert.equal(brokenThread.status, "error"); + const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2; + yield* sessions.close(brokenThread.providerSessionId!); + } + startsBeforeRecovery = (yield* Ref.get(runtimeStarts)).length; + yield* send("epsilon", CLAUDE_MODEL_SELECTION); + yield* worker.drain(); + yield* waitForIdle(freshThreadId); + } yield* send("delta", CODEX_MODEL_SELECTION); yield* worker.drain(); yield* waitForIdle(freshThreadId); @@ -4277,6 +4352,27 @@ describe("orchestration v2 provider switching", () => { if (queued) { assert.equal(turnFor("gamma").providerThreadId, turnFor("beta").providerThreadId); } + if (broken) { + const recovered = turnFor("epsilon"); + assert.equal(recovered.providerThreadId, turnFor("beta").providerThreadId); + assert.notEqual(recovered.nativeThreadId, turnFor("beta").nativeThreadId); + assert.include(recovered.text, "Prompt beta"); + assert.notInclude(recovered.text, "Prompt alpha"); + assert.notInclude(recovered.text, "Prompt zero"); + // The broken native id is never reopened; a reopened session starts fresh only once. + assert.deepEqual( + (yield* Ref.get(runtimeStarts)).slice(startsBeforeRecovery), + restarted ? ["new"] : ["replacement"], + ); + const recoveredRun = projection.runs.find( + (run) => run.userMessageId === `message:fresh-context:${key}:epsilon`, + )!; + assert.equal( + projection.contextHandoffs.find((handoff) => handoff.targetRunId === recoveredRun.id)! + .coveredRunOrdinals.from, + 3, + ); + } const codexTurn = turnFor("delta"); assert.notEqual(codexTurn.providerThreadId, turnFor("zero").providerThreadId); assert.include(codexTurn.text, "Prompt beta"); @@ -4410,6 +4506,8 @@ describe("orchestration v2 provider switching", () => { responseByRunOrdinal: {}, capturedTurns, nativeThreadGeneration: yield* Ref.make(0), + failedRunOrdinals: new Set([5]), + brokenRunOrdinals: new Set([5]), }), ]); const threadId = ThreadId.make("thread:scheduled-fresh-user-chat"); @@ -4457,6 +4555,7 @@ describe("orchestration v2 provider switching", () => { ["compaction", false], ["scheduled-after-compaction", true], ["user-third", false], + ["user-fourth", false], ] as const) { if (name === "compaction") { // The user's run compacts, so later dispatches no longer read the first scheduled run's message. @@ -4507,6 +4606,21 @@ describe("orchestration v2 provider switching", () => { // The scheduled run's fresh session must not replace the user's conversation. assert.equal(turnFor("user-second")!.nativeThreadId, turnFor("user-first")!.nativeThreadId); assert.equal(turnFor("user-third")!.nativeThreadId, turnFor("user-first")!.nativeThreadId); + // The user's session broke; recovery reads the whole thread, so scheduled runs do not cut it. + const recovered = turnFor("user-fourth")!; + assert.equal(recovered.providerThreadId, turnFor("user-first")!.providerThreadId); + assert.notEqual(recovered.nativeThreadId, turnFor("user-first")!.nativeThreadId); + assert.include(recovered.text, "user-first"); + assert.include(recovered.text, "user-third"); + const projection = yield* orchestrator.getThreadProjection(threadId); + const recoveredRun = projection.runs.find( + (run) => run.userMessageId === "message:scheduled-fresh-user-chat:user-fourth", + )!; + assert.equal( + projection.contextHandoffs.find((handoff) => handoff.targetRunId === recoveredRun.id)! + .coveredRunOrdinals.from, + 1, + ); }).pipe( Effect.provide( ProviderReplayHarness.layerWithRegistry( @@ -4643,6 +4757,7 @@ describe("orchestration v2 provider switching", () => { it.live.each([ ["automatic", "Claude"], ["queue.resume", "compatible Codex"], + ["queue.resume", "broken compatible Codex"], ] as const)( "delivers a queued PR update on the current provider through %s (%s)", ([delivery, target]) => @@ -4651,7 +4766,9 @@ describe("orchestration v2 provider switching", () => { const capturedTurns = yield* Ref.make>([]); const started = yield* Deferred.make(); const release = yield* Deferred.make(); - const compatible = target === "compatible Codex"; + const compatible = target !== "Claude"; + const broken = target === "broken compatible Codex"; + const generation = yield* Ref.make(0); const selection = { ...(compatible ? { ...CODEX_MODEL_SELECTION, instanceId: ProviderInstanceId.make("codex-alternate") } @@ -4663,7 +4780,7 @@ describe("orchestration v2 provider switching", () => { ...CodexProviderCapabilitiesV2, context: { ...CodexProviderCapabilitiesV2.context, - canConsumeHandoffSummaries: false, + canConsumeHandoffSummaries: broken, }, } : ClaudeProviderCapabilitiesV2; @@ -4678,6 +4795,9 @@ describe("orchestration v2 provider switching", () => { holdFirstTurn: started, releaseFirstTurn: release, failedRunOrdinals: new Set([1]), + ...(broken + ? { brokenRunOrdinals: new Set([1]), nativeThreadGeneration: generation } + : {}), failure: makeProviderFailure({ message: "Usage limit reached", class: "usage_limit", @@ -4691,6 +4811,9 @@ describe("orchestration v2 provider switching", () => { modelSelection: selection, responseByRunOrdinal: {}, capturedTurns, + ...(broken + ? { brokenRunOrdinals: new Set(), nativeThreadGeneration: generation } + : {}), }), ]; const layerRegistry = compatible @@ -4828,7 +4951,12 @@ describe("orchestration v2 provider switching", () => { assert.equal(executed.providerThreadId, turns[1]!.providerThreadId); assert.equal(executed.nativeThreadId, turns[1]!.nativeThreadId); } - if (compatible) { + if (broken) { + assert.notEqual(executed.nativeThreadId, turns[0]!.nativeThreadId); + assert.isFalse(executed.nativeThreadHasTurns); + assert.include(executed.text, "Original work"); + } + if (compatible && !broken) { assert.equal(executed.nativeThreadId, turns[0]!.nativeThreadId); assert.isEmpty(after.contextHandoffs); } diff --git a/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts b/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts index 52e96caa08aea..eb0695948b30c 100644 --- a/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts +++ b/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts @@ -6,6 +6,7 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import type * as EffectAcpSchema from "effect-acp/compat"; +import type { OrchestrationV2ProviderFailure } from "@t3tools/contracts"; import { watchAntigravityPromptOutcome } from "./AntigravityTurnOutcome.ts"; @@ -32,10 +33,19 @@ const RATE_LIMIT_ERROR = errorPayload( const INVALID_ARGUMENT_ERROR = errorPayload( "Error 400, Message: Request contains an invalid argument., Status: INVALID_ARGUMENT, Details: []", ); +// Vertex Claude rejects a resumed history whose saved thinking block lost its signature. +const MISSING_SIGNATURE_ERROR = errorPayload( + 'Error 400, Message: {"type":"error","error":{"type":"invalid_request_error","message":"messages.1.content.0.thinking.signature: Field required"},"request_id":"req_vrtx_test"}, Status: INVALID_ARGUMENT, Details: []', +); +const INVALID_SIGNATURE_ERROR = errorPayload( + 'Error 400, Message: {"type":"error","error":{"type":"invalid_request_error","message":"messages.3.content.0: Invalid `signature` in `thinking` block"}}, Status: INVALID_ARGUMENT, Details: []', +); // The model's reply quoting the agent's quota notice is an ordinary planner response. const QUOTED_NOTICE = Buffer.from( "Usage Limit Reached\n\nYou have reached your current quota for this period. Your limit will reset in 1 hour.", ); +const reusable = (failure: OrchestrationV2ProviderFailure) => + ({ failure, threadDisposition: "reusable" }) as const; describe("watchAntigravityPromptOutcome", () => { it.effect("fails only turns whose own steps end in an upstream error", () => @@ -83,13 +93,13 @@ describe("watchAntigravityPromptOutcome", () => { [USER_INPUT, input], [ERROR_MESSAGE, QUOTA_ERROR], ]), - { + reusable({ class: "usage_limit", message: "You have reached your Antigravity quota for this period.", code: "RESOURCE_EXHAUSTED", retryable: true, resetAt: "1970-01-01T01:00:00.000Z", - }, + }), ); // The earlier error step is outside this turn. assert.isUndefined( @@ -109,26 +119,35 @@ describe("watchAntigravityPromptOutcome", () => { [USER_INPUT, input], [ERROR_MESSAGE, RATE_LIMIT_ERROR], ]), - { + reusable({ class: "usage_limit", message: "Resource has been exhausted (e.g. check quota).", code: "RESOURCE_EXHAUSTED", retryable: true, resetAt: "1970-01-01T00:00:42.000Z", - }, + }), ); assert.deepEqual( yield* turn([ [USER_INPUT, input], [ERROR_MESSAGE, INVALID_ARGUMENT_ERROR], ]), - { + reusable({ class: "provider_error", message: "Request contains an invalid argument.", code: "INVALID_ARGUMENT", retryable: false, - }, + }), ); + // A saved thinking block without a valid signature fails every later prompt. + for (const error of [MISSING_SIGNATURE_ERROR, INVALID_SIGNATURE_ERROR]) { + const outcome = yield* turn([ + [USER_INPUT, input], + [ERROR_MESSAGE, error], + ]); + assert.equal(outcome?.failure.code, "INVALID_THINKING_SIGNATURE"); + assert.equal(outcome?.threadDisposition, "broken"); + } // A completed tool keeps its usage, and the turn still fails. assert.equal( (yield* turn( @@ -142,7 +161,7 @@ describe("watchAntigravityPromptOutcome", () => { stopReason: "end_turn", usage: { inputTokens: 40, outputTokens: 5, totalTokens: 45 }, }, - ))?.class, + ))?.failure.class, "usage_limit", ); assert.isUndefined( @@ -152,12 +171,15 @@ describe("watchAntigravityPromptOutcome", () => { ]), ); // The agent maps the SDK's QUOTA_EXHAUSTED stop reason to `refusal`. - assert.deepEqual(yield* turn([], { stopReason: "refusal" }), { - class: "usage_limit", - message: "You have reached your Antigravity quota for this period.", - code: "QUOTA_EXHAUSTED", - retryable: true, - }); + assert.deepEqual( + yield* turn([], { stopReason: "refusal" }), + reusable({ + class: "usage_limit", + message: "You have reached your Antigravity quota for this period.", + code: "QUOTA_EXHAUSTED", + retryable: true, + }), + ); }).pipe(Effect.provide(NodeServices.layer)), ); @@ -193,19 +215,22 @@ describe("watchAntigravityPromptOutcome", () => { const linked = yield* watchAntigravityPromptOutcome(profileDirectory, own); append(peer, ERROR_MESSAGE, QUOTA_ERROR); assert.isUndefined(yield* linked({ stopReason: "end_turn" })); - assert.equal((yield* linked({ stopReason: "refusal" }))?.class, "usage_limit"); + assert.equal((yield* linked({ stopReason: "refusal" }))?.failure.class, "usage_limit"); // An unreadable log gives no evidence, but the agent's typed refusal still fails the turn. yield* fs.remove(path.join(conversations, `${own}.db`)); yield* fs.writeFileString(path.join(conversations, `${own}.db`), "not a database"); const corrupt = yield* watchAntigravityPromptOutcome(profileDirectory, own); assert.isUndefined(yield* corrupt({ stopReason: "end_turn" })); - assert.deepEqual(yield* corrupt({ stopReason: "refusal" }), { - class: "usage_limit", - message: "You have reached your Antigravity quota for this period.", - code: "QUOTA_EXHAUSTED", - retryable: true, - }); + assert.deepEqual( + yield* corrupt({ stopReason: "refusal" }), + reusable({ + class: "usage_limit", + message: "You have reached your Antigravity quota for this period.", + code: "QUOTA_EXHAUSTED", + retryable: true, + }), + ); }).pipe(Effect.provide(NodeServices.layer)), ); }); diff --git a/apps/server/src/provider/acp/AntigravityTurnOutcome.ts b/apps/server/src/provider/acp/AntigravityTurnOutcome.ts index 41e25f2e417e1..2cbe4d62b3a4b 100644 --- a/apps/server/src/provider/acp/AntigravityTurnOutcome.ts +++ b/apps/server/src/provider/acp/AntigravityTurnOutcome.ts @@ -20,6 +20,10 @@ const MAX_ERROR_PAYLOAD_BYTES = 16_384; // The Go harness's rendering of a Google API error, as the agent's api_errors.py reads it. const API_ERROR = /Error (\d{3}), Message: (.+?), Status: ([A-Z_]+)/s; const QUOTA_EXHAUSTED = /\breason:QUOTA_EXHAUSTED\b/; +// Claude rejects a saved thinking block without a valid signature. It sits in the native +// history, so every later prompt to that session fails the same way. +const INVALID_THINKING_SIGNATURE = + /\bmessages\.\d+\.content\.\d+(?:\.thinking\.signature: Field required|: Invalid `signature` in `thinking` block)/; const RESET_TIMESTAMP = /\bquotaResetTimeStamp:([^\s\]]+)/; const RESET_DELAY = /\bquotaResetDelay:((?:\d+(?:\.\d+)?(?:ns|us|µs|μs|ms|h|m|s))+)(?=[\s\]])/; // google.rpc.RetryInfo, which plain rate limits carry instead of a quota reset. @@ -106,7 +110,12 @@ function turnFailure( stopReason: EffectAcpSchema.StopReason, step: LastStep | undefined, now: DateTime.Utc, -): OrchestrationV2ProviderFailure | undefined { +): + | { + readonly failure: OrchestrationV2ProviderFailure; + readonly threadDisposition: "reusable" | "broken"; + } + | undefined { const errorText = step?.type === ERROR_STEP_TYPE ? new TextDecoder().decode(step.payload ?? new Uint8Array()) @@ -115,30 +124,50 @@ function turnFailure( if (errorText === undefined && stopReason !== "refusal") return undefined; const text = errorText ?? ""; const apiError = API_ERROR.exec(text); + const reusable = (failure: OrchestrationV2ProviderFailure) => + ({ failure, threadDisposition: "reusable" }) as const; if (stopReason === "refusal" || QUOTA_EXHAUSTED.test(text)) { - return makeProviderFailure({ - class: "usage_limit", - message: "You have reached your Antigravity quota for this period.", - code: apiError?.[3] ?? "QUOTA_EXHAUSTED", - retryable: true, - resetAt: resetAtFrom(text, now) ?? null, - }); + return reusable( + makeProviderFailure({ + class: "usage_limit", + message: "You have reached your Antigravity quota for this period.", + code: apiError?.[3] ?? "QUOTA_EXHAUSTED", + retryable: true, + resetAt: resetAtFrom(text, now) ?? null, + }), + ); + } + if (INVALID_THINKING_SIGNATURE.test(text)) { + return { + failure: makeProviderFailure({ + class: "provider_error", + message: + "Antigravity's saved conversation can no longer be sent to the model. The next message starts a fresh Antigravity session with this thread's context.", + code: "INVALID_THINKING_SIGNATURE", + retryable: true, + }), + threadDisposition: "broken", + }; } if (apiError === null) { - return makeProviderFailure({ - class: "provider_error", - message: "Antigravity stopped this turn because of an error.", - }); + return reusable( + makeProviderFailure({ + class: "provider_error", + message: "Antigravity stopped this turn because of an error.", + }), + ); } const [, httpStatus, message, status] = apiError; const rateLimited = httpStatus === "429" || status === "RESOURCE_EXHAUSTED"; - return makeProviderFailure({ - class: rateLimited ? "usage_limit" : "provider_error", - message: message!.trim(), - code: status ?? null, - retryable: rateLimited || Number(httpStatus) >= 500, - resetAt: resetAtFrom(text, now) ?? null, - }); + return reusable( + makeProviderFailure({ + class: rateLimited ? "usage_limit" : "provider_error", + message: message!.trim(), + code: status ?? null, + retryable: rateLimited || Number(httpStatus) >= 500, + resetAt: resetAtFrom(text, now) ?? null, + }), + ); } const conversationSegments = ["antigravity-acp", "conversations"]; diff --git a/packages/provider-acp-registry/src/server/adapter.ts b/packages/provider-acp-registry/src/server/adapter.ts index 837d296773933..d730cbd5e6b1d 100644 --- a/packages/provider-acp-registry/src/server/adapter.ts +++ b/packages/provider-acp-registry/src/server/adapter.ts @@ -34,6 +34,7 @@ import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import type * as Scope from "effect/Scope"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import type * as EffectAcpSchema from "effect-acp/compat"; import * as EffectAcpErrors from "effect-acp/errors"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; @@ -261,7 +262,20 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu : {}), // glm-acp-agent is the one agent whose per-turn usage a live probe has verified. ...(registryAgentId === "glm-acp-agent" ? { reportsPerTurnPromptUsage: true } : {}), - ...(watchKimiPromptOutcome === undefined ? {} : { watchPromptOutcome: watchKimiPromptOutcome }), + ...(watchKimiPromptOutcome === undefined + ? {} + : { + watchPromptOutcome: (sessionId: string) => + Effect.map( + watchKimiPromptOutcome(sessionId), + (check) => (result: EffectAcpSchema.PromptResponse) => + Effect.map(check(result), (failure) => + failure === undefined + ? undefined + : { failure, threadDisposition: "reusable" as const }, + ), + ), + }), ...(registryAgentId === "mistral-vibe" ? { registerExtensions: registerMistralVibeAcpExtensions } : {}), diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 7abc540793aff..ea0bb5e46f46a 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -339,6 +339,11 @@ export function acpPerTurnPromptUsage( }; } +interface AcpPromptOutcomeFailure { + readonly failure: OrchestrationV2ProviderFailure; + readonly threadDisposition: "reusable" | "broken"; +} + export interface AcpAdapterV2Flavor { readonly buildAttachmentPrompt?: (input: { readonly text: string; @@ -353,14 +358,13 @@ export interface AcpAdapterV2Flavor { /** * Runs before `session/prompt`. The returned check sees a prompt the agent ended * without an error or cancel, and reports a failure its stop reason hid. A reported - * failure restarts the runtime before the next turn. + * failure restarts the runtime before the next turn. A `broken` thread's native + * history is unusable, so the next turn falls back to a fresh session. */ readonly watchPromptOutcome?: ( sessionId: string, ) => Effect.Effect< - ( - result: EffectAcpSchema.PromptResponse, - ) => Effect.Effect + (result: EffectAcpSchema.PromptResponse) => Effect.Effect >; readonly requiresSignIn?: (cause: unknown) => boolean; /** @@ -8050,10 +8054,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( context: ActiveAcpTurn, status: "completed" | "interrupted" | "failed" | "cancelled", failure?: OrchestrationV2ProviderFailure, - options?: { readonly childTurnsContinue?: boolean }, + options?: { + readonly childTurnsContinue?: boolean; + readonly threadDisposition?: "reusable" | "broken"; + }, ): Effect.fn.Return { if (context.finalized) return; const settledStatus = context.interrupted ? "interrupted" : status; + const threadDisposition = options?.threadDisposition ?? "reusable"; context.finalizedStatus = settledStatus; context.finalized = true; const watchdog = context.inactivityWatchdog; @@ -8152,7 +8160,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const updatedProviderThread: OrchestrationV2ProviderThread = { ...context.input.providerThread, providerSessionId: input.providerSessionId, - status: "active", + status: threadDisposition === "broken" ? "error" : "active", lastRunOrdinal: context.input.runOrdinal, firstRunOrdinal: context.input.providerThread.firstRunOrdinal ?? context.input.runOrdinal, @@ -8196,7 +8204,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( retry: context.providerRetry.retry, retryStartedAt: context.providerRetry.startedAt, }), - threadDisposition: "reusable", + threadDisposition, } : { type: "turn.terminal", @@ -8206,7 +8214,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( runOrdinal: context.input.runOrdinal, status: settledStatus, failure: null, - threadDisposition: "reusable", + threadDisposition, }, ); const subagentsRequiringCarryover = [...context.subagents.values()].filter( @@ -8951,7 +8959,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(runtimeRestartRequired, true); } const failure = - hiddenFailure ?? + hiddenFailure?.failure ?? (context.interrupted ? undefined : stopReasonFailure(result.stopReason, result.error)); @@ -8977,6 +8985,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( // background tools and subagents keep reporting to this run. yield* finalizeTurn(context, "failed", failure, { childTurnsContinue: hasSurvivingBackgroundWork(context), + ...(hiddenFailure === undefined + ? {} + : { threadDisposition: hiddenFailure.threadDisposition }), }); return; } @@ -9259,6 +9270,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( readonly modelSelection?: ModelSelection; readonly runtimePolicy?: ProviderAdapter.ProviderAdapterV2RuntimePolicy; }) { + if (threadInput.providerThread.status === "error") { + // A broken turn left this native history unusable; the caller recovers in a fresh session. + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + driver, + detail: "The native session history is unusable.", + }); + } return yield* runtimeTransitionPermit.withPermit( Effect.gen(function* () { yield* awaitRuntimeTeardown(); From 378584a7606cd0d1c1defddcb322efd77c822a3c Mon Sep 17 00:00:00 2001 From: Bilal Bakr <62337003+Bil0000@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:57:31 +0300 Subject: [PATCH 056/183] feat(web): hovering an issue link shows its preview card (#38294) Co-authored-by: maria-rcks Co-authored-by: shivam <91240327+shivamhwp@users.noreply.github.com> --- .../components/ChatMarkdown.browser.test.tsx | 2 +- apps/web/src/components/ChatMarkdown.tsx | 33 ++++- .../issue/IssueLinkPreview.browser.test.tsx | 74 ++++++++++++ .../src/components/issue/IssueLinkPreview.tsx | 113 ++++++++++++++++++ 4 files changed, 218 insertions(+), 4 deletions(-) create mode 100644 apps/web/src/components/issue/IssueLinkPreview.browser.test.tsx create mode 100644 apps/web/src/components/issue/IssueLinkPreview.tsx diff --git a/apps/web/src/components/ChatMarkdown.browser.test.tsx b/apps/web/src/components/ChatMarkdown.browser.test.tsx index e3ed31ee6902c..a80f2ad5b7217 100644 --- a/apps/web/src/components/ChatMarkdown.browser.test.tsx +++ b/apps/web/src/components/ChatMarkdown.browser.test.tsx @@ -47,7 +47,7 @@ vi.mock(import("../state/server"), async (original) => { const { Atom } = await import("effect/reactivity"); const noConfig = Atom.make(null); const modelsConfig = Atom.make({ - environment: { platform: { os: "darwin" } }, + environment: { platform: { os: "darwin" }, capabilities: {} }, availableEditors: [], settings: { providerInstances: {} }, providers: [ diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index e92ea73ec4f97..c4129edcf96d7 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -188,6 +188,7 @@ import { workspaceLinkLookupQuery, } from "@t3tools/client-runtime/workspace-basename-lookup"; import { resolvePullRequestPreviewTarget } from "@t3tools/client-runtime/change-request-links"; +import { resolveIssueLinkTarget } from "@t3tools/client-runtime/issue-links"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { useOpenChangeRequestLink } from "~/lib/openPullRequestLink"; import { textDirection } from "~/textDirection"; @@ -203,6 +204,7 @@ import { } from "../browser/openFileInPreview"; import { resolveLinkTarget } from "../browser/browserLinkTarget"; import { PullRequestLinkPreview } from "./pullRequest/PullRequestLinkPreview"; +import { IssueLinkPreview, IssueLinkPreviewFallback } from "./issue/IssueLinkPreview"; import { MarkdownCodeBlock, SuspenseShikiCodeBlock } from "./chat/MarkdownCodeBlock"; import { createMarkdownRenderer } from "./chat/markdownRenderer"; import { splitMarkdownBlocks } from "./chat/markdownStreamBlocks"; @@ -444,6 +446,7 @@ type MarkdownServerConfigFields = ReturnType; function markdownServerConfigFields(config: ServerConfig | null) { return { pullRequestsEnabled: config !== null, + issuesEnabled: config?.environment.capabilities.issues === true, isMacOS: config?.environment.platform.os === "darwin", availableEditors: config?.availableEditors ?? NO_MARKDOWN_EDITORS, revealInFileManager: @@ -459,6 +462,7 @@ function markdownServerConfigFieldsEqual( ): boolean { return ( previous.pullRequestsEnabled === next.pullRequestsEnabled && + previous.issuesEnabled === next.issuesEnabled && previous.isMacOS === next.isMacOS && previous.revealInFileManager === next.revealInFileManager && previous.availableEditors.length === next.availableEditors.length && @@ -662,9 +666,8 @@ function useChatMarkdownState({ }, ); }; - const { pullRequestsEnabled, availableEditors, revealInFileManager, isMacOS } = useAtomValue( - markdownServerConfigFieldsAtom(environmentId), - ); + const { pullRequestsEnabled, issuesEnabled, availableEditors, revealInFileManager, isMacOS } = + useAtomValue(markdownServerConfigFieldsAtom(environmentId)); const revealInFileManagerLabel = revealInFileManager === undefined ? undefined @@ -674,6 +677,7 @@ function useChatMarkdownState({ ? revealInFileExplorerLabelForKind(revealInFileManager, messages) : revealInFileExplorerLabelForOs(revealInFileManager, messages); const projects = useProjects(); + const issueProjects = projects.filter((project) => project.environmentId === environmentId); const [preferredEditor] = usePreferredEditor(availableEditors); const preferredEditorMenuLabel = openInEditorMenuLabel(preferredEditor, messages); const openInPreferredEditor = useOpenInPreferredEditor(environmentId, availableEditors, cwd); @@ -1022,10 +1026,12 @@ function useChatMarkdownState({ openExternalLinkInPreview, openMarkdownMedia, projects, + issueProjects, linkedThreadPullRequestFor, resolveThreadPullRequest, resolvedTheme, pullRequestsEnabled, + issuesEnabled, skills, threadRef, updateThreadPullRequestLink, @@ -1191,9 +1197,11 @@ const CHAT_MARKDOWN_COMPONENTS = { linkTargetPreference, openExternalLinkInPreview, projects, + issueProjects, linkedThreadPullRequestFor, resolveThreadPullRequest, pullRequestsEnabled, + issuesEnabled, updateThreadPullRequestLink, fileLinkChip, renderContextReference, @@ -1258,6 +1266,17 @@ const CHAT_MARKDOWN_COMPONENTS = { url: pullRequestCandidateUrl, }) : null; + const issueTarget = + issuesEnabled && environmentId !== null && href + ? resolveIssueLinkTarget({ + url: href, + projects: issueProjects, + }) + : null; + const issuePreviewTarget = + issueTarget === null || environmentId === null + ? null + : { environmentId, input: issueTarget.ref }; const isSameDocumentLink = href?.startsWith("#") ?? false; const onClick = props.onClick; const canOpenInPreview = @@ -1447,9 +1466,17 @@ const CHAT_MARKDOWN_COMPONENTS = { ); if (!opened) await openDeferredMarkdownLink(url); }} + fallback={ + issuePreviewTarget === null ? undefined : ( + + ) + } /> ); } + if (issuePreviewTarget !== null) { + return ; + } return ( diff --git a/apps/web/src/components/issue/IssueLinkPreview.browser.test.tsx b/apps/web/src/components/issue/IssueLinkPreview.browser.test.tsx new file mode 100644 index 0000000000000..ddc8a1f1951f7 --- /dev/null +++ b/apps/web/src/components/issue/IssueLinkPreview.browser.test.tsx @@ -0,0 +1,74 @@ +import { EnvironmentId, IssueTrackerKind, ProjectId } from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; + +const state = vi.hoisted(() => ({ detail: null as unknown, error: null as unknown })); +vi.mock(import("~/state/query"), async (original) => ({ + ...(await original()), + useEnvironmentQuery: ((atom: unknown) => ({ + data: atom === null ? null : state.detail, + dataUpdatedAt: 0, + error: atom === null ? null : state.error, + failure: null, + isPending: false, + isSuccess: state.detail !== null, + refresh: () => undefined, + })) as never, +})); + +import { render } from "../../../test/render"; +import { IssueLinkPreview } from "./IssueLinkPreview"; + +const url = "https://github.com/owner/repo/issues/7"; + +function setup({ detail = null as unknown, error = null as unknown } = {}) { + state.detail = detail; + state.error = error; +} + +function renderPreview() { + return render( + #7} + originalUrl={url} + target={{ + environmentId: EnvironmentId.make("environment"), + input: { + projectId: ProjectId.make("project"), + tracker: IssueTrackerKind.make("github"), + scope: "owner/repo", + key: "7", + }, + }} + />, + ); +} + +it("shows the issue's title, state and author on hover", async () => { + setup({ + detail: { + scope: "owner/repo", + displayKey: "#7", + title: "Hover cards for issues", + state: { category: "closed", name: "Closed", closeReason: "completed" }, + author: { login: "octocat" }, + createdAt: "2026-08-01T00:00:00Z", + }, + }); + await using screen = await renderPreview(); + + await userEvent.hover(screen.getByRole("link")); + + await expect.element(page.getByText("Hover cards for issues")).toBeVisible(); + await expect.element(page.getByText("Closed", { exact: true })).toBeVisible(); + await expect.element(page.getByText("octocat")).toBeVisible(); +}); + +it("falls back to the link's URL when the issue cannot be read", async () => { + setup({ error: new Error("unavailable") }); + await using screen = await renderPreview(); + + await userEvent.hover(screen.getByRole("link")); + + await expect.element(page.getByText(url)).toBeVisible(); +}); diff --git a/apps/web/src/components/issue/IssueLinkPreview.tsx b/apps/web/src/components/issue/IssueLinkPreview.tsx new file mode 100644 index 0000000000000..c4082f19633a2 --- /dev/null +++ b/apps/web/src/components/issue/IssueLinkPreview.tsx @@ -0,0 +1,113 @@ +import type { PreviewCard as PreviewCardPrimitive } from "@base-ui/react/preview-card"; +import type { EnvironmentId, IssueDetail, IssueRef } from "@t3tools/contracts"; +import { T, Var } from "gt-react"; +import { useRef, useState, type ComponentPropsWithoutRef, type ReactElement } from "react"; + +import { RelativeTime } from "~/components/RelativeTime"; +import { issueEnvironment } from "~/state/issues"; +import { useEnvironmentQuery } from "~/state/query"; + +import { PullRequestActorAvatar } from "../pullRequest/pullRequestPresentation"; +import { PreviewCard, PreviewCardPopup, PreviewCardTrigger } from "../ui/preview-card"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { issueStatePresentation } from "./issuePresentation"; + +export interface IssueLinkPreviewTarget { + readonly environmentId: EnvironmentId; + readonly input: IssueRef; +} + +export function IssueLinkPreview({ + link, + originalUrl, + target, +}: { + link: ReactElement>; + originalUrl: string; + target: IssueLinkPreviewTarget; +}) { + const [open, setOpen] = useState(false); + const previewActionsRef = useRef(null); + const detailQuery = useEnvironmentQuery(open ? issueEnvironment.detail(target) : null); + const detail = detailQuery.data; + const showUrlTooltip = open && detailQuery.error !== null && detail === null; + + return ( + + { + if (!nextOpen && detail === null) previewActionsRef.current?.close(); + }} + > + } + delay={350} + closeDelay={120} + /> + {originalUrl} + + {detail === null ? null : ( + +
+ +
+
+ )} +
+ ); +} + +/** A pull request card's fallback when its reference turns out to be an issue. */ +export function IssueLinkPreviewFallback({ + originalUrl, + target, +}: { + originalUrl: string; + target: IssueLinkPreviewTarget; +}) { + const detail = useEnvironmentQuery(issueEnvironment.detail(target)).data; + return detail === null ? ( +

{originalUrl}

+ ) : ( + + ); +} + +function IssuePreviewCardBody({ detail }: { detail: IssueDetail }) { + const state = issueStatePresentation(detail.state); + const createdAt = ; + const author = detail.author; + const authorLabel = + author === null + ? "ghost" + : author.name && author.name !== author.login + ? `${author.name} (@${author.login})` + : author.login; + return ( +
+
+ {detail.scope} + {detail.displayKey} + · + + + {state.label} + +
+

+ {detail.title} +

+
+ + {authorLabel} + · + + + opened {createdAt} + + +
+
+ ); +} From 39ad0c58ec3f38e89d595487c97cbf3de0e4d6fd Mon Sep 17 00:00:00 2001 From: Bilal Bakr <62337003+Bil0000@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:07:08 +0300 Subject: [PATCH 057/183] fix(agents): link tracked issues to their threads (#38356) Co-authored-by: maria-rcks --- .../multi_turn/muse_transcript.ndjson | 12 ++--- .../muse_permission/muse_transcript.ndjson | 12 ++--- .../muse_transcript.ndjson | 6 +-- .../muse_transcript.ndjson | 6 +-- .../muse_workflow/muse_transcript.ndjson | 6 +-- .../fixtures/simple/muse_transcript.ndjson | 6 +-- .../subagent_v2/muse_transcript.ndjson | 6 +-- .../turn_interrupt/muse_transcript.ndjson | 6 +-- .../src/provider/agentContextBudget.json | 4 +- evals/mcp-tool-use/README.md | 2 +- evals/mcp-tool-use/cases/issues.ndjson | 2 + evals/mcp-tool-use/run.test.ts | 49 +++++++++++++++++++ evals/mcp-tool-use/run.ts | 27 ++++++++-- .../src/server/runtimeInstructions.test.ts | 1 + .../src/server/runtimeInstructions.ts | 1 + 15 files changed, 108 insertions(+), 38 deletions(-) create mode 100644 evals/mcp-tool-use/cases/issues.ndjson diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/muse_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/muse_transcript.ndjson index 7cbdf94598d01..85c228e5e0a0c 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/muse_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/muse_transcript.ndjson @@ -7,13 +7,13 @@ {"type":"emit_inbound","label":"session/started","frame":{"jsonrpc":"2.0","method":"session/started","params":{"session":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","path":"~/.local/share/muse/sessions/2026/10/08/01a11a6b-707e-7000-9bb5-4079c7772ad0/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-08T07:30:11.238412Z","updatedAt":"2026-10-08T07:30:11.238416Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"approvalMode":{"mode":"allowAll","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"}},"emittedAtMs":1791444611408}} {"type":"emit_inbound","label":"response:session/start","frame":{"jsonrpc":"2.0","id":2,"result":{"session":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","path":"~/.local/share/muse/sessions/2026/10/08/01a11a6b-707e-7000-9bb5-4079c7772ad0/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-08T07:30:11.238412Z","updatedAt":"2026-10-08T07:30:11.238416Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"approvalMode":{"mode":"allowAll","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"},"viewCursor":"v:01a11a6b-707e-7000-9bb5-4079c7772ad0:1"}}} {"type":"emit_inbound","label":"session/approvalModeChanged","frame":{"jsonrpc":"2.0","method":"session/approvalModeChanged","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","viewCursor":"v:01a11a6b-707e-7000-9bb5-4079c7772ad0:1","sourceRange":{"stream":{"kind":"session","id":"01a11a6b-707e-7000-9bb5-4079c7772ad0"},"first":{"id":"37b19bd1-b212-4532-a0c9-a6677f303e26","sequence":5},"last":{"id":"37b19bd1-b212-4532-a0c9-a6677f303e26","sequence":5}},"mode":"allowAll","source":"approvalReconfigure","commandId":"01a11a6b-707e-7001-b2f4-23db74e60097","clientName":"t3_code"},"emittedAtMs":1791444611412}} -{"type":"expect_outbound","label":"turn/start","frame":{"jsonrpc":"2.0","id":3,"method":"turn/start","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","input":[{"type":"text","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\n"},{"type":"text","text":"Respond with exactly: first fixture turn complete"}],"displayText":"Respond with exactly: first fixture turn complete","workspaceRoots":[""],"ifBusy":"queue","reasoningEffort":"high","commandId":"01a11a6b-722c-7000-a73a-1d49a3a7f4c4"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"jsonrpc":"2.0","id":3,"method":"turn/start","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","input":[{"type":"text","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\n"},{"type":"text","text":"Respond with exactly: first fixture turn complete"}],"displayText":"Respond with exactly: first fixture turn complete","workspaceRoots":[""],"ifBusy":"queue","reasoningEffort":"high","commandId":"01a11a6b-722c-7000-a73a-1d49a3a7f4c4"}}} {"type":"emit_inbound","label":"session/branchChanged","frame":{"jsonrpc":"2.0","method":"session/branchChanged","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","viewCursor":"v:01a11a6b-707e-7000-9bb5-4079c7772ad0:2","sourceRange":{"stream":{"kind":"session","id":"01a11a6b-707e-7000-9bb5-4079c7772ad0"},"first":{"id":"2c530748-943b-4467-8473-da8b04c511c3","sequence":16},"last":{"id":"2c530748-943b-4467-8473-da8b04c511c3","sequence":16}},"workspaceRoot":"","branch":"main","vcs":"git"},"emittedAtMs":1791444611661}} {"type":"emit_inbound","label":"response:turn/start","frame":{"jsonrpc":"2.0","id":3,"result":{"commandId":"01a11a6b-722c-7000-a73a-1d49a3a7f4c4","status":"accepted","turnId":"01a11a6b-722c-7000-a73a-1d49a3a7f4c4","startedNewTurn":true,"disposition":"started"}}} {"type":"emit_inbound","label":"session/statusChanged","frame":{"jsonrpc":"2.0","method":"session/statusChanged","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","status":"running","viewCursor":"v:01a11a6b-707e-7000-9bb5-4079c7772ad0:3"},"emittedAtMs":1791444611674}} {"type":"emit_inbound","label":"turn/started","frame":{"jsonrpc":"2.0","method":"turn/started","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","viewCursor":"v:01a11a6b-707e-7000-9bb5-4079c7772ad0:3","sourceRange":{"stream":{"kind":"session","id":"01a11a6b-707e-7000-9bb5-4079c7772ad0"},"first":{"id":"2be0c9b5-9dc4-48f0-9b86-06aef4de31f3","sequence":18},"last":{"id":"2be0c9b5-9dc4-48f0-9b86-06aef4de31f3","sequence":18}},"turnId":"01a11a6b-722c-7000-a73a-1d49a3a7f4c4","commandId":"01a11a6b-722c-7000-a73a-1d49a3a7f4c4"},"emittedAtMs":1791444611675}} -{"type":"emit_inbound","label":"item/completed","frame":{"jsonrpc":"2.0","method":"item/completed","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","viewCursor":"v:01a11a6b-707e-7000-9bb5-4079c7772ad0:4","sourceRange":{"stream":{"kind":"session","id":"01a11a6b-707e-7000-9bb5-4079c7772ad0"},"first":{"id":"2be0c9b5-9dc4-48f0-9b86-06aef4de31f3","sequence":18},"last":{"id":"2be0c9b5-9dc4-48f0-9b86-06aef4de31f3","sequence":18}},"item":{"itemId":"1b470279-ee8c-4c74-a298-f37184145584","kind":"userMessage","turnId":"01a11a6b-722c-7000-a73a-1d49a3a7f4c4","revision":1,"status":"completed","recordedAt":"2026-10-08T07:30:11.66263Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nRespond with exactly: first fixture turn complete","commandId":"01a11a6b-722c-7000-a73a-1d49a3a7f4c4"}},"emittedAtMs":1791444611675}} -{"type":"emit_inbound","label":"item/updated","frame":{"jsonrpc":"2.0","method":"item/updated","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","viewCursor":"v:01a11a6b-707e-7000-9bb5-4079c7772ad0:5","sourceRange":{"stream":{"kind":"session","id":"01a11a6b-707e-7000-9bb5-4079c7772ad0"},"first":{"id":"31b500d6-40fc-4f4c-b097-6b7be8d77cee","sequence":20},"last":{"id":"31b500d6-40fc-4f4c-b097-6b7be8d77cee","sequence":20}},"item":{"itemId":"1b470279-ee8c-4c74-a298-f37184145584","kind":"userMessage","turnId":"01a11a6b-722c-7000-a73a-1d49a3a7f4c4","revision":2,"status":"completed","recordedAt":"2026-10-08T07:30:11.680942Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nRespond with exactly: first fixture turn complete","displayText":"Respond with exactly: first fixture turn complete","commandId":"01a11a6b-722c-7000-a73a-1d49a3a7f4c4"}},"emittedAtMs":1791444611689}} +{"type":"emit_inbound","label":"item/completed","frame":{"jsonrpc":"2.0","method":"item/completed","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","viewCursor":"v:01a11a6b-707e-7000-9bb5-4079c7772ad0:4","sourceRange":{"stream":{"kind":"session","id":"01a11a6b-707e-7000-9bb5-4079c7772ad0"},"first":{"id":"2be0c9b5-9dc4-48f0-9b86-06aef4de31f3","sequence":18},"last":{"id":"2be0c9b5-9dc4-48f0-9b86-06aef4de31f3","sequence":18}},"item":{"itemId":"1b470279-ee8c-4c74-a298-f37184145584","kind":"userMessage","turnId":"01a11a6b-722c-7000-a73a-1d49a3a7f4c4","revision":1,"status":"completed","recordedAt":"2026-10-08T07:30:11.66263Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\nRespond with exactly: first fixture turn complete","commandId":"01a11a6b-722c-7000-a73a-1d49a3a7f4c4"}},"emittedAtMs":1791444611675}} +{"type":"emit_inbound","label":"item/updated","frame":{"jsonrpc":"2.0","method":"item/updated","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","viewCursor":"v:01a11a6b-707e-7000-9bb5-4079c7772ad0:5","sourceRange":{"stream":{"kind":"session","id":"01a11a6b-707e-7000-9bb5-4079c7772ad0"},"first":{"id":"31b500d6-40fc-4f4c-b097-6b7be8d77cee","sequence":20},"last":{"id":"31b500d6-40fc-4f4c-b097-6b7be8d77cee","sequence":20}},"item":{"itemId":"1b470279-ee8c-4c74-a298-f37184145584","kind":"userMessage","turnId":"01a11a6b-722c-7000-a73a-1d49a3a7f4c4","revision":2,"status":"completed","recordedAt":"2026-10-08T07:30:11.680942Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\nRespond with exactly: first fixture turn complete","displayText":"Respond with exactly: first fixture turn complete","commandId":"01a11a6b-722c-7000-a73a-1d49a3a7f4c4"}},"emittedAtMs":1791444611689}} {"type":"emit_inbound","label":"item/started","frame":{"jsonrpc":"2.0","method":"item/started","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","viewCursor":"v:01a11a6b-707e-7000-9bb5-4079c7772ad0:6","sourceRange":{"stream":{"kind":"session","id":"01a11a6b-707e-7000-9bb5-4079c7772ad0"},"first":{"id":"077780ea-0dc9-4d7a-879c-ee368f3adbe0","sequence":37},"last":{"id":"077780ea-0dc9-4d7a-879c-ee368f3adbe0","sequence":37}},"item":{"itemId":"077780ea-0dc9-4d7a-879c-ee368f3adbe0","kind":"reminderChild","turnId":"01a11a6b-722c-7000-a73a-1d49a3a7f4c4","revision":1,"status":"inProgress","recordedAt":"2026-10-08T07:30:11.790301Z","fallbackText":"Reminder child session","childSessionId":"c13379db-6761-40b4-a974-b0f1a58717aa","reminderAgentId":"skill-reminder","generationId":1,"taskId":"01a11a6b-72ac-7972-a1df-b343b7804b38"}},"emittedAtMs":1791444611795}} {"type":"emit_inbound","label":"item/started","frame":{"jsonrpc":"2.0","method":"item/started","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","viewCursor":"v:01a11a6b-707e-7000-9bb5-4079c7772ad0:6.1","item":{"itemId":"f99b90e1-9d8b-4bf2-8e7a-e240e1cf9321","kind":"agentMessage","turnId":"01a11a6b-722c-7000-a73a-1d49a3a7f4c4","revision":1,"status":"inProgress","text":""}},"emittedAtMs":1791444618068}} {"type":"emit_inbound","label":"item/delta","frame":{"jsonrpc":"2.0","method":"item/delta","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","viewCursor":"v:01a11a6b-707e-7000-9bb5-4079c7772ad0:6.2","itemId":"f99b90e1-9d8b-4bf2-8e7a-e240e1cf9321","field":"text","delta":"first fixture turn complete"},"emittedAtMs":1791444618068}} @@ -29,12 +29,12 @@ {"type":"emit_inbound","label":"session/statusChanged","frame":{"jsonrpc":"2.0","method":"session/statusChanged","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","status":"idle","viewCursor":"v:01a11a6b-707e-7000-9bb5-4079c7772ad0:16"},"emittedAtMs":1791444621046}} {"type":"emit_inbound","label":"turn/completed","frame":{"jsonrpc":"2.0","method":"turn/completed","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","viewCursor":"v:01a11a6b-707e-7000-9bb5-4079c7772ad0:16","sourceRange":{"stream":{"kind":"session","id":"01a11a6b-707e-7000-9bb5-4079c7772ad0"},"first":{"id":"688a69c5-e353-4db9-bd8c-1beb033902ba","sequence":79},"last":{"id":"688a69c5-e353-4db9-bd8c-1beb033902ba","sequence":79}},"turnId":"01a11a6b-722c-7000-a73a-1d49a3a7f4c4","terminal":"completed","durationMs":9378,"timeToFirstTokenMs":6406},"emittedAtMs":1791444621047}} {"type":"emit_inbound","label":"session/branchChanged","frame":{"jsonrpc":"2.0","method":"session/branchChanged","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","viewCursor":"v:01a11a6b-707e-7000-9bb5-4079c7772ad0:17","sourceRange":{"stream":{"kind":"session","id":"01a11a6b-707e-7000-9bb5-4079c7772ad0"},"first":{"id":"36753b8a-26ce-4935-8127-bc9191cb328b","sequence":80},"last":{"id":"36753b8a-26ce-4935-8127-bc9191cb328b","sequence":80}},"workspaceRoot":"","branch":"main","vcs":"git"},"emittedAtMs":1791444621054}} -{"type":"expect_outbound","label":"turn/start","frame":{"jsonrpc":"2.0","id":4,"method":"turn/start","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","input":[{"type":"text","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\n"},{"type":"text","text":"Respond with exactly: second fixture turn complete"}],"displayText":"Respond with exactly: second fixture turn complete","workspaceRoots":[""],"ifBusy":"queue","reasoningEffort":"high","commandId":"01a11a6b-97ec-7000-bd1b-d7afbea11045"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"jsonrpc":"2.0","id":4,"method":"turn/start","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","input":[{"type":"text","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\n"},{"type":"text","text":"Respond with exactly: second fixture turn complete"}],"displayText":"Respond with exactly: second fixture turn complete","workspaceRoots":[""],"ifBusy":"queue","reasoningEffort":"high","commandId":"01a11a6b-97ec-7000-bd1b-d7afbea11045"}}} {"type":"emit_inbound","label":"response:turn/start","frame":{"jsonrpc":"2.0","id":4,"result":{"commandId":"01a11a6b-97ec-7000-bd1b-d7afbea11045","status":"accepted","turnId":"01a11a6b-97ec-7000-bd1b-d7afbea11045","startedNewTurn":true,"disposition":"started"}}} {"type":"emit_inbound","label":"session/statusChanged","frame":{"jsonrpc":"2.0","method":"session/statusChanged","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","status":"running","viewCursor":"v:01a11a6b-707e-7000-9bb5-4079c7772ad0:18"},"emittedAtMs":1791444621333}} {"type":"emit_inbound","label":"turn/started","frame":{"jsonrpc":"2.0","method":"turn/started","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","viewCursor":"v:01a11a6b-707e-7000-9bb5-4079c7772ad0:18","sourceRange":{"stream":{"kind":"session","id":"01a11a6b-707e-7000-9bb5-4079c7772ad0"},"first":{"id":"4aba96d5-f984-4bc0-bda4-7fb97f527686","sequence":87},"last":{"id":"4aba96d5-f984-4bc0-bda4-7fb97f527686","sequence":87}},"turnId":"01a11a6b-97ec-7000-bd1b-d7afbea11045","commandId":"01a11a6b-97ec-7000-bd1b-d7afbea11045"},"emittedAtMs":1791444621334}} -{"type":"emit_inbound","label":"item/completed","frame":{"jsonrpc":"2.0","method":"item/completed","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","viewCursor":"v:01a11a6b-707e-7000-9bb5-4079c7772ad0:19","sourceRange":{"stream":{"kind":"session","id":"01a11a6b-707e-7000-9bb5-4079c7772ad0"},"first":{"id":"4aba96d5-f984-4bc0-bda4-7fb97f527686","sequence":87},"last":{"id":"4aba96d5-f984-4bc0-bda4-7fb97f527686","sequence":87}},"item":{"itemId":"90719a5d-d2c1-46dc-ad4d-274adda02344","kind":"userMessage","turnId":"01a11a6b-97ec-7000-bd1b-d7afbea11045","revision":1,"status":"completed","recordedAt":"2026-10-08T07:30:21.321391Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nRespond with exactly: second fixture turn complete","commandId":"01a11a6b-97ec-7000-bd1b-d7afbea11045"}},"emittedAtMs":1791444621334}} -{"type":"emit_inbound","label":"item/updated","frame":{"jsonrpc":"2.0","method":"item/updated","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","viewCursor":"v:01a11a6b-707e-7000-9bb5-4079c7772ad0:20","sourceRange":{"stream":{"kind":"session","id":"01a11a6b-707e-7000-9bb5-4079c7772ad0"},"first":{"id":"dc502e2c-d81c-4f0e-ad86-dd11d1368677","sequence":89},"last":{"id":"dc502e2c-d81c-4f0e-ad86-dd11d1368677","sequence":89}},"item":{"itemId":"90719a5d-d2c1-46dc-ad4d-274adda02344","kind":"userMessage","turnId":"01a11a6b-97ec-7000-bd1b-d7afbea11045","revision":2,"status":"completed","recordedAt":"2026-10-08T07:30:21.338944Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nRespond with exactly: second fixture turn complete","displayText":"Respond with exactly: second fixture turn complete","commandId":"01a11a6b-97ec-7000-bd1b-d7afbea11045"}},"emittedAtMs":1791444621347}} +{"type":"emit_inbound","label":"item/completed","frame":{"jsonrpc":"2.0","method":"item/completed","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","viewCursor":"v:01a11a6b-707e-7000-9bb5-4079c7772ad0:19","sourceRange":{"stream":{"kind":"session","id":"01a11a6b-707e-7000-9bb5-4079c7772ad0"},"first":{"id":"4aba96d5-f984-4bc0-bda4-7fb97f527686","sequence":87},"last":{"id":"4aba96d5-f984-4bc0-bda4-7fb97f527686","sequence":87}},"item":{"itemId":"90719a5d-d2c1-46dc-ad4d-274adda02344","kind":"userMessage","turnId":"01a11a6b-97ec-7000-bd1b-d7afbea11045","revision":1,"status":"completed","recordedAt":"2026-10-08T07:30:21.321391Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\nRespond with exactly: second fixture turn complete","commandId":"01a11a6b-97ec-7000-bd1b-d7afbea11045"}},"emittedAtMs":1791444621334}} +{"type":"emit_inbound","label":"item/updated","frame":{"jsonrpc":"2.0","method":"item/updated","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","viewCursor":"v:01a11a6b-707e-7000-9bb5-4079c7772ad0:20","sourceRange":{"stream":{"kind":"session","id":"01a11a6b-707e-7000-9bb5-4079c7772ad0"},"first":{"id":"dc502e2c-d81c-4f0e-ad86-dd11d1368677","sequence":89},"last":{"id":"dc502e2c-d81c-4f0e-ad86-dd11d1368677","sequence":89}},"item":{"itemId":"90719a5d-d2c1-46dc-ad4d-274adda02344","kind":"userMessage","turnId":"01a11a6b-97ec-7000-bd1b-d7afbea11045","revision":2,"status":"completed","recordedAt":"2026-10-08T07:30:21.338944Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\nRespond with exactly: second fixture turn complete","displayText":"Respond with exactly: second fixture turn complete","commandId":"01a11a6b-97ec-7000-bd1b-d7afbea11045"}},"emittedAtMs":1791444621347}} {"type":"emit_inbound","label":"item/started","frame":{"jsonrpc":"2.0","method":"item/started","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","viewCursor":"v:01a11a6b-707e-7000-9bb5-4079c7772ad0:21","sourceRange":{"stream":{"kind":"session","id":"01a11a6b-707e-7000-9bb5-4079c7772ad0"},"first":{"id":"09cb4c2a-03c2-4089-ba12-8d5d31f7ea48","sequence":106},"last":{"id":"09cb4c2a-03c2-4089-ba12-8d5d31f7ea48","sequence":106}},"item":{"itemId":"09cb4c2a-03c2-4089-ba12-8d5d31f7ea48","kind":"reminderChild","turnId":"01a11a6b-97ec-7000-bd1b-d7afbea11045","revision":1,"status":"inProgress","recordedAt":"2026-10-08T07:30:21.446966Z","fallbackText":"Reminder child session","childSessionId":"cd97261a-3ea9-480f-9e54-5e59bb077da2","reminderAgentId":"skill-reminder","generationId":1,"taskId":"01a11a6b-9869-7061-a4f3-42daa3e3a8f1"}},"emittedAtMs":1791444621455}} {"type":"emit_inbound","label":"item/started","frame":{"jsonrpc":"2.0","method":"item/started","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","viewCursor":"v:01a11a6b-707e-7000-9bb5-4079c7772ad0:21.1","item":{"itemId":"2de26c0d-26b4-4533-8810-918ee44fcd82","kind":"agentMessage","turnId":"01a11a6b-97ec-7000-bd1b-d7afbea11045","revision":1,"status":"inProgress","text":""}},"emittedAtMs":1791444623127}} {"type":"emit_inbound","label":"item/delta","frame":{"jsonrpc":"2.0","method":"item/delta","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","viewCursor":"v:01a11a6b-707e-7000-9bb5-4079c7772ad0:21.2","itemId":"2de26c0d-26b4-4533-8810-918ee44fcd82","field":"text","delta":"second fixture turn complete"},"emittedAtMs":1791444623127}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/muse_permission/muse_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/muse_permission/muse_transcript.ndjson index e2861e91dbf31..157e5b91a07a4 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/muse_permission/muse_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/muse_permission/muse_transcript.ndjson @@ -7,13 +7,13 @@ {"type":"emit_inbound","label":"session/started","frame":{"jsonrpc":"2.0","method":"session/started","params":{"session":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","path":"~/.local/share/muse/sessions/2026/10/08/01a11a6d-39bb-7000-8c93-4594c98e6a11/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-08T07:32:08.30084Z","updatedAt":"2026-10-08T07:32:08.300844Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"approvalMode":{"mode":"promptUnmatched","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"}},"emittedAtMs":1791444728496}} {"type":"emit_inbound","label":"response:session/start","frame":{"jsonrpc":"2.0","id":2,"result":{"session":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","path":"~/.local/share/muse/sessions/2026/10/08/01a11a6d-39bb-7000-8c93-4594c98e6a11/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-08T07:32:08.30084Z","updatedAt":"2026-10-08T07:32:08.300844Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"approvalMode":{"mode":"promptUnmatched","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"},"viewCursor":"v:01a11a6d-39bb-7000-8c93-4594c98e6a11:1"}}} {"type":"emit_inbound","label":"session/approvalModeChanged","frame":{"jsonrpc":"2.0","method":"session/approvalModeChanged","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","viewCursor":"v:01a11a6d-39bb-7000-8c93-4594c98e6a11:1","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-39bb-7000-8c93-4594c98e6a11"},"first":{"id":"b05fb8ec-7b58-4cf7-a369-379938395230","sequence":5},"last":{"id":"b05fb8ec-7b58-4cf7-a369-379938395230","sequence":5}},"mode":"promptUnmatched","source":"approvalReconfigure","commandId":"01a11a6d-39bb-7001-923e-425cc6129ce7","clientName":"t3_code"},"emittedAtMs":1791444728501}} -{"type":"expect_outbound","label":"turn/start","frame":{"jsonrpc":"2.0","id":3,"method":"turn/start","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","input":[{"type":"text","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\n"},{"type":"text","text":"Run the shell command `touch muse-approved.txt` with your shell tool, then reply DONE."}],"displayText":"Run the shell command `touch muse-approved.txt` with your shell tool, then reply DONE.","workspaceRoots":[""],"ifBusy":"queue","reasoningEffort":"high","commandId":"01a11a6d-3b9f-7000-b6ad-ab05e6b973b6"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"jsonrpc":"2.0","id":3,"method":"turn/start","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","input":[{"type":"text","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\n"},{"type":"text","text":"Run the shell command `touch muse-approved.txt` with your shell tool, then reply DONE."}],"displayText":"Run the shell command `touch muse-approved.txt` with your shell tool, then reply DONE.","workspaceRoots":[""],"ifBusy":"queue","reasoningEffort":"high","commandId":"01a11a6d-3b9f-7000-b6ad-ab05e6b973b6"}}} {"type":"emit_inbound","label":"session/branchChanged","frame":{"jsonrpc":"2.0","method":"session/branchChanged","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","viewCursor":"v:01a11a6d-39bb-7000-8c93-4594c98e6a11:2","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-39bb-7000-8c93-4594c98e6a11"},"first":{"id":"6159e84a-ae1e-4fae-ae8b-49f41ca34509","sequence":16},"last":{"id":"6159e84a-ae1e-4fae-ae8b-49f41ca34509","sequence":16}},"workspaceRoot":"","branch":"main","vcs":"git"},"emittedAtMs":1791444728769}} {"type":"emit_inbound","label":"response:turn/start","frame":{"jsonrpc":"2.0","id":3,"result":{"commandId":"01a11a6d-3b9f-7000-b6ad-ab05e6b973b6","status":"accepted","turnId":"01a11a6d-3b9f-7000-b6ad-ab05e6b973b6","startedNewTurn":true,"disposition":"started"}}} {"type":"emit_inbound","label":"session/statusChanged","frame":{"jsonrpc":"2.0","method":"session/statusChanged","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","status":"running","viewCursor":"v:01a11a6d-39bb-7000-8c93-4594c98e6a11:3"},"emittedAtMs":1791444728783}} {"type":"emit_inbound","label":"turn/started","frame":{"jsonrpc":"2.0","method":"turn/started","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","viewCursor":"v:01a11a6d-39bb-7000-8c93-4594c98e6a11:3","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-39bb-7000-8c93-4594c98e6a11"},"first":{"id":"09218c3a-88fd-4bc8-ab45-d1aa69bea95a","sequence":18},"last":{"id":"09218c3a-88fd-4bc8-ab45-d1aa69bea95a","sequence":18}},"turnId":"01a11a6d-3b9f-7000-b6ad-ab05e6b973b6","commandId":"01a11a6d-3b9f-7000-b6ad-ab05e6b973b6"},"emittedAtMs":1791444728783}} -{"type":"emit_inbound","label":"item/completed","frame":{"jsonrpc":"2.0","method":"item/completed","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","viewCursor":"v:01a11a6d-39bb-7000-8c93-4594c98e6a11:4","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-39bb-7000-8c93-4594c98e6a11"},"first":{"id":"09218c3a-88fd-4bc8-ab45-d1aa69bea95a","sequence":18},"last":{"id":"09218c3a-88fd-4bc8-ab45-d1aa69bea95a","sequence":18}},"item":{"itemId":"dde9573b-650f-434b-ab99-60cfc820a0a5","kind":"userMessage","turnId":"01a11a6d-3b9f-7000-b6ad-ab05e6b973b6","revision":1,"status":"completed","recordedAt":"2026-10-08T07:32:08.769894Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nRun the shell command `touch muse-approved.txt` with your shell tool, then reply DONE.","commandId":"01a11a6d-3b9f-7000-b6ad-ab05e6b973b6"}},"emittedAtMs":1791444728784}} -{"type":"emit_inbound","label":"item/updated","frame":{"jsonrpc":"2.0","method":"item/updated","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","viewCursor":"v:01a11a6d-39bb-7000-8c93-4594c98e6a11:5","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-39bb-7000-8c93-4594c98e6a11"},"first":{"id":"76c57706-1378-4167-8bbf-f76d959804e8","sequence":20},"last":{"id":"76c57706-1378-4167-8bbf-f76d959804e8","sequence":20}},"item":{"itemId":"dde9573b-650f-434b-ab99-60cfc820a0a5","kind":"userMessage","turnId":"01a11a6d-3b9f-7000-b6ad-ab05e6b973b6","revision":2,"status":"completed","recordedAt":"2026-10-08T07:32:08.791728Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nRun the shell command `touch muse-approved.txt` with your shell tool, then reply DONE.","displayText":"Run the shell command `touch muse-approved.txt` with your shell tool, then reply DONE.","commandId":"01a11a6d-3b9f-7000-b6ad-ab05e6b973b6"}},"emittedAtMs":1791444728800}} +{"type":"emit_inbound","label":"item/completed","frame":{"jsonrpc":"2.0","method":"item/completed","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","viewCursor":"v:01a11a6d-39bb-7000-8c93-4594c98e6a11:4","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-39bb-7000-8c93-4594c98e6a11"},"first":{"id":"09218c3a-88fd-4bc8-ab45-d1aa69bea95a","sequence":18},"last":{"id":"09218c3a-88fd-4bc8-ab45-d1aa69bea95a","sequence":18}},"item":{"itemId":"dde9573b-650f-434b-ab99-60cfc820a0a5","kind":"userMessage","turnId":"01a11a6d-3b9f-7000-b6ad-ab05e6b973b6","revision":1,"status":"completed","recordedAt":"2026-10-08T07:32:08.769894Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\nRun the shell command `touch muse-approved.txt` with your shell tool, then reply DONE.","commandId":"01a11a6d-3b9f-7000-b6ad-ab05e6b973b6"}},"emittedAtMs":1791444728784}} +{"type":"emit_inbound","label":"item/updated","frame":{"jsonrpc":"2.0","method":"item/updated","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","viewCursor":"v:01a11a6d-39bb-7000-8c93-4594c98e6a11:5","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-39bb-7000-8c93-4594c98e6a11"},"first":{"id":"76c57706-1378-4167-8bbf-f76d959804e8","sequence":20},"last":{"id":"76c57706-1378-4167-8bbf-f76d959804e8","sequence":20}},"item":{"itemId":"dde9573b-650f-434b-ab99-60cfc820a0a5","kind":"userMessage","turnId":"01a11a6d-3b9f-7000-b6ad-ab05e6b973b6","revision":2,"status":"completed","recordedAt":"2026-10-08T07:32:08.791728Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\nRun the shell command `touch muse-approved.txt` with your shell tool, then reply DONE.","displayText":"Run the shell command `touch muse-approved.txt` with your shell tool, then reply DONE.","commandId":"01a11a6d-3b9f-7000-b6ad-ab05e6b973b6"}},"emittedAtMs":1791444728800}} {"type":"emit_inbound","label":"item/started","frame":{"jsonrpc":"2.0","method":"item/started","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","viewCursor":"v:01a11a6d-39bb-7000-8c93-4594c98e6a11:6","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-39bb-7000-8c93-4594c98e6a11"},"first":{"id":"29180105-84c4-4f9e-8bfd-003392b93b73","sequence":38},"last":{"id":"29180105-84c4-4f9e-8bfd-003392b93b73","sequence":38}},"item":{"itemId":"29180105-84c4-4f9e-8bfd-003392b93b73","kind":"reminderChild","turnId":"01a11a6d-3b9f-7000-b6ad-ab05e6b973b6","revision":1,"status":"inProgress","recordedAt":"2026-10-08T07:32:08.905989Z","fallbackText":"Reminder child session","childSessionId":"7c9485f9-26aa-4b56-8ca2-f36cb9cfb8c4","reminderAgentId":"skill-reminder","generationId":1,"taskId":"01a11a6d-3c27-73f2-8c27-cd06a3b7dadf"}},"emittedAtMs":1791444728910}} {"type":"emit_inbound","label":"session/tokenUsage","frame":{"jsonrpc":"2.0","method":"session/tokenUsage","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","viewCursor":"v:01a11a6d-39bb-7000-8c93-4594c98e6a11:7","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-39bb-7000-8c93-4594c98e6a11"},"first":{"id":"b1dab1f5-3c9e-4d92-b955-841a2269c23c","sequence":54},"last":{"id":"b1dab1f5-3c9e-4d92-b955-841a2269c23c","sequence":54}},"turnId":"01a11a6d-3b9f-7000-b6ad-ab05e6b973b6","modelId":"muse-spark-1.3-contributor","usage":{"inputTokens":32618,"outputTokens":315,"cachedTokens":0,"cacheWriteTokens":0,"cacheReadTokens":0,"reasoningTokens":227},"promptTokens":32618,"totalTokens":32933,"finishReason":"tool_calls","durationMs":2684,"cumulative":{"promptTokens":32618,"outputTokens":315,"totalTokens":32933,"cost":{"usd":0.0033248,"partial":false}}},"emittedAtMs":1791444731684}} {"type":"emit_inbound","label":"session/contextUsage","frame":{"jsonrpc":"2.0","method":"session/contextUsage","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","viewCursor":"v:01a11a6d-39bb-7000-8c93-4594c98e6a11:8","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-39bb-7000-8c93-4594c98e6a11"},"first":{"id":"b1dab1f5-3c9e-4d92-b955-841a2269c23c","sequence":54},"last":{"id":"b1dab1f5-3c9e-4d92-b955-841a2269c23c","sequence":54}},"windowTokens":1007997,"usedTokens":32933,"pressure":"normal"},"emittedAtMs":1791444731684}} @@ -42,12 +42,12 @@ {"type":"emit_inbound","label":"session/statusChanged","frame":{"jsonrpc":"2.0","method":"session/statusChanged","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","status":"idle","viewCursor":"v:01a11a6d-39bb-7000-8c93-4594c98e6a11:23"},"emittedAtMs":1791444747386}} {"type":"emit_inbound","label":"turn/completed","frame":{"jsonrpc":"2.0","method":"turn/completed","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","viewCursor":"v:01a11a6d-39bb-7000-8c93-4594c98e6a11:23","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-39bb-7000-8c93-4594c98e6a11"},"first":{"id":"7c29ac76-7e09-48c1-a18f-f336126e27d1","sequence":120},"last":{"id":"7c29ac76-7e09-48c1-a18f-f336126e27d1","sequence":120}},"turnId":"01a11a6d-3b9f-7000-b6ad-ab05e6b973b6","terminal":"completed","durationMs":18608,"timeToFirstTokenMs":4791},"emittedAtMs":1791444747387}} {"type":"emit_inbound","label":"session/branchChanged","frame":{"jsonrpc":"2.0","method":"session/branchChanged","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","viewCursor":"v:01a11a6d-39bb-7000-8c93-4594c98e6a11:24","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-39bb-7000-8c93-4594c98e6a11"},"first":{"id":"1e4afe30-d924-444c-8665-5e763f524e70","sequence":121},"last":{"id":"1e4afe30-d924-444c-8665-5e763f524e70","sequence":121}},"workspaceRoot":"","branch":"main","vcs":"git"},"emittedAtMs":1791444747394}} -{"type":"expect_outbound","label":"turn/start","frame":{"jsonrpc":"2.0","id":5,"method":"turn/start","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","input":[{"type":"text","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\n"},{"type":"text","text":"Run the shell command `touch muse-declined.txt` with your shell tool once. If it is rejected, do not retry; reply REJECTED."}],"displayText":"Run the shell command `touch muse-declined.txt` with your shell tool once. If it is rejected, do not retry; reply REJECTED.","workspaceRoots":[""],"ifBusy":"queue","reasoningEffort":"high","commandId":"01a11a6d-8566-7000-8ad1-6269ac187a29"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"jsonrpc":"2.0","id":5,"method":"turn/start","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","input":[{"type":"text","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\n"},{"type":"text","text":"Run the shell command `touch muse-declined.txt` with your shell tool once. If it is rejected, do not retry; reply REJECTED."}],"displayText":"Run the shell command `touch muse-declined.txt` with your shell tool once. If it is rejected, do not retry; reply REJECTED.","workspaceRoots":[""],"ifBusy":"queue","reasoningEffort":"high","commandId":"01a11a6d-8566-7000-8ad1-6269ac187a29"}}} {"type":"emit_inbound","label":"response:turn/start","frame":{"jsonrpc":"2.0","id":5,"result":{"commandId":"01a11a6d-8566-7000-8ad1-6269ac187a29","status":"accepted","turnId":"01a11a6d-8566-7000-8ad1-6269ac187a29","startedNewTurn":true,"disposition":"started"}}} {"type":"emit_inbound","label":"session/statusChanged","frame":{"jsonrpc":"2.0","method":"session/statusChanged","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","status":"running","viewCursor":"v:01a11a6d-39bb-7000-8c93-4594c98e6a11:25"},"emittedAtMs":1791444747660}} {"type":"emit_inbound","label":"turn/started","frame":{"jsonrpc":"2.0","method":"turn/started","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","viewCursor":"v:01a11a6d-39bb-7000-8c93-4594c98e6a11:25","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-39bb-7000-8c93-4594c98e6a11"},"first":{"id":"4a1cf90d-7457-448d-a2b5-d82108636b3b","sequence":128},"last":{"id":"4a1cf90d-7457-448d-a2b5-d82108636b3b","sequence":128}},"turnId":"01a11a6d-8566-7000-8ad1-6269ac187a29","commandId":"01a11a6d-8566-7000-8ad1-6269ac187a29"},"emittedAtMs":1791444747660}} -{"type":"emit_inbound","label":"item/completed","frame":{"jsonrpc":"2.0","method":"item/completed","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","viewCursor":"v:01a11a6d-39bb-7000-8c93-4594c98e6a11:26","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-39bb-7000-8c93-4594c98e6a11"},"first":{"id":"4a1cf90d-7457-448d-a2b5-d82108636b3b","sequence":128},"last":{"id":"4a1cf90d-7457-448d-a2b5-d82108636b3b","sequence":128}},"item":{"itemId":"27473708-71e0-4d3c-811c-a8bae6bbaa3b","kind":"userMessage","turnId":"01a11a6d-8566-7000-8ad1-6269ac187a29","revision":1,"status":"completed","recordedAt":"2026-10-08T07:32:27.650913Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nRun the shell command `touch muse-declined.txt` with your shell tool once. If it is rejected, do not retry; reply REJECTED.","commandId":"01a11a6d-8566-7000-8ad1-6269ac187a29"}},"emittedAtMs":1791444747660}} -{"type":"emit_inbound","label":"item/updated","frame":{"jsonrpc":"2.0","method":"item/updated","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","viewCursor":"v:01a11a6d-39bb-7000-8c93-4594c98e6a11:27","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-39bb-7000-8c93-4594c98e6a11"},"first":{"id":"4a056a03-469a-4c9f-94a9-78eb815023ad","sequence":130},"last":{"id":"4a056a03-469a-4c9f-94a9-78eb815023ad","sequence":130}},"item":{"itemId":"27473708-71e0-4d3c-811c-a8bae6bbaa3b","kind":"userMessage","turnId":"01a11a6d-8566-7000-8ad1-6269ac187a29","revision":2,"status":"completed","recordedAt":"2026-10-08T07:32:27.66745Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nRun the shell command `touch muse-declined.txt` with your shell tool once. If it is rejected, do not retry; reply REJECTED.","displayText":"Run the shell command `touch muse-declined.txt` with your shell tool once. If it is rejected, do not retry; reply REJECTED.","commandId":"01a11a6d-8566-7000-8ad1-6269ac187a29"}},"emittedAtMs":1791444747676}} +{"type":"emit_inbound","label":"item/completed","frame":{"jsonrpc":"2.0","method":"item/completed","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","viewCursor":"v:01a11a6d-39bb-7000-8c93-4594c98e6a11:26","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-39bb-7000-8c93-4594c98e6a11"},"first":{"id":"4a1cf90d-7457-448d-a2b5-d82108636b3b","sequence":128},"last":{"id":"4a1cf90d-7457-448d-a2b5-d82108636b3b","sequence":128}},"item":{"itemId":"27473708-71e0-4d3c-811c-a8bae6bbaa3b","kind":"userMessage","turnId":"01a11a6d-8566-7000-8ad1-6269ac187a29","revision":1,"status":"completed","recordedAt":"2026-10-08T07:32:27.650913Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\nRun the shell command `touch muse-declined.txt` with your shell tool once. If it is rejected, do not retry; reply REJECTED.","commandId":"01a11a6d-8566-7000-8ad1-6269ac187a29"}},"emittedAtMs":1791444747660}} +{"type":"emit_inbound","label":"item/updated","frame":{"jsonrpc":"2.0","method":"item/updated","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","viewCursor":"v:01a11a6d-39bb-7000-8c93-4594c98e6a11:27","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-39bb-7000-8c93-4594c98e6a11"},"first":{"id":"4a056a03-469a-4c9f-94a9-78eb815023ad","sequence":130},"last":{"id":"4a056a03-469a-4c9f-94a9-78eb815023ad","sequence":130}},"item":{"itemId":"27473708-71e0-4d3c-811c-a8bae6bbaa3b","kind":"userMessage","turnId":"01a11a6d-8566-7000-8ad1-6269ac187a29","revision":2,"status":"completed","recordedAt":"2026-10-08T07:32:27.66745Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\nRun the shell command `touch muse-declined.txt` with your shell tool once. If it is rejected, do not retry; reply REJECTED.","displayText":"Run the shell command `touch muse-declined.txt` with your shell tool once. If it is rejected, do not retry; reply REJECTED.","commandId":"01a11a6d-8566-7000-8ad1-6269ac187a29"}},"emittedAtMs":1791444747676}} {"type":"emit_inbound","label":"item/started","frame":{"jsonrpc":"2.0","method":"item/started","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","viewCursor":"v:01a11a6d-39bb-7000-8c93-4594c98e6a11:28","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-39bb-7000-8c93-4594c98e6a11"},"first":{"id":"3b28955d-a87a-4acb-97e9-14cad87fd41f","sequence":148},"last":{"id":"3b28955d-a87a-4acb-97e9-14cad87fd41f","sequence":148}},"item":{"itemId":"3b28955d-a87a-4acb-97e9-14cad87fd41f","kind":"reminderChild","turnId":"01a11a6d-8566-7000-8ad1-6269ac187a29","revision":1,"status":"inProgress","recordedAt":"2026-10-08T07:32:27.787099Z","fallbackText":"Reminder child session","childSessionId":"efd21bf1-4fd1-49a2-9c55-91b7fc099765","reminderAgentId":"skill-reminder","generationId":1,"taskId":"01a11a6d-85ed-7b91-8d91-c4ce76b6dfef"}},"emittedAtMs":1791444747794}} {"type":"emit_inbound","label":"session/tokenUsage","frame":{"jsonrpc":"2.0","method":"session/tokenUsage","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","viewCursor":"v:01a11a6d-39bb-7000-8c93-4594c98e6a11:29","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-39bb-7000-8c93-4594c98e6a11"},"first":{"id":"b032c01d-eae1-437e-910c-8756aedc6084","sequence":164},"last":{"id":"b032c01d-eae1-437e-910c-8756aedc6084","sequence":164}},"turnId":"01a11a6d-8566-7000-8ad1-6269ac187a29","modelId":"muse-spark-1.3-contributor","usage":{"inputTokens":33401,"outputTokens":201,"cachedTokens":33009,"cacheWriteTokens":0,"cacheReadTokens":33009,"reasoningTokens":108},"promptTokens":33401,"totalTokens":33602,"finishReason":"tool_calls","durationMs":2522,"cumulative":{"promptTokens":99045,"outputTokens":538,"totalTokens":99583,"cacheReadTokens":65506,"cost":{"usd":0.003592512,"partial":false}}},"emittedAtMs":1791444750395}} {"type":"emit_inbound","label":"session/contextUsage","frame":{"jsonrpc":"2.0","method":"session/contextUsage","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","viewCursor":"v:01a11a6d-39bb-7000-8c93-4594c98e6a11:30","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-39bb-7000-8c93-4594c98e6a11"},"first":{"id":"b032c01d-eae1-437e-910c-8756aedc6084","sequence":164},"last":{"id":"b032c01d-eae1-437e-910c-8756aedc6084","sequence":164}},"windowTokens":1007997,"usedTokens":33602,"pressure":"normal"},"emittedAtMs":1791444750395}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/muse_subagent_approval/muse_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/muse_subagent_approval/muse_transcript.ndjson index 2608785344676..8cdfe31903aab 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/muse_subagent_approval/muse_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/muse_subagent_approval/muse_transcript.ndjson @@ -7,13 +7,13 @@ {"type":"emit_inbound","label":"session/started","frame":{"jsonrpc":"2.0","method":"session/started","params":{"session":{"sessionId":"01a12d1d-a1b7-7000-9697-d430c2e2afd8","path":"~/.local/share/muse/sessions/2026/10/11/01a12d1d-a1b7-7000-9697-d430c2e2afd8/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-11T22:37:59.14136Z","updatedAt":"2026-10-11T22:37:59.141364Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"sideFrom":null,"approvalMode":{"mode":"promptUnmatched","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"}},"emittedAtMs":1791758279294}} {"type":"emit_inbound","label":"response:session/start","frame":{"jsonrpc":"2.0","id":2,"result":{"session":{"sessionId":"01a12d1d-a1b7-7000-9697-d430c2e2afd8","path":"~/.local/share/muse/sessions/2026/10/11/01a12d1d-a1b7-7000-9697-d430c2e2afd8/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-11T22:37:59.14136Z","updatedAt":"2026-10-11T22:37:59.141364Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"sideFrom":null,"approvalMode":{"mode":"promptUnmatched","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"},"viewCursor":"v:01a12d1d-a1b7-7000-9697-d430c2e2afd8:1"}}} {"type":"emit_inbound","label":"session/approvalModeChanged","frame":{"jsonrpc":"2.0","method":"session/approvalModeChanged","params":{"sessionId":"01a12d1d-a1b7-7000-9697-d430c2e2afd8","viewCursor":"v:01a12d1d-a1b7-7000-9697-d430c2e2afd8:1","sourceRange":{"stream":{"kind":"session","id":"01a12d1d-a1b7-7000-9697-d430c2e2afd8"},"first":{"id":"ed95a9db-eada-4751-a7e6-22ccc9bdabd5","sequence":5},"last":{"id":"ed95a9db-eada-4751-a7e6-22ccc9bdabd5","sequence":5}},"mode":"promptUnmatched","source":"approvalReconfigure","commandId":"01a12d1d-a1b8-7000-8d6c-f1324b724cdb","clientName":"t3_code"},"emittedAtMs":1791758279297}} -{"type":"expect_outbound","label":"turn/start","frame":{"jsonrpc":"2.0","id":3,"method":"turn/start","params":{"sessionId":"01a12d1d-a1b7-7000-9697-d430c2e2afd8","input":[{"type":"text","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\n"},{"type":"text","text":"Do not run any commands yourself. Spawn one subagent whose only task is to run this exact shell command: printf 'subagent approval fixture' > subagent-approval.txt and then reply with exactly: Written. Wait for it to finish, then reply with exactly what it said."}],"displayText":"Do not run any commands yourself. Spawn one subagent whose only task is to run this exact shell command: printf 'subagent approval fixture' > subagent-approval.txt and then reply with exactly: Written. Wait for it to finish, then reply with exactly what it said.","workspaceRoots":[""],"ifBusy":"queue","reasoningEffort":"high","commandId":"01a12d1d-a348-7000-ae97-9d27b5f80bce"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"jsonrpc":"2.0","id":3,"method":"turn/start","params":{"sessionId":"01a12d1d-a1b7-7000-9697-d430c2e2afd8","input":[{"type":"text","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\n"},{"type":"text","text":"Do not run any commands yourself. Spawn one subagent whose only task is to run this exact shell command: printf 'subagent approval fixture' > subagent-approval.txt and then reply with exactly: Written. Wait for it to finish, then reply with exactly what it said."}],"displayText":"Do not run any commands yourself. Spawn one subagent whose only task is to run this exact shell command: printf 'subagent approval fixture' > subagent-approval.txt and then reply with exactly: Written. Wait for it to finish, then reply with exactly what it said.","workspaceRoots":[""],"ifBusy":"queue","reasoningEffort":"high","commandId":"01a12d1d-a348-7000-ae97-9d27b5f80bce"}}} {"type":"emit_inbound","label":"session/branchChanged","frame":{"jsonrpc":"2.0","method":"session/branchChanged","params":{"sessionId":"01a12d1d-a1b7-7000-9697-d430c2e2afd8","viewCursor":"v:01a12d1d-a1b7-7000-9697-d430c2e2afd8:2","sourceRange":{"stream":{"kind":"session","id":"01a12d1d-a1b7-7000-9697-d430c2e2afd8"},"first":{"id":"4f170229-d428-4a64-9516-7a355ff3bcdb","sequence":15},"last":{"id":"4f170229-d428-4a64-9516-7a355ff3bcdb","sequence":15}},"workspaceRoot":"","branch":"main","vcs":"git"},"emittedAtMs":1791758279531}} {"type":"emit_inbound","label":"response:turn/start","frame":{"jsonrpc":"2.0","id":3,"result":{"commandId":"01a12d1d-a348-7000-ae97-9d27b5f80bce","status":"accepted","turnId":"01a12d1d-a348-7000-ae97-9d27b5f80bce","startedNewTurn":true,"disposition":"started"}}} {"type":"emit_inbound","label":"session/statusChanged","frame":{"jsonrpc":"2.0","method":"session/statusChanged","params":{"sessionId":"01a12d1d-a1b7-7000-9697-d430c2e2afd8","status":"running","viewCursor":"v:01a12d1d-a1b7-7000-9697-d430c2e2afd8:3"},"emittedAtMs":1791758279541}} {"type":"emit_inbound","label":"turn/started","frame":{"jsonrpc":"2.0","method":"turn/started","params":{"sessionId":"01a12d1d-a1b7-7000-9697-d430c2e2afd8","viewCursor":"v:01a12d1d-a1b7-7000-9697-d430c2e2afd8:3","sourceRange":{"stream":{"kind":"session","id":"01a12d1d-a1b7-7000-9697-d430c2e2afd8"},"first":{"id":"429e8ecf-d532-4b14-a303-b9f832c36a51","sequence":17},"last":{"id":"429e8ecf-d532-4b14-a303-b9f832c36a51","sequence":17}},"turnId":"01a12d1d-a348-7000-ae97-9d27b5f80bce","commandId":"01a12d1d-a348-7000-ae97-9d27b5f80bce"},"emittedAtMs":1791758279542}} -{"type":"emit_inbound","label":"item/completed","frame":{"jsonrpc":"2.0","method":"item/completed","params":{"sessionId":"01a12d1d-a1b7-7000-9697-d430c2e2afd8","viewCursor":"v:01a12d1d-a1b7-7000-9697-d430c2e2afd8:4","sourceRange":{"stream":{"kind":"session","id":"01a12d1d-a1b7-7000-9697-d430c2e2afd8"},"first":{"id":"429e8ecf-d532-4b14-a303-b9f832c36a51","sequence":17},"last":{"id":"429e8ecf-d532-4b14-a303-b9f832c36a51","sequence":17}},"item":{"itemId":"a4b3de8d-842b-4065-8769-aed18e62e9fc","kind":"userMessage","turnId":"01a12d1d-a348-7000-ae97-9d27b5f80bce","revision":1,"status":"completed","recordedAt":"2026-10-11T22:37:59.531477Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nDo not run any commands yourself. Spawn one subagent whose only task is to run this exact shell command: printf 'subagent approval fixture' > subagent-approval.txt and then reply with exactly: Written. Wait for it to finish, then reply with exactly what it said.","commandId":"01a12d1d-a348-7000-ae97-9d27b5f80bce"}},"emittedAtMs":1791758279542}} -{"type":"emit_inbound","label":"item/updated","frame":{"jsonrpc":"2.0","method":"item/updated","params":{"sessionId":"01a12d1d-a1b7-7000-9697-d430c2e2afd8","viewCursor":"v:01a12d1d-a1b7-7000-9697-d430c2e2afd8:5","sourceRange":{"stream":{"kind":"session","id":"01a12d1d-a1b7-7000-9697-d430c2e2afd8"},"first":{"id":"5a63e348-5bf6-4262-b37f-d31d307ea6d8","sequence":19},"last":{"id":"5a63e348-5bf6-4262-b37f-d31d307ea6d8","sequence":19}},"item":{"itemId":"a4b3de8d-842b-4065-8769-aed18e62e9fc","kind":"userMessage","turnId":"01a12d1d-a348-7000-ae97-9d27b5f80bce","revision":2,"status":"completed","recordedAt":"2026-10-11T22:37:59.545908Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nDo not run any commands yourself. Spawn one subagent whose only task is to run this exact shell command: printf 'subagent approval fixture' > subagent-approval.txt and then reply with exactly: Written. Wait for it to finish, then reply with exactly what it said.","displayText":"Do not run any commands yourself. Spawn one subagent whose only task is to run this exact shell command: printf 'subagent approval fixture' > subagent-approval.txt and then reply with exactly: Written. Wait for it to finish, then reply with exactly what it said.","commandId":"01a12d1d-a348-7000-ae97-9d27b5f80bce"}},"emittedAtMs":1791758279553}} +{"type":"emit_inbound","label":"item/completed","frame":{"jsonrpc":"2.0","method":"item/completed","params":{"sessionId":"01a12d1d-a1b7-7000-9697-d430c2e2afd8","viewCursor":"v:01a12d1d-a1b7-7000-9697-d430c2e2afd8:4","sourceRange":{"stream":{"kind":"session","id":"01a12d1d-a1b7-7000-9697-d430c2e2afd8"},"first":{"id":"429e8ecf-d532-4b14-a303-b9f832c36a51","sequence":17},"last":{"id":"429e8ecf-d532-4b14-a303-b9f832c36a51","sequence":17}},"item":{"itemId":"a4b3de8d-842b-4065-8769-aed18e62e9fc","kind":"userMessage","turnId":"01a12d1d-a348-7000-ae97-9d27b5f80bce","revision":1,"status":"completed","recordedAt":"2026-10-11T22:37:59.531477Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\nDo not run any commands yourself. Spawn one subagent whose only task is to run this exact shell command: printf 'subagent approval fixture' > subagent-approval.txt and then reply with exactly: Written. Wait for it to finish, then reply with exactly what it said.","commandId":"01a12d1d-a348-7000-ae97-9d27b5f80bce"}},"emittedAtMs":1791758279542}} +{"type":"emit_inbound","label":"item/updated","frame":{"jsonrpc":"2.0","method":"item/updated","params":{"sessionId":"01a12d1d-a1b7-7000-9697-d430c2e2afd8","viewCursor":"v:01a12d1d-a1b7-7000-9697-d430c2e2afd8:5","sourceRange":{"stream":{"kind":"session","id":"01a12d1d-a1b7-7000-9697-d430c2e2afd8"},"first":{"id":"5a63e348-5bf6-4262-b37f-d31d307ea6d8","sequence":19},"last":{"id":"5a63e348-5bf6-4262-b37f-d31d307ea6d8","sequence":19}},"item":{"itemId":"a4b3de8d-842b-4065-8769-aed18e62e9fc","kind":"userMessage","turnId":"01a12d1d-a348-7000-ae97-9d27b5f80bce","revision":2,"status":"completed","recordedAt":"2026-10-11T22:37:59.545908Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\nDo not run any commands yourself. Spawn one subagent whose only task is to run this exact shell command: printf 'subagent approval fixture' > subagent-approval.txt and then reply with exactly: Written. Wait for it to finish, then reply with exactly what it said.","displayText":"Do not run any commands yourself. Spawn one subagent whose only task is to run this exact shell command: printf 'subagent approval fixture' > subagent-approval.txt and then reply with exactly: Written. Wait for it to finish, then reply with exactly what it said.","commandId":"01a12d1d-a348-7000-ae97-9d27b5f80bce"}},"emittedAtMs":1791758279553}} {"type":"emit_inbound","label":"item/started","frame":{"jsonrpc":"2.0","method":"item/started","params":{"sessionId":"01a12d1d-a1b7-7000-9697-d430c2e2afd8","viewCursor":"v:01a12d1d-a1b7-7000-9697-d430c2e2afd8:6","sourceRange":{"stream":{"kind":"session","id":"01a12d1d-a1b7-7000-9697-d430c2e2afd8"},"first":{"id":"d55286a9-a9e2-4d7b-be97-d44360bcca2b","sequence":37},"last":{"id":"d55286a9-a9e2-4d7b-be97-d44360bcca2b","sequence":37}},"item":{"itemId":"d55286a9-a9e2-4d7b-be97-d44360bcca2b","kind":"reminderChild","turnId":"01a12d1d-a348-7000-ae97-9d27b5f80bce","revision":1,"status":"inProgress","recordedAt":"2026-10-11T22:37:59.660065Z","fallbackText":"Reminder child session","childSessionId":"0779d605-54b8-45dc-90b6-91dc58b9a52c","reminderAgentId":"skill-reminder","generationId":1,"taskId":"01a12d1d-a3d4-7712-8b98-26f3c4f9bf38"}},"emittedAtMs":1791758279666}} {"type":"emit_inbound","label":"item/started","frame":{"jsonrpc":"2.0","method":"item/started","params":{"sessionId":"01a12d1d-a1b7-7000-9697-d430c2e2afd8","viewCursor":"v:01a12d1d-a1b7-7000-9697-d430c2e2afd8:6.1","item":{"itemId":"21b74b34-fe9f-457c-83f0-cf49257b5948","kind":"reasoning","turnId":"01a12d1d-a348-7000-ae97-9d27b5f80bce","revision":1,"status":"inProgress","summary":[""]}},"emittedAtMs":1791758282481}} {"type":"emit_inbound","label":"item/delta","frame":{"jsonrpc":"2.0","method":"item/delta","params":{"sessionId":"01a12d1d-a1b7-7000-9697-d430c2e2afd8","viewCursor":"v:01a12d1d-a1b7-7000-9697-d430c2e2afd8:6.2","itemId":"21b74b34-fe9f-457c-83f0-cf49257b5948","field":"summary.0","delta":"Spawning a subagent via muse_subagent_spawn to run a shell command and return its exact output, while avoiding direct command execution."},"emittedAtMs":1791758282481}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/muse_subagent_interrupt/muse_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/muse_subagent_interrupt/muse_transcript.ndjson index 0c88688e6aed5..769f02f88c7ed 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/muse_subagent_interrupt/muse_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/muse_subagent_interrupt/muse_transcript.ndjson @@ -7,13 +7,13 @@ {"type":"emit_inbound","label":"session/started","frame":{"jsonrpc":"2.0","method":"session/started","params":{"session":{"sessionId":"01a12d28-7788-7000-a946-c407f380868e","path":"~/.local/share/muse/sessions/2026/10/11/01a12d28-7788-7000-a946-c407f380868e/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-11T22:49:49.235205Z","updatedAt":"2026-10-11T22:49:49.235209Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"sideFrom":null,"approvalMode":{"mode":"allowAll","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"}},"emittedAtMs":1791758989388}} {"type":"emit_inbound","label":"response:session/start","frame":{"jsonrpc":"2.0","id":2,"result":{"session":{"sessionId":"01a12d28-7788-7000-a946-c407f380868e","path":"~/.local/share/muse/sessions/2026/10/11/01a12d28-7788-7000-a946-c407f380868e/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-11T22:49:49.235205Z","updatedAt":"2026-10-11T22:49:49.235209Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"sideFrom":null,"approvalMode":{"mode":"allowAll","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"},"viewCursor":"v:01a12d28-7788-7000-a946-c407f380868e:1"}}} {"type":"emit_inbound","label":"session/approvalModeChanged","frame":{"jsonrpc":"2.0","method":"session/approvalModeChanged","params":{"sessionId":"01a12d28-7788-7000-a946-c407f380868e","viewCursor":"v:01a12d28-7788-7000-a946-c407f380868e:1","sourceRange":{"stream":{"kind":"session","id":"01a12d28-7788-7000-a946-c407f380868e"},"first":{"id":"29d4e769-78f7-48fa-90cd-3ac9f8fa04bf","sequence":5},"last":{"id":"29d4e769-78f7-48fa-90cd-3ac9f8fa04bf","sequence":5}},"mode":"allowAll","source":"approvalReconfigure","commandId":"01a12d28-7788-7001-a223-c10e52187cdf","clientName":"t3_code"},"emittedAtMs":1791758989391}} -{"type":"expect_outbound","label":"turn/start","frame":{"jsonrpc":"2.0","id":3,"method":"turn/start","params":{"sessionId":"01a12d28-7788-7000-a946-c407f380868e","input":[{"type":"text","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\n"},{"type":"text","text":"Spawn one subagent whose only task is to run the shell command `sleep 30` and then reply with exactly: Done. Wait for it to finish, then reply with exactly what it said."}],"displayText":"Spawn one subagent whose only task is to run the shell command `sleep 30` and then reply with exactly: Done. Wait for it to finish, then reply with exactly what it said.","workspaceRoots":[""],"ifBusy":"queue","reasoningEffort":"high","commandId":"01a12d28-7912-7000-993a-afd019e6ac5c"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"jsonrpc":"2.0","id":3,"method":"turn/start","params":{"sessionId":"01a12d28-7788-7000-a946-c407f380868e","input":[{"type":"text","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\n"},{"type":"text","text":"Spawn one subagent whose only task is to run the shell command `sleep 30` and then reply with exactly: Done. Wait for it to finish, then reply with exactly what it said."}],"displayText":"Spawn one subagent whose only task is to run the shell command `sleep 30` and then reply with exactly: Done. Wait for it to finish, then reply with exactly what it said.","workspaceRoots":[""],"ifBusy":"queue","reasoningEffort":"high","commandId":"01a12d28-7912-7000-993a-afd019e6ac5c"}}} {"type":"emit_inbound","label":"session/branchChanged","frame":{"jsonrpc":"2.0","method":"session/branchChanged","params":{"sessionId":"01a12d28-7788-7000-a946-c407f380868e","viewCursor":"v:01a12d28-7788-7000-a946-c407f380868e:2","sourceRange":{"stream":{"kind":"session","id":"01a12d28-7788-7000-a946-c407f380868e"},"first":{"id":"660e2cfd-318a-4d2d-87bb-0b1375d79fdf","sequence":15},"last":{"id":"660e2cfd-318a-4d2d-87bb-0b1375d79fdf","sequence":15}},"workspaceRoot":"","branch":"main","vcs":"git"},"emittedAtMs":1791758989619}} {"type":"emit_inbound","label":"response:turn/start","frame":{"jsonrpc":"2.0","id":3,"result":{"commandId":"01a12d28-7912-7000-993a-afd019e6ac5c","status":"accepted","turnId":"01a12d28-7912-7000-993a-afd019e6ac5c","startedNewTurn":true,"disposition":"started"}}} {"type":"emit_inbound","label":"session/statusChanged","frame":{"jsonrpc":"2.0","method":"session/statusChanged","params":{"sessionId":"01a12d28-7788-7000-a946-c407f380868e","status":"running","viewCursor":"v:01a12d28-7788-7000-a946-c407f380868e:3"},"emittedAtMs":1791758989632}} {"type":"emit_inbound","label":"turn/started","frame":{"jsonrpc":"2.0","method":"turn/started","params":{"sessionId":"01a12d28-7788-7000-a946-c407f380868e","viewCursor":"v:01a12d28-7788-7000-a946-c407f380868e:3","sourceRange":{"stream":{"kind":"session","id":"01a12d28-7788-7000-a946-c407f380868e"},"first":{"id":"5cb199bd-04e5-40d9-a299-8760be80e0a4","sequence":17},"last":{"id":"5cb199bd-04e5-40d9-a299-8760be80e0a4","sequence":17}},"turnId":"01a12d28-7912-7000-993a-afd019e6ac5c","commandId":"01a12d28-7912-7000-993a-afd019e6ac5c"},"emittedAtMs":1791758989632}} -{"type":"emit_inbound","label":"item/completed","frame":{"jsonrpc":"2.0","method":"item/completed","params":{"sessionId":"01a12d28-7788-7000-a946-c407f380868e","viewCursor":"v:01a12d28-7788-7000-a946-c407f380868e:4","sourceRange":{"stream":{"kind":"session","id":"01a12d28-7788-7000-a946-c407f380868e"},"first":{"id":"5cb199bd-04e5-40d9-a299-8760be80e0a4","sequence":17},"last":{"id":"5cb199bd-04e5-40d9-a299-8760be80e0a4","sequence":17}},"item":{"itemId":"5e234d9d-0744-4757-9629-761ea4e7f062","kind":"userMessage","turnId":"01a12d28-7912-7000-993a-afd019e6ac5c","revision":1,"status":"completed","recordedAt":"2026-10-11T22:49:49.620067Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nSpawn one subagent whose only task is to run the shell command `sleep 30` and then reply with exactly: Done. Wait for it to finish, then reply with exactly what it said.","commandId":"01a12d28-7912-7000-993a-afd019e6ac5c"}},"emittedAtMs":1791758989632}} -{"type":"emit_inbound","label":"item/updated","frame":{"jsonrpc":"2.0","method":"item/updated","params":{"sessionId":"01a12d28-7788-7000-a946-c407f380868e","viewCursor":"v:01a12d28-7788-7000-a946-c407f380868e:5","sourceRange":{"stream":{"kind":"session","id":"01a12d28-7788-7000-a946-c407f380868e"},"first":{"id":"5724636e-9398-4d23-87ac-1e9a2b83ad9f","sequence":19},"last":{"id":"5724636e-9398-4d23-87ac-1e9a2b83ad9f","sequence":19}},"item":{"itemId":"5e234d9d-0744-4757-9629-761ea4e7f062","kind":"userMessage","turnId":"01a12d28-7912-7000-993a-afd019e6ac5c","revision":2,"status":"completed","recordedAt":"2026-10-11T22:49:49.635395Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nSpawn one subagent whose only task is to run the shell command `sleep 30` and then reply with exactly: Done. Wait for it to finish, then reply with exactly what it said.","displayText":"Spawn one subagent whose only task is to run the shell command `sleep 30` and then reply with exactly: Done. Wait for it to finish, then reply with exactly what it said.","commandId":"01a12d28-7912-7000-993a-afd019e6ac5c"}},"emittedAtMs":1791758989642}} +{"type":"emit_inbound","label":"item/completed","frame":{"jsonrpc":"2.0","method":"item/completed","params":{"sessionId":"01a12d28-7788-7000-a946-c407f380868e","viewCursor":"v:01a12d28-7788-7000-a946-c407f380868e:4","sourceRange":{"stream":{"kind":"session","id":"01a12d28-7788-7000-a946-c407f380868e"},"first":{"id":"5cb199bd-04e5-40d9-a299-8760be80e0a4","sequence":17},"last":{"id":"5cb199bd-04e5-40d9-a299-8760be80e0a4","sequence":17}},"item":{"itemId":"5e234d9d-0744-4757-9629-761ea4e7f062","kind":"userMessage","turnId":"01a12d28-7912-7000-993a-afd019e6ac5c","revision":1,"status":"completed","recordedAt":"2026-10-11T22:49:49.620067Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\nSpawn one subagent whose only task is to run the shell command `sleep 30` and then reply with exactly: Done. Wait for it to finish, then reply with exactly what it said.","commandId":"01a12d28-7912-7000-993a-afd019e6ac5c"}},"emittedAtMs":1791758989632}} +{"type":"emit_inbound","label":"item/updated","frame":{"jsonrpc":"2.0","method":"item/updated","params":{"sessionId":"01a12d28-7788-7000-a946-c407f380868e","viewCursor":"v:01a12d28-7788-7000-a946-c407f380868e:5","sourceRange":{"stream":{"kind":"session","id":"01a12d28-7788-7000-a946-c407f380868e"},"first":{"id":"5724636e-9398-4d23-87ac-1e9a2b83ad9f","sequence":19},"last":{"id":"5724636e-9398-4d23-87ac-1e9a2b83ad9f","sequence":19}},"item":{"itemId":"5e234d9d-0744-4757-9629-761ea4e7f062","kind":"userMessage","turnId":"01a12d28-7912-7000-993a-afd019e6ac5c","revision":2,"status":"completed","recordedAt":"2026-10-11T22:49:49.635395Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\nSpawn one subagent whose only task is to run the shell command `sleep 30` and then reply with exactly: Done. Wait for it to finish, then reply with exactly what it said.","displayText":"Spawn one subagent whose only task is to run the shell command `sleep 30` and then reply with exactly: Done. Wait for it to finish, then reply with exactly what it said.","commandId":"01a12d28-7912-7000-993a-afd019e6ac5c"}},"emittedAtMs":1791758989642}} {"type":"emit_inbound","label":"item/started","frame":{"jsonrpc":"2.0","method":"item/started","params":{"sessionId":"01a12d28-7788-7000-a946-c407f380868e","viewCursor":"v:01a12d28-7788-7000-a946-c407f380868e:6","sourceRange":{"stream":{"kind":"session","id":"01a12d28-7788-7000-a946-c407f380868e"},"first":{"id":"44afb415-d6e4-4d51-9002-4deb196d463a","sequence":36},"last":{"id":"44afb415-d6e4-4d51-9002-4deb196d463a","sequence":36}},"item":{"itemId":"44afb415-d6e4-4d51-9002-4deb196d463a","kind":"reminderChild","turnId":"01a12d28-7912-7000-993a-afd019e6ac5c","revision":1,"status":"inProgress","recordedAt":"2026-10-11T22:49:49.743418Z","fallbackText":"Reminder child session","childSessionId":"4dd3511e-2115-4fbb-a4c4-383cbb383d63","reminderAgentId":"skill-reminder","generationId":1,"taskId":"01a12d28-7997-79d0-8a69-8ac0acf92a56"}},"emittedAtMs":1791758989750}} {"type":"emit_inbound","label":"session/tokenUsage","frame":{"jsonrpc":"2.0","method":"session/tokenUsage","params":{"sessionId":"01a12d28-7788-7000-a946-c407f380868e","viewCursor":"v:01a12d28-7788-7000-a946-c407f380868e:7","sourceRange":{"stream":{"kind":"session","id":"01a12d28-7788-7000-a946-c407f380868e"},"first":{"id":"c94f5484-20b7-4057-a736-303e97bc097c","sequence":52},"last":{"id":"c94f5484-20b7-4057-a736-303e97bc097c","sequence":52}},"turnId":"01a12d28-7912-7000-993a-afd019e6ac5c","modelId":"muse-spark-1.3-contributor","usage":{"inputTokens":32911,"outputTokens":264,"cachedTokens":0,"cacheWriteTokens":0,"cacheReadTokens":0,"reasoningTokens":143},"promptTokens":32911,"totalTokens":33175,"finishReason":"tool_calls","durationMs":3651,"cumulative":{"promptTokens":32911,"outputTokens":264,"totalTokens":33175,"cost":{"usd":0.0033439000000000003,"partial":false}}},"emittedAtMs":1791758993485}} {"type":"emit_inbound","label":"session/contextUsage","frame":{"jsonrpc":"2.0","method":"session/contextUsage","params":{"sessionId":"01a12d28-7788-7000-a946-c407f380868e","viewCursor":"v:01a12d28-7788-7000-a946-c407f380868e:8","sourceRange":{"stream":{"kind":"session","id":"01a12d28-7788-7000-a946-c407f380868e"},"first":{"id":"c94f5484-20b7-4057-a736-303e97bc097c","sequence":52},"last":{"id":"c94f5484-20b7-4057-a736-303e97bc097c","sequence":52}},"windowTokens":1007997,"usedTokens":33175,"pressure":"normal"},"emittedAtMs":1791758993485}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/muse_workflow/muse_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/muse_workflow/muse_transcript.ndjson index 5da7624808ead..0ba946164c9ed 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/muse_workflow/muse_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/muse_workflow/muse_transcript.ndjson @@ -8,13 +8,13 @@ {"type":"emit_inbound","label":"response:session/start","frame":{"jsonrpc":"2.0","id":2,"result":{"session":{"sessionId":"01a12d5d-405f-7000-89a3-5aa62af6ea23","path":"~/.local/share/muse/sessions/2026/10/11/01a12d5d-405f-7000-89a3-5aa62af6ea23/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-11T23:47:28.587276Z","updatedAt":"2026-10-11T23:47:28.587281Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"sideFrom":null,"approvalMode":{"mode":"allowAll","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"},"viewCursor":"v:01a12d5d-405f-7000-89a3-5aa62af6ea23:2"}}} {"type":"emit_inbound","label":"session/approvalModeChanged","frame":{"jsonrpc":"2.0","method":"session/approvalModeChanged","params":{"sessionId":"01a12d5d-405f-7000-89a3-5aa62af6ea23","viewCursor":"v:01a12d5d-405f-7000-89a3-5aa62af6ea23:1","sourceRange":{"stream":{"kind":"session","id":"01a12d5d-405f-7000-89a3-5aa62af6ea23"},"first":{"id":"0c13b14b-877c-4c5b-b05f-8ad250dfd381","sequence":5},"last":{"id":"0c13b14b-877c-4c5b-b05f-8ad250dfd381","sequence":5}},"mode":"allowAll","source":"approvalReconfigure","commandId":"01a12d5d-4060-7000-b6cd-aaabe26f80de","clientName":"t3_code"},"emittedAtMs":1791762448807}} {"type":"emit_inbound","label":"session/branchChanged","frame":{"jsonrpc":"2.0","method":"session/branchChanged","params":{"sessionId":"01a12d5d-405f-7000-89a3-5aa62af6ea23","viewCursor":"v:01a12d5d-405f-7000-89a3-5aa62af6ea23:2","sourceRange":{"stream":{"kind":"session","id":"01a12d5d-405f-7000-89a3-5aa62af6ea23"},"first":{"id":"28b1f3f4-4448-4a21-a1a0-2df72ad1d326","sequence":6},"last":{"id":"28b1f3f4-4448-4a21-a1a0-2df72ad1d326","sequence":6}},"workspaceRoot":"","branch":"main","vcs":"git"},"emittedAtMs":1791762448807}} -{"type":"expect_outbound","label":"turn/start","frame":{"jsonrpc":"2.0","id":3,"method":"turn/start","params":{"sessionId":"01a12d5d-405f-7000-89a3-5aa62af6ea23","input":[{"type":"text","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\n"},{"type":"text","text":"Use your workflow tool to launch a workflow with exactly TWO agents: one labeled 'ping' that replies with the word PING, and one labeled 'pong' that replies with the word PONG. Launch it and end your turn; do not wait for it."}],"displayText":"Use your workflow tool to launch a workflow with exactly TWO agents: one labeled 'ping' that replies with the word PING, and one labeled 'pong' that replies with the word PONG. Launch it and end your turn; do not wait for it.","workspaceRoots":[""],"ifBusy":"queue","reasoningEffort":"high","commandId":"01a12d5d-42c3-7000-ab94-c7f56ea457e5"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"jsonrpc":"2.0","id":3,"method":"turn/start","params":{"sessionId":"01a12d5d-405f-7000-89a3-5aa62af6ea23","input":[{"type":"text","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\n"},{"type":"text","text":"Use your workflow tool to launch a workflow with exactly TWO agents: one labeled 'ping' that replies with the word PING, and one labeled 'pong' that replies with the word PONG. Launch it and end your turn; do not wait for it."}],"displayText":"Use your workflow tool to launch a workflow with exactly TWO agents: one labeled 'ping' that replies with the word PING, and one labeled 'pong' that replies with the word PONG. Launch it and end your turn; do not wait for it.","workspaceRoots":[""],"ifBusy":"queue","reasoningEffort":"high","commandId":"01a12d5d-42c3-7000-ab94-c7f56ea457e5"}}} {"type":"emit_inbound","label":"session/branchChanged","frame":{"jsonrpc":"2.0","method":"session/branchChanged","params":{"sessionId":"01a12d5d-405f-7000-89a3-5aa62af6ea23","viewCursor":"v:01a12d5d-405f-7000-89a3-5aa62af6ea23:3","sourceRange":{"stream":{"kind":"session","id":"01a12d5d-405f-7000-89a3-5aa62af6ea23"},"first":{"id":"3f1880e1-81a0-4f21-b536-6b4fa5cf9d12","sequence":16},"last":{"id":"3f1880e1-81a0-4f21-b536-6b4fa5cf9d12","sequence":16}},"workspaceRoot":"","branch":"main","vcs":"git"},"emittedAtMs":1791762449097}} {"type":"emit_inbound","label":"response:turn/start","frame":{"jsonrpc":"2.0","id":3,"result":{"commandId":"01a12d5d-42c3-7000-ab94-c7f56ea457e5","status":"accepted","turnId":"01a12d5d-42c3-7000-ab94-c7f56ea457e5","startedNewTurn":true,"disposition":"started"}}} {"type":"emit_inbound","label":"session/statusChanged","frame":{"jsonrpc":"2.0","method":"session/statusChanged","params":{"sessionId":"01a12d5d-405f-7000-89a3-5aa62af6ea23","status":"running","viewCursor":"v:01a12d5d-405f-7000-89a3-5aa62af6ea23:4"},"emittedAtMs":1791762449102}} {"type":"emit_inbound","label":"turn/started","frame":{"jsonrpc":"2.0","method":"turn/started","params":{"sessionId":"01a12d5d-405f-7000-89a3-5aa62af6ea23","viewCursor":"v:01a12d5d-405f-7000-89a3-5aa62af6ea23:4","sourceRange":{"stream":{"kind":"session","id":"01a12d5d-405f-7000-89a3-5aa62af6ea23"},"first":{"id":"7a830825-f571-4781-8e4f-a4ef5e085bb7","sequence":18},"last":{"id":"7a830825-f571-4781-8e4f-a4ef5e085bb7","sequence":18}},"turnId":"01a12d5d-42c3-7000-ab94-c7f56ea457e5","commandId":"01a12d5d-42c3-7000-ab94-c7f56ea457e5"},"emittedAtMs":1791762449103}} -{"type":"emit_inbound","label":"item/completed","frame":{"jsonrpc":"2.0","method":"item/completed","params":{"sessionId":"01a12d5d-405f-7000-89a3-5aa62af6ea23","viewCursor":"v:01a12d5d-405f-7000-89a3-5aa62af6ea23:5","sourceRange":{"stream":{"kind":"session","id":"01a12d5d-405f-7000-89a3-5aa62af6ea23"},"first":{"id":"7a830825-f571-4781-8e4f-a4ef5e085bb7","sequence":18},"last":{"id":"7a830825-f571-4781-8e4f-a4ef5e085bb7","sequence":18}},"item":{"itemId":"0c1ceda9-41f7-4c3e-990e-4c53873c7ef5","kind":"userMessage","turnId":"01a12d5d-42c3-7000-ab94-c7f56ea457e5","revision":1,"status":"completed","recordedAt":"2026-10-11T23:47:29.098117Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nUse your workflow tool to launch a workflow with exactly TWO agents: one labeled 'ping' that replies with the word PING, and one labeled 'pong' that replies with the word PONG. Launch it and end your turn; do not wait for it.","commandId":"01a12d5d-42c3-7000-ab94-c7f56ea457e5"}},"emittedAtMs":1791762449103}} -{"type":"emit_inbound","label":"item/updated","frame":{"jsonrpc":"2.0","method":"item/updated","params":{"sessionId":"01a12d5d-405f-7000-89a3-5aa62af6ea23","viewCursor":"v:01a12d5d-405f-7000-89a3-5aa62af6ea23:6","sourceRange":{"stream":{"kind":"session","id":"01a12d5d-405f-7000-89a3-5aa62af6ea23"},"first":{"id":"0411a5c8-2c8a-4c9e-bb67-25fa3cef21a3","sequence":20},"last":{"id":"0411a5c8-2c8a-4c9e-bb67-25fa3cef21a3","sequence":20}},"item":{"itemId":"0c1ceda9-41f7-4c3e-990e-4c53873c7ef5","kind":"userMessage","turnId":"01a12d5d-42c3-7000-ab94-c7f56ea457e5","revision":2,"status":"completed","recordedAt":"2026-10-11T23:47:29.107019Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nUse your workflow tool to launch a workflow with exactly TWO agents: one labeled 'ping' that replies with the word PING, and one labeled 'pong' that replies with the word PONG. Launch it and end your turn; do not wait for it.","displayText":"Use your workflow tool to launch a workflow with exactly TWO agents: one labeled 'ping' that replies with the word PING, and one labeled 'pong' that replies with the word PONG. Launch it and end your turn; do not wait for it.","commandId":"01a12d5d-42c3-7000-ab94-c7f56ea457e5"}},"emittedAtMs":1791762449131}} +{"type":"emit_inbound","label":"item/completed","frame":{"jsonrpc":"2.0","method":"item/completed","params":{"sessionId":"01a12d5d-405f-7000-89a3-5aa62af6ea23","viewCursor":"v:01a12d5d-405f-7000-89a3-5aa62af6ea23:5","sourceRange":{"stream":{"kind":"session","id":"01a12d5d-405f-7000-89a3-5aa62af6ea23"},"first":{"id":"7a830825-f571-4781-8e4f-a4ef5e085bb7","sequence":18},"last":{"id":"7a830825-f571-4781-8e4f-a4ef5e085bb7","sequence":18}},"item":{"itemId":"0c1ceda9-41f7-4c3e-990e-4c53873c7ef5","kind":"userMessage","turnId":"01a12d5d-42c3-7000-ab94-c7f56ea457e5","revision":1,"status":"completed","recordedAt":"2026-10-11T23:47:29.098117Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\nUse your workflow tool to launch a workflow with exactly TWO agents: one labeled 'ping' that replies with the word PING, and one labeled 'pong' that replies with the word PONG. Launch it and end your turn; do not wait for it.","commandId":"01a12d5d-42c3-7000-ab94-c7f56ea457e5"}},"emittedAtMs":1791762449103}} +{"type":"emit_inbound","label":"item/updated","frame":{"jsonrpc":"2.0","method":"item/updated","params":{"sessionId":"01a12d5d-405f-7000-89a3-5aa62af6ea23","viewCursor":"v:01a12d5d-405f-7000-89a3-5aa62af6ea23:6","sourceRange":{"stream":{"kind":"session","id":"01a12d5d-405f-7000-89a3-5aa62af6ea23"},"first":{"id":"0411a5c8-2c8a-4c9e-bb67-25fa3cef21a3","sequence":20},"last":{"id":"0411a5c8-2c8a-4c9e-bb67-25fa3cef21a3","sequence":20}},"item":{"itemId":"0c1ceda9-41f7-4c3e-990e-4c53873c7ef5","kind":"userMessage","turnId":"01a12d5d-42c3-7000-ab94-c7f56ea457e5","revision":2,"status":"completed","recordedAt":"2026-10-11T23:47:29.107019Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\nUse your workflow tool to launch a workflow with exactly TWO agents: one labeled 'ping' that replies with the word PING, and one labeled 'pong' that replies with the word PONG. Launch it and end your turn; do not wait for it.","displayText":"Use your workflow tool to launch a workflow with exactly TWO agents: one labeled 'ping' that replies with the word PING, and one labeled 'pong' that replies with the word PONG. Launch it and end your turn; do not wait for it.","commandId":"01a12d5d-42c3-7000-ab94-c7f56ea457e5"}},"emittedAtMs":1791762449131}} {"type":"emit_inbound","label":"item/started","frame":{"jsonrpc":"2.0","method":"item/started","params":{"sessionId":"01a12d5d-405f-7000-89a3-5aa62af6ea23","viewCursor":"v:01a12d5d-405f-7000-89a3-5aa62af6ea23:7","sourceRange":{"stream":{"kind":"session","id":"01a12d5d-405f-7000-89a3-5aa62af6ea23"},"first":{"id":"95574bfe-853f-44cc-81f6-88b05d6c8c16","sequence":38},"last":{"id":"95574bfe-853f-44cc-81f6-88b05d6c8c16","sequence":38}},"item":{"itemId":"95574bfe-853f-44cc-81f6-88b05d6c8c16","kind":"reminderChild","turnId":"01a12d5d-42c3-7000-ab94-c7f56ea457e5","revision":1,"status":"inProgress","recordedAt":"2026-10-11T23:47:29.328939Z","fallbackText":"Reminder child session","childSessionId":"b16dbb52-7f62-4a5a-84c2-f68d7ea22b18","reminderAgentId":"skill-reminder","generationId":1,"taskId":"01a12d5d-4375-7d72-b5b2-4b096d0df507"}},"emittedAtMs":1791762449336}} {"type":"emit_inbound","label":"item/started","frame":{"jsonrpc":"2.0","method":"item/started","params":{"sessionId":"01a12d5d-405f-7000-89a3-5aa62af6ea23","viewCursor":"v:01a12d5d-405f-7000-89a3-5aa62af6ea23:7.1","item":{"itemId":"3ce724bc-dacf-400e-af9a-995104717cb1","kind":"reasoning","turnId":"01a12d5d-42c3-7000-ab94-c7f56ea457e5","revision":1,"status":"inProgress","summary":[""]}},"emittedAtMs":1791762451554}} {"type":"emit_inbound","label":"item/delta","frame":{"jsonrpc":"2.0","method":"item/delta","params":{"sessionId":"01a12d5d-405f-7000-89a3-5aa62af6ea23","viewCursor":"v:01a12d5d-405f-7000-89a3-5aa62af6ea23:7.2","itemId":"3ce724bc-dacf-400e-af9a-995104717cb1","field":"summary.0","delta":"Launching a two-agent ping-pong workflow via the workflow tool while skipping skill reading for a trivial task."},"emittedAtMs":1791762451554}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/simple/muse_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/simple/muse_transcript.ndjson index 6f577c17671bb..e8299c5796054 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/simple/muse_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/simple/muse_transcript.ndjson @@ -7,13 +7,13 @@ {"type":"emit_inbound","label":"session/started","frame":{"jsonrpc":"2.0","method":"session/started","params":{"session":{"sessionId":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5","path":"~/.local/share/muse/sessions/2026/10/08/01a11a6a-bbb5-7000-ad0b-0c9e728406e5/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-08T07:29:25.018803Z","updatedAt":"2026-10-08T07:29:25.018807Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"approvalMode":{"mode":"allowAll","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"}},"emittedAtMs":1791444565334}} {"type":"emit_inbound","label":"response:session/start","frame":{"jsonrpc":"2.0","id":2,"result":{"session":{"sessionId":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5","path":"~/.local/share/muse/sessions/2026/10/08/01a11a6a-bbb5-7000-ad0b-0c9e728406e5/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-08T07:29:25.018803Z","updatedAt":"2026-10-08T07:29:25.018807Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"approvalMode":{"mode":"allowAll","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"},"viewCursor":"v:01a11a6a-bbb5-7000-ad0b-0c9e728406e5:1"}}} {"type":"emit_inbound","label":"session/approvalModeChanged","frame":{"jsonrpc":"2.0","method":"session/approvalModeChanged","params":{"sessionId":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5","viewCursor":"v:01a11a6a-bbb5-7000-ad0b-0c9e728406e5:1","sourceRange":{"stream":{"kind":"session","id":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5"},"first":{"id":"cfd043e8-8728-493d-ba28-252ef91e8a80","sequence":5},"last":{"id":"cfd043e8-8728-493d-ba28-252ef91e8a80","sequence":5}},"mode":"allowAll","source":"approvalReconfigure","commandId":"01a11a6a-bbb6-7000-b1a4-a01ea59676ef","clientName":"t3_code"},"emittedAtMs":1791444565340}} -{"type":"expect_outbound","label":"turn/start","frame":{"jsonrpc":"2.0","id":3,"method":"turn/start","params":{"sessionId":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5","input":[{"type":"text","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\n"},{"type":"text","text":"Respond with the following text: fixture simple ok"}],"displayText":"Respond with the following text: fixture simple ok","workspaceRoots":[""],"ifBusy":"queue","reasoningEffort":"high","commandId":"01a11a6a-be41-7000-8db9-1d84c1b8be48"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"jsonrpc":"2.0","id":3,"method":"turn/start","params":{"sessionId":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5","input":[{"type":"text","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\n"},{"type":"text","text":"Respond with the following text: fixture simple ok"}],"displayText":"Respond with the following text: fixture simple ok","workspaceRoots":[""],"ifBusy":"queue","reasoningEffort":"high","commandId":"01a11a6a-be41-7000-8db9-1d84c1b8be48"}}} {"type":"emit_inbound","label":"session/branchChanged","frame":{"jsonrpc":"2.0","method":"session/branchChanged","params":{"sessionId":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5","viewCursor":"v:01a11a6a-bbb5-7000-ad0b-0c9e728406e5:2","sourceRange":{"stream":{"kind":"session","id":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5"},"first":{"id":"0f64f4ea-a08c-43e1-af53-cf85cee1a11c","sequence":16},"last":{"id":"0f64f4ea-a08c-43e1-af53-cf85cee1a11c","sequence":16}},"workspaceRoot":"","branch":"main","vcs":"git"},"emittedAtMs":1791444565612}} {"type":"emit_inbound","label":"response:turn/start","frame":{"jsonrpc":"2.0","id":3,"result":{"commandId":"01a11a6a-be41-7000-8db9-1d84c1b8be48","status":"accepted","turnId":"01a11a6a-be41-7000-8db9-1d84c1b8be48","startedNewTurn":true,"disposition":"started"}}} {"type":"emit_inbound","label":"session/statusChanged","frame":{"jsonrpc":"2.0","method":"session/statusChanged","params":{"sessionId":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5","status":"running","viewCursor":"v:01a11a6a-bbb5-7000-ad0b-0c9e728406e5:3"},"emittedAtMs":1791444565635}} {"type":"emit_inbound","label":"turn/started","frame":{"jsonrpc":"2.0","method":"turn/started","params":{"sessionId":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5","viewCursor":"v:01a11a6a-bbb5-7000-ad0b-0c9e728406e5:3","sourceRange":{"stream":{"kind":"session","id":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5"},"first":{"id":"1f33a521-7829-4cc3-97db-a3b5a6e7deaf","sequence":18},"last":{"id":"1f33a521-7829-4cc3-97db-a3b5a6e7deaf","sequence":18}},"turnId":"01a11a6a-be41-7000-8db9-1d84c1b8be48","commandId":"01a11a6a-be41-7000-8db9-1d84c1b8be48"},"emittedAtMs":1791444565635}} -{"type":"emit_inbound","label":"item/completed","frame":{"jsonrpc":"2.0","method":"item/completed","params":{"sessionId":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5","viewCursor":"v:01a11a6a-bbb5-7000-ad0b-0c9e728406e5:4","sourceRange":{"stream":{"kind":"session","id":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5"},"first":{"id":"1f33a521-7829-4cc3-97db-a3b5a6e7deaf","sequence":18},"last":{"id":"1f33a521-7829-4cc3-97db-a3b5a6e7deaf","sequence":18}},"item":{"itemId":"23294b54-8e67-4896-a7f3-681119e1ddbe","kind":"userMessage","turnId":"01a11a6a-be41-7000-8db9-1d84c1b8be48","revision":1,"status":"completed","recordedAt":"2026-10-08T07:29:25.627042Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nRespond with the following text: fixture simple ok","commandId":"01a11a6a-be41-7000-8db9-1d84c1b8be48"}},"emittedAtMs":1791444565635}} -{"type":"emit_inbound","label":"item/updated","frame":{"jsonrpc":"2.0","method":"item/updated","params":{"sessionId":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5","viewCursor":"v:01a11a6a-bbb5-7000-ad0b-0c9e728406e5:5","sourceRange":{"stream":{"kind":"session","id":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5"},"first":{"id":"8c00aa21-7809-4cb2-89f7-b499aaa8746d","sequence":20},"last":{"id":"8c00aa21-7809-4cb2-89f7-b499aaa8746d","sequence":20}},"item":{"itemId":"23294b54-8e67-4896-a7f3-681119e1ddbe","kind":"userMessage","turnId":"01a11a6a-be41-7000-8db9-1d84c1b8be48","revision":2,"status":"completed","recordedAt":"2026-10-08T07:29:25.643029Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nRespond with the following text: fixture simple ok","displayText":"Respond with the following text: fixture simple ok","commandId":"01a11a6a-be41-7000-8db9-1d84c1b8be48"}},"emittedAtMs":1791444565652}} +{"type":"emit_inbound","label":"item/completed","frame":{"jsonrpc":"2.0","method":"item/completed","params":{"sessionId":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5","viewCursor":"v:01a11a6a-bbb5-7000-ad0b-0c9e728406e5:4","sourceRange":{"stream":{"kind":"session","id":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5"},"first":{"id":"1f33a521-7829-4cc3-97db-a3b5a6e7deaf","sequence":18},"last":{"id":"1f33a521-7829-4cc3-97db-a3b5a6e7deaf","sequence":18}},"item":{"itemId":"23294b54-8e67-4896-a7f3-681119e1ddbe","kind":"userMessage","turnId":"01a11a6a-be41-7000-8db9-1d84c1b8be48","revision":1,"status":"completed","recordedAt":"2026-10-08T07:29:25.627042Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\nRespond with the following text: fixture simple ok","commandId":"01a11a6a-be41-7000-8db9-1d84c1b8be48"}},"emittedAtMs":1791444565635}} +{"type":"emit_inbound","label":"item/updated","frame":{"jsonrpc":"2.0","method":"item/updated","params":{"sessionId":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5","viewCursor":"v:01a11a6a-bbb5-7000-ad0b-0c9e728406e5:5","sourceRange":{"stream":{"kind":"session","id":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5"},"first":{"id":"8c00aa21-7809-4cb2-89f7-b499aaa8746d","sequence":20},"last":{"id":"8c00aa21-7809-4cb2-89f7-b499aaa8746d","sequence":20}},"item":{"itemId":"23294b54-8e67-4896-a7f3-681119e1ddbe","kind":"userMessage","turnId":"01a11a6a-be41-7000-8db9-1d84c1b8be48","revision":2,"status":"completed","recordedAt":"2026-10-08T07:29:25.643029Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\nRespond with the following text: fixture simple ok","displayText":"Respond with the following text: fixture simple ok","commandId":"01a11a6a-be41-7000-8db9-1d84c1b8be48"}},"emittedAtMs":1791444565652}} {"type":"emit_inbound","label":"item/started","frame":{"jsonrpc":"2.0","method":"item/started","params":{"sessionId":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5","viewCursor":"v:01a11a6a-bbb5-7000-ad0b-0c9e728406e5:6","sourceRange":{"stream":{"kind":"session","id":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5"},"first":{"id":"ed1680a5-6f99-4b0f-b9ea-d12193f0de1f","sequence":37},"last":{"id":"ed1680a5-6f99-4b0f-b9ea-d12193f0de1f","sequence":37}},"item":{"itemId":"ed1680a5-6f99-4b0f-b9ea-d12193f0de1f","kind":"reminderChild","turnId":"01a11a6a-be41-7000-8db9-1d84c1b8be48","revision":1,"status":"inProgress","recordedAt":"2026-10-08T07:29:25.781511Z","fallbackText":"Reminder child session","childSessionId":"9785bf9d-382d-4781-ab3b-3817c9e6a604","reminderAgentId":"skill-reminder","generationId":1,"taskId":"01a11a6a-bef1-7032-974a-059b8765c487"}},"emittedAtMs":1791444565789}} {"type":"emit_inbound","label":"item/started","frame":{"jsonrpc":"2.0","method":"item/started","params":{"sessionId":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5","viewCursor":"v:01a11a6a-bbb5-7000-ad0b-0c9e728406e5:6.1","item":{"itemId":"0a68e576-f554-4700-8853-a68ad2b7179b","kind":"agentMessage","turnId":"01a11a6a-be41-7000-8db9-1d84c1b8be48","revision":1,"status":"inProgress","text":""}},"emittedAtMs":1791444567707}} {"type":"emit_inbound","label":"item/delta","frame":{"jsonrpc":"2.0","method":"item/delta","params":{"sessionId":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5","viewCursor":"v:01a11a6a-bbb5-7000-ad0b-0c9e728406e5:6.2","itemId":"0a68e576-f554-4700-8853-a68ad2b7179b","field":"text","delta":"fixture simple ok"},"emittedAtMs":1791444567707}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/muse_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/muse_transcript.ndjson index 47f3e6ab24461..ad2bd13e75b6f 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/muse_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/muse_transcript.ndjson @@ -7,13 +7,13 @@ {"type":"emit_inbound","label":"session/started","frame":{"jsonrpc":"2.0","method":"session/started","params":{"session":{"sessionId":"01a12d17-75fa-7000-9157-e8365ce94492","path":"~/.local/share/muse/sessions/2026/10/11/01a12d17-75fa-7000-9157-e8365ce94492/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-11T22:31:14.73121Z","updatedAt":"2026-10-11T22:31:14.731214Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"sideFrom":null,"approvalMode":{"mode":"allowAll","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"}},"emittedAtMs":1791757874894}} {"type":"emit_inbound","label":"response:session/start","frame":{"jsonrpc":"2.0","id":2,"result":{"session":{"sessionId":"01a12d17-75fa-7000-9157-e8365ce94492","path":"~/.local/share/muse/sessions/2026/10/11/01a12d17-75fa-7000-9157-e8365ce94492/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-11T22:31:14.73121Z","updatedAt":"2026-10-11T22:31:14.731214Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"sideFrom":null,"approvalMode":{"mode":"allowAll","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"},"viewCursor":"v:01a12d17-75fa-7000-9157-e8365ce94492:1"}}} {"type":"emit_inbound","label":"session/approvalModeChanged","frame":{"jsonrpc":"2.0","method":"session/approvalModeChanged","params":{"sessionId":"01a12d17-75fa-7000-9157-e8365ce94492","viewCursor":"v:01a12d17-75fa-7000-9157-e8365ce94492:1","sourceRange":{"stream":{"kind":"session","id":"01a12d17-75fa-7000-9157-e8365ce94492"},"first":{"id":"94d1e1ed-1d3e-4cd5-91bf-a51394fc8a0a","sequence":5},"last":{"id":"94d1e1ed-1d3e-4cd5-91bf-a51394fc8a0a","sequence":5}},"mode":"allowAll","source":"approvalReconfigure","commandId":"01a12d17-75fa-7001-a940-79b5d7c648a4","clientName":"t3_code"},"emittedAtMs":1791757874898}} -{"type":"expect_outbound","label":"turn/start","frame":{"jsonrpc":"2.0","id":3,"method":"turn/start","params":{"sessionId":"01a12d17-75fa-7000-9157-e8365ce94492","input":[{"type":"text","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\n"},{"type":"text","text":"Spawn one subagent whose only task is to reply with exactly: Hello. Wait for it to finish, then reply with exactly what it said."}],"displayText":"Spawn one subagent whose only task is to reply with exactly: Hello. Wait for it to finish, then reply with exactly what it said.","workspaceRoots":[""],"ifBusy":"queue","reasoningEffort":"high","commandId":"01a12d17-7790-7000-967d-3f2246f38a60"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"jsonrpc":"2.0","id":3,"method":"turn/start","params":{"sessionId":"01a12d17-75fa-7000-9157-e8365ce94492","input":[{"type":"text","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\n"},{"type":"text","text":"Spawn one subagent whose only task is to reply with exactly: Hello. Wait for it to finish, then reply with exactly what it said."}],"displayText":"Spawn one subagent whose only task is to reply with exactly: Hello. Wait for it to finish, then reply with exactly what it said.","workspaceRoots":[""],"ifBusy":"queue","reasoningEffort":"high","commandId":"01a12d17-7790-7000-967d-3f2246f38a60"}}} {"type":"emit_inbound","label":"session/branchChanged","frame":{"jsonrpc":"2.0","method":"session/branchChanged","params":{"sessionId":"01a12d17-75fa-7000-9157-e8365ce94492","viewCursor":"v:01a12d17-75fa-7000-9157-e8365ce94492:2","sourceRange":{"stream":{"kind":"session","id":"01a12d17-75fa-7000-9157-e8365ce94492"},"first":{"id":"1dc98410-05c3-4618-a431-3638055e20df","sequence":15},"last":{"id":"1dc98410-05c3-4618-a431-3638055e20df","sequence":15}},"workspaceRoot":"","branch":"main","vcs":"git"},"emittedAtMs":1791757875120}} {"type":"emit_inbound","label":"response:turn/start","frame":{"jsonrpc":"2.0","id":3,"result":{"commandId":"01a12d17-7790-7000-967d-3f2246f38a60","status":"accepted","turnId":"01a12d17-7790-7000-967d-3f2246f38a60","startedNewTurn":true,"disposition":"started"}}} {"type":"emit_inbound","label":"session/statusChanged","frame":{"jsonrpc":"2.0","method":"session/statusChanged","params":{"sessionId":"01a12d17-75fa-7000-9157-e8365ce94492","status":"running","viewCursor":"v:01a12d17-75fa-7000-9157-e8365ce94492:3"},"emittedAtMs":1791757875131}} {"type":"emit_inbound","label":"turn/started","frame":{"jsonrpc":"2.0","method":"turn/started","params":{"sessionId":"01a12d17-75fa-7000-9157-e8365ce94492","viewCursor":"v:01a12d17-75fa-7000-9157-e8365ce94492:3","sourceRange":{"stream":{"kind":"session","id":"01a12d17-75fa-7000-9157-e8365ce94492"},"first":{"id":"766cb840-a6f1-41f2-8c7e-8c372d0470cd","sequence":17},"last":{"id":"766cb840-a6f1-41f2-8c7e-8c372d0470cd","sequence":17}},"turnId":"01a12d17-7790-7000-967d-3f2246f38a60","commandId":"01a12d17-7790-7000-967d-3f2246f38a60"},"emittedAtMs":1791757875132}} -{"type":"emit_inbound","label":"item/completed","frame":{"jsonrpc":"2.0","method":"item/completed","params":{"sessionId":"01a12d17-75fa-7000-9157-e8365ce94492","viewCursor":"v:01a12d17-75fa-7000-9157-e8365ce94492:4","sourceRange":{"stream":{"kind":"session","id":"01a12d17-75fa-7000-9157-e8365ce94492"},"first":{"id":"766cb840-a6f1-41f2-8c7e-8c372d0470cd","sequence":17},"last":{"id":"766cb840-a6f1-41f2-8c7e-8c372d0470cd","sequence":17}},"item":{"itemId":"95c179c8-e8f8-4629-80df-e28243a234ea","kind":"userMessage","turnId":"01a12d17-7790-7000-967d-3f2246f38a60","revision":1,"status":"completed","recordedAt":"2026-10-11T22:31:15.120499Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nSpawn one subagent whose only task is to reply with exactly: Hello. Wait for it to finish, then reply with exactly what it said.","commandId":"01a12d17-7790-7000-967d-3f2246f38a60"}},"emittedAtMs":1791757875132}} -{"type":"emit_inbound","label":"item/updated","frame":{"jsonrpc":"2.0","method":"item/updated","params":{"sessionId":"01a12d17-75fa-7000-9157-e8365ce94492","viewCursor":"v:01a12d17-75fa-7000-9157-e8365ce94492:5","sourceRange":{"stream":{"kind":"session","id":"01a12d17-75fa-7000-9157-e8365ce94492"},"first":{"id":"dcf03486-5149-4377-b325-dea3e118628a","sequence":19},"last":{"id":"dcf03486-5149-4377-b325-dea3e118628a","sequence":19}},"item":{"itemId":"95c179c8-e8f8-4629-80df-e28243a234ea","kind":"userMessage","turnId":"01a12d17-7790-7000-967d-3f2246f38a60","revision":2,"status":"completed","recordedAt":"2026-10-11T22:31:15.136047Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nSpawn one subagent whose only task is to reply with exactly: Hello. Wait for it to finish, then reply with exactly what it said.","displayText":"Spawn one subagent whose only task is to reply with exactly: Hello. Wait for it to finish, then reply with exactly what it said.","commandId":"01a12d17-7790-7000-967d-3f2246f38a60"}},"emittedAtMs":1791757875144}} +{"type":"emit_inbound","label":"item/completed","frame":{"jsonrpc":"2.0","method":"item/completed","params":{"sessionId":"01a12d17-75fa-7000-9157-e8365ce94492","viewCursor":"v:01a12d17-75fa-7000-9157-e8365ce94492:4","sourceRange":{"stream":{"kind":"session","id":"01a12d17-75fa-7000-9157-e8365ce94492"},"first":{"id":"766cb840-a6f1-41f2-8c7e-8c372d0470cd","sequence":17},"last":{"id":"766cb840-a6f1-41f2-8c7e-8c372d0470cd","sequence":17}},"item":{"itemId":"95c179c8-e8f8-4629-80df-e28243a234ea","kind":"userMessage","turnId":"01a12d17-7790-7000-967d-3f2246f38a60","revision":1,"status":"completed","recordedAt":"2026-10-11T22:31:15.120499Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\nSpawn one subagent whose only task is to reply with exactly: Hello. Wait for it to finish, then reply with exactly what it said.","commandId":"01a12d17-7790-7000-967d-3f2246f38a60"}},"emittedAtMs":1791757875132}} +{"type":"emit_inbound","label":"item/updated","frame":{"jsonrpc":"2.0","method":"item/updated","params":{"sessionId":"01a12d17-75fa-7000-9157-e8365ce94492","viewCursor":"v:01a12d17-75fa-7000-9157-e8365ce94492:5","sourceRange":{"stream":{"kind":"session","id":"01a12d17-75fa-7000-9157-e8365ce94492"},"first":{"id":"dcf03486-5149-4377-b325-dea3e118628a","sequence":19},"last":{"id":"dcf03486-5149-4377-b325-dea3e118628a","sequence":19}},"item":{"itemId":"95c179c8-e8f8-4629-80df-e28243a234ea","kind":"userMessage","turnId":"01a12d17-7790-7000-967d-3f2246f38a60","revision":2,"status":"completed","recordedAt":"2026-10-11T22:31:15.136047Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\nSpawn one subagent whose only task is to reply with exactly: Hello. Wait for it to finish, then reply with exactly what it said.","displayText":"Spawn one subagent whose only task is to reply with exactly: Hello. Wait for it to finish, then reply with exactly what it said.","commandId":"01a12d17-7790-7000-967d-3f2246f38a60"}},"emittedAtMs":1791757875144}} {"type":"emit_inbound","label":"item/started","frame":{"jsonrpc":"2.0","method":"item/started","params":{"sessionId":"01a12d17-75fa-7000-9157-e8365ce94492","viewCursor":"v:01a12d17-75fa-7000-9157-e8365ce94492:6","sourceRange":{"stream":{"kind":"session","id":"01a12d17-75fa-7000-9157-e8365ce94492"},"first":{"id":"599a220a-d212-4a81-a60d-7284ff290284","sequence":36},"last":{"id":"599a220a-d212-4a81-a60d-7284ff290284","sequence":36}},"item":{"itemId":"599a220a-d212-4a81-a60d-7284ff290284","kind":"reminderChild","turnId":"01a12d17-7790-7000-967d-3f2246f38a60","revision":1,"status":"inProgress","recordedAt":"2026-10-11T22:31:15.249949Z","fallbackText":"Reminder child session","childSessionId":"0b3f4f01-850a-43bd-af36-9b011699354f","reminderAgentId":"skill-reminder","generationId":1,"taskId":"01a12d17-7819-7212-8057-3558c2bdd46d"}},"emittedAtMs":1791757875258}} {"type":"emit_inbound","label":"session/tokenUsage","frame":{"jsonrpc":"2.0","method":"session/tokenUsage","params":{"sessionId":"01a12d17-75fa-7000-9157-e8365ce94492","viewCursor":"v:01a12d17-75fa-7000-9157-e8365ce94492:7","sourceRange":{"stream":{"kind":"session","id":"01a12d17-75fa-7000-9157-e8365ce94492"},"first":{"id":"9198dd8d-eede-487a-9109-a48d2563c371","sequence":51},"last":{"id":"9198dd8d-eede-487a-9109-a48d2563c371","sequence":51}},"turnId":"01a12d17-7790-7000-967d-3f2246f38a60","modelId":"muse-spark-1.3-contributor","usage":{"inputTokens":32900,"outputTokens":129,"cachedTokens":0,"cacheWriteTokens":0,"cacheReadTokens":0,"reasoningTokens":36},"promptTokens":32900,"totalTokens":33029,"finishReason":"tool_calls","durationMs":2354,"cumulative":{"promptTokens":32900,"outputTokens":129,"totalTokens":33029,"cost":{"usd":0.0033158000000000003,"partial":false}}},"emittedAtMs":1791757877764}} {"type":"emit_inbound","label":"session/contextUsage","frame":{"jsonrpc":"2.0","method":"session/contextUsage","params":{"sessionId":"01a12d17-75fa-7000-9157-e8365ce94492","viewCursor":"v:01a12d17-75fa-7000-9157-e8365ce94492:8","sourceRange":{"stream":{"kind":"session","id":"01a12d17-75fa-7000-9157-e8365ce94492"},"first":{"id":"9198dd8d-eede-487a-9109-a48d2563c371","sequence":51},"last":{"id":"9198dd8d-eede-487a-9109-a48d2563c371","sequence":51}},"windowTokens":1007997,"usedTokens":33029,"pressure":"normal"},"emittedAtMs":1791757877764}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/muse_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/muse_transcript.ndjson index 8a87c41eae4fa..12394dd806314 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/muse_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/muse_transcript.ndjson @@ -7,14 +7,14 @@ {"type":"emit_inbound","label":"session/started","frame":{"jsonrpc":"2.0","method":"session/started","params":{"session":{"sessionId":"01a11a6d-2d3d-7000-8178-411fdb90bc34","path":"~/.local/share/muse/sessions/2026/10/08/01a11a6d-2d3d-7000-8178-411fdb90bc34/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-08T07:32:05.094285Z","updatedAt":"2026-10-08T07:32:05.094289Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"approvalMode":{"mode":"allowAll","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"}},"emittedAtMs":1791444725265}} {"type":"emit_inbound","label":"response:session/start","frame":{"jsonrpc":"2.0","id":2,"result":{"session":{"sessionId":"01a11a6d-2d3d-7000-8178-411fdb90bc34","path":"~/.local/share/muse/sessions/2026/10/08/01a11a6d-2d3d-7000-8178-411fdb90bc34/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-08T07:32:05.094285Z","updatedAt":"2026-10-08T07:32:05.094289Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"approvalMode":{"mode":"allowAll","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"},"viewCursor":"v:01a11a6d-2d3d-7000-8178-411fdb90bc34:1"}}} {"type":"emit_inbound","label":"session/approvalModeChanged","frame":{"jsonrpc":"2.0","method":"session/approvalModeChanged","params":{"sessionId":"01a11a6d-2d3d-7000-8178-411fdb90bc34","viewCursor":"v:01a11a6d-2d3d-7000-8178-411fdb90bc34:1","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-2d3d-7000-8178-411fdb90bc34"},"first":{"id":"9865268e-0a39-43a0-89d0-251a820ec8a3","sequence":5},"last":{"id":"9865268e-0a39-43a0-89d0-251a820ec8a3","sequence":5}},"mode":"allowAll","source":"approvalReconfigure","commandId":"01a11a6d-2d3e-7000-b0e7-f04c53ee070b","clientName":"t3_code"},"emittedAtMs":1791444725268}} -{"type":"expect_outbound","label":"turn/start","frame":{"jsonrpc":"2.0","id":3,"method":"turn/start","params":{"sessionId":"01a11a6d-2d3d-7000-8178-411fdb90bc34","input":[{"type":"text","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\n"},{"type":"text","text":"Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally."}],"displayText":"Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally.","workspaceRoots":[""],"ifBusy":"queue","reasoningEffort":"high","commandId":"01a11a6d-2ee0-7000-be19-f20eda7ce5d5"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"jsonrpc":"2.0","id":3,"method":"turn/start","params":{"sessionId":"01a11a6d-2d3d-7000-8178-411fdb90bc34","input":[{"type":"text","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\n"},{"type":"text","text":"Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally."}],"displayText":"Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally.","workspaceRoots":[""],"ifBusy":"queue","reasoningEffort":"high","commandId":"01a11a6d-2ee0-7000-be19-f20eda7ce5d5"}}} {"type":"emit_inbound","label":"session/branchChanged","frame":{"jsonrpc":"2.0","method":"session/branchChanged","params":{"sessionId":"01a11a6d-2d3d-7000-8178-411fdb90bc34","viewCursor":"v:01a11a6d-2d3d-7000-8178-411fdb90bc34:2","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-2d3d-7000-8178-411fdb90bc34"},"first":{"id":"531b0e9e-c96d-4fa5-a6dd-5cc7d4569543","sequence":16},"last":{"id":"531b0e9e-c96d-4fa5-a6dd-5cc7d4569543","sequence":16}},"workspaceRoot":"","branch":"main","vcs":"git"},"emittedAtMs":1791444725509}} {"type":"emit_inbound","label":"response:turn/start","frame":{"jsonrpc":"2.0","id":3,"result":{"commandId":"01a11a6d-2ee0-7000-be19-f20eda7ce5d5","status":"accepted","turnId":"01a11a6d-2ee0-7000-be19-f20eda7ce5d5","startedNewTurn":true,"disposition":"started"}}} {"type":"expect_outbound","label":"turn/interrupt","frame":{"jsonrpc":"2.0","id":4,"method":"turn/interrupt","params":{"sessionId":"01a11a6d-2d3d-7000-8178-411fdb90bc34","turnId":"01a11a6d-2ee0-7000-be19-f20eda7ce5d5","commandId":"01a11a6d-2f0b-7000-a1d4-359cf54e471a"}}} {"type":"emit_inbound","label":"session/statusChanged","frame":{"jsonrpc":"2.0","method":"session/statusChanged","params":{"sessionId":"01a11a6d-2d3d-7000-8178-411fdb90bc34","status":"running","viewCursor":"v:01a11a6d-2d3d-7000-8178-411fdb90bc34:3"},"emittedAtMs":1791444725522}} {"type":"emit_inbound","label":"turn/started","frame":{"jsonrpc":"2.0","method":"turn/started","params":{"sessionId":"01a11a6d-2d3d-7000-8178-411fdb90bc34","viewCursor":"v:01a11a6d-2d3d-7000-8178-411fdb90bc34:3","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-2d3d-7000-8178-411fdb90bc34"},"first":{"id":"50d1fd8c-232b-47b9-9bfa-9b543961bbc9","sequence":18},"last":{"id":"50d1fd8c-232b-47b9-9bfa-9b543961bbc9","sequence":18}},"turnId":"01a11a6d-2ee0-7000-be19-f20eda7ce5d5","commandId":"01a11a6d-2ee0-7000-be19-f20eda7ce5d5"},"emittedAtMs":1791444725523}} -{"type":"emit_inbound","label":"item/completed","frame":{"jsonrpc":"2.0","method":"item/completed","params":{"sessionId":"01a11a6d-2d3d-7000-8178-411fdb90bc34","viewCursor":"v:01a11a6d-2d3d-7000-8178-411fdb90bc34:4","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-2d3d-7000-8178-411fdb90bc34"},"first":{"id":"50d1fd8c-232b-47b9-9bfa-9b543961bbc9","sequence":18},"last":{"id":"50d1fd8c-232b-47b9-9bfa-9b543961bbc9","sequence":18}},"item":{"itemId":"cfa989ad-2359-4da2-9fca-562855cc0ae8","kind":"userMessage","turnId":"01a11a6d-2ee0-7000-be19-f20eda7ce5d5","revision":1,"status":"completed","recordedAt":"2026-10-08T07:32:05.510508Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nDo not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally.","commandId":"01a11a6d-2ee0-7000-be19-f20eda7ce5d5"}},"emittedAtMs":1791444725523}} -{"type":"emit_inbound","label":"item/updated","frame":{"jsonrpc":"2.0","method":"item/updated","params":{"sessionId":"01a11a6d-2d3d-7000-8178-411fdb90bc34","viewCursor":"v:01a11a6d-2d3d-7000-8178-411fdb90bc34:5","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-2d3d-7000-8178-411fdb90bc34"},"first":{"id":"5db75d92-0e52-4bce-bb81-40e254b40bc3","sequence":20},"last":{"id":"5db75d92-0e52-4bce-bb81-40e254b40bc3","sequence":20}},"item":{"itemId":"cfa989ad-2359-4da2-9fca-562855cc0ae8","kind":"userMessage","turnId":"01a11a6d-2ee0-7000-be19-f20eda7ce5d5","revision":2,"status":"completed","recordedAt":"2026-10-08T07:32:05.530992Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nDo not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally.","displayText":"Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally.","commandId":"01a11a6d-2ee0-7000-be19-f20eda7ce5d5"}},"emittedAtMs":1791444725539}} +{"type":"emit_inbound","label":"item/completed","frame":{"jsonrpc":"2.0","method":"item/completed","params":{"sessionId":"01a11a6d-2d3d-7000-8178-411fdb90bc34","viewCursor":"v:01a11a6d-2d3d-7000-8178-411fdb90bc34:4","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-2d3d-7000-8178-411fdb90bc34"},"first":{"id":"50d1fd8c-232b-47b9-9bfa-9b543961bbc9","sequence":18},"last":{"id":"50d1fd8c-232b-47b9-9bfa-9b543961bbc9","sequence":18}},"item":{"itemId":"cfa989ad-2359-4da2-9fca-562855cc0ae8","kind":"userMessage","turnId":"01a11a6d-2ee0-7000-be19-f20eda7ce5d5","revision":1,"status":"completed","recordedAt":"2026-10-08T07:32:05.510508Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\nDo not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally.","commandId":"01a11a6d-2ee0-7000-be19-f20eda7ce5d5"}},"emittedAtMs":1791444725523}} +{"type":"emit_inbound","label":"item/updated","frame":{"jsonrpc":"2.0","method":"item/updated","params":{"sessionId":"01a11a6d-2d3d-7000-8178-411fdb90bc34","viewCursor":"v:01a11a6d-2d3d-7000-8178-411fdb90bc34:5","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-2d3d-7000-8178-411fdb90bc34"},"first":{"id":"5db75d92-0e52-4bce-bb81-40e254b40bc3","sequence":20},"last":{"id":"5db75d92-0e52-4bce-bb81-40e254b40bc3","sequence":20}},"item":{"itemId":"cfa989ad-2359-4da2-9fca-562855cc0ae8","kind":"userMessage","turnId":"01a11a6d-2ee0-7000-be19-f20eda7ce5d5","revision":2,"status":"completed","recordedAt":"2026-10-08T07:32:05.530992Z","text":"In case you're asked: you are running in T3 Code through the Muse Code harness, as muse-spark-1.3-contributor with high reasoning effort. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.\n\n\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\nDo not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally.","displayText":"Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally.","commandId":"01a11a6d-2ee0-7000-be19-f20eda7ce5d5"}},"emittedAtMs":1791444725539}} {"type":"emit_inbound","label":"item/started","frame":{"jsonrpc":"2.0","method":"item/started","params":{"sessionId":"01a11a6d-2d3d-7000-8178-411fdb90bc34","viewCursor":"v:01a11a6d-2d3d-7000-8178-411fdb90bc34:6","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-2d3d-7000-8178-411fdb90bc34"},"first":{"id":"ae604001-22b9-479c-a45b-3dcfed45996c","sequence":37},"last":{"id":"ae604001-22b9-479c-a45b-3dcfed45996c","sequence":37}},"item":{"itemId":"ae604001-22b9-479c-a45b-3dcfed45996c","kind":"reminderChild","turnId":"01a11a6d-2ee0-7000-be19-f20eda7ce5d5","revision":1,"status":"inProgress","recordedAt":"2026-10-08T07:32:05.638142Z","fallbackText":"Reminder child session","childSessionId":"1f58196a-6bf6-42da-9499-8f53a439e6e1","reminderAgentId":"skill-reminder","generationId":1,"taskId":"01a11a6d-2f65-70b1-bb8f-69b33bb4fc62"}},"emittedAtMs":1791444725646}} {"type":"emit_inbound","label":"response:turn/interrupt","frame":{"jsonrpc":"2.0","id":4,"result":{"commandId":"01a11a6d-2f0b-7000-a1d4-359cf54e471a","status":"accepted","turnId":"01a11a6d-2ee0-7000-be19-f20eda7ce5d5"}}} {"type":"emit_inbound","label":"item/completed","frame":{"jsonrpc":"2.0","method":"item/completed","params":{"sessionId":"01a11a6d-2d3d-7000-8178-411fdb90bc34","viewCursor":"v:01a11a6d-2d3d-7000-8178-411fdb90bc34:7","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-2d3d-7000-8178-411fdb90bc34"},"first":{"id":"ae604001-22b9-479c-a45b-3dcfed45996c","sequence":37},"last":{"id":"3962d8d1-4608-4dda-8fdc-39a1804474aa","sequence":50}},"item":{"itemId":"ae604001-22b9-479c-a45b-3dcfed45996c","kind":"reminderChild","turnId":"01a11a6d-2ee0-7000-be19-f20eda7ce5d5","revision":2,"status":"cancelled","recordedAt":"2026-10-08T07:32:05.727236Z","fallbackText":"Reminder child session","failureReason":"main run cancelled","childSessionId":"1f58196a-6bf6-42da-9499-8f53a439e6e1","reminderAgentId":"skill-reminder","generationId":1,"taskId":"01a11a6d-2f65-70b1-bb8f-69b33bb4fc62"}},"emittedAtMs":1791444725734}} diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 9c305c266f3dd..6658b3beaea3b 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { - "claudeSystemAppendBytes": 5930, - "codexAdditionalContextBytes": 7324, + "claudeSystemAppendBytes": 6037, + "codexAdditionalContextBytes": 7431, "mcpToolListJsonBytes": 52145 } diff --git a/evals/mcp-tool-use/README.md b/evals/mcp-tool-use/README.md index 25950e2098ee4..7004bcc65e163 100644 --- a/evals/mcp-tool-use/README.md +++ b/evals/mcp-tool-use/README.md @@ -28,7 +28,7 @@ Cases are JSON lines in `cases/`, one file per area. The case schema in `run.ts` - `experience`: the real mistake, in a sentence. `source`: where it happened. - `setup`: the fake thread, its `world` (repo, branch, files, PRs, pages), `priorTurns`, and `mocks` for tool results. With `world.backgroundTasks`, `t3_background_wait` answers from T3's own handler and ThreadManagementService, so its result and errors are the checkout's; a prior wait with `"result": "default"` gets that result too. - `setup.priorTurns[].toolCalls[].resultFile`: load a repository-relative file as the tool result instead of copying its contents into the case. An empty `prompt` resumes a top-level thread after its last prior tool result without adding a user message. Side-chat and subagent setups require a nonempty prompt. -- `expect`: the checks, such as `calls`, `callsMustNot`, `maxCalls`, `order`, `shellMust`, `textMust`, `finalTextMust` (the last text, once the turn ended), and `linked`. A call's `args` match partially: `~text` is a case-insensitive substring, `"<=N"` / `">=N"` bound a number, `null` matches a missing key, and keys may be dotted paths. Device cases also use `device` to check every child brief, forbid raw UI commands, bound failed device actions per user turn, and require artifact paths in completed final answers. Secrets cases use `secret` (see [Secrets cases](#secrets-cases)). +- `expect`: the checks, such as `calls`, `callsMustNot`, `maxCalls`, `order`, `shellMust`, `textMust`, `finalTextMust` (the last text, once the turn ended), and `linked`. A call's `args` match partially: `~text` is a case-insensitive substring, `"<=N"` / `">=N"` bound a number, `null` matches a missing key, and keys may be dotted paths. For `calls` and `callsMustNot`, `argsAnyOf` accepts any one of its partial argument objects, in addition to `args`. Only `calls` supports `success: true`, which requires a recorded successful result. `distinctCalls` supports only `tool` and `args`. Device cases also use `device` to check every child brief, forbid raw UI commands, bound failed device actions per user turn, and require artifact paths in completed final answers. Secrets cases use `secret` (see [Secrets cases](#secrets-cases)). Check that the case builds with `--dry-run --case `. Then run it on the text before your fix, where it must fail, and on the text after, where it must pass. diff --git a/evals/mcp-tool-use/cases/issues.ndjson b/evals/mcp-tool-use/cases/issues.ndjson new file mode 100644 index 0000000000000..b3c33cef640e9 --- /dev/null +++ b/evals/mcp-tool-use/cases/issues.ndjson @@ -0,0 +1,2 @@ +{"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"}} diff --git a/evals/mcp-tool-use/run.test.ts b/evals/mcp-tool-use/run.test.ts index ec1a121fee485..d754be92732e1 100644 --- a/evals/mcp-tool-use/run.test.ts +++ b/evals/mcp-tool-use/run.test.ts @@ -257,6 +257,55 @@ it("accepts any tool listed as an alternative", () => { assert.deepEqual(failed(expect, run("list_thread_pull_requests")), [ "calls link_pull_request|watch_pull_request", ]); + const issueCase = decodeDeviceCase( + NodeFS.readFileSync(new URL("./cases/issues.ndjson", import.meta.url), "utf8").split("\n")[0]!, + ); + for (const [input, passes] of [ + [{ url: "https://github.com/acme/app/issues/42" }, true], + [{ url: "https://github.com/acme/app/issues/42/" }, true], + [{ url: "https://github.com/acme/app/issues/42/", threadId: "issue-work-thread" }, true], + [{ url: "https://github.com/acme/app/issues/42/", threadId: "another-thread" }, false], + [{ key: "42", projectId: "app" }, true], + [{ key: "42" }, true], + [{ key: "42", threadId: "issue-work-thread" }, true], + [{ key: "42", threadId: "another-thread" }, false], + [{ key: "42", url: "https://github.com/acme/app/issues/43" }, false], + [{ url: "https://github.com/acme/app/issues/42", threadId: "issue-work-thread" }, true], + [{ key: "42", projectId: "app", threadId: "issue-work-thread" }, true], + [{ url: "https://github.com/acme/app/issues/42", threadId: "another-thread" }, false], + [{ key: "43", projectId: "app" }, false], + [{ key: "42", projectId: "other-project" }, false], + ] as const) { + assert.equal( + failed(issueCase.expect, { + ...run("link_issue"), + finalText: "Change Setings to Settings.", + calls: [{ step: 0, tool: "link_issue", input, failed: false }], + }).length === 0, + passes, + ); + } + assert.isNotEmpty( + failed(issueCase.expect, { + ...run("link_issue"), + finalText: "Change Setings to Settings.", + calls: [{ step: 0, tool: "link_issue", input: { key: "42" }, failed: true }], + }), + ); + assert.isNotEmpty( + failed(issueCase.expect, { + ...run("link_issue"), + finalText: "Linked the issue.", + calls: [{ step: 0, tool: "link_issue", input: { key: "42" }, failed: false }], + }), + ); + assert.isNotEmpty( + failed(issueCase.expect, { + ...run("link_issue"), + finalText: "Change Setings to Settings.", + calls: [{ step: 0, tool: "link_issue", input: { key: "42" } }], + }), + ); // A bound on alternatives counts their calls together. const both: SampleRun = { calls: ["preview_status", "preview_open"].map((tool) => ({ step: 0, tool, input: {} })), diff --git a/evals/mcp-tool-use/run.ts b/evals/mcp-tool-use/run.ts index b08cb8a490de3..d5879ae5c32ba 100644 --- a/evals/mcp-tool-use/run.ts +++ b/evals/mcp-tool-use/run.ts @@ -57,6 +57,7 @@ import { AttachmentToolkit } from "../../apps/server/src/mcp/toolkits/attachment import { DeviceToolkit } from "../../apps/server/src/mcp/toolkits/device/tools.ts"; import { EnvironmentToolkit } from "../../apps/server/src/mcp/toolkits/environment/tools.ts"; import { HtmlToolkit } from "../../apps/server/src/mcp/toolkits/html/tools.ts"; +import { IssuesToolkit } from "../../apps/server/src/mcp/toolkits/issues/tools.ts"; import { MessageToolkit } from "../../apps/server/src/mcp/toolkits/message/tools.ts"; import { OrchestratorToolkit } from "../../apps/server/src/mcp/toolkits/orchestrator/tools.ts"; import { PreviewToolkit } from "../../apps/server/src/mcp/toolkits/preview/tools.ts"; @@ -189,16 +190,24 @@ const McpToolUseCall = Schema.Struct({ tool: Schema.String, args: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)), }); -type McpToolUseCall = typeof McpToolUseCall.Type; +const McpToolUseCallWithAlternatives = Schema.Struct({ + ...McpToolUseCall.fields, + argsAnyOf: Schema.optional(Schema.Array(Schema.Record(Schema.String, Schema.Unknown))), +}); +const McpToolUseExpectedCall = Schema.Struct({ + ...McpToolUseCallWithAlternatives.fields, + success: Schema.optional(Schema.Literal(true)), +}); +type McpToolUseCall = typeof McpToolUseExpectedCall.Type; /** Grading rules. Tool names are bare: `delegate_task`, `Bash`, `Agent`. */ const McpToolUseExpect = Schema.Struct({ /** Each entry needs one matching call. */ - calls: Schema.optional(Schema.Array(McpToolUseCall)), + calls: Schema.optional(Schema.Array(McpToolUseExpectedCall)), /** Each entry matches a different call, and no call matches two entries; tool names are exact. */ distinctCalls: Schema.optional(Schema.Array(McpToolUseCall)), /** No call may match any entry. */ - callsMustNot: Schema.optional(Schema.Array(McpToolUseCall)), + callsMustNot: Schema.optional(Schema.Array(McpToolUseCallWithAlternatives)), notCalls: Schema.optional(Schema.Array(Schema.String)), /** First calls of these tools happen in this order. */ order: Schema.optional(Schema.Array(Schema.String)), @@ -458,6 +467,7 @@ const t3SourceTools: ReadonlyArray = [ WorktreeToolkit, PullRequestsToolkit, PreviewToolkit, + IssuesToolkit, DeviceToolkit, HtmlToolkit, MessageToolkit, @@ -1860,8 +1870,15 @@ export const gradeSample = ( // `tool` may list alternatives, as in "link_pull_request|watch_pull_request"; counts add up. const count = (tool: string) => calls.filter((call) => tool.split("|").includes(call.tool)).length; - const found = ({ tool, args = {} }: McpToolUseCall, among = calls) => - among.some((call) => tool.split("|").includes(call.tool) && matches(args, call.input)); + const found = ({ tool, args = {}, argsAnyOf, success }: McpToolUseCall, among = calls) => + among.some( + (call) => + tool.split("|").includes(call.tool) && + (success === undefined || call.failed === false) && + matches(args, call.input) && + (argsAnyOf === undefined || + argsAnyOf.some((alternative) => matches(alternative, call.input))), + ); const label = ({ tool, args }: McpToolUseCall) => (args ? `${tool} ${valueText(args)}` : tool); for (const call of expect.calls ?? []) add(`calls ${label(call)}`, found(call)); if (expect.distinctCalls !== undefined) { diff --git a/packages/provider-core/src/server/runtimeInstructions.test.ts b/packages/provider-core/src/server/runtimeInstructions.test.ts index bbc4aadb23f26..d60124ee168ca 100644 --- a/packages/provider-core/src/server/runtimeInstructions.test.ts +++ b/packages/provider-core/src/server/runtimeInstructions.test.ts @@ -19,6 +19,7 @@ describe("buildRuntimeInstructions", () => { assert.include(instructions, "Link each PR you create, take over, or push to"); assert.include(instructions, "every stack layer"); + assert.include(instructions, "link_issue"); assert.include(instructions, "Skip PRs you only read or review"); assert.include(instructions, "If linking fails, say so."); assert.notInclude(instructions, "git log -1"); diff --git a/packages/provider-core/src/server/runtimeInstructions.ts b/packages/provider-core/src/server/runtimeInstructions.ts index 3a956984f3227..12f5ea92609ab 100644 --- a/packages/provider-core/src/server/runtimeInstructions.ts +++ b/packages/provider-core/src/server/runtimeInstructions.ts @@ -1,6 +1,7 @@ /** Session-invariant; harnesses with a native system-prompt append can carry it once per session. */ export const PULL_REQUEST_LINKING_INSTRUCTIONS = ` Link each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch. +If available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read. `; /** Omit model and effort when the harness manages them dynamically. */ From 6927cfe2adb0867eb098009a5eb35e42da2b13a1 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 14:27:05 -0800 Subject: [PATCH 058/183] fix(web): dropped folders open on this computer's server when the desktop app's own environment is off (#38722) --- apps/desktop/src/app/DesktopApp.test.ts | 103 ++++++++++-------- apps/desktop/src/app/DesktopApp.ts | 11 +- apps/web/src/hooks/useDefaultTheme.ts | 8 +- apps/web/src/hooks/useHandleNewThread.test.ts | 31 ++++++ apps/web/src/hooks/useHandleNewThread.ts | 19 +++- apps/web/src/hooks/useOpenLocalWorkspace.ts | 28 ++--- apps/web/src/routes/__root.tsx | 6 +- apps/web/src/state/primaryEnvironment.test.ts | 16 +-- apps/web/src/state/primaryEnvironment.ts | 8 +- apps/web/src/state/server.ts | 4 +- apps/web/src/themeBackground.test.ts | 2 +- apps/web/src/themeBackground.ts | 4 +- 12 files changed, 151 insertions(+), 89 deletions(-) diff --git a/apps/desktop/src/app/DesktopApp.test.ts b/apps/desktop/src/app/DesktopApp.test.ts index 9cc3a187e83f3..8faaee8f41f18 100644 --- a/apps/desktop/src/app/DesktopApp.test.ts +++ b/apps/desktop/src/app/DesktopApp.test.ts @@ -84,6 +84,7 @@ interface StubbedDesktop { readonly backends?: ReadonlyArray<{ readonly stop: () => Effect.Effect }>; readonly flushRendererHistory?: Effect.Effect; readonly tokenRequested?: Deferred.Deferred; + readonly activationStarted?: Deferred.Deferred; } const runStubbedDesktop = (stub: StubbedDesktop) => @@ -189,7 +190,9 @@ const runStubbedDesktop = (stub: StubbedDesktop) => reconcile: Effect.void, } as DesktopWslBackend.DesktopWslBackend["Service"]), Effect.provideService(DesktopAppActivation.DesktopAppActivation, { - start: Effect.void, + start: stub.activationStarted + ? Deferred.succeed(stub.activationStarted, undefined) + : Effect.void, } as unknown as DesktopAppActivation.DesktopAppActivation["Service"]), Effect.provideService(DesktopRendererHistory.DesktopRendererHistory, { shutdown: stub.flushRendererHistory ?? Effect.void, @@ -323,52 +326,60 @@ it.effect.each([false, true])( }).pipe(Effect.provide(DesktopShutdown.layer)), ); -it.effect("points a stale t3 launcher at the updated AppImage with Local environment off", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-desktop-app-" }); - const launcher = DesktopCliShim.launcherPath({ - path, - baseDir, - platform: "linux", - } as DesktopEnvironment.DesktopEnvironment["Service"]); - const removedAppImage = path.join(baseDir, "T3-Code-0.1.6-x86_64.AppImage"); - const updatedAppImage = path.join(baseDir, "T3-Code-0.1.7-x86_64.AppImage"); - yield* fs.makeDirectory(path.dirname(launcher), { recursive: true }); - yield* fs.writeFileString( - launcher, - DesktopCliShim.renderCliShim({ - target: { kind: "appimage", appImage: removedAppImage, executableName: "t3code" }, - shimPath: launcher, - t3Home: baseDir, - }), - ); - yield* fs.writeFileString(updatedAppImage, "", { mode: 0o755 }); - const windowStarted = yield* Deferred.make(); - - const app = yield* runStubbedDesktop({ - localEnvironmentEnabled: false, - environment: { +it.effect( + "points a stale t3 launcher at the updated AppImage and accepts t3 with Local environment off", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-desktop-app-" }); + const launcher = DesktopCliShim.launcherPath({ path, baseDir, - serverRoot: path.join(baseDir, "resources", "app.asar"), - appImagePath: Option.some(updatedAppImage), - }, - fileSystem: Layer.succeed(FileSystem.FileSystem, fs), - record: () => Effect.void, - windowStarted, - registerLinuxUrlHandler: Effect.void, - }); - yield* Deferred.await(windowStarted); - yield* (yield* DesktopShutdown.DesktopShutdown).request; - yield* Fiber.join(app); + platform: "linux", + } as DesktopEnvironment.DesktopEnvironment["Service"]); + const removedAppImage = path.join(baseDir, "T3-Code-0.1.6-x86_64.AppImage"); + const updatedAppImage = path.join(baseDir, "T3-Code-0.1.7-x86_64.AppImage"); + yield* fs.makeDirectory(path.dirname(launcher), { recursive: true }); + yield* fs.writeFileString( + launcher, + DesktopCliShim.renderCliShim({ + target: { kind: "appimage", appImage: removedAppImage, executableName: "t3code" }, + shimPath: launcher, + t3Home: baseDir, + }), + ); + yield* fs.writeFileString(updatedAppImage, "", { mode: 0o755 }); + const windowStarted = yield* Deferred.make(); + const activationStarted = yield* Deferred.make(); - const content = yield* fs.readFileString(launcher); - assert.include( - content, - `app='${updatedAppImage}'`, - "startup left the t3 launcher pointing at the removed AppImage", - ); - }).pipe(Effect.provide(Layer.mergeAll(DesktopShutdown.layer, NodeServices.layer))), + const app = yield* runStubbedDesktop({ + localEnvironmentEnabled: false, + activationStarted, + environment: { + path, + baseDir, + serverRoot: path.join(baseDir, "resources", "app.asar"), + appImagePath: Option.some(updatedAppImage), + }, + fileSystem: Layer.succeed(FileSystem.FileSystem, fs), + record: () => Effect.void, + windowStarted, + registerLinuxUrlHandler: Effect.void, + }); + yield* Deferred.await(windowStarted); + yield* (yield* DesktopShutdown.DesktopShutdown).request; + yield* Fiber.join(app); + + const content = yield* fs.readFileString(launcher); + assert.include( + content, + `app='${updatedAppImage}'`, + "startup left the t3 launcher pointing at the removed AppImage", + ); + assert.isTrue( + yield* Deferred.isDone(activationStarted), + "startup left the t3 control socket closed", + ); + }).pipe(Effect.provide(Layer.mergeAll(DesktopShutdown.layer, NodeServices.layer))), ); diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts index 34476ee7855b5..0ccce648bba61 100644 --- a/apps/desktop/src/app/DesktopApp.ts +++ b/apps/desktop/src/app/DesktopApp.ts @@ -285,6 +285,10 @@ const bootstrap = Effect.fn("desktop.bootstrap")(function* (backendStarted: bool const snapShot = yield* DesktopSnapShot.DesktopSnapShot; const appActivation = yield* DesktopAppActivation.DesktopAppActivation; const settings = yield* desktopSettings.get; + const startAppActivation = appActivation.start.pipe( + Effect.tap(() => logBootstrapInfo("desktop app control socket ready")), + Effect.catch((error) => logStartupError("desktop app control socket unavailable", { error })), + ); if (settings.localEnvironmentEnabled && (!backendStarted || (yield* Ref.get(state.quitting)))) { return; } @@ -309,6 +313,8 @@ const bootstrap = Effect.fn("desktop.bootstrap")(function* (backendStarted: bool if (!(yield* Ref.get(state.quitting))) { yield* desktopWindow.createMainIfBackendReady; } + // `t3 ` still reaches the renderer, which opens it on this machine's connected service. + yield* startAppActivation; return; } @@ -321,10 +327,7 @@ const bootstrap = Effect.fn("desktop.bootstrap")(function* (backendStarted: bool ) { yield* desktopWindow.ensureMain; } - yield* appActivation.start.pipe( - Effect.tap(() => logBootstrapInfo("desktop app control socket ready")), - Effect.catch((error) => logStartupError("desktop app control socket unavailable", { error })), - ); + yield* startAppActivation; yield* Effect.forkScoped((yield* DesktopWslBackend.DesktopWslBackend).reconcile); }); diff --git a/apps/web/src/hooks/useDefaultTheme.ts b/apps/web/src/hooks/useDefaultTheme.ts index c50ba78cb0111..0f13d75727a4e 100644 --- a/apps/web/src/hooks/useDefaultTheme.ts +++ b/apps/web/src/hooks/useDefaultTheme.ts @@ -1,5 +1,5 @@ import { appAtomRegistry } from "../rpc/atomRegistry"; -import { themeEnvironmentIdAtom } from "../state/primaryEnvironment"; +import { localEnvironmentIdAtom } from "../state/primaryEnvironment"; import { themeServerSettingsAtom } from "../state/server"; import { getThemeDefinition, singleAppearanceOf, subscribeToCustomThemes } from "../themePalette"; import { getThemeSnapshot, setAppearanceMode, setTheme } from "./useTheme"; @@ -58,7 +58,7 @@ function writeAppliedGeneration(storageKey: string, generation: string): void { function adoptDefaultTheme(): void { if (typeof window === "undefined") return; - const environmentId = appAtomRegistry.get(themeEnvironmentIdAtom); + const environmentId = appAtomRegistry.get(localEnvironmentIdAtom); if (environmentId === null) return; const settings = appAtomRegistry.get(themeServerSettingsAtom); const { defaultTheme, defaultThemeSetAt } = settings; @@ -89,7 +89,7 @@ function adoptDefaultTheme(): void { /** Like the theme, the environment's mode applies once per set, then local choices win. */ function adoptDefaultAppearance(): void { if (typeof window === "undefined") return; - const environmentId = appAtomRegistry.get(themeEnvironmentIdAtom); + const environmentId = appAtomRegistry.get(localEnvironmentIdAtom); const { defaultAppearance, defaultAppearanceSetAt } = appAtomRegistry.get(themeServerSettingsAtom); const storageKey = `${APPLIED_DEFAULT_APPEARANCE_STORAGE_PREFIX}${environmentId}`; @@ -117,7 +117,7 @@ function adoptDefaults(): void { */ export function startDefaultThemeAdoption(): () => void { const unsubscribes = [ - appAtomRegistry.subscribe(themeEnvironmentIdAtom, adoptDefaults), + appAtomRegistry.subscribe(localEnvironmentIdAtom, adoptDefaults), appAtomRegistry.subscribe(themeServerSettingsAtom, adoptDefaults), subscribeToCustomThemes(adoptDefaults), ]; diff --git a/apps/web/src/hooks/useHandleNewThread.test.ts b/apps/web/src/hooks/useHandleNewThread.test.ts index 6f318bce409ce..7c64d0077cc2b 100644 --- a/apps/web/src/hooks/useHandleNewThread.test.ts +++ b/apps/web/src/hooks/useHandleNewThread.test.ts @@ -28,6 +28,9 @@ const testState = vi.hoisted(() => { navigate: vi.fn(async (request: { readonly params: { readonly draftId: string } }) => { router.state.location.href = `/draft/${request.params.draftId}`; }), + buildLocation: (request: { readonly params: { readonly draftId: string } }) => ({ + href: `/draft/${request.params.draftId}`, + }), }; const draftStore = { getComposerDraft: vi.fn((draftId: string) => ({ draftId })), @@ -78,6 +81,9 @@ const testState = vi.hoisted(() => { get openDraftRoute() { return openDraftRoute; }, + registerDraft(draft: NonNullable) { + storedDraft = draft; + }, openEmptyDraft(draftId: string) { openDraftRoute = { kind: "draft", draftId }; }, @@ -282,6 +288,31 @@ describe.each([ expect(testState.draftStore.setLogicalProjectDraftThreadId).not.toHaveBeenCalled(); }); + it("resolves to the draft another opener showed for the same project meanwhile", async () => { + testState.reset(draft); + const pendingOpen = useNewThreadHandler()( + { environmentId: "environment-ssh", projectId: "project-remote" } as never, + { replace: true }, + ); + + // The location moves before the route matches do. + testState.registerDraft({ + draftId: "draft-home", + environmentId: "environment-ssh", + promotedTo: null, + threadId: "thread-home", + }); + testState.router.state.location.href = "/draft/draft-home"; + testState.completeProjectFileRead(null); + + await expect(pendingOpen).resolves.toEqual({ + draftId: "draft-home", + threadId: "thread-home", + }); + expect(testState.router.navigate).not.toHaveBeenCalled(); + expect(testState.draftStore.setLogicalProjectDraftThreadId).not.toHaveBeenCalled(); + }); + it("sets the prompt before the draft shows", async () => { testState.reset(draft); const pendingOpen = useNewThreadHandler()( diff --git a/apps/web/src/hooks/useHandleNewThread.ts b/apps/web/src/hooks/useHandleNewThread.ts index 9fae0319539b4..49e8812628b1b 100644 --- a/apps/web/src/hooks/useHandleNewThread.ts +++ b/apps/web/src/hooks/useHandleNewThread.ts @@ -233,6 +233,21 @@ export function createNewThreadHandler(router: AnyRouter) { const logicalProjectKey = project ? deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings) : scopedProjectKey(projectRef); + // Another opener (home's own first-project draft) may have reached this project's draft first. + // Matches lag the location during a navigation, so compare against the location. + const resultIfAbandoned = () => { + const draft = getDraftSessionByLogicalProjectKey(logicalProjectKey); + if (draft === null || draft.promotedTo != null || readProject(projectRef) === null) { + return null; + } + const draftHref = router.buildLocation({ + to: "/draft/$draftId", + params: { draftId: draft.draftId }, + }).href; + return router.state.location.href === draftHref + ? { draftId: draft.draftId, threadId: draft.threadId } + : null; + }; const hasBranchOption = options?.branch !== undefined; const hasWorktreePathOption = options?.worktreePath !== undefined; const hasEnvModeOption = options?.envMode !== undefined; @@ -274,7 +289,7 @@ export function createNewThreadHandler(router: AnyRouter) { } else if (!isDraftAlreadyOpen) { const defaultEnvMode = await resolveDefaultEnvMode(); if (abandonedSinceRequest()) { - return null; + return resultIfAbandoned(); } // Concurrent calls may change the draft; stale resets, remaps, or navigation could clobber it. const routeTargetNow = getCurrentRouteTarget(); @@ -390,7 +405,7 @@ export function createNewThreadHandler(router: AnyRouter) { return (async () => { const initialEnvMode = options?.envMode ?? (await resolveDefaultEnvMode()); if (abandonedSinceRequest()) { - return null; + return resultIfAbandoned(); } // Reuse drafts registered while awaiting so their pending navigation cannot lose them. const racedDraft = getDraftSessionByLogicalProjectKey(logicalProjectKey); diff --git a/apps/web/src/hooks/useOpenLocalWorkspace.ts b/apps/web/src/hooks/useOpenLocalWorkspace.ts index 7f8c7999660d3..b6a34a91da6a1 100644 --- a/apps/web/src/hooks/useOpenLocalWorkspace.ts +++ b/apps/web/src/hooks/useOpenLocalWorkspace.ts @@ -3,6 +3,7 @@ import { findProjectByPath, inferProjectTitleFromPath, } from "@t3tools/client-runtime/state/projects"; +import { useAtomValue } from "@effect/atom-react"; import type { DesktopAppActivationRequest } from "@t3tools/contracts"; import { msg } from "gt-react"; @@ -10,7 +11,8 @@ import { handleDesktopAppActivationRequest } from "../desktopAppActivation"; import { m } from "../i18n/messages"; import { newProjectId } from "../lib/utils"; import { readProjects, waitForProject } from "../state/entities"; -import { usePrimaryEnvironment } from "../state/environments"; +import { useEnvironment } from "../state/environments"; +import { localEnvironmentIdAtom } from "../state/primaryEnvironment"; import { projectEnvironment } from "../state/projects"; import { useEnvironmentShellHasSnapshot } from "../state/shell"; import { useAtomCommand } from "../state/use-atom-command"; @@ -19,38 +21,36 @@ import { reportProjectFailure } from "./useProjectGroupUpdate"; import { useNewThreadHandler } from "./useHandleNewThread"; /** - * Opens a folder on this computer as a project in the primary environment: an + * Opens a folder on this computer as a project in this computer's environment: an * existing project opens (and unarchives), a new one is added. Used by `t3 ` - * activations and folders dropped on the sidebar. `ready` is false until the - * primary environment's projects have loaded, so a known folder is not added twice. + * activations and folders dropped on the sidebar. `ready` is false until that + * environment's projects have loaded, so a known folder is not added twice. */ export function useOpenLocalWorkspace() { - const primaryEnvironment = usePrimaryEnvironment(); + const localEnvironment = useEnvironment(useAtomValue(localEnvironmentIdAtom)); const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false }); const updateProject = useOrchestrationCommand(projectEnvironment.update, { label: "project unarchive", }); const openThread = useNewThreadHandler(); - const shellHasSnapshot = useEnvironmentShellHasSnapshot( - primaryEnvironment?.environmentId ?? null, - ); + const shellHasSnapshot = useEnvironmentShellHasSnapshot(localEnvironment?.environmentId ?? null); const ready = - primaryEnvironment?.connection.phase === "connected" && - primaryEnvironment.serverConfig !== null && + localEnvironment?.connection.phase === "connected" && + localEnvironment.serverConfig !== null && shellHasSnapshot; const open = (request: DesktopAppActivationRequest) => handleDesktopAppActivationRequest(request, { getTarget: () => { if ( - primaryEnvironment?.connection.phase !== "connected" || - primaryEnvironment.serverConfig === null + localEnvironment?.connection.phase !== "connected" || + localEnvironment.serverConfig === null ) { return null; } return { - environmentId: primaryEnvironment.environmentId, - platform: primaryEnvironment.serverConfig.environment.platform.os, + environmentId: localEnvironment.environmentId, + platform: localEnvironment.serverConfig.environment.platform.os, }; }, findProject: (environmentId, workspaceRoot) => diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx index 21a981ef00a76..3cbef77306c8e 100644 --- a/apps/web/src/routes/__root.tsx +++ b/apps/web/src/routes/__root.tsx @@ -186,9 +186,11 @@ function RootRouteBranch() { // first-run gate and the event router, whose first navigation would leave the page. const appHosts = ( <> - {primaryEnvironmentAuthenticated ? : null} {primaryEnvironmentAuthenticated || localEnvironmentDisabled ? ( - + <> + + + ) : null} {isElectron ? : null} diff --git a/apps/web/src/state/primaryEnvironment.test.ts b/apps/web/src/state/primaryEnvironment.test.ts index 4fbb52aed6cd6..aad415d94e2f4 100644 --- a/apps/web/src/state/primaryEnvironment.test.ts +++ b/apps/web/src/state/primaryEnvironment.test.ts @@ -8,18 +8,18 @@ import { EnvironmentId } from "@t3tools/contracts"; import { Atom, AtomRegistry } from "effect/reactivity"; import { describe, expect, it } from "vite-plus/test"; -import { createThemeEnvironmentIdAtom } from "./primaryEnvironment"; +import { createLocalEnvironmentIdAtom } from "./primaryEnvironment"; const PRIMARY = EnvironmentId.make("primary"); const SERVICE = EnvironmentId.make("service"); const REMOTE = EnvironmentId.make("remote"); -function themeEnvironmentId(input: { +function localEnvironmentId(input: { primary: EnvironmentId | null; host: string | null; catalog: ReadonlyArray; }) { - const atom = createThemeEnvironmentIdAtom({ + const atom = createLocalEnvironmentIdAtom({ primaryEnvironmentIdAtom: Atom.make(input.primary), hostEnvironmentIdAtom: Atom.make(input.host), catalogValueAtom: Atom.make({ entries: new Map(input.catalog.map((id) => [id, null])) }), @@ -27,22 +27,22 @@ function themeEnvironmentId(input: { return AtomRegistry.make().get(atom); } -describe("themeEnvironmentIdAtom", () => { +describe("localEnvironmentIdAtom", () => { it("prefers the primary environment over this machine's background service", () => { expect( - themeEnvironmentId({ primary: PRIMARY, host: "service", catalog: [PRIMARY, SERVICE] }), + localEnvironmentId({ primary: PRIMARY, host: "service", catalog: [PRIMARY, SERVICE] }), ).toBe(PRIMARY); }); it("uses the connected background service sharing the app's T3 home when there is no primary", () => { - expect(themeEnvironmentId({ primary: null, host: "service", catalog: [REMOTE, SERVICE] })).toBe( + expect(localEnvironmentId({ primary: null, host: "service", catalog: [REMOTE, SERVICE] })).toBe( SERVICE, ); }); it("uses no environment when that service is not among the connections", () => { - expect(themeEnvironmentId({ primary: null, host: "service", catalog: [REMOTE] })).toBeNull(); - expect(themeEnvironmentId({ primary: null, host: null, catalog: [REMOTE] })).toBeNull(); + expect(localEnvironmentId({ primary: null, host: "service", catalog: [REMOTE] })).toBeNull(); + expect(localEnvironmentId({ primary: null, host: null, catalog: [REMOTE] })).toBeNull(); }); }); diff --git a/apps/web/src/state/primaryEnvironment.ts b/apps/web/src/state/primaryEnvironment.ts index 51264adb7c5e7..3271cf9140a54 100644 --- a/apps/web/src/state/primaryEnvironment.ts +++ b/apps/web/src/state/primaryEnvironment.ts @@ -18,8 +18,8 @@ export const hostEnvironmentIdAtom = Atom.make(null).pipe( Atom.withLabel("web-host-environment-id"), ); -// Without a primary, only the service sharing the desktop app's T3 home supplies themes. -export function createThemeEnvironmentIdAtom(input: { +// This computer's environment: the primary, else a connection to the service sharing the app's T3 home. +export function createLocalEnvironmentIdAtom(input: { readonly primaryEnvironmentIdAtom: Atom.Atom; readonly hostEnvironmentIdAtom: Atom.Atom; readonly catalogValueAtom: Atom.Atom<{ readonly entries: ReadonlyMap }>; @@ -32,10 +32,10 @@ export function createThemeEnvironmentIdAtom(input: { if (environmentId === hostEnvironmentId) return environmentId; } return null; - }).pipe(Atom.withLabel("web-theme-environment-id")); + }).pipe(Atom.withLabel("web-local-environment-id")); } -export const themeEnvironmentIdAtom = createThemeEnvironmentIdAtom({ +export const localEnvironmentIdAtom = createLocalEnvironmentIdAtom({ primaryEnvironmentIdAtom, hostEnvironmentIdAtom, catalogValueAtom: environmentCatalog.catalogValueAtom, diff --git a/apps/web/src/state/server.ts b/apps/web/src/state/server.ts index 6e2a71baf53e4..eae8aaa9f0eea 100644 --- a/apps/web/src/state/server.ts +++ b/apps/web/src/state/server.ts @@ -25,7 +25,7 @@ import { isConnectedWithConfig } from "../components/settings/scopedSettings"; import { environmentCatalog } from "../connection/catalog"; import { connectionAtomRuntime } from "../connection/runtime"; import { environmentAtomList } from "./environmentAtomList"; -import { primaryEnvironmentIdAtom, themeEnvironmentIdAtom } from "./primaryEnvironment"; +import { primaryEnvironmentIdAtom, localEnvironmentIdAtom } from "./primaryEnvironment"; import { environmentSession } from "./session"; import { reuseProvidersIgnoringCheckedAt } from "./serverProviders.logic"; @@ -167,7 +167,7 @@ export const primaryServerKeybindingsAtom = createShortcutKeybindingsAtom({ const EMPTY_ENVIRONMENT_THEMES: ReadonlyArray = []; const themeServerConfigAtom = Atom.make((get): ServerConfig | null => { - const environmentId = get(themeEnvironmentIdAtom); + const environmentId = get(localEnvironmentIdAtom); return environmentId === null ? null : get(serverEnvironment.configValueAtom(environmentId)); }).pipe(Atom.withLabel("web-theme-server-config")); diff --git a/apps/web/src/themeBackground.test.ts b/apps/web/src/themeBackground.test.ts index 589b2d411f5d9..33d2a3dc4de8d 100644 --- a/apps/web/src/themeBackground.test.ts +++ b/apps/web/src/themeBackground.test.ts @@ -11,7 +11,7 @@ vi.mock( ); vi.mock(import("./state/primaryEnvironment"), async () => { const { Atom } = await import("effect/reactivity"); - return { themeEnvironmentIdAtom: Atom.make(EnvironmentId.make("host")) } as never; + return { localEnvironmentIdAtom: Atom.make(EnvironmentId.make("host")) } as never; }); vi.mock(import("./state/server"), async () => { const { Atom } = await import("effect/reactivity"); diff --git a/apps/web/src/themeBackground.ts b/apps/web/src/themeBackground.ts index 2eec19b5a98b5..22f5f8f1d34fe 100644 --- a/apps/web/src/themeBackground.ts +++ b/apps/web/src/themeBackground.ts @@ -4,7 +4,7 @@ import type { EnvironmentId } from "@t3tools/contracts"; import { appAtomRegistry, subscribeAtomChanges } from "./rpc/atomRegistry"; import { assetEnvironment } from "./state/assets"; -import { themeEnvironmentIdAtom } from "./state/primaryEnvironment"; +import { localEnvironmentIdAtom } from "./state/primaryEnvironment"; import { themeServerEnvironmentThemesAtom } from "./state/server"; import { environmentSession } from "./state/session"; import { getCustomThemes } from "./themePalette"; @@ -58,7 +58,7 @@ async function loadBackground( export function applyThemeBackground(themeId: string | undefined): void { if (typeof document === "undefined") return; appliedThemeId = themeId; - const environmentId = appAtomRegistry.get(themeEnvironmentIdAtom); + const environmentId = appAtomRegistry.get(localEnvironmentIdAtom); // A saved theme wins its id over a published one, so the published image is not its. const revision = themeId === undefined || getCustomThemes().some((theme) => theme.id === themeId) From 1cefbc4051ba687035b4cca3fa4a59309a8918a9 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 14:46:18 -0800 Subject: [PATCH 059/183] fix(mobile): Duo rail tools no longer slide under the workspace tabs (#38772) Co-authored-by: Claude Opus 5.5 --- apps/mobile/src/components/ui/AppBar.tsx | 42 +- .../pull-requests/PullRequestControls.tsx | 85 +++- .../pull-requests/PullRequestRouteScreen.tsx | 384 +++++++++--------- 3 files changed, 312 insertions(+), 199 deletions(-) diff --git a/apps/mobile/src/components/ui/AppBar.tsx b/apps/mobile/src/components/ui/AppBar.tsx index 8e197b5b308e2..5efe5f19d6d7f 100644 --- a/apps/mobile/src/components/ui/AppBar.tsx +++ b/apps/mobile/src/components/ui/AppBar.tsx @@ -20,7 +20,7 @@ import { NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED, } from "../../features/layout/native-mail-search-toolbar"; import { useAppearancePreferences } from "../../features/settings/appearance/AppearancePreferencesProvider"; -import type { AppBarMenuItem, AppBarProps } from "./AppBar.types"; +import type { AppBarMenu, AppBarMenuItem, AppBarProps } from "./AppBar.types"; import type { AppSymbolName } from "./AppSymbol"; import { useNativeMailSearchToolbar } from "../../native/use-native-mail-search-toolbar"; import { useControlTheme } from "./useControlTheme"; @@ -111,7 +111,41 @@ export function AppBar(props: AppBarProps) { search !== undefined && (search.compactToolbar ?? !layout.usesSplitView) && usesNativeMailSearchToolbar; - const visibleMenus = compactSearch ? (menus?.slice(1) ?? []) : (menus ?? []); + const trailingMenus = compactSearch ? (menus?.slice(1) ?? []) : (menus ?? []); + // The Duo's vertical bar never overflows: items that don't fit slide under the workspace tabs, + // and a Live Activity pushes them down further. More than one tool shares one menu there. + const groupTrailing = + usesNativeWorkspaceColumns && + isDuoDevice(deviceType) && + props.onClose === undefined && + (props.actions?.length ?? 0) + trailingMenus.length > 1; + const actions = groupTrailing ? [] : (props.actions ?? []); + const visibleMenus: ReadonlyArray = groupTrailing + ? [ + { + title: gt("More actions"), + icon: "ellipsis", + items: [ + ...(props.actions ?? []).map((action) => ({ + id: action.accessibilityLabel, + title: action.accessibilityLabel, + icon: iosIcon(action.icon), + subtitle: action.subtitle, + disabled: action.disabled || action.loading, + selected: action.selected, + destructive: action.destructive, + onPress: action.onPress, + })), + ...trailingMenus.map((menu) => ({ + id: menu.title, + title: menu.title, + icon: iosIcon(menu.icon), + items: menu.items, + })), + ], + }, + ] + : trailingMenus; // Where the mail toolbar isn't used, the Duo keeps search at the bottom of the pane like its // workspace lists; elsewhere inline search is a button in the bar. const duoBottomSearch = @@ -221,13 +255,13 @@ export function AppBar(props: AppBarProps) { ) : null} ) : null} - {props.actions?.length || + {actions.length || visibleMenus.length || props.trailing || props.confirm || closeInspector ? ( - {props.actions?.map(({ loading, ...action }) => + {actions.map(({ loading, ...action }) => loading ? ( void; readonly onHeightChange?: (height: number) => void; }) { @@ -119,8 +129,7 @@ export function PullRequestActionToolbar(props: { const { draft } = usePullRequestReviewDraft(props.params); const { themeVariables: colors } = useAppearancePreferences(); const insets = useSafeAreaInsets(); - const nativeMetrics = useNativeLayoutMetrics(); - const verticalControls = nativeMetrics !== null && nativeMetrics.verticalBarEdge !== "none"; + const verticalControls = usePullRequestVerticalControls(); const permissions = usePullRequestPermissions(props.params, props.pr); const agent = usePullRequestAgentActions(props.params, props.pr, props.filePath); const canReview = permissions.verdicts.length > 0; @@ -148,7 +157,10 @@ export function PullRequestActionToolbar(props: { const threadMenuItems = agent.threadActions("ask"); const openFiles = props.onOpenFiles ?? (() => navigation.navigate("PullRequestFiles", props.params)); - if (!props.pr) return null; + if (!props.pr) + return verticalControls ? ( + {createNativeHeaderMenu(props.menu)} + ) : null; const primaryDisabled = pendingReview ? false : agent.disabled; const showPrimary = pendingReview || canOpenThread; if (Platform.OS === "android") { @@ -285,12 +297,52 @@ export function PullRequestActionToolbar(props: { separateBackground /> ); + // The vertical bar never overflows into a menu, and with a Live Activity it fits about three + // buttons above the workspace tabs: back, the primary action and one menu. if (verticalControls) return ( - {filesControl} - {agentControl} {primaryControl} + {createNativeHeaderMenu({ + ...props.menu, + items: [ + { + id: "changed-files", + title: gt("Changed files"), + icon: "doc.text.magnifyingglass", + onPress: openFiles, + }, + ...(showAgentControls + ? [ + { + id: "ai-helpers", + title: gt("AI helpers"), + icon: "ellipsis.bubble", + items: agentActions.map((action): AppBarMenuItem => + chooseThread && !action.disabled + ? { + id: action.task, + title: action.title, + icon: action.icon, + items: appBarThreadMenuItems( + agent.threadActions(action.task), + agent.select, + ), + } + : { + id: action.task, + title: action.title, + icon: action.icon, + disabled: action.disabled || agent.disabled, + onPress: () => agent.start(action.task), + }, + ), + }, + ] + : []), + ...props.menu.items, + ], + })} ); return ( @@ -304,6 +356,29 @@ export function PullRequestActionToolbar(props: { ); } +function appBarThreadMenuItems( + items: MenuAction[], + select: (id: string) => void, +): ReadonlyArray { + return items.map((item) => + item.subactions + ? { + id: item.id ?? item.title, + title: item.title, + icon: item.image, + items: appBarThreadMenuItems(item.subactions, select), + } + : { + id: item.id ?? item.title, + title: item.title, + icon: item.image, + subtitle: item.subtitle, + disabled: item.attributes?.disabled, + onPress: () => item.id && select(item.id), + }, + ); +} + function renderThreadMenuItems(items: MenuAction[], select: (id: string) => void): ReactNode { return items.map((item) => item.subactions ? ( diff --git a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx index 01710fb095b0f..d55abf33503c5 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx @@ -71,7 +71,7 @@ import { NativeScrollView } from "../../native/NativeScrollViewMarker"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { AppText as Text } from "../../components/ui/AppText"; -import { AppBar } from "../../components/ui/AppBar"; +import { AppBar, type AppBarMenu } from "../../components/ui/AppBar"; import { useContentTopInset } from "../../components/ui/useBarInset"; import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing"; import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout"; @@ -102,7 +102,11 @@ import { useAppearancePreferences } from "../settings/appearance/AppearancePrefe import { useAppearanceCodeSurface } from "../settings/appearance/useAppearanceCodeSurface"; import { useNativeReviewDiffBridge } from "../review/useNativeReviewDiffBridge"; import { pullRequestTimelineRows } from "./PullRequestTimeline"; -import { PullRequestActionToolbar, PullRequestCardGroup } from "./PullRequestControls"; +import { + PullRequestActionToolbar, + PullRequestCardGroup, + usePullRequestVerticalControls, +} from "./PullRequestControls"; import { pullRequestTarget as requestTarget, usePullRequestDiff, @@ -589,6 +593,119 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps 0) requestAnimationFrame(jumpToFiles); } }; + const verticalControls = usePullRequestVerticalControls(); + const pullRequestMenu: AppBarMenu = { + title: gt( + "{term, select, mr {Merge request} cr {Change request} other {Pull request}} actions", + { term: changeRequestTermKind(terminology) }, + ), + icon: "ellipsis", + items: [ + ...(permissions.verdicts.length + ? [ + { + id: "submit-review", + title: gt("Submit review"), + icon: "text.bubble", + onPress: () => + navigation.navigate("PullRequestReview", { ...params, mode: "review" }), + }, + ] + : []), + ...(permissions.canComment + ? [ + { + id: "add-comment", + title: gt("Add comment"), + icon: "plus.bubble", + onPress: () => + navigation.navigate("PullRequestReview", { ...params, mode: "comment" }), + }, + ] + : []), + ...(permissions.canEditChangeRequest + ? [ + { + id: "edit-title", + title: gt("Edit title"), + icon: "pencil", + onPress: () => navigation.navigate("PullRequestEdit", { ...params, field: "title" }), + }, + { + id: "edit-description", + title: gt("Edit description"), + icon: "doc.text", + disabled: description.pending, + subtitle: description.pending ? gt("Saving…") : undefined, + onPress: () => navigation.navigate("PullRequestEdit", { ...params, field: "body" }), + }, + ] + : []), + ...(maintainerEdits.visible + ? [ + { + id: "maintainer-edits", + title: gt("Allow edits from maintainers"), + icon: "pencil", + selected: maintainerEdits.value, + disabled: maintainerEdits.saving, + subtitle: maintainerEdits.subtitle, + onPress: maintainerEdits.toggle, + }, + ] + : []), + ...(identity + ? [ + { + id: "open-on-provider", + title: openOnProviderLabel(identity.provider, messages), + icon: "arrow.up.right", + onPress: () => void Linking.openURL(identity.url), + }, + { + id: "copy-link", + title: gt("Copy link"), + icon: "link", + onPress: () => copyPullRequestLink(identity), + }, + { + id: "share", + title: gt("Share…"), + icon: "square.and.arrow.up", + onPress: () => sharePullRequestLink(identity), + }, + ] + : []), + ...(stateAction + ? [ + { + id: "state", + title: pullRequestActionLabel(stateAction, terminology, messages), + icon: PR_ACTION_ICONS[stateAction], + destructive: stateAction === "close", + onPress: runStateAction, + }, + ] + : []), + ...(showsDeleteBranch + ? [ + { + id: "delete-branch", + title: pullRequestActionLabel("delete-branch", terminology, messages), + icon: PR_ACTION_ICONS["delete-branch"], + destructive: true, + disabled: !action.available("delete-branch"), + subtitle: action.busy + ? gt("Deleting…") + : connected + ? pr.headBranch + : gt("Reconnect to delete this branch."), + onPress: confirmDeleteBranch, + }, + ] + : []), + ], + }; return ( @@ -600,122 +717,7 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps - navigation.navigate("PullRequestReview", { ...params, mode: "review" }), - }, - ] - : []), - ...(permissions.canComment - ? [ - { - id: "add-comment", - title: gt("Add comment"), - icon: "plus.bubble", - onPress: () => - navigation.navigate("PullRequestReview", { ...params, mode: "comment" }), - }, - ] - : []), - ...(permissions.canEditChangeRequest - ? [ - { - id: "edit-title", - title: gt("Edit title"), - icon: "pencil", - onPress: () => - navigation.navigate("PullRequestEdit", { ...params, field: "title" }), - }, - { - id: "edit-description", - title: gt("Edit description"), - icon: "doc.text", - disabled: description.pending, - subtitle: description.pending ? gt("Saving…") : undefined, - onPress: () => - navigation.navigate("PullRequestEdit", { ...params, field: "body" }), - }, - ] - : []), - ...(maintainerEdits.visible - ? [ - { - id: "maintainer-edits", - title: gt("Allow edits from maintainers"), - icon: "pencil", - selected: maintainerEdits.value, - disabled: maintainerEdits.saving, - subtitle: maintainerEdits.subtitle, - onPress: maintainerEdits.toggle, - }, - ] - : []), - ...(identity - ? [ - { - id: "open-on-provider", - title: openOnProviderLabel(identity.provider, messages), - icon: "arrow.up.right", - onPress: () => void Linking.openURL(identity.url), - }, - { - id: "copy-link", - title: gt("Copy link"), - icon: "link", - onPress: () => copyPullRequestLink(identity), - }, - { - id: "share", - title: gt("Share…"), - icon: "square.and.arrow.up", - onPress: () => sharePullRequestLink(identity), - }, - ] - : []), - ...(stateAction - ? [ - { - id: "state", - title: pullRequestActionLabel(stateAction, terminology, messages), - icon: PR_ACTION_ICONS[stateAction], - destructive: stateAction === "close", - onPress: runStateAction, - }, - ] - : []), - ...(showsDeleteBranch - ? [ - { - id: "delete-branch", - title: pullRequestActionLabel("delete-branch", terminology, messages), - icon: PR_ACTION_ICONS["delete-branch"], - destructive: true, - disabled: !action.available("delete-branch"), - subtitle: action.busy - ? gt("Deleting…") - : connected - ? pr.headBranch - : gt("Reconnect to delete this branch."), - onPress: confirmDeleteBranch, - }, - ] - : []), - ], - }, - ]} + menus={verticalControls ? undefined : [pullRequestMenu]} /> setViewportHeight(event.nativeEvent.layout.height)}> {(["overview", "guide", "activity"] as const) @@ -961,6 +963,7 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps @@ -1235,6 +1238,77 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) { const title = commit ? gt("Commit changes") : gt("Changes"); const seekingFile = !targetFile && result.nextCursor !== null; const loadingDiff = (result.isPending && !data.rows.length) || (seekingFile && !result.error); + const verticalControls = usePullRequestVerticalControls(); + const diffMenu: AppBarMenu = { + title: gt("Diff options"), + icon: "ellipsis", + items: [ + ...(permissions.verdicts.length + ? [ + { + id: "submit-review", + title: gt("Submit review"), + icon: "text.bubble", + onPress: () => + navigation.navigate("PullRequestReview", { + ...route.params, + mode: "review", + }), + }, + ] + : []), + ...(permissions.canComment + ? [ + { + id: "comment-on-pr", + title: gt("Add comment"), + icon: "plus.bubble", + onPress: () => + navigation.navigate("PullRequestReview", { + ...route.params, + mode: "comment", + }), + }, + ] + : []), + { + id: "word-wrap", + title: gt("Word wrap"), + icon: "text.alignleft", + selected: appearance.codeWordBreak, + onPress: () => setCodeWordBreak(!appearance.codeWordBreak), + }, + { + id: "hide-tests", + title: gt("Hide test files"), + icon: "line.3.horizontal.decrease", + selected: filter.hideTestFiles, + onPress: toggleTestFiles, + }, + ...(selectedRow && selectedFile && canCommentOnDiff + ? [ + { + id: "comment", + title: route.params.replacingDraftId + ? gt("Move draft to this line") + : gt("Add review comment"), + icon: "bubble.left", + onPress: () => commentOnLine(), + }, + ] + : []), + ...(selectedRow && selectedFile + ? [ + { + id: "copy", + title: gt("Copy line"), + icon: "document.on.document", + onPress: () => void Clipboard.setStringAsync(selectedRow.content ?? ""), + }, + ] + : []), + ], + }; return ( navigation.goBack()} - menus={[ - { - title: gt("Diff options"), - icon: "ellipsis", - items: [ - ...(permissions.verdicts.length - ? [ - { - id: "submit-review", - title: gt("Submit review"), - icon: "text.bubble", - onPress: () => - navigation.navigate("PullRequestReview", { - ...route.params, - mode: "review", - }), - }, - ] - : []), - ...(permissions.canComment - ? [ - { - id: "comment-on-pr", - title: gt("Add comment"), - icon: "plus.bubble", - onPress: () => - navigation.navigate("PullRequestReview", { - ...route.params, - mode: "comment", - }), - }, - ] - : []), - { - id: "word-wrap", - title: gt("Word wrap"), - icon: "text.alignleft", - selected: appearance.codeWordBreak, - onPress: () => setCodeWordBreak(!appearance.codeWordBreak), - }, - { - id: "hide-tests", - title: gt("Hide test files"), - icon: "line.3.horizontal.decrease", - selected: filter.hideTestFiles, - onPress: toggleTestFiles, - }, - ...(selectedRow && selectedFile && canCommentOnDiff - ? [ - { - id: "comment", - title: route.params.replacingDraftId - ? gt("Move draft to this line") - : gt("Add review comment"), - icon: "bubble.left", - onPress: () => commentOnLine(), - }, - ] - : []), - ...(selectedRow && selectedFile - ? [ - { - id: "copy", - title: gt("Copy line"), - icon: "document.on.document", - onPress: () => void Clipboard.setStringAsync(selectedRow.content ?? ""), - }, - ] - : []), - ], - }, - ]} + menus={verticalControls ? undefined : [diffMenu]} /> {route.params.replacingDraftId ? ( @@ -1483,6 +1486,7 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) { pr={detail.data} params={route.params} filePath={visibleFile?.path} + menu={diffMenu} onOpenFiles={() => navigation.navigate("PullRequestFiles", route.params)} onHeightChange={setToolbarHeight} /> From a5090a75767dfaef311932e4a466e5fe2ee2f0f2 Mon Sep 17 00:00:00 2001 From: Elias <69803556+elias1218@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:05:16 -0500 Subject: [PATCH 060/183] fix(web): Default effort no longer shows as the lowest bar (#38684) Co-authored-by: Julius Marminge --- apps/web/src/components/chat/EffortGlyph.test.ts | 5 ++++- apps/web/src/components/chat/EffortGlyph.tsx | 6 +++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/apps/web/src/components/chat/EffortGlyph.test.ts b/apps/web/src/components/chat/EffortGlyph.test.ts index 0b73e89e4f833..1c893050e0d41 100644 --- a/apps/web/src/components/chat/EffortGlyph.test.ts +++ b/apps/web/src/components/chat/EffortGlyph.test.ts @@ -25,8 +25,11 @@ describe("resolveEffortGlyph", () => { }); }); - it("names max instead of drawing it", () => { + it("names Max and Default instead of drawing them", () => { expect(resolveEffortGlyph(claude, "max")?.special).toBe("Max"); + const reported = descriptor(["default", "low", "medium", "high", "xhigh", "max"]); + expect(resolveEffortGlyph(reported, "default")?.special).toBe("Default"); + expect(resolveEffortGlyph(reported, "low")).toMatchObject({ count: 4, filled: 1 }); }); it("names Ultracode and Ultrathink instead of drawing a level", () => { diff --git a/apps/web/src/components/chat/EffortGlyph.tsx b/apps/web/src/components/chat/EffortGlyph.tsx index ae90228b8da1b..8220a2b27272c 100644 --- a/apps/web/src/components/chat/EffortGlyph.tsx +++ b/apps/web/src/components/chat/EffortGlyph.tsx @@ -11,15 +11,15 @@ const BASELINE_INSET = 2; type SelectDescriptor = Extract; // Older servers offer Ultracode as a level. It changes the workflow, so it keeps its name. -// Max is named too, so the full scale stops short of it. -const NAMED_LEVELS = new Set(["ultracode", "max"]); +// Max is named too, so the full scale stops short of it. Default leaves the level to the agent. +const NAMED_LEVELS = new Set(["ultracode", "max", "default"]); const OFF_LEVELS = new Set(["off", "none"]); // More bars than this no longer fit the glyph's height in whole pixels. const MAX_BARS = 7; /** * Maps a reasoning select to bars: one per ordinary level, filled up to the current one, with an - * off level as none filled. Max, prompt-injected and workflow levels are named instead of drawn. + * off level as none filled. Max, Default, prompt-injected and workflow levels are named instead. */ export function resolveEffortGlyph(descriptor: SelectDescriptor, current: string | null) { const special = new Set([...(descriptor.promptInjectedValues ?? []), ...NAMED_LEVELS]); From b6a0fd6d62ad52b6c3a4496eab042c85e3804cba Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 15:23:01 -0800 Subject: [PATCH 061/183] feat(issues): an issue shows every thread it is linked to (#38771) Co-authored-by: Claude Fable 5.2 --- .../src/features/issues/IssueRouteScreen.tsx | 73 ++++++ apps/mobile/src/i18n/translations/de.json | 5 +- apps/mobile/src/i18n/translations/en.json | 5 +- apps/mobile/src/i18n/translations/es.json | 5 +- apps/mobile/src/i18n/translations/fr.json | 5 +- apps/mobile/src/i18n/translations/ja.json | 5 +- apps/mobile/src/i18n/translations/ko.json | 5 +- apps/mobile/src/i18n/translations/pt-BR.json | 5 +- apps/mobile/src/i18n/translations/ru.json | 5 +- apps/mobile/src/i18n/translations/sv.json | 5 +- apps/mobile/src/i18n/translations/zh.json | 5 +- apps/server/src/auth/RpcAuthorization.ts | 1 + .../src/environment/ServerEnvironment.ts | 1 + apps/server/src/issue/linkedThreads.test.ts | 56 +++++ apps/server/src/issue/linkedThreads.ts | 64 ++++++ .../src/observability/RpcInstrumentation.ts | 1 + .../ThreadIssueService.test.ts | 2 + .../orchestration-v2/ThreadIssueService.ts | 14 +- .../src/pullRequest/linkedThreads.test.ts | 11 + apps/server/src/pullRequest/linkedThreads.ts | 14 +- apps/server/src/ws.test.ts | 2 + apps/server/src/ws.ts | 5 + apps/web/src/components/ThreadLinkPicker.tsx | 87 ++++++++ .../src/components/issue/IssueDetailPanel.tsx | 103 +-------- .../src/components/issue/IssueThreadLinks.tsx | 211 ++++++++++++++++++ .../pullRequest/PullRequestThreadLinks.tsx | 87 +------- apps/web/src/i18n/translations/de.json | 25 ++- apps/web/src/i18n/translations/en.json | 25 ++- apps/web/src/i18n/translations/es.json | 25 ++- apps/web/src/i18n/translations/fr.json | 25 ++- apps/web/src/i18n/translations/ja.json | 25 ++- apps/web/src/i18n/translations/ko.json | 25 ++- apps/web/src/i18n/translations/pt-BR.json | 25 ++- apps/web/src/i18n/translations/ru.json | 25 ++- apps/web/src/i18n/translations/sv.json | 25 ++- apps/web/src/i18n/translations/zh.json | 25 ++- packages/client-runtime/src/state/issues.ts | 12 + packages/contracts/src/environment.ts | 2 + packages/contracts/src/issue.ts | 15 ++ packages/contracts/src/rpc.ts | 10 + 40 files changed, 757 insertions(+), 314 deletions(-) create mode 100644 apps/server/src/issue/linkedThreads.test.ts create mode 100644 apps/server/src/issue/linkedThreads.ts create mode 100644 apps/web/src/components/ThreadLinkPicker.tsx create mode 100644 apps/web/src/components/issue/IssueThreadLinks.tsx diff --git a/apps/mobile/src/features/issues/IssueRouteScreen.tsx b/apps/mobile/src/features/issues/IssueRouteScreen.tsx index 1833b0d765850..c18a8cec2c2f0 100644 --- a/apps/mobile/src/features/issues/IssueRouteScreen.tsx +++ b/apps/mobile/src/features/issues/IssueRouteScreen.tsx @@ -3,6 +3,7 @@ import { StackActions, useNavigation, type StaticScreenProps } from "@react-navi import { issueEventSentence } from "@t3tools/client-runtime/issue-presentation"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { createIssueCommentPager } from "@t3tools/client-runtime/state/issues"; +import { visibleLinkedThreads } from "@t3tools/client-runtime/state/threads"; import type { IssueComment, IssueEvent, @@ -37,8 +38,10 @@ import { NativeLayoutObserver } from "../../native/NativeLayoutObserver"; import { useNativeWorkspaceColumnsSupported } from "../../native/NativeWorkspaceColumns"; import { useDeviceType, useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics"; import { NativeScrollView } from "../../native/NativeScrollViewMarker"; +import { useEnvironmentServerConfig } from "../../state/entities"; import { issueEnvironment, refreshIssueLists } from "../../state/issues"; import { useEnvironmentQuery } from "../../state/query"; +import { environmentThreadShells } from "../../state/threads"; import { useAtomCommand } from "../../state/use-atom-command"; import { usePullToRefresh } from "../../state/use-pull-to-refresh"; import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout"; @@ -299,6 +302,75 @@ function LinkedPullRequests(props: { ); } +/** The threads this issue is linked to, most recently active first; hidden while there are none. */ +function LinkedThreads(props: { readonly params: IssueParams; readonly host: string }) { + const gt = useGT(); + const navigation = useNavigation(); + const { environmentId, input } = issueTarget(props.params); + const listsThreads = + useEnvironmentServerConfig(environmentId)?.environment.capabilities.issueLinkedThreads === true; + const relations = useEnvironmentQuery( + listsThreads + ? issueEnvironment.linkedThreads({ + environmentId, + input: { tracker: input.tracker, host: props.host, scope: input.scope, key: input.key }, + }) + : null, + ); + const hiddenKeys = useAtomValue(environmentThreadShells.hiddenThreadKeysAtom); + const hidingAnywhere = useAtomValue(environmentThreadShells.anyEnvironmentHidingAtom); + const loadedThreadRefs = useAtomValue( + environmentThreadShells.environmentThreadRefsAtom(environmentId), + ); + const threads = visibleLinkedThreads( + relations.data?.threads ?? [], + environmentId, + loadedThreadRefs, + hiddenKeys, + hidingAnywhere, + ); + if (threads.length === 0) return null; + return ( + + + Linked threads + + {threads.map((thread) => { + const title = thread.title || gt("Untitled thread"); + return ( + + navigation.dispatch( + StackActions.push("Thread", { + environmentId: props.params.environmentId, + threadId: thread.id, + }), + ) + } + className="flex-row items-center gap-2 rounded-2xl bg-grouped-card p-3 active:opacity-70" + > + + + + {title} + + {thread.archivedAt !== null ? ( + + Archived thread + + ) : null} + + + + ); + })} + + ); +} + function IssueCommentCard(props: { readonly params: IssueParams; readonly comment: IssueComment; @@ -617,6 +689,7 @@ function IssueRoute({ params }: { readonly params: IssueParams }) { {detail.linkedPullRequests.length > 0 ? ( ) : null} + {detail.commentCount > 0 diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index c9d43d96b3eb8..8e07b70039554 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -2279,6 +2279,8 @@ "6fb238486abb5267": "Zugewiesene Personen bearbeiten", "a90c583cbd5151e5": "{status} Pull Request {number}, {title}", "e74de8decd998061": "schließt", + "2d7d0917e9d23b98": "Unbenannter Thread", + "2025fc2a5f89a7fb": "Thread {title} öffnen", "b7b88aa36ad9512b": "Jemand", "02de63c7a0ebd94c": "Issue wird geladen", "f776ce04009278c5": "Ältere Kommentare konnten nicht gelesen werden.", @@ -2316,6 +2318,8 @@ "115e0df4e8da2704": "Zugewiesene Personen", "7dd58ad67a6de5ba": "niemand", "325276a3fe4e9d12": "Verknüpfte Pull Requests", + "f7068768fdf3e96b": "Verknüpfte Threads", + "0cfebee8b40cdf6e": "Archivierter Thread", "ab8222ce9132da09": "Beschreibung", "051acc34eaf9d1df": "Aktivität", "9d82ebf35bfb4043": "Hier ist noch nichts passiert.", @@ -2372,7 +2376,6 @@ "e880959d9520231a": "Änderungen prüfen", "9e25940062052a95": "PR-Link oder Thread kopieren", "6a433e2e6d1cfd88": "Neuer Thread · {environment}", - "2d7d0917e9d23b98": "Unbenannter Thread", "fb49961cfffa5467": "Befehlspalette schließen", "6fdd3baa7bafa38b": "Befehle, Projekte und Threads durchsuchen", "fd47ac08956ffcbc": "Befehle, Projekte und Threads durchsuchen…", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 7a89a1cf37c22..6e9b23124aff0 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -2279,6 +2279,8 @@ "6fb238486abb5267": "Edit assignees", "a90c583cbd5151e5": "{status} pull request {number}, {title}", "e74de8decd998061": "closes", + "2d7d0917e9d23b98": "Untitled thread", + "2025fc2a5f89a7fb": "Open thread {title}", "b7b88aa36ad9512b": "Someone", "02de63c7a0ebd94c": "Loading issue", "f776ce04009278c5": "Older comments could not be read.", @@ -2316,6 +2318,8 @@ "115e0df4e8da2704": "Assignees", "7dd58ad67a6de5ba": "none", "325276a3fe4e9d12": "Linked pull requests", + "f7068768fdf3e96b": "Linked threads", + "0cfebee8b40cdf6e": "Archived thread", "ab8222ce9132da09": "Description", "051acc34eaf9d1df": "Activity", "9d82ebf35bfb4043": "Nothing has happened here yet.", @@ -2372,7 +2376,6 @@ "e880959d9520231a": "Review changes", "9e25940062052a95": "Copy PR link or thread", "6a433e2e6d1cfd88": "New thread · {environment}", - "2d7d0917e9d23b98": "Untitled thread", "fb49961cfffa5467": "Close command palette", "6fdd3baa7bafa38b": "Search commands, projects, and threads", "fd47ac08956ffcbc": "Search commands, projects, and threads…", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 288dbfc7da2cf..1464fc150ba83 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -2279,6 +2279,8 @@ "6fb238486abb5267": "Editar asignados", "a90c583cbd5151e5": "Pull request {number} {status}, {title}", "e74de8decd998061": "cierra", + "2d7d0917e9d23b98": "Hilo sin título", + "2025fc2a5f89a7fb": "Abrir el hilo {title}", "b7b88aa36ad9512b": "Alguien", "02de63c7a0ebd94c": "Cargando issue", "f776ce04009278c5": "No se pudieron leer los comentarios anteriores.", @@ -2312,6 +2314,8 @@ "115e0df4e8da2704": "Asignados", "7dd58ad67a6de5ba": "nadie", "325276a3fe4e9d12": "Pull requests vinculadas", + "f7068768fdf3e96b": "Hilos vinculados", + "0cfebee8b40cdf6e": "Hilo archivado", "ab8222ce9132da09": "Descripción", "051acc34eaf9d1df": "Actividad", "9d82ebf35bfb4043": "Aquí no ha pasado nada todavía.", @@ -2368,7 +2372,6 @@ "e880959d9520231a": "Revisar cambios", "9e25940062052a95": "Copiar enlace de la PR o hilo", "6a433e2e6d1cfd88": "Nuevo hilo · {environment}", - "2d7d0917e9d23b98": "Hilo sin título", "fb49961cfffa5467": "Cerrar paleta de comandos", "6fdd3baa7bafa38b": "Buscar comandos, proyectos e hilos", "fd47ac08956ffcbc": "Buscar comandos, proyectos e hilos…", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 28ec2284fca74..d9c524718f512 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -2279,6 +2279,8 @@ "6fb238486abb5267": "Modifier les assignés", "a90c583cbd5151e5": "Pull request {number} {status}, {title}", "e74de8decd998061": "ferme", + "2d7d0917e9d23b98": "Fil sans titre", + "2025fc2a5f89a7fb": "Ouvrir le fil {title}", "b7b88aa36ad9512b": "Quelqu’un", "02de63c7a0ebd94c": "Chargement du ticket", "f776ce04009278c5": "Les commentaires plus anciens n’ont pas pu être lus.", @@ -2312,6 +2314,8 @@ "115e0df4e8da2704": "Assignés", "7dd58ad67a6de5ba": "personne", "325276a3fe4e9d12": "Pull requests associées", + "f7068768fdf3e96b": "Fils associés", + "0cfebee8b40cdf6e": "Fil archivé", "ab8222ce9132da09": "Description", "051acc34eaf9d1df": "Activité", "9d82ebf35bfb4043": "Rien ne s’est encore passé ici.", @@ -2368,7 +2372,6 @@ "e880959d9520231a": "Vérifier les modifications", "9e25940062052a95": "Copier le lien de la PR ou le fil", "6a433e2e6d1cfd88": "Nouveau fil · {environment}", - "2d7d0917e9d23b98": "Fil sans titre", "fb49961cfffa5467": "Fermer la palette de commandes", "6fdd3baa7bafa38b": "Rechercher des commandes, des projets et des fils", "fd47ac08956ffcbc": "Rechercher des commandes, des projets et des fils…", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index f6741fdb8b775..ba07751a4be89 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -2278,6 +2278,8 @@ "6fb238486abb5267": "担当者を編集", "a90c583cbd5151e5": "{status}のプルリクエスト {number}、{title}", "e74de8decd998061": "クローズ予定", + "2d7d0917e9d23b98": "無題のスレッド", + "2025fc2a5f89a7fb": "スレッド {title} を開く", "b7b88aa36ad9512b": "誰か", "02de63c7a0ebd94c": "Issue を読み込んでいます", "f776ce04009278c5": "以前のコメントを読み取れませんでした。", @@ -2309,6 +2311,8 @@ "115e0df4e8da2704": "担当者", "7dd58ad67a6de5ba": "なし", "325276a3fe4e9d12": "リンクされたプルリクエスト", + "f7068768fdf3e96b": "リンクされたスレッド", + "0cfebee8b40cdf6e": "アーカイブ済みのスレッド", "ab8222ce9132da09": "説明", "051acc34eaf9d1df": "アクティビティ", "9d82ebf35bfb4043": "まだアクティビティはありません。", @@ -2365,7 +2369,6 @@ "e880959d9520231a": "変更を確認", "9e25940062052a95": "PR のリンクまたはスレッドをコピー", "6a433e2e6d1cfd88": "新しいスレッド · {environment}", - "2d7d0917e9d23b98": "無題のスレッド", "fb49961cfffa5467": "コマンドパレットを閉じる", "6fdd3baa7bafa38b": "コマンド、プロジェクト、スレッドを検索", "fd47ac08956ffcbc": "コマンド、プロジェクト、スレッドを検索…", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index b1ef20ba0f347..5ec8e88b484d4 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -2280,6 +2280,8 @@ "6fb238486abb5267": "담당자 편집", "a90c583cbd5151e5": "{status} 풀 리퀘스트 {number}, {title}", "e74de8decd998061": "닫을 예정", + "2d7d0917e9d23b98": "제목 없는 스레드", + "2025fc2a5f89a7fb": "스레드 {title} 열기", "b7b88aa36ad9512b": "알 수 없는 사용자", "02de63c7a0ebd94c": "이슈 불러오는 중", "f776ce04009278c5": "이전 댓글을 읽을 수 없습니다.", @@ -2313,6 +2315,8 @@ "115e0df4e8da2704": "담당자", "7dd58ad67a6de5ba": "없음", "325276a3fe4e9d12": "연결된 풀 리퀘스트", + "f7068768fdf3e96b": "연결된 스레드", + "0cfebee8b40cdf6e": "보관된 스레드", "ab8222ce9132da09": "설명", "051acc34eaf9d1df": "활동", "9d82ebf35bfb4043": "아직 활동이 없습니다.", @@ -2369,7 +2373,6 @@ "e880959d9520231a": "변경 사항 검토", "9e25940062052a95": "PR 링크 또는 스레드 복사", "6a433e2e6d1cfd88": "새 스레드 · {environment}", - "2d7d0917e9d23b98": "제목 없는 스레드", "fb49961cfffa5467": "명령 팔레트 닫기", "6fdd3baa7bafa38b": "명령, 프로젝트, 스레드 검색", "fd47ac08956ffcbc": "명령, 프로젝트, 스레드 검색…", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index b40494fca3885..e4e10d1234b27 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -2279,6 +2279,8 @@ "6fb238486abb5267": "Editar responsáveis", "a90c583cbd5151e5": "Pull request {number} {status}, {title}", "e74de8decd998061": "fecha", + "2d7d0917e9d23b98": "Thread sem título", + "2025fc2a5f89a7fb": "Abrir a thread {title}", "b7b88aa36ad9512b": "Alguém", "02de63c7a0ebd94c": "Carregando issue", "f776ce04009278c5": "Não foi possível ler os comentários mais antigos.", @@ -2312,6 +2314,8 @@ "115e0df4e8da2704": "Responsáveis", "7dd58ad67a6de5ba": "ninguém", "325276a3fe4e9d12": "Pull requests vinculados", + "f7068768fdf3e96b": "Threads vinculadas", + "0cfebee8b40cdf6e": "Thread arquivada", "ab8222ce9132da09": "Descrição", "051acc34eaf9d1df": "Atividade", "9d82ebf35bfb4043": "Nada aconteceu aqui ainda.", @@ -2368,7 +2372,6 @@ "e880959d9520231a": "Revisar alterações", "9e25940062052a95": "Copiar link do PR ou thread", "6a433e2e6d1cfd88": "Nova thread · {environment}", - "2d7d0917e9d23b98": "Thread sem título", "fb49961cfffa5467": "Fechar paleta de comandos", "6fdd3baa7bafa38b": "Pesquisar comandos, projetos e threads", "fd47ac08956ffcbc": "Pesquisar comandos, projetos e threads…", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index cadf07e57eda9..4323f4425f844 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -2327,6 +2327,8 @@ "6fb238486abb5267": "Изменить исполнителей", "a90c583cbd5151e5": "Пул-реквест {number} ({status}), {title}", "e74de8decd998061": "закроет", + "2d7d0917e9d23b98": "Тред без названия", + "2025fc2a5f89a7fb": "Открыть тред {title}", "b7b88aa36ad9512b": "Кто-то", "02de63c7a0ebd94c": "Загрузка issue", "f776ce04009278c5": "Не удалось прочитать старые комментарии.", @@ -2364,6 +2366,8 @@ "115e0df4e8da2704": "Исполнители", "7dd58ad67a6de5ba": "нет", "325276a3fe4e9d12": "Привязанные пул-реквесты", + "f7068768fdf3e96b": "Привязанные треды", + "0cfebee8b40cdf6e": "Архивный тред", "ab8222ce9132da09": "Описание", "051acc34eaf9d1df": "Активность", "9d82ebf35bfb4043": "Здесь пока ничего не происходило.", @@ -2420,7 +2424,6 @@ "e880959d9520231a": "Проверить изменения", "9e25940062052a95": "Копировать ссылку на PR или тред", "6a433e2e6d1cfd88": "Новый тред · {environment}", - "2d7d0917e9d23b98": "Тред без названия", "fb49961cfffa5467": "Закрыть палитру команд", "6fdd3baa7bafa38b": "Поиск команд, проектов и тредов", "fd47ac08956ffcbc": "Поиск команд, проектов и тредов…", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 3a0273aef36fd..13d654d07bba0 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -2279,6 +2279,8 @@ "6fb238486abb5267": "Redigera tilldelade", "a90c583cbd5151e5": "{status} pull request {number}, {title}", "e74de8decd998061": "stänger", + "2d7d0917e9d23b98": "Namnlös tråd", + "2025fc2a5f89a7fb": "Öppna tråden {title}", "b7b88aa36ad9512b": "Någon", "02de63c7a0ebd94c": "Läser in ärende", "f776ce04009278c5": "Äldre kommentarer kunde inte läsas.", @@ -2316,6 +2318,8 @@ "115e0df4e8da2704": "Tilldelade", "7dd58ad67a6de5ba": "ingen", "325276a3fe4e9d12": "Länkade pull requests", + "f7068768fdf3e96b": "Länkade trådar", + "0cfebee8b40cdf6e": "Arkiverad tråd", "ab8222ce9132da09": "Beskrivning", "051acc34eaf9d1df": "Aktivitet", "9d82ebf35bfb4043": "Inget har hänt här än.", @@ -2372,7 +2376,6 @@ "e880959d9520231a": "Granska ändringar", "9e25940062052a95": "Kopiera PR-länk eller tråd", "6a433e2e6d1cfd88": "Ny tråd · {environment}", - "2d7d0917e9d23b98": "Namnlös tråd", "fb49961cfffa5467": "Stäng kommandopaletten", "6fdd3baa7bafa38b": "Sök kommandon, projekt och trådar", "fd47ac08956ffcbc": "Sök kommandon, projekt och trådar…", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index f1c394c60c606..b80a4e832249a 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -2282,6 +2282,8 @@ "6fb238486abb5267": "编辑受理人", "a90c583cbd5151e5": "{status} 的 PR {number},{title}", "e74de8decd998061": "将关闭", + "2d7d0917e9d23b98": "未命名会话", + "2025fc2a5f89a7fb": "打开会话 {title}", "b7b88aa36ad9512b": "某人", "02de63c7a0ebd94c": "正在加载 issue", "f776ce04009278c5": "无法读取较早的评论。", @@ -2313,6 +2315,8 @@ "115e0df4e8da2704": "受理人", "7dd58ad67a6de5ba": "无", "325276a3fe4e9d12": "已关联 PR", + "f7068768fdf3e96b": "已关联的会话", + "0cfebee8b40cdf6e": "已归档的会话", "ab8222ce9132da09": "描述", "051acc34eaf9d1df": "活动", "9d82ebf35bfb4043": "这里还没有任何动态。", @@ -2369,7 +2373,6 @@ "e880959d9520231a": "查看更改", "9e25940062052a95": "复制 PR 链接或会话", "6a433e2e6d1cfd88": "新建会话 · {environment}", - "2d7d0917e9d23b98": "未命名会话", "fb49961cfffa5467": "关闭命令面板", "6fdd3baa7bafa38b": "搜索命令、项目和会话", "fd47ac08956ffcbc": "搜索命令、项目和会话…", diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index a765c28476322..2e73a401caaff 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -138,6 +138,7 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.issuesComments]: AuthOrchestrationReadScope, [WS_METHODS.issuesTemplates]: AuthOrchestrationReadScope, [WS_METHODS.issuesCandidates]: AuthOrchestrationReadScope, + [WS_METHODS.issuesLinkedThreads]: AuthOrchestrationReadScope, [WS_METHODS.issueTrackersList]: AuthOrchestrationReadScope, [WS_METHODS.issueTrackersConnect]: AuthSettingsWriteScope, [WS_METHODS.issueTrackersBindProject]: AuthSettingsWriteScope, diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index b651a8904f5bb..04f5c9082b606 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -230,6 +230,7 @@ export const make = Effect.gen(function* () { pullRequestChecks: true, issues: true, linkedThreadRefreshes: true, + issueLinkedThreads: true, sideChats: true, vcsBranchStatus: true, inlineMessageContext: true, diff --git a/apps/server/src/issue/linkedThreads.test.ts b/apps/server/src/issue/linkedThreads.test.ts new file mode 100644 index 0000000000000..6b5005398869a --- /dev/null +++ b/apps/server/src/issue/linkedThreads.test.ts @@ -0,0 +1,56 @@ +import { IssueTrackerKind } from "@t3tools/contracts"; +import { expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; + +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import { listLinkedIssueThreads } from "./linkedThreads.ts"; + +const encodePayload = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); + +it.effect("finds every thread linked to exactly one issue, newest activity first", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const at = (day: number) => `2026-11-0${day}T00:00:00.000Z`; + const issue = { tracker: "linear", host: "linear.app", scope: "eng", key: "ENG-7" }; + const fixtures = [ + { id: "older", day: 1, issues: [issue] }, + { id: "newer", day: 2, issues: [{ ...issue, key: "ENG-8" }, issue] }, + { id: "settled", day: 3, issues: [issue], payload: { settledOverride: "settled" } }, + { id: "archived", day: 4, issues: [issue], archived: true }, + { id: "deleted", day: 5, issues: [issue], deleted: true }, + { id: "side-chat", day: 5, issues: [issue], payload: { lineage: { sideChat: true } } }, + { id: "other-key", day: 5, issues: [{ ...issue, key: "ENG-70" }] }, + { id: "other-scope", day: 5, issues: [{ ...issue, scope: "design" }] }, + { id: "other-tracker", day: 5, issues: [{ ...issue, tracker: "github" }] }, + { id: "unlinked", day: 5, issues: [] }, + ]; + for (const fixture of fixtures) { + const payload = yield* encodePayload({ ...fixture.payload, issues: fixture.issues }); + yield* sql` + INSERT INTO orchestration_v2_projection_threads ( + thread_id, project_id, title, default_provider, runtime_mode, interaction_mode, + created_at, updated_at, archived_at, deleted_at, payload_json + ) VALUES ( + ${fixture.id}, 'project-1', ${fixture.id}, 'codex', 'full-access', 'default', + ${at(1)}, ${at(fixture.day)}, ${fixture.archived ? at(fixture.day) : null}, + ${fixture.deleted ? at(fixture.day) : null}, ${payload} + ) + `; + } + + const result = yield* listLinkedIssueThreads({ + tracker: IssueTrackerKind.make("linear"), + host: "Linear.app", + scope: "ENG", + key: "ENG-7", + }); + expect(result.threads.map((thread) => [thread.id, thread.settled, thread.archivedAt])).toEqual([ + ["archived", false, at(4)], + ["settled", true, null], + ["newer", false, null], + ["older", false, null], + ]); + }).pipe(Effect.provide(SqlitePersistence.layerMemory)), +); diff --git a/apps/server/src/issue/linkedThreads.ts b/apps/server/src/issue/linkedThreads.ts new file mode 100644 index 0000000000000..c38b75c6b0944 --- /dev/null +++ b/apps/server/src/issue/linkedThreads.ts @@ -0,0 +1,64 @@ +import { + IssueLinkedThreadsResult, + IssueOperationError, + threadIssueKeysEqual, + type ThreadIssueKey, +} from "@t3tools/contracts"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; + +const decodeLinkedThreads = Schema.decodeUnknownEffect(IssueLinkedThreadsResult); + +/** The threads an issue is linked to; the rows and filters `linkedThreads` uses for pull requests. */ +export const listLinkedIssueThreads = Effect.fn("listLinkedIssueThreads")( + function* (key: ThreadIssueKey) { + const sql = yield* SqlClient.SqlClient; + const rows = yield* sql<{ + id: string; + projectId: string; + title: string; + archivedAt: string | null; + settled: number; + tracker: ThreadIssueKey["tracker"]; + host: string; + scope: string; + key: string; + }>` + SELECT t.thread_id AS id, t.project_id AS "projectId", t.title, + t.archived_at AS "archivedAt", + (json_extract(t.payload_json, '$.settledAt') IS NOT NULL + OR json_extract(t.payload_json, '$.settledOverride') IS 'settled') AS settled, + json_extract(link.value, '$.tracker') AS tracker, + json_extract(link.value, '$.host') AS host, + json_extract(link.value, '$.scope') AS scope, + json_extract(link.value, '$.key') AS key, + 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 + ORDER BY "updatedAt" DESC, id ASC + `.pipe(NodeSqliteClient.readOnly); + const threads = rows + .filter((row) => threadIssueKeysEqual(row, key)) + .map(({ id, projectId, title, archivedAt, settled }) => ({ + id, + projectId, + title, + archivedAt, + settled: settled === 1, + })); + return yield* decodeLinkedThreads({ threads }); + }, + Effect.mapError( + (cause) => + new IssueOperationError({ + operation: "linkedThreads", + detail: "Could not load linked threads.", + cause, + }), + ), +); diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index a103dc14e3678..a2b698657afcb 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -149,6 +149,7 @@ const RPC_AGGREGATES = { [WS_METHODS.issuesComments]: "issues", [WS_METHODS.issuesTemplates]: "issues", [WS_METHODS.issuesCandidates]: "issues", + [WS_METHODS.issuesLinkedThreads]: "issues", [WS_METHODS.issuesCreate]: "issues", [WS_METHODS.issuesComment]: "issues", [WS_METHODS.issuesUpdate]: "issues", diff --git a/apps/server/src/orchestration-v2/ThreadIssueService.test.ts b/apps/server/src/orchestration-v2/ThreadIssueService.test.ts index 8ddbd52f069f1..0962e5ff165c1 100644 --- a/apps/server/src/orchestration-v2/ThreadIssueService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadIssueService.test.ts @@ -4,6 +4,7 @@ import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as Orchestrator from "./Orchestrator.ts"; import * as ThreadIssueService from "./ThreadIssueService.ts"; @@ -30,6 +31,7 @@ describe("ThreadIssueService", () => { ThreadIssueService.layer.pipe( Layer.provide( Layer.mergeAll( + SqlitePersistence.layerMemory, Layer.mock(Orchestrator.OrchestratorV2)({ getThreadShell: (threadId) => Effect.fail(new Orchestrator.OrchestratorProjectionError({ threadId })), diff --git a/apps/server/src/orchestration-v2/ThreadIssueService.ts b/apps/server/src/orchestration-v2/ThreadIssueService.ts index 49db6af410480..99e69ab610a47 100644 --- a/apps/server/src/orchestration-v2/ThreadIssueService.ts +++ b/apps/server/src/orchestration-v2/ThreadIssueService.ts @@ -8,6 +8,8 @@ import { CommandId, threadIssueKeysEqual, + type IssueLinkedThreadsResult, + type IssueOperationError, type IssueRef, type ThreadId, type ThreadIssueKey, @@ -17,7 +19,9 @@ import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/sql/SqlClient"; +import { listLinkedIssueThreads } from "../issue/linkedThreads.ts"; import * as Orchestrator from "./Orchestrator.ts"; export interface LinkThreadIssueInput { @@ -44,12 +48,17 @@ export class ThreadIssueService extends Context.Service< readonly unlink: ( input: UnlinkThreadIssueInput, ) => Effect.Effect<{ readonly wasLinked: boolean }, Orchestrator.OrchestratorV2Error>; + /** Every thread the issue is linked to, most recently active first. */ + readonly linkedThreads: ( + key: ThreadIssueKey, + ) => Effect.Effect; } >()("t3/orchestration-v2/ThreadIssueService") {} const make = Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; const random = yield* SecureRandom.SecureRandom; + const sql = yield* SqlClient.SqlClient; const commandId = (tag: string, threadId: ThreadId) => random.uuidV4().pipe( @@ -103,7 +112,10 @@ const make = Effect.gen(function* () { }, ); - return ThreadIssueService.of({ link, unlink }); + const linkedThreads: ThreadIssueService["Service"]["linkedThreads"] = (key) => + listLinkedIssueThreads(key).pipe(Effect.provideService(SqlClient.SqlClient, sql)); + + return ThreadIssueService.of({ link, unlink, linkedThreads }); }); export const layer = Layer.effect(ThreadIssueService, make); diff --git a/apps/server/src/pullRequest/linkedThreads.test.ts b/apps/server/src/pullRequest/linkedThreads.test.ts index 2dac788641586..90b097e147298 100644 --- a/apps/server/src/pullRequest/linkedThreads.test.ts +++ b/apps/server/src/pullRequest/linkedThreads.test.ts @@ -280,6 +280,17 @@ it("signals linked-thread changes only when a linked answer could change", () => null, ]); + const issue = { tracker: "linear", host: "linear.app", scope: "eng", key: "ENG-7" }; + const issueLinks = makeLinkedThreadsChangeDetector(); + expect( + [ + event("thread.created", {}), + event("thread.issue-synced", { issues: [issue as never] }), + event("thread.issue-synced", { issues: [issue as never] }), + event("thread.issue-synced", { issues: [] }), + ].map(issueLinks), + ).toEqual([null, "changed", null, "changed"]); + const afterRestart = makeLinkedThreadsChangeDetector(); expect(afterRestart(event("thread.created", { title: "New" }))).toBe(null); expect( diff --git a/apps/server/src/pullRequest/linkedThreads.ts b/apps/server/src/pullRequest/linkedThreads.ts index 1fb6b5f5dfebf..787a85ebdb3e2 100644 --- a/apps/server/src/pullRequest/linkedThreads.ts +++ b/apps/server/src/pullRequest/linkedThreads.ts @@ -7,6 +7,7 @@ import { import { PullRequestLinkedThreadsResult, PullRequestOperationError, + threadIssueKeyOf, type OrchestrationV2AppThread, type OrchestrationV2DomainEvent, type ThreadId, @@ -73,12 +74,13 @@ export const listLinkedPullRequestThreads = Effect.fn("listLinkedPullRequestThre ), ); -// Mirrors the rows and filters of `listLinkedPullRequestThreads`. +// Mirrors the rows and filters of `listLinkedPullRequestThreads` and `listLinkedIssueThreads`. function linkedKeys(thread: OrchestrationV2AppThread): ReadonlyArray { if (thread.deletedAt !== null || thread.lineage.sideChat === true) return []; - return visibleThreadPullRequests(thread.pullRequests ?? []) - .map(threadPullRequestKeyOf) - .toSorted(); + return [ + ...visibleThreadPullRequests(thread.pullRequests ?? []).map(threadPullRequestKeyOf), + ...(thread.issues ?? []).map(threadIssueKeyOf), + ].toSorted(); } function linkedThreadsView( @@ -97,8 +99,8 @@ function linkedThreadsView( } /** - * Tells how a domain event changed `pullRequests.linkedThreads` answers, so readers can refresh on - * change instead of polling. `reordered` means activity on a linked thread, or on one whose links + * Tells how a domain event changed `pullRequests.linkedThreads` and `issues.linkedThreads` + * answers, so readers can refresh on change instead of polling. `reordered` means activity on a linked thread, or on one whose links * are unknown since a restart, which can reorder answers. A thread's first full event after a * restart counts as a change, since its earlier links are unknown. */ diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index 4583ca2209277..26456c0da320d 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -115,6 +115,7 @@ import * as ProviderRegistry from "./provider/ProviderRegistry.ts"; import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts"; import * as PullRequestReviewGuideService from "./pullRequest/PullRequestReviewGuideService.ts"; import * as IssueService from "./issue/IssueService.ts"; +import * as ThreadIssueService from "./orchestration-v2/ThreadIssueService.ts"; import * as IssueTrackerConnections from "./issue/IssueTrackerConnections.ts"; import * as PullRequestService from "./pullRequest/PullRequestService.ts"; import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts"; @@ -861,6 +862,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}), Layer.mock(PullRequestService.PullRequestService)({}), Layer.mock(IssueService.IssueService)({}), + Layer.mock(ThreadIssueService.ThreadIssueService)({}), Layer.mock(IssueTrackerConnections.IssueTrackerConnections)({}), Layer.mock(PullRequestSyncReactor.PullRequestSyncReactor)({}), Layer.mock(RelayClient.RelayClient)({}), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index bbe80f28e9681..63d45c48816e4 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -250,6 +250,7 @@ import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts"; import * as TriageService from "./triage/TriageService.ts"; import * as PullRequestService from "./pullRequest/PullRequestService.ts"; import * as IssueService from "./issue/IssueService.ts"; +import * as ThreadIssueService from "./orchestration-v2/ThreadIssueService.ts"; import * as IssueTrackerConnections from "./issue/IssueTrackerConnections.ts"; import * as PullRequestReviewGuideService from "./pullRequest/PullRequestReviewGuideService.ts"; import { listLinkedPullRequestThreads } from "./pullRequest/linkedThreads.ts"; @@ -1484,6 +1485,7 @@ export const layerWsRpc = ( const guestShares = yield* GuestShareService.GuestShareService; const pullRequests = yield* PullRequestService.PullRequestService; const issues = yield* IssueService.IssueService; + const threadIssues = yield* ThreadIssueService.ThreadIssueService; const issueTrackers = yield* IssueTrackerConnections.IssueTrackerConnections; const reviewGuides = yield* PullRequestReviewGuideService.PullRequestReviewGuideService; const pullRequestSync = yield* PullRequestSyncReactor.PullRequestSyncReactor; @@ -1978,6 +1980,7 @@ export const layerWsRpc = ( [WS_METHODS.issuesComments]: (input) => issues.comments(input), [WS_METHODS.issuesTemplates]: (input) => issues.templates(input), [WS_METHODS.issuesCandidates]: (input) => issues.candidates(input), + [WS_METHODS.issuesLinkedThreads]: (input) => threadIssues.linkedThreads(input), [WS_METHODS.issuesCreate]: (input) => issues.create(input), [WS_METHODS.issuesComment]: (input) => issues.comment(input), [WS_METHODS.issuesUpdate]: (input) => issues.update(input), @@ -3601,6 +3604,7 @@ export const layer = Layer.unwrap( const npmRelease = yield* NpmRelease.NpmRelease; const pullRequests = yield* PullRequestService.PullRequestService; const issues = yield* IssueService.IssueService; + const threadIssues = yield* ThreadIssueService.ThreadIssueService; const issueTrackers = yield* IssueTrackerConnections.IssueTrackerConnections; const reviewGuides = yield* PullRequestReviewGuideService.PullRequestReviewGuideService; const peerLinks = yield* PeerLinks.PeerLinks; @@ -3692,6 +3696,7 @@ export const layer = Layer.unwrap( // Share server-lifetime PR caches so WS mutations invalidate every client's HTTP diffs. Layer.provide(Layer.succeed(PullRequestService.PullRequestService, pullRequests)), Layer.provide(Layer.succeed(IssueService.IssueService, issues)), + Layer.provide(Layer.succeed(ThreadIssueService.ThreadIssueService, threadIssues)), Layer.provide( Layer.succeed(IssueTrackerConnections.IssueTrackerConnections, issueTrackers), ), diff --git a/apps/web/src/components/ThreadLinkPicker.tsx b/apps/web/src/components/ThreadLinkPicker.tsx new file mode 100644 index 0000000000000..8b7befc6ba915 --- /dev/null +++ b/apps/web/src/components/ThreadLinkPicker.tsx @@ -0,0 +1,87 @@ +import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { CheckIcon, MessageSquareIcon } from "lucide-react"; +import { T, useGT } from "gt-react"; +import { useState } from "react"; + +import { useProjects, useVisibleThreadShells } from "~/state/entities"; +import { useThreadSearch } from "~/state/queries"; + +import { Command, CommandInput, CommandItem, CommandList } from "./ui/command"; + +type ThreadShell = ReturnType[number]; + +/** Search over an environment's unarchived threads, to link one to a pull request or an issue. */ +export function ThreadLinkPicker({ + environmentId, + pending, + isLinked, + onSelect, +}: { + environmentId: EnvironmentId; + pending: boolean; + isLinked: (thread: ThreadShell) => boolean; + onSelect: (threadId: ThreadId) => void; +}) { + const gt = useGT(); + const threads = useVisibleThreadShells(); + const projects = useProjects(); + const [query, setQuery] = useState(""); + // Mounts older settled threads matching the query, which shells may leave out. + useThreadSearch([environmentId], query, { titlesOnly: true }); + const projectNames = new Map( + projects + .filter((project) => project.environmentId === environmentId) + .map((project) => [project.id, project.title]), + ); + const search = query.trim().toLocaleLowerCase(); + const candidates = threads + .filter( + (thread) => + thread.environmentId === environmentId && + thread.archivedAt === null && + `${thread.title} ${projectNames.get(thread.projectId) ?? ""}` + .toLocaleLowerCase() + .includes(search), + ) + .toSorted((a, b) => b.updatedAt.localeCompare(a.updatedAt)); + return ( + + + + {candidates.length === 0 ? ( +
+ No active threads found. +
+ ) : ( + candidates.map((thread) => { + const linked = isLinked(thread); + return ( + onSelect(thread.id)} + > + + + {thread.title || gt("Untitled thread")} + + {projectNames.get(thread.projectId)} + + + {linked ? ( + <> + + + Linked + + + ) : null} + + ); + }) + )} +
+
+ ); +} diff --git a/apps/web/src/components/issue/IssueDetailPanel.tsx b/apps/web/src/components/issue/IssueDetailPanel.tsx index 20a9d7aa93cf8..e56a89c60f091 100644 --- a/apps/web/src/components/issue/IssueDetailPanel.tsx +++ b/apps/web/src/components/issue/IssueDetailPanel.tsx @@ -12,7 +12,6 @@ import { } from "@t3tools/client-runtime/issue-selection"; import { isSelected, toggleSelection } from "@t3tools/client-runtime/pull-request-selection"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; -import { AuthOrchestrationOperateScope, threadIssueKeysEqual } from "@t3tools/contracts"; import type { EnvironmentId, IssueAssigneeCandidate, @@ -31,8 +30,6 @@ import { CheckIcon, ChevronDownIcon, ExternalLinkIcon, - Link2Icon, - Link2OffIcon, TagIcon, UserPlusIcon, UsersIcon, @@ -43,10 +40,8 @@ import { useContext, useState, type ReactNode } from "react"; import { RefreshIcon } from "~/components/ui/refresh-icon"; import { m } from "~/i18n/messages"; import { issueEnvironment, refreshIssueLists } from "~/state/issues"; -import { useProjects, useThreadShell } from "~/state/entities"; +import { useProjects } from "~/state/entities"; import { useEnvironmentQuery } from "~/state/query"; -import { useEnvironmentScope } from "~/state/session"; -import { threadEnvironment } from "~/state/threads"; import { useAtomCommand } from "~/state/use-atom-command"; import { formatRelativeTimeLabel } from "~/timestampFormat"; @@ -57,7 +52,6 @@ import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu"; import { cn } from "~/lib/utils"; import { PullRequestMetaRow, PullRequestSection } from "../pullRequest/PullRequestSummaryTab"; import { toastManager } from "../ui/toast"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { PullRequestCandidatePicker } from "../pullRequest/PullRequestCandidatePicker"; import { PullRequestCommentBody } from "../pullRequest/PullRequestCommentBody"; import { PullRequestDetailTitleRow } from "../pullRequest/PullRequestDetailLayout"; @@ -74,89 +68,11 @@ import { } from "../pullRequest/pullRequestPresentation"; import { IssueCommentComposer } from "./IssueCommentComposer"; import { IssueDetailGhost } from "./IssueDetailGhost"; +import { IssueThreadLinks } from "./IssueThreadLinks"; import { ReactionBar } from "../pullRequest/PullRequestReactions"; import { PullRequestsUnavailableState } from "../pullRequest/PullRequestsUnavailableState"; import { issueTrackerPresentation, issueStatePresentation } from "./issuePresentation"; -/** - * Links or unlinks the issue to the thread it is shown beside. Dispatches the orchestration - * command directly, as pull request linking does. - */ -function IssueThreadLinkButton({ - environmentId, - reference, - issue, - threadRef, -}: { - environmentId: EnvironmentId; - reference: IssueRef; - issue: Pick; - threadRef: ScopedThreadRef; -}) { - const gt = useGT(); - const thread = useThreadShell(threadRef.environmentId === environmentId ? threadRef : null); - const canOperate = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope); - const link = useAtomCommand(threadEnvironment.linkIssue, { reportFailure: false }); - const unlink = useAtomCommand(threadEnvironment.unlinkIssue, { reportFailure: false }); - const [pending, setPending] = useState(false); - if (thread === null || !canOperate) return null; - const key = { ...reference, host: reference.host ?? "" }; - const linked = (thread.issues ?? []).some((existing) => threadIssueKeysEqual(existing, key)); - const toggle = async () => { - if (pending || reference.host === undefined) return; - setPending(true); - const result = await (linked - ? unlink({ environmentId, input: { threadId: threadRef.threadId, ...key } }) - : link({ - environmentId, - input: { - threadId: threadRef.threadId, - ...key, - url: issue.url, - displayKey: issue.displayKey, - title: issue.title, - source: "manual", - }, - })); - setPending(false); - if (result._tag === "Failure") { - toastManager.add({ - type: "error", - title: linked ? m(msg("Could not unlink the issue")) : m(msg("Could not link the issue")), - description: readableFailure( - squashAtomCommandFailure(result), - m(msg("The server refused it.")), - ), - }); - } - }; - return ( - - void toggle()} - /> - } - > - {linked ? ( - - ) : ( - - )} - - - {linked ? Unlink from this thread : Link to this thread} - - - ); -} - function IssueReactionBar({ reactions, canReact, @@ -649,14 +565,13 @@ export function IssueDetailPanel({ {stateControl} - {threadRef ? ( - - ) : null} + + } + /> + + {gt("{label}. Search in the command palette.", { label: linkedThreadsLabel })} + + + ) : null} + {canOperate ? ( + + { + if (thread === null) setPickerOpen(true); + else void changeLink(thread.id, linkedHere); + }} + /> + } + > + {linkedHere ? ( + + ) : ( + + )} + + + {linkedHere ? ( + Unlink from this thread + ) : thread === null ? ( + gt("Link to thread") + ) : ( + Link to this thread + )} + + + ) : null} + {pickerOpen ? ( + + + + Link issue to a thread + + + (candidate.issues ?? []).some((existing) => threadIssueKeysEqual(existing, key)) + } + onSelect={(threadId) => void changeLink(threadId, false)} + /> + + + ) : null} + + ); +} diff --git a/apps/web/src/components/pullRequest/PullRequestThreadLinks.tsx b/apps/web/src/components/pullRequest/PullRequestThreadLinks.tsx index 9aca4ad6c35b2..66c43846031da 100644 --- a/apps/web/src/components/pullRequest/PullRequestThreadLinks.tsx +++ b/apps/web/src/components/pullRequest/PullRequestThreadLinks.tsx @@ -5,7 +5,7 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { visibleLinkedThreads } from "@t3tools/client-runtime/state/threads"; import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import type { EnvironmentId, PullRequestRef, ScopedThreadRef, ThreadId } from "@t3tools/contracts"; -import { CheckIcon, MessageSquareIcon } from "lucide-react"; +import { MessageSquareIcon } from "lucide-react"; import { Branch, msg, T, useGT } from "gt-react"; import { useState } from "react"; @@ -18,19 +18,16 @@ import { normalizeThreadPullRequestKey } from "@t3tools/client-runtime/thread-pu import { useAnyEnvironmentHiding, useEnvironmentThreadRefs, - useProjects, useServerConfigs, useThreadShell, - useVisibleThreadShells, } from "~/state/entities"; import { pullRequestEnvironment } from "~/state/pullRequests"; import { environmentThreadShells } from "~/state/threads"; import { useEnvironmentQuery } from "~/state/query"; -import { useThreadSearch } from "~/state/queries"; import { appAtomRegistry } from "~/rpc/atomRegistry"; import { openCommandPalette } from "~/commandPaletteBus"; import { Button } from "../ui/button"; -import { Command, CommandInput, CommandItem, CommandList } from "../ui/command"; +import { ThreadLinkPicker } from "../ThreadLinkPicker"; import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog"; import { MenuItem } from "../ui/menu"; import { toastManager } from "../ui/toast"; @@ -217,10 +214,10 @@ function EnabledPullRequestThreadLinks({ to a thread - linking.isLinked(candidate, url)} onSelect={(threadId) => void changeLink(threadId, false)} /> @@ -229,79 +226,3 @@ function EnabledPullRequestThreadLinks({ ); } - -function ThreadPicker({ - environmentId, - url, - pending, - onSelect, -}: { - environmentId: EnvironmentId; - url: string; - pending: boolean; - onSelect: (threadId: ThreadId) => void; -}) { - const gt = useGT(); - const threads = useVisibleThreadShells(); - const linking = usePullRequestLinking(environmentId); - const projects = useProjects(); - const [query, setQuery] = useState(""); - // Mounts older settled threads matching the query, which shells may leave out. - useThreadSearch([environmentId], query, { titlesOnly: true }); - const projectNames = new Map( - projects - .filter((project) => project.environmentId === environmentId) - .map((project) => [project.id, project.title]), - ); - const search = query.trim().toLocaleLowerCase(); - const candidates = threads - .filter( - (thread) => - thread.environmentId === environmentId && - thread.archivedAt === null && - `${thread.title} ${projectNames.get(thread.projectId) ?? ""}` - .toLocaleLowerCase() - .includes(search), - ) - .toSorted((a, b) => b.updatedAt.localeCompare(a.updatedAt)); - return ( - - - - {candidates.length === 0 ? ( -
- No active threads found. -
- ) : ( - candidates.map((thread) => { - const linked = linking.isLinked(thread, url); - return ( - onSelect(thread.id)} - > - - - {thread.title || gt("Untitled thread")} - - {projectNames.get(thread.projectId)} - - - {linked ? ( - <> - - - Linked - - - ) : null} - - ); - }) - )} -
-
- ); -} diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 5aca70101b1f3..ddbfade77b4a8 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -2458,6 +2458,10 @@ "33c7e68fca089036": "Thread, {title}", "b4b98a0287c282e2": "Auf einem anderen Rechner, daher kann der Agent dieses Rechners es nicht lesen. Entferne es oder wechsle zum Senden zurück.", "c6196d99000642b4": "Thread öffnen", + "34cc63390ad793cc": "Thread wählen", + "8f12309ead62e38a": "Threads oder Projekte durchsuchen...", + "2f664754d005d9a7": "Keine aktiven Threads gefunden.", + "6095e59daf8ac2d6": "Verknüpft", "dd52ffa80d5eff97": "Thread abgeschlossen", "fd1316b1f627872b": "Genehmigung erforderlich", "a3178769f8308cbc": "Thread fehlgeschlagen", @@ -5654,9 +5658,6 @@ "cdac45c7efe1cfcc": "keine", "115e0df4e8da2704": "Zugewiesene Personen", "7dd58ad67a6de5ba": "niemand", - "4a9e547eda5a1d3b": "Die Verknüpfung des Issues konnte nicht aufgehoben werden", - "6672a18b56815053": "Das Issue konnte nicht verknüpft werden", - "a0295b5f63009ecf": "Der Server hat es abgelehnt.", "ae9a4e2921967de9": "Labels konnten nicht geändert werden", "6ec1aa91fbfa75d2": "Zugewiesene Personen konnten nicht geändert werden", "4f2e859dcaa7569c": "Ältere Kommentare konnten nicht gelesen werden", @@ -5692,8 +5693,6 @@ "52f00fe91208ef71": "_Keine Beschreibung angegeben._", "56ca98b79cc9ce49": "Aktivität ({count})", "ddc5e5413923c471": "Du kannst hier nicht kommentieren.", - "1d1268c1a332a292": "Verknüpfung mit diesem Thread aufheben", - "882a7614e3caa566": "Mit diesem Thread verknüpfen", "516def6f5a881e00": "Schließt dieses Issue", "0014ce0aaf1bd68a": "Schreibgeschützt", "fd93f4720ff70aaf": "Keine", @@ -5713,6 +5712,15 @@ "309a68dc21af399d": "Beliebig", "4dc86e84bb5ece63": "Die Personen konnten nicht gelesen werden", "4103b6b8e0ff3f46": "Es gibt mehr Personen, als hier aufgeführt sind.", + "4a9e547eda5a1d3b": "Die Verknüpfung des Issues konnte nicht aufgehoben werden", + "6672a18b56815053": "Das Issue konnte nicht verknüpft werden", + "a0295b5f63009ecf": "Der Server hat es abgelehnt.", + "5fb273ac66588155": "{count, plural, one {Verknüpft von {count} Thread} other {Verknüpft von {count} Threads}}", + "938b14127a3c907d": "Verknüpfte Threads", + "5bde91110c65afca": "{label}. In der Befehlspalette suchen.", + "1d1268c1a332a292": "Verknüpfung mit diesem Thread aufheben", + "882a7614e3caa566": "Mit diesem Thread verknüpfen", + "bdb2f1444e74c895": "Issue mit einem Thread verknüpfen", "6a717189b43e9f0e": "Offen", "f8700aef3eb2cf71": "Geschlossen", "c9735ce17719123b": "Alle", @@ -6868,13 +6876,8 @@ ], "94154d8491776868": "{term, select, mr {Die Verknüpfung des Merge Requests konnte nicht aufgehoben werden} cr {Die Verknüpfung der Änderungsanfrage konnte nicht aufgehoben werden} other {Die Verknüpfung des Pull Requests konnte nicht aufgehoben werden}}", "29bb9b5b565a6df6": "{term, select, mr {Der Merge Request konnte nicht verknüpft werden} cr {Die Änderungsanfrage konnte nicht verknüpft werden} other {Der Pull Request konnte nicht verknüpft werden}}", - "5fb273ac66588155": "{count, plural, one {Verknüpft von {count} Thread} other {Verknüpft von {count} Threads}}", - "938b14127a3c907d": "Verknüpfte Threads", - "5bde91110c65afca": "{label}. In der Befehlspalette suchen.", "d37dbc4847107d90": "Verknüpfung mit diesem Thread lösen", "141d12d6b7f3c002": "Mit diesem Thread verknüpfen", - "34cc63390ad793cc": "Thread wählen", - "8f12309ead62e38a": "Threads oder Projekte durchsuchen...", "beb920ffd1cac72b": [ { "t": "Branch", @@ -6891,8 +6894,6 @@ " ", "mit einem Thread verknüpfen" ], - "2f664754d005d9a7": "Keine aktiven Threads gefunden.", - "6095e59daf8ac2d6": "Verknüpft", "5d7ee2409e2c527c": "Aktivität auf dem Host öffnen", "fcc3e653e0fff1d9": "{count, plural, one {{formatted} Autor} other {{formatted} Autoren}}", "b105bbd107c5f3ea": "{count, plural, one {{formatted} Antwort} other {{formatted} Antworten}}", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 246e11939fd89..11c9c1d83dd04 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -2457,6 +2457,10 @@ "33c7e68fca089036": "Thread, {title}", "b4b98a0287c282e2": "On another machine, so this machine's agent can't read it. Remove it or switch back to send.", "c6196d99000642b4": "Open thread", + "34cc63390ad793cc": "Choose a thread", + "8f12309ead62e38a": "Search threads or projects...", + "2f664754d005d9a7": "No active threads found.", + "6095e59daf8ac2d6": "Linked", "dd52ffa80d5eff97": "Thread completed", "fd1316b1f627872b": "Approval needed", "a3178769f8308cbc": "Thread failed", @@ -5655,9 +5659,6 @@ "cdac45c7efe1cfcc": "none", "115e0df4e8da2704": "Assignees", "7dd58ad67a6de5ba": "none", - "4a9e547eda5a1d3b": "Could not unlink the issue", - "6672a18b56815053": "Could not link the issue", - "a0295b5f63009ecf": "The server refused it.", "ae9a4e2921967de9": "Could not change labels", "6ec1aa91fbfa75d2": "Could not change assignees", "4f2e859dcaa7569c": "Older comments could not be read", @@ -5693,8 +5694,6 @@ "52f00fe91208ef71": "_No description provided._", "56ca98b79cc9ce49": "Activity ({count})", "ddc5e5413923c471": "You cannot comment here.", - "1d1268c1a332a292": "Unlink from this thread", - "882a7614e3caa566": "Link to this thread", "516def6f5a881e00": "Closes this issue", "0014ce0aaf1bd68a": "Read-only", "fd93f4720ff70aaf": "None", @@ -5714,6 +5713,15 @@ "309a68dc21af399d": "Anyone", "4dc86e84bb5ece63": "The people could not be read", "4103b6b8e0ff3f46": "More people exist than are listed here.", + "4a9e547eda5a1d3b": "Could not unlink the issue", + "6672a18b56815053": "Could not link the issue", + "a0295b5f63009ecf": "The server refused it.", + "5fb273ac66588155": "{count, plural, one {Linked from {count} thread} other {Linked from {count} threads}}", + "938b14127a3c907d": "Linked threads", + "5bde91110c65afca": "{label}. Search in the command palette.", + "1d1268c1a332a292": "Unlink from this thread", + "882a7614e3caa566": "Link to this thread", + "bdb2f1444e74c895": "Link issue to a thread", "6a717189b43e9f0e": "Open", "f8700aef3eb2cf71": "Closed", "c9735ce17719123b": "All", @@ -6874,13 +6882,8 @@ ], "94154d8491776868": "Could not unlink the {term, select, mr {merge request} cr {change request} other {pull request}}", "29bb9b5b565a6df6": "Could not link the {term, select, mr {merge request} cr {change request} other {pull request}}", - "5fb273ac66588155": "{count, plural, one {Linked from {count} thread} other {Linked from {count} threads}}", - "938b14127a3c907d": "Linked threads", - "5bde91110c65afca": "{label}. Search in the command palette.", "d37dbc4847107d90": "Unlink from this thread", "141d12d6b7f3c002": "Link to this thread", - "34cc63390ad793cc": "Choose a thread", - "8f12309ead62e38a": "Search threads or projects...", "beb920ffd1cac72b": [ "Link", " ", @@ -6899,8 +6902,6 @@ " ", "to a thread" ], - "2f664754d005d9a7": "No active threads found.", - "6095e59daf8ac2d6": "Linked", "5d7ee2409e2c527c": "Open activity on host", "fcc3e653e0fff1d9": "{count, plural, one {{formatted} author} other {{formatted} authors}}", "b105bbd107c5f3ea": "{count, plural, one {{formatted} reply} other {{formatted} replies}}", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 38fe66011ed56..b85c0a6f1be1a 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -2457,6 +2457,10 @@ "33c7e68fca089036": "Hilo, {title}", "b4b98a0287c282e2": "Está en otra máquina, así que el agente de esta máquina no puede leerlo. Quítalo o vuelve a cambiar para enviar.", "c6196d99000642b4": "Abrir hilo", + "34cc63390ad793cc": "Elige un hilo", + "8f12309ead62e38a": "Buscar hilos o proyectos...", + "2f664754d005d9a7": "No se encontraron hilos activos.", + "6095e59daf8ac2d6": "Vinculado", "dd52ffa80d5eff97": "Hilo completado", "fd1316b1f627872b": "Se necesita aprobación", "a3178769f8308cbc": "El hilo falló", @@ -5653,9 +5657,6 @@ "cdac45c7efe1cfcc": "ninguna", "115e0df4e8da2704": "Asignados", "7dd58ad67a6de5ba": "nadie", - "4a9e547eda5a1d3b": "No se pudo desvincular la issue", - "6672a18b56815053": "No se pudo vincular la issue", - "a0295b5f63009ecf": "El servidor lo rechazó.", "ae9a4e2921967de9": "No se pudieron cambiar las etiquetas", "6ec1aa91fbfa75d2": "No se pudieron cambiar los asignados", "4f2e859dcaa7569c": "No se pudieron leer los comentarios anteriores", @@ -5691,8 +5692,6 @@ "52f00fe91208ef71": "_No se proporcionó ninguna descripción._", "56ca98b79cc9ce49": "Actividad ({count})", "ddc5e5413923c471": "No puedes comentar aquí.", - "1d1268c1a332a292": "Desvincular de este hilo", - "882a7614e3caa566": "Vincular a este hilo", "516def6f5a881e00": "Cierra esta issue", "0014ce0aaf1bd68a": "Solo lectura", "fd93f4720ff70aaf": "Ninguna", @@ -5712,6 +5711,15 @@ "309a68dc21af399d": "Cualquiera", "4dc86e84bb5ece63": "No se pudieron leer las personas", "4103b6b8e0ff3f46": "Hay más personas de las que se muestran aquí.", + "4a9e547eda5a1d3b": "No se pudo desvincular la issue", + "6672a18b56815053": "No se pudo vincular la issue", + "a0295b5f63009ecf": "El servidor lo rechazó.", + "5fb273ac66588155": "{count, plural, one {Vinculada desde {count} hilo} other {Vinculada desde {count} hilos}}", + "938b14127a3c907d": "Hilos vinculados", + "5bde91110c65afca": "{label}. Busca en la paleta de comandos.", + "1d1268c1a332a292": "Desvincular de este hilo", + "882a7614e3caa566": "Vincular a este hilo", + "bdb2f1444e74c895": "Vincular la issue a un hilo", "6a717189b43e9f0e": "Abierta", "f8700aef3eb2cf71": "Cerrada", "c9735ce17719123b": "Todas", @@ -6867,13 +6875,8 @@ ], "94154d8491776868": "No se pudo desvincular la {term, select, mr {merge request} cr {solicitud de cambios} other {pull request}}", "29bb9b5b565a6df6": "No se pudo vincular la {term, select, mr {merge request} cr {solicitud de cambios} other {pull request}}", - "5fb273ac66588155": "{count, plural, one {Vinculada desde {count} hilo} other {Vinculada desde {count} hilos}}", - "938b14127a3c907d": "Hilos vinculados", - "5bde91110c65afca": "{label}. Busca en la paleta de comandos.", "d37dbc4847107d90": "Desvincular de este hilo", "141d12d6b7f3c002": "Vincular a este hilo", - "34cc63390ad793cc": "Elige un hilo", - "8f12309ead62e38a": "Buscar hilos o proyectos...", "beb920ffd1cac72b": [ "Vincular la", " ", @@ -6892,8 +6895,6 @@ " ", "a un hilo" ], - "2f664754d005d9a7": "No se encontraron hilos activos.", - "6095e59daf8ac2d6": "Vinculado", "5d7ee2409e2c527c": "Abrir la actividad en el host", "fcc3e653e0fff1d9": "{count, plural, one {{formatted} autor} other {{formatted} autores}}", "b105bbd107c5f3ea": "{count, plural, one {{formatted} respuesta} other {{formatted} respuestas}}", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 658857f98fc48..a6fb1cd5ad026 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -2457,6 +2457,10 @@ "33c7e68fca089036": "Fil, {title}", "b4b98a0287c282e2": "Sur une autre machine, l’agent de cette machine ne peut donc pas le lire. Retirez-le ou revenez en arrière pour envoyer.", "c6196d99000642b4": "Ouvrir le fil", + "34cc63390ad793cc": "Choisir un fil", + "8f12309ead62e38a": "Rechercher des fils ou des projets...", + "2f664754d005d9a7": "Aucun fil actif trouvé.", + "6095e59daf8ac2d6": "Associé", "dd52ffa80d5eff97": "Fil terminé", "fd1316b1f627872b": "Approbation requise", "a3178769f8308cbc": "Échec du fil", @@ -5654,9 +5658,6 @@ "cdac45c7efe1cfcc": "aucun", "115e0df4e8da2704": "Assignés", "7dd58ad67a6de5ba": "personne", - "4a9e547eda5a1d3b": "Impossible de dissocier le ticket", - "6672a18b56815053": "Impossible d’associer le ticket", - "a0295b5f63009ecf": "Le serveur l’a refusé.", "ae9a4e2921967de9": "Impossible de modifier les libellés", "6ec1aa91fbfa75d2": "Impossible de modifier les assignés", "4f2e859dcaa7569c": "Les commentaires plus anciens n’ont pas pu être lus", @@ -5692,8 +5693,6 @@ "52f00fe91208ef71": "_Aucune description fournie._", "56ca98b79cc9ce49": "Activité ({count})", "ddc5e5413923c471": "Vous ne pouvez pas commenter ici.", - "1d1268c1a332a292": "Dissocier de ce fil", - "882a7614e3caa566": "Associer à ce fil", "516def6f5a881e00": "Ferme ce ticket", "0014ce0aaf1bd68a": "Lecture seule", "fd93f4720ff70aaf": "Aucun", @@ -5713,6 +5712,15 @@ "309a68dc21af399d": "N’importe qui", "4dc86e84bb5ece63": "Les personnes n’ont pas pu être lues", "4103b6b8e0ff3f46": "Il existe plus de personnes que celles listées ici.", + "4a9e547eda5a1d3b": "Impossible de dissocier le ticket", + "6672a18b56815053": "Impossible d’associer le ticket", + "a0295b5f63009ecf": "Le serveur l’a refusé.", + "5fb273ac66588155": "{count, plural, one {Associée depuis {count} fil} other {Associée depuis {count} fils}}", + "938b14127a3c907d": "Fils associés", + "5bde91110c65afca": "{label}. Recherchez dans la palette de commandes.", + "1d1268c1a332a292": "Dissocier de ce fil", + "882a7614e3caa566": "Associer à ce fil", + "bdb2f1444e74c895": "Associer le ticket à un fil", "6a717189b43e9f0e": "Ouvert", "f8700aef3eb2cf71": "Fermé", "c9735ce17719123b": "Tous", @@ -6868,13 +6876,8 @@ ], "94154d8491776868": "Impossible de dissocier la {term, select, mr {merge request} cr {demande de modification} other {pull request}}", "29bb9b5b565a6df6": "Impossible d’associer la {term, select, mr {merge request} cr {demande de modification} other {pull request}}", - "5fb273ac66588155": "{count, plural, one {Associée depuis {count} fil} other {Associée depuis {count} fils}}", - "938b14127a3c907d": "Fils associés", - "5bde91110c65afca": "{label}. Recherchez dans la palette de commandes.", "d37dbc4847107d90": "Dissocier de ce fil", "141d12d6b7f3c002": "Associer à ce fil", - "34cc63390ad793cc": "Choisir un fil", - "8f12309ead62e38a": "Rechercher des fils ou des projets...", "beb920ffd1cac72b": [ "Associer la", " ", @@ -6893,8 +6896,6 @@ " ", "à un fil" ], - "2f664754d005d9a7": "Aucun fil actif trouvé.", - "6095e59daf8ac2d6": "Associé", "5d7ee2409e2c527c": "Ouvrir l’activité sur l’hôte", "fcc3e653e0fff1d9": "{count, plural, one {{formatted} auteur} other {{formatted} auteurs}}", "b105bbd107c5f3ea": "{count, plural, one {{formatted} réponse} other {{formatted} réponses}}", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index a405829ae1a06..149a7e4799787 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -2455,6 +2455,10 @@ "33c7e68fca089036": "スレッド、{title}", "b4b98a0287c282e2": "別のマシン上にあるため、このマシンのエージェントは読み取れません。削除するか、元に戻してから送信してください。", "c6196d99000642b4": "スレッドを開く", + "34cc63390ad793cc": "スレッドを選択", + "8f12309ead62e38a": "スレッドまたはプロジェクトを検索...", + "2f664754d005d9a7": "アクティブなスレッドが見つかりません。", + "6095e59daf8ac2d6": "リンク済み", "dd52ffa80d5eff97": "スレッドが完了しました", "fd1316b1f627872b": "承認が必要です", "a3178769f8308cbc": "スレッドが失敗しました", @@ -5636,9 +5640,6 @@ "cdac45c7efe1cfcc": "なし", "115e0df4e8da2704": "担当者", "7dd58ad67a6de5ba": "なし", - "4a9e547eda5a1d3b": "Issue のリンクを解除できませんでした", - "6672a18b56815053": "Issue をリンクできませんでした", - "a0295b5f63009ecf": "サーバーが拒否しました。", "ae9a4e2921967de9": "ラベルを変更できませんでした", "6ec1aa91fbfa75d2": "担当者を変更できませんでした", "4f2e859dcaa7569c": "以前のコメントを読み取れませんでした", @@ -5674,8 +5675,6 @@ "52f00fe91208ef71": "_説明はありません。_", "56ca98b79cc9ce49": "アクティビティ ({count})", "ddc5e5413923c471": "ここではコメントできません。", - "1d1268c1a332a292": "このスレッドとのリンクを解除", - "882a7614e3caa566": "このスレッドにリンク", "516def6f5a881e00": "この Issue をクローズします", "0014ce0aaf1bd68a": "読み取り専用", "fd93f4720ff70aaf": "なし", @@ -5695,6 +5694,15 @@ "309a68dc21af399d": "すべてのユーザー", "4dc86e84bb5ece63": "ユーザーを読み取れませんでした", "4103b6b8e0ff3f46": "ここに表示されている以外にもユーザーがいます。", + "4a9e547eda5a1d3b": "Issue のリンクを解除できませんでした", + "6672a18b56815053": "Issue をリンクできませんでした", + "a0295b5f63009ecf": "サーバーが拒否しました。", + "5fb273ac66588155": "{count, plural, other {{count} 件のスレッドからリンク}}", + "938b14127a3c907d": "リンクされたスレッド", + "5bde91110c65afca": "{label}。コマンドパレットで検索します。", + "1d1268c1a332a292": "このスレッドとのリンクを解除", + "882a7614e3caa566": "このスレッドにリンク", + "bdb2f1444e74c895": "Issue をスレッドにリンク", "6a717189b43e9f0e": "オープン", "f8700aef3eb2cf71": "クローズ", "c9735ce17719123b": "すべて", @@ -6837,13 +6845,8 @@ ], "94154d8491776868": "{term, select, mr {マージリクエストのリンクを解除できませんでした} cr {変更リクエストのリンクを解除できませんでした} other {プルリクエストのリンクを解除できませんでした}}", "29bb9b5b565a6df6": "{term, select, mr {マージリクエストをリンクできませんでした} cr {変更リクエストをリンクできませんでした} other {プルリクエストをリンクできませんでした}}", - "5fb273ac66588155": "{count, plural, other {{count} 件のスレッドからリンク}}", - "938b14127a3c907d": "リンクされたスレッド", - "5bde91110c65afca": "{label}。コマンドパレットで検索します。", "d37dbc4847107d90": "このスレッドからリンクを解除", "141d12d6b7f3c002": "このスレッドにリンク", - "34cc63390ad793cc": "スレッドを選択", - "8f12309ead62e38a": "スレッドまたはプロジェクトを検索...", "beb920ffd1cac72b": [ { "t": "Branch", @@ -6859,8 +6862,6 @@ }, "をスレッドにリンク" ], - "2f664754d005d9a7": "アクティブなスレッドが見つかりません。", - "6095e59daf8ac2d6": "リンク済み", "5d7ee2409e2c527c": "ホストでアクティビティを開く", "fcc3e653e0fff1d9": "{count, plural, other {{formatted} 人の作成者}}", "b105bbd107c5f3ea": "{count, plural, other {{formatted} 件の返信}}", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index c5690cb564f42..6d105a882bf16 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -2456,6 +2456,10 @@ "33c7e68fca089036": "스레드, {title}", "b4b98a0287c282e2": "다른 머신에 있어 이 머신의 에이전트가 읽을 수 없습니다. 제거하거나 원래대로 전환한 후 보내세요.", "c6196d99000642b4": "스레드 열기", + "34cc63390ad793cc": "스레드 선택", + "8f12309ead62e38a": "스레드 또는 프로젝트 검색...", + "2f664754d005d9a7": "활성 스레드를 찾을 수 없습니다.", + "6095e59daf8ac2d6": "연결됨", "dd52ffa80d5eff97": "스레드 완료됨", "fd1316b1f627872b": "승인 필요", "a3178769f8308cbc": "스레드 실패", @@ -5634,9 +5638,6 @@ "cdac45c7efe1cfcc": "없음", "115e0df4e8da2704": "담당자", "7dd58ad67a6de5ba": "없음", - "4a9e547eda5a1d3b": "이슈 연결을 해제할 수 없습니다", - "6672a18b56815053": "이슈를 연결할 수 없습니다", - "a0295b5f63009ecf": "서버가 거부했습니다.", "ae9a4e2921967de9": "레이블을 변경할 수 없습니다", "6ec1aa91fbfa75d2": "담당자를 변경할 수 없습니다", "4f2e859dcaa7569c": "이전 댓글을 읽을 수 없습니다", @@ -5672,8 +5673,6 @@ "52f00fe91208ef71": "_설명이 없습니다._", "56ca98b79cc9ce49": "활동({count})", "ddc5e5413923c471": "여기에는 댓글을 달 수 없습니다.", - "1d1268c1a332a292": "이 스레드와 연결 해제", - "882a7614e3caa566": "이 스레드에 연결", "516def6f5a881e00": "이 이슈를 닫음", "0014ce0aaf1bd68a": "읽기 전용", "fd93f4720ff70aaf": "없음", @@ -5693,6 +5692,15 @@ "309a68dc21af399d": "모든 사람", "4dc86e84bb5ece63": "사용자 목록을 읽을 수 없습니다", "4103b6b8e0ff3f46": "여기에 표시된 것보다 사용자가 더 있습니다.", + "4a9e547eda5a1d3b": "이슈 연결을 해제할 수 없습니다", + "6672a18b56815053": "이슈를 연결할 수 없습니다", + "a0295b5f63009ecf": "서버가 거부했습니다.", + "5fb273ac66588155": "{count, plural, other {스레드 {count}개에서 연결됨}}", + "938b14127a3c907d": "연결된 스레드", + "5bde91110c65afca": "{label}. 명령 팔레트에서 검색하세요.", + "1d1268c1a332a292": "이 스레드와 연결 해제", + "882a7614e3caa566": "이 스레드에 연결", + "bdb2f1444e74c895": "이슈를 스레드에 연결", "6a717189b43e9f0e": "열림", "f8700aef3eb2cf71": "닫힘", "c9735ce17719123b": "전체", @@ -6839,13 +6847,8 @@ ], "94154d8491776868": "{term, select, mr {병합 요청} cr {변경 요청} other {풀 리퀘스트}} 연결을 해제할 수 없습니다", "29bb9b5b565a6df6": "{term, select, mr {병합 요청을} cr {변경 요청을} other {풀 리퀘스트를}} 연결할 수 없습니다", - "5fb273ac66588155": "{count, plural, other {스레드 {count}개에서 연결됨}}", - "938b14127a3c907d": "연결된 스레드", - "5bde91110c65afca": "{label}. 명령 팔레트에서 검색하세요.", "d37dbc4847107d90": "이 스레드에서 연결 해제", "141d12d6b7f3c002": "이 스레드에 연결", - "34cc63390ad793cc": "스레드 선택", - "8f12309ead62e38a": "스레드 또는 프로젝트 검색...", "beb920ffd1cac72b": [ { "t": "Branch", @@ -6862,8 +6865,6 @@ " ", "스레드에 연결" ], - "2f664754d005d9a7": "활성 스레드를 찾을 수 없습니다.", - "6095e59daf8ac2d6": "연결됨", "5d7ee2409e2c527c": "호스트에서 활동 열기", "fcc3e653e0fff1d9": "{count, plural, other {작성자 {formatted}명}}", "b105bbd107c5f3ea": "{count, plural, other {답글 {formatted}개}}", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 9c4552aed155b..ce5a544f36ed4 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -2457,6 +2457,10 @@ "33c7e68fca089036": "Thread, {title}", "b4b98a0287c282e2": "Está em outra máquina, então o agente desta máquina não consegue lê-lo. Remova-o ou volte para enviar.", "c6196d99000642b4": "Abrir thread", + "34cc63390ad793cc": "Escolha uma thread", + "8f12309ead62e38a": "Pesquisar threads ou projetos...", + "2f664754d005d9a7": "Nenhuma thread ativa encontrada.", + "6095e59daf8ac2d6": "Vinculada", "dd52ffa80d5eff97": "Thread concluída", "fd1316b1f627872b": "Aprovação necessária", "a3178769f8308cbc": "A thread falhou", @@ -5653,9 +5657,6 @@ "cdac45c7efe1cfcc": "nenhum", "115e0df4e8da2704": "Responsáveis", "7dd58ad67a6de5ba": "ninguém", - "4a9e547eda5a1d3b": "Não foi possível desvincular a issue", - "6672a18b56815053": "Não foi possível vincular a issue", - "a0295b5f63009ecf": "O servidor recusou.", "ae9a4e2921967de9": "Não foi possível alterar os rótulos", "6ec1aa91fbfa75d2": "Não foi possível alterar os responsáveis", "4f2e859dcaa7569c": "Não foi possível ler os comentários mais antigos", @@ -5691,8 +5692,6 @@ "52f00fe91208ef71": "_Nenhuma descrição fornecida._", "56ca98b79cc9ce49": "Atividade ({count})", "ddc5e5413923c471": "Você não pode comentar aqui.", - "1d1268c1a332a292": "Desvincular desta thread", - "882a7614e3caa566": "Vincular a esta thread", "516def6f5a881e00": "Fecha esta issue", "0014ce0aaf1bd68a": "Somente leitura", "fd93f4720ff70aaf": "Nenhuma", @@ -5712,6 +5711,15 @@ "309a68dc21af399d": "Qualquer pessoa", "4dc86e84bb5ece63": "Não foi possível ler as pessoas", "4103b6b8e0ff3f46": "Há mais pessoas do que as listadas aqui.", + "4a9e547eda5a1d3b": "Não foi possível desvincular a issue", + "6672a18b56815053": "Não foi possível vincular a issue", + "a0295b5f63009ecf": "O servidor recusou.", + "5fb273ac66588155": "{count, plural, one {Vinculado a partir de {count} thread} other {Vinculado a partir de {count} threads}}", + "938b14127a3c907d": "Threads vinculadas", + "5bde91110c65afca": "{label}. Pesquise na paleta de comandos.", + "1d1268c1a332a292": "Desvincular desta thread", + "882a7614e3caa566": "Vincular a esta thread", + "bdb2f1444e74c895": "Vincular a issue a uma thread", "6a717189b43e9f0e": "Aberta", "f8700aef3eb2cf71": "Fechada", "c9735ce17719123b": "Todas", @@ -6867,13 +6875,8 @@ ], "94154d8491776868": "Não foi possível desvincular {term, select, mr {o merge request} cr {a solicitação de alteração} other {o pull request}}", "29bb9b5b565a6df6": "Não foi possível vincular {term, select, mr {o merge request} cr {a solicitação de alteração} other {o pull request}}", - "5fb273ac66588155": "{count, plural, one {Vinculado a partir de {count} thread} other {Vinculado a partir de {count} threads}}", - "938b14127a3c907d": "Threads vinculadas", - "5bde91110c65afca": "{label}. Pesquise na paleta de comandos.", "d37dbc4847107d90": "Desvincular desta thread", "141d12d6b7f3c002": "Vincular a esta thread", - "34cc63390ad793cc": "Escolha uma thread", - "8f12309ead62e38a": "Pesquisar threads ou projetos...", "beb920ffd1cac72b": [ "Vincular", " ", @@ -6892,8 +6895,6 @@ " ", "a uma thread" ], - "2f664754d005d9a7": "Nenhuma thread ativa encontrada.", - "6095e59daf8ac2d6": "Vinculada", "5d7ee2409e2c527c": "Abrir a atividade no host", "fcc3e653e0fff1d9": "{count, plural, one {{formatted} autor} other {{formatted} autores}}", "b105bbd107c5f3ea": "{count, plural, one {{formatted} resposta} other {{formatted} respostas}}", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 7e36f4bd730a1..55c23f2d13153 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -2457,6 +2457,10 @@ "33c7e68fca089036": "Тред, {title}", "b4b98a0287c282e2": "Находится на другой машине, поэтому агент этой машины не может его прочитать. Удалите его или переключитесь обратно, чтобы отправить.", "c6196d99000642b4": "Открыть тред", + "34cc63390ad793cc": "Выберите тред", + "8f12309ead62e38a": "Поиск тредов или проектов...", + "2f664754d005d9a7": "Активные треды не найдены.", + "6095e59daf8ac2d6": "Привязан", "dd52ffa80d5eff97": "Тред завершён", "fd1316b1f627872b": "Нужно подтверждение", "a3178769f8308cbc": "Ошибка в треде", @@ -5653,9 +5657,6 @@ "cdac45c7efe1cfcc": "нет", "115e0df4e8da2704": "Исполнители", "7dd58ad67a6de5ba": "нет", - "4a9e547eda5a1d3b": "Не удалось отвязать issue", - "6672a18b56815053": "Не удалось привязать issue", - "a0295b5f63009ecf": "Сервер отклонил запрос.", "ae9a4e2921967de9": "Не удалось изменить метки", "6ec1aa91fbfa75d2": "Не удалось изменить исполнителей", "4f2e859dcaa7569c": "Не удалось прочитать старые комментарии", @@ -5691,8 +5692,6 @@ "52f00fe91208ef71": "_Описание отсутствует._", "56ca98b79cc9ce49": "Активность ({count})", "ddc5e5413923c471": "Здесь нельзя комментировать.", - "1d1268c1a332a292": "Отвязать от этого треда", - "882a7614e3caa566": "Привязать к этому треду", "516def6f5a881e00": "Закроет этот issue", "0014ce0aaf1bd68a": "Только чтение", "fd93f4720ff70aaf": "Нет", @@ -5712,6 +5711,15 @@ "309a68dc21af399d": "Любой", "4dc86e84bb5ece63": "Не удалось прочитать список людей", "4103b6b8e0ff3f46": "Людей больше, чем показано здесь.", + "4a9e547eda5a1d3b": "Не удалось отвязать issue", + "6672a18b56815053": "Не удалось привязать issue", + "a0295b5f63009ecf": "Сервер отклонил запрос.", + "5fb273ac66588155": "{count, plural, one {Привязан к {count} треду} few {Привязан к {count} тредам} many {Привязан к {count} тредам} other {Привязан к {count} треда}}", + "938b14127a3c907d": "Привязанные треды", + "5bde91110c65afca": "{label}. Ищите в палитре команд.", + "1d1268c1a332a292": "Отвязать от этого треда", + "882a7614e3caa566": "Привязать к этому треду", + "bdb2f1444e74c895": "Привязать issue к треду", "6a717189b43e9f0e": "Открыт", "f8700aef3eb2cf71": "Закрыт", "c9735ce17719123b": "Все", @@ -6867,13 +6875,8 @@ ], "94154d8491776868": "{term, select, mr {Не удалось отвязать мерж-реквест} cr {Не удалось отвязать запрос на изменение} other {Не удалось отвязать пул-реквест}}", "29bb9b5b565a6df6": "{term, select, mr {Не удалось привязать мерж-реквест} cr {Не удалось привязать запрос на изменение} other {Не удалось привязать пул-реквест}}", - "5fb273ac66588155": "{count, plural, one {Привязан к {count} треду} few {Привязан к {count} тредам} many {Привязан к {count} тредам} other {Привязан к {count} треда}}", - "938b14127a3c907d": "Привязанные треды", - "5bde91110c65afca": "{label}. Ищите в палитре команд.", "d37dbc4847107d90": "Отвязать от этого треда", "141d12d6b7f3c002": "Привязать к этому треду", - "34cc63390ad793cc": "Выберите тред", - "8f12309ead62e38a": "Поиск тредов или проектов...", "beb920ffd1cac72b": [ "Привязать", " ", @@ -6892,8 +6895,6 @@ " ", "к треду" ], - "2f664754d005d9a7": "Активные треды не найдены.", - "6095e59daf8ac2d6": "Привязан", "5d7ee2409e2c527c": "Открыть активность на хосте", "fcc3e653e0fff1d9": "{count, plural, one {{formatted} автор} few {{formatted} автора} many {{formatted} авторов} other {{formatted} автора}}", "b105bbd107c5f3ea": "{count, plural, one {{formatted} ответ} few {{formatted} ответа} many {{formatted} ответов} other {{formatted} ответа}}", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 95bcd0b80080a..deb8ea68511e9 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -2457,6 +2457,10 @@ "33c7e68fca089036": "Tråd, {title}", "b4b98a0287c282e2": "Finns på en annan dator, så den här datorns agent kan inte läsa den. Ta bort den eller byt tillbaka för att skicka.", "c6196d99000642b4": "Öppna tråd", + "34cc63390ad793cc": "Välj en tråd", + "8f12309ead62e38a": "Sök trådar eller projekt...", + "2f664754d005d9a7": "Inga aktiva trådar hittades.", + "6095e59daf8ac2d6": "Länkad", "dd52ffa80d5eff97": "Tråden slutfördes", "fd1316b1f627872b": "Godkännande behövs", "a3178769f8308cbc": "Tråden misslyckades", @@ -5654,9 +5658,6 @@ "cdac45c7efe1cfcc": "inga", "115e0df4e8da2704": "Tilldelade", "7dd58ad67a6de5ba": "ingen", - "4a9e547eda5a1d3b": "Kunde inte ta bort länken till ärendet", - "6672a18b56815053": "Kunde inte länka ärendet", - "a0295b5f63009ecf": "Servern nekade.", "ae9a4e2921967de9": "Kunde inte ändra etiketter", "6ec1aa91fbfa75d2": "Kunde inte ändra tilldelade", "4f2e859dcaa7569c": "Äldre kommentarer kunde inte läsas", @@ -5692,8 +5693,6 @@ "52f00fe91208ef71": "_Ingen beskrivning angiven._", "56ca98b79cc9ce49": "Aktivitet ({count})", "ddc5e5413923c471": "Du kan inte kommentera här.", - "1d1268c1a332a292": "Ta bort länken från den här tråden", - "882a7614e3caa566": "Länka till den här tråden", "516def6f5a881e00": "Stänger det här ärendet", "0014ce0aaf1bd68a": "Skrivskyddad", "fd93f4720ff70aaf": "Inga", @@ -5713,6 +5712,15 @@ "309a68dc21af399d": "Vem som helst", "4dc86e84bb5ece63": "Personerna kunde inte läsas", "4103b6b8e0ff3f46": "Det finns fler personer än som listas här.", + "4a9e547eda5a1d3b": "Kunde inte ta bort länken till ärendet", + "6672a18b56815053": "Kunde inte länka ärendet", + "a0295b5f63009ecf": "Servern nekade.", + "5fb273ac66588155": "{count, plural, one {Länkad från {count} tråd} other {Länkad från {count} trådar}}", + "938b14127a3c907d": "Länkade trådar", + "5bde91110c65afca": "{label}. Sök i kommandopaletten.", + "1d1268c1a332a292": "Ta bort länken från den här tråden", + "882a7614e3caa566": "Länka till den här tråden", + "bdb2f1444e74c895": "Länka ärendet till en tråd", "6a717189b43e9f0e": "Öppet", "f8700aef3eb2cf71": "Stängt", "c9735ce17719123b": "Alla", @@ -6873,13 +6881,8 @@ ], "94154d8491776868": "Kunde inte ta bort länken till {term, select, mr {merge requesten} cr {ändringsbegäran} other {pull requesten}}", "29bb9b5b565a6df6": "Kunde inte länka {term, select, mr {merge requesten} cr {ändringsbegäran} other {pull requesten}}", - "5fb273ac66588155": "{count, plural, one {Länkad från {count} tråd} other {Länkad från {count} trådar}}", - "938b14127a3c907d": "Länkade trådar", - "5bde91110c65afca": "{label}. Sök i kommandopaletten.", "d37dbc4847107d90": "Ta bort länken från den här tråden", "141d12d6b7f3c002": "Länka till den här tråden", - "34cc63390ad793cc": "Välj en tråd", - "8f12309ead62e38a": "Sök trådar eller projekt...", "beb920ffd1cac72b": [ "Länka", " ", @@ -6898,8 +6901,6 @@ " ", "till en tråd" ], - "2f664754d005d9a7": "Inga aktiva trådar hittades.", - "6095e59daf8ac2d6": "Länkad", "5d7ee2409e2c527c": "Öppna aktiviteten på värden", "fcc3e653e0fff1d9": "{count, plural, one {{formatted} författare} other {{formatted} författare}}", "b105bbd107c5f3ea": "{count, plural, one {{formatted} svar} other {{formatted} svar}}", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 7f161ed108acf..d7bf54efc0dd0 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -2461,6 +2461,10 @@ "33c7e68fca089036": "会话,{title}", "b4b98a0287c282e2": "它在另一台机器上,本机的智能体读不到它。请移除它,或切回那台机器再发送。", "c6196d99000642b4": "打开会话", + "34cc63390ad793cc": "选择会话", + "8f12309ead62e38a": "搜索会话或项目…", + "2f664754d005d9a7": "未找到活动会话。", + "6095e59daf8ac2d6": "已关联", "dd52ffa80d5eff97": "会话已完成", "fd1316b1f627872b": "需要批准", "a3178769f8308cbc": "会话失败", @@ -5660,9 +5664,6 @@ "cdac45c7efe1cfcc": "无", "115e0df4e8da2704": "受理人", "7dd58ad67a6de5ba": "无", - "4a9e547eda5a1d3b": "无法取消关联 issue", - "6672a18b56815053": "无法关联 issue", - "a0295b5f63009ecf": "服务器拒绝了操作。", "ae9a4e2921967de9": "无法更改标签", "6ec1aa91fbfa75d2": "无法更改受理人", "4f2e859dcaa7569c": "无法读取较早的评论", @@ -5698,8 +5699,6 @@ "52f00fe91208ef71": "_未提供描述。_", "56ca98b79cc9ce49": "活动({count})", "ddc5e5413923c471": "你无法在此评论。", - "1d1268c1a332a292": "取消与此会话的关联", - "882a7614e3caa566": "关联到此会话", "516def6f5a881e00": "将关闭此 issue", "0014ce0aaf1bd68a": "只读", "fd93f4720ff70aaf": "无", @@ -5719,6 +5718,15 @@ "309a68dc21af399d": "任何人", "4dc86e84bb5ece63": "无法读取人员列表", "4103b6b8e0ff3f46": "还有更多人员未在此列出。", + "4a9e547eda5a1d3b": "无法取消关联 issue", + "6672a18b56815053": "无法关联 issue", + "a0295b5f63009ecf": "服务器拒绝了操作。", + "5fb273ac66588155": "{count, plural, other {已从 {count} 个会话关联}}", + "938b14127a3c907d": "已关联的会话", + "5bde91110c65afca": "{label}。可在命令面板中搜索。", + "1d1268c1a332a292": "取消与此会话的关联", + "882a7614e3caa566": "关联到此会话", + "bdb2f1444e74c895": "将 issue 关联到会话", "6a717189b43e9f0e": "开放", "f8700aef3eb2cf71": "已关闭", "c9735ce17719123b": "全部", @@ -6882,13 +6890,8 @@ ], "94154d8491776868": "无法取消关联该 {term, select, mr {MR} cr {change request} other {PR}}", "29bb9b5b565a6df6": "无法关联该 {term, select, mr {MR} cr {change request} other {PR}}", - "5fb273ac66588155": "{count, plural, other {已从 {count} 个会话关联}}", - "938b14127a3c907d": "已关联的会话", - "5bde91110c65afca": "{label}。可在命令面板中搜索。", "d37dbc4847107d90": "取消与此会话的关联", "141d12d6b7f3c002": "关联到此会话", - "34cc63390ad793cc": "选择会话", - "8f12309ead62e38a": "搜索会话或项目…", "beb920ffd1cac72b": [ "将", " ", @@ -6907,8 +6910,6 @@ " ", "关联到会话" ], - "2f664754d005d9a7": "未找到活动会话。", - "6095e59daf8ac2d6": "已关联", "5d7ee2409e2c527c": "在托管平台上打开动态", "fcc3e653e0fff1d9": "{count, plural, other {{formatted} 位作者}}", "b105bbd107c5f3ea": "{count, plural, other {{formatted} 条回复}}", diff --git a/packages/client-runtime/src/state/issues.ts b/packages/client-runtime/src/state/issues.ts index 237610fe281d4..ac87ed088f6ff 100644 --- a/packages/client-runtime/src/state/issues.ts +++ b/packages/client-runtime/src/state/issues.ts @@ -23,6 +23,7 @@ import { createAtomCommandScheduler, createEnvironmentRpcCommand, createEnvironmentRpcQueryAtomFamily, + createEnvironmentRpcSubscriptionAtomFamily, } from "./runtime.ts"; import type { EnvironmentRegistry } from "../connection/registry.ts"; @@ -174,7 +175,18 @@ export function createIssueEnvironmentAtoms( { environmentId, input }: { readonly environmentId: EnvironmentId; readonly input: IssueRef }, registry: AtomRegistry.AtomRegistry, ) => Effect.sync(() => registry.refresh(detail({ environmentId, input: detailRef(input) }))); + const linkedThreadSignals = createEnvironmentRpcSubscriptionAtomFamily(runtime, { + label: "environment-data:issues:linked-thread-refreshes", + tag: WS_METHODS.pullRequestsSubscribeLinkedThreadRefreshes, + }); return { + /** The threads an issue is linked to, reread when the server signals a link changed. */ + linkedThreads: createEnvironmentRpcQueryAtomFamily(runtime, { + label: "environment-data:issues:linked-threads", + tag: WS_METHODS.issuesLinkedThreads, + staleTimeMs: 0, + refreshTrigger: ({ environmentId }) => linkedThreadSignals({ environmentId, input: {} }), + }), list: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:issues:list", tag: WS_METHODS.issuesList, diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index 4ad3fa3fd147f..f95b7f8c04b97 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -210,6 +210,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ shellOlderSettled: Schema.optionalKey(Schema.Boolean), /** Publishes a pull request refresh when linked-thread answers change; older servers need polling. */ linkedThreadRefreshes: Schema.optionalKey(Schema.Boolean), + /** Answers `issues.linkedThreads`, the threads an issue is linked to. */ + issueLinkedThreads: Schema.optionalKey(Schema.Boolean), }); export type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type; diff --git a/packages/contracts/src/issue.ts b/packages/contracts/src/issue.ts index 574399859d4f9..0dc9ab44fd167 100644 --- a/packages/contracts/src/issue.ts +++ b/packages/contracts/src/issue.ts @@ -7,6 +7,7 @@ import { NonNegativeInt, PositiveInt, ProjectId, + ThreadId, TrimmedNonEmptyString, } from "./baseSchemas.ts"; import { @@ -528,6 +529,20 @@ export function threadIssueKeysEqual(left: ThreadIssueKey, right: ThreadIssueKey return threadIssueKeyOf(left) === threadIssueKeyOf(right); } +/** The threads an issue is linked to, most recently active first. */ +export const IssueLinkedThreadsResult = Schema.Struct({ + threads: Schema.Array( + Schema.Struct({ + id: ThreadId, + projectId: ProjectId, + title: Schema.String, + archivedAt: Schema.NullOr(IsoDateTime), + settled: Schema.Boolean, + }), + ), +}); +export type IssueLinkedThreadsResult = typeof IssueLinkedThreadsResult.Type; + /** * A tracker that is not a git host: it is reached with its own credential rather than a * checkout's, and a project opts into it by binding one of the tracker's scopes. Everything a diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index d4206b74f2f57..41733dae56417 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -177,6 +177,7 @@ import { IssueCreateInput, IssueCreateResult, IssueDetail, + IssueLinkedThreadsResult, IssueListInput, IssueListResult, IssueOperationError, @@ -192,6 +193,7 @@ import { IssueTrackerConnectionList, IssueUnavailableError, IssueUpdateInput, + ThreadIssueKey, } from "./issue.ts"; import { GuestShareCreateError, @@ -637,6 +639,7 @@ export const WS_METHODS = { issuesUpdate: "issues.update", issuesSetState: "issues.setState", issuesReact: "issues.react", + issuesLinkedThreads: "issues.linkedThreads", issueTrackersList: "issueTrackers.list", issueTrackersConnect: "issueTrackers.connect", issueTrackersBindProject: "issueTrackers.bindProject", @@ -1341,6 +1344,12 @@ const WsIssuesDetailRpc = Rpc.make(WS_METHODS.issuesDetail, { }); /** Older comments, one page at a time, past the cursor the detail handed over. */ +const WsIssuesLinkedThreadsRpc = Rpc.make(WS_METHODS.issuesLinkedThreads, { + payload: ThreadIssueKey, + success: IssueLinkedThreadsResult, + error: IssueRpcError, +}); + const WsIssuesCommentsRpc = Rpc.make(WS_METHODS.issuesComments, { payload: IssueCommentsPageInput, success: IssueCommentsPage, @@ -2251,6 +2260,7 @@ export const WsRpcGroup = RpcGroup.make( WsIssuesCommentsRpc, WsIssuesTemplatesRpc, WsIssuesCandidatesRpc, + WsIssuesLinkedThreadsRpc, WsIssuesCreateRpc, WsIssuesCommentRpc, WsIssuesUpdateRpc, From 052ca497cf1103b001327bcd964188a71dfec213 Mon Sep 17 00:00:00 2001 From: Bilal Bakr <62337003+Bil0000@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:36:35 +0300 Subject: [PATCH 062/183] fix(web,mobile): side chats keep your attachments and context (#38350) Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks --- .../src/features/threads/useStartSideChat.ts | 21 +- 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 - .../src/state/thread-task-permissions.test.ts | 106 ++++++- .../src/state/use-thread-composer-state.ts | 138 ++++++--- .../src/components/ChatView.browser.test.tsx | 82 +++++ apps/web/src/components/ChatView.tsx | 2 +- apps/web/src/components/chat/chatViewSend.ts | 52 +++- .../src/components/chat/useComposerSend.ts | 283 ++++++++++++------ apps/web/src/components/chat/useSideChat.ts | 23 +- apps/web/src/i18n/translations/de.json | 1 - apps/web/src/i18n/translations/en.json | 1 - apps/web/src/i18n/translations/es.json | 1 - apps/web/src/i18n/translations/fr.json | 1 - apps/web/src/i18n/translations/ja.json | 1 - apps/web/src/i18n/translations/ko.json | 1 - apps/web/src/i18n/translations/pt-BR.json | 1 - apps/web/src/i18n/translations/ru.json | 1 - apps/web/src/i18n/translations/sv.json | 1 - apps/web/src/i18n/translations/zh.json | 1 - apps/web/test/fakeEnvironment.ts | 54 +++- 29 files changed, 572 insertions(+), 219 deletions(-) diff --git a/apps/mobile/src/features/threads/useStartSideChat.ts b/apps/mobile/src/features/threads/useStartSideChat.ts index 680251e1d91b5..6319896cdf9cc 100644 --- a/apps/mobile/src/features/threads/useStartSideChat.ts +++ b/apps/mobile/src/features/threads/useStartSideChat.ts @@ -1,6 +1,6 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { errorDisplayMessage } from "@t3tools/client-runtime/errors"; -import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations"; +import type { StartThreadTurnInput } from "@t3tools/client-runtime/operations"; import { isAtomCommandInterrupted, squashAtomCommandFailure, @@ -24,8 +24,13 @@ import { useAtomCommand } from "../../state/use-atom-command"; import { waitForThreadShell } from "./threadForkNavigation"; import { useOpenLinkedThread } from "./useOpenLinkedThread"; +export type SideChatMessage = Pick< + StartThreadTurnInput["message"], + "text" | "attachments" | "context" +> & { readonly titleSeed: string }; + /** - * Forks `source` at its latest stable point into a side chat, sends `prompt` there, and opens + * Forks `source` at its latest stable point into a side chat, sends `message` there, and opens * it like any linked thread. Resolves false when the side chat did not start. `settings` are * what the parent's composer would send, which its thread gets only on its next send. */ @@ -48,7 +53,7 @@ export function useStartSideChat() { return async ( source: ScopedThreadRef, - prompt: string, + message: SideChatMessage, settings: { readonly runtimeMode: RuntimeMode; readonly modelSelection: ModelSelection }, ): Promise => { const targetThreadId = ThreadId.make(uuidv4()); @@ -101,18 +106,14 @@ export function useStartSideChat() { return false; } } + const { titleSeed, ...content } = message; const turn = await startTurn({ environmentId: source.environmentId, input: { threadId: targetThreadId, - message: { - messageId: MessageId.make(uuidv4()), - role: "user", - text: prompt, - attachments: [], - }, + message: { messageId: MessageId.make(uuidv4()), role: "user", ...content }, modelSelection: settings.modelSelection, - titleSeed: deriveThreadTitleSeed({ text: prompt, attachments: [] }, m), + titleSeed, runtimeMode: settings.runtimeMode, interactionMode: "default", createdAt: new Date().toISOString(), diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 8e07b70039554..cb16b5a99f6b7 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -1580,8 +1580,6 @@ "b02695b75d8b050d": "Deine Bearbeitung ist noch im Eingabefeld.", "6ad508d2af838010": "Sie wurde möglicherweise bereits gestartet. Deine Bearbeitung ist noch im Eingabefeld.", "74e7e5c0536cda02": "Nebenchat nicht gestartet", - "be6231ac5b08f35e": "Nebenchats nehmen nur Text an", - "faf9ee0a28119e10": "Entferne die Anhänge und den Kontext und sende dann erneut.", "a0269861cbd8c727": "Eine Nebenfrage stellen", "d49fc7ca60395d59": "Gib die Frage nach {command} ein und sende sie dann.", "2498db230c4b87b6": "Zu viel Kontext", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 6e9b23124aff0..e9e28e75b1087 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -1580,8 +1580,6 @@ "b02695b75d8b050d": "Your edit is still in the composer.", "6ad508d2af838010": "It may have already started. Your edit is still in the composer.", "74e7e5c0536cda02": "Side chat not started", - "be6231ac5b08f35e": "Side chats take text only", - "faf9ee0a28119e10": "Remove the attachments and context, then send it again.", "a0269861cbd8c727": "Ask a side question", "d49fc7ca60395d59": "Type the question after {command}, then send it.", "2498db230c4b87b6": "Too much context", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 1464fc150ba83..ba5659fd91c8c 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -1580,8 +1580,6 @@ "b02695b75d8b050d": "Tu edición sigue en el cuadro de mensaje.", "6ad508d2af838010": "Puede que ya haya empezado. Tu edición sigue en el cuadro de mensaje.", "74e7e5c0536cda02": "Chat lateral no iniciado", - "be6231ac5b08f35e": "Los chats laterales solo admiten texto", - "faf9ee0a28119e10": "Quita los adjuntos y el contexto, y vuelve a enviarlo.", "a0269861cbd8c727": "Haz una pregunta aparte", "d49fc7ca60395d59": "Escribe la pregunta después de {command} y envíala.", "2498db230c4b87b6": "Demasiado contexto", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index d9c524718f512..67abb3657ba61 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -1580,8 +1580,6 @@ "b02695b75d8b050d": "Votre modification est toujours dans la zone de saisie.", "6ad508d2af838010": "Il a peut-être déjà démarré. Votre modification est toujours dans la zone de saisie.", "74e7e5c0536cda02": "Discussion annexe non démarrée", - "be6231ac5b08f35e": "Les discussions annexes n’acceptent que du texte", - "faf9ee0a28119e10": "Retirez les pièces jointes et le contexte, puis renvoyez.", "a0269861cbd8c727": "Poser une question annexe", "d49fc7ca60395d59": "Tapez la question après {command}, puis envoyez-la.", "2498db230c4b87b6": "Trop de contexte", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index ba07751a4be89..c780cf277194a 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -1580,8 +1580,6 @@ "b02695b75d8b050d": "編集内容は入力欄に残っています。", "6ad508d2af838010": "すでに開始されている可能性があります。編集内容は入力欄に残っています。", "74e7e5c0536cda02": "サイドチャットが開始されていません", - "be6231ac5b08f35e": "サイドチャットではテキストのみ使用できます", - "faf9ee0a28119e10": "添付ファイルとコンテキストを削除してから、もう一度送信してください。", "a0269861cbd8c727": "横から質問する", "d49fc7ca60395d59": "{command} の後に質問を入力して送信してください。", "2498db230c4b87b6": "コンテキストが多すぎます", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 5ec8e88b484d4..a931cebb71c62 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -1580,8 +1580,6 @@ "b02695b75d8b050d": "편집 내용은 입력창에 그대로 있습니다.", "6ad508d2af838010": "이미 시작되었을 수 있습니다. 편집 내용은 입력창에 그대로 있습니다.", "74e7e5c0536cda02": "사이드 채팅이 시작되지 않음", - "be6231ac5b08f35e": "사이드 채팅은 텍스트만 받습니다", - "faf9ee0a28119e10": "첨부 파일과 컨텍스트를 제거한 다음 다시 보내세요.", "a0269861cbd8c727": "곁가지 질문하기", "d49fc7ca60395d59": "{command} 뒤에 질문을 입력한 뒤 보내세요.", "2498db230c4b87b6": "컨텍스트가 너무 많습니다", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index e4e10d1234b27..7200f7fe4a0ef 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -1580,8 +1580,6 @@ "b02695b75d8b050d": "Sua edição continua no editor de mensagens.", "6ad508d2af838010": "Ela pode já ter começado. Sua edição continua no editor de mensagens.", "74e7e5c0536cda02": "Chat paralelo não iniciado", - "be6231ac5b08f35e": "Chats paralelos aceitam só texto", - "faf9ee0a28119e10": "Remova os anexos e o contexto e envie novamente.", "a0269861cbd8c727": "Fazer uma pergunta paralela", "d49fc7ca60395d59": "Digite a pergunta depois de {command} e envie.", "2498db230c4b87b6": "Contexto demais", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index 4323f4425f844..a5944903e1499 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -1580,8 +1580,6 @@ "b02695b75d8b050d": "Ваша правка всё ещё в поле ввода.", "6ad508d2af838010": "Возможно, оно уже начало выполняться. Ваша правка всё ещё в поле ввода.", "74e7e5c0536cda02": "Боковой чат не начат", - "be6231ac5b08f35e": "Боковые чаты принимают только текст", - "faf9ee0a28119e10": "Удалите вложения и контекст, затем отправьте снова.", "a0269861cbd8c727": "Задать вопрос в сторону", "d49fc7ca60395d59": "Введите вопрос после {command} и отправьте.", "2498db230c4b87b6": "Слишком много контекста", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 13d654d07bba0..1325edff83090 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -1580,8 +1580,6 @@ "b02695b75d8b050d": "Din redigering finns kvar i inmatningsfältet.", "6ad508d2af838010": "Det kan redan ha startat. Din redigering finns kvar i inmatningsfältet.", "74e7e5c0536cda02": "Sidochatten startades inte", - "be6231ac5b08f35e": "Sidochattar tar bara emot text", - "faf9ee0a28119e10": "Ta bort bilagorna och kontexten och skicka sedan igen.", "a0269861cbd8c727": "Ställ en sidofråga", "d49fc7ca60395d59": "Skriv frågan efter {command} och skicka den sedan.", "2498db230c4b87b6": "För mycket kontext", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index b80a4e832249a..615f6ad8c84a0 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -1581,8 +1581,6 @@ "b02695b75d8b050d": "你的编辑仍在输入框中。", "6ad508d2af838010": "它可能已经开始处理。你的编辑仍在输入框中。", "74e7e5c0536cda02": "侧聊未开始", - "be6231ac5b08f35e": "侧聊只支持文字", - "faf9ee0a28119e10": "请移除附件和上下文后再发送。", "a0269861cbd8c727": "问一个旁支问题", "d49fc7ca60395d59": "在 {command} 后输入问题,然后发送。", "2498db230c4b87b6": "上下文过多", diff --git a/apps/mobile/src/state/thread-task-permissions.test.ts b/apps/mobile/src/state/thread-task-permissions.test.ts index 640c409e53af2..57c8e5bfe9cc0 100644 --- a/apps/mobile/src/state/thread-task-permissions.test.ts +++ b/apps/mobile/src/state/thread-task-permissions.test.ts @@ -11,6 +11,7 @@ import { ThreadId, TurnItemId, type ModelSelection, + type OrchestrationMessageContext, type OrchestrationV2ThreadProjection, type RuntimeMode, type ServerConfig, @@ -35,6 +36,7 @@ const state = vi.hoisted(() => ({ draft: { text: "Keep my draft", attachments: [] as DraftComposerImageAttachment[], + context: undefined as OrchestrationMessageContext | undefined, modelSelection: undefined as ModelSelection | undefined, runtimeMode: undefined as RuntimeMode | undefined, }, @@ -48,6 +50,8 @@ const state = vi.hoisted(() => ({ setFreshPending: vi.fn(), clearDraft: vi.fn(), appendAttachments: vi.fn(), + mergeDraft: vi.fn(), + fileHolds: [] as string[], questionDrafts: {} as Record< string, { text: string; attachments: DraftComposerImageAttachment[] } @@ -105,8 +109,33 @@ vi.mock("@t3tools/client-runtime/state/context-window", async (importOriginal) = : null, })); vi.mock("../lib/clock", () => ({ useNowMinuteMs: () => 0 })); -vi.mock("../lib/attachmentUpload", () => ({ prepareTurnAttachments: vi.fn() })); +vi.mock("../lib/attachmentUpload", async () => { + const { Effect } = await import("effect"); + return { + prepareTurnAttachments: vi.fn( + (input: { readonly attachments: ReadonlyArray<{ readonly id: string }> }) => + Effect.succeed({ + status: "ready", + attachments: input.attachments.map((attachment) => ({ + type: "image", + id: `uploaded-${attachment.id}`, + name: "shot.png", + mimeType: "image/png", + sizeBytes: 1, + })), + }), + ), + }; +}); vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid" })); +vi.mock("../lib/composerAttachmentPreviewRetention", () => ({ + retainComposerAttachmentFileForPreview: (attachment: { readonly fileUri: string }) => { + state.fileHolds.push(attachment.fileUri); + return () => { + state.fileHolds.splice(state.fileHolds.indexOf(attachment.fileUri), 1); + }; + }, +})); vi.mock("./queued-run-edit", () => ({ useQueuedRunEdit: () => null, getQueuedRunEdit: () => null, @@ -169,6 +198,7 @@ vi.mock("./composer-attachment-uploads", async () => { composerAttachmentUploadsAtom: Atom.make({}), composerAttachmentUploadBlockReason: () => null, composerAttachmentsStillUploading: () => false, + uploadComposerAttachmentShared: vi.fn(), }; }); vi.mock("./use-composer-drafts", async () => { @@ -189,7 +219,7 @@ vi.mock("./use-composer-drafts", async () => { scheduleUnusedComposerAttachmentCleanup: () => {}, appendComposerDraftAttachments: state.appendAttachments, appendComposerDraftText: vi.fn(), - mergeComposerDraftContent: vi.fn(), + mergeComposerDraftContent: state.mergeDraft, removeComposerDraftAttachment: vi.fn(), useComposerDraft: () => state.draft, useComposerDraftSettings: () => state.draft, @@ -197,6 +227,8 @@ vi.mock("./use-composer-drafts", async () => { }; }); vi.mock("../lib/composerImages", () => ({ + isFileBackedComposerAttachment: (attachment: { readonly fileUri?: string }) => + attachment.fileUri !== undefined, convertPastedImagesToAttachments: vi.fn(), pickComposerFiles: vi.fn(), pickComposerMedia: vi.fn(), @@ -224,6 +256,7 @@ beforeEach(() => { state.draft = { text: "Keep my draft", attachments: [], + context: undefined, modelSelection: undefined, runtimeMode: undefined, }; @@ -431,25 +464,72 @@ describe("mobile task permissions", () => { expect(await composer.onSendMessage()).toBeNull(); expect(startSideChat).toHaveBeenCalledExactlyOnceWith( { environmentId: "secondary", threadId: "thread" }, - "why does this fail?", + { text: "why does this fail?", attachments: [], titleSeed: "why does this fail?" }, { runtimeMode: "approval-required", modelSelection: selection }, ); expect(state.enqueue).not.toHaveBeenCalled(); expect(state.clearDraft).toHaveBeenCalled(); - // An attachment added while the side chat starts stays in the draft. + // Attachments and context go to the side chat, bound to their uploaded ids. + vi.clearAllMocks(); + const imageRecord = { + version: 1, + kind: "image", + contextId: "image-shot", + label: "shot.png", + attachmentId: "shot", + name: "shot.png", + mimeType: "image/png", + sizeBytes: 1, + } as OrchestrationMessageContext["records"][number]; + state.draft = { + ...state.draft, + text: "/side what is this?", + attachments: [ + { id: "shot", type: "image", name: "shot.png" } as DraftComposerImageAttachment, + ], + context: { version: 1, records: [imageRecord] }, + }; + expect(await useThreadComposerState({ startSideChat }).onSendMessage()).toBeNull(); + expect(startSideChat).toHaveBeenCalledExactlyOnceWith( + { environmentId: "secondary", threadId: "thread" }, + expect.objectContaining({ + text: "what is this?", + attachments: [expect.objectContaining({ id: "uploaded-shot" })], + context: { version: 1, records: [{ ...imageRecord, attachmentId: "uploaded-shot" }] }, + }), + expect.anything(), + ); + expect(state.clearDraft).toHaveBeenCalled(); + state.draft = { ...state.draft, context: undefined }; + + // A failed start restores the draft: text first, since the merge caps attachments, then + // the uncapped attachments. The local file stays on disk meanwhile, and no send runs from + // the half-restored draft. vi.clearAllMocks(); + let heldDuringStart: string[] = []; startSideChat.mockImplementationOnce(async () => { - state.draft = { - ...state.draft, - attachments: [{ id: "added" } as DraftComposerImageAttachment], - }; - return true; + heldDuringStart = [...state.fileHolds]; + return false; }); - state.draft = { ...state.draft, text: "/side again?", attachments: [] }; - expect(await useThreadComposerState({ startSideChat }).onSendMessage()).toBeNull(); - expect(startSideChat).toHaveBeenCalledOnce(); - expect(state.clearDraft).not.toHaveBeenCalled(); + const shot = { id: "shot", fileUri: "file:///shot.png" } as DraftComposerImageAttachment; + const sent = { ...state.draft, attachments: [shot] }; + state.draft = sent; + const restoring = useThreadComposerState({ startSideChat }); + const restoreOrder: string[] = []; + state.mergeDraft.mockImplementationOnce(async (_key, content) => { + state.draft = { ...sent, text: "new text" }; + await restoring.onSendMessage(); + restoreOrder.push(`merge ${content.text}`); + }); + state.appendAttachments.mockImplementationOnce((_key, attachments, options) => + restoreOrder.push(`append ${attachments.length} restore=${options.restore}`), + ); + expect(await restoring.onSendMessage()).toBeNull(); + expect(restoreOrder).toEqual(["merge /side what is this?", "append 1 restore=true"]); + expect(state.enqueue).not.toHaveBeenCalled(); + expect(heldDuringStart).toEqual(["file:///shot.png"]); + expect(state.fileHolds).toEqual([]); // A model the send would refuse does not start a side chat either. vi.clearAllMocks(); state.serverConfig = { diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index 97b463e9b6a4a..69ec0af369956 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -45,9 +45,15 @@ import { type CodexFeedbackSubmission, } from "@t3tools/client-runtime/state/threads"; import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models"; +import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations"; import { upgradeLegacyContextMessage } from "@t3tools/shared/composerContextLegacy"; import { restoreAttachmentOnlyBootstrapPrompt } from "@t3tools/shared/composerContextReferences"; -import { composerContextSendBlockReason, reidentifyComposerContext } from "../lib/composerContext"; +import { + composerContextSendBlockReason, + reidentifyComposerContext, + serializeComposerMessageForServer, + uploadedComposerContext, +} from "../lib/composerContext"; import { uuidv4 } from "../lib/uuid"; import { useNowMinuteMs } from "../lib/clock"; @@ -57,7 +63,11 @@ import { isModelSelectionUnavailable, } from "../lib/modelOptions"; -import type { DraftComposerImageAttachment } from "../lib/composerImages"; +import { + type DraftComposerImageAttachment, + isFileBackedComposerAttachment, +} from "../lib/composerImages"; +import { retainComposerAttachmentFileForPreview } from "../lib/composerAttachmentPreviewRetention"; import { scopedThreadKey } from "../lib/scopedEntities"; import { buildThreadFeed, createThreadFeedCache } from "../lib/threadActivity"; import { @@ -71,6 +81,7 @@ import { import { threadAllowsProviderSwitch } from "./thread-provider-switching"; import { appAtomRegistry } from "./atom-registry"; import { pendingThreadCreationMessage } from "./pending-thread-creation"; +import type { SideChatMessage } from "../features/threads/useStartSideChat"; import { composerAttachmentUploadBlockReason, composerAttachmentUploadsAtom, @@ -211,10 +222,10 @@ export function useThreadDraftForThread(input: { } export function useThreadComposerState(input: { - /** Forks the thread into a side chat that gets `prompt`; resolves false when it did not start. */ + /** Forks the thread into a side chat that gets `message`; resolves false when it did not start. */ readonly startSideChat: ( source: ScopedThreadRef, - prompt: string, + message: SideChatMessage, settings: { readonly runtimeMode: RuntimeMode; readonly modelSelection: ModelSelection }, ) => Promise; }) { @@ -634,6 +645,8 @@ export function useThreadComposerState(input: { return null; } + // Until a side chat start settles, its draft may be only partly back in the composer. + if (startingSideChatRef.current) return null; const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id); const draft = getComposerDraftSnapshot(threadKey); if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null; @@ -666,47 +679,100 @@ export function useThreadComposerState(input: { ); Dialog.alert(title, detail); }; + // Recovery preserves over-cap attachments; require trimming or outbox delivery would reject indefinitely. + if (attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) { + Dialog.alert( + m(msg("Too many attachments")), + m( + msg("Remove attachments until there are at most {max}.", { + max: PROVIDER_SEND_TURN_MAX_ATTACHMENTS, + }), + ), + ); + return null; + } + + const contextBlockReason = composerContextSendBlockReason(draft.context); + if (contextBlockReason) { + Dialog.alert(m(msg("Too much context")), contextBlockReason); + return null; + } + // A redirect's text answers its approval, so `/side` there is that text, not the command. const sideChatCommand = beforeDispatch === undefined ? parseSideChatCommand(text) : null; if (sideChatCommand) { if (sideChatUnavailableReason !== null) { Dialog.alert(m(msg("Side chat not started")), sideChatUnavailableReason); - } else if (attachments.length > 0 || (draft.context?.records.length ?? 0) > 0) { - Dialog.alert( - m(msg("Side chats take text only")), - m(msg("Remove the attachments and context, then send it again.")), - ); - } else if (sideChatCommand.prompt.length === 0) { + } else if ( + sideChatCommand.prompt.length === 0 && + attachments.length === 0 && + (draft.context?.records.length ?? 0) === 0 + ) { Dialog.alert( m(msg("Ask a side question")), m(msg("Type the question after {command}, then send it.", { command: "/side" })), ); } else if (modelUnavailable) { alertModelUnavailable(); - } else if (!startingSideChatRef.current) { + } else { startingSideChatRef.current = true; - const started = await input - .startSideChat( + // Cleared at send, like a queued message, so nothing in it can vanish mid-start. The + // holds keep the local files until the side chat has them or the draft has them back. + const fileHolds = attachments + .filter(isFileBackedComposerAttachment) + .map(retainComposerAttachmentFileForPreview); + clearComposerDraftContent(threadKey, { deferAttachmentCleanup: true }); + const started = await settlePromise(async () => { + const prepared = await Effect.runPromise( + prepareTurnAttachments({ + environmentId: thread.environmentId, + attachments, + supportsImageUploads: true, + uploadAttachment: (attachment) => + uploadComposerAttachmentShared(thread.environmentId, attachment), + }), + ); + if (prepared.status !== "ready") return false; + return input.startSideChat( { environmentId: thread.environmentId, threadId: thread.id }, - sideChatCommand.prompt, + { + ...serializeComposerMessageForServer( + restoreAttachmentOnlyBootstrapPrompt( + sideChatCommand.prompt, + prepared.attachments.length > 0, + ), + uploadedComposerContext(draft.context, attachments, prepared.attachments), + ), + attachments: prepared.attachments, + titleSeed: deriveThreadTitleSeed({ text: sideChatCommand.prompt, attachments }, m), + }, { runtimeMode: draft.runtimeMode ?? thread.runtimeMode, modelSelection, }, - ) - .finally(() => { - startingSideChatRef.current = false; - }); - // Clear only what was sent; the draft may have changed while the side chat started. - const current = getComposerDraftSnapshot(threadKey); - if ( - started && - current.text === draft.text && - current.attachments.length === 0 && - (current.context?.records.length ?? 0) === 0 - ) { - clearComposerDraftContent(threadKey); + ); + }); + if (AsyncResult.isSuccess(started) && started.value) { + scheduleUnusedComposerAttachmentCleanup(attachments); + } else { + // Restore with uncapped append; a capped merge could drop attachments added meanwhile. + // A failed disk write still leaves the merged draft in memory, and the append saves again. + await mergeComposerDraftContent(threadKey, { + text: draft.text, + context: draft.context, + attachments: [], + }).catch(() => undefined); + appendComposerDraftAttachments(threadKey, attachments, { restore: true }); + if (AsyncResult.isFailure(started)) { + const error = squashAtomCommandFailure(started); + Dialog.alert( + m(msg("Side chat not started")), + error instanceof Error ? error.message : m(msg("Could not start a side chat.")), + ); + } } + startingSideChatRef.current = false; + for (const release of fileHolds) release(); } return null; } @@ -723,24 +789,6 @@ export function useThreadComposerState(input: { clearComposerDraftContent(threadKey); return null; } - // Recovery preserves over-cap attachments; require trimming or outbox delivery would reject indefinitely. - if (attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) { - Dialog.alert( - m(msg("Too many attachments")), - m( - msg("Remove attachments until there are at most {max}.", { - max: PROVIDER_SEND_TURN_MAX_ATTACHMENTS, - }), - ), - ); - return null; - } - - const contextBlockReason = composerContextSendBlockReason(draft.context); - if (contextBlockReason) { - Dialog.alert(m(msg("Too much context")), contextBlockReason); - return null; - } if (modelUnavailable) { alertModelUnavailable(); diff --git a/apps/web/src/components/ChatView.browser.test.tsx b/apps/web/src/components/ChatView.browser.test.tsx index a0458f9e80280..8c1ddf1d84122 100644 --- a/apps/web/src/components/ChatView.browser.test.tsx +++ b/apps/web/src/components/ChatView.browser.test.tsx @@ -662,3 +662,85 @@ it("selecting a side-chat tab focuses that side chat's composer", async () => { await expect.element(sideEditor).toHaveFocus(); await expect.element(mainEditor).toHaveTextContent("main draft"); }); + +it("/side sends the draft's attachments and context, and keeps them when it does not start", async () => { + await page.viewport(1400, 900); + const thread = threadWithHistory("side-attachments", 1); + let holdFork = false; + using _environment = installFakeEnvironment([thread], { + acceptCommands: true, + holdCommand: (command) => holdFork && command.type === "thread.fork", + }); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + const router = getRouter( + createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }), + ); + await router.load(); + await using _app = await render(, { + // AppRoot brings its own router. + router: false, + }); + using _uploads = acceptAttachmentUploads(); + await expect.element(page.getByText(`Answer 0 for ${thread.id}.`)).toBeVisible(); + + const editor = page.getByRole("textbox", { name: `Message ${thread.title}`, exact: true }); + const image = page.getByRole("img", { name: "shot.png" }); + const sendImageToSideChat = async () => { + 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 }), + ); + await expect.element(image).toBeVisible(); + await userEvent.keyboard("/side what is this?{Enter}"); + await expect.element(image).not.toBeInTheDocument(); + }; + const sentMessage = (fields: Record) => + vi.waitFor(() => + expect(dispatchedCommands()).toContainEqual( + expect.objectContaining({ type: "message.dispatch", ...fields }), + ), + ); + + await sendImageToSideChat(); + await sentMessage({ + text: "what is this?", + attachments: [expect.objectContaining({ type: "image", id: "upload-1" })], + context: { + version: 1, + records: [expect.objectContaining({ kind: "image", attachmentId: "upload-1" })], + }, + }); + + // A reply alone is enough to send. + await page.getByRole("button", { name: "Reply to this response" }).first().click(); + await userEvent.click(editor); + await userEvent.keyboard("/side {Enter}"); + await sentMessage({ + context: expect.objectContaining({ records: [expect.objectContaining({ kind: "response" })] }), + }); + + // A failed start puts the message back after the draft typed meanwhile. + holdFork = true; + await sendImageToSideChat(); + await userEvent.keyboard("next draft"); + await vi.waitFor(() => + expect(dispatchedCommands().filter((command) => command.type === "thread.fork")).toHaveLength( + 3, + ), + ); + await rejectPendingCommand("Side chats are paused."); + await expect.element(image).toBeVisible(); + await vi.waitFor(() => + expect((editor.element() as HTMLElement).innerText.split("\n").filter(Boolean)).toEqual([ + "next draft", + "/side what is this?", + ]), + ); +}); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index e69de418cd3ee..bceb3d9eb0788 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -2882,7 +2882,7 @@ export default function ChatView(props: ChatViewProps) { ? gt("Available once the thread's worktree is set up.") : null; const openSideChatStable = useStableCallback(() => void sideChat.open()); - const sendSideChatStable = useStableCallback((prompt: string) => sideChat.open(prompt)); + const sendSideChatStable = useStableCallback(sideChat.open); const { onConfirmRevertStable, onForkFromRunStable, onRevertTimelineTurnStable } = useTimelineRewind({ environmentId, diff --git a/apps/web/src/components/chat/chatViewSend.ts b/apps/web/src/components/chat/chatViewSend.ts index e6d802ffe7f92..b78fc6a0b9562 100644 --- a/apps/web/src/components/chat/chatViewSend.ts +++ b/apps/web/src/components/chat/chatViewSend.ts @@ -272,26 +272,58 @@ export async function rewindToMessage(input: { } } +function withRestored( + existing: ReadonlyArray | undefined, + restored: ReadonlyArray, + key: (item: T) => string, +): T[] { + const kept = existing ?? []; + return [...kept, ...restored.filter((item) => !kept.some((other) => key(other) === key(item)))]; +} + /** - * Writes a failed send's composer contents back into its draft. Returns the - * restored images, which are fresh copies so their preview URLs outlive the - * optimistic row that held the originals. + * Writes a failed send's composer contents back into its draft, after anything + * typed since. Returns the restored images, which are fresh copies so their + * preview URLs outlive the optimistic row that held the originals. */ export function restoreComposerDraft( draftTarget: ScopedThreadRef | DraftId, snapshot: ComposerSendSnapshot, ): ComposerImageAttachment[] { const store = useComposerDraftStore.getState(); + const current = store.getComposerDraft(draftTarget); const images = snapshot.images.map(cloneComposerImageForRetry); - store.setPrompt(draftTarget, snapshot.draftText); - store.setReplyTo(draftTarget, snapshot.replyTo); + store.setPrompt( + draftTarget, + current?.prompt.trim() ? `${current.prompt}\n\n${snapshot.draftText}` : snapshot.draftText, + ); + store.setReplyTo(draftTarget, current?.replyTo ?? snapshot.replyTo); store.addImages(draftTarget, images); store.addFiles(draftTarget, snapshot.files); - store.setTerminalContexts(draftTarget, snapshot.terminalContexts); - store.setPreviewAnnotations(draftTarget, snapshot.previewAnnotations); - store.setReviewComments(draftTarget, snapshot.reviewComments); - store.setThreadContexts(draftTarget, snapshot.threadContexts); - store.setEnvironmentContexts(draftTarget, snapshot.environmentContexts); + store.setTerminalContexts( + draftTarget, + withRestored(current?.terminalContexts, snapshot.terminalContexts, (context) => context.id), + ); + store.setPreviewAnnotations( + draftTarget, + withRestored(current?.previewAnnotations, snapshot.previewAnnotations, (entry) => entry.id), + ); + store.setReviewComments( + draftTarget, + withRestored(current?.reviewComments, snapshot.reviewComments, (comment) => comment.id), + ); + store.setThreadContexts( + draftTarget, + withRestored(current?.threadContexts, snapshot.threadContexts, (record) => record.contextId), + ); + store.setEnvironmentContexts( + draftTarget, + withRestored( + current?.environmentContexts, + snapshot.environmentContexts, + (record) => record.contextId, + ), + ); return images; } diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index 19a524369cbf7..43f2082e7b7e9 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -25,7 +25,9 @@ import { type EnvironmentId, type ModelSelection, type PreviewAnnotationPayload, + type ResponseContextRecord, type ScopedThreadRef, + type ThreadContextRecord, type ThreadId, ProviderInteractionMode, RuntimeMode, @@ -80,10 +82,7 @@ import { useComposerDraftStore, DraftId, } from "../../composerDraftStore"; -import { - filterTerminalContextsWithText, - type TerminalContextDraft, -} from "../../lib/terminalContext"; +import type { TerminalContextDraft } from "../../lib/terminalContext"; import { collectInlineContextIds, ensureInlineContextReferences, @@ -108,6 +107,7 @@ import { referencedThreadContexts, } from "./composerSend.logic"; import { useMultipleModelSend } from "./useMultipleModelSend"; +import type { SideChatMessage } from "./useSideChat"; import { type ComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch"; import { getUploadedAttachments, @@ -158,6 +158,32 @@ function readEnvironmentPresentation(environmentId: EnvironmentId) { return appAtomRegistry.get(environmentPresentations.presentationsAtom).get(environmentId); } +function liveAttachmentCapabilities( + environmentId: EnvironmentId, + files: ReadonlyArray, +) { + const config = appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId) ?? null; + const supportsAttachmentUploads = config !== null; + return { + supportsAttachmentUploads, + fileBlockReason: fileAttachmentCapabilityBlockReason({ + files, + attachmentUploadsCapabilityKnown: config !== null, + supportsAttachmentUploads, + maxFileAttachmentBytes: + config?.environment.capabilities.fileAttachments?.maxUploadBytes ?? null, + }), + }; +} + +// The reply leads the message, so its card sits above the text it is about. Text that +// already points at that response, from a pasted card, keeps its one reference. +function withReplyReference(prompt: string, replyTo: ResponseContextRecord | null) { + return replyTo && !collectInlineContextIds(prompt).includes(replyTo.contextId) + ? `${formatInlineContextReference(responseContextReference(replyTo))} ${prompt}` + : prompt; +} + function draftHasNonPromptContent(target: ComposerThreadTarget) { const draft = useComposerDraftStore.getState().getComposerDraft(target); return draft ? composerDraftHasUserContent({ ...draft, prompt: "" }) : false; @@ -247,8 +273,8 @@ interface ComposerSendInput { readonly setKeepFullHistory: (threadKey: string, keep: boolean) => void; readonly anchorNewTurn: TimelineFollow["anchorNewTurn"]; readonly acknowledgeActiveThreadWoke: () => void; - /** Resolves true once the side chat started and got the prompt. */ - readonly onSideChat?: ((prompt: string) => Promise) | undefined; + /** Resolves true once the side chat started and got the message. */ + readonly onSideChat?: ((message: SideChatMessage | undefined) => Promise) | undefined; /** Refuses `/side` with this reason and keeps the draft. */ readonly sideChatDisabledReason: string | null; readonly handleNewThreadInActiveProject: () => void; @@ -505,35 +531,177 @@ export function useComposerSend(input: ComposerSendInput) { ); return; } + const startDraftAttachmentUploads = ( + attachments: ReadonlyArray, + ) => { + for (const attachment of attachments) { + const upload = + readAttachmentUpload(attachment.id)?.status === "failed" + ? retryAttachmentUpload + : startAttachmentUpload; + upload({ environmentId, image: attachment, draftTarget: composerDraftTarget }); + } + }; + const warnStrandedThreadContext = ( + text: string, + records: ReadonlyArray, + ) => { + const strandedThread = threadContextsOutsideEnvironment({ + text, + records, + environmentId, + linkedEnvironments, + })[0]; + if (!strandedThread) return false; + const owner = + readEnvironmentPresentation(strandedThread.environmentId)?.entry.target.label ?? null; + toastManager.add( + stackedThreadToast({ + type: "warning", + title: m(msg("Attached thread is on another machine")), + description: + owner === null + ? m( + msg( + "This machine's agent can't read \"{title}\". Remove it, or switch back to its machine to send.", + { title: strandedThread.title }, + ), + ) + : m( + msg( + "This machine's agent can't read \"{title}\". Remove it, or switch back to {owner} to send.", + { title: strandedThread.title, owner }, + ), + ), + }), + ); + return true; + }; if (onSideChat && sendCtx && sideChatCommand && sideChatDisabledReason === null) { + const replyTo = + useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.replyTo ?? null; + const prompt = withReplyReference(sideChatCommand.prompt, replyTo); + const { sendableTerminalContexts, hasSendableContent } = deriveComposerSendState({ + prompt, + imageCount: sendCtx.images.length + sendCtx.files.length, + terminalContexts: sendCtx.terminalContexts, + elementContextCount: + (replyTo === null ? 0 : 1) + + sendCtx.previewAnnotations.length + + sendCtx.reviewComments.length + + sendCtx.threadContexts.length + + sendCtx.environmentContexts.length, + }); + // An answer's text and attachments live in the question's draft, apart from this one. if ( - sendCtx.images.length > 0 || - sendCtx.files.length > 0 || - filterTerminalContextsWithText(sendCtx.terminalContexts).length > 0 || - sendCtx.previewAnnotations.length > 0 || - sendCtx.reviewComments.length > 0 || - sendCtx.threadContexts.length > 0 || - sendCtx.environmentContexts.length > 0 || - useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.replyTo + sendCtx.answeringPendingUserInput && + (replyTo !== null || + sendCtx.images.length > 0 || + sendCtx.files.length > 0 || + sendableTerminalContexts.length > 0 || + sendCtx.previewAnnotations.length > 0 || + sendCtx.reviewComments.length > 0 || + sendCtx.threadContexts.length > 0 || + sendCtx.environmentContexts.length > 0) ) { toastManager.add( stackedThreadToast({ type: "warning", - title: m(msg("Side chats take text only")), + title: m(msg("Side chat not started")), description: m(msg("Remove the attachments and context, then send it again.")), }), ); return; } - const started = await onSideChat(sideChatCommand.prompt); - // Clear only what was sent; the user may have edited the draft or left meanwhile. - if ( - started && - currentRouteThreadKeyRef.current === routeThreadKey && - promptRef.current === promptAtSend - ) { + if (warnStrandedThreadContext(prompt, sendCtx.threadContexts)) return; + const snapshot = snapshotComposerSend({ + ...sendCtx, + prompt, + sendableTerminalContexts, + replyTo, + }); + const capabilities = liveAttachmentCapabilities(environmentId, snapshot.files); + if (capabilities.fileBlockReason !== null) { + setThreadError(activeThread.id, capabilities.fileBlockReason); + return; + } + const sendsDraft = hasSendableContent && !sendCtx.answeringPendingUserInput; + sendInFlightRef.current = true; + if (capabilities.supportsAttachmentUploads) startDraftAttachmentUploads(snapshot.attachments); + // Cleared at send, like a regular message, so nothing in it can change or vanish mid-start. + if (sendsDraft) { + clearComposerDraftContent(composerDraftTarget); promptRef.current = ""; - setComposerDraftPrompt(composerDraftTarget, ""); + composerRef.current?.resetCursorState(); + } + const started = await settlePromise(async () => { + if (!hasSendableContent) return onSideChat(undefined); + const attachments = await prepareTurnAttachments({ + environmentId, + attachments: snapshot.attachments, + usesAttachmentUploads: capabilities.supportsAttachmentUploads, + draftTarget: composerDraftTarget, + }); + // `onSideChat` forks the thread on screen, which may have changed during the upload. + if (currentRouteThreadKeyRef.current !== routeThreadKey) return false; + const attachmentIds = boundAttachmentIds(attachments, snapshot.attachments); + return onSideChat({ + attachments, + ...withMessageContext({ + text: snapshot.messageText || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, + context: buildMessageContext({ + ...snapshot, + attachments: snapshot.attachments.map((attachment, index) => ({ + attachment, + attachmentId: attachmentIds[index]!, + })), + }), + }), + titleSeed: deriveThreadTitleSeed( + { + text: snapshot.messageText, + attachments: snapshot.attachments, + fallbackLabels: sendTitleFallbackLabels(snapshot), + }, + m, + ), + }); + }).finally(() => { + sendInFlightRef.current = false; + }); + const startedOk = started._tag === "Success" && started.value; + if (started._tag === "Failure") { + const error = squashAtomCommandFailure(started); + setThreadError( + activeThread.id, + error instanceof Error ? error.message : m(msg("Could not start a side chat.")), + ); + } + if (sendsDraft) { + if (startedOk && capabilities.supportsAttachmentUploads) { + releaseDraftAttachments(snapshot.attachments); + } + // A restore clones the images first, so the sent previews can go either way. + if (!startedOk) + restoreComposerDraft(composerDraftTarget, { ...snapshot, draftText: promptAtSend }); + for (const image of snapshot.images) { + if (image.previewUrl.startsWith("blob:")) URL.revokeObjectURL(image.previewUrl); + } + if (!startedOk && currentRouteThreadKeyRef.current === routeThreadKey) { + const prompt = + useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.prompt ?? + promptAtSend; + promptRef.current = prompt; + composerRef.current?.resetCursorState({ prompt }); + } + return; + } + // Answering a question, the composer shows the answer, which lives apart from this draft. + if (startedOk && currentRouteThreadKeyRef.current === routeThreadKey) { + if (!sendCtx.answeringPendingUserInput && promptRef.current === promptAtSend) { + setComposerDraftPrompt(composerDraftTarget, ""); + promptRef.current = ""; + } composerRef.current?.resetCursorState(); } return; @@ -616,43 +784,8 @@ export function useComposerSend(input: ComposerSendInput) { : promptRef.current; const replyTo = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.replyTo ?? null; - // The reply leads the message, so its card sits above the text it is about. Text that - // already points at that response, from a pasted card, keeps its one reference. - const promptForSend = - replyTo && !collectInlineContextIds(draftPrompt).includes(replyTo.contextId) - ? `${formatInlineContextReference(responseContextReference(replyTo))} ${draftPrompt}` - : draftPrompt; - const strandedThread = threadContextsOutsideEnvironment({ - text: promptForSend, - records: composerThreadContexts, - environmentId, - linkedEnvironments, - })[0]; - if (strandedThread) { - const owner = - readEnvironmentPresentation(strandedThread.environmentId)?.entry.target.label ?? null; - toastManager.add( - stackedThreadToast({ - type: "warning", - title: m(msg("Attached thread is on another machine")), - description: - owner === null - ? m( - msg( - "This machine's agent can't read \"{title}\". Remove it, or switch back to its machine to send.", - { title: strandedThread.title }, - ), - ) - : m( - msg( - "This machine's agent can't read \"{title}\". Remove it, or switch back to {owner} to send.", - { title: strandedThread.title, owner }, - ), - ), - }), - ); - return; - } + const promptForSend = withReplyReference(draftPrompt, replyTo); + if (warnStrandedThreadContext(promptForSend, composerThreadContexts)) return; if (queuedRunEdit.isEditing) { // A queued message stays in its thread, so saving `/side` would send it to main. if (!directAnnotation && parseSideChatCommand(promptAtSend)) { @@ -888,20 +1021,8 @@ export function useComposerSend(input: ComposerSendInput) { return; } - const readLiveAttachmentCapabilities = () => { - const config = appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId) ?? null; - const liveSupportsAttachmentUploads = config !== null; - return { - supportsAttachmentUploads: liveSupportsAttachmentUploads, - fileBlockReason: fileAttachmentCapabilityBlockReason({ - files: composerFilesSnapshot, - attachmentUploadsCapabilityKnown: config !== null, - supportsAttachmentUploads: liveSupportsAttachmentUploads, - maxFileAttachmentBytes: - config?.environment.capabilities.fileAttachments?.maxUploadBytes ?? null, - }), - }; - }; + const readLiveAttachmentCapabilities = () => + liveAttachmentCapabilities(environmentId, composerFilesSnapshot); const multipleTargets: MultipleModelTarget[] = []; for (const resolved of resolveMultipleModelTargets({ @@ -938,19 +1059,7 @@ export function useComposerSend(input: ComposerSendInput) { ? attachmentCapabilitiesBeforeUpload.supportsAttachmentUploads : (readEnvironmentPresentation(environmentId)?.serverConfig ?? null) !== null; // Uploads finish after the message shows as sending; the turn starts once they land. - if (turnUsesAttachmentUploads) { - for (const attachment of composerAttachmentsSnapshot) { - const upload = - readAttachmentUpload(attachment.id)?.status === "failed" - ? retryAttachmentUpload - : startAttachmentUpload; - upload({ - environmentId, - image: attachment, - draftTarget: composerDraftTarget, - }); - } - } + if (turnUsesAttachmentUploads) startDraftAttachmentUploads(composerAttachmentsSnapshot); if ( multipleModelSelections === null && diff --git a/apps/web/src/components/chat/useSideChat.ts b/apps/web/src/components/chat/useSideChat.ts index 0793c61fbb05e..7a423f9f99a1b 100644 --- a/apps/web/src/components/chat/useSideChat.ts +++ b/apps/web/src/components/chat/useSideChat.ts @@ -3,7 +3,7 @@ import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; import { m } from "~/i18n/messages"; import type { ModelSelection, RuntimeMode, ScopedThreadRef } from "@t3tools/contracts"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; -import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations"; +import type { StartThreadTurnInput } from "@t3tools/client-runtime/operations"; import { type AtomCommandResult, isAtomCommandInterrupted, @@ -20,9 +20,14 @@ import { threadEnvironment } from "../../state/threads"; import { useAtomCommand } from "../../state/use-atom-command"; import { useOrchestrationCommand } from "../../state/use-orchestration-command"; +export type SideChatMessage = Pick< + StartThreadTurnInput["message"], + "text" | "attachments" | "context" +> & { readonly titleSeed: string }; + /** * Starts side chats from `threadRef`, or offers none when it is null. `open` forks the - * thread's latest stable point, sends `prompt` there with `readSettings()`, the parent + * thread's latest stable point, sends `message` there with `readSettings()`, the parent * composer's settings, and shows the tab. It resolves false when the side chat did not * start, or another one is still starting. */ @@ -51,7 +56,7 @@ export function useSideChat(input: { const error = squashAtomCommandFailure(failure); input.onError(thrownErrorMessage(error, m) ?? fallback); }; - const start = async (threadRef: ScopedThreadRef, prompt: string | undefined) => { + const start = async (threadRef: ScopedThreadRef, message: SideChatMessage | undefined) => { const { runtimeMode, modelSelection } = input.readSettings(); const targetThreadId = newThreadId(); const fork = await forkSideChat({ @@ -92,16 +97,16 @@ export function useSideChat(input: { return false; } } - const text = prompt?.trim(); // Send before showing the tab: closing a tab whose side chat has no run deletes it. - if (text) { + if (message) { + const { titleSeed, ...content } = message; const turn = await startThreadTurn({ environmentId: threadRef.environmentId, input: { threadId: targetThreadId, - message: { messageId: newMessageId(), role: "user", text, attachments: [] }, + message: { messageId: newMessageId(), role: "user", ...content }, ...(modelSelection === undefined ? {} : { modelSelection }), - titleSeed: deriveThreadTitleSeed({ text, attachments: [] }, m), + titleSeed, runtimeMode, interactionMode: "default", createdAt: new Date().toISOString(), @@ -118,11 +123,11 @@ export function useSideChat(input: { useRightPanelStore.getState().openSideChat(threadRef, targetThreadId); return true; }; - const open = async (prompt?: string) => { + const open = async (message?: SideChatMessage) => { const { threadRef } = input; if (!threadRef || pendingRef.current) return false; pendingRef.current = true; - return start(threadRef, prompt).finally(() => { + return start(threadRef, message).finally(() => { pendingRef.current = false; }); }; diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index ddbfade77b4a8..7cd1b127f65d2 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -4599,7 +4599,6 @@ "6d00220bfee72afd": "Nicht verbunden: Nachricht nicht gesendet", "f62c43120e8c60e7": "Verbindung zur Umgebung wird wiederhergestellt. Versuche es erneut, sobald sie verbunden ist.", "74e7e5c0536cda02": "Nebenchat nicht gestartet", - "be6231ac5b08f35e": "Nebenchats nehmen nur Text an", "faf9ee0a28119e10": "Entferne die Anhänge und den Kontext und sende dann erneut.", "1778ba2f32077b39": "Aktualisiere diesen Server, bevor du mehrere Modelle startest.", "736caccf2954a7f5": "Modelle und einen Basis-Branch wählen", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 11c9c1d83dd04..4754afcb4269e 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -4598,7 +4598,6 @@ "6d00220bfee72afd": "Not connected: message not sent", "f62c43120e8c60e7": "Reconnecting to the environment. Try again once it is connected.", "74e7e5c0536cda02": "Side chat not started", - "be6231ac5b08f35e": "Side chats take text only", "faf9ee0a28119e10": "Remove the attachments and context, then send it again.", "1778ba2f32077b39": "Update this server before starting multiple models.", "736caccf2954a7f5": "Choose models and a base branch", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index b85c0a6f1be1a..bace8792e3fad 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -4596,7 +4596,6 @@ "6d00220bfee72afd": "Sin conexión: mensaje no enviado", "f62c43120e8c60e7": "Reconectando con el entorno. Vuelve a intentarlo cuando esté conectado.", "74e7e5c0536cda02": "Chat lateral no iniciado", - "be6231ac5b08f35e": "Los chats laterales solo admiten texto", "faf9ee0a28119e10": "Quita los adjuntos y el contexto, y vuelve a enviarlo.", "1778ba2f32077b39": "Actualiza este servidor antes de iniciar varios modelos.", "736caccf2954a7f5": "Elige los modelos y una rama base", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index a6fb1cd5ad026..a658ad17a447a 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -4597,7 +4597,6 @@ "6d00220bfee72afd": "Non connecté : message non envoyé", "f62c43120e8c60e7": "Reconnexion à l’environnement. Réessayez une fois la connexion établie.", "74e7e5c0536cda02": "Discussion annexe non démarrée", - "be6231ac5b08f35e": "Les discussions annexes n’acceptent que du texte", "faf9ee0a28119e10": "Retirez les pièces jointes et le contexte, puis renvoyez.", "1778ba2f32077b39": "Mettez à jour ce serveur avant de lancer plusieurs modèles.", "736caccf2954a7f5": "Choisissez des modèles et une branche de base", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 149a7e4799787..0472298922416 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -4586,7 +4586,6 @@ "6d00220bfee72afd": "未接続: メッセージは送信されませんでした", "f62c43120e8c60e7": "環境に再接続しています。接続されたらもう一度お試しください。", "74e7e5c0536cda02": "サイドチャットが開始されていません", - "be6231ac5b08f35e": "サイドチャットではテキストのみ使用できます", "faf9ee0a28119e10": "添付ファイルとコンテキストを削除してから、もう一度送信してください。", "1778ba2f32077b39": "複数のモデルを開始する前に、このサーバーを更新してください。", "736caccf2954a7f5": "モデルとベースブランチを選択", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 6d105a882bf16..8fc59766937af 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -4583,7 +4583,6 @@ "6d00220bfee72afd": "연결되지 않음: 메시지를 보내지 않았습니다", "f62c43120e8c60e7": "환경에 다시 연결하는 중입니다. 연결되면 다시 시도하세요.", "74e7e5c0536cda02": "사이드 채팅이 시작되지 않음", - "be6231ac5b08f35e": "사이드 채팅은 텍스트만 받습니다", "faf9ee0a28119e10": "첨부 파일과 컨텍스트를 제거한 다음 다시 보내세요.", "1778ba2f32077b39": "여러 모델을 시작하기 전에 이 서버를 업데이트하세요.", "736caccf2954a7f5": "모델과 기본 브랜치를 선택하세요", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index ce5a544f36ed4..75d7b6c3eaf07 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -4596,7 +4596,6 @@ "6d00220bfee72afd": "Não conectado: mensagem não enviada", "f62c43120e8c60e7": "Reconectando ao ambiente. Tente novamente quando estiver conectado.", "74e7e5c0536cda02": "Chat paralelo não iniciado", - "be6231ac5b08f35e": "Chats paralelos aceitam só texto", "faf9ee0a28119e10": "Remova os anexos e o contexto e envie novamente.", "1778ba2f32077b39": "Atualize este servidor antes de iniciar vários modelos.", "736caccf2954a7f5": "Escolha os modelos e um branch base", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 55c23f2d13153..9eedde5b11474 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -4596,7 +4596,6 @@ "6d00220bfee72afd": "Нет подключения: сообщение не отправлено", "f62c43120e8c60e7": "Переподключение к окружению. Повторите, когда подключение восстановится.", "74e7e5c0536cda02": "Боковой чат не начат", - "be6231ac5b08f35e": "Боковые чаты принимают только текст", "faf9ee0a28119e10": "Удалите вложения и контекст, затем отправьте снова.", "1778ba2f32077b39": "Обновите этот сервер, прежде чем запускать несколько моделей.", "736caccf2954a7f5": "Выберите модели и базовую ветку", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index deb8ea68511e9..0b84b622d8ef4 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -4597,7 +4597,6 @@ "6d00220bfee72afd": "Inte ansluten: meddelandet skickades inte", "f62c43120e8c60e7": "Återansluter till miljön. Försök igen när den är ansluten.", "74e7e5c0536cda02": "Sidochatten startades inte", - "be6231ac5b08f35e": "Sidochattar tar bara emot text", "faf9ee0a28119e10": "Ta bort bilagorna och kontexten och skicka sedan igen.", "1778ba2f32077b39": "Uppdatera den här servern innan du startar flera modeller.", "736caccf2954a7f5": "Välj modeller och en basgren", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index d7bf54efc0dd0..5a8e6e2c6782f 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -4603,7 +4603,6 @@ "6d00220bfee72afd": "未连接:消息没有发送", "f62c43120e8c60e7": "正在重新连接环境,连接后请重试。", "74e7e5c0536cda02": "侧聊未开始", - "be6231ac5b08f35e": "侧聊只支持文字", "faf9ee0a28119e10": "请移除附件和上下文后再发送。", "1778ba2f32077b39": "请先更新此服务器,再同时启动多个模型。", "736caccf2954a7f5": "请选择模型和基准分支", diff --git a/apps/web/test/fakeEnvironment.ts b/apps/web/test/fakeEnvironment.ts index 42afe2ef59911..00cae2abfc567 100644 --- a/apps/web/test/fakeEnvironment.ts +++ b/apps/web/test/fakeEnvironment.ts @@ -67,7 +67,7 @@ const descriptor = { // A matching version, since a mismatch adds an update banner a typical user never sees. serverVersion: APP_VERSION, orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION, - capabilities: { repositoryIdentity: true }, + capabilities: { repositoryIdentity: true, sideChats: true }, }; const auth = { policy: "loopback-browser", @@ -406,6 +406,7 @@ const json = (body: unknown, status = 200) => // Keyed by thread id: a live thread subscription's queue, for pushing events to it. const threadSubscribers = new Map>(); let terminalMetadataSubscriber: Queue.Queue | null = null; +let shellSubscriber: Queue.Queue | null = null; let threads: ReadonlyArray = []; let dispatched: OrchestrationV2Command[] = []; let acceptCommands = false; @@ -438,8 +439,25 @@ const handlers: Record unknown> = { [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) => Effect.suspend(() => { dispatched.push(command); - if (acceptCommands && !holdCommand(command)) - return Effect.succeed({ sequence: sequence + 1 }); + if (acceptCommands && !holdCommand(command)) { + if (command.type !== "thread.fork" || !command.sideChat || shellSubscriber === null) + return Effect.succeed({ sequence: sequence + 1 }); + const fork: FakeThread = { + id: command.targetThreadId, + title: command.title ?? "Side chat", + sideChatOf: command.sourceThreadId, + runs: [], + items: [], + }; + threads = [...threads, fork]; + sequence += 1; + return Queue.offer(shellSubscriber, { + kind: "thread.updated", + sequence, + location: "active", + thread: shellOf(fork), + }).pipe(Effect.as({ sequence })); + } const reply = Deferred.makeUnsafe(); pendingDispatches.push({ command, reply }); return Deferred.await(reply); @@ -459,19 +477,27 @@ const handlers: Record unknown> = { }; }), [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => - subscribe([ - { - kind: "snapshot", - snapshot: { - schemaVersion: 1, - snapshotSequence: sequence, - projects, - threads: threads.filter((thread) => !thread.olderSettled).map(shellOf), - archivedThreads: [], + subscribe( + [ + { + kind: "snapshot", + snapshot: { + schemaVersion: 1, + snapshotSequence: sequence, + projects, + threads: threads.filter((thread) => !thread.olderSettled).map(shellOf), + archivedThreads: [], + }, }, + { kind: "synchronized" }, + ], + (queue) => { + shellSubscriber = queue; + return () => { + if (shellSubscriber === queue) shellSubscriber = null; + }; }, - { kind: "synchronized" }, - ]), + ), [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: (input: { readonly threadId: ThreadId }) => { const thread = threads.find((candidate) => candidate.id === input.threadId); if (!thread) return Stream.never; From c350ee7e15d0f993b406d243d2b4685b10a437e0 Mon Sep 17 00:00:00 2001 From: Bilal Bakr <62337003+Bil0000@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:54:50 +0300 Subject: [PATCH 063/183] feat(web): filter the issues list by project (#38256) Co-authored-by: Claude Co-authored-by: maria-rcks Co-authored-by: shivam <91240327+shivamhwp@users.noreply.github.com> --- apps/server/src/issue/IssueService.test.ts | 17 +++++- .../issue/IssueListFilterPickers.tsx | 52 ++++++++++++++++++- apps/web/src/components/issue/IssuesPage.tsx | 34 ++++++++++-- .../components/issue/issueListPreferences.ts | 11 +++- .../components/issue/issueSavedViews.test.ts | 5 ++ .../issue/issuesSearch.logic.test.ts | 28 +++++++++- .../components/issue/issuesSearch.logic.ts | 16 ++++++ docs/user/source-control.md | 2 +- packages/client-runtime/src/issueList.test.ts | 41 +++++++++++++++ packages/client-runtime/src/issueList.ts | 5 ++ 10 files changed, 199 insertions(+), 12 deletions(-) diff --git a/apps/server/src/issue/IssueService.test.ts b/apps/server/src/issue/IssueService.test.ts index e4f61ff49b82b..723228a64f04a 100644 --- a/apps/server/src/issue/IssueService.test.ts +++ b/apps/server/src/issue/IssueService.test.ts @@ -548,15 +548,20 @@ describe("IssueService with a standalone tracker", () => { const projects = [project({ id: "web", repository: "acme/web" }), project({ id: "notes" })]; const trackers = [fakeTracker(record(GITHUB)), fakeStandaloneTracker(record(LINEAR))]; const bound = yield* makeService({ - projects, + projects: [...projects, project({ id: "api", repository: "acme/api" })], trackers, bindings: { ["web" as ProjectId]: { tracker: LINEAR, scope: "ENG" } }, }); const result = yield* bound.list({ state: "open" }); - expect(listed.sort()).toEqual(["github github.com acme/web", "linear linear.app ENG"]); + expect(listed.sort()).toEqual([ + "github github.com acme/api", + "github github.com acme/web", + "linear linear.app ENG", + ]); expect(result.entries.map((entry) => [entry.tracker, entry.scope, entry.key]).sort()).toEqual( [ + ["github", "acme/api", "1"], ["github", "acme/web", "1"], ["linear", "ENG", "ENG-1"], ], @@ -571,6 +576,14 @@ describe("IssueService with a standalone tracker", () => { host: "linear.app", scope: "ENG", }); + // Narrowed to one project, both of its trackers are still read. + listed.length = 0; + const selected = yield* bound.list({ state: "open", projectId: "web" as ProjectId }); + expect(listed.sort()).toEqual(["github github.com acme/web", "linear linear.app ENG"]); + expect(selected.entries.map((entry) => [entry.projectId, entry.scope]).sort()).toEqual([ + ["web", "ENG"], + ["web", "acme/web"], + ]); // A reference picks the project's tracker by kind; both are the project's own, so writable. const linearRef = { projectId: "web" as ProjectId, diff --git a/apps/web/src/components/issue/IssueListFilterPickers.tsx b/apps/web/src/components/issue/IssueListFilterPickers.tsx index c3da3d05e8d55..ff40d1c3f8f45 100644 --- a/apps/web/src/components/issue/IssueListFilterPickers.tsx +++ b/apps/web/src/components/issue/IssueListFilterPickers.tsx @@ -1,6 +1,11 @@ import type { IssueCandidatesTarget } from "@t3tools/client-runtime/state/issues"; -import type { IssueInvolvement, IssueListState } from "@t3tools/contracts"; -import { LayersIcon, ListFilterIcon, TagIcon, UserIcon } from "lucide-react"; +import type { + EnvironmentId, + IssueInvolvement, + IssueListState, + ProjectId, +} from "@t3tools/contracts"; +import { FolderGit2Icon, LayersIcon, ListFilterIcon, TagIcon, UserIcon } from "lucide-react"; import { T, useGT } from "gt-react"; import { useState } from "react"; @@ -21,13 +26,17 @@ import { } from "~/components/ui/menu"; import { useIssueFilterCandidates } from "~/state/issues"; +import type { ProjectFaviconProject } from "../ProjectFavicon"; + import { PullRequestFilterRadioSubmenu, + pullRequestProjectKey, type PullRequestFilterOption, } from "../pullRequest/PullRequestListFilters"; import { pullRequestLabelColor } from "../pullRequest/pullRequestList.logic"; const VISIBLE_CHOICES = 30; +const ALL_PROJECTS = "all"; const matches = (needle: string, ...fields: ReadonlyArray) => needle.length === 0 || fields.some((field) => field?.toLowerCase().includes(needle)); @@ -44,15 +53,39 @@ export function IssueFiltersMenu(props: { onLabels: (labels: ReadonlyArray) => void; assignee: string | undefined; onAssignee: (assignee: string | undefined) => void; + projects: ReadonlyArray; + project: { environmentId: EnvironmentId; projectId: ProjectId } | undefined; + onProject: (project: { environmentId: EnvironmentId; projectId: ProjectId } | undefined) => void; }) { const gt = useGT(); const [open, setOpen] = useState(false); const count = [ props.state !== "open", props.involvement !== "all", + props.project, props.assignee, ...props.labels, ].filter(Boolean).length; + const projectValue = props.project + ? pullRequestProjectKey({ + id: props.project.projectId, + environmentId: props.project.environmentId, + }) + : ALL_PROJECTS; + const projectOptions: ReadonlyArray> = [ + { value: ALL_PROJECTS, label: gt("All projects"), Icon: LayersIcon }, + // A remembered project this client does not list stays shown, so the filter can be taken off. + ...(projectValue !== ALL_PROJECTS && + !props.projects.some((project) => pullRequestProjectKey(project) === projectValue) + ? [{ value: projectValue, label: gt("Unavailable project"), Icon: FolderGit2Icon }] + : []), + ...props.projects.map((project) => ({ + value: pullRequestProjectKey(project), + label: project.title, + Icon: FolderGit2Icon, + project, + })), + ]; // Read when the menu opens, not with every listing: one request per scope. const scopes = open ? props.scopes : []; return ( @@ -81,6 +114,21 @@ export function IssueFiltersMenu(props: { options={props.involvementOptions} onChange={props.onInvolvement} /> + {props.projects.length > 1 || props.project ? ( + { + const project = props.projects.find((p) => pullRequestProjectKey(p) === next); + props.onProject( + project + ? { environmentId: project.environmentId, projectId: project.id } + : undefined, + ); + }} + /> + ) : null} diff --git a/apps/web/src/components/issue/IssuesPage.tsx b/apps/web/src/components/issue/IssuesPage.tsx index bd8627a2e6689..707cda40fb889 100644 --- a/apps/web/src/components/issue/IssuesPage.tsx +++ b/apps/web/src/components/issue/IssuesPage.tsx @@ -55,6 +55,7 @@ import { import { m, type MessageResolver } from "~/i18n/messages"; import { resolveFilterOptions } from "../pullRequest/pullRequestListOptions"; import { IssueFiltersMenu } from "./IssueListFilterPickers"; +import { issueFilterProjects } from "./issuesSearch.logic"; import { ISSUE_SAVED_VIEWS } from "./issueSavedViews"; import { SavedViewsMenu } from "~/components/SavedViewsMenu"; import { PullRequestCompactFilterMenu } from "../pullRequest/PullRequestCompactFilterMenu"; @@ -199,22 +200,32 @@ export function IssuesPage() { (environment) => environment.serverConfig?.environment.capabilities.issues === true, ); const environmentLabels = new Map(environments.map((e) => [e.environmentId, e.label] as const)); + const filterProjects = issueFilterProjects( + projects.filter((project) => + capableEnvironments.some((e) => e.environmentId === project.environmentId), + ), + environmentLabels, + ); + const scopedProject = + search.issueServer && search.issueProject + ? { environmentId: search.issueServer, projectId: search.issueProject } + : undefined; const debouncedQuery = useDebouncedValue(search.q ?? "", 300); const listInput: IssueListInput = { state: search.status, involvement: search.who, limit: PAGE_SIZE, + ...(scopedProject ? { projectId: scopedProject.projectId } : {}), ...(search.host ? { host: search.host } : {}), ...(debouncedQuery ? { query: debouncedQuery } : {}), ...(search.label?.length ? { labels: search.label } : {}), ...(search.assignee ? { assignee: search.assignee } : {}), ...(search.order ? { sort: search.order } : {}), }; - const targets: ReadonlyArray = capableEnvironments.map((e) => ({ - environmentId: e.environmentId, - input: listInput, - })); + const targets: ReadonlyArray = capableEnvironments + .filter((e) => scopedProject === undefined || e.environmentId === scopedProject.environmentId) + .map((e) => ({ environmentId: e.environmentId, input: listInput })); const list = useIssueList(targets); // Refreshing a list still loading would cancel it and start over, losing the scopes already read. useLiveRefresh( @@ -277,7 +288,7 @@ export function IssuesPage() { ) : held; const groups = groupIssues(shown, debouncedQuery, projects, search.order ?? "updated"); - const filterScopes = issueFilterScopes(shown, projects); + const filterScopes = issueFilterScopes(shown, projects, scopedProject); const hostOptions = hostOptionsFor( [...held.values()].flatMap((page) => page.answer.trackers), @@ -290,6 +301,9 @@ export function IssuesPage() { const next: IssuesSearch = { who: merged.who ?? search.who, status: merged.status ?? search.status, + ...(merged.issueServer && merged.issueProject + ? { issueServer: merged.issueServer, issueProject: merged.issueProject } + : {}), ...(merged.host ? { host: merged.host } : {}), q: merged.q || undefined, ...(merged.label?.length ? { label: merged.label } : {}), @@ -676,6 +690,14 @@ export function IssuesPage() { onLabels={(label) => updateSearch({ label })} assignee={search.assignee} onAssignee={(assignee) => updateSearch({ assignee })} + projects={filterProjects} + project={scopedProject} + onProject={(project) => + updateSearch({ + issueServer: project?.environmentId, + issueProject: project?.projectId, + }) + } /> | undefined; @@ -57,6 +63,9 @@ export function issueListPreferences(search: { return { who: search.who, status: search.status, + ...(search.issueServer && search.issueProject + ? { issueServer: search.issueServer, issueProject: search.issueProject } + : {}), ...(search.host ? { host: search.host } : {}), ...(search.q ? { q: search.q } : {}), ...(search.label?.length ? { label: search.label } : {}), diff --git a/apps/web/src/components/issue/issueSavedViews.test.ts b/apps/web/src/components/issue/issueSavedViews.test.ts index bb4be62a9221f..0933dc008edef 100644 --- a/apps/web/src/components/issue/issueSavedViews.test.ts +++ b/apps/web/src/components/issue/issueSavedViews.test.ts @@ -1,10 +1,14 @@ import { describe, expect, it } from "vite-plus/test"; +import { EnvironmentId, ProjectId } from "@t3tools/contracts"; + import { issueViewMatches } from "./issueSavedViews"; const preferences = { who: "assigned", status: "open", + issueServer: EnvironmentId.make("env-1"), + issueProject: ProjectId.make("project-1"), host: "github.com", q: "crash", label: ["bug", "priority"], @@ -20,5 +24,6 @@ describe("saved issue views", () => { ); expect(issueViewMatches(view, { ...preferences, assignee: undefined })).toBe(false); expect(issueViewMatches(view, { ...preferences, label: ["bug"] })).toBe(false); + expect(issueViewMatches(view, { ...preferences, issueProject: undefined })).toBe(false); }); }); diff --git a/apps/web/src/components/issue/issuesSearch.logic.test.ts b/apps/web/src/components/issue/issuesSearch.logic.test.ts index 0ea88f19959bd..2d4aad1072b01 100644 --- a/apps/web/src/components/issue/issuesSearch.logic.test.ts +++ b/apps/web/src/components/issue/issuesSearch.logic.test.ts @@ -1,6 +1,9 @@ import { describe, expect, it } from "vite-plus/test"; -import { issuesSearchFromUrl } from "./issuesSearch.logic"; +import type { EnvironmentProject } from "@t3tools/client-runtime/state/models"; +import { EnvironmentId, ProjectId } from "@t3tools/contracts"; + +import { issueFilterProjects, issuesSearchFromUrl } from "./issuesSearch.logic"; describe("issuesSearchFromUrl", () => { it("replaces a malformed filter instead of letting the raw value through", () => { @@ -18,3 +21,26 @@ describe("issuesSearchFromUrl", () => { }); }); }); + +describe("issueFilterProjects", () => { + it("keeps every project on one repository as its own choice", () => { + const environmentId = EnvironmentId.make("env"); + const project = (id: string, isScratch = false) => + ({ + id: ProjectId.make(id), + environmentId, + title: "t3code", + workspaceRoot: `/work/${id}`, + repositoryIdentity: { canonicalKey: "github.com/pingdotgg/t3code" }, + isScratch, + }) as unknown as EnvironmentProject; + const choices = issueFilterProjects( + [project("main"), project("worktree"), project("scratch", true)], + new Map([[environmentId, "laptop"]]), + ); + expect(choices.map((choice) => [choice.id, choice.title])).toEqual([ + ["main", "t3code · laptop · /work/main"], + ["worktree", "t3code · laptop · /work/worktree"], + ]); + }); +}); diff --git a/apps/web/src/components/issue/issuesSearch.logic.ts b/apps/web/src/components/issue/issuesSearch.logic.ts index ba0db88e6ddaf..808acd1242f0d 100644 --- a/apps/web/src/components/issue/issuesSearch.logic.ts +++ b/apps/web/src/components/issue/issuesSearch.logic.ts @@ -1,3 +1,5 @@ +import { pullRequestFilterProjects } from "@t3tools/client-runtime/pull-request-project-filter"; +import type { EnvironmentProject } from "@t3tools/client-runtime/state/models"; import type { EnvironmentId, ProjectId } from "@t3tools/contracts"; import type { IssuesSearch } from "./IssuesPage"; @@ -19,6 +21,8 @@ export const issuesSearchFromUrl = (raw: Record): IssuesSearch who: raw.who === "assigned" || raw.who === "authored" || raw.who === "mentioned" ? raw.who : "all", status: raw.status === "closed" || raw.status === "all" ? raw.status : "open", + issueServer: bounded(raw.issueServer) as EnvironmentId | undefined, + issueProject: bounded(raw.issueProject) as ProjectId | undefined, host: bounded(raw.host), q: bounded(raw.q), label: labels(raw.label), @@ -31,3 +35,15 @@ export const issuesSearchFromUrl = (raw: Record): IssuesSearch scope: bounded(raw.scope), key: bounded(raw.key), }); + +/** One choice per project: projects on one repository can read different Linear teams. */ +export const issueFilterProjects = ( + projects: ReadonlyArray, + environmentLabels: ReadonlyMap, +) => + pullRequestFilterProjects( + projects + .filter((project) => !project.isScratch) + .map((project) => ({ ...project, repositoryIdentity: null })), + environmentLabels, + ); diff --git a/docs/user/source-control.md b/docs/user/source-control.md index f1a1454ff8dcc..5acbac0e22be4 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -361,7 +361,7 @@ out from the matching organization and repository. The Issues page lists the issues of every project whose remote is on GitHub, GitLab, Azure DevOps or Forgejo, grouped per tracker account. Open it from the sidebar's utility row or with **Open issues** in the command palette. Filter by open or closed, by your involvement -(assigned, opened by you, mentioning you), and by tracker; the search box asks the tracker +(assigned, opened by you, mentioning you), by project, and by tracker; the search box asks the tracker itself where it can search. Press **Load more** at the end of a group to read further back. The **Views** menu saves and restores a search, filter, and sort setup, as it does for pull requests. diff --git a/packages/client-runtime/src/issueList.test.ts b/packages/client-runtime/src/issueList.test.ts index 5085c10e51887..300eacc5a3408 100644 --- a/packages/client-runtime/src/issueList.test.ts +++ b/packages/client-runtime/src/issueList.test.ts @@ -6,6 +6,7 @@ import type { IssueTrackerSummary, ProjectId, } from "@t3tools/contracts"; +import type { EnvironmentProject } from "./state/models.ts"; import { describe, expect, it } from "vite-plus/test"; import { @@ -142,6 +143,46 @@ describe("issueFilterScopes", () => { [environmentId, hold(answer({ trackers: [tracker({})], entries: [], scopes: [scope] }))], ]); expect(issueFilterScopes(held, [])).toEqual([{ environmentId, input: scope }]); + const otherProjectId = "web" as ProjectId; + const projects = [api, otherProjectId].map((id) => ({ + id, + environmentId, + repositoryIdentity: { + provider: "github", + canonicalKey: `github.com/acme/${id}`, + owner: "acme", + name: id, + }, + })) as unknown as ReadonlyArray; + const withRepositories = new Map([ + [ + environmentId, + hold( + answer({ + trackers: [ + tracker({}), + tracker({ tracker: "github" as IssueTrackerKind, host: "github.com" }), + ], + scopes: [scope, { ...scope, projectId: otherProjectId, scope: "WEB" }], + }), + ), + ], + ]); + expect( + issueFilterScopes(withRepositories, projects, { environmentId, projectId: api }), + ).toEqual([ + { + environmentId, + input: { projectId: api, tracker: "github", host: "github.com", scope: "acme/api" }, + }, + { environmentId, input: scope }, + ]); + expect( + issueFilterScopes(withRepositories, projects, { + environmentId: "other" as EnvironmentId, + projectId: api, + }), + ).toEqual([]); }); it("skips a tracker that cannot be read", () => { diff --git a/packages/client-runtime/src/issueList.ts b/packages/client-runtime/src/issueList.ts index df0f80aae5c57..a5f3f2d5d1709 100644 --- a/packages/client-runtime/src/issueList.ts +++ b/packages/client-runtime/src/issueList.ts @@ -8,6 +8,7 @@ import type { IssueScopeRef, IssueTrackerSummary, SourceControlProviderKind, + ProjectId, } from "@t3tools/contracts"; import { mergeIssueListPage } from "./state/issues.ts"; @@ -167,11 +168,14 @@ export function groupIssues( export function issueFilterScopes( held: ReadonlyMap, projects: ReadonlyArray, + selectedProject?: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId }, ) { const scopes: Array<{ readonly environmentId: EnvironmentId; readonly input: IssueScopeRef }> = []; for (const [environmentId, page] of held) { + if (selectedProject && selectedProject.environmentId !== environmentId) continue; for (const project of projects) { + if (selectedProject && selectedProject.projectId !== project.id) continue; if (project.environmentId !== environmentId) continue; const identity = project.repositoryIdentity; const kind = identity?.provider as SourceControlProviderKind | undefined; @@ -204,6 +208,7 @@ export function issueFilterScopes( scope, })); for (const input of covered) { + if (selectedProject && selectedProject.projectId !== input.projectId) continue; const host = input.host?.toLowerCase(); const tracker = page.answer.trackers.find( (t) => t.tracker === input.tracker && t.host.toLowerCase() === host, From 2e3d9fccddd4a26ad4eed71ef2b99f47b5af7666 Mon Sep 17 00:00:00 2001 From: Bilal Bakr <62337003+Bil0000@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:00:11 +0300 Subject: [PATCH 064/183] feat(web): show linked issues beside thread pull requests (#38282) Co-authored-by: shivam <91240327+shivamhwp@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks --- .../BranchToolbarBranchSelector.tsx | 15 +- .../src/components/ChatView.browser.test.tsx | 120 +++++++++++ apps/web/src/components/ChatView.tsx | 7 +- apps/web/src/components/CommandPalette.tsx | 8 +- apps/web/src/components/RightPanelTabs.tsx | 10 +- .../chat/ThreadDetailsIssueRows.tsx | 186 +++++++++++++++--- .../chat/ThreadDetailsPrRow.browser.test.tsx | 22 ++- .../pullRequest/ThreadPullRequestsPanel.tsx | 42 +++- .../components/sidebar/SidebarThreadRow.tsx | 72 ++++++- apps/web/src/i18n/translations/de.json | 21 +- apps/web/src/i18n/translations/en.json | 21 +- apps/web/src/i18n/translations/es.json | 21 +- apps/web/src/i18n/translations/fr.json | 21 +- apps/web/src/i18n/translations/ja.json | 21 +- apps/web/src/i18n/translations/ko.json | 21 +- apps/web/src/i18n/translations/pt-BR.json | 21 +- apps/web/src/i18n/translations/ru.json | 21 +- apps/web/src/i18n/translations/sv.json | 21 +- apps/web/src/i18n/translations/zh.json | 21 +- apps/web/src/state/issues.ts | 25 ++- apps/web/test/fakeEnvironment.ts | 17 +- docs/user/source-control.md | 13 +- .../client-runtime/src/state/runtime.test.ts | 8 +- packages/client-runtime/src/state/runtime.ts | 33 ++-- 24 files changed, 614 insertions(+), 174 deletions(-) diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index e10c48ce7a9a8..591f7c5ab969f 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -913,20 +913,7 @@ export function BranchToolbarBranchSelector({ /> ) : null} {displayMode === "panel" ? ( - { - event.stopPropagation(); - useRightPanelStore.getState().openIssue(threadRef, { - projectId: link.projectId, - tracker: link.tracker, - host: link.host, - scope: link.scope, - key: link.key, - url: link.url, - }); - }} - /> + ) : null}